Initial import of weiyuan frontend
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user