sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization

- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
This commit is contained in:
qiubaishen
2026-11-18 10:22:02 +08:00
parent 914e5e2c67
commit db8cdf3360
157 changed files with 29960 additions and 1197 deletions
+11 -12
View File
@@ -22,7 +22,6 @@ import {
Check as ActionCheck,
Copy as ActionCopy,
} from '@/components/common/icons/ActionIcons';
import { writeClipboardText } from '../../helpers/clipboard';
import TableEmpty from '../../components/common/table/TableEmpty';
import TableToolbar from '../../components/common/table/TableToolbar';
import {
@@ -42,7 +41,7 @@ import {
InputNumber,
} from '@/components/ui';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { showError, copy } from '../../helpers';
import { renderQuota } from '../../helpers/render';
const paymentMethodMap = {
@@ -220,16 +219,16 @@ const AdminOrder = () => {
setAppliedMaxMoney(undefined);
};
const copyText = (text, id) => {
writeClipboardText(text)
.then(() => {
setCopiedId(id);
Toast.success(t('已复制'));
setTimeout(() => setCopiedId(null), 2000);
})
.catch(() => {
showError(t('复制失败'));
});
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到。
const copyText = async (text, id) => {
if (await copy(text)) {
setCopiedId(id);
Toast.success(t('已复制'));
setTimeout(() => setCopiedId(null), 2000);
} else {
showError(t('复制失败'));
}
};
const formatTime = (timestamp) => {
+73
View File
@@ -76,6 +76,10 @@ const ORG_FEATURE_KEYS = [
{ key: 'approval', label: '审批中心' },
{ key: 'analytics', label: '用量分析' },
{ key: 'quality_monitor', label: '调用质量' },
// 智能模型路由:功能键只表示可用,企业出境同意由企业所有者在企业中心授权(§9.5)
{ key: 'smart_router', label: '智能路由' },
{ key: 'smart_router_jev', label: '智能路由 · Jev 判定(可用)' },
{ key: 'smart_router_eval', label: '智能路由 · 质量评估(可用)' },
{ key: 'enterprise_login', label: '企业登录入口' },
{ key: 'org_only_mode', label: '仅企业资源模式' },
{ key: 'content_moderation', label: '内容审核' },
@@ -95,6 +99,9 @@ import {
ConsoleFilterActions,
} from '../../components/console/ConsoleModuleFilters';
// 与后端 model.OrgMaxConcurrencyCeiling 保持一致,超出后端会直接拒绝
const ORG_MAX_CONCURRENCY_CEILING = 100000;
const AdminOrganizations = () => {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -124,6 +131,7 @@ const AdminOrganizations = () => {
max_members: 50,
max_tokens: 100,
cloud_brain_concurrency: 12,
max_concurrency: 0,
sales_rep: '',
});
const [createCredentialResult, setCreateCredentialResult] = useState(null);
@@ -138,6 +146,7 @@ const AdminOrganizations = () => {
max_members: 50,
max_tokens: 100,
cloud_brain_concurrency: 12,
max_concurrency: 0,
default_member_quota: 0,
description: '',
contact_name: '',
@@ -305,6 +314,7 @@ const AdminOrganizations = () => {
max_members: 50,
max_tokens: 100,
cloud_brain_concurrency: 12,
max_concurrency: 0,
sales_rep: '',
});
};
@@ -545,6 +555,8 @@ const AdminOrganizations = () => {
data.max_tokens = createForm.max_tokens;
if (createForm.cloud_brain_concurrency != null)
data.cloud_brain_concurrency = createForm.cloud_brain_concurrency;
if (createForm.max_concurrency != null)
data.max_concurrency = createForm.max_concurrency;
if ((createForm.sales_rep || '').trim())
data.sales_rep = createForm.sales_rep.trim();
const res = await API.post('/api/admin/organizations/', data);
@@ -578,6 +590,7 @@ const AdminOrganizations = () => {
max_members: record.max_members ?? 50,
max_tokens: record.max_tokens ?? 100,
cloud_brain_concurrency: record.cloud_brain_concurrency ?? 12,
max_concurrency: record.max_concurrency ?? 0,
default_member_quota: record.default_member_quota || 0,
description: record.description || '',
contact_name: record.contact_name || '',
@@ -617,6 +630,11 @@ const AdminOrganizations = () => {
editForm.cloud_brain_concurrency != null
? editForm.cloud_brain_concurrency
: undefined,
// 后端是指针字段,0(不限制)也必须真的发出去,不能被 falsy 判断吞掉
max_concurrency:
editForm.max_concurrency != null
? Math.max(0, Number(editForm.max_concurrency) || 0)
: undefined,
default_member_quota:
editForm.default_member_quota != null
? Math.max(0, Number(editForm.default_member_quota) || 0)
@@ -812,6 +830,18 @@ const AdminOrganizations = () => {
</span>
),
},
{
title: t('API 并发'),
width: 90,
render: (_, record) =>
record.max_concurrency > 0 ? (
<Tag size='small' color='orange'>
{record.max_concurrency}
</Tag>
) : (
<span className='text-xs text-gray-400'>{t('不限制')}</span>
),
},
{
title: t('创建时间'),
dataIndex: 'created_at',
@@ -1386,8 +1416,33 @@ const AdminOrganizations = () => {
max={1000}
placeholder='12'
/>
<div className='mt-1 text-xs text-gray-400'>
{t(
'限制云端大脑异步任务的同时排队/运行数,与下方 API 并发无关',
)}
</div>
</div>
)}
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t('API 最大并发')}
</label>
<InputNumber
value={createForm.max_concurrency}
onChange={(v) =>
setCreateForm({ ...createForm, max_concurrency: v })
}
style={{ width: '100%' }}
min={0}
max={ORG_MAX_CONCURRENCY_CEILING}
placeholder='0'
/>
<div className='mt-1 text-xs text-gray-400'>
{t(
'企业同时在飞的 API 转发请求上限,超出直接返回 429。0 表示不限制',
)}
</div>
</div>
</div>
)}
</Modal>
@@ -1515,6 +1570,24 @@ const AdminOrganizations = () => {
</p>
</div>
)}
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t('API 最大并发')}
</label>
<InputNumber
value={editForm.max_concurrency}
onChange={(v) => setEditForm({ ...editForm, max_concurrency: v })}
style={{ width: '100%' }}
min={0}
max={ORG_MAX_CONCURRENCY_CEILING}
placeholder='0'
/>
<p className='text-xs text-gray-500 mt-1'>
{t(
'企业同时在飞的 API 转发请求上限,超出直接返回 429。0 表示不限制;当前占用可在运营看板「企业用量分析」中查看。',
)}
</p>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t('企业描述')}
+27 -11
View File
@@ -45,7 +45,6 @@ import {
TrendingUp,
Server,
Trophy,
CreditCard,
FileText,
UserCheck,
Wallet,
@@ -54,15 +53,17 @@ import {
Upload,
Building2,
Activity,
Gauge,
} from 'lucide-react';
import useAnalyticsData from '../../hooks/analytics/useAnalyticsData';
import useOrgConsumptionData from '../../hooks/analytics/useOrgConsumptionData';
import useOrgRealtimeUsage from '../../hooks/analytics/useOrgRealtimeUsage';
import useRiskControlData from '../../hooks/analytics/useRiskControlData';
import OverviewCards from '../../components/analytics/OverviewCards';
import OrgRealtimeUsage from '../../components/analytics/OrgRealtimeUsage';
import TrendCharts from '../../components/analytics/TrendCharts';
import ChannelConsumption from '../../components/analytics/ChannelConsumption';
import UserRanking from '../../components/analytics/UserRanking';
import TopupChannelChart from '../../components/analytics/TopupChannelChart';
import DailyStatsTable from '../../components/analytics/DailyStatsTable';
import CollapsibleHeader from '../../components/analytics/CollapsibleHeader';
import UserSurveyStats from '../../components/analytics/UserSurveyStats';
@@ -91,6 +92,9 @@ const TabChunkFallback = () => (
</div>
);
// 企业实时用量看板取前 N 名,与后端默认值保持一致
const ORG_REALTIME_LIMIT = 10;
// 从 URL ?tab= 派生 activeTab,未知值落回 operations
const readTabFromURL = () => {
try {
@@ -167,7 +171,6 @@ const Analytics = () => {
financeTrend,
channelConsumption,
userRanking,
topupChannel,
dailyStats,
userTopupRanking,
period,
@@ -179,6 +182,13 @@ const Analytics = () => {
activeTab === 'operations' && isAnalyticsTabVisible('operations'),
);
// 企业实时用量:独立于上面的时间筛选器,固定 3 秒轮询近 60 秒滚动窗口。
// 只在运营看板 Tab 可见时才起定时器。
const orgRealtime = useOrgRealtimeUsage(
activeTab === 'operations' && isAnalyticsTabVisible('operations'),
{ limit: ORG_REALTIME_LIMIT },
);
// 懒加载:仅当用户切到风控 Tab 时才发起风控 API 请求
const risk = useRiskControlData(
activeTab === 'risk' && isAnalyticsTabVisible('risk'),
@@ -372,6 +382,18 @@ const Analytics = () => {
t={t}
/>
{/* 企业实时用量(并发 / RPM / TPM),3 秒自刷新 */}
<OrgRealtimeUsage
data={orgRealtime.data}
loading={orgRealtime.loading}
sortBy={orgRealtime.sortBy}
onSortChange={orgRealtime.setSortBy}
limit={ORG_REALTIME_LIMIT}
title={t('企业用量分析')}
icon={<Gauge className='w-5 h-5' />}
t={t}
/>
{/* Trend Charts */}
<div className='grid grid-cols-1 lg:grid-cols-2 gap-4'>
<TrendCharts
@@ -390,14 +412,8 @@ const Analytics = () => {
/>
</div>
{/* Distribution Charts */}
<div className='grid grid-cols-1 lg:grid-cols-2 gap-4'>
<TopupChannelChart
data={topupChannel}
title={t('充值渠道分布')}
icon={<CreditCard className='w-5 h-5' />}
t={t}
/>
{/* User Ranking(充值渠道分布已由 c5e276491 下线) */}
<div>
<UserRanking
data={userRanking}
title={t('用户消耗 TOP100')}
+6 -7
View File
@@ -33,7 +33,6 @@ import {
ThumbsDown as ActionThumbsDown,
Download as ActionDownload,
} from '@/components/common/icons/ActionIcons';
import { writeClipboardText } from '../../helpers/clipboard';
import React, {
useCallback,
useEffect,
@@ -74,6 +73,7 @@ import { SSE } from 'sse.js';
import { API } from '../../helpers/api';
import { getServerURL } from '../../helpers/config';
import {
copy,
showError,
showSuccess,
getUserIdFromLocalStorage,
@@ -1423,11 +1423,11 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
const content = runDetail?.artifact?.content;
if (!content) return;
const identity = contextIdentity;
try {
await writeClipboardText(content);
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,裸调复制不到
if (await copy(content)) {
if (identity === contextIdentityRef.current)
showSuccess(t('已复制产物内容'));
} catch {
} else {
if (identity === contextIdentityRef.current)
showError(t('复制失败,请手动选择文本复制'));
}
@@ -1455,11 +1455,10 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
reason ? `${t('失败原因')}: ${t(reason)}` : '',
raw ? `${t('原始报错')}: ${raw}` : '',
].filter(Boolean);
try {
await writeClipboardText(lines.join('\n'));
if (await copy(lines.join('\n'))) {
if (identity === contextIdentityRef.current)
showSuccess(t('已复制报错信息'));
} catch {
} else {
if (identity === contextIdentityRef.current)
showError(t('复制失败,请手动选择文本复制'));
}
+551
View File
@@ -0,0 +1,551 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { shouldLoadHistoricalTrend } from './dashboardHistory';
import './dashboard.css';
const EMPTY = [];
const DAY = 86400;
const amount = (value) => (Number.isFinite(Number(value)) ? Number(value) : 0);
const protectionUntil = (row) =>
amount(row.extended_until || row.protected_until);
const salesAmount = (row) =>
row.base_amount_uyuan ?? row.sales_amount_uyuan ?? row.sales_uyuan;
const inMonth = (row, month) =>
!row.statement_month || row.statement_month === month;
function sixMonths(month) {
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month || '')) return [];
const [year, number] = month.split('-').map(Number);
return Array.from({ length: 6 }, (_, index) => {
const date = new Date(Date.UTC(year, number - 6 + index, 1));
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`;
});
}
export default function Dashboard({
bills = EMPTY,
partners = EMPTY,
assignments = EMPTY,
exceptions = EMPTY,
realtime = EMPTY,
options = {},
tiers = EMPTY,
month,
onNavigate,
trend = EMPTY,
ready = false,
}) {
const { t, i18n } = useTranslation();
const [retry, setRetry] = useState(0);
const [history, setHistory] = useState({
month: '',
rows: [],
failed: [],
loading: true,
});
const months = useMemo(() => sixMonths(month), [month]);
const suppliedTrend = trend.length > 0;
const historicalMonths = months.slice(0, -1).join(',');
useEffect(() => {
if (
!shouldLoadHistoricalTrend({
ready,
suppliedTrend,
historicalMonths,
})
)
return;
let cancelled = false;
const controller = new AbortController();
setHistory({ month, rows: [], failed: [], loading: true });
const keys = historicalMonths.split(',');
Promise.allSettled(
keys.map(async (key) => {
const response = await API.get(
`/api/commission/v2/statements?month=${encodeURIComponent(key)}`,
{
skipErrorHandler: true,
disableDuplicate: true,
signal: controller.signal,
},
);
if (!response.data?.success || (response.data.data != null && !Array.isArray(response.data.data))) {
throw new Error('Invalid statement response');
}
return response.data.data || [];
}),
).then((results) => {
if (cancelled) return;
const rows = [];
const failed = [];
results.forEach((result, index) => {
if (result.status === 'fulfilled') rows.push(...result.value);
else failed.push(keys[index]);
});
setHistory({ month, rows, failed, loading: false });
});
return () => {
cancelled = true;
controller.abort();
};
}, [month, historicalMonths, ready, suppliedTrend, retry]);
const numberFormat = useMemo(
() =>
new Intl.NumberFormat(i18n.language, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}),
[i18n.language],
);
const money = (value) => `¥ ${numberFormat.format(amount(value) / 1e6)}`;
const now = Date.now() / 1000;
const currentBills = bills.filter((row) => inMonth(row, month));
const currentRealtime = realtime.filter((row) => inMonth(row, month));
const estimated = currentRealtime.reduce(
(total, row) => total + amount(row.estimated_uyuan),
0,
);
const hasSales =
currentRealtime.length === 0 ||
currentRealtime.every((row) => salesAmount(row) != null);
const sales = currentRealtime.reduce(
(total, row) => total + amount(salesAmount(row)),
0,
);
const partnerById = new Map(partners.map((row) => [String(row.id), row]));
const protectedAssignments = assignments.filter(
(row) =>
['protected', 'protected_extended', 'pending_conversion'].includes(
row.status,
) && !row.ended_at,
);
const expiring = protectedAssignments.filter(
(row) =>
['protected', 'protected_extended'].includes(row.status) &&
protectionUntil(row) > now &&
protectionUntil(row) <= now + 7 * DAY,
);
const conversions = assignments.filter(
(row) => row.status === 'pending_conversion',
);
const agreements = partners.filter(
(row) =>
amount(row.agreement_expires_at) > now &&
amount(row.agreement_expires_at) <= now + 30 * DAY,
);
const openExceptions = exceptions.filter((row) => row.status === 'open');
const checking = currentBills.filter((row) => row.status === 'checking');
const fees = currentBills.filter(
(row) =>
['estimated', 'checking'].includes(row.status) &&
!row.fee_recorded &&
partnerById.get(String(row.partner_id))?.type === 'individual',
);
const payments = currentBills.filter(
(row) => row.status === 'confirmed' && amount(row.payable_uyuan) > 0,
);
const overdue = currentBills.filter(
(row) =>
row.status === 'pending_confirmation' &&
amount(row.confirmation_deadline) > 0 &&
amount(row.confirmation_deadline) <= now,
);
const activeTiers = tiers.filter(
(tier) =>
amount(tier.effective_from) <= now &&
(!amount(tier.effective_to) || amount(tier.effective_to) > now),
);
const boundChannels = new Set();
const boundLevels = new Set();
activeTiers.forEach((tier) => {
if (tier.source_type === 'channel') {
const ids = tier.channel_ids?.length
? tier.channel_ids
: [tier.source_id];
ids.forEach((id) => boundChannels.add(String(id)));
} else if (tier.source_type === 'level') {
boundLevels.add(`${tier.level_type}:${tier.tier_key}`);
}
});
const unboundChannels = (options.channels || []).filter(
(row) =>
(row.status == null || Number(row.status) === 1) &&
!boundChannels.has(String(row.id)),
);
const unboundLevels = (options.levels || []).filter(
(row) =>
!row.is_default &&
row.key !== 'default' &&
!boundLevels.has(`${row.type}:${row.key}`),
);
const summaryTodos = [
{
label: '保护期 7 日内到期',
rows: expiring,
target: 'assignments',
filter: 'expiring_protection',
tone: 'warning',
},
{
label: '待确认转化',
rows: conversions,
target: 'assignments',
filter: 'pending_conversion',
tone: 'primary',
},
{
label: '待修复计提异常',
rows: openExceptions,
target: 'exceptions',
filter: 'open',
tone: 'danger',
},
{
label: '协议 30 日内到期',
rows: agreements,
target: 'partners',
filter: 'expiring_agreement',
tone: 'warning',
},
];
const detailedTodos = [
{
label: '账单待核对',
description: '核对销售额、提成与调整后发出确认',
rows: checking,
filter: 'checking',
action: '去核对',
tone: 'primary',
},
{
label: '个人手续费待录入',
description: '个人伙伴账单需录入手续费后出账',
rows: fees,
filter: 'fee_missing',
action: '录入手续费',
tone: 'warning',
},
{
label: '已确认待打款',
description: '账单已确认,可登记付款结果',
rows: payments,
filter: 'pending_payment',
action: '去打款',
tone: 'primary',
},
{
label: '已超过确认截止日',
description: '检查确认状态并处理逾期账单',
rows: overdue,
filter: 'overdue_confirmation',
action: '去处理',
tone: 'danger',
},
];
const navigateTodo = (todo, target = 'bills') =>
onNavigate?.(todo.target || target, {
todo: todo.filter,
ids: todo.rows.map((row) => row.id),
});
const historyMatches = history.month === month;
const trendLoading =
!suppliedTrend && (!historyMatches || history.loading) && months.length > 0;
const failedMonths =
!suppliedTrend && historyMatches ? history.failed : EMPTY;
const chartRows = suppliedTrend
? trend
: historyMatches
? history.rows
: EMPTY;
const totals = new Map();
chartRows.forEach((row) => {
const key = row.statement_month;
totals.set(key, (totals.get(key) || 0) + amount(row.payable_uyuan));
});
const chart = months.map((key, index) => ({
month: key,
value: index === 5 ? estimated : (totals.get(key) ?? 0),
hasData: index === 5 ? currentRealtime.length > 0 : totals.has(key),
failed: failedMonths.includes(key),
estimated: index === 5,
}));
const chartMax = Math.max(1, ...chart.map((row) => Math.abs(row.value)));
return (
<div className='commission-dashboard'>
<section aria-labelledby='commission-month-overview'>
<h3 id='commission-month-overview'>{t('本月概览')}</h3>
<div className='commission-dashboard-core'>
<div className='commission-dashboard-stat'>
<span>{t('预估有效销售额')}</span>
<strong>{hasSales ? money(sales) : '—'}</strong>
{!hasSales && <small>{t('暂无销售额数据')}</small>}
</div>
<div className='commission-dashboard-stat commission-dashboard-stat--featured'>
<span>{t('预估应付提成')}</span>
<strong>{money(estimated)}</strong>
</div>
<div className='commission-dashboard-stat'>
<span>{t('占销售额比例')}</span>
<strong>
{hasSales && sales > 0
? `${numberFormat.format((estimated / sales) * 100)}%`
: '—'}
</strong>
</div>
</div>
<div className='commission-dashboard-support'>
{[
[
'生效合作伙伴',
partners.filter((row) => row.status === 'active').length,
],
[
'正式归属客户',
assignments.filter(
(row) => row.status === 'formal' && !row.ended_at,
).length,
],
['保护期客户', protectedAssignments.length],
].map(([label, count]) => (
<div className='commission-dashboard-stat' key={label}>
<span>{t(label)}</span>
<strong>{count}</strong>
</div>
))}
</div>
<p className='commission-dashboard-note'>
{t('预估数据会因人工调整发生变化,以正式账单为准。')}
</p>
</section>
<div className='commission-dashboard-main'>
<section
className='commission-dashboard-card'
aria-labelledby='commission-dashboard-todos'
>
<h3 id='commission-dashboard-todos'>{t('待办事项')}</h3>
<div className='commission-dashboard-todo-summary'>
{summaryTodos.map((todo) => (
<button
type='button'
className='commission-dashboard-summary-item'
key={todo.filter}
onClick={() => navigateTodo(todo)}
>
<span>{t(todo.label)}</span>
<strong className={`commission-dashboard-${todo.tone}`}>
{todo.rows.length}
</strong>
</button>
))}
</div>
<div className='commission-dashboard-todo-list'>
{detailedTodos.map((todo) => (
<div className='commission-dashboard-todo' key={todo.filter}>
<div>
<span
className={`commission-dashboard-tag commission-dashboard-tag--${todo.tone}`}
>
{t(todo.label)}
</span>
<h4>
{t('待处理 {{count}} 项', { count: todo.rows.length })}
</h4>
<p>{t(todo.description)}</p>
{todo.rows.length > 0 && (
<small>
{todo.rows
.slice(0, 2)
.map((row) =>
t('{{partner}} · {{month}}', {
partner:
partnerById.get(String(row.partner_id))?.name ||
t('伙伴 #{{id}}', { id: row.partner_id }),
month: row.statement_month,
}),
)
.join(' / ')}
</small>
)}
</div>
<button
type='button'
className={`commission-dashboard-button${todo.rows.length ? ' commission-dashboard-button--primary' : ''}`}
onClick={() => navigateTodo(todo)}
aria-label={t('{{action}}:{{label}},{{count}} 项', {
action: t(todo.action),
label: t(todo.label),
count: todo.rows.length,
})}
>
{t(todo.action)}
</button>
</div>
))}
</div>
</section>
<section
className='commission-dashboard-card commission-dashboard-health'
aria-labelledby='commission-dashboard-health'
>
<h3 id='commission-dashboard-health'>{t('数据健康')}</h3>
<p>{t('关注分佣档位配置完整性')}</p>
<div className='commission-dashboard-health-metrics'>
<button
type='button'
className='commission-dashboard-health-item'
onClick={() =>
onNavigate?.('tiers', {
source_type: 'channel',
unbound: true,
ids: unboundChannels.map((row) => row.id),
})
}
>
<span>{t('未绑定档位渠道')}</span>
<strong
className={
unboundChannels.length
? 'commission-dashboard-danger'
: 'commission-dashboard-success'
}
>
{unboundChannels.length}
</strong>
<small>{t('查看渠道档位')} →</small>
</button>
<button
type='button'
className='commission-dashboard-health-item'
onClick={() =>
onNavigate?.('tiers', {
source_type: 'level',
unbound: true,
levels: unboundLevels.map((row) => `${row.type}:${row.key}`),
})
}
>
<span>{t('未绑定档位等级')}</span>
<strong
className={
unboundLevels.length
? 'commission-dashboard-danger'
: 'commission-dashboard-success'
}
>
{unboundLevels.length}
</strong>
<p>{t('不含跟随模型或渠道档位的默认等级')}</p>
<small>{t('查看等级档位')} →</small>
</button>
</div>
</section>
</div>
<section
className='commission-dashboard-card commission-dashboard-trend'
aria-labelledby='commission-dashboard-trend'
>
<div className='commission-dashboard-trend-heading'>
<h3 id='commission-dashboard-trend'>{t('近 6 个月提成应付趋势')}</h3>
<span>{t('单位:万元 · 本月为预估')}</span>
</div>
{trendLoading && <p role='status'>{t('正在加载历史账单')}</p>}
{failedMonths.length > 0 && (
<div className='commission-dashboard-trend-error' role='alert'>
<span>
{t('部分月份加载失败:{{months}}', {
months: failedMonths.join('、'),
})}
</span>
<button
type='button'
className='commission-dashboard-button'
onClick={() => setRetry((value) => value + 1)}
>
{t('重试')}
</button>
</div>
)}
<div className='commission-dashboard-chart' aria-busy={trendLoading}>
{chart.map((row) => (
<button
type='button'
key={row.month}
className={`commission-dashboard-chart-column${row.estimated ? ' commission-dashboard-chart-column--current' : ''}`}
onClick={() => onNavigate?.('bills', { month: row.month })}
aria-label={t('{{month}}:{{amount}},{{status}}', {
month: row.month,
amount: money(row.value),
status: t(
row.failed
? '加载失败'
: row.estimated
? '实时预估'
: row.hasData
? '账单应付'
: '暂无数据',
),
})}
>
<span className='commission-dashboard-chart-plot'>
<span
className='commission-dashboard-chart-bar'
style={{
height: `${Math.max(row.value ? 2 : 0, (Math.abs(row.value) / chartMax) * 100)}%`,
}}
>
<span className='commission-dashboard-chart-value'>
{row.failed || (trendLoading && !row.estimated)
? '—'
: numberFormat.format(row.value / 1e10)}
</span>
</span>
</span>
<span className='commission-dashboard-chart-month'>
{row.month.slice(5)}
{t('月')}
</span>
<span className='commission-dashboard-chart-status'>
{row.failed
? t('加载失败')
: row.estimated
? t('预估')
: trendLoading
? t('加载中')
: !row.hasData
? t('暂无数据')
: '\u00a0'}
</span>
</button>
))}
</div>
</section>
</div>
);
}
+160
View File
@@ -0,0 +1,160 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Alert, Button } from 'antd';
import { useTranslation } from 'react-i18next';
import ListPanel from './ListPanel';
import { latestTierURL, fetchAllLatestTiers } from './latestTiers';
export default function LatestTierPanel({
fetchJSON,
columns,
onExport,
refreshToken,
}) {
const { t } = useTranslation();
const generation = useRef(0);
// 依赖变化时生成新的上下文对象,用于丢弃旧请求结果(原有逻辑,依赖为有意设置)。
// eslint-disable-next-line react-hooks/exhaustive-deps
const context = useMemo(() => ({}), [fetchJSON, refreshToken]);
const activeContext = useRef(context);
activeContext.current = context;
const exportRequest = useRef(null);
const [query, setQuery] = useState({ status: 'all', page: 1 });
const [state, setState] = useState({
items: [],
total: 0,
counts: {},
busy: true,
error: '',
});
const [exporting, setExporting] = useState(false);
const load = useCallback(async () => {
const current = ++generation.current;
setExporting(false);
setState((old) => ({ ...old, context, items: [], busy: true, error: '' }));
try {
const result = await fetchJSON(latestTierURL(query, query.page));
if (current !== generation.current || activeContext.current !== context)
return;
setState({
...result,
context,
items: result.items.map((item) => ({ ...item, __asOf: result.as_of })),
busy: false,
error: '',
});
} catch (error) {
if (current === generation.current && activeContext.current === context)
setState((old) => ({
...old,
items: [],
busy: false,
error: error.message,
}));
}
}, [fetchJSON, query, context]);
useEffect(() => {
load();
return () => {
// 卸载或重新加载时作废进行中的请求(原有逻辑)。
// eslint-disable-next-line react-hooks/exhaustive-deps
generation.current++;
};
}, [load]);
const exportAll = async () => {
if (
exportRequest.current?.context === context ||
state.busy ||
state.context !== context
)
return;
const request = { context };
exportRequest.current = request;
const current = generation.current;
setExporting(true);
try {
const rows = await fetchAllLatestTiers(fetchJSON, query);
if (current === generation.current && activeContext.current === context)
onExport(rows);
} catch (error) {
if (current === generation.current && activeContext.current === context)
setState((old) => ({ ...old, error: error.message }));
} finally {
if (exportRequest.current === request) exportRequest.current = null;
if (current === generation.current && activeContext.current === context)
setExporting(false);
}
};
const visible =
state.context === context
? state
: {
...state,
items: [],
total: 0,
counts: {},
busy: true,
error: '',
revision: undefined,
};
return (
<div data-testid='commission-latest-tiers' data-revision={visible.revision}>
{visible.error && (
<Alert
type='error'
showIcon
className='commission-inline-alert'
title={visible.error}
action={
<Button size='small' onClick={load}>
{t('重试')}
</Button>
}
/>
)}
<ListPanel
section='tiers'
rows={visible.items}
columns={columns}
partners={[]}
searchableText={() => ''}
onExport={exportAll}
server={{
...visible,
page: query.page,
exporting,
onChange: (next) => {
generation.current++;
exportRequest.current = null;
setExporting(false);
setState((old) => ({ ...old, items: [], busy: true, error: '' }));
setQuery(next);
},
}}
/>
</div>
);
}
+289
View File
@@ -0,0 +1,289 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Card, Empty, Input, Select, Table } from 'antd';
import { Search } from 'lucide-react';
import { filterCommissionRows, matchesStatus } from './listFilters';
export default function ListPanel({
section,
rows,
columns,
partners,
searchableText,
onExport,
context,
server,
}) {
const { t } = useTranslation();
const [draft, setDraft] = useState({ query: '', type: '', partner: '' });
const [filters, setFilters] = useState({});
const [scopedIds, setScopedIds] = useState(context?.ids || null);
const [status, setStatus] = useState('all');
const [page, setPage] = useState(1);
const set = (key, value) =>
setDraft((current) => ({ ...current, [key]: value }));
const tabSets = {
assignments: [
['all', '全部'],
['protect', '保护中'],
['pending_conversion', '待确认转化'],
['formal', '正式归属'],
['history', '历史归属'],
],
bills: [
['all', '全部'],
['estimated', '本月预估'],
['checking', '待核对'],
['pending_confirmation', '待确认'],
['confirmed', '已确认'],
['completed', '已完成'],
],
adjustments: [
['all', '全部'],
['applied', '已生效'],
['voided', '已作废'],
],
tiers: [
['all', '全部档位'],
['enabled', '启用中'],
['scheduled', '待生效'],
['disabled', '已停用'],
],
};
const typeOptions =
section === 'partners'
? [
['company', '企业'],
['individual', '个人'],
]
: section === 'assignments'
? [
['organization', '企业'],
['user', 'C 端'],
]
: section === 'tiers'
? [
['level', '等级档位'],
['model', '模型档位'],
['channel', '渠道档位'],
]
: null;
const placeholders = {
partners: '搜索伙伴名称 / 编号 / 协议编号',
assignments: '搜索客户名称 / ID',
tiers: '搜索档位 / 模型 / 渠道',
bills: '搜索伙伴 / 账单号',
adjustments: '搜索调整单 / 客户 / 原因',
audit: '搜索操作 / 实体 / 操作人',
exceptions: '搜索异常码 / 计费事实 / 说明',
};
const scopedRows = scopedIds
? rows.filter((row) => scopedIds.includes(row.id))
: rows;
const filtered = server
? rows
: filterCommissionRows(
scopedRows,
{
...filters,
status: section === 'partners' ? filters.status : status,
},
section,
searchableText,
);
const query = () => {
setFilters(draft);
setPage(1);
server?.onChange({ ...draft, status, page: 1 });
};
return (
<Card
className={`commission-card commission-list commission-list--${section}`}
>
{tabSets[section] && (
<div
className='commission-list-tabs'
role='tablist'
aria-label={t('状态筛选')}
>
{tabSets[section].map(([key, label]) => (
<button
key={key}
type='button'
role='tab'
aria-selected={status === key}
className={status === key ? 'is-active' : ''}
onClick={() => {
setStatus(key);
setPage(1);
server?.onChange({ ...filters, status: key, page: 1 });
}}
>
{t(label)}
<span>
{server
? server.counts[
{ enabled: 'active', scheduled: 'pending' }[key] || key
] || 0
: rows.filter((row) => matchesStatus(row, key, section))
.length}
</span>
</button>
))}
</div>
)}
{scopedIds && (
<div className='commission-context-filter'>
{t('正在查看工作台待办筛选结果')}
<Button
type='link'
size='small'
onClick={() => {
setScopedIds(null);
setPage(1);
}}
>
{t('查看全部')}
</Button>
</div>
)}
<div className='commission-filter-bar'>
<Input
prefix={<Search size={16} aria-hidden />}
value={draft.query}
onChange={(event) => set('query', event.target.value)}
onPressEnter={query}
allowClear
placeholder={t(placeholders[section])}
aria-label={t(placeholders[section])}
/>
{typeOptions && (
<Select
aria-label={t('类型筛选')}
value={draft.type}
onChange={(value) => set('type', value)}
options={[
{
value: '',
label: t(
section === 'assignments'
? '全部客户类型'
: section === 'tiers'
? '全部来源'
: '全部类型',
),
},
...typeOptions.map(([value, label]) => ({
value,
label: t(label),
})),
]}
/>
)}
{section === 'partners' && (
<Select
aria-label={t('状态筛选')}
value={draft.status || ''}
onChange={(value) => set('status', value)}
options={['', 'draft', 'active', 'suspended', 'terminated'].map(
(value, i) => ({
value,
label: t(['全部状态', '草稿', '生效中', '已暂停', '已终止'][i]),
}),
)}
/>
)}
{['assignments', 'bills', 'adjustments'].includes(section) && (
<Select
aria-label={t('合作伙伴筛选')}
showSearch={{ optionFilterProp: 'label' }}
value={draft.partner}
onChange={(value) => set('partner', value)}
options={[
{ value: '', label: t('全部合作伙伴') },
...partners.map((row) => ({ value: row.id, label: row.name })),
]}
/>
)}
<Button type='primary' onClick={query}>
{t('查询')}
</Button>
<Button
onClick={() => {
setDraft({ query: '', type: '', partner: '' });
setFilters({});
setStatus('all');
server?.onChange({ status: 'all', page: 1 });
setScopedIds(null);
setPage(1);
}}
>
{t('重置')}
</Button>
<div className='commission-filter-end'>
<span>
{t('共 {{count}} 条', {
count: server ? server.total : filtered.length,
})}
</span>
{onExport && (
<Button
loading={server?.exporting}
disabled={!!server?.busy}
onClick={() => onExport(filtered)}
>
{t('导出')}
</Button>
)}
</div>
</div>
<Table
rowKey='id'
loading={server?.busy}
columns={columns}
dataSource={filtered}
size='middle'
scroll={{ x: 'max-content' }}
pagination={{
size: 'small',
pageSize: server ? 100 : 10,
total: server ? server.total : filtered.length,
current: server ? server.page : page,
onChange: (next) => {
setPage(next);
server?.onChange({ ...filters, status, page: next });
},
showSizeChanger: false,
showTotal: (total) => t('共 {{total}} 条', { total }),
}}
locale={{
emptyText: (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={t('暂无数据')}
/>
),
}}
/>
</Card>
);
}
+194
View File
@@ -0,0 +1,194 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState } from 'react';
import { Alert, Button, Descriptions, Drawer, Spin, Table, Tag } from 'antd';
import { useTranslation } from 'react-i18next';
import { commissionActorName, commissionLabel, statusTagColor } from './labels';
import { EvidenceLink } from './operations';
export default function PartnerDetail({
partner,
assignments,
audit,
fetchJSON,
onClose,
onEdit,
}) {
const { t, i18n } = useTranslation();
const [record, setRecord] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
let current = true;
setRecord(null);
setError('');
if (partner)
fetchJSON(`/api/commission/v2/partners/${partner.id}`)
.then((value) => current && setRecord(value))
.catch((err) => current && setError(err.message));
return () => {
current = false;
};
}, [partner, fetchJSON]);
const row = record || partner || {};
const date = (value) =>
value ? new Date(value * 1000).toLocaleDateString(i18n.language) : '—';
const section = (title, fields) => (
<section className='commission-profile-section'>
<h3>{t(title)}</h3>
<Descriptions
size='small'
column={{ xs: 1, md: 2 }}
items={fields.map(([key, value]) => ({
key,
label: t(key),
children: value || '—',
}))}
/>
</section>
);
return (
<Drawer
rootClassName='commission-profile-drawer commission-detail-drawer'
title={
<span>
{row.name}{' '}
<Tag color={statusTagColor(row.status)}>
{commissionLabel(t, 'status', row.status)}
</Tag>
</span>
}
open={!!partner}
placement='right'
size={820}
onClose={onClose}
footer={
<div className='commission-drawer-actions'>
<Button onClick={onClose}>{t('关闭')}</Button>
<Button type='primary' onClick={() => onEdit(partner)}>
{t('编辑伙伴档案')}
</Button>
</div>
}
>
{error && (
<Alert
type='error'
showIcon
className='commission-inline-alert'
title={error}
/>
)}
{!record && !error ? (
<Spin className='commission-drawer-spin' />
) : (
<>
{section('基本信息', [
['伙伴编号', row.partner_code],
['主体类型', commissionLabel(t, 'partnerType', row.type)],
['状态', commissionLabel(t, 'status', row.status)],
['伙伴名称', row.name],
['登录主体', `#${row.user_id}`],
['证件号码', row.identity_no],
['联系人', row.contact_name],
['联系电话', row.contact_phone],
['通知邮箱', row.contact_email],
])}
{section('协议信息', [
['协议编号', row.agreement_no],
[
'协议有效期',
`${date(row.agreement_effective_at)} ~ ${date(row.agreement_expires_at)}`,
],
[
'协议附件',
row.agreement_evidence ? (
<EvidenceLink value={row.agreement_evidence} />
) : null,
],
])}
{section('结算资料', [
['收款账户名', row.receiving_name],
['收款账号', row.receiving_account],
['开户行', row.receiving_bank],
])}
<section className='commission-profile-section'>
<h3>{t('名下客户')}</h3>
<Table
rowKey='id'
size='middle'
scroll={{ x: 'max-content' }}
dataSource={assignments.filter(
(item) => item.partner_id === row.id,
)}
pagination={{ pageSize: 5, size: 'small' }}
columns={[
{
title: t('客户'),
render: (_, item) =>
item.customer_name || `#${item.subject_id}`,
},
{
title: t('类型'),
render: (_, item) =>
commissionLabel(t, 'subjectType', item.subject_type),
},
{
title: t('状态'),
render: (_, item) =>
commissionLabel(t, 'status', item.status),
},
{
title: t('起止时间'),
render: (_, item) =>
`${date(item.started_at)} ~ ${date(item.ended_at)}`,
},
]}
/>
</section>
<section className='commission-profile-section'>
<h3>{t('变更记录')}</h3>
<div className='commission-timeline'>
{audit
.filter(
(item) =>
item.entity_type === 'partner' && item.entity_id === row.id,
)
.map((item) => (
<div key={item.id}>
<strong>
{commissionLabel(t, 'operation', item.action)}
</strong>
<p>
{date(item.created_at)} · {t('操作人')}{' '}
{commissionActorName(t, item)}
</p>
</div>
))}
{!audit.some(
(item) =>
item.entity_type === 'partner' && item.entity_id === row.id,
) && <p className='commission-muted'>{t('暂无操作记录')}</p>}
</div>
</section>
</>
)}
</Drawer>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,183 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { Alert, Button, Select } from 'antd';
import { useTranslation } from 'react-i18next';
import {
createRequestGeneration,
mergeIdentityOptions,
identityOptionLabel,
} from './latestTiers';
const RemoteIdentitySelect = forwardRef(function RemoteIdentitySelect(
{ type, value, onChange, fetchJSON },
ref,
) {
const { t } = useTranslation();
const gate = useRef(createRequestGeneration());
const timer = useRef();
const [query, setQuery] = useState('');
const [state, setState] = useState({
items: [],
total: 0,
page: 0,
busy: false,
error: '',
});
const selected = useRef(null);
const active = useRef(true);
useImperativeHandle(
ref,
() => ({
invalidate() {
active.current = false;
gate.current.next();
clearTimeout(timer.current);
},
}),
[],
);
const load = async (q, page, generation) => {
setState((old) => ({ ...old, busy: true, error: '' }));
try {
const result = await fetchJSON(
`/api/commission/v2/options/${type === 'company' ? 'organizations' : 'users'}?${new URLSearchParams({ q, p: String(page), page_size: '20' })}`,
);
if (!gate.current.current(generation)) return;
setState((old) => ({
items: mergeIdentityOptions(
page === 1 ? [] : old.items,
result.items || [],
selected.current,
),
total: result.total,
page,
busy: false,
error: '',
}));
} catch (error) {
if (gate.current.current(generation))
setState((old) => ({ ...old, busy: false, error: error.message }));
}
};
const search = (q) => {
clearTimeout(timer.current);
const generation = gate.current.next();
setQuery(q);
setState({
items: selected.current ? [selected.current] : [],
total: 0,
page: 0,
busy: true,
error: '',
});
timer.current = setTimeout(() => load(q, 1, generation), 300);
};
useEffect(() => {
active.current = true;
search('');
return () => {
active.current = false;
// 卸载时作废进行中的请求(原有逻辑)。
// eslint-disable-next-line react-hooks/exhaustive-deps
gate.current.next();
clearTimeout(timer.current);
};
// 仅在类型或数据源变化时重新搜索(原有逻辑,依赖为有意设置)。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [type, fetchJSON]);
const selectIdentity = (id) => {
if (!active.current) return;
selected.current = state.items.find((item) => item.id === id) || null;
onChange(id);
};
return (
<div>
<Select
aria-label={t(type === 'company' ? '关联企业' : '关联个人用户')}
placeholder={t(
type === 'company'
? '输入企业 ID、名称或编码'
: '输入用户 ID、用户名或显示名',
)}
showSearch={{ filterOption: false, onSearch: search }}
allowClear
style={{ width: '100%' }}
value={value}
loading={state.busy}
// 选中即提交,保证快速保存时读取到的就是界面显示的 ID。
onSelect={selectIdentity}
onChange={(id) => {
if (id == null) selectIdentity(id);
}}
options={state.items.map((item) => ({
value: item.id,
label: identityOptionLabel(item),
disabled: item.disabled,
}))}
notFoundContent={
state.error
? t('加载失败')
: state.busy
? t('加载中')
: t(
type === 'company'
? '未找到可关联企业,请核对 ID 或企业状态'
: '未找到可关联用户,请核对 ID 或账号状态',
)
}
onOpenChange={(visible) => {
if (visible && !state.page && !state.busy) search(query);
}}
/>
{state.error && (
<Alert
type='error'
showIcon
className='commission-inline-alert'
title={state.error}
/>
)}
{state.error && (
<Button
aria-label={t('重试加载身份')}
onClick={() => load(query, state.page + 1, gate.current.next())}
>
{t('重试')}
</Button>
)}
{!state.error && state.page * 20 < state.total && (
<Button
aria-label={t('加载更多身份')}
loading={state.busy}
onClick={() => load(query, state.page + 1, gate.current.next())}
>
{t('加载更多')}
</Button>
)}
</div>
);
});
export default RemoteIdentitySelect;
+492
View File
@@ -0,0 +1,492 @@
.commission-dashboard {
--dash-line: var(--border-subtle, rgba(15, 23, 42, 0.12));
--dash-muted: var(--text-tertiary, var(--text-secondary, #7b8798));
--dash-primary: var(
--commission-primary-solid,
var(--commission-primary, var(--brand-primary, #165dff))
);
--dash-text: var(--text-primary, #1d2129);
--dash-card: var(--surface-card, #fff);
--dash-soft: color-mix(in srgb, var(--surface-bg-base) 52%, var(--dash-card));
--dash-featured-bg: color-mix(
in srgb,
var(--commission-primary-soft, #e8f0ff) 62%,
var(--dash-card)
);
--dash-featured-line: color-mix(
in srgb,
var(--dash-primary) 24%,
var(--dash-line)
);
--dash-warning: color-mix(in srgb, #f59e0b 78%, var(--dash-text));
--dash-danger: color-mix(in srgb, #f56c7a 82%, var(--dash-text));
--dash-success: color-mix(in srgb, #22c55e 78%, var(--dash-text));
--dash-warning-bg: color-mix(in srgb, #f59e0b 12%, var(--dash-card));
--dash-danger-bg: color-mix(in srgb, #f56c7a 12%, var(--dash-card));
--dash-grid: color-mix(in srgb, var(--dash-text) 11%, transparent);
--dash-muted-bar: color-mix(
in srgb,
var(--dash-primary) 28%,
var(--dash-card)
);
color: var(--dash-text);
min-width: 0;
}
.commission-dashboard-heading,
.commission-dashboard-trend-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.commission-dashboard-heading {
margin-bottom: 20px;
}
.commission-dashboard h2 {
margin: 0 0 6px;
font-size: 22px;
font-weight: 600;
line-height: 1.4;
}
.commission-dashboard h3 {
margin: 0 0 18px;
color: var(--dash-text);
font-size: 15px;
font-weight: 600;
line-height: 1.5;
}
.commission-dashboard p {
margin: 0;
font-size: 13px;
color: var(--dash-muted);
line-height: 1.8;
}
.commission-dashboard-period {
flex-shrink: 0;
border: 1px solid var(--dash-line);
border-radius: 4px;
background: var(--dash-card);
padding: 6px 12px;
font-size: 12px;
color: var(--dash-muted);
}
.commission-dashboard-core,
.commission-dashboard-support {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
}
.commission-dashboard-stat,
.commission-dashboard-card {
border: 1px solid var(--dash-line);
border-radius: 6px;
background: var(--dash-card);
box-shadow: none;
min-width: 0;
}
.commission-dashboard-stat {
padding: 16px 20px;
}
.commission-dashboard-stat > span,
.commission-dashboard-summary-item > span,
.commission-dashboard-health-item > span {
display: block;
font-size: 13px;
font-weight: 400;
color: var(--dash-muted);
line-height: 1.5;
}
.commission-dashboard strong {
font-variant-numeric: tabular-nums;
}
.commission-dashboard-stat > strong {
display: block;
margin-top: 8px;
font-size: 28px;
font-weight: 600;
letter-spacing: -0.7px;
line-height: 1.3;
overflow-wrap: anywhere;
}
.commission-dashboard-stat > small {
display: block;
margin-top: 6px;
color: var(--dash-muted);
font-size: 12px;
}
.commission-dashboard-stat--featured {
background: var(--dash-featured-bg);
border-color: var(--dash-featured-line);
}
.commission-dashboard-stat--featured > strong {
color: var(--dash-primary);
}
.commission-dashboard-support {
margin-top: 12px;
}
.commission-dashboard-support .commission-dashboard-stat {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 20px;
}
.commission-dashboard-support .commission-dashboard-stat > strong {
margin: 0;
font-size: 22px;
}
.commission-dashboard p.commission-dashboard-note {
margin-top: 12px;
font-size: 12px;
}
.commission-dashboard-main {
display: grid;
grid-template-columns: minmax(0, 2.2fr) minmax(260px, 1fr);
gap: 16px;
margin: 16px 0;
}
.commission-dashboard-card {
padding: 18px 20px;
}
.commission-dashboard-todo-summary {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-bottom: 8px;
}
.commission-dashboard button {
font-family: inherit;
cursor: pointer;
}
.commission-dashboard button:focus-visible {
outline: 2px solid var(--dash-primary);
outline-offset: 3px;
}
.commission-dashboard-summary-item {
padding: 10px 12px;
text-align: left;
border: 1px solid var(--dash-line);
border-radius: 4px;
background: var(--dash-soft);
min-width: 0;
}
.commission-dashboard-summary-item > span {
font-size: 12px;
}
.commission-dashboard-summary-item > strong {
display: block;
margin-top: 6px;
font-size: 22px;
font-weight: 600;
}
.commission-dashboard-primary {
color: var(--dash-primary);
}
.commission-dashboard-warning {
color: var(--dash-warning);
}
.commission-dashboard-danger {
color: var(--dash-danger);
}
.commission-dashboard-success {
color: var(--dash-success);
}
.commission-dashboard-todo {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
border-bottom: 1px solid var(--dash-line);
padding: 15px 0;
}
.commission-dashboard-todo:last-child {
border: 0;
padding-bottom: 0;
}
.commission-dashboard-todo > div {
min-width: 0;
}
.commission-dashboard-tag {
display: inline-block;
border-radius: 4px;
padding: 1px 7px;
font-size: 11px;
line-height: 1.8;
}
.commission-dashboard-tag--primary {
background: var(--dash-featured-bg);
color: var(--dash-primary);
}
.commission-dashboard-tag--warning {
background: var(--dash-warning-bg);
color: var(--dash-warning);
}
.commission-dashboard-tag--danger {
background: var(--dash-danger-bg);
color: var(--dash-danger);
}
.commission-dashboard-todo h4 {
margin: 5px 0 2px;
font-size: 13px;
font-weight: 600;
}
.commission-dashboard-todo small {
display: block;
color: var(--dash-muted);
font-size: 12px;
overflow-wrap: anywhere;
}
.commission-dashboard-button {
flex-shrink: 0;
border: 1px solid var(--dash-line);
border-radius: 4px;
padding: 6px 12px;
color: var(--text-secondary);
background: var(--dash-card);
font-size: 12px;
line-height: 1.5;
}
.commission-dashboard-button--primary {
border-color: var(--dash-primary);
color: #fff;
background: var(--dash-primary);
}
.commission-dashboard-button:hover,
.commission-dashboard-summary-item:hover,
.commission-dashboard-health-item:hover {
filter: brightness(0.97);
}
.commission-dashboard-health h3 {
margin-bottom: 8px;
}
.commission-dashboard-health-item {
width: 100%;
margin-top: 12px;
border: 0;
border: 1px solid var(--dash-line);
border-radius: 4px;
padding: 16px;
text-align: left;
background: var(--dash-soft);
}
.commission-dashboard-health-item > strong {
display: block;
margin-top: 8px;
font-size: 28px;
line-height: 1.3;
font-weight: 600;
}
.commission-dashboard-health-item > p {
margin-top: 12px;
font-size: 12px;
}
.commission-dashboard-health-item > small {
display: block;
margin-top: 12px;
color: var(--dash-primary);
font-size: 12px;
}
.commission-dashboard-trend-heading {
margin-bottom: 20px;
}
.commission-dashboard-trend-heading h3 {
margin: 0;
}
.commission-dashboard-trend-heading > span {
color: var(--dash-muted);
font-size: 12px;
}
.commission-dashboard-trend-error {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0 0 20px;
border: 1px solid
color-mix(in srgb, var(--dash-warning) 24%, var(--dash-line));
border-radius: 4px;
padding: 10px 12px;
background: var(--dash-warning-bg);
color: var(--dash-warning);
font-size: 12px;
}
.commission-dashboard-chart {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
padding-top: 16px;
}
.commission-dashboard-chart-column {
min-width: 0;
border: 0;
padding: 0;
background: transparent;
text-align: center;
color: var(--dash-muted);
}
.commission-dashboard-chart-plot {
display: flex;
align-items: flex-end;
justify-content: center;
height: 145px;
border-bottom: 1px solid var(--dash-line);
background: repeating-linear-gradient(
to top,
transparent 0,
transparent 47px,
var(--dash-grid) 47px,
var(--dash-grid) 48px
);
}
.commission-dashboard-chart-bar {
position: relative;
display: block;
width: 42%;
max-width: 72px;
min-height: 1px;
border-radius: 2px 2px 0 0;
background: var(--dash-muted-bar);
}
.commission-dashboard-chart-column--current .commission-dashboard-chart-bar {
background: var(--dash-primary);
}
.commission-dashboard-chart-value {
position: absolute;
left: 50%;
bottom: calc(100% + 8px);
transform: translateX(-50%);
font-size: 12px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.commission-dashboard-chart-month {
display: block;
margin-top: 10px;
font-size: 12px;
}
.commission-dashboard-chart-status {
display: block;
margin-top: 3px;
color: var(--dash-muted);
font-size: 11px;
}
@media (max-width: 1150px) {
.commission-dashboard-todo-summary {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.commission-dashboard-stat {
padding: 18px;
}
.commission-dashboard-stat > strong {
font-size: 26px;
}
}
@media (max-width: 900px) {
.commission-dashboard-main {
grid-template-columns: 1fr;
}
.commission-dashboard-core,
.commission-dashboard-support {
grid-template-columns: 1fr;
}
.commission-dashboard-health-metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
}
@media (max-width: 520px) {
.commission-dashboard-heading,
.commission-dashboard-trend-heading {
align-items: flex-start;
flex-direction: column;
gap: 10px;
}
.commission-dashboard-card {
padding: 16px;
}
.commission-dashboard-health-metrics {
grid-template-columns: 1fr;
gap: 0;
}
.commission-dashboard-todo {
align-items: flex-start;
}
.commission-dashboard-button {
padding: 6px 9px;
}
.commission-dashboard-chart-value {
font-size: 10px;
}
}
@@ -0,0 +1,26 @@
/*
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 function shouldLoadHistoricalTrend({
ready,
suppliedTrend,
historicalMonths,
}) {
return Boolean(ready && !suppliedTrend && historicalMonths);
}
@@ -0,0 +1,60 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import { shouldLoadHistoricalTrend } from './dashboardHistory.js';
test('historical trend waits for authenticated dashboard data', () => {
assert.equal(
shouldLoadHistoricalTrend({
ready: false,
suppliedTrend: false,
historicalMonths: '2026-06,2026-07',
}),
false,
);
assert.equal(
shouldLoadHistoricalTrend({
ready: true,
suppliedTrend: false,
historicalMonths: '2026-06,2026-07',
}),
true,
);
});
test('historical trend does not load when trend data is supplied or months are empty', () => {
assert.equal(
shouldLoadHistoricalTrend({
ready: true,
suppliedTrend: true,
historicalMonths: '2026-06',
}),
false,
);
assert.equal(
shouldLoadHistoricalTrend({
ready: true,
suppliedTrend: false,
historicalMonths: '',
}),
false,
);
});
+30
View File
@@ -0,0 +1,30 @@
/*
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 function pickerEpoch(firstValue, secondValue) {
// Semi DatePicker defaults to onChangeWithDateFirst=true, but callers can
// opt into the legacy text-first order. Prefer the actual Date object in
// either position so localized display text is never parsed as the value.
const dateValue = [firstValue, secondValue].find(
(value) => value instanceof Date && !Number.isNaN(value.getTime()),
);
const selected = dateValue ?? firstValue ?? secondValue;
if (!selected) return 0;
const timestamp = new Date(selected).getTime();
return Number.isFinite(timestamp) ? Math.floor(timestamp / 1000) : 0;
}
+42
View File
@@ -0,0 +1,42 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import { pickerEpoch } from './datePicker.js';
test('pickerEpoch handles Semi DatePicker date-first callback order', () => {
const selected = new Date('2026-12-24T08:30:00.000Z');
assert.equal(
pickerEpoch(selected, '2026-12-25 00:00:00'),
Math.floor(selected.getTime() / 1000),
);
});
test('pickerEpoch also handles text-first callbacks', () => {
const selected = new Date('2026-12-24T08:30:00.000Z');
assert.equal(
pickerEpoch('2026-12-25 00:00:00', selected),
Math.floor(selected.getTime() / 1000),
);
});
test('pickerEpoch returns zero for an empty or invalid selection', () => {
assert.equal(pickerEpoch('', undefined), 0);
assert.equal(pickerEpoch('invalid localized date', undefined), 0);
});
+63
View File
@@ -0,0 +1,63 @@
/*
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 COMMISSION_EVIDENCE_MAX_BYTES = 10 * 1024 * 1024;
export const COMMISSION_EVIDENCE_ACCEPT =
'.pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx';
const supportedExtensions = new Set([
'pdf',
'jpg',
'jpeg',
'png',
'webp',
'doc',
'docx',
'xls',
'xlsx',
]);
export function validateCommissionEvidenceFile(file) {
if (!file) return '请选择要上传的凭证文件';
const extension = String(file.name || '')
.split('.')
.pop()
.toLowerCase();
if (!supportedExtensions.has(extension)) {
return '凭证支持 PDF、JPG、PNG、WEBP、Word 或 Excel 文件';
}
if (Number(file.size || 0) > COMMISSION_EVIDENCE_MAX_BYTES) {
return '凭证文件不能超过 10MB';
}
return '';
}
export function commissionEvidenceErrorMessage(error) {
const serverMessage = error?.response?.data?.message;
if (typeof serverMessage === 'string' && serverMessage.trim()) {
return serverMessage.trim();
}
if (error?.code === 'ERR_NETWORK' || error?.message === 'Network Error') {
return '上传服务不可用,请检查后端服务和平台私有文件存储配置';
}
if (typeof error?.message === 'string' && error.message.trim()) {
return error.message.trim();
}
return '凭证上传失败,请稍后重试';
}
@@ -0,0 +1,69 @@
/*
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 assert from 'node:assert/strict';
import test from 'node:test';
import {
commissionEvidenceErrorMessage,
validateCommissionEvidenceFile,
} from './evidenceUpload.js';
test('accepts supported evidence files within the size limit', () => {
assert.equal(
validateCommissionEvidenceFile({ name: 'agreement.pdf', size: 1024 }),
'',
);
assert.equal(
validateCommissionEvidenceFile({
name: 'invoice.xlsx',
size: 10 * 1024 * 1024,
}),
'',
);
});
test('rejects unsupported or oversized evidence files before upload', () => {
assert.equal(
validateCommissionEvidenceFile({ name: 'notes.txt', size: 1024 }),
'凭证支持 PDF、JPG、PNG、WEBP、Word 或 Excel 文件',
);
assert.equal(
validateCommissionEvidenceFile({
name: 'large.pdf',
size: 10 * 1024 * 1024 + 1,
}),
'凭证文件不能超过 10MB',
);
});
test('turns network and server errors into actionable upload messages', () => {
assert.equal(
commissionEvidenceErrorMessage({ message: 'Network Error' }),
'上传服务不可用,请检查后端服务和平台私有文件存储配置',
);
assert.equal(
commissionEvidenceErrorMessage({
response: {
data: { message: '请先配置平台私有文件存储;也可填写线下凭证编号' },
},
message: 'Request failed',
}),
'请先配置平台私有文件存储;也可填写线下凭证编号',
);
});
+128
View File
@@ -0,0 +1,128 @@
/* Commission operation forms follow the same compact layout as the prototype. */
.commission-form-section {
grid-column: 1 / -1;
min-width: 0;
padding: 0;
}
.commission-form-section > h3 {
margin: 0 0 14px;
color: var(--text-primary);
font-size: 14px;
font-weight: 500;
line-height: 22px;
}
.commission-form-section-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
min-width: 0;
}
.commission-form-section-grid > .ant-alert,
.commission-form-section-grid > .commission-tier-targets,
.commission-form-section-grid > .commission-checklist,
.commission-form-section-grid > .commission-form-span,
.commission-form-section-grid > .commission-form-field:has(textarea),
.commission-form-section-grid
> .commission-form-field:has(.commission-evidence-input) {
grid-column: 1 / -1;
}
.commission-form-section-grid .commission-form-field {
gap: 6px;
}
.commission-form-section-grid .ant-input-number,
.commission-form-section-grid .ant-picker {
width: 100%;
}
.commission-required {
margin-right: 4px;
color: var(--commission-danger);
}
.commission-partner-sheet {
--commission-control-height: 32px;
}
.commission-partner-sheet .ant-drawer-body {
padding: 24px;
background: var(--surface-card);
scrollbar-gutter: stable;
}
.commission-partner-sheet .commission-operation-form {
display: flex;
flex-direction: column;
gap: 16px;
}
.commission-partner-sheet .commission-form-section {
padding: 20px;
border: 1px solid var(--border-subtle);
border-radius: 6px;
background: var(--surface-card);
}
.commission-partner-sheet .commission-form-section > h3 {
margin-bottom: 16px;
font-size: 16px;
}
.commission-partner-sheet-actions {
display: flex;
justify-content: flex-end;
gap: 14px;
}
.commission-partner-sheet .ant-radio-group {
min-height: 32px;
display: flex;
align-items: center;
gap: 16px;
}
.commission-partner-sheet .commission-evidence-upload-button {
height: 32px;
border-radius: 4px;
}
.commission-partner-sheet .commission-evidence-meta {
flex-wrap: wrap;
}
.commission-settlement-context {
grid-column: 1 / -1;
padding: 12px 16px;
border-radius: 4px;
background: var(--surface-card);
}
.commission-settlement-context .ant-descriptions-item {
padding-bottom: 0;
}
.commission-modal--settlement .commission-checklist {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 12px;
padding: 12px 0;
}
@media (max-width: 640px) {
.commission-form-section-grid {
grid-template-columns: minmax(0, 1fr);
}
.commission-partner-sheet .ant-drawer-body {
padding: 16px;
}
.commission-partner-sheet .commission-form-section {
padding: 16px;
}
}
File diff suppressed because it is too large Load Diff
+209
View File
@@ -0,0 +1,209 @@
/*
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
*/
// Keep API codes unchanged; translate only known display labels.
export const commissionLabels = {
level: {
default: '默认',
standard: '标准',
premium: '高级',
},
status: {
estimated: '本月预估',
checking: '待核对',
pending_confirmation: '待确认',
confirmed: '已确认',
completed: '已完成',
draft: '草稿',
active: '合作中',
suspended: '已暂停',
terminated: '已终止',
protected: '保护期内',
protected_extended: '保护期已延长',
pending_conversion: '待转正',
formal: '正式归属',
expired: '已过期',
transferred: '已转移',
applied: '已生效',
pending: '待处理',
open: '待处理',
resolved: '已处理',
voided: '已作废',
},
operation: {
status_transition: '状态流转',
completed: '登记完成',
adjustment_applied: '应用调整',
fee_set: '录入手续费',
issued: '正式出账',
deadline_changed: '修改确认截止日期',
partner_confirmed: '伙伴确认',
partner_rejected: '伙伴驳回',
auto_confirmed: '逾期视同确认',
adjustment_created: '创建调整单',
adjustment_updated: '修改调整单',
adjustment_voided: '作废调整单',
payment_recorded: '登记已打款',
statement_refreshed: '刷新金额',
blocked: '出账阻断',
unblocked: '解除出账阻断',
created: '新增',
extended: '延期',
converted: '转正',
rejected: '驳回',
transferred: '转移',
terminated: '终止',
activated: '启用',
suspended: '暂停',
resumed: '恢复',
partner_created: '新增伙伴',
partner_updated: '更新伙伴档案',
partner_activated: '启用伙伴',
partner_suspended: '暂停伙伴',
partner_terminated: '终止伙伴',
agreement_created: '登记协议',
agreement_renewed: '续签协议',
assignment_created: '建立归属',
assignment_extended: '延期保护期',
assignment_converted: '确认转正',
assignment_rejected: '驳回转化',
assignment_transferred: '转移归属',
assignment_terminated: '终止归属',
tier_created: '新增档位',
tier_version_created: '新增档位',
tier_updated: '更新档位',
tier_enabled: '启用档位',
tier_disabled: '停用档位',
pending_conversion: '待转正',
expired: '已过期',
resolved: '已处理',
},
partnerType: {
individual: '个人伙伴',
enterprise: '企业伙伴',
company: '企业伙伴',
},
subjectType: {
user: '个人用户',
organization: '企业组织',
},
sourceType: {
channel: '渠道档位',
model: '模型档位',
level: '等级档位',
},
adjustmentType: {
sales_amount: '销售额',
commission_amount: '提成金额',
},
entityType: {
statement: '账单',
partner: '伙伴',
assignment: '客户归属',
tier: '分佣档位',
},
};
export const statusColors = {
estimated: 'blue',
checking: 'orange',
pending_confirmation: 'amber',
confirmed: 'green',
completed: 'grey',
draft: 'grey',
active: 'green',
suspended: 'orange',
terminated: 'grey',
protected: 'blue',
protected_extended: 'cyan',
pending_conversion: 'orange',
formal: 'green',
expired: 'grey',
transferred: 'grey',
applied: 'green',
pending: 'orange',
open: 'orange',
resolved: 'green',
voided: 'grey',
};
// Semi 时代的状态色名 → antd 语义色(UI_COMPONENT_STANDARDS 第 11 节:状态用语义色)。
// 只影响 Tag 的视觉,不改变状态判定。
const STATUS_TAG_COLORS = {
blue: 'processing',
cyan: 'cyan',
orange: 'warning',
amber: 'warning',
green: 'success',
red: 'error',
grey: 'default',
};
export const statusTagColor = (status) =>
STATUS_TAG_COLORS[statusColors[status]] || 'default';
// The API keeps immutable event codes for auditability. These aliases translate
// the codes emitted by the V2 statement/adjustment services into the existing
// display labels without changing persisted data or export values.
const operationAliases = {
ADJ_CREATED: 'adjustment_created',
ADJ_UPDATED: 'adjustment_updated',
ADJ_DELETED: 'adjustment_voided',
BILL_CREATED: 'created',
BILL_ISSUED: 'issued',
FEE_ENTERED: 'fee_set',
PAID_REGISTERED: 'payment_recorded',
PARTNER_CONFIRMED: 'partner_confirmed',
PARTNER_REJECTED: 'partner_rejected',
AUTO_CONFIRMED: 'auto_confirmed',
BLOCK_DETECTED: 'blocked',
BLOCK_CLEARED: 'unblocked',
DEADLINE_CHANGED: 'deadline_changed',
RECALC: 'statement_refreshed',
agreement_registered: 'agreement_created',
agreement_expired: 'expired',
partner_status_changed: 'status_transition',
exception_resolved: 'resolved',
binding_created: 'created',
transferred_in: 'transferred',
pending_conversion: 'pending_conversion',
conversion_rejected: 'rejected',
};
export function commissionLabel(t, category, value) {
const labels = commissionLabels[category];
const normalizedValue =
category === 'operation' && typeof value === 'string'
? operationAliases[value] ||
operationAliases[value.toUpperCase()] ||
value
: value;
return labels && Object.hasOwn(labels, normalizedValue)
? t(labels[normalizedValue])
: value || '-';
}
export function commissionLevelName(t, { key, name }) {
return name && name !== key ? name : commissionLabel(t, 'level', key);
}
export function commissionActorName(t, { actor_id, actor_username }) {
if (actor_id === 0 || actor_id === '0') return t('系统');
return actor_username || t('未知用户');
}
+144
View File
@@ -0,0 +1,144 @@
/*
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 assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { createInstance } from 'i18next';
import { LANGUAGE_CODES } from '../../i18n/catalog.js';
import {
commissionLabel,
commissionLabels,
commissionLevelName,
commissionActorName,
} from './labels.js';
const resources = Object.fromEntries(
LANGUAGE_CODES.map((code) => [
code,
JSON.parse(
readFileSync(
new URL(`../../i18n/locales/${code}.json`, import.meta.url),
'utf8',
),
),
]),
);
test('audit operators show account names, distinguish system actions and missing accounts', () => {
const t = (key) => key;
assert.equal(
commissionActorName(t, { actor_id: 5, actor_username: 'admin.account' }),
'admin.account',
);
assert.equal(commissionActorName(t, { actor_id: 0 }), '系统');
assert.equal(commissionActorName(t, { actor_id: '0' }), '系统');
assert.equal(commissionActorName(t, { actor_id: 99 }), '未知用户');
assert.equal(commissionActorName(t, {}), '未知用户');
});
test('commission labels follow the selected language and preserve custom values', async () => {
const i18n = createInstance();
await i18n.init({
lng: 'zh',
resources,
fallbackLng: false,
keySeparator: false,
nsSeparator: false,
});
assert.equal(commissionLabel(i18n.t, 'level', 'default'), '默认');
assert.equal(commissionLabel(i18n.t, 'level', 'standard'), '标准');
assert.equal(commissionLabel(i18n.t, 'level', 'premium'), '高级');
assert.equal(commissionLabel(i18n.t, 'operation', 'fee_set'), '录入手续费');
for (const [action, expected] of Object.entries({
ADJ_CREATED: '创建调整单',
ADJ_UPDATED: '修改调整单',
ADJ_DELETED: '作废调整单',
BILL_CREATED: '新增',
BILL_ISSUED: '正式出账',
FEE_ENTERED: '录入手续费',
PAID_REGISTERED: '登记已打款',
PARTNER_CONFIRMED: '伙伴确认',
PARTNER_REJECTED: '伙伴驳回',
AUTO_CONFIRMED: '逾期视同确认',
BLOCK_DETECTED: '出账阻断',
BLOCK_CLEARED: '解除出账阻断',
DEADLINE_CHANGED: '修改确认截止日期',
RECALC: '刷新金额',
})) {
assert.equal(commissionLabel(i18n.t, 'operation', action), expected);
}
await i18n.changeLanguage('en');
assert.equal(commissionLabel(i18n.t, 'level', 'default'), 'Default');
assert.equal(commissionLabel(i18n.t, 'level', 'premium'), 'Premium');
assert.equal(commissionLabel(i18n.t, 'status', 'active'), 'Active');
assert.equal(commissionLabel(i18n.t, 'operation', 'fee_set'), 'Set fee');
assert.equal(commissionLabel(i18n.t, 'level', 'VIP-custom'), 'VIP-custom');
assert.equal(
commissionLabel(i18n.t, 'operation', 'new_action'),
'new_action',
);
assert.equal(commissionLabel(i18n.t, 'level', 'toString'), 'toString');
assert.equal(commissionLabel(i18n.t, 'level', null), '-');
assert.equal(
commissionLevelName(i18n.t, { key: 'default', name: 'default' }),
'Default',
);
assert.equal(
commissionLevelName(i18n.t, { key: 'default', name: '定制等级' }),
'定制等级',
);
await i18n.changeLanguage('zh-TW');
assert.equal(commissionLabel(i18n.t, 'level', 'default'), '預設');
});
test('every supported language has non-empty commission enum translations', () => {
for (const code of LANGUAGE_CODES) {
for (const labels of Object.values(commissionLabels)) {
for (const key of Object.values(labels)) {
assert.ok(
resources[code].translation[key]?.trim(),
`${code} is missing ${key}`,
);
}
}
}
});
test('commission page translations retain interpolation variables in every language', () => {
const source = ['index.jsx', 'operations.jsx']
.map((file) => readFileSync(new URL(`./${file}`, import.meta.url), 'utf8'))
.join('\n');
const keys = new Set(
[...source.matchAll(/\bt\('([^']+)'/gu)].map((match) => match[1]),
);
const variables = (text) =>
[...text.matchAll(/\{\{(\w+)\}\}/gu)].map((match) => match[1]).sort();
for (const code of LANGUAGE_CODES) {
for (const key of keys) {
const translated = resources[code].translation[key];
assert.ok(translated?.trim(), `${code} is missing ${key}`);
assert.deepEqual(
variables(translated),
variables(key),
`${code}: ${key}`,
);
}
}
});
+85
View File
@@ -0,0 +1,85 @@
/*
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 function latestTierURL(filters = {}, page = 1, snapshot = {}) {
const params = new URLSearchParams({
view: 'latest',
p: String(page),
page_size: '100',
});
if (filters.query?.trim()) params.set('q', filters.query.trim());
if (filters.type) params.set('source_type', filters.type);
const status =
{ enabled: 'active', scheduled: 'pending' }[filters.status] ||
filters.status;
if (status && status !== 'all') params.set('status', status);
if (snapshot.as_of) params.set('as_of', String(snapshot.as_of));
if (snapshot.revision != null)
params.set('revision', String(snapshot.revision));
return `/api/commission/v2/tiers?${params}`;
}
export async function fetchAllLatestTiers(fetchJSON, filters = {}) {
const rows = [];
let snapshot;
let total;
for (let page = 1; ; page++) {
const result = await fetchJSON(latestTierURL(filters, page, snapshot));
if (!snapshot) {
snapshot = { as_of: result.as_of, revision: result.revision };
total = result.total;
}
if (
result.as_of !== snapshot.as_of ||
result.revision !== snapshot.revision ||
result.total !== total
)
throw new Error('档位配置已变化,请重新加载或重新导出');
if (
!Array.isArray(result.items) ||
(rows.length < total && !result.items.length)
)
throw new Error('无法取得完整档位列表,请重试');
rows.push(...result.items);
if (rows.length === total) return rows;
if (rows.length > total) throw new Error('档位配置已变化,请重新导出');
}
}
export function mergeIdentityOptions(previous, next, selected) {
return [
...new Map(
[...(selected ? [selected] : []), ...previous, ...next].map((item) => [
Number(item.id),
item,
]),
).values(),
];
}
export function createRequestGeneration() {
let generation = 0;
return { next: () => ++generation, current: (value) => generation === value };
}
export function identityOptionLabel(item) {
const name =
item.name || item.display_name || item.username || item.code || '';
const identifier = item.name ? item.code : item.username;
return `${name}${identifier && identifier !== name ? ` · ${identifier}` : ''} (#${item.id})${item.disabled_reason ? ` · ${item.disabled_reason}` : ''}`;
}
+108
View File
@@ -0,0 +1,108 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
latestTierURL,
fetchAllLatestTiers,
mergeIdentityOptions,
createRequestGeneration,
identityOptionLabel,
} from './latestTiers.js';
test('identity labels distinguish duplicate display names by account and organization code', () => {
assert.equal(
identityOptionLabel({ id: 8, display_name: '红星', username: 'hongxing' }),
'红星 · hongxing (#8)',
);
assert.equal(
identityOptionLabel({
id: 8,
display_name: 'hongxing',
username: 'hongxing',
}),
'hongxing (#8)',
);
assert.equal(
identityOptionLabel({
id: 9,
name: '红星公司',
code: 'red-star',
disabled_reason: '已关联',
}),
'红星公司 · red-star (#9) · 已关联',
);
});
test('latest all status is omitted and export pins server snapshot across all pages', async () => {
assert.equal(
new URL(latestTierURL({ status: 'all' }), 'http://local').searchParams.has(
'status',
),
false,
);
const urls = [];
const rows = await fetchAllLatestTiers(
async (url) => {
urls.push(url);
const p = Number(new URL(url, 'http://local').searchParams.get('p'));
return {
items: p === 1 ? [{ id: 1 }] : [{ id: 2 }],
total: 2,
as_of: 123,
revision: 7,
};
},
{ query: '中文', type: 'level' },
);
assert.equal(rows.length, 2);
assert.match(urls[1], /as_of=123/);
assert.match(urls[1], /revision=7/);
});
test('export refuses changed revision and incomplete pages', async () => {
let p = 0;
await assert.rejects(
fetchAllLatestTiers(async () => ({
items: [{ id: ++p }],
total: 2,
as_of: 123,
revision: p,
})),
/变化/,
);
await assert.rejects(
fetchAllLatestTiers(async () => ({
items: [],
total: 2,
as_of: 123,
revision: 1,
})),
/完整/,
);
});
test('remote identity pages retain selection and stale lifecycle is invalidated synchronously', () => {
assert.deepEqual(
mergeIdentityOptions([{ id: 1 }], [{ id: 2 }], { id: 500 }),
[{ id: 500 }, { id: 1 }, { id: 2 }],
);
const gate = createRequestGeneration();
const old = gate.next();
gate.next();
assert.equal(gate.current(old), false);
});
+51
View File
@@ -0,0 +1,51 @@
/*
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 function tierStatus(row, now = Date.now() / 1000) {
if (row.effective_to && row.effective_to <= now) return 'disabled';
if (row.effective_from > now) return 'scheduled';
return 'enabled';
}
export function matchesStatus(row, status, key, now = Date.now() / 1000) {
if (!status || status === 'all') return true;
if (key === 'tiers') return tierStatus(row, now) === status;
if (status === 'protect')
return ['protected', 'protected_extended'].includes(row.status);
if (status === 'history')
return ['expired', 'transferred', 'terminated'].includes(row.status);
return row.status === status;
}
export function filterCommissionRows(rows, filters, key, searchableText) {
const query = (filters.query || '').trim().toLocaleLowerCase();
return rows.filter(
(row) =>
matchesStatus(row, filters.status, key) &&
(!filters.type ||
(key === 'partners'
? row.type
: key === 'tiers'
? row.source_type
: row.subject_type) === filters.type) &&
(!filters.partner ||
Number(row.partner_id) === Number(filters.partner)) &&
(!query || searchableText(row).toLocaleLowerCase().includes(query)),
);
}
@@ -0,0 +1,81 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
filterCommissionRows,
matchesStatus,
tierStatus,
} from './listFilters.js';
test('assignment protection and history tabs include all corresponding lifecycle states', () => {
assert.equal(
matchesStatus({ status: 'protected_extended' }, 'protect', 'assignments'),
true,
);
assert.equal(
matchesStatus({ status: 'pending_conversion' }, 'protect', 'assignments'),
false,
);
for (const status of ['expired', 'transferred', 'terminated'])
assert.equal(matchesStatus({ status }, 'history', 'assignments'), true);
});
test('future tier end dates remain enabled and future versions are scheduled', () => {
assert.equal(
tierStatus({ effective_from: 10, effective_to: 200 }, 100),
'enabled',
);
assert.equal(
tierStatus({ effective_from: 150, effective_to: 0 }, 100),
'scheduled',
);
assert.equal(
tierStatus({ effective_from: 10, effective_to: 100 }, 100),
'disabled',
);
});
test('search, customer type, partner and status combine without modifying the source', () => {
const rows = [
{
id: 1,
name: 'Acme',
subject_type: 'organization',
partner_id: 3,
status: 'formal',
},
{
id: 2,
name: 'Acme',
subject_type: 'user',
partner_id: 4,
status: 'formal',
},
];
assert.deepEqual(
filterCommissionRows(
rows,
{ query: ' ACME ', type: 'organization', partner: '3', status: 'formal' },
'assignments',
(r) => r.name,
).map((r) => r.id),
[1],
);
assert.equal(rows.length, 2);
});
+93
View File
@@ -0,0 +1,93 @@
/*
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 function validateContractSignedConversion(
form,
translate = (key) => key,
) {
if (
!form.reference?.trim() ||
!form.contract_subject?.trim() ||
!form.signed_at
) {
return translate('请填写合同编号、签约主体和签署日期');
}
if (form.signed_at > form.fact_at) {
return translate('合同签署日期不能晚于实际转化事实时间');
}
return '';
}
export function partnerIdentityPayload(form, translate = (key) => key) {
if (
!form.name?.trim() ||
(form.type === 'company' ? !form.organization_id : !form.user_id)
)
throw new Error(translate('请完整填写伙伴名称和关联身份'));
const payload = { ...form };
if (form.type === 'company') delete payload.user_id;
else delete payload.organization_id;
return payload;
}
export function levelBindingPayload(form, level, translate = (key) => key) {
if (!level || !form.config_id)
throw new Error(translate('请选择客户等级及等级档位'));
if (level.is_default || level.key === 'default')
throw new Error(translate('默认等级跟随渠道,不能绑定等级档位'));
return {
level_type: level.type,
level_key: level.key,
config_id: form.config_id,
effective_from: form.effective_from || form.effective_at,
};
}
export function getInitialOperationForm(operation, now = Date.now()) {
const kind = operation?.kind || '';
const row = operation?.row || {};
const seconds = Math.floor(now / 1000);
return {
type: 'individual',
status: 'protected',
method: 'contract_signed',
days: 30,
effective_at: seconds,
fact_at: seconds,
source_type: 'channel',
rate_bps: 0,
effective_from: seconds,
...row,
...(kind === 'tier-create'
? {
channel_ids: row.channel_ids?.length
? [...row.channel_ids]
: row.source_type === 'channel' && row.source_id
? [row.source_id]
: [],
model_names: [...(row.model_names || [])],
previous_tier_id: row.id || undefined,
effective_from: seconds,
}
: {}),
...(kind === 'partner-create' ? { status: 'draft' } : {}),
...(kind === 'assignment-transfer' ? { partner_id: undefined } : {}),
};
}
@@ -0,0 +1,167 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
getInitialOperationForm,
validateContractSignedConversion,
partnerIdentityPayload,
levelBindingPayload,
} from './operationForm.js';
test('company payload requires only organization and omits legacy administrator identity', () => {
assert.deepEqual(
partnerIdentityPayload({
type: 'company',
name: '企业',
organization_id: 44,
user_id: 9,
}),
{ type: 'company', name: '企业', organization_id: 44 },
);
assert.throws(
() =>
partnerIdentityPayload({
type: 'individual',
name: '个人',
organization_id: 44,
}),
/身份/,
);
assert.deepEqual(
partnerIdentityPayload({
type: 'individual',
name: '个人',
user_id: 9,
organization_id: 44,
}),
{ type: 'individual', name: '个人', user_id: 9 },
);
});
test('binding submits configuration identity and selected time for server-side version resolution', () => {
assert.deepEqual(
levelBindingPayload(
{ config_id: 55, tier_id: 999, effective_from: 123 },
{ type: 'enterprise', key: 'gold' },
),
{
config_id: 55,
effective_from: 123,
level_type: 'enterprise',
level_key: 'gold',
},
);
assert.throws(
() =>
levelBindingPayload(
{ config_id: 55, effective_from: 123 },
{ type: 'enterprise', key: 'default' },
),
/默认/,
);
});
test('contract signing validation explains when the signed date is after conversion time', () => {
assert.equal(
validateContractSignedConversion(
{
reference: '1488999',
contract_subject: '测试公司',
signed_at: 1_000,
fact_at: 900,
},
(key) => key,
),
'合同签署日期不能晚于实际转化事实时间',
);
});
test('contract signing validation accepts a signed date at or before conversion time', () => {
assert.equal(
validateContractSignedConversion(
{
reference: '1488999',
contract_subject: '测试公司',
signed_at: 900,
fact_at: 900,
},
(key) => key,
),
'',
);
});
test('tier editing hydrates legacy channels and starts a new effective version', () => {
const form = getInitialOperationForm(
{
kind: 'tier-create',
row: { id: 12, source_type: 'channel', source_id: 7, effective_from: 10 },
},
200000,
);
assert.deepEqual(form.channel_ids, [7]);
assert.equal(form.previous_tier_id, 12);
assert.equal(form.effective_from, 200);
});
test('shared tier editing preserves every model or channel target', () => {
const form = getInitialOperationForm({
kind: 'tier-create',
row: {
id: 13,
source_type: 'model',
model_names: ['gpt-4o', 'gpt-4o-mini'],
},
});
assert.deepEqual(form.model_names, ['gpt-4o', 'gpt-4o-mini']);
assert.deepEqual(form.channel_ids, []);
});
test('new partner form always starts in draft status', () => {
const form = getInitialOperationForm(
{
kind: 'partner-create',
row: { status: 'protected', display_name: '测试伙伴' },
},
1_700_000_000_000,
);
assert.equal(form.status, 'draft');
assert.equal(form.display_name, '测试伙伴');
});
test('customer assignment form keeps protected status', () => {
const form = getInitialOperationForm(
{ kind: 'assignment-create', row: {} },
1_700_000_000_000,
);
assert.equal(form.status, 'protected');
});
test('editing a partner preserves the row status', () => {
const form = getInitialOperationForm(
{ kind: 'partner-edit', row: { status: 'active' } },
1_700_000_000_000,
);
assert.equal(form.status, 'active');
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,32 @@
/*
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 PARTNER_NAVIGATION = [
{ key: 'overview', label: '分佣概览' },
{ key: 'customers', label: '我的客户' },
{ key: 'estimate', label: '本月预估' },
{ key: 'bills', label: '我的提成' },
{ key: 'rules', label: '分佣规则' },
];
export function partnerView(search) {
const view = new URLSearchParams(search).get('view');
return PARTNER_NAVIGATION.some((item) => item.key === view)
? view
: 'overview';
}
+545
View File
@@ -0,0 +1,545 @@
.partner-portal .commission-v2-sider {
width: 220px !important;
flex-basis: 220px !important;
}
/* Organization owns the global header, sidebar and scroll container. */
.partner-portal-scope--embedded {
display: flex;
min-height: 100%;
}
.commission-admin-workspace.partner-portal--embedded {
/* 与企业中心其他页面同底色与标准卡片色(不再用分佣旧版灰卡) */
--commission-surface-raised: var(--surface-card);
flex: 1;
margin-top: 0;
min-height: 0;
background: transparent;
}
/* 企业中心「企业分佣」:按带侧栏页面统一规格(GLOBAL_UI_BASELINE §4.4)——
面包屑 12/18px、距顶 30px、与标题 24px;标题 28/32px/650;副标题 14/22px;页头与首块 18px;
内容边距取 --uc-page-pad-*(桌面 30/36/36,≤768px 16/16/24),不再使用白色面包屑横条。 */
.partner-portal--embedded .commission-workspace-bar {
flex: none;
height: auto;
padding: var(--uc-page-pad-top) var(--uc-page-pad-x) 0;
border-bottom: 0;
background: transparent;
color: var(--text-secondary);
font-size: 12px;
line-height: 18px;
}
.partner-portal--embedded .commission-workspace-bar b {
font-weight: 400;
}
.partner-portal--embedded .commission-crumb-slash {
padding: 0 10px;
color: var(--text-secondary);
}
.partner-portal--embedded .commission-v2-content {
padding: 24px var(--uc-page-pad-x) var(--uc-page-pad-bottom);
background: transparent;
}
.partner-portal--embedded .commission-page-header {
align-items: flex-end;
margin-bottom: 18px;
}
.partner-portal--embedded .commission-page-heading h4.ant-typography {
color: var(--uc-heading);
font-size: 28px;
line-height: 32px;
font-weight: 650;
letter-spacing: -0.6px;
}
.partner-portal--embedded
.commission-page-heading
> .ant-typography:last-child {
margin-top: 6px;
color: var(--uc-subtitle);
font-size: 14px;
line-height: 22px;
}
/* 嵌入控制台(/console/my-commission):伙伴导航按卡片呈现,与内容区间距 24px;
窄屏导航堆叠在上方时改为上距 16px(GLOBAL_UI_BASELINE §5 间距 8/16/24) */
.console-page
.partner-portal:not(.partner-portal--embedded)
.commission-v2-sider {
align-self: flex-start;
overflow: hidden;
border: 1px solid var(--border-subtle);
border-radius: 10px;
}
.console-page
.partner-portal:not(.partner-portal--embedded)
.commission-v2-content {
padding: 0 0 0 24px;
}
@media (max-width: 640px) {
/* antd 6 Layout hasSider 固定 flex-direction: row,窄屏需显式改为导航在上、内容在下 */
.commission-admin-workspace.partner-portal.ant-layout-has-sider {
flex-direction: column;
}
.commission-admin-workspace.partner-portal.ant-layout-has-sider
> .ant-layout {
width: auto;
}
.console-page
.partner-portal:not(.partner-portal--embedded)
.commission-v2-content {
padding: 16px 0 0;
}
}
/* antd 6 Layout:内容列允许收缩,避免宽表格撑开侧栏布局 */
.commission-admin-workspace.partner-portal > .ant-layout {
min-width: 0;
}
/* 卡片内边距:UI_COMPONENT_STANDARDS §3(桌面 24px,移动 16px) */
.partner-portal-card.ant-card > .ant-card-body {
padding: 24px;
}
/* 宽卡片铺满,窄屏保留可横向滚动的最小宽度(含账单详情页签) */
.commission-v2.partner-portal .ant-table table {
min-width: max(100%, 720px);
}
.partner-portal .partner-portal-estimate-table .ant-table table {
min-width: max(100%, 520px);
}
.partner-portal .ant-alert,
.partner-portal-modal .ant-alert {
border-radius: var(--commission-radius);
}
.partner-portal-welcome {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
padding: 10px 14px;
border: 1px solid
color-mix(in srgb, var(--commission-primary) 24%, transparent);
border-radius: 4px;
background: var(--commission-primary-soft);
color: var(--text-primary);
font-size: 13px;
}
.partner-portal-welcome > svg {
flex-shrink: 0;
color: var(--commission-primary-readable);
}
.partner-portal-metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 12px;
}
.partner-portal-metrics-three {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.partner-portal-metric {
min-width: 0;
min-height: 118px;
padding: 16px 20px;
border: 1px solid var(--border-subtle);
border-radius: 4px;
background: var(--commission-surface-raised);
}
.partner-portal-metric-label {
color: var(--text-tertiary);
font-size: 13px;
}
.partner-portal-metric-value {
margin-top: 6px;
color: var(--text-primary);
font-size: 28px;
font-weight: 600;
font-variant-numeric: tabular-nums;
line-height: 36px;
overflow-wrap: anywhere;
}
.partner-portal-metric.is-primary .partner-portal-metric-value {
color: var(--commission-primary-readable);
}
.partner-portal-metric-note {
margin-top: 6px;
color: var(--text-tertiary);
font-size: 12px;
}
.partner-portal-two-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: stretch;
gap: 12px;
}
.partner-portal-two-columns > .commission-card {
min-width: 0;
}
.partner-portal-card-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 16px;
color: var(--text-primary);
font-size: 14px;
font-weight: 600;
}
.partner-portal-card-title > span {
color: var(--text-tertiary);
font-size: 12px;
font-weight: 400;
}
.partner-portal-chart {
display: flex;
align-items: flex-end;
justify-content: space-around;
gap: 12px;
min-height: 208px;
padding: 12px 4px 0;
overflow-x: auto;
}
.partner-portal-chart-column {
display: flex;
align-items: center;
justify-content: flex-end;
flex: 1;
flex-direction: column;
min-width: max-content;
}
.partner-portal-chart-value {
margin-bottom: 7px;
color: var(--text-secondary);
font-size: 11px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.partner-portal-chart-bar {
width: min(100%, 40px);
border-radius: 2px 2px 0 0;
background: var(--commission-primary-hover);
}
.partner-portal-chart-bar.is-negative {
background: #f76560;
}
.partner-portal-chart-label {
margin-top: 10px;
color: var(--text-tertiary);
font-size: 11px;
white-space: nowrap;
}
.partner-portal-reminders {
display: grid;
}
.partner-portal-reminder {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
min-height: 66px;
padding: 12px 0;
border: 0;
border-bottom: 1px solid var(--surface-bg-base);
background: var(--surface-card);
color: var(--text-secondary);
font: inherit;
font-size: 13px;
text-align: left;
}
button.partner-portal-reminder {
cursor: pointer;
}
button.partner-portal-reminder:hover {
color: var(--commission-primary-readable);
}
.partner-portal-reminder:last-child {
border-bottom: 0;
}
.partner-portal-reminder > span:nth-child(2) {
flex: 1;
}
.partner-portal-reminder small {
display: block;
margin-top: 3px;
color: var(--text-tertiary);
font-size: 12px;
}
.partner-portal-reminder-icon {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 34px;
height: 34px;
border-radius: 4px;
background: var(--commission-primary-soft);
color: var(--commission-primary-readable);
}
.partner-portal-reminder-icon.is-warning {
background: var(--commission-warning-soft);
color: var(--commission-warning);
}
.partner-portal-filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
}
.partner-portal-filters > .ant-input-affix-wrapper,
.partner-portal-filters > .ant-input {
width: 280px;
max-width: 100%;
}
.partner-portal-filters > .ant-select {
min-width: 150px;
}
.partner-portal-filters > .ant-typography {
margin-left: auto;
font-size: 12px;
}
.partner-portal-card .ant-alert {
margin-bottom: 16px;
}
/* 行操作:UI_COMPONENT_STANDARDS §5.2 link + small,间距 8px,危险操作 danger */
.partner-portal-row-actions {
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
}
.partner-portal .partner-portal-row-actions .ant-btn-link {
padding: 0;
}
.partner-portal-mono {
font-family: ui-monospace, 'SFMono-Regular', Consolas, monospace;
}
.partner-portal-hint {
margin: 12px 0 0;
color: var(--text-tertiary);
font-size: 12px;
line-height: 1.8;
}
.partner-portal-detail-meta {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
color: var(--text-secondary);
font-size: 13px;
}
.partner-portal-detail-meta + .ant-alert {
margin-top: 12px;
margin-bottom: 0;
}
.partner-portal .partner-portal-back.ant-btn {
height: 24px;
margin: 0 0 8px;
padding: 0;
font-size: 13px;
}
.partner-portal .commission-tier-summary > .ant-typography {
/* The surrounding partner card already names this summary. */
display: none;
}
.partner-portal-detail-search {
max-width: 360px;
margin: 8px 0 12px;
}
.partner-portal-loading {
display: flex;
align-items: center;
justify-content: center;
min-height: 220px;
}
.partner-portal-rule-block {
margin-bottom: 20px;
}
.partner-portal-rule-block h3 {
margin: 0 0 8px;
color: var(--text-primary);
font-size: 13px;
font-weight: 600;
}
.partner-portal-rule-block p,
.partner-portal-rule-list {
margin: 0;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.9;
}
.partner-portal-rule-list {
margin-bottom: 16px;
padding-left: 22px;
}
.partner-portal-rule-list li {
margin-bottom: 14px;
padding-left: 4px;
}
.partner-portal-modal .ant-alert {
margin-bottom: 16px;
}
.partner-portal-reason-label {
display: block;
margin-bottom: 8px;
color: var(--text-primary);
font-size: 13px;
}
.partner-portal-reason-label span {
margin-left: 4px;
color: var(--ant-color-error);
}
@media (max-width: 1100px) {
.partner-portal-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.partner-portal-two-columns {
grid-template-columns: minmax(0, 1fr);
}
.partner-portal-metrics-three > :last-child {
grid-column: 1 / -1;
}
}
@media (max-width: 700px) {
.partner-portal .commission-v2-sider {
width: 168px !important;
flex-basis: 168px !important;
}
.partner-portal .commission-brand {
padding: 0 12px;
font-size: 14px;
}
.partner-portal .commission-page-header {
flex-direction: column;
}
.partner-portal .commission-actions {
max-width: 100%;
justify-content: flex-start;
}
.partner-portal .commission-workspace-role {
display: none;
}
.partner-portal--embedded .commission-page-header {
flex-direction: row;
flex-wrap: wrap;
}
.partner-portal--embedded .commission-page-heading {
flex: 1;
min-width: 180px;
}
}
@media (max-width: 640px) {
.partner-portal .commission-v2-sider {
width: 100% !important;
flex-basis: auto !important;
}
.partner-portal .partner-portal-card.ant-card > .ant-card-body {
padding: 16px;
}
.partner-portal-filters {
gap: 10px;
}
.partner-portal-filters > .ant-input-affix-wrapper,
.partner-portal-filters > .ant-input {
width: 100%;
}
.partner-portal-filters > .ant-select {
flex: 1;
min-width: 0;
}
.partner-portal-filters > .ant-typography {
flex-shrink: 0;
}
.partner-portal-metric {
min-height: 104px;
padding: 12px;
}
.partner-portal-metric-value {
font-size: 24px;
line-height: 32px;
}
.partner-portal-card-title {
flex-wrap: wrap;
}
}
+72
View File
@@ -0,0 +1,72 @@
/*
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
*/
const PARTNER_PREFIX = '/api/partner/v2';
export function partnerScope(userId, organizationId = null) {
const enterprise = organizationId !== null && organizationId !== undefined;
const org = Number(organizationId);
return {
key: `${Number(userId) || 0}:${enterprise ? org : 'personal'}`,
valid:
Number(userId) > 0 &&
(!enterprise || (Number.isSafeInteger(org) && org > 0)),
enterprise,
organizationId: enterprise ? org : null,
headers: enterprise ? { 'X-Org-Id': String(org) } : {},
url(value) {
if (!value.startsWith(`${PARTNER_PREFIX}/`))
throw new Error('仅允许访问伙伴接口');
return enterprise
? `/api/org/commission${value.slice(PARTNER_PREFIX.length)}`
: value;
},
};
}
// Capture one immutable scope. Neither future localStorage changes nor callers'
// headers may reinterpret a queued operation as another enterprise's request.
export function createPartnerTransport(scope, api, isCurrent) {
const check = () => {
if (!scope.valid || !isCurrent())
throw new Error('企业或登录身份已切换,请重新操作');
};
const configFor = (config = {}) => ({
...config,
skipErrorHandler: true,
headers: { ...config.headers, ...scope.headers },
});
return {
async fetchJSON(url, config) {
check();
const response = await api.get(scope.url(url), configFor(config));
check();
if (!response.data?.success)
throw new Error(response.data?.message || '加载失败');
return response.data.data || [];
},
async mutateJSON(method, url, body) {
check();
const response = await api[method](scope.url(url), body, configFor());
check();
if (!response.data?.success)
throw new Error(response.data?.message || '操作失败');
return response.data.data;
},
};
}
+103
View File
@@ -0,0 +1,103 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import { partnerScope, createPartnerTransport } from './partnerScope.js';
test('enterprise transport pins organization headers for both reads and confirmations', async () => {
const calls = [];
const api = {
get: async (...args) => {
calls.push(args);
return { data: { success: true, data: { id: 3 } } };
},
post: async (...args) => {
calls.push(args);
return { data: { success: true } };
},
};
const scope = partnerScope(9, 101);
const client = createPartnerTransport(scope, api, () => true);
await client.fetchJSON('/api/partner/v2/statements', {
headers: { 'X-Org-Id': '102' },
});
await client.mutateJSON('post', '/api/partner/v2/statements/3/transition', {
to: 'confirmed',
});
assert.equal(calls[0][0], '/api/org/commission/statements');
assert.equal(calls[0][1].headers['X-Org-Id'], '101');
assert.equal(calls[1][0], '/api/org/commission/statements/3/transition');
assert.equal(calls[1][2].headers['X-Org-Id'], '101');
});
test('old scope cannot dispatch queued confirmations and late reads are discarded', async () => {
let current = true,
writes = 0,
resolve;
const response = new Promise((done) => {
resolve = done;
});
const api = {
get: () => response,
post: async () => {
writes++;
return { data: { success: true } };
},
};
const client = createPartnerTransport(
partnerScope(9, 101),
api,
() => current,
);
const pending = client.fetchJSON('/api/partner/v2/summary');
current = false;
await assert.rejects(
client.mutateJSON('post', '/api/partner/v2/statements/1/transition', {}),
/切换/,
);
assert.equal(writes, 0);
resolve({ data: { success: true, data: { name: 'old organization' } } });
await assert.rejects(pending, /切换/);
});
test('personal and enterprise identities never share cache keys or endpoints', () => {
const personal = partnerScope(9),
enterprise = partnerScope(9, 101);
assert.notEqual(personal.key, enterprise.key);
assert.notEqual(enterprise.key, partnerScope(9, 102).key);
assert.notEqual(enterprise.key, partnerScope(10, 101).key);
assert.equal(
personal.url('/api/partner/v2/summary'),
'/api/partner/v2/summary',
);
// 入口探测:个人与企业作用域分别命中各自的 access 接口
assert.equal(
personal.url('/api/partner/v2/access'),
'/api/partner/v2/access',
);
assert.equal(
enterprise.url('/api/partner/v2/access'),
'/api/org/commission/access',
);
assert.equal(partnerScope(9, 0).valid, false);
assert.throws(
() => enterprise.url('/api/commission/v2/partners'),
/伙伴接口/,
);
});
+978
View File
@@ -0,0 +1,978 @@
/* Product prototype tokens are scoped to the commission workspace and portals. */
.commission-v2,
.commission-modal,
.commission-profile-drawer,
.commission-partner-sheet {
/* 新版分佣只消费全局主题 token,主题色和明暗模式由控制台统一驱动。 */
--commission-primary: var(--brand-primary);
--commission-primary-hover: var(--brand-primary-hover);
--commission-primary-soft: var(--brand-primary-soft);
/* Links on dark surfaces need a lighter reading color than the brand swatch. */
--commission-primary-readable: color-mix(
in srgb,
var(--commission-primary) 58%,
var(--text-primary)
);
/* White text on the default brand blue is below AA contrast; deepen solid fills. */
--commission-primary-solid: color-mix(
in srgb,
var(--commission-primary) 78%,
#000
);
--commission-success: color-mix(in srgb, #22c55e 78%, var(--text-primary));
--commission-success-soft: color-mix(
in srgb,
#22c55e 12%,
var(--surface-card)
);
--commission-warning: color-mix(in srgb, #f59e0b 82%, var(--text-primary));
--commission-warning-soft: color-mix(
in srgb,
#f59e0b 12%,
var(--surface-card)
);
--commission-danger: color-mix(in srgb, #f56c7a 82%, var(--text-primary));
--commission-danger-soft: color-mix(
in srgb,
#f56c7a 12%,
var(--surface-card)
);
--commission-info: color-mix(in srgb, #22d3ee 78%, var(--text-primary));
--commission-info-soft: color-mix(in srgb, #22d3ee 12%, var(--surface-card));
--text-tertiary: var(--text-secondary);
--commission-radius: 4px;
--commission-control-height: 32px;
--commission-surface-raised: color-mix(
in srgb,
var(--surface-card) 94%,
var(--text-primary)
);
--commission-surface-toolbar: color-mix(
in srgb,
var(--surface-card) 86%,
var(--surface-bg-base)
);
--commission-surface-control: color-mix(
in srgb,
var(--surface-card) 78%,
var(--surface-bg-base)
);
--commission-border-strong: color-mix(
in srgb,
var(--border-subtle) 78%,
var(--text-primary)
);
/* Controls need a distinct resting edge on dark cards. Keep the value
* derived from the global theme so custom brand and light themes still
* follow the console palette. */
--commission-control-border: var(--commission-border-strong);
--commission-control-border-hover: color-mix(
in srgb,
var(--commission-primary) 52%,
var(--commission-control-border)
);
--commission-control-focus-ring: color-mix(
in srgb,
var(--commission-primary) 28%,
transparent
);
color: var(--text-primary);
font-family:
-apple-system, 'PingFang SC', 'Microsoft YaHei', 'Helvetica Neue', Arial,
sans-serif;
font-size: 14px;
line-height: 1.5715;
}
.commission-v2 {
min-height: calc(100vh - var(--app-header-height, 64px));
background: var(--surface-bg-base);
}
.commission-admin-workspace {
display: flex;
flex-direction: column;
margin-top: var(--app-header-height, 64px);
width: 100%;
align-items: stretch;
}
/* 嵌入控制台外壳(ConsolePageContainer 已提供页头、面包屑与内边距)时:
去掉旧布局为固定顶栏预留的偏移与整屏最小高度,并隐藏重复的面包屑条 */
.console-page .commission-admin-workspace {
margin-top: 0;
min-height: 0;
}
.console-page .commission-admin-workspace .commission-workspace-bar {
display: none;
}
.console-page .commission-admin-workspace .commission-v2-content {
padding: 0;
}
/* 嵌入控制台时与其他控制台页面同一套底色:外层透出控制台页面底,卡片用标准卡片色,区块间距 18px。
原 !important 用于压 Semi Layout 背景,Semi 已移除,故去掉以便此处按作用域覆盖。 */
.console-page .commission-admin-workspace,
.console-page .commission-admin-workspace .commission-v2-content {
background: transparent;
}
.console-page .commission-admin-workspace {
--commission-surface-raised: var(--surface-card);
}
.console-page .commission-admin-workspace .commission-card {
margin-top: 18px;
}
.console-page
.commission-admin-workspace
.commission-v2-content
> .commission-card:first-child {
margin-top: 0;
}
/* 嵌入控制台时页面标题即控制台页标题:沿用控制台页头规格(28/32px/650、副标题 14/22px、与首块 18px) */
.console-page .commission-admin-workspace .commission-page-header {
align-items: flex-end;
margin-bottom: 18px;
}
.console-page
.commission-admin-workspace
.commission-page-heading
h4.ant-typography {
color: var(--text-primary);
font-size: 28px;
line-height: 32px;
font-weight: 650;
letter-spacing: -0.6px;
}
.console-page
.commission-admin-workspace
.commission-page-heading
> .ant-typography:last-child {
margin-top: 6px;
color: var(--text-secondary);
font-size: 14px;
line-height: 22px;
}
.commission-admin-workspace > .commission-admin-main {
display: flex;
flex: auto;
flex-direction: column;
min-width: 0;
}
.commission-v2-sider {
flex: 0 0 220px;
width: 220px;
background: var(--surface-sidebar);
border-right: 1px solid var(--border-subtle);
}
.commission-brand {
display: flex;
align-items: center;
gap: 8px;
height: 56px;
padding: 0 20px;
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
border-bottom: 1px solid var(--border-subtle);
}
.commission-brand-mark {
width: 24px;
height: 24px;
flex-shrink: 0;
border-radius: 4px;
background: var(--commission-primary-solid);
}
.commission-navigation {
padding: 8px 8px 16px;
}
.commission-nav-group {
padding: 14px 12px 6px;
color: var(--text-tertiary);
font-size: 12px;
}
.commission-nav-item {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
height: 38px;
margin: 2px 0;
padding: 0 12px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--text-secondary);
font: inherit;
font-size: 14px;
text-align: left;
cursor: pointer;
}
.commission-nav-item svg {
flex-shrink: 0;
stroke-width: 2px;
}
.commission-nav-item:hover {
background: var(--surface-bg-base);
color: var(--text-primary);
}
.commission-nav-item.is-active {
background: var(--commission-primary-soft);
color: var(--commission-primary-readable);
font-weight: 500;
box-shadow: inset 2px 0 0 var(--commission-primary);
}
.commission-nav-item:focus-visible {
outline: 2px solid var(--commission-primary);
outline-offset: -2px;
}
.commission-nav-badge {
margin-left: auto;
padding: 0 6px;
border-radius: 8px;
color: #fff;
background: #f53f3f;
font-size: 12px;
line-height: 16px;
}
.commission-workspace-bar {
display: flex;
align-items: center;
justify-content: space-between;
flex: 0 0 56px;
height: 56px;
padding: 0 20px;
background: var(--surface-header);
border-bottom: 1px solid var(--border-subtle);
color: var(--text-tertiary);
font-size: 13px;
}
.commission-workspace-bar b {
color: var(--text-primary);
font-weight: 500;
}
.commission-crumb-slash {
padding: 0 8px;
color: #c9cdd4;
}
.commission-workspace-role {
padding: 3px 12px;
border-radius: 3px;
background: var(--commission-primary-soft);
color: var(--commission-primary-readable);
}
.commission-v2-content {
min-width: 0;
padding: 16px 20px 32px;
background: var(--surface-bg-base);
}
.commission-page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.commission-page-heading {
min-width: 0;
}
.commission-page-heading h4.ant-typography {
margin: 0;
font-size: 20px;
line-height: 28px;
font-weight: 600;
}
.commission-page-heading > .ant-typography:last-child {
display: block;
margin-top: 2px;
color: var(--text-tertiary);
font-size: 13px;
}
.commission-actions {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 8px;
flex-wrap: wrap;
flex-shrink: 0;
max-width: 65%;
}
.commission-actions .ant-picker {
width: 138px;
}
.commission-card {
margin-top: 12px;
border: 1px solid var(--border-subtle);
border-radius: 10px;
background: var(--commission-surface-raised);
box-shadow: none;
}
.commission-v2-content > .commission-card:first-child {
margin-top: 0;
}
.commission-card > .ant-card-body > h5.ant-typography {
margin: 0 0 12px;
font-size: 16px;
font-weight: 500;
}
.commission-row-actions {
display: inline-flex;
align-items: center;
gap: 8px;
flex-wrap: nowrap;
white-space: nowrap;
}
.commission-row-actions .commission-more-actions {
position: relative;
}
.commission-entity {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 100px;
}
.commission-entity-name {
color: var(--text-primary);
font-weight: 500;
}
.commission-entity-reference {
max-width: 380px;
color: var(--text-tertiary);
font-size: 12px;
line-height: 18px;
white-space: normal;
overflow-wrap: anywhere;
}
.commission-entity--compact .commission-entity-reference {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.commission-v2 .commission-status {
height: 22px;
padding: 0 8px;
border-radius: 2px;
font-size: 12px;
white-space: nowrap;
}
.commission-muted {
color: var(--text-tertiary);
font-size: 12px;
}
.commission-money {
font-variant-numeric: tabular-nums;
font-weight: 500;
color: var(--text-primary);
}
.commission-list-tabs {
display: flex;
align-items: stretch;
gap: 4px;
overflow-x: auto;
border-bottom: 1px solid var(--commission-border-strong);
padding: 0 4px;
margin-bottom: 12px;
}
.commission-list-tabs > button {
position: relative;
flex-shrink: 0;
padding: 10px 16px;
border: 0;
background: transparent;
font: inherit;
color: var(--text-secondary);
cursor: pointer;
}
.commission-list-tabs > button:hover {
color: var(--commission-primary-readable);
}
.commission-list-tabs > button.is-active {
color: var(--commission-primary-readable);
font-weight: 500;
}
.commission-list-tabs > button.is-active::after {
content: '';
position: absolute;
bottom: 0;
left: 12px;
right: 12px;
height: 2px;
background: var(--commission-primary);
}
.commission-list-tabs > button > span {
margin-left: 6px;
padding: 0 6px;
border-radius: 8px;
background: var(--surface-bg-base);
color: var(--text-tertiary);
font-size: 12px;
}
.commission-list-tabs > button.is-active > span {
color: var(--commission-primary-readable);
background: var(--commission-primary-soft);
}
.commission-filter-bar {
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
padding: 10px 12px;
border: 1px solid var(--border-subtle);
border-radius: 4px;
background: var(--commission-surface-toolbar);
margin-bottom: 12px;
}
.commission-filter-bar > .ant-input-affix-wrapper {
width: 220px;
}
.commission-filter-bar > .ant-select {
min-width: 140px;
max-width: 200px;
}
.commission-filter-end {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
color: var(--text-tertiary);
font-size: 12px;
}
.commission-loading {
min-height: 360px;
display: grid;
place-items: center;
}
/* 页面级提示与弹层内提示统一使用 antd Alert 默认外观,只补块间距。 */
.commission-v2 .ant-alert,
.commission-inline-alert.ant-alert {
margin-bottom: 16px;
}
.commission-modal {
max-width: calc(100vw - 32px);
}
.commission-modal .ant-modal-body {
max-height: min(68vh, 680px);
overflow-y: auto;
}
.commission-modal .ant-modal-body > .ant-spin {
min-height: 160px;
display: flex;
align-items: center;
justify-content: center;
}
.commission-modal .ant-modal-body > .ant-typography {
display: block;
margin-top: 12px;
font-size: 12px;
line-height: 20px;
}
.commission-modal-alert {
margin-bottom: 16px;
}
.commission-operation-form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
padding: 0;
}
.commission-operation-form > .ant-alert,
.commission-operation-form > .commission-tier-targets,
.commission-operation-form > .ant-descriptions,
.commission-operation-form > .commission-evidence-input,
.commission-operation-form > .commission-tier-summary,
.commission-operation-form > .commission-form-field:has(textarea),
.commission-operation-form
> .commission-form-field:has(.commission-evidence-input) {
grid-column: 1/-1;
}
.commission-form-field {
display: flex;
flex-direction: column;
min-width: 0;
gap: 6px;
color: var(--text-secondary);
font-size: 14px;
}
.commission-form-field .ant-select {
width: 100%;
}
.commission-tier-targets {
display: flex;
flex-direction: column;
min-width: 0;
gap: 8px;
}
.commission-tier-targets .ant-select {
height: auto;
min-height: 32px;
}
.commission-field-hint {
color: var(--text-tertiary);
font-size: 12px;
line-height: 20px;
}
.commission-checklist {
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px 14px;
grid-column: 1/-1;
border-radius: 4px;
background: var(--surface-bg-base);
}
.commission-checklist .ant-checkbox-wrapper {
line-height: 22px;
}
.commission-picker-content,
.commission-confirm-content {
display: flex;
flex-direction: column;
gap: 12px;
}
.commission-picker-content .ant-typography,
.commission-confirm-content .ant-typography {
margin: 0;
line-height: 20px;
}
.commission-history-table {
grid-column: 1/-1;
width: 100%;
min-width: 0;
}
.commission-history-table table {
min-width: 760px;
table-layout: fixed;
}
.commission-history-table .ant-table-thead > tr > th {
padding: 10px 14px;
background: var(--surface-bg-base);
color: var(--text-primary);
font-size: 13px;
font-weight: 500;
white-space: nowrap;
}
.commission-history-table .ant-table-tbody > tr > td {
padding: 11px 14px;
color: var(--text-secondary);
line-height: 20px;
overflow-wrap: anywhere;
}
.commission-history-nowrap {
white-space: nowrap;
}
.commission-exception-content {
grid-column: 1/-1;
display: flex;
flex-direction: column;
gap: 16px;
}
.commission-exception-content .ant-descriptions {
padding: 12px;
border-radius: 4px;
background: var(--surface-bg-base);
overflow-wrap: anywhere;
}
.commission-evidence-input {
display: flex;
flex-direction: column;
min-width: 0;
gap: 8px;
}
.commission-evidence-input-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.commission-evidence-upload-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 108px;
height: 32px;
gap: 7px;
padding: 0 14px;
border: 1px solid var(--border-subtle);
border-radius: 4px;
background: var(--surface-card);
color: var(--commission-primary-readable);
cursor: pointer;
font-size: 13px;
}
.commission-evidence-upload-button:hover {
border-color: var(--commission-primary);
background: var(--commission-primary-soft);
}
.commission-evidence-upload-button input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.commission-evidence-meta {
display: flex;
align-items: center;
min-width: 0;
gap: 10px;
color: var(--text-tertiary);
font-size: 12px;
line-height: 18px;
}
.commission-evidence-file {
min-width: 0;
overflow: hidden;
color: var(--text-secondary);
text-overflow: ellipsis;
white-space: nowrap;
}
.commission-evidence-meta .ant-btn {
height: 24px;
padding: 0 8px;
font-size: 12px;
}
.commission-detail-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.commission-detail-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
}
.statement-summary-heading {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
}
.statement-summary-heading .ant-typography {
margin-top: 0;
}
.statement-summary-values {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 20px;
}
.statement-summary-values > div {
display: flex;
flex-direction: column;
gap: 6px;
padding: 16px 20px;
border: 1px solid var(--border-subtle);
border-radius: 4px;
background: var(--surface-card);
}
.statement-summary-values > div:last-child {
border-color: color-mix(in srgb, var(--commission-primary) 24%, transparent);
background: var(--commission-primary-soft);
}
.statement-summary-values .ant-typography {
color: var(--text-tertiary);
font-size: 13px;
}
.statement-summary-values strong {
font-size: 26px;
color: var(--text-primary);
font-variant-numeric: tabular-nums;
}
.statement-summary-values > div:last-child strong {
color: var(--commission-primary-readable);
}
.commission-detail-tabs {
margin-top: 12px;
padding: 0 20px 16px;
border-radius: 4px;
background: var(--surface-card);
}
.commission-tier-summary {
margin: 12px 0;
overflow: auto;
}
.commission-tier-summary > .ant-typography {
margin: 0 0 12px;
font-size: 16px;
font-weight: 500;
}
.commission-bill-steps {
display: flex;
margin: 20px 0 4px;
}
.commission-bill-step {
position: relative;
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
color: var(--text-tertiary);
font-size: 13px;
}
.commission-bill-step::after {
content: '';
position: absolute;
top: 12px;
left: 50%;
width: 100%;
height: 1px;
background: var(--border-subtle);
}
.commission-bill-step:last-child::after {
display: none;
}
.commission-bill-step > span {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 24px;
height: 24px;
border-radius: 50%;
background: var(--surface-bg-base);
}
.commission-bill-step.is-current {
color: var(--commission-primary-readable);
font-weight: 500;
}
.commission-bill-step.is-current > span,
.commission-bill-step.is-done > span {
background: var(--commission-primary);
color: #fff;
}
.commission-bill-step.is-done::after {
background: var(--commission-primary);
}
.commission-profile-drawer .ant-drawer-body {
padding: 24px;
background: var(--surface-bg-base);
scrollbar-gutter: stable;
}
.commission-drawer-spin {
display: flex;
justify-content: center;
padding: 48px 0;
}
.commission-drawer-actions {
display: flex;
justify-content: flex-end;
gap: 14px;
}
.commission-profile-section {
margin-bottom: 12px;
padding: 16px 20px;
border-radius: 4px;
background: var(--surface-card);
}
.commission-profile-section h3 {
margin: 0 0 12px;
font-size: 16px;
font-weight: 500;
}
.commission-profile-section .ant-descriptions {
overflow-wrap: anywhere;
}
.commission-timeline > div {
position: relative;
padding: 0 0 16px 20px;
border-left: 1px solid var(--border-subtle);
}
.commission-timeline > div::before {
content: '';
position: absolute;
top: 6px;
left: -4px;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--commission-primary);
}
.commission-timeline p {
margin: 4px 0 0;
color: var(--text-tertiary);
font-size: 12px;
}
.partner-statements {
margin-top: calc(var(--app-header-height, 64px) - 24px);
padding: 16px 20px 32px;
}
.partner-statements > .commission-v2-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.partner-statements > .commission-v2-header h4 {
margin: 0;
font-size: 20px;
}
.commission-detail-total {
margin: 10px 0;
color: var(--commission-primary-readable);
font-size: 30px;
font-weight: 600;
}
.commission-todos {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding-top: 12px;
}
@media (max-width: 1100px) {
.commission-v2-sider {
flex-basis: 200px;
width: 200px;
}
.commission-page-header {
flex-wrap: wrap;
}
.commission-actions {
max-width: 100%;
justify-content: flex-start;
}
.statement-summary-values {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 640px) {
.commission-admin-workspace {
flex-direction: column;
}
.commission-v2-sider {
flex: 0 0 auto;
width: 100%;
border-right: 0;
border-bottom: 1px solid var(--border-subtle);
}
.commission-brand {
display: none;
}
.commission-navigation {
display: flex;
gap: 4px;
overflow-x: auto;
padding: 8px;
}
.commission-nav-group {
display: none;
}
.commission-nav-item {
width: auto;
flex: 0 0 auto;
}
.commission-workspace-bar {
height: 44px;
flex-basis: 44px;
padding: 0 16px;
}
.commission-v2-content,
.partner-statements {
padding: 16px;
}
.commission-page-header {
gap: 12px;
}
.commission-actions {
gap: 8px;
}
.commission-filter-end {
margin-left: 0;
}
.commission-filter-bar > .ant-input-affix-wrapper {
width: 100%;
}
.commission-filter-bar > .ant-select {
flex: 1;
min-width: 120px;
}
.commission-list > .ant-card-body {
padding: 12px !important;
}
.commission-list-tabs > button {
padding: 10px 12px;
}
.commission-operation-form {
grid-template-columns: 1fr;
}
.commission-evidence-input-row {
grid-template-columns: 1fr;
}
.commission-evidence-upload-button {
width: 100%;
}
.commission-modal {
max-width: calc(100vw - 24px);
}
.commission-detail-toolbar {
align-items: flex-start;
flex-direction: column;
}
.commission-detail-actions {
justify-content: flex-start;
}
.statement-summary-heading {
flex-wrap: wrap;
}
.statement-summary-values > div {
padding: 12px;
}
.statement-summary-values strong {
font-size: 22px;
}
.commission-history-table table {
min-width: 680px;
}
}
.commission-code {
font-family: Consolas, Menlo, monospace;
font-size: 13px;
}
.commission-protection-period {
white-space: nowrap;
font-size: 13px;
}
.commission-protection-period span {
color: var(--text-tertiary);
margin-right: 4px;
}
.commission-protection-period small {
font-size: 12px;
color: var(--text-secondary);
}
.commission-protection-period small.is-urgent {
color: var(--commission-warning);
}
.commission-context-filter {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
color: var(--commission-primary-readable);
font-size: 13px;
}
.commission-deduction-summary {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin: 12px 0 20px;
padding: 16px;
background: var(--surface-bg-base);
border-radius: 4px;
}
.commission-deduction-summary > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 13px;
}
@media (max-width: 760px) {
.commission-deduction-summary {
grid-template-columns: 1fr;
}
}
+6 -6
View File
@@ -18,10 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess } from '../../helpers';
import { copy, showError, showSuccess } from '../../helpers';
import './styles.css';
const Docs = () => {
@@ -42,11 +41,12 @@ const Docs = () => {
{ id: 'comparison', icon: 'fa-chart-bar', label: t('工具对比') },
];
// 复制代码功能
// 复制代码功能:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
// 裸调会同步抛错、点了无反应
const copyCode = (code) => {
writeClipboardText(code)
.then(() => showSuccess(t('复制成功')))
.catch(() => showError(t('复制失败,请手动复制')));
copy(code).then((ok) =>
ok ? showSuccess(t('复制成功')) : showError(t('复制失败,请手动复制')),
);
};
// 滚动到顶部
@@ -100,7 +100,7 @@ const MODE_ICONS = { text2image: Type, edit: ImageIcon };
// 与视频页一致的预算来源文案(估价 budget_source 的前缀)
const BUDGET_SOURCE_LABELS = {
org_budget: '部门 / 项目预算',
token: '令牌额度',
token: '密钥额度',
org_member: '成员额度',
org_gift: '企业赠送额度',
org: '企业额度',
@@ -58,7 +58,7 @@ const { Title, Text, Paragraph } = Typography;
// 估价 budget_source → 预算层级名(i18n key);org_budget 实际值为 org_budget:<subject_type>
const BUDGET_SOURCE_LABELS = {
org_budget: '部门 / 项目预算',
token: '令牌额度',
token: '密钥额度',
org_member: '成员额度',
org_gift: '企业赠送额度',
org: '企业额度',
+9 -11
View File
@@ -23,7 +23,6 @@ import {
Zap as ActionZap,
RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons';
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useState, useCallback, useEffect, useContext } from 'react';
import { Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -62,7 +61,7 @@ import {
getImageCapability,
buildImageRequestBody,
} from '../../constants/imageModelCapabilities';
import { API, showError, showSuccess } from '../../helpers';
import { API, copy, showError, showSuccess } from '../../helpers';
import { StatusContext } from '../../context/Status';
import { isCreationStudioEnabled } from '../../helpers/creationStudio';
@@ -324,16 +323,15 @@ const ImageGeneration = () => {
setPagination((prev) => ({ ...prev, page: 1, pageSize }));
};
// 复制图片链接
// 复制图片链接:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到。
const copyImageLink = useCallback(
(imageUrl) => {
writeClipboardText(imageUrl)
.then(() => {
showSuccess(t('链接已复制'));
})
.catch(() => {
showError(t('复制失败'));
});
async (imageUrl) => {
if (await copy(imageUrl)) {
showSuccess(t('链接已复制'));
} else {
showError(t('复制失败'));
}
},
[t],
);
+2
View File
@@ -94,6 +94,7 @@ const actionConfig = {
create_token: { label: '创建密钥', color: 'green' },
update_token: { label: '更新密钥', color: 'blue' },
delete_token: { label: '删除密钥', color: 'red' },
view_token_key: { label: '查看密钥', color: 'orange' },
admin_create_org: { label: '管理员创建企业', color: 'cyan' },
admin_update_org: { label: '管理员更新企业', color: 'cyan' },
@@ -290,6 +291,7 @@ const OrgAudit = ({ orgId }) => {
{ value: 'create_token', label: t('创建密钥') },
{ value: 'update_token', label: t('更新密钥') },
{ value: 'delete_token', label: t('删除密钥') },
{ value: 'view_token_key', label: t('查看密钥') },
// 管理员操作
{ value: 'admin_create_org', label: t('管理员创建企业') },
{ value: 'admin_update_org', label: t('管理员更新企业') },
+42 -8
View File
@@ -39,6 +39,7 @@ import {
Progress,
Popconfirm,
} from '@/components/ui';
import { Tabs as AntTabs } from 'antd';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import {
@@ -50,6 +51,8 @@ import {
import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import OrgDeptFunds from './fund/OrgDeptFunds';
import { isOrgFeatureEnabled } from './orgFeatureFlags';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
@@ -72,8 +75,13 @@ const cycleLabel = (t, c) =>
})[c] || c;
// 预算中心:管理员配置部门/项目预算 cap(§5.3)。只提 cap,不增企业池。
const OrgBudgets = ({ orgId }) => {
// 「部门资金」页签(MaaS V2.1.0 P0):同时开通 dept 与 budget 才展示(M-08)。
const OrgBudgets = ({ orgId, featureFlags }) => {
const { t } = useTranslation();
const fundsAvailable =
isOrgFeatureEnabled(featureFlags, 'dept') &&
isOrgFeatureEnabled(featureFlags, 'budget');
const [tab, setTab] = useState('limits');
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const [updatingBudgetId, setUpdatingBudgetId] = useState(null);
@@ -429,13 +437,9 @@ const OrgBudgets = ({ orgId }) => {
},
];
return (
<div className='uc-page oc-page'>
<OrgPageHeader
title={t('预算中心')}
subtitle={t('管理部门、项目与成员的额度上限')}
/>
const onLimits = tab === 'limits';
const limitsContent = (
<>
{/* 原型 .eb-policy 说明条:替换原“预算实时拦截未生效”警告与 cap 说明两条 Banner */}
<div className='oc-policy' role='note'>
{t(
@@ -564,6 +568,36 @@ const OrgBudgets = ({ orgId }) => {
)}
</Form>
</OrgModal>
</>
);
return (
<div className='uc-page oc-page'>
<OrgPageHeader
title={t('预算中心')}
subtitle={
onLimits
? t('管理部门、项目与成员的额度上限')
: t('将企业资金分配给部门独立使用,与预算限额分别计算')
}
/>
{fundsAvailable ? (
<>
{/* 预算限额 / 部门资金(weiyuan afc2a61a7):.oc-list-tabs 只切换下方内容 */}
<AntTabs
className='oc-list-tabs oc-tabs-nav-only'
activeKey={tab}
onChange={setTab}
items={[
{ key: 'limits', label: t('预算限额') },
{ key: 'funds', label: t('部门资金') },
]}
/>
{onLimits ? limitsContent : <OrgDeptFunds orgId={orgId} />}
</>
) : (
limitsContent
)}
</div>
);
};
@@ -0,0 +1,112 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useId, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Wallet } from 'lucide-react';
import { ChevronDown as ActionChevronDown } from '@/components/common/icons/ActionIcons';
import {
PARTNER_NAVIGATION,
partnerView,
} from '../CommissionV2/partnerNavigation';
export default function OrgCommissionNavigation({
collapsed,
expandSidebar,
query,
renderText,
onNavigate,
}) {
const { t } = useTranslation();
const location = useLocation();
const active = location.pathname === '/org/commission';
const view = partnerView(location.search);
const [open, setOpen] = useState(active);
const submenuId = useId();
useEffect(() => {
if (active) setOpen(true);
}, [active, location.key]);
const expanded = !collapsed && (open || !!query);
const parentMatches = t('企业分佣').toLowerCase().includes(query);
const children = PARTNER_NAVIGATION.filter(
(item) =>
!query || parentMatches || t(item.label).toLowerCase().includes(query),
);
// 样式与控制台二级菜单一致(center-layout.css 的 .ui-console-submenu-*):父项 16px 图标 + 展开箭头,
// 子项无图标、与父项文字左对齐并带层级引导线;收起态点击先展开侧栏。
return (
<div className='ui-console-submenu org-commission-navigation'>
<button
type='button'
className='ui-center-menu-item ui-console-submenu-toggle'
data-child-active={active || undefined}
aria-label={t('企业分佣')}
title={collapsed ? t('企业分佣') : undefined}
aria-expanded={expanded}
aria-controls={submenuId}
onClick={() => {
if (collapsed) {
expandSidebar();
setOpen(true);
} else setOpen((value) => !value);
}}
>
<Wallet size={16} strokeWidth={1.5} aria-hidden='true' />
{!collapsed && (
<>
<span className='ui-center-menu-label'>
{renderText(t('企业分佣'))}
</span>
<ActionChevronDown
size={14}
className='ui-console-submenu-arrow'
aria-hidden
/>
</>
)}
</button>
<div
id={submenuId}
role='group'
aria-label={t('企业分佣')}
className='ui-org-group-items ui-console-submenu-items'
hidden={!expanded}
>
{children.map((item) => {
const selected = active && view === item.key;
return (
<Link
key={item.key}
to={`/org/commission?view=${item.key}`}
onClick={() => onNavigate?.()}
aria-current={selected ? 'page' : undefined}
data-active={selected || undefined}
className='ui-center-menu-item ui-console-submenu-item'
>
<span className='ui-center-menu-label'>
{renderText(t(item.label))}
</span>
</Link>
);
})}
</div>
</div>
);
}
+151 -3
View File
@@ -20,7 +20,13 @@ import {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
} from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Banner, Button, Form, Toast, Empty, Spin } from '@/components/ui';
import { Network } from 'lucide-react';
@@ -32,9 +38,21 @@ import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import DeptFlowCanvas from './components/DeptFlowCanvas';
import { buildDeptTreeData } from './components/deptTree';
import { orgFundApi } from './fund/fundApi';
import { renderQuota } from '../../helpers/render';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 确认弹窗包成 Promise:取消/关闭都视为不继续
const confirmAsync = (config) =>
new Promise((resolve) => {
OrgModal.confirm({
...config,
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
// 部门管理:组织架构画布(多棵树)+ 节点内操作;移动走后端 MoveDepartmentTx 级联 path
const OrgDepartments = ({ orgId }) => {
const { t } = useTranslation();
@@ -166,14 +184,139 @@ const OrgDepartments = ({ orgId }) => {
}
}, [modalVisible, editing, createParentId, formApi]);
const deptName = useCallback(
(id) =>
id ? list.find((d) => d.id === id)?.name || `#${id}` : t('顶级部门'),
[list, t],
);
// 调整上级(F-17):已建账企业二次确认资金与管理范围变化;预览拉取失败时不放行
const confirmMove = useCallback(
async (deptId, oldParentId, newParentId) => {
let preview;
try {
const res = await orgFundApi.movePreview(orgId, deptId);
if (!res?.data?.success) {
showError(res?.data?.message || t('加载失败,请重试'));
return false;
}
preview = res.data.data;
} catch {
showError(t('加载失败,请重试'));
return false;
}
if (!preview || preview.fund_state === 0) return true;
return confirmAsync({
title: t('确认调整部门上级'),
okText: t('确认调整'),
cancelText: t('取消'),
content: (
<div className='flex flex-col gap-2'>
<div>
{t(
'将把「{{dept}}」从「{{from}}」调整至「{{to}}」。该部门及随迁子部门的资金账户和余额将保留,原上级将失去相应资金查看及回收权限。本次不会再次扣减原上级账户。',
{
dept: deptName(deptId),
from: deptName(oldParentId),
to: deptName(newParentId),
},
)}
</div>
<div className='tabular-nums text-[var(--text-secondary)]'>
{t('自身可用 {{a}} / 随迁部门可用合计 {{b}}', {
a: renderQuota(preview.self_balance || 0, 2),
b: renderQuota(preview.subtree_balance || 0, 2),
})}
</div>
</div>
),
});
},
[orgId, t, deptName],
);
// 停用/启用(M-04):复用停用成员的逻辑,提示连带影响;预览拉取失败时不放行
const confirmStatus = async (deptId, nextStatus) => {
let p;
try {
const res = await API.get(`/api/org/dept/${deptId}/status-preview`, {
headers: getOrgHeaders(orgId),
skipErrorHandler: true,
});
if (!res?.data?.success) {
showError(res?.data?.message || t('加载失败,请重试'));
return false;
}
p = res.data.data;
} catch {
showError(t('加载失败,请重试'));
return false;
}
const disabling = nextStatus === 2;
const lines = disabling
? [
t(
'停用后,该部门 {{n}} 名直属成员将被一并停用,其 API 令牌将被禁用;下级部门不受影响。',
{ n: p.to_disable },
),
t('部门资金余额保留,不能再接收分配,仍可被回收。'),
]
: [
t(
'启用后,该部门 {{n}} 名已停用的直属成员将恢复启用(包括此前被单独停用的成员),已禁用的 API 令牌需重新启用。',
{ n: p.to_enable },
),
];
if (disabling && p.has_owner) lines.push(t('企业所有者不会被停用。'));
if (disabling && p.affected_managers?.length)
lines.push(
t('以下部门管理员也将被停用,并失去管理入口:{{names}}', {
names: p.affected_managers.join('、'),
}),
);
return confirmAsync({
title: disabling ? t('确认停用部门') : t('确认启用部门'),
okText: disabling ? t('确认停用') : t('确认启用'),
cancelText: t('取消'),
content: (
<div className='flex flex-col gap-1.5'>
{lines.map((l) => (
<div key={l}>{l}</div>
))}
</div>
),
});
};
// 提交锁:拉取影响预览、等待二次确认期间 saving 尚未置位,连点会叠出多个确认框并重复提交
const submittingRef = useRef(false);
const handleSubmit = async () => {
if (!formApi || saving) return;
if (!formApi || submittingRef.current) return;
submittingRef.current = true;
try {
await submitForm();
} finally {
submittingRef.current = false;
}
};
const submitForm = async () => {
let values;
try {
values = await formApi.validate();
} catch {
return;
}
if (editing) {
if ((values.status || 1) !== (editing.status || 1)) {
if (!(await confirmStatus(editing.id, values.status))) return;
}
const oldParent = editing.parent_id || 0;
const newParent = values.parent_id || 0;
if (newParent !== oldParent) {
if (!(await confirmMove(editing.id, oldParent, newParent))) return;
}
}
setSaving(true);
try {
let res;
@@ -222,6 +365,11 @@ const OrgDepartments = ({ orgId }) => {
// 画布连线触发:把 childId 移到 parentId 之下(后端 MoveDepartmentTx 防环并级联 path)
const handleMove = useCallback(
async (childId, parentId) => {
const child = list.find((d) => d.id === childId);
if (!(await confirmMove(childId, child?.parent_id || 0, parentId))) {
fetchList(); // 画布已预演连线,取消后按服务端状态重绘
return;
}
try {
const res = await API.put(
`/api/org/dept/${childId}`,
@@ -239,7 +387,7 @@ const OrgDepartments = ({ orgId }) => {
fetchList();
}
},
[orgId, t, fetchList],
[orgId, t, fetchList, list, confirmMove],
);
return (
+30 -1
View File
@@ -41,7 +41,7 @@ import {
Spin,
Typography,
} from '@/components/ui';
import { Users, TrendingUp, FileClock } from 'lucide-react';
import { Users, TrendingUp, FileClock, Wallet } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import { renderQuota } from '../../helpers/render';
@@ -51,6 +51,7 @@ import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import { orgStatusColor } from './components/orgStatus';
import DeptFundsPanel from './fund/DeptFundsPanel';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
@@ -83,6 +84,11 @@ const isFeatureEnabled = (flags, key) => {
const OrgDeptManage = ({ orgId, featureFlags }) => {
const { t } = useTranslation();
const approvalEnabled = isFeatureEnabled(featureFlags, 'approval');
// 部门资金(MaaS V2.1.0 P0):同时开通 dept 与 budget 才展示(M-08)
const fundsEnabled =
isFeatureEnabled(featureFlags, 'dept') &&
isFeatureEnabled(featureFlags, 'budget');
const [fundsRefreshKey, setFundsRefreshKey] = useState(0);
const [departments, setDepartments] = useState([]);
const [deptId, setDeptId] = useState(null);
const [myMemberId, setMyMemberId] = useState(0);
@@ -327,6 +333,7 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
onClick={() => {
if (tab === 'members') fetchMembers();
else if (tab === 'usage') fetchUsage();
else if (tab === 'funds') setFundsRefreshKey((k) => k + 1);
else fetchRequests();
}}
>
@@ -477,6 +484,28 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
)}
</TabPane>
)}
{fundsEnabled && (
<TabPane
tab={
<span className='inline-flex items-center gap-1.5'>
<Wallet size={14} /> {t('部门资金')}
</span>
}
itemKey='funds'
>
{tab === 'funds' && (
<DeptFundsPanel
orgId={orgId}
deptId={deptId}
deptName={
departments.find((d) => d.id === deptId)?.name || ''
}
refreshKey={fundsRefreshKey}
/>
)}
</TabPane>
)}
</Tabs>
</OrgPanel>
)}
+51 -7
View File
@@ -46,6 +46,7 @@ import {
import OrgPageHeader from './components/OrgPageHeader';
import { OrgFilterCard, OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import { fundAccountDisplay, fundDeptDisplay } from './fund/fundFormat';
import OrgTaskRecords from './components/OrgTaskRecords';
import { useOrgLogsThemeStyle } from './components/useOrgLogsThemeStyle';
import {
@@ -113,6 +114,22 @@ const EXPORT_FIELDS = [
width: 16,
value: (r) => r.display_name || r.username || '',
},
// 部门资金归属快照(F-36):消费受理时固定,导出与列表同值
{
id: 'fundDept',
label: '归属部门',
width: 16,
value: (r, t) => fundDeptDisplay(t, r.fund_dept_id, r.fund_dept_name),
},
{
id: 'fundAccount',
label: '扣费账户',
width: 22,
value: (r, t) =>
r.fund_account_type === null || r.fund_account_type === undefined
? '—'
: fundAccountDisplay(t, r.fund_account_type, r.fund_dept_name),
},
{ id: 'model', label: '模型', width: 24, value: (r) => r.model_name || '' },
{
id: 'tokenName',
@@ -154,8 +171,8 @@ const EXPORT_FIELDS = [
];
// 将选中字段组装成一个 worksheet(含表头、列宽)
function buildWorksheet(XLSX, rows, fields, header) {
const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r)))];
function buildWorksheet(XLSX, rows, fields, header, t) {
const aoa = [header, ...rows.map((r) => fields.map((f) => f.value(r, t)))];
const ws = XLSX.utils.aoa_to_sheet(aoa);
ws['!cols'] = fields.map((f) => ({ wch: f.width || 14 }));
return ws;
@@ -376,10 +393,15 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
loadExportPrefs()?.mode === 'perUser' ? 'perUser' : 'summary',
);
const [exportFields, setExportFields] = useState(() => {
const saved = loadExportPrefs()?.fields;
const prefs = loadExportPrefs();
const saved = prefs?.fields;
const useSaved = Array.isArray(saved) && saved.length > 0;
// 保存偏好之后新增的字段(如归属部门/扣费账户)默认勾选;known 缺失的旧偏好只认识原有字段
const known = Array.isArray(prefs?.known) ? prefs.known : null;
const isNewField = (id) =>
known ? !known.includes(id) : id === 'fundDept' || id === 'fundAccount';
return EXPORT_FIELDS.reduce((acc, f) => {
acc[f.id] = useSaved ? saved.includes(f.id) : true;
acc[f.id] = useSaved ? saved.includes(f.id) || isNewField(f.id) : true;
return acc;
}, {});
});
@@ -392,7 +414,11 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
try {
localStorage.setItem(
EXPORT_PREFS_KEY,
JSON.stringify({ mode: exportMode, fields }),
JSON.stringify({
mode: exportMode,
fields,
known: EXPORT_FIELDS.map((f) => f.id),
}),
);
} catch {
// 忽略 localStorage 写入失败(隐私模式等)
@@ -531,7 +557,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
);
for (const { name, rows } of groups.values()) {
const ws = buildWorksheet(XLSX, rows, fields, header);
const ws = buildWorksheet(XLSX, rows, fields, header, t);
XLSX.utils.book_append_sheet(
wb,
ws,
@@ -540,7 +566,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
}
} else {
// 汇总:所有记录放在一个 sheet 页
const ws = buildWorksheet(XLSX, allLogs, fields, header);
const ws = buildWorksheet(XLSX, allLogs, fields, header, t);
XLSX.utils.book_append_sheet(
wb,
ws,
@@ -675,6 +701,24 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
align: 'right',
render: (v) => (v ? `${v}s` : '-'),
},
// 归属部门 / 扣费账户放在最后:不把消耗额度、耗时等核心列挤出可视区域
{
title: t('归属部门'),
dataIndex: 'fund_dept_name',
width: 120,
ellipsis: true,
render: (_, r) => fundDeptDisplay(t, r.fund_dept_id, r.fund_dept_name),
},
{
title: t('扣费账户'),
dataIndex: 'fund_account_type',
width: 150,
ellipsis: true,
render: (v, r) =>
v === null || v === undefined
? '—'
: fundAccountDisplay(t, v, r.fund_dept_name),
},
],
[t],
);
+11 -2
View File
@@ -385,7 +385,16 @@ const OrgMemberAccounts = ({
width: 260,
render: (_, r) => {
const managed = r.created_by_org_id === r.organization_id;
const canReset = managed || isSuperAdmin;
// 与后端 model.ResetManagedMemberPassword 的分级拦截保持一致
let resetBlockedReason = '';
if (!managed && !isSuperAdmin) {
resetBlockedReason = t('个人平台账号,请由本人通过找回密码修改');
} else if (r.role === 'owner' && !isSuperAdmin) {
resetBlockedReason = t('企业所有者的密码只能由本人修改');
} else if (r.role === 'admin' && !isSuperAdmin && orgRole !== 'owner') {
resetBlockedReason = t('仅企业所有者可重置企业管理员的密码');
}
const canReset = !resetBlockedReason;
return (
<OrgRowActions>
{deptEnabled && (
@@ -414,7 +423,7 @@ const OrgMemberAccounts = ({
<Button type='link'>{t('重置密码')}</Button>
</Popconfirm>
) : (
<Tooltip content={t('个人平台账号,请由本人通过找回密码修改')}>
<Tooltip content={resetBlockedReason}>
<Button type='link' disabled>
{t('重置密码')}
</Button>
+13 -1
View File
@@ -681,6 +681,8 @@ const OrgMembers = ({
agent_effect_view: !!perms.agent_effect_view,
agent_policy_manage: !!perms.agent_policy_manage,
quality_view: !!perms.quality_view,
smart_router_view: !!perms.smart_router_view,
smart_router_manage: !!perms.smart_router_manage,
});
setPermModalVisible(true);
}}
@@ -1054,6 +1056,8 @@ const OrgMembers = ({
['agent_effect_view', '查看 Agent 效能'],
['agent_policy_manage', '管理 Agent 安全策略'],
['quality_view', '查看调用质量'],
['smart_router_view', '查看智能路由'],
['smart_router_manage', '管理智能路由集合'],
].map(([key, label]) => (
<div
key={key}
@@ -1068,7 +1072,15 @@ const OrgMembers = ({
<Switch
checked={!!extraPerms[key]}
onChange={(checked) =>
setExtraPerms((old) => ({ ...old, [key]: checked }))
setExtraPerms((old) => {
const next = { ...old, [key]: checked };
// 管理智能路由隐含查看权限(列表与看板接口需要 smart_router_view)
if (key === 'smart_router_manage' && checked)
next.smart_router_view = true;
if (key === 'smart_router_view' && !checked)
next.smart_router_manage = false;
return next;
})
}
/>
</div>
+15 -2
View File
@@ -60,6 +60,7 @@ const OrgRecharge = ({ orgId }) => {
// 企业信息
const [orgQuota, setOrgQuota] = useState(0);
const [orgGiftQuota, setOrgGiftQuota] = useState(0);
const [orgUsedQuota, setOrgUsedQuota] = useState(0);
// 充值配置
@@ -149,8 +150,9 @@ const OrgRecharge = ({ orgId }) => {
try {
const res = await API.get('/api/org/quota', { headers: orgHeaders });
if (res.data.success) {
const { quota, used_quota } = res.data.data;
const { quota, gift_quota, used_quota } = res.data.data;
setOrgQuota(quota || 0);
setOrgGiftQuota(gift_quota || 0);
setOrgUsedQuota(used_quota || 0);
}
} catch (e) {
@@ -581,7 +583,18 @@ const OrgRecharge = ({ orgId }) => {
<div className='oc-rc-account'>
<div>
<span>{t('企业可用余额')}</span>
<strong className='oc-rc-balance'>{renderQuota(orgQuota)}</strong>
{/* 企业总剩余含赠送钱包,与预算中心「部门资金」口径一致 */}
<strong className='oc-rc-balance'>
{renderQuota(orgQuota + orgGiftQuota)}
</strong>
{orgGiftQuota > 0 && (
<span>
{t('主池 {{main}} · 赠送 {{gift}}', {
main: renderQuota(orgQuota),
gift: renderQuota(orgGiftQuota),
})}
</span>
)}
</div>
<div>
<span>{t('累计消耗')}</span>
+67 -2
View File
@@ -49,11 +49,13 @@ import {
Zap,
Check,
Activity,
Route as RouteIcon,
} from 'lucide-react';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { StatusContext } from '../../context/Status';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
import { canAccessOrgSettings } from './orgFeatureFlags';
import OrgCommissionNavigation from './OrgCommissionNavigation';
import {
isMiniProgramPaymentPath,
isMiniProgramWebView,
@@ -73,6 +75,7 @@ const pathFeatureRequirements = {
'/org/connectors': 'connector',
'/org/effectiveness': 'agent_effectiveness',
'/org/quality': 'quality_monitor',
'/org/smart-router': 'smart_router',
'/org/departments': 'dept',
'/org/projects': 'project',
'/org/budgets': 'budget',
@@ -88,6 +91,9 @@ const isFeatureEnabled = (flags, key) => {
const OrgSidebar = ({
orgName,
organizations = [],
currentOrgId,
onOrganizationChange,
orgRole,
featureFlags,
isDeptManager = false,
@@ -100,6 +106,9 @@ const OrgSidebar = ({
canAuditAgentMetadata = false,
canViewAgentEffect = false,
canViewQuality = false,
canViewCommission = false,
canViewSmartRouter = false,
smartRouterConsentOnly = false,
isMemberActor = true,
onNavigate,
mobile = false,
@@ -231,6 +240,14 @@ const OrgSidebar = ({
adminOnly: true,
qualityView: true,
},
{
itemKey: '/org/smart-router',
text: t('智能路由'),
icon: RouteIcon,
group: 'overview',
adminOnly: true,
smartRouterView: true,
},
{
itemKey: '/org/agent-audit',
text: t('Agent 任务审计'),
@@ -306,6 +323,13 @@ const OrgSidebar = ({
group: 'records',
adminOnly: true,
},
{
itemKey: '/org/commission',
text: t('企业分佣'),
icon: Wallet,
group: 'records',
commissionAccess: true,
},
{
itemKey: '/org/logs',
text: isAdmin || isDeptManager ? t('消耗明细') : t('我的消耗明细'),
@@ -344,6 +368,7 @@ const OrgSidebar = ({
'/org/connectors': 'connectors',
'/org/effectiveness': 'effectiveness',
'/org/quality': 'quality',
'/org/smart-router': 'smartRouter',
'/org/dashboard': 'dashboard',
'/org/members': 'members',
'/org/departments': 'departments',
@@ -356,6 +381,7 @@ const OrgSidebar = ({
'/org/logs': 'logs',
'/org/audit': 'audit',
'/org/recharge': 'recharge',
'/org/commission': 'commission',
'/org/settings': 'settings',
};
@@ -390,6 +416,11 @@ const OrgSidebar = ({
if (item.agentAudit && !canAuditAgentMetadata) return false;
if (item.effectView && !canViewAgentEffect) return false;
if (item.qualityView && !canViewQuality) return false;
if (item.commissionAccess && !canViewCommission) return false;
// 仅授权模式:功能已关闭但所有者仍有生效中的出境同意,入口保留以便撤回(与路由守卫同口径)
if (item.itemKey === '/org/smart-router' && smartRouterConsentOnly)
return true;
if (item.smartRouterView && !canViewSmartRouter) return false;
if (item.connectorManage && !canManageConnectors) return false;
// 与路由守卫一致:管理员只有 data_security 授权后才显示设置入口。
if (item.ownerOnly && !canManageSettings) return false;
@@ -440,6 +471,9 @@ const OrgSidebar = ({
canAuditAgentMetadata,
canViewAgentEffect,
canViewQuality,
canViewCommission,
canViewSmartRouter,
smartRouterConsentOnly,
isMemberActor,
canManageConnectors,
orgConfig,
@@ -505,13 +539,13 @@ const OrgSidebar = ({
setFoldedGroups((prev) =>
prev.includes(activeGroup) ? prev.filter((k) => k !== activeGroup) : prev,
);
}, [selectedKey, groupedItems]);
}, [selectedKey, groupedItems, location.key]);
// 选中项滚入可视区(分组较多时避免高亮项被折叠区/滚动区遮住)
useEffect(() => {
const el = navRef.current?.querySelector('[data-active="true"]');
el?.scrollIntoView({ block: 'nearest' });
}, [selectedKey]);
}, [selectedKey, location.search]);
return (
<aside
@@ -528,6 +562,25 @@ const OrgSidebar = ({
</span>
{orgRole && <span className='ui-org-role'>{roleLabel}</span>}
</div>
{organizations.length > 1 && (
<select
aria-label={t('切换企业')}
className='mt-3 w-full rounded-md border border-[var(--border-subtle)] bg-[var(--surface-card)] px-2 py-1 text-sm'
value={currentOrgId}
onChange={(event) =>
onOrganizationChange?.(Number(event.target.value))
}
>
{!organizations.some((org) => org.id === currentOrgId) && (
<option value={currentOrgId}>{orgName}</option>
)}
{organizations.map((org) => (
<option key={org.id} value={org.id}>
{org.name}
</option>
))}
</select>
)}
</div>
)}
<nav ref={navRef} className='ui-center-sidebar-nav'>
@@ -552,6 +605,18 @@ const OrgSidebar = ({
)}
<div className='ui-org-group-items' hidden={folded && !collapsed}>
{group.items.map((item) => {
// 企业分佣二级导航(weiyuan eb3936cf0);企业侧栏无菜单搜索,query 恒为空
if (item.commissionAccess)
return (
<OrgCommissionNavigation
key={item.itemKey}
collapsed={collapsed}
expandSidebar={toggleCollapsed}
query=''
renderText={(text) => text}
onNavigate={onNavigate}
/>
);
const isSelected = selectedKey === item.itemKey;
const IconComponent = item.icon;
return (
+94
View File
@@ -0,0 +1,94 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Tabs as AntTabs } from 'antd';
import ProfileTable from '../../components/smart-router/ProfileTable';
import ConsentPanel from '../../components/smart-router/ConsentPanel';
import DecisionTable from '../../components/smart-router/DecisionTable';
import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard } from './components/OrgListCard';
import '../../components/smart-router/smart-router.css';
// 企业中心 · 智能路由(嵌在企业中心布局内,背景与顶部让位由企业中心处理)
// consentOnly:平台已关闭本企业的智能路由,但仍有生效中的出境同意——只展示授权页签供所有者撤回
const OrgSmartRouter = ({
orgId,
canManage,
isOwner,
consentOnly = false,
onConsentChange,
}) => {
const { t } = useTranslation();
const [tab, setTab] = useState(consentOnly ? 'consent' : 'profiles');
const tabItems = [
...(!consentOnly ? [{ key: 'profiles', label: t('企业集合') }] : []),
{ key: 'consent', label: t('数据出境授权') },
...(!consentOnly ? [{ key: 'decisions', label: t('判定明细') }] : []),
];
return (
<div className='uc-page oc-page smart-router-scope'>
<OrgPageHeader
title={t('智能路由')}
subtitle={t(
'企业集合只对本企业令牌生效。候选模型同样受作用域模型白名单约束:使用作用域白名单时,需同时加入 router/ 虚拟名与它的候选模型,否则判定时候选会被过滤。',
)}
/>
{consentOnly && (
<Alert
className='smart-router-alert'
type='warning'
showIcon
title={t(
'平台已关闭本企业的智能路由。之前授予的数据出境同意仍然有效,功能重新开启后会自动生效;如不再需要,请在此撤回。',
)}
/>
)}
{/* 只切换下方内容:保持原“仅渲染当前页签”的挂载与请求时机 */}
<AntTabs
className='oc-list-tabs oc-tabs-nav-only'
activeKey={tab}
onChange={setTab}
items={tabItems}
/>
<OrgListCard>
{tab === 'profiles' && (
<ProfileTable
mode='org'
orgId={orgId}
canWrite={canManage}
emptyHint={t('与平台集合同名时,本企业令牌优先使用企业集合。')}
/>
)}
{tab === 'consent' && (
<ConsentPanel
mode='org'
orgId={orgId}
canWrite={isOwner}
onChange={onConsentChange}
/>
)}
{tab === 'decisions' && <DecisionTable mode='org' orgId={orgId} />}
</OrgListCard>
</div>
);
};
export default OrgSmartRouter;
+458 -121
View File
@@ -21,10 +21,10 @@ import {
EyeOff as ActionEyeOff,
Eye as ActionEye,
Copy as ActionCopy,
Check as ActionCheck,
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
} from '@/components/common/icons/ActionIcons';
import { writeClipboardText } from '../../helpers/clipboard';
import TableEmpty from '../../components/common/table/TableEmpty';
import React, {
useEffect,
@@ -50,13 +50,15 @@ import {
TextArea,
} from '@/components/ui';
import { useOrgTokens } from '../../hooks/org/useOrgData';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import {
API,
copy,
showError,
getModelCategories,
selectFilter,
} from '../../helpers';
import { renderQuota } from '../../helpers/render';
import { renderGroup, renderQuota } from '../../helpers/render';
import QuotaInput from '../../components/common/ui/QuotaInput';
import OrgPageHeader from './components/OrgPageHeader';
import {
@@ -64,13 +66,58 @@ import {
Button as AntButton,
Collapse,
Divider,
Empty as AntEmpty,
Form as AntForm,
Radio,
Typography as AntTypography,
} from 'antd';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import OrgSideSheet from './components/OrgSideSheet';
import TableColumnSettings from '../../components/common/table/ColumnSettings';
// 复制到剪贴板:走公共 copy(HTTP 部署下 navigator.clipboard 为 undefined,
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到——这正是复制按钮"没反应"的原因)。
const copyText = async (text, t, successMsg) => {
if (await copy(text)) {
Toast.success(successMsg || t('已复制到剪贴板'));
return true;
}
Toast.error(t('复制失败,请手动复制'));
return false;
};
// 企业令牌分组:空串表示未显式指定,调用时按成员/项目的作用域默认分组解析
const renderOrgTokenGroup = (group, t) => {
if (!group) {
return (
<Tag color='default' bordered={false}>
{t('默认分组')}
</Tag>
);
}
if (group === 'auto') {
return (
<Tag color='purple' bordered={false}>
{t('智能熔断')}
</Tag>
);
}
return renderGroup(group);
};
// 后端状态位是惰性更新的(调用时才翻成过期/用尽),列表里可能出现
// status=1 但实际已不可用的令牌;这里按过期时间/剩余额度算出真实问题。
const getTokenProblem = (token) => {
// 与网关 validateUserToken 同口径:只有 -1 表示永不过期(0 等历史脏数据视为已过期)
if (token.expired_time !== -1 && token.expired_time * 1000 <= Date.now()) {
return 'expired';
}
if (!token.unlimited_quota && (token.remain_quota || 0) <= 0) {
return 'exhausted';
}
return null;
};
// 获取当前登录用户ID
const getCurrentUserId = () => {
try {
@@ -82,17 +129,23 @@ const getCurrentUserId = () => {
};
const OrgTokens = ({ orgId, orgRole }) => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const {
tokens,
total,
loading,
error,
fetch,
createToken,
deleteToken,
updateToken,
getTokenEditOptions,
fetchTokenKey,
} = useOrgTokens(orgId);
const [page, setPage] = useState(1);
// 窄屏下两侧固定列(名称+操作≈400px)会占满可视宽度,中间列无处可显示,故仅桌面端固定
const isMobile = useIsMobile();
const fixedSide = (side) => (isMobile ? undefined : side);
const [pageSize, setPageSize] = useState(20);
const [visibleColumns, setVisibleColumns] = useState([
'name',
@@ -101,12 +154,16 @@ const OrgTokens = ({ orgId, orgRole }) => {
'models',
'status',
'used_quota',
'expired_time',
'creator_name',
'created_time',
'actions',
]);
const [createModalVisible, setCreateModalVisible] = useState(false);
const [showKeys, setShowKeys] = useState({});
// 列表只有脱敏密钥;点"显示"后按需取回的完整密钥按令牌 ID 暂存,列表刷新即清空
const [revealedKeys, setRevealedKeys] = useState({});
const [keyLoadingId, setKeyLoadingId] = useState(null);
useEffect(() => setRevealedKeys({}), [tokens]);
const [modelsSheetVisible, setModelsSheetVisible] = useState(false);
const [selectedToken, setSelectedToken] = useState(null);
const [editModalVisible, setEditModalVisible] = useState(false);
@@ -148,36 +205,82 @@ const OrgTokens = ({ orgId, orgRole }) => {
const ok = await deleteToken(tokenId);
if (ok) {
Toast.success(t('密钥已删除'));
fetch(page, pageSize);
// 删掉的是当前页最后一条时回退一页,否则会停在空页上误显示"暂无令牌"
if (tokens.length === 1 && page > 1) {
setPage(page - 1);
} else {
fetch(page, pageSize);
}
}
},
[deleteToken, fetch, page, pageSize, t],
[deleteToken, fetch, page, pageSize, t, tokens.length],
);
const handleStatusToggle = useCallback(
async (tokenId, currentStatus) => {
const newStatus = currentStatus === 1 ? 2 : 1;
const ok = await updateToken(tokenId, { status: newStatus });
if (ok) {
Toast.success(t('状态已更新'));
fetch(page, pageSize);
}
},
[updateToken, fetch, page, pageSize, t],
);
const copyToClipboard = (text) => {
writeClipboardText(text)
.then(() => {
Toast.success(t('已复制到剪贴板'));
})
.catch(() => {
Toast.error(t('复制失败,请手动复制'));
});
// 从"启用"按钮被拦截跳来编辑时,用户的意图是启用:保存修复后一并启用
// (否则手动禁用过的令牌改完过期时间仍是禁用,用户却以为已经可用)。
const [enableAfterSave, setEnableAfterSave] = useState(false);
const openEdit = (token, enableAfter = false) => {
setEditingToken(token);
setEnableAfterSave(enableAfter);
setEditModalVisible(true);
};
const toggleShowKey = (tokenId) => {
setShowKeys((prev) => ({ ...prev, [tokenId]: !prev[tokenId] }));
// 正在切换状态的令牌,防连点重复提交
const [togglingId, setTogglingId] = useState(null);
const handleStatusToggle = async (record) => {
const enabling = record.status !== 1;
// 已过期/已用尽的令牌直接启用会被网关立刻再次判为不可用,
// 后端却照样返回成功——先引导用户去改过期时间或额度。
const problem = enabling ? getTokenProblem(record) : null;
if (problem) {
Toast.warning(
problem === 'expired'
? t('令牌已过期,请先修改过期时间')
: t('令牌额度已用尽,请先调整额度'),
);
openEdit(record, true);
return;
}
setTogglingId(record.id);
const ok = await updateToken(record.id, { status: enabling ? 1 : 2 });
// 只清自己:并发点了别的行时不能把那一行的 loading 一起清掉
setTogglingId((cur) => (cur === record.id ? null : cur));
if (ok) {
Toast.success(t('状态已更新'));
fetch(page, pageSize);
}
};
const [copiedId, setCopiedId] = useState(null);
const copiedTimer = useRef(null);
useEffect(() => () => clearTimeout(copiedTimer.current), []);
const loadFullKey = async (tokenId) => {
if (revealedKeys[tokenId]) return revealedKeys[tokenId];
setKeyLoadingId(tokenId);
const fullKey = await fetchTokenKey(tokenId);
setKeyLoadingId((cur) => (cur === tokenId ? null : cur));
return fullKey;
};
const handleCopyKey = async (tokenId) => {
const fullKey = await loadFullKey(tokenId);
if (fullKey && (await copyText(fullKey, t))) {
setCopiedId(tokenId);
clearTimeout(copiedTimer.current);
copiedTimer.current = setTimeout(() => setCopiedId(null), 1500);
}
};
const toggleShowKey = async (tokenId) => {
if (revealedKeys[tokenId]) {
setRevealedKeys(({ [tokenId]: _, ...rest }) => rest);
return;
}
const fullKey = await loadFullKey(tokenId);
if (fullKey) {
setRevealedKeys((prev) => ({ ...prev, [tokenId]: fullKey }));
}
};
const handleViewModels = (token) => {
@@ -203,6 +306,8 @@ const OrgTokens = ({ orgId, orgRole }) => {
key: 'name',
dataIndex: 'name',
width: 230,
// 列数较多,常规桌面宽度也会横向滚动:名称与操作列固定在两侧,滚动时始终可见
fixed: fixedSide('left'),
ellipsis: { showTitle: false },
render: (name, record) => (
<Tooltip content={name} position='topLeft'>
@@ -228,12 +333,14 @@ const OrgTokens = ({ orgId, orgRole }) => {
dataIndex: 'key',
width: 335,
render: (key, record) => {
const fullKey = 'sk-' + (key || '');
const isVisible = showKeys[record.id];
// key 为后端脱敏值(前 4 + **** + 后 4)
const fullKey = revealedKeys[record.id];
const isVisible = !!fullKey;
const keyBusy = keyLoadingId === record.id;
const displayKey = key
? isVisible
? fullKey
: `sk-${key.substring(0, 4)}${'•'.repeat(8)}${key.substring(key.length - 4)}`
: `sk-${key.replace(/\*/g, '•')}`
: '-';
return (
<div className='oc-secret'>
@@ -253,6 +360,7 @@ const OrgTokens = ({ orgId, orgRole }) => {
)
}
onClick={() => toggleShowKey(record.id)}
disabled={keyBusy}
/>
</Tooltip>
<Tooltip content={t('复制密钥')}>
@@ -261,8 +369,15 @@ const OrgTokens = ({ orgId, orgRole }) => {
type='text'
size='small'
aria-label={t('复制密钥')}
icon={<ActionCopy size={16} />}
onClick={() => copyToClipboard(fullKey)}
icon={
copiedId === record.id ? (
<ActionCheck size={16} />
) : (
<ActionCopy size={16} />
)
}
disabled={keyBusy}
onClick={() => handleCopyKey(record.id)}
/>
</Tooltip>
</>
@@ -277,7 +392,8 @@ const OrgTokens = ({ orgId, orgRole }) => {
dataIndex: 'group',
width: 150,
render: (group) => {
const label = group === 'auto' ? t('智能熔断') : group || '-';
// 空串表示未显式指定,调用时按成员/项目作用域默认分组解析(weiyuan 8d9caa881)
const label = group === 'auto' ? t('智能熔断') : group || t('默认分组');
return (
<Tooltip content={label}>
<span className='oc-token-group'>{label}</span>
@@ -308,34 +424,86 @@ const OrgTokens = ({ orgId, orgRole }) => {
key: 'status',
dataIndex: 'status',
width: 110,
render: (status, record) => (
<div className='oc-token-status'>
<Switch
size='small'
checked={status === 1}
checkedText={t('启用')}
uncheckedText={t('禁用')}
disabled={!canOperateRow(record)}
aria-label={`${record.name || ''}${t('启用状态')}`}
onChange={() => handleStatusToggle(record.id, record.status)}
/>
{status !== 1 && status !== 2 && (
<Tag color='grey' bordered={false}>
{t('已用尽')}
</Tag>
)}
</div>
),
// 与 common.TokenStatus* 对齐:1 启用 / 2 禁用 / 3 过期 / 4 用尽
render: (rawStatus, record) => {
const problem = rawStatus === 1 ? getTokenProblem(record) : null;
const status =
problem === 'expired' ? 3 : problem === 'exhausted' ? 4 : rawStatus;
const problemMeta = {
3: { color: 'warning', label: t('已过期') },
4: { color: 'grey', label: t('已用尽') },
}[status];
return (
<div className='oc-token-status'>
<Switch
size='small'
checked={rawStatus === 1}
checkedText={t('启用')}
uncheckedText={t('禁用')}
loading={togglingId === record.id}
disabled={!canOperateRow(record)}
aria-label={`${record.name || ''}${t('启用状态')}`}
onChange={() => handleStatusToggle(record)}
/>
{problemMeta && (
<Tag color={problemMeta.color} bordered={false}>
{problemMeta.label}
</Tag>
)}
</div>
);
},
},
{
title: t('已用额度'),
key: 'used_quota',
dataIndex: 'used_quota',
width: 115,
render: (v) => (
<span className='oc-number'>{renderQuota(v || 0, 2)}</span>
width: 120,
render: (v, record) => (
<div>
<span className='oc-number'>{renderQuota(v || 0, 2)}</span>
<AntTypography.Text
type='secondary'
style={{ display: 'block', fontSize: 12, lineHeight: '18px' }}
>
{record.unlimited_quota
? t('无限额度')
: `${t('剩余')} ${renderQuota(record.remain_quota || 0, 2)}`}
</AntTypography.Text>
</div>
),
},
{
title: t('过期时间'),
key: 'expired_time',
dataIndex: 'expired_time',
width: 110,
render: (v) => {
if (v === -1 || v == null) {
return (
<AntTypography.Text type='secondary'>
{t('永不过期')}
</AntTypography.Text>
);
}
const date = new Date(v * 1000);
const expired = date.getTime() <= Date.now();
return (
<Tooltip content={date.toLocaleString(i18n.language)}>
<AntTypography.Text
className='oc-number'
type={expired ? 'danger' : 'secondary'}
>
{date.toLocaleDateString(i18n.language, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})}
</AntTypography.Text>
</Tooltip>
);
},
},
// 管理员可见:创建者列
...(isAdmin
? [
@@ -359,18 +527,13 @@ const OrgTokens = ({ orgId, orgRole }) => {
title: t('操作'),
key: 'actions',
width: 90,
fixed: fixedSide('right'),
render: (_, record) => {
// 管理员/超管可操作所有Token,普通成员只能操作自己创建的。
if (!canOperateRow(record)) return '-';
return (
<OrgRowActions>
<Button
type='link'
onClick={() => {
setEditingToken(record);
setEditModalVisible(true);
}}
>
<Button type='link' onClick={() => openEdit(record)}>
{t('编辑')}
</Button>
<Popconfirm
@@ -451,7 +614,37 @@ const OrgTokens = ({ orgId, orgRole }) => {
scroll={{
x: tableColumns.reduce((sum, column) => sum + column.width, 0),
}}
empty={<TableEmpty />}
empty={
// 加载失败时给错误态+重试,不能误显示"暂无数据"并引导去创建
error ? (
<AntEmpty
image={AntEmpty.PRESENTED_IMAGE_SIMPLE}
description={typeof error === 'string' ? error : t('加载失败')}
>
<Button
icon={<ActionRefreshCw size={16} />}
onClick={() => fetch(page, pageSize)}
>
{t('重试')}
</Button>
</AntEmpty>
) : canCreate && !loading ? (
<AntEmpty
image={AntEmpty.PRESENTED_IMAGE_SIMPLE}
description={t('创建第一个令牌,即可通过 API 调用企业可用模型')}
>
<Button
type='primary'
icon={<ActionPlus size={16} />}
onClick={() => setCreateModalVisible(true)}
>
{t('创建密钥')}
</Button>
</AntEmpty>
) : (
<TableEmpty />
)
}
pagination={{
currentPage: page,
pageSize,
@@ -484,7 +677,9 @@ const OrgTokens = ({ orgId, orgRole }) => {
setEditingToken(null);
}}
token={editingToken}
enableAfterSave={enableAfterSave}
updateToken={updateToken}
getTokenEditOptions={getTokenEditOptions}
projects={projects}
orgId={orgId}
// 前端按角色粗判以决定是否展示控件;真正的授权判定在后端
@@ -686,6 +881,7 @@ const CreateTokenModal = ({
}) => {
const [step, setStep] = useState('form'); // 'form' | 'success'
const [newKey, setNewKey] = useState('');
const [createdGroup, setCreatedGroup] = useState('');
const [loading, setLoading] = useState(false);
const [name, setName] = useState('');
const [neverExpire, setNeverExpire] = useState(true);
@@ -843,16 +1039,6 @@ const CreateTokenModal = ({
setExpiredTime(...EXPIRY_PRESETS.find((p) => p.key === key).args);
};
const copyKey = (key) => {
writeClipboardText(key)
.then(() => {
Toast.success(t('已复制到剪贴板'));
})
.catch(() => {
Toast.error(t('复制失败,请手动复制'));
});
};
const handleCreate = async () => {
if (!name.trim()) {
Toast.warning(t('请输入密钥名称'));
@@ -885,6 +1071,8 @@ const CreateTokenModal = ({
setLoading(false);
if (result) {
setNewKey(result.key);
// 以后端实际落库的分组为准(前端预选可能为空,后端会解析出作用域默认分组)
setCreatedGroup(result.group ?? group);
setStep('success');
onSuccess?.();
}
@@ -937,11 +1125,15 @@ const CreateTokenModal = ({
size='small'
theme='light'
icon={<ActionCopy size={14} />}
onClick={() => copyKey(newKey)}
onClick={() => copyText(newKey, t)}
>
{t('复制')}
</Button>
</div>
<div className='flex items-center text-sm text-gray-500 dark:text-gray-400'>
<span className='mr-2'>{t('分组')}:</span>
{renderOrgTokenGroup(createdGroup, t)}
</div>
</div>
) : (
<OrgKeyForm
@@ -952,24 +1144,29 @@ const CreateTokenModal = ({
projectId={projectId}
setProjectId={setProjectId}
groupField={
/* 分组选择:有多个可用分组,或当前预选分组(如被等级隐藏的默认分组)
不在可选列表内时展示——否则唯一可见分组会因选择器缺席而无法选中 */
(usableGroups.length > 1 ||
(usableGroups.length > 0 &&
group &&
!usableGroups.includes(group))) && (
/* 分组:有多个可用分组,或当前预选分组(如被等级隐藏的默认分组)
不在可选列表内时给选择器——否则唯一可见分组会因选择器缺席而无法选中;
只有一个分组时只读展示,让用户在创建时就知道密钥归属哪个分组 */
(usableGroups.length > 0 || group) && (
<AntForm.Item
label={t('密钥分组')}
extra={t('决定计费倍率与可用模型')}
>
<Select
value={group}
onChange={setGroup}
optionList={usableGroups}
placeholder={t('选择分组')}
filter={selectFilter}
style={{ width: '100%' }}
/>
{usableGroups.length > 1 ||
(usableGroups.length > 0 &&
group &&
!usableGroups.some((g) => g.value === group)) ? (
<Select
value={group}
onChange={setGroup}
optionList={usableGroups}
placeholder={t('选择分组')}
filter={selectFilter}
style={{ width: '100%' }}
/>
) : (
renderOrgTokenGroup(group, t)
)}
</AntForm.Item>
)
}
@@ -998,7 +1195,9 @@ const EditTokenModal = ({
visible,
onClose,
token,
enableAfterSave = false,
updateToken,
getTokenEditOptions,
projects = [],
orgId,
canBindSkills = false,
@@ -1017,6 +1216,13 @@ const EditTokenModal = ({
const [orgModels, setOrgModels] = useState([]);
const [loadingModels, setLoadingModels] = useState(false);
const fetchModelsSeq = useRef(0);
const [group, setGroup] = useState('');
const [usableGroups, setUsableGroups] = useState([]);
const [groupsLoaded, setGroupsLoaded] = useState(false);
const [groupLoadError, setGroupLoadError] = useState(false);
const selectedModelsRef = useRef([]);
const modelContextRef = useRef(null);
const initialGroupRef = useRef('');
// 技能注入(方案 §3.1/§3.3)。企业密钥的候选集是**企业已启用集**,
// 不是平台全量——后端解析层还会再收窄一次,这里只是不给出会被静默丢弃的选项。
const [skillInjectionEnabled, setSkillInjectionEnabled] = useState(false);
@@ -1043,10 +1249,19 @@ const EditTokenModal = ({
setRemainQuota(token.remain_quota || null);
setAllowIps(token.allow_ips || '');
setProjectId(token.project_id || 0);
setGroup(token.group || '');
initialGroupRef.current = token.group || '';
setUsableGroups([]);
setGroupsLoaded(false);
setGroupLoadError(false);
modelContextRef.current = null;
if (token.model_limits_enabled && token.model_limits) {
setSelectedModels(token.model_limits.split(',').filter(Boolean));
const limits = token.model_limits.split(',').filter(Boolean);
setSelectedModels(limits);
selectedModelsRef.current = limits;
} else {
setSelectedModels([]);
selectedModelsRef.current = [];
}
setSkillInjectionEnabled(!!token.skill_injection_enabled);
// skill_ids 落库形态是 JSON 数组文本;解析失败退化为空数组
@@ -1059,6 +1274,55 @@ const EditTokenModal = ({
}
}, [visible, token]);
useEffect(() => {
if (!visible || !token) return;
setGroupsLoaded(false);
let cancelled = false;
(async () => {
try {
const data = await getTokenEditOptions(token.id, projectId);
if (cancelled) return;
if (data) {
const groups = data.groups || [];
const defaultGroup = data.default_group || '';
const options = groups.map((value) => ({ label: value, value }));
// 保留当前令牌分组,避免因等级/作用域变化导致 Select 无法展示当前值;
// 保存时仍由后端按令牌所属成员的最终作用域做权威校验。
const currentGroup = data.token?.current_group || token.group || '';
if (
currentGroup &&
!options.some((item) => item.value === currentGroup)
) {
options.unshift({
label: `${currentGroup}(${t('当前不可用')})`,
value: currentGroup,
disabled: true,
});
}
setUsableGroups(options);
setGroupLoadError(false);
setGroup((current) => {
if (current && options.some((item) => item.value === current)) {
return current;
}
return defaultGroup || options[0]?.value || '';
});
} else {
setGroupLoadError(true);
}
} catch {
// 编辑选项接口失败时保留令牌原分组,保存仍由后端校验。
if (!cancelled) setGroupLoadError(true);
} finally {
if (!cancelled) setGroupsLoaded(true);
}
})();
return () => {
cancelled = true;
fetchModelsSeq.current += 1;
};
}, [visible, token, projectId, getTokenEditOptions, t]);
useEffect(() => {
if (!visible || !canBindSkills || !orgId) return;
let cancelled = false;
@@ -1102,10 +1366,12 @@ const EditTokenModal = ({
const seq = ++fetchModelsSeq.current;
setLoadingModels(true);
try {
const params = { token_id: token.id };
if (token.group) params.group = token.group;
if (projectId) params.project_id = projectId;
const res = await API.get('/api/org/my-models', { params });
const params = { token_id: token.id, project_id: projectId };
if (group) params.group = group;
const res = await API.get('/api/org/my-models', {
params,
headers: { 'X-Org-Id': String(orgId) },
});
if (seq !== fetchModelsSeq.current) return;
if (res.data.success) {
const categories = getModelCategories(t);
@@ -1134,20 +1400,31 @@ const EditTokenModal = ({
};
});
setOrgModels(options);
setSelectedModels((prev) => prev.filter((m) => allowed.has(m)));
const previous = selectedModelsRef.current;
const next = previous.filter((m) => allowed.has(m));
const removed = previous.filter((m) => !allowed.has(m));
const contextKey = `${group}|${projectId}`;
if (removed.length > 0 && modelContextRef.current !== null) {
Toast.warning(
t('以下模型在新分组下不可用,已自动移除:{{models}}', {
models: removed.join(', '),
}),
);
}
modelContextRef.current = contextKey;
selectedModelsRef.current = next;
setSelectedModels(next);
}
} catch {}
if (seq === fetchModelsSeq.current) {
setLoadingModels(false);
}
}, [visible, token, projectId, t]);
}, [visible, token, projectId, group, orgId, t]);
useEffect(() => {
if (!visible || !groupsLoaded) return;
fetchModels();
return () => {
fetchModelsSeq.current += 1;
};
}, [fetchModels]);
}, [visible, groupsLoaded, group, projectId, fetchModels]);
const setExpiredTime = (month, day, hour, minute) => {
if (month === 0 && day === 0 && hour === 0 && minute === 0) {
@@ -1198,16 +1475,35 @@ const EditTokenModal = ({
Toast.warning(t('请输入有效的额度'));
return;
}
if (groupLoadError && group !== initialGroupRef.current) {
Toast.warning(t('分组加载失败,请刷新后重试'));
return;
}
const nextExpiredTime = neverExpire
? -1
: Math.ceil(expireDate.getTime() / 1000);
const nextRemainQuota = unlimitedQuota ? 0 : parseInt(remainQuota);
// 因过期/用尽而失效的令牌,本次修改已消除原因时顺带恢复启用;
// 被手动禁用(status=2)的默认不动,尊重禁用意图——除非用户是点"启用"被引导来的。
const recovered =
token.status !== 1 &&
(token.status === 3 || token.status === 4 || enableAfterSave) &&
!getTokenProblem({
expired_time: nextExpiredTime,
unlimited_quota: unlimitedQuota,
remain_quota: nextRemainQuota,
});
setLoading(true);
const ok = await updateToken(token.id, {
name: name.trim(),
expired_time: neverExpire ? -1 : Math.ceil(expireDate.getTime() / 1000),
expired_time: nextExpiredTime,
unlimited_quota: unlimitedQuota,
remain_quota: unlimitedQuota ? 0 : parseInt(remainQuota),
remain_quota: nextRemainQuota,
model_limits: selectedModels.join(','),
model_limits_enabled: selectedModels.length > 0,
allow_ips: allowIps ?? '',
project_id: projectId || 0,
group: group || '',
// 无绑定权限时不提交这两个字段:后端按指针语义判定"本次不动",
// 避免普通成员保存一次名字就把管理员配好的注入设置清掉。
...(canBindSkills
@@ -1217,9 +1513,19 @@ const EditTokenModal = ({
}
: {}),
});
// 启用单独提交:启用会受企业令牌数上限(MaxTokens)约束,和修改合并提交时
// 一旦超限会连同本次修改整体被拒;分开后修改照常保存,启用失败由 hook 弹出原因。
if (ok && recovered) {
await updateToken(token.id, { status: 1 });
}
setLoading(false);
if (ok) {
Toast.success(t('密钥已更新'));
// 后端在原分组对该成员已不可用(或为空)时会回落到作用域默认分组,
// 计费倍率随之变化,必须明确告知而不是静默改掉。
if (typeof ok === 'object' && (ok.group || '') !== (token.group || '')) {
Toast.info(t('令牌分组已调整为 {{group}}', { group: ok.group }));
}
onSuccess?.();
onClose();
}
@@ -1235,7 +1541,12 @@ const EditTokenModal = ({
footer={
<div className='oc-drawer-footer'>
<Button onClick={onClose}>{t('取消')}</Button>
<Button type='primary' loading={loading} onClick={handleSave}>
<Button
type='primary'
loading={loading}
disabled={groupLoadError && group !== initialGroupRef.current}
onClick={handleSave}
>
{t('保存')}
</Button>
</div>
@@ -1248,6 +1559,27 @@ const EditTokenModal = ({
projects={projects}
projectId={projectId}
setProjectId={setProjectId}
groupField={
/* 分组切换会重新加载可用模型,后端保存时还会按令牌所属成员的作用域复核。 */
<AntForm.Item
label={t('密钥分组')}
extra={t('决定计费倍率与可用模型')}
>
{usableGroups.length > 0 ? (
<Select
value={group}
onChange={setGroup}
optionList={usableGroups}
loading={!groupsLoaded}
placeholder={t('选择分组')}
filter={selectFilter}
style={{ width: '100%' }}
/>
) : (
renderOrgTokenGroup(group || token?.group, t)
)}
</AntForm.Item>
}
expiryPreset={expiryPreset}
onExpiryChange={handleExpiryChange}
expireDate={expireDate}
@@ -1257,7 +1589,10 @@ const EditTokenModal = ({
remainQuota={remainQuota}
setRemainQuota={setRemainQuota}
selectedModels={selectedModels}
setSelectedModels={setSelectedModels}
setSelectedModels={(values) => {
selectedModelsRef.current = values;
setSelectedModels(values);
}}
orgModels={orgModels}
loadingModels={loadingModels}
allowIps={allowIps}
@@ -1307,18 +1642,24 @@ const ModelsSideSheet = ({ visible, onClose, token, orgId, t }) => {
const [models, setModels] = useState([]);
const [loading, setLoading] = useState(false);
const [copiedModel, setCopiedModel] = useState(null);
const copiedModelTimer = useRef(null);
useEffect(() => () => clearTimeout(copiedModelTimer.current), []);
const categories = getModelCategories(t);
useEffect(() => {
if (!visible || !token) return;
// 快速切换令牌时丢弃旧请求的响应,避免 A 的结果覆盖 B 的列表
let cancelled = false;
const loadModels = async () => {
setLoading(true);
setModels([]);
try {
const params = { token_id: token.id };
if (token.group) params.group = token.group;
if (token.project_id) params.project_id = token.project_id;
const res = await API.get('/api/org/my-models', { params });
if (cancelled) return;
if (!res.data.success) {
showError(res.data.message);
setLoading(false);
@@ -1334,12 +1675,16 @@ const ModelsSideSheet = ({ visible, onClose, token, orgId, t }) => {
setModels(scopedModels);
}
} catch (error) {
if (cancelled) return;
showError(error.message);
}
setLoading(false);
};
loadModels();
return () => {
cancelled = true;
};
}, [visible, token, t]);
// 按分类组织模型
@@ -1358,16 +1703,13 @@ const ModelsSideSheet = ({ visible, onClose, token, orgId, t }) => {
groupedModels[category].push(model);
});
const handleCopyModel = (model) => {
writeClipboardText(model)
.then(() => {
setCopiedModel(model);
Toast.success(t('已复制模型名称'));
setTimeout(() => setCopiedModel(null), 1500);
})
.catch(() => {
Toast.error(t('复制失败,请手动复制'));
});
const handleCopyModel = async (model) => {
if (await copyText(model, t, t('已复制模型名称'))) {
setCopiedModel(model);
// 连续复制时清掉上一个定时器,否则 A 的定时器会提前抹掉 B 的对勾
clearTimeout(copiedModelTimer.current);
copiedModelTimer.current = setTimeout(() => setCopiedModel(null), 1500);
}
};
return (
@@ -1404,17 +1746,12 @@ const ModelsSideSheet = ({ visible, onClose, token, orgId, t }) => {
<div className='font-medium text-gray-900 dark:text-white'>
{token?.name || t('未命名密钥')}
</div>
{token?.group && (
<div className='mt-2'>
{token && (
<div className='mt-2 flex items-center'>
<span className='text-sm text-gray-500 dark:text-gray-400 mr-2'>
{t('分组')}:
</span>
<Tag
color={token.group === 'auto' ? 'violet' : 'blue'}
size='small'
>
{token.group === 'auto' ? t('智能熔断') : token.group}
</Tag>
{renderOrgTokenGroup(token.group, t)}
</div>
)}
{/* 模型来源说明 */}
@@ -0,0 +1,391 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Button, Tag, Typography } from 'antd';
import Table from '../../../components/ui/CenterActionTable';
// 流水入口:ActionIcons 无 ScrollText,使用账本语义的 ReceiptText
import { ReceiptText as ScrollText } from '@/components/common/icons/ActionIcons';
import {
ArrowDownToLine,
ArrowUpFromLine,
Flame,
Network,
Wallet,
} from 'lucide-react';
import OrgStatCard from '../components/OrgStatCard';
import OrgStateBlock from '../components/OrgStateBlock';
import { OrgRowActions } from '../components/OrgListCard';
import { renderQuota } from '../../../helpers/render';
import { deptFundApi } from './fundApi';
import { FUND_STATE, buildFundTree } from './fundFormat';
import FundTransferModal from './FundTransferModal';
import FundLedgerSheet from './FundLedgerSheet';
const metricCell = (v) => (
<span className='tabular-nums'>{renderQuota(v || 0, 2)}</span>
);
/**
* 部门管理(部门管理员)→ 部门资金(F-27)。
* 操作中心 = 页头所选的直接负责部门(AUTH-04);分配从它到任意层级下级,回收从下级回到它(AUTH-02)。
* 查看下级账户不改变操作中心(AUTH-03)。
*/
const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
const { t } = useTranslation();
const [overview, setOverview] = useState(null);
const [rows, setRows] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [transfer, setTransfer] = useState(null);
const [ledgerAccount, setLedgerAccount] = useState(null);
const [accountsError, setAccountsError] = useState(false);
// 切换负责部门时旧请求可能晚到:只采纳最新一次加载,避免指标与“操作中心”错位
const seqRef = useRef(0);
const load = useCallback(async () => {
if (!orgId || !deptId) return;
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const ov = await deptFundApi.overview(orgId, deptId);
if (seq !== seqRef.current) return;
if (!ov?.data?.success) {
setError(ov?.data?.message || t('加载失败,请重试'));
return;
}
let nextRows = [];
let accErr = false;
if (ov.data.data?.fund_state !== FUND_STATE.NEVER) {
try {
const ac = await deptFundApi.accounts(orgId, deptId);
if (ac?.data?.success) nextRows = ac.data.data?.departments || [];
else accErr = true;
} catch {
accErr = true;
}
if (seq !== seqRef.current) return;
}
// 指标与下级列表一起落地,不出现“先空表再填充”
setOverview(ov.data.data);
setRows(nextRows);
setAccountsError(accErr);
} catch {
if (seq === seqRef.current) setError(t('加载失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [orgId, deptId, t]);
useEffect(() => {
setOverview(null);
setRows([]);
setAccountsError(false);
load();
}, [load, refreshKey]);
const fetchLedger = useCallback(
(id, params) => deptFundApi.ledger(orgId, id, params),
[orgId],
);
const tree = useMemo(() => buildFundTree(rows, deptId), [rows, deptId]);
if (error && !overview) {
return (
<OrgStateBlock
title={t('加载失败,请重试')}
description={error}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
);
}
if (!overview) return <OrgStateBlock loading />;
const state = overview.fund_state;
if (state === FUND_STATE.NEVER) {
return (
<Alert
type='info'
showIcon
title={t('部门资金管理未开启,当前统一使用企业资金')}
/>
);
}
const acct = overview.account || {};
const operable = state === FUND_STATE.ON;
// 资金数据异常(4.8):提示并禁用分配回收,服务端同样拦截
const anomaly = !!overview.anomaly;
const canTransfer = operable && !anomaly;
// 停用的负责部门不能发起新分配,但可以接收下级回收款(F-10)
const centerDisabled = acct.status === 2;
const transferRow = transfer?.row;
const isRecall = transfer?.mode === 'recall';
const columns = [
{
title: t('下级部门'),
dataIndex: 'name',
render: (v, r) => (
<span className='inline-flex items-center gap-1.5 min-w-0'>
<span className='truncate max-w-[220px]' title={r.pathLabel || v}>
{v}
</span>
{r.dept_status === 2 && (
<Tag color='default' variant='filled'>
{t('已停用')}
</Tag>
)}
</span>
),
},
{
title: t('累计转入'),
width: 120,
align: 'right',
render: (_, r) => metricCell(r.account?.total_in),
},
{
title: t('累计转出'),
width: 120,
align: 'right',
render: (_, r) => metricCell(r.account?.total_out),
},
{
title: t('累计消耗'),
width: 120,
align: 'right',
render: (_, r) => metricCell(r.account?.total_consumed),
},
{
title: t('可用余额'),
width: 130,
align: 'right',
render: (_, r) => (
<span className='tabular-nums font-semibold'>
{renderQuota(r.account?.balance || 0, 2)}
</span>
),
},
{
title: t('操作'),
width: 210,
fixed: 'right',
render: (_, r) => (
<OrgRowActions>
{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>
</>
)}
{r.account && (
<Button
size='small'
type='link'
onClick={() =>
setLedgerAccount({ id: r.account.id, name: r.name })
}
>
{t('流水')}
</Button>
)}
</OrgRowActions>
),
},
];
return (
<div className='flex flex-col gap-4'>
{anomaly && (
<Alert
type='error'
showIcon
title={t('资金数据异常,请联系平台管理员')}
/>
)}
{!operable && (
<Alert
type='info'
showIcon
title={t('部门资金管理未开启,当前统一使用企业资金')}
/>
)}
{centerDisabled && operable && (
<Alert
type='warning'
showIcon
title={t('当前负责部门已停用,暂不能分配资金,仍可回收下级资金')}
/>
)}
<div className='flex items-center justify-between gap-2 flex-wrap'>
<div className='text-sm'>
<span className='text-[var(--text-secondary)]'>
{t('操作中心')}:
</span>
<span className='font-semibold'>{deptName}</span>
</div>
{acct.id && (
<Button
icon={<ScrollText size={16} />}
onClick={() => setLedgerAccount({ id: acct.id, name: deptName })}
>
{t('本部门流水')}
</Button>
)}
</div>
{/* F-27 五项指标:顺序固定;仅“全部门累计消耗”含所有下级 */}
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3'>
<OrgStatCard
icon={ArrowDownToLine}
label={t('累计转入')}
value={renderQuota(acct.total_in || 0, 2)}
hint={t('收到的分配资金与从下级回收的资金')}
/>
<OrgStatCard
icon={ArrowUpFromLine}
tone='violet'
label={t('累计转出')}
value={renderQuota(acct.total_out || 0, 2)}
hint={t('向下级分配及被企业或上级回收的资金')}
/>
<OrgStatCard
icon={Flame}
tone='amber'
label={t('本部门累计消耗')}
value={renderQuota(acct.total_consumed || 0, 2)}
hint={t('从本部门账户扣除的模型消费')}
/>
<OrgStatCard
icon={Network}
tone='sky'
label={t('全部门累计消耗')}
value={renderQuota(overview.subtree_consumed || 0, 2)}
hint={t('本部门及所有下级部门的累计消耗')}
/>
<OrgStatCard
icon={Wallet}
label={t('可用余额')}
value={renderQuota(acct.balance || 0, 2)}
hint={t('累计转入 − 累计转出 − 本部门累计消耗')}
/>
</div>
<div className='text-xs text-[var(--text-secondary)]'>
{t(
'仅“全部门累计消耗”包含所有下级,其余指标仅统计本部门账户;资金与预算限额分别计算。',
)}{' '}
{t('资金余额为 0 时无法继续消费;预算上限为 0 表示不限')}
</div>
{error && (
<div className='flex items-center gap-2 text-xs'>
<Typography.Text type='danger' className='text-xs'>
{t('数据刷新失败,请重试')}
</Typography.Text>
<Button size='small' type='link' onClick={load}>
{t('重试')}
</Button>
</div>
)}
{accountsError ? (
<OrgStateBlock
title={t('加载失败,请重试')}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
) : rows.length === 0 ? (
<OrgStateBlock title={t('当前部门暂无下级部门')} />
) : (
<Table
key={`${deptId}-${rows.length}`}
columns={columns}
dataSource={tree}
loading={loading}
rowKey='key'
pagination={false}
expandable={{ defaultExpandAllRows: true }}
size='middle'
scroll={{ x: 860 }}
/>
)}
<FundTransferModal
deptSide
visible={!!transfer}
mode={transfer?.mode}
sourceLabel={
isRecall ? transferRow?.pathLabel || transferRow?.name : deptName
}
targetLabel={
isRecall ? deptName : transferRow?.pathLabel || transferRow?.name
}
sourceBalance={
isRecall ? transferRow?.account?.balance || 0 : acct.balance || 0
}
targetBalance={
isRecall ? acct.balance || 0 : transferRow?.account?.balance || 0
}
submit={(body) => {
const payload = {
...body,
source_dept_id: deptId,
target_dept_id: transferRow.department_id,
};
return isRecall
? deptFundApi.recall(orgId, payload)
: deptFundApi.allocate(orgId, payload);
}}
lookup={(opId) => deptFundApi.transfer(orgId, opId)}
onClose={() => setTransfer(null)}
onDone={load}
/>
<FundLedgerSheet
key={ledgerAccount?.id || 'closed'}
visible={!!ledgerAccount}
account={ledgerAccount}
fetchLedger={fetchLedger}
onClose={() => setLedgerAccount(null)}
/>
</div>
);
};
export default DeptFundsPanel;
@@ -0,0 +1,291 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, DatePicker, Select, Spin, Tag, Typography } from 'antd';
import dayjs from 'dayjs';
import { Table } from '@/components/ui';
import { RefreshCw } from '@/components/common/icons/ActionIcons';
import OrgSideSheet from '../components/OrgSideSheet';
import OrgStateBlock from '../components/OrgStateBlock';
import { renderQuota } from '../../../helpers/render';
import { timestamp2string } from '../../../helpers/utils';
import {
FUND_ENTRY_TYPES,
FUND_LEDGER_PENDING,
fundEntryLabel,
} from './fundFormat';
const PAGE_SIZE = 20;
const defaultRange = () => {
const end = new Date();
return [new Date(end.getTime() - 30 * 24 * 3600 * 1000), end];
};
/**
* 账户流水(F-29):所选账户、时间范围(默认近 30 日)、类型;时间倒序、每页 20 条。
* 金额:消费类保留 6 位(与消费明细一致),资金操作类 2 位。
*
* @param {(accountId, params)=>Promise} fetchLedger 企业侧或部门侧的流水接口
*/
const FundLedgerSheet = ({ visible, account, fetchLedger, onClose }) => {
const { t } = useTranslation();
const [range, setRange] = useState(defaultRange);
const [types, setTypes] = useState([]);
const [page, setPage] = useState(1);
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [rangeError, setRangeError] = useState('');
// 筛选状态随组件挂载初始化:父组件按账户 key 重新挂载本抽屉,不会沿用上一个账户的筛选/页码。
// 请求序号:快速改筛选或翻页时只采纳最后一次请求的结果。
const seqRef = useRef(0);
const load = useCallback(async () => {
if (!visible || !account?.id) return;
const [start, end] = range || [];
if (start && end && start > end) {
setRangeError(t('开始时间不能晚于结束时间'));
return;
}
setRangeError('');
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const res = await fetchLedger(account.id, {
start_timestamp: start ? Math.floor(start.getTime() / 1000) : undefined,
end_timestamp: end ? Math.floor(end.getTime() / 1000) : undefined,
type: types.length ? types.join(',') : undefined,
p: page,
page_size: PAGE_SIZE,
});
if (seq !== seqRef.current) return;
if (res?.data?.success) {
setItems(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setError(res?.data?.message || t('加载失败,请重试'));
}
} catch {
// 保留旧数据并标识刷新失败,不把旧数据冒充为最新
if (seq === seqRef.current) setError(t('数据刷新失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [visible, account?.id, range, types, page, fetchLedger, t]);
useEffect(() => {
load();
}, [load]);
const isConsume = (r) =>
r.entry_type === 'consume' || r.entry_type === 'consume_adjust';
const columns = [
{
title: t('时间'),
dataIndex: 'created_at',
width: 170,
render: (v) => (v ? timestamp2string(v) : '—'),
},
{
title: t('类型'),
dataIndex: 'entry_type',
width: 120,
render: (v, r) => (
<span className='inline-flex items-center gap-1'>
{fundEntryLabel(t, v)}
{r.status === FUND_LEDGER_PENDING && (
<Tag color='gold' variant='filled'>
{t('结算中')}
</Tag>
)}
</span>
),
},
{
title: t('金额'),
dataIndex: 'amount',
width: 140,
align: 'right',
render: (v, r) => (
<Typography.Text
className='tabular-nums'
type={v < 0 ? 'danger' : 'success'}
>
{v > 0 ? '+' : v < 0 ? '-' : ''}
{renderQuota(Math.abs(v), isConsume(r) ? 6 : 2)}
</Typography.Text>
),
},
{
title: t('对方账户'),
dataIndex: 'counterpart_name',
render: (v, r) => (
<span className='block max-w-[180px] truncate' title={v}>
{isConsume(r) ? t('系统消费') : v || '—'}
</span>
),
},
{
title: t('操作人'),
dataIndex: 'operator_name',
width: 120,
render: (v, r) => {
// 消费、结算调账等系统产生的行没有操作人
const name =
r.operator_kind === 'platform'
? t('平台管理员')
: isConsume(r) || !r.operator_user_id
? t('系统')
: v || `#${r.operator_user_id}`;
return (
<span className='block max-w-[120px] truncate' title={name}>
{name}
</span>
);
},
},
{
title: t('操作后余额'),
dataIndex: 'balance_after',
width: 130,
align: 'right',
render: (v) => (
<span className='tabular-nums'>{renderQuota(v || 0, 2)}</span>
),
},
{
title: t('备注'),
render: (_, r) => {
const badDebt = isConsume(r) ? r.amount_due + r.amount : 0;
if (r.entry_type === 'consume' && badDebt > 0) {
return (
<Typography.Text type='warning' className='text-xs'>
{t('应扣 {{due}},未收回 {{bad}}', {
due: renderQuota(r.amount_due, 6),
bad: renderQuota(badDebt, 6),
})}
</Typography.Text>
);
}
return (
<span className='text-xs text-[var(--text-secondary)] break-all'>
{r.ref_type === 'transfer' || isConsume(r) ? r.ref_id : ''}
</span>
);
},
},
];
const filtered = types.length > 0;
return (
<OrgSideSheet
visible={visible}
onCancel={onClose}
width={820}
closeOnEsc
title={`${t('资金流水')} · ${account?.name || ''}`}
>
<div className='flex flex-wrap items-center gap-2 mb-3'>
{/* 状态仍为 Date[](请求换算不变),仅在控件边界与 dayjs 互转 */}
<DatePicker.RangePicker
showTime
value={range?.length ? range.map((d) => dayjs(d)) : null}
onChange={(v) => {
setRange(v ? v.map((d) => d.toDate()) : []);
setPage(1);
}}
style={{ maxWidth: 380 }}
/>
<Select
mode='multiple'
allowClear
maxTagCount={2}
placeholder={t('全部类型')}
value={types}
onChange={(v) => {
setTypes(v);
setPage(1);
}}
style={{ minWidth: 200 }}
options={FUND_ENTRY_TYPES.map((k) => ({
value: k,
label: fundEntryLabel(t, k),
}))}
/>
<Button icon={<RefreshCw size={16} />} onClick={load} loading={loading}>
{t('刷新')}
</Button>
</div>
{rangeError && (
<Typography.Text type='danger' className='mb-2 block text-xs'>
{rangeError}
</Typography.Text>
)}
{error && (
<div className='mb-2 flex items-center gap-2 text-xs'>
<Typography.Text type='danger' className='text-xs'>
{error}
</Typography.Text>
<Button size='small' type='link' onClick={load}>
{t('重试')}
</Button>
</div>
)}
<Table
columns={columns}
dataSource={items}
loading={loading && items.length > 0}
rowKey='id'
size='middle'
scroll={{ x: 'max-content' }}
pagination={{
currentPage: page,
pageSize: PAGE_SIZE,
showSizeChanger: false,
total,
onPageChange: setPage,
showTotal: (n) => t('共 {{total}} 条', { total: n }),
}}
empty={
loading ? (
<div className='flex justify-center py-16'>
<Spin size='large' description={t('正在加载资金流水')}>
<div className='h-10 w-10' />
</Spin>
</div>
) : (
<OrgStateBlock
title={
filtered ? t('未找到符合条件的资金流水') : t('暂无资金流水')
}
/>
)
}
/>
</OrgSideSheet>
);
};
export default FundLedgerSheet;
@@ -0,0 +1,365 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Button, Checkbox, Input, theme } from 'antd';
import { ArrowRight } from 'lucide-react';
import OrgModal from '../components/OrgModal';
import {
displayAmountToQuota,
getQuotaInputUnit,
renderQuota,
} from '../../../helpers/render';
import { showSuccess, showWarning } from '../../../helpers/utils';
import { newFundOpId, validateFundAmountInput } from './fundFormat';
// TOKENS 展示模式下 renderQuota 会缩写(如 1.2M),而输入框要求精确整数:弹窗里一律显示完整数值
const fundAmountText = (quota) =>
getQuotaInputUnit().isToken
? Math.round(quota || 0).toLocaleString()
: renderQuota(quota, 2);
/**
* 分配 / 回收弹窗(F-07~F-13)。来源与去向由入口固定,弹窗内不可改。
*
* @param {'allocate'|'recall'} mode
* @param {string} sourceLabel / targetLabel 固定的来源 / 去向(部门路径或“企业未分配户”)
* @param {number} sourceBalance / targetBalance 双方当前真实可用(内部额度)
* @param {(body)=>Promise} submit 提交 { amount_quota | all, op_id } 的接口
* @param {(opId)=>Promise} lookup 按操作 ID 核实结果(结果未知时使用)
* @param {()=>void} onDone 成功后刷新
* @param {boolean} deptSide 部门管理员入口:分配时提示“分配后本部门可用余额”(F-08)
*/
const FundTransferModal = ({
visible,
mode,
sourceLabel,
targetLabel,
sourceBalance = 0,
targetBalance = 0,
submit,
lookup,
onClose,
onDone,
deptSide = false,
}) => {
const { t } = useTranslation();
const { token } = theme.useToken();
const unit = getQuotaInputUnit();
const [amount, setAmount] = useState('');
const [all, setAll] = useState(false);
const [touched, setTouched] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [phase, setPhase] = useState('input'); // input | unknown
// 进入过“结果未知”后锁定金额与“全部回收”:同一 op_id 只能原样重试。改金额重发可能遇上
// 迟到成功的原请求,引导用户换新 op_id 再提交就会重复划拨
const [frozen, setFrozen] = useState(false);
const [failure, setFailure] = useState('');
const opIdRef = useRef('');
// 结果未知后的重试必须与首次提交逐字一致(金额不随余额刷新或取整兜底重新计算)
const frozenBodyRef = useRef(null);
const isRecall = mode === 'recall';
useEffect(() => {
if (visible) {
opIdRef.current = newFundOpId();
setAmount('');
setAll(false);
setTouched(false);
setPhase('input');
setFrozen(false);
frozenBodyRef.current = null;
setFailure('');
}
}, [visible]);
const inputError = all ? '' : validateFundAmountInput(amount, unit.isToken);
// 余额按 2 位小数四舍五入展示:照着展示值输入“全部余额”时,换算回的额度可能比真实余额多出不到半个展示单位,
// 这种情况按真实余额提交,而不是误报余额不足
const rawQuota = all ? sourceBalance : displayAmountToQuota(amount);
const roundingSlack = unit.isToken ? 0 : displayAmountToQuota(0.005);
const quota =
!all &&
rawQuota > sourceBalance &&
rawQuota - sourceBalance <= roundingSlack
? sourceBalance
: rawQuota;
const overBalance = !all && !inputError && quota > sourceBalance;
const nothingToRecall = isRecall && sourceBalance <= 0;
const canSubmit =
!submitting && !nothingToRecall && !inputError && !overBalance && quota > 0;
const preview = useMemo(() => {
const q = inputError && !all ? 0 : quota;
return {
source: sourceBalance - q,
target: targetBalance + q,
};
}, [inputError, all, quota, sourceBalance, targetBalance]);
const finishSuccess = (transfer) => {
if (isRecall && transfer?.is_full_recall) {
showSuccess(
t('已全部回收,该部门可用余额为 {{amount}}', {
amount: fundAmountText(0),
}),
);
} else {
showSuccess(isRecall ? t('资金回收成功') : t('资金分配成功'));
}
onDone?.();
onClose?.();
};
const handleSubmit = async () => {
setTouched(true);
const retryBody = frozen ? frozenBodyRef.current : null;
if (submitting || (!retryBody && !canSubmit)) return;
setSubmitting(true);
setFailure('');
const body =
retryBody ||
(all
? { all: true, op_id: opIdRef.current }
: { amount_quota: quota, op_id: opIdRef.current });
try {
const res = await submit(body);
if (res?.data?.success) {
finishSuccess(res.data.data?.transfer);
} else {
// 业务明确拒绝:资金未变动,可修改后重试(同一 op_id 仍安全)。
// 例外:原操作此前已按原金额完成(迟到成功)——刷新列表,提示核实流水
if (res?.data?.data?.already_done) onDone?.();
setFailure(res?.data?.message || t('操作失败,资金未变动,请重试'));
}
} catch {
// 网络中断/超时:服务端可能已记账,进入结果确认,不能宣告资金未变动
setPhase('unknown');
setFrozen(true);
frozenBodyRef.current = body;
} finally {
setSubmitting(false);
}
};
const handleVerify = async () => {
setSubmitting(true);
try {
const res = await lookup(opIdRef.current);
if (res?.data?.success && res.data.data?.found) {
finishSuccess(res.data.data.transfer);
return;
}
if (res?.data?.success) {
// 核实到未记账:允许用同一操作 ID 安全重试
setPhase('input');
setFailure(t('操作未完成,资金未变动,请重试'));
return;
}
showWarning(t('数据刷新失败,请重试'));
} catch {
showWarning(t('数据刷新失败,请重试'));
} finally {
setSubmitting(false);
}
};
const title = isRecall ? t('回收资金') : t('分配资金');
const footer =
phase === 'unknown' ? (
<Button type='primary' loading={submitting} onClick={handleVerify}>
{t('核实结果')}
</Button>
) : (
<div className='flex justify-end gap-2'>
<Button onClick={onClose} disabled={submitting}>
{t('取消')}
</Button>
<Button
type='primary'
loading={submitting}
disabled={nothingToRecall}
onClick={handleSubmit}
>
{isRecall ? t('确认回收') : t('确认分配')}
</Button>
</div>
);
return (
<OrgModal
title={title}
visible={visible}
onCancel={submitting ? undefined : onClose}
maskClosable={!submitting}
closable={!submitting}
footer={footer}
width={520}
>
{phase === 'unknown' ? (
<Alert
type='warning'
showIcon
title={t('操作结果确认中,请刷新流水核实')}
/>
) : (
<div className='flex flex-col gap-4'>
<div className='grid grid-cols-[1fr_auto_1fr] items-center gap-3 rounded-lg border border-[var(--border-subtle)] p-3'>
<div className='min-w-0'>
<div className='text-xs text-[var(--text-secondary)]'>
{isRecall ? t('被回收部门') : t('资金来源')}
</div>
<div className='truncate font-medium' title={sourceLabel}>
{sourceLabel}
</div>
<div className='text-xs text-[var(--text-secondary)] tabular-nums'>
{isRecall ? t('可回收余额') : t('来源可用')}{' '}
{fundAmountText(sourceBalance)}
</div>
</div>
<ArrowRight size={16} className='text-[var(--text-secondary)]' />
<div className='min-w-0'>
<div className='text-xs text-[var(--text-secondary)]'>
{isRecall ? t('回收去向') : t('接收部门')}
</div>
<div className='truncate font-medium' title={targetLabel}>
{targetLabel}
</div>
<div className='text-xs text-[var(--text-secondary)] tabular-nums'>
{t('当前可用')} {fundAmountText(targetBalance)}
</div>
</div>
</div>
{nothingToRecall ? (
<Alert type='info' showIcon title={t('该部门暂无可回收余额')} />
) : (
<div>
{!all && (
<Input
value={amount}
onChange={(e) => {
setAmount(e.target.value);
setTouched(true);
}}
placeholder={
isRecall ? t('请输入回收金额') : t('请输入分配金额')
}
prefix={unit.isToken ? null : unit.symbol}
status={
touched && (inputError || overBalance) ? 'error' : undefined
}
inputMode='decimal'
disabled={frozen}
aria-label={isRecall ? t('回收金额') : t('分配金额')}
/>
)}
{deptSide && !isRecall && (
<div className='mt-1 text-xs text-[var(--text-secondary)] tabular-nums'>
{t('分配后本部门可用余额为 {{amount}}', {
amount: fundAmountText(Math.max(preview.source, 0)),
})}
</div>
)}
{frozen && (
<div className='mt-1 text-xs text-[var(--text-secondary)]'>
{t('上一次提交结果未确认,只能按原金额重试')}
</div>
)}
{touched && !all && (inputError || overBalance) && (
<div
className='mt-1 text-xs'
style={{ color: token.colorError }}
>
{overBalance
? t('可用余额不足,请刷新后重试')
: t(inputError)}
</div>
)}
{isRecall && (
<div className='mt-3'>
<Checkbox
checked={all}
disabled={frozen}
onChange={(e) => setAll(e.target.checked)}
>
{t('全部回收')}
</Checkbox>
{all && (
<div className='mt-1 text-xs text-[var(--text-secondary)]'>
<div className='tabular-nums'>
{t('全部可回收余额')} {fundAmountText(sourceBalance)}
</div>
{t('按实际余额全部回收,回收后余额为 {{amount}}', {
amount: fundAmountText(0),
})}
</div>
)}
</div>
)}
</div>
)}
{!nothingToRecall && (
<div className='grid grid-cols-2 gap-3 text-xs tabular-nums'>
<div
className='rounded-md px-3 py-2'
style={{ background: token.colorFillTertiary }}
>
<div className='text-[var(--text-secondary)]'>
{t('操作后来源余额')}
</div>
<div className='text-sm font-semibold'>
{fundAmountText(Math.max(preview.source, 0))}
</div>
</div>
<div
className='rounded-md px-3 py-2'
style={{ background: token.colorFillTertiary }}
>
<div className='text-[var(--text-secondary)]'>
{t('操作后目标余额')}
</div>
<div className='text-sm font-semibold'>
{fundAmountText(preview.target)}
</div>
</div>
</div>
)}
<div className='text-xs text-[var(--text-secondary)]'>
{isRecall
? t('仅回收所选部门自身余额,不包含子部门')
: t('仅操作所选部门自身账户金额,不包含子部门账户余额')}
</div>
{failure && <Alert type='error' showIcon title={failure} />}
{submitting && (
<div className='text-xs text-[var(--text-secondary)]'>
{t('正在处理,请勿重复提交')}
</div>
)}
</div>
)}
</OrgModal>
);
};
export default FundTransferModal;
@@ -0,0 +1,548 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Alert, Button, Switch, Tag, Typography } from 'antd';
import { Building2, Layers, PiggyBank, Power, Wallet } from 'lucide-react';
import Table from '../../../components/ui/CenterActionTable';
// 流水入口:ActionIcons 无 ScrollText,使用账本语义的 ReceiptText
import { ReceiptText as ScrollText } from '@/components/common/icons/ActionIcons';
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 { showError, showSuccess } from '../../../helpers/utils';
import { renderQuota } from '../../../helpers/render';
import { orgFundApi } from './fundApi';
import { FUND_ACCOUNT_STATUS, FUND_STATE, buildFundTree } from './fundFormat';
import FundTransferModal from './FundTransferModal';
import FundLedgerSheet from './FundLedgerSheet';
const { Text } = Typography;
// 每行自身账户四项指标(F-26):不混入子部门
const metricCell = (v) => (
<span className='tabular-nums'>{renderQuota(v || 0, 2)}</span>
);
/**
* 预算中心 → 部门资金(企业管理员)。
* 资金操作固定为“企业未分配户 ↔ 所选部门”(AUTH-01);分配与回收不改变企业总剩余。
*/
const OrgDeptFunds = ({ orgId }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [overview, setOverview] = useState(null);
const [rows, setRows] = useState([]);
const [archived, setArchived] = useState([]);
const [includeArchived, setIncludeArchived] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [toggling, setToggling] = useState(false);
const [transfer, setTransfer] = useState(null); // { mode, row }
const [ledgerAccount, setLedgerAccount] = useState(null);
const state = overview?.fund_state ?? FUND_STATE.NEVER;
const established = state !== FUND_STATE.NEVER;
const operable = state === FUND_STATE.ON;
// 资金数据异常(4.8):提示并禁用分配回收,服务端同样拦截
const anomaly = !!overview?.anomaly;
const canTransfer = operable && !anomaly;
const [accountsError, setAccountsError] = useState(false);
// 快速切换“包含已归档部门”等会并发多次加载:只采纳最新一次
const seqRef = useRef(0);
const load = useCallback(async () => {
if (!orgId) return;
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const ov = await orgFundApi.overview(orgId);
if (seq !== seqRef.current) return;
if (!ov?.data?.success) {
setError(ov?.data?.message || t('加载失败,请重试'));
return;
}
let nextRows = [];
let nextArchived = [];
let accErr = false;
if (ov.data.data?.fund_state !== FUND_STATE.NEVER) {
try {
const ac = await orgFundApi.accounts(orgId, includeArchived);
if (ac?.data?.success) {
nextRows = ac.data.data?.departments || [];
nextArchived = ac.data.data?.archived || [];
} else accErr = true;
} catch {
accErr = true;
}
if (seq !== seqRef.current) return;
}
// 概览与账户列表一起落地;列表失败时显示错误态,不用空列表冒充“没有数据”(4.8)
setOverview(ov.data.data);
setRows(nextRows);
setArchived(nextArchived);
setAccountsError(accErr);
} catch {
if (seq === seqRef.current) setError(t('加载失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [orgId, includeArchived, t]);
useEffect(() => {
load();
}, [load]);
const tree = useMemo(() => buildFundTree(rows), [rows]);
// 稳定引用:流水抽屉的加载回调依赖它,内联箭头函数会让抽屉每次渲染都重新请求
const fetchLedger = useCallback(
(id, params) => orgFundApi.ledger(orgId, id, params),
[orgId],
);
const unallocated = overview?.unallocated;
const confirmEnable = () => {
const first = state === FUND_STATE.NEVER;
OrgModal.confirm({
title: first ? t('开启部门资金管理') : t('重新开启部门资金管理'),
content: first
? t(
'开启后,有部门的成员将使用所属部门资金。各部门初始可用余额为 0,分配资金前将无法调用模型;未归属部门的成员继续使用企业未分配资金。是否开启?',
)
: t(
'将沿用原部门账户及历史数据。请在开启后重新分配资金,余额不足的部门成员将无法调用模型。',
),
okText: t('确认开启'),
cancelText: t('取消'),
onOk: async () => {
setToggling(true);
try {
const res = await orgFundApi.enable(orgId);
if (res?.data?.success) {
showSuccess(
first
? t('部门资金管理已开启,请分配部门资金')
: t('部门资金管理已开启'),
);
load();
} else {
showError(res?.data?.message || t('操作失败,请重试'));
}
} catch {
showError(t('操作失败,请重试'));
} finally {
setToggling(false);
}
},
});
};
const tryDisable = async () => {
setToggling(true);
try {
const res = await orgFundApi.closeCheck(orgId);
if (!res?.data?.success) {
showError(res?.data?.message || t('加载失败,请重试'));
return;
}
const check = res.data.data || {};
if (check.depts_with_balance > 0) {
OrgModal.warning({
title: t('关闭部门资金管理'),
content: t(
'暂不能关闭:仍有 {{n}} 个部门存在可用余额,请逐个回收后重试。',
{ n: check.depts_with_balance },
),
okText: t('知道了'),
hasCancel: false,
});
return;
}
if (check.pending_consumption > 0) {
OrgModal.warning({
title: t('关闭部门资金管理'),
content: t('仍有消费正在结算,请稍后重试'),
okText: t('知道了'),
hasCancel: false,
});
return;
}
OrgModal.confirm({
title: t('关闭部门资金管理'),
content: t(
'关闭后,所有成员统一使用企业未分配资金,现有预算限额继续生效。部门账户和历史记录将保留。是否关闭?',
),
okText: t('确认关闭'),
cancelText: t('取消'),
onOk: async () => {
try {
const r = await orgFundApi.disable(orgId);
if (r?.data?.success) {
showSuccess(t('部门资金管理已关闭'));
} else {
showError(r?.data?.message || t('操作失败,请重试'));
}
} catch {
showError(t('操作失败,请重试'));
} finally {
load();
}
},
});
} catch {
showError(t('加载失败,请重试'));
} finally {
setToggling(false);
}
};
const statusTag = (row) => {
if (row.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED)
return <Tag variant='filled'>{t('已归档')}</Tag>;
if (row.dept_status === 2)
return (
<Tag color='default' variant='filled'>
{t('已停用')}
</Tag>
);
return null;
};
const columns = [
{
title: t('部门'),
dataIndex: 'name',
render: (v, r) => (
<span className='inline-flex items-center gap-1.5 min-w-0'>
<span className='truncate max-w-[240px]' title={r.pathLabel || v}>
{v}
</span>
{statusTag(r)}
</span>
),
},
{
title: t('累计转入'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_in),
},
{
title: t('累计转出'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_out),
},
{
title: t('累计消耗'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_consumed),
},
{
title: t('可用余额'),
width: 140,
align: 'right',
render: (_, r) => (
<span className='tabular-nums font-semibold'>
{renderQuota(r.account?.balance || 0, 2)}
</span>
),
},
{
title: t('操作'),
width: 220,
fixed: 'right',
render: (_, r) => {
const isArchived = r.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED;
return (
<OrgRowActions>
{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>
</>
)}
{r.account && (
<Button
size='small'
type='link'
onClick={() =>
setLedgerAccount({ id: r.account.id, name: r.name })
}
>
{t('流水')}
</Button>
)}
</OrgRowActions>
);
},
},
];
const archivedRows = archived.map((a) => ({
key: `archived-${a.id}`,
name: a.name,
account: a,
dept_status: 2,
}));
if (error && !overview) {
return (
<OrgStateBlock
title={t('加载失败,请重试')}
description={error}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
);
}
if (!overview) return <OrgStateBlock loading />;
const transferRow = transfer?.row;
const isRecall = transfer?.mode === 'recall';
return (
<div className='flex flex-col gap-4'>
<OrgPanel
icon={Power}
title={t('部门资金管理')}
subtitle={
established
? `${t('分配与回收不改变企业总剩余;资金与预算限额分别计算')} ${t('资金余额为 0 时无法继续消费;预算上限为 0 表示不限')}`
: t(
'开启后,可将企业资金分配给部门独立使用。未开启时,所有成员继续使用企业资金池,现有预算限额仍生效。',
)
}
actions={
<div className='flex items-center gap-2'>
<Tag color={operable ? 'success' : 'default'} variant='filled'>
{operable ? t('已开启') : t('未开启')}
</Tag>
{operable ? (
<Button danger loading={toggling} onClick={tryDisable}>
{t('关闭')}
</Button>
) : (
<Button type='primary' loading={toggling} onClick={confirmEnable}>
{state === FUND_STATE.OFF ? t('重新开启') : t('开启')}
</Button>
)}
</div>
}
>
<div className='grid grid-cols-1 sm:grid-cols-3 gap-3'>
<OrgStatCard
icon={Wallet}
label={t('企业总剩余')}
value={renderQuota(overview.enterprise_total || 0, 2)}
hint={t('主池 {{main}} · 赠送 {{gift}}', {
main: renderQuota(overview.quota || 0, 2),
gift: renderQuota(overview.gift_quota || 0, 2),
})}
/>
{established && (
<>
<OrgStatCard
icon={PiggyBank}
tone='amber'
label={t('企业未分配可用')}
value={renderQuota(unallocated?.balance || 0, 2)}
hint={
unallocated ? (
<Button
size='small'
type='link'
icon={<ScrollText size={16} />}
onClick={() =>
setLedgerAccount({
id: unallocated.id,
name: t('企业未分配户'),
})
}
>
{t('查看流水')}
</Button>
) : null
}
/>
<OrgStatCard
icon={Layers}
tone='sky'
label={t('部门可用合计')}
value={renderQuota(overview.dept_available_sum || 0, 2)}
/>
</>
)}
</div>
{error && (
<div className='mt-3 flex items-center gap-2 text-xs'>
<Typography.Text type='danger' className='text-xs'>
{t('数据刷新失败,请重试')}
</Typography.Text>
<Button size='small' type='link' onClick={load}>
{t('重试')}
</Button>
</div>
)}
</OrgPanel>
{anomaly && (
<Alert
type='error'
showIcon
title={t('资金数据异常,请联系平台管理员')}
/>
)}
{state === FUND_STATE.OFF && (
<Alert
type='info'
showIcon
title={t(
'部门资金管理未开启,当前统一使用企业资金。可查看原资金账户与流水,不能分配或回收。',
)}
/>
)}
{established && (
<OrgPanel
icon={Building2}
title={t('部门账户')}
subtitle={t(
'每行仅统计该部门自身账户,不含子部门;回收只回收所选部门自身余额。',
)}
actions={
<span className='inline-flex items-center gap-2 text-sm'>
<Switch
size='small'
checked={includeArchived}
onChange={setIncludeArchived}
aria-label={t('包含已归档部门')}
/>
<Text className='text-xs'>{t('包含已归档部门')}</Text>
</span>
}
padding='p-2'
>
{accountsError ? (
<OrgStateBlock
title={t('加载失败,请重试')}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
) : overview.department_count === 0 && rows.length === 0 ? (
<OrgStateBlock
title={t('暂无部门,请先在部门管理中创建部门')}
action={
<Button onClick={() => navigate('/org/departments')}>
{t('前往部门管理')}
</Button>
}
/>
) : (
<Table
key={`${includeArchived}-${rows.length}-${archived.length}`}
columns={columns}
dataSource={[...tree, ...(includeArchived ? archivedRows : [])]}
loading={loading}
rowKey='key'
pagination={false}
expandable={{ defaultExpandAllRows: true }}
size='middle'
scroll={{ x: 900 }}
/>
)}
</OrgPanel>
)}
<FundTransferModal
visible={!!transfer}
mode={transfer?.mode}
sourceLabel={
isRecall
? transferRow?.pathLabel || transferRow?.name
: t('企业未分配户')
}
targetLabel={
isRecall
? t('企业未分配户')
: transferRow?.pathLabel || transferRow?.name
}
sourceBalance={
isRecall
? transferRow?.account?.balance || 0
: unallocated?.balance || 0
}
targetBalance={
isRecall
? unallocated?.balance || 0
: transferRow?.account?.balance || 0
}
submit={(body) =>
isRecall
? orgFundApi.recall(orgId, {
...body,
dept_id: transferRow.department_id,
})
: orgFundApi.allocate(orgId, {
...body,
dept_id: transferRow.department_id,
})
}
lookup={(opId) => orgFundApi.transfer(orgId, opId)}
onClose={() => setTransfer(null)}
onDone={load}
/>
<FundLedgerSheet
key={ledgerAccount?.id || 'closed'}
visible={!!ledgerAccount}
account={ledgerAccount}
fetchLedger={fetchLedger}
onClose={() => setLedgerAccount(null)}
/>
</div>
);
};
export default OrgDeptFunds;
+80
View File
@@ -0,0 +1,80 @@
/*
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 { API } from '../../../helpers/api';
// 部门资金管理接口(技术评审稿 §7)。查询失败由页面自己展示错误态,统一静默全局 toast;
// 分配/回收提交需要区分“明确失败”与“结果未知(网络中断)”,同样自行处理。
const opts = (orgId, extra = {}) => ({
headers: { 'X-Org-Id': String(orgId) },
skipErrorHandler: true,
...extra,
});
export const orgFundApi = {
overview: (orgId) => API.get('/api/org/fund/overview', opts(orgId)),
enable: (orgId) => API.post('/api/org/fund/enable', {}, opts(orgId)),
closeCheck: (orgId) => API.get('/api/org/fund/close-check', opts(orgId)),
disable: (orgId) => API.post('/api/org/fund/disable', {}, opts(orgId)),
accounts: (orgId, includeArchived) =>
API.get(
`/api/org/fund/accounts${includeArchived ? '?include_archived=1' : ''}`,
opts(orgId),
),
allocate: (orgId, body) =>
API.post('/api/org/fund/allocate', body, opts(orgId)),
recall: (orgId, body) => API.post('/api/org/fund/recall', body, opts(orgId)),
ledger: (orgId, accountId, params) =>
API.get(
`/api/org/fund/accounts/${accountId}/ledger`,
opts(orgId, { params }),
),
transfer: (orgId, opId) =>
API.get(`/api/org/fund/transfers/${encodeURIComponent(opId)}`, opts(orgId)),
movePreview: (orgId, deptId) =>
API.get(`/api/org/dept/${deptId}/move-preview`, opts(orgId)),
};
export const deptFundApi = {
scope: (orgId) => API.get('/api/org/dept-managed/fund/scope', opts(orgId)),
overview: (orgId, sourceDeptId) =>
API.get(
'/api/org/dept-managed/fund/overview',
opts(orgId, { params: { source_dept_id: sourceDeptId } }),
),
accounts: (orgId, sourceDeptId) =>
API.get(
'/api/org/dept-managed/fund/accounts',
opts(orgId, { params: { source_dept_id: sourceDeptId } }),
),
allocate: (orgId, body) =>
API.post('/api/org/dept-managed/fund/allocate', body, opts(orgId)),
recall: (orgId, body) =>
API.post('/api/org/dept-managed/fund/recall', body, opts(orgId)),
ledger: (orgId, accountId, params) =>
API.get(
`/api/org/dept-managed/fund/accounts/${accountId}/ledger`,
opts(orgId, { params }),
),
transfer: (orgId, opId) =>
API.get(
`/api/org/dept-managed/fund/transfers/${encodeURIComponent(opId)}`,
opts(orgId),
),
};
+133
View File
@@ -0,0 +1,133 @@
/*
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
*/
// 与后端 model/org_fund.go 常量一一对应
export const FUND_STATE = { NEVER: 0, ON: 1, OFF: 2 };
export const FUND_ACCOUNT_TYPE = { POOL: 0, UNALLOCATED: 1, DEPT: 2 };
export const FUND_ACCOUNT_STATUS = { ACTIVE: 1, DISABLED: 2, ARCHIVED: 3 };
export const FUND_LEDGER_PENDING = 1;
export const FUND_ENTRY_TYPES = [
'allocate_in',
'allocate_out',
'recall_in',
'recall_out',
'consume',
'consume_adjust',
'recharge',
'platform_add',
'platform_sub',
'baseline',
];
export const fundEntryLabel = (t, type) =>
({
baseline: t('首次开启基线'),
allocate_in: t('分配转入'),
allocate_out: t('分配转出'),
recall_in: t('回收转入'),
recall_out: t('回收转出'),
consume: t('消费'),
consume_adjust: t('消费调账'),
recharge: t('充值入账'),
platform_add: t('平台调增'),
platform_sub: t('平台调减'),
})[type] || type;
// 扣费账户展示值(F-36):企业资金池 / 企业未分配户 / 部门账户 · {名称快照}
export const fundAccountDisplay = (t, accountType, deptName) => {
if (accountType === FUND_ACCOUNT_TYPE.UNALLOCATED) return t('企业未分配户');
if (accountType === FUND_ACCOUNT_TYPE.DEPT)
return `${t('部门账户')} · ${deptName || ''}`;
return t('企业资金池');
};
// 归属部门展示值:未快照(历史待补齐)为 “—”,部门为 0 是“未归属部门”
export const fundDeptDisplay = (t, deptId, deptName) => {
if (deptId === null || deptId === undefined) return '—';
if (!deptId) return t('未归属部门');
return deptName || `#${deptId}`;
};
// 一次分配/回收的幂等键:打开弹窗时生成,重试沿用(F-12)。
// 旧内核(Chromium < 92)没有 crypto.randomUUID,退回 getRandomValues 拼装。
export const newFundOpId = () => {
const c = typeof window !== 'undefined' ? window.crypto : undefined;
if (c?.randomUUID) return c.randomUUID();
const bytes = new Uint8Array(16);
if (c?.getRandomValues) c.getRandomValues(bytes);
else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
};
// 手动金额校验(F-13):正数、最多两位小数;TOKENS 展示模式只收整数。
// 不接受负数、0、科学计数法、非数字文本。返回 i18n 键,合法返回 ''。
export const validateFundAmountInput = (raw, isTokenUnit) => {
const s = String(raw ?? '').trim();
if (!s) return '请输入金额';
const pattern = isTokenUnit ? /^\d+$/ : /^\d+(\.\d{1,2})?$/;
if (!pattern.test(s) || !(Number(s) > 0))
return '请输入大于 0、最多两位小数的金额';
if (Number(s) > 1e9) return '金额超出可操作范围';
return '';
};
// 按 parent_id 组装树(同级按 sort、id 排序),供 Semi Table 树形展示
export const buildFundTree = (rows, rootParentId = 0) => {
const byParent = new Map();
rows.forEach((r) => {
const p = r.parent_id || 0;
if (!byParent.has(p)) byParent.set(p, []);
byParent.get(p).push(r);
});
const ids = new Set(rows.map((r) => r.department_id));
const sortRows = (list) =>
[...list].sort(
(a, b) =>
(a.sort || 0) - (b.sort || 0) || a.department_id - b.department_id,
);
const build = (parentId, trail) =>
sortRows(byParent.get(parentId) || []).map((r) => {
const path = [...trail, r.name];
const children = build(r.department_id, path);
return {
...r,
key: r.department_id,
pathLabel: path.join(' / '),
children: children.length ? children : undefined,
};
});
// 根:rootParentId 的直接子节点;另外把父节点不在列表里的行也当作根(下级视图里的顶层)
const roots = build(rootParentId, []);
const orphanRoots = rows.filter(
(r) => (r.parent_id || 0) !== rootParentId && !ids.has(r.parent_id),
);
return [
...roots,
...sortRows(orphanRoots).map((r) => {
const children = build(r.department_id, [r.name]);
return {
...r,
key: r.department_id,
pathLabel: r.name,
children: children.length ? children : undefined,
};
}),
];
};
+206 -7
View File
@@ -27,11 +27,13 @@ import React, {
} from 'react';
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui';
import { Button, Spin } from '@/components/ui';
import OrgSideSheet from './components/OrgSideSheet';
import { StatusContext } from '../../context/Status';
import { useMarquee } from '../../hooks/common/useMarquee';
import { UserContext } from '../../context/User';
import { OrgContext } from '../../context/Org';
import { usePartnerWorkspaceAccess } from '../../hooks/common/usePartnerWorkspaceEntry';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { isMiniProgramWebView } from '../../helpers/miniProgram';
@@ -64,6 +66,8 @@ import OrgAgentAudit from './OrgAgentAudit';
import OrgConnectors from './OrgConnectors';
import OrgEffectiveness from './OrgEffectiveness';
import OrgQuality from './OrgQuality';
import OrgSmartRouter from './OrgSmartRouter';
import { getConsents as getRouterConsents } from '../../components/smart-router/api';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
import { canAccessOrgSettings } from './orgFeatureFlags';
import {
@@ -72,6 +76,12 @@ import {
} from '../../config/cloudBrainUi';
import '../../styles/org.css';
const OrganizationCommission = React.lazy(() =>
import('../CommissionV2').then((module) => ({
default: module.PartnerWorkspace,
})),
);
const routeFeatureRequirements = {
cloudBrain: 'cloud_brain',
knowledge: 'knowledge_base',
@@ -84,6 +94,7 @@ const routeFeatureRequirements = {
myConnectors: 'connector',
effectiveness: 'agent_effectiveness',
quality: 'quality_monitor',
smartRouter: 'smart_router',
privateSkills: 'skill_market',
departments: 'dept',
projects: 'project',
@@ -117,6 +128,45 @@ const Organization = () => {
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
// Context changes make same-tab enterprise switches reactive; storage covers other tabs.
const [, , orgActions] = useContext(OrgContext);
const [, refreshOrgStorage] = useState(0);
useEffect(() => {
const onStorage = (event) => {
if (event.key === 'current_org_id' || event.key === null)
refreshOrgStorage((value) => value + 1);
};
window.addEventListener('storage', onStorage);
return () => window.removeEventListener('storage', onStorage);
}, []);
const orgId = Number(localStorage.getItem('current_org_id')) || 0;
const user = userState?.user;
const [availableOrgs, setAvailableOrgs] = useState([]);
useEffect(() => {
let current = true;
setAvailableOrgs([]);
if (!user?.id || user.org_only_mode) return undefined;
API.get('/api/org/list', { skipErrorHandler: true })
.then((response) => {
if (current && response.data?.success)
setAvailableOrgs(
(response.data.data || []).filter(
(org) =>
org.status === 1 && ['owner', 'admin'].includes(org.role),
),
);
})
.catch(() => {});
return () => {
current = false;
};
}, [user]);
const liveOrgScope = useRef(null);
liveOrgScope.current = { orgId, user };
const orgRequest = useRef(0);
const [loadedOrgScope, setLoadedOrgScope] = useState(null);
const { status: commissionAccess } = usePartnerWorkspaceAccess(orgId);
const canViewCommission = commissionAccess === 'allowed';
// org_only 员工被 App 守卫限制在 /org;这里的回退不能再把他们踢回 C 端,否则死循环
const isOrgUser = userState?.user?.org_only_mode === true;
const [orgInfo, setOrgInfo] = useState(null);
@@ -132,6 +182,12 @@ const Organization = () => {
const [canAuditAgentContent, setCanAuditAgentContent] = useState(false);
const [canViewAgentEffect, setCanViewAgentEffect] = useState(false);
const [canViewQuality, setCanViewQuality] = useState(false);
const [canViewSmartRouter, setCanViewSmartRouter] = useState(false);
// 平台关闭智能路由后,企业所有者仍需能看到并撤回已授予的数据出境同意(第 5 轮 review M-2)
const [routerConsentGranted, setRouterConsentGranted] = useState(false);
// 授权状态是否已查询完成:未完成前不能让路由守卫把直接打开 /org/smart-router 的所有者重定向走(第 6 轮 review)
const [routerConsentChecked, setRouterConsentChecked] = useState(false);
const [canManageSmartRouter, setCanManageSmartRouter] = useState(false);
const [canManageAgentPolicy, setCanManageAgentPolicy] = useState(false);
// 平台超管查看企业时没有成员身份,成员型接口一律 member_actor_required;
// 用该标志收敛“我的技能/我的业务系统授权”这类必失败入口。
@@ -168,10 +224,22 @@ const Organization = () => {
},
[orgConfig, orgFeatureFlags],
);
const smartRouterFeatureOn = isFeatureEnabled(
orgFeatureFlags,
routeFeatureRequirements.smartRouter,
);
// 仅授权模式:功能已关闭但仍有生效中的同意,只展示授权页签供所有者撤回
const smartRouterConsentOnly =
!smartRouterFeatureOn && orgRole === 'owner' && routerConsentGranted;
const smartRouterConsentPending =
!smartRouterFeatureOn && orgRole === 'owner' && !routerConsentChecked;
const visibleOrgRoutes = useMemo(() => {
const routes = [];
// 管理员默认落 dashboard;普通成员默认落 workbench(§36 角色化首屏)
if (isAdmin && isOrgModuleVisible('dashboard')) routes.push('dashboard');
if (canViewCommission && isOrgModuleVisible('commission'))
routes.push('commission');
if (isOrgModuleVisible('workbench')) routes.push('workbench');
if (isOrgModuleVisible('cloudBrain')) routes.push('cloud-brain');
// 成员型入口对无成员身份的超管隐藏;否则模块配置特定组合下
@@ -190,6 +258,11 @@ const Organization = () => {
routes.push('effectiveness');
if (isAdmin && canViewQuality && isOrgModuleVisible('quality'))
routes.push('quality');
if (
(isAdmin && canViewSmartRouter && isOrgModuleVisible('smartRouter')) ||
smartRouterConsentOnly
)
routes.push('smart-router');
// 审计路由组后端是 OrgAdminAuth(仅 owner/admin),不放行部门负责人;
// 这里必须同样只认 isAdmin。此前的 isDeptManager 分支当前不可达
// (canAuditAgentMetadata 对非 owner/admin 恒 false),但一旦把
@@ -249,9 +322,12 @@ const Organization = () => {
canAuditAgentMetadata,
canViewAgentEffect,
canViewQuality,
canViewSmartRouter,
smartRouterConsentOnly,
isDeptManager,
isProjectManager,
isMemberActor,
canViewCommission,
canManageSettings,
isOrgModuleVisible,
]);
@@ -267,8 +343,6 @@ const Organization = () => {
return element;
};
// 从 localStorage 获取当前企业ID
const orgId = parseInt(localStorage.getItem('current_org_id') || '0', 10);
// localStorage 不会触发重渲染:解析器写入/清除 current_org_id 后靠它刷新。
// failedOrgIds 累计本次挂载内加载失败过的企业,交给解析器跳过:只记最近一个会在
// 两个都失败的企业之间 A→B→A 来回自动切换(每轮都发请求并弹错误提示)。
@@ -280,8 +354,53 @@ const Organization = () => {
setLoading(true);
setOrgResolveTick((n) => n + 1);
}, []);
const switchOrganization = (id) => {
const org = availableOrgs.find((item) => item.id === Number(id));
if (!org || org.id === orgId) return;
// Invalidate in the event handler, before React applies the next render.
orgRequest.current++;
liveOrgScope.current = { orgId: org.id, user };
localStorage.setItem('current_org_id', String(org.id));
orgActions?.setCurrentOrg?.(org, org.role);
setMobileNavOpen(false);
handleOrgResolved();
};
useEffect(() => {
if (!orgId || orgRole !== 'owner' || !orgInfo || smartRouterFeatureOn) {
setRouterConsentGranted(false);
setRouterConsentChecked(!!orgInfo);
return;
}
let alive = true;
setRouterConsentChecked(false);
getRouterConsents('org', orgId)
.then((list) => {
if (alive)
setRouterConsentGranted(
(list || []).some((x) => x && x.granted === true),
);
})
.catch(() => {
// 查询失败时仍进入仅授权页:由授权面板展示错误与重试,而不是把所有者静默重定向走(第 8 轮 review)
if (alive) setRouterConsentGranted(true);
})
.finally(() => {
if (alive) setRouterConsentChecked(true);
});
return () => {
alive = false;
};
// 依赖企业 id 而不是 orgInfo 对象:企业信息每次刷新都会换新对象,不必每次重查授权(第 8 轮 review)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [orgId, orgRole, orgInfo?.id, smartRouterFeatureOn]);
const fetchOrgInfo = useCallback(async () => {
const request = ++orgRequest.current;
const isCurrent = () =>
request === orgRequest.current &&
liveOrgScope.current?.orgId === orgId &&
liveOrgScope.current?.user === user;
if (!orgId) {
setLoading(false);
return;
@@ -292,9 +411,11 @@ const Organization = () => {
const res = await API.get('/api/org/info', {
headers: { 'X-Org-Id': String(orgId) },
});
if (!isCurrent()) return;
if (res.data.success) {
const member = res.data.data.member || res.data.data;
setOrgInfo(res.data.data.organization);
setLoadedOrgScope({ orgId, user });
setOrgRole(member.role);
setCanManageCloudBrain(member.can_manage_cloud_brain === true);
setCanManageKnowledge(member.can_manage_knowledge === true);
@@ -305,6 +426,8 @@ const Organization = () => {
setCanManageConnectors(member.can_manage_connectors === true);
setCanViewAgentEffect(member.can_view_agent_effect === true);
setCanViewQuality(member.can_view_quality === true);
setCanViewSmartRouter(member.can_view_smart_router === true);
setCanManageSmartRouter(member.can_manage_smart_router === true);
setCanManageAgentPolicy(member.can_manage_agent_policy === true);
// 后端未返回该键时按“有成员身份”处理,避免旧后端下入口消失。
setIsMemberActor(member.is_member_actor !== false);
@@ -312,6 +435,11 @@ const Organization = () => {
setCanAuditAgentContent(member.can_audit_agent_content === true);
} else if (res.data.code === 'org_pending_activation') {
// 待激活:不跳转创建页,展示占位页,保留 current_org_id
// Clear the previous organization's state so its scope guard cannot
// hide the current pending-activation screen behind a permanent spinner.
setOrgInfo(null);
setOrgRole(null);
setLoadedOrgScope({ orgId, user });
setPendingActivation(true);
} else {
showError(res.data.message);
@@ -319,15 +447,19 @@ const Organization = () => {
setFailedOrgIds((ids) => (ids.includes(orgId) ? ids : [...ids, orgId]));
}
} catch {
if (!isCurrent()) return;
localStorage.removeItem('current_org_id');
setFailedOrgIds((ids) => (ids.includes(orgId) ? ids : [...ids, orgId]));
} finally {
setLoading(false);
if (isCurrent()) setLoading(false);
}
}, [orgId]);
}, [orgId, user]);
useEffect(() => {
fetchOrgInfo();
return () => {
orgRequest.current++;
};
}, [fetchOrgInfo]);
// 是否为部门负责人(控制「部门管理」入口/路由),失败按非负责人处理。
@@ -412,7 +544,11 @@ const Organization = () => {
);
}
if (loading) {
if (
loading ||
(orgInfo &&
(loadedOrgScope?.orgId !== orgId || loadedOrgScope?.user !== user))
) {
return <Loading />;
}
@@ -453,6 +589,7 @@ const Organization = () => {
}
if (!firstOrgRoute) {
if (commissionAccess === 'loading') return <Loading />;
if (isOrgUser) return orgUnavailableFallback;
return <Navigate to='/user-center/dashboard' replace />;
}
@@ -465,6 +602,9 @@ const Organization = () => {
<div className='hidden md:block flex-shrink-0 h-full'>
<OrgSidebar
orgName={orgInfo?.name}
organizations={availableOrgs}
currentOrgId={orgId}
onOrganizationChange={switchOrganization}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
isDeptManager={isDeptManager}
@@ -477,6 +617,9 @@ const Organization = () => {
canAuditAgentMetadata={canAuditAgentMetadata}
canViewAgentEffect={canViewAgentEffect}
canViewQuality={canViewQuality}
canViewCommission={canViewCommission}
canViewSmartRouter={canViewSmartRouter}
smartRouterConsentOnly={smartRouterConsentOnly}
isMemberActor={isMemberActor}
/>
</div>
@@ -504,6 +647,18 @@ const Organization = () => {
<div className='relative z-10 h-full overflow-y-auto uc-page-scrollbar'>
<Routes>
<Route
path='commission'
element={guardOrgRoute(
'commission',
<React.Suspense fallback={<Loading />}>
<OrganizationCommission
key={`${user?.id}:${orgId}`}
organizationId={orgId}
/>
</React.Suspense>,
)}
/>
{/* 默认路由:管理员进数据看板,普通成员进工作台 */}
<Route
path='/'
@@ -767,6 +922,38 @@ const Organization = () => {
)
}
/>
<Route
path='smart-router'
element={
smartRouterConsentPending ? (
<div className='flex justify-center py-16'>
<Spin />
</div>
) : smartRouterConsentOnly ? (
<OrgSmartRouter
orgId={orgId}
isOwner
consentOnly
onConsentChange={(rows) =>
setRouterConsentGranted(
(rows || []).some((x) => x && x.granted === true),
)
}
/>
) : isAdmin && canViewSmartRouter ? (
guardOrgRoute(
'smartRouter',
<OrgSmartRouter
orgId={orgId}
canManage={canManageSmartRouter}
isOwner={orgRole === 'owner'}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='quality'
element={
@@ -869,7 +1056,13 @@ const Organization = () => {
path='budgets'
element={
isAdmin ? (
guardOrgRoute('budgets', <OrgBudgets orgId={orgId} />)
guardOrgRoute(
'budgets',
<OrgBudgets
orgId={orgId}
featureFlags={orgFeatureFlags}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
@@ -914,6 +1107,9 @@ const Organization = () => {
>
<OrgSidebar
orgName={orgInfo?.name}
organizations={availableOrgs}
currentOrgId={orgId}
onOrganizationChange={switchOrganization}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
isDeptManager={isDeptManager}
@@ -926,6 +1122,9 @@ const Organization = () => {
canAuditAgentMetadata={canAuditAgentMetadata}
canViewAgentEffect={canViewAgentEffect}
canViewQuality={canViewQuality}
canViewCommission={canViewCommission}
canViewSmartRouter={canViewSmartRouter}
smartRouterConsentOnly={smartRouterConsentOnly}
isMemberActor={isMemberActor}
mobile
onNavigate={() => setMobileNavOpen(false)}
+2 -1
View File
@@ -47,7 +47,8 @@ export default function PartnerConsole() {
const [statusState] = useContext(StatusContext);
const portalClosed =
!!statusState?.status &&
statusState.status.commission_partner_portal_enabled !== true;
(statusState.status.commission_enabled === false ||
statusState.status.commission_partner_portal_enabled !== true);
const [phase, setPhase] = useState('loading'); // loading | apply | status | dashboard | error
const [self, setSelf] = useState(null);
const [dashboard, setDashboard] = useState(null);
+13 -9
View File
@@ -26,13 +26,14 @@ import { StatusContext } from '../../context/Status';
import GlassCard from '../../components/auth/GlassCard';
import AuthCardHeader from '../../components/auth/AuthCardHeader';
import AuthBackground from '../../components/common/AuthBackground';
import { resolvePartnerPortalRedirect } from './redirect';
const { Text } = Typography;
/**
* 合作伙伴门户(对外入口)
* 仅承担未登录引导:登录统一走主站登录页并自动回跳;
* 已登录用户一律转入 /console/partner(个人中心 · 合作伙伴),申请/审核/工作台均在 console 内完成。
* 已登录的新版伙伴进入新版分佣工作台;旧版伙伴身份不再回退到旧伙伴控制台。
*/
export default function PartnerPortal() {
const { t } = useTranslation();
@@ -42,17 +43,20 @@ export default function PartnerPortal() {
const [statusState] = useContext(StatusContext);
const portalClosed =
!!statusState?.status &&
statusState.status.commission_partner_portal_enabled !== true;
(statusState.status.commission_enabled === false ||
statusState.status.commission_partner_portal_enabled !== true);
useEffect(() => {
// 已知关闭(伙伴入口或分佣总开关)时不探测伙伴身份:页面只展示未开放提示,
// 接口也会被后端闸门直接拒绝。
if (portalClosed) return;
(async () => {
try {
// skipErrorHandler:未登录访问是常态入口,不弹全局错误 toast
const res = await API.get('/api/partner/self', {
skipErrorHandler: true,
});
if (res.data.success) {
navigate('/console/partner', { replace: true });
// skipErrorHandler:未登录访问是常态入口,不弹全局错误 toast。
// 新版接口必须先判定,否则同时存在旧伙伴记录时会被旧入口截走。
const redirect = await resolvePartnerPortalRedirect(API.get);
if (redirect) {
navigate(redirect, { replace: true });
return;
}
setPhase('login');
@@ -60,7 +64,7 @@ export default function PartnerPortal() {
setPhase('login');
}
})();
}, [navigate]);
}, [navigate, portalClosed]);
// 登录统一走主站登录页(完整支持人机验证/第三方登录/用户上下文分发),
// 登录成功后经 consumePostLoginRedirect 自动回跳本页,再由本页转入 console
+85
View File
@@ -0,0 +1,85 @@
/*
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
*/
// 伙伴入口探测:非伙伴返回 200 + allowed=false(后端不再以 403 表达"非伙伴")。
// 企业作用域由 partnerScope 映射为 /api/org/commission/access。
const V2_ACCESS_URL = '/api/partner/v2/access';
/**
* 探测伙伴身份:status 为 allowed / denied / error;partnerType 为 individual(个人伙伴)
* 或 company(企业伙伴,只从企业中心「企业分佣」进入,不展示顶栏「伙伴工作台」)。
*/
export async function resolvePartnerWorkspaceIdentity(get) {
try {
const response = await get(V2_ACCESS_URL, { skipErrorHandler: true });
if (response?.data?.success !== true) return { status: 'error' };
const data = response.data.data || {};
return data.allowed === true
? { status: 'allowed', partnerType: data.partner_type || '' }
: { status: 'denied' };
} catch (error) {
// 401(会话失效)与门户开关关闭时的 403 仍视为无入口
return {
status: [401, 403].includes(error?.response?.status) ? 'denied' : 'error',
};
}
}
export async function resolvePartnerWorkspaceAccess(get) {
return (await resolvePartnerWorkspaceIdentity(get)).status;
}
// 伙伴工作台入口:企业伙伴走企业中心「企业分佣」,其余(个人伙伴)走控制台「我的提成」
export const COMPANY_PARTNER_WORKSPACE_PATH = '/org/commission';
export function partnerWorkspacePath(partnerType) {
return partnerType === 'company'
? COMPANY_PARTNER_WORKSPACE_PATH
: '/console/my-commission';
}
export function partnerWorkspaceFallback(role) {
if (role >= 100) return '/console/commission';
if (role >= 10) return '/console/analytics';
return '/forbidden';
}
/**
* Resolve the destination for an authenticated partner entry request.
*
* The v2 identity is the only supported destination. Legacy partner records
* must be migrated by the platform instead of being sent back to the retired
* partner console.
*/
export async function resolvePartnerPortalRedirect(get) {
const request = (url) => get(url, { skipErrorHandler: true });
try {
const response = await request(V2_ACCESS_URL);
const data = response?.data?.success ? response.data.data : null;
if (data?.allowed === true) {
// 企业伙伴只从企业中心「企业分佣」进入;个人伙伴(或旧后端未返回类型)进入个人伙伴工作台
return partnerWorkspacePath(data.partner_type);
}
} catch {
// Unauthenticated or non-v2 users stay on the public entry page. The
// retired legacy partner API is intentionally not queried.
}
return null;
}
+150
View File
@@ -0,0 +1,150 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
resolvePartnerPortalRedirect,
resolvePartnerWorkspaceAccess,
resolvePartnerWorkspaceIdentity,
partnerWorkspaceFallback,
} from './redirect.js';
test('伙伴页面依据服务端权限,不按平台角色推断伙伴身份', async () => {
const calls = [];
assert.equal(
await resolvePartnerWorkspaceAccess(async (url) => {
calls.push(url);
return { data: { success: true, data: { allowed: true } } };
}),
'allowed',
);
assert.deepEqual(calls, ['/api/partner/v2/access']);
// 非伙伴:探测接口返回 200 + allowed=false,不再依赖 403
assert.equal(
await resolvePartnerWorkspaceAccess(async () => ({
data: { success: true, data: { allowed: false } },
})),
'denied',
);
for (const status of [401, 403]) {
assert.equal(
await resolvePartnerWorkspaceAccess(async () => {
throw { response: { status } };
}),
'denied',
);
}
});
test('探测结果区分个人伙伴与企业伙伴,供顶栏入口只对个人伙伴展示', async () => {
for (const type of ['individual', 'company']) {
assert.deepEqual(
await resolvePartnerWorkspaceIdentity(async () => ({
data: { success: true, data: { allowed: true, partner_type: type } },
})),
{ status: 'allowed', partnerType: type },
);
}
assert.deepEqual(
await resolvePartnerWorkspaceIdentity(async () => ({
data: { success: true, data: { allowed: false } },
})),
{ status: 'denied' },
);
});
test('服务异常保持可重试状态,不误判为无伙伴权限', async () => {
for (const error of [new Error('offline'), { response: { status: 500 } }]) {
assert.equal(
await resolvePartnerWorkspaceAccess(async () => {
throw error;
}),
'error',
);
}
assert.equal(
await resolvePartnerWorkspaceAccess(async () => ({
data: { success: false },
})),
'error',
);
});
test('无伙伴权限时超管进入分佣管理,普通管理员不越权进入分佣管理', () => {
assert.equal(partnerWorkspaceFallback(100), '/console/commission');
assert.equal(partnerWorkspaceFallback(10), '/console/analytics');
assert.equal(partnerWorkspaceFallback(1), '/forbidden');
assert.equal(partnerWorkspaceFallback(undefined), '/forbidden');
});
test('新版伙伴身份优先进入新版伙伴分佣工作台', async () => {
const calls = [];
const redirect = await resolvePartnerPortalRedirect(async (url) => {
calls.push(url);
if (url === '/api/partner/v2/access') {
return { data: { success: true, data: { allowed: true } } };
}
throw new Error('旧版接口不应被调用');
});
assert.equal(redirect, '/console/my-commission');
assert.deepEqual(calls, ['/api/partner/v2/access']);
});
test('只有旧版伙伴身份时不再回退到旧版伙伴控制台', async () => {
const calls = [];
const redirect = await resolvePartnerPortalRedirect(async (url) => {
calls.push(url);
if (url === '/api/partner/v2/access') {
return { data: { success: true, data: { allowed: false } } };
}
return { data: { success: true } };
});
assert.equal(redirect, null);
assert.deepEqual(calls, ['/api/partner/v2/access']);
});
test('普通登录用户没有伙伴身份时不返回入口地址', async () => {
const redirect = await resolvePartnerPortalRedirect(async () => {
throw new Error('无伙伴身份');
});
assert.equal(redirect, null);
});
test('企业伙伴从公共入口进入企业中心「企业分佣」,个人伙伴进入我的提成', async () => {
const redirectFor = (data) =>
resolvePartnerPortalRedirect(async () => ({
data: { success: true, data },
}));
assert.equal(
await redirectFor({ allowed: true, partner_type: 'company' }),
'/org/commission',
);
assert.equal(
await redirectFor({ allowed: true, partner_type: 'individual' }),
'/console/my-commission',
);
// 旧后端不返回类型时保持原行为
assert.equal(await redirectFor({ allowed: true }), '/console/my-commission');
assert.equal(await redirectFor({ allowed: false }), null);
});
+25 -2
View File
@@ -58,6 +58,7 @@ export default function SettingClaudeModel(props) {
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
'claude.cache_creation_5m_ratio': 1.25,
'claude.cache_creation_1h_ratio': 2,
'claude.cache_creation_default_ttl': '1h',
'claude.cache_ttl_override': 'off',
});
const refForm = useRef();
@@ -226,7 +227,7 @@ export default function SettingClaudeModel(props) {
field={'claude.cache_creation_5m_ratio'}
initValue={''}
extraText={t(
'当前未生效:Claude 模型的全部缓存创建均按 1 小时缓存创建倍率计费',
'仅作用于 Claude 模型,相对输入价格的倍率;上游返回 ephemeral_5m 分档的缓存创建按此倍率计费(官方口径 1.25)',
)}
min={0}
step={0.05}
@@ -244,7 +245,7 @@ export default function SettingClaudeModel(props) {
field={'claude.cache_creation_1h_ratio'}
initValue={''}
extraText={t(
'仅作用于 Claude 模型,相对输入价格的倍率;5 分钟及未区分时长的缓存创建也统一按此倍率计费',
'仅作用于 Claude 模型,相对输入价格的倍率;上游返回 ephemeral_1h 分档的缓存创建按此倍率计费(官方口径 2)',
)}
min={0}
step={0.05}
@@ -256,6 +257,28 @@ export default function SettingClaudeModel(props) {
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
label={t('未分档缓存创建默认档位')}
field={'claude.cache_creation_default_ttl'}
style={{ width: '100%' }}
optionList={[
{ label: t('按 1 小时档计费'), value: '1h' },
{ label: t('按 5 分钟档计费'), value: '5m' },
]}
extraText={t(
'上游只返回缓存创建总量、未给出 5m/1h 拆分时,这部分按哪一档倍率计费。渠道管理里可按渠道单独覆盖,渠道设置优先于此处。',
)}
onChange={(value) =>
setInputs({
...inputs,
'claude.cache_creation_default_ttl': value,
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
label={t('缓存时长强制改写')}
@@ -17,7 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef, useMemo } from 'react';
import React, { useContext, useEffect, useState, useRef, useMemo } from 'react';
import { StatusContext } from '../../../context/Status';
import {
Banner,
Button,
@@ -30,7 +31,13 @@ import {
InputGroup,
Input,
} from '@/components/ui';
import { API, showError, showSuccess, showWarning } from '../../../helpers';
import {
API,
isRoot,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
const API_MAPPING = {
@@ -54,6 +61,7 @@ const DEFAULT_INPUTS = {
DemoSiteEnabled: false,
SelfUseModeEnabled: false,
LanguageSwitchEnabled: true,
CommissionEnabled: true,
CosEnabled: false,
CosSecretId: '',
CosSecretKey: '',
@@ -70,6 +78,7 @@ export default function GeneralSettings(props) {
const [loading, setLoading] = useState(false);
const [showQuotaWarning, setShowQuotaWarning] = useState(false);
const [testingCos, setTestingCos] = useState(false);
const [statusState, statusDispatch] = useContext(StatusContext);
const [inputs, setInputs] = useState(DEFAULT_INPUTS);
const refForm = useRef();
@@ -163,6 +172,24 @@ export default function GeneralSettings(props) {
return showError(t('部分保存失败,请重试'));
}
showSuccess(t('保存成功'));
// 分佣总开关决定侧栏/顶栏的分佣入口,保存成功后同步到全局 status,
// 否则要整页刷新菜单才会跟着变。
const commissionIndex = updateArray.findIndex(
(item) => item.key === 'CommissionEnabled',
);
if (
commissionIndex >= 0 &&
res[commissionIndex]?.data?.success &&
statusState?.status
) {
statusDispatch({
type: 'set',
payload: {
...statusState.status,
commission_enabled: updateArray[commissionIndex].newValue,
},
});
}
// 刷新数据
props.refresh();
})
@@ -405,6 +432,22 @@ export default function GeneralSettings(props) {
onChange={handleFieldChange('LanguageSwitchEnabled')}
/>
</Col>
{/* 分佣总开关仅超级管理员可改(后端未登记到下放清单,默认 root-only) */}
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'CommissionEnabled'}
label={t('启用分佣功能')}
extraText={t(
'关闭后停止全部分佣计提、后台任务与分佣/伙伴接口,不再产生任何分佣相关的数据库读写',
)}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('CommissionEnabled')}
/>
</Col>
)}
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
@@ -333,6 +333,11 @@ export default function SettingsSidebarModulesAdmin(props) {
title: t('监控中心'),
description: t('运行状态和监控面板'),
},
{
key: 'smart-router',
title: t('智能路由'),
description: t('智能路由集合与判定明细'),
},
],
},
{
@@ -76,6 +76,7 @@ export default function SettingsSidebarModulesUser() {
midjourney: isSidebarModuleAllowed('console', 'midjourney'),
task: isSidebarModuleAllowed('console', 'task'),
monitor: isSidebarModuleAllowed('console', 'monitor'),
'smart-router': isSidebarModuleAllowed('console', 'smart-router'),
};
}
+249 -89
View File
@@ -19,7 +19,14 @@ For commercial licensing, please contact support@quantumnous.com
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { createCostRequestGuard } from './costRequestGuard';
import {
Banner,
Button,
@@ -27,7 +34,6 @@ import {
Input,
InputNumber,
Modal,
Popconfirm,
Radio,
RadioGroup,
Select,
@@ -145,6 +151,24 @@ export default function ModelCostSettings() {
const [channels, setChannels] = useState([]);
const [channelsLoading, setChannelsLoading] = useState(false);
const [channelId, setChannelId] = useState('');
const guardRef = useRef(null);
if (!guardRef.current) guardRef.current = createCostRequestGuard();
const guard = guardRef.current;
const context = guard.snapshot();
const [writeBusy, setWriteBusy] = useState(false);
const writeAllowed = guard.canWrite(context);
const discountContext = useRef(null);
const mounted = useRef(false);
const beginWrite = (captured) => {
const ticket = guard.beginWrite(captured);
if (ticket) setWriteBusy(true);
return ticket;
};
const endWrite = (ticket) => {
guard.endWrite(ticket);
if (mounted.current) setWriteBusy(false);
};
const [scopeModels, setScopeModels] = useState([]);
const [official, setOfficial] = useState({});
@@ -203,68 +227,88 @@ export default function ModelCostSettings() {
const total = res.data.data?.total ?? 0;
if (items.length === 0 || all.length >= total) break;
}
if (!mounted.current) return;
setChannels(all);
setChannelId((prev) => {
if (prev) return prev;
if (!guard.snapshot().channel) {
const remembered = localStorage.getItem(CHANNEL_STORAGE_KEY);
if (remembered && all.some((c) => String(c.id) === remembered)) {
return remembered;
}
// 默认落在第一个启用渠道上:进页面即可用,不必先做一次无意义的选择
const first = all.find((c) => c.status === 1) || all[0];
return first ? String(first.id) : '';
});
const next =
remembered && all.some((c) => String(c.id) === remembered)
? remembered
: first
? String(first.id)
: '';
if (guard.select(next)) setChannelId(next);
}
} catch (e) {
showError(t('加载渠道列表失败'));
if (mounted.current) showError(t('加载渠道列表失败'));
} finally {
setChannelsLoading(false);
if (mounted.current) setChannelsLoading(false);
}
}, [t]);
}, [guard, t]);
const load = useCallback(async () => {
if (!channelId) {
setScopeModels([]);
setCostRows([]);
const load = useCallback(
async (channel, ticket = null, { preserveDrafts = false } = {}) => {
if (!mounted.current) return;
const request = guard.beginLoad(channel, ticket);
if (!request) return;
setLoaded(false);
return;
}
setLoading(true);
try {
const params = { scope: 'channel', scope_key: channelId };
// skipErrorHandler:全局拦截器对网络/HTTP 错误直接 showError(error)(英文原文),
// 不跳过会与这里的中文提示双弹
const [sm, rows] = await Promise.all([
API.get('/api/commission/costs/scope_models', {
params,
skipErrorHandler: true,
}),
API.get('/api/commission/costs/', { params, skipErrorHandler: true }),
]);
if (!sm.data.success) {
showError(sm.data.message || t('加载渠道模型清单失败'));
return;
setLoading(true);
if (!preserveDrafts) setAdvanced(null);
setHistoryModel(null);
setDiscountVisible(false);
try {
const params = { scope: 'channel', scope_key: channel };
// skipErrorHandler:全局拦截器对网络/HTTP 错误直接 showError(error)(英文原文),
// 不跳过会与这里的中文提示双弹
const [sm, rows] = await Promise.all([
API.get('/api/commission/costs/scope_models', {
params,
skipErrorHandler: true,
}),
API.get('/api/commission/costs/', { params, skipErrorHandler: true }),
]);
if (!guard.isCurrent(request)) return;
if (!sm.data.success) {
showError(sm.data.message || t('加载渠道模型清单失败'));
return;
}
if (!rows.data.success) {
showError(rows.data.message || t('加载成本配置失败'));
return;
}
setScopeModels(sm.data.data?.models || []);
setOfficial(sm.data.data?.official || {});
setLegacyCount(sm.data.data?.legacy_non_channel || 0);
setCostRows(rows.data.data || []);
setNowTs(Math.floor(Date.now() / 1000));
if (!preserveDrafts) {
setEdits({});
setDrafts({});
setErrors({});
}
setSelectedRowKeys([]);
setSnapshotTick((v) => v + 1);
guard.completeLoad(request);
setLoaded(true);
return { context: request, rows: rows.data.data || [] };
} catch (e) {
if (!guard.isCurrent(request)) return;
const message = e?.response?.data?.message;
showError(
e?.response?.status === 410 &&
typeof message === 'string' &&
message.trim()
? message
: t('加载成本配置失败,请重试'),
);
} finally {
if (guard.isCurrent(request)) setLoading(false);
}
if (!rows.data.success) {
showError(rows.data.message || t('加载成本配置失败'));
return;
}
setScopeModels(sm.data.data?.models || []);
setOfficial(sm.data.data?.official || {});
setLegacyCount(sm.data.data?.legacy_non_channel || 0);
setCostRows(rows.data.data || []);
setNowTs(Math.floor(Date.now() / 1000));
setEdits({});
setDrafts({});
setErrors({});
setSelectedRowKeys([]);
setSnapshotTick((v) => v + 1);
setLoaded(true);
} catch (e) {
showError(t('加载成本配置失败,请重试'));
} finally {
setLoading(false);
}
}, [channelId, t]);
},
[guard, t],
);
const loadUncovered = useCallback(async () => {
try {
@@ -272,7 +316,7 @@ export default function ModelCostSettings() {
params: { limit: 200 },
skipErrorHandler: true,
});
if (res.data.success) {
if (mounted.current && res.data.success) {
setUncoveredTotal(res.data.data.total || 0);
setUncoveredItems(res.data.data.items || []);
}
@@ -282,13 +326,18 @@ export default function ModelCostSettings() {
}, []);
useEffect(() => {
mounted.current = true;
loadChannels();
loadUncovered();
}, [loadChannels, loadUncovered]);
return () => {
mounted.current = false;
guard.invalidate();
};
}, [guard, loadChannels, loadUncovered]);
useEffect(() => {
load();
}, [load]);
load(channelId);
}, [channelId, load]);
useEffect(() => {
if (channelId) localStorage.setItem(CHANNEL_STORAGE_KEY, channelId);
@@ -296,15 +345,16 @@ export default function ModelCostSettings() {
// 有未保存修改时离开页面给出浏览器级确认
const dirtyKeys = useMemo(() => Object.keys(edits), [edits]);
const unsavedCount = new Set([...dirtyKeys, ...Object.keys(errors)]).size;
useEffect(() => {
if (dirtyKeys.length === 0) return undefined;
if (unsavedCount === 0) return undefined;
const handler = (e) => {
e.preventDefault();
e.returnValue = '';
};
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [dirtyKeys.length]);
}, [unsavedCount]);
// --------------------------------------------------------------------------
// 视图模型:一行 = 一个模型
@@ -514,6 +564,7 @@ export default function ModelCostSettings() {
// --------------------------------------------------------------------------
const updateSlot = (row, slotKey, value) => {
if (!guard.canWrite(context)) return;
const fk = fieldKeyOf(row.model_name, slotKey);
const cur = row.effective.get(slotKey);
const savedYuan = cur ? cur.cost_uyuan_per_unit / UYUAN_PER_YUAN : null;
@@ -559,6 +610,7 @@ export default function ModelCostSettings() {
};
const resetEdits = () => {
if (guard.isBusy()) return;
setEdits({});
setDrafts({});
setErrors({});
@@ -567,20 +619,55 @@ export default function ModelCostSettings() {
// 切渠道会整份重载,行内未保存的改价会被无声丢弃——切之前必须问一句
const switchChannel = (id) => {
const next = id || '';
const next = id ? String(id) : '';
if (guard.isBusy()) return;
if (next === channelId) return;
if (Object.keys(edits).length === 0) {
const applySwitch = () => {
if (!guard.isCurrent(context) || !guard.select(next)) return;
setScopeModels([]);
setOfficial({});
setLegacyCount(0);
setCostRows([]);
setLoaded(false);
setLoading(false);
resetEdits();
setSelectedRowKeys([]);
setAdvanced(null);
setHistoryModel(null);
setDiscountVisible(false);
setEffectiveFrom(null);
setChannelId(next);
};
if (unsavedCount === 0) {
applySwitch();
return;
}
Modal.confirm({
title: t('切换渠道将丢弃未保存的修改'),
content: t('当前有 {{count}} 项成本价改动尚未保存,切换渠道后将丢失。', {
count: Object.keys(edits).length,
count: unsavedCount,
}),
okText: t('放弃修改并切换'),
cancelText: t('留在当前渠道'),
onOk: () => setChannelId(next),
onOk: applySwitch,
});
};
const refresh = () => {
if (guard.isBusy() || !channelId || loading) return;
const reload = () => {
if (guard.isCurrent(context) && !guard.isBusy())
return load(context.channel);
};
if (!unsavedCount) return reload();
Modal.confirm({
title: t('刷新将丢弃未保存的修改'),
content: t('当前有 {{count}} 项成本价改动尚未保存。', {
count: unsavedCount,
}),
okText: t('放弃修改并刷新'),
cancelText: t('取消'),
onOk: reload,
});
};
@@ -613,6 +700,7 @@ export default function ModelCostSettings() {
const dirty = pending.items.length > 0 || pending.deleteIds.length > 0;
const doSave = async () => {
if (!guard.canWrite(context)) return;
if (errorCount > 0) {
showError(t('存在非法输入,请先修正标红的价格'));
return;
@@ -634,6 +722,8 @@ export default function ModelCostSettings() {
const from = effectiveFrom
? Math.floor(new Date(effectiveFrom).getTime() / 1000)
: 0;
const ticket = beginWrite(context);
if (!ticket) return;
setSaving(true);
try {
let ok = true;
@@ -642,7 +732,7 @@ export default function ModelCostSettings() {
'/api/commission/costs/apply',
{
scope: 'channel',
scope_key: channelId,
scope_key: ticket.channel,
effective_from: from,
mode: 'new_version',
items: pending.items,
@@ -689,17 +779,19 @@ export default function ModelCostSettings() {
showError(res.data?.message || t('删除失败'));
}
}
await load();
await load(ticket.channel, ticket);
if (ok) await loadUncovered();
} catch (e) {
showError(t('保存失败,请重试'));
await load();
await load(ticket.channel, ticket);
} finally {
endWrite(ticket);
setSaving(false);
}
};
const onSave = () => {
if (!guard.canWrite(context)) return;
if (pending.deleteIds.length === 0) {
doSave();
return;
@@ -737,6 +829,8 @@ export default function ModelCostSettings() {
);
const runDiscount = async () => {
const captured = discountContext.current;
if (!guard.canWrite(context) || !guard.canWrite(captured)) return;
const d = discount === '' ? NaN : Number(discount);
if (!Number.isFinite(d) || d <= 0 || d > 1) {
showError(t('折扣必须在 (0,1] 区间'));
@@ -746,20 +840,22 @@ export default function ModelCostSettings() {
showError(t('没有可应用的模型'));
return;
}
if (dirty) {
if (unsavedCount > 0) {
showError(t('请先保存或撤销行内的未保存修改,再执行批量折扣'));
return;
}
const from = effectiveFrom
? Math.floor(new Date(effectiveFrom).getTime() / 1000)
: 0;
const ticket = beginWrite(captured);
if (!ticket) return;
setDiscountRunning(true);
try {
const res = await API.post(
'/api/commission/costs/generate',
{
scope: 'channel',
scope_key: channelId,
scope_key: ticket.channel,
discount: d,
effective_from: from,
mode: discountMode,
@@ -799,7 +895,6 @@ export default function ModelCostSettings() {
);
}
setDiscountVisible(false);
await load();
await loadUncovered();
} else {
showError(res.data?.message || t('批量应用失败'));
@@ -807,6 +902,8 @@ export default function ModelCostSettings() {
} catch (e) {
showError(t('批量应用失败,请重试'));
} finally {
await load(ticket.channel, ticket);
endWrite(ticket);
setDiscountRunning(false);
}
};
@@ -817,6 +914,7 @@ export default function ModelCostSettings() {
const submitAdvanced = async () => {
const a = advanced;
if (!a || !guard.canWrite(a.context)) return;
const yuanNum = a.yuan === '' ? NaN : Number(a.yuan);
const uyuan = Number.isFinite(yuanNum)
? Math.round(yuanNum * UYUAN_PER_YUAN)
@@ -837,7 +935,10 @@ export default function ModelCostSettings() {
showError(t('失效时间必须晚于生效时间'));
return;
}
const ticket = beginWrite(a.context);
if (!ticket) return;
setAdvancedSaving(true);
let succeeded = false;
try {
// 整行回传(保留 created_at / created_by 等原字段),仅覆盖界面上可改的字段
const res = await API.put(
@@ -854,9 +955,9 @@ export default function ModelCostSettings() {
{ skipErrorHandler: true },
);
if (res.data?.success) {
succeeded = true;
showSuccess(t('保存成功'));
setAdvanced(null);
await load();
} else {
const fails = res.data?.data?.failures || [];
showError(
@@ -869,24 +970,52 @@ export default function ModelCostSettings() {
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
const refreshed = await load(ticket.channel, ticket, {
preserveDrafts: !succeeded,
});
if (!succeeded && refreshed) {
// Keep the user's failed edit, but only allow retry against the row
// returned by the new snapshot. A removed row must not be resurrected.
const base = refreshed.rows.find((row) => row.id === a.base.id);
setAdvanced((current) => {
if (!current || current.context !== a.context) return current;
return base ? { ...current, base, context: refreshed.context } : null;
});
}
endWrite(ticket);
setAdvancedSaving(false);
}
};
const deleteRow = async (id) => {
const deleteRow = async (id, captured) => {
const ticket = beginWrite(captured);
if (!ticket) return;
let succeeded = false;
try {
const res = await API.delete(`/api/commission/costs/${id}`, {
skipErrorHandler: true,
});
if (res.data?.success) {
succeeded = true;
showSuccess(t('已删除'));
await load();
} else showError(res.data?.message || t('删除失败'));
} catch (e) {
showError(t('删除失败,请重试'));
} finally {
await load(ticket.channel, ticket, { preserveDrafts: !succeeded });
endWrite(ticket);
}
};
const confirmDelete = (id) => {
if (!guard.canWrite(context)) return;
Modal.confirm({
title: t('确认删除该价格版本?'),
content: t('删除后该区间的消耗将退回「官方牌价 × 兜底折扣」预估'),
onOk: () => deleteRow(id, context),
});
};
// --------------------------------------------------------------------------
// 渲染片段
// --------------------------------------------------------------------------
@@ -1049,6 +1178,7 @@ export default function ModelCostSettings() {
return (
<div key={k}>
<InputNumber
disabled={!writeAllowed}
prefix='¥'
suffix={
<span className='text-xs text-gray-400'>
@@ -1304,7 +1434,10 @@ export default function ModelCostSettings() {
{t('版本')}({historyCount(row)})
</Button>
<Button
disabled={!row.slots.some((k) => isPositive(slotValue(row, k)))}
disabled={
!writeAllowed ||
!row.slots.some((k) => isPositive(slotValue(row, k)))
}
onClick={() => clearModel(row)}
type='link'
size='small'
@@ -1362,6 +1495,16 @@ export default function ModelCostSettings() {
/>
)}
{!loaded && !loading && rows.length > 0 && (
<Banner
type='warning'
closeIcon={null}
description={t(
'当前展示上次加载的数据,暂不能修改成本配置,请刷新成功后重试。',
)}
/>
)}
{orphanRows.length > 0 && (
<Banner
type='warning'
@@ -1390,6 +1533,7 @@ export default function ModelCostSettings() {
onChange={(v) => switchChannel(v || '')}
optionList={channelOptions}
loading={channelsLoading}
disabled={writeBusy}
placeholder={t('选择要维护成本价的渠道')}
style={{ width: 320 }}
/>
@@ -1460,20 +1604,33 @@ export default function ModelCostSettings() {
{t('全站未配置成本')}: {uncoveredTotal}
</Button>
)}
<Button onClick={load} loading={loading} disabled={!channelId}>
<Button
onClick={refresh}
loading={loading}
disabled={!channelId || writeBusy || loading}
>
{t('刷新')}
</Button>
<Button
type='secondary'
disabled={!channelId || rows.length === 0}
onClick={() => setDiscountVisible(true)}
disabled={!writeAllowed || rows.length === 0}
onClick={() => {
if (!guard.canWrite(context)) return;
discountContext.current = context;
setDiscountVisible(true);
}}
>
{t('按官方价折扣批量定价')}
</Button>
{/* errorCount 也要放行:只剩非法输入时 dirty 为 false,
不给撤销入口的话满屏标红既存不下也清不掉,只能逐个手动删 */}
{(dirty || errorCount > 0) && (
<Button theme='borderless' type='tertiary' onClick={resetEdits}>
<Button
theme='borderless'
type='tertiary'
onClick={resetEdits}
disabled={writeBusy || loading}
>
{t('撤销修改')}
</Button>
)}
@@ -1481,7 +1638,7 @@ export default function ModelCostSettings() {
theme='solid'
type='primary'
loading={saving}
disabled={!dirty || errorCount > 0}
disabled={!writeAllowed || !dirty || errorCount > 0}
onClick={onSave}
>
{t('保存成本价')}
@@ -1497,6 +1654,7 @@ export default function ModelCostSettings() {
<DatePicker
type='dateTime'
value={effectiveFrom}
disabled={!writeAllowed}
onChange={(d) => setEffectiveFrom(d || null)}
showClear
placeholder={t('立即生效')}
@@ -1563,6 +1721,7 @@ export default function ModelCostSettings() {
visible={discountVisible}
onOk={runDiscount}
confirmLoading={discountRunning}
okButtonProps={{ disabled: !writeAllowed }}
onCancel={() => setDiscountVisible(false)}
width={560}
>
@@ -1712,8 +1871,10 @@ export default function ModelCostSettings() {
render: (_, r) => (
<Space>
<Button
disabled={!writeAllowed}
onClick={() =>
setAdvanced({
context,
base: r,
yuan: r.cost_uyuan_per_unit / UYUAN_PER_YUAN,
effective_from: tsToDate(r.effective_from),
@@ -1726,17 +1887,15 @@ export default function ModelCostSettings() {
>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该价格版本?')}
content={t(
'删除后该区间的消耗将退回「官方牌价 × 兜底折扣」预估',
)}
onConfirm={() => deleteRow(r.id)}
<Button
type='link'
size='small'
danger
disabled={!writeAllowed}
onClick={() => confirmDelete(r.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
{t('删除')}
</Button>
</Space>
),
},
@@ -1754,6 +1913,7 @@ export default function ModelCostSettings() {
visible={!!advanced}
onOk={submitAdvanced}
confirmLoading={advancedSaving}
okButtonProps={{ disabled: !writeAllowed }}
onCancel={() => setAdvanced(null)}
width={460}
>
@@ -0,0 +1,68 @@
/*
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
*/
// Synchronous ownership checks also protect callbacks retained by confirmation
// dialogs, before React has rendered disabled controls.
export function createCostRequestGuard() {
let channel = '';
let sequence = 0;
let ready = false;
let writer = null;
const snapshot = () => ({ channel, sequence });
const isCurrent = (context) =>
!!context && context.channel === channel && context.sequence === sequence;
const canWrite = (context) =>
Boolean(channel) && ready && !writer && isCurrent(context);
return {
snapshot,
isCurrent,
canWrite,
isBusy: () => writer !== null,
invalidate() {
sequence++;
ready = false;
},
select(next) {
if (writer) return false;
channel = next;
this.invalidate();
return true;
},
beginLoad(selected, owner = null) {
if (!selected || selected !== channel || (writer && owner !== writer)) {
return null;
}
this.invalidate();
return snapshot();
},
completeLoad(context) {
if (!isCurrent(context)) return false;
ready = true;
return true;
},
beginWrite(context) {
if (!canWrite(context)) return null;
writer = { ...context };
return writer;
},
endWrite(owner) {
if (writer === owner) writer = null;
},
};
}
@@ -0,0 +1,89 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import { createCostRequestGuard } from './costRequestGuard.js';
const ready = (guard, channel) => {
guard.select(channel);
const request = guard.beginLoad(channel);
guard.completeLoad(request);
return request;
};
test('failed channel load cannot reuse previous prices or confirmations', () => {
const guard = createCostRequestGuard();
const a = ready(guard, 'A');
guard.select('B');
const b = guard.beginLoad('B');
assert.equal(guard.completeLoad(a), false);
assert.equal(guard.beginWrite(a), null);
assert.equal(guard.beginWrite(b), null);
assert.equal(guard.completeLoad(b), true);
assert.ok(guard.beginWrite(b));
});
test('same-channel refresh invalidates old confirmation even after success', () => {
const guard = createCostRequestGuard();
const previous = ready(guard, 'A');
const latest = guard.beginLoad('A');
assert.equal(guard.canWrite(previous), false);
assert.equal(guard.completeLoad(previous), false);
guard.completeLoad(latest);
assert.equal(guard.beginWrite(previous), null);
assert.ok(guard.beginWrite(latest));
});
test('all writers share a synchronous lock held through internal reload', () => {
const guard = createCostRequestGuard();
const context = ready(guard, 'A');
const writer = guard.beginWrite(context);
assert.ok(writer);
assert.equal(guard.beginWrite(context), null);
assert.equal(guard.select('B'), false);
assert.equal(guard.beginLoad('A'), null);
const reload = guard.beginLoad('A', writer);
assert.ok(reload);
guard.completeLoad(reload);
assert.equal(guard.canWrite(reload), false);
guard.endWrite({});
assert.equal(guard.canWrite(reload), false);
guard.endWrite(writer);
assert.equal(guard.canWrite(reload), true);
});
test('failed internal reload stays read-only after writer releases lock', () => {
const guard = createCostRequestGuard();
const writer = guard.beginWrite(ready(guard, 'A'));
const failed = guard.beginLoad('A', writer);
guard.endWrite(writer);
assert.equal(guard.canWrite(failed), false);
});
test('clear selection and unmount invalidate late callbacks', () => {
const guard = createCostRequestGuard();
const a = ready(guard, 'A');
guard.select('');
assert.equal(guard.beginLoad(''), null);
assert.equal(guard.beginWrite(a), null);
const next = ready(guard, 'A');
guard.invalidate();
assert.equal(guard.isCurrent(next), false);
assert.equal(guard.completeLoad(next), false);
});
@@ -480,7 +480,7 @@ const SettingsWeyAiContentEditor = ({
<DatePicker
type='dateTime'
value={toDate(form.start_at)}
onChange={(_, d) => set('start_at', toSec(d))}
onChange={(d) => set('start_at', toSec(d))}
placeholder={t('不限')}
/>
</div>
@@ -489,7 +489,7 @@ const SettingsWeyAiContentEditor = ({
<DatePicker
type='dateTime'
value={toDate(form.end_at)}
onChange={(_, d) => set('end_at', toSec(d))}
onChange={(d) => set('end_at', toSec(d))}
placeholder={t('不限')}
/>
</div>
@@ -308,7 +308,7 @@ const SettingsWeyAiReleaseNotes = () => {
? new Date(draft.released_at * 1000)
: undefined
}
onChange={(_, date) =>
onChange={(date) =>
setDraft({
...draft,
// Local noon: the same calendar day in every time zone within ±12 h.
+111
View File
@@ -0,0 +1,111 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
ConsoleCard,
ConsoleTabs,
} from '../../components/console/ConsolePrimitives';
import ProfileTable from '../../components/smart-router/ProfileTable';
import ConsentPanel from '../../components/smart-router/ConsentPanel';
import DecisionTable from '../../components/smart-router/DecisionTable';
import GlobalSettings from '../../components/smart-router/GlobalSettings';
import { isAdmin, isRoot } from '../../helpers';
import '../../components/smart-router/smart-router.css';
// 智能模型路由控制台页(docs/04-渠道与路由/19-智能模型路由方案.md §十二)。
// 页头、顶栏让位与内边距由 ConsolePageContainer 统一(CONSOLE_SPEC §1),页面不再自绘背景。
const SmartRouterPage = () => {
const { t } = useTranslation();
const admin = isAdmin();
const root = isRoot();
const [tab, setTab] = useState(() => {
try {
return localStorage.getItem('smart_router_tab') || 'mine';
} catch (e) {
return 'mine';
}
});
const onTab = (k) => {
setTab(k);
try {
localStorage.setItem('smart_router_tab', k);
} catch (e) {
/* 浏览器存储不可用时忽略 */
}
};
const tabs = useMemo(() => {
const list = [
{ key: 'mine', title: t('我的集合') },
{ key: 'consent', title: t('数据出境授权') },
{ key: 'decisions', title: t('判定明细') },
];
if (admin) {
list.push({ key: 'system', title: t('平台集合') });
list.push({ key: 'all-decisions', title: t('全部判定明细') });
}
if (root) list.push({ key: 'settings', title: t('全局设置') });
return list;
}, [admin, root, t]);
const activeKey = tabs.some((x) => x.key === tab) ? tab : 'mine';
return (
<div className='smart-router-page'>
<div className='smart-router-hero'>
<div className='smart-router-eyebrow'>{t('Smart Router')}</div>
<h1>{t('智能路由')}</h1>
<p>
{t(
'一个虚拟模型名背后挂多个候选模型,按请求自动选择合适的模型。调用时把模型名写成 router/短名 即可。',
)}
</p>
</div>
<ConsoleCard>
<ConsoleTabs
activeKey={activeKey}
onChange={onTab}
items={tabs.map((x) => ({ key: x.key, label: x.title }))}
/>
<div>
{activeKey === 'mine' && (
<ProfileTable
mode='personal'
emptyHint={t('个人集合只对你自己的令牌和 Playground 生效。')}
/>
)}
{activeKey === 'consent' && <ConsentPanel mode='personal' />}
{activeKey === 'decisions' && <DecisionTable mode='personal' />}
{activeKey === 'system' && (
<ProfileTable
mode='admin'
emptyHint={t(
'平台集合对所有用户可用;修改候选会影响所有引用它的令牌,并写入审计日志。',
)}
/>
)}
{activeKey === 'all-decisions' && <DecisionTable mode='admin' />}
{activeKey === 'settings' && <GlobalSettings />}
</div>
</ConsoleCard>
</div>
);
};
export default SmartRouterPage;
+5 -5
View File
@@ -19,7 +19,6 @@ For commercial licensing, please contact support@quantumnous.com
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useState, useContext, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
@@ -47,6 +46,7 @@ import {
} from '@/components/ui/icons';
import { StatusContext } from '../../context/Status';
import { DEFAULT_LOGIN_REDIRECT } from '../../helpers/data';
import { copy } from '../../helpers';
import { isMiniProgramWebView } from '../../helpers/miniProgram';
import VideoTutorial from './components/VideoTutorial';
import './styles.css';
@@ -114,14 +114,14 @@ const Tutorial = () => {
},
];
// 复制代码
// 复制代码:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
// 裸调只会报错而复制不到,公共 copy 带 execCommand 降级
const copyCode = async (code, index) => {
try {
await writeClipboardText(code);
if (await copy(code)) {
setCopiedIndex(index);
Toast.success(t('已复制到剪贴板'));
setTimeout(() => setCopiedIndex(null), 2000);
} catch (err) {
} else {
Toast.error(t('复制失败'));
}
};
+1
View File
@@ -202,6 +202,7 @@ const Invite = () => {
showError(t('邀请链接获取中,请稍后'));
return;
}
// 按实际结果提示(此前调用未处理结果,点击后无任何反馈)
if (await copy(affLink)) showSuccess(t('邀请链接已复制到剪切板'));
else showError(t('复制失败,请手动复制'));
};
+1 -1
View File
@@ -151,7 +151,7 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
placeholder='请选择发布日期'
style={{ width: '100%' }}
value={draft.date || undefined}
onChange={(value) => change('date', value)}
onChange={(_, value) => change('date', value)}
/>,
true,
)}