fix(ui): 修复登录与并发请求并统一表格、主题和页面展示

验证:868 项单测、ESLint、Prettier、UI 依赖审计和差异检查通过。
This commit is contained in:
zhanjunhao
2026-11-19 18:58:46 +08:00
parent 99fe167103
commit 13105bdba5
128 changed files with 4672 additions and 5391 deletions
+23 -10
View File
@@ -130,9 +130,11 @@ const ORG_USER_NAV_PATHS = {
keyManagement: ['/key-management', '/user-center/key-management'],
userCenter: ['/user-center'],
};
const matchesPathPrefix = (pathname, prefix) =>
pathname === prefix || pathname.startsWith(`${prefix}/`);
const isOrgAllowedPath = (pathname, extraPrefixes = []) =>
[...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some(
(p) => pathname === p || pathname.startsWith(p + '/'),
[...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some((prefix) =>
matchesPathPrefix(pathname, prefix),
);
// 模型超市旧路径 /pricing → /market。用组件而非静态 <Navigate>,
@@ -220,27 +222,38 @@ function App() {
// /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。
// 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对
// 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。
if (isOrgAdmin && !prefixes.includes('/skill-market')) {
if (
orgMembershipLoaded &&
isOrgAdmin &&
!prefixes.includes('/skill-market')
) {
prefixes.push('/skill-market');
}
return prefixes;
}, [statusState?.status?.HeaderNavModulesOrgUser, isOrgAdmin]);
}, [
statusState?.status?.HeaderNavModulesOrgUser,
orgMembershipLoaded,
isOrgAdmin,
]);
// 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。
// 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。
// 企业列表未到位前不做封锁判定:isOrgAdmin 首帧恒 false,此时若直接重定向,
// 硬刷新/收藏夹直达 /skill-market 的 org_only 管理员会在放行判据还没算出来时
// 就被弹回 /org,而重定向不可逆——之后 isOrgAdmin 变 true 也回不去。
// 只有技能超市的企业管理员特例需要等待企业列表;等待时也不挂载受限页面。
const routePath = location.pathname.toLowerCase();
const orgConfined =
userState?.user?.org_only_mode === true &&
orgMembershipLoaded &&
isOrgCenterAvailable &&
!isOrgAllowedPath(location.pathname, orgUserAllowedPrefixes);
!isOrgAllowedPath(routePath, orgUserAllowedPrefixes);
if (orgConfined) {
return (
<SetupCheck>
<Navigate to='/org' replace />
{!orgMembershipLoaded &&
matchesPathPrefix(routePath, '/skill-market') ? (
<Loading />
) : (
<Navigate to='/org' replace />
)}
</SetupCheck>
);
}
@@ -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>
),
},
];
@@ -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>
))}
@@ -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 { 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';
@@ -275,7 +276,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
+2 -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 { formatPercent } from '../../helpers/safeDisplay';
import React from 'react';
import { Card } from '@/components/ui';
@@ -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>
+7 -2
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 { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -104,9 +105,13 @@ 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}
</span>
+3 -2
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 } 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),
},
],
},
@@ -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 { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -80,9 +81,9 @@ 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}
@@ -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>
);
};
+17 -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 { formatPercent } from '../../../helpers/safeDisplay';
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
@@ -52,7 +54,15 @@ export const formatRate = (rate) =>
? '—'
: `${rate >= 0 ? '+' : ''}${rate.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 +415,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 +436,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 +477,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;
@@ -118,6 +118,28 @@ export function ConsoleSearchActions({
);
}
export function ConsoleFilterGrid({ children, onReset, onSearch, loading }) {
return (
<div className='console-filter-panel'>
<div className='console-filter-grid'>{children}</div>
<ConsoleSearchActions
onReset={onReset}
onSearch={onSearch}
loading={loading}
/>
</div>
);
}
export function ConsoleFilterField({ label, id, children }) {
return (
<div className='console-filter-field'>
<label htmlFor={id}>{label}</label>
{children}
</div>
);
}
export const ConsoleForm = forwardRef(function ConsoleForm(
{ className, layout = 'vertical', ...props },
ref,
@@ -167,6 +189,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');
+61
View File
@@ -233,6 +233,67 @@
gap: var(--console-space-1);
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);
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}
+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;
}
}
+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'>
+4 -2
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,
@@ -110,7 +112,7 @@ const RemoteSelect = ({
const name = labels.current[String(value)];
opts.unshift({
value: String(value),
label: name ? `${name} (#${value})` : `#${value}`,
label: name ? `${name} (#${value})` : formatIdReference(value),
});
}
return opts;
@@ -193,7 +195,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
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(
+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}>
@@ -21,6 +21,7 @@ import {
Plus as ActionPlus,
Upload as ActionUpload,
} from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect, useCallback } from 'react';
import {
Card,
@@ -31,7 +32,6 @@ import {
Select,
Tag,
Avatar,
Popconfirm,
Typography,
Space,
Banner,
@@ -307,28 +307,34 @@ const CustomerServiceSetting = () => {
title: t('操作'),
dataIndex: 'action',
render: (_, record) => (
<Space>
<Button
onClick={() => handleToggleStatus(record)}
type='link'
size='small'
danger={(record.status === 1 ? 'danger' : 'primary') === 'danger'}
>
{record.status === 1 ? t('下线') : t('上线')}
</Button>
<TableRowActions
items={[
{
key: 'status',
label: record.status === 1 ? t('下线') : t('上线'),
onClick: () => handleToggleStatus(record),
danger: (record.status === 1 ? 'danger' : 'primary') === 'danger',
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除'),
content: t('确定要删除这个客服吗?'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => handleDelete(record.id),
}),
},
]}
>
<Button onClick={() => openModal(record)} type='link' size='small'>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除')}
content={t('确定要删除这个客服吗?')}
onConfirm={() => handleDelete(record.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
</TableRowActions>
),
},
];
+27 -25
View File
@@ -24,6 +24,7 @@ import {
ChevronDown as ActionChevronDown,
ChevronRight as ActionChevronRight,
} from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
Card,
@@ -989,7 +990,31 @@ const LevelPolicySetting = () => {
title: t('操作'),
width: 260,
render: (_, r) => (
<Space>
<TableRowActions
items={[
{
key: 'copy',
label: t('复制'),
onClick: () => duplicateLevel(type, r.code),
title: t('以该等级为模板新建'),
},
{
key: 'delete',
label: t('删除'),
disabled: deletingCode === `${type}/${r.code}`,
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除该等级?'),
content: t('被用户/企业/默认等级引用时会被拒绝'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => deleteLevel(type, r.code),
}),
},
]}
>
<Button
onClick={() => openEditor(type, r.code)}
type='link'
@@ -997,30 +1022,7 @@ const LevelPolicySetting = () => {
>
{t('编辑')}
</Button>
<Tooltip content={t('以该等级为模板新建')}>
<Button
onClick={() => duplicateLevel(type, r.code)}
type='link'
size='small'
>
{t('复制')}
</Button>
</Tooltip>
<Popconfirm
title={t('确认删除该等级?')}
content={t('被用户/企业/默认等级引用时会被拒绝')}
onConfirm={() => deleteLevel(type, r.code)}
>
<Button
loading={deletingCode === `${type}/${r.code}`}
type='link'
size='small'
danger
>
{t('删除')}
</Button>
</Popconfirm>
</Space>
</TableRowActions>
),
},
];
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -27,7 +28,6 @@ import {
Modal,
Form,
Toast,
Popconfirm,
Switch,
Tag,
Progress,
@@ -262,7 +262,29 @@ const TutorialVideoSetting = () => {
title: t('操作'),
width: 180,
render: (_, record) => (
<div style={{ display: 'flex', gap: 8 }}>
<TableRowActions
items={[
{
key: 'edit',
label: t('编辑'),
onClick: () => handleEdit(record),
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确定删除这个视频吗?'),
content: t('删除后将无法恢复'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => handleDelete(record.id),
}),
},
]}
>
<Button
onClick={() => handlePreview(record)}
type='link'
@@ -270,19 +292,7 @@ const TutorialVideoSetting = () => {
>
{t('预览')}
</Button>
<Button onClick={() => handleEdit(record)} type='link' size='small'>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除这个视频吗?')}
content={t('删除后将无法恢复')}
onConfirm={() => handleDelete(record.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</div>
</TableRowActions>
),
},
];
+34 -28
View File
@@ -19,7 +19,8 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Empty, Popconfirm, Space, Tag, Typography } from 'antd';
import { Button, Empty, Modal, Space, Tag, Typography } from 'antd';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { Table } from '@/components/ui';
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { Plus } from '../common/icons/ActionIcons';
@@ -148,7 +149,37 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
fixed: 'right',
width: 180,
render: (_, r) => (
<Space size={8} wrap>
<TableRowActions
items={[
canWrite && {
key: 'edit',
label: t('编辑'),
onClick: () => setEditing(r),
},
canWrite && {
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除该集合?'),
content: t('使用该虚拟模型名的请求将返回"模型不存在"。'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: async () => {
try {
await deleteProfile(mode, orgId, r.id);
showSuccess(t('已删除'));
load();
} catch (e) {
if (e?.message) showError(e.message);
}
},
}),
},
]}
>
<Button
type='link'
size='small'
@@ -157,32 +188,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
>
{t('试路由')}
</Button>
{canWrite && (
<>
<Button type='link' size='small' onClick={() => setEditing(r)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该集合?')}
description={t('使用该虚拟模型名的请求将返回"模型不存在"。')}
okButtonProps={{ danger: true }}
onConfirm={async () => {
try {
await deleteProfile(mode, orgId, r.id);
showSuccess(t('已删除'));
load();
} catch (e) {
if (e?.message) showError(e.message);
}
}}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</>
)}
</Space>
</TableRowActions>
),
},
];
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { writeClipboardText } from '../../../helpers/clipboard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState } from 'react';
import { Switch } from 'antd';
import {
@@ -729,142 +730,110 @@ export const getChannelsColumns = ({
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => {
if (record.children === undefined) {
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({
title: t('确定是否要删除此渠道?'),
content,
onOk: () => {
(async () => {
await manageChannel(record.id, 'delete', record);
await refresh();
setTimeout(() => {
if (channels.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
})();
},
});
},
},
{
node: 'item',
name: t('复制'),
type: 'tertiary',
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
];
if (!isRoot()) return null;
if (record.children !== undefined) {
return (
<Space wrap className='console-module-row-actions'>
{isRoot() && (
<>
<Button
type='link'
size='small'
onClick={() => testChannel(record, '')}
>
{t('测试')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
}}
>
{t('批量测试')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='link'
danger
size='small'
onClick={moreMenuItems[0].onClick}
>
{t('删除')}
</Button>
<Button
type='link'
size='small'
onClick={moreMenuItems[1].onClick}
>
{t('复制')}
</Button>
{record.channel_info?.is_multi_key && (
<Button
type='link'
size='small'
onClick={() => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
}}
>
{t('多密钥管理')}
</Button>
)}
</>
)}
</Space>
);
} else {
// 标签操作按钮
return (
<Space wrap>
{isRoot() && (
<>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'enable')}
>
{t('启用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'disable')}
>
{t('禁用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</>
)}
</Space>
<TableRowActions
items={[
{
key: 'enable',
label: t('启用全部'),
onClick: () => manageTag(record.key, 'enable'),
},
{
key: 'disable',
label: t('禁用全部'),
onClick: () => manageTag(record.key, 'disable'),
},
]}
>
<Button
type='link'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</TableRowActions>
);
}
return (
<TableRowActions
items={[
{
key: 'batch-test',
label: t('批量测试'),
onClick: () => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
},
},
record.channel_info?.is_multi_key && {
key: 'multi-key',
label: t('多密钥管理'),
onClick: () => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
},
},
{
key: 'copy',
label: t('复制'),
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({
title: t('确定是否要删除此渠道?'),
content,
onOk: () => {
(async () => {
await manageChannel(record.id, 'delete', record);
await refresh();
setTimeout(() => {
if (channels.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
})();
},
});
},
},
]}
>
<Button
type='link'
size='small'
onClick={() => testChannel(record, '')}
>
{t('测试')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
</TableRowActions>
);
},
},
];
@@ -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
@@ -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,9 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { Copy as ActionCopy } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React from 'react';
import { Button as AntButton, Tooltip as AntTooltip } from 'antd';
import { Button, Space, Tag, Modal, Tooltip } from '@/components/ui';
import { Button, Tag, Modal, Tooltip } from '@/components/ui';
import {
timestamp2string,
getLobeHubIcon,
@@ -239,64 +240,57 @@ const renderOperations = (
setDetailModel,
) => {
return (
<Space wrap className='console-module-row-actions'>
<TableRowActions
items={
isRoot()
? [
{
key: 'toggle-status',
label: record.status === 1 ? t('禁用') : t('启用'),
onClick: () =>
manageModel(
record.id,
record.status === 1 ? 'disable' : 'enable',
record,
),
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () => {
Modal.confirm({
title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageModel(record.id, 'delete', record);
await refresh();
})();
},
});
},
},
]
: []
}
>
<Button type='link' size='small' onClick={() => setDetailModel(record)}>
{t('详情')}
</Button>
{isRoot() && (
<>
{record.status === 1 ? (
<Button
type='link'
danger
size='small'
onClick={() => manageModel(record.id, 'disable', record)}
>
{t('禁用')}
</Button>
) : (
<Button
type='link'
size='small'
onClick={() => manageModel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
<Button
type='link'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='link'
danger
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageModel(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</>
<Button
type='link'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
)}
</Space>
</TableRowActions>
);
};
@@ -38,37 +38,21 @@ 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 onClick={batchCopyRedemptions}>
{t('复制所选兑换码到剪贴板')}
</Button>
{isAdmin() && (
<Button
type='danger'
className='w-full md:w-auto'
onClick={batchDeleteRedemptions}
size='small'
>
<Button type='danger' onClick={batchDeleteRedemptions}>
{t('清除失效兑换码')}
</Button>
)}
{isAdmin() && (
<Button type='primary' onClick={handleAddRedemption}>
{t('添加兑换码')}
</Button>
)}
</div>
);
};
@@ -18,8 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@/components/ui';
import { IconMore } from '@/components/ui/icons';
import { Tag, Button, Popover } from '@/components/ui';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import {
renderQuota,
timestamp2string,
@@ -144,46 +144,42 @@ export const getRedemptionsColumns = ({
},
},
{
title: '',
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 205,
width: 215,
render: (text, record) => {
// Create dropdown menu items for more operations
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
const moreMenuItems = [];
if (isAdmin() && !isExpired(record)) {
const unused = record.status === REDEMPTION_STATUS.UNUSED;
moreMenuItems.push({
node: 'item',
name: t('禁用'),
type: 'warning',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.DISABLE, record);
},
});
} else if (!isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('启用'),
type: 'secondary',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.ENABLE, record);
},
key: 'toggle-status',
label: unused ? t('禁用') : t('启用'),
disabled: record.status === REDEMPTION_STATUS.USED,
onClick: () =>
manageRedemption(
record.id,
unused ? REDEMPTION_ACTIONS.DISABLE : REDEMPTION_ACTIONS.ENABLE,
record,
),
});
}
moreMenuItems.unshift({
key: 'copy',
label: t('复制'),
onClick: () => copyText(record.key),
});
if (isAdmin()) {
moreMenuItems.push({
key: 'delete',
label: t('删除'),
danger: true,
onClick: () => showDeleteRedemptionModal(record),
});
}
return (
<Space>
<TableRowActions items={moreMenuItems}>
<Popover
// 触屏必须 click:这是查看兑换码明文的唯一入口
trigger={hoverOrClickTrigger()}
@@ -191,41 +187,24 @@ export const getRedemptionsColumns = ({
style={{ padding: 20 }}
position='top'
>
<Button type='tertiary' size='small'>
<Button type='link' size='small'>
{t('查看')}
</Button>
</Popover>
<Button
size='small'
onClick={async () => {
await copyText(record.key);
}}
>
{t('复制')}
</Button>
{isAdmin() && (
<>
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
}}
disabled={record.status !== REDEMPTION_STATUS.UNUSED}
>
{t('编辑')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button type='tertiary' size='small' icon={<IconMore />} />
</Dropdown>
</>
<Button
type='link'
size='small'
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
}}
disabled={record.status !== REDEMPTION_STATUS.UNUSED}
>
{t('编辑')}
</Button>
)}
</Space>
</TableRowActions>
);
},
},
@@ -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}
@@ -18,11 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import {
Button,
Dropdown,
Space,
SplitButtonGroup,
Tag,
AvatarGroup,
Avatar,
@@ -40,12 +39,7 @@ import {
getModelCategories,
showError,
} from '../../../helpers';
import {
IconTreeTriangleDown,
IconCopy,
IconEyeOpened,
IconEyeClosed,
} from '@/components/ui/icons';
import { IconCopy, IconEyeOpened, IconEyeClosed } from '@/components/ui/icons';
// progress color helper
const getProgressColor = (pct) => {
@@ -327,7 +321,6 @@ const renderOperations = (
const name = Object.keys(item)[0];
if (!name) continue;
chatsArray.push({
node: 'item',
key: i,
name,
value: item[name],
@@ -340,87 +333,70 @@ const renderOperations = (
}
return (
<Space wrap>
<SplitButtonGroup
className='overflow-hidden'
aria-label={t('项目操作按钮组')}
>
<Button
size='small'
type='tertiary'
onClick={() => {
if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接'));
} else {
const first = chatsArray[0];
onOpenLink(first.name, first.value, record);
}
}}
>
{t('聊天')}
</Button>
<Dropdown trigger='click' position='bottomRight' menu={chatsArray}>
<Button
type='tertiary'
icon={<IconTreeTriangleDown />}
size='small'
></Button>
</Dropdown>
</SplitButtonGroup>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={async () => {
await manageToken(record.id, 'disable', record);
<TableRowActions
items={[
chatsArray.length > 0 && {
key: 'chat-links',
label: t('聊天链接'),
children: chatsArray.map((item) => ({
key: `chat-${item.key}`,
label: item.name,
onClick: item.onClick,
})),
},
{
key: 'status',
label: record.status === 1 ? t('禁用') : t('启用'),
danger: record.status === 1,
onClick: async () => {
await manageToken(
record.id,
record.status === 1 ? 'disable' : 'enable',
record,
);
await refresh();
}}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={async () => {
await manageToken(record.id, 'enable', record);
await refresh();
}}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingToken(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此密钥?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
},
},
{
key: 'edit',
label: t('编辑'),
onClick: () => {
setEditingToken(record);
setShowEdit(true);
},
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确定是否要删除此密钥?'),
content: t('此修改将不可逆'),
okButtonProps: { danger: true },
onOk: async () => {
await manageToken(record.id, 'delete', record);
await refresh();
})();
},
});
},
}),
},
]}
>
<Button
size='small'
type='link'
onClick={() => {
if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接'));
} else {
const first = chatsArray[0];
onOpenLink(first.name, first.value, record);
}
}}
>
{t('删除')}
{t('聊天')}
</Button>
</Space>
</TableRowActions>
);
};
+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,
+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);
}
+24 -32
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import {
getUserIdFromLocalStorage,
redirectToExpiredLogin,
showError,
formatMessageForAPI,
isValidMessage,
@@ -29,6 +30,7 @@ import i18next from 'i18next';
import { MESSAGE_ROLES } from '../constants/playground.constants';
import { getServerURL } from './config';
import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
import { installRequestLifecycle } from './requestLifecycle';
function createAPIInstance() {
const serverURL = getServerURL();
@@ -41,14 +43,20 @@ function createAPIInstance() {
});
}
export let API = createAPIInstance();
export let API;
let retireAPI;
function patchAPIInstance(instance) {
const originalGet = instance.get.bind(instance);
const inFlightGetRequests = new Map();
instance.get = (url, config = {}) => {
if (config?.disableDuplicate) {
if (
config?.disableDuplicate ||
config?.signal ||
config?.cancelToken ||
config?.requestGroup
) {
return originalGet(url, config);
}
@@ -56,12 +64,13 @@ function patchAPIInstance(instance) {
url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
? localStorage.getItem('current_org_id') || ''
: '';
const key = buildGetRequestKey(
const requestKey = buildGetRequestKey(
url,
config,
fallbackOrgId,
getUserIdFromLocalStorage(),
);
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}`;
if (inFlightGetRequests.has(key)) {
return inFlightGetRequests.get(key);
}
@@ -75,23 +84,6 @@ function patchAPIInstance(instance) {
};
}
patchAPIInstance(API);
// 添加 response interceptor 的函数
function addResponseInterceptor(instance) {
instance.interceptors.response.use(
(response) => response,
(error) => {
// 如果请求配置中显式要求跳过全局错误处理,则不弹出默认错误提示
if (error.config && error.config.skipErrorHandler) {
return Promise.reject(error);
}
showError(error);
return Promise.reject(error);
},
);
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
function addOrgHeaderInterceptor(instance) {
instance.interceptors.request.use((config) => {
@@ -107,19 +99,21 @@ function addOrgHeaderInterceptor(instance) {
});
}
// 初始化时添加 interceptor
addResponseInterceptor(API);
addOrgHeaderInterceptor(API);
export function updateAPI() {
API = createAPIInstance();
patchAPIInstance(API);
// 重新添加 interceptors
addResponseInterceptor(API);
addOrgHeaderInterceptor(API);
const instance = createAPIInstance();
patchAPIInstance(instance);
addOrgHeaderInterceptor(instance);
const previous = retireAPI;
retireAPI = installRequestLifecycle(instance, {
onError: (error) => showError(error, { redirectOnUnauthorized: false }),
onSessionExpired: redirectToExpiredLogin,
});
API = instance;
previous?.();
}
updateAPI();
// playground
// 构建API请求负载
@@ -310,8 +304,6 @@ export const processGroupsData = (data, userGroup) => {
return groupOptions;
};
// 原来components中的utils.js
export async function getOAuthState() {
let path = '/api/oauth/state';
let affCode = localStorage.getItem('aff');
+1 -7
View File
@@ -25,11 +25,7 @@ import { StatusContext } from '../context/Status';
import { canAccessDelegatedAdminPage } from './adminDelegation';
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
import Loading from '../components/common/ui/Loading';
import {
getUserData,
isSafePostLoginRedirect,
savePostLoginRedirect,
} from './data';
import { getUserData, isSafePostLoginRedirect } from './data';
import { authRedirectTarget } from './authRedirect';
/**
@@ -49,11 +45,9 @@ export const isAuthPagePath = (pathname) =>
/^\/org\/[^/]+\/login$/.test(pathname);
// 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。
// 回跳地址已存本地(savePostLoginRedirect),切换到个人登录后仍可正常回跳。
const getLoginTarget = (location) => {
const target = `${location.pathname}${location.search}${location.hash}`;
if (isSafePostLoginRedirect(target)) {
savePostLoginRedirect(target);
return `/org/login?redirect=${encodeURIComponent(target)}`;
}
return '/org/login';
+126
View File
@@ -0,0 +1,126 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { colord, extend } from 'colord';
import a11yPlugin from 'colord/plugins/a11y';
import mixPlugin from 'colord/plugins/mix';
extend([a11yPlugin, mixPlugin]);
export const PROTOTYPE_LIGHT_PRIMARY = '#b96508';
export const PROTOTYPE_DARK_PRIMARY = '#d1963a';
export const PROTOTYPE_DARK_SEED = '#f2ad41';
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
function toneAtContrast(color, surface, minimum, lighter) {
const { h: hue, s: saturation } = color.toHsl();
const tone = (lightness) => colord({ h: hue, s: saturation, l: lightness });
let low = 0;
let high = 100;
for (let step = 0; step < 12; step++) {
const middle = (low + high) / 2;
if (tone(middle).contrast(surface) >= minimum === lighter) high = middle;
else low = middle;
}
return tone(lighter ? high : low);
}
const readable = (color, surface, dark) =>
color.contrast(surface) >= 4.7
? color
: toneAtContrast(color, surface, 4.7, dark);
export function resolveBrandPalette(configured, dark, surface) {
const prototype = dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY;
const parsed = colord(configured);
const input = parsed.isValid() ? parsed.alpha(1) : colord(prototype);
const isPrototype = input.toHex() === prototype;
const hsl = input.toHsl();
const seed = isPrototype
? input
: colord({ ...hsl, s: Math.min(hsl.s, 68), l: clamp(hsl.l, 28, 70) });
const onSolid = dark ? '#11151c' : '#ffffff';
let normal;
let hover;
let active;
if (dark) {
const base = seed.contrast(onSolid);
const target = clamp(base, 5.3, isPrototype ? 7.2 : 6.45);
const fill = (ratio) => toneAtContrast(seed, onSolid, ratio, true);
normal = base === target ? seed : fill(target);
hover = fill(target + 0.5);
active = fill(target - 0.55);
} else {
normal = readable(seed, onSolid, false);
hover = normal.darken(0.035);
active = normal.darken(0.07);
}
const backdrop = colord(surface);
const tint = backdrop.mix(normal, dark ? 0.14 : 0.085);
const tintHover = backdrop.mix(normal, dark ? 0.2 : 0.135);
const ink = readable(normal, tintHover, dark).toHex();
return {
isPrototype,
onSolid,
normal: normal.toHex(),
hover: hover.toHex(),
active: active.toHex(),
accent: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : prototype) : ink,
selectionBg: isPrototype ? (dark ? '#382b1b' : '#fff3df') : tint.toHex(),
selectionText: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : '#a45a07') : ink,
tint: tint.toHex(),
tintHover: tintHover.toHex(),
};
}
export function resolveGradientLabel(stops, surface) {
const backdrop = colord(surface);
const base = backdrop.toRgb();
const colors = stops.map((stop) => {
const parsed = colord(stop);
return parsed.isValid() ? parsed.toRgb() : base;
});
const composite = (channel, from, to, progress) =>
from[channel] * from.a * (1 - progress) +
to[channel] * to.a * progress +
base[channel] * (1 - from.a * (1 - progress) - to.a * progress);
const samples = colors.flatMap((from, index) => {
const to = colors[index + 1] ?? from;
return [0, 0.25, 0.5, 0.75].map((progress) =>
colord({
r: composite('r', from, to, progress),
g: composite('g', from, to, progress),
b: composite('b', from, to, progress),
}),
);
});
const inks = ['#ffffff', '#11151c'];
const minimum = (ink) =>
Math.min(...samples.map((sample) => sample.contrast(ink)));
const chosen = minimum(inks[0]) >= minimum(inks[1]) ? inks[0] : inks[1];
if (samples.length > 0 && minimum(chosen) >= 4.5) return { color: chosen };
return {
color:
backdrop.contrast(inks[0]) >= backdrop.contrast(inks[1])
? inks[0]
: inks[1],
background: backdrop.toHex(),
};
}
+35 -3
View File
@@ -145,11 +145,43 @@ export function isSafePostLoginRedirect(path) {
export function savePostLoginRedirect(path) {
if (isSafePostLoginRedirect(path)) {
sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path);
} else {
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
}
}
export function consumePostLoginRedirect(defaultPath = DEFAULT_LOGIN_REDIRECT) {
const path = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY);
export function consumePostLoginRedirect({
redirect = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY),
enterprise = false,
orgOnly = false,
} = {}) {
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
return isSafePostLoginRedirect(path) ? path : defaultPath;
const fallback = enterprise
? '/org/workbench'
: orgOnly
? '/org'
: DEFAULT_LOGIN_REDIRECT;
if (!isSafePostLoginRedirect(redirect)) return fallback;
let normalizedPath;
try {
const base = 'https://login.invalid';
const target = new URL(redirect, base);
if (target.origin !== base) return fallback;
normalizedPath =
decodeURI(target.pathname).toLowerCase().replace(/\/+$/, '') || '/';
} catch {
return fallback;
}
if (
!isSafePostLoginRedirect(normalizedPath) ||
normalizedPath === '/forbidden' ||
normalizedPath === '/user/reset'
)
return fallback;
if (!enterprise && !orgOnly && /^\/org(?:\/|$)/.test(normalizedPath))
return fallback;
if ((enterprise || orgOnly) && /^\/console(?:\/|$)/.test(normalizedPath))
return fallback;
return redirect;
}
+16 -17
View File
@@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { API, updateAPI } from './api';
import { clearUserData, consumePostLoginRedirect, setUserData } from './data';
import { showError, showSuccess } from './utils';
import { showError } from './utils';
const SESSION_NOT_PERSISTED_MESSAGE =
'登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试';
@@ -35,8 +35,8 @@ export async function finishLogin({
userDispatch,
navigate,
t = (s) => s,
successMessage,
redirectOverride,
redirect,
enterprise = false,
}) {
setUserData(data);
// Recreate the axios instance so any in-flight request map from a prior
@@ -49,7 +49,11 @@ export async function finishLogin({
skipErrorHandler: true,
disableDuplicate: true,
});
if (!res.data?.success || !res.data?.data) {
if (
!res.data?.success ||
data?.id == null ||
String(res.data?.data?.id) !== String(data.id)
) {
throw new Error(res.data?.message || 'session verify failed');
}
verifiedUser = res.data.data;
@@ -64,18 +68,13 @@ export async function finishLogin({
setUserData(verifiedUser);
userDispatch({ type: 'login', payload: verifiedUser });
const message =
successMessage === undefined ? t('登录成功!') : successMessage;
if (message) {
showSuccess(message);
}
// org_only(仅企业资源)用户默认落企业空间,与 AuthRedirect 一致:默认落地页
// (密钥管理)挂载即调用被 BlockOrgOnlyMode 拦截的 /api/token,会先弹报错再被
// orgConfined 踢回 /org;企业中心整体关闭时 orgConfined 不生效,会一直停在报错页
const defaultRedirect =
verifiedUser.org_only_mode === true ? '/org' : undefined;
navigate(redirectOverride ?? consumePostLoginRedirect(defaultRedirect), {
replace: true,
});
navigate(
consumePostLoginRedirect({
redirect,
enterprise,
orgOnly: verifiedUser.org_only_mode === true,
}),
{ replace: true },
);
return true;
}
+109
View File
@@ -0,0 +1,109 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { CanceledError, isCancel } from 'axios';
const PUBLIC_API_PATH =
/^\/api\/(?:status|setup|i18n|notice|about|privacy_policy|user_agreement|home_page_content|customer-service|verification|reset_password|oauth|user\/(?:login|register|reset|passkey\/login)|org\/(?:login|register))(?:\/|$)/;
const READ_METHODS = new Set(['get', 'head', 'options']);
function isSessionBound(config) {
const pathname = config?.url?.split(/[?#]/, 1)[0];
return (
config?.sessionBound !== false &&
pathname?.startsWith('/api/') &&
!PUBLIC_API_PATH.test(pathname)
);
}
function combineSignals(signals, config, cleanups) {
const inputs = [...new Set(signals.filter(Boolean))];
if (inputs.length < 2) return inputs[0];
if (typeof AbortSignal.any === 'function') return AbortSignal.any(inputs);
const controller = new AbortController();
const abort = () => controller.abort();
for (const input of inputs) {
if (input.aborted) abort();
else input.addEventListener('abort', abort, { once: true });
}
cleanups.set(config, () => {
for (const input of inputs) input.removeEventListener('abort', abort);
});
return controller.signal;
}
export function installRequestLifecycle(
instance,
{ onError, onSessionExpired },
) {
const session = new AbortController();
const cleanups = new WeakMap();
instance.interceptors.request.use((config) => {
const sessionBound = isSessionBound(config);
const read = READ_METHODS.has(config.method);
const groupSignal = read ? config.requestGroup?.signal : undefined;
if ((sessionBound && session.signal.aborted) || groupSignal?.aborted) {
throw new CanceledError(undefined, config);
}
config.signal = combineSignals(
[config.signal, read && sessionBound && session.signal, groupSignal],
config,
cleanups,
);
return config;
});
const cleanup = (config) => {
cleanups.get(config)?.();
cleanups.delete(config);
};
instance.interceptors.response.use(
(response) => {
cleanup(response.config);
return response;
},
(error) => {
const { config, response } = error;
cleanup(config);
const sessionBound = isSessionBound(config);
const read = READ_METHODS.has(config?.method);
if (isCancel(error)) throw error;
if (sessionBound && session.signal.aborted) {
if (read) throw new CanceledError(undefined, config);
throw error;
}
if (response?.status >= 400 && read) config.requestGroup?.abort();
if (!config?.skipErrorHandler) {
if (response?.status === 401 && sessionBound) {
session.abort();
onSessionExpired();
} else {
onError(error);
}
}
throw error;
},
);
return () => session.abort();
}
+52
View File
@@ -0,0 +1,52 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export const toFiniteNumber = (value) => {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
export const formatPercent = (value, digits = 1, fallback = '-') => {
const number = toFiniteNumber(value);
return number === null ? fallback : `${number.toFixed(digits)}%`;
};
export const formatRatioPercent = (part, total, digits = 1, fallback = '-') => {
const numerator = toFiniteNumber(part);
const denominator = toFiniteNumber(total);
if (numerator === null || denominator === null || denominator <= 0) {
return fallback;
}
return formatPercent((numerator / denominator) * 100, digits, fallback);
};
export const formatUserReference = (name, id, fallback = '-') => {
const displayName = typeof name === 'string' ? name.trim() : name;
if (displayName) return String(displayName);
const userId = toFiniteNumber(id);
return userId === null ? fallback : `User#${userId}`;
};
export const formatIdReference = (id, fallback = '-') => {
if (id === null || id === undefined || id === '') return fallback;
const value = String(id).trim();
return value ? `#${value}` : fallback;
};
+56 -53
View File
@@ -28,12 +28,7 @@ import {
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
// 官方价折扣计算(纯函数):管理端与市场页共用
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
import {
clearUserData,
getUserData,
isSafePostLoginRedirect,
savePostLoginRedirect,
} from './data';
import { clearUserData, getUserData, isSafePostLoginRedirect } from './data';
const HTMLToastContent = ({ htmlContent }) => {
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
@@ -128,56 +123,64 @@ if (isMobileScreen) {
// showNoticeOptions.transition = 'flip';
}
export function showError(error) {
console.error(error);
if (error.message) {
if (error.name === 'AxiosError') {
// 检查 response 是否存在(网络错误时 response 为 undefined)
if (!error.response) {
Toast.error(i18next.t('错误:网络请求失败,请检查网络连接'));
return;
}
switch (error.response.status) {
case 401:
// 清除用户状态
clearUserData();
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
const redirect = isSafePostLoginRedirect(currentPath)
? `&redirect=${encodeURIComponent(currentPath)}`
: '';
if (redirect) {
savePostLoginRedirect(currentPath);
}
// toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
// 会话过期统一回企业登录(默认登录入口),OrgLogin 会识别 expired/redirect 参数
window.location.href = `/org/login?expired=true${redirect}`;
break;
case 429:
Toast.error(i18next.t('错误:请求次数过多,请稍后再试!'));
break;
case 500:
Toast.error(i18next.t('错误:服务器内部错误,请联系管理员!'));
break;
case 405:
Toast.info(i18next.t('本站仅作演示之用,无服务端!'));
break;
default: {
// 后端业务错误(4xx/5xx)带有面向用户的 message 字段;
// 优先展示它,而不是 axios 的 "Request failed with status code XXX"。
const backendMessage = error.response?.data?.message;
Toast.error(
i18next.t('错误:{{message}}', {
message: backendMessage || error.message,
}),
);
}
}
let redirectingToLogin = false;
const reportedRequestErrors = new WeakSet();
export function redirectToExpiredLogin() {
if (redirectingToLogin) return;
redirectingToLogin = true;
clearUserData();
const { pathname, search, hash } = window.location;
const currentPath = `${pathname}${search}${hash}`;
const redirect = isSafePostLoginRedirect(currentPath)
? `&redirect=${encodeURIComponent(currentPath)}`
: '';
window.location.replace(`/org/login?expired=true${redirect}`);
}
export function showError(error, { redirectOnUnauthorized = true } = {}) {
if (
error?.code === 'ERR_CANCELED' ||
error === 'canceled' ||
(redirectingToLogin && error === 'Request failed with status code 401')
)
return;
if (error?.isAxiosError || error?.name === 'AxiosError') {
if (reportedRequestErrors.has(error)) return;
reportedRequestErrors.add(error);
const status = error.response?.status;
if (status === 401 && redirectOnUnauthorized) {
redirectToExpiredLogin();
return;
}
Toast.error(i18next.t('错误:{{message}}', { message: error.message }));
} else {
Toast.error(i18next.t('错误:{{message}}', { message: error }));
if (status === 405) {
Toast.info({
key: 'http-error:405',
content: i18next.t('本站仅作演示之用,无服务端!'),
});
return;
}
let content;
if (!error.response) {
content = i18next.t('错误:网络请求失败,请检查网络连接');
} else if (status === 429) {
content = i18next.t('错误:请求次数过多,请稍后再试!');
} else if (status === 500) {
content = i18next.t('错误:服务器内部错误,请联系管理员!');
} else {
content = i18next.t('错误:{{message}}', {
message: error.response.data?.message || error.message,
});
}
Toast.error({ key: `http-error:${content}`, content });
return;
}
console.error(error);
Toast.error(
i18next.t('错误:{{message}}', { message: error?.message || error }),
);
}
export function showWarning(message) {
+3 -3
View File
@@ -28,7 +28,7 @@ import {
getSystemName,
API,
clearUserData,
showSuccess,
updateAPI,
} from '../../helpers';
import { rememberUserLanguage } from '../../i18n/bootstrap';
import { useIsMobile } from './useIsMobile';
@@ -163,11 +163,11 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
// Actions
const logout = useCallback(async () => {
await API.get('/api/user/logout');
showSuccess(t('注销成功!'));
userDispatch({ type: 'logout' });
clearUserData();
updateAPI();
navigate('/org/login');
}, [navigate, t, userDispatch]);
}, [navigate, userDispatch]);
const handleLanguageChange = useCallback(
(lang) => {
@@ -276,11 +276,6 @@ export const useRedemptionsData = () => {
// Close edit modal
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingRedemption({
id: undefined,
});
}, 500);
};
// Remove record (for UI update after deletion)
+116 -128
View File
@@ -16,24 +16,21 @@ 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 {
Eye as ActionEye,
Check as ActionCheck,
X as ActionX,
Ban as ActionBan,
RotateCw as ActionRotateCw,
} from '@/components/common/icons/ActionIcons';
import {
ConsoleCard,
ConsoleSearchBar,
ConsoleSearchActions,
ConsoleFilterField,
ConsoleFilterGrid,
ConsoleListTable,
} from '../../components/console/ConsolePrimitives';
import ConsoleCollection from '../../components/console/ConsoleCollection';
import { TableRowActions } from '../../components/common/table/TableToolbar';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../helpers/utils';
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Input,
Tag,
@@ -63,6 +60,7 @@ const paymentMethodMap = {
const AdminInvoice = () => {
const { t, i18n } = useTranslation();
const isMobile = useIsMobile();
const [invoices, setInvoices] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
@@ -118,6 +116,13 @@ const AdminInvoice = () => {
setSearchKeyword(keyword);
};
const handleReset = () => {
setPage(1);
setKeyword('');
setSearchKeyword('');
setStatusFilter('');
};
const handleStatusFilterChange = (value) => {
setPage(1);
setStatusFilter(value || '');
@@ -301,138 +306,118 @@ const AdminInvoice = () => {
},
{
title: t('操作'),
width: 200,
key: 'actions',
width: 140,
fixed: 'right',
render: (_, record) => (
<div className='flex items-center gap-1 flex-wrap'>
<TableRowActions
items={[
record.status === INVOICE_STATUS.PENDING && {
key: 'approve',
label: t('通过'),
onClick: () => {
setApproveId(record.id);
setApproveVisible(true);
},
},
record.status === INVOICE_STATUS.PENDING && {
key: 'reject',
label: t('拒绝'),
danger: true,
onClick: () => {
setRejectId(record.id);
setRejectVisible(true);
},
},
record.status === INVOICE_STATUS.FAILED && {
key: 'retry',
label: t('重试'),
onClick: () => handleRetry(record.id),
},
[
INVOICE_STATUS.APPROVED,
INVOICE_STATUS.INVOICING,
INVOICE_STATUS.FAILED,
].includes(record.status) && {
key: 'cancel',
label: t('取消'),
danger: true,
onClick: () => handleFailCancel(record.id),
},
]}
>
<Button
type='link'
size='small'
theme='borderless'
icon={<ActionEye size={14} />}
onClick={() => handleViewDetail(record.id)}
/>
{record.status === INVOICE_STATUS.PENDING && (
<>
<Button
size='small'
theme='borderless'
type='primary'
icon={<ActionCheck size={14} />}
onClick={() => {
setApproveId(record.id);
setApproveVisible(true);
}}
>
{t('通过')}
</Button>
<Button
size='small'
theme='borderless'
type='danger'
icon={<ActionX size={14} />}
onClick={() => {
setRejectId(record.id);
setRejectVisible(true);
}}
>
{t('拒绝')}
</Button>
</>
)}
{(record.status === INVOICE_STATUS.APPROVED ||
record.status === INVOICE_STATUS.INVOICING) && (
<Button
size='small'
theme='borderless'
type='danger'
icon={<ActionBan size={14} />}
onClick={() => handleFailCancel(record.id)}
>
{t('取消')}
</Button>
)}
{record.status === INVOICE_STATUS.FAILED && (
<>
<Button
size='small'
theme='borderless'
icon={<ActionRotateCw size={14} />}
onClick={() => handleRetry(record.id)}
>
{t('重试')}
</Button>
<Button
size='small'
theme='borderless'
type='danger'
icon={<ActionBan size={14} />}
onClick={() => handleFailCancel(record.id)}
>
{t('取消')}
</Button>
</>
)}
</div>
>
{t('详情')}
</Button>
</TableRowActions>
),
},
];
return (
<div className='console-content'>
{/* 筛选区:标题与筛选项同行 */}
<ConsoleSearchBar formProps={{ layout: 'inline' }}>
<div className='console-search-fields'>
<Input
prefix={<Search size={14} />}
placeholder={t('搜索抬头/税号/订单号/用户')}
value={keyword}
onChange={setKeyword}
onEnterPress={handleSearch}
style={{ width: 240 }}
/>
<Select
placeholder={t('状态')}
value={statusFilter || undefined}
onChange={handleStatusFilterChange}
style={{ width: 120 }}
allowClear
optionList={[
{ label: t('待审核'), value: '1' },
{ label: t('审核通过'), value: '2' },
{ label: t('已拒绝'), value: '3' },
{ label: t('开票中'), value: '4' },
{ label: t('已开票'), value: '5' },
{ label: t('已取消'), value: '6' },
{ label: t('开票失败'), value: '7' },
]}
/>
<ConsoleSearchActions onSearch={handleSearch} loading={loading} />
</div>
</ConsoleSearchBar>
{/* 表格 */}
<ConsoleCard>
<Table
<ConsoleCollection
searchArea={
<ConsoleFilterGrid
onReset={handleReset}
onSearch={handleSearch}
loading={loading}
>
<ConsoleFilterField label={t('搜索关键字')} id='invoice-keyword'>
<Input
id='invoice-keyword'
prefix={<Search size={14} />}
placeholder={t('搜索抬头/税号/订单号/用户')}
value={keyword}
onChange={setKeyword}
onEnterPress={handleSearch}
/>
</ConsoleFilterField>
<ConsoleFilterField label={t('状态')} id='invoice-status'>
<Select
id='invoice-status'
placeholder={t('状态')}
value={statusFilter || undefined}
onChange={handleStatusFilterChange}
allowClear
optionList={[
{ label: t('待审核'), value: '1' },
{ label: t('审核通过'), value: '2' },
{ label: t('已拒绝'), value: '3' },
{ label: t('开票中'), value: '4' },
{ label: t('已开票'), value: '5' },
{ label: t('已取消'), value: '6' },
{ label: t('开票失败'), value: '7' },
]}
/>
</ConsoleFilterField>
</ConsoleFilterGrid>
}
paginationArea={createCardProPagination({
currentPage: page,
pageSize,
total,
onPageChange: setPage,
onPageSizeChange: (size) => {
setPage(1);
setPageSize(size);
},
isMobile,
t,
})}
>
<ConsoleListTable
columns={columns}
dataSource={invoices}
loading={loading}
rowKey='id'
pagination={{
currentPage: page,
total,
pageSize,
onPageChange: setPage,
onPageSizeChange: (size) => {
setPage(1);
setPageSize(size);
},
showTotal: true,
}}
scroll={{ x: 1100 }}
size='middle'
empty={t('暂无发票数据')}
pagination={false}
/>
</ConsoleCard>
</ConsoleCollection>
{/* 审核通过弹窗 */}
<Modal
@@ -510,7 +495,10 @@ const AdminInvoice = () => {
<div>
{detailData.display_name ||
detailData.username ||
`User#${detailData.user_id}`}
formatUserReference(
detailData.display_name || detailData.username,
detailData.user_id,
)}
</div>
</div>
<div>
+63 -86
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 { TableRowActions } from '@/components/common/table/TableToolbar';
import {
ExternalLink as ActionExternalLink,
BarChart3 as ActionBarChart3,
@@ -852,95 +853,71 @@ const AdminOrganizations = () => {
},
{
title: t('操作'),
width: 380,
render: (_, record) => (
<div className='console-module-row-actions'>
{isAdmin() && (
<>
<Button
type='link'
size='small'
onClick={() => openEditModal(record)}
>
{t('编辑')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
key: 'actions',
width: 140,
fixed: 'right',
render: (_, record) =>
isAdmin() ? (
<TableRowActions
items={[
{
key: 'quota',
label: t('调额'),
onClick: () => {
setQuotaOrgId(record.id);
setQuotaAmount(0);
setQuotaModalVisible(true);
}}
>
{t('调额')}
</Button>
<Button
type='link'
size='small'
onClick={() => openFeatureModal(record)}
>
{t('功能开关')}
</Button>
{record.status === 4 ? (
<Button
size='small'
type='link'
onClick={() => handleActivate(record.id)}
>
{t('激活')}
</Button>
) : record.status === 1 ? (
<Button
size='small'
type='link'
onClick={() => handleStatusChange(record.id, 2)}
>
{t('冻结')}
</Button>
) : (
<Button
size='small'
type='link'
onClick={() => handleStatusChange(record.id, 1)}
>
{t('解冻')}
</Button>
)}
<Button
type='link'
size='small'
danger
onClick={() => handleDelete(record.id)}
>
{t('删除')}
</Button>
{isRoot() && (
<Button
size='small'
type='link'
loading={alertToggleLoading === record.id}
title={
alertExcludedIds.has(record.id)
? t('已屏蔽预警,点击恢复')
: t('屏蔽该企业的预警通知')
}
aria-label={
alertExcludedIds.has(record.id)
? t('恢复该企业的预警')
: t('屏蔽该企业的预警')
}
onClick={() => toggleAlertExclude(record)}
>
{alertExcludedIds.has(record.id)
? t('恢复通知')
: t('屏蔽通知')}
</Button>
)}
</>
)}
</div>
),
},
},
{
key: 'features',
label: t('功能开关'),
onClick: () => openFeatureModal(record),
},
{
key: 'status',
label:
record.status === 4
? t('激活')
: record.status === 1
? t('冻结')
: t('解冻'),
onClick: () =>
record.status === 4
? handleActivate(record.id)
: handleStatusChange(
record.id,
record.status === 1 ? 2 : 1,
),
},
isRoot() && {
key: 'notifications',
disabled: alertToggleLoading === record.id,
label: alertExcludedIds.has(record.id)
? t('恢复通知')
: t('屏蔽通知'),
title: alertExcludedIds.has(record.id)
? t('已屏蔽预警,点击恢复')
: t('屏蔽该企业的预警通知'),
onClick: () => toggleAlertExclude(record),
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () => handleDelete(record.id),
},
]}
>
<Button
type='link'
size='small'
onClick={() => openEditModal(record)}
>
{t('编辑')}
</Button>
</TableRowActions>
) : null,
},
];
+2 -2
View File
@@ -522,8 +522,8 @@
两列都给定上限并整体居中——否则宽屏下 1fr 撑满而 composer 自身
max-width 封顶,右侧会空出一大片(用户反馈:大面积空白)。 */
.brain-expert-layout.is-composing {
grid-template-columns: minmax(220px, 280px) minmax(0, 860px);
justify-content: center;
grid-template-columns: minmax(220px, 280px) minmax(0, 1fr);
justify-content: start;
}
.brain-expert-grid {
display: grid;
+13 -6
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 { formatPercent } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -1611,7 +1613,7 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
}
if (assignmentScope === 'member') {
return members.map((item) => ({
label: item.display_name || item.username || `#${item.id}`,
label: item.display_name || item.username || formatIdReference(item.id),
value: item.id,
}));
}
@@ -1640,9 +1642,11 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
)
.map((item) => ({
...item,
expert_name: expertNameById.get(item.expert_id) || `#${item.expert_id}`,
expert_name:
expertNameById.get(item.expert_id) ||
formatIdReference(item.expert_id),
scope_type_label: scopeTypeLabel[item.scope_type] || item.scope_type,
scope_label: item.scope_name || `#${item.scope_id}`,
scope_label: item.scope_name || formatIdReference(item.scope_id),
}));
}, [assignments, expertCatalog, t]);
@@ -1882,7 +1886,9 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
</div>
<div>
<span>{t('任务完成率')}</span>
<strong>{(metrics.completion_rate * 100).toFixed(1)}%</strong>
<strong>
{formatPercent(Number(metrics.completion_rate) * 100, 1)}
</strong>
</div>
<div>
<span>{t('平均耗时')}</span>
@@ -1892,7 +1898,7 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
<span>{t('用户认可率')}</span>
<strong>
{metrics.feedback_count
? `${(metrics.useful_rate * 100).toFixed(1)}%`
? formatPercent(Number(metrics.useful_rate) * 100, 1)
: '—'}
</strong>
</div>
@@ -2702,7 +2708,8 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
<b>[{citation.citation_id}]</b>
<span>{citation.source_label}</span>
<small>
{t('相关度')} {(citation.score * 100).toFixed(1)}%
{t('相关度')}{' '}
{formatPercent(Number(citation.score) * 100, 1)}
</small>
</div>
))}
+4 -2
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, { useEffect, useState } from 'react';
import { Button, Descriptions, Spin, Tag } from 'antd';
@@ -112,7 +114,7 @@ export default function PartnerDetail({
['主体类型', commissionLabel(t, 'partnerType', row.type)],
['状态', commissionLabel(t, 'status', row.status)],
['伙伴名称', row.name],
['登录主体', `#${row.user_id}`],
['登录主体', formatUserReference('', row.user_id, t('未知用户'))],
['证件号码', row.identity_no],
['联系人', row.contact_name],
['联系电话', row.contact_phone],
@@ -150,7 +152,7 @@ export default function PartnerDetail({
{
title: t('客户'),
render: (_, item) =>
item.customer_name || `#${item.subject_id}`,
item.customer_name || formatIdReference(item.subject_id),
},
{
title: t('类型'),
+30 -32
View File
@@ -16,7 +16,9 @@ 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 { TableRowActions } from '@/components/common/table/TableToolbar';
import React, {
useCallback,
useEffect,
@@ -494,9 +496,25 @@ export default function PartnerPortal({
},
{
title: t('操作'),
width: 230,
width: 175,
render: (_, row) => (
<div className='partner-portal-row-actions'>
<TableRowActions
items={[
{
key: 'export',
label: t('导出'),
disabled: exportingId !== null || mutationLoading,
onClick: () => exportStatement(row),
},
row.status === 'pending_confirmation' && {
key: 'reject',
label: t('驳回'),
danger: true,
disabled: mutationLoading,
onClick: () => open(row, 'reject'),
},
]}
>
<Button
type='link'
size='small'
@@ -506,36 +524,16 @@ export default function PartnerPortal({
{t('查看')}
</Button>
{row.status === 'pending_confirmation' && (
<>
<Button
type='link'
size='small'
disabled={mutationLoading}
onClick={() => open(row, 'confirm')}
>
{t('确认')}
</Button>
<Button
type='link'
size='small'
danger
disabled={mutationLoading}
onClick={() => open(row, 'reject')}
>
{t('驳回')}
</Button>
</>
<Button
type='link'
size='small'
disabled={mutationLoading}
onClick={() => open(row, 'confirm')}
>
{t('确认')}
</Button>
)}
<Button
type='link'
size='small'
disabled={exportingId !== null || mutationLoading}
loading={exportingId === row.id}
onClick={() => exportStatement(row)}
>
{t('导出')}
</Button>
</div>
</TableRowActions>
),
},
];
@@ -887,7 +885,7 @@ export default function PartnerPortal({
<Users size={17} />
</span>
<span>
{row.customer_name || `#${row.subject_id}`} ·{' '}
{row.customer_name || formatIdReference(row.subject_id)} ·{' '}
{t('客户保护期临近到期')}
<small>{date(protectionUntil(row))}</small>
</span>
+111 -154
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 React, {
useCallback,
@@ -56,7 +57,6 @@ import {
PencilLine,
ScrollText,
ShieldAlert,
ChevronDown,
} from 'lucide-react';
import Dashboard from './Dashboard';
import ListPanel from './ListPanel';
@@ -65,20 +65,12 @@ import PartnerDetail from './PartnerDetail';
import PartnerPortal from './PartnerPortal';
import { partnerScope, createPartnerTransport } from './partnerScope';
import { tierStatus } from './listFilters';
import {
Button,
DatePicker,
Dropdown,
Empty,
Select,
Spin,
Tag,
Typography,
} from 'antd';
import { Button, DatePicker, Empty, Select, Spin, Tag, Typography } from 'antd';
import dayjs from 'dayjs';
import { Plus, RefreshCw } from '../../components/common/icons/ActionIcons';
import { API } from '../../helpers';
import * as XLSX from 'xlsx';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import './styles.css';
import {
OperationsDialog,
@@ -194,7 +186,7 @@ function TierSummary({ items }) {
const key = `${item.subject_type}:${item.subject_id}:${item.customer_name}:${item.tier_source}:${item.tier_key}:${item.group_name || item.group || ''}:${item.rate_bps}`;
const value = groups.get(key) || {
id: key,
customer: item.customer_name || `#${item.subject_id || '—'}`,
customer: item.customer_name || formatIdReference(item.subject_id, '—'),
tier: item.tier_name || item.tier_key || '—',
group: item.group_name || item.group || '—',
rate_bps: item.rate_bps,
@@ -930,7 +922,9 @@ function AdminPage() {
dataIndex: 'user_id',
render: (value, row) => (
<EntityLabel
name={entityNames.users.get(Number(value)) || `#${value}`}
name={
entityNames.users.get(Number(value)) || formatIdReference(value)
}
reference={
row.organization_id
? entityNames.organizations.get(Number(row.organization_id))
@@ -990,7 +984,59 @@ function AdminPage() {
title: t('操作'),
width: 175,
render: (_, row) => (
<div className='commission-row-actions'>
<TableRowActions
items={[
{
key: 'partner-agreement',
label: t('登记或续签协议'),
onClick: () =>
setOperation({ kind: 'partner-agreement', row }),
},
...(['draft', 'suspended'].includes(row.status)
? [
{
key: 'partner-active',
label: t(row.status === 'draft' ? '启用' : '恢复生效'),
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'active',
}),
},
]
: []),
...(row.status === 'active'
? [
{
key: 'partner-suspend',
label: t('暂停合作'),
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'suspended',
}),
},
]
: []),
...(row.status !== 'terminated'
? [
{
key: 'partner-terminate',
label: t('终止合作'),
danger: true,
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'terminated',
}),
},
]
: []),
]}
>
<Button
onClick={() => setPartnerDetail(row)}
type='link'
@@ -1005,75 +1051,7 @@ function AdminPage() {
>
{t('编辑')}
</Button>
<Dropdown
trigger={['click']}
placement='bottomRight'
menu={{
items: [
{
key: 'partner-agreement',
label: t('登记或续签协议'),
onClick: () =>
setOperation({ kind: 'partner-agreement', row }),
},
...(['draft', 'suspended'].includes(row.status)
? [
{
key: 'partner-active',
label: t(
row.status === 'draft' ? '启用' : '恢复生效',
),
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'active',
}),
},
]
: []),
...(row.status === 'active'
? [
{
key: 'partner-suspend',
label: t('暂停合作'),
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'suspended',
}),
},
]
: []),
...(row.status !== 'terminated'
? [
{
key: 'partner-terminate',
label: t('终止合作'),
danger: true,
onClick: () =>
setOperation({
kind: 'partner-status',
row,
status: 'terminated',
}),
},
]
: []),
],
}}
>
<Button
type='link'
size='small'
icon={<ChevronDown size={14} aria-hidden />}
iconPlacement='end'
>
{t('更多')}
</Button>
</Dropdown>
</div>
</TableRowActions>
),
},
],
@@ -1173,84 +1151,62 @@ function AdminPage() {
},
{
title: t('操作'),
width: 300,
width: 155,
render: (_, row) => (
<div className='commission-row-actions'>
<TableRowActions
items={[
row.status === 'protected' && {
key: 'extend',
label: t('延期'),
onClick: () =>
setOperation({ kind: 'assignment-extend', row }),
},
[
'protected',
'protected_extended',
'pending_conversion',
].includes(row.status) && {
key: 'convert',
label: t('转正'),
onClick: () =>
setOperation({ kind: 'assignment-convert', row }),
},
row.status === 'pending_conversion' && {
key: 'reject',
label: t('驳回'),
onClick: () =>
setOperation({ kind: 'assignment-reject', row }),
},
row.status === 'formal' && {
key: 'transfer',
label: t('转移'),
onClick: () =>
setOperation({ kind: 'assignment-transfer', row }),
},
[
'formal',
'protected',
'protected_extended',
'pending_conversion',
].includes(row.status) && {
key: 'terminate',
label: t('终止'),
danger: true,
onClick: () =>
setOperation({ kind: 'assignment-terminate', row }),
},
]}
>
<Button
type='link'
size='small'
onClick={() =>
setOperation({ kind: 'assignment-history', row })
}
type='link'
size='small'
>
{t('历史')}
</Button>
{row.status === 'protected' && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-extend', row })
}
type='link'
size='small'
>
{t('延期')}
</Button>
)}
{[
'protected',
'protected_extended',
'pending_conversion',
].includes(row.status) && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-convert', row })
}
type='link'
size='small'
>
{t('转正')}
</Button>
)}
{row.status === 'pending_conversion' && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-reject', row })
}
type='link'
size='small'
>
{t('驳回')}
</Button>
)}
{row.status === 'formal' && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-transfer', row })
}
type='link'
size='small'
>
{t('转移')}
</Button>
)}
{[
'formal',
'protected',
'protected_extended',
'pending_conversion',
].includes(row.status) && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-terminate', row })
}
type='link'
size='small'
danger
>
{t('终止')}
</Button>
)}
</div>
</TableRowActions>
),
},
],
@@ -1284,7 +1240,8 @@ function AdminPage() {
)
.map(
(id) =>
entityNames.channels.get(Number(id)) || `#${id}`,
entityNames.channels.get(Number(id)) ||
formatIdReference(id),
)
.join('、')
: row.source_type === 'model'
@@ -6,11 +6,40 @@
--igf-ink: var(--text-primary);
--igf-muted: var(--text-secondary);
--igf-line: var(--border-subtle);
--igf-surface: var(--surface-card);
--igf-accent: var(--ui-color-primary);
--igf-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
--igf-danger: var(--ui-color-danger);
--igf-warning: var(--ui-color-warning);
--igf-ring: color-mix(in srgb, var(--ui-color-primary) 55%, transparent);
background: var(--igf-surface);
}
.igf-form-scroll {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
padding: 16px;
}
/* Keep disabled generation actions grounded in the same surface and border token. */
.image-generation-form .igf-generate .ant-btn:disabled,
.image-generation-form .igf-generate .ant-btn[disabled] {
border: 1px solid var(--igf-line);
background: var(--igf-fill);
box-shadow: none;
color: var(--igf-muted);
cursor: not-allowed;
opacity: 1;
}
.image-generation-form .igf-generate .ant-btn:disabled:hover,
.image-generation-form .igf-generate .ant-btn[disabled]:hover {
border-color: var(--igf-line);
background: var(--igf-fill);
box-shadow: none;
color: var(--igf-muted);
}
.image-generation-form button:focus-visible,
@@ -152,6 +181,13 @@
gap: 6px;
}
.igf-generate-wrap {
flex: 0 0 auto;
padding: 16px 16px max(16px, env(safe-area-inset-bottom));
border-top: 1px solid var(--igf-line);
background: var(--igf-surface);
}
.igf-quote {
min-height: 18px;
color: var(--igf-muted);
@@ -140,7 +140,7 @@ const hasImageTaskType = (dataTransfer) =>
const Section = ({ title, extra, children, className = '' }) => (
<div
className={`mb-4 rounded-3xl border border-white/[0.45] bg-white/[0.28] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045] ${className}`}
className={`mb-4 rounded-3xl border border-[var(--igf-line)] bg-white/[0.28] p-3 backdrop-blur-xl dark:bg-white/[0.045] ${className}`}
>
{title || extra ? (
<div className='flex items-center justify-between gap-2 mb-2'>
@@ -383,12 +383,14 @@ const ImageGenerationForm = ({ creation }) => {
loading={submitting}
onClick={handleSubmit}
disabled={isButtonDisabled}
className='!rounded-2xl !shadow-lg !shadow-brand/20 hover:!shadow-xl hover:!shadow-brand/25 !transition-all'
className='!rounded-2xl !transition-colors'
style={{
background: isButtonDisabled
? 'var(--ui-color-fill-1)'
: 'linear-gradient(135deg, var(--brand-gradient-from) 0%, var(--brand-primary) 52%, var(--brand-gradient-to) 100%)',
border: 'none',
border: isButtonDisabled
? '1px solid var(--igf-line)'
: '1px solid transparent',
color: isButtonDisabled ? 'var(--ui-color-text-3)' : 'white',
height: '48px',
fontSize: '15px',
@@ -538,328 +540,337 @@ const ImageGenerationForm = ({ creation }) => {
return (
<div
className={`image-generation-form relative flex h-full flex-col overflow-y-auto overflow-x-hidden rounded-[28px] border border-white/[0.55] bg-white/[0.42] p-4 shadow-[0_24px_80px_rgba(15,23,42,0.10)] backdrop-blur-2xl backdrop-saturate-150 transition-colors app-scrollbar dark:border-white/10 dark:bg-neutral-950/[0.40] dark:shadow-[0_24px_80px_rgba(0,0,0,0.35)]${dropActive ? ' is-drop-active' : ''}`}
className={`image-generation-form relative flex h-full min-h-0 flex-col overflow-hidden rounded-[28px] border border-[var(--igf-line)] bg-white/[0.42] shadow-[0_24px_80px_rgba(15,23,42,0.10)] backdrop-blur-2xl backdrop-saturate-150 transition-colors dark:bg-neutral-950/[0.40] dark:shadow-[0_24px_80px_rgba(0,0,0,0.35)]${dropActive ? ' is-drop-active' : ''}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{/* 标题 */}
<div className='mb-5 rounded-3xl border border-white/60 bg-white/[0.50] p-4 shadow-sm backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.05]'>
<div className='flex items-center justify-between gap-2'>
<div className='flex-1 min-w-0'>
<div className='mb-2 inline-flex items-center gap-2 rounded-full border border-brand/25 bg-brand/10 px-2.5 py-1 text-[11px] font-medium text-brand-deep dark:border-brand/25 dark:bg-brand/15 dark:text-brand-from'>
<Sparkles size={12} />
{t('AI 图片创作')}
<div className='igf-form-scroll app-scrollbar'>
{/* 标题 */}
<div className='mb-5 rounded-3xl border border-white/60 bg-white/[0.50] p-4 shadow-sm backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.05]'>
<div className='flex items-center justify-between gap-2'>
<div className='flex-1 min-w-0'>
<div className='mb-2 inline-flex items-center gap-2 rounded-full border border-brand/25 bg-brand/10 px-2.5 py-1 text-[11px] font-medium text-brand-deep dark:border-brand/25 dark:bg-brand/15 dark:text-brand-from'>
<Sparkles size={12} />
{t('AI 图片创作')}
</div>
<Title
heading={4}
style={{ margin: 0 }}
className='text-gray-900 dark:text-white'
>
{t('图片生成')}
</Title>
<Text
type='secondary'
size='small'
className='text-gray-500 dark:text-gray-400 mt-1 block truncate'
>
{formBodyHidden && selectedModel
? selectedModel.display_name || selectedModel.model
: t('输入描述即可生成图片')}
</Text>
</div>
<Title
heading={4}
style={{ margin: 0 }}
className='text-gray-900 dark:text-white'
>
{t('图片生成')}
</Title>
<div className='flex items-center gap-1'>
{!formBodyHidden && (
<Button
icon={<ActionRotateCcw size={12} />}
size='small'
theme='borderless'
onClick={handleReset}
className='!text-gray-500 hover:!text-brand-deep dark:hover:!text-brand-from'
>
{t('重置')}
</Button>
)}
{isMobile && (
<Button
icon={
mobileCollapsed ? (
<ActionChevronDown size={14} />
) : (
<ActionChevronUp size={14} />
)
}
size='small'
theme='borderless'
onClick={() => setMobileCollapsed(!mobileCollapsed)}
className='!text-gray-500'
>
{mobileCollapsed ? t('展开') : t('收起')}
</Button>
)}
</div>
</div>
</div>
{/* 移动端折叠时只显示生成按钮 + 简略 */}
{formBodyHidden && (
<div className='mt-2'>
{renderGenerateArea()}
<Text
type='secondary'
type='tertiary'
size='small'
className='text-gray-500 dark:text-gray-400 mt-1 block truncate'
className='block mt-2 text-center'
>
{formBodyHidden && selectedModel
? selectedModel.display_name || selectedModel.model
: t('输入描述即可生成图片')}
{prompt
? prompt.length > 50
? prompt.slice(0, 50) + '...'
: prompt
: t('点击展开编辑参数')}
</Text>
</div>
<div className='flex items-center gap-1'>
{!formBodyHidden && (
<Button
icon={<ActionRotateCcw size={12} />}
size='small'
theme='borderless'
onClick={handleReset}
className='!text-gray-500 hover:!text-brand-deep dark:hover:!text-brand-from'
>
{t('重置')}
</Button>
)}
{isMobile && (
<Button
icon={
mobileCollapsed ? (
<ActionChevronDown size={14} />
) : (
<ActionChevronUp size={14} />
)
}
size='small'
theme='borderless'
onClick={() => setMobileCollapsed(!mobileCollapsed)}
className='!text-gray-500'
>
{mobileCollapsed ? t('展开') : t('收起')}
</Button>
)}
</div>
</div>
</div>
)}
{/* 移动端折叠时只显示生成按钮 + 简略 */}
{formBodyHidden && (
<div className='mt-2'>
{renderGenerateArea()}
<Text type='tertiary' size='small' className='block mt-2 text-center'>
{prompt
? prompt.length > 50
? prompt.slice(0, 50) + '...'
: prompt
: t('点击展开编辑参数')}
</Text>
</div>
)}
{!formBodyHidden && (
<>
{/* 模型选择 */}
<Section title={t('选择模型')}>{renderModelSection()}</Section>
{!formBodyHidden && (
<>
{/* 模型选择 */}
<Section title={t('选择模型')}>{renderModelSection()}</Section>
{/* 生成方式(来自 schema modes) */}
{selectedModel && modeOptions.length > 1 ? (
<Section title={t('生成方式')}>
<OptionGroup
options={modeOptions.map((o) => o.mode)}
value={formData.mode}
onChange={setMode}
ariaLabel={t('生成方式')}
optionDisabledReasons={Object.fromEntries(
modeOptions
.filter((o) => o.disabled)
.map((o) => [o.mode, t(o.reason || '当前不可用')]),
)}
renderOption={(mode) => {
const Icon = MODE_ICONS[mode] || Type;
return (
<span className='igf-mode-option'>
<Icon size={14} aria-hidden='true' />
{t(MODE_LABEL_KEYS[mode] || mode)}
</span>
);
}}
/>
</Section>
) : null}
{/* 生成方式(来自 schema modes) */}
{selectedModel && modeOptions.length > 1 ? (
<Section title={t('生成方式')}>
<OptionGroup
options={modeOptions.map((o) => o.mode)}
value={formData.mode}
onChange={setMode}
ariaLabel={t('生成方式')}
optionDisabledReasons={Object.fromEntries(
modeOptions
.filter((o) => o.disabled)
.map((o) => [o.mode, t(o.reason || '当前不可用')]),
)}
renderOption={(mode) => {
const Icon = MODE_ICONS[mode] || Type;
return (
<span className='igf-mode-option'>
<Icon size={14} aria-hidden='true' />
{t(MODE_LABEL_KEYS[mode] || mode)}
</span>
);
}}
/>
</Section>
) : null}
{/* 提示词 + 模板 + 历史 */}
<Section
title={t('提示词')}
extra={
<div className='flex items-center gap-2'>
{/* AI 优化提示词 —— 按钮始终可点击,handler 内判断并 Toast 解释原因 */}
<button
type='button'
onClick={handleOptimizePrompt}
aria-label={t('AI 优化提示词')}
className={[
'app-action-button',
[
'flex items-center gap-1 text-[10px] transition-colors',
optimizing
? 'text-brand-from'
: 'text-gray-400 hover:text-brand-deep dark:hover:text-brand-from',
].join(' '),
]
.filter(Boolean)
.join(' ')}
title={
textModels?.length
? t('AI 优化提示词 (使用 {{m}})', {
m: textModels[0].model_name,
})
: t('AI 优化提示词')
}
>
<Sparkles
size={10}
className={optimizing ? 'animate-pulse' : ''}
/>
<span>{optimizing ? t('优化中...') : t('AI 优化')}</span>
</button>
{promptHistory.length > 0 && (
<Dropdown
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu style={{ maxWidth: 360 }}>
{promptHistory.map((p, idx) => (
<Dropdown.Item key={idx} onClick={() => setPrompt(p)}>
<div
style={{
maxWidth: 320,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
title={p}
>
{p}
</div>
</Dropdown.Item>
))}
</Dropdown.Menu>
{/* 提示词 + 模板 + 历史 */}
<Section
title={t('提示词')}
extra={
<div className='flex items-center gap-2'>
{/* AI 优化提示词 —— 按钮始终可点击,handler 内判断并 Toast 解释原因 */}
<button
type='button'
onClick={handleOptimizePrompt}
aria-label={t('AI 优化提示词')}
className={[
'app-action-button',
[
'flex items-center gap-1 text-[10px] transition-colors',
optimizing
? 'text-brand-from'
: 'text-gray-400 hover:text-brand-deep dark:hover:text-brand-from',
].join(' '),
]
.filter(Boolean)
.join(' ')}
title={
textModels?.length
? t('AI 优化提示词 (使用 {{m}})', {
m: textModels[0].model_name,
})
: t('AI 优化提示词')
}
>
<button
type='button'
className='app-action-button flex items-center gap-1 text-[10px] text-gray-400 hover:text-brand-deep dark:hover:text-brand-from transition-colors'
<Sparkles
size={10}
className={optimizing ? 'animate-pulse' : ''}
/>
<span>{optimizing ? t('优化中...') : t('AI 优化')}</span>
</button>
{promptHistory.length > 0 && (
<Dropdown
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu style={{ maxWidth: 360 }}>
{promptHistory.map((p, idx) => (
<Dropdown.Item
key={idx}
onClick={() => setPrompt(p)}
>
<div
style={{
maxWidth: 320,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
title={p}
>
{p}
</div>
</Dropdown.Item>
))}
</Dropdown.Menu>
}
>
<ActionHistory size={10} />
<span>{t('历史')}</span>
</button>
</Dropdown>
)}
<span className='flex items-center gap-1 text-[10px] text-gray-400'>
{IS_MAC ? (
<Command size={10} />
) : (
<span>{I18N_TECHNICAL_TEXT.CTRL}</span>
<button
type='button'
className='app-action-button flex items-center gap-1 text-[10px] text-gray-400 hover:text-brand-deep dark:hover:text-brand-from transition-colors'
>
<ActionHistory size={10} />
<span>{t('历史')}</span>
</button>
</Dropdown>
)}
<span>+</span>
<span>{I18N_TECHNICAL_TEXT.ENTER}</span>
<span>{t('生成')}</span>
</span>
</div>
}
>
<TextArea
placeholder={t('描述你想要生成的图片内容...')}
value={prompt}
onChange={setPrompt}
onKeyDown={handlePromptKeyDown}
rows={3}
maxCount={2000}
showClear
className='[&_.ant-input-textarea]:!rounded-2xl [&_.ant-input-textarea]:!border-white/[0.55] [&_.ant-input-textarea]:!bg-white/[0.55] [&_.ant-input-textarea]:!shadow-inner dark:[&_.ant-input-textarea]:!border-white/10 dark:[&_.ant-input-textarea]:!bg-white/[0.06] [&_.ant-input-textarea:hover]:!border-brand/30 [&_.ant-input-textarea:focus]:!border-brand'
/>
<div className='flex flex-wrap items-center gap-1.5 mt-2'>
<div className='flex items-center gap-1 text-[10px] text-gray-400 mr-1'>
<Sparkles size={10} />
<span>{t('快速模板')}</span>
</div>
{PROMPT_TEMPLATES.map((tpl) => (
<Tag
key={tpl.label}
size='small'
color='grey'
onClick={() => handleApplyTemplate(tpl)}
className='!cursor-pointer !rounded-full !border-white/50 !bg-white/[0.45] !backdrop-blur hover:!bg-brand/10 dark:!border-white/10 dark:!bg-white/[0.06] dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-colors'
>
{t(tpl.label)}
</Tag>
))}
</div>
</Section>
{/* 参考图:编辑模式的带标签槽位;当前模型 / 模式用不到的图片置灰保留 */}
{selectedModel && imageSlots.length > 0 ? (
<Section
title={t('参考图片')}
extra={
<Text type='tertiary' className='!text-[10px]'>
{t('可从右侧历史拖拽图片到这里')}
</Text>
<span className='flex items-center gap-1 text-[10px] text-gray-400'>
{IS_MAC ? (
<Command size={10} />
) : (
<span>{I18N_TECHNICAL_TEXT.CTRL}</span>
)}
<span>+</span>
<span>{I18N_TECHNICAL_TEXT.ENTER}</span>
<span>{t('生成')}</span>
</span>
</div>
}
>
<div className='igf-slots'>
{imageSlots.map((entry) => {
const slot = entry.slot;
const value = slot
? {
previewUrl: slot.previewUrl,
status: entry.active
? slot.status || 'ready'
: 'unused',
error: slot.error,
}
: null;
return (
<ImageSlot
key={`ref-${entry.index}-${slot?.id || 'empty'}`}
label={slotLabel(entry)}
value={value}
onPick={(file) => pickImage(entry.index, file)}
onRemove={() => removeImage(entry.index)}
onRetry={() => retryImage(entry.index, slot)}
/>
);
})}
</div>
{hasUnusedImage ? (
<div className='igf-muted igf-note' role='note'>
{t('置灰的图片当前不会提交,切回支持的模型或模式后自动恢复')}
<TextArea
placeholder={t('描述你想要生成的图片内容...')}
value={prompt}
onChange={setPrompt}
onKeyDown={handlePromptKeyDown}
rows={3}
maxCount={2000}
showClear
className='[&_.ant-input-textarea]:!rounded-2xl [&_.ant-input-textarea]:!border-white/[0.55] [&_.ant-input-textarea]:!bg-white/[0.55] [&_.ant-input-textarea]:!shadow-inner dark:[&_.ant-input-textarea]:!border-white/10 dark:[&_.ant-input-textarea]:!bg-white/[0.06] [&_.ant-input-textarea:hover]:!border-brand/30 [&_.ant-input-textarea:focus]:!border-brand'
/>
<div className='flex flex-wrap items-center gap-1.5 mt-2'>
<div className='flex items-center gap-1 text-[10px] text-gray-400 mr-1'>
<Sparkles size={10} />
<span>{t('快速模板')}</span>
</div>
) : null}
{PROMPT_TEMPLATES.map((tpl) => (
<Tag
key={tpl.label}
size='small'
color='grey'
onClick={() => handleApplyTemplate(tpl)}
className='!cursor-pointer !rounded-full !border-white/50 !bg-white/[0.45] !backdrop-blur hover:!bg-brand/10 dark:!border-white/10 dark:!bg-white/[0.06] dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-colors'
>
{t(tpl.label)}
</Tag>
))}
</div>
</Section>
) : null}
{/* 尺寸 + 常用参数(画质 / 数量等) */}
{selectedModel && (sizeParam || dockParams.length > 0) ? (
<Section title={sizeParam ? t('尺寸') : t('生成参数')}>
{sizeParam ? (
<ImageSizePicker
param={sizeParam}
value={formData.params?.size}
onChange={(v) => updateParam('size', v)}
/>
) : null}
{dockParams.length > 0 ? (
<ParamRenderer
className={sizeParam ? 'igf-dock-params' : ''}
params={visibleParams}
values={formData.params}
onChange={updateParam}
placement='dock'
constraints={constraints}
/>
) : null}
</Section>
) : null}
{/* 高级选项 */}
{selectedModel && advancedParams.length > 0 ? (
<Section>
<button
type='button'
onClick={() => setShowAdvanced(!showAdvanced)}
aria-expanded={showAdvanced}
className='app-action-button flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from transition-colors'
{/* 参考图:编辑模式的带标签槽位;当前模型 / 模式用不到的图片置灰保留 */}
{selectedModel && imageSlots.length > 0 ? (
<Section
title={t('参考图片')}
extra={
<Text type='tertiary' className='!text-[10px]'>
{t('可从右侧历史拖拽图片到这里')}
</Text>
}
>
<ActionSettings size={12} />
<span>{t('高级选项')}</span>
{showAdvanced ? (
<ActionChevronUp size={12} />
) : (
<ActionChevronDown size={12} />
)}
</button>
<Collapsible isOpen={showAdvanced} keepDOM>
<div className='pt-3'>
<div className='igf-slots'>
{imageSlots.map((entry) => {
const slot = entry.slot;
const value = slot
? {
previewUrl: slot.previewUrl,
status: entry.active
? slot.status || 'ready'
: 'unused',
error: slot.error,
}
: null;
return (
<ImageSlot
key={`ref-${entry.index}-${slot?.id || 'empty'}`}
label={slotLabel(entry)}
value={value}
onPick={(file) => pickImage(entry.index, file)}
onRemove={() => removeImage(entry.index)}
onRetry={() => retryImage(entry.index, slot)}
/>
);
})}
</div>
{hasUnusedImage ? (
<div className='igf-muted igf-note' role='note'>
{t(
'置灰的图片当前不会提交,切回支持的模型或模式后自动恢复',
)}
</div>
) : null}
</Section>
) : null}
{/* 尺寸 + 常用参数(画质 / 数量等) */}
{selectedModel && (sizeParam || dockParams.length > 0) ? (
<Section title={sizeParam ? t('尺寸') : t('生成参数')}>
{sizeParam ? (
<ImageSizePicker
param={sizeParam}
value={formData.params?.size}
onChange={(v) => updateParam('size', v)}
/>
) : null}
{dockParams.length > 0 ? (
<ParamRenderer
className={sizeParam ? 'igf-dock-params' : ''}
params={visibleParams}
values={formData.params}
onChange={updateParam}
placement='advanced'
placement='dock'
constraints={constraints}
/>
</div>
</Collapsible>
</Section>
) : null}
) : null}
</Section>
) : null}
{/* 生成按钮 + 估价 */}
<div className='sticky bottom-0 -mx-4 mt-auto bg-transparent px-4 pt-4 pb-1'>
{renderGenerateArea()}
</div>
</>
{/* 高级选项 */}
{selectedModel && advancedParams.length > 0 ? (
<Section>
<button
type='button'
onClick={() => setShowAdvanced(!showAdvanced)}
aria-expanded={showAdvanced}
className='app-action-button flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-brand-deep dark:hover:text-brand-from transition-colors'
>
<ActionSettings size={12} />
<span>{t('高级选项')}</span>
{showAdvanced ? (
<ActionChevronUp size={12} />
) : (
<ActionChevronDown size={12} />
)}
</button>
<Collapsible isOpen={showAdvanced} keepDOM>
<div className='pt-3'>
<ParamRenderer
params={visibleParams}
values={formData.params}
onChange={updateParam}
placement='advanced'
constraints={constraints}
/>
</div>
</Collapsible>
</Section>
) : null}
</>
)}
</div>
{!formBodyHidden && (
<div className='igf-generate-wrap'>{renderGenerateArea()}</div>
)}
</div>
);
@@ -203,6 +203,22 @@
overflow: hidden;
}
/* Override antd Collapse defaults so the advanced panel shares the input cards' line. */
.vip-advanced .ant-collapse {
border: 0;
border-radius: inherit;
background: transparent;
}
.vip-advanced .ant-collapse-item {
border-bottom: 0;
}
.vip-advanced .ant-collapse-header:focus-visible {
outline: 2px solid var(--vip-accent);
outline-offset: -2px;
}
.vip-advanced .ant-collapse-header {
margin: 0;
padding: 12px 16px;
@@ -24,6 +24,7 @@ import {
Trash2 as ActionTrash2,
AlertCircle as ActionAlertCircle,
} from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect } from 'react';
import {
Table,
@@ -239,69 +240,63 @@ const VideoTaskQueue = ({
{
title: t('操作'),
dataIndex: 'operate',
width: !isCompact ? 220 : 180,
width: 168,
fixed: 'right',
render: (text, record) => {
const normalizedStatus = normalizeVideoTaskStatus(record.status);
return (
<Space>
{/* 播放和下载按钮:仅根据状态显示,视频URL在点击时才获取 */}
<TableRowActions
items={[
normalizedStatus === 'success' && {
key: 'download',
label: t('下载'),
onClick: () => onDownload(record),
icon: <ActionDownload size={14} />,
},
(normalizedStatus === 'success' ||
normalizedStatus === 'failure') &&
canRegenerateVideoTask(record) && {
key: 'regenerate',
label: t('再生成'),
onClick: () => onRegenerate && onRegenerate(record),
icon: <ActionRefreshCw size={14} />,
},
{
key: 'delete',
label: t('删除'),
onClick: () => {
Modal.warning({
title: t('确定删除此任务?'),
content: t('删除后将无法恢复'),
icon: (
<ActionAlertCircle
size={24}
style={{ color: '#f59e0b' }}
/>
),
okText: t('确定'),
cancelText: t('取消'),
onOk: () => onDelete(record.task_id),
centered: true,
okButtonProps: { type: 'danger' },
});
},
icon: <ActionTrash2 size={14} />,
danger: true,
},
]}
>
{normalizedStatus === 'success' && (
<>
<Button
size='small'
type='tertiary'
icon={<ActionPlay size={14} />}
onClick={() => onPlay && onPlay(record)}
>
{!isCompact ? t('播放') : ''}
</Button>
<Button
size='small'
type='tertiary'
icon={<ActionDownload size={14} />}
onClick={() => onDownload(record)}
>
{!isCompact ? t('下载') : ''}
</Button>
</>
<Button
size='small'
type='tertiary'
icon={<ActionPlay size={14} />}
onClick={() => onPlay && onPlay(record)}
>
{t('播放')}
</Button>
)}
{/* 再生成按钮 - 对所有已完成或失败的任务显示 */}
{(normalizedStatus === 'success' ||
normalizedStatus === 'failure') &&
canRegenerateVideoTask(record) && (
<Button
size='small'
type='primary'
icon={<ActionRefreshCw size={14} />}
onClick={() => onRegenerate && onRegenerate(record)}
>
{!isCompact ? t('再生成') : ''}
</Button>
)}
<Button
size='small'
type='danger'
icon={<ActionTrash2 size={14} />}
onClick={() => {
Modal.warning({
title: t('确定删除此任务?'),
content: t('删除后将无法恢复'),
icon: (
<ActionAlertCircle size={24} style={{ color: '#f59e0b' }} />
),
okText: t('确定'),
cancelText: t('取消'),
onOk: () => onDelete(record.task_id),
centered: true,
okButtonProps: { type: 'danger' },
});
}}
>
{!isCompact ? t('删除') : ''}
</Button>
</Space>
</TableRowActions>
);
},
},
+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 { formatIdReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import {
@@ -2340,8 +2341,8 @@ const ExpertPlatform = () => {
className={`expert-diagnose-model ${row.success ? 'is-ok' : 'is-blocked'}`}
>
<strong>
{row.channel_name || `#${row.channel_id}`}
<em>{`#${row.channel_id}`}</em>
{row.channel_name || formatIdReference(row.channel_id)}
<em>{formatIdReference(row.channel_id)}</em>
</strong>
<small>
{row.success
@@ -2392,7 +2393,7 @@ const ExpertPlatform = () => {
}
optionList={channels.map((channel) => ({
value: channel.id,
label: `#${channel.id} · ${channel.name}`,
label: `${formatIdReference(channel.id)} · ${channel.name}`,
}))}
placeholder={t('选择已启用渠道')}
/>
+2 -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 { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useState, useEffect } from 'react';
@@ -455,7 +456,7 @@ const ChannelMonitor = () => {
: 'var(--ui-color-danger)',
}}
>
{channel.uptime.toFixed(2)}%
{formatPercent(channel.uptime, 2)}
</span>
</div>
<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 { formatPercent } from '../../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React from 'react';
@@ -220,7 +221,10 @@ const ChannelMonitorView = ({ channelStatus, onRefresh }) => {
>
{renderSparkline(channel.uptime || 0)}
<Text type='success' strong>
{((channel.uptime || 0) * 100).toFixed(1)}%
{formatPercent(
Number(channel.uptime || 0) * 100,
1,
)}
</Text>
</div>
</div>
+8 -18
View File
@@ -34,11 +34,7 @@ import {
} from '@/components/ui';
import { API } from '../../helpers/api';
import { showError, getLogo, getSystemName } from '../../helpers';
import {
setUserData,
savePostLoginRedirect,
consumePostLoginRedirect,
} from '../../helpers/data';
import { setUserData } from '../../helpers/data';
import { updateAPI } from '../../helpers/api';
import { finishLogin } from '../../helpers/loginFlow';
import { UserContext } from '../../context/User';
@@ -219,14 +215,10 @@ const OrgLogin = () => {
}
};
// 与 /login 对齐的入口参数处理:?redirect= 写回本地存储(新标签页打开也能回跳),
// ?expired=true 提示会话过期后从 URL 清除(避免刷新重复提示)。
const expiryShown = useRef(false);
useEffect(() => {
const redirect = searchParams.get('redirect');
if (redirect) {
savePostLoginRedirect(redirect);
}
if (searchParams.get('expired')) {
if (searchParams.get('expired') && !expiryShown.current) {
expiryShown.current = true;
showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired');
@@ -283,9 +275,8 @@ const OrgLogin = () => {
userDispatch,
navigate,
t,
// 消费被保护页跳来时保存的回跳地址(尊重深链意图,同时避免残留值
// 影响之后的个人登录);无保存值则进企业工作台
redirectOverride: consumePostLoginRedirect('/org/workbench'),
enterprise: true,
redirect: searchParams.get('redirect'),
});
}
};
@@ -416,9 +407,8 @@ const OrgLogin = () => {
userDispatch,
navigate,
t,
successMessage: '',
// 首登改密路径同样消费保存的回跳地址,默认进企业工作台
redirectOverride: consumePostLoginRedirect('/org/workbench'),
enterprise: true,
redirect: searchParams.get('redirect'),
});
} else {
showError(res.data.message);
+2 -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 { formatUserReference } from '../../helpers/safeDisplay';
import {
Search as ActionSearch,
RefreshCw as ActionRefreshCw,
@@ -306,7 +307,7 @@ const OrgAudit = ({ orgId }) => {
title: t('操作者'),
dataIndex: 'operator_name',
width: 130,
render: (name, record) => name || `User#${record.operator_id}`,
render: (name, record) => formatUserReference(name, record.operator_id),
},
{
title: t('操作类型'),
+17 -8
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 {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
@@ -106,10 +107,14 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (!orgId) return;
setLoading(true);
try {
const options = {
headers: getOrgHeaders(orgId),
requestGroup: new AbortController(),
};
const [b, d, p] = await Promise.all([
API.get('/api/org/budget', { headers: getOrgHeaders(orgId) }),
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
API.get('/api/org/project', { headers: getOrgHeaders(orgId) }),
API.get('/api/org/budget', options),
API.get('/api/org/dept', options),
API.get('/api/org/project', options),
]);
if (b.data.success) {
// 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组。
@@ -122,7 +127,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (d.data.success) setDepts(d.data.data || []);
if (p.data.success) setProjects(p.data.data || []);
} catch (err) {
showError(err.message);
if (!err?.isAxiosError) showError(err);
} finally {
setLoading(false);
}
@@ -139,7 +144,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
const st = r.subject_type;
if (r.subject_exists !== undefined) {
return {
name: r.subject_name || `#${r.subject_id}`,
name: r.subject_name || formatIdReference(r.subject_id),
exists: !!r.subject_exists,
disabled: r.subject_status === 2,
};
@@ -147,7 +152,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (st === 'department') {
const d = depts.find((x) => x.id === r.subject_id);
return {
name: d?.name || `#${r.subject_id}`,
name: d?.name || formatIdReference(r.subject_id),
exists: !!d,
disabled: d?.status === 2,
};
@@ -155,13 +160,17 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (st === 'project') {
const p = projects.find((x) => x.id === r.subject_id);
return {
name: p?.name || `#${r.subject_id}`,
name: p?.name || formatIdReference(r.subject_id),
exists: !!p,
disabled: p?.status === 2,
};
}
// 旧后端下成员/密钥无从解析,按存在处理,避免误标「已删除」
return { name: `#${r.subject_id}`, exists: true, disabled: false };
return {
name: formatIdReference(r.subject_id),
exists: true,
disabled: false,
};
},
[depts, projects],
);
+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 {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
@@ -186,7 +187,9 @@ const OrgDepartments = ({ orgId }) => {
const deptName = useCallback(
(id) =>
id ? list.find((d) => d.id === id)?.name || `#${id}` : t('顶级部门'),
id
? list.find((d) => d.id === id)?.name || formatIdReference(id)
: t('顶级部门'),
[list, t],
);
+11 -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 {
RefreshCw as ActionRefreshCw,
Check as ActionCheck,
@@ -213,7 +215,8 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
const nameMap = useMemo(() => {
const m = {};
members.forEach((x) => {
m[x.id] = x.remark || x.display_name || x.username || `#${x.id}`;
m[x.id] =
x.remark || x.display_name || x.username || formatIdReference(x.id);
});
return m;
}, [members]);
@@ -273,7 +276,7 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
{
title: t('成员'),
dataIndex: 'display_name',
render: (v, r) => r.remark || v || r.username || `#${r.id}`,
render: (v, r) => r.remark || v || r.username || formatIdReference(r.id),
},
{
title: t('已用额度'),
@@ -299,7 +302,8 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
{
title: t('成员'),
dataIndex: 'display_name',
render: (v, r) => v || r.username || `#${r.user_id}`,
render: (v, r) =>
formatUserReference(v || r.username, r.user_id, t('未知用户')),
},
{
title: t('消耗'),
@@ -437,8 +441,10 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
>
<div className='min-w-0'>
<Text>
{nameMap[r.requester_id] || `#${r.requester_id}`} ·{' '}
{t('提额')} {renderQuota(parseDelta(r.payload), 2)}
{nameMap[r.requester_id] ||
formatIdReference(r.requester_id)}{' '}
· {t('提额')}{' '}
{renderQuota(parseDelta(r.payload), 2)}
</Text>
<div>
<Text type='tertiary' size='small'>
+16 -6
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 { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
@@ -414,13 +416,15 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
title: t('技能'),
dataIndex: 'name',
render: (name, record) =>
name || record.canonical_id || `#${record.skill_id}`,
name ||
record.canonical_id ||
formatIdReference(record.skill_id),
},
{ title: t('调用次数'), dataIndex: 'request_count' },
{
title: t('占比'),
dataIndex: 'share_percent',
render: (share) => `${(share || 0).toFixed(1)}%`,
render: (share) => formatPercent(share, 1),
},
{
title: t('提示词 token'),
@@ -545,13 +549,16 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
<span>
{t('首次交付通过率')}:{' '}
{row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足')}
</span>
<span>
{t('退回率')}:{' '}
{row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足')}
</span>
<span>
@@ -574,14 +581,17 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
title: t('首次交付通过率'),
render: (_, row) =>
row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足'),
},
{
title: t('退回率'),
render: (_, row) =>
row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足'),
},
{
+6 -2
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 { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import {
@@ -1887,7 +1889,7 @@ const OrgKnowledge = ({ orgId, canAuditContent = false }) => {
label:
member.display_name ||
member.username ||
`#${member.id}`,
formatIdReference(member.id),
}))}
/>
<Select
@@ -1959,7 +1961,9 @@ const OrgKnowledge = ({ orgId, canAuditContent = false }) => {
<div className='knowledge-hit-body'>
<div className='knowledge-hit-title'>
<strong>{hit.source_label}</strong>
<span>{(hit.score * 100).toFixed(1)}%</span>
<span>
{formatPercent(Number(hit.score) * 100, 1)}
</span>
</div>
<div className='knowledge-hit-meta'>
{hit.base_name && <span>{hit.base_name}</span>}
+10 -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 { formatUserReference } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import {
@@ -486,7 +487,10 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
const key = log.user_id ?? 'unknown';
if (!groups.has(key)) {
groups.set(key, {
name: log.display_name || log.username || `User#${log.user_id}`,
name: formatUserReference(
log.display_name || log.username,
log.user_id,
),
rows: [],
});
}
@@ -595,7 +599,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
members.forEach((m) => {
opts.push({
value: m.user_id,
label: m.display_name || m.username || `User#${m.user_id}`,
label: formatUserReference(m.display_name || m.username, m.user_id),
});
});
return opts;
@@ -616,7 +620,10 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
: t('仅本人');
if (canViewTeamUsage && af.userId) {
const m = members.find((x) => String(x.user_id) === String(af.userId));
member = m ? m.display_name || m.username : `User#${af.userId}`;
member = formatUserReference(
m?.display_name || m?.username,
m?.user_id ?? af.userId,
);
}
const time =
af.startTimestamp && af.endTimestamp
+60 -51
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 {
RefreshCw as ActionRefreshCw,
UserPlus as ActionUserPlus,
@@ -30,7 +32,7 @@ import {
Form,
Toast,
Tag,
Popconfirm,
Modal,
Banner,
Typography,
Tooltip,
@@ -40,7 +42,8 @@ import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import DeptTreeSelect from './components/DeptTreeSelect';
import {
@@ -327,7 +330,13 @@ const OrgMemberAccounts = ({
title: t('成员'),
render: (_, r) => (
<div className='flex items-center gap-2'>
<span>{r.display_name || r.username || `#${r.user_id}`}</span>
<span>
{formatUserReference(
r.display_name || r.username,
r.user_id,
t('未知用户'),
)}
</span>
{r.created_by_org_id !== r.organization_id && (
<Tooltip content={t('个人平台账号(非本企业托管)')}>
<Tag size='small' color='blue'>
@@ -351,8 +360,8 @@ const OrgMemberAccounts = ({
width: 120,
render: (v) =>
v ? (
<Tooltip content={deptFullNameMap[v] || `#${v}`}>
<span>{deptNameMap[v] || `#${v}`}</span>
<Tooltip content={deptFullNameMap[v] || formatIdReference(v)}>
<span>{deptNameMap[v] || formatIdReference(v)}</span>
</Tooltip>
) : (
<span className='text-gray-400'>{t('未分配')}</span>
@@ -382,7 +391,7 @@ const OrgMemberAccounts = ({
},
{
title: t('操作'),
width: 260,
width: 110,
render: (_, r) => {
const managed = r.created_by_org_id === r.organization_id;
// 与后端 model.ResetManagedMemberPassword 的分级拦截保持一致
@@ -396,53 +405,53 @@ const OrgMemberAccounts = ({
}
const canReset = !resetBlockedReason;
return (
<OrgRowActions>
{deptEnabled && (
<Button
type='link'
onClick={() => {
<TableRowActions
items={[
deptEnabled && {
key: 'department',
label: t('分配部门'),
onClick: () => {
setDeptAssignFor(r);
setDeptAssignVal(r.department_id || 0);
}}
>
{t('分配部门')}
</Button>
)}
{canReset ? (
<Popconfirm
title={t('重置该账号密码?')}
content={
managed
? t('将生成一次性临时密码,并要求首次登录改密')
: t(
'该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人',
)
}
onConfirm={() => resetPassword(r)}
>
<Button type='link'>{t('重置密码')}</Button>
</Popconfirm>
) : (
<Tooltip content={resetBlockedReason}>
<Button type='link' disabled>
{t('重置密码')}
</Button>
</Tooltip>
)}
{r.status === 1 && r.role !== 'owner' && (
<Popconfirm
title={t('确认离职回收该成员?')}
content={t(
'将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户',
)}
onConfirm={() => offboard(r.id)}
>
<Button type='link' danger>
{t('离职回收')}
</Button>
</Popconfirm>
)}
</OrgRowActions>
},
},
{
key: 'reset-password',
label: t('重置密码'),
disabled: !canReset,
title: resetBlockedReason || undefined,
onClick: () =>
Modal.confirm({
title: t('重置该账号密码?'),
content: managed
? t('将生成一次性临时密码,并要求首次登录改密')
: t(
'该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人',
),
okText: t('确认'),
cancelText: t('取消'),
onOk: () => resetPassword(r),
}),
},
r.status === 1 &&
r.role !== 'owner' && {
key: 'offboard',
label: t('离职回收'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认离职回收该成员?'),
content: t(
'将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户',
),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => offboard(r.id),
}),
},
]}
/>
);
},
},
+54 -59
View File
@@ -30,7 +30,7 @@ import {
Input,
Select,
Tag,
Popconfirm,
Modal,
Toast,
Tooltip,
Switch,
@@ -42,7 +42,8 @@ import QuotaInput from '../../components/common/ui/QuotaInput';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import { Alert as AntAlert, Tabs as AntTabs } from 'antd';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import OrgMemberAccounts from './OrgMemberAccounts';
@@ -572,7 +573,7 @@ const OrgMembers = ({
if (canWrite) {
memberColumns.push({
title: t('操作'),
width: 260,
width: 110,
fixed: 'right',
render: (_, record) => {
if (record.role === 'owner') {
@@ -580,11 +581,13 @@ const OrgMembers = ({
}
const isSelf = Number(record.user_id) === currentUserId;
return (
<OrgRowActions>
<Tooltip content={t('设置该成员的个人额度上限')}>
<Button
type='link'
onClick={() => {
<TableRowActions
items={[
{
key: 'quota',
label: t('配额'),
title: t('设置该成员的个人额度上限'),
onClick: () => {
setQuotaMemberId(record.id);
setQuotaMemberName(
record.display_name || record.username || '',
@@ -592,15 +595,13 @@ const OrgMembers = ({
setQuotaLimit(record.quota_limit || 0);
setQuotaPeriod(record.quota_period || 'none');
setQuotaModalVisible(true);
}}
>
{t('配额')}
</Button>
</Tooltip>
<Tooltip content={t('设置该成员可用的模型范围')}>
<Button
type='link'
onClick={async () => {
},
},
{
key: 'models',
label: t('模型'),
title: t('设置该成员可用的模型范围'),
onClick: async () => {
setModelLimitsMemberId(record.id);
setModelLimitsMemberName(
record.display_name || record.username || '',
@@ -629,22 +630,15 @@ const OrgMembers = ({
/* ignore */
}
setLoadingOrgModels(false);
}}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip
content={
isSelf
},
},
{
key: 'groups',
label: t('分组'),
title: isSelf
? t('不能修改自己的可调用分组')
: t('设置该成员可调用的分组')
}
>
<Button
type='link'
disabled={isSelf}
onClick={() => {
: t('设置该成员可调用的分组'),
onClick: () => {
if (isSelf) return;
setGroupsMemberId(record.id);
setGroupsMemberName(
@@ -652,16 +646,15 @@ const OrgMembers = ({
);
setSelectedMemberGroups(parseMemberGroups(record));
setGroupsModalVisible(true);
}}
>
{t('分组')}
</Button>
</Tooltip>
{orgRole === 'owner' && record.role === 'admin' && (
<Tooltip content={t('设置该管理员的细粒度权限')}>
<Button
type='link'
onClick={() => {
},
disabled: isSelf,
},
orgRole === 'owner' &&
record.role === 'admin' && {
key: 'permissions',
label: t('权限'),
title: t('设置该管理员的细粒度权限'),
onClick: () => {
setPermMemberId(record.id);
setPermMemberName(
record.display_name || record.username || '',
@@ -685,23 +678,25 @@ const OrgMembers = ({
smart_router_manage: !!perms.smart_router_manage,
});
setPermModalVisible(true);
}}
>
{t('权限')}
</Button>
</Tooltip>
)}
<Tooltip content={t('从企业中移除该成员')}>
<Popconfirm
title={t('确定移除该成员?移除后该成员将失去企业访问权限。')}
onConfirm={() => handleRemove(record.id)}
>
<Button type='link' danger>
{t('移除')}
</Button>
</Popconfirm>
</Tooltip>
</OrgRowActions>
},
},
{
key: 'remove',
label: t('移除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t(
'确定移除该成员?移除后该成员将失去企业访问权限。',
),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => handleRemove(record.id),
}),
},
]}
/>
);
},
});
+104 -106
View File
@@ -24,6 +24,7 @@ import {
OctagonX as ActionOctagonX,
Code2 as ActionCode2,
} from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
Button,
@@ -217,118 +218,115 @@ const OrgPrivateSkills = ({ orgId }) => {
currentUserId > 0 && Number(row.version?.created_by) === currentUserId;
const isReviewer =
currentUserId > 0 && Number(row.review?.reviewer_id) === currentUserId;
return (
<div className='flex flex-wrap gap-2'>
<Button
size='small'
disabled={row.definition.emergency_stopped}
onClick={() => {
setEditingSkill(row.definition);
setForm({
...blankSkill,
canonical_id: row.definition.canonical_id,
});
setEditorVisible(true);
}}
>
{t('新版本')}
</Button>
<Button size='small' onClick={() => openHistory(row.definition)}>
{t('历史版本')}
</Button>
<Button
size='small'
disabled={!versionId}
onClick={() => {
// Clear residue from a previous version's test before reopening.
setEvidence({ model: '', input: '' });
setEvidenceVersion(versionId);
}}
>
{t('执行模型实测')}
</Button>
<Button
size='small'
disabled={!versionId || row.review?.status !== 'pending' || isAuthor}
onClick={() =>
action(`/api/org/skills/private/versions/${versionId}/review/start`)
}
>
{isAuthor && row.review?.status === 'pending'
const [primaryAction, ...moreActions] = [
{
key: 'new-version',
label: t('新版本'),
onClick: () => {
setEditingSkill(row.definition);
setForm({
...blankSkill,
canonical_id: row.definition.canonical_id,
});
setEditorVisible(true);
},
disabled: row.definition.emergency_stopped,
},
{
key: 'history',
label: t('历史版本'),
onClick: () => openHistory(row.definition),
},
{
key: 'runtime',
label: t('执行模型实测'),
onClick: () => {
// Clear residue from a previous version's test before reopening.
setEvidence({ model: '', input: '' });
setEvidenceVersion(versionId);
},
disabled: !versionId,
},
{
key: 'claim',
label:
isAuthor && row.review?.status === 'pending'
? t('待他人审核')
: t('领取审核')}
</Button>
<Button
size='small'
icon={<ActionFileCheck2 size={14} />}
disabled={
!versionId || row.review?.status !== 'reviewing' || !isReviewer
}
onClick={() =>
: t('领取审核'),
onClick: () =>
action(`/api/org/skills/private/versions/${versionId}/review/start`),
disabled: !versionId || row.review?.status !== 'pending' || isAuthor,
},
{
key: 'approve',
label: t('通过'),
onClick: () =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: true, conclusion: { decision: 'approved' } },
),
disabled:
!versionId || row.review?.status !== 'reviewing' || !isReviewer,
icon: <ActionFileCheck2 size={14} />,
},
{
key: 'reject',
label: t('驳回'),
onClick: () =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: false, conclusion: { decision: 'rejected' } },
),
disabled:
!versionId || row.review?.status !== 'reviewing' || !isReviewer,
danger: true,
},
{
key: 'publish',
label: t('发布'),
onClick: () =>
action(`/api/org/skills/private/versions/${versionId}/publish`),
disabled: !versionId || row.review?.status !== 'approved',
},
{
key: 'rollback',
label: t('回滚'),
onClick: () =>
askReason(t('回滚到当前列表版本'), (reason) =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: true, conclusion: { decision: 'approved' } },
)
}
>
{t('通过')}
</Button>
<Button
size='small'
type='danger'
disabled={
!versionId || row.review?.status !== 'reviewing' || !isReviewer
}
onClick={() =>
`/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`,
{ reason },
),
),
disabled: !versionId,
icon: <ActionRotateCcw size={14} />,
},
{
key: 'stop',
label: t('紧急停用'),
onClick: () =>
askReason(t('紧急停用 Skill'), (reason) =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: false, conclusion: { decision: 'rejected' } },
)
}
>
{t('驳回')}
</Button>
`/api/org/skills/private/${row.definition.id}/emergency-stop`,
{ reason },
),
),
disabled: row.definition.emergency_stopped,
icon: <ActionOctagonX size={14} />,
danger: true,
},
];
return (
<TableRowActions items={moreActions}>
<Button
size='small'
disabled={!versionId || row.review?.status !== 'approved'}
onClick={() =>
action(`/api/org/skills/private/versions/${versionId}/publish`)
}
type='link'
disabled={primaryAction.disabled}
onClick={primaryAction.onClick}
>
{t('发布')}
{primaryAction.label}
</Button>
<Button
size='small'
icon={<ActionRotateCcw size={14} />}
disabled={!versionId}
onClick={() =>
askReason(t('回滚到当前列表版本'), (reason) =>
action(
`/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`,
{ reason },
),
)
}
>
{t('回滚')}
</Button>
<Button
size='small'
type='danger'
icon={<ActionOctagonX size={14} />}
disabled={row.definition.emergency_stopped}
onClick={() =>
askReason(t('紧急停用 Skill'), (reason) =>
action(
`/api/org/skills/private/${row.definition.id}/emergency-stop`,
{ reason },
),
)
}
>
{t('紧急停用')}
</Button>
</div>
</TableRowActions>
);
};
const openCreateEditor = () => {
@@ -500,7 +498,7 @@ const OrgPrivateSkills = ({ orgId }) => {
},
{
title: t('操作'),
width: 430,
width: 170,
render: (_, row) => renderSkillActions(row),
},
]}
+5 -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 {
RefreshCw as ActionRefreshCw,
Pencil as ActionPencil,
@@ -44,7 +45,10 @@ const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const memberName = (m) =>
m.remark || m.display_name || m.username || `#${m.org_member_id}`;
m.remark ||
m.display_name ||
m.username ||
formatIdReference(m.org_member_id);
// 我的项目(阶段一):项目经理(项目负责人/项目管理员)自助管理项目成员与项目名。
const OrgProjectManage = ({ orgId }) => {
+36 -26
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 {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
@@ -36,7 +37,8 @@ import {
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import OrgScopedLimitButtons from './components/OrgScopedLimitButtons';
@@ -105,7 +107,7 @@ const OrgProjects = ({ orgId }) => {
const memberNameMap = useMemo(() => {
const m = {};
members.forEach((mem) => {
m[mem.id] = mem.display_name || mem.username || `#${mem.id}`;
m[mem.id] = mem.display_name || mem.username || formatIdReference(mem.id);
});
return m;
}, [members]);
@@ -303,12 +305,11 @@ const OrgProjects = ({ orgId }) => {
return members
.filter((mem) => !inProject.has(mem.id))
.map((mem) => ({
label: mem.display_name || mem.username || `#${mem.id}`,
label: mem.display_name || mem.username || formatIdReference(mem.id),
value: mem.id,
}));
}, [members, projectMembers]);
// 列宽与渲染对齐原型 EnterpriseProjects(150/350/120/140/300,scroll.x 1060);
const columns = [
{
title: t('项目编码'),
@@ -351,27 +352,36 @@ const OrgProjects = ({ orgId }) => {
},
{
title: t('操作'),
width: 300,
width: 168,
render: (_, record) => (
<OrgRowActions>
<OrgScopedLimitButtons
orgId={orgId}
record={record}
apiBase='/api/org/project'
scopeLabel='项目'
onSaved={fetchList}
variant='link'
/>
<Button type='link' onClick={() => openMembers(record)}>
{t('成员')}
</Button>
<Button type='link' onClick={() => openTokens(record)}>
{t('密钥')}
</Button>
<Button type='link' onClick={() => openEdit(record)}>
{t('编辑')}
</Button>
</OrgRowActions>
<OrgScopedLimitButtons
orgId={orgId}
record={record}
apiBase='/api/org/project'
scopeLabel='项目'
onSaved={fetchList}
renderActions={(limitItems) => (
<TableRowActions
items={[
...limitItems,
{
key: 'members',
label: t('成员'),
onClick: () => openMembers(record),
},
{
key: 'tokens',
label: t('密钥'),
onClick: () => openTokens(record),
},
]}
>
<Button type='link' size='small' onClick={() => openEdit(record)}>
{t('编辑')}
</Button>
</TableRowActions>
)}
/>
),
},
];
@@ -491,7 +501,7 @@ const OrgProjects = ({ orgId }) => {
{
title: t('成员'),
dataIndex: 'org_member_id',
render: (v) => memberNameMap[v] || `#${v}`,
render: (v) => memberNameMap[v] || formatIdReference(v),
},
{
title: t('角色'),
@@ -550,7 +560,7 @@ const OrgProjects = ({ orgId }) => {
</Tag>
) : (
<Tag color='blue' size='small'>
{projectNameMap[v] || `#${v}`}
{projectNameMap[v] || formatIdReference(v)}
</Tag>
),
},
+6 -2
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 { formatUserReference } from '../../helpers/safeDisplay';
import {
Copy as ActionCopy,
Search as ActionSearch,
@@ -250,7 +251,10 @@ const OrgPromptRecords = ({ orgId }) => {
() => [
{ value: '', label: t('全部成员') },
...members.map((member) => {
const name = member.name || member.username || `User#${member.user_id}`;
const name = formatUserReference(
member.name || member.username,
member.user_id,
);
return {
value: member.member_id,
label:
@@ -271,7 +275,7 @@ const OrgPromptRecords = ({ orgId }) => {
member?.remark ||
member?.display_name ||
record.username ||
`User#${record.user_id}`
formatUserReference(record.name || record.username, record.user_id)
);
};
+2 -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 { formatUserReference } from '../../helpers/safeDisplay';
import {
RefreshCw as ActionRefreshCw,
@@ -1013,7 +1014,7 @@ const OrgSettings = ({ orgId, orgRole }) => {
value={transferTargetId}
onChange={(v) => setTransferTargetId(v)}
optionList={members.map((m) => ({
label: `${m.user_name || m.username || 'User#' + m.user_id} (${m.role})`,
label: `${formatUserReference(m.user_name || m.username, m.user_id, t('未知用户'))} (${m.role})`,
value: m.user_id,
}))}
/>
+6 -2
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 {
EyeOff as ActionEyeOff,
@@ -512,7 +514,7 @@ const OrgTokens = ({ orgId, orgRole }) => {
key: 'creator_name',
dataIndex: 'creator_name',
width: 140,
render: (name, record) => name || `User#${record.user_id}`,
render: (name, record) => formatUserReference(name, record.user_id),
},
]
: []),
@@ -1348,7 +1350,9 @@ const EditTokenModal = ({
(libraryRes.data.data || [])
.filter((policy) => policy.enabled)
.map((policy) => ({
label: nameById.get(policy.skill_id) || `#${policy.skill_id}`,
label:
nameById.get(policy.skill_id) ||
formatIdReference(policy.skill_id),
value: policy.skill_id,
})),
);
@@ -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 {
ChevronRight as ActionChevronRight,
@@ -774,7 +775,11 @@ const FlowInner = ({
) : (
<div className='space-y-1'>
{sheetMembers.map((m) => {
const name = m.display_name || m.username || `#${m.user_id}`;
const name = formatUserReference(
m.display_name || m.username,
m.user_id,
t('未知用户'),
);
return (
<div
key={m.user_id}
@@ -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 { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -93,11 +94,16 @@ const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) {
return <small>{t('无上期对比')}</small>;
}
const pct = ((cur - prev) / prev) * 100;
const up = pct >= 0;
const pct = Number.isFinite(Number(cur))
? ((Number(cur) - Number(prev)) / Number(prev)) * 100
: null;
const up = pct !== null && pct >= 0;
return (
<small className={up ? 'is-up' : 'is-down'}>
{up ? '↑' : '↓'} {Math.abs(pct).toFixed(1)}%<em>{t('较上期')}</em>
{pct === null
? '-'
: `${up ? '↑' : '↓'} ${formatPercent(Math.abs(pct), 1)}`}
<em>{t('较上期')}</em>
</small>
);
};
@@ -432,12 +438,14 @@ const OrgAnalyticsPanel = ({
width: 300,
render: (_, r) => {
const pct =
breakdownTotal > 0 ? ((r.quota || 0) / breakdownTotal) * 100 : 0;
breakdownTotal > 0
? ((Number(r.quota) || 0) / breakdownTotal) * 100
: null;
return (
<div className='oc-ea-cost-share'>
<div>
<strong>{renderQuota(r.quota || 0, 2)}</strong>
<span>{pct.toFixed(1)}%</span>
<span>{formatPercent(pct, 1)}</span>
</div>
<Progress
percent={Math.round(pct)}
@@ -59,7 +59,7 @@ const OrgScopedLimitButtons = ({
apiBase,
scopeLabel,
onSaved,
variant = 'default',
renderActions,
}) => {
const { t } = useTranslation();
@@ -171,46 +171,47 @@ const OrgScopedLimitButtons = ({
return (
<>
<Tooltip
content={t(
'设置该{{scope}}成员默认可用的模型范围(与成员/项目/部门限制取交集)',
{ scope: t(scopeLabel) },
)}
>
<Button
{...(variant === 'link'
? { type: 'link' }
: {
size: 'small',
theme: 'light',
type: modelConfigured ? 'primary' : 'tertiary',
icon: <ActionLayers size={14} />,
})}
onClick={openModelModal}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip
content={t(
'设置该{{scope}}成员默认可调用的分组(与成员/项目/部门限制取交集)',
{ scope: t(scopeLabel) },
)}
>
<Button
{...(variant === 'link'
? { type: 'link' }
: {
size: 'small',
theme: 'light',
type: groupConfigured ? 'primary' : 'tertiary',
icon: <ActionLayers size={14} />,
})}
onClick={openGroupsModal}
>
{t('分组')}
</Button>
</Tooltip>
{renderActions ? (
renderActions([
{ key: 'models', label: t('模型'), onClick: openModelModal },
{ key: 'groups', label: t('分组'), onClick: openGroupsModal },
])
) : (
<>
<Tooltip
content={t(
'设置该{{scope}}成员默认可用的模型范围(与成员/项目/部门限制取交集)',
{ scope: t(scopeLabel) },
)}
>
<Button
size='small'
theme='light'
type={modelConfigured ? 'primary' : 'tertiary'}
icon={<ActionLayers size={14} />}
onClick={openModelModal}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip
content={t(
'设置该{{scope}}成员默认可调用的分组(与成员/项目/部门限制取交集)',
{ scope: t(scopeLabel) },
)}
>
<Button
size='small'
theme='light'
type={groupConfigured ? 'primary' : 'tertiary'}
icon={<ActionLayers size={14} />}
onClick={openGroupsModal}
>
{t('分组')}
</Button>
</Tooltip>
</>
)}
{/* 模型限制 Modal */}
<OrgModal
@@ -19,12 +19,10 @@ For commercial licensing, please contact support@quantumnous.com
import { useMemo } from 'react';
import { theme } from 'antd';
import { useActualTheme } from '../../../context/Theme';
import { brandAccentFromToken } from '../../../components/ui/UiThemeProvider';
/**
* 消耗明细页(/org/logs)主题桥:只从 Ant token 推导页面局部变量,挂在页面根节点 style 上。
* - --oc-brand:原型 --brand(页签、额度、统计图标等强调色),浅色 / 深色 / 自定义主色三态跟随 token。
* - --oc-brand 继承页面作用域的品牌强调色。
* - --oc-stat-brand-bg:统计图标浅底(原型 #b9650810 = 品牌色 6.3% 透明度)。
* - --ur-progress-done:任务进度满格描边(原型 strokeColor = var(--brand))。
* - --oc-task-{success|failure|pending}-{text|bg|border}:绘图与视频“本页统计”语义色(Ant success / error / warning)。
@@ -32,10 +30,8 @@ import { brandAccentFromToken } from '../../../components/ui/UiThemeProvider';
*/
export function useOrgLogsThemeStyle() {
const { token } = theme.useToken();
const dark = useActualTheme() === 'dark';
return useMemo(
() => ({
'--oc-brand': brandAccentFromToken(token.colorPrimary, dark),
'--oc-stat-brand-bg':
'color-mix(in srgb, var(--oc-brand) 6.3%, transparent)',
'--ur-progress-done': 'var(--oc-brand)',
@@ -49,7 +45,7 @@ export function useOrgLogsThemeStyle() {
'--oc-task-pending-bg': token.colorWarningBg,
'--oc-task-pending-border': token.colorWarningBorder,
}),
[token, dark],
[token],
);
}
+31 -22
View File
@@ -38,7 +38,7 @@ import {
} from 'lucide-react';
import OrgStatCard from '../components/OrgStatCard';
import OrgStateBlock from '../components/OrgStateBlock';
import { OrgRowActions } from '../components/OrgListCard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { renderQuota } from '../../../helpers/render';
import { deptFundApi } from './fundApi';
import { FUND_STATE, buildFundTree } from './fundFormat';
@@ -193,30 +193,39 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
},
{
title: t('操作'),
width: 210,
width: 168,
fixed: 'right',
render: (_, r) => (
<OrgRowActions>
<TableRowActions
items={
canTransfer
? [
r.account && {
key: 'ledger',
label: t('流水'),
onClick: () =>
setLedgerAccount({ id: r.account.id, name: r.name }),
},
{
key: 'recall',
label: t('回收'),
onClick: () => setTransfer({ mode: 'recall', row: r }),
},
]
: []
}
>
{canTransfer && (
<>
<Button
size='small'
type='link'
disabled={centerDisabled || r.dept_status === 2}
onClick={() => setTransfer({ mode: 'allocate', row: r })}
>
{t('分配')}
</Button>
<Button
size='small'
type='link'
onClick={() => setTransfer({ mode: 'recall', row: r })}
>
{t('回收')}
</Button>
</>
<Button
size='small'
type='link'
disabled={centerDisabled || r.dept_status === 2}
onClick={() => setTransfer({ mode: 'allocate', row: r })}
>
{t('分配')}
</Button>
)}
{r.account && (
{!canTransfer && r.account && (
<Button
size='small'
type='link'
@@ -227,7 +236,7 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
{t('流水')}
</Button>
)}
</OrgRowActions>
</TableRowActions>
),
},
];
@@ -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 React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -157,7 +158,7 @@ const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
? t('平台管理员')
: isConsume(r) || !r.operator_user_id
? t('系统')
: v || `#${r.operator_user_id}`;
: v || formatIdReference(r.operator_user_id);
return (
<span className='block max-w-[120px] truncate' title={name}>
{name}
+31 -22
View File
@@ -35,7 +35,7 @@ import OrgPanel from '../components/OrgPanel';
import OrgStatCard from '../components/OrgStatCard';
import OrgStateBlock from '../components/OrgStateBlock';
import OrgModal from '../components/OrgModal';
import { OrgRowActions } from '../components/OrgListCard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { showError, showSuccess } from '../../../helpers/utils';
import { renderQuota } from '../../../helpers/render';
import { orgFundApi } from './fundApi';
@@ -279,32 +279,41 @@ const OrgDeptFunds = ({ orgId }) => {
},
{
title: t('操作'),
width: 220,
width: 168,
fixed: 'right',
render: (_, r) => {
const isArchived = r.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED;
return (
<OrgRowActions>
<TableRowActions
items={
canTransfer && !isArchived
? [
r.account && {
key: 'ledger',
label: t('流水'),
onClick: () =>
setLedgerAccount({ id: r.account.id, name: r.name }),
},
{
key: 'recall',
label: t('回收'),
onClick: () => setTransfer({ mode: 'recall', row: r }),
},
]
: []
}
>
{canTransfer && !isArchived && (
<>
<Button
size='small'
type='link'
disabled={r.dept_status === 2}
onClick={() => setTransfer({ mode: 'allocate', row: r })}
>
{t('分配')}
</Button>
<Button
size='small'
type='link'
onClick={() => setTransfer({ mode: 'recall', row: r })}
>
{t('回收')}
</Button>
</>
<Button
size='small'
type='link'
disabled={r.dept_status === 2}
onClick={() => setTransfer({ mode: 'allocate', row: r })}
>
{t('分配')}
</Button>
)}
{r.account && (
{(!canTransfer || isArchived) && r.account && (
<Button
size='small'
type='link'
@@ -315,7 +324,7 @@ const OrgDeptFunds = ({ orgId }) => {
{t('流水')}
</Button>
)}
</OrgRowActions>
</TableRowActions>
);
},
},
+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 { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import {
@@ -366,7 +367,7 @@ const GroupMonitor = () => {
className='text-sm font-medium'
style={{ color: getUptimeColor(value) }}
>
{(value || 0).toFixed(1)}%
{formatPercent(value || 0, 1)}
</span>
</div>
),
@@ -511,7 +512,7 @@ const GroupMonitor = () => {
<div
className={`service-uptime-badge px-4 py-2 rounded-xl text-sm font-bold ${getUptimeClass(uptimePercent)}`}
>
{uptimePercent.toFixed(2)}%
{formatPercent(uptimePercent, 2)}
</div>
</div>
</div>
@@ -591,7 +592,7 @@ const GroupMonitor = () => {
<div
className={`service-uptime-badge px-3 py-1.5 rounded-lg text-xs font-bold ${getUptimeClass(uptimePercent)}`}
>
{uptimePercent.toFixed(2)}%
{formatPercent(uptimePercent, 2)}
</div>
</div>
<div className='text-center'>
@@ -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 { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
@@ -544,7 +545,7 @@ const GroupMonitorAdmin = () => {
className='text-3xl font-bold'
style={{ color: getHealthColor(overview.average_uptime) }}
>
{overview.average_uptime.toFixed(1)}%
{formatPercent(overview.average_uptime, 1)}
</div>
<div className='text-gray-500 mt-1'>{t('平均可用率')}</div>
</Card>
@@ -659,7 +660,7 @@ const GroupMonitorAdmin = () => {
color: getHealthColor(group.uptime_percent),
}}
>
{group.uptime_percent.toFixed(1)}%
{formatPercent(group.uptime_percent, 1)}
</div>
<div className='text-xs text-gray-500'>
{t('可用率')}
@@ -708,7 +709,7 @@ const GroupMonitorAdmin = () => {
color: getHealthColor(group.uptime_percent),
}}
>
{group.uptime_percent.toFixed(1)}%
{formatPercent(group.uptime_percent, 1)}
</div>
<div className='stat-box-label'>{t('可用率')}</div>
</div>
+33 -10
View File
@@ -32,6 +32,10 @@ import {
import { useTranslation } from 'react-i18next';
import i18next from 'i18next';
import { colord } from 'colord';
import {
resolveBrandPalette,
resolveGradientLabel,
} from '../../../helpers/brandPalette';
import { API, showError, showSuccess } from '../../../helpers';
import { StatusContext } from '../../../context/Status';
import { PRESETS, DEFAULT_PRESET_KEY } from '../../../styles/presets';
@@ -1327,6 +1331,16 @@ function t_alpha(pct) {
* 让用户能直观对比两组色板互不影响。 */
function PreviewMini({ palette, colorMode, t }) {
const isDark = colorMode === 'dark';
const previewSurface = isDark ? '#101014' : '#f6f8fb';
const interaction = resolveBrandPalette(
palette['brand-primary'],
isDark,
previewSurface,
);
const bubbleStops = ['from', 'via', 'to'].map(
(stop) => palette[`brand-gradient-${stop}`],
);
const bubbleLabel = resolveGradientLabel(bubbleStops, previewSurface);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* —— 前景:按钮 / 气泡 / 强调色 —— */}
@@ -1335,7 +1349,7 @@ function PreviewMini({ palette, colorMode, t }) {
padding: 16,
borderRadius: 10,
border: '1px solid var(--ui-color-border)',
background: isDark ? '#101014' : '#f6f8fb',
background: previewSurface,
display: 'flex',
alignItems: 'center',
gap: 16,
@@ -1346,36 +1360,45 @@ function PreviewMini({ palette, colorMode, t }) {
style={{
padding: '8px 16px',
borderRadius: 8,
color: '#fff',
color: interaction.onSolid,
fontWeight: 500,
fontSize: 13,
background: `linear-gradient(135deg, ${palette['brand-gradient-from']} 0%, ${palette['brand-gradient-via']} 50%, ${palette['brand-gradient-to']} 100%)`,
boxShadow: `0 4px 12px ${palette['brand-primary-soft'] || 'rgba(0,0,0,0.1)'}`,
background: interaction.normal,
}}
>
{t('主按钮')}
</div>
<a
<span
style={{
color: palette['brand-primary'],
color: interaction.selectionText,
textDecoration: 'underline',
fontSize: 13,
}}
>
{t('链接示例')}
</a>
</span>
<div
style={{
padding: '8px 14px',
borderRadius: '14px 14px 4px 14px',
color: '#fff',
fontSize: 12,
background: `linear-gradient(135deg, ${palette['brand-gradient-from']} 0%, ${palette['brand-gradient-via']} 50%, ${palette['brand-gradient-to']} 100%)`,
background: `linear-gradient(135deg, ${bubbleStops[0]} 0%, ${bubbleStops[1]} 50%, ${bubbleStops[2]} 100%)`,
}}
>
{t('聊天气泡')}
<span
style={{
color: bubbleLabel.color,
...(bubbleLabel.background && {
background: bubbleLabel.background,
borderRadius: 4,
padding: '1px 4px',
}),
}}
>
{t('聊天气泡')}
</span>
</div>
<div
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { Trans } from 'react-i18next';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, {
useCallback,
useEffect,
@@ -593,7 +594,40 @@ export default function SettingsPaymentGatewayPayPal(props) {
{
title: t('操作'),
render: (_, row) => (
<div className='flex flex-wrap gap-2'>
<TableRowActions
items={[
{
key: 'reconcile',
label: t('触发对账'),
onClick: () => reconcileOperationOrder(row.trade_no),
disabled: !row.third_trade_no,
},
{
key: 'expire',
label: t('确认未付款并过期'),
onClick: () => {
setExpireOrder(row);
setForceExpire(false);
setForceExpireConfirmed(false);
setExpireReason(t('确认该订单未完成 PayPal 支付'));
},
danger: true,
},
{
key: 'force-expire',
label: t('强制过期'),
onClick: () => {
setExpireOrder(row);
setForceExpire(true);
setForceExpireConfirmed(false);
setExpireReason(
t('管理员确认远端状态无法核验,强制关闭该 PayPal 订单'),
);
},
danger: true,
},
]}
>
<Button
htmlType='button'
onClick={() => inspectOperationOrder(row.trade_no)}
@@ -602,45 +636,7 @@ export default function SettingsPaymentGatewayPayPal(props) {
>
{t('查询远端状态')}
</Button>
<Button
htmlType='button'
onClick={() => reconcileOperationOrder(row.trade_no)}
disabled={!row.third_trade_no}
type='link'
size='small'
>
{t('触发对账')}
</Button>
<Button
htmlType='button'
onClick={() => {
setExpireOrder(row);
setForceExpire(false);
setForceExpireConfirmed(false);
setExpireReason(t('确认该订单未完成 PayPal 支付'));
}}
type='link'
size='small'
danger
>
{t('确认未付款并过期')}
</Button>
<Button
htmlType='button'
onClick={() => {
setExpireOrder(row);
setForceExpire(true);
setForceExpireConfirmed(false);
setExpireReason(
t('管理员确认远端状态无法核验,强制关闭该 PayPal 订单'),
);
}}
type='link'
size='small'
>
{t('强制过期')}
</Button>
</div>
</TableRowActions>
),
},
],
@@ -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';
@@ -364,7 +365,7 @@ export default function ModelCostSettings() {
() =>
channels.map((c) => ({
value: String(c.id),
label: `#${c.id} ${c.name}${c.status === 1 ? '' : t('(已禁用)')}`,
label: `${formatIdReference(c.id)} ${c.name}${c.status === 1 ? '' : t('(已禁用)')}`,
})),
[channels, t],
);
@@ -1996,7 +1997,8 @@ export default function ModelCostSettings() {
columns={[
{
title: t('渠道'),
render: (_, r) => `#${r.channel_id} ${r.channel_name}`,
render: (_, r) =>
`${formatIdReference(r.channel_id)} ${r.channel_name}`,
},
{ title: t('模型(上游名)'), dataIndex: 'model_name' },
{
+2 -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';
// 系统设置 →「WeyAi」页签 →「账号接入」子页签(方案 M8;M21 起从「系统设置」页签搬到这里)。只对超级管理员展示;
// 这些 key 在后端登记为 root-only(setting/console_setting/admin_delegation.go)。
@@ -338,7 +339,7 @@ function OrgSelect({
const selectedValues = (value || []).map((item) => `${item}`);
const options = selectedValues.map((item) => ({
value: item,
label: orgLabels[item] || `#${item}`,
label: orgLabels[item] || formatIdReference(item),
}));
const seen = new Set(selectedValues);
results.forEach((org) => {
@@ -23,14 +23,14 @@ For commercial licensing, please contact support@quantumnous.com
// root 和被下放了「WeyAi」页签的管理员都能用。
import { Trans } from 'react-i18next';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useCallback, useEffect, useState } from 'react';
import {
Banner,
Button,
Card,
Popconfirm,
Modal,
Select,
Space,
Spin,
Table,
Tag,
@@ -264,7 +264,48 @@ const SettingsWeyAiContent = () => {
title: t('操作'),
width: 300,
render: (_, item, index) => (
<Space wrap>
<TableRowActions
items={[
item.status === 'published' && {
key: 'offline',
label: t('下架'),
onClick: () => setStatus(item, 'offline'),
disabled: busyId === item.id,
},
item.status !== 'published' && {
key: 'publish',
label: t('发布'),
onClick: () => setStatus(item, 'published'),
disabled: busyId === item.id,
},
{
key: 'up',
label: t('上移'),
onClick: () => move(index, -1),
disabled: index === 0,
},
{
key: 'down',
label: t('下移'),
onClick: () => move(index, 1),
disabled: index === items.length - 1,
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确定删除这个条目?'),
content: t('删除后客户端不再显示;它的文件 7 天后清理'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => remove(item),
}),
},
]}
>
<Button
onClick={() => setEditor({ visible: true, item })}
type='link'
@@ -272,53 +313,7 @@ const SettingsWeyAiContent = () => {
>
{t('编辑')}
</Button>
{item.status === 'published' ? (
<Button
loading={busyId === item.id}
onClick={() => setStatus(item, 'offline')}
type='link'
size='small'
>
{t('下架')}
</Button>
) : (
<Button
loading={busyId === item.id}
onClick={() => setStatus(item, 'published')}
type='link'
size='small'
>
{t('发布')}
</Button>
)}
<Button
disabled={index === 0}
aria-label={t('上移')}
onClick={() => move(index, -1)}
type='link'
size='small'
>
{t('上移')}
</Button>
<Button
disabled={index === items.length - 1}
aria-label={t('下移')}
onClick={() => move(index, 1)}
type='link'
size='small'
>
{t('下移')}
</Button>
<Popconfirm
title={t('确定删除这个条目?')}
content={t('删除后客户端不再显示;它的文件 7 天后清理')}
onConfirm={() => remove(item)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
</TableRowActions>
),
},
];

Some files were not shown because too many files have changed in this diff Show More