/*
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, { useEffect, useRef, useState } from 'react';
import {
Modal,
Form,
Switch,
InputNumber,
Input,
Typography,
Banner,
Button,
Space,
} from '@/components/ui';
import { renderQuota } from '../../helpers';
const { Text } = Typography;
const defaultValues = {
id: 0,
name: '高频低消耗自动封号',
enabled: false,
window_minutes: 1440,
scan_interval_minutes: 10,
warn_min_requests: 500,
warn_max_avg_quota: 50,
auto_ban_enabled: true,
ban_min_requests: 1000,
ban_max_avg_quota: 5,
ban_max_total_quota: 5000,
notify_admin: true,
};
const RiskControlRulesModal = ({
visible,
onClose,
rules,
saveRule,
triggerScanNow,
t,
}) => {
const [form, setForm] = useState(defaultValues);
const [saving, setSaving] = useState(false);
// 仅在 Modal 由"关闭→打开"的瞬间同步表单,避免 rules 异步到达时覆盖用户正在编辑的值
const prevVisibleRef = useRef(false);
useEffect(() => {
if (visible && !prevVisibleRef.current) {
if (rules && rules.length > 0) {
setForm({ ...defaultValues, ...rules[0] });
} else {
setForm(defaultValues);
}
}
prevVisibleRef.current = visible;
}, [visible, rules]);
const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));
const handleSave = async (alsoScan) => {
// 仅在启用了自动封号时校验封号阈值
if (form.auto_ban_enabled) {
if (
form.ban_min_requests > 0 &&
form.ban_min_requests < form.warn_min_requests
) {
Modal.warning({
title: t('阈值不合法'),
content: t('封号最低请求数不能低于预警阈值'),
});
return;
}
if (
form.ban_max_avg_quota > 0 &&
form.warn_max_avg_quota > 0 &&
form.ban_max_avg_quota > form.warn_max_avg_quota
) {
Modal.warning({
title: t('阈值不合法'),
content: t('封号平均消耗上限不能高于预警阈值'),
});
return;
}
}
setSaving(true);
const ok = await saveRule(form);
setSaving(false);
if (!ok) return;
if (alsoScan) {
await triggerScanNow();
}
onClose();
};
return (
}
width={620}
>