Files
monkey-ai-web/src/pages/AdminOrganizations/OrgAlertSettingsModal.jsx
T

579 lines
20 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
*/
// 企业通知预警 · 通知设置弹窗(方案 11 号文档 §8-2 / §8.1)
// 配置存储为 org_alert_setting.* 的 option 行(root-only,未登记下放白名单即天然 root-only)。
// 密钥回读为 ***ALREADY_SET*** 时置空展示、未改动不提交,防掩码覆盖真值。
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Modal,
Input,
InputNumber,
Select,
Switch,
Spin,
Button,
Tag,
TimePicker,
Collapse,
Toast,
} from '@/components/ui';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
const OPTION_PREFIX = 'org_alert_setting.';
// 字段默认值与后端 setting/operation_setting/org_alert_setting.go 保持一致
const DEFAULTS = {
enabled: false,
scan_interval_minutes: 30,
title_prefix: '',
excluded_org_ids: '',
test_stage_threshold: 1000,
webhook_url: '',
WebhookSecret: '',
webhook_format: 'generic',
market_webhook_url: '',
MarketWebhookSecret: '',
market_webhook_format: '',
daily_report_enabled: true,
daily_report_time: '09:00',
daily_report_max_rows: 50,
daily_report_include_inactive: false,
no_consumption_enabled: true,
no_consumption_days: 3,
no_consumption_min_amount: 0,
exhausted_prod_enabled: true,
exhausted_test_enabled: true,
exhausted_threshold: 1,
};
const BOOL_KEYS = new Set([
'enabled',
'daily_report_enabled',
'daily_report_include_inactive',
'no_consumption_enabled',
'exhausted_prod_enabled',
'exhausted_test_enabled',
]);
const NUMBER_KEYS = new Set([
'scan_interval_minutes',
'test_stage_threshold',
'daily_report_max_rows',
'no_consumption_days',
'no_consumption_min_amount',
'exhausted_threshold',
]);
const SECRET_KEYS = new Set(['WebhookSecret', 'MarketWebhookSecret']);
// V1 仅放出三种格式,dingtalk 枚举预留 V2(方案 §6.1)。
// 标签走 t():模块级常量里写死中文会在英文界面直显中文。
const formatOptions = (t) => [
{ value: 'generic', label: t('通用 JSON') },
{ value: 'feishu', label: t('飞书机器人') },
{ value: 'wecom', label: t('企业微信机器人') },
];
const parseOptionValue = (key, raw) => {
if (BOOL_KEYS.has(key)) return raw === 'true';
if (NUMBER_KEYS.has(key)) {
const n = parseFloat(raw);
return Number.isFinite(n) ? n : DEFAULTS[key];
}
return raw ?? '';
};
// 后端这几个字段是 Go int:存进小数或空串会让 ParseInt 失败而"静默保持旧值"——
// 界面显示已保存、实际未生效,重启后还会退回编译期默认值。这里取整兜底,
// 配合 InputNumber 的 precision={0}。
const INT_KEYS = new Set([
'scan_interval_minutes',
'daily_report_max_rows',
'no_consumption_days',
]);
const serializeValue = (key, value) => {
if (BOOL_KEYS.has(key)) return value ? 'true' : 'false';
if (NUMBER_KEYS.has(key)) {
// 清空输入框给的是 '',Number('') === 0 会把配置存成字面 0:
// 后端各自钳制成 5 分钟/1 天/最小阈值,于是"界面显示 0、引擎按别的值跑"。
// 空值一律回落该字段的默认值。
if (value === '' || value === null || value === undefined) {
return String(DEFAULTS[key]);
}
const n = Number(value);
if (!Number.isFinite(n)) return String(DEFAULTS[key]);
return String(INT_KEYS.has(key) ? Math.round(n) : n);
}
return String(value ?? '');
};
const OrgAlertSettingsModal = ({ visible, onClose, onSaved }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState('');
const [form, setForm] = useState({ ...DEFAULTS });
// 已加载的原始值(序列化后),保存时只提交变更过的字段
const [loaded, setLoaded] = useState({});
// 密钥是否已设置(回读为掩码):置空展示 placeholder,未改动不提交
const [secretSet, setSecretSet] = useState({});
useEffect(() => {
if (!visible) return;
let cancelled = false;
(async () => {
setLoading(true);
try {
const res = await API.get('/api/option/');
if (cancelled) return;
if (!res.data?.success) {
showError(res.data?.message || t('配置加载失败'));
return;
}
const next = { ...DEFAULTS };
const raw = {};
const secrets = {};
(res.data.data || []).forEach(({ key, value }) => {
if (!key.startsWith(OPTION_PREFIX)) return;
const field = key.slice(OPTION_PREFIX.length);
if (!(field in DEFAULTS)) return;
if (SECRET_KEYS.has(field)) {
// 后端对空密钥根本不返回该 key,所以行存在即已设置(掩码值同理非空)
secrets[field] = value !== '';
next[field] = '';
raw[field] = '';
return;
}
next[field] = parseOptionValue(field, value);
raw[field] = value;
});
setForm(next);
setLoaded(raw);
setSecretSet(secrets);
} catch (err) {
// 传 error 对象而非 err.message:showError 只有拿到 AxiosError 对象才会把
// 401/429/500/网络错误翻成中文,传字符串会直显 "Request failed with status code 500"
if (!cancelled) showError(err);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [visible, t]);
const setField = (key) => (value) => setForm((f) => ({ ...f, [key]: value }));
const excludedIdList = (form.excluded_org_ids || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const handleSave = async () => {
setSaving(true);
try {
const puts = [];
Object.keys(DEFAULTS).forEach((key) => {
if (SECRET_KEYS.has(key)) {
// 密钥留空 = 不修改(防把掩码/空值覆盖回真值)
if ((form[key] || '').trim() !== '') {
puts.push({ key: OPTION_PREFIX + key, value: form[key].trim() });
}
return;
}
const serialized = serializeValue(key, form[key]);
const before =
key in loaded ? loaded[key] : serializeValue(key, DEFAULTS[key]);
if (serialized !== before) {
puts.push({ key: OPTION_PREFIX + key, value: serialized });
}
});
for (const item of puts) {
const res = await API.put('/api/option/', item);
if (!res.data?.success) {
showError(res.data?.message || t('保存失败'));
return;
}
}
Toast.success(
puts.length ? t('通知设置已保存') : t('没有需要保存的变更'),
);
onSaved?.();
onClose();
} catch (err) {
showError(err);
} finally {
setSaving(false);
}
};
const handleTest = async (channel) => {
setTesting(channel);
try {
const res = await API.post('/api/org_alert/test', { channel });
if (res.data?.success) {
// 市场通道未配地址时后端会回落默认通道,必须如实告知,否则会误以为市场通道已配好
if (res.data?.data?.fell_back) {
Toast.warning(res.data.data.message);
} else {
Toast.success(t('测试消息已发送,请到目标群确认'));
}
} else {
// 透传后端具体失败原因(SSRF 拒绝 / 对端错误码),便于排障
showError(res.data?.message || t('测试发送失败'));
}
} catch (err) {
showError(err);
} finally {
setTesting('');
}
};
const timeToDate = (str) => {
const m = /^(\d{1,2}):(\d{2})$/.exec(str || '');
const d = new Date();
d.setHours(m ? parseInt(m[1], 10) : 9, m ? parseInt(m[2], 10) : 0, 0, 0);
return d;
};
const labelCls =
'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
const sectionCls =
'text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500 pt-2';
const rowCls = 'flex items-center justify-between gap-3';
return (
<Modal
title={t('企业预警通知设置')}
visible={visible}
onOk={handleSave}
onCancel={onClose}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
width={640}
style={{ maxWidth: 'calc(100vw - 32px)' }}
bodyStyle={{
maxHeight: 'calc(100vh - 220px)',
overflowY: 'auto',
overscrollBehavior: 'contain',
scrollbarGutter: 'stable',
}}
>
{loading ? (
<div className='flex justify-center py-10'>
<Spin size='large' />
</div>
) : (
<div className='space-y-4'>
{/* —— 通用 —— */}
<div className={sectionCls}>{t('通用')}</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('启用企业预警通知')}
</span>
<Switch checked={form.enabled} onChange={setField('enabled')} />
</div>
<div className='grid grid-cols-2 gap-3'>
<div>
<label className={labelCls}>{t('扫描周期(分钟)')}</label>
<InputNumber
value={form.scan_interval_minutes}
onChange={setField('scan_interval_minutes')}
min={5}
max={1440}
precision={0}
style={{ width: '100%' }}
/>
</div>
<div>
<label className={labelCls}>{t('生产/测试分界')}</label>
<InputNumber
value={form.test_stage_threshold}
onChange={setField('test_stage_threshold')}
min={0}
suffix={t('元')}
style={{ width: '100%' }}
/>
</div>
</div>
<div>
<label className={labelCls}>{t('消息标题前缀')}</label>
<Input
value={form.title_prefix}
onChange={setField('title_prefix')}
placeholder={t('如 [生产],多环境共用群时区分来源')}
/>
</div>
<div>
<label className={labelCls}>{t('已屏蔽预警的企业')}</label>
{/* 只读展示:编辑入口唯一收敛到企业列表的行内铃铛按钮(走 CAS 接口)。
若这里也做整串编辑,弹窗持有的是打开那一刻的快照,保存会把期间
别人用行内开关加入的企业静默抹掉。 */}
<div className='flex flex-wrap items-center gap-1.5'>
{excludedIdList.length ? (
excludedIdList.map((id) => (
<Tag key={id} size='small' color='grey'>
#{id}
</Tag>
))
) : (
<span className='text-sm text-gray-400 dark:text-gray-500'>
{t('暂无')}
</span>
)}
</div>
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
{t('在企业列表中用铃铛按钮屏蔽/恢复单个企业')}
</p>
</div>
{/* —— 投递通道 —— */}
<div className={sectionCls}>{t('投递通道')}</div>
<div>
<label className={labelCls}>
{t('默认通道 Webhook 地址')}
<span className='text-gray-400 font-normal ml-1'>
{t('(日报走此通道)')}
</span>
</label>
<Input
value={form.webhook_url}
onChange={setField('webhook_url')}
placeholder='https://...'
className='break-all'
/>
</div>
<div className='grid grid-cols-2 gap-3'>
<div>
<label className={labelCls}>{t('消息格式')}</label>
<Select
value={form.webhook_format}
onChange={setField('webhook_format')}
optionList={formatOptions(t)}
style={{ width: '100%' }}
/>
</div>
<div>
<label className={labelCls}>{t('签名密钥')}</label>
<Input
mode='password'
value={form.WebhookSecret}
onChange={setField('WebhookSecret')}
placeholder={
secretSet.WebhookSecret
? t('已设置,留空则不修改')
: t('可选')
}
/>
</div>
</div>
<Collapse>
<Collapse.Panel
header={t('市场通道(可选,预警走此通道,留空回落默认通道)')}
itemKey='market'
>
<div className='space-y-3'>
<div>
<label className={labelCls}>
{t('市场通道 Webhook 地址')}
</label>
<Input
value={form.market_webhook_url}
onChange={setField('market_webhook_url')}
placeholder='https://...'
className='break-all'
/>
</div>
<div className='grid grid-cols-2 gap-3'>
<div>
<label className={labelCls}>{t('消息格式')}</label>
<Select
value={form.market_webhook_format || ''}
onChange={setField('market_webhook_format')}
optionList={[
{ value: '', label: t('跟随默认通道') },
...formatOptions(t),
]}
style={{ width: '100%' }}
/>
</div>
<div>
<label className={labelCls}>{t('签名密钥')}</label>
<Input
mode='password'
value={form.MarketWebhookSecret}
onChange={setField('MarketWebhookSecret')}
placeholder={
secretSet.MarketWebhookSecret
? t('已设置,留空则不修改')
: t('可选')
}
/>
</div>
</div>
</div>
</Collapse.Panel>
</Collapse>
{/* —— 日报 —— */}
<div className={sectionCls}>{t('每日使用报表')}</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('启用每日报表')}
</span>
<Switch
checked={form.daily_report_enabled}
onChange={setField('daily_report_enabled')}
/>
</div>
<div className='grid grid-cols-2 gap-3'>
<div>
<label className={labelCls}>{t('发送时刻')}</label>
<TimePicker
format='HH:mm'
value={timeToDate(form.daily_report_time)}
onChange={(_, timeString) => {
if (typeof timeString === 'string' && timeString) {
setField('daily_report_time')(timeString.slice(0, 5));
}
}}
style={{ width: '100%' }}
/>
</div>
<div>
<label className={labelCls}>{t('正文行数上限')}</label>
<InputNumber
value={form.daily_report_max_rows}
onChange={setField('daily_report_max_rows')}
min={1}
max={200}
precision={0}
style={{ width: '100%' }}
/>
</div>
</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('包含零消耗零余额企业')}
</span>
<Switch
checked={form.daily_report_include_inactive}
onChange={setField('daily_report_include_inactive')}
/>
</div>
{/* —— 预警 —— */}
<div className={sectionCls}>{t('预警规则')}</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('加额未消耗提醒')}
</span>
<Switch
checked={form.no_consumption_enabled}
onChange={setField('no_consumption_enabled')}
/>
</div>
<div className='grid grid-cols-2 gap-3'>
<div>
<label className={labelCls}>{t('未消耗观察天数')}</label>
<InputNumber
value={form.no_consumption_days}
onChange={setField('no_consumption_days')}
min={1}
max={30}
precision={0}
style={{ width: '100%' }}
/>
</div>
<div>
<label className={labelCls}>{t('加额金额门槛')}</label>
<InputNumber
value={form.no_consumption_min_amount}
onChange={setField('no_consumption_min_amount')}
min={0}
suffix={t('元')}
style={{ width: '100%' }}
/>
</div>
</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('生产企业额度用尽提醒')}
</span>
<Switch
checked={form.exhausted_prod_enabled}
onChange={setField('exhausted_prod_enabled')}
/>
</div>
<div className={rowCls}>
<span className='text-sm text-gray-700 dark:text-gray-300'>
{t('测试企业额度用尽提醒')}
</span>
<Switch
checked={form.exhausted_test_enabled}
onChange={setField('exhausted_test_enabled')}
/>
</div>
<div>
<label className={labelCls}>{t('用尽阈值')}</label>
<InputNumber
value={form.exhausted_threshold}
onChange={setField('exhausted_threshold')}
min={0}
suffix={t('元')}
style={{ width: '100%' }}
/>
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
{t(
'余额低于此值视为用尽;应不低于客户典型单次请求成本,调大可当低余额提醒用',
)}
</p>
</div>
{/* —— 发送测试 —— */}
<div className='flex flex-wrap items-center gap-2 pt-2 border-t border-gray-100 dark:border-neutral-800'>
<Button
loading={testing === 'default'}
disabled={!!testing}
onClick={() => handleTest('default')}
>
{t('测试默认通道')}
</Button>
<Button
loading={testing === 'market'}
disabled={!!testing}
onClick={() => handleTest('market')}
>
{t('测试市场通道')}
</Button>
<span className='text-xs text-gray-400 dark:text-gray-500 self-center'>
{t('测试使用已保存的配置,改动请先保存')}
</span>
</div>
</div>
)}
</Modal>
);
};
export default OrgAlertSettingsModal;