Files
monkey-ai-web/src/pages/Organization/OrgRequests.jsx
T

312 lines
10 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import TableEmpty from '../../components/common/table/TableEmpty';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Form as AntForm, Tabs as AntTabs } from 'antd';
import { Table, Button, Tag, Toast, Input, Popconfirm } from '@/components/ui';
import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers';
import { renderQuota } from '../../helpers/render';
import { formatIdReference } from '../../helpers/safeDisplay';
import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import { orgStatusColor } from './components/orgStatus';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const isFeatureEnabled = (flags, key) => {
const value = flags?.[key];
return value === true || value === 'true' || value === '1' || value === 1;
};
// 预算主体(dept/project/org/token 的提额加的是预算 cap,需开启实时拦截才生效);
// member 主体改的是个人 quota_limit,始终生效。
const BUDGET_SUBJECT_TYPES = ['department', 'project', 'org', 'token'];
const statusTag = (t, s) => {
const m = {
pending: { x: t('待审批') },
approved: { x: t('已通过') },
rejected: { x: t('已拒绝') },
canceled: { x: t('已取消') },
expired: { x: t('已过期') },
};
const v = m[s] || { x: s };
return (
<Tag color={orgStatusColor(s)} bordered={false}>
{v.x}
</Tag>
);
};
const parseDelta = (payload) => {
try {
return JSON.parse(payload || '{}').cycle_quota_delta || 0;
} catch {
return 0;
}
};
// 审批中心:管理员审批提额申请(PR7)。通过即原子提高目标预算 cap。
const OrgRequests = ({ orgId, orgRole, featureFlags }) => {
const { t } = useTranslation();
const isApprover =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const enforcementOff = !isFeatureEnabled(featureFlags, 'budget_enforcement');
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const [statusFilter, setStatusFilter] = useState('pending');
const [rejectFor, setRejectFor] = useState(null);
const [rejectComment, setRejectComment] = useState('');
const listSeqRef = useRef(0);
const fetchList = useCallback(async () => {
if (!orgId) return;
// 翻页把一次加载从 1 个请求放大到最多 20 个,切换筛选的竞态窗口随之变大:
// 旧筛选的翻页循环若在新请求之后才结束,会用旧数据覆盖列表。用 seq 围栏
// 让过期的循环提前停止、且不再 setState。
const seq = ++listSeqRef.current;
setLoading(true);
try {
// 逐页取全:后端把 page_size 静默钳到 100,申请数超过 100 条时
// 原先的单次请求会让较早的申请无声消失在列表外。
const { items, message } = await collectPagedItems(
(page, size) =>
// 页码参数必须是 p —— common.GetPageQuery 只读 p/ps/size,从不读
// page。原先写死 page=1 时这个错误无害(后端拿不到就默认第 1 页),
// 改成翻页后却会让每一页都返回第 1 页,把同样的 100 条累加多次。
API.get(
`/api/org/requests?p=${page}&page_size=${size}${statusFilter ? `&status=${statusFilter}` : ''}`,
{ headers: getOrgHeaders(orgId) },
),
{ shouldAbort: () => seq !== listSeqRef.current },
);
if (seq !== listSeqRef.current) return;
setList(items);
if (message) showError(message);
} catch (err) {
if (seq === listSeqRef.current) showError(err.message);
} finally {
if (seq === listSeqRef.current) setLoading(false);
}
}, [orgId, statusFilter]);
useEffect(() => {
fetchList();
}, [fetchList]);
const decide = async (id, decision, comment) => {
try {
const res = await API.put(
`/api/org/requests/${id}/decision`,
{ decision, comment: comment || '' },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(decision === 'approved' ? t('已通过') : t('已拒绝'));
setRejectFor(null);
setRejectComment('');
fetchList();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
// 列宽与渲染对齐原型 EnterpriseApprovals(80/90/210/140/300/120/130,scroll.x 1080)
const columns = [
{ title: 'ID', dataIndex: 'id', width: 80 },
{
title: t('类型'),
dataIndex: 'request_type',
width: 90,
render: (v) => (v === 'quota' ? t('提额') : v),
},
{
title: t('对象'),
width: 210,
ellipsis: true,
render: (_, r) => {
const label =
{
project: t('项目'),
department: t('部门'),
member: t('成员'),
token: t('密钥'),
org: t('企业'),
}[r.subject_type] || r.subject_type;
// 后端已富化 subject_name;主体被删除等极端情况回退为 #ID
return r.subject_name
? `${label} · ${r.subject_name}`
: `${label} ${formatIdReference(r.subject_id, t('未知主体'))}`;
},
},
{
title: t('提额'),
width: 140,
render: (_, r) => (
<span className='oc-number'>
{r.request_type === 'quota'
? renderQuota(parseDelta(r.payload), 2)
: '-'}
</span>
),
},
{
title: t('理由'),
dataIndex: 'reason',
width: 300,
ellipsis: true,
render: (v) => v || '-',
},
{
title: t('状态'),
dataIndex: 'status',
width: 120,
render: (v) => statusTag(t, v),
},
{
title: t('操作'),
width: 130,
render: (_, r) =>
isApprover && r.status === 'pending' ? (
<OrgRowActions>
<Popconfirm
title={t('确认通过该提额申请?')}
content={
<div className='max-w-xs'>
<div>
{r.request_type === 'quota'
? `${t('通过后将立即提高目标额度上限')} ${renderQuota(parseDelta(r.payload), 2)}`
: t('通过后将立即生效')}
</div>
{enforcementOff &&
BUDGET_SUBJECT_TYPES.includes(r.subject_type) && (
<div className='mt-1.5 text-xs text-amber-600 dark:text-amber-400'>
{t(
'注意:企业未开启「预算实时拦截」,本次提额不会立即影响实际使用,请先在企业设置开启。',
)}
</div>
)}
</div>
}
okType='warning'
position='topRight'
onConfirm={() => decide(r.id, 'approved')}
>
<Button type='link'>{t('通过')}</Button>
</Popconfirm>
<Button type='link' danger onClick={() => setRejectFor(r.id)}>
{t('拒绝')}
</Button>
</OrgRowActions>
) : (
'-'
),
},
];
const filters = ['pending', 'approved', 'rejected', ''];
return (
<div className='uc-page oc-page'>
<OrgPageHeader
title={isApprover ? t('审批中心') : t('我的申请')}
subtitle={t('提额申请与审批')}
/>
{/* 原型 platform-list-tabs:状态筛选页签(只切换筛选,不承载内容),回调沿用 setStatusFilter */}
<AntTabs
className='oc-list-tabs oc-tabs-nav-only'
activeKey={statusFilter || 'all'}
onChange={(key) => setStatusFilter(key === 'all' ? '' : key)}
items={filters.map((f) => ({
key: f || 'all',
label:
f === 'pending'
? t('待审批')
: f === 'approved'
? t('已通过')
: f === 'rejected'
? t('已拒绝')
: t('全部'),
}))}
/>
<OrgListCard
title={t('申请列表')}
tools={
<Button
icon={<ActionRefreshCw size={16} />}
loading={loading}
onClick={fetchList}
>
{t('刷新')}
</Button>
}
>
<Table
columns={columns}
dataSource={list}
loading={loading}
empty={<TableEmpty />}
pagination={{
resetOnDataChange: true,
showTotal: (total) => t('共 {{total}} 条', { total }),
}}
rowKey='id'
scroll={{ x: 1080 }}
/>
</OrgListCard>
<OrgModal
className='oc-dialog oc-reject-dialog'
width={520}
title={t('拒绝申请')}
visible={!!rejectFor}
onOk={() => decide(rejectFor, 'rejected', rejectComment)}
onCancel={() => {
setRejectFor(null);
setRejectComment('');
}}
okText={t('确认拒绝')}
cancelText={t('取消')}
>
{/* 原型:竖排表单项“拒绝理由(可选)”;仅布局,取值与提交沿用 rejectComment / decide */}
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('拒绝理由(可选)')}>
<Input
placeholder={t('请输入拒绝理由')}
value={rejectComment}
onChange={setRejectComment}
/>
</AntForm.Item>
</AntForm>
</OrgModal>
</div>
);
};
export default OrgRequests;