Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+361
View File
@@ -0,0 +1,361 @@
/*
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, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Select,
Switch,
TabPane,
Tabs,
Tag,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import './org-experts.css';
const { Title, Paragraph, Text } = Typography;
const AUDIT_PAGE_SIZE = 30;
const OrgAgentAudit = ({ orgId, canAuditContent, canManagePolicy }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [runs, setRuns] = useState([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [cases, setCases] = useState([]);
const [policies, setPolicies] = useState({});
const [retention, setRetention] = useState({
hot_days: 90,
archive_enabled: true,
});
const [status, setStatus] = useState('');
const [reason, setReason] = useState('');
const [selected, setSelected] = useState(null);
const [confirmRun, setConfirmRun] = useState(null);
const [inspecting, setInspecting] = useState(false);
const load = useCallback(async () => {
const [runResponse, caseResponse, policyResponse, retentionResponse] =
await Promise.all([
API.get('/api/org/agent-audit/runs', {
headers,
params: { status, page, page_size: AUDIT_PAGE_SIZE },
}),
API.get('/api/org/agent-audit/reconciliation', { headers }),
API.get('/api/org/agent-audit/policies', { headers }),
API.get('/api/org/agent-audit/retention', { headers }),
]);
if (runResponse.data?.success) {
setRuns(runResponse.data.data || []);
setTotal(runResponse.data.total || 0);
}
if (caseResponse.data?.success) setCases(caseResponse.data.data || []);
if (policyResponse.data?.success)
setPolicies(policyResponse.data.data || {});
if (retentionResponse.data?.success)
setRetention((current) => retentionResponse.data.data || current);
}, [headers, page, status]);
useEffect(() => {
// The interceptor already toasts HTTP failures; swallow the rejection so
// it does not surface as an unhandled promise error.
load().catch(() => {});
}, [load]);
const requestInspect = (run) => {
if (!canAuditContent) return;
const length = reason.trim().length;
if (length < 4 || length > 500) {
Toast.warning(t('审计原因需为 4 到 500 个字符'));
return;
}
// A real confirmation step: the request is only sent after the auditor
// explicitly confirms in the dialog below.
setConfirmRun(run);
};
const inspect = async () => {
if (!confirmRun) return;
setInspecting(true);
try {
// Reason travels in the POST body: browsers reject non-Latin-1 header
// values, so a Chinese reason can never be sent as a request header.
const response = await API.post(
`/api/org/agent-audit/runs/${confirmRun.id}/content`,
{ reason: reason.trim(), confirm: true },
{ headers, skipErrorHandler: true },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('读取审计正文失败'));
return;
}
setSelected(response.data.data);
setConfirmRun(null);
} catch (error) {
Toast.error(
error?.response?.data?.message ||
error?.message ||
t('读取审计正文失败'),
);
} finally {
setInspecting(false);
}
};
const saveRetention = async () => {
try {
const response = await API.put(
'/api/org/agent-audit/retention',
{
hot_days: Number(retention.hot_days),
archive_enabled: !!retention.archive_enabled,
},
{ headers, skipErrorHandler: true },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('保留策略保存失败'));
return;
}
setRetention(response.data.data);
Toast.success(t('保留策略已保存'));
} catch (error) {
Toast.error(
error?.response?.data?.message ||
error?.message ||
t('保留策略保存失败'),
);
}
};
const pageCount = Math.max(1, Math.ceil(total / AUDIT_PAGE_SIZE));
return (
<main className='org-expert-page'>
<header className='org-audit-hero'>
<div>
<Title heading={3}>{t('Agent 任务审计')}</Title>
<Paragraph>
{t(
'元数据默认可见;正文访问需要独立权限、明确原因、二次确认与水印。',
)}
</Paragraph>
</div>
<Select
value={status}
onChange={(value) => {
setPage(1);
setStatus(value);
}}
optionList={[
{ value: '', label: t('全部状态') },
{ value: 'succeeded', label: t('已完成') },
{
value: 'completed_with_warnings',
label: t('完成但有警告'),
},
{ value: 'failed', label: t('失败') },
{ value: 'cancelled', label: t('已取消') },
]}
/>
</header>
<Tabs type='line'>
<TabPane tab={`${t('任务元数据')} · ${total}`} itemKey='runs'>
{canAuditContent && (
<div className='org-audit-reason'>
<Text>{t('正文审计原因')}</Text>
<Input
value={reason}
onChange={setReason}
placeholder={t('原因将写入不可变审计记录')}
/>
</div>
)}
<section className='org-audit-list'>
{runs.map((run) => (
<article key={run.id}>
<div>
<code>{run.id}</code>
<Tag>{run.status}</Tag>
<Tag
color={
run.billing_status === 'pending_reconciliation'
? 'orange'
: 'green'
}
>
{run.billing_status}
</Tag>
</div>
<div className='org-audit-metrics'>
<span>
{t('专家')} #{run.expert_id}
</span>
<span>
{t('模型')} {run.model_used || '-'}
</span>
<span>
{t('消费')} {run.effective_quota}
</span>
<span>
{t('成员')} #{run.org_member_id}
</span>
</div>
<div className='org-audit-skills'>
{(run.matched_skills || []).map((skill) => (
<Tag key={skill.id}>{skill.match_reason}</Tag>
))}
</div>
{canAuditContent && (
<Button size='small' onClick={() => requestInspect(run)}>
{t('二次确认查看正文')}
</Button>
)}
</article>
))}
</section>
{total > AUDIT_PAGE_SIZE && (
<div className='org-audit-pagination'>
<Button
size='small'
disabled={page <= 1}
onClick={() => setPage((old) => Math.max(1, old - 1))}
>
{t('上一页')}
</Button>
<Text type='tertiary'>
{page} / {pageCount}
</Text>
<Button
size='small'
disabled={page >= pageCount}
onClick={() => setPage((old) => old + 1)}
>
{t('下一页')}
</Button>
</div>
)}
</TabPane>
<TabPane
tab={`${t('待对账')} · ${cases.length}`}
itemKey='reconciliation'
>
<section className='org-audit-list'>
{cases.map((item) => (
<article key={item.id}>
<div>
<code>{item.request_id}</code>
<Tag color='orange'>{item.status}</Tag>
</div>
<Text>
{item.workload_type} / {item.reason}
</Text>
</article>
))}
</section>
</TabPane>
<TabPane tab={t('安全策略')} itemKey='policies'>
<section className='org-policy-grid'>
<article>
<strong>{t('任务保留策略')}</strong>
<Text>{t('热数据保留天数')}</Text>
<InputNumber
min={7}
max={3650}
disabled={!canManagePolicy}
value={retention.hot_days}
onChange={(hot_days) =>
setRetention((current) => ({ ...current, hot_days }))
}
/>
<Switch
disabled={!canManagePolicy}
checked={!!retention.archive_enabled}
onChange={(archive_enabled) =>
setRetention((current) => ({
...current,
archive_enabled,
}))
}
/>
{canManagePolicy && (
<Button size='small' onClick={saveRetention}>
{t('保存保留策略')}
</Button>
)}
</article>
{Object.entries(policies).map(([key, value]) => (
<article key={key}>
<strong>{key}</strong>
<Text>
{typeof value === 'string' ? value : JSON.stringify(value)}
</Text>
</article>
))}
</section>
</TabPane>
</Tabs>
<Modal
title={t('确认查看任务正文')}
visible={!!confirmRun}
onCancel={() => setConfirmRun(null)}
onOk={inspect}
confirmLoading={inspecting}
>
<Paragraph>
{t('此操作将在返回内容前写入不可变审计记录,正文携带你的专属水印。')}
</Paragraph>
<Text type='tertiary'>
{t('任务')}: <code>{confirmRun?.id}</code>
</Text>
<Paragraph>
{t('审计原因')}: {reason.trim()}
</Paragraph>
</Modal>
<Modal
title={t('受保护的任务正文')}
visible={!!selected}
footer={null}
onCancel={() => setSelected(null)}
width={920}
>
{selected && (
<div className='org-audit-content'>
<Tag color='red'>{selected.watermark}</Tag>
<h4>{t('输入')}</h4>
<pre>{selected.input}</pre>
<h4>{t('步骤')}</h4>
{(selected.steps || []).map((step) => (
<pre key={step.id}>{step.output_message}</pre>
))}
<h4>{t('产物')}</h4>
<pre>{selected.artifact?.content}</pre>
</div>
)}
</Modal>
</main>
);
};
export default OrgAgentAudit;
+472
View File
@@ -0,0 +1,472 @@
/*
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 { getQuotaPerUnit } from '../../helpers';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import { RefreshCw, ScrollText } from 'lucide-react';
import {
Table,
Select,
Button,
Tag,
Tooltip,
Tabs,
TabPane,
} from '@douyinfe/semi-ui';
import { API } from '../../helpers/api';
import { useOrgAuditLogs } from '../../hooks/org/useOrgData';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgStateBlock from './components/OrgStateBlock';
import OrgPromptRecords from './OrgPromptRecords';
import {
formatQuotaAsCNY,
isQuotaDetailValue,
isZeroUnlimitedQuotaKey,
} from './orgAuditFormat';
import { parseOrgFeatureFlag } from './orgFeatureFlags';
const tokenStatusMap = {
1: '已启用',
2: '已禁用',
3: '已过期',
4: '已耗尽',
};
const orgStatusMap = {
1: '正常',
2: '冻结',
3: '欠费',
};
const memberStatusMap = {
1: '正常',
2: '禁用',
};
const targetTypeLabels = {
token: '令牌',
member: '成员',
organization: '企业',
invitation: '邀请',
};
const targetTypeColors = {
token: 'violet',
member: 'blue',
organization: 'green',
invitation: 'orange',
};
// 操作分类:颜色 + 标签
const actionConfig = {
create_org: { label: '创建企业', color: 'green' },
update_settings: { label: '更新设置', color: 'blue' },
dissolve_org: { label: '解散企业', color: 'red' },
transfer_ownership: { label: '转让所有权', color: 'orange' },
join_org: { label: '加入企业', color: 'green' },
leave_org: { label: '退出企业', color: 'orange' },
update_quota_alert: { label: '更新配额预警', color: 'blue' },
invite_member: { label: '邀请成员', color: 'green' },
remove_member: { label: '移除成员', color: 'red' },
update_member_role: { label: '更新角色', color: 'blue' },
update_member_quota: { label: '更新配额', color: 'blue' },
update_member_status: { label: '更新状态', color: 'blue' },
update_member_model_limits: { label: '更新模型限制', color: 'blue' },
update_member_admin_permissions: { label: '更新管理员权限', color: 'blue' },
accept_invitation: { label: '接受邀请', color: 'green' },
cancel_invitation: { label: '取消邀请', color: 'grey' },
create_token: { label: '创建令牌', color: 'green' },
update_token: { label: '更新令牌', color: 'blue' },
delete_token: { label: '删除令牌', color: 'red' },
admin_create_org: { label: '管理员创建企业', color: 'cyan' },
admin_update_org: { label: '管理员更新企业', color: 'cyan' },
admin_delete_org: { label: '管理员删除企业', color: 'red' },
// 注:建企业时配的初始额度也写这条 action(供预警取"加额时刻",detail.source=org_create_initial),
// 渲染时按 source 区分,避免审计阅读者把它误读成"建号当天有人又改了一次额度"
admin_adjust_quota: { label: '管理员调整额度', color: 'cyan' },
org_alert_mute: { label: '屏蔽预警通知', color: 'grey' },
org_alert_unmute: { label: '恢复预警通知', color: 'green' },
admin_update_status: { label: '管理员更新状态', color: 'cyan' },
};
const detailKeyLabels = {
name: '名称',
code: '邀请码',
status: '状态',
unlimited_quota: '无限额度',
remain_quota: '剩余额度',
quota_limit: '额度上限',
email: '邮箱',
role: '角色',
from: '原值',
to: '新值',
member_id: '成员ID',
method: '方式',
model_limits_enabled: '模型限制',
model_limits: '可用模型',
threshold: '预警阈值',
owner: '所有者',
amount: '调整额度',
org_name: '企业名称',
before_quota: '调整前额度',
expired_time: '过期时间',
allow_ips: 'IP白名单',
group: '分组',
max_members: '最大成员数',
max_tokens: '最大令牌数',
default_member_quota: '新成员默认额度上限',
cycle_quota: '周期额度',
cycle_quota_delta: '周期额度增量',
quota_period: '配额周期',
};
// 根据 action 上下文选择正确的 status 映射
function getStatusLabel(action, value) {
if (
action.startsWith('admin_') ||
action === 'create_org' ||
action === 'dissolve_org'
) {
return orgStatusMap[value];
}
if (action.includes('member')) {
return memberStatusMap[value];
}
return tokenStatusMap[value];
}
function formatDetailValue(action, key, value, t, quotaPerUnit) {
if (isQuotaDetailValue(action, key)) {
// 保留旧行为:空字符串表示「已清除」,不能落进 Number('')===0 → ¥0.00
if (typeof value === 'string' && value === '') {
return t('已清除');
}
// 上限类字段 0 = 不限制(后端 QuotaLimit <= 0 跳过限额),显示 ¥0.00 会误导为零额度
if (Number(value) === 0 && isZeroUnlimitedQuotaKey(key)) {
return t('不限制');
}
return formatQuotaAsCNY(value, quotaPerUnit);
}
if (key === 'status') {
const label = getStatusLabel(action, value);
return label ? t(label) : String(value);
}
if (key === 'unlimited_quota' || key === 'model_limits_enabled') {
return value ? t('是') : t('否');
}
if (key === 'expired_time') {
if (value === -1) return t('永不过期');
return timestamp2string(value);
}
if (typeof value === 'string' && value === '') {
return t('已清除');
}
return String(value);
}
function formatDetail(action, obj, t, quotaPerUnit) {
if (!obj) return '-';
const parts = [];
Object.entries(obj).forEach(([k, v]) => {
if (v === null || v === undefined) return;
const label = t(detailKeyLabels[k] || k);
parts.push(label + ': ' + formatDetailValue(action, k, v, t, quotaPerUnit));
});
return parts.length > 0 ? parts.join(', ') : '-';
}
function formatRelativeTime(timestamp, t) {
if (!timestamp) return '-';
const now = Date.now();
const diff = now - timestamp * 1000;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) return t('刚刚');
if (minutes < 60) return minutes + t('分钟前');
if (hours < 24) return hours + t('小时前');
if (days < 30) return days + t('天前');
return new Date(timestamp * 1000).toLocaleDateString();
}
const OrgAudit = ({ orgId }) => {
const { t } = useTranslation();
const quotaPerUnit = getQuotaPerUnit();
const { logs, total, loading, fetch } = useOrgAuditLogs(orgId);
const [page, setPage] = useState(1);
const [actionFilter, setActionFilter] = useState('');
const [activeTab, setActiveTab] = useState('operations');
// 提示词记录 tab 由企业 feature flag(prompt_archive)控制显隐
const [promptArchiveEnabled, setPromptArchiveEnabled] = useState(false);
// 且需当前用户具备查看权限(owner 恒真;admin 需 owner 授予),与后端 RequireOrgAdminPermission 对齐
const [canViewPromptRecords, setCanViewPromptRecords] = useState(false);
useEffect(() => {
fetch(page, 20, actionFilter);
}, [fetch, page, actionFilter]);
useEffect(() => {
if (!orgId) return;
let cancelled = false;
// 切换企业先隐藏,避免上一企业的 flag/权限残留
setPromptArchiveEnabled(false);
setCanViewPromptRecords(false);
// 两个判断相互独立:feature flag 与个人权限各自 try,一个失败不牵连另一个(避免整块 tab 误隐)
(async () => {
try {
const res = await API.get('/api/org/info', {
headers: { 'X-Org-Id': String(orgId) },
});
const flags = res.data?.data?.organization?.feature_flags;
// 解析语义必须与后端 RequireOrgFeature 一致,否则 tab 显隐与接口放行口径割裂
if (!cancelled)
setPromptArchiveEnabled(parseOrgFeatureFlag(flags, 'prompt_archive'));
} catch {
// 忽略:无 flag 时不展示提示词 tab
}
})();
(async () => {
try {
const res = await API.get('/api/org/me/summary', {
headers: { 'X-Org-Id': String(orgId) },
});
// 与后端 RequireOrgAdminPermission 对齐:owner 恒真,admin 依 owner 授予
if (!cancelled)
setCanViewPromptRecords(
!!res.data?.data?.member?.can_view_prompt_records,
);
} catch {
// 忽略:拉取失败时按无权限处理(fail-closed)
}
})();
return () => {
cancelled = true;
};
}, [orgId]);
const actionOptions = [
{ value: '', label: t('全部操作') },
// 企业操作
{ value: 'create_org', label: t('创建企业') },
{ value: 'update_settings', label: t('更新设置') },
{ value: 'transfer_ownership', label: t('转让所有权') },
{ value: 'update_quota_alert', label: t('更新配额预警') },
{ value: 'dissolve_org', label: t('解散企业') },
// 成员操作
{ value: 'invite_member', label: t('邀请成员') },
{ value: 'accept_invitation', label: t('接受邀请') },
{ value: 'cancel_invitation', label: t('取消邀请') },
{ value: 'join_org', label: t('加入企业') },
{ value: 'leave_org', label: t('退出企业') },
{ value: 'remove_member', label: t('移除成员') },
{ value: 'update_member_role', label: t('更新角色') },
{ value: 'update_member_quota', label: t('更新配额') },
{ value: 'update_member_status', label: t('更新状态') },
{ value: 'update_member_model_limits', label: t('更新模型限制') },
{ value: 'update_member_admin_permissions', label: t('更新管理员权限') },
// 令牌操作
{ value: 'create_token', label: t('创建令牌') },
{ value: 'update_token', label: t('更新令牌') },
{ value: 'delete_token', label: t('删除令牌') },
// 管理员操作
{ value: 'admin_create_org', label: t('管理员创建企业') },
{ value: 'admin_update_org', label: t('管理员更新企业') },
{ value: 'admin_delete_org', label: t('管理员删除企业') },
{ value: 'admin_adjust_quota', label: t('管理员调整额度') },
{ value: 'admin_update_status', label: t('管理员更新状态') },
];
const columns = [
{
title: t('操作者'),
dataIndex: 'operator_name',
width: 120,
render: (name, record) => (
<span className='text-sm text-gray-700 dark:text-gray-300 truncate'>
{name || `User#${record.operator_id}`}
</span>
),
},
{
title: t('操作'),
dataIndex: 'action',
width: 170,
render: (action, record) => {
const config = actionConfig[action];
if (!config) return <Tag size='small'>{action}</Tag>;
// 建企业时配的初始额度复用 admin_adjust_quota(供预警取"加额时刻"),
// 但它不是二次人工调额,按 detail.source 区分展示
let label = config.label;
if (action === 'admin_adjust_quota') {
try {
const detail = record?.detail ? JSON.parse(record.detail) : null;
if (detail?.source === 'org_create_initial') {
label = '建企业初始额度';
}
} catch {
// detail 非 JSON 时按默认标签展示
}
}
return (
<Tag size='small' color={config.color} type='light'>
{t(label)}
</Tag>
);
},
},
{
title: t('目标类型'),
dataIndex: 'target_type',
width: 90,
render: (type) => (
<Tag size='small' color={targetTypeColors[type] || 'grey'} type='ghost'>
{t(targetTypeLabels[type] || type)}
</Tag>
),
},
{
title: t('详情'),
dataIndex: 'detail',
render: (detail, record) => {
if (!detail)
return <span className='text-gray-400 dark:text-gray-500'>-</span>;
try {
const obj = JSON.parse(detail);
const text = formatDetail(record.action, obj, t, quotaPerUnit);
if (text.length > 60) {
return (
<Tooltip
content={text}
position='topLeft'
style={{ maxWidth: 400 }}
>
<span className='text-xs text-gray-600 dark:text-gray-400 cursor-default truncate block max-w-xs'>
{text}
</span>
</Tooltip>
);
}
return (
<span className='text-xs text-gray-600 dark:text-gray-400'>
{text}
</span>
);
} catch {
return (
<span className='text-xs text-gray-600 dark:text-gray-400'>
{detail}
</span>
);
}
},
},
{
title: t('时间'),
dataIndex: 'created_at',
width: 140,
render: (v) =>
v ? (
<Tooltip content={new Date(v * 1000).toLocaleString('zh-CN')}>
<span className='text-xs text-gray-500 dark:text-gray-400 cursor-default'>
{formatRelativeTime(v, t)}
</span>
</Tooltip>
) : (
'-'
),
},
];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={t('审计日志')}
subtitle={t('查看企业操作记录')}
actions={
activeTab === 'operations' ? (
<>
<Button
icon={<RefreshCw size={14} />}
onClick={() => fetch(page, 20, actionFilter)}
loading={loading}
>
{t('刷新')}
</Button>
<Select
value={actionFilter}
onChange={(v) => {
setActionFilter(v);
setPage(1);
}}
optionList={actionOptions}
style={{ width: 200 }}
placeholder={t('筛选操作')}
filter
/>
</>
) : null
}
/>
<Tabs
type='line'
activeKey={activeTab}
onChange={setActiveTab}
className='mt-2'
>
<TabPane tab={t('操作审计')} itemKey='operations'>
<OrgPanel bodyClassName='overflow-x-auto' className='mt-4'>
<Table
columns={columns}
dataSource={logs}
loading={loading}
rowKey='id'
pagination={{
currentPage: page,
pageSize: 20,
total,
onPageChange: setPage,
}}
empty={
<OrgStateBlock icon={ScrollText} title={t('暂无审计日志')} />
}
/>
</OrgPanel>
</TabPane>
{promptArchiveEnabled && canViewPromptRecords && (
<TabPane tab={t('提示词记录')} itemKey='prompt-records'>
<OrgPromptRecords key={orgId} orgId={orgId} />
</TabPane>
)}
</Tabs>
</div>
);
};
export default OrgAudit;
+543
View File
@@ -0,0 +1,543 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Form,
Toast,
Tag,
Progress,
Banner,
Popconfirm,
} from '@douyinfe/semi-ui';
import { RefreshCw, Plus, Pencil, Trash2 } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import {
renderQuota,
displayAmountToQuota,
quotaToDisplayAmount,
getQuotaInputUnit,
} from '../../helpers/render';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const subjectTypeLabel = (t, st) =>
({
department: t('部门'),
project: t('项目'),
member: t('成员'),
token: t('令牌'),
org: t('企业'),
})[st] || st;
const cycleLabel = (t, c) =>
({
none: t('不限周期'),
daily: t('每日'),
weekly: t('每周'),
monthly: t('每月'),
custom: t('自定义'),
})[c] || c;
// 预算中心:管理员配置部门/项目预算 cap(§5.3)。只提 cap,不增企业池。
const OrgBudgets = ({ orgId }) => {
const { t } = useTranslation();
const [list, setList] = useState([]);
// null=未知(接口未返回该字段的旧后端),true/false=预算 cap 是否真正在扣费链路生效
const [enforcementEnabled, setEnforcementEnabled] = useState(null);
// 未生效的细分原因:平台级引擎急停(engine=false) vs 企业未开「预算实时拦截」
const [engineEnabled, setEngineEnabled] = useState(null);
const [loading, setLoading] = useState(false);
const [depts, setDepts] = useState([]);
const [projects, setProjects] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [formApi, setFormApi] = useState(null);
const [subjectType, setSubjectType] = useState('project');
// 编辑中的预算行;null=新建。后端 PUT 为按主体 upsert,编辑复用同一接口
const [editing, setEditing] = useState(null);
// 金额输入单位跟随站点展示货币(TOKENS 模式为原始额度单位)。
// 每次 render 实时读取,避免货币配置异步落地后 label 与换算口径脱节
const unit = getQuotaInputUnit();
const quotaFieldLabel = (name) =>
unit.isToken
? `${name}(${t('额度单位')},0=${t('不限')})`
: `${name}(${unit.symbol},0=${t('不限')})`;
const fetchAll = useCallback(async () => {
if (!orgId) return;
setLoading(true);
try {
const [b, d, p] = await Promise.all([
API.get('/api/org/budget', { headers: getOrgHeaders(orgId) }),
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
API.get('/api/org/project', { headers: getOrgHeaders(orgId) }),
]);
if (b.data.success) {
// 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组
const payload = b.data.data;
if (Array.isArray(payload)) {
setList(payload || []);
setEnforcementEnabled(null);
setEngineEnabled(null);
} else {
setList(payload?.items || []);
setEnforcementEnabled(payload?.enforcement_enabled ?? null);
setEngineEnabled(payload?.engine_enabled ?? null);
}
} else {
showError(b.data.message);
// 拉取失败回到「未知」,避免 Banner 停留在陈旧状态
setEnforcementEnabled(null);
setEngineEnabled(null);
}
if (d.data.success) setDepts(d.data.data || []);
if (p.data.success) setProjects(p.data.data || []);
} catch (err) {
showError(err.message);
setEnforcementEnabled(null);
setEngineEnabled(null);
} finally {
setLoading(false);
}
}, [orgId]);
useEffect(() => {
fetchAll();
}, [fetchAll]);
// 主体名称与存在性优先取后端 subject_* 字段(覆盖成员/令牌,且能区分「已删除」与「已停用」);
// 旧后端未返回时回落到本地部门/项目列表匹配。
const subjectOf = useCallback(
(r) => {
const st = r.subject_type;
if (r.subject_exists !== undefined) {
return {
name: r.subject_name || `#${r.subject_id}`,
exists: !!r.subject_exists,
disabled: r.subject_status === 2,
};
}
if (st === 'department') {
const d = depts.find((x) => x.id === r.subject_id);
return {
name: d?.name || `#${r.subject_id}`,
exists: !!d,
disabled: d?.status === 2,
};
}
if (st === 'project') {
const p = projects.find((x) => x.id === r.subject_id);
return {
name: p?.name || `#${r.subject_id}`,
exists: !!p,
disabled: p?.status === 2,
};
}
// 旧后端下成员/令牌无从解析,按存在处理,避免误标「已删除」
return { name: `#${r.subject_id}`, exists: true, disabled: false };
},
[depts, projects],
);
const subjectIdOptions = useMemo(() => {
if (subjectType === 'department')
return depts.map((d) => ({ label: d.name, value: d.id }));
if (subjectType === 'project')
return projects.map((p) => ({ label: p.name, value: p.id }));
return [];
}, [subjectType, depts, projects]);
const openCreate = () => {
setEditing(null);
setSubjectType('project');
setModalVisible(true);
};
const openEdit = (row) => {
setEditing(row);
setSubjectType(row.subject_type);
setModalVisible(true);
};
useEffect(() => {
if (modalVisible && formApi) {
if (editing) {
// 编辑:金额字段回填为展示货币数值(与提交换算互逆)
formApi.setValues({
cycle_type: editing.cycle_type || 'none',
custom_cycle_days: editing.custom_cycle_days || 0,
over_limit_action: editing.over_limit_action || 'block',
cycle_quota: quotaToDisplayAmount(editing.cycle_quota || 0),
total_quota: quotaToDisplayAmount(editing.total_quota || 0),
status: editing.status === 2 ? 2 : 1,
});
} else {
// subject_id/custom_cycle_days 需显式重置:setValues 为合并模式,
// 上一次编辑/新建的残留值会泄漏进本次提交
formApi.setValues({
subject_type: 'project',
subject_id: undefined,
cycle_type: 'monthly',
custom_cycle_days: 0,
over_limit_action: 'block',
cycle_quota: 0,
total_quota: 0,
status: 1,
});
}
}
}, [modalVisible, formApi, editing]);
const submit = async () => {
if (!formApi) return;
let v;
try {
v = await formApi.validate();
} catch {
return;
}
try {
const res = await API.put(
'/api/org/budget',
{
// 编辑时主体不可变,取自被编辑行;后端按主体 upsert
subject_type: editing ? editing.subject_type : v.subject_type,
subject_id: editing ? editing.subject_id : v.subject_id,
cycle_type: v.cycle_type,
cycle_quota: displayAmountToQuota(v.cycle_quota || 0),
total_quota: displayAmountToQuota(v.total_quota || 0),
// 弹窗未提供该字段的输入控件,编辑时从被编辑行透传,不依赖表单状态
// (若表单丢弃未注册字段,这里取 0 会把存量自定义周期静默改成 30 天兜底)
custom_cycle_days: editing
? editing.custom_cycle_days || 0
: v.custom_cycle_days || 0,
over_limit_action: v.over_limit_action,
// 不传 status 后端会默认置回启用,编辑停用中的预算会被悄悄激活,必须显式携带
status: v.status === 2 ? 2 : 1,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('预算已保存'));
setModalVisible(false);
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const handleDelete = async (record) => {
try {
const res = await API.delete(`/api/org/budget/${record.id}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
Toast.success(t('预算已删除'));
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const columns = [
{
title: t('主体'),
render: (_, r) => {
const subj = subjectOf(r);
return (
<span>
<Tag color='blue' size='small'>
{subjectTypeLabel(t, r.subject_type)}
</Tag>{' '}
<span className={subj.exists ? '' : 'text-gray-400 line-through'}>
{subj.name}
</span>{' '}
{!subj.exists && (
<Tag color='red' size='small'>
{t('主体已删除')}
</Tag>
)}
{subj.exists && subj.disabled && (
<Tag color='grey' size='small'>
{t('已停用')}
</Tag>
)}
</span>
);
},
},
{
title: t('周期'),
dataIndex: 'cycle_type',
render: (v) => cycleLabel(t, v),
width: 90,
},
{
title: t('周期用量 / cap'),
width: 220,
render: (_, r) => {
if (!r.cycle_quota)
return <span className='text-xs text-gray-400'>{t('不限')}</span>;
const pct = Math.min(
100,
Math.round((r.used_in_cycle / r.cycle_quota) * 100),
);
return (
<div>
<Progress
percent={pct}
size='small'
stroke={pct >= 90 ? 'var(--semi-color-danger)' : undefined}
/>
<span className='text-xs text-gray-500'>
{renderQuota(r.used_in_cycle, 2)}
{r.reserved_in_cycle > 0
? ` (+${renderQuota(r.reserved_in_cycle, 2)} ${t('预留')})`
: ''}
{' / '}
{renderQuota(r.cycle_quota, 2)}
</span>
</div>
);
},
},
{
title: t('超限动作'),
dataIndex: 'over_limit_action',
// 90px 是按中文两字标签定的,泰语最短的地道说法 "เมื่อเกินขีดจำกัด" 也要 ~150px;
// 这一列没有更短的译法,只能让列让位(其余列头已在 kt_overrides_th.json 收敛用词)
width: 150,
render: () => t('拦截'),
},
{
title: t('状态'),
dataIndex: 'status',
width: 80,
render: (v) => (
<Tag color={v === 1 ? 'green' : 'grey'}>
{v === 1 ? t('启用') : t('停用')}
</Tag>
),
},
{
title: t('操作'),
width: 160,
render: (_, r) => {
const subj = subjectOf(r);
return (
<div className='flex gap-1'>
{/* 主体已删除的孤儿行改不了(后端 upsert 会因主体不存在报错),只留删除 */}
{subj.exists && (
<Button
size='small'
theme='light'
icon={<Pencil size={14} />}
onClick={() => openEdit(r)}
>
{t('编辑')}
</Button>
)}
<Popconfirm
title={t('确认删除该预算?')}
content={t(
'删除后该主体不再受此额度上限约束,历史用量流水保留不受影响',
)}
onConfirm={() => handleDelete(r)}
>
<Button
size='small'
theme='light'
type='danger'
icon={<Trash2 size={14} />}
>
{t('删除')}
</Button>
</Popconfirm>
</div>
);
},
},
];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={t('预算中心')}
subtitle={t('部门 / 项目 / 成员的额度上限')}
actions={
<>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={fetchAll}
>
{t('刷新')}
</Button>
<Button
theme='solid'
icon={<Plus size={14} />}
onClick={openCreate}
>
{t('配置预算')}
</Button>
</>
}
/>
{enforcementEnabled === false && (
<Banner
type='warning'
closeIcon={null}
description={
engineEnabled === false
? t(
'预算引擎已被平台全局急停:所有企业的预算拦截与用量统计均暂停,恢复需平台管理员开启系统开关,与本企业配置无关。',
)
: t(
'预算实时拦截当前未生效:这里的配置只会被保存,不会拦截超额调用,也不会累计用量统计。请联系平台管理员开启本企业的「预算实时拦截」功能。',
)
}
className='mb-4'
/>
)}
<Banner
type='info'
closeIcon={null}
description={t(
'预算只设置「最多能花多少」的上限(cap),不增加企业真实额度池;提额仅提高上限。',
)}
className='mb-4'
/>
<OrgPanel padding='p-2'>
<Table
columns={columns}
dataSource={list}
loading={loading}
pagination={false}
rowKey='id'
/>
</OrgPanel>
<OrgModal
title={editing ? t('编辑预算') : t('配置预算')}
visible={modalVisible}
onOk={submit}
onCancel={() => setModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
>
<Form getFormApi={setFormApi}>
{editing ? (
<div className='mb-3'>
<Tag color='blue' size='small'>
{subjectTypeLabel(t, editing.subject_type)}
</Tag>{' '}
{subjectOf(editing).name}
</div>
) : (
<>
<Form.Select
field='subject_type'
label={t('主体类型')}
optionList={[
{ label: t('项目'), value: 'project' },
{ label: t('部门'), value: 'department' },
]}
onChange={(v) => setSubjectType(v)}
style={{ width: '100%' }}
/>
<Form.Select
field='subject_id'
label={t('主体')}
optionList={subjectIdOptions}
rules={[{ required: true, message: t('请选择主体') }]}
style={{ width: '100%' }}
/>
</>
)}
<Form.Select
field='cycle_type'
label={t('周期')}
optionList={[
{ label: t('每月'), value: 'monthly' },
{ label: t('每周'), value: 'weekly' },
{ label: t('每日'), value: 'daily' },
{ label: t('不限周期'), value: 'none' },
// 该 UI 暂不支持新建自定义周期,仅在编辑存量自定义周期预算时保留原值
...(editing?.cycle_type === 'custom'
? [{ label: t('自定义'), value: 'custom' }]
: []),
]}
style={{ width: '100%' }}
/>
<Form.InputNumber
field='cycle_quota'
label={quotaFieldLabel(t('周期上限'))}
min={0}
precision={unit.isToken ? 0 : 2}
suffix={unit.isToken ? null : unit.symbol}
style={{ width: '100%' }}
/>
<Form.InputNumber
field='total_quota'
label={quotaFieldLabel(t('总上限'))}
min={0}
precision={unit.isToken ? 0 : 2}
suffix={unit.isToken ? null : unit.symbol}
style={{ width: '100%' }}
/>
<Form.Select
field='over_limit_action'
label={t('超限动作')}
optionList={[{ label: t('拦截'), value: 'block' }]}
style={{ width: '100%' }}
/>
{editing && (
<Form.Select
field='status'
label={t('状态')}
optionList={[
{ label: t('启用'), value: 1 },
{ label: t('停用'), value: 2 },
]}
style={{ width: '100%' }}
/>
)}
</Form>
</OrgModal>
</div>
);
};
export default OrgBudgets;
+757
View File
@@ -0,0 +1,757 @@
/*
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, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Select,
SideSheet,
Switch,
TabPane,
Tabs,
Tag,
TextArea,
Toast,
} from '@douyinfe/semi-ui';
import { Cable, KeyRound, Plus, RefreshCw, ShieldCheck } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers/api';
import {
usePageGuide,
PageGuideDrawer,
PageGuidePill,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import './org-connectors.css';
const headersFor = (orgId) => ({ 'X-Org-Id': String(orgId) });
const blankConnector = {
definition_id: undefined,
instance_key: '',
display_name: '',
base_url: '',
config: '{}',
allowed_hosts: '',
allowed_cidrs: '',
egress_policy: 'public_https',
};
const parseLines = (value) =>
value
.split(/[,\n]/)
.map((item) => item.trim())
.filter(Boolean);
const OrgConnectors = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => headersFor(orgId), [orgId]);
const [definitions, setDefinitions] = useState([]);
const [connectors, setConnectors] = useState([]);
const [grants, setGrants] = useState([]);
const [audit, setAudit] = useState([]);
const [loading, setLoading] = useState(true);
const [editorOpen, setEditorOpen] = useState(false);
const [credentialOpen, setCredentialOpen] = useState(false);
const [grantOpen, setGrantOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [form, setForm] = useState(blankConnector);
const [selected, setSelected] = useState(null);
const [credential, setCredential] = useState(
'{\n "headers": {\n "Authorization": "Bearer ..."\n }\n}',
);
const [grant, setGrant] = useState({
grant_key: '',
connector_id: undefined,
expert_id: undefined,
scope_type: 'organization',
scope_id: 0,
method_keys: [],
access_level: 'read',
confirmation_policy: 'write',
external_allowed: false,
max_calls_per_run: 5,
max_result_bytes: 65536,
});
const load = useCallback(async () => {
setLoading(true);
try {
const [
definitionResponse,
connectorResponse,
grantResponse,
auditResponse,
] = await Promise.all([
API.get('/api/org/connectors/definitions', { headers }),
API.get('/api/org/connectors', { headers }),
API.get('/api/org/connectors/grants', { headers }),
API.get('/api/org/connectors/audit', { headers }),
]);
setDefinitions(definitionResponse.data?.data || []);
setConnectors(connectorResponse.data?.data || []);
setGrants(grantResponse.data?.data || []);
setAudit(auditResponse.data?.data || []);
} catch (error) {
Toast.error(error?.response?.data?.message || error.message);
} finally {
setLoading(false);
}
}, [headers]);
useEffect(() => {
void load();
}, [load]);
const definitionsById = useMemo(
() => new Map(definitions.map((item) => [item.definition.id, item])),
[definitions],
);
const connectorRows = useMemo(
() => connectors.map((item) => item.connector || item),
[connectors],
);
const connectorViewById = useMemo(
() =>
new Map(connectors.map((item) => [(item.connector || item).id, item])),
[connectors],
);
const selectedGrantConnector = connectorRows.find(
(item) => item.id === grant.connector_id,
);
const grantDefinition = selectedGrantConnector
? definitionsById.get(selectedGrantConnector.definition_id)
: null;
// Method options must come from the instance's PINNED definition version
// (the backend validates against it); the definition catalog only carries
// the latest version, whose new methods would be rejected on save.
const grantConnectorView = grant.connector_id
? connectorViewById.get(grant.connector_id)
: null;
const grantMethodOptions =
grantConnectorView?.methods || grantDefinition?.methods || [];
const grantConnectorType =
grantDefinition?.version?.connector_type ||
grantDefinition?.definition?.connector_type ||
'';
const openCreate = () => {
setSelected(null);
setForm(blankConnector);
setEditorOpen(true);
};
const openEdit = (row) => {
setSelected(row);
setForm({
id: row.id,
definition_id: row.definition_id,
definition_version_id: row.definition_version_id,
instance_key: row.instance_key,
display_name: row.display_name,
base_url: row.base_url || '',
config: row.config || row.ConfigJSON || row.config_json || '{}',
allowed_hosts: (() => {
try {
return JSON.parse(
row.allowed_hosts || row.allowed_hosts_json || '[]',
).join('\n');
} catch {
return '';
}
})(),
allowed_cidrs: (() => {
try {
return JSON.parse(
row.allowed_cidrs || row.allowed_cidrs_json || '[]',
).join('\n');
} catch {
return '';
}
})(),
egress_policy: row.egress_policy || 'public_https',
});
setEditorOpen(true);
};
const saveConnector = async () => {
let config;
try {
config = JSON.parse(form.config || '{}');
} catch {
Toast.warning(t('配置必须是有效 JSON'));
return;
}
setSaving(true);
try {
const payload = {
...form,
config,
allowed_hosts: parseLines(form.allowed_hosts),
allowed_cidrs: parseLines(form.allowed_cidrs),
};
const url = form.id
? `/api/org/connectors/${form.id}`
: '/api/org/connectors';
const response = form.id
? await API.put(url, payload, { headers })
: await API.post(url, payload, { headers });
if (!response.data?.success) throw new Error(response.data?.message);
setEditorOpen(false);
Toast.success(t('Connector 配置已保存'));
await load();
} catch (error) {
Toast.error(error?.response?.data?.message || error.message);
} finally {
setSaving(false);
}
};
const saveCredential = async () => {
let parsed;
try {
parsed = JSON.parse(credential);
} catch {
Toast.warning(t('凭据必须是有效 JSON'));
return;
}
setSaving(true);
try {
await API.put(
`/api/org/connectors/${selected.id}/credential`,
{ credential: parsed },
{ headers },
);
setCredentialOpen(false);
Toast.success(t('凭据已加密轮换,旧凭据已停用'));
await load();
} catch (error) {
Toast.error(error?.response?.data?.message || error.message);
} finally {
setSaving(false);
}
};
const saveGrant = async () => {
setSaving(true);
try {
await API.post('/api/org/connectors/grants', grant, { headers });
setGrantOpen(false);
Toast.success(t('授权版本已发布'));
await load();
} catch (error) {
Toast.error(error?.response?.data?.message || error.message);
} finally {
setSaving(false);
}
};
const revoke = (row) => {
Modal.confirm({
title: t('撤销 Connector'),
content: t('撤销后,排队和等待确认的调用都会在执行前重新校验并被阻断。'),
onOk: async () => {
await API.post(
`/api/org/connectors/${row.id}/revoke`,
{ reason: 'Revoked from organization connector console' },
{ headers },
);
await load();
},
});
};
// 使用指引:连接器从接入到可被专家调用的四步,完成态由真实数据驱动。
const guide = usePageGuide({
guideKey: 'org-connectors',
ready: !loading,
title: t('业务系统连接器 · 使用指引'),
intro: t(
'配置实例 → 加密凭据 → 发布授权 → 审计治理,让专家安全地调用业务系统',
),
steps: [
{
title: t('配置 Connector 实例'),
detail: t('选择连接器类型,设置地址与网络边界'),
done: connectorRows.length > 0,
cta: t('去配置实例'),
onAction: openCreate,
points: [
t('填写实例键、显示名与 Base URL;主机白名单精确到域名'),
t('出网策略二选一:公网 HTTPS,或已审批的内网 CIDR 段'),
t('能力边界用 JSON 描述,保存前会做合法性校验'),
],
},
{
title: t('轮换加密凭据'),
detail: t('凭据只进不出,界面永远只显示哈希后缀'),
done: connectors.some((item) => Boolean(item.credential)),
points: [
t('在实例卡片点「轮换凭据」,粘贴 JSON 形式的认证头'),
t('轮换后旧凭据立即停用;服务端不会回显明文'),
],
},
{
title: t('发布授权版本'),
detail: t('按「专家 × 范围」发布不可变授权,专家才可调用'),
done: grants.length > 0,
points: [
t('在「授权矩阵」页点「发布授权」,选择连接器、专家与范围'),
t(
'访问级别 read/write 与确认策略 never/write/always 决定哪些调用需成员确认',
),
t('每次任务的调用次数与返回字节都有上限,防止失控'),
],
},
{
title: t('审计与治理'),
detail: t('每次调用都有审计记录,出问题可随时撤销'),
done: grants.length > 0,
points: [
t('「审计」页记录每次调用的动作、状态与摘要'),
t('「撤销」实例后,排队和等待确认的调用都会在执行前被阻断'),
],
},
],
faq: [
{
q: t('成员没有确认操作的入口?'),
a: t(
'确认发生在云端大脑的任务详情里;成员可在「我的业务系统授权」查看自己的授权范围',
),
},
{
q: t('HTTP 类型连接器发布授权被拦?'),
a: t('需要先开启「允许向已审批外部系统发送必要参数」开关'),
},
],
});
const closeGuide = guide.close;
// 抽屉进度是组织私有的:切组织时关闭,避免带着旧组织的完成态短暂展示。
useEffect(() => {
closeGuide();
}, [orgId, closeGuide]);
return (
<main className='org-connector-page'>
<header className='org-connector-hero'>
<div>
<h1>{t('业务系统连接器')}</h1>
<p>{t('凭据、授权范围、写操作确认和调用审计在同一控制面闭环。')}</p>
</div>
<div className='org-connector-actions'>
<PageGuideTrigger guide={guide} />
<Button
icon={<RefreshCw size={16} />}
loading={loading}
onClick={load}
>
{t('刷新')}
</Button>
<Button theme='solid' icon={<Plus size={16} />} onClick={openCreate}>
{t('配置 Connector')}
</Button>
</div>
</header>
<PageGuidePill guide={guide} />
<PageGuideDrawer guide={guide} />
<Tabs type='line'>
<TabPane
tab={`${t('实例')} · ${connectorRows.length}`}
itemKey='instances'
>
<section className='org-connector-grid'>
{connectorRows.map((row) => {
const definition = definitionsById.get(row.definition_id);
const credentialState = connectorViewById.get(row.id)?.credential;
return (
<article key={row.id} className='org-connector-card'>
<div className='org-connector-card-top'>
<span className='org-connector-icon'>
<Cable size={20} />
</span>
<Tag color={row.status === 'active' ? 'green' : 'red'}>
{row.status}
</Tag>
</div>
<h3>{row.display_name}</h3>
<p>
{definition?.version?.description_zh ||
definition?.version?.description_en}
</p>
<dl>
<div>
<dt>{t('实例键')}</dt>
<dd>{row.instance_key}</dd>
</div>
<div>
<dt>{t('网络策略')}</dt>
<dd>{row.egress_policy}</dd>
</div>
<div>
<dt>{t('凭据')}</dt>
<dd>
{credentialState
? `•••• ${credentialState.masked_suffix}`
: t('未配置')}
</dd>
</div>
</dl>
<div className='org-connector-card-actions'>
<Button size='small' onClick={() => openEdit(row)}>
{t('配置')}
</Button>
<Button
size='small'
icon={<KeyRound size={14} />}
onClick={() => {
setSelected(row);
setCredentialOpen(true);
}}
>
{t('轮换凭据')}
</Button>
{row.status === 'active' && (
<Button
size='small'
type='danger'
onClick={() => revoke(row)}
>
{t('撤销')}
</Button>
)}
</div>
</article>
);
})}
</section>
</TabPane>
<TabPane tab={`${t('授权矩阵')} · ${grants.length}`} itemKey='grants'>
<div className='org-connector-section-head'>
<p>
{t('授权按专家与组织、部门、项目或成员范围发布为不可变版本。')}
</p>
<Button
theme='solid'
icon={<ShieldCheck size={16} />}
onClick={() => {
setGrant((current) => ({
...current,
connector_id: connectorRows[0]?.id,
}));
setGrantOpen(true);
}}
>
{t('发布授权')}
</Button>
</div>
<section className='org-connector-list'>
{grants.map((item) => (
<article key={item.id}>
<div>
<strong>
{item.scope_type} #{item.scope_id || 0}
</strong>
<Tag>v{item.version}</Tag>
</div>
<code>{item.method_keys}</code>
<span>
{item.access_level} · {item.confirmation_policy} ·{' '}
{item.max_calls_per_run}/run
</span>
</article>
))}
</section>
</TabPane>
<TabPane tab={`${t('审计')} · ${audit.length}`} itemKey='audit'>
<section className='org-connector-list org-connector-audit'>
{audit.map((item) => (
<article key={item.id}>
<div>
<strong>{item.action}</strong>
<Tag color={item.status === 'succeeded' ? 'green' : 'orange'}>
{item.status}
</Tag>
</div>
<code>{item.method_key || item.tool_call_id || '-'}</code>
<span>{item.summary}</span>
</article>
))}
</section>
</TabPane>
</Tabs>
<SideSheet
title={form.id ? t('编辑 Connector') : t('配置 Connector')}
visible={editorOpen}
onCancel={() => setEditorOpen(false)}
width={520}
footer={
<Button theme='solid' loading={saving} onClick={saveConnector}>
{t('保存配置')}
</Button>
}
>
<div className='org-connector-form'>
<label>
{t('Connector 类型')}
<Select
value={form.definition_id}
disabled={!!form.id}
onChange={(value) => setForm({ ...form, definition_id: value })}
optionList={definitions.map((item) => ({
value: item.definition.id,
label: item.version.name_zh || item.version.name_en,
}))}
/>
</label>
<label>
{t('实例键')}
<Input
value={form.instance_key}
onChange={(value) => setForm({ ...form, instance_key: value })}
placeholder='gitlab_primary'
/>
</label>
<label>
{t('显示名称')}
<Input
value={form.display_name}
onChange={(value) => setForm({ ...form, display_name: value })}
/>
</label>
<label>
{t('Base URL(HTTP 类型)')}
<Input
value={form.base_url}
onChange={(value) => setForm({ ...form, base_url: value })}
placeholder='https://api.example.com'
/>
</label>
<label>
{t('精确域名白名单')}
<TextArea
value={form.allowed_hosts}
onChange={(value) => setForm({ ...form, allowed_hosts: value })}
placeholder='api.example.com'
/>
</label>
<label>
{t('出站策略')}
<Select
value={form.egress_policy}
onChange={(value) => setForm({ ...form, egress_policy: value })}
optionList={[
{ value: 'public_https', label: 'Public HTTPS' },
{ value: 'approved_private', label: 'Approved private CIDR' },
]}
/>
</label>
<label>
{t('授权 CIDR(仅运维审批私网)')}
<TextArea
value={form.allowed_cidrs}
onChange={(value) => setForm({ ...form, allowed_cidrs: value })}
placeholder={'10.20.0.0/16\nfd00:1::/48'}
/>
<span className='org-connector-note'>
{t(
'仅接受具体的私网网段:IPv4 须为 RFC1918 且前缀 ≥ /16,IPv6 须为 fc00::/7 内且前缀 ≥ /48;每行一条。',
)}
</span>
</label>
<label>
{t('能力边界 JSON')}
<TextArea
autosize
value={form.config}
onChange={(value) => setForm({ ...form, config: value })}
placeholder='{"project_ids":["123"],"path_prefixes":["src/"]}'
/>
</label>
</div>
</SideSheet>
<Modal
title={t('轮换加密凭据')}
visible={credentialOpen}
onCancel={() => setCredentialOpen(false)}
onOk={saveCredential}
confirmLoading={saving}
>
<p className='org-connector-note'>
{t('提交后只显示哈希尾号,服务端不会回显明文。')}
</p>
<TextArea autosize value={credential} onChange={setCredential} />
</Modal>
<SideSheet
title={t('发布授权版本')}
visible={grantOpen}
onCancel={() => setGrantOpen(false)}
width={520}
footer={
<Button theme='solid' loading={saving} onClick={saveGrant}>
{t('发布授权')}
</Button>
}
>
<div className='org-connector-form'>
<label>
{t('授权键')}
<Input
value={grant.grant_key}
onChange={(value) => setGrant({ ...grant, grant_key: value })}
placeholder='gitlab_read_engineering'
/>
</label>
<label>
{t('Connector 实例')}
<Select
value={grant.connector_id}
onChange={(value) =>
setGrant({ ...grant, connector_id: value, method_keys: [] })
}
optionList={connectorRows
.filter((item) => item.status === 'active')
.map((item) => ({ value: item.id, label: item.display_name }))}
/>
</label>
<label>
{t('专家 ID')}
<InputNumber
min={1}
value={grant.expert_id}
onChange={(value) => setGrant({ ...grant, expert_id: value })}
/>
</label>
<label>
{t('范围')}
<Select
value={grant.scope_type}
onChange={(value) =>
setGrant({
...grant,
scope_type: value,
scope_id: value === 'organization' ? 0 : undefined,
})
}
optionList={[
'organization',
'department',
'project',
'member',
].map((value) => ({ value, label: value }))}
/>
</label>
{grant.scope_type !== 'organization' && (
<label>
{t('范围 ID')}
<InputNumber
min={1}
value={grant.scope_id}
onChange={(value) => setGrant({ ...grant, scope_id: value })}
/>
</label>
)}
<label>
{t('允许的方法')}
<Select
multiple
value={grant.method_keys}
onChange={(value) => setGrant({ ...grant, method_keys: value })}
optionList={grantMethodOptions.map((item) => ({
value: item.method_key,
label: `${item.name_zh || item.name_en} · ${item.operation_type}`,
}))}
/>
</label>
<label>
{t('访问级别')}
<Select
value={grant.access_level}
onChange={(value) => setGrant({ ...grant, access_level: value })}
optionList={[
{ value: 'read', label: 'read' },
{ value: 'write', label: 'write' },
]}
/>
</label>
<label>
{t('确认策略')}
<Select
value={grant.confirmation_policy}
onChange={(value) =>
setGrant({ ...grant, confirmation_policy: value })
}
optionList={['never', 'write', 'always'].map((value) => ({
value,
label: value,
}))}
/>
</label>
<label className='org-connector-switch'>
<span>{t('允许向已审批外部系统发送必要参数')}</span>
<Switch
checked={grant.external_allowed}
onChange={(value) =>
setGrant({ ...grant, external_allowed: value })
}
/>
</label>
{grantConnectorType === 'http' && !grant.external_allowed && (
<p className='org-connector-note'>
{t(
'HTTP 类型 Connector 必须开启此开关才会在任务运行时生效,关闭状态下无法发布授权。',
)}
</p>
)}
<label>
{t('单任务调用上限')}
<InputNumber
min={1}
max={10}
value={grant.max_calls_per_run}
onChange={(value) =>
setGrant({ ...grant, max_calls_per_run: value })
}
/>
</label>
<label>
{t('结果上限(字节)')}
<InputNumber
min={1024}
max={1048576}
value={grant.max_result_bytes}
onChange={(value) =>
setGrant({ ...grant, max_result_bytes: value })
}
/>
</label>
</div>
</SideSheet>
</main>
);
};
export default OrgConnectors;
+299
View File
@@ -0,0 +1,299 @@
/*
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, useCallback, useEffect, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import {
Building2,
KeyRound,
ArrowRight,
HelpCircle,
Home,
AlertTriangle,
RefreshCw,
} from 'lucide-react';
import { Input, Button, Toast } from '@douyinfe/semi-ui';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { UserContext } from '../../context/User';
import Loading from '../../components/common/ui/Loading';
import PageBackground from '../../components/common/PageBackground';
// 企业创建已收归系统管理员手动创建(/api/admin/organizations/)。
// 此页面是「无企业归属」用户的落地引导页,按意图区分三态:
// join —— 用户不属于任何企业,展示企业代码加入入口
// inactive —— 用户有企业但均非活跃(冻结/欠费/待激活),引导联系管理员,避免误导其"加入"
// error —— 企业列表加载失败,提供重试
const ORG_STATUS_TEXT = {
2: '已被冻结',
3: '已欠费',
4: '待激活',
};
const OrgCreate = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const [userState] = useContext(UserContext);
const isOrgOnly = userState?.user?.org_only_mode === true;
const [joinLoading, setJoinLoading] = useState(false);
const [orgCode, setOrgCode] = useState('');
// 'checking' | 'join' | 'inactive' | 'error'
const [mode, setMode] = useState('checking');
const [inactiveOrgs, setInactiveOrgs] = useState([]);
// 检查用户企业归属并决定落地状态。
// 有 active(status=1) 企业 → 写入 current_org_id 并跳转控制台(仅认 active,防冻结企业死循环)。
const runCheck = useCallback(async () => {
setMode('checking');
try {
const res = await API.get('/api/org/list');
if (res.data.success) {
const orgs = res.data.data || [];
const activeOrgs = orgs.filter((o) => o.status === 1);
if (activeOrgs.length > 0) {
const savedOrgId = parseInt(
localStorage.getItem('current_org_id') || '0',
10,
);
const savedOrg =
savedOrgId > 0 ? activeOrgs.find((o) => o.id === savedOrgId) : null;
const targetOrg = savedOrg || activeOrgs[0];
localStorage.setItem('current_org_id', String(targetOrg.id));
navigate('/org/dashboard', { replace: true });
return;
}
if (orgs.length > 0) {
setInactiveOrgs(orgs);
setMode('inactive');
return;
}
setMode('join');
return;
}
setMode('error');
} catch {
setMode('error');
}
}, [navigate]);
useEffect(() => {
runCheck();
}, [runCheck]);
const handleJoin = useCallback(async () => {
if (!orgCode.trim()) {
Toast.warning(t('请输入企业代码'));
return;
}
setJoinLoading(true);
try {
const res = await API.post('/api/org/join', { code: orgCode.trim() });
if (res.data.success) {
Toast.success(t('成功加入企业'));
const data = res.data.data;
if (data && data.organization && data.organization.id) {
localStorage.setItem('current_org_id', String(data.organization.id));
}
navigate('/org/dashboard');
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setJoinLoading(false);
}
}, [orgCode, t, navigate]);
if (mode === 'checking') {
return <Loading />;
}
// 非 org_only 用户提供「返回首页」出口,避免被困在本页;org_only 员工受守卫限制在 /org,不提供。
const backHome = !isOrgOnly && (
<div className='mt-6 text-center'>
<button
onClick={() => navigate('/')}
className='inline-flex items-center gap-1.5 text-sm text-gray-400 dark:text-gray-500 hover:text-brand-deep transition-colors'
>
<Home size={14} />
{t('返回首页')}
</button>
</div>
);
return (
<div className='org-center relative min-h-screen flex items-center justify-center bg-[var(--surface-bg-base)] py-16 px-4 transition-colors duration-300'>
{/* 统一页面背景层 —— 唯一背景来源,走 bg-glow-* 主题变量 */}
<PageBackground />
<div className='w-full max-w-md relative z-10'>
{mode === 'join' && (
<>
<div className='text-center mb-7'>
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-brand-from via-brand-via to-brand-to mb-5 shadow-lg shadow-brand/25 dark:shadow-brand/15'>
<Building2 size={34} className='text-white' />
</div>
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
{t('加入企业')}
</h1>
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
{t('输入企业管理员提供的企业代码,即可加入你的团队')}
</p>
</div>
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
{t('企业代码')}
</label>
<Input
value={orgCode}
onChange={(v) => setOrgCode(v)}
placeholder={t('请输入 8 位企业代码')}
size='large'
prefix={<KeyRound size={18} className='text-gray-400 ml-1' />}
onEnterPress={handleJoin}
className='tracking-wide'
/>
<Button
type='primary'
size='large'
block
loading={joinLoading}
onClick={handleJoin}
icon={<ArrowRight size={18} />}
iconPosition='right'
className='mt-4'
>
{t('加入企业')}
</Button>
<div className='mt-5 pt-5 border-t border-gray-100 dark:border-neutral-800 flex items-start gap-2.5'>
<HelpCircle
size={16}
className='text-gray-400 dark:text-gray-500 mt-0.5 flex-shrink-0'
/>
<p className='text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
{t(
'没有企业代码?请联系你的企业管理员获取,或由管理员直接为你创建企业账号。',
)}
</p>
</div>
</div>
{backHome}
</>
)}
{mode === 'inactive' && (
<>
<div className='text-center mb-7'>
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-amber-400 to-amber-500 mb-5 shadow-lg shadow-amber-500/25 dark:shadow-amber-500/15'>
<AlertTriangle size={34} className='text-white' />
</div>
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
{t('企业暂不可用')}
</h1>
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
{t('你所属的企业当前无法访问,请联系管理员处理')}
</p>
</div>
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
<div className='space-y-2.5'>
{inactiveOrgs.map((org) => (
<div
key={org.id}
className='flex items-center justify-between gap-3 p-3 rounded-xl bg-gray-50 dark:bg-neutral-800/60 border border-gray-100 dark:border-neutral-800'
>
<div className='flex items-center gap-2.5 min-w-0'>
<Building2
size={16}
className='text-gray-400 flex-shrink-0'
/>
<span className='text-sm font-medium text-gray-900 dark:text-white truncate'>
{org.name || t('企业') + ' #' + org.id}
</span>
</div>
<span className='text-xs font-medium text-amber-600 dark:text-amber-400 flex-shrink-0'>
{t(ORG_STATUS_TEXT[org.status] || '不可用')}
</span>
</div>
))}
</div>
<div className='mt-5 pt-5 border-t border-gray-100 dark:border-neutral-800 flex items-start gap-2.5'>
<HelpCircle
size={16}
className='text-gray-400 dark:text-gray-500 mt-0.5 flex-shrink-0'
/>
<p className='text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
{t(
'企业激活、解冻或续费由平台管理员处理,请联系企业管理员或平台客服。',
)}
</p>
</div>
<Button
size='large'
block
icon={<RefreshCw size={16} />}
onClick={runCheck}
className='mt-4'
>
{t('刷新状态')}
</Button>
</div>
{backHome}
</>
)}
{mode === 'error' && (
<>
<div className='text-center mb-7'>
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-red-400 to-red-500 mb-5 shadow-lg shadow-red-500/25 dark:shadow-red-500/15'>
<AlertTriangle size={34} className='text-white' />
</div>
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
{t('加载失败')}
</h1>
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
{t('无法获取你的企业信息,请检查网络后重试')}
</p>
</div>
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
<Button
type='primary'
size='large'
block
icon={<RefreshCw size={16} />}
onClick={runCheck}
>
{t('重试')}
</Button>
</div>
{backHome}
</>
)}
</div>
</div>
);
};
export default OrgCreate;
+895
View File
@@ -0,0 +1,895 @@
/*
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,
useCallback,
useContext,
useRef,
} from 'react';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
import {
BarChart2,
Users,
Key,
Wallet,
TrendingUp,
ArrowRight,
ShieldCheck,
Crown,
Shield,
PiggyBank,
Flame,
Coins,
RefreshCw,
Search,
FileText,
CreditCard,
Activity,
} from 'lucide-react';
import {
Progress,
Table,
Tag,
Button,
DatePicker,
Input,
Spin,
Tooltip,
} from '@douyinfe/semi-ui';
import { useOrgDashboard, useOrgQuota } from '../../hooks/org/useOrgData';
import { renderQuota } from '../../helpers/render';
import { API, showError } from '../../helpers';
import Loading from '../../components/common/ui/Loading';
import OrgPageHeader from './components/OrgPageHeader';
import OrgAnalyticsPanel from './components/OrgAnalyticsPanel';
import StatCard from './components/OrgStatCard';
import OrgPanel from './components/OrgPanel';
import OrgSideSheet from './components/OrgSideSheet';
import OrgStateBlock from './components/OrgStateBlock';
import { StatusContext } from '../../context/Status';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 周期配额:daily/weekly/monthly 才有「周期内已用/重置」概念;none 为终身累计。
const isPeriodicQuotaPeriod = (period) =>
period === 'daily' || period === 'weekly' || period === 'monthly';
const safeQuotaNumber = (value) => Math.max(0, Number(value || 0));
// 用量阈值 → 语义色(Semi token,随明暗主题自适应)。
// 页面内所有「使用进度」类指示(统计卡进度条 / 使用率大进度条 / 成员表进度条)
// 统一走这一套:>80% 危险、>60% 警告、其余正常。
const usageStrokeColor = (percent) =>
percent > 80
? 'var(--semi-color-danger)'
: percent > 60
? 'var(--semi-color-warning)'
: 'var(--semi-color-success)';
const quotaPeriodLimitLabel = (t, period) => {
switch (period) {
case 'daily':
return t('每日个人上限');
case 'weekly':
return t('每周个人上限');
case 'monthly':
return t('每月个人上限');
default:
return t('个人终身上限');
}
};
const isFeatureEnabled = (flags, key) => {
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
// 状态配置
const getStatusConfig = (status, t) => {
const map = {
1: { label: t('正常'), tagLabel: t('运行正常'), color: 'green' },
2: { label: t('冻结'), tagLabel: t('已被冻结'), color: 'red' },
3: { label: t('欠费'), tagLabel: t('额度不足'), color: 'orange' },
};
return map[status] || { label: '-', tagLabel: '-', color: 'grey' };
};
// 成员用量明细抽屉组件
const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [dateRange, setDateRange] = useState([]);
const [modelName, setModelName] = useState('');
const [appliedFilters, setAppliedFilters] = useState({
dateRange: [],
modelName: '',
});
const requestSeq = useRef(0);
const pageSize = 20;
const fetchLogs = useCallback(
async (p = 1, filters = appliedFilters) => {
if (!member || !orgId) return;
const seq = ++requestSeq.current;
setLoading(true);
try {
let url = `/api/org/logs?user_id=${member.user_id}&p=${p}&page_size=${pageSize}`;
if (filters.dateRange && filters.dateRange.length === 2) {
if (filters.dateRange[0])
url += `&start_timestamp=${Math.floor(filters.dateRange[0].getTime() / 1000)}`;
if (filters.dateRange[1])
url += `&end_timestamp=${Math.floor(filters.dateRange[1].getTime() / 1000)}`;
}
if (filters.modelName)
url += `&model_name=${encodeURIComponent(filters.modelName)}`;
const res = await API.get(url, { headers: getOrgHeaders(orgId) });
if (seq !== requestSeq.current) return;
if (res.data.success) {
setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,保留首页已知总数,
// 否则 total 变 -1 会让"total > pageSize"不成立、分页器消失(与 useOrgLogs 同款约定)
const nextTotal = res.data.data?.total;
if (typeof nextTotal === 'number' && nextTotal >= 0) {
setTotal(nextTotal);
}
setPage(p);
} else {
showError(res.data.message);
}
} catch (err) {
if (seq === requestSeq.current) showError(err.message);
} finally {
if (seq === requestSeq.current) setLoading(false);
}
},
[member, orgId, appliedFilters],
);
useEffect(() => {
if (visible && member && orgId) {
// 重置过滤条件和分页状态
setDateRange([]);
setModelName('');
setAppliedFilters({ dateRange: [], modelName: '' });
setPage(1);
setLogs([]);
setTotal(0);
// 直接发起无过滤的请求(不依赖 state 更新)
const loadInitial = async () => {
const seq = ++requestSeq.current;
setLoading(true);
try {
const url = `/api/org/logs?user_id=${member.user_id}&p=1&page_size=${pageSize}`;
const res = await API.get(url, { headers: getOrgHeaders(orgId) });
if (seq !== requestSeq.current) return;
if (res.data.success) {
setLogs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
showError(res.data.message);
}
} catch (err) {
if (seq === requestSeq.current) showError(err.message);
} finally {
if (seq === requestSeq.current) setLoading(false);
}
};
loadInitial();
}
}, [visible, member, orgId]);
const handleSearch = () => {
const filters = { dateRange, modelName: modelName.trim() };
setAppliedFilters(filters);
fetchLogs(1, filters);
};
const logColumns = useMemo(
() => [
{
title: t('时间'),
dataIndex: 'created_at',
width: 160,
render: (v) => (v ? timestamp2string(v) : '-'),
},
{
title: t('模型'),
dataIndex: 'model_name',
width: 180,
ellipsis: true,
render: (v) => (
<code className='text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-neutral-800 rounded'>
{v || '-'}
</code>
),
},
{
title: t('Token 用量'),
width: 120,
render: (_, record) => (
<div className='text-xs text-gray-600 dark:text-gray-400'>
<span title='Prompt'>{record.prompt_tokens || 0}</span>
<span className='mx-1 text-gray-300 dark:text-gray-600'>/</span>
<span title='Completion'>{record.completion_tokens || 0}</span>
</div>
),
},
{
title: t('消耗额度'),
dataIndex: 'quota',
width: 100,
align: 'right',
render: (v) => (
<span className='text-orange-600 dark:text-orange-400 font-medium text-sm'>
{renderQuota(v, 6)}
</span>
),
},
],
[t],
);
return (
<OrgSideSheet
title={
<div className='flex items-center gap-2'>
<FileText size={18} className='text-brand-deep' />
<span>{member?.display_name || member?.username || ''}</span>
<span className='text-sm text-gray-400 font-normal'>
- {t('用量明细')}
</span>
</div>
}
visible={visible}
onCancel={onClose}
placement='right'
width={640}
bodyStyle={{ background: 'var(--semi-color-bg-0)' }}
style={{ background: 'var(--semi-color-bg-0)' }}
mask={true}
maskClosable={true}
maskStyle={{
backgroundColor: 'rgba(0, 0, 0, 0.45)',
backdropFilter: 'blur(4px)',
WebkitBackdropFilter: 'blur(4px)',
}}
>
<div className='space-y-4'>
{/* 过滤器 */}
<div className='flex flex-wrap items-end gap-3 p-3 bg-white dark:bg-neutral-900 rounded-lg border border-gray-200 dark:border-neutral-800'>
<div className='flex-1 min-w-[200px]'>
<div className='text-xs text-gray-500 dark:text-gray-400 mb-1'>
{t('时间范围')}
</div>
<DatePicker
type='dateTimeRange'
density='compact'
value={dateRange}
onChange={setDateRange}
placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: '100%' }}
/>
</div>
<div className='min-w-[140px]'>
<div className='text-xs text-gray-500 dark:text-gray-400 mb-1'>
{t('模型名称')}
</div>
<Input
size='small'
placeholder={t('输入模型名称')}
value={modelName}
onChange={setModelName}
onEnterPress={handleSearch}
/>
</div>
<Button
size='small'
theme='solid'
icon={<Search size={14} />}
onClick={handleSearch}
loading={loading}
>
{t('查询')}
</Button>
</div>
{/* 统计 */}
<div className='text-xs text-gray-400 dark:text-gray-500'>
{t('共 {{count}} 条记录', { count: total })}
</div>
{/* 日志表格 */}
{loading && logs.length === 0 ? (
<div className='flex items-center justify-center py-12'>
<Spin />
</div>
) : (
<Table
columns={logColumns}
dataSource={logs}
rowKey='id'
size='small'
loading={loading}
pagination={
total > pageSize
? {
currentPage: page,
pageSize,
total,
onPageChange: (p) => fetchLogs(p),
}
: false
}
empty={
<div className='py-8 text-center'>
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-2'>
<FileText
size={20}
className='text-gray-400 dark:text-gray-500'
/>
</div>
<p className='text-gray-400 dark:text-gray-500 text-sm'>
{t('暂无用量记录')}
</p>
</div>
}
/>
)}
</div>
</OrgSideSheet>
);
};
const OrgDashboard = ({ orgId, orgRole, featureFlags }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [statusState] = useContext(StatusContext);
const { data, loading, fetch } = useOrgDashboard(orgId);
const {
data: quotaData,
loading: quotaLoading,
fetch: fetchQuota,
} = useOrgQuota(orgId);
const [usageSheetVisible, setUsageSheetVisible] = useState(false);
const [selectedMember, setSelectedMember] = useState(null);
const isAdmin =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const analyticsEnabled = isFeatureEnabled(featureFlags, 'analytics');
const analyticsModuleOn = useMemo(() => {
const cfg = normalizeSidebarModulesAdmin(
statusState?.status?.SidebarModulesAdmin,
).orgCenter;
return cfg?.enabled !== false && cfg?.analytics !== false;
}, [statusState?.status?.SidebarModulesAdmin]);
const showAnalytics = isAdmin && analyticsEnabled && analyticsModuleOn;
const handleViewMemberUsage = useCallback((member) => {
setSelectedMember(member);
setUsageSheetVisible(true);
}, []);
// 成员额度表格列(useMemo 必须在所有早返回之前,保证 hooks 调用顺序一致)
const memberColumns = useMemo(
() => [
{
title: t('成员'),
dataIndex: 'display_name',
width: 200,
render: (text, record) => (
<div className='flex items-center gap-2.5'>
<div className='flex-shrink-0 w-8 h-8 rounded-full bg-brand/10 text-brand flex items-center justify-center text-xs font-semibold'>
{(text || record.username || '?').charAt(0).toUpperCase()}
</div>
<div className='min-w-0'>
{isAdmin ? (
<div
className='font-medium text-brand-deep truncate text-sm cursor-pointer hover:text-brand hover:underline transition-colors'
onClick={() => handleViewMemberUsage(record)}
>
{text || record.username}
</div>
) : (
<div className='font-medium text-gray-900 dark:text-white truncate text-sm'>
{text || record.username}
</div>
)}
</div>
</div>
),
},
{
title: t('角色'),
dataIndex: 'role',
width: 100,
align: 'center',
render: (role) => {
const config = {
owner: { label: t('所有者'), color: 'red', icon: Crown },
admin: { label: t('管理员'), color: 'blue', icon: ShieldCheck },
dept_admin: {
label: t('部门管理员'),
color: 'cyan',
icon: ShieldCheck,
},
super_admin: {
label: t('超级管理员'),
color: 'violet',
icon: ShieldCheck,
},
member: { label: t('成员'), color: 'grey', icon: Shield },
};
const c = config[role] || config.member;
return (
<div className='flex items-center justify-center gap-1'>
<c.icon
size={12}
className={
role === 'owner'
? 'text-amber-500'
: role === 'admin' ||
role === 'dept_admin' ||
role === 'super_admin'
? 'text-brand-deep'
: 'text-gray-400 dark:text-gray-500'
}
/>
<Tag size='small' color={c.color}>
{c.label}
</Tag>
</div>
);
},
},
{
title: t('周期内已用'),
dataIndex: 'quota_used_in_period',
width: 120,
align: 'right',
render: (v, record) =>
isPeriodicQuotaPeriod(record.quota_period) ? (
<span className='text-gray-700 dark:text-gray-300 font-medium'>
{renderQuota(safeQuotaNumber(v), 2)}
</span>
) : (
<span className='text-xs text-gray-400 dark:text-gray-500'>—</span>
),
},
{
title: t('总已用额度'),
dataIndex: 'used_quota',
width: 120,
align: 'right',
render: (v) => (
<span className='text-gray-700 dark:text-gray-300 font-medium'>
{renderQuota(safeQuotaNumber(v), 2)}
</span>
),
},
{
title: t('额度上限/周期'),
dataIndex: 'quota_limit',
width: 150,
align: 'right',
render: (v, record) => {
const quotaLimit = safeQuotaNumber(v);
return quotaLimit > 0 ? (
<div className='text-right'>
<div className='text-gray-700 dark:text-gray-300'>
{renderQuota(quotaLimit, 2)}
</div>
<div
className={`text-[11px] ${
isPeriodicQuotaPeriod(record.quota_period)
? 'text-gray-400 dark:text-gray-500'
: 'text-amber-500'
}`}
>
{quotaPeriodLimitLabel(t, record.quota_period)}
{!isPeriodicQuotaPeriod(record.quota_period) &&
` · ${t('不重置')}`}
</div>
</div>
) : (
<span className='text-gray-400 dark:text-gray-500'>
{t('不限')}
</span>
);
},
},
{
title: t('使用进度'),
width: 160,
render: (_, record) => {
const quotaLimit = safeQuotaNumber(record.quota_limit);
if (quotaLimit <= 0) {
return (
<span className='text-xs text-gray-400 dark:text-gray-500'>
-
</span>
);
}
// 周期模式按「周期内已用 / 上限」;终身模式按「总已用 / 上限」。
const usedForProgress = isPeriodicQuotaPeriod(record.quota_period)
? safeQuotaNumber(record.quota_used_in_period)
: safeQuotaNumber(record.used_quota);
const percent = Math.min(
100,
Math.round((usedForProgress / quotaLimit) * 100),
);
return (
<div className='flex items-center gap-2'>
<Progress
percent={percent}
size='small'
style={{ width: 100 }}
stroke={usageStrokeColor(percent)}
/>
<span className='text-xs text-gray-500 dark:text-gray-400 w-8 text-right'>
{percent}%
</span>
</div>
);
},
},
],
[t, isAdmin, handleViewMemberUsage],
);
useEffect(() => {
fetch();
fetchQuota();
}, [fetch, fetchQuota]);
if (loading && !data) {
return <Loading />;
}
// 额度使用率(防御性处理)
const totalQuota = data
? Number(data.quota || 0) + Number(data.used_quota || 0)
: 0;
const usedQuota = Number(data?.used_quota || 0);
const usedPercent =
totalQuota > 0
? Math.min(100, Math.round((usedQuota / totalQuota) * 100))
: 0;
// 成员/令牌容量占用率:与其他使用进度共用同一套阈值语义色
const memberPercent =
data?.max_members > 0
? Math.min(
100,
Math.round((Number(data.member_count || 0) / data.max_members) * 100),
)
: 0;
const tokenPercent =
data?.max_tokens > 0
? Math.min(
100,
Math.round((Number(data.token_count || 0) / data.max_tokens) * 100),
)
: 0;
const statusConfig = getStatusConfig(data?.status, t);
// 成员明细对账:成员合计(终身已用)与企业池已用(org.UsedQuota)通常不相等,
// 差额为「未归属」消费(令牌未绑定成员 / 管理员直接使用 / 成员跟踪前的历史),
// 显式列出避免用户误以为成员明细加总应等于顶部「已用额度」。
const memberQuotaRows = quotaData?.member_quotas || [];
const memberQuotaPage = Number(quotaData?.member_page || 1);
const memberQuotaPageSize = Number(quotaData?.member_page_size || 10);
const memberQuotaTotal = Number(
quotaData?.member_total ?? memberQuotaRows.length,
);
const memberUsedSum = Number(
quotaData?.member_used_quota ??
memberQuotaRows.reduce(
(sum, m) => sum + Math.max(0, Number(m.used_quota || 0)),
0,
),
);
const poolUsedQuota = Number(quotaData?.used_quota ?? data?.used_quota ?? 0);
const unattributedQuota = Math.max(0, poolUsedQuota - memberUsedSum);
return (
<div className='p-4 sm:p-6 lg:p-8 space-y-6'>
{/* Header */}
<OrgPageHeader
icon={BarChart2}
title={t('企业概览')}
subtitle={t(
'聚合企业额度、组织规模与成员消耗,和个人工作台保持职责分离',
)}
actions={
<>
{isAdmin && (
<Button
icon={<CreditCard size={14} />}
theme='solid'
type='primary'
onClick={() => navigate('/org/recharge')}
className='!bg-gradient-to-r !from-emerald-500 !to-emerald-600 !border-0 !shadow-md !shadow-emerald-500/30'
>
{t('立即充值')}
</Button>
)}
<Button
icon={<RefreshCw size={14} />}
onClick={() => {
fetch();
fetchQuota(memberQuotaPage, memberQuotaPageSize);
}}
loading={loading || quotaLoading}
>
{t('刷新')}
</Button>
</>
}
/>
{/* 统计卡片 - 三列 */}
<div className='grid grid-cols-1 sm:grid-cols-3 gap-4'>
<StatCard
icon={Users}
title={t('企业成员')}
value={data?.member_count ?? 0}
tone='brand'
loading={loading}
subtitle={
data?.max_members > 0
? `${t('上限')}: ${data.max_members}`
: t('不限')
}
extra={
data?.max_members > 0 && (
<Progress
percent={memberPercent}
size='small'
stroke={usageStrokeColor(memberPercent)}
/>
)
}
/>
<StatCard
icon={Key}
title={t('企业令牌')}
value={data?.token_count ?? 0}
tone='amber'
loading={loading}
subtitle={
data?.max_tokens > 0
? `${t('上限')}: ${data.max_tokens}`
: t('不限')
}
extra={
data?.max_tokens > 0 && (
<Progress
percent={tokenPercent}
size='small'
stroke={usageStrokeColor(tokenPercent)}
/>
)
}
/>
<StatCard
icon={TrendingUp}
title={t('企业状态')}
value={statusConfig.label}
tone='sky'
loading={loading}
extra={
data && (
<Tag
size='small'
color={statusConfig.color}
type='light'
className='mt-0.5'
>
{statusConfig.tagLabel}
</Tag>
)
}
/>
</div>
{/* 额度使用详情 - 全宽 */}
<OrgPanel icon={Wallet} title={t('额度使用详情')} padding='p-5'>
<div className='grid grid-cols-1 sm:grid-cols-3 gap-4'>
{/* 总额度 */}
<div className='flex items-center gap-3 p-4 rounded-xl bg-gray-50/80 dark:bg-neutral-800/50 border border-gray-100 dark:border-neutral-700/50'>
<div className='p-2 rounded-lg bg-brand/10'>
<Coins size={16} className='text-brand-deep' />
</div>
<div>
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
{t('总额度')}
</div>
<div className='text-lg font-bold text-gray-900 dark:text-white'>
{data ? renderQuota(totalQuota, 2) : '-'}
</div>
</div>
</div>
{/* 已用额度 */}
<div className='flex items-center gap-3 p-4 rounded-xl bg-orange-50/80 dark:bg-orange-900/10 border border-orange-100 dark:border-orange-800/30'>
<div className='p-2 rounded-lg bg-orange-100 dark:bg-orange-900/30'>
<Flame
size={16}
className='text-orange-600 dark:text-orange-400'
/>
</div>
<div>
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
{t('已用额度')}
</div>
<div className='text-lg font-bold text-orange-600 dark:text-orange-400'>
{data ? renderQuota(usedQuota, 2) : '-'}
</div>
</div>
</div>
{/* 剩余额度 */}
<div className='flex items-center gap-3 p-4 rounded-xl bg-emerald-50/80 dark:bg-emerald-900/10 border border-emerald-100 dark:border-emerald-800/30'>
<div className='p-2 rounded-lg bg-emerald-100 dark:bg-emerald-900/30'>
<PiggyBank
size={16}
className='text-emerald-600 dark:text-emerald-400'
/>
</div>
<div>
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
{t('剩余额度')}
</div>
<div className='text-lg font-bold text-emerald-600 dark:text-emerald-400'>
{data ? renderQuota(Number(data.quota || 0), 2) : '-'}
</div>
</div>
</div>
</div>
{/* 使用率进度条 */}
<div className='mt-5 pt-4 border-t border-gray-100 dark:border-neutral-800'>
<div className='flex items-center justify-between mb-2'>
<span className='text-sm text-gray-500 dark:text-gray-400'>
{t('使用率(累计)')}
</span>
<span
className='text-sm font-semibold'
style={{ color: usageStrokeColor(usedPercent) }}
>
{usedPercent}%
</span>
</div>
<div className='w-full h-3 bg-gray-100 dark:bg-neutral-800 rounded-full overflow-hidden'>
{/* 渐变由同一语义色的浅调 → 本色构成(单色相),
不再引入第二色相(旧 emerald→teal 与用量分析的 teal 系列色撞车) */}
<div
className='h-full rounded-full transition-all duration-1000 ease-out'
style={{
width: `${Math.max(usedPercent, 0)}%`,
background: `linear-gradient(90deg, color-mix(in srgb, ${usageStrokeColor(usedPercent)} 72%, #fff) 0%, ${usageStrokeColor(usedPercent)} 100%)`,
}}
/>
</div>
</div>
</OrgPanel>
{/* 成员用量明细 */}
<OrgPanel
icon={Users}
title={t('成员用量明细')}
padding='p-5'
bodyClassName='overflow-x-auto'
actions={
<Link
to='/org/members'
className='flex items-center gap-1 text-xs text-brand-deep hover:text-brand transition-colors'
>
{t('查看全部')}
<ArrowRight size={12} />
</Link>
}
>
<Table
columns={memberColumns}
dataSource={memberQuotaRows}
loading={quotaLoading}
rowKey='member_id'
pagination={
memberQuotaTotal > memberQuotaPageSize
? {
currentPage: memberQuotaPage,
pageSize: memberQuotaPageSize,
total: memberQuotaTotal,
showSizeChanger: false,
onPageChange: (page) => fetchQuota(page, memberQuotaPageSize),
}
: false
}
size='small'
empty={<OrgStateBlock icon={Users} title={t('暂无成员数据')} />}
/>
{memberQuotaRows.length > 0 && (
<div className='mt-3 pt-3 border-t border-gray-100 dark:border-neutral-800 flex flex-wrap items-center gap-x-6 gap-y-1 text-xs'>
<span className='text-gray-500 dark:text-gray-400'>
{t('成员合计已用')}:
<span className='font-medium text-gray-700 dark:text-gray-300'>
{renderQuota(memberUsedSum, 2)}
</span>
</span>
<span className='text-gray-500 dark:text-gray-400'>
{t('企业池已用')}:
<span className='font-medium text-gray-700 dark:text-gray-300'>
{renderQuota(poolUsedQuota, 2)}
</span>
</span>
{unattributedQuota > 0 && (
<Tooltip
content={t(
'企业池已用包含未绑定到具体成员的消费(如管理员直接使用、令牌未分配成员、成员跟踪前的历史数据),因此成员合计通常小于企业池已用。',
)}
>
<span className='text-amber-600 dark:text-amber-400 cursor-help'>
{t('未归属差额')}:
<span className='font-medium'>
{renderQuota(unattributedQuota, 2)}
</span>
</span>
</Tooltip>
)}
</div>
)}
</OrgPanel>
{showAnalytics && (
<div className='space-y-3'>
<div className='flex items-center gap-2 px-1'>
<Activity size={16} className='text-brand-deep' />
<div>
<div className='font-semibold text-gray-950 dark:text-white'>
{t('多维用量分析')}
</div>
<div className='text-xs text-gray-500 dark:text-gray-400'>
{t('管理员专属经营数据,避免与个人工作台重复展示')}
</div>
</div>
</div>
<OrgAnalyticsPanel orgId={orgId} />
</div>
)}
{/* 成员用量明细抽屉 */}
<MemberUsageSheet
visible={usageSheetVisible}
onClose={() => setUsageSheetVisible(false)}
member={selectedMember}
orgId={orgId}
t={t}
/>
</div>
);
};
export default OrgDashboard;
@@ -0,0 +1,65 @@
/*
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 from 'react';
import { useTranslation } from 'react-i18next';
import { Tabs, TabPane } from '@douyinfe/semi-ui';
import OrgDsPolicy from './datasecurity/OrgDsPolicy';
import OrgDsRules from './datasecurity/OrgDsRules';
import OrgDsTest from './datasecurity/OrgDsTest';
import OrgDsHitLogs from './datasecurity/OrgDsHitLogs';
import OrgDsChanges from './datasecurity/OrgDsChanges';
// OrgDataSecurity 企业自助数据安全 tab(/org/settings,功能开关 data_security 控制)。
// 五个子 tab:策略配置(覆盖平台默认,只能收紧)/ 自定义规则(企业私有,只增加检测项)/
// 脱敏测试 / 命中审计(本企业口径统计+明细)/ 变更记录(审批与生效留痕)。
// 父组件以 key={orgId} 挂载,切换企业时整棵子树重挂载,各子 tab 无跨企业残留。
// lazyRender:只在首次激活时挂载子 tab,避免一进页面并发拉全部数据。
// 页签形态:这是「企业设置」一级页签里的下一层,必须与一级的下划线页签区分开,
// 所以走 button 型 + .org-nested-tabs(styles/org.css 第 6 节)的分段控件观感;
// 两层都用 line 型时上下两条页签条完全同形,用户读不出层级。
const OrgDataSecurity = ({ orgId, isSuperAdmin, refreshVersion = 0 }) => {
const { t } = useTranslation();
return (
<div className='org-nested-tabs'>
<Tabs type='button' lazyRender keepDOM>
<TabPane tab={t('策略配置')} itemKey='policy'>
<OrgDsPolicy
orgId={orgId}
isSuperAdmin={isSuperAdmin}
refreshVersion={refreshVersion}
/>
</TabPane>
<TabPane tab={t('自定义规则')} itemKey='rules'>
<OrgDsRules orgId={orgId} isSuperAdmin={isSuperAdmin} />
</TabPane>
<TabPane tab={t('脱敏测试')} itemKey='test'>
<OrgDsTest orgId={orgId} />
</TabPane>
<TabPane tab={t('命中审计')} itemKey='hitlogs'>
<OrgDsHitLogs orgId={orgId} />
</TabPane>
<TabPane tab={t('变更记录')} itemKey='changes'>
<OrgDsChanges orgId={orgId} />
</TabPane>
</Tabs>
</div>
);
};
export default OrgDataSecurity;
+366
View File
@@ -0,0 +1,366 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Banner, Button, Form, Toast, Empty, Spin } from '@douyinfe/semi-ui';
import { RefreshCw, Plus, Network } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import { useActualTheme } from '../../context/Theme';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import DeptFlowCanvas from './components/DeptFlowCanvas';
import { buildDeptTreeData } from './components/deptTree';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 部门管理:组织架构画布(多棵树)+ 节点内操作;移动走后端 MoveDepartmentTx 级联 path
const OrgDepartments = ({ orgId }) => {
const { t } = useTranslation();
const actualTheme = useActualTheme();
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [editing, setEditing] = useState(null); // null=新建,否则为编辑对象
const [createParentId, setCreateParentId] = useState(0); // 新建时预填父部门
const [formApi, setFormApi] = useState(null);
const [saving, setSaving] = useState(false);
const [direction, setDirection] = useState('TB'); // TB 纵向 / LR 横向
const [members, setMembers] = useState([]); // 活跃成员(含 department_id),供画布展示成员数/列表
const [budgets, setBudgets] = useState([]); // 部门预算行,供画布节点展示预算用量
// 预算拦截是否生效:false 时不渲染用量条(used 恒为 0,显示会误导管理员"本月没花钱")
const [budgetEnforced, setBudgetEnforced] = useState(null);
const fetchList = useCallback(async () => {
if (!orgId) return;
setLoading(true);
try {
const [res, mres, bres] = await Promise.all([
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
// 成员数据仅是画布辅助信息:网络失败兜底为 null,不连坐部门树
API.get('/api/org/members/all', {
headers: getOrgHeaders(orgId),
}).catch(() => null),
// 部门预算仅是画布辅助信息:失败/未开启预算功能时静默降级为不展示。
// skipErrorHandler:若后端将来把 feature 未开改成真 4xx,.catch 拦不住
// axios 全局拦截器的 toast,必须在请求层显式静默
API.get('/api/org/budget?subject_type=department', {
headers: getOrgHeaders(orgId),
skipErrorHandler: true,
}).catch(() => null),
]);
if (res.data.success) {
setList(res.data.data || []);
} else {
showError(res.data.message);
}
// 成员列表仅用于画布展示,拉取失败不阻塞部门树
if (mres?.data?.success) setMembers(mres.data.data || []);
if (bres?.data?.success) {
// 新后端返回 {items, enforcement_enabled};兼容旧后端直接返回数组
const payload = bres.data.data;
const items = Array.isArray(payload) ? payload : payload?.items || [];
setBudgets(items.filter((b) => b.subject_type === 'department'));
setBudgetEnforced(
Array.isArray(payload)
? null
: (payload?.enforcement_enabled ?? null),
);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
setLoaded(true);
}
}, [orgId]);
useEffect(() => {
fetchList();
}, [fetchList]);
// 上级部门树:编辑时排除自身及其整棵子树(path 前缀判断,避免选出环)。
// 与成员分配不同,上级可以是任意层级节点(disableNonLeaf=false),停用部门不可作新上级。
const parentTreeData = useMemo(
() => [
{ label: t('顶级部门'), value: 0, key: '0' },
...buildDeptTreeData(list, {
disableNonLeaf: false,
excludeSubtreeOf: editing,
disabledLabel: t('已停用'),
}),
],
[list, editing, t],
);
// 弹窗内实时跟踪所选上级(表单值变化同步),用于「上级已有直属成员」提示
const [modalParentId, setModalParentId] = useState(0);
const memberCountByDept = useMemo(() => {
const m = {};
members.forEach((mm) => {
if (mm.department_id)
m[mm.department_id] = (m[mm.department_id] || 0) + 1;
});
return m;
}, [members]);
const parentMemberCount =
modalParentId > 0 ? memberCountByDept[modalParentId] || 0 : 0;
const openCreate = useCallback((parentId = 0) => {
setEditing(null);
setCreateParentId(parentId);
setModalParentId(parentId);
setModalVisible(true);
}, []);
const openEdit = useCallback((record) => {
setEditing(record);
setModalParentId(record.parent_id || 0);
setModalVisible(true);
}, []);
const handleAddChild = useCallback(
(parent) => openCreate(parent.id),
[openCreate],
);
useEffect(() => {
if (modalVisible && formApi) {
if (editing) {
formApi.setValues({
name: editing.name,
parent_id: editing.parent_id || 0,
sort: editing.sort || 0,
status: editing.status || 1,
});
} else {
formApi.setValues({
name: '',
parent_id: createParentId,
sort: 0,
status: 1,
});
}
}
}, [modalVisible, editing, createParentId, formApi]);
const handleSubmit = async () => {
if (!formApi || saving) return;
let values;
try {
values = await formApi.validate();
} catch {
return;
}
setSaving(true);
try {
let res;
if (editing) {
res = await API.put(`/api/org/dept/${editing.id}`, values, {
headers: getOrgHeaders(orgId),
});
} else {
res = await API.post('/api/org/dept', values, {
headers: getOrgHeaders(orgId),
});
}
if (res.data.success) {
Toast.success(editing ? t('部门已更新') : t('部门已创建'));
setModalVisible(false);
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSaving(false);
}
};
const handleDelete = useCallback(
async (record) => {
try {
const res = await API.delete(`/api/org/dept/${record.id}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
Toast.success(t('部门已删除'));
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
},
[orgId, t, fetchList],
);
// 画布连线触发:把 childId 移到 parentId 之下(后端 MoveDepartmentTx 防环并级联 path)
const handleMove = useCallback(
async (childId, parentId) => {
try {
const res = await API.put(
`/api/org/dept/${childId}`,
{ parent_id: parentId },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('部门层级已调整'));
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
fetchList();
}
},
[orgId, t, fetchList],
);
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
icon={Network}
title={t('部门管理')}
subtitle={t('组织架构与部门预算')}
actions={
<>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={fetchList}
>
{t('刷新')}
</Button>
<Button
theme='solid'
icon={<Plus size={14} />}
onClick={() => openCreate(0)}
>
{t('新建顶级部门')}
</Button>
</>
}
/>
<OrgPanel padding='p-0'>
<div className='h-[calc(100vh-270px)] min-h-[480px]'>
{!loaded && loading ? (
<div className='flex h-full items-center justify-center'>
<Spin size='large' />
</div>
) : list.length === 0 ? (
<div className='flex h-full items-center justify-center'>
<Empty
description={t('暂无部门,创建第一个部门开始搭建组织架构')}
>
<Button
theme='solid'
icon={<Plus size={14} />}
onClick={() => openCreate(0)}
>
{t('新建顶级部门')}
</Button>
</Empty>
</div>
) : (
<DeptFlowCanvas
orgId={orgId}
depts={list}
members={members}
budgets={budgetEnforced === false ? [] : budgets}
direction={direction}
onDirectionChange={setDirection}
colorMode={actualTheme === 'dark' ? 'dark' : 'light'}
onAddChild={handleAddChild}
onEdit={openEdit}
onDelete={handleDelete}
onMove={handleMove}
onSaved={fetchList}
/>
)}
</div>
</OrgPanel>
<OrgModal
title={editing ? t('编辑部门') : t('新建部门')}
visible={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
>
{parentMemberCount > 0 && (
<Banner
type='info'
closeIcon={null}
className='mb-3'
description={`${t('所选上级部门已有')} ${parentMemberCount} ${t('名直属成员,新增下级后建议将这些成员迁移到末级部门')}`}
/>
)}
<Form
getFormApi={setFormApi}
onValueChange={(values) =>
setModalParentId((prev) => values.parent_id ?? prev)
}
>
<Form.Input
field='name'
label={t('部门名称')}
rules={[{ required: true, message: t('请输入部门名称') }]}
/>
<Form.TreeSelect
field='parent_id'
label={t('上级部门')}
treeData={parentTreeData}
filterTreeNode
showFilteredOnly
expandAll
style={{ width: '100%' }}
/>
<Form.InputNumber
field='sort'
label={t('排序')}
style={{ width: '100%' }}
/>
{editing && (
<Form.Select
field='status'
label={t('状态')}
optionList={[
{ label: t('启用'), value: 1 },
{ label: t('停用'), value: 2 },
]}
style={{ width: '100%' }}
/>
)}
</Form>
</OrgModal>
</div>
);
};
export default OrgDepartments;
+547
View File
@@ -0,0 +1,547 @@
/*
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 {
Table,
Button,
Select,
Tabs,
TabPane,
Tag,
Toast,
Empty,
Spin,
Typography,
} from '@douyinfe/semi-ui';
import {
RefreshCw,
Users,
TrendingUp,
FileClock,
Check,
X,
} from 'lucide-react';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import { renderQuota } from '../../helpers/render';
import QuotaInput from '../../components/common/ui/QuotaInput';
import { timestamp2string } from '../../helpers/utils';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import { orgStatusColor } from './components/orgStatus';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const reqStatusTag = (t, status) => {
const map = {
pending: t('待审批'),
approved: t('已通过'),
rejected: t('已拒绝'),
canceled: t('已取消'),
expired: t('已过期'),
};
return <Tag color={orgStatusColor(status)}>{map[status] || status}</Tag>;
};
const parseDelta = (payload) => {
try {
return JSON.parse(payload || '{}').cycle_quota_delta || 0;
} catch {
return 0;
}
};
const isFeatureEnabled = (flags, key) => {
const v = flags?.[key];
return v === true || v === 'true' || v === '1' || v === 1;
};
// 部门管理(阶段一):部门负责人管理本部门子树——成员额度 / 部门用量 / 部门审批。
const OrgDeptManage = ({ orgId, featureFlags }) => {
const { t } = useTranslation();
const approvalEnabled = isFeatureEnabled(featureFlags, 'approval');
const [departments, setDepartments] = useState([]);
const [deptId, setDeptId] = useState(null);
const [myMemberId, setMyMemberId] = useState(0);
const [tab, setTab] = useState('members');
const [members, setMembers] = useState([]);
const [membersLoading, setMembersLoading] = useState(false);
const [stat, setStat] = useState(null);
const [ranking, setRanking] = useState([]);
const [usageLoading, setUsageLoading] = useState(false);
const [requests, setRequests] = useState([]);
const [reqLoading, setReqLoading] = useState(false);
const [quotaModal, setQuotaModal] = useState(false);
const [quotaTarget, setQuotaTarget] = useState(null);
const [quotaValue, setQuotaValue] = useState(0);
const [quotaPeriod, setQuotaPeriod] = useState('none');
const [quotaSaving, setQuotaSaving] = useState(false);
// 翻页把一次加载从 1 个请求放大到最多 20 个,切部门/切页签的竞态窗口随之
// 变大:旧部门的翻页循环若在新请求之后才结束,会用旧部门的数据覆盖列表。
const membersSeqRef = useRef(0);
const requestsSeqRef = useRef(0);
const headers = useMemo(() => getOrgHeaders(orgId), [orgId]);
const fetchScope = useCallback(async () => {
try {
const res = await API.get('/api/org/me/dept-scope', { headers });
if (res.data.success) {
const list = res.data.data?.departments || [];
setDepartments(list);
setMyMemberId(res.data.data?.member_id || 0);
setDeptId((prev) => prev || (list[0] ? list[0].id : null));
}
} catch (err) {
showError(err.message);
}
}, [headers]);
useEffect(() => {
fetchScope();
}, [fetchScope]);
const fetchMembers = useCallback(async () => {
if (!deptId) return;
const seq = ++membersSeqRef.current;
setMembersLoading(true);
try {
// 后端 GetPageQuery 把 page_size 静默钳到 100(见 helpers/paging.js),
// 单次请求只拿得到 100 条——部门人数超过 100 时成员列表会静默缺人。
const { items, message } = await collectPagedItems(
(page, size) =>
API.get(
`/api/org/dept-managed/members?dept_id=${deptId}&p=${page}&page_size=${size}`,
{ headers },
),
{ shouldAbort: () => seq !== membersSeqRef.current },
);
if (seq !== membersSeqRef.current) return;
setMembers(items);
if (message) showError(message);
} catch (err) {
if (seq === membersSeqRef.current) showError(err.message);
} finally {
if (seq === membersSeqRef.current) setMembersLoading(false);
}
}, [deptId, headers]);
const fetchUsage = useCallback(async () => {
if (!deptId) return;
setUsageLoading(true);
try {
const [s, r] = await Promise.all([
API.get(`/api/org/dept-managed/stat?dept_id=${deptId}`, { headers }),
API.get(`/api/org/dept-managed/ranking?dept_id=${deptId}&limit=20`, {
headers,
}),
]);
if (s.data.success) setStat(s.data.data);
if (r.data.success) setRanking(r.data.data || []);
} catch (err) {
showError(err.message);
} finally {
setUsageLoading(false);
}
}, [deptId, headers]);
const fetchRequests = useCallback(async () => {
const seq = ++requestsSeqRef.current;
setReqLoading(true);
try {
// 逐页取全:后端把 page_size 静默钳到 100(见 helpers/paging.js)。
const { items, message } = await collectPagedItems(
(page, size) =>
API.get(
`/api/org/requests?status=pending&p=${page}&page_size=${size}`,
{ headers },
),
{ shouldAbort: () => seq !== requestsSeqRef.current },
);
if (seq !== requestsSeqRef.current) return;
setRequests(items);
if (message) showError(message);
} catch (err) {
if (seq === requestsSeqRef.current) showError(err.message);
} finally {
if (seq === requestsSeqRef.current) setReqLoading(false);
}
}, [headers]);
// 部门变化时始终加载成员(成员额度表 + 审批中申请人名称映射都依赖它)
useEffect(() => {
if (deptId) fetchMembers();
}, [deptId, fetchMembers]);
useEffect(() => {
if (tab === 'usage') fetchUsage();
else if (tab === 'approvals' && approvalEnabled) fetchRequests();
}, [tab, deptId, approvalEnabled, fetchUsage, fetchRequests]);
const nameMap = useMemo(() => {
const m = {};
members.forEach((x) => {
m[x.id] = x.remark || x.display_name || x.username || `#${x.id}`;
});
return m;
}, [members]);
const openQuota = (record) => {
setQuotaTarget(record);
setQuotaValue(record.quota_limit || 0);
setQuotaPeriod(record.quota_period || 'none');
setQuotaModal(true);
};
const submitQuota = async () => {
if (!quotaTarget) return;
setQuotaSaving(true);
try {
const res = await API.put(
`/api/org/dept-managed/members/${quotaTarget.id}/quota`,
{
quota_limit: Math.max(0, Number(quotaValue) || 0),
quota_period: quotaPeriod,
},
{ headers },
);
if (res.data.success) {
Toast.success(t('额度已更新'));
setQuotaModal(false);
fetchMembers();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setQuotaSaving(false);
}
};
const decide = async (id, decision) => {
try {
const res = await API.put(
`/api/org/requests/${id}/decision`,
{ decision },
{ headers },
);
if (res.data.success) {
Toast.success(decision === 'approved' ? t('已通过') : t('已拒绝'));
fetchRequests();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const memberColumns = [
{
title: t('成员'),
dataIndex: 'display_name',
render: (v, r) => r.remark || v || r.username || `#${r.id}`,
},
{
title: t('已用额度'),
dataIndex: 'used_quota',
render: (v) => renderQuota(v || 0, 2),
},
{
title: t('额度上限'),
dataIndex: 'quota_limit',
render: (v) => (v > 0 ? renderQuota(v, 2) : t('不限')),
},
{
title: t('操作'),
render: (_, r) => (
<Button size='small' theme='light' onClick={() => openQuota(r)}>
{t('改额度')}
</Button>
),
},
];
const rankColumns = [
{
title: t('成员'),
dataIndex: 'display_name',
render: (v, r) => v || r.username || `#${r.user_id}`,
},
{
title: t('消耗'),
dataIndex: 'quota',
render: (v) => renderQuota(v || 0, 6),
},
{ title: t('请求数'), dataIndex: 'requests' },
{ title: t('Token'), dataIndex: 'tokens' },
];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={t('部门管理')}
subtitle={t('管理本部门成员额度、用量与审批')}
actions={
<>
<Select
value={deptId}
onChange={setDeptId}
placeholder={t('选择部门')}
style={{ width: 180 }}
optionList={departments.map((d) => ({
label: `${d.name}(${d.member_count})`,
value: d.id,
}))}
/>
<Button
theme='light'
icon={<RefreshCw size={14} />}
onClick={() => {
if (tab === 'members') fetchMembers();
else if (tab === 'usage') fetchUsage();
else fetchRequests();
}}
>
{t('刷新')}
</Button>
</>
}
/>
{departments.length === 0 ? (
<Empty
description={t('您当前没有管辖的部门')}
style={{ padding: 60 }}
/>
) : (
<OrgPanel>
<Tabs activeKey={tab} onChange={setTab} type='line'>
<TabPane
tab={
<span className='inline-flex items-center gap-1.5'>
<Users size={14} /> {t('成员额度')}
</span>
}
itemKey='members'
>
<Table
columns={memberColumns}
dataSource={members}
loading={membersLoading}
rowKey='id'
pagination={false}
empty={<Empty description={t('暂无成员')} />}
/>
</TabPane>
<TabPane
tab={
<span className='inline-flex items-center gap-1.5'>
<TrendingUp size={14} /> {t('部门用量')}
</span>
}
itemKey='usage'
>
{usageLoading ? (
<div className='flex justify-center py-10'>
<Spin />
</div>
) : (
<>
<div className='flex gap-4 mb-4'>
<div className='px-4 py-3 rounded-lg bg-[var(--semi-color-fill-0)]'>
<div className='text-xs text-gray-500'>
{t('累计消耗')}
</div>
<div className='text-lg font-semibold'>
{renderQuota(stat?.quota || 0, 2)}
</div>
</div>
<div className='px-4 py-3 rounded-lg bg-[var(--semi-color-fill-0)]'>
<div className='text-xs text-gray-500'>{t('请求数')}</div>
<div className='text-lg font-semibold'>
{stat?.rpm || 0}
</div>
</div>
</div>
<Table
columns={rankColumns}
dataSource={ranking}
rowKey='user_id'
pagination={false}
empty={<Empty description={t('暂无用量数据')} />}
/>
</>
)}
</TabPane>
{approvalEnabled && (
<TabPane
tab={
<span className='inline-flex items-center gap-1.5'>
<FileClock size={14} /> {t('部门审批')}
</span>
}
itemKey='approvals'
>
{reqLoading ? (
<div className='flex justify-center py-10'>
<Spin />
</div>
) : requests.length === 0 ? (
<Empty
description={t('暂无待审批工单')}
style={{ padding: 40 }}
/>
) : (
<div className='flex flex-col divide-y divide-[var(--semi-color-border)]'>
{requests.map((r) => (
<div
key={r.id}
className='flex items-center justify-between py-3 gap-3 flex-wrap'
>
<div className='min-w-0'>
<Text>
{nameMap[r.requester_id] || `#${r.requester_id}`} ·{' '}
{t('提额')} {renderQuota(parseDelta(r.payload), 2)}
</Text>
<div>
<Text type='tertiary' size='small'>
{r.reason ? r.reason + ' · ' : ''}
{r.created_at
? timestamp2string(r.created_at)
: ''}
</Text>
</div>
</div>
<div className='flex items-center gap-2'>
{reqStatusTag(t, r.status)}
{r.status === 'pending' &&
r.requester_id === myMemberId && (
<Tag color='grey'>{t('我的申请')}</Tag>
)}
{r.status === 'pending' &&
r.requester_id !== myMemberId && (
<>
<Button
size='small'
theme='solid'
icon={<Check size={14} />}
onClick={() => decide(r.id, 'approved')}
>
{t('通过')}
</Button>
<Button
size='small'
type='danger'
theme='light'
icon={<X size={14} />}
onClick={() => decide(r.id, 'rejected')}
>
{t('拒绝')}
</Button>
</>
)}
</div>
</div>
))}
</div>
)}
</TabPane>
)}
</Tabs>
</OrgPanel>
)}
<OrgModal
title={t('修改成员额度上限')}
visible={quotaModal}
onOk={submitQuota}
onCancel={() => setQuotaModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={quotaSaving}
>
<p className='text-sm text-gray-500 mb-1'>
{quotaTarget
? quotaTarget.remark ||
quotaTarget.display_name ||
quotaTarget.username
: ''}
</p>
<p className='text-xs text-gray-400 mb-2'>
{t(
'设置该成员的个人额度上限(已用额度达到上限即受限),0 表示不限制;与「提额审批」提升的预算 cap 是不同机制。',
)}
</p>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t('配额周期')}
</label>
<Select
value={quotaPeriod}
onChange={(v) => setQuotaPeriod(v)}
style={{ width: '100%' }}
optionList={[
{ label: t('不限周期(终身累计)'), value: 'none' },
{ label: t('每日'), value: 'daily' },
{ label: t('每周'), value: 'weekly' },
{ label: t('每月'), value: 'monthly' },
]}
/>
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1 mb-2'>
{quotaPeriod === 'none'
? t('终身累计:成员历史消耗达到上限即受限,不重置。')
: quotaPeriod === 'monthly'
? t(
'自然月重置:每月 1 日 00:00 清零,周期为当月 1 日至下月 1 日前。',
)
: t(
'按周期重置:每个周期开始时已用额度清零,上限为单个周期内的可用额度。',
)}
</p>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t('额度上限')}
</label>
<QuotaInput
value={quotaValue}
onChange={setQuotaValue}
minQuota={0}
style={{ width: '100%' }}
placeholder={t('请输入金额,0 表示不限制')}
/>
</OrgModal>
</div>
);
};
export default OrgDeptManage;
+784
View File
@@ -0,0 +1,784 @@
/*
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, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Table,
Tag,
TextArea,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import {
Activity,
FlaskConical,
Gauge,
RefreshCw,
ShieldAlert,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import OrgPanel from './components/OrgPanel';
import './org-effectiveness.css';
const { Title, Text } = Typography;
const dimensions = [
{ value: 'organization', label: '企业总览' },
{ value: 'department', label: '部门' },
{ value: 'project', label: '项目' },
{ value: 'expert', label: '专家' },
{ value: 'skill', label: 'Skill' },
];
const initialExperiment = {
name: '',
skill_id: 0,
version_a_id: 0,
version_b_id: 0,
stable_version_id: 0,
hypothesis: '',
primary_metric: 'quality.adoption_rate',
guardrail_metrics: 'efficiency.quota,quality.return_rate',
target_sample: 100,
allocation_bps: 5000,
stop_conditions: '{"max_cost_increase":0.2,"min_quality_score":60}',
};
const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [dimension, setDimension] = useState('organization');
const [dimensionId, setDimensionId] = useState(0);
const [data, setData] = useState({ metrics: [], alerts: [], states: [] });
const [experiments, setExperiments] = useState([]);
const [loading, setLoading] = useState(false);
const [experimentVisible, setExperimentVisible] = useState(false);
const [experiment, setExperiment] = useState(initialExperiment);
const [comparisonSkillId, setComparisonSkillId] = useState(0);
const [comparison, setComparison] = useState([]);
// 直连链路的技能使用统计(方案 §5.3)。云脑面的效能由 agent_effectiveness 覆盖,
// 直连面此前完全没有回流口径——同一个技能在网关上被用了多少次是看不到的。
const [directUsage, setDirectUsage] = useState([]);
const load = useCallback(async () => {
setLoading(true);
try {
const params = {};
if (dimension !== 'organization') {
params.dimension_type = dimension;
params.dimension_id = dimensionId;
} else {
params.dimension_type = 'organization';
params.dimension_id = 0;
}
const [metrics, experimentRows, usageRows] = await Promise.all([
API.get('/api/org/effectiveness', { headers, params }),
API.get('/api/org/effectiveness/experiments', { headers }),
API.get('/api/org/effectiveness/skill-usage', { headers }),
]);
if (metrics.data?.success) setData(metrics.data.data || {});
if (experimentRows.data?.success)
setExperiments(experimentRows.data.data || []);
// 直连统计失败不阻断整页:它是新增的补充维度,企业若未开 agent_effectiveness
// 功能开关、或成员无 agent_effect_view 权限,该接口会拒绝,此时留空即可。
setDirectUsage(usageRows.data?.success ? usageRows.data.data || [] : []);
} catch (error) {
Toast.error(error.message);
} finally {
setLoading(false);
}
}, [dimension, dimensionId, headers]);
useEffect(() => {
void load();
}, [load]);
const metric = useMemo(() => {
const result = new Map();
for (const row of data.metrics || []) {
const current = result.get(row.metric_key) || {
value: 0,
numerator: 0,
denominator: 0,
};
current.value += Number(row.value || 0);
current.numerator += Number(row.numerator || 0);
current.denominator += Number(row.denominator || 0);
current.latest = row;
result.set(row.metric_key, current);
}
return result;
}, [data.metrics]);
const value = (key, rate = false) => {
const row = metric.get(key);
if (!row) return 0;
return rate && row.denominator
? row.numerator / row.denominator
: row.value;
};
const aggregateToday = async () => {
const metricDate = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date());
const response = await API.post(
'/api/org/effectiveness/aggregate',
{ metric_date: metricDate },
{ headers },
);
if (response.data?.success) {
Toast.success(t('聚合已完成'));
await load();
}
};
const createExperiment = async () => {
let stopConditions;
try {
stopConditions = JSON.parse(experiment.stop_conditions);
} catch {
Toast.error(t('停止条件必须是合法 JSON'));
return;
}
const response = await API.post(
'/api/org/effectiveness/experiments',
{
...experiment,
guardrail_metrics: experiment.guardrail_metrics
.split(',')
.map((item) => item.trim())
.filter(Boolean),
stop_conditions: stopConditions,
},
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('创建失败'));
return;
}
setExperimentVisible(false);
setExperiment(initialExperiment);
await load();
};
const experimentAction = async (row, action) => {
const endpoint = `/api/org/effectiveness/experiments/${row.id}/${action}`;
const payload =
action === 'start'
? {}
: {
rollback: true,
winner_version_id: row.stable_version_id,
reason: '管理员立即停止并回退到稳定版本',
};
const response = await API.post(endpoint, payload, { headers });
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
await load();
};
// 实验此前只能建、只能起停:建错的草稿和终态实验会永久堆在列表里。
// 运行中的实验后端会拒绝删除(须先停止或回退),这里按状态禁用按钮先行拦一层。
const deleteExperiment = async (row) => {
const response = await API.delete(
`/api/org/effectiveness/experiments/${row.id}`,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
Toast.success(t('实验已删除'));
await load();
};
const loadComparison = async () => {
if (!comparisonSkillId) return;
const response = await API.get(
`/api/org/effectiveness/quality/skills/${comparisonSkillId}/versions`,
{ headers },
);
if (response.data?.success) setComparison(response.data.data || []);
};
const showAlertSamples = (row) => {
let ids = [];
try {
ids = JSON.parse(row.sample_run_ids || '[]');
} catch {
ids = [];
}
Modal.info({
title: t('告警任务样本'),
content: (
<div className='org-effect-samples'>
{ids.map((id) => (
<code key={id}>{id}</code>
))}
</div>
),
});
};
const cards = [
{
label: t('覆盖任务'),
value: Math.round(value('coverage.task_count')).toLocaleString(),
detail: `${Math.round(value('coverage.active_member_count'))} ${t('活跃员工')}`,
icon: Activity,
},
{
label: t('节省时间'),
value: `${Math.round(value('efficiency.saved_minutes'))} min`,
detail: `${Math.round(value('efficiency.manual_minutes'))} min ${t('人工基线')}`,
icon: Gauge,
},
{
label: t('质量评分'),
value: metric.has('quality.score')
? value('quality.score', true).toFixed(1)
: t('数据不足'),
detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`,
icon: FlaskConical,
},
{
label: t('治理风险'),
value: Math.round(value('governance.failed_tool_call_count')),
detail: `${Math.round(value('governance.write_call_count'))} ${t('写操作')}`,
icon: ShieldAlert,
},
];
// 使用指引:看板阅读指南(无上手流程,不出进度胶囊)——重点解释
// 每个指标的口径和数据来源,避免管理员把抽样数据当精确账。
const guide = usePageGuide({
guideKey: 'org-effectiveness',
title: t('效能分析 · 使用指引'),
intro: t('回答四个问题:谁在用、省了多少时间、成本对不对账、质量是否改善'),
steps: [
{
title: t('选维度查看'),
detail: t('从企业总览切到部门 / 项目 / 专家 / Skill 维度'),
points: [
t('非总览维度需在旁边输入框填对应 ID(部门 ID、项目 ID 等)'),
t('切换后数据自动刷新;「刷新」按钮可随时重拉'),
],
},
{
title: t('读懂四张指标卡'),
detail: t('覆盖、节省、质量、风险各一张'),
points: [
t('「节省时间」的基线来自成员完成任务后的「确认节省时间」抽样'),
t('「质量评分」样本不足时显示「数据不足」,不是故障'),
t('「治理风险」统计失败的工具调用与写操作次数'),
],
},
{
title: t('下钻分析'),
detail: t('从汇总数字追到具体任务与版本'),
points: [
t('「成本对账」三栏:运行结算、消费明细、差额;差额红色需关注'),
t('「质量告警」每行可「下钻」查看样本任务 ID'),
t('「灰度版本质量对比」输入 Skill ID 可对比各版本首交付通过率'),
],
},
{
title: t('让数据更准'),
detail: t('看板质量取决于回流数据的完整度'),
points: [
t('鼓励成员在任务完成后点 👍/👎 并填写「确认节省时间」'),
t('「网关直连技能使用」需密钥开启「技能注入」后才有数据'),
t('注意:直连面板的 token 与额度是整请求口径,不能跨技能相加'),
],
},
],
faq: [
{
q: t('指标全是 0 或「数据不足」?'),
a: t('刚启用时样本少属正常,随任务量与成员反馈积累会逐步补全'),
},
{
q: t('「重算今日」是干什么的?'),
a: t(
'管理员手动触发当日指标聚合(按 Asia/Shanghai 日期),通常无需使用',
),
},
],
});
return (
<div className='org-effect-page'>
<header className='org-effect-hero'>
<div>
<Title heading={2}>{t('效能分析')}</Title>
<Text type='tertiary'>
{t('回答谁在用、节省多少时间、成本是否对账、质量与安全是否改善。')}
</Text>
</div>
<div className='org-effect-toolbar'>
<PageGuideTrigger guide={guide} />
<Select
value={dimension}
optionList={dimensions}
onChange={setDimension}
/>
{dimension !== 'organization' && (
<InputNumber
min={1}
value={dimensionId}
onChange={setDimensionId}
/>
)}
<Button
icon={<RefreshCw size={15} />}
loading={loading}
onClick={load}
>
{t('刷新')}
</Button>
{canManagePolicy && (
<Button onClick={aggregateToday}>{t('重算今日')}</Button>
)}
</div>
</header>
<PageGuideDrawer guide={guide} />
<section className='org-effect-grid'>
{cards.map(({ label, value: cardValue, detail, icon: Icon }) => (
<article className='org-effect-card' key={label}>
<Icon size={20} />
<Text>{label}</Text>
<strong>{cardValue}</strong>
<small>{detail}</small>
</article>
))}
</section>
<OrgPanel title={t('网关直连技能使用(近 30 天)')}>
{directUsage.length === 0 ? (
<Text type='tertiary'>
{t(
'暂无数据。开启密钥的「技能注入」后,用该密钥直连调用的技能使用情况会回流到这里。',
)}
</Text>
) : (
<>
<Text type='tertiary' size='small'>
{t(
'统计口径:token 与额度是整条请求的量级,多技能同时命中时全额计入每个技能,不是按技能分摊的成本,勿相加。',
)}
</Text>
<Table
size='small'
pagination={false}
dataSource={directUsage}
rowKey='skill_id'
columns={[
{
title: t('技能'),
dataIndex: 'name',
render: (name, record) =>
name || record.canonical_id || `#${record.skill_id}`,
},
{ title: t('调用次数'), dataIndex: 'request_count' },
{
title: t('占比'),
dataIndex: 'share_percent',
render: (share) => `${(share || 0).toFixed(1)}%`,
},
{
title: t('提示词 token'),
dataIndex: 'prompt_tokens',
render: (tokens) => (tokens || 0).toLocaleString(),
},
]}
/>
</>
)}
</OrgPanel>
<div className='org-effect-columns'>
<OrgPanel title={t('成本对账')}>
<div className='org-effect-reconcile'>
<span>{t('运行结算')}</span>
<b>{Math.round(value('efficiency.quota')).toLocaleString()}</b>
<span>{t('消费明细')}</span>
<b>
{Math.round(
value('efficiency.settlement_quota') +
value('efficiency.adjustment_quota'),
).toLocaleString()}
</b>
<span>{t('差额')}</span>
<b
className={
value('efficiency.reconciliation_gap') ? 'is-risk' : 'is-ok'
}
>
{Math.round(
value('efficiency.reconciliation_gap'),
).toLocaleString()}
</b>
</div>
</OrgPanel>
<OrgPanel title={t('质量告警')}>
{isMobile ? (
<div className='org-effect-mobile-list'>
{(data.alerts || []).map((row) => (
<article key={row.id}>
<div>
<strong>Skill #{row.dimension_id}</strong>
<Tag color={row.status === 'open' ? 'red' : 'green'}>
{row.status}
</Tag>
</div>
<span>
{t('评分')}: {Number(row.score).toFixed(1)}
</span>
<span>
{t('样本')}: {row.sample_count}
</span>
<Button size='small' onClick={() => showAlertSamples(row)}>
{t('下钻')}
</Button>
</article>
))}
</div>
) : (
<Table
size='small'
pagination={false}
dataSource={data.alerts || []}
columns={[
{ title: t('Skill'), dataIndex: 'dimension_id' },
{
title: t('评分'),
dataIndex: 'score',
render: (score) => Number(score).toFixed(1),
},
{ title: t('样本'), dataIndex: 'sample_count' },
{
title: t('样本任务'),
render: (_, row) => (
<Button size='small' onClick={() => showAlertSamples(row)}>
{t('下钻')}
</Button>
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (status) => (
<Tag color={status === 'open' ? 'red' : 'green'}>
{status}
</Tag>
),
},
]}
/>
)}
</OrgPanel>
</div>
<OrgPanel
title={t('灰度版本质量对比')}
actions={
<div className='flex gap-2'>
<InputNumber
min={1}
placeholder='Skill ID'
value={comparisonSkillId}
onChange={setComparisonSkillId}
/>
<Button onClick={loadComparison}>{t('下钻版本')}</Button>
</div>
}
>
{isMobile ? (
<div className='org-effect-mobile-list'>
{comparison.map((row) => (
<article key={row.version_id}>
<strong>
{t('版本')} #{row.version_id}
</strong>
<span>
{t('首次交付样本')}: {row.first_delivery_count}
</span>
<span>
{t('首次交付通过率')}:{' '}
{row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
: t('数据不足')}
</span>
<span>
{t('退回率')}:{' '}
{row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
: t('数据不足')}
</span>
<span>
{t('平均成本')}:{' '}
{row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足')}
</span>
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={comparison}
columns={[
{ title: t('版本'), dataIndex: 'version_id' },
{ title: t('首次交付样本'), dataIndex: 'first_delivery_count' },
{
title: t('首次交付通过率'),
render: (_, row) =>
row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
: t('数据不足'),
},
{
title: t('退回率'),
render: (_, row) =>
row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
: t('数据不足'),
},
{
title: t('平均成本'),
render: (_, row) =>
row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足'),
},
]}
/>
)}
</OrgPanel>
<OrgPanel
title={t('Skill A/B 实验')}
actions={
canManageSkills ? (
<Button onClick={() => setExperimentVisible(true)}>
{t('新建实验')}
</Button>
) : null
}
>
{isMobile ? (
<div className='org-effect-mobile-list'>
{experiments.map((row) => (
<article key={row.id}>
<div>
<strong>{row.name}</strong>
<Tag>{row.status}</Tag>
</div>
<span>Skill #{row.skill_id}</span>
<span>
A / B: {row.version_a_id} / {row.version_b_id}
</span>
<span>
{t('目标样本')}: {row.target_sample}
</span>
{canManageSkills && (
<div className='flex gap-1'>
<Button
size='small'
type={row.status === 'running' ? 'danger' : 'primary'}
disabled={!['draft', 'running'].includes(row.status)}
onClick={() =>
experimentAction(
row,
row.status === 'draft' ? 'start' : 'stop',
)
}
>
{row.status === 'draft' ? t('开始') : t('停止并回退')}
</Button>
<Popconfirm
title={t('确认删除该实验?')}
content={t(
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
)}
onConfirm={() => deleteExperiment(row)}
>
<Button
size='small'
theme='light'
type='danger'
disabled={row.status === 'running'}
>
{t('删除')}
</Button>
</Popconfirm>
</div>
)}
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={experiments}
columns={[
{ title: t('实验'), dataIndex: 'name' },
{ title: 'Skill', dataIndex: 'skill_id' },
{
title: 'A / B',
render: (_, row) => `${row.version_a_id} / ${row.version_b_id}`,
},
{ title: t('目标样本'), dataIndex: 'target_sample' },
{
title: t('状态'),
dataIndex: 'status',
render: (status) => <Tag>{status}</Tag>,
},
{
title: t('操作'),
render: (_, row) =>
canManageSkills && (
<div className='flex gap-1'>
<Button
size='small'
type={row.status === 'running' ? 'danger' : 'primary'}
disabled={!['draft', 'running'].includes(row.status)}
onClick={() =>
experimentAction(
row,
row.status === 'draft' ? 'start' : 'stop',
)
}
>
{row.status === 'draft' ? t('开始') : t('停止并回退')}
</Button>
<Popconfirm
title={t('确认删除该实验?')}
content={t(
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
)}
onConfirm={() => deleteExperiment(row)}
>
<Button
size='small'
theme='light'
type='danger'
disabled={row.status === 'running'}
>
{t('删除')}
</Button>
</Popconfirm>
</div>
),
},
]}
/>
)}
</OrgPanel>
<Modal
title={t('新建 Skill A/B 实验')}
visible={experimentVisible}
onCancel={() => setExperimentVisible(false)}
onOk={createExperiment}
width={680}
>
<div className='org-effect-form'>
<Input
placeholder={t('实验名称')}
value={experiment.name}
onChange={(name) => setExperiment({ ...experiment, name })}
/>
{[
'skill_id',
'version_a_id',
'version_b_id',
'stable_version_id',
].map((key) => (
<InputNumber
key={key}
min={1}
placeholder={key}
value={experiment[key]}
onChange={(next) => setExperiment({ ...experiment, [key]: next })}
/>
))}
<TextArea
placeholder={t('实验假设')}
value={experiment.hypothesis}
onChange={(hypothesis) =>
setExperiment({ ...experiment, hypothesis })
}
/>
<Input
placeholder={t('主指标')}
value={experiment.primary_metric}
onChange={(primary_metric) =>
setExperiment({ ...experiment, primary_metric })
}
/>
<Input
placeholder={t('护栏指标,逗号分隔')}
value={experiment.guardrail_metrics}
onChange={(guardrail_metrics) =>
setExperiment({ ...experiment, guardrail_metrics })
}
/>
<InputNumber
min={10}
placeholder={t('目标样本')}
value={experiment.target_sample}
onChange={(target_sample) =>
setExperiment({ ...experiment, target_sample })
}
/>
<TextArea
placeholder={t('停止条件 JSON')}
value={experiment.stop_conditions}
onChange={(stop_conditions) =>
setExperiment({ ...experiment, stop_conditions })
}
/>
</div>
</Modal>
</div>
);
};
export default OrgEffectiveness;
+646
View File
@@ -0,0 +1,646 @@
/*
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, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Select,
TabPane,
Tabs,
Tag,
TextArea,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import OrgPanel from './components/OrgPanel';
import {
usePageGuide,
PageGuideDrawer,
PageGuidePill,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import './org-experts.css';
const { Title, Paragraph, Text } = Typography;
const emptyForm = {
definition_id: 0,
expert_key: '',
source_expert_id: 0,
name_zh: '',
name_en: '',
description_zh: '',
description_en: '',
scenario_zh: '',
scenario_en: '',
system_prompt_zh: '',
system_prompt_en: '',
default_model: '',
fallback_models: '',
input_schema:
'{\n "type": "object",\n "properties": {\n "task": { "type": "string" }\n },\n "required": ["task"]\n}',
required_sections_zh: '',
required_sections_en: '',
forbidden_placeholders: '',
contract_type: 'markdown',
artifact_mode: 'inline',
artifact_file_name: '',
artifact_content_type: '',
max_output_tokens: 2048,
max_total_output_tokens: 4096,
max_step_quota: 100000,
max_task_quota: 200000,
default_language: 'zh',
safety_policy_ref: 'org-default',
step_plan:
'[\n {\n "key": "primary",\n "name_zh": "生成交付物",\n "name_en": "Generate deliverable",\n "instruction_zh": "根据任务生成最终交付物。",\n "instruction_en": "Generate the final deliverable for the task.",\n "max_output_tokens": 2048\n }\n]',
};
const csv = (value) =>
String(value || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean);
const OrgExperts = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [definitions, setDefinitions] = useState([]);
const [sources, setSources] = useState([]);
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
const [loaded, setLoaded] = useState(false);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [form, setForm] = useState(emptyForm);
const load = useCallback(async () => {
// allSettled: a transient catalog failure must not discard the managed
// expert list and render a misleading "no experts yet" empty state.
const [managed, catalog] = await Promise.allSettled([
API.get('/api/org/experts', { headers, skipErrorHandler: true }),
// Mirrored under the experts router so an admin holding only
// expert_manage (without the cloud_brain admin permission) can still
// load the platform source catalog.
API.get('/api/org/experts/catalog?locale=zh', {
headers,
skipErrorHandler: true,
}),
]);
if (managed.status === 'fulfilled' && managed.value.data?.success) {
setDefinitions(managed.value.data.data || []);
} else {
const message =
managed.status === 'fulfilled'
? managed.value.data?.message
: managed.reason?.response?.data?.message;
Toast.error(message || t('企业专家列表加载失败'));
}
if (catalog.status === 'fulfilled' && catalog.value.data?.success) {
setSources(
(catalog.value.data.data || []).filter((item) => !item.organization_id),
);
} else {
const message =
catalog.status === 'fulfilled'
? catalog.value.data?.message
: catalog.reason?.response?.data?.message;
Toast.error(message || t('平台专家目录不可用,请检查管理权限'));
}
setLoaded(true);
}, [headers, t]);
useEffect(() => {
void load();
}, [load]);
const update = (key, value) =>
setForm((current) => ({ ...current, [key]: value }));
const beginVersion = (view) => {
const current = view?.current;
if (!current) {
// A definition whose first version is still draft/pending_review has no
// `current`; keep its identity so the new version attaches to it
// instead of colliding with the (organization_id, expert_key) unique
// index as a brand-new definition.
setForm({
...emptyForm,
definition_id: view?.definition?.id || 0,
expert_key: view?.definition?.expert_key || '',
});
} else {
let contract = {};
try {
contract = JSON.parse(current.output_contract || '{}');
} catch {
contract = {};
}
setForm({
...emptyForm,
definition_id: view.definition.id,
expert_key: current.expert_key,
source_expert_id: current.source_expert_id,
name_zh: current.name_zh,
name_en: current.name_en,
description_zh: current.description_zh,
description_en: current.description_en,
scenario_zh: current.scenario_zh,
scenario_en: current.scenario_en,
system_prompt_zh: '',
system_prompt_en: '',
default_model: current.default_model,
fallback_models: (() => {
try {
return JSON.parse(current.fallback_models || '[]').join(', ');
} catch {
return '';
}
})(),
input_schema: current.input_schema || emptyForm.input_schema,
required_sections_zh: (contract.required_sections_zh || []).join(', '),
required_sections_en: (contract.required_sections_en || []).join(', '),
forbidden_placeholders: (contract.forbidden_placeholders || []).join(
', ',
),
contract_type: contract.type || 'markdown',
artifact_mode: contract.artifact_mode || 'inline',
artifact_file_name: contract.file_name || '',
artifact_content_type: contract.content_type || '',
max_output_tokens: current.max_output_tokens,
max_total_output_tokens: current.max_total_output_tokens,
max_step_quota: current.max_step_quota,
max_task_quota: current.max_task_quota,
default_language: current.default_language,
safety_policy_ref: current.safety_policy_ref,
step_plan: current.step_plan || emptyForm.step_plan,
});
}
setOpen(true);
};
const save = async () => {
let inputSchema;
let stepPlan;
try {
inputSchema = JSON.parse(form.input_schema);
stepPlan = JSON.parse(form.step_plan);
} catch {
Toast.error(t('输入 Schema 与步骤计划必须是合法 JSON'));
return;
}
setSaving(true);
try {
const response = await API.post(
'/api/org/experts/versions',
{
...form,
fallback_models: csv(form.fallback_models),
input_schema: inputSchema,
output_contract: {
type: form.contract_type,
required_sections_zh: csv(form.required_sections_zh),
required_sections_en: csv(form.required_sections_en),
required_table_columns: [],
require_citations: false,
forbidden_placeholders: csv(form.forbidden_placeholders),
repair_once: true,
artifact_mode: form.artifact_mode,
file_name:
form.artifact_mode === 'file' ? form.artifact_file_name : '',
content_type:
form.artifact_mode === 'file' ? form.artifact_content_type : '',
},
step_plan: stepPlan,
skill_ids: [],
},
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('保存失败'));
return;
}
Toast.success(t('专家草稿版本已创建'));
setOpen(false);
await load();
} finally {
setSaving(false);
}
};
const submit = async (id) => {
const response = await API.post(
`/api/org/experts/versions/${id}/submit`,
{},
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('提交失败'));
return;
}
Toast.success(t('已提交平台审核'));
await load();
};
// 使用指引:企业专家从派生到上岗的流程,完成态由专家/版本数据驱动。
const guide = usePageGuide({
guideKey: 'org-experts',
ready: loaded,
title: t('企业专家工坊 · 使用指引'),
intro: t('派生 → 配置 → 平台审核 → 发布上岗,版本不可变、全程留审计'),
steps: [
{
title: t('从平台来源派生专家'),
detail: t('选择一个平台专家作为安全基线开始创建'),
done: definitions.length > 0,
cta: t('去创建专家'),
onAction: () => beginVersion(null),
points: [
t('专家标识创建后不可更改;「平台来源」决定继承哪套安全基线'),
t('填写中英文名称、说明与适用场景,成员在云端大脑会看到这些信息'),
],
},
{
title: t('配置模型与输出契约'),
detail: t('默认模型、降级序列、提示词与交付格式'),
done: definitions.length > 0,
points: [
t('「身份与模型」页配置默认模型与逗号分隔的降级模型序列'),
t(
'「提示词与契约」页定义系统提示词、输入 Schema 与产物形式(页面文本或安全文件)',
),
t('「步骤与预算」页规划多步骤交付路径和 token 预算上限'),
],
},
{
title: t('提交平台审核'),
detail: t('保存生成草稿版本,草稿需平台审核后才能发布'),
done: definitions.some((view) =>
(view.versions || []).some((version) => version.status !== 'draft'),
),
points: [
t('在专家卡片的版本列表里对 draft 版本点「提交审核」'),
t('每个版本不可变:审核中发现问题就「创建新版本」修正后重新提交'),
],
},
{
title: t('发布后到云端大脑分发'),
detail: t('审核通过的版本成为当前版本,再决定谁能用'),
done: definitions.some((view) => Boolean(view.current)),
points: [
t(
'到「云端大脑」右上角「管理企业专家」按全企业/部门/项目/成员启停分发',
),
t('停用后该范围内成员无法创建新任务,进行中任务按安全策略结算'),
],
},
],
faq: [
{
q: t('版本一直是 draft?'),
a: t('草稿不会自动送审,需要在版本列表手动点「提交审核」'),
},
{
q: t('专家显示「等待首个版本发布」?'),
a: t('尚无审核通过的版本;通过后自动成为当前版本'),
},
],
});
const closeGuide = guide.close;
// 抽屉进度是组织私有的:切组织时关闭并复位 loaded,
// 否则重取窗口内胶囊会按旧组织数据渲染完成态。
useEffect(() => {
setLoaded(false);
closeGuide();
}, [orgId, closeGuide]);
return (
<main className='org-expert-page'>
<header className='org-expert-hero'>
<div>
<Title heading={3}>{t('企业专家工坊')}</Title>
<Paragraph>
{t(
'从平台安全基线派生不可变版本,配置模型、契约与多步骤交付路径。',
)}
</Paragraph>
</div>
<div className='org-expert-hero-actions'>
<PageGuideTrigger guide={guide} />
<Button
theme='solid'
type='primary'
onClick={() => beginVersion(null)}
>
{t('创建企业专家')}
</Button>
</div>
</header>
<PageGuidePill guide={guide} />
<PageGuideDrawer guide={guide} />
<section className='org-expert-grid'>
{definitions.length === 0 ? (
<div className='org-expert-empty'>
<strong>{t('尚未创建企业专家')}</strong>
<Text type='tertiary'>
{t('选择一个平台专家作为安全来源开始派生。')}
</Text>
</div>
) : (
definitions.map((view) => (
<OrgPanel
key={view.definition.id}
title={view.current?.name_zh || view.definition.expert_key}
actions={<Tag color='green'>{view.definition.status}</Tag>}
>
<Paragraph>
{view.current?.description_zh || t('等待首个版本发布')}
</Paragraph>
<div className='org-expert-version-list'>
{(view.versions || []).map((version) => (
<div key={version.id}>
<span>v{version.version}</span>
<Tag>{version.status}</Tag>
{version.status === 'draft' && (
<Button size='small' onClick={() => submit(version.id)}>
{t('提交审核')}
</Button>
)}
</div>
))}
</div>
<Button onClick={() => beginVersion(view)}>
{t('创建新版本')}
</Button>
</OrgPanel>
))
)}
</section>
<Modal
title={form.definition_id ? t('创建专家新版本') : t('创建企业专家')}
visible={open}
onCancel={() => setOpen(false)}
onOk={save}
confirmLoading={saving}
width={880}
className='org-expert-modal'
>
<Tabs type='line'>
<TabPane tab={t('身份与模型')} itemKey='identity'>
<div className='org-expert-form-grid'>
<label>
{t('专家标识')}
<Input
value={form.expert_key}
disabled={!!form.definition_id}
onChange={(v) => update('expert_key', v)}
/>
</label>
<label>
{t('平台来源')}
<Select
value={form.source_expert_id || undefined}
onChange={(v) => update('source_expert_id', v)}
optionList={sources.map((item) => ({
value: item.id,
label: `${item.name} · v${item.version}`,
}))}
/>
</label>
<label>
{t('中文名称')}
<Input
value={form.name_zh}
onChange={(v) => update('name_zh', v)}
/>
</label>
<label>
{t('英文名称')}
<Input
value={form.name_en}
onChange={(v) => update('name_en', v)}
/>
</label>
<label className='wide'>
{t('中文描述')}
<TextArea
value={form.description_zh}
onChange={(v) => update('description_zh', v)}
/>
</label>
<label className='wide'>
{t('英文描述')}
<TextArea
value={form.description_en}
onChange={(v) => update('description_en', v)}
/>
</label>
<label>
{t('中文场景')}
<Input
value={form.scenario_zh}
onChange={(v) => update('scenario_zh', v)}
/>
</label>
<label>
{t('英文场景')}
<Input
value={form.scenario_en}
onChange={(v) => update('scenario_en', v)}
/>
</label>
<label>
{t('默认模型')}
<Input
value={form.default_model}
onChange={(v) => update('default_model', v)}
/>
</label>
<label>
{t('降级模型序列')}
<Input
value={form.fallback_models}
onChange={(v) => update('fallback_models', v)}
placeholder='model-a, model-b'
/>
</label>
</div>
</TabPane>
<TabPane tab={t('提示词与契约')} itemKey='contract'>
<div className='org-expert-form-grid'>
<label className='wide'>
{t('中文系统提示词')}
<TextArea
autosize={{ minRows: 5, maxRows: 12 }}
value={form.system_prompt_zh}
onChange={(v) => update('system_prompt_zh', v)}
/>
</label>
<label className='wide'>
{t('英文系统提示词')}
<TextArea
autosize={{ minRows: 5, maxRows: 12 }}
value={form.system_prompt_en}
onChange={(v) => update('system_prompt_en', v)}
/>
</label>
<label className='wide'>
{t('输入 JSON Schema')}
<TextArea
className='mono'
autosize={{ minRows: 6, maxRows: 14 }}
value={form.input_schema}
onChange={(v) => update('input_schema', v)}
/>
</label>
<label>
{t('输出类型')}
<Select
value={form.contract_type}
onChange={(v) => update('contract_type', v)}
optionList={['markdown', 'json', 'text'].map((v) => ({
value: v,
label: v,
}))}
/>
</label>
<label>
{t('默认语言')}
<Select
value={form.default_language}
onChange={(v) => update('default_language', v)}
optionList={[
{ value: 'zh', label: '中文' },
{ value: 'en', label: 'English' },
]}
/>
</label>
<label>
{t('产物交付方式')}
<Select
value={form.artifact_mode}
onChange={(v) => update('artifact_mode', v)}
optionList={[
{ value: 'inline', label: t('页面内文本') },
{ value: 'file', label: t('安全文件下载') },
]}
/>
</label>
{form.artifact_mode === 'file' && (
<>
<label>
{t('文件名')}
<Input
value={form.artifact_file_name}
onChange={(v) => update('artifact_file_name', v)}
placeholder='artifact.md'
/>
</label>
<label>
{t('文件 MIME 类型')}
<Select
value={form.artifact_content_type || undefined}
onChange={(v) => update('artifact_content_type', v)}
optionList={[
{ value: 'text/markdown', label: 'text/markdown' },
{
value: 'application/json',
label: 'application/json',
},
{ value: 'text/plain', label: 'text/plain' },
{ value: 'text/csv', label: 'text/csv' },
]}
/>
</label>
<p className='wide org-expert-help'>
{t(
'文件会先校验格式、拦截 CSV 公式注入并通过恶意软件扫描,再写入带版本号的私有 COS;下载链接每次重新鉴权且仅短期有效。',
)}
</p>
</>
)}
<label>
{t('中文必需章节')}
<Input
value={form.required_sections_zh}
onChange={(v) => update('required_sections_zh', v)}
/>
</label>
<label>
{t('英文必需章节')}
<Input
value={form.required_sections_en}
onChange={(v) => update('required_sections_en', v)}
/>
</label>
<label className='wide'>
{t('禁用占位符')}
<Input
value={form.forbidden_placeholders}
onChange={(v) => update('forbidden_placeholders', v)}
/>
</label>
</div>
</TabPane>
<TabPane tab={t('步骤与预算')} itemKey='steps'>
<div className='org-expert-form-grid'>
<label className='wide'>
{t('步骤计划 JSON')}
<TextArea
className='mono'
autosize={{ minRows: 10, maxRows: 20 }}
value={form.step_plan}
onChange={(v) => update('step_plan', v)}
/>
</label>
{[
'max_output_tokens',
'max_total_output_tokens',
'max_step_quota',
'max_task_quota',
].map((key) => (
<label key={key}>
{key}
<InputNumber
value={form[key]}
min={1}
onChange={(v) => update(key, Number(v))}
/>
</label>
))}
<label className='wide'>
{t('安全策略引用')}
<Input
value={form.safety_policy_ref}
onChange={(v) => update('safety_policy_ref', v)}
/>
</label>
</div>
</TabPane>
</Tabs>
</Modal>
</main>
);
};
export default OrgExperts;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,753 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Form,
Toast,
Tag,
Popconfirm,
Banner,
Typography,
Tooltip,
} from '@douyinfe/semi-ui';
import {
RefreshCw,
UserPlus,
Upload as UploadIcon,
KeyRound,
IdCard,
} from 'lucide-react';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import DeptTreeSelect from './components/DeptTreeSelect';
import {
buildDeptTreeData,
buildDeptFullNameMap,
hasChildDept,
} from './components/deptTree';
import { isOrgFeatureEnabled } from './orgFeatureFlags';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const formatImportError = (t, row) => {
const params = row?.error_params || {};
switch (row?.error_code) {
case 'login_name_required':
return t('企业内登录名必填');
case 'login_name_too_long':
return t(
'企业内登录名不能超过 {{max}} 个字符,当前 {{actual}} 个字符',
params,
);
case 'employee_no_too_long':
return t('工号不能超过 {{max}} 个字符', params);
case 'login_name_exists':
return t('企业内登录名已存在');
case 'login_name_reserved':
return t('该登录名为系统保留名称,请换一个登录名');
case 'email_exists':
return t('该邮箱已是平台用户,请使用企业代码加入企业');
case 'member_limit_reached':
return t('企业成员数量已达到上限 {{max}}', params);
case 'password_generation_failed':
return t('初始密码生成失败,请重试');
case 'create_failed':
return t('账号创建失败,请检查数据后重试');
default:
return row?.error || t('导入失败');
}
};
// 状态色遵循 components/orgStatus.js 的统一口径:正常=green,停用/离职=grey(归档态,非错误态)
const statusTag = (t, s) =>
s === 1 ? (
<Tag color='green'>{t('正常')}</Tag>
) : (
<Tag color='grey'>{t('已停用/离职')}</Tag>
);
// 员工账号:企业托管账号生命周期(建号/CSV导入/重置密码/离职回收,PR6a)。
const OrgMemberAccounts = ({
orgId,
orgRole = null,
embedded = false,
featureFlags = null,
}) => {
const { t } = useTranslation();
// 企业管理员只能重置本企业托管账号;平台超管额外可重置个人账号(后端同口径校验)
const isSuperAdmin = orgRole === 'super_admin';
// dept 功能开关关闭时:不请求 /api/org/dept(后端 403),并隐藏部门列/分配入口/建号主部门字段
const deptEnabled = isOrgFeatureEnabled(featureFlags, 'dept');
const [members, setMembers] = useState([]);
const [membersTotal, setMembersTotal] = useState(0);
const [depts, setDepts] = useState([]);
const [loading, setLoading] = useState(false);
const [createVisible, setCreateVisible] = useState(false);
const [createFormApi, setCreateFormApi] = useState(null);
const [pwdResult, setPwdResult] = useState(null); // {username, login_name, initial_password}
const [importVisible, setImportVisible] = useState(false);
const [importResult, setImportResult] = useState(null);
const [importFile, setImportFile] = useState(null);
const [deptAssignFor, setDeptAssignFor] = useState(null); // 正在分配部门的成员
const [deptAssignVal, setDeptAssignVal] = useState(0);
const fetchAll = useCallback(async () => {
if (!orgId) return;
setLoading(true);
try {
const [m, d] = await Promise.all([
// 逐页取全:后端把 page_size 静默钳到 100。本页表格用的是**前端分页**
// (pageSize 15),单次只取 100 条会让管理员翻到最后一页、以为已看完
// 全部员工,而第 101 位之后的人根本不在表格里——total 也会与实际
// 行数对不上。
collectPagedItems((page, size) =>
API.get(`/api/org/members?p=${page}&page_size=${size}`, {
headers: getOrgHeaders(orgId),
}),
),
deptEnabled
? // 部门数据仅用于列展示与分配弹窗:网络失败兜底为 null,不连坐员工列表
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }).catch(
() => null,
)
: Promise.resolve(null),
]);
setMembers(m.items);
setMembersTotal(m.total);
if (m.message) showError(m.message);
// 触达 20 页上限(2000 人)时必须明说:本页顶部显示的是后端真实总数,
// 不提示的话又会变成"数字与表格行数对不上"的静默截断——正是本轮要消除的问题。
if (m.truncated)
showError(
t(
'员工数量超出单次加载上限,列表可能不完整,请用搜索或部门筛选缩小范围',
),
);
if (d) {
if (d.data.success) setDepts(d.data.data || []);
else showError(d.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [orgId, deptEnabled, t]);
useEffect(() => {
fetchAll();
}, [fetchAll]);
// 建号弹窗主部门的树数据(与分配弹窗同规则:末级可选、停用置灰)
const deptTreeData = useMemo(
() => buildDeptTreeData(depts, { disabledLabel: t('已停用') }),
[depts, t],
);
const deptNameMap = useMemo(() => {
const m = {};
depts.forEach((d) => (m[d.id] = d.name));
return m;
}, [depts]);
const deptFullNameMap = useMemo(() => buildDeptFullNameMap(depts), [depts]);
// 当前归属部门如今已停用或有了下级(存量数据):仍正常回显,仅提示建议迁移
const assignCurrentDeptBlocked = useMemo(() => {
const deptId = deptAssignFor?.department_id;
if (!deptId) return false;
const dept = depts.find((d) => d.id === deptId);
if (!dept) return false;
return dept.status !== 1 || hasChildDept(depts, deptId);
}, [deptAssignFor, depts]);
const assignDept = async () => {
if (!deptAssignFor) return;
// 未变化直接关闭:存量归属可能已不满足「末级+启用」校验,原样提交会被后端拒绝
if ((deptAssignVal || 0) === (deptAssignFor.department_id || 0)) {
setDeptAssignFor(null);
return;
}
try {
const res = await API.put(
`/api/org/members/${deptAssignFor.id}/dept`,
{ department_id: deptAssignVal || 0 },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('部门已分配'));
setDeptAssignFor(null);
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const submitCreate = async () => {
if (!createFormApi) return;
let v;
try {
v = await createFormApi.validate();
} catch {
return;
}
// 统一 trim 后再判空/提交:纯空格登录名在这里即被拦下,而不是到后端才报错。
// 后端建号硬性要求 login_name(登录只认登录名),提示与后端对齐,不再误导"填邮箱也行"。
const loginName = (v.login_name || '').trim();
const email = (v.email || '').trim();
if (!loginName) {
Toast.warning(t('请填写企业内登录名'));
return;
}
try {
const res = await API.post(
'/api/org/members/create-account',
{
login_name: loginName,
display_name: (v.display_name || '').trim(),
email,
employee_no: (v.employee_no || '').trim(),
department_id: v.department_id || 0,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
setCreateVisible(false);
setPwdResult({
username: res.data.data.username,
login_name: res.data.data.login_name,
initial_password: res.data.data.initial_password,
login_name_global_collision:
res.data.data.login_name_global_collision,
});
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const submitImport = async () => {
if (!importFile) {
Toast.warning(t('请选择 CSV 文件'));
return;
}
const fd = new FormData();
fd.append('file', importFile);
try {
const res = await API.post('/api/org/members/import', fd, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
setImportResult(res.data.data);
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const resetPassword = async (member) => {
try {
const res = await API.put(
`/api/org/members/${member.id}/reset-password`,
{},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
// 回显被重置的账号:个人账号没有企业内登录名,只能凭系统用户名登录,不回显就无从告知本人。
// 托管账号只回显企业内登录名:其系统用户名是 o{orgId}_随机串,企业登录入口不认,
// 回显会被误读成“用户名被改了”并分发给员工,导致登录失败
const isManaged = member.created_by_org_id === member.organization_id;
setPwdResult({
username: isManaged && member.login_name ? '' : member.username || '',
login_name: member.login_name || '',
initial_password: res.data.data.temp_password,
reset: true,
});
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const offboard = async (memberId) => {
try {
const res = await API.put(
`/api/org/members/${memberId}/offboard`,
{},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('已离职回收'));
fetchAll();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const columns = [
{
title: t('成员'),
render: (_, r) => (
<div className='flex items-center gap-2'>
<span>{r.display_name || r.username || `#${r.user_id}`}</span>
{r.created_by_org_id !== r.organization_id && (
<Tooltip
content={t('通过企业代码加入的个人平台账号,非本企业托管')}
>
<Tag size='small' color='blue'>
{t('个人账号')}
</Tag>
</Tooltip>
)}
</div>
),
},
{
title: t('企业内登录名'),
dataIndex: 'login_name',
render: (v) => v || '-',
},
...(deptEnabled
? [
{
title: t('部门'),
dataIndex: 'department_id',
width: 120,
render: (v) =>
v ? (
<Tooltip content={deptFullNameMap[v] || `#${v}`}>
<span>{deptNameMap[v] || `#${v}`}</span>
</Tooltip>
) : (
<span className='text-gray-400'>{t('未分配')}</span>
),
},
]
: []),
{ title: t('工号'), dataIndex: 'employee_no', render: (v) => v || '-' },
{
title: t('角色'),
dataIndex: 'role',
width: 90,
render: (v) =>
v === 'owner'
? t('Owner')
: v === 'admin'
? t('Admin')
: v === 'dept_admin'
? t('Dept Admin')
: t('Member'),
},
{
title: t('状态'),
dataIndex: 'status',
width: 110,
render: (v) => statusTag(t, v),
},
{
title: t('操作'),
width: 300,
render: (_, r) => {
const managed = r.created_by_org_id === r.organization_id;
const canReset = managed || isSuperAdmin;
return (
<div className='flex items-center gap-2'>
{deptEnabled && (
<Button
size='small'
theme='light'
onClick={() => {
setDeptAssignFor(r);
setDeptAssignVal(r.department_id || 0);
}}
>
{t('分配部门')}
</Button>
)}
{canReset ? (
<Popconfirm
title={t('重置该账号密码?')}
content={
managed
? t('将生成一次性临时密码,并要求首次登录改密')
: t(
'该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人',
)
}
onConfirm={() => resetPassword(r)}
>
<Button
size='small'
theme='light'
icon={<KeyRound size={14} />}
>
{t('重置密码')}
</Button>
</Popconfirm>
) : (
<Tooltip content={t('个人平台账号,请由本人通过找回密码修改')}>
<Button
size='small'
theme='light'
disabled
icon={<KeyRound size={14} />}
>
{t('重置密码')}
</Button>
</Tooltip>
)}
{r.status === 1 && r.role !== 'owner' && (
<Popconfirm
title={t('确认离职回收该成员?')}
content={t(
'将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户',
)}
onConfirm={() => offboard(r.id)}
>
<Button size='small' theme='light' type='danger'>
{t('离职回收')}
</Button>
</Popconfirm>
)}
</div>
);
},
},
];
const actions = (
<>
<Button theme='light' icon={<RefreshCw size={14} />} onClick={fetchAll}>
{t('刷新')}
</Button>
<Button
theme='light'
icon={<UploadIcon size={14} />}
onClick={() => {
setImportResult(null);
setImportFile(null);
setImportVisible(true);
}}
>
{t('CSV 导入')}
</Button>
<Button
theme='solid'
icon={<UserPlus size={14} />}
onClick={() => setCreateVisible(true)}
>
{t('创建员工账号')}
</Button>
</>
);
return (
<div className={embedded ? 'space-y-4' : 'p-4 sm:p-6 lg:p-8'}>
{embedded ? (
<div className='flex items-start justify-between gap-3 flex-wrap rounded-2xl border border-dashed border-brand/25 bg-brand/5 p-4 dark:border-brand/25 dark:bg-brand/10'>
<div className='flex items-start gap-3'>
<span className='inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-white text-brand-deep shadow-sm dark:bg-white/10 dark:text-brand-from'>
<IdCard size={18} />
</span>
<div>
<div className='font-semibold text-gray-950 dark:text-white'>
{t('员工账号')}
</div>
<Text type='tertiary' size='small'>
{t('集中管理员工登录、批量导入、重置密码与离职回收')}
</Text>
</div>
</div>
<div className='flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
</div>
) : (
<OrgPageHeader
icon={IdCard}
title={t('员工账号')}
subtitle={t('集中管理员工登录账号')}
actions={actions}
/>
)}
{membersTotal > members.length && (
<Banner
type='warning'
closeIcon={null}
className='mb-3'
description={t(
'员工账号数量已达 100 条上限,当前仅显示前 100 条,请使用搜索定位具体成员。',
)}
/>
)}
<OrgPanel padding='p-2'>
<Table
columns={columns}
dataSource={members}
loading={loading}
pagination={{ pageSize: 15, showSizeChanger: false }}
rowKey='id'
/>
</OrgPanel>
{/* 创建账号 */}
<OrgModal
title={t('创建员工账号')}
visible={createVisible}
onOk={submitCreate}
onCancel={() => setCreateVisible(false)}
okText={t('创建')}
cancelText={t('取消')}
>
<Form getFormApi={setCreateFormApi}>
<Form.Input
field='login_name'
label={t('企业内登录名')}
placeholder={t('企业内唯一,如 zhangsan')}
rules={[
{
// 与后端一致按码点计数;不用 maxLength 静默截断,让用户明确看到超长提醒
validator: (rule, value) =>
!value || Array.from(value.trim()).length <= 64,
message: t('登录名不能超过 64 个字符'),
},
]}
/>
<Form.Input field='display_name' label={t('姓名/显示名')} />
<Form.Input
field='email'
label={t('邮箱(可选)')}
placeholder={t('已是平台用户的邮箱请改用企业代码加入')}
rules={[
{
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: t('邮箱格式不正确'),
},
]}
/>
<Form.Input
field='employee_no'
label={t('工号(可选)')}
rules={[
{
validator: (rule, value) =>
!value || Array.from(value.trim()).length <= 64,
message: t('工号不能超过 64 个字符'),
},
]}
/>
{deptEnabled && (
<Form.TreeSelect
field='department_id'
label={t('主部门')}
treeData={deptTreeData}
showClear
filterTreeNode
showFilteredOnly
expandAll
placeholder={t('未分配')}
style={{ width: '100%' }}
/>
)}
</Form>
</OrgModal>
{/* 一次性密码结果 */}
<OrgModal
title={pwdResult?.reset ? t('密码已重置') : t('账号已创建')}
visible={!!pwdResult}
onCancel={() => setPwdResult(null)}
footer={
<Button theme='solid' onClick={() => setPwdResult(null)}>
{t('我已记录')}
</Button>
}
>
<Banner
type='warning'
closeIcon={null}
description={t(
'初始密码仅显示这一次,请立即复制并安全分发给员工。关闭后无法再次查看。',
)}
className='mb-3'
/>
{pwdResult?.username ? (
<div className='mb-2'>
<Text type='tertiary'>{t('系统用户名')}: </Text>
<Text copyable>{pwdResult.username}</Text>
</div>
) : null}
{pwdResult?.login_name ? (
<div className='mb-2'>
<Text type='tertiary'>{t('企业内登录名')}: </Text>
<Text copyable>{pwdResult.login_name}</Text>
</div>
) : null}
{pwdResult?.login_name_global_collision ? (
<Banner
type='info'
closeIcon={null}
description={t(
'提示:该登录名在其他企业也存在。若已开启「免企业标识直接登录」,该员工登录时可能需要从多个企业中选择。可考虑使用更唯一的登录名(如加工号)。',
)}
className='mb-3'
/>
) : null}
<div>
<Text type='tertiary'>{t('初始密码')}: </Text>
<Text copyable strong>
{pwdResult?.initial_password}
</Text>
</div>
</OrgModal>
{/* 分配部门 */}
<OrgModal
title={`${t('分配部门')} - ${deptAssignFor?.display_name || deptAssignFor?.username || ''}`}
visible={!!deptAssignFor}
onOk={assignDept}
onCancel={() => setDeptAssignFor(null)}
okText={t('保存')}
cancelText={t('取消')}
>
{assignCurrentDeptBlocked && (
<Banner
type='info'
closeIcon={null}
className='mb-3'
description={t(
'该成员当前归属的部门已停用或已有下级部门,建议迁移到具体的末级部门。',
)}
/>
)}
<DeptTreeSelect
depts={depts}
value={deptAssignVal}
onChange={setDeptAssignVal}
/>
</OrgModal>
{/* CSV 导入 */}
<OrgModal
title={t('CSV 批量导入')}
visible={importVisible}
onOk={importResult ? () => setImportVisible(false) : submitImport}
onCancel={() => setImportVisible(false)}
okText={importResult ? t('完成') : t('开始导入')}
cancelText={t('取消')}
width={620}
>
{!importResult ? (
<>
<Banner
type='info'
closeIcon={null}
className='mb-3'
description={t(
'表头需含 login_name,display_name,email,employee_no(login_name 必填,不超过 64 个字符)。单次最多 500 行。每个账号返回一次性初始密码。',
)}
/>
<input
type='file'
accept='.csv'
onChange={(e) => setImportFile(e.target.files?.[0] || null)}
/>
</>
) : (
<>
<Banner
type={importResult.failed > 0 ? 'warning' : 'success'}
closeIcon={null}
className='mb-3'
description={`${t('成功')} ${importResult.success} · ${t('失败')} ${importResult.failed} / ${t('共')} ${importResult.total}`}
/>
<Table
size='small'
pagination={false}
rowKey={(r) => `${r.row}`}
dataSource={importResult.details || []}
columns={[
{ title: t('行'), dataIndex: 'row', width: 50 },
{ title: t('登录名'), dataIndex: 'login_name' },
{
title: t('结果'),
render: (_, r) =>
r.success ? (
<span>
<Tag color='green' size='small'>
{t('成功')}
</Tag>{' '}
<Text
size='small'
copyable={{ content: r.initial_password }}
>
{t('初始密码')}
</Text>
</span>
) : (
<Tooltipless error={formatImportError(t, r)} t={t} />
),
},
]}
/>
<Text type='tertiary' size='small'>
{t('初始密码仅此一次,请及时导出/分发。')}
</Text>
</>
)}
</OrgModal>
</div>
);
};
// 简单错误展示(避免引入额外组件)
const Tooltipless = ({ error, t }) => (
<span>
<Tag color='red' size='small'>
{t('失败')}
</Tag>{' '}
<Text type='danger' size='small'>
{error}
</Text>
</span>
);
export default OrgMemberAccounts;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,57 @@
/*
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 from 'react';
import { useTranslation } from 'react-i18next';
import OrgSubpageTabs from './components/OrgSubpageTabs';
import OrgMySkills from './OrgMySkills';
import OrgMyConnectors from './OrgMyConnectors';
/**
* 我的 AI 能力:成员自助视图的合并入口(我的技能 + 业务系统授权)。
*
* 两个页签都是 isMemberActor 守卫的只读/自助页,各自受不同的企业功能位
* (skill_market / connector)与站点级模块开关控制,由 showSkills /
* showConnectors 决定可见性。旧路由 /org/my-skills、/org/my-connectors
* 重定向到对应页签。
*/
const OrgMyCapabilities = ({
orgId,
showSkills = true,
showConnectors = true,
}) => {
const { t } = useTranslation();
return (
<OrgSubpageTabs
tabs={[
showSkills && {
key: 'skills',
label: t('我的技能'),
node: <OrgMySkills orgId={orgId} />,
},
showConnectors && {
key: 'connectors',
label: t('业务系统授权'),
node: <OrgMyConnectors orgId={orgId} />,
},
]}
/>
);
};
export default OrgMyCapabilities;
+169
View File
@@ -0,0 +1,169 @@
/*
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 { Button, Empty, Tag } from '@douyinfe/semi-ui';
import { Cable, LockKeyhole } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers/api';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import './org-connectors.css';
const OrgMyConnectors = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [items, setItems] = useState([]);
const [loadError, setLoadError] = useState('');
useEffect(() => {
let active = true;
API.get('/api/org/connectors/mine', { headers, skipErrorHandler: true })
.then((response) => {
if (!active) return;
if (response.data?.success) {
setItems(response.data.data || []);
setLoadError('');
} else {
// A failed load must not masquerade as "no authorizations".
setLoadError(response.data?.message || t('授权列表加载失败'));
}
})
.catch((error) => {
if (active)
setLoadError(
error?.response?.data?.message ||
error?.message ||
t('授权列表加载失败'),
);
});
return () => {
active = false;
};
}, [headers, t]);
// 使用指引:成员视角的阅读式说明(无上手流程,不出进度胶囊)。
const guide = usePageGuide({
guideKey: 'org-my-connectors',
title: t('我的业务系统授权 · 使用指引'),
intro: t('这里列出专家在任务中可以代表你调用的业务系统与边界'),
steps: [
{
title: t('看懂授权卡片'),
detail: t('一张卡片对应一个已授权的业务系统连接器'),
points: [
t('右上角标签是访问级别:read 只读,write 可执行写操作'),
t('卡片中的标签列出专家可调用的具体方法'),
],
},
{
title: t('理解确认策略'),
detail: t('确认策略决定哪些调用执行前需要你亲自确认'),
points: [
t('never 无需确认;write 写操作前确认;always 每次调用都确认'),
],
},
{
title: t('任务中的确认操作'),
detail: t('确认动作发生在云端大脑的任务详情页'),
points: [
t('专家发起调用时任务会停在「等待操作确认」'),
t('展开「查看冻结参数」核对操作内容,填写原因后确认或拒绝'),
t('长时间不处理会确认超时,任务按已发生用量结算'),
],
},
{
title: t('需要调整授权'),
detail: t('授权由企业管理员统一发布与撤销'),
points: [t('缺少某个系统的授权或范围不足时,请联系企业管理员')],
},
],
faq: [
{
q: t('列表是空的?'),
a: t('管理员发布授权并覆盖到你之后才会显示,请联系企业管理员'),
},
{
q: t('「企业服务账号由管理员管理」是什么意思?'),
a: t('该连接器以企业级凭据运行,个人无法自行撤销'),
},
],
});
return (
<main className='org-connector-page'>
<header className='org-connector-hero'>
<div>
<h1>{t('我的业务系统授权')}</h1>
<p>{t('查看专家在任务中可代表你调用的业务系统、方法和确认策略。')}</p>
</div>
<div className='org-connector-actions'>
<PageGuideTrigger guide={guide} />
</div>
</header>
<PageGuideDrawer guide={guide} />
{loadError ? (
<Empty title={t('授权列表加载失败')} description={loadError} />
) : items.length === 0 ? (
<Empty
title={t('当前没有 Connector 授权')}
description={t('管理员发布授权并覆盖到你后会显示在这里。')}
/>
) : (
<section className='org-connector-grid'>
{items.map((item) => (
<article className='org-connector-card' key={item.grant.id}>
<div className='org-connector-card-top'>
<span className='org-connector-icon'>
<Cable size={20} />
</span>
<Tag
color={
item.grant.access_level === 'write' ? 'orange' : 'green'
}
>
{item.grant.access_level}
</Tag>
</div>
<h3>{item.connector_name}</h3>
<p>{item.definition_name}</p>
<div className='org-connector-tags'>
{item.methods.map((method) => (
<Tag key={method}>{method}</Tag>
))}
</div>
<p>
<LockKeyhole size={14} /> {t('确认策略')}:{' '}
{item.grant.confirmation_policy}
</p>
<Button disabled={!item.revocable}>
{item.revocable
? t('撤销个人委托')
: t('企业服务账号由管理员管理')}
</Button>
</article>
))}
</section>
)}
</main>
);
};
export default OrgMyConnectors;
+184
View File
@@ -0,0 +1,184 @@
/*
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, useState } from 'react';
import { Switch, Toast, Typography } from '@douyinfe/semi-ui';
import { LockKeyhole } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import {
AssignmentModeTag,
ScopeSourceBadge,
SkillEmptyGuide,
} from '../../components/skill';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import './org-skills.css';
const { Title, Paragraph, Text } = Typography;
const OrgMySkills = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [items, setItems] = useState([]);
const load = useCallback(async () => {
const response = await API.get('/api/org/skills/mine', { headers });
if (response.data?.success) {
setItems(response.data.data || []);
}
}, [headers]);
useEffect(() => {
void load();
}, [load]);
const choose = async (item, enabled) => {
const response = await API.put(
`/api/org/skills/mine/${item.skill_id}`,
{ enabled },
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
await load();
};
// 使用指引:成员视角的阅读式说明(无上手流程,不出进度胶囊)。
const guide = usePageGuide({
guideKey: 'org-my-skills',
title: t('我的技能 · 使用指引'),
intro: t('这里是任务运行时真实生效的能力集,来源与状态一目了然'),
steps: [
{
title: t('看懂每一行'),
detail: t('名称 + 版本号是企业审核过的不可变技能版本'),
points: [
t('「必需锁定」带锁图标,是管理员强制启用的技能,不可关闭'),
t(
'标签含义:必需锁定 / 默认开启 / 推荐 / 可选,决定技能如何对你生效',
),
],
},
{
title: t('追溯生效来源'),
detail: t('来源徽章回答「为什么这个技能对我生效」'),
points: [
t('徽章显示分发范围(企业 / 部门 / 项目 / 角色 / 成员)与目标值'),
t('鼠标悬停可见该来源的分发模式与激活方式'),
],
},
{
title: t('启停技能'),
detail: t('用每行右侧开关控制技能是否对自己生效'),
points: [
t('关闭后,专家执行你的任务时不再注入该能力'),
t('带锁的必需技能开关为灰色,如需调整请联系企业管理员'),
],
},
{
title: t('想要新技能'),
detail: t('到技能超市点「我想要」,把诉求告诉管理员'),
points: [
t('管理员启用并创建分发策略覆盖到你之后,技能会自动出现在这里'),
],
},
],
faq: [
{
q: t('技能列表为空?'),
a: t('企业管理员在技能超市为企业启用并分发后才会显示'),
},
{
q: t('开关是灰色的?'),
a: t('该技能被管理员设为「必需锁定」,不可自行关闭'),
},
],
});
return (
<main className='org-skills-page'>
<header className='org-skills-hero'>
<div>
<Title heading={3}>{t('我的技能')}</Title>
<Paragraph>
{t(
'这里展示与任务运行时相同的有效能力集,以及每项技能为什么对你生效。',
)}
</Paragraph>
</div>
<div className='org-skills-hero-actions'>
<PageGuideTrigger guide={guide} />
</div>
</header>
<PageGuideDrawer guide={guide} />
{items.length === 0 ? (
<SkillEmptyGuide
title={t('当前没有可用技能')}
description={t('企业管理员启用并分发后会显示在这里。')}
/>
) : (
<section className='org-my-skills'>
{items
.filter((item) => item.mode !== 'forbidden')
.map((item) => {
const locked = item.mode === 'required_locked';
return (
<article key={item.skill_id}>
<div>
<span className='org-my-skill-title'>
{locked && <LockKeyhole size={16} />}
<Text strong>
{item.customization?.display_name || item.canonical_id}
</Text>
<AssignmentModeTag mode={item.mode} />
</span>
<Paragraph>
{item.customization?.description_zh ||
item.customization?.usage_boundary ||
t('企业已审核的方法能力')}
</Paragraph>
<div className='org-my-skill-sources'>
{(item.sources || []).map((source) => (
<ScopeSourceBadge
key={source.id}
source={`${source.scope_type}:${source.scope_id || source.scope_value || 'all'}`}
detail={`${source.mode} / ${source.activation}`}
/>
))}
</div>
</div>
<div>
<Text type='tertiary'>v#{item.version_id}</Text>
<Switch
disabled={locked}
checked={item.enabled}
onChange={(enabled) => choose(item, enabled)}
/>
</div>
</article>
);
})}
</section>
)}
</main>
);
};
export default OrgMySkills;
@@ -0,0 +1,520 @@
/*
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, useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Button,
InputNumber,
Spin,
Tabs,
TabPane,
Typography,
} from '@douyinfe/semi-ui';
import {
Bell,
Building2,
KeyRound,
Pencil,
UserRound,
UserCog,
Wallet,
} from 'lucide-react';
import { API } from '../../helpers/api';
import {
showError,
showSuccess,
setUserData,
parseUserSetting,
USER_AVATAR_TYPES,
getAvatarPresetById,
getDefaultAvatarPresetId,
} from '../../helpers';
import { renderQuota } from '../../helpers/render';
import { UserContext } from '../../context/User';
import NotifyChannelForm from '../../components/settings/NotifyChannelForm';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgAvatarSection from './components/OrgAvatarSection';
import OrgNicknameModal from './components/OrgNicknameModal';
import OrgPasswordModal from './components/OrgPasswordModal';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const roleLabel = (t, role) =>
role === 'owner'
? t('所有者')
: role === 'admin'
? t('管理员')
: role === 'super_admin'
? t('超级管理员')
: t('成员');
const PERIODIC_QUOTA_PERIODS = new Set(['daily', 'weekly', 'monthly']);
const quotaPeriodHint = (t, period) => {
switch (period) {
case 'daily':
return t('每日重置');
case 'weekly':
return t('每周重置');
case 'monthly':
return t('每月重置');
default:
return '';
}
};
// 信息行:label + 右侧内容(个人资料/企业身份卡片共用)
const InfoRow = ({ label, children, last = false }) => (
<div
className={`flex items-center justify-between gap-3 py-3 ${
last ? '' : 'border-b border-[var(--border-subtle)]'
}`}
>
<Text type='tertiary' className='flex-shrink-0'>
{label}
</Text>
<div className='flex items-center gap-2 min-w-0'>{children}</div>
</div>
);
/*
* 成员个人设置页(/org/personal-settings,全员可见)。
* 企业中心是独立空间:改密/昵称走企业端接口,通知为企业维度的成员配额预警,
* 不出现个人余额概念(方案 docs/06-企业运营治理中心/11-企业用户个人设置页面方案.md)。
*/
const OrgPersonalSettings = ({ orgId }) => {
const { t } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const [summary, setSummary] = useState(null);
const [summaryLoading, setSummaryLoading] = useState(true);
const [nickModal, setNickModal] = useState(false);
const [pwdModal, setPwdModal] = useState(false);
// 头像:与个人中心共用 user.setting 存储,保存走企业端 /me/profile 后端合并
const [avatarSettings, setAvatarSettings] = useState({
avatarType: USER_AVATAR_TYPES.PRESET,
avatarPreset: getDefaultAvatarPresetId(userState?.user),
customAvatarUrl: '',
});
const [savingAvatar, setSavingAvatar] = useState(false);
// 通知:企业维度(成员配额预警),存 organization_members
const [notifyValue, setNotifyValue] = useState({ notify_type: 'email' });
const [alertThreshold, setAlertThreshold] = useState(0);
const [savingNotify, setSavingNotify] = useState(false);
// 系统超管直通企业时无真实成员行(member.id=0),通知设置无从挂靠
const isSuperAdminView =
summary?.member?.role === 'super_admin' || summary?.member?.id === 0;
const fetchSummary = useCallback(async () => {
if (!orgId) return;
try {
const res = await API.get('/api/org/me/summary', {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
setSummary(res.data.data);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSummaryLoading(false);
}
}, [orgId]);
const fetchNotifySetting = useCallback(async () => {
if (!orgId) return;
try {
const res = await API.get('/api/org/me/notify-setting', {
headers: getOrgHeaders(orgId),
});
if (res.data.success && res.data.data) {
const d = res.data.data;
setNotifyValue({
notify_type: d.notify_type || 'email',
notification_email: d.notification_email || '',
webhook_url: d.webhook_url || '',
webhook_secret: d.webhook_secret || '',
});
setAlertThreshold(d.quota_alert_threshold || 0);
}
} catch (err) {
// 超管直通等场景后端返回错误,静默降级(通知区块会被禁用)
}
}, [orgId]);
useEffect(() => {
fetchSummary();
fetchNotifySetting();
}, [fetchSummary, fetchNotifySetting]);
// 从 user.setting 初始化头像(与个人中心 PersonalSetting 同款逻辑)
useEffect(() => {
if (userState?.user?.setting) {
const settings = parseUserSetting(userState.user.setting);
setAvatarSettings({
avatarType: Object.values(USER_AVATAR_TYPES).includes(
settings.avatar_type,
)
? settings.avatar_type
: USER_AVATAR_TYPES.PRESET,
avatarPreset: getAvatarPresetById(
settings.avatar_preset || getDefaultAvatarPresetId(userState.user),
).id,
customAvatarUrl: settings.custom_avatar_url || '',
});
} else if (userState?.user) {
setAvatarSettings((prev) => ({
...prev,
avatarPreset:
prev.avatarPreset || getDefaultAvatarPresetId(userState.user),
}));
}
}, [userState?.user?.id, userState?.user?.setting]);
const handleAvatarSettingChange = (type, value) => {
setAvatarSettings((prev) => ({ ...prev, [type]: value }));
};
// 头像保存后刷新 UserContext,全局顶栏头像即时更新(/api/user/self 对企业员工放行)
const refreshUserSelf = async () => {
try {
const res = await API.get('/api/user/self');
if (res.data.success) {
userDispatch({ type: 'login', payload: res.data.data });
setUserData(res.data.data);
}
} catch (err) {
// ignore
}
};
const saveAvatarSettings = async () => {
if (
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
!avatarSettings.customAvatarUrl?.trim()
) {
showError(t('请先填写自定义头像图片 URL'));
return;
}
setSavingAvatar(true);
try {
const res = await API.put(
'/api/org/me/profile',
{
avatar_type: avatarSettings.avatarType,
avatar_preset: avatarSettings.avatarPreset,
custom_avatar_url: avatarSettings.customAvatarUrl,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
showSuccess(t('头像设置已保存'));
await refreshUserSelf();
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('头像设置保存失败'));
} finally {
setSavingAvatar(false);
}
};
const saveNotifySettings = async () => {
const type = notifyValue.notify_type || 'email';
if (type === 'email' && !notifyValue.notification_email?.trim()) {
showError(t('请填写有效的通知邮箱'));
return;
}
if (type === 'webhook' && !notifyValue.webhook_url?.trim()) {
showError(t('Webhook地址不能为空'));
return;
}
setSavingNotify(true);
try {
const res = await API.put(
'/api/org/me/notify-setting',
{
notify_type: type,
notification_email: notifyValue.notification_email || '',
webhook_url: notifyValue.webhook_url || '',
webhook_secret: notifyValue.webhook_secret || '',
quota_alert_threshold: Number(alertThreshold) || 0,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
showSuccess(t('通知设置已保存'));
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSavingNotify(false);
}
};
const member = summary?.member || {};
const myQuota = summary?.my_quota || {};
const quotaLimit = Number(myQuota.quota_limit || 0);
const isPeriodic = PERIODIC_QUOTA_PERIODS.has(myQuota.quota_period);
const usedQuota = Number(
isPeriodic ? myQuota.quota_used_in_period || 0 : myQuota.used_quota || 0,
);
const remainQuota = Math.max(0, quotaLimit - usedQuota);
// 展示百分比:耗尽=100;否则四舍五入,但「有用量至少 1%、未耗尽最多 99%」,
// 避免"有微量用量却显示 0%"或"未用尽却显示 100%"的误导。进度条与文案共用同一值。
const usedPct =
quotaLimit <= 0
? 0
: usedQuota >= quotaLimit
? 100
: Math.min(
99,
Math.max(
usedQuota > 0 ? 1 : 0,
Math.round((usedQuota / quotaLimit) * 100),
),
);
// 进度条随用量升温:正常品牌色,≥80% 转琥珀,≥95% 转红,给成员用尽预警
const quotaBarClass =
usedPct >= 95 ? 'bg-red-500' : usedPct >= 80 ? 'bg-amber-500' : 'bg-brand';
const displayName =
member.display_name ||
userState?.user?.display_name ||
userState?.user?.username ||
'';
if (summaryLoading) {
return (
<div className='flex items-center justify-center h-full min-h-[240px]'>
<Spin size='large' />
</div>
);
}
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
icon={UserCog}
title={t('个人设置')}
subtitle={t('管理你的头像、昵称、密码与通知偏好')}
/>
<Tabs type='line' className='mt-2'>
<TabPane tab={t('个人资料')} itemKey='profile'>
{/* 头像设置上移至页面上半部分,作为视觉锚点,保存走企业端接口 */}
<div className='mt-4'>
<OrgAvatarSection
t={t}
userState={userState}
avatarSettings={avatarSettings}
handleAvatarSettingChange={handleAvatarSettingChange}
saveAvatarSettings={saveAvatarSettings}
saving={savingAvatar}
/>
</div>
{/* 基本资料 / 企业身份 / 个人配额:三栏均分,卡片等高,避免高度失衡 */}
<div className='mt-4 grid grid-cols-1 lg:grid-cols-3 gap-4'>
{/* 基本资料:昵称 + 登录密码(复用工作台同款弹窗与企业端接口) */}
<OrgPanel title={t('基本资料')} icon={UserRound} padding='px-5 py-2'>
<InfoRow label={t('昵称')}>
<Text className='truncate'>{displayName || t('未设置')}</Text>
<Button
theme='light'
size='small'
icon={<Pencil size={13} />}
onClick={() => setNickModal(true)}
>
{t('编辑')}
</Button>
</InfoRow>
<InfoRow label={t('登录密码')} last>
<Text type='tertiary'>••••••••</Text>
<Button
theme='light'
size='small'
icon={<KeyRound size={13} />}
onClick={() => setPwdModal(true)}
>
{t('修改密码')}
</Button>
</InfoRow>
</OrgPanel>
{/* 企业身份只读信息(数据源 /api/org/me/summary,与工作台一致) */}
<OrgPanel title={t('企业身份')} icon={Building2} padding='px-5 py-2'>
<InfoRow label={t('所属企业')}>
<Text className='truncate'>
{summary?.organization?.name || '-'}
</Text>
</InfoRow>
<InfoRow label={t('我的角色')}>
<span className='inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
{roleLabel(t, member.role)}
</span>
</InfoRow>
<InfoRow label={t('所属部门')} last>
<Text className='truncate'>
{member.department_name || t('未分配')}
</Text>
</InfoRow>
</OrgPanel>
{/* 个人配额:成员高频关注项,抽成带进度条的重点块 */}
<OrgPanel title={t('个人配额')} icon={Wallet} padding='p-5'>
{quotaLimit > 0 ? (
<div>
<div className='flex items-end justify-between gap-3'>
<div className='min-w-0'>
<div className='text-xs text-[var(--text-secondary)]'>
{t('剩余可用')}
</div>
<div className='mt-0.5 text-2xl font-semibold text-[var(--text-primary)] truncate'>
{renderQuota(remainQuota)}
</div>
</div>
<div className='shrink-0 text-right text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
<div>
{t('已用')} {renderQuota(usedQuota)}
</div>
<div>
{t('总额')} {renderQuota(quotaLimit)}
</div>
</div>
</div>
<div className='mt-3 h-2 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-white/[0.08]'>
<div
className={`h-full rounded-full transition-all duration-300 ${quotaBarClass}`}
style={{ width: `${usedPct}%` }}
/>
</div>
<div className='mt-2 flex items-center justify-between text-xs'>
<span className='text-gray-500 dark:text-gray-400'>
{t('已用')} {usedPct}%
</span>
{isPeriodic && (
<span className='text-brand font-medium'>
{quotaPeriodHint(t, myQuota.quota_period)}
</span>
)}
</div>
</div>
) : (
<div className='flex items-center gap-2 py-1.5'>
<span className='inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
{t('不限额')}
</span>
<Text type='tertiary' size='small'>
{t('企业未对你设置配额上限')}
</Text>
</div>
)}
</OrgPanel>
</div>
</TabPane>
<TabPane
tab={t('通知设置')}
itemKey='notify'
disabled={isSuperAdminView}
>
<OrgPanel
title={t('配额预警通知')}
subtitle={t(
'企业分配给你的额度即将用尽或已用尽时,通过以下渠道提醒你',
)}
icon={Bell}
padding='p-5'
className='mt-4'
actions={
<Button
theme='solid'
loading={savingNotify}
onClick={saveNotifySettings}
>
{t('保存通知设置')}
</Button>
}
>
<NotifyChannelForm
value={notifyValue}
onChange={setNotifyValue}
channels={['email', 'webhook']}
emailPlaceholder={t('必填,用于接收预警通知')}
/>
<div className='mt-5 pt-4 border-t border-[var(--border-subtle)]'>
<label className='block text-sm font-medium text-[var(--text-primary)] mb-2'>
{t('预警阈值')}
</label>
{quotaLimit > 0 ? (
<>
<InputNumber
value={alertThreshold}
onChange={(v) => setAlertThreshold(v)}
min={0}
step={1000}
style={{ width: '100%', maxWidth: 260 }}
/>
<div className='mt-2'>
<Text type='tertiary' size='small'>
{t('剩余额度低于该值时提醒,0 表示关闭')}
{Number(alertThreshold) > 0 &&
` · ${t('约合')} ${renderQuota(Number(alertThreshold))}`}
{` · ${t('当前剩余')} ${renderQuota(remainQuota)}`}
</Text>
</div>
</>
) : (
<Text type='tertiary'>
{t('企业未对你设置配额上限,无需配置预警')}
</Text>
)}
</div>
</OrgPanel>
</TabPane>
</Tabs>
<OrgNicknameModal
visible={nickModal}
onClose={() => setNickModal(false)}
orgId={orgId}
currentName={displayName}
onSuccess={() => {
fetchSummary();
refreshUserSelf();
}}
/>
<OrgPasswordModal visible={pwdModal} onClose={() => setPwdModal(false)} />
</div>
);
};
export default OrgPersonalSettings;
+654
View File
@@ -0,0 +1,654 @@
/*
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, useState } from 'react';
import {
Button,
Input,
Modal,
Table,
Tag,
TextArea,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { Code2, FileCheck2, OctagonX, RotateCcw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, getUserIdFromLocalStorage } from '../../helpers';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { SkillEmptyGuide } from '../../components/skill';
import {
usePageGuide,
PageGuideDrawer,
PageGuidePill,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import OrgPanel from './components/OrgPanel';
import './org-skills.css';
const { Title, Text, Paragraph } = Typography;
const blankSkill = {
canonical_id: '',
body: '# Method\n\nDescribe a safe, evidence-led method.',
name_zh: '',
name_en: '',
description_zh: '',
description_en: '',
triggers_zh: '',
triggers_en: '',
scenarios_zh: '',
scenarios_en: '',
compact_constraint_zh: '',
compact_constraint_en: '',
default_output_language: 'auto',
capabilities: 'prompt_only',
tags: 'internal',
change_statement: '',
};
const split = (value) =>
String(value || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean);
const OrgPrivateSkills = ({ orgId }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [items, setItems] = useState([]);
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
const [loaded, setLoaded] = useState(false);
const [editorVisible, setEditorVisible] = useState(false);
const [editingSkill, setEditingSkill] = useState(null);
const [form, setForm] = useState(blankSkill);
const [evidenceVersion, setEvidenceVersion] = useState(null);
const [historySkill, setHistorySkill] = useState(null);
const [history, setHistory] = useState([]);
const [evidence, setEvidence] = useState({
model: '',
input: '',
});
const load = useCallback(async () => {
// finally 保证请求失败也置 loaded:拦截器已 toast,此处只需不让
// 未捕获 reject 把 loaded 卡在 false。
try {
const response = await API.get('/api/org/skills/private', { headers });
if (response.data?.success) setItems(response.data.data || []);
} finally {
setLoaded(true);
}
}, [headers]);
useEffect(() => {
void load();
}, [load]);
const payload = () => ({
...form,
triggers_zh: split(form.triggers_zh),
triggers_en: split(form.triggers_en),
scenarios_zh: split(form.scenarios_zh),
scenarios_en: split(form.scenarios_en),
capabilities: split(form.capabilities),
tags: split(form.tags),
});
// Backend business rejections arrive as HTTP 4xx (axios throws); read the
// response body so the audited reason reaches the user instead of a generic
// "Request failed with status code 409".
const backendMessage = (error, fallback) =>
error?.response?.data?.message || error?.message || fallback;
const save = async () => {
const endpoint = editingSkill
? `/api/org/skills/private/${editingSkill.id}/versions`
: '/api/org/skills/private';
try {
const response = await API.post(endpoint, payload(), {
headers,
skipErrorHandler: true,
});
if (!response.data?.success) {
Toast.error(response.data?.message || t('保存失败'));
return;
}
setEditorVisible(false);
setEditingSkill(null);
setForm(blankSkill);
await load();
} catch (error) {
Toast.error(backendMessage(error, t('保存失败')));
}
};
const recordEvidence = async () => {
if (!evidence.model.trim() || !evidence.input.trim()) {
Toast.error(t('模型名称与测试输入不能为空'));
return;
}
try {
const response = await API.post(
`/api/org/skills/private/versions/${evidenceVersion}/test`,
{ model: evidence.model, input: evidence.input },
{ headers, skipErrorHandler: true },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('模型实测失败'));
return;
}
Toast.success(t('模型实测完成,证据已落库'));
setEvidenceVersion(null);
await load();
} catch (error) {
Toast.error(backendMessage(error, t('模型实测失败')));
}
};
const action = async (endpoint, body = {}) => {
try {
const response = await API.post(endpoint, body, {
headers,
skipErrorHandler: true,
});
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
Toast.success(t('操作完成'));
await load();
} catch (error) {
Toast.error(backendMessage(error, t('操作失败')));
}
};
const openHistory = async (skill) => {
try {
const response = await API.get(
`/api/org/skills/private/${skill.id}/versions`,
{ headers, skipErrorHandler: true },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('历史版本加载失败'));
return;
}
setHistory(response.data.data || []);
setHistorySkill(skill);
} catch (error) {
Toast.error(backendMessage(error, t('历史版本加载失败')));
}
};
const askReason = (title, onOk) => {
let reason = '';
Modal.confirm({
title,
content: (
<TextArea
placeholder={t('请输入可审计原因')}
onChange={(value) => {
reason = value;
}}
/>
),
onOk: () => onOk(reason),
});
};
const renderSkillActions = (row) => {
const versionId = row.version?.id;
const currentUserId = Number(getUserIdFromLocalStorage()) || 0;
// Two-person review is enforced server side; mirror it here so buttons
// that are guaranteed to be rejected are not clickable.
const isAuthor =
currentUserId > 0 && Number(row.version?.created_by) === currentUserId;
const isReviewer =
currentUserId > 0 && Number(row.review?.reviewer_id) === currentUserId;
return (
<div className='flex flex-wrap gap-2'>
<Button
size='small'
disabled={row.definition.emergency_stopped}
onClick={() => {
setEditingSkill(row.definition);
setForm({
...blankSkill,
canonical_id: row.definition.canonical_id,
});
setEditorVisible(true);
}}
>
{t('新版本')}
</Button>
<Button size='small' onClick={() => openHistory(row.definition)}>
{t('历史版本')}
</Button>
<Button
size='small'
disabled={!versionId}
onClick={() => {
// Clear residue from a previous version's test before reopening.
setEvidence({ model: '', input: '' });
setEvidenceVersion(versionId);
}}
>
{t('执行模型实测')}
</Button>
<Button
size='small'
disabled={!versionId || row.review?.status !== 'pending' || isAuthor}
onClick={() =>
action(`/api/org/skills/private/versions/${versionId}/review/start`)
}
>
{isAuthor && row.review?.status === 'pending'
? t('待他人审核')
: t('领取审核')}
</Button>
<Button
size='small'
icon={<FileCheck2 size={14} />}
disabled={
!versionId || row.review?.status !== 'reviewing' || !isReviewer
}
onClick={() =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: true, conclusion: { decision: 'approved' } },
)
}
>
{t('通过')}
</Button>
<Button
size='small'
type='danger'
disabled={
!versionId || row.review?.status !== 'reviewing' || !isReviewer
}
onClick={() =>
action(
`/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: false, conclusion: { decision: 'rejected' } },
)
}
>
{t('驳回')}
</Button>
<Button
size='small'
disabled={!versionId || row.review?.status !== 'approved'}
onClick={() =>
action(`/api/org/skills/private/versions/${versionId}/publish`)
}
>
{t('发布')}
</Button>
<Button
size='small'
icon={<RotateCcw size={14} />}
disabled={!versionId}
onClick={() =>
askReason(t('回滚到当前列表版本'), (reason) =>
action(
`/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`,
{ reason },
),
)
}
>
{t('回滚')}
</Button>
<Button
size='small'
type='danger'
icon={<OctagonX size={14} />}
disabled={row.definition.emergency_stopped}
onClick={() =>
askReason(t('紧急停用 Skill'), (reason) =>
action(
`/api/org/skills/private/${row.definition.id}/emergency-stop`,
{ reason },
),
)
}
>
{t('紧急停用')}
</Button>
</div>
);
};
const openCreateEditor = () => {
setEditingSkill(null);
setForm(blankSkill);
setEditorVisible(true);
};
// 使用指引:自研 Skill 从创建到发布的门禁流程,完成态由列表真实数据驱动。
const guide = usePageGuide({
guideKey: 'org-private-skills',
ready: loaded,
title: t('企业自研 Skill · 使用指引'),
intro: t('创建 → 模型实测 → 双人审核 → 发布,每一步都留审计'),
steps: [
{
title: t('创建私有 Skill'),
detail: t('撰写方法正文与中英文元数据'),
done: items.length > 0,
cta: t('去创建'),
onAction: openCreateEditor,
points: [
t('Skill Markdown 正文就是方法内容,创建后版本不可变'),
t('后续改动走「新版本」,历史版本全部保留可回滚'),
],
},
{
title: t('执行模型实测'),
detail: t('用真实模型跑一遍正文,产生审核证据'),
done: items.some((row) => row.runtime?.conclusion === 'pass'),
points: [
t('「执行模型实测」会实际调用所选模型执行该版本正文'),
t('真实响应自动落库为审核证据;扫描列变绿色 pass 即通过'),
],
},
{
title: t('双人审核'),
detail: t('作者不能审核自己的版本'),
done: items.some((row) => row.review?.status === 'approved'),
points: [
t('作者视角按钮显示「待他人审核」;其他管理员「领取审核」'),
t('领取后由审核人「通过」或「驳回」,结论进入审计'),
],
},
{
title: t('发布与治理'),
detail: t('审核通过后发布;回滚与紧急停用随时可用'),
// 后端 SkillState 发布态只有 'published'(model/skill_supply.go)。
done: items.some((row) => row.definition.status === 'published'),
points: [
t('「发布」后技能按企业分发策略对成员生效,范围在「分发与锁定」配置'),
t('「回滚」可退回任一审核通过的历史版本,「紧急停用」立即止血'),
t('回滚与紧急停用都必须填写可审计原因'),
],
},
],
faq: [
{
q: t('「领取审核」按钮点不了?'),
a: t('你是该版本的作者,双人审核要求由其他管理员领取'),
},
{
q: t('技能被紧急停用后能恢复吗?'),
a: t('解除停用前无法创建新版本;恢复操作同样需要可审计原因'),
},
],
});
const closeGuide = guide.close;
// 抽屉进度是组织私有的:切组织时关闭并复位 loaded,
// 否则重取窗口内胶囊会按旧组织数据渲染完成态。
useEffect(() => {
setLoaded(false);
closeGuide();
}, [orgId, closeGuide]);
return (
<div className='org-skills-page'>
<header className='org-skills-hero'>
<div>
<Title heading={3}>{t('企业自研 Skill')}</Title>
<Text type='tertiary'>
{t(
'版本内容不可变;兼容扫描、双人审核、发布、回滚与紧急停用均保留审计。',
)}
</Text>
</div>
<div className='org-skills-hero-actions'>
<PageGuideTrigger guide={guide} />
<Button icon={<Code2 size={16} />} onClick={openCreateEditor}>
{t('创建私有 Skill')}
</Button>
</div>
</header>
<PageGuidePill guide={guide} />
<PageGuideDrawer guide={guide} />
<OrgPanel>
{items.length === 0 ? (
<SkillEmptyGuide
title={t('还没有自研 Skill')}
description={t(
'把企业沉淀的方法写成 Skill,经实测与双人审核后发布给成员使用。',
)}
actionLabel={t('创建私有 Skill')}
onAction={openCreateEditor}
/>
) : isMobile ? (
<div className='org-skill-mobile-list'>
{items.map((row) => (
<article key={row.definition.id}>
<div>
<strong>{row.definition.canonical_id}</strong>
<Tag
color={row.definition.emergency_stopped ? 'red' : 'blue'}
>
{row.definition.status}
</Tag>
</div>
<span>
{t('版本')}: {row.version?.version_no || '-'}
</span>
<span>
{t('扫描')}: {row.runtime?.conclusion || '-'}
</span>
<span>
{t('审核')}: {row.review?.status || '-'}
</span>
{renderSkillActions(row)}
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={items}
rowKey={(row) => row.definition.id}
columns={[
{
title: t('标识'),
render: (_, row) => row.definition.canonical_id,
},
{
title: t('版本'),
render: (_, row) => row.version?.version_no || '-',
},
{
title: t('扫描'),
render: (_, row) => (
<Tag
color={
row.runtime?.conclusion === 'pass' ? 'green' : 'orange'
}
>
{row.runtime?.conclusion || '-'}
</Tag>
),
},
{
title: t('审核'),
render: (_, row) => <Tag>{row.review?.status || '-'}</Tag>,
},
{
title: t('状态'),
render: (_, row) => (
<Tag
color={row.definition.emergency_stopped ? 'red' : 'blue'}
>
{row.definition.status}
</Tag>
),
},
{
title: t('操作'),
width: 430,
render: (_, row) => renderSkillActions(row),
},
]}
/>
)}
</OrgPanel>
<Modal
title={editingSkill ? t('创建不可变新版本') : t('创建企业私有 Skill')}
visible={editorVisible}
onCancel={() => setEditorVisible(false)}
onOk={save}
width={820}
>
<div className='org-private-skill-form'>
<Input
disabled={!!editingSkill}
placeholder='canonical_id'
value={form.canonical_id}
onChange={(canonical_id) => setForm({ ...form, canonical_id })}
/>
{[
'name_zh',
'name_en',
'description_zh',
'description_en',
'triggers_zh',
'triggers_en',
'scenarios_zh',
'scenarios_en',
'compact_constraint_zh',
'compact_constraint_en',
'tags',
'change_statement',
].map((key) => (
<Input
key={key}
placeholder={key}
value={form[key]}
onChange={(value) => setForm({ ...form, [key]: value })}
/>
))}
<TextArea
rows={10}
placeholder='Skill Markdown'
value={form.body}
onChange={(body) => setForm({ ...form, body })}
/>
</div>
</Modal>
<Modal
title={t('执行真实模型测试')}
visible={!!evidenceVersion}
onCancel={() => setEvidenceVersion(null)}
onOk={recordEvidence}
>
<div className='org-private-skill-form'>
<Input
placeholder={t('模型名称')}
value={evidence.model}
onChange={(model) => setEvidence({ ...evidence, model })}
/>
<TextArea
placeholder={t('测试输入')}
value={evidence.input}
onChange={(input) => setEvidence({ ...evidence, input })}
/>
<Paragraph type='tertiary'>
{t(
'提交后将实际调用所选模型执行该版本正文,真实响应自动落库为审核证据。',
)}
</Paragraph>
</div>
</Modal>
<Modal
title={t('不可变历史版本')}
visible={!!historySkill}
onCancel={() => setHistorySkill(null)}
footer={null}
width={760}
>
{isMobile ? (
<div className='org-skill-mobile-list'>
{history.map((row) => (
<article key={row.version.id}>
<strong>
v{row.version.version_no} / #{row.version.id}
</strong>
<span>
{t('扫描')}: {row.runtime?.conclusion || '-'}
</span>
<span>
{t('审核')}: {row.review?.status || '-'}
</span>
<Button
size='small'
icon={<RotateCcw size={14} />}
disabled={row.review?.status !== 'approved'}
onClick={() =>
askReason(t('回滚到该历史版本'), async (reason) => {
await action(
`/api/org/skills/private/${historySkill.id}/versions/${row.version.id}/rollback`,
{ reason },
);
setHistorySkill(null);
})
}
>
{t('回滚')}
</Button>
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={history}
rowKey={(row) => row.version.id}
columns={[
{
title: t('版本'),
render: (_, row) => `v${row.version.version_no}`,
},
{ title: t('版本 ID'), render: (_, row) => row.version.id },
{
title: t('扫描'),
render: (_, row) => row.runtime?.conclusion || '-',
},
{
title: t('审核'),
render: (_, row) => row.review?.status || '-',
},
{
title: t('操作'),
render: (_, row) => (
<Button
size='small'
icon={<RotateCcw size={14} />}
disabled={row.review?.status !== 'approved'}
onClick={() =>
askReason(t('回滚到该历史版本'), async (reason) => {
await action(
`/api/org/skills/private/${historySkill.id}/versions/${row.version.id}/rollback`,
{ reason },
);
setHistorySkill(null);
})
}
>
{t('回滚')}
</Button>
),
},
]}
/>
)}
</Modal>
</div>
);
};
export default OrgPrivateSkills;
+346
View File
@@ -0,0 +1,346 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Select,
Input,
Tag,
Toast,
Popconfirm,
Empty,
Typography,
} from '@douyinfe/semi-ui';
import { RefreshCw, Plus, Pencil } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const memberName = (m) =>
m.remark || m.display_name || m.username || `#${m.org_member_id}`;
// 我的项目(阶段一):项目经理(项目负责人/项目管理员)自助管理项目成员与项目名。
const OrgProjectManage = ({ orgId }) => {
const { t } = useTranslation();
const [projects, setProjects] = useState([]);
const [memberOptions, setMemberOptions] = useState([]);
const [projectId, setProjectId] = useState(null);
const [members, setMembers] = useState([]);
const [loading, setLoading] = useState(false);
const [addModal, setAddModal] = useState(false);
const [addMemberId, setAddMemberId] = useState(null);
const [addRole, setAddRole] = useState('project_member');
const [adding, setAdding] = useState(false);
const [renameModal, setRenameModal] = useState(false);
const [renameValue, setRenameValue] = useState('');
const [renaming, setRenaming] = useState(false);
const headers = useMemo(() => getOrgHeaders(orgId), [orgId]);
const currentProject = useMemo(
() => projects.find((p) => p.id === projectId) || null,
[projects, projectId],
);
const fetchScope = useCallback(async () => {
try {
const res = await API.get('/api/org/me/project-scope', { headers });
if (res.data.success) {
const list = res.data.data?.projects || [];
setProjects(list);
setMemberOptions(res.data.data?.member_options || []);
setProjectId((prev) => prev || (list[0] ? list[0].id : null));
}
} catch (err) {
showError(err.message);
}
}, [headers]);
useEffect(() => {
fetchScope();
}, [fetchScope]);
const fetchMembers = useCallback(async () => {
if (!projectId) return;
setLoading(true);
try {
const res = await API.get(`/api/org/project/${projectId}/members`, {
headers,
});
if (res.data.success) setMembers(res.data.data || []);
else showError(res.data.message);
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [projectId, headers]);
useEffect(() => {
if (projectId) fetchMembers();
}, [projectId, fetchMembers]);
// 可添加成员:排除已在项目中的
const addableOptions = useMemo(() => {
const inProject = new Set(members.map((m) => m.org_member_id));
return memberOptions
.filter((o) => !inProject.has(o.member_id))
.map((o) => ({ label: o.name, value: o.member_id }));
}, [memberOptions, members]);
const submitAdd = async () => {
if (!addMemberId) {
Toast.warning(t('请选择成员'));
return;
}
setAdding(true);
try {
const res = await API.post(
`/api/org/project/${projectId}/members`,
{ org_member_id: addMemberId, role: addRole },
{ headers },
);
if (res.data.success) {
Toast.success(t('成员已添加'));
setAddModal(false);
setAddMemberId(null);
setAddRole('project_member');
fetchMembers();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setAdding(false);
}
};
const removeMember = async (orgMemberId) => {
try {
const res = await API.delete(
`/api/org/project/${projectId}/members/${orgMemberId}`,
{ headers },
);
if (res.data.success) {
Toast.success(t('成员已移除'));
fetchMembers();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const submitRename = async () => {
const name = renameValue.trim();
if (!name) {
showError(t('项目名称不能为空'));
return;
}
setRenaming(true);
try {
const res = await API.put(
`/api/org/project/${projectId}`,
{ name },
{ headers },
);
if (res.data.success) {
Toast.success(t('项目已更新'));
setRenameModal(false);
fetchScope();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setRenaming(false);
}
};
const columns = [
{ title: t('成员'), render: (_, r) => memberName(r) },
{
title: t('项目角色'),
dataIndex: 'role',
render: (v) => (
<Tag color={v === 'project_admin' ? 'blue' : 'grey'}>
{v === 'project_admin' ? t('项目管理员') : t('项目成员')}
</Tag>
),
},
{
title: t('操作'),
render: (_, r) => (
<Popconfirm
title={t('确认移除该成员?')}
content={t('移除后该成员将失去对本项目的访问权限。')}
onConfirm={() => removeMember(r.org_member_id)}
>
<Button size='small' type='danger' theme='light'>
{t('移除')}
</Button>
</Popconfirm>
),
},
];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={t('我的项目')}
subtitle={t('管理您负责的项目成员')}
actions={
<>
<Select
value={projectId}
onChange={setProjectId}
placeholder={t('选择项目')}
style={{ width: 200 }}
optionList={projects.map((p) => ({
label: p.code ? `${p.name}(${p.code})` : p.name,
value: p.id,
}))}
/>
<Button
theme='light'
icon={<RefreshCw size={14} />}
onClick={() => {
fetchScope();
fetchMembers();
}}
>
{t('刷新')}
</Button>
</>
}
/>
{projects.length === 0 ? (
<Empty
description={t('您当前没有负责的项目')}
style={{ padding: 60 }}
/>
) : (
<OrgPanel>
<div className='flex items-center justify-between mb-3 flex-wrap gap-2'>
<div>
<Text strong>{currentProject?.name || ''}</Text>
{currentProject?.code && (
<Text type='tertiary' size='small' className='ml-2'>
{currentProject.code}
</Text>
)}
</div>
<div className='flex items-center gap-2'>
<Button
size='small'
theme='light'
icon={<Pencil size={14} />}
onClick={() => {
setRenameValue(currentProject?.name || '');
setRenameModal(true);
}}
>
{t('重命名')}
</Button>
<Button
size='small'
theme='solid'
icon={<Plus size={14} />}
onClick={() => setAddModal(true)}
>
{t('添加成员')}
</Button>
</div>
</div>
<Table
columns={columns}
dataSource={members}
loading={loading}
rowKey='org_member_id'
pagination={false}
empty={<Empty description={t('暂无项目成员')} />}
/>
</OrgPanel>
)}
{/* 添加成员 */}
<OrgModal
title={t('添加项目成员')}
visible={addModal}
onOk={submitAdd}
onCancel={() => setAddModal(false)}
okText={t('添加')}
cancelText={t('取消')}
confirmLoading={adding}
>
<div className='space-y-3'>
<Select
placeholder={t('选择成员')}
style={{ width: '100%' }}
value={addMemberId}
onChange={setAddMemberId}
filter
optionList={addableOptions}
/>
<Select
style={{ width: '100%' }}
value={addRole}
onChange={setAddRole}
optionList={[
{ label: t('项目成员'), value: 'project_member' },
{ label: t('项目管理员'), value: 'project_admin' },
]}
/>
</div>
</OrgModal>
{/* 重命名项目 */}
<OrgModal
title={t('重命名项目')}
visible={renameModal}
onOk={submitRename}
onCancel={() => setRenameModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={renaming}
>
<Input
value={renameValue}
onChange={setRenameValue}
placeholder={t('请输入项目名称')}
onEnterPress={submitRename}
/>
</OrgModal>
</div>
);
};
export default OrgProjectManage;
+554
View File
@@ -0,0 +1,554 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Form,
Toast,
Popconfirm,
Tag,
Select,
} from '@douyinfe/semi-ui';
import { RefreshCw, Plus, Users } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import OrgScopedLimitButtons from './components/OrgScopedLimitButtons';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 项目管理:项目增删改 + 项目成员管理(成本归属/项目预算 cap 的载体)
const OrgProjects = ({ orgId }) => {
const { t } = useTranslation();
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const [members, setMembers] = useState([]); // 企业全部成员(用于成员选择)
const [modalVisible, setModalVisible] = useState(false);
const [editing, setEditing] = useState(null);
const [formApi, setFormApi] = useState(null);
const [memberModal, setMemberModal] = useState(null); // 当前管理成员的项目
const [projectMembers, setProjectMembers] = useState([]);
const [addMemberIds, setAddMemberIds] = useState([]); // 支持一次添加多个成员
const [addMemberRole, setAddMemberRole] = useState('project_member');
const [tokenModal, setTokenModal] = useState(null); // 当前管理令牌的项目
const [orgTokens, setOrgTokens] = useState([]);
const fetchList = useCallback(async () => {
if (!orgId) return;
setLoading(true);
try {
const res = await API.get('/api/org/project', {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
setList(res.data.data || []);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
}, [orgId]);
const fetchMembers = useCallback(async () => {
if (!orgId) return;
try {
// 逐页取全:后端把 page_size 静默钳到 100,成员超过 100 人时
// 原先的单次请求会让第 101 位之后的人无法被选进项目。
const { items } = await collectPagedItems((page, size) =>
API.get(`/api/org/members?p=${page}&page_size=${size}`, {
headers: getOrgHeaders(orgId),
}),
);
setMembers(items);
} catch (err) {
showError(err.message);
}
}, [orgId]);
useEffect(() => {
fetchList();
fetchMembers();
}, [fetchList, fetchMembers]);
const memberNameMap = useMemo(() => {
const m = {};
members.forEach((mem) => {
m[mem.id] = mem.display_name || mem.username || `#${mem.id}`;
});
return m;
}, [members]);
const openCreate = () => {
setEditing(null);
setModalVisible(true);
};
const openEdit = (record) => {
setEditing(record);
setModalVisible(true);
};
useEffect(() => {
if (modalVisible && formApi) {
if (editing) {
formApi.setValues({
code: editing.code,
name: editing.name,
status: editing.status || 1,
});
} else {
formApi.setValues({ code: '', name: '', status: 1 });
}
}
}, [modalVisible, editing, formApi]);
const handleSubmit = async () => {
if (!formApi) return;
let values;
try {
values = await formApi.validate();
} catch {
return;
}
try {
let res;
if (editing) {
res = await API.put(`/api/org/project/${editing.id}`, values, {
headers: getOrgHeaders(orgId),
});
} else {
res = await API.post('/api/org/project', values, {
headers: getOrgHeaders(orgId),
});
}
if (res.data.success) {
Toast.success(editing ? t('项目已更新') : t('项目已创建'));
setModalVisible(false);
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const handleDisable = async (record) => {
try {
const res = await API.delete(`/api/org/project/${record.id}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
Toast.success(t('项目已停用'));
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const openMembers = async (record) => {
setMemberModal(record);
setAddMemberIds([]);
setAddMemberRole('project_member');
try {
const res = await API.get(`/api/org/project/${record.id}/members`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
setProjectMembers(res.data.data || []);
}
} catch (err) {
showError(err.message);
}
};
const handleAddMember = async () => {
if (!addMemberIds.length) {
Toast.warning(t('请选择成员'));
return;
}
// 逐个添加(后端为单成员接口)。用 allSettled 保证个别网络失败不会中断
// 其余请求,且无论结果如何都刷新一次,让表格反映后端真实状态。
const results = await Promise.allSettled(
addMemberIds.map((id) =>
API.post(
`/api/org/project/${memberModal.id}/members`,
{ org_member_id: id, role: addMemberRole },
{ headers: getOrgHeaders(orgId) },
),
),
);
const firstError = results.find(
(r) => r.status === 'rejected' || !r.value?.data?.success,
);
if (!firstError) {
Toast.success(t('成员已添加'));
} else {
const msg =
firstError.status === 'rejected'
? firstError.reason?.message || t('网络错误')
: firstError.value.data.message;
showError(t('部分成员添加失败:{{msg}}', { msg }));
}
openMembers(memberModal);
};
const handleRemoveMember = async (orgMemberId) => {
try {
const res = await API.delete(
`/api/org/project/${memberModal.id}/members/${orgMemberId}`,
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('成员已移除'));
openMembers(memberModal);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const projectNameMap = useMemo(() => {
const m = {};
list.forEach((p) => (m[p.id] = p.name));
return m;
}, [list]);
const openTokens = async (project) => {
setTokenModal(project);
try {
const { items } = await collectPagedItems((page, size) =>
API.get(`/api/org/tokens?p=${page}&page_size=${size}`, {
headers: getOrgHeaders(orgId),
}),
);
setOrgTokens(items);
} catch (err) {
showError(err.message);
}
};
const bindToken = async (tokenId, projectId) => {
try {
const res = await API.put(
`/api/org/tokens/${tokenId}/project`,
{ project_id: projectId },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(projectId ? t('已绑定到本项目') : t('已解绑'));
openTokens(tokenModal);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
// 可添加的成员(排除已在项目中的)
const addableMembers = useMemo(() => {
const inProject = new Set(projectMembers.map((pm) => pm.org_member_id));
return members
.filter((mem) => !inProject.has(mem.id))
.map((mem) => ({
label: mem.display_name || mem.username || `#${mem.id}`,
value: mem.id,
}));
}, [members, projectMembers]);
const columns = [
{ title: t('项目编码'), dataIndex: 'code' },
{ title: t('项目名称'), dataIndex: 'name' },
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (v) => (
<Tag color={v === 1 ? 'green' : 'grey'}>
{v === 1 ? t('启用') : t('停用')}
</Tag>
),
},
{
title: t('到期时间'),
dataIndex: 'expired_at',
width: 120,
render: (v) => (v ? new Date(v * 1000).toLocaleDateString() : '-'),
},
{
title: t('操作'),
width: 420,
render: (_, record) => (
<div className='flex items-center gap-2 flex-wrap'>
<OrgScopedLimitButtons
orgId={orgId}
record={record}
apiBase='/api/org/project'
scopeLabel='项目'
onSaved={fetchList}
/>
<Button
size='small'
theme='light'
icon={<Users size={14} />}
onClick={() => openMembers(record)}
>
{t('成员')}
</Button>
<Button size='small' theme='light' onClick={() => openTokens(record)}>
{t('令牌')}
</Button>
<Button size='small' theme='light' onClick={() => openEdit(record)}>
{t('编辑')}
</Button>
{record.status === 1 && (
<Popconfirm
title={t('确认停用该项目?')}
content={t('停用后保留历史,不再接受新调用绑定')}
onConfirm={() => handleDisable(record)}
>
<Button size='small' theme='light' type='danger'>
{t('停用')}
</Button>
</Popconfirm>
)}
</div>
),
},
];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={t('项目管理')}
subtitle={t('项目成员与项目预算')}
actions={
<>
<Button
theme='light'
icon={<RefreshCw size={14} />}
onClick={fetchList}
>
{t('刷新')}
</Button>
<Button
theme='solid'
icon={<Plus size={14} />}
onClick={openCreate}
>
{t('新建项目')}
</Button>
</>
}
/>
<OrgPanel padding='p-2'>
<Table
columns={columns}
dataSource={list}
loading={loading}
pagination={{ pageSize: 15, showSizeChanger: false }}
rowKey='id'
/>
</OrgPanel>
{/* 项目创建/编辑 */}
<OrgModal
title={editing ? t('编辑项目') : t('新建项目')}
visible={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
>
<Form getFormApi={setFormApi}>
<Form.Input
field='code'
label={t('项目编码')}
disabled={!!editing}
rules={[{ required: true, message: t('请输入项目编码') }]}
/>
<Form.Input
field='name'
label={t('项目名称')}
rules={[{ required: true, message: t('请输入项目名称') }]}
/>
{editing && (
<Form.Select
field='status'
label={t('状态')}
optionList={[
{ label: t('启用'), value: 1 },
{ label: t('停用'), value: 2 },
]}
style={{ width: '100%' }}
/>
)}
</Form>
</OrgModal>
{/* 项目成员管理 */}
<OrgModal
title={`${t('项目成员')} - ${memberModal?.name || ''}`}
visible={!!memberModal}
onCancel={() => setMemberModal(null)}
footer={null}
>
<div className='flex items-center gap-2 mb-4'>
<Select
placeholder={t('选择成员')}
optionList={addableMembers}
value={addMemberIds}
onChange={setAddMemberIds}
filter
multiple
maxTagCount={2}
showClear
style={{ flex: 1 }}
/>
<Select
value={addMemberRole}
onChange={setAddMemberRole}
optionList={[
{ label: t('项目成员'), value: 'project_member' },
{ label: t('项目管理员'), value: 'project_admin' },
]}
style={{ width: 130 }}
/>
<Button theme='solid' onClick={handleAddMember}>
{t('添加')}
</Button>
</div>
<Table
columns={[
{
title: t('成员'),
dataIndex: 'org_member_id',
render: (v) => memberNameMap[v] || `#${v}`,
},
{
title: t('角色'),
dataIndex: 'role',
width: 110,
render: (v) =>
v === 'project_admin' ? t('项目管理员') : t('项目成员'),
},
{
title: t('操作'),
width: 90,
render: (_, record) => (
<Popconfirm
title={t('确认移除该成员?')}
content={t('移除后该成员将失去对本项目的访问权限。')}
okType='danger'
position='left'
onConfirm={() => handleRemoveMember(record.org_member_id)}
>
<Button size='small' theme='light' type='danger'>
{t('移除')}
</Button>
</Popconfirm>
),
},
]}
dataSource={projectMembers}
pagination={false}
rowKey='org_member_id'
size='small'
/>
</OrgModal>
{/* 项目令牌绑定 */}
<OrgModal
title={`${t('项目令牌')} - ${tokenModal?.name || ''}`}
visible={!!tokenModal}
onCancel={() => setTokenModal(null)}
footer={null}
width={560}
>
<Table
columns={[
{ title: t('令牌'), dataIndex: 'name' },
{
title: t('当前归属'),
dataIndex: 'project_id',
width: 130,
render: (v) =>
!v ? (
<Tag size='small'>{t('未绑定')}</Tag>
) : v === tokenModal?.id ? (
<Tag color='green' size='small'>
{t('本项目')}
</Tag>
) : (
<Tag color='blue' size='small'>
{projectNameMap[v] || `#${v}`}
</Tag>
),
},
{
title: t('操作'),
width: 130,
render: (_, tk) =>
tk.project_id === tokenModal?.id ? (
<Button
size='small'
theme='light'
type='danger'
onClick={() => bindToken(tk.id, 0)}
>
{t('解绑')}
</Button>
) : (
<Button
size='small'
theme='light'
onClick={() => bindToken(tk.id, tokenModal.id)}
>
{t('绑定到本项目')}
</Button>
),
},
]}
dataSource={orgTokens}
pagination={false}
rowKey='id'
size='small'
/>
</OrgModal>
</div>
);
};
export default OrgProjects;
+650
View File
@@ -0,0 +1,650 @@
/*
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 {
Copy,
Database,
MessageSquareText,
RefreshCw,
RotateCcw,
Search,
SlidersHorizontal,
} from 'lucide-react';
import {
Table,
Button,
Input,
Select,
Tag,
Tooltip,
DatePicker,
} from '@douyinfe/semi-ui';
import { copy, getQuotaPerUnit, showError, showSuccess } from '../../helpers';
import { API } from '../../helpers/api';
import { useOrgPromptRecords } from '../../hooks/org/useOrgData';
import OrgPanel from './components/OrgPanel';
import OrgStateBlock from './components/OrgStateBlock';
import { formatQuotaAsCNY } from './orgAuditFormat';
const emptyFilters = {
memberId: '',
modelName: '',
keyword: '',
startTimestamp: 0,
endTimestamp: 0,
};
const tokenNumberFormatter = new Intl.NumberFormat('zh-CN');
const formatTokenCount = (value) =>
tokenNumberFormatter.format(Number(value) || 0);
// 下钻明细:一条提示词记录 → 该次用户输入的全部接口调用行(首调 + agent 中间调用)。
// 数据来自平台消费日志(logs.prompt_group_key 索引等值查询),展开行时按需拉取。
const PromptCallDetails = ({ orgId, groupKey }) => {
const { t } = useTranslation();
const quotaPerUnit = getQuotaPerUnit();
const [calls, setCalls] = useState(null); // null = 加载中
const [error, setError] = useState('');
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await API.get('/api/org/prompt-archive/records/calls', {
headers: { 'X-Org-Id': String(orgId) },
params: { group_key: groupKey },
});
if (cancelled) return;
if (res.data.success) {
setCalls(res.data.data?.items || []);
} else {
setError(res.data.message || t('查询失败'));
setCalls([]);
}
} catch (e) {
if (!cancelled) {
setError(e.message);
setCalls([]);
}
}
})();
return () => {
cancelled = true;
};
}, [orgId, groupKey, t]);
if (calls === null) {
return (
<div className='text-xs text-gray-400 dark:text-gray-500 mt-2'>
{t('调用明细加载中…')}
</div>
);
}
if (error) {
return (
<div className='text-xs text-red-500 mt-2'>
{t('调用明细加载失败')}:{error}
</div>
);
}
if (calls.length === 0) {
return (
<div className='text-xs text-gray-400 dark:text-gray-500 mt-2'>
{t('无关联调用明细(该记录产生于下钻功能上线之前,或消费日志已清理)')}
</div>
);
}
return (
<div className='mt-3'>
<div className='text-xs font-medium text-gray-500 dark:text-gray-400 mb-1'>
{t('调用明细')}({calls.length}
{calls.length >= 200 ? '+' : ''})
<span className='ml-2 font-normal text-gray-400 dark:text-gray-500'>
{t(
'明细为该提示词的全部调用;跨 30 分钟统计桶或多令牌时,条数可能多于本行调用次数',
)}
</span>
</div>
<div className='overflow-x-auto'>
<table className='w-full text-xs text-gray-600 dark:text-gray-400'>
<thead>
<tr className='text-left text-gray-400 dark:text-gray-500'>
<th className='py-1 pr-3 font-normal'>{t('时间')}</th>
<th className='py-1 pr-3 font-normal'>{t('模型')}</th>
<th className='py-1 pr-3 font-normal'>{t('输入/输出 tokens')}</th>
<th className='py-1 pr-3 font-normal'>{t('花费')}</th>
<th className='py-1 pr-3 font-normal'>{t('耗时')}</th>
<th className='py-1 pr-3 font-normal'>{t('流式')}</th>
</tr>
</thead>
<tbody>
{calls.map((log) => (
<tr
key={log.id}
className='border-t border-gray-100 dark:border-white/[0.06]'
>
<td className='py-1 pr-3'>
{new Date(log.created_at * 1000).toLocaleString('zh-CN')}
</td>
<td className='py-1 pr-3'>{log.model_name}</td>
<td className='py-1 pr-3'>
{log.prompt_tokens} / {log.completion_tokens}
</td>
<td className='py-1 pr-3'>
{formatQuotaAsCNY(log.quota, quotaPerUnit)}
</td>
<td className='py-1 pr-3'>{log.use_time}s</td>
<td className='py-1 pr-3'>
{log.is_stream ? t('是') : t('否')}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
// 提示词记录审计表(方案 §35 一期):数据来自企业自行配置的数据库,
// 一行 = 一次「用户输入 → 最终 AI 返回」,agent 中间过程调用只累计次数与花费。
const OrgPromptRecords = ({ orgId }) => {
const { t } = useTranslation();
const quotaPerUnit = getQuotaPerUnit();
const { records, total, loading, error, fetch } = useOrgPromptRecords(orgId);
const [page, setPage] = useState(1);
const [members, setMembers] = useState([]);
const [membersLoading, setMembersLoading] = useState(true);
const [selectedMemberId, setSelectedMemberId] = useState('');
const [modelName, setModelName] = useState('');
const [keyword, setKeyword] = useState('');
const [timeRange, setTimeRange] = useState(null);
const [appliedFilters, setAppliedFilters] = useState(emptyFilters);
const buildFilters = () => {
const [start, end] = Array.isArray(timeRange) ? timeRange : [null, null];
return {
memberId: selectedMemberId,
modelName: modelName.trim(),
keyword: keyword.trim(),
startTimestamp: start ? Math.floor(start.getTime() / 1000) : 0,
endTimestamp: end ? Math.floor(end.getTime() / 1000) : 0,
};
};
useEffect(() => {
setSelectedMemberId('');
setModelName('');
setKeyword('');
setTimeRange(null);
setAppliedFilters(emptyFilters);
setPage(1);
}, [orgId]);
useEffect(() => {
let cancelled = false;
setMembers([]);
setMembersLoading(true);
(async () => {
try {
const res = await API.get('/api/org/prompt-archive/members', {
headers: { 'X-Org-Id': String(orgId) },
});
if (!cancelled && res.data.success) {
setMembers(res.data.data?.items || []);
} else if (!cancelled) {
showError(res.data.message || t('加载历史成员失败'));
}
} catch (err) {
if (!cancelled) {
setMembers([]);
showError(err.message);
}
} finally {
if (!cancelled) setMembersLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [orgId, t]);
useEffect(() => {
if (membersLoading) return;
fetch(page, 20, appliedFilters);
}, [appliedFilters, fetch, membersLoading, page]);
const applyFilter = () => {
setAppliedFilters(buildFilters());
setPage(1);
};
const resetFilters = () => {
setSelectedMemberId('');
setModelName('');
setKeyword('');
setTimeRange(null);
setAppliedFilters(emptyFilters);
setPage(1);
};
const memberOptions = useMemo(
() => [
{ value: '', label: t('全部成员') },
...members.map((member) => {
const name = member.name || member.username || `User#${member.user_id}`;
return {
value: member.member_id,
label:
member.status === 1 ? name : t('{{name}}(历史成员)', { name }),
};
}),
],
[members, t],
);
const getMemberName = (record) => {
const member = members.find(
(item) => String(item.member_id) === String(record.org_member_id),
);
return (
record.member_name ||
member?.name ||
member?.remark ||
member?.display_name ||
record.username ||
`User#${record.user_id}`
);
};
const handleCopyPrompt = async (event, prompt) => {
event?.stopPropagation();
const text = prompt || '';
if (!text) return;
if (await copy(text)) {
showSuccess(t('已复制提示词'));
} else {
showError(t('复制失败,请手动复制'));
}
};
const columns = [
{
title: t('成员'),
dataIndex: 'member_name',
width: 180,
render: (_, record) => {
const name = getMemberName(record);
return (
<Tooltip content={name} position='topLeft'>
<div className='flex min-w-0 max-w-[164px] items-center gap-2.5 whitespace-nowrap'>
<span className='inline-flex h-7 w-7 flex-none items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand'>
{name.trim().slice(0, 1).toUpperCase() || '#'}
</span>
<span className='min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium text-[var(--text-primary)]'>
{name}
</span>
</div>
</Tooltip>
);
},
},
{
title: t('模型'),
dataIndex: 'model_name',
width: 170,
render: (v) => (
<Tooltip content={v || '-'} position='top'>
<Tag
size='small'
color='violet'
type='light'
style={{ maxWidth: 154 }}
>
<span className='block overflow-hidden text-ellipsis whitespace-nowrap'>
{v || '-'}
</span>
</Tag>
</Tooltip>
),
},
{
title: t('提示词'),
dataIndex: 'prompt',
render: (prompt) => {
const text = prompt || '';
const brief = text.length > 80 ? text.slice(0, 80) + '…' : text;
const preview = text.length > 240 ? text.slice(0, 240) + '…' : text;
return (
<div className='flex w-full min-w-0 items-center gap-1.5'>
<Tooltip
content={preview}
position='topLeft'
style={{ maxWidth: 480 }}
>
<span className='min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-[13px] leading-5 text-gray-600 dark:text-gray-300'>
{brief || '-'}
</span>
</Tooltip>
{text && (
<Tooltip content={t('复制提示词')} position='top'>
<button
type='button'
aria-label={t('复制提示词')}
className='inline-flex h-7 w-7 flex-none items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-brand/10 hover:text-brand focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40'
onClick={(event) => handleCopyPrompt(event, text)}
>
<Copy size={14} />
</button>
</Tooltip>
)}
</div>
);
},
},
{
title: t('来源'),
dataIndex: 'source',
width: 90,
render: (v) => (
<Tag
size='small'
color={v === 'playground' ? 'blue' : v === 'mobile' ? 'teal' : 'grey'}
type='ghost'
>
{v === 'playground' ? t('对话面板') : v === 'mobile' ? 'App' : 'API'}
</Tag>
),
},
{
title: t('调用次数'),
dataIndex: 'call_count',
width: 90,
render: (v) => (
<span className='inline-flex min-w-7 justify-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-semibold text-gray-700 dark:bg-white/[0.06] dark:text-gray-300'>
{formatTokenCount(v)}
</span>
),
},
{
title: t('总花费'),
dataIndex: 'total_quota',
width: 110,
render: (v) => (
<span className='whitespace-nowrap text-sm font-semibold text-[var(--text-primary)]'>
{formatQuotaAsCNY(v, quotaPerUnit)}
</span>
),
},
{
title: t('Token 消耗'),
dataIndex: 'prompt_tokens',
width: 230,
render: (v, record) => (
<Tooltip
content={
t('输入 / 输出 tokens(全过程累计)') +
`,${t('缓存命中')} ${record.cache_hit_tokens || 0}` +
`,${t('缓存创建')} ${record.cache_creation_tokens || 0}`
}
position='top'
>
<div className='grid cursor-default grid-cols-2 gap-x-4 gap-y-1 whitespace-nowrap text-xs'>
<span className='text-gray-400 dark:text-gray-500'>
{t('输入')}
</span>
<span className='text-right font-medium tabular-nums text-gray-700 dark:text-gray-300'>
{formatTokenCount(v)}
</span>
<span className='text-gray-400 dark:text-gray-500'>
{t('输出')}
</span>
<span className='text-right font-medium tabular-nums text-gray-700 dark:text-gray-300'>
{formatTokenCount(record.completion_tokens)}
</span>
<span className='text-amber-600 dark:text-amber-400'>
{t('缓存创建')}
</span>
<span className='text-right font-medium tabular-nums text-amber-700 dark:text-amber-300'>
{formatTokenCount(record.cache_creation_tokens)}
</span>
<span className='text-emerald-600 dark:text-emerald-400'>
{t('缓存命中')}
</span>
<span className='text-right font-medium tabular-nums text-emerald-700 dark:text-emerald-300'>
{formatTokenCount(record.cache_hit_tokens)}
</span>
</div>
</Tooltip>
),
},
{
title: t('时间'),
dataIndex: 'last_at',
width: 175,
render: (v, record) => (
<Tooltip
content={
t('首次') +
': ' +
new Date(record.first_at * 1000).toLocaleString('zh-CN') +
',' +
t('最后') +
': ' +
new Date(v * 1000).toLocaleString('zh-CN')
}
>
<span className='cursor-default whitespace-nowrap text-xs tabular-nums text-gray-500 dark:text-gray-400'>
{v ? new Date(v * 1000).toLocaleString('zh-CN') : '-'}
</span>
</Tooltip>
),
},
];
const expandedRowRender = (record) => (
<div className='bg-gray-50/70 p-4 text-sm dark:bg-white/[0.02] sm:p-5'>
<div className='mb-2.5 flex items-center justify-between gap-3'>
<div className='min-w-0 text-xs text-gray-400 dark:text-gray-500'>
{record.trace_id
? `Trace ID: ${record.trace_id}`
: t('归组方式:启发式(同一输入 30 分钟内的调用自动归为一条)')}
{record.truncated ? ` · ${t('内容超长已截断')}` : ''}
</div>
{record.prompt && (
<button
type='button'
className='inline-flex h-8 flex-none items-center gap-1.5 rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] px-2.5 text-xs font-medium text-gray-600 transition-colors hover:border-brand/30 hover:bg-brand/5 hover:text-brand focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 dark:text-gray-300'
onClick={(event) => handleCopyPrompt(event, record.prompt)}
>
<Copy size={14} />
{t('复制提示词')}
</button>
)}
</div>
<pre className='max-h-80 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] p-3.5 text-xs leading-5 text-gray-700 dark:text-gray-300'>
{record.prompt || '-'}
</pre>
{record.group_key && (
<PromptCallDetails orgId={orgId} groupKey={record.group_key} />
)}
</div>
);
const activeFilterCount =
Number(Boolean(appliedFilters.memberId)) +
Number(Boolean(appliedFilters.modelName)) +
Number(Boolean(appliedFilters.keyword)) +
Number(
Boolean(appliedFilters.startTimestamp || appliedFilters.endTimestamp),
);
return (
<>
<div className='mb-4 mt-4 flex items-start gap-3 rounded-xl border border-brand/15 bg-brand/[0.045] px-4 py-3 text-xs leading-5 text-gray-600 dark:text-gray-300'>
<Database size={16} className='mt-0.5 flex-none text-brand' />
<div>
<div className='font-medium text-[var(--text-primary)]'>
{t('企业自有提示词记录库')}
</div>
<div className='mt-0.5 text-gray-500 dark:text-gray-400'>
{t(
'数据来自「企业设置 → 提示词采集」中配置的自有数据库,仅记录成员输入,不包含 AI 回复。',
)}
</div>
</div>
</div>
<OrgPanel
icon={SlidersHorizontal}
title={t('筛选条件')}
subtitle={
activeFilterCount > 0
? t('已应用 {{count}} 个筛选条件', { count: activeFilterCount })
: t('可按成员、模型、关键词和时间范围组合查询')
}
className='mb-4'
>
<div className='grid grid-cols-1 items-end gap-3 sm:grid-cols-2 xl:grid-cols-[180px_180px_minmax(200px,1fr)_360px_auto]'>
<label className='min-w-0'>
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
{t('企业成员')}
</span>
<Select
value={selectedMemberId}
onChange={setSelectedMemberId}
optionList={memberOptions}
placeholder={t('全部成员')}
style={{ width: '100%' }}
loading={membersLoading}
filter
/>
</label>
<label className='min-w-0'>
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
{t('模型')}
</span>
<Input
value={modelName}
onChange={setModelName}
placeholder={t('输入模型名称')}
showClear
onEnterPress={applyFilter}
/>
</label>
<label className='min-w-0'>
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
{t('提示词')}
</span>
<Input
value={keyword}
onChange={setKeyword}
placeholder={t('搜索提示词关键词')}
showClear
onEnterPress={applyFilter}
/>
</label>
<label className='min-w-0 sm:col-span-2 xl:col-span-1'>
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
{t('时间范围')}
</span>
<DatePicker
type='dateTimeRange'
density='compact'
value={timeRange}
onChange={setTimeRange}
placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: '100%' }}
/>
</label>
<div className='flex flex-wrap gap-2 sm:col-span-2 xl:col-span-1 xl:flex-nowrap'>
<Button
type='primary'
icon={<Search size={14} />}
onClick={applyFilter}
loading={loading || membersLoading}
>
{t('查询')}
</Button>
<Button icon={<RotateCcw size={14} />} onClick={resetFilters}>
{t('重置')}
</Button>
</div>
</div>
</OrgPanel>
<OrgPanel
title={t('提示词调用记录')}
subtitle={
loading
? t('正在加载记录…')
: t('共 {{count}} 条记录,展开行可查看完整提示词与调用明细', {
count: total,
})
}
actions={
<Button
icon={<RefreshCw size={14} />}
onClick={() => fetch(page, 20, appliedFilters)}
loading={loading || membersLoading}
>
{t('刷新')}
</Button>
}
padding='p-0'
bodyClassName='overflow-x-auto'
>
{/* 宽屏占满卡片,窄屏保持 1400px 最小宽度并由外层横向滚动。 */}
<Table
className='org-prompt-records-table'
columns={columns}
dataSource={records}
loading={loading}
rowKey='id'
expandedRowRender={expandedRowRender}
expandRowByClick
onRow={() => ({ className: 'cursor-pointer' })}
scroll={{ x: 'max(100%, 1400px)' }}
pagination={{
currentPage: page,
pageSize: 20,
total,
onPageChange: setPage,
}}
empty={
<OrgStateBlock
icon={MessageSquareText}
title={error || t('暂无提示词记录')}
description={
error
? t(
'请企业所有者在「企业设置 → 提示词采集」中完成数据库配置并初始化数据表',
)
: undefined
}
/>
}
/>
</OrgPanel>
</>
);
};
export default OrgPromptRecords;
+97
View File
@@ -0,0 +1,97 @@
/*
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 from 'react';
import { Typography } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import QualityDashboard from '../../components/quality/QualityDashboard';
import './org-quality.css';
const { Title, Text } = Typography;
/** 企业中心 · 调用质量:只见本企业数据,渠道与上游细节由后端屏蔽 */
const OrgQuality = ({ orgId }) => {
const { t } = useTranslation();
const guide = usePageGuide({
guideKey: 'org-quality',
title: t('调用质量 · 使用指引'),
intro: t('回答三个问题:调用成不成功、失败怪谁、哪些成员 / 模型受影响最大'),
steps: [
{
title: t('读懂结局'),
detail: t('每次调用只归入一种结局'),
points: [
t(
'「兜底成功」:首选线路失败,平台自动切换备用线路后成功,对使用者无感',
),
t('「兜底失败」:所有备用线路都失败,需要关注'),
t(
'「客户端中断」「内容安全拦截」默认不计入成功率分母,可在「更多筛选」中勾选纳入',
),
],
},
{
title: t('区分责任方'),
detail: t('失败按原因归类,便于判断是否需要自查'),
points: [
t('「请求参数问题」「额度 / 限流」通常可由企业侧调整解决'),
t('「服务侧故障」由平台负责处理,持续偏高可联系平台'),
],
},
{
title: t('下钻定位'),
detail: t('从汇总一路点到具体请求'),
points: [
t('点击指标卡直接查看对应结局的请求明细'),
t(
'点击趋势柱子放大到该时段;点击分布表格的行按该部门 / 成员 / 模型筛选',
),
t('按成员 / 部门 / 项目筛选时直接统计调用日志,时间范围最长 7 天'),
],
},
],
});
return (
<div className='org-quality-page'>
<header className='org-quality-hero'>
<div className='min-w-0'>
<div className='org-quality-eyebrow'>{t('调用质量')}</div>
<Title heading={3}>{t('企业调用质量')}</Title>
<Text type='tertiary'>
{t(
'查看本企业调用的成功率、自动兜底效果与失败原因,定位受影响的成员与模型。',
)}
</Text>
</div>
<PageGuideTrigger guide={guide} />
</header>
<PageGuideDrawer guide={guide} />
<QualityDashboard scope='org' orgId={orgId} />
</div>
);
};
export default OrgQuality;
+855
View File
@@ -0,0 +1,855 @@
/*
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, useCallback, useMemo } from 'react';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import {
Typography,
Button,
Spin,
Table,
Tag,
InputNumber,
Select,
} from '@douyinfe/semi-ui';
import {
CreditCard,
Wallet,
TrendingUp,
Coins,
History,
CheckCircle,
Clock,
XCircle,
Pencil,
} from 'lucide-react';
import {
API,
showError,
showInfo,
showSuccess,
renderQuota,
getQuotaPerUnit,
} from '../../helpers';
import AmountCard from '../Recharge/AmountCard';
import WechatQRModal from '../../components/topup/modals/WechatQRModal';
import PaymentConfirmModal from '../../components/topup/modals/PaymentConfirmModal';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import { orgStatusColor } from './components/orgStatus';
import {
formatPayPalUSD,
getPayPalReturnState,
parsePayPalQuote,
requestPayPalOrder,
removePayPalReturnState,
} from '../../helpers/paypalPayment';
const { Text, Title } = Typography;
const OrgRecharge = ({ orgId }) => {
const { t } = useTranslation();
// 企业信息
const [orgQuota, setOrgQuota] = useState(0);
const [orgUsedQuota, setOrgUsedQuota] = useState(0);
// 充值配置
const [presetAmounts, setPresetAmounts] = useState([]);
const [payMethods, setPayMethods] = useState([]);
const [enableWechatTopUp, setEnableWechatTopUp] = useState(false);
const [enableAlipayTopUp, setEnableAlipayTopUp] = useState(false);
const [enablePayPalTopUp, setEnablePayPalTopUp] = useState(false);
const [infoLoading, setInfoLoading] = useState(true);
// 充值交互状态
const [selectedPreset, setSelectedPreset] = useState(null);
const [selectedPresetObj, setSelectedPresetObj] = useState(null);
const [payWay, setPayWay] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const [amountLoading, setAmountLoading] = useState(false);
const [payPalQuote, setPayPalQuote] = useState(null);
// 自定义充值(与预设档位互斥;自定义金额无折扣,原价到账)
const [isCustomMode, setIsCustomMode] = useState(false);
const [customAmount, setCustomAmount] = useState(null);
const [customUnit, setCustomUnit] = useState(1000); // 1000=千 / 10000=万
const customEffectiveAmount = useMemo(() => {
if (!customAmount || customAmount < 1) return 0;
return Math.floor(Number(customAmount)) * customUnit;
}, [customAmount, customUnit]);
const customValid = customEffectiveAmount >= 1000;
// 当前生效的金额/折扣/赠送(自定义优先)
const effectiveAmountYuan = isCustomMode
? customEffectiveAmount
: selectedPresetObj?.value || 0;
const effectiveDiscount = isCustomMode
? 1.0
: selectedPresetObj?.discount || 1.0;
const effectiveBonus = isCustomMode ? 0 : selectedPresetObj?.bonus || 0;
// 微信二维码
const [wechatQRVisible, setWechatQRVisible] = useState(false);
const [wechatOrderData, setWechatOrderData] = useState(null);
// 充值记录
const [history, setHistory] = useState([]);
const [historyTotal, setHistoryTotal] = useState(0);
const [historyPage, setHistoryPage] = useState(1);
const [historyLoading, setHistoryLoading] = useState(false);
const [refreshHistory, setRefreshHistory] = useState(0);
const orgHeaders = { 'X-Org-Id': String(orgId) };
// 获取企业配额
const fetchOrgQuota = useCallback(async () => {
try {
const res = await API.get('/api/org/quota', { headers: orgHeaders });
if (res.data.success) {
const { quota, used_quota } = res.data.data;
setOrgQuota(quota || 0);
setOrgUsedQuota(used_quota || 0);
}
} catch (e) {
// ignore
}
}, [orgId]);
// 获取充值配置
const fetchTopUpInfo = useCallback(async () => {
setInfoLoading(true);
try {
const res = await API.get('/api/org/topup/info', { headers: orgHeaders });
if (res.data.success) {
const data = res.data.data;
setEnableWechatTopUp(data.enable_wechat_topup || false);
setEnableAlipayTopUp(data.enable_alipay_topup || false);
setEnablePayPalTopUp(data.enable_paypal_topup || false);
setPayMethods(data.pay_methods || []);
if (data.amount_options_v2 && data.amount_options_v2.length > 0) {
const sorted = [...data.amount_options_v2].sort(
(a, b) => (a.sort || 0) - (b.sort || 0),
);
setPresetAmounts(
sorted.map((opt) => ({
id: opt.id,
value: opt.amount,
discount: opt.discount || 1.0,
label: opt.label,
badge: opt.badge,
badgeColor: opt.badge_color,
isRecommend: opt.is_recommend,
isHot: opt.is_hot,
bonus: opt.bonus,
minVipLevel: opt.min_vip_level,
})),
);
}
}
} catch (e) {
showError(t('获取充值配置失败'));
} finally {
setInfoLoading(false);
}
}, [orgId]);
// 获取充值记录
const fetchHistory = useCallback(
async (page = 1) => {
setHistoryLoading(true);
try {
const res = await API.get(`/api/org/topup?p=${page}&page_size=10`, {
headers: orgHeaders,
});
if (res.data.success) {
const data = res.data.data;
setHistory(data.items || []);
setHistoryTotal(data.total || 0);
}
} catch (e) {
// ignore
} finally {
setHistoryLoading(false);
}
},
[orgId],
);
useEffect(() => {
fetchOrgQuota();
fetchTopUpInfo();
}, [fetchOrgQuota, fetchTopUpInfo]);
useEffect(() => {
fetchHistory(historyPage);
}, [fetchHistory, historyPage, refreshHistory]);
useEffect(() => {
const result = getPayPalReturnState(window.location.search);
if (!result) return;
if (result.status === 'success') showSuccess(t('PayPal 充值成功'));
else if (result.status === 'pending')
showInfo(t('PayPal 支付处理中,请稍后查看充值记录'));
else if (result.status === 'cancelled') showInfo(t('已取消 PayPal 支付'));
else showError(t('PayPal 支付确认失败,请稍后重试'));
fetchOrgQuota();
setRefreshHistory((previous) => previous + 1);
window.history.replaceState(
{},
'',
removePayPalReturnState(window.location.href),
);
// The callback query must be consumed exactly once on page entry.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selectPreset = (preset) => {
setSelectedPreset(preset.id);
setSelectedPresetObj(preset);
setIsCustomMode(false);
setCustomAmount(null);
};
const handleCustomAmountChange = (v) => {
setCustomAmount(v);
if (v && Number(v) > 0) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
} else {
setIsCustomMode(false);
}
};
const handleCustomUnitChange = (v) => {
setCustomUnit(v);
if (customAmount && Number(customAmount) > 0) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
}
};
// 自定义充值快速选择档位
const customQuickPicks = [
{ amount: 1, unit: 1000 },
{ amount: 5, unit: 1000 },
{ amount: 1, unit: 10000 },
{ amount: 5, unit: 10000 },
{ amount: 10, unit: 10000 },
];
const applyCustomQuickPick = (amount, unit) => {
setCustomAmount(amount);
setCustomUnit(unit);
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
};
// 自定义充值预览额度(与后端 service.CalculateQuota 一致:originalMoney * QuotaPerUnit + bonus,自定义 bonus=0)
const customPreviewQuota =
customEffectiveAmount > 0
? customEffectiveAmount * (getQuotaPerUnit() || 500000)
: 0;
const handlePreTopUp = async (paymentType) => {
if (isCustomMode) {
if (!customValid) {
showError(t('自定义充值金额最少为 1000 元'));
return;
}
} else if (!selectedPresetObj) {
showError(t('请先选择充值金额'));
return;
}
setPayWay(paymentType);
if (paymentType === 'paypal') {
if (!enablePayPalTopUp) {
showError(t('管理员未开启 PayPal 充值!'));
return;
}
setAmountLoading(true);
try {
const response = await API.post(
'/api/org/topup/paypal/amount',
buildPayBody(),
{ headers: orgHeaders },
);
if (!response.data.success) {
throw new Error(response.data.message || t('获取金额失败'));
}
setPayPalQuote(parsePayPalQuote(response));
} catch (error) {
showError(error?.message || t('获取金额失败'));
return;
} finally {
setAmountLoading(false);
}
}
setConfirmOpen(true);
};
const buildPayBody = () =>
isCustomMode
? { custom_amount: customEffectiveAmount }
: { amount_option_id: selectedPresetObj.id };
const isMobile = /iPhone|Android|iPad|Mobile/i.test(navigator.userAgent);
const handleConfirmPay = async () => {
if (!isCustomMode && !selectedPresetObj) return;
if (isCustomMode && !customValid) return;
setConfirmLoading(true);
try {
let res;
const payBody = buildPayBody();
if (payWay === 'wxpay' && enableWechatTopUp) {
const wechatEndpoint = isMobile
? '/api/org/topup/wechat/h5'
: '/api/org/topup/wechat/native';
res = await API.post(wechatEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
if (isMobile) {
// H5:直接跳转微信支付页
window.location.href = res.data.data.h5_url;
setConfirmOpen(false);
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
} else {
// Native:弹出二维码
setWechatOrderData(res.data.data);
setConfirmOpen(false);
setWechatQRVisible(true);
}
return;
}
} else if (payWay === 'paypal' && enablePayPalTopUp) {
res = await requestPayPalOrder(
API,
'/api/org/topup/paypal',
{ ...payBody, quote_token: payPalQuote?.quoteToken },
{ headers: orgHeaders, skipErrorHandler: true },
);
if (res.data.success && res.data.data?.approval_url) {
setPayPalQuote(parsePayPalQuote(res));
window.location.href = res.data.data.approval_url;
return;
}
if (
res.status === 202 &&
res.data?.message === 'PAYPAL_ORDER_CREATING'
) {
showInfo(t('PayPal 订单创建中,请稍后重试'));
return;
}
} else if (payWay === 'alipay' && enableAlipayTopUp) {
const alipayEndpoint = isMobile
? '/api/org/topup/alipay/wap'
: '/api/org/topup/alipay/pc';
res = await API.post(alipayEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
// Safari 会拦截 await 之后的 window.open(用户手势已过期),改为同标签跳转
const isSafari =
navigator.userAgent.indexOf('Safari') > -1 &&
navigator.userAgent.indexOf('Chrome') < 1;
if (isSafari) {
window.location.href = res.data.data.pay_url;
return;
}
window.open(res.data.data.pay_url, '_blank');
setConfirmOpen(false);
// 用户从支付宝标签页切回时自动刷新余额和记录
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
return;
}
}
// 失败处理
const msg = res?.data?.message || t('支付请求失败');
showError(msg);
} catch (e) {
const code = e?.response?.data?.message;
if (payWay === 'paypal' && code?.startsWith('PAYPAL_QUOTE_')) {
try {
const response = await API.post(
'/api/org/topup/paypal/amount',
buildPayBody(),
{ headers: orgHeaders },
);
if (!response.data.success) throw new Error(response.data.message);
setPayPalQuote(parsePayPalQuote(response));
showInfo(t('PayPal 报价已更新,请重新确认'));
} catch {
showError(t('获取金额失败'));
}
} else {
showError(e?.response?.data?.message || t('支付请求失败'));
}
} finally {
setConfirmLoading(false);
}
};
const handleWechatComplete = (success) => {
setWechatQRVisible(false);
setWechatOrderData(null);
if (success) {
showSuccess(t('充值成功!'));
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
}
};
const renderAmount = () => {
if (payWay === 'paypal') {
return formatPayPalUSD(payPalQuote?.payAmount);
}
if (effectiveAmountYuan <= 0) return '';
const pay = effectiveAmountYuan * effectiveDiscount;
return `${pay.toFixed(2)} ${t('元')}`;
};
// 充值记录状态渲染
const renderStatus = (status) => {
const map = {
success: {
icon: <CheckCircle size={12} />,
text: t('成功'),
},
pending: {
icon: <Clock size={12} />,
text: t('待支付'),
},
expired: { icon: <XCircle size={12} />, text: t('已过期') },
};
const s = map[status] || { icon: null, text: status };
return (
<Tag
color={orgStatusColor(status)}
size='small'
className='flex items-center gap-1'
>
{s.icon}
{s.text}
</Tag>
);
};
const historyColumns = [
{
title: t('订单号'),
dataIndex: 'trade_no',
render: (v) => (
<Text size='small' className='font-mono'>
{v}
</Text>
),
ellipsis: true,
},
{
title: t('金额'),
dataIndex: 'money',
render: (v) => <Text size='small'>¥{Number(v).toFixed(2)}</Text>,
width: 90,
},
{
title: t('获得额度'),
dataIndex: 'amount',
render: (v) => <Text size='small'>{renderQuota(v)}</Text>,
width: 110,
},
{
title: t('支付方式'),
dataIndex: 'payment_channel',
render: (v) => (
<Text size='small'>
{v === 'paypal_checkout' ? 'PayPal' : v || '-'}
</Text>
),
width: 110,
},
{
title: t('状态'),
dataIndex: 'status',
render: (v) => renderStatus(v),
width: 90,
},
{
title: t('时间'),
dataIndex: 'create_time',
render: (v) => <Text size='small'>{timestamp2string(v)}</Text>,
width: 160,
},
];
const hasAnyPayment =
enableWechatTopUp || enableAlipayTopUp || enablePayPalTopUp;
return (
<div className='p-4 sm:p-6 lg:p-8 space-y-6'>
<OrgPageHeader title={t('企业充值')} subtitle={t('为企业账户充值额度')} />
{/* 签名时刻:余额展示区(本页唯一的品牌渐变区,渐变走 --brand-* token 随预设切换) */}
<div className='relative overflow-hidden bg-gradient-to-r from-brand-from via-brand-via to-brand-to rounded-xl p-5 shadow-[var(--elevation-md)]'>
<div className='flex items-center justify-between gap-4 flex-wrap'>
<div className='flex items-center gap-3'>
<div className='p-2 bg-white/15 rounded-lg'>
<Wallet size={20} className='text-white' />
</div>
<div>
<Text className='!text-white/80 text-xs font-medium block'>
{t('企业可用余额')}
</Text>
<Title heading={4} className='!text-white !mb-0 tabular-nums'>
{renderQuota(orgQuota)}
</Title>
</div>
</div>
<div className='w-px h-10 bg-white/20 flex-shrink-0' />
<div className='flex items-center gap-3'>
<div className='p-2 bg-white/10 rounded-lg'>
<TrendingUp size={18} className='text-white/80' />
</div>
<div>
<Text className='!text-white/60 text-xs block'>
{t('累计消耗')}
</Text>
<Text className='!text-white font-semibold text-sm tabular-nums'>
{renderQuota(orgUsedQuota)}
</Text>
</div>
</div>
</div>
</div>
{/* 充值区域 */}
<OrgPanel icon={Coins} title={t('选择充值档位')}>
{infoLoading ? (
<div className='py-10 flex justify-center'>
<Spin />
</div>
) : presetAmounts.length > 0 ? (
<>
<div className='grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2.5 mb-4'>
{presetAmounts.map((preset, idx) => (
<AmountCard
key={idx}
preset={preset}
selected={selectedPreset === preset.id}
onClick={() => selectPreset(preset)}
topupInfo={{ amount_options: [], discount: {} }}
priceRatio={1}
t={t}
/>
))}
</div>
{/* 自定义充值(与档位互斥;自定义金额无折扣,原价到账) */}
<div
className={`mb-5 rounded-xl border-2 border-dashed transition-all ${
isCustomMode
? 'border-emerald-400 bg-gradient-to-br from-emerald-50/60 to-emerald-50/25 dark:from-emerald-900/15 dark:to-emerald-900/10 dark:border-emerald-600 shadow-sm shadow-emerald-500/5'
: 'border-gray-200 dark:border-neutral-700 hover:border-emerald-300 dark:hover:border-emerald-700'
}`}
>
{/* 头部 */}
<div className='px-4 pt-3.5 pb-2.5 flex items-center justify-between flex-wrap gap-1.5'>
<div className='flex items-center gap-1.5'>
<div className='p-1 rounded-md bg-emerald-100 dark:bg-emerald-900/40'>
<Pencil
size={12}
className='text-emerald-600 dark:text-emerald-400'
/>
</div>
<Text
strong
className='text-gray-800 dark:text-gray-200 text-sm'
>
{t('自定义充值')}
</Text>
{isCustomMode && (
<Tag color='green' size='small'>
{t('已选')}
</Tag>
)}
</div>
<Text type='tertiary' size='small'>
{t('原价到账,不参与折扣')}
</Text>
</div>
{/* 输入区 */}
<div className='px-4 pb-3'>
<div className='flex items-center gap-2'>
<InputNumber
value={customAmount}
onChange={handleCustomAmountChange}
min={1}
precision={0}
hideButtons
size='large'
placeholder={t('请输入整数,如 1、5、10')}
className='!flex-1'
style={{ width: '100%' }}
/>
<Select
value={customUnit}
onChange={handleCustomUnitChange}
size='large'
style={{ width: 96 }}
optionList={[
{ label: t('千'), value: 1000 },
{ label: t('万'), value: 10000 },
]}
/>
</div>
{/* 快速选择 */}
<div className='mt-2.5 flex items-center gap-1.5 flex-wrap'>
<Text
type='tertiary'
size='small'
className='!text-xs flex-shrink-0'
>
{t('快速选择:')}
</Text>
{customQuickPicks.map((pick) => {
const active =
isCustomMode &&
Number(customAmount) === pick.amount &&
customUnit === pick.unit;
const label = `${pick.amount}${pick.unit === 1000 ? t('千') : t('万')}`;
return (
<button
key={`${pick.amount}-${pick.unit}`}
type='button'
onClick={() =>
applyCustomQuickPick(pick.amount, pick.unit)
}
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors border ${
active
? 'bg-emerald-500 text-white border-emerald-500 shadow-sm shadow-emerald-500/20'
: 'bg-white dark:bg-neutral-800 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-neutral-700 hover:border-emerald-300 hover:text-emerald-600 dark:hover:border-emerald-700 dark:hover:text-emerald-400'
}`}
>
{label}
</button>
);
})}
</div>
</div>
{/* 实时预览(仅在金额合法时显示) */}
{customEffectiveAmount > 0 && customValid && (
<div className='mx-4 mb-3 rounded-lg p-3 bg-[var(--surface-card)] border border-[var(--border-subtle)]'>
<div className='flex items-center justify-between gap-3 flex-wrap'>
<div className='flex items-center gap-2'>
<div className='w-7 h-7 rounded-lg bg-rose-500/10 text-rose-600 dark:text-rose-400 flex items-center justify-center'>
<Wallet size={14} />
</div>
<div>
<Text
type='tertiary'
size='small'
className='!text-xs block leading-tight'
>
{t('实付金额')}
</Text>
<Text
strong
className='!text-rose-600 dark:!text-rose-400 text-base leading-tight'
>
¥{customEffectiveAmount.toLocaleString()}
</Text>
</div>
</div>
<div className='flex items-center gap-2'>
<div className='w-7 h-7 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400 flex items-center justify-center'>
<Coins size={14} />
</div>
<div className='text-right'>
<Text
type='tertiary'
size='small'
className='!text-xs block leading-tight'
>
{t('获得额度')}
</Text>
<Text
strong
className='!text-amber-600 dark:!text-amber-400 text-base leading-tight'
>
{renderQuota(customPreviewQuota)}
</Text>
</div>
</div>
</div>
</div>
)}
{/* 底部说明(金额不达标时变橙色) */}
<div className='px-4 pb-3'>
<Text
size='small'
className={`!text-xs ${
customEffectiveAmount > 0 && !customValid
? '!text-amber-600 dark:!text-amber-400'
: '!text-gray-400 dark:!text-gray-500'
}`}
>
{customEffectiveAmount > 0 && !customValid
? `${t('当前 ¥')}${customEffectiveAmount.toLocaleString()}${t(',未达到最低 ¥1,000')}`
: t('最少 1000 元,必须为 1000 元的整倍数')}
</Text>
</div>
</div>
{/* 支付方式 */}
<div className='flex items-center gap-2 mb-3'>
<div className='p-1.5 rounded-lg bg-brand/10 text-brand'>
<CreditCard size={14} />
</div>
<Text strong className='text-gray-800 dark:text-gray-200'>
{t('支付方式')}
</Text>
</div>
{hasAnyPayment ? (
<div className='flex flex-wrap gap-3'>
{payMethods.map((method) => {
const isWechat = method.type === 'wxpay';
const isAlipay = method.type === 'alipay';
const isPayPal = method.type === 'paypal';
const disabled =
(isWechat && !enableWechatTopUp) ||
(isAlipay && !enableAlipayTopUp) ||
(isPayPal && !enablePayPalTopUp);
return (
<Button
key={method.type}
theme={payWay === method.type ? 'solid' : 'light'}
type={payWay === method.type ? 'primary' : 'tertiary'}
disabled={disabled}
loading={amountLoading && payWay === method.type}
onClick={() => handlePreTopUp(method.type)}
className={`!rounded-lg !px-5 !py-2.5 !h-auto transition-colors ${
payWay === method.type
? ''
: 'hover:!bg-brand/5 dark:hover:!bg-brand-deep/20 hover:!border-brand-from'
}`}
>
{method.name}
</Button>
);
})}
</div>
) : (
<Text type='tertiary' size='small'>
{t('暂无可用的支付方式,请联系管理员配置')}
</Text>
)}
</>
) : (
<Text type='tertiary'>{t('暂无充值档位,请联系管理员配置')}</Text>
)}
</OrgPanel>
{/* 充值记录 */}
<OrgPanel
icon={History}
title={t('充值记录')}
bodyClassName='overflow-x-auto'
>
<Table
columns={historyColumns}
dataSource={history}
loading={historyLoading}
pagination={{
currentPage: historyPage,
total: historyTotal,
pageSize: 10,
onPageChange: setHistoryPage,
}}
size='small'
empty={<Text type='tertiary'>{t('暂无充值记录')}</Text>}
/>
</OrgPanel>
{/* 支付确认弹窗 */}
<PaymentConfirmModal
t={t}
open={confirmOpen}
onlineTopUp={handleConfirmPay}
handleCancel={() => setConfirmOpen(false)}
confirmLoading={confirmLoading}
topUpCount={effectiveAmountYuan}
renderQuotaWithAmount={() => {
if (payWay === 'paypal' && payPalQuote?.quota) {
return renderQuota(payPalQuote.quota);
}
if (effectiveAmountYuan <= 0) return renderQuota(0);
// 额度 = 原始金额 × QuotaPerUnit + 赠送额度(与后端 CalculateQuota 逻辑一致,折扣只影响实付金额,不影响获得的额度)
const quotaPerUnit = getQuotaPerUnit() || 500000;
const baseQuota = effectiveAmountYuan * quotaPerUnit;
return renderQuota(baseQuota + effectiveBonus);
}}
amountLoading={amountLoading}
renderAmount={renderAmount}
payWay={payWay}
payMethods={payMethods}
amountNumber={
payWay === 'paypal' ? 0 : effectiveAmountYuan * effectiveDiscount
}
discountRate={payWay === 'paypal' ? 1 : effectiveDiscount}
payPalQuote={payPalQuote}
/>
{/* 微信二维码弹窗 */}
<WechatQRModal
visible={wechatQRVisible}
onClose={handleWechatComplete}
orderData={wechatOrderData}
pollFn={async (tradeNo) => {
const res = await API.get(
`/api/org/topup?p=1&page_size=1&keyword=${tradeNo}`,
{ headers: orgHeaders },
);
const items = res.data.data?.items || [];
return items.length > 0 ? items[0] : null;
}}
/>
</div>
);
};
export default OrgRecharge;
+307
View File
@@ -0,0 +1,307 @@
/*
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 {
Table,
Button,
Tag,
Toast,
Input,
Empty,
Popconfirm,
} from '@douyinfe/semi-ui';
import { RefreshCw, Check, X } from 'lucide-react';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import { renderQuota } from '../../helpers/render';
import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel';
import OrgModal from './components/OrgModal';
import { orgStatusColor } from './components/orgStatus';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const isFeatureEnabled = (flags, key) => {
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
// 预算主体(dept/project/org/token 的提额加的是预算 cap,需开启实时拦截才生效);
// member 主体改的是个人 quota_limit,始终生效。
const BUDGET_SUBJECT_TYPES = ['department', 'project', 'org', 'token'];
const statusTag = (t, s) => {
const m = {
pending: { x: t('待审批') },
approved: { x: t('已通过') },
rejected: { x: t('已拒绝') },
canceled: { x: t('已取消') },
expired: { x: t('已过期') },
};
const v = m[s] || { x: s };
return <Tag color={orgStatusColor(s)}>{v.x}</Tag>;
};
const parseDelta = (payload) => {
try {
return JSON.parse(payload || '{}').cycle_quota_delta || 0;
} catch {
return 0;
}
};
// 审批中心:管理员审批提额申请(PR7)。通过即原子提高目标预算 cap。
const OrgRequests = ({ orgId, orgRole, featureFlags }) => {
const { t } = useTranslation();
const isApprover =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const enforcementOff = !isFeatureEnabled(featureFlags, 'budget_enforcement');
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const [statusFilter, setStatusFilter] = useState('pending');
const [rejectFor, setRejectFor] = useState(null);
const [rejectComment, setRejectComment] = useState('');
const listSeqRef = useRef(0);
const fetchList = useCallback(async () => {
if (!orgId) return;
// 翻页把一次加载从 1 个请求放大到最多 20 个,切换筛选的竞态窗口随之变大:
// 旧筛选的翻页循环若在新请求之后才结束,会用旧数据覆盖列表。用 seq 围栏
// 让过期的循环提前停止、且不再 setState。
const seq = ++listSeqRef.current;
setLoading(true);
try {
// 逐页取全:后端把 page_size 静默钳到 100,申请数超过 100 条时
// 原先的单次请求会让较早的申请无声消失在列表外。
const { items, message } = await collectPagedItems(
(page, size) =>
// 页码参数必须是 p —— common.GetPageQuery 只读 p/ps/size,从不读
// page。原先写死 page=1 时这个错误无害(后端拿不到就默认第 1 页),
// 改成翻页后却会让每一页都返回第 1 页,把同样的 100 条累加多次。
API.get(
`/api/org/requests?p=${page}&page_size=${size}${statusFilter ? `&status=${statusFilter}` : ''}`,
{ headers: getOrgHeaders(orgId) },
),
{ shouldAbort: () => seq !== listSeqRef.current },
);
if (seq !== listSeqRef.current) return;
setList(items);
if (message) showError(message);
} catch (err) {
if (seq === listSeqRef.current) showError(err.message);
} finally {
if (seq === listSeqRef.current) setLoading(false);
}
}, [orgId, statusFilter]);
useEffect(() => {
fetchList();
}, [fetchList]);
const decide = async (id, decision, comment) => {
try {
const res = await API.put(
`/api/org/requests/${id}/decision`,
{ decision, comment: comment || '' },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(decision === 'approved' ? t('已通过') : t('已拒绝'));
setRejectFor(null);
setRejectComment('');
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const columns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('类型'),
dataIndex: 'request_type',
width: 90,
render: (v) => (v === 'quota' ? t('提额') : v),
},
{
title: t('对象'),
width: 160,
ellipsis: true,
render: (_, r) => {
const label =
{
project: t('项目'),
department: t('部门'),
member: t('成员'),
token: t('令牌'),
org: t('企业'),
}[r.subject_type] || r.subject_type;
// 后端已富化 subject_name;主体被删除等极端情况回退为 #ID
return r.subject_name
? `${label} · ${r.subject_name}`
: `${label} #${r.subject_id}`;
},
},
{
title: t('提额'),
width: 110,
render: (_, r) =>
r.request_type === 'quota'
? renderQuota(parseDelta(r.payload), 2)
: '-',
},
{ title: t('理由'), dataIndex: 'reason', ellipsis: true },
{
title: t('状态'),
dataIndex: 'status',
width: 90,
render: (v) => statusTag(t, v),
},
{
title: t('操作'),
width: 220,
render: (_, r) =>
isApprover && r.status === 'pending' ? (
<div className='flex items-center gap-2'>
<Popconfirm
title={t('确认通过该提额申请?')}
content={
<div className='max-w-xs'>
<div>
{r.request_type === 'quota'
? `${t('通过后将立即提高目标额度上限')} ${renderQuota(parseDelta(r.payload), 2)}`
: t('通过后将立即生效')}
</div>
{enforcementOff &&
BUDGET_SUBJECT_TYPES.includes(r.subject_type) && (
<div className='mt-1.5 text-xs text-amber-600 dark:text-amber-400'>
{t(
'注意:企业未开启「预算实时拦截」,本次提额不会立即影响实际使用,请先在企业设置开启。',
)}
</div>
)}
</div>
}
okType='warning'
position='topRight'
onConfirm={() => decide(r.id, 'approved')}
>
<Button
size='small'
theme='solid'
type='primary'
icon={<Check size={14} />}
>
{t('通过')}
</Button>
</Popconfirm>
<Button
size='small'
theme='light'
type='danger'
icon={<X size={14} />}
onClick={() => setRejectFor(r.id)}
>
{t('拒绝')}
</Button>
</div>
) : (
<span className='text-xs text-gray-400'>-</span>
),
},
];
const filters = ['pending', 'approved', 'rejected', ''];
return (
<div className='p-4 sm:p-6 lg:p-8'>
<OrgPageHeader
title={isApprover ? t('审批中心') : t('我的申请')}
subtitle={t('提额申请与审批')}
actions={
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={fetchList}
>
{t('刷新')}
</Button>
}
/>
<div className='flex items-center gap-2 mb-3'>
{filters.map((f) => (
<Button
key={f || 'all'}
size='small'
theme={statusFilter === f ? 'solid' : 'light'}
onClick={() => setStatusFilter(f)}
>
{f === 'pending'
? t('待审批')
: f === 'approved'
? t('已通过')
: f === 'rejected'
? t('已拒绝')
: t('全部')}
</Button>
))}
</div>
<OrgPanel padding='p-2'>
{list.length === 0 && !loading ? (
<Empty description={t('暂无申请')} style={{ padding: 40 }} />
) : (
<Table
columns={columns}
dataSource={list}
loading={loading}
pagination={{ pageSize: 15, showSizeChanger: false }}
rowKey='id'
/>
)}
</OrgPanel>
<OrgModal
title={t('拒绝申请')}
visible={!!rejectFor}
onOk={() => decide(rejectFor, 'rejected', rejectComment)}
onCancel={() => {
setRejectFor(null);
setRejectComment('');
}}
okText={t('确认拒绝')}
cancelText={t('取消')}
>
<Input
placeholder={t('拒绝理由(可选)')}
value={rejectComment}
onChange={setRejectComment}
/>
</OrgModal>
</div>
);
};
export default OrgRequests;
File diff suppressed because it is too large Load Diff
+784
View File
@@ -0,0 +1,784 @@
/*
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, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
BarChart2,
Users,
Key,
FileSearch,
Receipt,
Settings,
ChevronDown,
ChevronLeft,
ChevronRight,
Building2,
Search,
X,
CreditCard,
Network,
FolderKanban,
LayoutGrid,
Wallet,
FileClock,
UserRound,
BrainCircuit,
LibraryBig,
Blocks,
ListChecks,
Bot,
ShieldCheck,
Cable,
Gauge,
Sparkles,
Activity,
} from 'lucide-react';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { StatusContext } from '../../context/Status';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
import { canAccessOrgSettings } from './orgFeatureFlags';
import {
CLOUD_BRAIN_UI_ENABLED,
isCloudBrainOrgPath,
} from '../../config/cloudBrainUi';
const pathFeatureRequirements = {
'/org/cloud-brain': 'cloud_brain',
'/org/knowledge': 'knowledge_base',
'/org/skill-center': 'skill_market',
'/org/skill-assignments': 'skill_market',
'/org/experts': 'expert',
'/org/agent-audit': 'cloud_brain',
'/org/connectors': 'connector',
'/org/effectiveness': 'agent_effectiveness',
'/org/quality': 'quality_monitor',
'/org/departments': 'dept',
'/org/projects': 'project',
'/org/budgets': 'budget',
'/org/requests': 'approval',
'/org/project-manage': 'project',
};
const isFeatureEnabled = (flags, key) => {
if (!key) return true;
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
const OrgSidebar = ({
orgName,
orgRole,
featureFlags,
isDeptManager = false,
isProjectManager = false,
canManageKnowledge = false,
canManageSkills = false,
canAssignSkills = false,
canManageExperts = false,
canManageConnectors = false,
canAuditAgentMetadata = false,
canViewAgentEffect = false,
canViewQuality = false,
isMemberActor = true,
onNavigate,
mobile = false,
}) => {
const { t } = useTranslation();
const location = useLocation();
const [collapsedState, toggleCollapsed] = useSidebarCollapsed();
// 移动端抽屉里始终展开,不允许折叠
const collapsed = mobile ? false : collapsedState;
const [statusState] = useContext(StatusContext);
const orgConfig = useMemo(
() =>
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin)
.orgCenter,
[statusState?.status?.SidebarModulesAdmin],
);
const isAdmin =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
// owner/超管可管理完整设置;普通管理员仅在平台授权数据安全自助配置时进入该页。
const canManageSettings = canAccessOrgSettings(orgRole, featureFlags);
const roleLabel = useMemo(() => {
if (orgRole === 'super_admin') return t('超级管理员');
if (orgRole === 'owner') return t('所有者');
if (orgRole === 'admin') return t('企业管理员');
if (orgRole === 'dept_admin' && isProjectManager)
return t('部门/项目管理员');
if (orgRole === 'dept_admin' || isDeptManager) return t('部门管理员');
if (isProjectManager) return t('项目管理员');
return t('成员');
}, [t, orgRole, isDeptManager, isProjectManager]);
// 菜单分组(云平台风格的分组导航,给扁平的十几个入口建立层次)
const groups = useMemo(
() => [
{ key: 'overview', label: t('概览') },
{ key: 'ai', label: t('AI 能力管理') },
{ key: 'org', label: t('组织管理') },
{ key: 'governance', label: t('额度与治理') },
{ key: 'records', label: t('财务与日志') },
{ key: 'settings', label: t('系统设置') },
],
[t],
);
// 统一单一品牌色高亮(云平台风格),不再每项一种颜色
const items = useMemo(() => {
if (orgConfig?.enabled === false) {
return [];
}
// adminOnly 仅 owner/admin/super_admin 可见;其余所有成员可见
const all = [
{
itemKey: '/org/workbench',
text: t('工作台'),
icon: LayoutGrid,
group: 'overview',
},
{
itemKey: '/org/cloud-brain',
text: t('云端大脑'),
icon: BrainCircuit,
group: 'overview',
beta: true,
},
{
itemKey: '/org/knowledge',
text: t('企业知识'),
icon: LibraryBig,
group: 'overview',
adminOnly: true,
knowledgePermission: true,
beta: true,
},
{
// 我的技能 + 业务系统授权合并页:成员自助视图,归入概览组,
// 让「AI 能力管理」成为纯管理员分组。
itemKey: '/org/my-capabilities',
text: t('我的 AI 能力'),
icon: Sparkles,
group: 'overview',
},
{
// 企业技能库 + 企业自研 Skill 合并页;平台技能的启用在技能超市完成
itemKey: '/org/skill-center',
text: t('技能中心'),
icon: Blocks,
group: 'ai',
adminOnly: true,
skillManage: true,
},
{
itemKey: '/org/skill-assignments',
text: t('分发与锁定'),
icon: ListChecks,
group: 'ai',
assignmentPermission: true,
},
{
itemKey: '/org/experts',
text: t('企业专家工坊'),
icon: Bot,
group: 'ai',
adminOnly: true,
expertManage: true,
},
{
itemKey: '/org/connectors',
text: t('Connector 管理'),
icon: Cable,
group: 'ai',
adminOnly: true,
connectorManage: true,
},
{
itemKey: '/org/effectiveness',
text: t('效能分析'),
icon: Gauge,
group: 'overview',
adminOnly: true,
effectView: true,
},
{
itemKey: '/org/quality',
text: t('调用质量'),
icon: Activity,
group: 'overview',
adminOnly: true,
qualityView: true,
},
{
itemKey: '/org/agent-audit',
text: t('Agent 任务审计'),
icon: ShieldCheck,
group: 'records',
agentAudit: true,
},
{
itemKey: '/org/dashboard',
text: t('数据看板'),
icon: BarChart2,
group: 'overview',
adminOnly: true,
},
{
itemKey: '/org/members',
text: t('员工管理'),
icon: Users,
group: 'org',
adminOnly: true,
},
{
itemKey: '/org/dept-manage',
text: t('部门管理'),
icon: Network,
group: 'org',
deptScope: true,
},
{
itemKey: '/org/project-manage',
text: t('我的项目'),
icon: FolderKanban,
group: 'org',
projectScope: true,
},
{
itemKey: '/org/departments',
text: t('部门管理'),
icon: Network,
group: 'org',
adminOnly: true,
},
{
itemKey: '/org/projects',
text: t('项目管理'),
icon: FolderKanban,
group: 'org',
adminOnly: true,
},
{
itemKey: '/org/budgets',
text: t('预算中心'),
icon: Wallet,
group: 'governance',
adminOnly: true,
},
{
itemKey: '/org/requests',
text: isAdmin ? t('审批中心') : t('我的申请'),
icon: FileClock,
group: 'governance',
},
{
itemKey: '/org/tokens',
text: t('令牌管理'),
icon: Key,
group: 'governance',
},
{
itemKey: '/org/recharge',
text: t('企业充值'),
icon: CreditCard,
group: 'records',
adminOnly: true,
},
{
itemKey: '/org/logs',
text: isAdmin || isDeptManager ? t('消耗明细') : t('我的消耗明细'),
icon: Receipt,
group: 'records',
},
{
itemKey: '/org/audit',
text: t('审计日志'),
icon: FileSearch,
group: 'records',
adminOnly: true,
},
{
itemKey: '/org/personal-settings',
text: t('个人设置'),
icon: UserRound,
group: 'settings',
},
{
itemKey: '/org/settings',
text: t('企业设置'),
icon: Settings,
group: 'settings',
ownerOnly: true,
},
];
const visibilityByPath = {
'/org/workbench': 'workbench',
'/org/cloud-brain': 'cloudBrain',
'/org/knowledge': 'knowledge',
'/org/skill-assignments': 'skillAssignments',
'/org/experts': 'experts',
'/org/agent-audit': 'agentAudit',
'/org/connectors': 'connectors',
'/org/effectiveness': 'effectiveness',
'/org/quality': 'quality',
'/org/dashboard': 'dashboard',
'/org/members': 'members',
'/org/departments': 'departments',
'/org/projects': 'projects',
'/org/dept-manage': 'deptManage',
'/org/project-manage': 'projectManage',
'/org/budgets': 'budgets',
'/org/requests': 'requests',
'/org/tokens': 'tokens',
'/org/logs': 'logs',
'/org/audit': 'audit',
'/org/recharge': 'recharge',
'/org/settings': 'settings',
};
return all.filter((item) => {
if (!CLOUD_BRAIN_UI_ENABLED && isCloudBrainOrgPath(item.itemKey)) {
return false;
}
if (item.adminOnly && !isAdmin) return false;
// 平台超管(无成员身份)访问成员型入口必被 member_actor_required 拒绝。
if (!isMemberActor && item.itemKey === '/org/my-capabilities')
return false;
if (item.knowledgePermission && !canManageKnowledge) return false;
if (item.skillManage && !canManageSkills) return false;
// 与路由守卫一致:分发页要求 (isAdmin || isDeptManager) && canAssignSkills,
// 只查权限位会给无管辖部门的 dept_admin 一个点击即被重定向的死入口。
if (
item.assignmentPermission &&
!(canAssignSkills && (isAdmin || isDeptManager))
)
return false;
if (item.expertManage && !canManageExperts) return false;
// 不变量:除 can_assign_skills 外,全部 can_* 都由
// MemberHasAdminPermission 计算,对非 owner/admin 恒 false——即权限位
// 本身已蕴含 isAdmin,菜单无需重复判角色。路由守卫(Organization/index.jsx)
// 写成 isAdmin && can_xxx 是防御性冗余,两者当前等价。
// ⚠️ 若将来把某个权限下放给 dept_admin(做法参照 can_assign_skills 的
// `Role == DeptAdmin || MemberHasAdminPermission(...)`),该不变量即被打破,
// 必须同步在这里补角色条件,否则会变成"菜单可见但路由守卫拒绝"的死入口。
if (item.agentAudit && !canAuditAgentMetadata) return false;
if (item.effectView && !canViewAgentEffect) return false;
if (item.qualityView && !canViewQuality) return false;
if (item.connectorManage && !canManageConnectors) return false;
// 与路由守卫一致:管理员只有 data_security 授权后才显示设置入口。
if (item.ownerOnly && !canManageSettings) return false;
// 部门管理:仅部门负责人可见(与路由门控一致;纯管理员用员工管理页,避免点了被重定向)
if (item.deptScope && !isDeptManager) return false;
// 我的项目:仅项目经理可见(同上,纯管理员用项目管理页)
if (item.projectScope && !isProjectManager) return false;
const key = visibilityByPath[item.itemKey];
const requiredFeature = pathFeatureRequirements[item.itemKey];
// 合并页跨两个模块开关/功能位,任一页签可见即显示入口(与路由守卫同口径)
if (item.itemKey === '/org/my-capabilities') {
return (
(orgConfig?.mySkills !== false &&
isFeatureEnabled(featureFlags, 'skill_market')) ||
(orgConfig?.myConnectors !== false &&
isFeatureEnabled(featureFlags, 'connector'))
);
}
if (item.itemKey === '/org/skill-center') {
return (
isFeatureEnabled(featureFlags, 'skill_market') &&
(orgConfig?.skillLibrary !== false ||
orgConfig?.privateSkills !== false)
);
}
if (item.itemKey === '/org/members') {
return (
(orgConfig?.members !== false ||
orgConfig?.memberAccounts !== false) &&
isFeatureEnabled(featureFlags, requiredFeature)
);
}
return (
(!key || orgConfig?.[key] !== false) &&
isFeatureEnabled(featureFlags, requiredFeature)
);
});
}, [
t,
isAdmin,
canManageSettings,
isDeptManager,
isProjectManager,
canManageKnowledge,
canManageSkills,
canAssignSkills,
canManageExperts,
canAuditAgentMetadata,
canViewAgentEffect,
canViewQuality,
isMemberActor,
canManageConnectors,
orgConfig,
featureFlags,
]);
// 按分组聚合,保持 groups 顺序,自动跳过空组
const groupedItems = useMemo(
() =>
groups
.map((g) => ({ ...g, items: items.filter((it) => it.group === g.key) }))
.filter((g) => g.items.length > 0),
[groups, items],
);
// 菜单搜索:命中项按分组展示;搜索中忽略折叠状态,保证结果可见
const [searchText, setSearchText] = useState('');
const searchInputRef = useRef(null);
const navRef = useRef(null);
const query = searchText.trim().toLowerCase();
const visibleGroups = useMemo(() => {
if (!query) return groupedItems;
return groupedItems
.map((g) => ({
...g,
items: g.items.filter((it) => it.text.toLowerCase().includes(query)),
}))
.filter((g) => g.items.length > 0);
}, [groupedItems, query]);
// 二级分组折叠:仅记录用户手动收起的组,跨会话记忆
const FOLDED_GROUPS_KEY = 'org_sidebar_folded_groups';
const [foldedGroups, setFoldedGroups] = useState(() => {
try {
const saved = JSON.parse(localStorage.getItem(FOLDED_GROUPS_KEY) || '[]');
return Array.isArray(saved) ? saved : [];
} catch {
return [];
}
});
const toggleGroup = (key) => {
setFoldedGroups((prev) => {
const next = prev.includes(key)
? prev.filter((k) => k !== key)
: [...prev, key];
try {
localStorage.setItem(FOLDED_GROUPS_KEY, JSON.stringify(next));
} catch {
/* 隐私模式等场景下写入失败可忽略,仅丢失记忆 */
}
return next;
});
};
const getSelectedKey = () => {
if (location.pathname === '/org/member-accounts') {
return '/org/members';
}
if (items.some((item) => item.itemKey === location.pathname)) {
return location.pathname;
}
if (location.pathname === '/org' || location.pathname === '/org/') {
return items[0]?.itemKey || '';
}
return '';
};
const selectedKey = getSelectedKey();
// 当前路由所在分组自动展开(仅本次会话,不覆盖用户的持久化选择)
useEffect(() => {
const activeGroup = groupedItems.find((g) =>
g.items.some((it) => it.itemKey === selectedKey),
)?.key;
if (!activeGroup) return;
setFoldedGroups((prev) =>
prev.includes(activeGroup) ? prev.filter((k) => k !== activeGroup) : prev,
);
}, [selectedKey, groupedItems]);
// 选中项滚入可视区(分组较多时避免高亮项被折叠区/滚动区遮住)
useEffect(() => {
const el = navRef.current?.querySelector('[data-active="true"]');
el?.scrollIntoView({ block: 'nearest' });
}, [selectedKey]);
// 搜索命中片段高亮
const renderItemText = (text) => {
if (!query) return text;
const idx = text.toLowerCase().indexOf(query);
if (idx === -1) return text;
return (
<>
{text.slice(0, idx)}
<mark className='rounded-sm bg-brand/20 px-0.5 text-inherit'>
{text.slice(idx, idx + query.length)}
</mark>
{text.slice(idx + query.length)}
</>
);
};
return (
<div
className={`
relative flex flex-col h-full transition-all duration-300 ease-out
bg-[var(--surface-sidebar)]
border-r border-[var(--border-subtle)]
${collapsed ? 'w-[68px]' : 'w-[240px]'}
`}
>
{/* 标题区域 */}
{!collapsed && (
<div className='px-4 pt-5 pb-3'>
<div className='flex items-center gap-2'>
<div className='p-1.5 rounded-lg bg-brand/10 text-brand'>
<Building2 size={16} />
</div>
<div className='min-w-0'>
<span className='font-bold text-gray-900 dark:text-white block truncate text-sm'>
{orgName || t('企业中心')}
</span>
{orgRole && (
<span className='text-[10px] text-gray-500 dark:text-gray-400'>
{roleLabel}
</span>
)}
</div>
</div>
</div>
)}
{/* 菜单搜索(折叠态显示放大镜按钮,点击先展开侧栏再聚焦输入框) */}
{!collapsed ? (
<div className='px-3 pb-1'>
<div className='relative'>
<Search
size={14}
className='pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500'
/>
<input
ref={searchInputRef}
type='text'
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') setSearchText('');
}}
placeholder={t('搜索菜单')}
aria-label={t('搜索菜单')}
className='h-8 w-full rounded-lg border border-transparent bg-[var(--semi-color-fill-0)] pl-8 pr-7 text-sm text-[var(--text-primary)] outline-none transition-colors duration-200 placeholder:text-gray-400 focus:border-brand/40 focus:bg-[var(--surface-card)] dark:placeholder:text-gray-500'
/>
{searchText && (
<button
type='button'
onClick={() => setSearchText('')}
aria-label={t('清空搜索')}
className='absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-gray-400 transition-colors hover:text-gray-700 dark:hover:text-gray-200'
>
<X size={13} />
</button>
)}
</div>
</div>
) : (
<div className='px-3 pb-1 pt-3'>
<button
type='button'
onClick={() => {
toggleCollapsed();
setTimeout(() => searchInputRef.current?.focus(), 350);
}}
aria-label={t('搜索菜单')}
className='flex w-full items-center justify-center rounded-lg p-2 text-gray-500 transition-colors duration-200 hover:bg-brand/10 hover:text-brand-deep dark:text-gray-400 dark:hover:bg-brand/15 dark:hover:text-brand-from'
>
<Search size={16} />
</button>
</div>
)}
{/* 导航区域 */}
<nav
ref={navRef}
className='app-scrollbar relative flex-1 px-3 pt-1 pb-2 overflow-y-auto overflow-x-hidden'
>
{query && visibleGroups.length === 0 && (
<div className='px-2 py-8 text-center text-xs text-gray-400 dark:text-gray-500'>
{t('没有匹配的菜单')}
</div>
)}
{visibleGroups.map((group, gi) => {
// 搜索中强制展开,保证命中项可见;平时遵循用户的折叠选择
const folded = !query && foldedGroups.includes(group.key);
return (
<div key={group.key} className={gi > 0 ? 'mt-3' : ''}>
{/* 分组标题(展开态,可点击折叠)/ 分隔线(折叠态) */}
{!collapsed ? (
<button
type='button'
onClick={() => toggleGroup(group.key)}
aria-expanded={!folded}
className='mb-1 flex w-full select-none items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-gray-400 transition-colors duration-200 hover:bg-[var(--semi-color-fill-0)] hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300'
>
<span className='truncate'>{group.label}</span>
<span className='ml-auto text-[10px] font-normal tabular-nums opacity-70'>
{group.items.length}
</span>
<ChevronDown
size={13}
className={`shrink-0 transition-transform duration-200 ${folded ? '-rotate-90' : ''}`}
/>
</button>
) : (
gi > 0 && (
<div className='mx-2 mb-3 h-px bg-gray-200/50 dark:bg-neutral-700/50' />
)
)}
{/* grid-rows 0fr→1fr 实现平滑的折叠动画 */}
<div
className={`grid transition-[grid-template-rows] duration-200 ease-out ${
folded && !collapsed ? 'grid-rows-[0fr]' : 'grid-rows-[1fr]'
}`}
>
<div className='overflow-hidden'>
<div className='space-y-1.5 pb-0.5'>
{group.items.map((item) => {
const isSelected = selectedKey === item.itemKey;
const IconComponent = item.icon;
return (
<Link
key={item.itemKey}
to={item.itemKey}
onClick={() => onNavigate?.()}
data-active={isSelected || undefined}
className={`
group relative flex items-center gap-3 rounded-lg transition-colors duration-200
${collapsed ? 'justify-center p-3' : 'px-3 py-2'}
${
isSelected
? 'bg-brand/10 dark:bg-brand/15'
: 'hover:bg-brand/5 dark:hover:bg-brand/10'
}
`}
>
{isSelected && (
<div className='absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 rounded-r-full bg-brand transition-all duration-200' />
)}
<div
className={`
relative flex-shrink-0 p-1.5 rounded-lg transition-colors duration-200
${
isSelected
? 'bg-brand text-white'
: 'text-gray-500 dark:text-gray-400 group-hover:text-brand-deep dark:group-hover:text-brand-from'
}
`}
>
<IconComponent size={18} strokeWidth={2} />
</div>
{!collapsed && (
<span className='flex min-w-0 items-center gap-2'>
<span
className={`
text-sm transition-colors truncate
${
isSelected
? 'text-brand-deep dark:text-brand-from font-semibold'
: 'font-medium text-gray-600 dark:text-gray-300 group-hover:text-brand-deep dark:group-hover:text-brand-from'
}
`}
>
{renderItemText(item.text)}
</span>
{item.beta && (
<span className='shrink-0 rounded-full border border-orange-300/70 bg-orange-50 px-1.5 py-0.5 font-mono text-[8px] font-bold tracking-wider text-orange-700 dark:border-orange-700/50 dark:bg-orange-950/40 dark:text-orange-300'>
BETA
</span>
)}
</span>
)}
{collapsed && (
<div
className='
absolute left-full ml-2 px-2.5 py-1.5
bg-gray-900 dark:bg-white text-white dark:text-gray-900
text-xs font-medium rounded-lg shadow-lg
opacity-0 invisible group-hover:opacity-100 group-hover:visible
transition-all duration-200 whitespace-nowrap z-50
'
>
{item.text}
<div
className='absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2
border-4 border-transparent border-r-gray-900 dark:border-r-white'
/>
</div>
)}
</Link>
);
})}
</div>
</div>
</div>
</div>
);
})}
</nav>
{/* 底部分隔线 */}
{!mobile && (
<div className='mx-4 h-px bg-gradient-to-r from-transparent via-gray-200/60 dark:via-neutral-700/60 to-transparent' />
)}
{/* 折叠按钮(移动端抽屉里不显示) */}
{!mobile && (
<div className='relative p-3'>
<button
onClick={toggleCollapsed}
className={`
flex items-center justify-center gap-2 w-full py-2 rounded-lg
text-gray-500 dark:text-gray-400 text-sm font-medium
border border-[var(--border-subtle)]
hover:bg-brand/10 dark:hover:bg-brand/15
hover:text-brand-deep dark:hover:text-brand-from
hover:border-brand/30 transition-colors duration-200
${collapsed ? 'px-2' : 'px-3'}
`}
>
{collapsed ? (
<ChevronRight size={16} strokeWidth={2.5} />
) : (
<>
<ChevronLeft size={16} strokeWidth={2.5} />
<span>{t('收起')}</span>
</>
)}
</button>
</div>
)}
</div>
);
};
export default OrgSidebar;
@@ -0,0 +1,478 @@
/*
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, useState } from 'react';
import {
Button,
InputNumber,
Modal,
Select,
Table,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import {
ActivationModeTag,
AssignmentModeTag,
SkillEmptyGuide,
} from '../../components/skill';
import {
usePageGuide,
PageGuideDrawer,
PageGuidePill,
PageGuideTrigger,
flashGuideTarget,
} from '../../components/common/PageGuide';
import OrgPanel from './components/OrgPanel';
import './org-skills.css';
const { Title, Paragraph, Text } = Typography;
const defaultForm = {
skill_id: 0,
scope_type: 'organization',
scope_id: 0,
scope_value: '',
mode: 'optional',
activation: 'manual',
version_policy: 'follow',
version_id: 0,
effective_from: 0,
effective_to: 0,
};
const OrgSkillAssignments = ({ orgId, orgRole = '' }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
// Department admins are legitimate assignment actors but can only target
// their own subtree; offering organization/project/member scopes would
// produce guaranteed backend rejections.
const isDeptAdmin = orgRole === 'dept_admin';
const deptDefaultForm = useMemo(
() =>
isDeptAdmin ? { ...defaultForm, scope_type: 'department' } : defaultForm,
[isDeptAdmin],
);
const scopeOptions = isDeptAdmin
? ['department', 'department_leader']
: [
'organization',
'department',
'project',
'role',
'department_leader',
'member',
];
const [items, setItems] = useState([]);
const [library, setLibrary] = useState([]);
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
const [loaded, setLoaded] = useState(false);
const [visible, setVisible] = useState(false);
const [previewMember, setPreviewMember] = useState(0);
const [preview, setPreview] = useState([]);
const [form, setForm] = useState(deptDefaultForm);
const load = useCallback(async () => {
// finally 保证请求失败也置 loaded:拦截器已 toast,此处只需不让
// 未捕获 reject 把 loaded 卡在 false。
try {
const [assignments, policies] = await Promise.all([
API.get('/api/org/skills/assignments', { headers }),
// The options endpoint is readable by every assignment actor;
// /library requires skill_manage, which dept_admin does not hold.
API.get('/api/org/skills/assignments/options', { headers }),
]);
if (assignments.data?.success) setItems(assignments.data.data || []);
if (policies.data?.success)
setLibrary((policies.data.data || []).filter((item) => item.enabled));
} finally {
setLoaded(true);
}
}, [headers]);
useEffect(() => {
void load();
}, [load]);
const save = async () => {
try {
const response = await API.post('/api/org/skills/assignments', form, {
headers,
skipErrorHandler: true,
});
if (!response.data?.success) {
Toast.error(response.data?.message || t('保存失败'));
return;
}
(response.data.warnings || []).forEach((warning) =>
Toast.warning(warning),
);
setVisible(false);
setForm(deptDefaultForm);
await load();
} catch (error) {
Toast.error(
error.response?.data?.message || error.message || t('保存失败'),
);
}
};
const remove = async (id) => {
const response = await API.delete(`/api/org/skills/assignments/${id}`, {
headers,
});
if (response.data?.success) await load();
};
// 指引步骤④「用预览验证」的完成态按组织持久化:preview 是会话内状态,
// 不落盘的话每次进页胶囊都会复活(与知识页 verified-key 同语义)。
// setItem 在隐私模式/配额耗尽时会抛异常,必须吞掉。
const previewedKey = `org-skill-assignments-previewed-${orgId}`;
const runPreview = async () => {
const response = await API.get('/api/org/skills/preview', {
headers,
params: { member_id: previewMember },
});
if (!response.data?.success) {
Toast.error(response.data?.message || t('预览失败'));
return;
}
setPreview(response.data.data || []);
try {
window.localStorage.setItem(previewedKey, '1');
} catch {
// 忽略:仅损失跨会话记忆
}
};
const previewVerified = (() => {
try {
return window.localStorage.getItem(previewedKey) === '1';
} catch {
return false;
}
})();
const columns = [
{ title: t('Skill'), dataIndex: 'skill_id' },
{
title: t('范围'),
render: (_, row) =>
`${row.scope_type}:${row.scope_id || row.scope_value || 'all'}`,
},
{
title: t('模式'),
render: (_, row) => <AssignmentModeTag mode={row.mode} />,
},
{
title: t('激活'),
render: (_, row) => <ActivationModeTag mode={row.activation} />,
},
{ title: t('版本策略'), dataIndex: 'version_policy' },
{
title: t('操作'),
render: (_, row) => (
<Button type='danger' theme='borderless' onClick={() => remove(row.id)}>
{t('删除')}
</Button>
),
},
];
const openCreateModal = () => {
setForm(deptDefaultForm);
setVisible(true);
};
// 使用指引:分发策略决定「谁能用哪些技能」,完成态由策略/预览数据驱动。
const guide = usePageGuide({
guideKey: 'org-skill-assignments',
ready: loaded,
title: t('分发与锁定 · 使用指引'),
intro: t('技能启用后,靠分发策略决定对哪些成员生效'),
steps: [
{
title: t('创建分发策略'),
detail: t('选技能、选范围、定模式,一条策略就是一条生效规则'),
done: items.length > 0,
cta: t('去创建策略'),
onAction: openCreateModal,
points: [
t(
'可选范围:全企业 / 部门子树 / 项目 / 角色 / 部门负责人 / 指定成员',
),
isDeptAdmin
? t('部门管理员只能面向本部门子树与部门负责人分发')
: t('技能下拉里只出现已在技能库启用的技能'),
],
},
{
title: t('理解模式与激活'),
detail: t('模式决定成员能否关闭,激活决定何时注入'),
done: items.length > 0,
points: [
t('模式:必需锁定(强制启用不可关)/ 默认开启 / 推荐 / 可选 / 禁止'),
t(
'激活:always 始终注入 / auto 按任务自动匹配 / manual 成员手动开启',
),
t('多条策略叠加时按范围精细度取胜;保存时的黄色提示会指出冲突'),
],
},
{
title: t('版本策略'),
detail: t('决定成员用的是哪个版本'),
done: items.length > 0,
points: [
t('「跟随升级」自动使用企业技能库的当前版本'),
t('「锁定版本」填写版本 ID,把该范围固定在指定版本上'),
],
},
{
title: t('用预览验证'),
detail: t('回答「为什么成员 X 有 / 没有技能 Y」'),
done: preview.length > 0 || previewVerified,
cta: t('去预览'),
onAction: () =>
flashGuideTarget(
'.org-skill-preview',
'.org-skill-preview-controls input',
),
points: [
t('在「成员能力预览」输入成员 ID,查看该成员最终生效的能力集'),
t('每行展示生效来源链,与成员「我的技能」页看到的一致'),
],
},
],
faq: [
{
q: t('创建时弹出黄色警告?'),
a: t('策略已保存,警告提示与既有策略存在覆盖或冲突,按提示核对即可'),
},
{
q: t('下拉里找不到想分发的技能?'),
a: t('先到「技能超市」为企业启用该技能,使其进入企业技能库'),
},
],
});
const closeGuide = guide.close;
// 预览结果与抽屉进度都是组织私有状态:切组织时清空/关闭并复位 loaded,
// 否则旧组织的预览行/策略数据会把新组织的完成态渲染错。
useEffect(() => {
setPreview([]);
setPreviewMember(0);
setLoaded(false);
closeGuide();
}, [orgId, closeGuide]);
return (
<main className='org-skills-page'>
<header className='org-skills-hero'>
<div>
<Title heading={3}>{t('分发与锁定')}</Title>
<Paragraph>
{t(
'按企业、部门子树、项目、角色、负责人或成员分发,并实时预览最终能力集。',
)}
</Paragraph>
</div>
<div className='org-skills-hero-actions'>
<PageGuideTrigger guide={guide} />
<Button theme='solid' type='primary' onClick={openCreateModal}>
{t('创建分发策略')}
</Button>
</div>
</header>
<PageGuidePill guide={guide} />
<PageGuideDrawer guide={guide} />
<OrgPanel title={t('策略列表')}>
{items.length === 0 ? (
<SkillEmptyGuide
title={t('还没有分发策略')}
description={t(
'技能启用后还需要分发策略才会对成员生效,先创建第一条。',
)}
actionLabel={t('创建分发策略')}
onAction={openCreateModal}
/>
) : (
<Table
columns={columns}
dataSource={items}
rowKey='id'
pagination={false}
/>
)}
</OrgPanel>
<OrgPanel title={t('成员能力预览')} className='org-skill-preview'>
<div className='org-skill-preview-controls'>
<InputNumber
min={1}
value={previewMember}
onChange={setPreviewMember}
placeholder={t('成员 ID')}
/>
<Button onClick={runPreview}>{t('预览')}</Button>
</div>
{preview.map((item) => (
<div key={item.skill_id} className='org-skill-preview-row'>
<Text strong>{item.canonical_id}</Text>
<AssignmentModeTag mode={item.mode} />
<Text>{item.enabled ? t('生效') : t('未生效')}</Text>
<Text type='tertiary'>
{(item.sources || [])
.map(
(source) =>
`${source.scope_type}:${source.scope_id || source.scope_value || 'all'}`,
)
.join(' > ')}
</Text>
</div>
))}
</OrgPanel>
<Modal
title={t('创建分发策略')}
visible={visible}
onCancel={() => setVisible(false)}
onOk={save}
>
<div className='org-skill-form'>
<label>
<Text>Skill</Text>
<Select
value={form.skill_id}
onChange={(skill_id) => setForm((old) => ({ ...old, skill_id }))}
>
{library.map((item) => (
<Select.Option key={item.skill_id} value={item.skill_id}>
Skill #{item.skill_id}
</Select.Option>
))}
</Select>
</label>
<label>
<Text>{t('范围')}</Text>
<Select
value={form.scope_type}
onChange={(scope_type) =>
setForm((old) => ({
...old,
scope_type,
scope_id: scope_type === 'organization' ? 0 : old.scope_id,
}))
}
>
{scopeOptions.map((value) => (
<Select.Option key={value} value={value}>
{value}
</Select.Option>
))}
{!isDeptAdmin && (
<Select.Option value='expert'>{t('指定专家')}</Select.Option>
)}
</Select>
</label>
{form.scope_type !== 'organization' && form.scope_type !== 'role' && (
<label>
<Text>Scope ID</Text>
<InputNumber
min={1}
value={form.scope_id}
onChange={(scope_id) =>
setForm((old) => ({ ...old, scope_id }))
}
/>
</label>
)}
{form.scope_type === 'role' && (
<label>
<Text>{t('角色')}</Text>
<Select
value={form.scope_value}
onChange={(scope_value) =>
setForm((old) => ({ ...old, scope_value }))
}
>
{['owner', 'admin', 'dept_admin', 'member'].map((value) => (
<Select.Option key={value} value={value}>
{value}
</Select.Option>
))}
</Select>
</label>
)}
<label>
<Text>{t('模式')}</Text>
<Select
value={form.mode}
onChange={(mode) => setForm((old) => ({ ...old, mode }))}
>
{[
'required_locked',
'default_on',
'recommended',
'optional',
'forbidden',
].map((value) => (
<Select.Option key={value} value={value}>
{value}
</Select.Option>
))}
</Select>
</label>
<label>
<Text>{t('激活')}</Text>
<Select
value={form.activation}
onChange={(activation) =>
setForm((old) => ({ ...old, activation }))
}
>
{['always', 'auto', 'manual'].map((value) => (
<Select.Option key={value} value={value}>
{value}
</Select.Option>
))}
<Select.Option value='workflow_step' disabled>
{t('工作流步骤(ADR 批准并独立立项后开放)')}
</Select.Option>
</Select>
</label>
<label>
<Text>{t('版本策略')}</Text>
<Select
value={form.version_policy}
onChange={(version_policy) =>
setForm((old) => ({ ...old, version_policy }))
}
>
<Select.Option value='follow'>{t('跟随升级')}</Select.Option>
<Select.Option value='locked'>{t('锁定版本')}</Select.Option>
</Select>
</label>
{form.version_policy === 'locked' && (
<label>
<Text>Version ID</Text>
<InputNumber
min={1}
value={form.version_id}
onChange={(version_id) =>
setForm((old) => ({ ...old, version_id }))
}
/>
</label>
)}
</div>
</Modal>
</main>
);
};
export default OrgSkillAssignments;
+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
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import OrgSubpageTabs from './components/OrgSubpageTabs';
import OrgSkillLibrary from './OrgSkillLibrary';
import OrgPrivateSkills from './OrgPrivateSkills';
/**
* 技能中心:企业技能库 + 企业自研 Skill 的合并入口。
*
* 两个页签共用同一权限口径(isAdmin && canManageSkills),差异只在站点级
* 模块开关,由 showLibrary / showPrivate 控制。
*
* 平台技能的"引入企业"有两条路径:企业管理员可在平台技能超市
* (/skill-market,原独立的企业技能市场页已并入其中,旧路由重定向过去)
* 就地启用;企业技能库页内的「引入技能」抽屉则是平台超管与被顶栏配置挡在
* 超市之外的 org_only 管理员的入口。两条路径写同一端点、同一审计。
*/
const OrgSkillCenter = ({
orgId,
orgRole,
canAssignSkills = false,
showLibrary = true,
showPrivate = true,
}) => {
const { t } = useTranslation();
return (
<OrgSubpageTabs
tabs={[
showLibrary && {
key: 'library',
label: t('企业技能库'),
// orgRole 用于识别平台超管(超市页解析不出其企业上下文,页内引入
// 抽屉是其唯一的"代客开通"入口);canAssignSkills 决定引入成功后的
// 指引指向哪里——超管的该权限位后端恒 false,不能让文案把人指向
// 一个结构上进不去的页面。两者都复用父层已取的 /api/org/info。
node: (
<OrgSkillLibrary
orgId={orgId}
orgRole={orgRole}
canAssignSkills={canAssignSkills}
/>
),
},
showPrivate && {
key: 'private',
label: t('企业自研 Skill'),
node: <OrgPrivateSkills orgId={orgId} />,
},
]}
/>
);
};
export default OrgSkillCenter;
+839
View File
@@ -0,0 +1,839 @@
/*
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,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import {
Button,
Empty,
Input,
InputNumber,
Modal,
Select,
SideSheet,
Switch,
Tag,
TextArea,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { Search } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { API } from '../../helpers';
import {
LicenseBadge,
RiskBadge,
SkillEmptyGuide,
SkillStatusTag,
} from '../../components/skill';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import OrgPanel from './components/OrgPanel';
import { StatusContext } from '../../context/Status';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
import './org-skills.css';
const { Title, Text, Paragraph } = Typography;
const jsonList = (value) => {
try {
const parsed = JSON.parse(value || '[]');
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
};
const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [statusState] = useContext(StatusContext);
// 平台超管(查看企业时 org_role=super_admin、无成员身份)拿不到 /api/org/list
// 里的这个企业,所以在平台超市页 activeOrg 解析不出来、没有启用面。他们的
// 企业上下文只有在 /org 内才明确(current_org_id),因此页内引入抽屉是超管
// 唯一可用的"代客开通"入口。
const isPlatformSuperAdmin = orgRole === 'super_admin';
// 与技能超市页同一开关:站点关闭「技能超市 · 为企业启用」后,超市页不再有
// 启用按钮,跳过去的入口必须同步收起,否则就是一条通向空手而归的路。
// 超管不受此开关约束——该开关的语义正是"仅平台可代为启用"。
const selfEnableAllowed = useMemo(() => {
const orgCenter = normalizeSidebarModulesAdmin(
statusState?.status?.SidebarModulesAdmin,
).orgCenter;
return orgCenter?.enabled !== false && orgCenter?.skillMarket !== false;
}, [statusState?.status?.SidebarModulesAdmin]);
const canImport = selfEnableAllowed || isPlatformSuperAdmin;
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [items, setItems] = useState([]);
const [catalog, setCatalog] = useState(new Map());
const [selected, setSelected] = useState(null);
const [derivePolicy, setDerivePolicy] = useState(null);
const [derivedVersions, setDerivedVersions] = useState([]);
const [evidenceVersion, setEvidenceVersion] = useState(null);
const [evidence, setEvidence] = useState({
model: '',
input: '',
});
// 页内引入:直接复用 load() 已经取回的 catalog(/api/org/skills/market),
// 不额外发请求。主要服务平台超管——超市页对其解析不出企业上下文;对普通
// 管理员它是"就地快速添加",与超市页的分页/分类/需求热度视图互补。
const [importOpen, setImportOpen] = useState(false);
const [importKeyword, setImportKeyword] = useState('');
const [importingId, setImportingId] = useState(0);
// 三态分离:首次加载完成前不渲染空态(否则闪一下"技能库为空"),
// 加载失败要说人话且与"确实为空"区分开。
const [loaded, setLoaded] = useState(false);
const [loadError, setLoadError] = useState({ library: '', catalog: '' });
const [form, setForm] = useState({
display_name: '',
description_zh: '',
applicable_roles: '[]',
usage_boundary: '',
default_activation: 'manual',
derived_version_id: 0,
});
const load = useCallback(async () => {
// allSettled 而非 all:任一端点失败都会让两个 setState 都不执行,于是主
// 列表显示"企业技能库为空"、抽屉显示"平台目录暂无可用技能"——把硬故障
// 说成"平台还没上架技能",安抚性文案盖住真实错误。分别降级并记录错误态。
const [libraryOutcome, marketOutcome] = await Promise.allSettled([
API.get('/api/org/skills/library', { headers, skipErrorHandler: true }),
API.get('/api/org/skills/market', { headers, skipErrorHandler: true }),
]);
const pick = (outcome) =>
outcome.status === 'fulfilled' ? outcome.value : null;
const libraryRes = pick(libraryOutcome);
const marketRes = pick(marketOutcome);
const readError = (outcome, res) =>
outcome.status === 'rejected'
? outcome.reason?.response?.data?.message ||
outcome.reason?.message ||
t('加载失败')
: res?.data?.success
? ''
: res?.data?.message || t('加载失败');
if (libraryRes?.data?.success) setItems(libraryRes.data.data || []);
if (marketRes?.data?.success)
setCatalog(
new Map(
(marketRes.data.data || []).map((item) => [item.definition.id, item]),
),
);
setLoadError({
library: readError(libraryOutcome, libraryRes),
catalog: readError(marketOutcome, marketRes),
});
setLoaded(true);
}, [headers, t]);
useEffect(() => {
void load();
}, [load]);
// 库里已有的技能(无论启停)不重复出现在引入列表里——它们的启停归本页主列表管。
const libraryIds = useMemo(
() => new Set(items.map((policy) => policy.skill_id)),
[items],
);
const catalogName = useCallback(
(item) =>
item?.locales?.find((locale) => locale.locale === 'zh')?.name ||
item?.locales?.[0]?.name ||
item?.definition?.canonical_id ||
`Skill #${item?.definition?.id}`,
[],
);
const importCandidates = useMemo(() => {
const keyword = importKeyword.trim().toLowerCase();
return [...catalog.values()]
.filter((item) => !libraryIds.has(item.definition.id))
.filter((item) => {
if (!keyword) return true;
return (
catalogName(item).toLowerCase().includes(keyword) ||
String(item.definition?.canonical_id || '')
.toLowerCase()
.includes(keyword)
);
});
}, [catalog, libraryIds, importKeyword, catalogName]);
const importSkill = async (skillId) => {
// 有请求在飞时不接受新点击:单值 importingId 无法表达多个并发,
// 先完成的那个会把 loading 清掉,让仍在飞行的按钮看起来可再点。
if (importingId) return;
setImportingId(skillId);
let enabled = false;
try {
// 与技能超市页同一端点。失败分两路:controller 的 brainError 走 400/422
// (axios reject,故需 skipErrorHandler 避免双 Toast),中间件 abortOrg
// 走 200+success:false(axios 不 reject,只有 !success 分支能兜住)。
const response = await API.put(
`/api/org/skills/library/${skillId}/enabled`,
{ enabled: true },
{ headers, skipErrorHandler: true },
);
if (!response.data?.success) {
throw new Error(response.data?.message || t('操作失败'));
}
enabled = true;
// 平台超管的 can_assign_skills 后端恒 false(无成员身份,分发路由的
// RequireOrgMemberActor 必拒),菜单里也没有该入口。把他们指向"分发与
// 锁定"等于指向一个进不去的页面——代客开通的收尾必须由企业管理员完成。
Toast.success({
content: canAssignSkills
? t('已加入企业技能库;还需在「分发与锁定」建策略,成员才可用')
: t(
'已加入企业技能库;还需由企业管理员在「分发与锁定」建策略,成员才可用',
),
duration: 6,
});
} catch (error) {
Toast.error(
error?.response?.data?.message || error?.message || t('操作失败'),
);
} finally {
setImportingId(0);
}
if (!enabled) return;
// 启用即视为采纳该技能下的员工诉求(与技能超市页同口径);处置失败静默,
// 下次进页面还会看到该诉求。不做的话超市页的「N 人想要」永不消失。
try {
await API.put(
`/api/org/skills/demand/${skillId}`,
{ status: 'accepted' },
{ headers, skipErrorHandler: true },
);
} catch (_error) {
/* 见上:静默 */
}
// 刷新放在 try 之外:load() 内部的 GET 未跳过全局拦截器,放在同一个 try 里
// 会在刷新失败时叠加一条"失败"Toast(且是 axios 英文原文),而启用其实已
// 经成功。失败时保持旧列表即可,用户再操作一次会自然重拉。
await load().catch(() => {});
};
const openCustomization = (policy, derivedVersionId) => {
const customization = policy.customization || {};
setForm({
display_name: customization.display_name || '',
description_zh: customization.description_zh || '',
applicable_roles: customization.applicable_roles || '[]',
usage_boundary: customization.usage_boundary || '',
default_activation: customization.default_activation || 'manual',
derived_version_id:
derivedVersionId ?? customization.derived_version_id ?? 0,
});
setSelected(policy);
};
const configure = async (policy, patch) => {
const payload = {
enabled: policy.enabled,
emergency_stopped: policy.emergency_stopped,
version_policy: policy.version_policy || 'follow',
locked_version_id: policy.locked_version_id || 0,
...patch,
};
const response = await API.put(
`/api/org/skills/library/${policy.skill_id}/policy`,
payload,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
await load();
};
const saveCustomization = async () => {
const payload = {
...form,
applicable_roles_json: form.applicable_roles || '[]',
};
const response = await API.put(
`/api/org/skills/library/${selected.skill_id}/customization`,
payload,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
Toast.success(t('企业定制已保存'));
setSelected(null);
await load();
};
const [deriveForm, setDeriveForm] = useState({
body: '',
name_zh: '',
name_en: '',
description_zh: '',
description_en: '',
triggers_zh: '',
triggers_en: '',
scenarios_zh: '',
scenarios_en: '',
compact_constraint_zh: '',
compact_constraint_en: '',
change_statement: '',
default_output_language: 'auto',
capabilities: ['prompt_only'],
tags: [],
});
const saveDerived = async () => {
const list = (value) =>
String(value || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean);
const parentVersion = catalog.get(derivePolicy.skill_id)?.version;
if (!parentVersion) {
Toast.error(t('平台当前版本不可用,无法创建派生版本'));
return;
}
if (!String(deriveForm.body || '').trim()) {
Toast.warning(t('请先填写派生版本正文(body)'));
return;
}
const response = await API.post(
`/api/org/skills/versions/${parentVersion.id}/derive`,
{
...deriveForm,
triggers_zh: list(deriveForm.triggers_zh),
triggers_en: list(deriveForm.triggers_en),
scenarios_zh: list(deriveForm.scenarios_zh),
scenarios_en: list(deriveForm.scenarios_en),
},
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
Toast.success(t('企业派生版本已创建,请完成模型实测和审核后再激活'));
await loadDerivedVersions(derivePolicy.skill_id);
await load();
};
const loadDerivedVersions = async (skillId) => {
const response = await API.get(
`/api/org/skills/library/${skillId}/derived-versions`,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('派生版本加载失败'));
return;
}
setDerivedVersions(response.data.data || []);
};
const openDerived = async (policy) => {
const catalogItem = catalog.get(policy.skill_id);
const version = catalogItem?.version;
const zh = catalogItem?.locales?.find((item) => item.locale === 'zh') || {};
const en = catalogItem?.locales?.find((item) => item.locale === 'en') || {};
setDeriveForm({
// The platform never serializes version bodies to organizations, so a
// derived version's full body must be authored here from scratch.
body: '',
name_zh: zh.name || '',
name_en: en.name || '',
description_zh: zh.description || '',
description_en: en.description || '',
triggers_zh: jsonList(zh.triggers).join(', '),
triggers_en: jsonList(en.triggers).join(', '),
scenarios_zh: jsonList(zh.scenarios).join(', '),
scenarios_en: jsonList(en.scenarios).join(', '),
compact_constraint_zh: zh.compact_constraint || '',
compact_constraint_en: en.compact_constraint || '',
change_statement: '',
default_output_language: version?.default_output_language || 'auto',
capabilities: jsonList(version?.capabilities),
tags: jsonList(version?.tags),
});
setDerivePolicy(policy);
setDerivedVersions([]);
await loadDerivedVersions(policy.skill_id);
};
const derivedAction = async (versionId, suffix, body = {}) => {
const response = await API.post(
`/api/org/skills/versions/${versionId}/${suffix}`,
body,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return false;
}
await loadDerivedVersions(derivePolicy.skill_id);
return true;
};
const recordDerivedEvidence = async () => {
if (!evidence.model.trim() || !evidence.input.trim()) {
Toast.error(t('模型名称与测试输入不能为空'));
return;
}
if (
await derivedAction(evidenceVersion, 'test', {
model: evidence.model,
input: evidence.input,
})
) {
Toast.success(t('模型实测完成,证据已落库'));
setEvidenceVersion(null);
}
};
// 使用指引:技能库四项治理动作的阅读式说明(无上手流程,不出进度胶囊)。
const guide = usePageGuide({
guideKey: 'org-skill-library',
title: t('企业技能库 · 使用指引'),
intro: t('已启用技能的治理中心:启停、版本、止血与企业化定制'),
steps: [
{
title: t('启用状态与版本策略'),
detail: t('每行开关控制启用;版本策略决定是否跟随平台升级'),
points: [
t('「跟随平台升级」自动使用平台最新审核版本'),
t('「锁定版本」把当前版本固定下来,平台升级不影响企业在用版本'),
],
},
{
title: t('紧急停用'),
detail: t('发现质量或安全问题时的止血开关'),
points: [t('点「紧急停用」该技能立即对全企业失效,点「恢复」重新生效')],
},
{
title: t('企业展示定制'),
detail: t('把平台技能翻译成员工看得懂的说法'),
points: [
t('可设置企业内展示名称、中文说明与使用边界'),
t('成员在「我的技能」里看到的就是这里配置的内容'),
],
},
{
title: t('内容派生'),
detail: t('基于平台版本创建带企业知识的派生版本'),
points: [
t('派生版本的正文需要自行撰写——平台不会下发原始正文'),
t(
'流程:创建派生 → 执行模型实测 → 领取审核 → 审核通过 → 设为企业版本',
),
t('模型实测会真实调用所选模型,响应自动留档为审核证据'),
],
},
],
faq: [
{
q: t('技能库为空?'),
a: t('点页面右上角「引入技能」,从平台目录中为企业启用'),
},
{
q: t('已启用但成员看不到?'),
a: t('还需要在「分发与锁定」创建分发策略覆盖到目标成员'),
},
],
});
return (
<main className='org-skills-page'>
<header className='org-skills-hero'>
<div>
<Title heading={3}>{t('企业技能库')}</Title>
<Paragraph>
{t('控制启用状态、版本锁定、紧急停用和企业展示定制。')}
</Paragraph>
</div>
<div className='org-skills-hero-actions'>
{/* 页内引入:对平台超管这是唯一可用入口(超市页解析不出其企业上下文);
对普通管理员是就地快速添加。数据复用已加载的 catalog,不额外发请求。 */}
{canImport ? (
<Button theme='solid' onClick={() => setImportOpen(true)}>
{t('引入技能')}
</Button>
) : null}
{/* 浏览完整平台目录(分页/搜索/分类)仍去超市页;超管在那里没有企业
上下文,故不对其展示,避免点过去发现无法启用。 */}
{selfEnableAllowed && !isPlatformSuperAdmin ? (
<Button
theme='borderless'
onClick={() => navigate('/skill-market')}
>
{t('浏览技能超市')}
</Button>
) : null}
<PageGuideTrigger guide={guide} />
</div>
</header>
<PageGuideDrawer guide={guide} />
{!loaded ? (
<SkillEmptyGuide title={t('正在加载企业技能库')} />
) : loadError.library ? (
// 错误态必须与"确实为空"分开:否则接口 5xx 会被渲染成
// "企业技能库为空 / 点引入技能",把硬故障说成正常状态。
<SkillEmptyGuide
title={t('企业技能库加载失败')}
description={loadError.library}
actionLabel={t('重试')}
onAction={() => void load()}
/>
) : items.length === 0 ? (
<SkillEmptyGuide
title={t('企业技能库为空')}
description={
canImport
? t('点「引入技能」从平台目录中为企业启用 Skill。')
: t('平台已关闭自助启用,请联系平台管理员为企业启用 Skill。')
}
actionLabel={canImport ? t('引入技能') : undefined}
onAction={canImport ? () => setImportOpen(true) : undefined}
/>
) : (
<section className='org-skill-library-list'>
{items.map((policy) => (
<OrgPanel
key={policy.id}
title={
catalog
.get(policy.skill_id)
?.locales?.find((item) => item.locale === 'zh')?.name ||
`Skill #${policy.skill_id}`
}
actions={
<SkillStatusTag
status={
policy.emergency_stopped
? 'quarantined'
: policy.enabled
? 'published'
: 'withdrawn'
}
/>
}
>
<div className='org-skill-policy-row'>
<label>
<Text>{t('启用')}</Text>
<Switch
checked={policy.enabled}
onChange={(enabled) => configure(policy, { enabled })}
/>
</label>
<label>
<Text>{t('版本策略')}</Text>
<Select
value={policy.version_policy || 'follow'}
onChange={(version_policy) =>
configure(policy, {
version_policy,
locked_version_id:
version_policy === 'locked'
? catalog.get(policy.skill_id)?.version?.id || 0
: 0,
})
}
>
<Select.Option value='follow'>
{t('跟随平台升级')}
</Select.Option>
<Select.Option value='locked'>
{t('锁定版本')}
</Select.Option>
</Select>
</label>
<Button
type='danger'
onClick={() =>
configure(policy, {
emergency_stopped: !policy.emergency_stopped,
})
}
>
{policy.emergency_stopped ? t('恢复') : t('紧急停用')}
</Button>
<Button onClick={() => openCustomization(policy)}>
{t('企业定制')}
</Button>
<Button onClick={() => void openDerived(policy)}>
{t('内容派生')}
</Button>
</div>
</OrgPanel>
))}
</section>
)}
<Modal
title={t('企业展示定制')}
visible={!!selected}
onCancel={() => setSelected(null)}
onOk={saveCustomization}
>
<div className='org-skill-form'>
<label>
<Text>{t('展示名称')}</Text>
<TextArea
value={form.display_name}
onChange={(value) =>
setForm((old) => ({ ...old, display_name: value }))
}
autosize
/>
</label>
<label>
<Text>{t('中文说明')}</Text>
<TextArea
value={form.description_zh}
onChange={(value) =>
setForm((old) => ({ ...old, description_zh: value }))
}
autosize
/>
</label>
<label>
<Text>{t('使用边界')}</Text>
<TextArea
value={form.usage_boundary}
onChange={(value) =>
setForm((old) => ({ ...old, usage_boundary: value }))
}
autosize
/>
</label>
<label>
<Text>{t('已审核派生版本 ID')}</Text>
<InputNumber
min={0}
value={form.derived_version_id}
onChange={(derived_version_id) =>
setForm((old) => ({ ...old, derived_version_id }))
}
/>
</label>
</div>
</Modal>
<Modal
title={t('创建企业派生版本')}
visible={!!derivePolicy}
onCancel={() => setDerivePolicy(null)}
onOk={saveDerived}
width={760}
>
<div className='org-skill-form'>
{derivedVersions.map((item) => (
<div key={item.version.id} className='org-skill-policy-row'>
<Text>v{item.version.version_no}</Text>
<Tag>{item.runtime?.conclusion || 'scan_pending'}</Tag>
<Tag>{item.review?.status || 'pending'}</Tag>
<Button
size='small'
onClick={() => {
// Reset the captured inputs on every open: the Form fields
// remount empty, so stale state from a previous version's
// test must never be silently submitted for this one.
setEvidence({ model: '', input: '' });
setEvidenceVersion(item.version.id);
}}
>
{t('执行模型实测')}
</Button>
<Button
size='small'
disabled={item.review?.status !== 'pending'}
onClick={() =>
void derivedAction(item.version.id, 'review/start')
}
>
{t('领取审核')}
</Button>
<Button
size='small'
disabled={item.review?.status !== 'reviewing'}
onClick={() =>
void derivedAction(item.version.id, 'review/decision', {
approved: true,
conclusion: { decision: 'approved' },
})
}
>
{t('审核通过')}
</Button>
<Button
size='small'
disabled={item.review?.status !== 'approved'}
onClick={() => {
openCustomization(derivePolicy, item.version.id);
setDerivePolicy(null);
}}
>
{t('设为企业版本')}
</Button>
</div>
))}
{[
'name_zh',
'name_en',
'description_zh',
'description_en',
'triggers_zh',
'triggers_en',
'scenarios_zh',
'scenarios_en',
'compact_constraint_zh',
'compact_constraint_en',
'change_statement',
].map((field) => (
<label key={field}>
<Text>{field}</Text>
<TextArea
value={deriveForm[field]}
onChange={(value) =>
setDeriveForm((old) => ({ ...old, [field]: value }))
}
autosize
/>
</label>
))}
<label>
<Text>body</Text>
<TextArea
value={deriveForm.body}
onChange={(value) =>
setDeriveForm((old) => ({ ...old, body: value }))
}
placeholder={t(
'平台正文不会同步到企业侧,请在此完整撰写派生版本的正文内容',
)}
autosize={{ minRows: 10 }}
/>
</label>
</div>
</Modal>
<Modal
title={t('执行真实模型测试')}
visible={!!evidenceVersion}
onCancel={() => setEvidenceVersion(null)}
onOk={recordDerivedEvidence}
>
{/* Plain controlled inputs: Semi Form fields keep their own state and
ignore the value prop, which previously let stale state diverge
from what the user saw on screen. */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Input
placeholder={t('模型')}
value={evidence.model}
onChange={(model) => setEvidence((old) => ({ ...old, model }))}
/>
<TextArea
placeholder={t('测试输入')}
value={evidence.input}
onChange={(input) => setEvidence((old) => ({ ...old, input }))}
/>
<Paragraph type='tertiary'>
{t(
'提交后将实际调用所选模型执行该版本正文,真实响应自动落库为审核证据。',
)}
</Paragraph>
</div>
</Modal>
<SideSheet
title={t('引入技能')}
visible={importOpen}
onCancel={() => {
setImportOpen(false);
setImportKeyword('');
}}
width={560}
className='org-sidesheet'
>
<div className='org-skill-import'>
<Paragraph type='tertiary'>
{t(
'从平台已审核的技能目录中为本企业启用。启用后还需在「分发与锁定」建策略,成员才可用。',
)}
</Paragraph>
<Input
value={importKeyword}
onChange={setImportKeyword}
prefix={<Search size={15} />}
placeholder={t('搜索技能名称或标识')}
showClear
/>
{!loaded ? (
<Empty title={t('正在加载平台目录')} />
) : loadError.catalog ? (
// 同上:目录接口失败不能显示成"平台暂无可用技能"。
<Empty
title={t('平台目录加载失败')}
description={loadError.catalog}
/>
) : importCandidates.length === 0 ? (
<Empty
title={
catalog.size === 0
? t('平台目录暂无可用技能')
: importKeyword.trim()
? t('没有匹配的技能')
: t('平台目录中的技能都已在企业技能库中')
}
description={
catalog.size === 0
? t('平台审核通过的技能会出现在这里,稍后再来看看。')
: undefined
}
/>
) : (
<ul className='org-skill-import-list'>
{importCandidates.map((item) => (
<li key={item.definition.id}>
<div className='org-skill-import-main'>
<Text strong>{catalogName(item)}</Text>
<Text type='tertiary' size='small'>
{item.definition?.canonical_id} · v
{item.version?.version_no}
</Text>
</div>
{/* 合规徽章与启用按钮同排:启用是留审计的治理写入,
许可证决策与运行时安全结论必须在决策点可见。 */}
<div className='org-skill-import-actions'>
<LicenseBadge
expression={item.license?.expression}
decision={item.license?.decision}
/>
<RiskBadge conclusion={item.runtime?.conclusion} />
<Button
size='small'
theme='solid'
loading={importingId === item.definition.id}
onClick={() => void importSkill(item.definition.id)}
>
{t('启用')}
</Button>
</div>
</li>
))}
</ul>
)}
</div>
</SideSheet>
</main>
);
};
export default OrgSkillLibrary;
File diff suppressed because it is too large Load Diff
+630
View File
@@ -0,0 +1,630 @@
/*
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, useState } from 'react';
import { timestamp2string } from '../../helpers/utils';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Button,
Tag,
Progress,
Form,
Toast,
Empty,
Spin,
Typography,
} from '@douyinfe/semi-ui';
import {
Wallet,
Key,
FileClock,
Plus,
RefreshCw,
Pencil,
Clock,
TrendingUp,
Coins,
KeyRound,
} from 'lucide-react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import {
renderQuota,
getCurrencyConfig,
displayAmountToQuota,
} from '../../helpers/render';
import OrgHero from './components/OrgHero';
import OrgModal from './components/OrgModal';
import OrgNicknameModal from './components/OrgNicknameModal';
import OrgPasswordModal from './components/OrgPasswordModal';
import { orgStatusColor } from './components/orgStatus';
import OrgPanel from './components/OrgPanel';
import StatCard from './components/OrgStatCard';
// 时段问候(工作台 hero 签名区的 eyebrow)
const getGreeting = (t) => {
const hour = new Date().getHours();
if (hour < 6) return t('凌晨好');
if (hour < 12) return t('早上好');
if (hour < 14) return t('中午好');
if (hour < 18) return t('下午好');
return t('晚上好');
};
const { Text, Title } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const PERIODIC_QUOTA_PERIODS = new Set(['daily', 'weekly', 'monthly']);
const isPeriodicQuotaPeriod = (period) => PERIODIC_QUOTA_PERIODS.has(period);
const safeQuotaNumber = (value) => Math.max(0, Number(value || 0));
const quotaPeriodResetHint = (t, period) => {
switch (period) {
case 'daily':
return t('每日 00:00 重置(企业时区)');
case 'weekly':
return t('每周一 00:00 重置(企业时区)');
case 'monthly':
return t('自然月:每月 1 日 00:00 重置');
default:
return t('按周期重置');
}
};
const quotaPeriodLimitLabel = (t, period) => {
switch (period) {
case 'daily':
return t('每日个人上限');
case 'weekly':
return t('每周个人上限');
case 'monthly':
return t('每月个人上限');
default:
return t('个人终身上限');
}
};
const roleLabel = (t, role) =>
role === 'owner'
? t('所有者')
: role === 'admin'
? t('管理员')
: role === 'super_admin'
? t('超级管理员')
: t('成员');
const reqStatusTag = (t, status) => {
const map = {
pending: { text: t('待审批') },
approved: { text: t('已通过') },
rejected: { text: t('已拒绝') },
canceled: { text: t('已取消') },
expired: { text: t('已过期') },
};
const s = map[status] || { text: status };
return <Tag color={orgStatusColor(status)}>{s.text}</Tag>;
};
const isFeatureEnabled = (flags, key) => {
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
// 用量趋势小块:窗口标题 + 消耗 + 请求数
const UsageBlock = ({ t, title, data }) => (
<div className='flex-1 min-w-[140px] rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] px-4 py-3'>
<div className='text-xs font-medium text-gray-500 dark:text-gray-400 mb-1'>
{title}
</div>
<div className='text-lg font-semibold tabular-nums text-[var(--text-primary)]'>
{renderQuota(data?.quota || 0, 2)}
</div>
<div className='text-xs text-gray-500 mt-0.5'>
{t('请求数')} {data?.requests || 0} · {t('Token 总量')}{' '}
{data?.tokens || 0}
</div>
</div>
);
// 企业工作台:员工自助门户(§36.1)——个人额度/用量统计/令牌/申请。
const OrgWorkbench = ({ orgId, orgRole, featureFlags }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [summary, setSummary] = useState(null);
const [loading, setLoading] = useState(true);
const [projects, setProjects] = useState([]);
const [reqModal, setReqModal] = useState(false);
const [formApi, setFormApi] = useState(null);
const [nickModal, setNickModal] = useState(false);
// 自助改密(方案 §12.8)
const [pwdModal, setPwdModal] = useState(false);
const [approvers, setApprovers] = useState([]);
const approvalEnabled = isFeatureEnabled(featureFlags, 'approval');
const projectEnabled = isFeatureEnabled(featureFlags, 'project');
const role = orgRole || summary?.member?.role;
const fetchSummary = useCallback(
async (silent = false) => {
if (!orgId) return;
if (!silent) setLoading(true);
try {
const res = await API.get('/api/org/me/summary', {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
setSummary(res.data.data);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
if (!silent) setLoading(false);
}
},
[orgId],
);
const fetchProjects = useCallback(async () => {
if (!orgId || !projectEnabled) {
setProjects([]);
return;
}
try {
const res = await API.get('/api/org/project', {
headers: getOrgHeaders(orgId),
});
if (res.data.success) setProjects(res.data.data || []);
} catch {
/* 忽略:提额申请仍可选部门 */
}
}, [orgId, projectEnabled]);
useEffect(() => {
fetchSummary();
fetchProjects();
}, [fetchSummary, fetchProjects]);
useEffect(() => {
if (!orgId) return undefined;
let lastRefreshAt = 0;
const refreshSilently = () => {
const now = Date.now();
if (now - lastRefreshAt < 5000) return;
lastRefreshAt = now;
fetchSummary(true);
};
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
refreshSilently();
}
};
window.addEventListener('focus', refreshSilently);
document.addEventListener('visibilitychange', handleVisibilityChange);
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') {
refreshSilently();
}
}, 60000);
return () => {
window.removeEventListener('focus', refreshSilently);
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.clearInterval(timer);
};
}, [orgId, fetchSummary]);
const quotaLimit = safeQuotaNumber(summary?.my_quota?.quota_limit);
const usedQuota = safeQuotaNumber(summary?.my_quota?.used_quota);
const totalUsedQuota = safeQuotaNumber(
summary?.my_quota?.total_used_quota ?? usedQuota,
);
const quotaPeriod = summary?.my_quota?.quota_period || 'none';
const resetSource = summary?.reset_source || '';
const resetAt = safeQuotaNumber(summary?.reset_at);
const usage = summary?.usage || {};
const quotaIsPeriodic = isPeriodicQuotaPeriod(quotaPeriod);
const quotaResetHint = quotaPeriodResetHint(t, quotaPeriod);
const quotaPercent = useMemo(() => {
if (!quotaLimit || quotaLimit <= 0) return 0;
return Math.min(100, Math.round((usedQuota / quotaLimit) * 100));
}, [quotaLimit, usedQuota]);
// 可用额度:有个人上限时 = 上限-已用;无个人上限时不展示整个企业池数字
// (会被成员误读为「我的额度」),仅提示从共享池扣减。
const availableDisplay = useMemo(() => {
if (quotaLimit > 0) {
return renderQuota(Math.max(0, quotaLimit - usedQuota), 2);
}
return t('共享企业池');
}, [quotaLimit, usedQuota, t]);
const availableHint =
quotaLimit > 0
? quotaIsPeriodic
? t('当前周期个人额度剩余')
: t('个人额度上限内剩余')
: t('未设个人上限,从企业统一额度池扣减');
const quotaUsageLabel = quotaIsPeriodic
? t('本周期已用额度')
: t('总已用额度');
const quotaLimitLabel = quotaPeriodLimitLabel(t, quotaPeriod);
const quotaLimitHint =
quotaLimit > 0
? quotaIsPeriodic
? `${quotaLimitLabel} ${renderQuota(quotaLimit, 2)} · ${quotaResetHint}`
: `${quotaLimitLabel} ${renderQuota(quotaLimit, 2)}`
: t('未设个人上限');
const resetHint =
resetAt > 0
? resetSource === 'member_quota'
? quotaResetHint
: resetSource === 'budget'
? t('按预算周期重置')
: t('按周期重置')
: quotaIsPeriodic
? quotaResetHint
: t('无重置周期');
const resetValue =
resetAt > 0
? timestamp2string(resetAt)
: quotaIsPeriodic
? t('待初始化')
: t('不重置');
// 提额输入单位:跟随站点展示货币(TOKENS 模式下为原始额度单位)。
// 每次 render 重新读取,不能用空依赖 memo:货币配置由 /api/status 异步写入
// localStorage,冻结快照会导致 label 单位与提交时的换算口径脱节
const deltaCurrency = getCurrencyConfig();
const deltaIsToken = deltaCurrency.type === 'TOKENS';
const deltaLabel = deltaIsToken
? t('提额数量(额度单位)')
: `${t('提额数量')}(${deltaCurrency.symbol})`;
// 提额申请目标选项:优先申请个人额度;部门/项目属于预算额度,周期可能不同。
const subjectOptions = useMemo(() => {
const opts = [];
if (summary?.member?.id && quotaLimit > 0) {
opts.push({
label: `${t('我的个人额度')}(${quotaLimitLabel})`,
value: `member:${summary.member.id}`,
});
}
if (summary?.member?.department_id) {
opts.push({
label: `${t('部门')}:${summary.member.department_name || '#' + summary.member.department_id}`,
value: `department:${summary.member.department_id}`,
});
}
projects.forEach((p) => {
opts.push({ label: `${t('项目')}:${p.name}`, value: `project:${p.id}` });
});
return opts;
}, [summary, projects, quotaLimit, quotaLimitLabel, t]);
const openReqModal = async () => {
setReqModal(true);
try {
const res = await API.get('/api/org/me/approvers', {
headers: getOrgHeaders(orgId),
});
if (res.data.success) setApprovers(res.data.data?.approvers || []);
} catch {
/* 忽略:无上级候选时仅保留「企业管理员」默认项 */
}
};
const submitRequest = async () => {
if (!formApi) return;
let values;
try {
values = await formApi.validate();
} catch {
return;
}
const [subject_type, subject_id] = String(values.subject).split(':');
try {
const res = await API.post(
'/api/org/requests',
{
request_type: 'quota',
subject_type,
subject_id: parseInt(subject_id, 10),
cycle_quota_delta: displayAmountToQuota(values.delta),
approver_member_id: values.approver || 0,
reason: values.reason || '',
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('提额申请已提交,等待管理员审批'));
setReqModal(false);
fetchSummary();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const openNickModal = () => {
setNickModal(true);
};
if (loading) {
return (
<div className='flex items-center justify-center h-full'>
<Spin size='large' />
</div>
);
}
const memberName =
summary?.member?.display_name || summary?.member?.username || '';
return (
<div className='org-stagger p-4 sm:p-6 lg:p-8 space-y-5'>
{/* 签名时刻:hero 问候区(每页至多一个签名渐变区,见方案 A+ 冲击力护栏) */}
<OrgHero
eyebrow={`${getGreeting(t)}${memberName ? ',' + memberName : ''}`}
title={summary?.organization?.name || t('企业工作台')}
subtitle={`${t('个人工作台')} · ${t('我的角色')}:${roleLabel(t, role)}${summary?.member?.department_name ? ' · ' + summary.member.department_name : ''}`}
actions={
<>
<Button
theme='light'
icon={<Pencil size={14} />}
onClick={openNickModal}
>
{t('编辑昵称')}
</Button>
<Button
theme='light'
icon={<KeyRound size={14} />}
onClick={() => setPwdModal(true)}
>
{t('修改密码')}
</Button>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={() => {
fetchSummary();
fetchProjects();
}}
>
{t('刷新')}
</Button>
</>
}
/>
{/* 关键指标卡组 */}
<div className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
<StatCard
icon={Coins}
label={quotaUsageLabel}
value={renderQuota(usedQuota, 2)}
hint={quotaLimitHint}
/>
<StatCard
icon={Wallet}
label={t('可用额度')}
value={availableDisplay}
hint={availableHint}
/>
<StatCard
icon={Clock}
label={t('额度重置时间')}
value={resetValue}
hint={resetHint}
/>
<StatCard
icon={FileClock}
label={t('待处理申请')}
countTo={summary?.pending_request_count ?? 0}
hint={t('我提交的提额申请')}
/>
</div>
{/* 我的额度进度 + 我的令牌 */}
<div className='grid grid-cols-1 md:grid-cols-3 gap-4'>
<OrgPanel className='md:col-span-2'>
<div className='flex items-center gap-2 mb-3'>
<Wallet size={18} className='text-brand-deep' />
<Text strong>{t('我的额度')}</Text>
</div>
{quotaLimit > 0 ? (
<>
<Progress
percent={quotaPercent}
stroke={
quotaPercent >= 90 ? 'var(--semi-color-danger)' : undefined
}
style={{ marginBottom: 8 }}
/>
<Text type='tertiary' size='small'>
{quotaIsPeriodic ? t('本周期已用') : t('已用')}{' '}
{renderQuota(usedQuota, 2)} / {renderQuota(quotaLimit, 2)}
{quotaIsPeriodic
? ` · ${t('累计已用')} ${renderQuota(totalUsedQuota, 2)}`
: ''}
</Text>
</>
) : (
<Text type='tertiary' size='small'>
{t('未设个人上限,使用企业统一额度池')}
</Text>
)}
<div className='mt-2'>
<Text type='tertiary' size='small'>
{t('实际可用还受所在部门/项目及企业预算约束。')}
</Text>
</div>
<div className='mt-3'>
<Button
size='small'
icon={<Plus size={14} />}
onClick={openReqModal}
disabled={!approvalEnabled || subjectOptions.length === 0}
>
{t('申请提额')}
</Button>
</div>
</OrgPanel>
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<Key size={18} className='text-brand-deep' />
<Text strong>{t('我的令牌')}</Text>
</div>
<Title heading={2} style={{ margin: '4px 0' }}>
{summary?.token_count ?? 0}
</Title>
<Button
size='small'
theme='light'
onClick={() => navigate('/org/tokens')}
>
{t('管理令牌')}
</Button>
</OrgPanel>
</div>
{/* 个人用量趋势 */}
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<TrendingUp size={18} className='text-brand-deep' />
<Text strong>{t('个人用量趋势')}</Text>
</div>
<div className='flex flex-wrap gap-4'>
<UsageBlock t={t} title={t('今日')} data={usage.today} />
<UsageBlock t={t} title={t('近 7 天')} data={usage.last7d} />
<UsageBlock t={t} title={t('近 30 天')} data={usage.last30d} />
<UsageBlock t={t} title={t('累计')} data={usage.total} />
</div>
</OrgPanel>
{/* 最近申请 */}
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<FileClock size={18} className='text-brand-deep' />
<Text strong>{t('最近申请')}</Text>
</div>
{summary?.recent_requests?.length ? (
<div className='flex flex-col divide-y divide-[var(--semi-color-border)]'>
{summary.recent_requests.map((r) => (
<div
key={r.id}
className='flex items-center justify-between py-2.5'
>
<div>
<Text>
{r.request_type === 'quota'
? t('提额申请')
: r.request_type}
{r.reason ? ` · ${r.reason}` : ''}
</Text>
<div>
<Text type='tertiary' size='small'>
{r.created_at ? timestamp2string(r.created_at) : ''}
</Text>
</div>
</div>
{reqStatusTag(t, r.status)}
</div>
))}
</div>
) : (
<Empty description={t('暂无申请记录')} />
)}
</OrgPanel>
{/* 提额申请弹窗 */}
<OrgModal
title={t('申请提额')}
visible={reqModal}
onOk={submitRequest}
onCancel={() => setReqModal(false)}
okText={t('提交申请')}
cancelText={t('取消')}
>
<Form getFormApi={setFormApi}>
<Form.Select
field='subject'
label={t('提额对象')}
initValue={subjectOptions[0]?.value}
optionList={subjectOptions}
rules={[{ required: true, message: t('请选择提额对象') }]}
style={{ width: '100%' }}
/>
<Text type='tertiary' size='small'>
{t(
'个人额度用于解除您自己的使用上限;部门/项目额度属于预算上限,可能有独立周期。',
)}
</Text>
<Form.InputNumber
field='delta'
label={deltaLabel}
min={deltaIsToken ? 1 : 0.01}
precision={deltaIsToken ? 0 : 2}
suffix={deltaIsToken ? null : deltaCurrency.symbol}
rules={[{ required: true, message: t('请输入提额数量') }]}
style={{ width: '100%' }}
/>
<Form.Select
field='approver'
label={t('审批人')}
initValue={0}
optionList={[
{ label: t('企业管理员(默认)'), value: 0 },
...approvers.map((a) => ({
label: `${t('上级')}:${a.name}`,
value: a.member_id,
})),
]}
style={{ width: '100%' }}
/>
<Form.TextArea field='reason' label={t('申请理由')} maxCount={200} />
</Form>
</OrgModal>
{/* 编辑昵称弹窗(共享组件,与个人设置页共用) */}
<OrgNicknameModal
visible={nickModal}
onClose={() => setNickModal(false)}
orgId={orgId}
currentName={summary?.member?.display_name || ''}
onSuccess={() => fetchSummary()}
/>
{/* 自助改密(方案 §12.8,共享组件) */}
<OrgPasswordModal visible={pwdModal} onClose={() => setPwdModal(false)} />
</div>
);
};
export default OrgWorkbench;
@@ -0,0 +1,141 @@
/*
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
*/
/* 部门画布「影棚」皮肤:去点阵,改用品牌色辉光 + 渐晕背景;
卡片/工具条/控件/小地图统一磨玻璃。深浅色跟随 React Flow
colorMode(容器上的 .dark/.light 类,与全局主题一致)。 */
.dept-flow-cinema {
--dfc-glow: color-mix(in srgb, var(--semi-color-primary) 16%, transparent);
--dfc-glow-soft: color-mix(
in srgb,
var(--semi-color-primary) 9%,
transparent
);
/* 不支持 color-mix 的旧内核退化为纯渐变底 */
background: linear-gradient(180deg, #f7f9fd 0%, #edf1f8 100%);
background: radial-gradient(
1100px 520px at 50% -8%,
var(--dfc-glow),
transparent 62%
),
radial-gradient(
900px 480px at 88% 110%,
var(--dfc-glow-soft),
transparent 60%
),
linear-gradient(180deg, #f7f9fd 0%, #edf1f8 100%);
}
.dept-flow-cinema.dark {
background: linear-gradient(180deg, #0b1020 0%, #0d1329 55%, #090e1c 100%);
background: radial-gradient(
1100px 520px at 50% -8%,
color-mix(in srgb, var(--semi-color-primary) 24%, transparent),
transparent 62%
),
radial-gradient(
900px 480px at 88% 110%,
rgba(56, 189, 248, 0.1),
transparent 60%
),
linear-gradient(180deg, #0b1020 0%, #0d1329 55%, #090e1c 100%);
}
/* 四周渐晕(vignette):盖在节点上、面板下,视觉聚焦画布中心 */
.dept-flow-cinema::after {
content: '';
position: absolute;
inset: 0;
z-index: 4;
pointer-events: none;
background: radial-gradient(
120% 90% at 50% 45%,
transparent 60%,
rgba(15, 23, 42, 0.07) 100%
);
}
.dept-flow-cinema.dark::after {
background: radial-gradient(
120% 90% at 50% 45%,
transparent 55%,
rgba(0, 0, 0, 0.45) 100%
);
}
/* 连线:品牌色 + 轻辉光 */
.dept-flow-cinema .react-flow__edge-path {
stroke: color-mix(
in srgb,
var(--semi-color-primary) 55%,
rgba(148, 163, 184, 0.45)
);
filter: drop-shadow(0 0 3px var(--dfc-glow));
}
.dept-flow-cinema .react-flow__edge.selected .react-flow__edge-path {
stroke: var(--semi-color-primary);
}
.dept-flow-cinema .react-flow__connection-path {
stroke: var(--semi-color-primary);
}
/* 缩放控件:磨玻璃 */
.dept-flow-cinema .react-flow__controls {
overflow: hidden;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.55);
background: rgba(255, 255, 255, 0.6);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
box-shadow: 0 8px 24px -12px rgba(15, 23, 42, 0.35);
}
.dept-flow-cinema .react-flow__controls-button {
border-bottom: 1px solid rgba(148, 163, 184, 0.25);
background: transparent;
}
.dept-flow-cinema .react-flow__controls-button:hover {
background: rgba(148, 163, 184, 0.15);
}
.dept-flow-cinema.dark .react-flow__controls {
border-color: rgba(255, 255, 255, 0.12);
background: rgba(13, 19, 41, 0.55);
box-shadow: 0 8px 24px -12px rgba(0, 0, 0, 0.6);
}
.dept-flow-cinema.dark .react-flow__controls-button {
border-bottom-color: rgba(255, 255, 255, 0.08);
}
.dept-flow-cinema.dark .react-flow__controls-button svg {
fill: #cbd5e1;
}
/* 小地图:磨玻璃 */
.dept-flow-cinema .react-flow__minimap {
border-radius: 10px;
overflow: hidden;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
@@ -0,0 +1,823 @@
/*
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, {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
ReactFlow,
ReactFlowProvider,
Controls,
MiniMap,
Panel,
Handle,
Position,
useNodesState,
useEdgesState,
useReactFlow,
useUpdateNodeInternals,
} from '@xyflow/react';
import dagre from '@dagrejs/dagre';
import {
Avatar,
Button,
Popconfirm,
RadioGroup,
Radio,
SideSheet,
Tag,
Tooltip,
Typography,
} from '@douyinfe/semi-ui';
import {
Plus,
Pencil,
Trash2,
LayoutGrid,
Network,
Building2,
ChevronDown,
ChevronRight,
Users,
} from 'lucide-react';
import OrgScopedLimitButtons from './OrgScopedLimitButtons';
import { buildDeptFullNameMap } from './deptTree';
import { renderQuota } from '../../../helpers/render';
import '@xyflow/react/dist/style.css';
import './DeptFlowCanvas.css';
const { Text } = Typography;
// dagre 布局用的节点占位尺寸(与卡片实际渲染尺寸保持一致,决定节点间距)。
// 高度按「带预算行」的卡片取值——无预算的卡片略矮只会让间距更宽松,不会重叠。
const NODE_WIDTH = 264;
const NODE_HEIGHT = 144;
const parseGroups = (raw) => {
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string' && raw.trim()) {
try {
const arr = JSON.parse(raw);
if (Array.isArray(arr)) return arr;
} catch {
/* ignore */
}
}
return [];
};
// 部门预算行 → 卡片展示用摘要:优先周期口径,无周期上限再看总上限;双 0(不限)不展示。
const summarizeBudget = (t, budget) => {
if (!budget || budget.status !== 1) return null;
const cycleLabels = {
daily: t('每日'),
weekly: t('每周'),
monthly: t('每月'),
custom: t('自定义'),
};
// used 含预留中份额:与预算中心「used (+reserved 预留)」口径一致,
// 否则两页同开时百分比自相矛盾,且接近 cap 时画布不变红失去预警
if (budget.cycle_quota > 0) {
return {
label: cycleLabels[budget.cycle_type] || t('周期上限'),
used: (budget.used_in_cycle || 0) + (budget.reserved_in_cycle || 0),
cap: budget.cycle_quota,
};
}
if (budget.total_quota > 0) {
return {
label: t('总上限'),
used: (budget.used_total || 0) + (budget.reserved_total || 0),
cap: budget.total_quota,
};
}
return null;
};
/** 部门卡片节点:信息展示 + 卡片内操作区(操作区带 nodrag,避免与画布拖拽冲突) */
const DeptNode = memo(({ data, selected }) => {
const { t } = useTranslation();
const {
dept,
childCount,
memberCount,
collapsed,
hiddenCount,
direction,
orgId,
budget,
onAddChild,
onEdit,
onDelete,
onSaved,
onToggleCollapse,
onShowMembers,
} = data;
const budgetInfo = summarizeBudget(t, budget);
const active = dept.status === 1;
const isRoot = !dept.parent_id;
const groupCount = parseGroups(dept.groups).length;
const modelCount =
dept.model_limits_enabled && dept.model_limits
? dept.model_limits.split(',').filter(Boolean).length
: 0;
const targetPos = direction === 'LR' ? Position.Left : Position.Top;
const sourcePos = direction === 'LR' ? Position.Right : Position.Bottom;
const DeptIcon = isRoot ? Building2 : Network;
return (
<div
className={`relative rounded-xl border bg-white/75 backdrop-blur-xl transition-all duration-150 dark:bg-[#0e1430]/65 ${
selected
? 'border-[var(--semi-color-primary)] shadow-lg ring-2 ring-[var(--semi-color-primary-light-default)]'
: 'border-white/60 shadow-[0_10px_30px_-14px_rgba(15,23,42,0.35)] hover:border-[var(--semi-color-primary-light-active)] hover:shadow-lg dark:border-white/10'
} ${active ? '' : 'opacity-70'}`}
style={{ width: NODE_WIDTH }}
>
{/* 根节点渐变顶条:一眼区分树的入口 */}
{isRoot && (
<div className='absolute inset-x-0 top-0 h-[3px] rounded-t-xl bg-gradient-to-r from-[var(--semi-color-primary)] to-[var(--semi-color-primary-light-active)]' />
)}
<Handle
type='target'
position={targetPos}
className='!w-2.5 !h-2.5 !bg-[var(--semi-color-primary)] !border-2 !border-[var(--surface-card)]'
/>
<div className='px-3.5 pt-3'>
<div className='flex items-center justify-between gap-2'>
<div className='flex items-center gap-2 min-w-0'>
<span className='inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-brand/10 text-brand'>
<DeptIcon size={13} />
</span>
<span
className='text-sm font-semibold text-[var(--text-primary)] truncate'
title={dept.name}
>
{dept.name}
</span>
</div>
<div className='flex items-center gap-1 flex-shrink-0'>
{childCount > 0 && (
<Tooltip
content={
collapsed
? `${t('展开')}(${t('已收起')} ${hiddenCount} ${t('个下级')})`
: t('收起下级部门')
}
>
<button
type='button'
className='nodrag inline-flex h-5 items-center gap-0.5 rounded-md px-1 text-xs text-gray-500 transition-colors hover:bg-brand/10 hover:text-brand dark:text-gray-400'
onClick={(e) => {
e.stopPropagation();
onToggleCollapse(dept.id);
}}
onDoubleClick={(e) => e.stopPropagation()}
>
{collapsed ? (
<>
<ChevronRight size={13} />
<span className='font-medium'>+{hiddenCount}</span>
</>
) : (
<ChevronDown size={13} />
)}
</button>
</Tooltip>
)}
<Tag size='small' color={active ? 'green' : 'grey'}>
{active ? t('启用') : t('停用')}
</Tag>
</div>
</div>
<div className='mt-1.5 flex items-center gap-2 flex-wrap'>
<Text type='tertiary' size='small'>
{t('子部门')} {childCount} · {t('排序')} {dept.sort || 0}
</Text>
<Tooltip content={t('查看直属成员')}>
<button
type='button'
className='nodrag inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-gray-500 transition-colors hover:bg-brand/10 hover:text-brand dark:text-gray-400'
onClick={(e) => {
e.stopPropagation();
onShowMembers(dept);
}}
onDoubleClick={(e) => e.stopPropagation()}
>
<Users size={11} />
{memberCount}
</button>
</Tooltip>
{modelCount > 0 && (
<Tag size='small' color='blue'>
{t('模型限制')} {modelCount}
</Tag>
)}
{groupCount > 0 && (
<Tag size='small' color='purple'>
{t('限定分组')} {groupCount}
</Tag>
)}
</div>
{budgetInfo &&
(() => {
const pct = Math.min(
100,
Math.round((budgetInfo.used / budgetInfo.cap) * 100),
);
const danger = pct >= 90;
return (
<div className='mt-2 rounded-md bg-[var(--semi-color-fill-0)] px-2 py-1'>
<div className='flex items-center justify-between gap-2 text-[11px] leading-4'>
<span className='text-gray-500 dark:text-gray-400 flex-shrink-0'>
{t('预算')} · {budgetInfo.label}
</span>
<span
className={
danger
? 'font-medium text-[var(--semi-color-danger)] truncate'
: 'text-gray-600 dark:text-gray-300 truncate'
}
title={`${renderQuota(budgetInfo.used, 2)} / ${renderQuota(budgetInfo.cap, 2)}`}
>
{renderQuota(budgetInfo.used, 2)} /{' '}
{renderQuota(budgetInfo.cap, 2)}
</span>
</div>
<div className='mt-1 h-1 overflow-hidden rounded-full bg-black/10 dark:bg-white/10'>
<div
className='h-full rounded-full transition-all'
style={{
width: `${pct}%`,
background: danger
? 'var(--semi-color-danger)'
: 'var(--semi-color-primary)',
}}
/>
</div>
</div>
);
})()}
</div>
<div
className='nodrag mt-2.5 flex items-center gap-1 border-t border-black/5 px-2 py-1.5 dark:border-white/10'
onDoubleClick={(e) => e.stopPropagation()}
>
<OrgScopedLimitButtons
orgId={orgId}
record={dept}
apiBase='/api/org/dept'
scopeLabel='部门'
onSaved={onSaved}
/>
<div className='flex-1' />
{/* 停用部门下不允许新建子部门(后端同校验),直接隐藏入口 */}
{active && (
<Tooltip content={t('添加子部门')}>
<Button
size='small'
theme='borderless'
type='tertiary'
icon={<Plus size={14} />}
onClick={() => onAddChild(dept)}
/>
</Tooltip>
)}
<Tooltip content={t('编辑')}>
<Button
size='small'
theme='borderless'
type='tertiary'
icon={<Pencil size={14} />}
onClick={() => onEdit(dept)}
/>
</Tooltip>
<Popconfirm
title={t('确认删除该部门?')}
content={t('仅可删除无子部门、无成员的空部门')}
onConfirm={() => onDelete(dept)}
>
<Button
size='small'
theme='borderless'
type='danger'
icon={<Trash2 size={14} />}
/>
</Popconfirm>
</div>
<Handle
type='source'
position={sourcePos}
className='!w-2.5 !h-2.5 !bg-[var(--semi-color-primary)] !border-2 !border-[var(--surface-card)]'
/>
</div>
);
});
DeptNode.displayName = 'DeptNode';
const nodeTypes = { dept: DeptNode };
/** dagre 自动布局:多棵树(森林)各自成块排布 */
const layoutPositions = (depts, direction) => {
const g = new dagre.graphlib.Graph();
g.setGraph({
rankdir: direction,
nodesep: 36,
ranksep: direction === 'LR' ? 96 : 64,
marginx: 24,
marginy: 24,
});
g.setDefaultEdgeLabel(() => ({}));
const idSet = new Set(depts.map((d) => d.id));
depts.forEach((d) => {
g.setNode(String(d.id), { width: NODE_WIDTH, height: NODE_HEIGHT });
});
depts.forEach((d) => {
// 跳过自环(脏数据防护)与悬空父级(当作根节点)
if (d.parent_id && d.parent_id !== d.id && idSet.has(d.parent_id)) {
g.setEdge(String(d.parent_id), String(d.id));
}
});
dagre.layout(g);
const positions = {};
depts.forEach((d) => {
const n = g.node(String(d.id));
positions[d.id] = {
x: n.x - NODE_WIDTH / 2,
y: n.y - NODE_HEIGHT / 2,
};
});
return positions;
};
const FlowInner = ({
orgId,
depts,
members,
budgets,
direction,
onDirectionChange,
colorMode,
onAddChild,
onEdit,
onDelete,
onMove,
onSaved,
}) => {
const { t } = useTranslation();
const { fitView } = useReactFlow();
const updateNodeInternals = useUpdateNodeInternals();
// 卸载守卫:pending 的 rAF 回调在画布卸载后不再触碰 React Flow 实例。
// body 里必须复位为 true —— StrictMode 下 effect 会「跑→清理→再跑」,
// 只写清理函数会让守卫在开发模式永久为 false,拦死 fitView。
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const deptMap = useMemo(() => {
const m = {};
depts.forEach((d) => {
m[d.id] = d;
});
return m;
}, [depts]);
const childCountMap = useMemo(() => {
const m = {};
depts.forEach((d) => {
if (d.parent_id && d.parent_id !== d.id)
m[d.parent_id] = (m[d.parent_id] || 0) + 1;
});
return m;
}, [depts]);
// 每部门的整棵子树规模(不含自身,path 解析祖先链),收起时展示「+N」
const descendantCountMap = useMemo(() => {
const m = {};
depts.forEach((d) => {
if (!d.path) return;
d.path
.split('/')
.filter(Boolean)
.map(Number)
.forEach((aid) => {
if (aid !== d.id) m[aid] = (m[aid] || 0) + 1;
});
});
return m;
}, [depts]);
// 直属成员:仅活跃成员(/members/all 已过滤),按主归属分桶
const membersByDept = useMemo(() => {
const m = {};
(members || []).forEach((mm) => {
const k = mm.department_id || 0;
if (!m[k]) m[k] = [];
m[k].push(mm);
});
return m;
}, [members]);
// 部门预算行按 subject_id 索引,节点卡片展示预算用量
const budgetByDept = useMemo(() => {
const m = {};
(budgets || []).forEach((b) => {
if (b.subject_id) m[b.subject_id] = b;
});
return m;
}, [budgets]);
// 子树收起:被收起节点的全部子孙不参与布局与渲染(path 前缀判断)
const [collapsedIds, setCollapsedIds] = useState(() => new Set());
const toggleCollapse = useCallback((deptId) => {
setCollapsedIds((prev) => {
const next = new Set(prev);
if (next.has(deptId)) next.delete(deptId);
else next.add(deptId);
return next;
});
}, []);
const visibleDepts = useMemo(() => {
if (collapsedIds.size === 0) return depts;
const collapsedPaths = depts
.filter((d) => collapsedIds.has(d.id) && d.path)
.map((d) => d.path);
if (!collapsedPaths.length) return depts;
return depts.filter(
(d) =>
!collapsedPaths.some(
(p) => d.path && d.path !== p && d.path.startsWith(p),
),
);
}, [depts, collapsedIds]);
// 对收起的节点添加子部门:先自动展开,否则新建的子部门会被隐藏,像创建失败
const handleAddChild = useCallback(
(dept) => {
setCollapsedIds((prev) => {
if (!prev.has(dept.id)) return prev;
const next = new Set(prev);
next.delete(dept.id);
return next;
});
onAddChild(dept);
},
[onAddChild],
);
// 成员列表侧栏
const [memberSheetDept, setMemberSheetDept] = useState(null);
const showMembers = useCallback((dept) => setMemberSheetDept(dept), []);
const deptFullNameMap = useMemo(() => buildDeptFullNameMap(depts), [depts]);
const { layoutNodes, layoutEdges } = useMemo(() => {
const positions = layoutPositions(visibleDepts, direction);
const idSet = new Set(visibleDepts.map((d) => d.id));
const nodes = visibleDepts.map((d) => ({
id: String(d.id),
type: 'dept',
position: positions[d.id],
data: {
dept: d,
childCount: childCountMap[d.id] || 0,
memberCount: (membersByDept[d.id] || []).length,
collapsed: collapsedIds.has(d.id),
hiddenCount: descendantCountMap[d.id] || 0,
direction,
orgId,
budget: budgetByDept[d.id],
onAddChild: handleAddChild,
onEdit,
onDelete,
onSaved,
onToggleCollapse: toggleCollapse,
onShowMembers: showMembers,
},
}));
const edges = visibleDepts
.filter(
(d) => d.parent_id && d.parent_id !== d.id && idSet.has(d.parent_id),
)
.map((d) => ({
id: `e-${d.parent_id}-${d.id}`,
source: String(d.parent_id),
target: String(d.id),
type: 'smoothstep',
// defaultEdgeOptions 只作用于交互新建的边,受控 edges 必须自带样式
style: { strokeWidth: 1.5 },
}));
return { layoutNodes: nodes, layoutEdges: edges };
}, [
visibleDepts,
direction,
childCountMap,
membersByDept,
budgetByDept,
collapsedIds,
descendantCountMap,
orgId,
handleAddChild,
onEdit,
onDelete,
onSaved,
toggleCollapse,
showMembers,
]);
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
// 自适应视野:双层 rAF 等 React Flow 完成节点量测后再 fitView(v12 尺寸量测异步);
// maxZoom 限制避免节点少时过度放大。
const fitViewSoon = useCallback(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (mountedRef.current) {
fitView({ padding: 0.2, duration: 300, maxZoom: 1 });
}
});
});
}, [fitView]);
// 结构指纹:节点集合 + 父子关系 + 排序 + 布局方向 + 收起集合(sort 决定 dagre
// 兄弟顺序;收起/展开改变可见节点集,同样触发整体重排 + fitView)。
// 只有结构变化才整体重排 + fitView;普通数据刷新(如改模型/分组限制)
// 保留用户手动摆放的位置与选中态,避免视野跳动。
const collapsedKey = useMemo(
() => [...collapsedIds].sort((a, b) => a - b).join('.'),
[collapsedIds],
);
const structureKey = useMemo(
() =>
direction +
'|' +
collapsedKey +
'|' +
depts
.map((d) => `${d.id}:${d.parent_id}:${d.sort || 0}`)
.sort()
.join(','),
[depts, direction, collapsedKey],
);
const prevStructureRef = useRef('');
useEffect(() => {
const structureChanged = prevStructureRef.current !== structureKey;
prevStructureRef.current = structureKey;
if (structureChanged) {
setNodes(layoutNodes);
setEdges(layoutEdges);
fitViewSoon();
} else {
setNodes((prev) => {
const prevMap = {};
prev.forEach((p) => {
prevMap[p.id] = p;
});
return layoutNodes.map((n) =>
prevMap[n.id]
? {
...n,
position: prevMap[n.id].position,
selected: prevMap[n.id].selected,
}
: n,
);
});
setEdges(layoutEdges);
}
}, [structureKey, layoutNodes, layoutEdges, setNodes, setEdges, fitViewSoon]);
const relayout = useCallback(() => {
setNodes(layoutNodes);
setEdges(layoutEdges);
fitViewSoon();
}, [layoutNodes, layoutEdges, setNodes, setEdges, fitViewSoon]);
// 布局方向切换会改变 Handle 挂载边(上下 ↔ 左右),必须通知 React Flow
// 重新量测锚点,否则连线仍吸附在节点旧边缘(RF 官方要求)。只量测当前渲染的节点。
useEffect(() => {
const ids = visibleDepts.map((d) => String(d.id));
const raf = requestAnimationFrame(() => {
if (mountedRef.current) updateNodeInternals(ids);
});
return () => cancelAnimationFrame(raf);
}, [direction, visibleDepts, updateNodeInternals]);
// 连线即移动层级:从父节点拖到子节点。禁止连向自己的祖先链(防环,后端仍有兜底)。
const isValidConnection = useCallback(
(conn) => {
if (!conn.source || !conn.target || conn.source === conn.target)
return false;
const source = deptMap[parseInt(conn.source, 10)];
const target = deptMap[parseInt(conn.target, 10)];
if (!source || !target) return false;
// 已停用部门不可作为新上级(与后端 MoveDepartmentTx 校验一致,拖线时即时拦截)
if (source.status !== 1) return false;
if (target.path && source.path && source.path.startsWith(target.path))
return false;
return true;
},
[deptMap],
);
const onConnect = useCallback(
(conn) => {
const parentId = parseInt(conn.source, 10);
const childId = parseInt(conn.target, 10);
const child = deptMap[childId];
if (!child || child.parent_id === parentId) return;
onMove(childId, parentId);
},
[deptMap, onMove],
);
const sheetMembers = memberSheetDept
? membersByDept[memberSheetDept.id] || []
: [];
return (
<>
<ReactFlow
className='dept-flow-cinema'
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
isValidConnection={isValidConnection}
onNodeDoubleClick={(_, node) => {
const dept = deptMap[parseInt(node.id, 10)];
if (dept) onEdit(dept);
}}
colorMode={colorMode}
fitView
minZoom={0.2}
maxZoom={1.5}
zoomOnDoubleClick={false}
deleteKeyCode={null}
defaultEdgeOptions={{ type: 'smoothstep', style: { strokeWidth: 1.5 } }}
connectionRadius={30}
>
{/* 影棚风背景由 .dept-flow-cinema 提供(辉光渐变+渐晕),不再渲染点阵 Background */}
<Controls showInteractive={false} position='bottom-right' />
<MiniMap
pannable
zoomable
position='top-right'
className='!rounded-lg !border !border-white/50 !overflow-hidden dark:!border-white/10'
nodeColor={(n) => {
const dept = deptMap[parseInt(n.id, 10)];
return dept && dept.status === 1
? 'var(--semi-color-primary-light-active)'
: 'var(--semi-color-fill-2)';
}}
maskColor={
colorMode === 'dark'
? 'rgba(3, 7, 18, 0.55)'
: 'rgba(226, 232, 240, 0.55)'
}
style={{
backgroundColor:
colorMode === 'dark'
? 'rgba(13, 19, 41, 0.5)'
: 'rgba(255, 255, 255, 0.5)',
}}
/>
<Panel position='top-left'>
<div className='flex items-center gap-2 rounded-lg border border-white/50 bg-white/60 px-2 py-1.5 shadow-[0_8px_24px_-12px_rgba(15,23,42,0.35)] backdrop-blur-md dark:border-white/10 dark:bg-[#0d1329]/60'>
<RadioGroup
type='button'
buttonSize='small'
value={direction}
onChange={(e) => onDirectionChange(e.target.value)}
>
<Radio value='TB'>{t('纵向')}</Radio>
<Radio value='LR'>{t('横向')}</Radio>
</RadioGroup>
<div className='h-4 w-px bg-black/10 dark:bg-white/15' />
<Button
size='small'
theme='light'
icon={<LayoutGrid size={13} />}
onClick={relayout}
>
{t('整理布局')}
</Button>
</div>
</Panel>
<Panel position='bottom-center'>
<Text
type='tertiary'
size='small'
className='rounded-md border border-white/40 bg-white/55 px-2 py-1 backdrop-blur-md dark:border-white/10 dark:bg-[#0d1329]/55'
>
{t(
'拖动节点可自由摆放;从节点边缘拖出连线到另一部门可调整上级;双击节点编辑',
)}
</Text>
</Panel>
</ReactFlow>
{/* 直属成员列表(仅活跃成员;主归属=该部门) */}
<SideSheet
title={
memberSheetDept
? `${memberSheetDept.name} · ${t('成员')} ${sheetMembers.length}`
: ''
}
visible={!!memberSheetDept}
onCancel={() => setMemberSheetDept(null)}
width={380}
>
{memberSheetDept && (
<div className='space-y-3'>
<Text type='tertiary' size='small'>
{deptFullNameMap[memberSheetDept.id] || memberSheetDept.name}
</Text>
{sheetMembers.length === 0 ? (
<div className='py-10 text-center text-sm text-gray-400'>
{t('该部门暂无直属成员')}
</div>
) : (
<div className='space-y-1'>
{sheetMembers.map((m) => {
const name = m.display_name || m.username || `#${m.user_id}`;
return (
<div
key={m.user_id}
className='flex items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-[var(--semi-color-fill-0)]'
>
<Avatar size='extra-small' color='blue'>
{name.slice(0, 1).toUpperCase()}
</Avatar>
<div className='min-w-0'>
<div className='truncate text-sm text-[var(--text-primary,inherit)]'>
{name}
</div>
{m.username && m.username !== name && (
<Text
type='tertiary'
size='small'
className='block truncate'
>
{m.username}
</Text>
)}
</div>
</div>
);
})}
</div>
)}
</div>
)}
</SideSheet>
</>
);
};
/**
* 部门组织架构画布(React Flow + dagre 自动布局,影棚风视觉)。
* - 多棵树:顶级部门(parent_id=0)各自成树
* - 子树可收起/展开(收起后子孙不参与布局,重排并 fitView)
* - 节点展示直属成员数,点击打开成员列表侧栏(members 由外部传入)
* - 节点展示部门预算用量条(budgets 由外部传入;无预算行/双 0 不限时不展示)
* - 深浅色跟随全局主题(colorMode 由外部传入)
* - 节点卡片内含操作区:模型/分组限制、加子部门、编辑、删除
*/
const DeptFlowCanvas = (props) => (
<ReactFlowProvider>
<FlowInner {...props} />
</ReactFlowProvider>
);
export default DeptFlowCanvas;
@@ -0,0 +1,62 @@
/*
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 } from 'react';
import { useTranslation } from 'react-i18next';
import { TreeSelect } from '@douyinfe/semi-ui';
import { buildDeptTreeData } from './deptTree';
// 部门树选择(受控):按组织架构展示层级,默认只允许选末级部门(成员主归属
// 挂末级,报表沿 path 上卷);停用部门置灰。清空 = 不分配(onChange 回 0)。
const DeptTreeSelect = ({
depts,
value,
onChange,
disableNonLeaf = true,
excludeSubtreeOf = null,
placeholder,
style,
...rest
}) => {
const { t } = useTranslation();
const treeData = useMemo(
() =>
buildDeptTreeData(depts, {
disableNonLeaf,
excludeSubtreeOf,
disabledLabel: t('已停用'),
}),
[depts, disableNonLeaf, excludeSubtreeOf, t],
);
return (
<TreeSelect
treeData={treeData}
value={value || undefined}
onChange={(v) => onChange?.(v || 0)}
showClear
filterTreeNode
showFilteredOnly
expandAll
placeholder={placeholder || t('未分配(清空即不归属任何部门)')}
style={{ width: '100%', ...style }}
{...rest}
/>
);
};
export default DeptTreeSelect;
@@ -0,0 +1,646 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Select,
Empty,
Spin,
Progress,
Typography,
} from '@douyinfe/semi-ui';
import OrgPanel from './OrgPanel';
import { VChart } from '@visactor/react-vchart';
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
import {
RefreshCw,
PieChart,
TrendingUp,
BarChart3,
Crown,
} from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import { renderQuota } from '../../../helpers/render';
import { useActualTheme } from '../../../context/Theme';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
/* 系列色运行时读取品牌 token(--brand-*),随主题预设整套切换。
* 不再硬编码(旧值 #14b8a6 在 azure 等预设下与全站主色打架)。 */
const readBrandColors = () => {
if (typeof window === 'undefined') {
return { brand: '#1668dc', brand2: '#13c2c2' };
}
const style = getComputedStyle(document.documentElement);
return {
brand: style.getPropertyValue('--brand-primary').trim() || '#1668dc',
brand2: style.getPropertyValue('--accent-teal').trim() || '#13c2c2',
};
};
const getChartTokens = (isDark) => ({
axisLabel: isDark ? '#94a3b8' : '#64748b',
axisLine: isDark ? 'rgba(148, 163, 184, 0.28)' : '#e5e7eb',
grid: isDark ? 'rgba(148, 163, 184, 0.14)' : '#edf2f7',
tooltipBg: isDark ? 'rgba(15, 23, 42, 0.96)' : 'rgba(255, 255, 255, 0.98)',
tooltipBorder: isDark ? 'rgba(148, 163, 184, 0.22)' : '#e5e7eb',
tooltipText: isDark ? '#e2e8f0' : '#0f172a',
tooltipMuted: isDark ? '#94a3b8' : '#64748b',
});
const chartTooltipStyle = (tokens) => ({
panel: {
backgroundColor: tokens.tooltipBg,
borderColor: tokens.tooltipBorder,
shadowBlur: 18,
shadowColor: 'rgba(15, 23, 42, 0.25)',
},
titleLabel: { fontColor: tokens.tooltipText },
keyLabel: { fontColor: tokens.tooltipMuted },
valueLabel: { fontColor: tokens.tooltipText },
});
const chartAxisLine = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartTick = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartGrid = (tokens) => ({
visible: true,
style: { stroke: tokens.grid, lineDash: [4, 4] },
});
// 环比徽标:本期 vs 上期。增长绿、下降红;无上期数据时灰显。
// 状态色统一走 Semi 语义 token(与页面各处使用进度条同一套红绿,且随明暗主题自适应)。
const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) {
return <span className='text-xs text-gray-400'>{t('无上期对比')}</span>;
}
const pct = ((cur - prev) / prev) * 100;
const up = pct >= 0;
return (
<span
className='text-xs font-medium'
style={{
color: up ? 'var(--semi-color-success)' : 'var(--semi-color-danger)',
}}
>
{up ? '▲' : '▼'} {Math.abs(pct).toFixed(1)}%
<span className='text-gray-400 ml-1'>{t('较上期')}</span>
</span>
);
};
const KpiCard = ({ label, value, sub }) => (
<div className='px-4 py-3 rounded-xl bg-[var(--semi-color-fill-0)]'>
<div className='text-xs text-gray-500 mb-1'>{label}</div>
<div className='text-lg font-semibold text-gray-900 dark:text-white truncate'>
{value}
</div>
{sub ? <div className='mt-0.5'>{sub}</div> : null}
</div>
);
// 把 time 维度的小时行聚合成趋势序列:>7 天按天汇总,否则按小时。
const buildTrend = (rows, rangeDays, field) => {
if (!rows || rows.length === 0) return [];
if (rangeDays > 7) {
const map = new Map();
rows.forEach((r) => {
const day = (r.name || '').slice(0, 10);
if (!day) return;
map.set(day, (map.get(day) || 0) + (r[field] || 0));
});
return Array.from(map, ([date, value]) => ({ date, value })).sort((a, b) =>
a.date < b.date ? -1 : 1,
);
}
return rows
.map((r) => ({ date: r.name || String(r.key), value: r[field] || 0 }))
.sort((a, b) => (a.date < b.date ? -1 : 1));
};
const sumField = (rows, field) =>
(rows || []).reduce((s, r) => s + (r[field] || 0), 0);
const localizeAnalyticsRows = (rows, dimension, t) =>
(rows || []).map((row) => {
let name = row.name;
if (row.key === '0') {
const zeroName = {
department: t('未分配部门'),
project: t('未绑定项目'),
member: t('未归属成员'),
token: t('未绑定令牌'),
}[dimension];
if (zeroName) name = zeroName;
} else if (dimension === 'member' && name === `成员#${row.key}`) {
name = `${t('成员')}#${row.key}`;
} else if (dimension === 'token' && name === `令牌#${row.key}`) {
name = `${t('令牌')}#${row.key}`;
}
return name === row.name ? row : { ...row, name };
});
// 多维用量分析面板(§5.6):经营看板视角——KPI+环比、消耗趋势折线、维度分布柱状、明细表。
// 仅 admin + analytics 特性开启时挂载(前端门控),后端接口仍 admin+feature 鉴权。
const OrgAnalyticsPanel = ({ orgId }) => {
const { t } = useTranslation();
const actualTheme = useActualTheme();
const isDarkMode = actualTheme === 'dark';
const chartTokens = useMemo(() => getChartTokens(isDarkMode), [isDarkMode]);
// 系列色跟随品牌 token:明暗切换(isDarkMode)与预设注入(theme-tokens-applied 事件)都会刷新
const [brandColors, setBrandColors] = useState(readBrandColors);
useEffect(() => {
const refresh = () => setBrandColors(readBrandColors());
refresh();
window.addEventListener('theme-tokens-applied', refresh);
return () => window.removeEventListener('theme-tokens-applied', refresh);
}, [isDarkMode]);
const [dimension, setDimension] = useState('model');
const [rangeDays, setRangeDays] = useState(7);
const [trendMetric, setTrendMetric] = useState('quota');
const [breakdownRows, setBreakdownRows] = useState([]);
const [trendRows, setTrendRows] = useState([]);
const [prevRows, setPrevRows] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
initVChartSemiTheme({ isWatchingThemeSwitch: true });
}, []);
const dimensions = useMemo(
() => [
{ label: t('模型'), value: 'model' },
{ label: t('项目'), value: 'project' },
{ label: t('部门'), value: 'department' },
{ label: t('成员'), value: 'member' },
{ label: t('令牌'), value: 'token' },
{ label: t('时间'), value: 'time' },
],
[t],
);
const dimLabel =
dimensions.find((d) => d.value === dimension)?.label || t('维度');
const fetchAll = useCallback(
async (fresh = false) => {
if (!orgId) return;
setLoading(true);
try {
// 按分钟归一化时间窗,保证 30s 缓存可命中,同时只遗漏当前未完成分钟。
const end = Math.floor(Date.now() / 60000) * 60;
const span = rangeDays * 86400;
const start = end - span;
const prevStart = start - span;
// 仅「刷新」按钮 fresh=true 时带 nocache 拿最新;维度/时间切换走 30s 缓存。
const nc = fresh ? '&nocache=1' : '';
const get = (dim, s, e) =>
API.get(
`/api/org/analytics?dimension=${dim}&start=${s}&end=${e}${nc}`,
{
headers: getOrgHeaders(orgId),
},
).then((r) => {
// 后端以 HTTP 200 返回 success:false(如特性关闭/越权)时,抛错让 catch 提示,
// 而非静默展示空图表,避免误以为「无数据」。
if (r.data && r.data.success === false) {
throw new Error(r.data.message || t('加载用量分析失败'));
}
return r.data?.data?.rows || [];
});
const reqs = [get('time', start, end), get('time', prevStart, start)];
if (dimension !== 'time') reqs.push(get(dimension, start, end));
const [timeRows, prevTimeRows, breakdown] = await Promise.all(reqs);
const localizedTimeRows = localizeAnalyticsRows(timeRows, 'time', t);
setTrendRows(localizedTimeRows);
setPrevRows(localizeAnalyticsRows(prevTimeRows, 'time', t));
setBreakdownRows(
dimension === 'time'
? localizedTimeRows
: localizeAnalyticsRows(breakdown || [], dimension, t),
);
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId, dimension, rangeDays, t],
);
useEffect(() => {
fetchAll(false);
}, [fetchAll]);
// KPI:本期/上期总量 + 环比;日均;Top1 消耗对象
const curQuota = useMemo(() => sumField(trendRows, 'quota'), [trendRows]);
const curReq = useMemo(
() => sumField(trendRows, 'request_count'),
[trendRows],
);
const prevQuota = useMemo(() => sumField(prevRows, 'quota'), [prevRows]);
const prevReq = useMemo(
() => sumField(prevRows, 'request_count'),
[prevRows],
);
const topRow = useMemo(() => {
if (dimension === 'time') return null;
return (
[...breakdownRows].sort((a, b) => (b.quota || 0) - (a.quota || 0))[0] ||
null
);
}, [breakdownRows, dimension]);
// 趋势折线 spec
const trendData = useMemo(
() =>
buildTrend(
trendRows,
rangeDays,
trendMetric === 'requests' ? 'request_count' : 'quota',
),
[trendRows, rangeDays, trendMetric],
);
const isMoney = trendMetric === 'quota';
const trendSpec = useMemo(() => {
if (!trendData.length) return null;
return {
type: 'area',
background: 'transparent',
data: [{ id: 'trend', values: trendData }],
xField: 'date',
yField: 'value',
point: { visible: trendData.length <= 60, size: 3 },
line: { style: { lineWidth: 2, stroke: brandColors.brand } },
area: {
style: {
fill: {
gradient: 'linear',
x0: 0,
y0: 0,
x1: 0,
y1: 1,
stops: [
{ offset: 0, color: brandColors.brand, opacity: 0.35 },
{ offset: 1, color: brandColors.brand, opacity: 0.02 },
],
},
},
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
dimension: {
visible: true,
content: [
{
key: () => (isMoney ? t('消耗') : t('请求数')),
value: (datum) =>
isMoney
? renderQuota(datum?.value || 0, 2)
: `${(datum?.value || 0).toLocaleString()} ${t('次')}`,
},
],
},
},
crosshair: {
xField: {
visible: true,
line: { visible: true, style: { stroke: chartTokens.axisLine } },
},
},
axes: [
{
orient: 'bottom',
label: { style: { angle: -45, fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'left',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => (isMoney ? renderQuota(v, 0) : Math.round(v)),
},
},
],
};
}, [trendData, isMoney, t, chartTokens, brandColors]);
// 维度分布柱状 spec(Top 10,横向)
const barData = useMemo(() => {
if (dimension === 'time') return [];
return [...breakdownRows]
.sort((a, b) => (b.quota || 0) - (a.quota || 0))
.slice(0, 10)
.map((r) => ({ name: r.name || '-', value: r.quota || 0 }));
}, [breakdownRows, dimension]);
const barSpec = useMemo(() => {
if (!barData.length) return null;
return {
type: 'bar',
background: 'transparent',
data: [{ id: 'bar', values: barData }],
direction: 'horizontal',
xField: 'value',
yField: 'name',
color: [brandColors.brand2],
barMaxWidth: 22,
label: {
visible: true,
position: 'right',
style: { fill: chartTokens.axisLabel },
formatMethod: (text, datum) =>
renderQuota(
datum && datum.value != null ? datum.value : Number(text) || 0,
2,
),
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => renderQuota(datum?.value || 0, 2),
},
],
},
},
axes: [
{
orient: 'left',
label: { style: { fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'bottom',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => renderQuota(v, 0),
},
},
],
};
}, [barData, chartTokens, brandColors]);
// 明细表:占比分母用「当前维度行的合计」而非时间维度总量,
// 保证表内各行占比之和恒为 100%(两者数学上应相等,但用自身合计更稳健)。
const breakdownTotal = useMemo(
() => sumField(breakdownRows, 'quota'),
[breakdownRows],
);
const columns = useMemo(
() => [
{ title: dimLabel, dataIndex: 'name', width: 200 },
{
title: t('消耗占比'),
render: (_, r) => {
const pct =
breakdownTotal > 0 ? ((r.quota || 0) / breakdownTotal) * 100 : 0;
return (
<div className='flex items-center gap-2'>
<Progress
percent={Math.round(pct)}
style={{ flex: 1 }}
stroke={brandColors.brand2}
showInfo={false}
/>
<span className='text-xs text-gray-500 whitespace-nowrap'>
{renderQuota(r.quota || 0, 2)} ({pct.toFixed(1)}%)
</span>
</div>
);
},
},
{ title: t('请求数'), dataIndex: 'request_count', width: 100 },
{
title: t('Token (入/出)'),
width: 160,
render: (_, r) =>
`${r.prompt_tokens || 0} / ${r.completion_tokens || 0}`,
},
],
[dimLabel, breakdownTotal, t, brandColors],
);
const rangeOptions = [
{ label: t('近 7 天'), value: 7 },
{ label: t('近 30 天'), value: 30 },
{ label: t('近 90 天'), value: 90 },
];
return (
<div className='space-y-4'>
{/* 控制区 */}
<OrgPanel>
<div className='flex flex-wrap items-center justify-between gap-3'>
<div className='flex items-center gap-2'>
<PieChart size={18} className='text-brand-deep' />
<Text strong>{t('企业用量分析')}</Text>
<Text type='tertiary' size='small'>
{t('趋势 · 结构 · 与消耗明细一致')}
</Text>
</div>
<div className='flex items-center gap-2'>
<Select
value={dimension}
onChange={setDimension}
optionList={dimensions}
style={{ width: 110 }}
/>
<Select
value={rangeDays}
onChange={setRangeDays}
optionList={rangeOptions}
style={{ width: 110 }}
/>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={() => fetchAll(true)}
>
{t('刷新')}
</Button>
</div>
</div>
{/* KPI + 环比 */}
<div className='grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4'>
<KpiCard
label={t('本期总消耗')}
value={renderQuota(curQuota, 2)}
sub={<DeltaBadge cur={curQuota} prev={prevQuota} t={t} />}
/>
<KpiCard
label={t('本期总请求')}
value={curReq.toLocaleString()}
sub={<DeltaBadge cur={curReq} prev={prevReq} t={t} />}
/>
<KpiCard
label={t('日均消耗')}
value={renderQuota(rangeDays > 0 ? curQuota / rangeDays : 0, 2)}
sub={
<span className='text-xs text-gray-400'>
{t('近 {{n}} 天均值', { n: rangeDays })}
</span>
}
/>
<KpiCard
label={t('消耗最高')}
value={topRow ? topRow.name : '-'}
sub={
topRow ? (
<span className='text-xs text-amber-500 inline-flex items-center gap-1'>
<Crown size={11} /> {renderQuota(topRow.quota || 0, 2)}
</span>
) : (
<span className='text-xs text-gray-400'>
{dimension === 'time' ? t('按时间维度无排名') : '-'}
</span>
)
}
/>
</div>
</OrgPanel>
{/* 消耗趋势折线 */}
<OrgPanel>
<div className='flex items-center justify-between mb-3'>
<div className='flex items-center gap-2'>
<TrendingUp size={16} className='text-brand-deep' />
<Text strong>{t('用量趋势')}</Text>
</div>
<Select
value={trendMetric}
onChange={setTrendMetric}
optionList={[
{ label: t('消耗'), value: 'quota' },
{ label: t('请求数'), value: 'requests' },
]}
style={{ width: 100 }}
size='small'
/>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : trendSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`trend-${actualTheme}`}
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 280 }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
{/* 维度分布柱状(time 维度不展示,趋势图已覆盖) */}
{dimension !== 'time' && (
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<BarChart3 size={16} className='text-brand-deep' />
<Text strong>{t('{{dim}}消耗分布', { dim: dimLabel })}</Text>
<Text type='tertiary' size='small'>
{t('Top 10')}
</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : barSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`bar-${actualTheme}`}
spec={barSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: Math.max(220, barData.length * 34 + 60) }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
)}
{/* 明细表 */}
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<Text strong>{t('{{dim}}明细', { dim: dimLabel })}</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : breakdownRows.length === 0 ? (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
) : (
<Table
columns={columns}
dataSource={breakdownRows}
rowKey='key'
pagination={
breakdownRows.length > 20
? { pageSize: 20, showSizeChanger: false }
: false
}
/>
)}
</OrgPanel>
</div>
);
};
export default OrgAnalyticsPanel;
@@ -0,0 +1,221 @@
/*
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 from 'react';
import { Button, Input, Radio, RadioGroup } from '@douyinfe/semi-ui';
import { Check, Image as ImageIcon, Palette, Type, UserRound } from 'lucide-react';
import OrgPanel from './OrgPanel';
import {
CARTOON_AVATAR_PRESETS,
USER_AVATAR_TYPES,
getCartoonAvatarDataUrl,
getInitialAvatarDataUrl,
} from '../../../helpers';
const AVATAR_TYPE_OPTIONS = [
{
value: USER_AVATAR_TYPES.PRESET,
label: '卡通形象',
desc: '从系统内置卡通头像中选择,适合默认展示',
icon: Palette,
},
{
value: USER_AVATAR_TYPES.INITIAL,
label: '姓名首字',
desc: '根据用户名自动生成简洁文字头像',
icon: Type,
},
{
value: USER_AVATAR_TYPES.CUSTOM,
label: '图片链接',
desc: '填写公网图片 URL,使用自己的头像',
icon: ImageIcon,
},
];
/*
* 企业中心头像设置区块。
* 与个人中心的 AvatarSection 分开:企业空间是实底卡片 + 品牌色体系(OrgPanel),
* 而非个人中心的毛玻璃 + 玫红渐变,避免颜色与整站主体色冲突。
*/
const OrgAvatarSection = ({
t,
userState,
avatarSettings,
handleAvatarSettingChange,
saveAvatarSettings,
saving,
}) => {
const username =
userState?.user?.display_name || userState?.user?.username || 'User';
const previewUrl =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
avatarSettings.customAvatarUrl
? avatarSettings.customAvatarUrl
: avatarSettings.avatarType === USER_AVATAR_TYPES.INITIAL
? getInitialAvatarDataUrl(username, 128)
: getCartoonAvatarDataUrl(avatarSettings.avatarPreset, 128);
const customAvatarInvalid =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
!avatarSettings.customAvatarUrl?.trim();
const activeDesc =
AVATAR_TYPE_OPTIONS.find(
(item) => item.value === avatarSettings.avatarType,
)?.desc || '';
return (
<OrgPanel
title={t('头像设置')}
subtitle={t('选择你在平台内展示的头像样式')}
icon={UserRound}
padding='p-5'
actions={
<Button
theme='solid'
loading={saving}
disabled={customAvatarInvalid}
onClick={saveAvatarSettings}
>
{t('保存头像')}
</Button>
}
>
<div className='grid grid-cols-1 xl:grid-cols-[240px_1fr] gap-5 items-start'>
{/* 实时预览:品牌色描边,实底卡面 */}
<div className='flex flex-col items-center text-center rounded-xl border border-[var(--border-subtle)] bg-brand/[0.04] px-5 py-6'>
<div className='relative mb-4'>
<img
src={previewUrl}
alt={t('头像预览')}
className='w-24 h-24 rounded-2xl object-cover ring-2 ring-brand/30'
/>
<span className='absolute -bottom-0.5 -right-0.5 h-5 w-5 rounded-full bg-emerald-500 border-2 border-[var(--surface-card)]' />
</div>
<div className='text-sm font-semibold text-[var(--text-primary)] truncate max-w-full'>
{username}
</div>
<div className='mt-1.5 text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
{t('该头像会同步展示在右上角用户入口和体验中心文本对话中。')}
</div>
<span className='mt-3 inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
{t('实时预览')}
</span>
</div>
{/* 头像类型 + 具体选择 */}
<div>
<label className='block text-xs font-medium text-[var(--text-secondary)] mb-2'>
{t('头像类型')}
</label>
<RadioGroup
type='button'
value={avatarSettings.avatarType}
onChange={(e) =>
handleAvatarSettingChange('avatarType', e.target.value)
}
className='!flex !flex-wrap !gap-2'
>
{AVATAR_TYPE_OPTIONS.map((option) => {
const Icon = option.icon;
return (
<Radio key={option.value} value={option.value}>
<span className='inline-flex items-center gap-1.5'>
<Icon size={14} />
{t(option.label)}
</span>
</Radio>
);
})}
</RadioGroup>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t(activeDesc)}
</p>
{avatarSettings.avatarType === USER_AVATAR_TYPES.PRESET && (
<div className='mt-5'>
<label className='block text-xs font-medium text-[var(--text-secondary)] mb-2.5'>
{t('选择卡通形象')}
</label>
<div className='grid grid-cols-2 sm:grid-cols-4 gap-3'>
{CARTOON_AVATAR_PRESETS.map((preset) => {
const selected = avatarSettings.avatarPreset === preset.id;
return (
<button
key={preset.id}
type='button'
onClick={() => {
handleAvatarSettingChange(
'avatarType',
USER_AVATAR_TYPES.PRESET,
);
handleAvatarSettingChange('avatarPreset', preset.id);
}}
className={`group relative flex flex-col items-center rounded-xl border p-3 transition-colors duration-150 ${
selected
? 'border-brand bg-brand/[0.06]'
: 'border-[var(--border-subtle)] bg-[var(--surface-card)] hover:border-brand/40'
}`}
>
<img
src={getCartoonAvatarDataUrl(preset.id, 96)}
alt={preset.label}
className='w-14 h-14 rounded-xl object-cover transition-transform group-hover:scale-105'
/>
<div className='mt-2 text-xs font-medium text-[var(--text-primary)] truncate max-w-full'>
{t(preset.label)}
</div>
{selected && (
<span className='absolute top-1.5 right-1.5 inline-flex h-4 w-4 items-center justify-center rounded-full bg-brand text-white'>
<Check size={11} strokeWidth={3} />
</span>
)}
</button>
);
})}
</div>
</div>
)}
{avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM && (
<div className='mt-5 rounded-xl border border-[var(--border-subtle)] bg-brand/[0.04] p-4'>
<Input
value={avatarSettings.customAvatarUrl}
onChange={(value) =>
handleAvatarSettingChange('customAvatarUrl', value)
}
placeholder={t(
'请输入图片 URL,例如 https://example.com/avatar.png',
)}
prefix={<ImageIcon size={15} className='text-brand ml-1' />}
showClear
/>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t('支持公网图片链接。若图片加载失败,会回退到默认卡通头像。')}
</p>
</div>
)}
</div>
</div>
</OrgPanel>
);
};
export default OrgAvatarSection;
@@ -0,0 +1,71 @@
/*
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 from 'react';
/**
* 企业中心签名渐变区(方案 A+ 签名层的核心组件)。
*
* 冲击力护栏:每页至多使用一次;品牌渐变全部走 --brand-* token,
* 随主题预设整套切换。亮色 = 品牌渐变实底;暗色 = midnight glow
* (深底 + 渐变辉光边缘),两套模式各有性格。
*
* @param {React.ReactNode} eyebrow 顶部小字(如时段问候/版块名)
* @param {React.ReactNode} title 大标题
* @param {React.ReactNode} [subtitle] 副文案
* @param {React.ReactNode} [actions] 右侧操作区
* @param {React.ReactNode} [children] 底部扩展槽(如 KPI 行)
* @param {string} [className]
*/
const OrgHero = ({ eyebrow, title, subtitle, actions, children, className = '' }) => (
<div
className={`relative overflow-hidden rounded-xl border border-brand/20 bg-gradient-to-br from-brand-from via-brand-via to-brand-to text-white shadow-[var(--elevation-md)] dark:border-white/10 dark:from-brand-via/30 dark:via-neutral-950 dark:to-neutral-950 ${className}`}
>
{/* 暗色 midnight glow:左上角品牌辉光,亮色下渐变实底本身就是签名,不再叠加 */}
<div className='pointer-events-none absolute -left-16 -top-24 hidden h-56 w-56 rounded-full bg-brand-from/25 blur-3xl dark:block' />
<div className='pointer-events-none absolute inset-x-0 top-0 hidden h-px bg-gradient-to-r from-transparent via-white/25 to-transparent dark:block' />
<div className='relative px-5 py-5 sm:px-6 sm:py-6'>
<div className='flex items-start justify-between gap-4 flex-wrap'>
<div className='min-w-0'>
{eyebrow && (
<div className='mb-1 text-xs font-medium text-white/75 dark:text-brand-from/90'>
{eyebrow}
</div>
)}
<h1 className='text-xl sm:text-2xl font-bold tracking-tight truncate'>
{title}
</h1>
{subtitle && (
<p className='mt-1 max-w-2xl text-sm text-white/70 dark:text-gray-400'>
{subtitle}
</p>
)}
</div>
{actions && (
<div className='org-hero-actions flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
{children && <div className='mt-4'>{children}</div>}
</div>
</div>
);
export default OrgHero;
@@ -0,0 +1,44 @@
/*
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 from 'react';
import { Modal } from '@douyinfe/semi-ui';
/*
* 企业中心统一弹窗包装。
*
* Semi Modal 渲染到 body 的 portal,企业中心的 .org-center 作用域样式
* 够不着它,必须通过 className 挂载精修样式(styles/org.css 的 .org-modal,
* 沿用 index.css 中 .notice-modal-enhanced 的先例模式)。
* 企业中心所有 <Modal> 一律使用本组件,不要直接引 Semi Modal。
*/
const withOrgClass = (className) =>
className ? `org-modal ${className}` : 'org-modal';
const OrgModal = ({ className, ...rest }) => (
<Modal className={withOrgClass(className)} {...rest} />
);
/* 命令式 API 同样注入 className(如 OrgModal.confirm({...})) */
['confirm', 'info', 'success', 'warning', 'error'].forEach((method) => {
OrgModal[method] = (config = {}) =>
Modal[method]({ ...config, className: withOrgClass(config.className) });
});
OrgModal.destroyAll = Modal.destroyAll;
export default OrgModal;
@@ -0,0 +1,101 @@
/*
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 { useTranslation } from 'react-i18next';
import { Input, Toast, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const { Text } = Typography;
/*
* 成员自助编辑昵称弹窗(PUT /api/org/me/profile)。
* 工作台 hero 与个人设置页共用;自管输入态,打开时以 currentName 初始化。
*/
const OrgNicknameModal = ({
visible,
onClose,
orgId,
currentName,
onSuccess,
}) => {
const { t } = useTranslation();
const [value, setValue] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (visible) {
setValue(currentName || '');
}
}, [visible, currentName]);
const submit = async () => {
const name = value.trim();
if (!name) {
showError(t('昵称不能为空'));
return;
}
setSaving(true);
try {
const res = await API.put(
'/api/org/me/profile',
{ display_name: name },
{ headers: { 'X-Org-Id': String(orgId) } },
);
if (res.data.success) {
Toast.success(t('昵称已更新'));
onClose();
onSuccess?.(name);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSaving(false);
}
};
return (
<OrgModal
title={t('编辑昵称')}
visible={visible}
onOk={submit}
onCancel={onClose}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
>
<Text type='tertiary' size='small'>
{t('昵称用于成员排行与用量分析中标识您,最多 20 个字符')}
</Text>
<Input
value={value}
onChange={setValue}
maxLength={20}
placeholder={t('请输入昵称')}
style={{ marginTop: 12 }}
onEnterPress={submit}
/>
</OrgModal>
);
};
export default OrgNicknameModal;
@@ -0,0 +1,57 @@
/*
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 from 'react';
/**
* 企业中心统一页面标题区。
* 所有企业页(/org/*)共用,保证标题字号、副标题、右侧操作区写法一致。
*
* @param {React.ComponentType} [icon] 可选的 lucide 图标组件(如 Wallet)
* @param {React.ReactNode} title 主标题
* @param {React.ReactNode} [subtitle] 副标题(一句话说明本页用途)
* @param {React.ReactNode} [actions] 右侧操作区(刷新/新建等按钮)
*/
const OrgPageHeader = ({ icon: Icon, title, subtitle, actions }) => (
<div className='mb-5 flex items-start justify-between gap-4 flex-wrap'>
<div className='flex items-center gap-3 min-w-0'>
{Icon && (
<div className='flex-shrink-0 inline-flex h-9 w-9 items-center justify-center rounded-lg bg-brand/10 text-brand'>
<Icon size={18} />
</div>
)}
<div className='min-w-0'>
<h1 className='text-lg sm:text-xl font-semibold tracking-tight text-[var(--text-primary)] truncate'>
{title}
</h1>
{subtitle && (
<p className='text-[13px] text-gray-500 dark:text-gray-400 mt-0.5 max-w-3xl'>
{subtitle}
</p>
)}
</div>
</div>
{actions && (
<div className='flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
);
export default OrgPageHeader;
@@ -0,0 +1,83 @@
/*
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 from 'react';
/**
* 企业中心统一卡片容器(方案 A+ 底盘层)。
* 实底表面 + 小圆角 + 1px 细边框 + 极轻海拔,靠边框分层,不用毛玻璃;
* 消除「裸表格」「Semi Card」「卡片表格」并存的不一致。
*
* @param {React.ReactNode} [title] 可选卡片标题(提供时渲染统一头部)
* @param {React.ReactNode} [subtitle] 标题下方副说明
* @param {React.ComponentType} [icon] 标题左侧 lucide 图标
* @param {React.ReactNode} [actions] 头部右侧操作区
* @param {string} [className] 追加类名
* @param {string} [padding] 内容内边距类,默认 'p-4';表格场景可传 'p-0' / 'p-2'
* @param {string} [bodyClassName] 内容容器追加类名
*/
const OrgPanel = ({
children,
title,
subtitle,
icon: Icon,
actions,
className = '',
padding = 'p-4',
bodyClassName = '',
}) => {
const hasHeader = title || actions;
return (
<div
className={`relative overflow-hidden rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-xs)] ${className}`}
>
{hasHeader && (
<div className='flex items-start justify-between gap-3 flex-wrap border-b border-[var(--border-subtle)] px-5 py-3.5'>
<div className='flex items-center gap-2.5 min-w-0'>
{Icon && (
<span className='inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand'>
<Icon size={16} />
</span>
)}
<div className='min-w-0'>
{title && (
<div className='text-sm font-semibold text-[var(--text-primary)] truncate'>
{title}
</div>
)}
{subtitle && (
<div className='mt-0.5 text-xs text-gray-500 dark:text-gray-400'>
{subtitle}
</div>
)}
</div>
</div>
{actions && (
<div className='flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
)}
<div className={`${padding} ${bodyClassName}`}>{children}</div>
</div>
);
};
export default OrgPanel;
@@ -0,0 +1,118 @@
/*
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 { useTranslation } from 'react-i18next';
import { Input, Toast, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const { Text } = Typography;
const EMPTY_FORM = { old: '', next: '', confirm: '' };
/*
* 成员自助改密弹窗(POST /api/org/account/change-password,方案 §12.8)。
* 工作台 hero 与个人设置页共用;打开时清空表单。
*/
const OrgPasswordModal = ({ visible, onClose }) => {
const { t } = useTranslation();
const [form, setForm] = useState(EMPTY_FORM);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (visible) {
setForm(EMPTY_FORM);
}
}, [visible]);
const submit = async () => {
const { old: oldPwd, next, confirm } = form;
if (!oldPwd || !next) {
showError(t('请输入原密码和新密码'));
return;
}
if (next !== confirm) {
showError(t('两次输入的新密码不一致'));
return;
}
// 与后端一致:8-20 位 + 至少两类字符
if (next.length < 8 || next.length > 20) {
showError(t('新密码长度需为 8-20 位'));
return;
}
setSaving(true);
try {
const res = await API.post('/api/org/account/change-password', {
old_password: oldPwd,
new_password: next,
});
if (res.data.success) {
Toast.success(t('密码已修改'));
onClose();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSaving(false);
}
};
return (
<OrgModal
title={t('修改密码')}
visible={visible}
onOk={submit}
onCancel={onClose}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
>
<Text type='tertiary' size='small'>
{t('新密码需为 8-20 位,且至少包含字母、数字、符号中的两类')}
</Text>
<Input
mode='password'
value={form.old}
onChange={(v) => setForm((prev) => ({ ...prev, old: v }))}
placeholder={t('原密码')}
style={{ marginTop: 12 }}
/>
<Input
mode='password'
value={form.next}
onChange={(v) => setForm((prev) => ({ ...prev, next: v }))}
placeholder={t('新密码')}
style={{ marginTop: 10 }}
/>
<Input
mode='password'
value={form.confirm}
onChange={(v) => setForm((prev) => ({ ...prev, confirm: v }))}
placeholder={t('确认新密码')}
style={{ marginTop: 10 }}
onEnterPress={submit}
/>
</OrgModal>
);
};
export default OrgPasswordModal;
@@ -0,0 +1,265 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Select, Toast, Tooltip } from '@douyinfe/semi-ui';
import { Layers } from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 解析分组字段:兼容 JSON 字符串/数组;为空表示该维度未配置分组。
const parseGroups = (raw) => {
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string' && raw.trim()) {
try {
const arr = JSON.parse(raw);
if (Array.isArray(arr)) return arr;
} catch {
/* ignore */
}
}
return [];
};
/**
* 部门/项目「模型 / 分组」限制配置入口(操作列复用组件)。
* 生效规则:成员个人、项目、部门按维度取交集,由后端鉴权链路裁决。
*
* props:
* - orgId
* - record: 行数据(含 model_limits_enabled / model_limits / groups)
* - apiBase: '/api/org/dept' 或 '/api/org/project'
* - scopeLabel: '部门' | '项目'(用于弹窗标题与文案)
* - onSaved: 保存成功后回调(刷新列表)
*/
const OrgScopedLimitButtons = ({ orgId, record, apiBase, scopeLabel, onSaved }) => {
const { t } = useTranslation();
const [modelModalVisible, setModelModalVisible] = useState(false);
const [orgModels, setOrgModels] = useState([]);
const [loadingModels, setLoadingModels] = useState(false);
const [selectedModels, setSelectedModels] = useState([]);
const [groupsModalVisible, setGroupsModalVisible] = useState(false);
const [orgGroups, setOrgGroups] = useState([]);
const [selectedGroups, setSelectedGroups] = useState([]);
const scopeName = record?.name || '';
const openModelModal = useCallback(async () => {
setSelectedModels(
record.model_limits_enabled && record.model_limits
? record.model_limits.split(',').filter(Boolean)
: [],
);
setModelModalVisible(true);
setLoadingModels(true);
try {
const res = await API.get('/api/org/models', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
setOrgModels((res.data.data || []).map((m) => ({ label: m, value: m })));
}
} catch {
/* ignore */
}
setLoadingModels(false);
}, [orgId, record]);
const openGroupsModal = useCallback(async () => {
setSelectedGroups(parseGroups(record?.groups));
setGroupsModalVisible(true);
try {
const res = await API.get('/api/org/info', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
const org = res.data.data?.organization || {};
let groups = [];
if (Array.isArray(org.groups)) {
groups = org.groups;
} else if (typeof org.groups === 'string' && org.groups.trim()) {
try {
groups = JSON.parse(org.groups);
} catch {
groups = [];
}
}
if (!groups.length && org.group) groups = [org.group];
setOrgGroups(groups.map((g) => ({ label: g, value: g })));
}
} catch {
/* ignore */
}
}, [orgId, record]);
const handleModelSave = useCallback(async () => {
const enabled = selectedModels.length > 0;
try {
const res = await API.put(
`${apiBase}/${record.id}/models`,
{ model_limits_enabled: enabled, model_limits: selectedModels.join(',') },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('模型限制已更新'));
setModelModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedModels, onSaved, t]);
const handleGroupsSave = useCallback(async () => {
try {
const res = await API.put(
`${apiBase}/${record.id}/groups`,
{ groups: selectedGroups },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('分组已更新'));
setGroupsModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedGroups, onSaved, t]);
const modelConfigured = record.model_limits_enabled;
const groupConfigured = parseGroups(record?.groups).length > 0;
return (
<>
<Tooltip content={t('设置该{{scope}}成员默认可用的模型范围(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
size='small'
theme='light'
type={modelConfigured ? 'primary' : 'tertiary'}
icon={<Layers size={14} />}
onClick={openModelModal}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip content={t('设置该{{scope}}成员默认可调用的分组(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
size='small'
theme='light'
type={groupConfigured ? 'primary' : 'tertiary'}
icon={<Layers size={14} />}
onClick={openGroupsModal}
>
{t('分组')}
</Button>
</Tooltip>
{/* 模型限制 Modal */}
<OrgModal
title={`${t(scopeLabel)}${t('模型限制')}${scopeName ? ` - ${scopeName}` : ''}`}
visible={modelModalVisible}
onOk={handleModelSave}
onCancel={() => setModelModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'限制该{{scope}}成员默认可使用的模型。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用模型取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可用模型')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedModels}
onChange={setSelectedModels}
optionList={orgModels}
loading={loadingModels}
placeholder={t('选择可用模型,留空则支持所有模型')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
{/* 可调用分组 Modal */}
<OrgModal
title={`${t(scopeLabel)}${t('可调用分组')}${scopeName ? ` - ${scopeName}` : ''}`}
visible={groupsModalVisible}
onOk={handleGroupsSave}
onCancel={() => setGroupsModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'设置该{{scope}}成员默认可调用的分组,只能从企业已配置的可用分组中选择。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用分组取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可调用分组')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedGroups}
onChange={setSelectedGroups}
optionList={orgGroups}
placeholder={t('选择可调用的分组')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
</>
);
};
export default OrgScopedLimitButtons;
@@ -0,0 +1,47 @@
/*
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 from 'react';
import { SideSheet } from '@douyinfe/semi-ui';
/*
* 企业中心统一侧滑面板包装。与 OrgModal 同理:SideSheet 走 portal,
* 通过 className 挂载 styles/org.css 的 .org-sidesheet 精修样式。
* 企业中心所有 <SideSheet> 一律使用本组件。
*
* 移动端适配:调用方普遍传固定像素宽(如技能详情的 720),在手机上会超出视口——
* Semi 把 width 作为内联样式打在 .semi-sidesheet-inner 上,面板 right:0 定位,
* 超出的部分被推到屏幕左侧外并裁掉。这里统一把像素宽钳到视口内。
*
* 用 min() 钳制而不是「窄屏一律 100%」:企业中心的移动端导航抽屉是
* placement='left' width={260} closable={false},一旦被强制拉满整个视口,
* 遮罩被完全盖住(点不到 maskClosable)、又没有关闭按钮,用户会被困在抽屉里。
* 钳制语义下 260px 本来就没超出视口,保持原样。
*
* 字符串宽度(如 '95%')原样透传;placement 也不拦截——Semi 对 top/bottom
* 侧滑本来就忽略 width(见 sideSheet/index.js 的 isVertical 分支)。
*/
const OrgSideSheet = ({ className, width, ...rest }) => (
<SideSheet
className={className ? `org-sidesheet ${className}` : 'org-sidesheet'}
width={typeof width === 'number' ? `min(${width}px, 100vw)` : width}
{...rest}
/>
);
export default OrgSideSheet;
@@ -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 from 'react';
import useCountUp from '../../../hooks/common/useCountUp';
/**
* 企业中心统一统计卡(KPI 卡,方案 A+ 底盘层)。
* 实底、紧凑、tabular-nums 等宽数字;图标品牌色浅底(不再渐变实底);
* 数值可选 count-up 滚动(签名层动效,respect prefers-reduced-motion)。
*
* @param {React.ComponentType} icon lucide 图标组件
* @param {React.ReactNode} label 标题(兼容旧用法的 title)
* @param {React.ReactNode} title label 的别名
* @param {React.ReactNode} value 主数值(直接展示)
* @param {number} [countTo] 数值 count-up 目标;提供时优先于 value 渲染
* @param {(n:number)=>React.ReactNode} [formatter] countTo 的格式化函数(默认 toLocaleString)
* @param {number} [decimals] countTo 保留小数位,默认 0
* @param {React.ReactNode} [hint] 副说明(兼容旧用法的 subtitle)
* @param {React.ReactNode} [subtitle] hint 的别名
* @param {React.ReactNode} [extra] 底部扩展槽(进度条等)
* @param {string} [tone] 'brand' | 'amber' | 'rose' | 'sky' | 'violet'
* @param {boolean} [danger] 危险态(红色强调),等价于 tone='rose'
* @param {boolean} [loading] 骨架加载态
* @param {boolean} [compact] 紧凑横向布局(用于密集 KPI 行)
* @param {string} [className] 追加类名
*/
// tone -> 图标浅底色/数值强调色。底盘层原则:色彩只用于图标与语义强调,不再渐变铺装饰。
const TONES = {
brand: {
icon: 'bg-brand/10 text-brand',
value: 'text-[var(--text-primary)]',
},
amber: {
icon: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
value: 'text-[var(--text-primary)]',
},
rose: {
icon: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',
value: 'text-rose-600 dark:text-rose-400',
},
sky: {
icon: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',
value: 'text-[var(--text-primary)]',
},
violet: {
icon: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',
value: 'text-[var(--text-primary)]',
},
};
const OrgStatCard = ({
icon: Icon,
label,
title,
value,
countTo,
formatter,
decimals = 0,
hint,
subtitle,
extra,
tone = 'brand',
danger = false,
loading = false,
compact = false,
className = '',
}) => {
const resolvedTone = danger ? 'rose' : tone;
const palette = TONES[resolvedTone] || TONES.brand;
const heading = label ?? title;
const sub = hint ?? subtitle;
const hasCountUp = typeof countTo === 'number';
const animated = useCountUp(hasCountUp ? countTo : 0, { decimals });
const displayValue = hasCountUp
? (formatter ? formatter(animated) : animated.toLocaleString())
: value;
return (
<div
className={`rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-xs)] ${compact ? 'p-3' : 'p-4'} ${className}`}
>
<div className={`flex ${compact ? 'items-center gap-3' : 'flex-col'}`}>
<div className={`flex items-center gap-2.5 ${compact ? '' : 'mb-2.5'}`}>
{Icon && (
<span
className={`inline-flex flex-shrink-0 items-center justify-center rounded-lg ${palette.icon} ${compact ? 'h-8 w-8' : 'h-9 w-9'}`}
>
<Icon size={compact ? 15 : 17} />
</span>
)}
{compact && (
<div className='flex min-w-0 flex-col'>
<span className='truncate text-xs font-medium text-gray-500 dark:text-gray-400'>
{heading}
</span>
{loading ? (
<span className='org-skeleton mt-1 h-4 w-16 rounded bg-gray-200 dark:bg-neutral-700' />
) : (
<span
className={`truncate text-sm font-semibold tabular-nums ${palette.value}`}
>
{displayValue}
</span>
)}
</div>
)}
{!compact && (
<span className='text-[13px] font-medium text-gray-500 dark:text-gray-400'>
{heading}
</span>
)}
</div>
{!compact &&
(loading ? (
<div className='space-y-2'>
<div className='org-skeleton h-7 w-24 rounded bg-gray-200 dark:bg-neutral-700' />
{(sub || extra) && (
<div className='org-skeleton h-4 w-28 rounded bg-gray-100 dark:bg-neutral-800' />
)}
</div>
) : (
<>
<div
className={`text-2xl font-semibold tracking-tight tabular-nums ${palette.value}`}
>
{displayValue}
</div>
{sub && (
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
{sub}
</div>
)}
{extra && <div className='mt-3'>{extra}</div>}
</>
))}
</div>
</div>
);
};
export default OrgStatCard;
@@ -0,0 +1,78 @@
/*
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 from 'react';
import { Spin } from '@douyinfe/semi-ui';
import { Inbox } from 'lucide-react';
/**
* 企业中心统一「加载中 / 空数据」占位块。
* 替代各页自造的空态 div 与零散的 Spin 写法,统一图标、文案排版与留白。
* 既可独立使用,也可作为 Semi Table 的 empty 槽。
*
* @param {boolean} [loading] 加载态:渲染居中 Spin
* @param {React.ComponentType} [icon] 空态图标(默认 Inbox)
* @param {React.ReactNode} [title] 空态主文案
* @param {React.ReactNode} [description] 空态副文案
* @param {React.ReactNode} [action] 空态操作区(如「新建」按钮)
* @param {string} [className] 追加类名
*/
const OrgStateBlock = ({
loading = false,
icon: Icon = Inbox,
title,
description,
action,
className = '',
}) => {
if (loading) {
return (
<div
className={`flex items-center justify-center py-16 ${className}`}
>
<Spin size='large' />
</div>
);
}
return (
<div
className={`flex flex-col items-center justify-center px-6 py-14 text-center ${className}`}
>
{/* 仪式感空状态:品牌浅底同心圆图标,空态也是被设计过的时刻 */}
<div className='mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-brand/5'>
<div className='inline-flex h-11 w-11 items-center justify-center rounded-full bg-brand/10 text-brand'>
<Icon size={22} strokeWidth={1.75} />
</div>
</div>
{title && (
<div className='text-sm font-semibold text-[var(--text-primary)]'>
{title}
</div>
)}
{description && (
<div className='mt-1 max-w-sm text-xs text-gray-500 dark:text-gray-400'>
{description}
</div>
)}
{action && <div className='mt-4'>{action}</div>}
</div>
);
};
export default OrgStateBlock;
@@ -0,0 +1,79 @@
/*
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 } from 'react';
import { TabPane, Tabs } from '@douyinfe/semi-ui';
import { useSearchParams } from 'react-router-dom';
/**
* 企业中心合并页通用的二级页签容器。
*
* 页签状态同步到 ?tab=,让旧路由的重定向(如 /org/skill-library →
* /org/skill-center?tab=library)与收藏链接可以直达指定页签。
* tabs 数组允许传 falsy 项(站点级模块开关关掉的页签),会被过滤;
* 只剩一个可见页签时不渲染页签条,直接铺内容,避免"单页签"的怪异观感。
*/
const OrgSubpageTabs = ({ tabs }) => {
const [searchParams, setSearchParams] = useSearchParams();
const visible = (tabs || []).filter(Boolean);
const requested = searchParams.get('tab');
const activeKey =
visible.length > 0 && visible.some((item) => item.key === requested)
? requested
: visible[0]?.key;
// ?tab= 指向不存在/已被模块开关关掉的页签时,回落到第一个可见页签并把 URL
// 一并纠正——否则地址栏还挂着无效的 tab,转发给同事仍会落到这里再回落一次,
// URL 与实际内容长期不符。hook 顺序要求这个 effect 在任何 early return 之前。
useEffect(() => {
if (!activeKey || requested === activeKey) return;
const next = new URLSearchParams(searchParams);
next.set('tab', activeKey);
setSearchParams(next, { replace: true });
}, [requested, activeKey, searchParams, setSearchParams]);
if (visible.length === 0) return null;
if (visible.length === 1) return visible[0].node;
return (
<div className='org-subpage-tabs'>
<Tabs
type='line'
// 必须惰性渲染:Semi 默认 lazyRender=false 会把所有 TabPane 的 children
// 立即挂载,于是两个子页会同时拉数、各自的 PageGuide 抽屉(SideSheet 走
// Portal,不受非激活 pane 的 display:none 约束)在首访时叠着弹出,
// 且两个 guideKey 一起被 markSeen,用户再也看不到本该出现的那一份。
// keepDOM 默认 true,切回已访问过的页签不会重新拉数。
lazyRender
activeKey={activeKey}
onChange={(key) => {
// 就地改写 tab,保留其余 query(子页面可能带自己的筛选参数);
// 直接传对象字面量会把整串 query 冲掉。
const next = new URLSearchParams(searchParams);
next.set('tab', key);
setSearchParams(next, { replace: true });
}}
>
{visible.map((item) => (
<TabPane key={item.key} tab={item.label} itemKey={item.key}>
{item.node}
</TabPane>
))}
</Tabs>
</div>
);
};
export default OrgSubpageTabs;
@@ -0,0 +1,107 @@
/*
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
*/
// 部门树构建工具:/api/org/dept 返回按 sort asc, id asc 排序的扁平列表,
// 这里按 parent_id 组装成 Semi Tree/TreeSelect 的 treeData。
/**
* buildDeptTreeData 扁平部门列表 → Semi treeData。
*
* @param {Array} depts 后端返回的部门列表(保持返回顺序即层内排序)
* @param {Object} options
* - disableNonLeaf 有子部门的节点不可选(成员主归属只允许挂末级部门)
* - excludeSubtreeOf 排除某部门自身及其整棵子树(编辑部门选上级时防环),
* 传含 id/path 的部门对象
* - disabledLabel 停用部门的后缀文案(外部传入以走 i18n)
*/
export function buildDeptTreeData(depts, options = {}) {
const {
disableNonLeaf = true,
excludeSubtreeOf = null,
disabledLabel = '已停用',
} = options;
const excluded = (d) =>
excludeSubtreeOf &&
(d.id === excludeSubtreeOf.id ||
(excludeSubtreeOf.path &&
d.path &&
d.path.startsWith(excludeSubtreeOf.path)));
const visible = (depts || []).filter((d) => !excluded(d));
const childCount = {};
visible.forEach((d) => {
childCount[d.parent_id] = (childCount[d.parent_id] || 0) + 1;
});
const idSet = new Set(visible.map((d) => d.id));
const nodeMap = {};
visible.forEach((d) => {
const stopped = d.status !== 1;
const nonLeafBlocked = disableNonLeaf && (childCount[d.id] || 0) > 0;
nodeMap[d.id] = {
label: stopped ? `${d.name}(${disabledLabel})` : d.name,
value: d.id,
key: String(d.id),
disabled: stopped || nonLeafBlocked,
children: [],
};
});
const roots = [];
visible.forEach((d) => {
const node = nodeMap[d.id];
if (d.parent_id && idSet.has(d.parent_id)) {
nodeMap[d.parent_id].children.push(node);
} else {
// 顶级部门;父节点缺失/被排除的孤儿也挂根兜底,避免整棵子树消失
roots.push(node);
}
});
// 叶子节点去掉空 children,避免渲染多余的展开箭头
Object.values(nodeMap).forEach((n) => {
if (n.children.length === 0) delete n.children;
});
return roots;
}
/**
* buildDeptFullNameMap 部门 id → 全路径名(如「华南事业部 / 研发中心 / 平台组」)。
* 基于 path 字段("/1/4/9/")解析祖先链;path 异常时退回自身名称。
*/
export function buildDeptFullNameMap(depts) {
const nameById = {};
(depts || []).forEach((d) => {
nameById[d.id] = d.name;
});
const map = {};
(depts || []).forEach((d) => {
const names = (d.path || '')
.split('/')
.filter(Boolean)
.map((seg) => nameById[Number(seg)])
.filter(Boolean);
map[d.id] = names.length ? names.join(' / ') : d.name;
});
return map;
}
/** hasChildDept 某部门当前是否存在子部门 */
export function hasChildDept(depts, deptId) {
return (depts || []).some((d) => d.parent_id === deptId);
}
@@ -0,0 +1,54 @@
/*
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
*/
// 企业中心统一状态语义色映射(Semi Tag color)。
// 统一各页面 Tag 颜色口径,避免「pending 一会 amber 一会 orange」「停用一会红一会灰」。
const ORG_STATUS_COLOR = {
// 审批 / 流程
pending: 'amber',
approved: 'green',
rejected: 'red',
canceled: 'grey',
expired: 'grey',
processing: 'blue',
// 启停 / 成员 / 令牌
active: 'green',
enabled: 'green',
normal: 'green',
disabled: 'grey',
inactive: 'grey',
offboarded: 'grey',
banned: 'red',
// 充值 / 支付
paid: 'green',
success: 'green',
failed: 'red',
// 额度
exhausted: 'grey',
};
/**
* 取企业状态对应的统一 Semi Tag 颜色。未知状态回退 grey。
* @param {string} status 状态键(小写)
* @returns {string} Semi Tag color
*/
export const orgStatusColor = (status) =>
ORG_STATUS_COLOR[String(status || '').toLowerCase()] || 'grey';
export default orgStatusColor;
@@ -0,0 +1,261 @@
/*
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, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { History } from 'lucide-react';
import { Button, Spin, Table, Tag, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
const PAGE_SIZE = 20;
const fmtTime = (v) => (v ? new Date(v * 1000).toLocaleString() : '-');
// 审计 target 前缀 → 人类可读标签(与后端 afterOrgRuleChange / applyOrgConfig* 的写入口径对应)
const AUDIT_TARGET_LABELS = [
['org_rule_create', '新增自定义规则'],
['org_rule_update', '修改自定义规则'],
['org_rule_delete', '删除自定义规则'],
['org_config_delete', '删除策略覆盖(恢复继承)'],
['org_config', '更新策略覆盖'],
];
const auditTargetLabel = (target, t) => {
for (const [prefix, label] of AUDIT_TARGET_LABELS) {
if (String(target || '').startsWith(prefix)) {
const suffix = String(target).slice(prefix.length);
return `${t(label)}${suffix ? ` (${suffix})` : ''}`;
}
}
return target || '-';
};
// OrgDsChanges 变更记录子 tab:本企业提交的审批请求 + 与本企业相关的配置/规则变更审计。
// 只读留痕,供合规举证;两个分区独立分页(复用同一后端端点的对应分区)。
const OrgDsChanges = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [requests, setRequests] = useState([]);
const [reqPage, setReqPage] = useState(1);
const [reqTotal, setReqTotal] = useState(0);
const [audits, setAudits] = useState([]);
const [auditPage, setAuditPage] = useState(1);
const [auditTotal, setAuditTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const fetchChanges = useCallback(
async ({ reqP = 1, auditP = 1, section = 'both' } = {}) => {
setLoading(true);
setLoadError(false);
try {
// 后端同一端点按 page 同步分页两个分区;此处按需各取所需分区,互不干扰。
const load = async (p) => {
const res = await API.get(
`/api/org/data-security/changes?page=${p}&page_size=${PAGE_SIZE}`,
{ headers },
);
if (!res.data.success) {
throw new Error(res.data.message || t('读取变更记录失败'));
}
return res.data.data;
};
if (section === 'both') {
// 两分区页码可能不同(各自独立翻页后重试):并发取两页、各取所需分区,
// 避免"重试"退化成只刷其中一个分区(review R38 发现)。
const [dReq, dAudit] = await Promise.all([
load(reqP),
auditP === reqP ? null : load(auditP),
]);
const auditSource = dAudit || dReq;
setRequests(dReq.requests?.items || []);
setReqTotal(dReq.requests?.total || 0);
setReqPage(reqP);
setAudits(auditSource.audits?.items || []);
setAuditTotal(auditSource.audits?.total || 0);
setAuditPage(auditP);
} else if (section === 'requests') {
const d = await load(reqP);
setRequests(d.requests?.items || []);
setReqTotal(d.requests?.total || 0);
setReqPage(reqP);
} else {
const d = await load(auditP);
setAudits(d.audits?.items || []);
setAuditTotal(d.audits?.total || 0);
setAuditPage(auditP);
}
} catch (err) {
setLoadError(true);
// axios 错误已由全局拦截器弹出中文提示;业务失败(load 内 throw)在此弹出
if (err?.name !== 'AxiosError') showError(err);
} finally {
setLoading(false);
}
},
[headers, t],
);
useEffect(() => {
fetchChanges();
}, [fetchChanges]);
const STATUS_TAG = {
pending: <Tag color='amber'>{t('待审批')}</Tag>,
approved: <Tag color='green'>{t('已通过')}</Tag>,
rejected: <Tag color='grey'>{t('已驳回')}</Tag>,
};
const requestColumns = [
{
title: t('摘要'),
dataIndex: 'summary',
render: (v) => <span className='break-all'>{v}</span>,
},
{
title: t('状态'),
dataIndex: 'status',
width: 100,
render: (v) => STATUS_TAG[v] || v,
},
{ title: t('提交人'), dataIndex: 'maker_name', width: 120 },
{
title: t('审批意见'),
dataIndex: 'review_comment',
render: (v) => (v ? <span className='break-all'>{v}</span> : '-'),
},
{
title: t('提交时间'),
dataIndex: 'created_at',
render: fmtTime,
width: 170,
},
{
title: t('审批时间'),
dataIndex: 'reviewed_at',
render: fmtTime,
width: 170,
},
];
const auditColumns = [
{ title: t('时间'), dataIndex: 'created_at', render: fmtTime, width: 170 },
{
title: t('操作人'),
dataIndex: 'operator_name',
width: 120,
// 平台侧操作者不下发真实账号名(后端置空 + operator_is_platform 标记)
render: (v, row) => (row.operator_is_platform ? t('平台管理员') : v),
},
{
title: t('变更项'),
dataIndex: 'target',
render: (v) => auditTargetLabel(v, t),
},
{
title: t('变更内容'),
render: (_, row) => {
const oldV = row.old_value || '';
const newV = row.new_value || '';
if (!oldV && !newV) return '-';
return (
<Typography.Text size='small' className='font-mono break-all'>
{oldV || '∅'} → {newV || '∅'}
</Typography.Text>
);
},
},
];
return (
<OrgPanel
icon={History}
title={t('变更记录')}
subtitle={t('本企业数据安全配置与规则的变更留痕(只读,供合规举证)')}
padding='p-4'
className='mt-3 mb-2'
actions={
loadError && (
<Button
size='small'
type='danger'
theme='light'
onClick={() => fetchChanges({ reqP: reqPage, auditP: auditPage })}
>
{t('加载失败,点击重试')}
</Button>
)
}
>
<Spin spinning={loading}>
<div className='text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
{t('审批请求')}
</div>
<Table
columns={requestColumns}
dataSource={requests}
rowKey='id'
size='small'
scroll={{ x: 'max(100%, 900px)' }}
empty={
<span className='text-sm text-gray-400'>
{t(
'暂无审批请求。平台开启变更审批后,本企业提交的策略变更会在此排队并显示审批结果。',
)}
</span>
}
pagination={{
currentPage: reqPage,
pageSize: PAGE_SIZE,
total: reqTotal,
onPageChange: (p) =>
fetchChanges({ reqP: p, auditP: auditPage, section: 'requests' }),
}}
/>
<div className='text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 mt-5'>
{t('生效变更审计')}
</div>
<Table
columns={auditColumns}
dataSource={audits}
rowKey='id'
size='small'
scroll={{ x: 'max(100%, 760px)' }}
empty={
<span className='text-sm text-gray-400'>
{t('暂无变更审计。策略覆盖或自定义规则实际生效后会在此留痕。')}
</span>
}
pagination={{
currentPage: auditPage,
pageSize: PAGE_SIZE,
total: auditTotal,
onPageChange: (p) =>
fetchChanges({ reqP: reqPage, auditP: p, section: 'audits' }),
}}
/>
</Spin>
</OrgPanel>
);
};
export default OrgDsChanges;
@@ -0,0 +1,274 @@
/*
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 { Activity } from 'lucide-react';
import { Button, Select, Spin, Switch, Table, Tag } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
const PAGE_SIZE = 20;
const WINDOW_OPTIONS = [
{ value: 24, label: '近 24 小时' },
{ value: 24 * 7, label: '近 7 天' },
{ value: 24 * 30, label: '近 30 天' },
];
const fmtTime = (v) => (v ? new Date(v * 1000).toLocaleString() : '-');
// OrgDsHitLogs 命中审计子 tab:本企业口径的聚合统计 + 命中明细(仅元信息,绝无原文)。
const OrgDsHitLogs = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [stats, setStats] = useState(null);
// 统计失败必须显式呈现:合规巡检语境下"静默显示 0"会被当成真实结论
const [statsError, setStatsError] = useState(false);
const [windowHours, setWindowHours] = useState(24);
const [logs, setLogs] = useState([]);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const [onlySensitive, setOnlySensitive] = useState(false);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
// 请求代次守卫:快速切换时间窗/筛选/翻页时,旧请求的迟到响应不得覆盖新状态——
// 否则统计牌标着"近 30 天"显示的却是 24 小时的迟到数据(R39 修复)。
const statsSeqRef = useRef(0);
const logsSeqRef = useRef(0);
// 记录最后一次尝试的页码:翻页失败后"重试"应重放失败的那次动作,而不是回到上次成功页
const lastAttemptedPageRef = useRef(1);
const fetchStats = useCallback(
async (hours) => {
const seq = ++statsSeqRef.current;
try {
const res = await API.get(
`/api/org/data-security/metrics?since_hours=${hours}`,
{ headers },
);
if (seq !== statsSeqRef.current) return;
if (res.data.success) {
setStats(res.data.data);
setStatsError(false);
} else {
setStatsError(true);
showError(res.data.message || t('读取统计失败'));
}
} catch (err) {
if (seq !== statsSeqRef.current) return;
setStatsError(true);
// axios 错误已由全局拦截器弹出中文提示,这里只兜非网络类异常
if (err?.name !== 'AxiosError') showError(err);
}
},
[headers, t],
);
const fetchLogs = useCallback(
async (p, sensitiveOnly) => {
const seq = ++logsSeqRef.current;
lastAttemptedPageRef.current = p;
setLoading(true);
setLoadError(false);
try {
const res = await API.get(
`/api/org/data-security/logs?page=${p}&page_size=${PAGE_SIZE}&only_sensitive=${sensitiveOnly}`,
{ headers },
);
if (seq !== logsSeqRef.current) return;
if (res.data.success) {
setLogs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
setPage(p);
} else {
setLoadError(true);
showError(res.data.message || t('加载命中审计失败'));
}
} catch (err) {
if (seq !== logsSeqRef.current) return;
setLoadError(true);
if (err?.name !== 'AxiosError') showError(err);
} finally {
if (seq === logsSeqRef.current) setLoading(false);
}
},
[headers, t],
);
useEffect(() => {
fetchStats(windowHours);
}, [fetchStats, windowHours]);
useEffect(() => {
fetchLogs(1, onlySensitive);
}, [fetchLogs, onlySensitive]);
const w = stats?.window_stats || {};
// 统计未就绪/失败时显示 '-' 而非 0:0 是一个有含义的合规结论,不能由失败态冒充
const statValue = (v) => (statsError || stats === null ? '-' : (v ?? 0));
const statTiles = [
{ label: t('审计记录数'), value: statValue(w.total) },
{
label: t('命中敏感 PII 请求'),
value: statValue(w.sensitive_hits),
danger: true,
},
{ label: t('命中总次数'), value: statValue(w.total_hits) },
{ label: t('旁路请求'), value: statValue(w.bypassed_count) },
{
label: t('fail_open 请求'),
value: statValue(w.fail_open_count),
danger: true,
},
];
const columns = [
{ title: t('时间'), dataIndex: 'created_at', render: fmtTime, width: 170 },
{ title: t('用户'), dataIndex: 'user_id', width: 80 },
{
title: t('模型'),
dataIndex: 'model',
render: (v) => <span className='break-all'>{v || '-'}</span>,
},
{ title: t('命中数'), dataIndex: 'hit_count', width: 80 },
{
title: t('敏感 PII'),
dataIndex: 'has_sensitive_pii',
width: 90,
render: (v) =>
v ? <Tag color='red'>{t('是')}</Tag> : <Tag>{t('否')}</Tag>,
},
{
title: t('豁免'),
dataIndex: 'bypassed',
width: 80,
render: (v) => (v ? <Tag color='orange'>{t('是')}</Tag> : '-'),
},
{
title: 'fail_open',
dataIndex: 'fail_open',
width: 100,
render: (v) => (v ? <Tag color='red'>fail_open</Tag> : '-'),
},
{ title: t('原文长度'), dataIndex: 'content_length', width: 90 },
{ title: t('耗时(ms)'), dataIndex: 'desensitize_ms', width: 90 },
];
return (
<OrgPanel
icon={Activity}
title={t('命中审计')}
subtitle={t('仅记录规则命中统计与元信息,绝不存储请求原文')}
padding='p-4'
className='mt-3 mb-2'
actions={
<Select
value={windowHours}
onChange={setWindowHours}
optionList={WINDOW_OPTIONS.map((o) => ({ ...o, label: t(o.label) }))}
size='small'
style={{ width: 130 }}
/>
}
>
<div className='grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 mb-4'>
{statTiles.map((s) => (
<div
key={s.label}
className='rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] px-3 py-2.5'
>
<div className='text-xs text-gray-500 dark:text-gray-400 truncate'>
{s.label}
</div>
<div
className={`mt-1 text-xl font-semibold ${
s.danger && Number(s.value) > 0
? 'text-red-500'
: 'text-[var(--text-primary)]'
}`}
style={{ fontVariantNumeric: 'tabular-nums' }}
>
{s.value}
</div>
</div>
))}
</div>
<div className='flex items-center justify-between gap-3 mb-3 flex-wrap'>
<div className='flex items-center gap-2'>
<Switch
checked={onlySensitive}
onChange={setOnlySensitive}
size='small'
/>
<span className='text-sm text-gray-600 dark:text-gray-300'>
{t('仅看命中敏感 PII 的请求')}
</span>
</div>
{(loadError || statsError) && (
<Button
size='small'
type='danger'
theme='light'
onClick={() => {
if (statsError) fetchStats(windowHours);
if (loadError)
fetchLogs(lastAttemptedPageRef.current, onlySensitive);
}}
>
{t('加载失败,点击重试')}
</Button>
)}
</div>
<Spin spinning={loading}>
<Table
columns={columns}
dataSource={logs}
rowKey='id'
size='small'
scroll={{ x: 'max(100%, 980px)' }}
empty={
<span className='text-sm text-gray-400'>
{loadError
? t('加载失败,点击上方按钮重试')
: t(
'暂无命中记录。平台开启脱敏且本企业流量命中规则后,这里会出现审计明细。',
)}
</span>
}
pagination={{
currentPage: page,
pageSize: PAGE_SIZE,
total,
onPageChange: (p) => fetchLogs(p, onlySensitive),
}}
/>
</Spin>
</OrgPanel>
);
};
export default OrgDsHitLogs;
@@ -0,0 +1,460 @@
/*
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 { ShieldCheck } from 'lucide-react';
import { Button, Select, Toast } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
import OrgModal from '../components/OrgModal';
// 策略枚举与控制台 DataSecuritySetting 保持一致(同一后端校验 ValidateConfigValue)
const MODE_OPTIONS = [
{ value: 'detect_only', label: '仅检测告警' },
{ value: 'standard', label: '标准脱敏(可逆占位符)' },
{ value: 'strict', label: '严格不可逆' },
{ value: 'block', label: '阻断模式' },
];
const FAILURE_OPTIONS = [
{ value: 'fail_closed', label: 'fail_closed(失败即拒绝,推荐)' },
{ value: 'fail_open', label: 'fail_open(失败透传,高风险)' },
];
const MULTIMODAL_OPTIONS = [
{ value: 'warn', label: 'warn(放行+对文本脱敏+告警)' },
{ value: 'reject', label: 'reject(拒绝含图片/音频请求)' },
{
value: 'passthrough_with_audit',
label: 'passthrough_with_audit(放行+审计)',
},
];
const SENSITIVE_OPTIONS = [
{ value: 'allow', label: 'allow(标准脱敏后放行,用户无感)' },
{ value: 'require_consent', label: 'require_consent(需用户单独同意)' },
{ value: 'block_sensitive', label: 'block_sensitive(直接拒绝)' },
{ value: 'strict_anonymize', label: 'strict_anonymize(强制不可逆)' },
];
const ANTI_EVASION_OPTIONS = [
{ value: 'true', label: '功能已开启' },
{ value: 'false', label: '功能已关闭' },
];
const POLICY_RANKS = {
mode: { detect_only: 0, standard: 1, strict: 2, block: 3 },
failure_strategy: { fail_open: 0, fail_closed: 1 },
multimodal_strategy: { passthrough_with_audit: 0, warn: 1, reject: 2 },
};
const SENSITIVE_ALLOWED = {
allow: ['allow', 'require_consent', 'strict_anonymize', 'block_sensitive'],
require_consent: ['require_consent', 'block_sensitive'],
strict_anonymize: ['strict_anonymize', 'block_sensitive'],
block_sensitive: ['block_sensitive'],
};
const POLICY_FIELDS = [
{
key: 'mode',
label: '脱敏模式',
options: MODE_OPTIONS,
hint: '命中敏感信息时如何处理请求内容',
},
{
key: 'failure_strategy',
label: '失败处理策略',
options: FAILURE_OPTIONS,
hint: '脱敏引擎自身出错时放行还是拒绝',
},
{
key: 'multimodal_strategy',
label: '多模态内容策略',
options: MULTIMODAL_OPTIONS,
hint: '请求携带图片/音频等无法扫描的内容时的处理方式',
},
{
key: 'sensitive_strategy',
label: '敏感个人信息策略',
options: SENSITIVE_OPTIONS,
hint: '命中身份证号、银行卡号等敏感级个人信息时的处理方式(脱敏模式为 detect_only 时仅记录、不拦截)',
},
{
key: 'anti_evasion',
label: '反绕过检测',
options: ANTI_EVASION_OPTIONS,
hint: '对 base64/hex 编码及全角变形内容解码后重新扫描',
isBool: true,
},
];
const DEFAULT_DRAFT = {
mode: '',
failure_strategy: '',
multimodal_strategy: '',
sensitive_strategy: '',
anti_evasion: '',
};
// OrgDsPolicy 企业自助数据安全「策略配置」子 tab(自 OrgDataSecurity 平移,行为不变)。
// 空值=继承平台默认;仅覆盖策略项,脱敏总开关等仍由平台把控。
const OrgDsPolicy = ({ orgId, isSuperAdmin, refreshVersion = 0 }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [draft, setDraft] = useState({ ...DEFAULT_DRAFT });
const [globalCfg, setGlobalCfg] = useState(null);
const [platformEnabled, setPlatformEnabled] = useState(true);
const [canEdit, setCanEdit] = useState(false);
// 待平台审批的变更(后端在存在 pending 时会拒绝新的写操作,此处同步锁定 UI)
const [pendingRequest, setPendingRequest] = useState(null);
// 配置成功加载前禁用编辑:空表单一旦可保存,会把已有覆盖冲掉(与提示词采集同款防护)
const [loaded, setLoaded] = useState(false);
const [loadError, setLoadError] = useState(false);
// 请求代次:切换企业后,旧企业迟到的响应不得覆盖新企业状态
const seqRef = useRef(0);
const orgIdRef = useRef(orgId);
orgIdRef.current = orgId;
const [saving, setSaving] = useState(false);
const [resetting, setResetting] = useState(false);
// 服务端是否已存在覆盖行(区别于 hasOverride 的"草稿有定制项"):
// 无行且草稿全继承时禁用保存,防止落一条全空覆盖行;恢复默认按行存在性启用,
// 否则全空行会因 hasOverride=false 而无法从企业侧清除(R41)。
const [overrideRowExists, setOverrideRowExists] = useState(false);
// loadError 必须参与锁定:首载成功后 refetch 失败时,横幅宣称"编辑已禁用"
// 而 !loaded 已不成立,若不锁会出现提示与实态矛盾、且可把陈旧草稿保存回去
// 覆盖审批/平台侧刚落地的新配置(R40 平台侧同款修复的企业侧补齐,R41)。
// saving/resetting 互锁:保存与恢复默认不得并发(终态取决于落库顺序)。
const fieldsLocked =
isSuperAdmin ||
!loaded ||
loadError ||
!canEdit ||
!!pendingRequest ||
saving ||
resetting;
const hasOverride = POLICY_FIELDS.some((f) => draft[f.key] !== '');
useEffect(() => {
seqRef.current += 1;
setDraft({ ...DEFAULT_DRAFT });
setGlobalCfg(null);
setCanEdit(false);
setPendingRequest(null);
setLoaded(false);
setLoadError(false);
setSaving(false);
setResetting(false);
setOverrideRowExists(false);
return () => {
seqRef.current += 1;
};
}, [orgId]);
const fetchConfig = useCallback(
async ({ silent = false } = {}) => {
const requestOrgId = orgId;
const seq = seqRef.current;
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current) return;
if (!silent) setLoadError(false);
try {
const res = await API.get('/api/org/data-security/config', {
headers: { 'X-Org-Id': String(requestOrgId) },
});
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current) return;
if (res.data.success && res.data.data) {
const d = res.data.data;
if (Number(d.org_id) !== Number(requestOrgId)) {
throw new Error(t('数据安全配置响应的企业标识不匹配'));
}
setPlatformEnabled(!!d.platform_enabled);
setCanEdit(d.can_edit !== false);
setPendingRequest(d.pending_request || null);
setGlobalCfg(d.global || null);
setDraft({
mode: d.override?.mode || '',
failure_strategy: d.override?.failure_strategy || '',
multimodal_strategy: d.override?.multimodal_strategy || '',
sensitive_strategy: d.override?.sensitive_strategy || '',
anti_evasion: d.override?.anti_evasion || '',
});
setOverrideRowExists(
!!d.override &&
(Number(d.override.updated_at) > 0 ||
POLICY_FIELDS.some((f) => (d.override[f.key] || '') !== '')),
);
setLoadError(false);
setLoaded(true);
} else {
if (!silent) {
setLoadError(true);
showError(res.data.message || t('数据安全配置加载失败'));
}
}
} catch (err) {
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current) return;
if (!silent) {
setLoadError(true);
// 网络层错误由全局拦截器统一提示,这里只补业务层错误,避免双 toast
// 且直显英文 axios 原文(与其余子页同一约定,R41)。
if (err?.name !== 'AxiosError') showError(err.message);
}
}
},
[orgId, t],
);
useEffect(() => {
fetchConfig();
}, [fetchConfig, refreshVersion]);
useEffect(() => {
if (!pendingRequest) return undefined;
const timer = window.setInterval(
() => fetchConfig({ silent: true }),
10000,
);
return () => window.clearInterval(timer);
}, [fetchConfig, pendingRequest]);
// 「继承平台默认」选项上内联展示平台当前值,管理员无需跳出页面即可判断是否需要定制
const inheritLabel = useCallback(
(field) => {
if (!globalCfg) return t('继承平台默认');
let current;
if (field.isBool) {
current = globalCfg[field.key] ? t('功能已开启') : t('功能已关闭');
} else {
current = field.options.find(
(o) => o.value === globalCfg[field.key],
)?.label;
current = current ? t(current) : globalCfg[field.key];
}
return `${t('继承平台默认')}(${t('当前')}:${current})`;
},
[globalCfg, t],
);
const isOptionAllowed = useCallback(
(field, value) => {
if (!globalCfg) return true;
const globalValue = globalCfg[field.key];
if (field.key === 'anti_evasion') {
return !globalValue || value === 'true';
}
if (field.key === 'sensitive_strategy') {
return (SENSITIVE_ALLOWED[globalValue] || []).includes(value);
}
const ranks = POLICY_RANKS[field.key];
return ranks?.[value] >= ranks?.[globalValue];
},
[globalCfg],
);
const handleSave = useCallback(async () => {
if (fieldsLocked) return;
const requestOrgId = orgId;
const seq = seqRef.current;
setSaving(true);
try {
const res = await API.put('/api/org/data-security/config', draft, {
headers,
});
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current) return;
if (res.data.success) {
Toast.success(
res.data.data?.request_id
? t('已提交平台审批,审批通过后生效')
: t('配置已保存'),
);
fetchConfig();
} else {
showError(res.data.message);
}
} catch (err) {
if (requestOrgId === orgIdRef.current && seq === seqRef.current) {
if (err?.name !== 'AxiosError') showError(err.message);
}
} finally {
if (requestOrgId === orgIdRef.current && seq === seqRef.current) {
setSaving(false);
}
}
}, [fieldsLocked, orgId, draft, headers, t, fetchConfig]);
const handleReset = useCallback(() => {
if (fieldsLocked) return;
const requestOrgId = orgId;
const seq = seqRef.current;
OrgModal.confirm({
title: t('恢复继承平台默认'),
content: t('将清除本企业的全部数据安全定制项,恢复为继承平台默认策略。'),
onOk: async () => {
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current) return;
setResetting(true);
try {
const res = await API.delete('/api/org/data-security/config', {
headers,
});
if (requestOrgId !== orgIdRef.current || seq !== seqRef.current)
return;
if (res.data.success) {
Toast.success(
res.data.data?.request_id
? t('已提交平台审批,审批通过后生效')
: t('已恢复继承平台默认'),
);
fetchConfig();
} else {
showError(res.data.message);
}
} catch (err) {
if (requestOrgId === orgIdRef.current && seq === seqRef.current) {
if (err?.name !== 'AxiosError') showError(err.message);
}
} finally {
if (requestOrgId === orgIdRef.current && seq === seqRef.current) {
setResetting(false);
}
}
},
});
}, [fieldsLocked, orgId, headers, t, fetchConfig]);
return (
<OrgPanel
icon={ShieldCheck}
title={t('数据安全策略')}
padding='p-5'
className='mt-3 mb-2'
>
<p className='text-sm text-gray-500 dark:text-gray-400 mb-4'>
{t(
'为本企业定制敏感信息脱敏策略,未定制的项自动继承平台默认值。脱敏总开关由平台统一管理;此处仅可在平台开启脱敏的前提下调整本企业的策略档位。',
)}
</p>
{!platformEnabled && loaded && (
<div className='mb-4 px-3 py-2 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900/40'>
<span className='text-sm text-amber-600 dark:text-amber-400'>
{t('平台脱敏功能当前未开启,以下配置将在平台开启后自动生效。')}
</span>
</div>
)}
{!!pendingRequest && (
<div className='mb-4 px-3 py-2 rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/40'>
<span className='text-sm text-blue-600 dark:text-blue-400'>
{t('有一条变更正在等待平台审批,期间无法再次修改。')}
{pendingRequest.created_at
? `(${t('提交于')} ${new Date(pendingRequest.created_at * 1000).toLocaleString()})`
: ''}
</span>
</div>
)}
{loaded && !canEdit && (
<div className='mb-4 px-3 py-2 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900/40'>
<span className='text-sm text-amber-600 dark:text-amber-400'>
{t(
'平台已为本企业下发专属数据安全策略。该策略只能由平台管理员修改,企业侧仅可查看。',
)}
</span>
</div>
)}
{loadError && (
<div className='flex items-center justify-between gap-3 mb-4 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900/40'>
<span className='text-sm text-red-600 dark:text-red-400'>
{t('配置加载失败,为防止误覆盖已有配置,编辑已禁用。')}
</span>
<Button
size='small'
type='danger'
theme='light'
onClick={() => fetchConfig()}
>
{t('重试')}
</Button>
</div>
)}
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
{POLICY_FIELDS.map((field) => (
<div key={field.key}>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{t(field.label)}
</label>
<Select
value={draft[field.key]}
onChange={(v) => setDraft({ ...draft, [field.key]: v })}
optionList={[
{ value: '', label: inheritLabel(field) },
...field.options.map((o) => ({
...o,
label: t(o.label),
disabled: !isOptionAllowed(field, o.value),
})),
]}
style={{ width: '100%' }}
disabled={fieldsLocked}
/>
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
{t(field.hint)} {t('企业策略只能保持或收紧平台安全基线。')}
</p>
</div>
))}
</div>
{!isSuperAdmin && (
<div className='mt-5 flex flex-wrap items-center justify-end gap-2'>
<Button
type='tertiary'
loading={resetting}
disabled={(fieldsLocked && !resetting) || !overrideRowExists}
onClick={handleReset}
>
{t('恢复继承平台默认')}
</Button>
<Button
type='primary'
loading={saving}
disabled={
(fieldsLocked && !saving) || (!hasOverride && !overrideRowExists)
}
onClick={handleSave}
>
{t('保存配置')}
</Button>
</div>
)}
<p className='text-xs text-gray-400 dark:text-gray-500 mt-3'>
{t(
'定制项即时生效(多节点约 1 分钟内同步);平台开启变更审批时,保存将提交平台管理员复核后生效。',
)}
</p>
</OrgPanel>
);
};
export default OrgDsPolicy;
@@ -0,0 +1,405 @@
/*
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 { ListChecks, ShieldPlus } from 'lucide-react';
import {
Button,
Input,
Popconfirm,
Select,
Spin,
Switch,
Table,
Tag,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
import OrgModal from '../components/OrgModal';
const EMPTY_RULE_DRAFT = {
name: '',
category: '',
pattern: '',
pii_level: 'general',
enabled: true,
};
const PII_LEVEL_OPTIONS = [
{ value: 'general', label: '一般个人信息' },
{ value: 'sensitive', label: '敏感个人信息' },
];
const piiLevelTag = (v, t) =>
v === 'sensitive' ? (
<Tag color='red'>{t('敏感')}</Tag>
) : (
<Tag color='blue'>{t('一般')}</Tag>
);
// OrgDsRules 企业私有自定义规则子 tab:平台规则只读展示 + 本企业规则 CRUD。
// 企业规则只增加检测项(收紧)、仅对本企业流量生效,保存后即时生效(多节点约 1 分钟同步)。
const OrgDsRules = ({ orgId, isSuperAdmin }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const [platformRules, setPlatformRules] = useState([]);
const [customRules, setCustomRules] = useState([]);
const [quota, setQuota] = useState({ used: 0, max: 20 });
// 规则编辑弹窗(受控字段,null=关闭;editingId=null 表示新增)
const [modalVisible, setModalVisible] = useState(false);
const [editingId, setEditingId] = useState(null);
const [draft, setDraft] = useState({ ...EMPTY_RULE_DRAFT });
const [submitting, setSubmitting] = useState(false);
// 请求代次:连续增删触发的多次刷新可能乱序返回,旧响应不得覆盖新列表
// (否则刚删除的规则会短暂"复活",R41;同 OrgDsHitLogs 的 seq 守卫模式)。
const rulesSeqRef = useRef(0);
const fetchRules = useCallback(async () => {
const seq = ++rulesSeqRef.current;
setLoading(true);
setLoadError(false);
try {
const res = await API.get('/api/org/data-security/rules', { headers });
if (seq !== rulesSeqRef.current) return;
if (res.data.success && res.data.data) {
setPlatformRules(res.data.data.platform || []);
setCustomRules(res.data.data.custom || []);
setQuota(res.data.data.quota || { used: 0, max: 20 });
} else {
setLoadError(true);
showError(res.data.message || t('规则列表加载失败'));
}
} catch (err) {
if (seq !== rulesSeqRef.current) return;
setLoadError(true);
if (err?.name !== 'AxiosError') showError(err);
} finally {
if (seq === rulesSeqRef.current) setLoading(false);
}
}, [headers, t]);
useEffect(() => {
fetchRules();
}, [fetchRules]);
const openCreate = () => {
setEditingId(null);
setDraft({ ...EMPTY_RULE_DRAFT });
setModalVisible(true);
};
const openEdit = (rule) => {
setEditingId(rule.id);
setDraft({
name: rule.name || '',
category: rule.category || '',
pattern: rule.pattern || '',
pii_level: rule.pii_level || 'general',
enabled: !!rule.enabled,
});
setModalVisible(true);
};
const submitRule = async () => {
if (!draft.name.trim()) {
showError(t('规则名称不能为空'));
return;
}
if (!draft.pattern.trim()) {
showError(t('正则不能为空'));
return;
}
setSubmitting(true);
try {
const payload = { ...draft, name: draft.name.trim() };
const res = editingId
? await API.put(`/api/org/data-security/rules/${editingId}`, payload, {
headers,
})
: await API.post('/api/org/data-security/rules', payload, { headers });
if (res.data.success) {
Toast.success(t('规则已保存并即时生效'));
setModalVisible(false);
fetchRules();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (err) {
if (err?.name !== 'AxiosError') showError(err);
} finally {
setSubmitting(false);
}
};
const deleteRule = async (rule) => {
try {
const res = await API.delete(`/api/org/data-security/rules/${rule.id}`, {
headers,
});
if (res.data.success) {
Toast.success(t('删除成功'));
fetchRules();
} else {
showError(res.data.message || t('删除失败'));
}
} catch (err) {
if (err?.name !== 'AxiosError') showError(err);
}
};
const platformColumns = [
{ title: t('规则名'), dataIndex: 'name' },
{ title: t('类别'), dataIndex: 'category' },
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{
title: t('来源'),
dataIndex: 'builtin',
render: (v) =>
v ? (
<Tag>{t('内置规则')}</Tag>
) : (
<Tag color='cyan'>{t('平台自定义')}</Tag>
),
},
];
const customColumns = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{
title: t('规则名'),
dataIndex: 'name',
render: (v) => <span className='break-all'>{v}</span>,
},
{ title: t('类别'), dataIndex: 'category' },
{
title: t('正则'),
dataIndex: 'pattern',
render: (v) => (
<Typography.Text code className='break-all'>
{v}
</Typography.Text>
),
},
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{
title: t('启用'),
dataIndex: 'enabled',
render: (v) =>
v ? <Tag color='green'>{t('启用')}</Tag> : <Tag>{t('停用')}</Tag>,
},
...(isSuperAdmin
? []
: [
{
title: t('操作'),
width: 150,
render: (_, rule) => (
<div className='flex items-center gap-2'>
<Button size='small' onClick={() => openEdit(rule)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该规则?删除后即时生效。')}
onConfirm={() => deleteRule(rule)}
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</div>
),
},
]),
];
return (
<Spin spinning={loading}>
{loadError && (
<div className='flex items-center justify-between gap-3 mt-3 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900/40'>
<span className='text-sm text-red-600 dark:text-red-400'>
{t('规则列表加载失败,请重试。')}
</span>
<Button size='small' type='danger' theme='light' onClick={fetchRules}>
{t('重试')}
</Button>
</div>
)}
<OrgPanel
icon={ShieldPlus}
title={t('企业自定义规则')}
subtitle={t('仅对本企业流量生效,只能增加检测项,不能停用平台规则')}
padding='p-4'
className='mt-3'
actions={
!isSuperAdmin && (
<div className='flex items-center gap-3'>
<span
className='text-xs text-gray-500 dark:text-gray-400'
style={{ fontVariantNumeric: 'tabular-nums' }}
>
{t('配额')} {quota.used}/{quota.max}
</span>
<Button
theme='solid'
type='primary'
disabled={loading || loadError || quota.used >= quota.max}
onClick={openCreate}
>
{t('新增规则')}
</Button>
</div>
)
}
>
<p className='text-xs text-gray-500 dark:text-gray-400 mb-3'>
{t(
'自定义规则使用 RE2 正则(线性时间、抗 ReDoS),不超过 500 字符、不得匹配空串。命中后与平台规则同等参与脱敏;敏感级规则会触发敏感个人信息策略。保存后即时生效(多节点约 1 分钟内同步)。',
)}
</p>
<Table
columns={customColumns}
dataSource={customRules}
pagination={false}
rowKey='id'
size='small'
scroll={{ x: 'max(100%, 900px)' }}
empty={
<span className='text-sm text-gray-400'>
{t(
'暂无企业自定义规则。点击「新增规则」为本企业增加专属检测项(如员工号、内部项目代号)。',
)}
</span>
}
/>
</OrgPanel>
<OrgPanel
icon={ListChecks}
title={t('平台规则(只读)')}
subtitle={t('由平台统一维护,对本企业流量始终生效')}
padding='p-4'
className='mt-4 mb-2'
>
<Table
columns={platformColumns}
dataSource={platformRules.map((r, i) => ({ ...r, _key: i }))}
pagination={false}
rowKey='_key'
size='small'
scroll={{ x: 'max(100%, 640px)' }}
/>
</OrgPanel>
<OrgModal
title={editingId ? t('编辑自定义规则') : t('新增自定义规则')}
visible={modalVisible}
onOk={submitRule}
onCancel={() => setModalVisible(false)}
okButtonProps={{ loading: submitting }}
maskClosable={false}
>
<div className='flex flex-col gap-3'>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
{t('规则名称')}
</label>
<Input
value={draft.name}
maxLength={64}
onChange={(v) => setDraft({ ...draft, name: v })}
placeholder={t('例如:员工工号')}
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
{t('类别标签(可选,默认 CUSTOM)')}
</label>
<Input
value={draft.category}
maxLength={32}
onChange={(v) => setDraft({ ...draft, category: v })}
placeholder='EMPLOYEE'
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
{t('正则表达式(RE2)')}
</label>
<Input
value={draft.pattern}
onChange={(v) => setDraft({ ...draft, pattern: v })}
placeholder={t('例如') + ' EMP[0-9]{6}'}
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
{t('PII 分级')}
</label>
<Select
value={draft.pii_level}
onChange={(v) => setDraft({ ...draft, pii_level: v })}
optionList={PII_LEVEL_OPTIONS.map((o) => ({
...o,
label: t(o.label),
}))}
style={{ width: '100%' }}
/>
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
{t(
'敏感级规则命中时会触发本企业的敏感个人信息策略(可能直接拒绝请求),请谨慎选择。',
)}
</p>
</div>
<div className='flex items-center gap-2'>
<Switch
checked={draft.enabled}
onChange={(v) => setDraft({ ...draft, enabled: v })}
/>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('启用')}
</span>
</div>
</div>
</OrgModal>
</Spin>
);
};
export default OrgDsRules;
@@ -0,0 +1,139 @@
/*
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 { FlaskConical } from 'lucide-react';
import { Button, Tag, TextArea, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
// OrgDsTest 脱敏测试子 tab:按本企业生效策略 + 生效规则集(含企业私有规则)演示脱敏效果。
// 样本仅内存处理、不入库。
const OrgDsTest = ({ orgId }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [text, setText] = useState('我的邮箱 zhang@abc.com,手机 13800138000');
const [testing, setTesting] = useState(false);
const [result, setResult] = useState(null);
const runTest = async () => {
if (!text.trim()) {
showError(t('请输入要测试的样本文本'));
return;
}
setTesting(true);
try {
const res = await API.post(
'/api/org/data-security/test',
{ text },
{ headers },
);
if (res.data.success) {
setResult(res.data.data);
} else {
showError(res.data.message || t('测试失败'));
}
} catch (err) {
if (err?.name !== 'AxiosError') showError(err);
} finally {
setTesting(false);
}
};
return (
<OrgPanel
icon={FlaskConical}
title={t('脱敏测试')}
subtitle={t(
'按本企业生效策略与规则集演示脱敏效果,样本仅内存处理、不入库',
)}
padding='p-5'
className='mt-3 mb-2'
>
<TextArea
value={text}
onChange={setText}
autosize={{ minRows: 3, maxRows: 8 }}
maxLength={10000}
placeholder={t('输入样本文本(样本不入库,仅内存处理)')}
/>
<div className='mt-3 flex items-center justify-end'>
<Button
theme='solid'
type='primary'
loading={testing}
disabled={!text.trim()}
onClick={runTest}
>
{t('测试脱敏效果')}
</Button>
</div>
{result && (
<div className='mt-4'>
<div className='flex flex-wrap items-center gap-2 mb-2'>
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('脱敏后')}
</span>
{result.mode && (
<Tag color='blue'>
{t('本企业生效模式')}: {result.mode}
</Tag>
)}
{(result.mode === 'detect_only' || result.mode === 'block') && (
<Tag color='amber'>
{result.mode === 'block'
? t('block 模式下命中即拒绝,以下为命中演示')
: t('detect_only 模式下不改写,以下为命中演示')}
</Tag>
)}
</div>
<Typography.Paragraph
copyable
className='rounded-lg px-3 py-2 break-all'
style={{ background: 'var(--semi-color-fill-0)' }}
>
{result.desensitized}
</Typography.Paragraph>
<div className='mt-2 flex flex-wrap items-center gap-1.5'>
<span
className='text-sm text-gray-600 dark:text-gray-300 mr-1'
style={{ fontVariantNumeric: 'tabular-nums' }}
>
{t('命中')} {result.hit_count}
</span>
{(result.hits || []).map((h, i) => (
<Tag key={i} color={h.pii_level === 'sensitive' ? 'red' : 'blue'}>
{h.category} → {h.token}
</Tag>
))}
{result.hit_count === 0 && (
<span className='text-sm text-gray-400'>
{t('未命中任何规则')}
</span>
)}
</div>
</div>
)}
</OrgPanel>
);
};
export default OrgDsTest;
+915
View File
@@ -0,0 +1,915 @@
/*
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, {
useContext,
useEffect,
useState,
useCallback,
useRef,
useMemo,
} from 'react';
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@douyinfe/semi-ui';
import OrgSideSheet from './components/OrgSideSheet';
import { Menu } from 'lucide-react';
import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
import Loading from '../../components/common/ui/Loading';
import PageBackground from '../../components/common/PageBackground';
import OrgSidebar from './OrgSidebar';
import OrgWorkbench from './OrgWorkbench';
import OrgDashboard from './OrgDashboard';
import OrgMembers from './OrgMembers';
import OrgDepartments from './OrgDepartments';
import OrgProjects from './OrgProjects';
import OrgBudgets from './OrgBudgets';
import OrgRequests from './OrgRequests';
import OrgTokens from './OrgTokens';
import OrgDeptManage from './OrgDeptManage';
import OrgProjectManage from './OrgProjectManage';
import OrgAudit from './OrgAudit';
import OrgLogs from './OrgLogs';
import OrgSettings from './OrgSettings';
import OrgRecharge from './OrgRecharge';
import OrgPersonalSettings from './OrgPersonalSettings';
import CloudBrain from '../CloudBrain';
import OrgKnowledge from './OrgKnowledge';
import OrgSkillCenter from './OrgSkillCenter';
import OrgSkillAssignments from './OrgSkillAssignments';
import OrgMyCapabilities from './OrgMyCapabilities';
import OrgExperts from './OrgExperts';
import OrgAgentAudit from './OrgAgentAudit';
import OrgConnectors from './OrgConnectors';
import OrgEffectiveness from './OrgEffectiveness';
import OrgQuality from './OrgQuality';
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
import { canAccessOrgSettings } from './orgFeatureFlags';
import {
CLOUD_BRAIN_UI_ENABLED,
isCloudBrainOrgModule,
} from '../../config/cloudBrainUi';
import '../../styles/org.css';
const routeFeatureRequirements = {
cloudBrain: 'cloud_brain',
knowledge: 'knowledge_base',
skillLibrary: 'skill_market',
skillAssignments: 'skill_market',
mySkills: 'skill_market',
experts: 'expert',
agentAudit: 'cloud_brain',
connectors: 'connector',
myConnectors: 'connector',
effectiveness: 'agent_effectiveness',
quality: 'quality_monitor',
privateSkills: 'skill_market',
departments: 'dept',
projects: 'project',
projectManage: 'project',
budgets: 'budget',
requests: 'approval',
};
const parseFeatureFlags = (raw) => {
if (!raw) return {};
if (typeof raw === 'object') return raw;
try {
return JSON.parse(raw) || {};
} catch {
return {};
}
};
const isFeatureEnabled = (flags, key) => {
if (!key) return true;
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
const Organization = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const [mobileNavOpen, setMobileNavOpen] = useState(false);
const navigateRef = useRef(navigate);
navigateRef.current = navigate;
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
// org_only 员工被 App 守卫限制在 /org;这里的回退不能再把他们踢回 C 端,否则死循环
const isOrgUser = userState?.user?.org_only_mode === true;
const [orgInfo, setOrgInfo] = useState(null);
const [orgRole, setOrgRole] = useState(null);
const [canManageCloudBrain, setCanManageCloudBrain] = useState(false);
const [canManageKnowledge, setCanManageKnowledge] = useState(false);
const [canAuditKnowledge, setCanAuditKnowledge] = useState(false);
const [canManageSkills, setCanManageSkills] = useState(false);
const [canAssignSkills, setCanAssignSkills] = useState(false);
const [canManageExperts, setCanManageExperts] = useState(false);
const [canManageConnectors, setCanManageConnectors] = useState(false);
const [canAuditAgentMetadata, setCanAuditAgentMetadata] = useState(false);
const [canAuditAgentContent, setCanAuditAgentContent] = useState(false);
const [canViewAgentEffect, setCanViewAgentEffect] = useState(false);
const [canViewQuality, setCanViewQuality] = useState(false);
const [canManageAgentPolicy, setCanManageAgentPolicy] = useState(false);
// 平台超管查看企业时没有成员身份,成员型接口一律 member_actor_required;
// 用该标志收敛“我的技能/我的业务系统授权”这类必失败入口。
const [isMemberActor, setIsMemberActor] = useState(true);
const [loading, setLoading] = useState(true);
const [pendingActivation, setPendingActivation] = useState(false);
const [isDeptManager, setIsDeptManager] = useState(false);
const [deptScopeLoaded, setDeptScopeLoaded] = useState(false);
const [isProjectManager, setIsProjectManager] = useState(false);
const [projectScopeLoaded, setProjectScopeLoaded] = useState(false);
const hasMarquee = !!statusState?.status?.marquee_content?.trim();
const isAdmin =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const orgConfig = useMemo(
() =>
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin)
.orgCenter,
[statusState?.status?.SidebarModulesAdmin],
);
const orgFeatureFlags = useMemo(
() => parseFeatureFlags(orgInfo?.feature_flags),
[orgInfo?.feature_flags],
);
const canManageSettings = canAccessOrgSettings(orgRole, orgFeatureFlags);
const isOrgModuleVisible = useCallback(
(key) => {
if (!CLOUD_BRAIN_UI_ENABLED && isCloudBrainOrgModule(key)) return false;
return (
orgConfig?.enabled !== false &&
orgConfig?.[key] !== false &&
isFeatureEnabled(orgFeatureFlags, routeFeatureRequirements[key])
);
},
[orgConfig, orgFeatureFlags],
);
const visibleOrgRoutes = useMemo(() => {
const routes = [];
// 管理员默认落 dashboard;普通成员默认落 workbench(§36 角色化首屏)
if (isAdmin && isOrgModuleVisible('dashboard')) routes.push('dashboard');
if (isOrgModuleVisible('workbench')) routes.push('workbench');
if (isOrgModuleVisible('cloudBrain')) routes.push('cloud-brain');
// 成员型入口对无成员身份的超管隐藏;否则模块配置特定组合下
// hiddenOrgTarget 可能算出指向自身的 Navigate 造成重定向自环。
// 我的技能 + 业务系统授权已合并为「我的 AI 能力」,任一页签可见即入路由。
if (
isMemberActor &&
(isOrgModuleVisible('mySkills') || isOrgModuleVisible('myConnectors'))
)
routes.push('my-capabilities');
if (isAdmin && canManageConnectors && isOrgModuleVisible('connectors'))
routes.push('connectors');
if (isAdmin && canManageExperts && isOrgModuleVisible('experts'))
routes.push('experts');
if (isAdmin && canViewAgentEffect && isOrgModuleVisible('effectiveness'))
routes.push('effectiveness');
if (isAdmin && canViewQuality && isOrgModuleVisible('quality'))
routes.push('quality');
// 审计路由组后端是 OrgAdminAuth(仅 owner/admin),不放行部门负责人;
// 这里必须同样只认 isAdmin。此前的 isDeptManager 分支当前不可达
// (canAuditAgentMetadata 对非 owner/admin 恒 false),但一旦把
// agent_audit_metadata 下放给 dept_admin,就会变成"入口可见但接口必 403"。
if (isAdmin && canAuditAgentMetadata && isOrgModuleVisible('agentAudit'))
routes.push('agent-audit');
// 技能库 + 自研 Skill 已合并为「技能中心」;平台技能的启用动作
// 有两个入口:平台技能超市(/skill-market)就地启用,或技能中心内的
// 「引入技能」抽屉(供超管与被挡在超市外的管理员使用)。企业技能市场
// 路由已不存在,旧路径重定向。
if (
isAdmin &&
canManageSkills &&
(isOrgModuleVisible('skillLibrary') ||
isOrgModuleVisible('privateSkills'))
)
routes.push('skill-center');
if (
(isAdmin || isDeptManager) &&
canAssignSkills &&
isOrgModuleVisible('skillAssignments')
)
routes.push('skill-assignments');
if (isAdmin && canManageKnowledge && isOrgModuleVisible('knowledge'))
routes.push('knowledge');
if (
isAdmin &&
(isOrgModuleVisible('members') || isOrgModuleVisible('memberAccounts'))
) {
routes.push('members');
}
if (isDeptManager && isOrgModuleVisible('deptManage'))
routes.push('dept-manage');
if (isProjectManager && isOrgModuleVisible('projectManage'))
routes.push('project-manage');
if (isAdmin && isOrgModuleVisible('departments'))
routes.push('departments');
if (isAdmin && isOrgModuleVisible('projects')) routes.push('projects');
if (isAdmin && isOrgModuleVisible('budgets')) routes.push('budgets');
if (isOrgModuleVisible('requests')) routes.push('requests');
if (isOrgModuleVisible('tokens')) routes.push('tokens');
if (isOrgModuleVisible('logs')) routes.push('logs');
if (isAdmin && isOrgModuleVisible('audit')) routes.push('audit');
if (isAdmin && isOrgModuleVisible('recharge')) routes.push('recharge');
if (canManageSettings && isOrgModuleVisible('settings'))
routes.push('settings');
return routes;
}, [
isAdmin,
canManageKnowledge,
canManageSkills,
canAssignSkills,
canManageExperts,
canManageConnectors,
canAuditAgentMetadata,
canViewAgentEffect,
canViewQuality,
isDeptManager,
isProjectManager,
isMemberActor,
canManageSettings,
isOrgModuleVisible,
]);
const firstOrgRoute = visibleOrgRoutes[0] || null;
const firstOrgTarget = firstOrgRoute
? `/org/${firstOrgRoute}`
: '/user-center/dashboard';
const hiddenOrgTarget = firstOrgTarget;
const guardOrgRoute = (key, element) => {
if (!isOrgModuleVisible(key)) {
return <Navigate to={hiddenOrgTarget} replace />;
}
return element;
};
// 从 localStorage 获取当前企业ID
const orgId = parseInt(localStorage.getItem('current_org_id') || '0', 10);
const fetchOrgInfo = useCallback(async () => {
if (!orgId) {
setLoading(false);
return;
}
setLoading(true);
setPendingActivation(false);
try {
const res = await API.get('/api/org/info', {
headers: { 'X-Org-Id': String(orgId) },
});
if (res.data.success) {
const member = res.data.data.member || res.data.data;
setOrgInfo(res.data.data.organization);
setOrgRole(member.role);
setCanManageCloudBrain(member.can_manage_cloud_brain === true);
setCanManageKnowledge(member.can_manage_knowledge === true);
setCanAuditKnowledge(member.can_audit_knowledge === true);
setCanManageSkills(member.can_manage_skills === true);
setCanAssignSkills(member.can_assign_skills === true);
setCanManageExperts(member.can_manage_experts === true);
setCanManageConnectors(member.can_manage_connectors === true);
setCanViewAgentEffect(member.can_view_agent_effect === true);
setCanViewQuality(member.can_view_quality === true);
setCanManageAgentPolicy(member.can_manage_agent_policy === true);
// 后端未返回该键时按“有成员身份”处理,避免旧后端下入口消失。
setIsMemberActor(member.is_member_actor !== false);
setCanAuditAgentMetadata(member.can_audit_agent_metadata === true);
setCanAuditAgentContent(member.can_audit_agent_content === true);
} else if (res.data.code === 'org_pending_activation') {
// 待激活:不跳转创建页,展示占位页,保留 current_org_id
setPendingActivation(true);
} else {
showError(res.data.message);
localStorage.removeItem('current_org_id');
navigateRef.current('/org/create', { replace: true });
}
} catch {
localStorage.removeItem('current_org_id');
navigateRef.current('/org/create', { replace: true });
} finally {
setLoading(false);
}
}, [orgId]);
useEffect(() => {
fetchOrgInfo();
}, [fetchOrgInfo]);
// 是否为部门负责人(控制「部门管理」入口/路由),失败按非负责人处理。
useEffect(() => {
let cancelled = false;
if (!orgId) {
setIsDeptManager(false);
setDeptScopeLoaded(true);
return () => {
cancelled = true;
};
}
setIsDeptManager(false);
setDeptScopeLoaded(false);
API.get('/api/org/me/dept-scope', {
headers: { 'X-Org-Id': String(orgId) },
})
.then((res) => {
if (!cancelled) {
setIsDeptManager(
!!(res.data.success && res.data.data?.is_dept_manager),
);
}
})
.catch(() => {
if (!cancelled) setIsDeptManager(false);
})
.finally(() => {
if (!cancelled) setDeptScopeLoaded(true);
});
return () => {
cancelled = true;
};
}, [orgId]);
// 是否为项目经理(控制「我的项目」入口/路由)
useEffect(() => {
if (!orgId) {
setIsProjectManager(false);
setProjectScopeLoaded(true);
return;
}
setProjectScopeLoaded(false);
API.get('/api/org/me/project-scope', {
headers: { 'X-Org-Id': String(orgId) },
})
.then((res) => {
setIsProjectManager(
!!(res.data.success && res.data.data?.is_project_manager),
);
})
.catch(() => setIsProjectManager(false))
.finally(() => setProjectScopeLoaded(true));
}, [orgId]);
// org_only 员工无可用企业功能时的非循环提示(不跳 C 端)
const orgUnavailableFallback = (
<div className='flex flex-col items-center justify-center h-screen px-6 text-center bg-[var(--surface-bg-base)]'>
<div className='max-w-md'>
<div className='text-2xl font-semibold mb-3'>
{t('暂无可用的企业功能')}
</div>
<p className='text-[var(--text-secondary)]'>
{t('您的账号当前没有可访问的企业功能,请联系企业管理员开通。')}
</p>
</div>
</div>
);
if (orgConfig.enabled === false) {
if (isOrgUser) return orgUnavailableFallback;
return <Navigate to='/user-center/dashboard' replace />;
}
if (!orgId) {
return <Navigate to='/org/create' replace />;
}
if (loading) {
return <Loading />;
}
// 待激活占位页:不展示任何企业功能,仅引导联系客服/管理员
if (pendingActivation) {
return (
<div className='flex flex-col items-center justify-center h-screen px-6 text-center bg-[var(--surface-bg-base)]'>
<div className='max-w-md'>
<div className='text-2xl font-semibold mb-3'>{t('企业待激活')}</div>
<p className='text-[var(--text-secondary)] mb-6'>
{t(
'您的企业已创建,正在等待平台管理员审核激活。激活后即可使用企业工作台与治理功能,请联系客服或销售协助开通。',
)}
</p>
<div className='flex gap-3 justify-center'>
<button
className='px-4 py-2 rounded-md border border-[var(--semi-color-border)]'
onClick={() => fetchOrgInfo()}
>
{t('刷新状态')}
</button>
{!isOrgUser && (
<button
className='px-4 py-2 rounded-md bg-[var(--semi-color-primary)] text-white'
onClick={() =>
navigateRef.current('/user-center/dashboard', {
replace: true,
})
}
>
{t('返回个人中心')}
</button>
)}
</div>
</div>
</div>
);
}
if (!firstOrgRoute) {
if (isOrgUser) return orgUnavailableFallback;
return <Navigate to='/user-center/dashboard' replace />;
}
return (
<div
className={`org-center flex flex-col md:flex-row h-screen overflow-hidden bg-[var(--surface-bg-base)] transition-colors duration-300 ${hasMarquee ? 'pt-[96px] sm:pt-[104px]' : 'pt-14 sm:pt-16'}`}
>
{/* Sidebar - desktop only */}
<div className='hidden md:block flex-shrink-0 h-full'>
<OrgSidebar
orgName={orgInfo?.name}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
isDeptManager={isDeptManager}
isProjectManager={isProjectManager}
canManageKnowledge={canManageKnowledge}
canManageSkills={canManageSkills}
canAssignSkills={canAssignSkills}
canManageExperts={canManageExperts}
canManageConnectors={canManageConnectors}
canAuditAgentMetadata={canAuditAgentMetadata}
canViewAgentEffect={canViewAgentEffect}
canViewQuality={canViewQuality}
isMemberActor={isMemberActor}
/>
</div>
{/* Main Content */}
<div className='flex-1 h-full overflow-hidden relative flex flex-col'>
{/* 移动端顶栏:汉堡菜单 + 当前企业名(窄屏唯一的菜单入口) */}
<div className='md:hidden flex items-center gap-2 px-3 h-12 flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--surface-header)] relative z-20'>
<Button
icon={<Menu size={20} />}
theme='borderless'
type='tertiary'
onClick={() => setMobileNavOpen(true)}
aria-label={t('打开菜单')}
/>
<span className='font-semibold text-gray-900 dark:text-white truncate'>
{orgInfo?.name || t('企业中心')}
</span>
</div>
<div className='flex-1 relative overflow-hidden'>
{/* 统一页面背景层 —— 唯一背景来源;实底卡片方案下降为 subtle 档,
不再叠加硬编码渐变装饰层(原 teal/amber 层不跟主题预设,已删除) */}
<PageBackground variant='subtle' />
<div className='relative z-10 h-full overflow-y-auto uc-page-scrollbar'>
<Routes>
{/* 默认路由:管理员进数据看板,普通成员进工作台 */}
<Route
path='/'
element={<Navigate to={firstOrgTarget} replace />}
/>
{/* 数据看板、员工管理、审计日志、企业设置仅 admin/owner 可访问;消耗明细普通成员可看本人 */}
<Route
path='dashboard'
element={
isAdmin ? (
guardOrgRoute(
'dashboard',
<OrgDashboard
orgId={orgId}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='members'
element={
isAdmin &&
(isOrgModuleVisible('members') ||
isOrgModuleVisible('memberAccounts')) ? (
<OrgMembers
orgId={orgId}
orgRole={orgRole}
showMemberList={isOrgModuleVisible('members')}
showAccounts={isOrgModuleVisible('memberAccounts')}
featureFlags={orgFeatureFlags}
/>
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='member-accounts'
element={
isAdmin &&
(isOrgModuleVisible('members') ||
isOrgModuleVisible('memberAccounts')) ? (
<Navigate to='/org/members' replace />
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='departments'
element={
isAdmin ? (
guardOrgRoute(
'departments',
<OrgDepartments orgId={orgId} orgRole={orgRole} />,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='projects'
element={
isAdmin ? (
guardOrgRoute(
'projects',
<OrgProjects orgId={orgId} orgRole={orgRole} />,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='logs'
element={guardOrgRoute(
'logs',
isAdmin || deptScopeLoaded ? (
<OrgLogs
orgId={orgId}
orgRole={orgRole}
isDeptManager={isDeptManager}
/>
) : (
<Loading />
),
)}
/>
<Route
path='audit'
element={
isAdmin ? (
guardOrgRoute('audit', <OrgAudit orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='settings'
element={
canManageSettings ? (
guardOrgRoute(
'settings',
<OrgSettings
key={orgId}
orgId={orgId}
orgRole={orgRole}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='recharge'
element={
isAdmin ? (
guardOrgRoute('recharge', <OrgRecharge orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 部门管理 - 部门负责人可访问(阶段一);与菜单/project-manage
同口径消费 deptManage 管理开关,避免"菜单隐藏但直达 URL 可进" */}
<Route
path='dept-manage'
element={
isDeptManager && isOrgModuleVisible('deptManage') ? (
<OrgDeptManage
orgId={orgId}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
/>
) : !deptScopeLoaded ? (
<Loading />
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 我的项目 - 项目经理可访问(阶段一) */}
<Route
path='project-manage'
element={
isProjectManager && isOrgModuleVisible('projectManage') ? (
<OrgProjectManage orgId={orgId} orgRole={orgRole} />
) : !projectScopeLoaded ? (
<Loading />
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 企业工作台 - 所有成员可访问(§36.1) */}
<Route
path='workbench'
element={guardOrgRoute(
'workbench',
<OrgWorkbench
orgId={orgId}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
/>,
)}
/>
<Route
path='cloud-brain'
element={guardOrgRoute(
'cloudBrain',
<CloudBrain
organization
orgId={orgId}
canManage={canManageCloudBrain}
/>,
)}
/>
<Route
path='knowledge'
element={
isAdmin && canManageKnowledge ? (
guardOrgRoute(
'knowledge',
<OrgKnowledge
orgId={orgId}
canAuditContent={canAuditKnowledge}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 我的 AI 能力:我的技能 + 业务系统授权 合并页(成员自助视图) */}
<Route
path='my-capabilities'
element={
isMemberActor &&
(isOrgModuleVisible('mySkills') ||
isOrgModuleVisible('myConnectors')) ? (
<OrgMyCapabilities
orgId={orgId}
showSkills={isOrgModuleVisible('mySkills')}
showConnectors={isOrgModuleVisible('myConnectors')}
/>
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 旧路径兼容:合并前的两个成员页重定向到对应页签 */}
<Route
path='my-connectors'
element={
<Navigate to='/org/my-capabilities?tab=connectors' replace />
}
/>
<Route
path='connectors'
element={
isAdmin && canManageConnectors ? (
guardOrgRoute('connectors', <OrgConnectors orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='experts'
element={
isAdmin && canManageExperts ? (
guardOrgRoute('experts', <OrgExperts orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='effectiveness'
element={
isAdmin && canViewAgentEffect ? (
guardOrgRoute(
'effectiveness',
<OrgEffectiveness
orgId={orgId}
canManagePolicy={canManageAgentPolicy}
canManageSkills={canManageSkills}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='quality'
element={
isAdmin && canViewQuality ? (
guardOrgRoute('quality', <OrgQuality orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='agent-audit'
element={
isAdmin && canAuditAgentMetadata ? (
guardOrgRoute(
'agentAudit',
<OrgAgentAudit
orgId={orgId}
canAuditContent={canAuditAgentContent}
canManagePolicy={canManageAgentPolicy}
/>,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
<Route
path='my-skills'
element={
<Navigate to='/org/my-capabilities?tab=skills' replace />
}
/>
{/* 技能中心:企业技能库 + 企业自研 Skill 合并页 */}
<Route
path='skill-center'
element={
isAdmin &&
canManageSkills &&
(isOrgModuleVisible('skillLibrary') ||
isOrgModuleVisible('privateSkills')) ? (
<OrgSkillCenter
orgId={orgId}
orgRole={orgRole}
canAssignSkills={canAssignSkills}
showLibrary={isOrgModuleVisible('skillLibrary')}
showPrivate={isOrgModuleVisible('privateSkills')}
/>
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 企业技能市场页已并入平台技能超市:管理员在 /skill-market 就地
为企业启用技能(普通成员落到超市浏览页也无害) */}
<Route
path='skill-market'
element={<Navigate to='/skill-market' replace />}
/>
{/* 旧路径兼容:合并前的两个管理页重定向到对应页签 */}
<Route
path='skill-library'
element={
<Navigate to='/org/skill-center?tab=library' replace />
}
/>
<Route
path='private-skills'
element={
<Navigate to='/org/skill-center?tab=private' replace />
}
/>
<Route
path='skill-assignments'
element={
(isAdmin || isDeptManager) && canAssignSkills ? (
guardOrgRoute(
'skillAssignments',
<OrgSkillAssignments orgId={orgId} orgRole={orgRole} />,
)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 申请/审批 - 所有成员可访问(成员看自己,管理员审批) */}
<Route
path='requests'
element={guardOrgRoute(
'requests',
<OrgRequests
orgId={orgId}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
/>,
)}
/>
{/* 预算中心 - 仅管理员 */}
<Route
path='budgets'
element={
isAdmin ? (
guardOrgRoute('budgets', <OrgBudgets orgId={orgId} />)
) : (
<Navigate to={hiddenOrgTarget} replace />
)
}
/>
{/* 用量分析统一归入数据看板,旧路径重定向 */}
<Route
path='analytics'
element={
<Navigate
to={isAdmin ? '/org/dashboard' : hiddenOrgTarget}
replace
/>
}
/>
{/* 令牌管理 - 所有成员可访问 */}
<Route
path='tokens'
element={guardOrgRoute(
'tokens',
<OrgTokens orgId={orgId} orgRole={orgRole} />,
)}
/>
{/* 个人设置 - 所有成员可访问(头像/昵称/密码/配额预警通知) */}
<Route
path='personal-settings'
element={<OrgPersonalSettings key={orgId} orgId={orgId} />}
/>
</Routes>
</div>
</div>
</div>
{/* 移动端侧栏抽屉(窄屏点击顶栏汉堡菜单打开) */}
<OrgSideSheet
placement='left'
visible={mobileNavOpen}
onCancel={() => setMobileNavOpen(false)}
width={260}
closable={false}
bodyStyle={{ padding: 0 }}
>
<OrgSidebar
orgName={orgInfo?.name}
orgRole={orgRole}
featureFlags={orgFeatureFlags}
isDeptManager={isDeptManager}
isProjectManager={isProjectManager}
canManageKnowledge={canManageKnowledge}
canManageSkills={canManageSkills}
canAssignSkills={canAssignSkills}
canManageExperts={canManageExperts}
canManageConnectors={canManageConnectors}
canAuditAgentMetadata={canAuditAgentMetadata}
canViewAgentEffect={canViewAgentEffect}
canViewQuality={canViewQuality}
isMemberActor={isMemberActor}
mobile
onNavigate={() => setMobileNavOpen(false)}
/>
</OrgSideSheet>
</div>
);
};
export default Organization;
+213
View File
@@ -0,0 +1,213 @@
/* Connector 控制台样式对齐企业中心设计系统:不再自绘整页渐变背景
(整页背景唯一来源是 index.jsx 的 <PageBackground>),改用主题变量,
随亮/暗色主题自适应。OrgConnectors 与 OrgMyConnectors 共用本文件。 */
.org-connector-page {
display: grid;
gap: 20px;
padding: 16px;
color: var(--text-primary);
}
@media (min-width: 640px) {
.org-connector-page {
padding: 24px;
}
}
@media (min-width: 1024px) {
.org-connector-page {
padding: 32px;
}
}
.org-connector-hero,
.org-connector-section-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
}
/* 控制台式页头:实底卡片 + 细边框,标题紧凑无衬线(参考主流云厂商控制台) */
.org-connector-hero {
padding: 20px 24px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-connector-hero > div {
max-width: 760px;
}
/* 使用指引胶囊(PageGuide 通用组件):作为 grid 子项靠左收缩 */
.org-connector-page .page-guide-pill {
justify-self: start;
}
.org-connector-hero h1 {
margin: 0 0 6px;
color: var(--text-primary);
font-size: 20px;
font-weight: 600;
line-height: 1.35;
}
.org-connector-hero p,
.org-connector-section-head p {
margin: 0;
color: var(--text-secondary);
font-size: 13px;
}
.org-connector-actions {
display: flex;
gap: 10px;
/* 加入「使用指引」后为 3 个按钮,窄屏(<400px)需可换行防横向溢出 */
flex-wrap: wrap;
}
.org-connector-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
padding-top: 18px;
}
.org-connector-card {
padding: 20px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
transition:
border-color 0.2s ease,
box-shadow 0.2s ease;
}
.org-connector-card:hover {
border-color: color-mix(in srgb, var(--semi-color-primary) 35%, transparent);
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
}
.org-connector-card-top,
.org-connector-card-actions,
.org-connector-list article > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.org-connector-icon {
display: grid;
place-items: center;
width: 40px;
height: 40px;
border-radius: 10px;
color: var(--semi-color-primary);
background: color-mix(in srgb, var(--semi-color-primary) 12%, transparent);
}
.org-connector-card h3 {
margin: 14px 0 4px;
color: var(--text-primary);
font-size: 16px;
font-weight: 600;
line-height: 1.4;
}
.org-connector-card p {
min-height: 38px;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.55;
}
.org-connector-card dl {
display: grid;
gap: 8px;
padding: 12px;
border-radius: 8px;
background: var(--semi-color-fill-0);
font-size: 13px;
}
.org-connector-card dl div {
display: flex;
justify-content: space-between;
gap: 12px;
}
.org-connector-card dt {
color: var(--text-secondary);
}
.org-connector-card dd {
margin: 0;
color: var(--text-primary);
font-family: 'IBM Plex Mono', 'Cascadia Code', monospace;
text-align: right;
}
.org-connector-card-actions {
justify-content: flex-start;
flex-wrap: wrap;
margin-top: 16px;
}
.org-connector-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
min-height: 32px;
}
.org-connector-list {
display: grid;
gap: 10px;
padding-top: 16px;
}
.org-connector-list article {
display: grid;
grid-template-columns: minmax(190px, 0.7fr) minmax(220px, 1.2fr) minmax(
200px,
1fr
);
gap: 14px;
padding: 14px 18px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-connector-list code {
overflow: hidden;
color: var(--text-primary);
font-family: 'IBM Plex Mono', 'Cascadia Code', monospace;
text-overflow: ellipsis;
}
.org-connector-list span {
color: var(--text-secondary);
}
.org-connector-form {
display: grid;
gap: 16px;
}
.org-connector-form label {
display: grid;
gap: 7px;
color: var(--semi-color-text-1);
font-weight: 600;
}
.org-connector-form .org-connector-switch {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px;
border-radius: 12px;
background: var(--semi-color-fill-0);
}
.org-connector-note {
padding: 10px 12px;
border-left: 3px solid var(--semi-color-warning);
border-radius: 0 8px 8px 0;
color: var(--semi-color-text-2);
background: color-mix(in srgb, var(--semi-color-warning) 10%, transparent);
}
@media (max-width: 1000px) {
.org-connector-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 760px) {
.org-connector-hero,
.org-connector-section-head {
align-items: stretch;
flex-direction: column;
}
.org-connector-grid {
grid-template-columns: 1fr;
}
.org-connector-list article {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,157 @@
/* 效能分析页样式对齐企业中心设计系统(控制台风格):
全部走主题 token,随亮/暗色主题与品牌色自适应,不再硬编码米黄/墨绿。 */
.org-effect-page {
display: grid;
gap: 16px;
padding: 16px;
color: var(--text-primary);
}
@media (min-width: 640px) {
.org-effect-page {
padding: 24px;
}
}
@media (min-width: 1024px) {
.org-effect-page {
padding: 32px;
}
}
/* 控制台式页头:实底卡片 + 细边框(参考主流云厂商控制台) */
.org-effect-hero {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
padding: 20px 24px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
/* 页头标题统一 20px/600(Semi Title 默认字号偏大) */
.org-effect-hero h1,
.org-effect-hero h2,
.org-effect-hero h3 {
font-size: 20px;
font-weight: 600;
line-height: 1.35;
}
.org-effect-toolbar,
.org-effect-form {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.org-effect-form > * {
flex: 1 1 280px;
}
.org-effect-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 14px;
}
/* KPI 指标卡:云控制台常见的统计瓦片 */
.org-effect-card {
display: grid;
gap: 8px;
min-height: 128px;
padding: 18px 20px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
transition:
border-color 0.2s ease,
box-shadow 0.2s ease;
}
.org-effect-card:hover {
border-color: color-mix(in srgb, var(--semi-color-primary) 30%, transparent);
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
}
.org-effect-card strong {
font-size: clamp(24px, 2.2vw, 30px);
font-weight: 600;
font-variant-numeric: tabular-nums;
line-height: 1.1;
}
.org-effect-card small {
color: var(--semi-color-text-2);
}
.org-effect-columns {
display: grid;
grid-template-columns: minmax(260px, 0.75fr) minmax(420px, 1.25fr);
gap: 16px;
}
.org-effect-reconcile {
display: grid;
grid-template-columns: 1fr auto;
gap: 14px;
font-size: 14px;
}
.org-effect-reconcile b {
font-variant-numeric: tabular-nums;
}
.org-effect-reconcile .is-ok {
color: var(--semi-color-success);
}
.org-effect-reconcile .is-risk {
color: var(--semi-color-danger);
}
.org-effect-samples {
display: grid;
gap: 7px;
max-height: 320px;
overflow: auto;
}
.org-effect-mobile-list {
display: grid;
gap: 10px;
}
.org-effect-mobile-list article {
display: grid;
gap: 8px;
padding: 14px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-effect-mobile-list article > div:first-child {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
@media (max-width: 960px) {
.org-effect-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.org-effect-columns {
grid-template-columns: 1fr;
}
}
@media (max-width: 640px) {
.org-effect-hero {
align-items: stretch;
flex-direction: column;
padding: 16px 18px;
}
.org-effect-grid {
grid-template-columns: 1fr;
}
}
+205
View File
@@ -0,0 +1,205 @@
/* 页面留白对齐企业中心标准页(p-4 sm:p-6 lg:p-8),不做整页居中收窄 */
.org-expert-page {
display: grid;
gap: 20px;
padding: 16px;
}
@media (min-width: 640px) {
.org-expert-page {
padding: 24px;
}
}
@media (min-width: 1024px) {
.org-expert-page {
padding: 32px;
}
}
/* 控制台式页头:实底卡片 + 细边框(参考主流云厂商控制台) */
.org-expert-hero,
.org-audit-hero {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 18px;
padding: 20px 24px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-expert-hero > div,
.org-audit-hero > div {
max-width: 760px;
}
/* 页头标题统一 20px/600(Semi Title 默认字号偏大) */
.org-expert-hero h1,
.org-expert-hero h2,
.org-expert-hero h3,
.org-audit-hero h1,
.org-audit-hero h2,
.org-audit-hero h3 {
font-size: 20px;
font-weight: 600;
line-height: 1.35;
}
.org-expert-hero .semi-typography-paragraph,
.org-audit-hero .semi-typography-paragraph {
font-size: 13px;
}
/* 页头右侧动作区:使用指引入口与既有按钮并排 */
.org-expert-hero-actions {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
/* 使用指引胶囊(PageGuide 通用组件):作为 grid 子项靠左收缩 */
.org-expert-page .page-guide-pill {
justify-self: start;
}
.org-expert-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.org-expert-empty {
grid-column: 1 / -1;
display: grid;
place-items: center;
gap: 8px;
min-height: 240px;
border: 1px dashed var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-expert-version-list {
display: grid;
gap: 8px;
margin: 14px 0;
}
.org-expert-version-list > div {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 0;
border-top: 1px solid var(--border-subtle);
}
.org-expert-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
padding-top: 14px;
}
.org-expert-form-grid label {
display: grid;
gap: 6px;
color: var(--semi-color-text-1);
}
.org-expert-form-grid .wide {
grid-column: 1 / -1;
}
.org-expert-help {
margin: 0;
color: var(--semi-color-text-2);
font-size: 12px;
line-height: 1.6;
}
.org-expert-form-grid .mono textarea,
.org-audit-content pre,
/* request_id 是 varchar(128)、run.id 是 char(36),都是不可断行的 ASCII。
承载它们的是 flex 行,flex 项的 min-width:auto 不会收缩到 min-content 以下,
缺这条会把整个 待对账 页撑出横向滚动条。 */
.org-audit-list code {
min-width: 0;
overflow-wrap: anywhere;
word-break: break-all;
}
.org-audit-list code {
font-family: 'IBM Plex Mono', 'Cascadia Code', monospace;
}
.org-audit-reason {
display: grid;
grid-template-columns: auto minmax(240px, 520px);
align-items: center;
gap: 12px;
margin: 8px 0 16px;
}
.org-audit-list {
display: grid;
gap: 12px;
}
.org-audit-list article {
display: grid;
gap: 10px;
padding: 16px 18px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
.org-audit-list article > div:first-child,
.org-audit-metrics,
.org-audit-skills {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.org-audit-metrics span {
padding-right: 12px;
border-right: 1px solid var(--border-subtle);
color: var(--semi-color-text-1);
}
.org-policy-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.org-policy-grid article {
display: grid;
gap: 8px;
padding: 16px 18px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
.org-audit-content {
display: grid;
gap: 10px;
}
.org-audit-content pre {
max-height: 300px;
overflow: auto;
white-space: pre-wrap;
padding: 14px;
border-radius: 10px;
background: var(--semi-color-fill-0);
}
@media (max-width: 760px) {
.org-expert-grid,
.org-expert-form-grid,
.org-policy-grid {
grid-template-columns: 1fr;
}
.org-expert-form-grid .wide {
grid-column: auto;
}
.org-expert-hero,
.org-audit-hero {
align-items: stretch;
flex-direction: column;
}
.org-audit-reason {
grid-template-columns: 1fr;
}
}
.org-audit-pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin-top: 16px;
}
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
/* 企业中心 · 调用质量页:布局对齐企业中心标准页(p-4 / sm:p-6 / lg:p-8),配色全部走 token */
.org-quality-page {
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
color: var(--text-primary);
min-width: 0;
}
@media (min-width: 640px) {
.org-quality-page {
padding: 24px;
}
}
@media (min-width: 1024px) {
.org-quality-page {
padding: 32px;
}
}
.org-quality-hero {
display: flex;
align-items: flex-end;
justify-content: space-between;
flex-wrap: wrap;
gap: 12px 24px;
padding: 20px 24px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-quality-hero h3 {
font-size: 20px;
font-weight: 600;
line-height: 1.35;
letter-spacing: -0.01em;
}
.org-quality-eyebrow {
margin-bottom: 4px;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.08em;
color: var(--semi-color-primary);
}
+210
View File
@@ -0,0 +1,210 @@
/* 页面留白对齐企业中心标准页(p-4 sm:p-6 lg:p-8),不做整页居中收窄 */
.org-skills-page {
display: grid;
gap: 20px;
padding: 16px;
}
@media (min-width: 640px) {
.org-skills-page {
padding: 24px;
}
}
@media (min-width: 1024px) {
.org-skills-page {
padding: 32px;
}
}
.org-private-skill-form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.org-private-skill-form .semi-textarea-wrapper {
grid-column: 1 / -1;
}
.org-skill-mobile-list {
display: grid;
gap: 12px;
}
.org-skill-mobile-list article {
display: grid;
gap: 9px;
padding: 14px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
/* canonical_id 是 varchar(64) 不可断行 ASCII,管理员没设 display_name 时直接渲染原始 id。
下列容器都是 flex 行,缺 min-width:0 会撑破页面,或被 OrgPanel 的 overflow:hidden 静默裁掉。 */
.org-skill-mobile-list article > div:first-child > *,
.org-skill-preview-row > *,
.org-my-skill-title > * {
min-width: 0;
overflow-wrap: anywhere;
}
.org-skill-mobile-list article > div:first-child {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
@media (max-width: 640px) {
.org-private-skill-form {
grid-template-columns: 1fr;
}
}
/* 控制台式页头:实底卡片 + 细边框(参考主流云厂商控制台) */
.org-skills-hero {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 18px;
padding: 20px 24px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
}
.org-skills-hero > div {
max-width: 760px;
}
/* 页头右侧动作区:使用指引入口与既有按钮并排 */
.org-skills-hero-actions {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
/* 使用指引胶囊(PageGuide 通用组件):作为 grid 子项靠左收缩 */
.org-skills-page .page-guide-pill {
justify-self: start;
}
/* 页头标题统一 20px/600(Semi Title 默认字号偏大) */
.org-skills-hero h1,
.org-skills-hero h2,
.org-skills-hero h3 {
font-size: 20px;
font-weight: 600;
line-height: 1.35;
}
.org-skills-hero .semi-typography-paragraph,
.org-skills-hero .semi-typography-tertiary {
font-size: 13px;
}
.org-skills-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.org-skill-library-list,
.org-skill-form,
.org-skill-preview,
.org-my-skills {
display: grid;
gap: 14px;
}
.org-skill-policy-row,
.org-skill-preview-controls,
.org-skill-preview-row,
.org-my-skill-title,
.org-my-skill-sources {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.org-skill-policy-row label,
.org-skill-form label {
display: grid;
gap: 6px;
}
.org-skill-preview-row {
padding: 12px;
border-top: 1px solid var(--border-subtle);
}
.org-my-skills article {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 16px 20px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
.org-my-skills article > div:last-child {
display: grid;
justify-items: end;
gap: 8px;
}
@media (max-width: 980px) {
.org-skills-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 640px) {
.org-skills-grid {
grid-template-columns: 1fr;
}
.org-skills-hero,
.org-my-skills article {
align-items: stretch;
flex-direction: column;
}
.org-my-skills article > div:last-child {
display: flex;
justify-content: space-between;
}
}
/* ============ 引入技能抽屉 ============ */
/* 平台超管与被顶栏配置挡在超市外的管理员,都从这里为企业启用平台技能。
* 配色全部 token 派生,随主题预设与亮暗自动适配。 */
.org-skill-import {
display: grid;
gap: 14px;
}
.org-skill-import-list {
display: grid;
gap: 10px;
margin: 0;
padding: 0;
list-style: none;
}
.org-skill-import-list > li {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 12px 14px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--surface-card);
transition: border-color 0.2s ease;
}
.org-skill-import-list > li:hover {
border-color: color-mix(in srgb, var(--brand-primary) 35%, transparent);
}
.org-skill-import-main {
display: grid;
gap: 2px;
min-width: 0;
flex: 1 1 220px;
}
/* 技能标识可能很长,必须截断而不是把行撑破 */
.org-skill-import-main > * {
overflow-wrap: anywhere;
}
.org-skill-import-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.org-skill-import button:focus-visible {
outline: 2px solid color-mix(in srgb, var(--brand-primary) 55%, transparent);
outline-offset: 2px;
}
+68
View File
@@ -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
*/
const FALLBACK_QUOTA_PER_CNY = 500000;
const quotaDetailKeys = new Set([
'quota',
'remain_quota',
'quota_limit',
'before_quota',
'after_quota',
'default_member_quota',
'cycle_quota',
'cycle_quota_delta',
'daily_quota',
'used_quota',
'total_used_quota',
'quota_used_in_period',
'membership_daily_quota',
'membership_used_quota',
]);
const cnyFormatter = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY',
currencyDisplay: 'narrowSymbol',
minimumFractionDigits: 2,
maximumFractionDigits: 6,
});
// 0 表示「不限制」的上限类字段(对应后端 QuotaLimit <= 0 跳过限额检查的语义):
// 这类字段渲染成 ¥0.00 会被误读成「零额度」,与真实语义完全相反。
const zeroMeansUnlimitedKeys = new Set(['quota_limit', 'default_member_quota']);
export function isZeroUnlimitedQuotaKey(key) {
return zeroMeansUnlimitedKeys.has(key);
}
export function isQuotaDetailValue(action, key) {
if (quotaDetailKeys.has(key)) return true;
if (action === 'update_quota_alert' && key === 'threshold') return true;
return action === 'admin_adjust_quota' && key === 'amount';
}
export function formatQuotaAsCNY(value, quotaPerCNY = FALLBACK_QUOTA_PER_CNY) {
const quota = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(quota)) return String(value);
const unit = Number(quotaPerCNY);
const safeUnit =
Number.isFinite(unit) && unit > 0 ? unit : FALLBACK_QUOTA_PER_CNY;
return cnyFormatter.format(quota / safeUnit);
}
@@ -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 {
formatQuotaAsCNY,
isQuotaDetailValue,
isZeroUnlimitedQuotaKey,
} from './orgAuditFormat.js';
test('formatQuotaAsCNY converts internal quota units to RMB at 500000:1', () => {
assert.equal(formatQuotaAsCNY(10000000), '¥20.00');
assert.equal(formatQuotaAsCNY(-5000000), '-¥10.00');
assert.equal(formatQuotaAsCNY(3763155038), '¥7,526.310076');
});
test('formatQuotaAsCNY preserves non-zero quota values down to one internal unit', () => {
assert.equal(formatQuotaAsCNY(1), '¥0.000002');
assert.equal(formatQuotaAsCNY(-1), '-¥0.000002');
assert.equal(formatQuotaAsCNY(2499), '¥0.004998');
});
test('formatQuotaAsCNY follows configured quota units and safely falls back', () => {
assert.equal(formatQuotaAsCNY(10000000, 1000000), '¥10.00');
assert.equal(formatQuotaAsCNY(10000000, Number.NaN), '¥20.00');
assert.equal(formatQuotaAsCNY(10000000, 0), '¥20.00');
});
test('isQuotaDetailValue covers every quota field rendered by org audit logs', () => {
for (const key of [
'remain_quota',
'quota_limit',
'before_quota',
'default_member_quota',
'cycle_quota',
'cycle_quota_delta',
]) {
assert.equal(isQuotaDetailValue('any_action', key), true, key);
}
assert.equal(isQuotaDetailValue('update_quota_alert', 'threshold'), true);
assert.equal(isQuotaDetailValue('admin_adjust_quota', 'amount'), true);
});
test('isZeroUnlimitedQuotaKey marks limit-type fields where 0 means unlimited', () => {
// quota_limit=0 表示不限制(后端 QuotaLimit <= 0 跳过限额检查),
// 渲染层必须显示「不限制」而不是 ¥0.00
assert.equal(isZeroUnlimitedQuotaKey('quota_limit'), true);
assert.equal(isZeroUnlimitedQuotaKey('default_member_quota'), true);
// 消费/调整类字段 0 就是真实的零金额
assert.equal(isZeroUnlimitedQuotaKey('quota'), false);
assert.equal(isZeroUnlimitedQuotaKey('amount'), false);
assert.equal(isZeroUnlimitedQuotaKey('used_quota'), false);
});
test('isQuotaDetailValue leaves unrelated counts and metadata unchanged', () => {
assert.equal(isQuotaDetailValue('admin_adjust_quota', 'max_tokens'), false);
assert.equal(
isQuotaDetailValue('update_member_quota', 'quota_period'),
false,
);
assert.equal(isQuotaDetailValue('create_token', 'amount'), false);
});
+49
View File
@@ -0,0 +1,49 @@
/*
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
*/
// parseOrgFeatureFlag 解析企业 feature_flags JSON 中某个开关的生效值。
// 语义必须与后端 model.OrgFeatureEnabled 完全一致(bool 原值 / 字符串仅
// 'true'、'1' 为真 / 数字非 0 为真),否则前端 tab 显隐会与后端
// RequireOrgFeature 的放行口径割裂——例如 `!!flags.key` 会把字符串
// 'false' 判为开启,展示一个后端必 403 的入口。
export function isOrgFeatureEnabled(flagsJson, key) {
if (!flagsJson) return false;
let flags = flagsJson;
if (typeof flagsJson === 'string') {
try {
flags = JSON.parse(flagsJson);
} catch {
return false;
}
}
const v = flags?.[key];
if (typeof v === 'boolean') return v;
if (typeof v === 'string') return v === 'true' || v === '1';
if (typeof v === 'number') return v !== 0;
return false;
}
export function parseOrgFeatureFlag(flagsJson, key) {
return isOrgFeatureEnabled(flagsJson, key);
}
export function canAccessOrgSettings(role, featureFlags) {
if (role === 'owner' || role === 'super_admin') return true;
return role === 'admin' && isOrgFeatureEnabled(featureFlags, 'data_security');
}
@@ -0,0 +1,54 @@
/*
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 {
canAccessOrgSettings,
isOrgFeatureEnabled,
parseOrgFeatureFlag,
} from './orgFeatureFlags.js';
test('organization feature flags accept the same truthy forms as the backend', () => {
assert.equal(
isOrgFeatureEnabled({ data_security: true }, 'data_security'),
true,
);
assert.equal(
isOrgFeatureEnabled({ data_security: '1' }, 'data_security'),
true,
);
assert.equal(
parseOrgFeatureFlag('{"data_security":1}', 'data_security'),
true,
);
assert.equal(
parseOrgFeatureFlag('{"data_security":"false"}', 'data_security'),
false,
);
assert.equal(parseOrgFeatureFlag('invalid-json', 'data_security'), false);
});
test('enterprise admins enter settings only when data security is authorized', () => {
assert.equal(canAccessOrgSettings('owner', {}), true);
assert.equal(canAccessOrgSettings('super_admin', {}), true);
assert.equal(canAccessOrgSettings('admin', { data_security: true }), true);
assert.equal(canAccessOrgSettings('admin', { data_security: false }), false);
assert.equal(canAccessOrgSettings('member', { data_security: true }), false);
});