2aa9d73325
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
563 lines
19 KiB
React
563 lines
19 KiB
React
import { formatIdReference } from '../../helpers/safeDisplay';
|
||
import { formatUserReference } from '../../helpers/safeDisplay';
|
||
import {
|
||
RefreshCw as ActionRefreshCw,
|
||
Check as ActionCheck,
|
||
X as ActionX,
|
||
} from '@/components/common/icons/ActionIcons';
|
||
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 '@/components/ui';
|
||
import { Users, TrendingUp, FileClock, Wallet } 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';
|
||
import DeptFundsPanel from './fund/DeptFundsPanel';
|
||
|
||
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');
|
||
// 部门资金(MaaS V2.1.0 P0):同时开通 dept 与 budget 才展示(M-08)
|
||
const fundsEnabled =
|
||
isFeatureEnabled(featureFlags, 'dept') &&
|
||
isFeatureEnabled(featureFlags, 'budget');
|
||
const [fundsRefreshKey, setFundsRefreshKey] = useState(0);
|
||
const [departments, setDepartments] = useState([]);
|
||
const [deptId, setDeptId] = useState(null);
|
||
const [myMemberId, setMyMemberId] = useState(0);
|
||
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 || formatIdReference(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 || formatIdReference(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) =>
|
||
formatUserReference(v || r.username, r.user_id, t('未知用户')),
|
||
},
|
||
{
|
||
title: t('消耗'),
|
||
dataIndex: 'quota',
|
||
render: (v) => renderQuota(v || 0, 6),
|
||
},
|
||
{ title: t('请求数'), dataIndex: 'requests' },
|
||
{ title: t('Token'), dataIndex: 'tokens' },
|
||
];
|
||
|
||
return (
|
||
<div className='uc-page'>
|
||
<OrgPageHeader
|
||
title={t('部门管理')}
|
||
subtitle={t('管理本部门成员额度、用量与审批')}
|
||
actions={
|
||
<>
|
||
<Select
|
||
value={deptId}
|
||
onChange={setDeptId}
|
||
placeholder={t('选择部门')}
|
||
style={{ width: 180 }}
|
||
optionList={departments.map((d) => ({
|
||
label: `${d.name || t('未命名部门')}(${d.member_count ?? 0})`,
|
||
value: d.id,
|
||
}))}
|
||
/>
|
||
<Button
|
||
theme='light'
|
||
icon={<ActionRefreshCw size={14} />}
|
||
onClick={() => {
|
||
if (tab === 'members') fetchMembers();
|
||
else if (tab === 'usage') fetchUsage();
|
||
else if (tab === 'funds') setFundsRefreshKey((k) => k + 1);
|
||
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={{ resetOnDataChange: true }}
|
||
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(--ui-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(--ui-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={{ resetOnDataChange: true }}
|
||
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(--ui-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] ||
|
||
formatIdReference(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={<ActionCheck size={14} />}
|
||
onClick={() => decide(r.id, 'approved')}
|
||
>
|
||
{t('通过')}
|
||
</Button>
|
||
<Button
|
||
size='small'
|
||
type='danger'
|
||
theme='light'
|
||
icon={<ActionX size={14} />}
|
||
onClick={() => decide(r.id, 'rejected')}
|
||
>
|
||
{t('拒绝')}
|
||
</Button>
|
||
</>
|
||
)}
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</TabPane>
|
||
)}
|
||
|
||
{fundsEnabled && (
|
||
<TabPane
|
||
tab={
|
||
<span className='inline-flex items-center gap-1.5'>
|
||
<Wallet size={14} /> {t('部门资金')}
|
||
</span>
|
||
}
|
||
itemKey='funds'
|
||
>
|
||
{tab === 'funds' && (
|
||
<DeptFundsPanel
|
||
orgId={orgId}
|
||
deptId={deptId}
|
||
deptName={
|
||
departments.find((d) => d.id === deptId)?.name || ''
|
||
}
|
||
refreshKey={fundsRefreshKey}
|
||
/>
|
||
)}
|
||
</TabPane>
|
||
)}
|
||
</Tabs>
|
||
</OrgPanel>
|
||
)}
|
||
|
||
<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;
|