/* 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 . 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 ( {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: 90, }, { title: t('周期用量 / cap'), width: 220, 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(--semi-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', // 90px 是按中文两字标签定的,泰语最短的地道说法 "เมื่อเกินขีดจำกัด" 也要 ~150px; // 这一列没有更短的译法,只能让列让位(其余列头已在 kt_overrides_th.json 收敛用词) width: 150, render: () => t('拦截'), }, { title: t('状态'), dataIndex: 'status', width: 80, render: (v) => ( {v === 1 ? t('启用') : t('停用')} ), }, { title: t('操作'), width: 160, render: (_, r) => { const subj = subjectOf(r); return (
{/* 主体已删除的孤儿行改不了(后端 upsert 会因主体不存在报错),只留删除 */} {subj.exists && ( )} handleDelete(r)} >
); }, }, ]; return (
} /> {enforcementEnabled === false && ( )} setModalVisible(false)} okText={t('保存')} cancelText={t('取消')} >
{editing ? (
{subjectTypeLabel(t, editing.subject_type)} {' '} {subjectOf(editing).name}
) : ( <> setSubjectType(v)} style={{ width: '100%' }} /> )} {editing && ( )}
); }; export default OrgBudgets;