阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -1,11 +1,134 @@
|
||||
export {
|
||||
createNotificationChannel,
|
||||
deleteNotificationChannel,
|
||||
getNotificationChannels,
|
||||
getSystemSettings,
|
||||
testNotificationChannel,
|
||||
updateNotificationChannel,
|
||||
updateSystemSettings,
|
||||
} from '../../../services/api';
|
||||
import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract';
|
||||
|
||||
// notifications feature 通过本适配层声明渠道和 SMTP API 的来源。
|
||||
/** 通知渠道写入时使用的具名请求 DTO。 */
|
||||
export interface NotificationChannelRequest {
|
||||
/** 管理界面展示的渠道名称。 */
|
||||
name?: string;
|
||||
/** 后端支持的渠道类型。 */
|
||||
type?: string;
|
||||
/** 由各渠道表单构造的非敏感配置。 */
|
||||
config?: Record<string, unknown>;
|
||||
/** 需要订阅的系统事件。 */
|
||||
event_types?: NotificationEventType[];
|
||||
/** 渠道是否参与通知投递。 */
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
/** 将后端字符串或历史分隔文本转换为稳定事件类型列表。 */
|
||||
const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => {
|
||||
if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||
try {
|
||||
// parsed 是解析后的历史 JSON 事件列表。
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[];
|
||||
} catch {
|
||||
// 非 JSON 历史值继续按分隔符兼容解析。
|
||||
}
|
||||
return raw.split(/[,\s;]+/).map(value => value.trim()).filter(Boolean) as NotificationEventType[];
|
||||
};
|
||||
|
||||
/** 将事件类型列表序列化为后端稳定保存的 JSON 文本。 */
|
||||
const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]): string => {
|
||||
// uniqueTypes 是去重且去除空值后的事件列表。
|
||||
const uniqueTypes = Array.from(new Set((eventTypes || []).filter(Boolean)));
|
||||
return uniqueTypes.length > 0 ? JSON.stringify(uniqueTypes) : '';
|
||||
};
|
||||
|
||||
/** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */
|
||||
const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => {
|
||||
// config 是解析失败时降级为空对象的渠道配置。
|
||||
let config: Record<string, unknown> = {};
|
||||
try {
|
||||
// parsed 是配置文本解析后的未知 JSON 值。
|
||||
const parsed: unknown = typeof channel.config === 'string' ? JSON.parse(channel.config) : channel.config;
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
// 历史损坏配置不阻止用户继续编辑渠道。
|
||||
}
|
||||
// type 是处理 ding_talk/lark 历史别名后的渠道类型。
|
||||
const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type'];
|
||||
return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled, created_at: channel.created_at, updated_at: channel.updated_at };
|
||||
};
|
||||
|
||||
/** 获取全部通知渠道并转换为编辑器模型。 */
|
||||
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => {
|
||||
// response 是渠道列表的原始传输响应。
|
||||
const response = await get<NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] }>('/api/v1/notifications/channels', undefined, options);
|
||||
// channels 是兼容直接数组与包装数组后的原始渠道列表。
|
||||
const channels = Array.isArray(response) ? response : response.data || response.channels || [];
|
||||
return { success: true, data: channels.map(toNotificationChannel) };
|
||||
};
|
||||
|
||||
/** 创建通知渠道,并在传输边界序列化配置与事件。 */
|
||||
export const createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => post('/api/v1/notifications/channels', { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) }, options);
|
||||
|
||||
/** 更新通知渠道的可编辑字段。 */
|
||||
export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
// payload 是已完成配置和事件序列化的更新请求。
|
||||
const payload: Record<string, unknown> = { ...data };
|
||||
if ('config' in data) payload.config = JSON.stringify(data.config);
|
||||
if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types);
|
||||
return put(`/api/v1/notifications/channels/${channelID}`, payload, options);
|
||||
};
|
||||
|
||||
/** 删除指定通知渠道。 */
|
||||
export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => del(`/api/v1/notifications/channels/${channelID}`, undefined, options);
|
||||
|
||||
/** 获取并展平按账号分组存储的消息通知绑定。 */
|
||||
export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => {
|
||||
// response 是按账号 ID 分组的通知绑定响应。
|
||||
const response = await get<Record<string, NotificationBinding[]>>('/api/v1/notifications/messages');
|
||||
// bindings 是供页面直接渲染的扁平绑定集合。
|
||||
const bindings: NotificationBinding[] = [];
|
||||
for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) {
|
||||
if (!Array.isArray(channelBindings)) continue;
|
||||
for (const /* binding 是当前待展平的单个账号渠道绑定。 */ binding of channelBindings) bindings.push({ ...binding, cookie_id: accountID });
|
||||
}
|
||||
return { success: true, data: bindings };
|
||||
};
|
||||
|
||||
/** 设置单个账号与渠道之间的启用状态。 */
|
||||
export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_id: channelID, enabled });
|
||||
|
||||
/** 删除单个消息通知绑定。 */
|
||||
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/${notificationID}`);
|
||||
|
||||
/** 删除指定账号的全部消息通知绑定。 */
|
||||
export const deleteAccountNotifications = async (accountID: string): Promise<OperationResponse> => del(`/api/v1/notifications/messages/account/${accountID}`);
|
||||
|
||||
/** 读取指定账号已绑定的通知渠道主键。 */
|
||||
export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise<number[]> => {
|
||||
// response 是账号渠道绑定的具名响应。
|
||||
const response = await get<{ /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }>(`/api/v1/notifications/accounts/${accountID}/bindings`, undefined, options);
|
||||
return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : [];
|
||||
};
|
||||
|
||||
/** 覆盖保存指定账号的通知渠道绑定。 */
|
||||
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs });
|
||||
|
||||
/** 向单一通知渠道发送测试投递。 */
|
||||
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options);
|
||||
|
||||
/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */
|
||||
const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSettings => {
|
||||
// result 是不改变原始响应对象的设置副本。
|
||||
const result: Record<string, unknown> = { ...settings };
|
||||
if ('renewal_log_retention_days' in result) {
|
||||
// days 是已校验的日志保留天数。
|
||||
const days = Number(result.renewal_log_retention_days);
|
||||
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
|
||||
}
|
||||
return result as SystemSettings;
|
||||
};
|
||||
|
||||
/** 获取通知 SMTP 编辑器需要的系统设置。 */
|
||||
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
|
||||
// response 是服务端可能以 data 包装的系统设置响应。
|
||||
const response = await get<{ /** data 是当前服务端系统设置。 */ data?: Record<string, unknown>; /** settings 是兼容字段。 */ settings?: Record<string, unknown> } & Record<string, unknown>>('/api/v1/settings/system', undefined, options);
|
||||
return normalizeSystemSettings(response.data || response.settings || response);
|
||||
};
|
||||
|
||||
/** 保存通知 SMTP 编辑器提交的系统设置。 */
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/settings/system', settings, options);
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react';
|
||||
import type { NotificationChannel } from '../../../../types';
|
||||
import type { NotificationChannel } from '../../../../shared/api-contract';
|
||||
import { notificationChannelTypes, notificationEventSummary } from '../state';
|
||||
|
||||
// NotificationChannelListProps 描述通知渠道列表的操作边界。
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react';
|
||||
import { enableCustomSMTP } from '../../../../notificationEmailConfig';
|
||||
import { notificationChannelTypes } from '../state';
|
||||
import { NotificationEventSelector } from './NotificationEventSelector';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract';
|
||||
import type { NotificationForm } from '../types';
|
||||
|
||||
// NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { Check } from 'lucide-react';
|
||||
import { notificationEvents } from '../state';
|
||||
import type { NotificationEventType } from '../../../../types';
|
||||
import type { NotificationEventType } from '../../../../shared/api-contract';
|
||||
|
||||
// NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。
|
||||
export interface NotificationEventSelectorProps {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react';
|
||||
import type { SystemSettings } from '../../../../types';
|
||||
import type { SystemSettings } from '../../../../shared/api-contract';
|
||||
|
||||
// NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。
|
||||
export interface NotificationSmtpSettingsProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { NotificationChannel, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { useNotifications } from './hooks';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state';
|
||||
import type { NotificationForm, NotificationState } from './types';
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import React from 'react';
|
||||
import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react';
|
||||
import { NotificationChannelList } from '../components/NotificationChannelList';
|
||||
import { NotificationChannelModal } from '../components/NotificationChannelModal';
|
||||
import { NotificationSmtpSettings } from '../components/NotificationSmtpSettings';
|
||||
import { useNotifications } from '../hooks';
|
||||
|
||||
// NotificationsProps 描述通知页面接收的权限上下文。
|
||||
interface NotificationsProps {
|
||||
// isAdmin 表示当前用户是否可以查看和保存系统 SMTP 配置。
|
||||
isAdmin?: boolean;
|
||||
}
|
||||
|
||||
// Notifications 渲染通知渠道列表、SMTP 配置和渠道编辑边界。
|
||||
const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
|
||||
// notificationState 统一提供通知页面的数据、表单和异步动作。
|
||||
const notificationState = useNotifications(isAdmin);
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
|
||||
<div><h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">通知设置</h2><p className="text-gray-500 mt-2 font-medium">配置通知渠道,账号异常时主动推送告警</p></div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={notificationState.loadChannels} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors"><RefreshCw className="w-4 h-4" />刷新</button>
|
||||
<button onClick={notificationState.openCreate} className="ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2"><Plus className="w-4 h-4" />新建渠道</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100">
|
||||
<div className="flex items-start gap-3"><Bell className="w-5 h-5 text-brand mt-0.5 flex-shrink-0" /><div className="text-sm text-gray-700 leading-6">配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:<ul className="mt-2 space-y-1 text-gray-600"><li>• <strong>账号 session 失效</strong>:系统正在尝试自动恢复(警告)</li><li>• <strong>自动恢复失败</strong>:账号已停止,需人工处理(严重)</li><li>• <strong>触发风控验证</strong>:可能需要扫码完成验证(警告)</li></ul></div></div>
|
||||
</div>
|
||||
|
||||
{notificationState.loading ? <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 text-brand animate-spin" /></div> : <NotificationChannelList channels={notificationState.channels} testingId={notificationState.testingId} onEdit={notificationState.openEdit} onDelete={notificationState.handleDelete} onToggleEnabled={notificationState.handleToggleEnabled} onTest={notificationState.handleTest} />}
|
||||
|
||||
{isAdmin && <NotificationSmtpSettings smtp={notificationState.smtp} setSmtp={notificationState.setSmtp} smtpSaving={notificationState.smtpSaving} showPassword={notificationState.showSmtpPassword} setShowPassword={notificationState.setShowSmtpPassword} onSave={notificationState.handleSaveSmtp} />}
|
||||
|
||||
<NotificationChannelModal showModal={notificationState.showModal} editing={notificationState.editing} form={notificationState.form} setForm={notificationState.setForm} smtp={notificationState.smtp} showChannelSmtpPassword={notificationState.showChannelSmtpPassword} setShowChannelSmtpPassword={notificationState.setShowChannelSmtpPassword} saving={notificationState.saving} onClose={notificationState.closeModal} onSave={notificationState.handleSave} />
|
||||
|
||||
{notificationState.toast && <div className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${notificationState.toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>{notificationState.toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}{notificationState.toast.text}</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Notifications;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { NotificationChannel } from '../../../types';
|
||||
import type { NotificationChannel } from '../../../shared/api-contract';
|
||||
import type { NotificationForm } from './types';
|
||||
import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig';
|
||||
import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Dispatch, ElementType, SetStateAction } from 'react';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types';
|
||||
import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract';
|
||||
|
||||
// NotificationField 描述通知渠道表单中的一个配置字段。
|
||||
export interface NotificationField {
|
||||
|
||||
Reference in new issue
Block a user