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 (
{subjectTypeLabel(t, r.subject_type)} {subj.name} {!subj.exists && ( {t('主体已删除')} )} {subj.exists && subj.disabled && ( {t('已停用')} )}
); }, }, { title: t('周期'), dataIndex: 'cycle_type', render: (v) => cycleLabel(t, v), width: 110, }, { title: t('周期用量 / 上限'), width: 260, render: (_, r) => { if (!r.cycle_quota) return {t('不限')}; const pct = Math.min( 100, Math.round((r.used_in_cycle / r.cycle_quota) * 100), ); return (
= 90 ? 'var(--ui-color-danger)' : undefined} /> {renderQuota(r.used_in_cycle, 2)} {r.reserved_in_cycle > 0 ? ` (+${renderQuota(r.reserved_in_cycle, 2)} ${t('预留')})` : ''} / {renderQuota(r.cycle_quota, 2)}
); }, }, { title: t('超限动作'), dataIndex: 'over_limit_action', // 原型 120px;表头 nowrap,较长译文(如泰语)由表格自动撑开列宽,不截断 width: 120, render: () => t('拦截'), }, { title: t('状态'), dataIndex: 'status', width: 120, render: (v, record) => ( handleStatusChange(record, checked)} /> ), }, { title: t('操作'), width: 130, render: (_, r) => { const subj = subjectOf(r); return ( {/* 主体已删除的孤儿行改不了(后端 upsert 会因主体不存在报错),只留删除 */} {subj.exists && ( )} handleDelete(r)} > ); }, }, ]; const onLimits = tab === 'limits'; const limitsContent = ( <> {/* 原型 .eb-policy 说明条:替换原“预算实时拦截未生效”警告与 cap 说明两条 Banner */}
{t( '预算只设置「最多能花多少」的上限,不增加企业真实额度池;提额仅提高上限。', )}
} > } columns={columns} dataSource={list} loading={loading} pagination={{ resetOnDataChange: true }} rowKey='id' scroll={{ x: 1040 }} /> setModalVisible(false)} okText={t('保存')} cancelText={t('取消')} >
{editing ? (
{subjectTypeLabel(t, editing.subject_type)} {subjectOf(editing).name}
) : ( <> setSubjectType(v)} style={{ width: '100%' }} /> )} {editing && ( )}
); return (
{fundsAvailable ? ( <> {/* 预算限额 / 部门资金(weiyuan afc2a61a7):.oc-list-tabs 只切换下方内容 */} {onLimits ? limitsContent : } ) : ( limitsContent )}
); }; export default OrgBudgets;