/*
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 { 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 (
{v.x}
);
};
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) => (
{r.request_type === 'quota'
? renderQuota(parseDelta(r.payload), 2)
: '-'}
),
},
{
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' ? (
{r.request_type === 'quota'
? `${t('通过后将立即提高目标额度上限')} ${renderQuota(parseDelta(r.payload), 2)}`
: t('通过后将立即生效')}
{enforcementOff &&
BUDGET_SUBJECT_TYPES.includes(r.subject_type) && (
{t(
'注意:企业未开启「预算实时拦截」,本次提额不会立即影响实际使用,请先在企业设置开启。',
)}
)}
}
okType='warning'
position='topRight'
onConfirm={() => decide(r.id, 'approved')}
>
) : (
'-'
),
},
];
const filters = ['pending', 'approved', 'rejected', ''];
return (
);
};
export default OrgRequests;