8a48765a46
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
597 lines
19 KiB
React
597 lines
19 KiB
React
import { formatIdReference } from '../../helpers/safeDisplay';
|
||
import {
|
||
RefreshCw as ActionRefreshCw,
|
||
Plus as ActionPlus,
|
||
} from '@/components/common/icons/ActionIcons';
|
||
import TableEmpty from '../../components/common/table/TableEmpty';
|
||
import React, {
|
||
useCallback,
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
} from 'react';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { Switch } from 'antd';
|
||
import {
|
||
Table,
|
||
Button,
|
||
Form,
|
||
Toast,
|
||
Tag,
|
||
Progress,
|
||
Popconfirm,
|
||
} from '@/components/ui';
|
||
import { Tabs as AntTabs } from 'antd';
|
||
import { API } from '../../helpers/api';
|
||
import { showError } from '../../helpers';
|
||
import {
|
||
renderQuota,
|
||
displayAmountToQuota,
|
||
quotaToDisplayAmount,
|
||
getQuotaInputUnit,
|
||
} from '../../helpers/render';
|
||
import OrgPageHeader from './components/OrgPageHeader';
|
||
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
|
||
import OrgModal from './components/OrgModal';
|
||
import OrgDeptFunds from './fund/OrgDeptFunds';
|
||
import { isOrgFeatureEnabled } from './orgFeatureFlags';
|
||
|
||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||
|
||
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,不增企业池。
|
||
// 「部门资金」页签(MaaS V2.1.0 P0):同时开通 dept 与 budget 才展示(M-08)。
|
||
const OrgBudgets = ({ orgId, featureFlags }) => {
|
||
const { t } = useTranslation();
|
||
const fundsAvailable =
|
||
isOrgFeatureEnabled(featureFlags, 'dept') &&
|
||
isOrgFeatureEnabled(featureFlags, 'budget');
|
||
const [tab, setTab] = useState('limits');
|
||
const [list, setList] = useState([]);
|
||
const [loading, setLoading] = useState(false);
|
||
const [updatingBudgetId, setUpdatingBudgetId] = useState(null);
|
||
const updatingBudgetRef = useRef(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 options = {
|
||
headers: getOrgHeaders(orgId),
|
||
requestGroup: new AbortController(),
|
||
};
|
||
const [b, d, p] = await Promise.all([
|
||
API.get('/api/org/budget', options),
|
||
API.get('/api/org/dept', options),
|
||
API.get('/api/org/project', options),
|
||
]);
|
||
if (b.data.success) {
|
||
// 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组。
|
||
// enforcement/engine 两个字段原只驱动表格上方旧提示栏,提示栏按原型移除后不再读取。
|
||
const payload = b.data.data;
|
||
setList(Array.isArray(payload) ? payload || [] : payload?.items || []);
|
||
} else {
|
||
showError(b.data.message);
|
||
}
|
||
if (d.data.success) setDepts(d.data.data || []);
|
||
if (p.data.success) setProjects(p.data.data || []);
|
||
} catch (err) {
|
||
if (!err?.isAxiosError) showError(err);
|
||
} 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 || formatIdReference(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 || formatIdReference(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 || formatIdReference(r.subject_id),
|
||
exists: !!p,
|
||
disabled: p?.status === 2,
|
||
};
|
||
}
|
||
// 旧后端下成员/密钥无从解析,按存在处理,避免误标「已删除」
|
||
return {
|
||
name: formatIdReference(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 handleStatusChange = async (record, enabled) => {
|
||
if (
|
||
updatingBudgetRef.current ||
|
||
(record.status === 1) === enabled ||
|
||
!subjectOf(record).exists
|
||
)
|
||
return;
|
||
updatingBudgetRef.current = true;
|
||
setUpdatingBudgetId(record.id);
|
||
try {
|
||
// Reuse the edit upsert contract with raw quotas, without currency conversion.
|
||
const res = await API.put(
|
||
'/api/org/budget',
|
||
{
|
||
subject_type: record.subject_type,
|
||
subject_id: record.subject_id,
|
||
cycle_type: record.cycle_type,
|
||
cycle_quota: record.cycle_quota,
|
||
total_quota: record.total_quota,
|
||
custom_cycle_days: record.custom_cycle_days || 0,
|
||
over_limit_action: record.over_limit_action,
|
||
status: enabled ? 1 : 2,
|
||
},
|
||
{ headers: getOrgHeaders(orgId), skipErrorHandler: true },
|
||
);
|
||
if (res.data.success) {
|
||
Toast.success({
|
||
content: t('状态已更新'),
|
||
key: `org-budget-status-${orgId}-${record.id}`,
|
||
});
|
||
setList((items) =>
|
||
items.map((item) =>
|
||
item.id === record.id ? { ...item, status: enabled ? 1 : 2 } : item,
|
||
),
|
||
);
|
||
} else {
|
||
showError(res.data.message);
|
||
}
|
||
} catch (err) {
|
||
showError(err.message);
|
||
} finally {
|
||
updatingBudgetRef.current = false;
|
||
setUpdatingBudgetId(null);
|
||
}
|
||
};
|
||
|
||
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);
|
||
}
|
||
};
|
||
|
||
// 列宽与渲染对齐原型 EnterpriseBudget(300/110/260/120/120/130,scroll.x 1040);取值与判定沿用原逻辑
|
||
const columns = [
|
||
{
|
||
title: t('主体'),
|
||
width: 300,
|
||
render: (_, r) => {
|
||
const subj = subjectOf(r);
|
||
return (
|
||
<div className='oc-budget-subject'>
|
||
<Tag color='gold' bordered={false}>
|
||
{subjectTypeLabel(t, r.subject_type)}
|
||
</Tag>
|
||
<span className={subj.exists ? '' : 'oc-muted line-through'}>
|
||
{subj.name}
|
||
</span>
|
||
{!subj.exists && (
|
||
<Tag color='red' bordered={false}>
|
||
{t('主体已删除')}
|
||
</Tag>
|
||
)}
|
||
{subj.exists && subj.disabled && (
|
||
<Tag color='grey' bordered={false}>
|
||
{t('已停用')}
|
||
</Tag>
|
||
)}
|
||
</div>
|
||
);
|
||
},
|
||
},
|
||
{
|
||
title: t('周期'),
|
||
dataIndex: 'cycle_type',
|
||
render: (v) => cycleLabel(t, v),
|
||
width: 110,
|
||
},
|
||
{
|
||
title: t('周期用量 / 上限'),
|
||
width: 260,
|
||
render: (_, r) => {
|
||
if (!r.cycle_quota)
|
||
return <span className='oc-budget-unlimited'>{t('不限')}</span>;
|
||
const pct = Math.min(
|
||
100,
|
||
Math.round((r.used_in_cycle / r.cycle_quota) * 100),
|
||
);
|
||
return (
|
||
<div className='oc-budget-usage'>
|
||
<Progress
|
||
percent={pct}
|
||
size='small'
|
||
showInfo={false}
|
||
stroke={pct >= 90 ? 'var(--ui-color-danger)' : undefined}
|
||
/>
|
||
<span>
|
||
{renderQuota(r.used_in_cycle, 2)}
|
||
{r.reserved_in_cycle > 0
|
||
? ` (+${renderQuota(r.reserved_in_cycle, 2)} ${t('预留')})`
|
||
: ''}
|
||
<i>/</i>
|
||
{renderQuota(r.cycle_quota, 2)}
|
||
</span>
|
||
</div>
|
||
);
|
||
},
|
||
},
|
||
{
|
||
title: t('超限动作'),
|
||
dataIndex: 'over_limit_action',
|
||
// 原型 120px;表头 nowrap,较长译文(如泰语)由表格自动撑开列宽,不截断
|
||
width: 120,
|
||
render: () => t('拦截'),
|
||
},
|
||
{
|
||
title: t('状态'),
|
||
dataIndex: 'status',
|
||
width: 120,
|
||
render: (v, record) => (
|
||
<Switch
|
||
size='small'
|
||
checked={v === 1}
|
||
checkedChildren={t('启用')}
|
||
unCheckedChildren={t('禁用')}
|
||
aria-label={`${subjectOf(record).name} ${t('状态')}`}
|
||
loading={updatingBudgetId === record.id}
|
||
disabled={updatingBudgetId !== null || !subjectOf(record).exists}
|
||
onChange={(checked) => handleStatusChange(record, checked)}
|
||
/>
|
||
),
|
||
},
|
||
{
|
||
title: t('操作'),
|
||
width: 130,
|
||
render: (_, r) => {
|
||
const subj = subjectOf(r);
|
||
return (
|
||
<OrgRowActions>
|
||
{/* 主体已删除的孤儿行改不了(后端 upsert 会因主体不存在报错),只留删除 */}
|
||
{subj.exists && (
|
||
<Button type='link' onClick={() => openEdit(r)}>
|
||
{t('编辑')}
|
||
</Button>
|
||
)}
|
||
<Popconfirm
|
||
title={t('确认删除该预算?')}
|
||
content={t(
|
||
'删除后该主体不再受此额度上限约束,历史用量流水保留不受影响',
|
||
)}
|
||
onConfirm={() => handleDelete(r)}
|
||
>
|
||
<Button type='link' danger>
|
||
{t('删除')}
|
||
</Button>
|
||
</Popconfirm>
|
||
</OrgRowActions>
|
||
);
|
||
},
|
||
},
|
||
];
|
||
|
||
const onLimits = tab === 'limits';
|
||
const limitsContent = (
|
||
<>
|
||
{/* 原型 .eb-policy 说明条:替换原“预算实时拦截未生效”警告与 cap 说明两条 Banner */}
|
||
<div className='oc-policy' role='note'>
|
||
{t(
|
||
'预算只设置「最多能花多少」的上限,不增加企业真实额度池;提额仅提高上限。',
|
||
)}
|
||
</div>
|
||
|
||
<OrgListCard
|
||
title={t('预算列表')}
|
||
tools={
|
||
<>
|
||
<Button
|
||
icon={<ActionRefreshCw size={16} />}
|
||
loading={loading}
|
||
onClick={fetchAll}
|
||
>
|
||
{t('刷新')}
|
||
</Button>
|
||
<Button
|
||
theme='solid'
|
||
icon={<ActionPlus size={16} />}
|
||
onClick={openCreate}
|
||
>
|
||
{t('配置预算')}
|
||
</Button>
|
||
</>
|
||
}
|
||
>
|
||
<Table
|
||
empty={<TableEmpty />}
|
||
columns={columns}
|
||
dataSource={list}
|
||
loading={loading}
|
||
pagination={{ resetOnDataChange: true }}
|
||
rowKey='id'
|
||
scroll={{ x: 1040 }}
|
||
/>
|
||
</OrgListCard>
|
||
|
||
<OrgModal
|
||
className='oc-dialog oc-budget-dialog'
|
||
width={560}
|
||
title={editing ? t('编辑预算') : t('配置预算')}
|
||
visible={modalVisible}
|
||
onOk={submit}
|
||
onCancel={() => setModalVisible(false)}
|
||
okText={t('保存')}
|
||
cancelText={t('取消')}
|
||
>
|
||
<Form getFormApi={setFormApi}>
|
||
{editing ? (
|
||
<div className='oc-budget-edit-subject'>
|
||
<Tag color='gold' bordered={false}>
|
||
{subjectTypeLabel(t, editing.subject_type)}
|
||
</Tag>
|
||
<strong>{subjectOf(editing).name}</strong>
|
||
</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>
|
||
</>
|
||
);
|
||
|
||
return (
|
||
<div className='uc-page oc-page'>
|
||
<OrgPageHeader
|
||
title={t('预算中心')}
|
||
subtitle={
|
||
onLimits
|
||
? t('管理部门、项目与成员的额度上限')
|
||
: t('将企业资金分配给部门独立使用,与预算限额分别计算')
|
||
}
|
||
/>
|
||
{fundsAvailable ? (
|
||
<>
|
||
{/* 预算限额 / 部门资金(weiyuan afc2a61a7):.oc-list-tabs 只切换下方内容 */}
|
||
<AntTabs
|
||
className='oc-list-tabs oc-tabs-nav-only'
|
||
activeKey={tab}
|
||
onChange={setTab}
|
||
items={[
|
||
{ key: 'limits', label: t('预算限额') },
|
||
{ key: 'funds', label: t('部门资金') },
|
||
]}
|
||
/>
|
||
{onLimits ? limitsContent : <OrgDeptFunds orgId={orgId} />}
|
||
</>
|
||
) : (
|
||
limitsContent
|
||
)}
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default OrgBudgets;
|