/*
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,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { ListChecks, ShieldPlus } from 'lucide-react';
import {
Button,
Input,
Popconfirm,
Select,
Spin,
Switch,
Table,
Tag,
Toast,
Typography,
} from '@/components/ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgPanel from '../components/OrgPanel';
import OrgModal from '../components/OrgModal';
const EMPTY_RULE_DRAFT = {
name: '',
category: '',
pattern: '',
pii_level: 'general',
enabled: true,
};
const PII_LEVEL_OPTIONS = [
{ value: 'general', label: '一般个人信息' },
{ value: 'sensitive', label: '敏感个人信息' },
];
const piiLevelTag = (v, t) =>
v === 'sensitive' ? (
{t('敏感')}
) : (
{t('一般')}
);
// OrgDsRules 企业私有自定义规则子 tab:平台规则只读展示 + 本企业规则 CRUD。
// 企业规则只增加检测项(收紧)、仅对本企业流量生效,保存后即时生效(多节点约 1 分钟同步)。
const OrgDsRules = ({ orgId, isSuperAdmin }) => {
const { t } = useTranslation();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const [platformRules, setPlatformRules] = useState([]);
const [customRules, setCustomRules] = useState([]);
const [quota, setQuota] = useState({ used: 0, max: 20 });
// 规则编辑弹窗(受控字段,null=关闭;editingId=null 表示新增)
const [modalVisible, setModalVisible] = useState(false);
const [editingId, setEditingId] = useState(null);
const [draft, setDraft] = useState({ ...EMPTY_RULE_DRAFT });
const [submitting, setSubmitting] = useState(false);
// 请求代次:连续增删触发的多次刷新可能乱序返回,旧响应不得覆盖新列表
// (否则刚删除的规则会短暂"复活",R41;同 OrgDsHitLogs 的 seq 守卫模式)。
const rulesSeqRef = useRef(0);
const fetchRules = useCallback(async () => {
const seq = ++rulesSeqRef.current;
setLoading(true);
setLoadError(false);
try {
const res = await API.get('/api/org/data-security/rules', { headers });
if (seq !== rulesSeqRef.current) return;
if (res.data.success && res.data.data) {
setPlatformRules(res.data.data.platform || []);
setCustomRules(res.data.data.custom || []);
setQuota(res.data.data.quota || { used: 0, max: 20 });
} else {
setLoadError(true);
showError(res.data.message || t('规则列表加载失败'));
}
} catch (err) {
if (seq !== rulesSeqRef.current) return;
setLoadError(true);
if (err?.name !== 'AxiosError') showError(err);
} finally {
if (seq === rulesSeqRef.current) setLoading(false);
}
}, [headers, t]);
useEffect(() => {
fetchRules();
}, [fetchRules]);
const openCreate = () => {
setEditingId(null);
setDraft({ ...EMPTY_RULE_DRAFT });
setModalVisible(true);
};
const openEdit = (rule) => {
setEditingId(rule.id);
setDraft({
name: rule.name || '',
category: rule.category || '',
pattern: rule.pattern || '',
pii_level: rule.pii_level || 'general',
enabled: !!rule.enabled,
});
setModalVisible(true);
};
const submitRule = async () => {
if (!draft.name.trim()) {
showError(t('规则名称不能为空'));
return;
}
if (!draft.pattern.trim()) {
showError(t('正则不能为空'));
return;
}
setSubmitting(true);
try {
const payload = { ...draft, name: draft.name.trim() };
const res = editingId
? await API.put(`/api/org/data-security/rules/${editingId}`, payload, {
headers,
})
: await API.post('/api/org/data-security/rules', payload, { headers });
if (res.data.success) {
Toast.success(t('规则已保存并即时生效'));
setModalVisible(false);
fetchRules();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (err) {
if (err?.name !== 'AxiosError') showError(err);
} finally {
setSubmitting(false);
}
};
const deleteRule = async (rule) => {
try {
const res = await API.delete(`/api/org/data-security/rules/${rule.id}`, {
headers,
});
if (res.data.success) {
Toast.success(t('删除成功'));
fetchRules();
} else {
showError(res.data.message || t('删除失败'));
}
} catch (err) {
if (err?.name !== 'AxiosError') showError(err);
}
};
const platformColumns = [
{ title: t('规则名'), dataIndex: 'name' },
{ title: t('类别'), dataIndex: 'category' },
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{
title: t('来源'),
dataIndex: 'builtin',
render: (v) =>
v ? (
{t('内置规则')}
) : (
{t('平台自定义')}
),
},
];
const customColumns = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{
title: t('规则名'),
dataIndex: 'name',
render: (v) => {v},
},
{ title: t('类别'), dataIndex: 'category' },
{
title: t('正则'),
dataIndex: 'pattern',
render: (v) => (
{v}
),
},
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{
title: t('启用'),
dataIndex: 'enabled',
render: (v) =>
v ? {t('启用')} : {t('停用')},
},
...(isSuperAdmin
? []
: [
{
title: t('操作'),
width: 150,
render: (_, rule) => (
deleteRule(rule)}
>
),
},
]),
];
return (
{loadError && (
{t('规则列表加载失败,请重试。')}
)}
{t('配额')} {quota.used}/{quota.max}
)
}
>
{t(
'自定义规则使用 RE2 正则(线性时间、抗 ReDoS),不超过 500 字符、不得匹配空串。命中后与平台规则同等参与脱敏;敏感级规则会触发敏感个人信息策略。保存后即时生效(多节点约 1 分钟内同步)。',
)}
{t(
'暂无企业自定义规则。点击「新增规则」为本企业增加专属检测项(如员工号、内部项目代号)。',
)}
}
/>
({ ...r, _key: i }))}
pagination={{ resetOnDataChange: true }}
rowKey='_key'
size='small'
scroll={{ x: 'max(100%, 640px)' }}
/>
setModalVisible(false)}
okButtonProps={{ loading: submitting }}
maskClosable={false}
>
);
};
export default OrgDsRules;