功能:支持来源系统白名单与系统默认通道
This commit is contained in:
+6
-1
@@ -1,8 +1,8 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -51,6 +51,11 @@ public class GlobalExceptionHandler {
|
||||
if (message != null && message.contains("message_channel_config") && message.contains("doesn't exist")) {
|
||||
return ApiResponse.error("缺少消息通道配置表,请先执行 2026-03-23_message_channel_management_patch.sql");
|
||||
}
|
||||
if (message != null
|
||||
&& ((message.contains("message_source_system") && message.contains("doesn't exist"))
|
||||
|| (message.contains("message_source_system_channel") && message.contains("doesn't exist")))) {
|
||||
return ApiResponse.error("缺少来源系统配置表,请先执行 2026-03-23_message_source_system_patch.sql");
|
||||
}
|
||||
return ApiResponse.error("数据库语句执行失败,请检查 MessageHub 初始化 SQL");
|
||||
}
|
||||
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/source-systems")
|
||||
public class MessageSourceSystemAdminController {
|
||||
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
|
||||
public MessageSourceSystemAdminController(MessageSourceSystemService sourceSystemService) {
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<SourceSystemView>> listSourceSystems() {
|
||||
return ApiResponse.success(sourceSystemService.listSourceSystems());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<SourceSystemView> getSourceSystem(@PathVariable Long id) {
|
||||
return ApiResponse.success(sourceSystemService.getSourceSystem(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<SourceSystemView> createSourceSystem(@Valid @RequestBody SourceSystemSaveRequest request) {
|
||||
return ApiResponse.success("来源系统创建成功", sourceSystemService.createSourceSystem(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<SourceSystemView> updateSourceSystem(@PathVariable Long id,
|
||||
@Valid @RequestBody SourceSystemSaveRequest request) {
|
||||
return ApiResponse.success("来源系统更新成功", sourceSystemService.updateSourceSystem(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<SourceSystemView> updateSourceSystemStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody SourceSystemStatusUpdateRequest request) {
|
||||
return ApiResponse.success("来源系统状态更新成功",
|
||||
sourceSystemService.updateSourceSystemStatus(id, request.getEnabled()));
|
||||
}
|
||||
}
|
||||
@@ -39,8 +39,8 @@ public class MessageDTO {
|
||||
*/
|
||||
private Long channelId;
|
||||
|
||||
@NotBlank(message = "来源系统不能为空")
|
||||
@Size(max = 50, message = "来源系统长度不能超过 50")
|
||||
@NotBlank(message = "来源系统标识不能为空")
|
||||
@Size(max = 64, message = "来源系统标识长度不能超过 64")
|
||||
private String sourceSystem;
|
||||
|
||||
@NotBlank(message = "唯一标识不能为空")
|
||||
|
||||
@@ -1,22 +1,17 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 短信消息DTO
|
||||
* 用于封装短信发送所需的所有信息
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-03-02
|
||||
* 短信消息 DTO。
|
||||
*/
|
||||
@Data
|
||||
public class SmsMessageDTO extends MessageDTO{
|
||||
// 发送方式,用于指定短信发送渠道
|
||||
public class SmsMessageDTO extends MessageDTO {
|
||||
|
||||
@NotBlank(message = "发送方式不能为空")
|
||||
@Pattern(regexp = "^(SPUG|OTHER)$", message = "发送方式必须是SPUG或OTHER")
|
||||
@Pattern(regexp = "^(SPUG|OTHER)$", message = "发送方式必须是 SPUG 或 OTHER")
|
||||
private String sendMethod;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ public class ChannelConfigSaveRequest {
|
||||
@NotBlank(message = "通道类型不能为空")
|
||||
private String channelType;
|
||||
|
||||
@NotBlank(message = "提供方不能为空")
|
||||
@NotBlank(message = "提供商不能为空")
|
||||
private String providerCode;
|
||||
|
||||
@NotBlank(message = "通道名称不能为空")
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import java.util.Map;
|
||||
@Data
|
||||
public class ChannelConfigTestRequest {
|
||||
|
||||
@NotNull(message = "通道ID不能为空")
|
||||
@NotNull(message = "通道 ID 不能为空")
|
||||
private Long channelId;
|
||||
|
||||
@NotBlank(message = "接收目标不能为空")
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class SourceSystemSaveRequest {
|
||||
|
||||
@NotBlank(message = "系统标识不能为空")
|
||||
@Size(max = 64, message = "系统标识长度不能超过 64")
|
||||
private String systemCode;
|
||||
|
||||
@NotBlank(message = "系统名称不能为空")
|
||||
@Size(max = 100, message = "系统名称长度不能超过 100")
|
||||
private String systemName;
|
||||
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@Size(max = 255, message = "备注长度不能超过 255")
|
||||
private String remark;
|
||||
|
||||
private Long defaultSmsChannelId;
|
||||
|
||||
private Long defaultEmailChannelId;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class SourceSystemStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启停状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SourceSystemView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String systemCode;
|
||||
|
||||
private String systemName;
|
||||
|
||||
private Boolean enabled;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Long defaultSmsChannelId;
|
||||
|
||||
private String defaultSmsChannelName;
|
||||
|
||||
private Long defaultEmailChannelId;
|
||||
|
||||
private String defaultEmailChannelName;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_source_system_channel")
|
||||
public class MessageSourceSystemChannelDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_id")
|
||||
private Long systemId;
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_source_system")
|
||||
public class MessageSourceSystemDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_code")
|
||||
private String systemCode;
|
||||
|
||||
@TableField("system_name")
|
||||
private String systemName;
|
||||
|
||||
@TableField("enabled")
|
||||
private Integer enabled;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableLogic
|
||||
@TableField("deleted")
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+59
-100
@@ -1,136 +1,95 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.service.EmailSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.rabbitmq.client.Channel;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 邮件队列监听器
|
||||
* 用于监听和处理邮件队列中的消息
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EmailQueueListener {
|
||||
|
||||
@Autowired
|
||||
private EmailSendService emailSendService; // 邮件发送服务
|
||||
private final EmailSendService emailSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private MessageHandleService messageHandleService; // 消息处理服务
|
||||
public EmailQueueListener(EmailSendService emailSendService,
|
||||
MessageHandleService messageHandleService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.emailSendService = emailSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper; // JSON对象映射器
|
||||
|
||||
/**
|
||||
* 处理邮件消息的方法
|
||||
*
|
||||
* @param message RabbitMQ消息对象
|
||||
* @param channel RabbitMQ通道对象
|
||||
*/
|
||||
@org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "emailQueue")
|
||||
@RabbitListener(queues = "emailQueue")
|
||||
public void handleEmailMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId(); // 获取消息ID
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
|
||||
try {
|
||||
// 将消息体转换为字符串
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
// 打印接收消息的日志
|
||||
log.info("========================================");
|
||||
log.info("收到邮件消息");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("消息内容: {}", messageBody);
|
||||
log.info("========================================");
|
||||
|
||||
// 将消息体转换为MessageDTO对象
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
|
||||
// 验证消息并保存日志
|
||||
boolean isValid = messageHandleService.validateAndSaveLog(messageDTO, messageId, java.time.LocalDateTime.now());
|
||||
|
||||
if (isValid) {
|
||||
// 构建邮件主题和内容
|
||||
String subject = buildSubject(messageDTO);
|
||||
String content = buildContent(messageDTO);
|
||||
|
||||
// 发送邮件
|
||||
emailSendService.sendEmail(messageDTO.getReceiver(), subject, content, messageDTO.getChannelId());
|
||||
|
||||
// 打印处理完成的日志
|
||||
log.info("========================================");
|
||||
log.info("邮件消息处理完成");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("收件人: {}", messageDTO.getReceiver());
|
||||
log.info("主题: {}", subject);
|
||||
log.info("========================================");
|
||||
} else {
|
||||
log.warn("消息校验失败,消息ID: {}", messageId);
|
||||
boolean valid = messageHandleService.validateAndSaveLog(messageDTO, messageId, LocalDateTime.now());
|
||||
if (!valid) {
|
||||
log.warn("邮件消息校验未通过,消息ID: {}", messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 确认消息处理完成
|
||||
String subject = buildSubject(messageDTO);
|
||||
String content = buildContent(messageDTO);
|
||||
emailSendService.sendEmail(
|
||||
messageDTO.getReceiver(),
|
||||
subject,
|
||||
content,
|
||||
messageDTO.getChannelId(),
|
||||
messageDTO.getSourceSystem()
|
||||
);
|
||||
messageHandleService.markSendSuccess(messageId, content);
|
||||
|
||||
log.info("========================================");
|
||||
log.info("邮件消息处理完成");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("收件人: {}", messageDTO.getReceiver());
|
||||
log.info("主题: {}", subject);
|
||||
log.info("========================================");
|
||||
} catch (Exception exception) {
|
||||
log.error("处理邮件消息时发生异常,消息ID: {}", messageId, exception);
|
||||
messageHandleService.updatePushLogStatus(messageId, 2, exception.getMessage());
|
||||
} finally {
|
||||
acknowledge(message, channel);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSubject(MessageDTO messageDTO) {
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
return "[" + messageDTO.getTemplateCode() + "] " + messageDTO.getMsgType();
|
||||
}
|
||||
return messageDTO.getMsgType();
|
||||
}
|
||||
|
||||
private String buildContent(MessageDTO messageDTO) {
|
||||
return messageHandleService.buildFinalContent(messageDTO.getTemplateCode(), messageDTO.getTemplateParams());
|
||||
}
|
||||
|
||||
private void acknowledge(Message message, Channel channel) {
|
||||
try {
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception e) {
|
||||
// 处理异常情况
|
||||
log.error("处理邮件消息时发生异常,消息ID: {}", messageId, e);
|
||||
|
||||
try {
|
||||
// 即使发生异常也要确认消息处理完成,避免重复处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建邮件主题
|
||||
*
|
||||
* @param messageDTO 消息DTO对象
|
||||
* @return 构建好的邮件主题
|
||||
*/
|
||||
private String buildSubject(MessageDTO messageDTO) {
|
||||
String subject;
|
||||
|
||||
// 如果有模板代码,则将其添加到主题中
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
subject = "[" + messageDTO.getTemplateCode() + "] " + messageDTO.getMsgType();
|
||||
} else {
|
||||
subject = messageDTO.getMsgType();
|
||||
}
|
||||
|
||||
return subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建邮件内容
|
||||
*
|
||||
* @param messageDTO 消息DTO对象
|
||||
* @return 构建好的邮件内容
|
||||
*/
|
||||
private String buildContent(MessageDTO messageDTO) {
|
||||
// 如果有模板代码,则使用模板替换占位符
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
return messageHandleService.replaceTemplatePlaceholders(
|
||||
// 如果没有模板代码,则尝试从模板参数中获取消息内容
|
||||
messageDTO.getTemplateCode(),
|
||||
messageDTO.getTemplateParams()
|
||||
);
|
||||
} else {
|
||||
if (messageDTO.getTemplateParams() != null && messageDTO.getTemplateParams().containsKey("message")) {
|
||||
return messageDTO.getTemplateParams().get("message").toString();
|
||||
} else {
|
||||
return "无内容";
|
||||
}
|
||||
} catch (Exception ackException) {
|
||||
log.error("邮件消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,136 +3,81 @@ package com.xiaowang.messagehub.listener;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 短信队列监听器
|
||||
* 用于监听和处理短信队列中的消息,实现短信发送功能
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component
|
||||
public class SmsQueueListener {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsQueueListener.class);
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper; // JSON对象映射器,用于处理消息序列化和反序列化
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SmsSendService smsSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
|
||||
@Autowired
|
||||
private SmsSendService smsSendService; // 短信服务,用于发送短信
|
||||
public SmsQueueListener(ObjectMapper objectMapper,
|
||||
SmsSendService smsSendService,
|
||||
MessageHandleService messageHandleService) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.smsSendService = smsSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private PushLogMapper pushLogMapper; // 推送日志映射器,用于数据库操作
|
||||
|
||||
/**
|
||||
* 处理短信消息的方法
|
||||
* @param message 接收到的消息对象
|
||||
* @param channel RabbitMQ通道,用于消息确认
|
||||
*/
|
||||
@RabbitListener(queues = "smsQueue") // 监听名为smsQueue的队列
|
||||
@RabbitListener(queues = "smsQueue")
|
||||
public void handleSmsMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId(); // 获取消息ID
|
||||
LocalDateTime sendTime = LocalDateTime.now(); // 获取当前接收时间
|
||||
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
|
||||
try {
|
||||
// 将消息体转换为字符串
|
||||
String messageBody = new String(message.getBody(), "UTF-8");
|
||||
// 打印消息接收日志
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
logger.info("========================================");
|
||||
logger.info("收到短信消息");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("消息内容: {}", messageBody);
|
||||
logger.info("========================================");
|
||||
|
||||
// 将消息体反序列化为SmsMessageDTO对象
|
||||
SmsMessageDTO smsMessageDTO = objectMapper.readValue(messageBody, SmsMessageDTO.class);
|
||||
boolean valid = messageHandleService.validateAndSaveLog(smsMessageDTO, messageId, sendTime);
|
||||
if (!valid) {
|
||||
logger.warn("短信消息校验未通过,messageId: {}", messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 基础格式验证已通过@Valid注解在DTO中完成
|
||||
logger.info("消息格式验证通过");
|
||||
|
||||
// 保存推送日志
|
||||
savePushLog(messageId, smsMessageDTO, sendTime, 0, null);
|
||||
|
||||
// 发送短信
|
||||
smsSendService.sendSms(smsMessageDTO);
|
||||
String finalContent = messageHandleService.buildFinalContent(
|
||||
smsMessageDTO.getTemplateCode(),
|
||||
smsMessageDTO.getTemplateParams()
|
||||
);
|
||||
messageHandleService.markSendSuccess(messageId, finalContent);
|
||||
|
||||
logger.info("========================================");
|
||||
logger.info("消息接收处理完成");
|
||||
logger.info("短信消息处理完成");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("手机号: {}", smsMessageDTO.getReceiver());
|
||||
logger.info("发送方式: {}", smsMessageDTO.getSendMethod());
|
||||
logger.info("========================================");
|
||||
|
||||
// 确认消息已被处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception e) {
|
||||
// 异常处理
|
||||
logger.error("处理短信消息时发生异常,消息ID: {}", messageId, e);
|
||||
|
||||
// 更新日志状态为发送失败
|
||||
updatePushLogStatus(messageId, 2, e.getMessage());
|
||||
|
||||
try {
|
||||
// 即使发生异常也确认消息,避免重复处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
logger.error("消息确认失败", ackException);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
logger.error("处理短信消息时发生异常,消息ID: {}", messageId, exception);
|
||||
messageHandleService.updatePushLogStatus(messageId, 2, exception.getMessage());
|
||||
} finally {
|
||||
acknowledge(message, channel);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存推送日志
|
||||
* @param messageId 消息ID
|
||||
* @param smsMessageDTO 短信消息DTO
|
||||
* @param sendTime 发送时间
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
private void savePushLog(String messageId, SmsMessageDTO smsMessageDTO, LocalDateTime sendTime, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setSourceSystem(smsMessageDTO.getSourceSystem());
|
||||
pushLog.setUniqueId(smsMessageDTO.getUniqueId());
|
||||
pushLog.setReceiver(smsMessageDTO.getReceiver());
|
||||
pushLog.setChannelType(smsMessageDTO.getChannelType()); // 使用DTO中的渠道类型
|
||||
pushLog.setMsgType(smsMessageDTO.getMsgType()); // 使用DTO中的消息类型
|
||||
pushLog.setTemplateCode(smsMessageDTO.getTemplateCode());
|
||||
pushLog.setTemplateParams(smsMessageDTO.getTemplateParams() != null ? smsMessageDTO.getTemplateParams().toString() : null);
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setRetryCount(0);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.info("推送日志保存成功,消息ID: {}", messageId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新推送日志状态
|
||||
* @param messageId 消息ID
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
private void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
logger.info("推送日志状态更新成功,消息ID: {}, 状态: {}", messageId, status);
|
||||
private void acknowledge(Message message, Channel channel) {
|
||||
try {
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
logger.error("短信消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemChannelDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageSourceSystemChannelMapper extends BaseMapper<MessageSourceSystemChannelDO> {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageSourceSystemMapper extends BaseMapper<MessageSourceSystemDO> {
|
||||
}
|
||||
@@ -18,5 +18,7 @@ public class SmsDispatchRequest {
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
@@ -22,4 +22,10 @@ public class EmailSendService {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}", to, subject, channelId);
|
||||
messageChannelService.sendEmail(to, subject, content, channelId);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId, String sourceSystem) {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}, sourceSystem: {}",
|
||||
to, subject, channelId, sourceSystem);
|
||||
messageChannelService.sendEmail(to, subject, content, channelId, sourceSystem);
|
||||
}
|
||||
}
|
||||
|
||||
+49
-27
@@ -20,6 +20,7 @@ import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.service.channel.email.EmailChannelProvider;
|
||||
import com.xiaowang.messagehub.service.channel.sms.SmsChannelProvider;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -42,6 +43,7 @@ public class MessageChannelService {
|
||||
private final MessageChannelProperties properties;
|
||||
private final List<EmailChannelProvider> emailProviders;
|
||||
private final List<SmsChannelProvider> smsProviders;
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
|
||||
public MessageChannelService(MessageChannelConfigMapper channelConfigMapper,
|
||||
PushTemplateMapper pushTemplateMapper,
|
||||
@@ -50,7 +52,8 @@ public class MessageChannelService {
|
||||
ChannelEnvironmentService environmentService,
|
||||
MessageChannelProperties properties,
|
||||
List<EmailChannelProvider> emailProviders,
|
||||
List<SmsChannelProvider> smsProviders) {
|
||||
List<SmsChannelProvider> smsProviders,
|
||||
MessageSourceSystemService sourceSystemService) {
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
this.pushTemplateMapper = pushTemplateMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -59,6 +62,7 @@ public class MessageChannelService {
|
||||
this.properties = properties;
|
||||
this.emailProviders = emailProviders;
|
||||
this.smsProviders = smsProviders;
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
}
|
||||
|
||||
public List<ChannelConfigView> listChannels() {
|
||||
@@ -90,7 +94,7 @@ public class MessageChannelService {
|
||||
if (Boolean.TRUE.equals(request.getEnabled())) {
|
||||
persistHealth(entity, checkHealth(buildManagedChannel(entity)));
|
||||
} else {
|
||||
markUnknown(entity, "Channel disabled");
|
||||
markUnknown(entity, "通道已停用");
|
||||
channelConfigMapper.updateById(entity);
|
||||
}
|
||||
return toView(requireChannel(id));
|
||||
@@ -102,7 +106,7 @@ public class MessageChannelService {
|
||||
entity.setEnabled(enabled ? 1 : 0);
|
||||
if (!enabled) {
|
||||
entity.setIsDefault(0);
|
||||
markUnknown(entity, "Channel disabled");
|
||||
markUnknown(entity, "通道已停用");
|
||||
} else {
|
||||
if (!existsEnabledDefault(entity.getChannelType(), id)) {
|
||||
clearDefaultByChannelType(entity.getChannelType(), id);
|
||||
@@ -131,18 +135,18 @@ public class MessageChannelService {
|
||||
if (!properties.getMock().isAutoBootstrap() || !environmentService.isDevelopmentEnvironment()) {
|
||||
return;
|
||||
}
|
||||
ensureMockChannel(ChannelTypeEnum.SMS, ChannelProviderCodeEnum.MOCK_SMS, "Dev Mock SMS Channel");
|
||||
ensureMockChannel(ChannelTypeEnum.EMAIL, ChannelProviderCodeEnum.MOCK_EMAIL, "Dev Mock Email Channel");
|
||||
ensureMockChannel(ChannelTypeEnum.SMS, ChannelProviderCodeEnum.MOCK_SMS, "开发环境 Mock 短信通道");
|
||||
ensureMockChannel(ChannelTypeEnum.EMAIL, ChannelProviderCodeEnum.MOCK_EMAIL, "开发环境 Mock 邮件通道");
|
||||
}
|
||||
|
||||
public String sendTest(ChannelConfigTestRequest request) {
|
||||
ManagedChannelConfig channelConfig = buildManagedChannel(requireChannel(request.getChannelId()));
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(channelConfig.entity().getChannelType());
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
String subject = StringUtils.hasText(request.getSubject()) ? request.getSubject() : "MessageHub Test Email";
|
||||
String content = StringUtils.hasText(request.getContent()) ? request.getContent() : "This is a test email from MessageHub.";
|
||||
String subject = StringUtils.hasText(request.getSubject()) ? request.getSubject() : "MessageHub 测试邮件";
|
||||
String content = StringUtils.hasText(request.getContent()) ? request.getContent() : "这是一封来自 MessageHub 的测试邮件。";
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request.getReceiver(), subject, content);
|
||||
return "Email test message sent";
|
||||
return "邮件测试发送成功";
|
||||
}
|
||||
|
||||
SmsDispatchRequest smsDispatchRequest = new SmsDispatchRequest();
|
||||
@@ -155,16 +159,16 @@ public class MessageChannelService {
|
||||
|
||||
if (ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(channelConfig.entity().getProviderCode())) {
|
||||
if (!StringUtils.hasText(request.getTemplateCode())) {
|
||||
throw new IllegalArgumentException("Spug SMS test requires templateCode");
|
||||
throw new IllegalArgumentException("Spug 短信测试必须填写模板编码");
|
||||
}
|
||||
smsDispatchRequest.setTemplateExternalId(requireTemplateExternalId(request.getTemplateCode()));
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(smsDispatchRequest.getContent())) {
|
||||
smsDispatchRequest.setContent("This is a test SMS from MessageHub.");
|
||||
smsDispatchRequest.setContent("这是一条来自 MessageHub 的测试短信。");
|
||||
}
|
||||
resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, smsDispatchRequest);
|
||||
return "SMS test message sent";
|
||||
return "短信测试发送成功";
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
@@ -172,12 +176,17 @@ public class MessageChannelService {
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, channelId);
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, channelId, null);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, to, subject, content);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId, String sourceSystem) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, channelId, sourceSystem);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, to, subject, content);
|
||||
}
|
||||
|
||||
public void sendSms(SmsDispatchRequest request) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.SMS, request.getChannelId());
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.SMS, request.getChannelId(), request.getSourceSystem());
|
||||
if (ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(channelConfig.entity().getProviderCode())
|
||||
&& !StringUtils.hasText(request.getTemplateExternalId())) {
|
||||
request.setTemplateExternalId(requireTemplateExternalId(request.getTemplateCode()));
|
||||
@@ -250,15 +259,15 @@ public class MessageChannelService {
|
||||
entity.setEnabled(noEnabledChannel ? 1 : 0);
|
||||
entity.setIsDefault(noEnabledChannel ? 1 : 0);
|
||||
entity.setHealthStatus(ChannelHealthStatusEnum.UNKNOWN.getCode());
|
||||
entity.setHealthMessage("Pending");
|
||||
entity.setRemark("Auto-generated mock channel for development");
|
||||
entity.setHealthMessage("待检测");
|
||||
entity.setRemark("开发环境自动补齐的 Mock 通道");
|
||||
channelConfigMapper.insert(entity);
|
||||
}
|
||||
|
||||
private MessageChannelConfigDO requireChannel(Long id) {
|
||||
MessageChannelConfigDO entity = channelConfigMapper.selectById(id);
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Channel not found: " + id);
|
||||
throw new IllegalArgumentException("通道不存在: " + id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
@@ -267,20 +276,33 @@ public class MessageChannelService {
|
||||
return new ManagedChannelConfig(entity, readJsonMap(entity.getConfigJson()), readSecretJson(entity.getSecretJson()));
|
||||
}
|
||||
|
||||
private ManagedChannelConfig resolveDispatchChannel(ChannelTypeEnum channelType, Long channelId) {
|
||||
private ManagedChannelConfig resolveDispatchChannel(ChannelTypeEnum channelType, Long channelId, String sourceSystem) {
|
||||
if (StringUtils.hasText(sourceSystem)) {
|
||||
sourceSystemService.requireEnabledSourceSystem(sourceSystem);
|
||||
}
|
||||
if (channelId != null) {
|
||||
return selectSpecifiedChannel(channelType, channelId);
|
||||
}
|
||||
if (StringUtils.hasText(sourceSystem)) {
|
||||
Long sourceDefaultChannelId = sourceSystemService.resolveSystemDefaultChannelId(sourceSystem, channelType.getCode());
|
||||
if (sourceDefaultChannelId != null) {
|
||||
try {
|
||||
return selectSpecifiedChannel(channelType, sourceDefaultChannelId);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new IllegalStateException("来源系统默认通道不可用: " + sourceSystem + " / " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
return selectActiveChannel(channelType);
|
||||
}
|
||||
|
||||
private ManagedChannelConfig selectSpecifiedChannel(ChannelTypeEnum channelType, Long channelId) {
|
||||
MessageChannelConfigDO entity = requireChannel(channelId);
|
||||
if (!channelType.getCode().equalsIgnoreCase(entity.getChannelType())) {
|
||||
throw new IllegalArgumentException("Channel type does not match channelId: " + channelId);
|
||||
throw new IllegalArgumentException("通道类型与 channelId 不匹配: " + channelId);
|
||||
}
|
||||
if (entity.getEnabled() == null || entity.getEnabled() != 1) {
|
||||
throw new IllegalArgumentException("Channel is disabled: " + channelId);
|
||||
throw new IllegalArgumentException("通道已停用: " + channelId);
|
||||
}
|
||||
return buildManagedChannel(entity);
|
||||
}
|
||||
@@ -288,7 +310,7 @@ public class MessageChannelService {
|
||||
private ManagedChannelConfig selectActiveChannel(ChannelTypeEnum channelType) {
|
||||
List<MessageChannelConfigDO> enabledChannels = listEnabledChannelEntities(channelType.getCode());
|
||||
if (enabledChannels.isEmpty()) {
|
||||
throw new IllegalStateException(channelType.getCode() + " channel is not configured");
|
||||
throw new IllegalStateException(channelType.getCode() + " 通道尚未配置");
|
||||
}
|
||||
|
||||
MessageChannelConfigDO selected = null;
|
||||
@@ -308,21 +330,21 @@ public class MessageChannelService {
|
||||
return emailProviders.stream()
|
||||
.filter(provider -> provider.supports(providerCode))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Email provider not found: " + providerCode));
|
||||
.orElseThrow(() -> new IllegalArgumentException("邮件提供商不存在: " + providerCode));
|
||||
}
|
||||
|
||||
private SmsChannelProvider resolveSmsProvider(String providerCode) {
|
||||
return smsProviders.stream()
|
||||
.filter(provider -> provider.supports(providerCode))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("SMS provider not found: " + providerCode));
|
||||
.orElseThrow(() -> new IllegalArgumentException("短信提供商不存在: " + providerCode));
|
||||
}
|
||||
|
||||
private void validateProvider(String channelType, String providerCode) {
|
||||
ChannelTypeEnum typeEnum = ChannelTypeEnum.fromCode(channelType);
|
||||
ChannelProviderCodeEnum providerCodeEnum = ChannelProviderCodeEnum.fromCode(providerCode);
|
||||
if (!providerCodeEnum.getChannelType().equalsIgnoreCase(typeEnum.getCode())) {
|
||||
throw new IllegalArgumentException("Provider and channelType do not match");
|
||||
throw new IllegalArgumentException("提供商与通道类型不匹配");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,10 +420,10 @@ public class MessageChannelService {
|
||||
private String requireTemplateExternalId(String templateCode) {
|
||||
PushTemplateDO template = pushTemplateMapper.selectByTemplateCode(templateCode);
|
||||
if (template == null || template.getIsEnable() == null || template.getIsEnable() != 1) {
|
||||
throw new IllegalArgumentException("Template is missing or disabled: " + templateCode);
|
||||
throw new IllegalArgumentException("模板不存在或已停用: " + templateCode);
|
||||
}
|
||||
if (!StringUtils.hasText(template.getExternalId())) {
|
||||
throw new IllegalArgumentException("Template externalId is empty: " + templateCode);
|
||||
throw new IllegalArgumentException("模板 externalId 为空: " + templateCode);
|
||||
}
|
||||
return template.getExternalId();
|
||||
}
|
||||
@@ -425,7 +447,7 @@ public class MessageChannelService {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value == null ? Collections.emptyMap() : value);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Failed to serialize channel config", exception);
|
||||
throw new IllegalStateException("通道配置序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,7 +466,7 @@ public class MessageChannelService {
|
||||
return objectMapper.readValue(json, new TypeReference<>() {
|
||||
});
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Failed to deserialize channel config", exception);
|
||||
throw new IllegalStateException("通道配置反序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+123
-112
@@ -1,14 +1,14 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import com.xiaowang.messagehub.mapper.PushTemplateMapper;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@@ -17,37 +17,109 @@ import javax.validation.Validator;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 消息队列数据校验以及数据库操作服务类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
* 队列消息校验、模板渲染和日志落库服务。
|
||||
*/
|
||||
@Service
|
||||
public class MessageHandleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class); // 日志记录器
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class);
|
||||
|
||||
@Autowired
|
||||
private Validator validator; // 数据校验器
|
||||
private final Validator validator;
|
||||
private final PushLogMapper pushLogMapper;
|
||||
private final PushTemplateMapper pushTemplateMapper;
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
|
||||
@Autowired
|
||||
private PushLogMapper pushLogMapper; // 推送日志数据访问层
|
||||
public MessageHandleService(Validator validator,
|
||||
PushLogMapper pushLogMapper,
|
||||
PushTemplateMapper pushTemplateMapper,
|
||||
MessageSourceSystemService sourceSystemService) {
|
||||
this.validator = validator;
|
||||
this.pushLogMapper = pushLogMapper;
|
||||
this.pushTemplateMapper = pushTemplateMapper;
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private PushTemplateMapper pushTemplateMapper; // 推送模板数据访问层
|
||||
|
||||
/**
|
||||
* 验证消息数据并保存日志
|
||||
* @param messageDTO 消息数据传输对象
|
||||
* @param messageId 消息ID
|
||||
* @param sendTime 发送时间
|
||||
* @return 验证是否通过
|
||||
*/
|
||||
public boolean validateAndSaveLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
Set<ConstraintViolation<MessageDTO>> violations = validator.validate(messageDTO);
|
||||
PushLogDO pushLog = buildPushLog(messageDTO, messageId, sendTime);
|
||||
String failReason = validateMessage(messageDTO);
|
||||
|
||||
if (failReason != null) {
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.warn("消息校验失败,messageId: {}, reason: {}", messageId, failReason);
|
||||
return false;
|
||||
}
|
||||
|
||||
pushLog.setStatus(0);
|
||||
pushLog.setFailReason(null);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.info("消息校验通过,messageId: {}, sourceSystem: {}, channelType: {}",
|
||||
messageId, messageDTO.getSourceSystem(), messageDTO.getChannelType());
|
||||
return true;
|
||||
}
|
||||
|
||||
public PushTemplateDO getTemplateByCode(String templateCode) {
|
||||
LambdaQueryWrapper<PushTemplateDO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(PushTemplateDO::getTemplateCode, templateCode)
|
||||
.eq(PushTemplateDO::getIsEnable, 1);
|
||||
return pushTemplateMapper.selectOne(wrapper);
|
||||
}
|
||||
|
||||
public String buildFinalContent(String templateCode, Map<String, Object> templateParams) {
|
||||
if (!StringUtils.hasText(templateCode)) {
|
||||
if (templateParams != null && templateParams.containsKey("message")) {
|
||||
Object message = templateParams.get("message");
|
||||
return message == null ? "无内容" : String.valueOf(message);
|
||||
}
|
||||
return "无内容";
|
||||
}
|
||||
|
||||
PushTemplateDO template = getTemplateByCode(templateCode);
|
||||
if (template == null) {
|
||||
throw new IllegalArgumentException("消息模板不存在或已禁用: " + templateCode);
|
||||
}
|
||||
return replaceTemplatePlaceholders(template.getContentPattern(), templateParams);
|
||||
}
|
||||
|
||||
public void markSendSuccess(String messageId, String finalContent) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(1);
|
||||
pushLog.setFailReason(null);
|
||||
pushLog.setFinalContent(finalContent);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public String replaceTemplatePlaceholders(String contentPattern, Map<String, Object> templateParams) {
|
||||
if (!StringUtils.hasText(contentPattern)) {
|
||||
return contentPattern;
|
||||
}
|
||||
if (templateParams == null || templateParams.isEmpty()) {
|
||||
return contentPattern;
|
||||
}
|
||||
|
||||
String result = contentPattern;
|
||||
for (Map.Entry<String, Object> entry : templateParams.entrySet()) {
|
||||
String placeholder = "${" + entry.getKey() + "}";
|
||||
String value = entry.getValue() != null ? entry.getValue().toString() : "";
|
||||
result = result.replace(placeholder, value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private PushLogDO buildPushLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setSourceSystem(messageDTO.getSourceSystem());
|
||||
@@ -59,100 +131,39 @@ public class MessageHandleService {
|
||||
pushLog.setTemplateParams(messageDTO.getTemplateParams() != null ? messageDTO.getTemplateParams().toString() : null);
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setRetryCount(0);
|
||||
|
||||
String channelType = messageDTO.getChannelType();
|
||||
String receiver = messageDTO.getReceiver();
|
||||
|
||||
logger.info("开始校验消息ID: {}, 接收者: {}, 渠道类型: {}", messageId, receiver, channelType);
|
||||
|
||||
if (violations.isEmpty()) {
|
||||
pushLog.setStatus(0);
|
||||
pushLog.setFailReason(null);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.info("参数校验通过,消息ID: {}", messageId);
|
||||
return true;
|
||||
} else {
|
||||
StringBuilder errorBuilder = new StringBuilder();
|
||||
for (ConstraintViolation<MessageDTO> violation : violations) {
|
||||
errorBuilder.append(violation.getMessage()).append("; ");
|
||||
}
|
||||
String failReason = errorBuilder.toString();
|
||||
|
||||
if ("SMS".equalsIgnoreCase(channelType)) {
|
||||
if (receiver == null || !receiver.matches("^1[3-9]\\d{9}$")) {
|
||||
failReason = "手机号格式不正确";
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
} else if ("EMAIL".equalsIgnoreCase(channelType)) {
|
||||
if (receiver == null || !receiver.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
|
||||
failReason = "邮箱格式不正确";
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.error("参数校验失败,消息ID: {}, 错误: {}", messageId, failReason);
|
||||
return false;
|
||||
}
|
||||
return pushLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据模板代码获取推送模板
|
||||
* @param templateCode 模板代码
|
||||
* @return 推送模板对象
|
||||
*/
|
||||
public PushTemplateDO getTemplateByCode(String templateCode) {
|
||||
LambdaQueryWrapper<PushTemplateDO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(PushTemplateDO::getTemplateCode, templateCode) // 匹配模板代码
|
||||
.eq(PushTemplateDO::getIsEnable, 1); // 只查询启用的模板
|
||||
return pushTemplateMapper.selectOne(wrapper); // 查询并返回模板
|
||||
private String validateMessage(MessageDTO messageDTO) {
|
||||
Set<ConstraintViolation<MessageDTO>> violations = validator.validate(messageDTO);
|
||||
if (!violations.isEmpty()) {
|
||||
return violations.stream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.joining(";"));
|
||||
}
|
||||
|
||||
if ("SMS".equalsIgnoreCase(messageDTO.getChannelType()) && !isValidPhone(messageDTO.getReceiver())) {
|
||||
return "手机号格式不正确";
|
||||
}
|
||||
|
||||
if ("EMAIL".equalsIgnoreCase(messageDTO.getChannelType()) && !isValidEmail(messageDTO.getReceiver())) {
|
||||
return "邮箱格式不正确";
|
||||
}
|
||||
|
||||
try {
|
||||
sourceSystemService.requireEnabledSourceSystem(messageDTO.getSourceSystem());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return exception.getMessage();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新推送日志状态
|
||||
* @param messageId 消息ID
|
||||
* @param status 状态码
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
public void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(pushLog); // 更新日志状态
|
||||
private boolean isValidPhone(String receiver) {
|
||||
return receiver != null && receiver.matches("^1[3-9]\\d{9}$");
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换模板中的占位符
|
||||
* @param contentPattern 模板内容
|
||||
* @param templateParams 模板参数
|
||||
* @return 替换后的内容
|
||||
*/
|
||||
public String replaceTemplatePlaceholders(String contentPattern, Map<String, Object> templateParams) {
|
||||
// 如果模板内容为空,直接返回
|
||||
if (!StringUtils.hasText(contentPattern)) {
|
||||
return contentPattern;
|
||||
}
|
||||
|
||||
// 如果模板参数为空,直接返回模板内容
|
||||
if (templateParams == null || templateParams.isEmpty()) {
|
||||
return contentPattern;
|
||||
}
|
||||
|
||||
String result = contentPattern;
|
||||
// 遍历所有参数,替换模板中的占位符
|
||||
for (Map.Entry<String, Object> entry : templateParams.entrySet()) {
|
||||
String placeholder = "${" + entry.getKey() + "}"; // 构建占位符
|
||||
String value = entry.getValue() != null ? entry.getValue().toString() : ""; // 获取参数值
|
||||
result = result.replace(placeholder, value); // 替换占位符
|
||||
}
|
||||
|
||||
return result; // 返回替换后的结果
|
||||
private boolean isValidEmail(String receiver) {
|
||||
return receiver != null && receiver.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -28,7 +28,7 @@ public class SmsSendServiceImpl implements SmsSendService {
|
||||
try {
|
||||
PushTemplateDO templateByCode = messageHandleService.getTemplateByCode(smsMessage.getTemplateCode());
|
||||
if (templateByCode == null) {
|
||||
throw new RuntimeException("短信模板不存在: " + smsMessage.getTemplateCode());
|
||||
throw new RuntimeException("短信模板不存在或已禁用: " + smsMessage.getTemplateCode());
|
||||
}
|
||||
|
||||
SmsDispatchRequest dispatchRequest = new SmsDispatchRequest();
|
||||
@@ -36,6 +36,7 @@ public class SmsSendServiceImpl implements SmsSendService {
|
||||
dispatchRequest.setTemplateCode(smsMessage.getTemplateCode());
|
||||
dispatchRequest.setTemplateExternalId(templateByCode.getExternalId());
|
||||
dispatchRequest.setChannelId(smsMessage.getChannelId());
|
||||
dispatchRequest.setSourceSystem(smsMessage.getSourceSystem());
|
||||
dispatchRequest.setTemplateParams(smsMessage.getTemplateParams());
|
||||
|
||||
messageChannelService.sendSms(dispatchRequest);
|
||||
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package com.xiaowang.messagehub.service.source;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemView;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemChannelDO;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemDO;
|
||||
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
|
||||
import com.xiaowang.messagehub.mapper.MessageSourceSystemChannelMapper;
|
||||
import com.xiaowang.messagehub.mapper.MessageSourceSystemMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class MessageSourceSystemService {
|
||||
|
||||
private final MessageSourceSystemMapper sourceSystemMapper;
|
||||
private final MessageSourceSystemChannelMapper sourceSystemChannelMapper;
|
||||
private final MessageChannelConfigMapper channelConfigMapper;
|
||||
|
||||
public MessageSourceSystemService(MessageSourceSystemMapper sourceSystemMapper,
|
||||
MessageSourceSystemChannelMapper sourceSystemChannelMapper,
|
||||
MessageChannelConfigMapper channelConfigMapper) {
|
||||
this.sourceSystemMapper = sourceSystemMapper;
|
||||
this.sourceSystemChannelMapper = sourceSystemChannelMapper;
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
}
|
||||
|
||||
public List<SourceSystemView> listSourceSystems() {
|
||||
LambdaQueryWrapper<MessageSourceSystemDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.orderByDesc(MessageSourceSystemDO::getEnabled)
|
||||
.orderByAsc(MessageSourceSystemDO::getSystemCode)
|
||||
.orderByDesc(MessageSourceSystemDO::getUpdateTime);
|
||||
return toViews(sourceSystemMapper.selectList(queryWrapper));
|
||||
}
|
||||
|
||||
public SourceSystemView getSourceSystem(Long id) {
|
||||
return toView(requireSourceSystem(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SourceSystemView createSourceSystem(SourceSystemSaveRequest request) {
|
||||
ensureUniqueSystemCode(request.getSystemCode(), null);
|
||||
MessageSourceSystemDO entity = new MessageSourceSystemDO();
|
||||
applySourceSystem(entity, request);
|
||||
sourceSystemMapper.insert(entity);
|
||||
persistDefaultChannel(entity.getId(), ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
|
||||
persistDefaultChannel(entity.getId(), ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
|
||||
return getSourceSystem(entity.getId());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SourceSystemView updateSourceSystem(Long id, SourceSystemSaveRequest request) {
|
||||
MessageSourceSystemDO entity = requireSourceSystem(id);
|
||||
ensureUniqueSystemCode(request.getSystemCode(), id);
|
||||
applySourceSystem(entity, request);
|
||||
sourceSystemMapper.updateById(entity);
|
||||
persistDefaultChannel(id, ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
|
||||
persistDefaultChannel(id, ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
|
||||
return getSourceSystem(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SourceSystemView updateSourceSystemStatus(Long id, boolean enabled) {
|
||||
MessageSourceSystemDO entity = requireSourceSystem(id);
|
||||
entity.setEnabled(enabled ? 1 : 0);
|
||||
sourceSystemMapper.updateById(entity);
|
||||
return getSourceSystem(id);
|
||||
}
|
||||
|
||||
public void requireEnabledSourceSystem(String systemCode) {
|
||||
requireEnabledSourceSystemEntity(systemCode);
|
||||
}
|
||||
|
||||
public Long resolveSystemDefaultChannelId(String systemCode, String channelType) {
|
||||
MessageSourceSystemDO entity = requireEnabledSourceSystemEntity(systemCode);
|
||||
LambdaQueryWrapper<MessageSourceSystemChannelDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageSourceSystemChannelDO::getSystemId, entity.getId())
|
||||
.eq(MessageSourceSystemChannelDO::getChannelType, channelType);
|
||||
MessageSourceSystemChannelDO mapping = sourceSystemChannelMapper.selectOne(queryWrapper);
|
||||
return mapping == null ? null : mapping.getChannelId();
|
||||
}
|
||||
|
||||
private List<SourceSystemView> toViews(List<MessageSourceSystemDO> systems) {
|
||||
if (systems.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Map<Long, MessageSourceSystemDO> systemMap = systems.stream()
|
||||
.collect(Collectors.toMap(MessageSourceSystemDO::getId, Function.identity()));
|
||||
|
||||
LambdaQueryWrapper<MessageSourceSystemChannelDO> mappingQuery = new LambdaQueryWrapper<>();
|
||||
mappingQuery.in(MessageSourceSystemChannelDO::getSystemId, systemMap.keySet());
|
||||
List<MessageSourceSystemChannelDO> mappings = sourceSystemChannelMapper.selectList(mappingQuery);
|
||||
|
||||
Set<Long> channelIds = mappings.stream()
|
||||
.map(MessageSourceSystemChannelDO::getChannelId)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, MessageChannelConfigDO> channelMap = fetchChannelMap(channelIds);
|
||||
|
||||
Map<Long, Map<String, MessageSourceSystemChannelDO>> mappingMap = new LinkedHashMap<>();
|
||||
for (MessageSourceSystemChannelDO mapping : mappings) {
|
||||
mappingMap.computeIfAbsent(mapping.getSystemId(), key -> new LinkedHashMap<>())
|
||||
.put(mapping.getChannelType(), mapping);
|
||||
}
|
||||
|
||||
return systems.stream()
|
||||
.map(system -> toView(system, mappingMap.get(system.getId()), channelMap))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private SourceSystemView toView(MessageSourceSystemDO entity) {
|
||||
return toViews(List.of(entity)).get(0);
|
||||
}
|
||||
|
||||
private SourceSystemView toView(MessageSourceSystemDO entity,
|
||||
Map<String, MessageSourceSystemChannelDO> mappingByType,
|
||||
Map<Long, MessageChannelConfigDO> channelMap) {
|
||||
SourceSystemView view = new SourceSystemView();
|
||||
view.setId(entity.getId());
|
||||
view.setSystemCode(entity.getSystemCode());
|
||||
view.setSystemName(entity.getSystemName());
|
||||
view.setEnabled(entity.getEnabled() != null && entity.getEnabled() == 1);
|
||||
view.setRemark(entity.getRemark());
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
|
||||
if (mappingByType != null) {
|
||||
fillDefaultChannel(view, ChannelTypeEnum.SMS.getCode(), mappingByType.get(ChannelTypeEnum.SMS.getCode()), channelMap);
|
||||
fillDefaultChannel(view, ChannelTypeEnum.EMAIL.getCode(), mappingByType.get(ChannelTypeEnum.EMAIL.getCode()), channelMap);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private void fillDefaultChannel(SourceSystemView view,
|
||||
String channelType,
|
||||
MessageSourceSystemChannelDO mapping,
|
||||
Map<Long, MessageChannelConfigDO> channelMap) {
|
||||
if (mapping == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
MessageChannelConfigDO channel = channelMap.get(mapping.getChannelId());
|
||||
if (ChannelTypeEnum.SMS.getCode().equals(channelType)) {
|
||||
view.setDefaultSmsChannelId(mapping.getChannelId());
|
||||
view.setDefaultSmsChannelName(channel == null ? null : channel.getChannelName());
|
||||
return;
|
||||
}
|
||||
|
||||
view.setDefaultEmailChannelId(mapping.getChannelId());
|
||||
view.setDefaultEmailChannelName(channel == null ? null : channel.getChannelName());
|
||||
}
|
||||
|
||||
private Map<Long, MessageChannelConfigDO> fetchChannelMap(Set<Long> channelIds) {
|
||||
if (channelIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return channelConfigMapper.selectBatchIds(channelIds).stream()
|
||||
.collect(Collectors.toMap(MessageChannelConfigDO::getId, Function.identity()));
|
||||
}
|
||||
|
||||
private void applySourceSystem(MessageSourceSystemDO entity, SourceSystemSaveRequest request) {
|
||||
entity.setSystemCode(normalizeSystemCode(request.getSystemCode()));
|
||||
entity.setSystemName(request.getSystemName().trim());
|
||||
entity.setEnabled(Boolean.TRUE.equals(request.getEnabled()) ? 1 : 0);
|
||||
entity.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
|
||||
}
|
||||
|
||||
private void ensureUniqueSystemCode(String systemCode, Long excludeId) {
|
||||
LambdaQueryWrapper<MessageSourceSystemDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageSourceSystemDO::getSystemCode, normalizeSystemCode(systemCode));
|
||||
if (excludeId != null) {
|
||||
queryWrapper.ne(MessageSourceSystemDO::getId, excludeId);
|
||||
}
|
||||
if (sourceSystemMapper.selectCount(queryWrapper) > 0) {
|
||||
throw new IllegalArgumentException("系统标识已存在: " + normalizeSystemCode(systemCode));
|
||||
}
|
||||
}
|
||||
|
||||
private void persistDefaultChannel(Long systemId, String channelType, Long channelId) {
|
||||
LambdaQueryWrapper<MessageSourceSystemChannelDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageSourceSystemChannelDO::getSystemId, systemId)
|
||||
.eq(MessageSourceSystemChannelDO::getChannelType, channelType);
|
||||
MessageSourceSystemChannelDO existing = sourceSystemChannelMapper.selectOne(queryWrapper);
|
||||
|
||||
if (channelId == null) {
|
||||
if (existing != null) {
|
||||
sourceSystemChannelMapper.deleteById(existing.getId());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
validateChannelForDefault(channelId, channelType);
|
||||
if (existing == null) {
|
||||
MessageSourceSystemChannelDO entity = new MessageSourceSystemChannelDO();
|
||||
entity.setSystemId(systemId);
|
||||
entity.setChannelType(channelType);
|
||||
entity.setChannelId(channelId);
|
||||
sourceSystemChannelMapper.insert(entity);
|
||||
return;
|
||||
}
|
||||
|
||||
existing.setChannelId(channelId);
|
||||
sourceSystemChannelMapper.updateById(existing);
|
||||
}
|
||||
|
||||
private void validateChannelForDefault(Long channelId, String channelType) {
|
||||
MessageChannelConfigDO channel = channelConfigMapper.selectById(channelId);
|
||||
if (channel == null) {
|
||||
throw new IllegalArgumentException("默认通道不存在: " + channelId);
|
||||
}
|
||||
if (!channelType.equalsIgnoreCase(channel.getChannelType())) {
|
||||
throw new IllegalArgumentException("默认通道类型不匹配: " + channelId);
|
||||
}
|
||||
if (channel.getEnabled() == null || channel.getEnabled() != 1) {
|
||||
throw new IllegalArgumentException("默认通道未启用: " + channelId);
|
||||
}
|
||||
}
|
||||
|
||||
private MessageSourceSystemDO requireSourceSystem(Long id) {
|
||||
MessageSourceSystemDO entity = sourceSystemMapper.selectById(id);
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("来源系统不存在: " + id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private MessageSourceSystemDO findBySystemCode(String systemCode) {
|
||||
LambdaQueryWrapper<MessageSourceSystemDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageSourceSystemDO::getSystemCode, normalizeSystemCode(systemCode));
|
||||
return sourceSystemMapper.selectOne(queryWrapper);
|
||||
}
|
||||
|
||||
private MessageSourceSystemDO requireEnabledSourceSystemEntity(String systemCode) {
|
||||
MessageSourceSystemDO entity = findBySystemCode(systemCode);
|
||||
if (entity == null || entity.getEnabled() == null || entity.getEnabled() != 1) {
|
||||
throw new IllegalArgumentException("来源系统未登记或已停用: " + normalizeSystemCode(systemCode));
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private String normalizeSystemCode(String systemCode) {
|
||||
if (!StringUtils.hasText(systemCode)) {
|
||||
throw new IllegalArgumentException("来源系统标识不能为空");
|
||||
}
|
||||
return systemCode.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
@@ -4,90 +4,87 @@
|
||||
|
||||
2026-03-23
|
||||
|
||||
## 变更主题
|
||||
## 本轮主题
|
||||
|
||||
通道配置后台化与运行文档补齐
|
||||
来源系统白名单与系统级默认通道落地
|
||||
|
||||
## 本次主要变更
|
||||
## 主要变更
|
||||
|
||||
### 1. 通道配置从 Nacos/YAML 改为数据库维护
|
||||
### 1. 新增来源系统白名单能力
|
||||
|
||||
- 新增 `message_channel_config` 表
|
||||
- 短信/邮件发送逻辑改为优先读取数据库中的通道配置
|
||||
- 不再依赖原有 `sms.*`、`email.*` 的固定配置方式
|
||||
- 新增 `message_source_system` 表
|
||||
- 后台可维护允许接入的来源系统
|
||||
- 外围系统消息必须传 `sourceSystem`
|
||||
- 若 `sourceSystem` 未登记或已停用,消费阶段直接拒绝
|
||||
|
||||
### 2. 新增独立后台页面
|
||||
### 2. 新增“来源系统默认通道”能力
|
||||
|
||||
- 新增 `static/messagehub-admin/` 管理页面
|
||||
- 支持通道的新增、编辑、启停、健康检查、测试发送
|
||||
- 新增 `message_source_system_channel` 表
|
||||
- 每个来源系统可分别配置默认短信通道、默认邮件通道
|
||||
- 当消息未传 `channelId` 时,优先走来源系统默认通道
|
||||
- 若来源系统未配置默认通道,则回退到全局默认通道
|
||||
|
||||
### 3. 敏感字段加密存储
|
||||
### 3. 支持 `channelId` 显式指定通道
|
||||
|
||||
- Spug `apiKey`
|
||||
- SMTP `password`
|
||||
|
||||
加密方式为 AES-GCM。
|
||||
|
||||
### 4. 启动期增强
|
||||
|
||||
- 开发环境自动补齐 Mock 通道
|
||||
- 启动后执行通道健康检查
|
||||
- 为 Nacos 客户端自动准备可写日志目录与快照目录
|
||||
|
||||
### 5. 异常提示优化
|
||||
|
||||
- 当数据库未执行补丁时,`/admin/api/channels` 会明确提示:
|
||||
- `缺少消息通道配置表,请先执行 2026-03-23_message_channel_management_patch.sql`
|
||||
|
||||
### 6. 新增可选 channelId 指定发送
|
||||
|
||||
- 业务消息体新增可选字段 `channelId`
|
||||
- 不传时,仍按通道类型走默认通道
|
||||
- 业务消息体保留可选字段 `channelId`
|
||||
- 传入时,按 `channelType + channelId` 精确匹配
|
||||
- 后台页面通道列表与保存提示中会直接展示通道 ID
|
||||
- 不传时,走“来源系统默认通道 -> 全局默认通道”的回退链路
|
||||
|
||||
### 4. 后台管理页扩展
|
||||
|
||||
- 后台页面从“仅通道管理”升级为:
|
||||
- 来源系统管理
|
||||
- 通道管理
|
||||
- 测试发送
|
||||
- 后台可直接配置不同来源系统的默认短信/邮件通道
|
||||
|
||||
### 5. 消费链路与日志修正
|
||||
|
||||
- 短信监听器改为走统一校验入口
|
||||
- 邮件监听器补齐发送失败日志回写
|
||||
- 日志状态支持:
|
||||
- `0` 待发送
|
||||
- `1` 发送成功
|
||||
- `2` 发送失败
|
||||
- 邮件正文模板渲染改为按模板内容渲染,不再误把模板编码当正文
|
||||
|
||||
### 6. 中文提示与初始化说明补齐
|
||||
|
||||
- 后台相关接口提示统一改为中文
|
||||
- 当缺少来源系统相关表时,会明确提示执行:
|
||||
- `2026-03-23_message_source_system_patch.sql`
|
||||
|
||||
## 数据库 SQL
|
||||
|
||||
本轮数据库变更 SQL 如下:
|
||||
本轮新增 SQL 文件:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS `message_channel_config` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
||||
`channel_type` VARCHAR(20) NOT NULL COMMENT 'SMS / EMAIL',
|
||||
`provider_code` VARCHAR(50) NOT NULL COMMENT 'SPUG / GMAIL / QQMAIL / MOCK_SMS / MOCK_EMAIL',
|
||||
`channel_name` VARCHAR(100) NOT NULL COMMENT 'Display name',
|
||||
`config_json` TEXT NULL COMMENT 'Public config JSON',
|
||||
`secret_json` TEXT NULL COMMENT 'Encrypted secret JSON',
|
||||
`enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '1 enabled, 0 disabled',
|
||||
`is_default` TINYINT NOT NULL DEFAULT 0 COMMENT '1 default, 0 non-default',
|
||||
`health_status` VARCHAR(20) NOT NULL DEFAULT 'UNKNOWN' COMMENT 'UNKNOWN / HEALTHY / UNHEALTHY',
|
||||
`health_message` VARCHAR(255) NULL COMMENT 'Last health message',
|
||||
`last_health_check_time` DATETIME NULL COMMENT 'Last health check time',
|
||||
`remark` VARCHAR(255) NULL COMMENT 'Remark',
|
||||
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT 'Logical delete flag',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Create time',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_message_channel_type_provider` (`channel_type`, `provider_code`),
|
||||
KEY `idx_message_channel_enabled_default` (`channel_type`, `enabled`, `is_default`),
|
||||
KEY `idx_message_channel_deleted` (`deleted`),
|
||||
KEY `idx_message_channel_name` (`channel_name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Message channel management';
|
||||
```
|
||||
- [2026-03-23_message_source_system_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_source_system_patch.sql)
|
||||
|
||||
正式执行文件:
|
||||
推荐执行顺序:
|
||||
|
||||
- [2026-03-23_message_channel_management_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_channel_management_patch.sql)
|
||||
1. [2026-03-23_message_channel_management_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_channel_management_patch.sql)
|
||||
2. [2026-03-23_message_source_system_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_source_system_patch.sql)
|
||||
|
||||
## 验证情况
|
||||
## 对外围系统的调用约定
|
||||
|
||||
- `MessageHub` 已重新打包
|
||||
- `MessageHub` 服务已启动
|
||||
- 管理页 `/messagehub-admin/` 可访问
|
||||
- 未执行 SQL 补丁时,接口会返回明确中文提示
|
||||
外围系统仍然只需要往现有队列发消息:
|
||||
|
||||
- 短信:`smsQueue`
|
||||
- 邮件:`emailQueue`
|
||||
|
||||
但消息体现在需要满足:
|
||||
|
||||
- 必传 `sourceSystem`
|
||||
- 可选传 `channelId`
|
||||
|
||||
分发优先级:
|
||||
|
||||
1. `channelId`
|
||||
2. 来源系统默认通道
|
||||
3. 全局默认通道
|
||||
|
||||
## 备注
|
||||
|
||||
- 本文件用于放在 `resources` 目录中,便于部署时随包查看
|
||||
- 更完整的任务归档记录见:
|
||||
- [2026-03-23-MessageHub通道配置后台化.md](/E:/code/xiaowang/docs/changes/2026-03-23-MessageHub通道配置后台化.md)
|
||||
- 数据库仍由你手工执行 SQL,不做自动迁移
|
||||
- 更完整的任务归档见:
|
||||
- [2026-03-23-MessageHub来源系统白名单与系统默认通道.md](/E:/code/xiaowang/docs/changes/2026-03-23-MessageHub来源系统白名单与系统默认通道.md)
|
||||
|
||||
@@ -2,130 +2,62 @@
|
||||
|
||||
## 1. 项目定位
|
||||
|
||||
`MessageHub` 是 `YumiNail` 体系中的独立消息中心服务,负责统一承接短信、邮件、模板消息发送,以及通过消息队列进行异步消费。
|
||||
`MessageHub` 是 `YumiNail` 体系中的独立消息中心服务,负责统一承接短信、邮件、模板消息发送,并通过 RabbitMQ 进行异步消费。
|
||||
|
||||
当前版本已经从“配置文件驱动通道”调整为“数据库驱动通道”:
|
||||
当前版本已经具备以下核心能力:
|
||||
|
||||
- 短信/邮件通道配置以数据库表为主
|
||||
- 后台可维护通道的新增、修改、启停、健康检查、测试发送
|
||||
- 敏感字段加密存储
|
||||
- 开发环境支持 Mock 通道,方便本地或测试环境联调
|
||||
- 通道配置从 Nacos/YAML 改为数据库可维护
|
||||
- 通道敏感字段加密存储
|
||||
- 后台支持新增、修改、启停、健康检查、测试发送
|
||||
- 开发环境自动补齐 Mock 短信/邮件通道
|
||||
- 外围系统必须携带 `sourceSystem`
|
||||
- 支持按来源系统配置短信/邮件默认通道
|
||||
- 消息体可选传入 `channelId` 指定通道
|
||||
|
||||
## 2. 运行依赖
|
||||
|
||||
服务启动和正常运行依赖以下基础设施:
|
||||
服务启动与运行依赖以下基础设施:
|
||||
|
||||
- MySQL:存储消息记录、模板、通道配置
|
||||
- MySQL:存储消息日志、模板、通道配置、来源系统白名单
|
||||
- RabbitMQ:承接异步消息投递
|
||||
- Nacos:服务注册与配置中心
|
||||
|
||||
默认启动后会注册到 `MessageHub` 命名空间,并通过 HTTP 提供后台管理入口。
|
||||
## 3. 推荐数据库执行顺序
|
||||
|
||||
## 3. 资源目录说明
|
||||
当前推荐的 MessageHub 数据库执行顺序如下:
|
||||
|
||||
1. 执行 [2026-03-23_message_channel_management_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_channel_management_patch.sql)
|
||||
2. 执行 [2026-03-23_message_source_system_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_source_system_patch.sql)
|
||||
|
||||
说明:
|
||||
|
||||
- 第一份 SQL 创建通道配置表
|
||||
- 第二份 SQL 创建来源系统白名单表和“来源系统默认通道”映射表
|
||||
- 本轮仍然不做自动迁移,SQL 需要手工执行
|
||||
|
||||
## 4. 资源目录说明
|
||||
|
||||
`src/main/resources` 下当前关键内容如下:
|
||||
|
||||
- `application.yml`
|
||||
- `MessageHub` 自身配置
|
||||
- 通道加密主密钥、Mock 自动补齐开关
|
||||
- MessageHub 自身配置
|
||||
- 通道加密主密钥
|
||||
- Mock 通道自动补齐开关
|
||||
- `bootstrap.yaml`
|
||||
- Nacos 注册与配置中心接入
|
||||
- `log4j2.xml`
|
||||
- 服务日志输出配置
|
||||
- Nacos 注册与配置接入
|
||||
- `sql/2026-03-23_message_channel_management_patch.sql`
|
||||
- 本轮数据库补丁,新增消息通道配置表
|
||||
- 通道管理表补丁
|
||||
- `sql/2026-03-23_message_source_system_patch.sql`
|
||||
- 来源系统白名单与系统默认通道补丁
|
||||
- `static/messagehub-admin/`
|
||||
- 独立后台页面
|
||||
- 后台管理页面
|
||||
- 访问地址:`http://<host>:8080/messagehub-admin/`
|
||||
- `files/`
|
||||
- 现有业务资源文件目录
|
||||
|
||||
## 4. 代码结构概览
|
||||
## 5. 发送规则
|
||||
|
||||
`src/main/java/com/xiaowang/messagehub` 主要分层如下:
|
||||
外围系统仍然通过 MQ 向 `MessageHub` 投递消息,不需要直连具体短信或邮件提供商。
|
||||
|
||||
- `controller`
|
||||
- 对外接口与后台管理接口
|
||||
- `service`
|
||||
- 消息发送主流程
|
||||
- `service/channel`
|
||||
- 通道配置、加密、环境识别、通道分发
|
||||
- `service/channel/email`
|
||||
- 邮件通道实现,当前支持 SMTP 与 Mock
|
||||
- `service/channel/sms`
|
||||
- 短信通道实现,当前支持 Spug 与 Mock
|
||||
- `mapper`
|
||||
- MyBatis-Plus 数据访问层
|
||||
- `entity`
|
||||
- 数据库实体
|
||||
- `dto`
|
||||
- 后台页面接口入参/出参
|
||||
- `model`
|
||||
- 通道运行期模型
|
||||
- `listener`
|
||||
- 启动完成后的依赖检查、Mock 通道补齐、健康检查
|
||||
|
||||
## 5. 通道管理能力
|
||||
|
||||
当前已实现的后台能力包括:
|
||||
|
||||
- 查看全部通道
|
||||
- 新增通道
|
||||
- 编辑通道
|
||||
- 启停通道
|
||||
- 设置默认通道
|
||||
- 通道健康检查
|
||||
- 测试发送
|
||||
- 展示通道 ID,供外围系统在消息体中按需指定
|
||||
|
||||
当前支持的通道类型与提供商:
|
||||
|
||||
- 短信
|
||||
- `SPUG`
|
||||
- `MOCK_SMS`
|
||||
- 邮件
|
||||
- `GMAIL`
|
||||
- `QQMAIL`
|
||||
- `MOCK_EMAIL`
|
||||
|
||||
## 6. 数据库变动
|
||||
|
||||
本轮数据库只有一项变动:新增消息通道配置表 `message_channel_config`。
|
||||
|
||||
执行 SQL 文件:
|
||||
|
||||
- [2026-03-23_message_channel_management_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_channel_management_patch.sql)
|
||||
|
||||
表的用途:
|
||||
|
||||
- 保存短信/邮件通道基础配置
|
||||
- 保存加密后的敏感配置
|
||||
- 记录通道启停状态
|
||||
- 记录默认通道
|
||||
- 记录健康检查结果
|
||||
|
||||
## 7. 建议执行顺序
|
||||
|
||||
部署或初始化时建议按以下顺序处理:
|
||||
|
||||
1. 先准备 MySQL、RabbitMQ、Nacos
|
||||
2. 执行 `sql/2026-03-23_message_channel_management_patch.sql`
|
||||
3. 启动 `MessageHub`
|
||||
4. 打开 `/messagehub-admin/`
|
||||
5. 配置短信/邮件通道
|
||||
6. 通过“健康检查”和“测试发送”验证配置
|
||||
|
||||
## 8. 外围系统调用约定
|
||||
|
||||
外围系统仍然通过 MQ 向 `MessageHub` 投递业务消息,不直接调用某个提供商。
|
||||
|
||||
- 不传 `channelId`
|
||||
- `MessageHub` 会按消息类型自动选择当前默认通道
|
||||
- 传入 `channelId`
|
||||
- `MessageHub` 会按 `channelType + channelId` 精确匹配通道
|
||||
- 若通道不存在、类型不匹配或已停用,则直接返回错误
|
||||
|
||||
推荐消息体字段:
|
||||
消息体最少应包含以下字段:
|
||||
|
||||
- `receiver`
|
||||
- `channelType`
|
||||
@@ -134,10 +66,43 @@
|
||||
- `templateParams`
|
||||
- `sourceSystem`
|
||||
- `uniqueId`
|
||||
- `channelId` 可选
|
||||
## 9. 当前已知说明
|
||||
|
||||
- 如果未执行 SQL 补丁,管理页可以打开,但通道列表接口会提示缺少 `message_channel_config` 表
|
||||
- 当前管理页未接入登录鉴权,适合内网管理场景
|
||||
- `MessageHub` 启动时已做 Nacos 日志目录兜底,避免某些环境下因系统用户目录不可写而启动失败
|
||||
- 开发环境下会自动补齐 Mock 通道;生产环境不会自动启用 Mock 通道
|
||||
可选字段:
|
||||
|
||||
- `channelId`
|
||||
|
||||
分发规则如下:
|
||||
|
||||
1. 先校验 `sourceSystem` 是否已在后台登记且处于启用状态
|
||||
2. 如果消息显式传入 `channelId`,按 `channelType + channelId` 精确匹配
|
||||
3. 如果未传 `channelId`,优先查找该 `sourceSystem` 对应类型的默认通道
|
||||
4. 如果该系统未配置默认通道,则回退到该类型的全局默认通道
|
||||
|
||||
## 6. 后台管理能力
|
||||
|
||||
当前后台页面覆盖两类管理对象:
|
||||
|
||||
### 6.1 来源系统
|
||||
|
||||
- 新增来源系统
|
||||
- 编辑来源系统
|
||||
- 启停来源系统
|
||||
- 配置每个来源系统的默认短信通道
|
||||
- 配置每个来源系统的默认邮件通道
|
||||
|
||||
### 6.2 消息通道
|
||||
|
||||
- 新增短信/邮件通道
|
||||
- 编辑通道配置
|
||||
- 启停通道
|
||||
- 设置全局默认通道
|
||||
- 执行健康检查
|
||||
- 发送测试消息
|
||||
- 展示通道 ID,供外围系统显式指定
|
||||
|
||||
## 7. 当前已知说明
|
||||
|
||||
- 如果未执行 SQL 补丁,后台相关接口会返回明确中文提示
|
||||
- 未登记来源系统的消息会被拒绝,并写入失败日志
|
||||
- 后台测试发送是“直连指定通道”模式,不依赖来源系统白名单
|
||||
- 开发环境下会自动补齐 Mock 通道,生产环境不会自动启用 Mock 通道
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
CREATE TABLE IF NOT EXISTS `message_source_system` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
||||
`system_code` VARCHAR(64) NOT NULL COMMENT 'External source system code',
|
||||
`system_name` VARCHAR(100) NOT NULL COMMENT 'External source system name',
|
||||
`enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '1 enabled, 0 disabled',
|
||||
`remark` VARCHAR(255) NULL COMMENT 'Remark',
|
||||
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT 'Logical delete flag',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Create time',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_message_source_system_code` (`system_code`),
|
||||
KEY `idx_message_source_system_enabled` (`enabled`),
|
||||
KEY `idx_message_source_system_deleted` (`deleted`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Allowed source systems';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `message_source_system_channel` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
||||
`system_id` BIGINT NOT NULL COMMENT 'Source system id',
|
||||
`channel_type` VARCHAR(20) NOT NULL COMMENT 'SMS / EMAIL',
|
||||
`channel_id` BIGINT NOT NULL COMMENT 'Default channel id for this source system and type',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Create time',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_message_source_system_channel` (`system_id`, `channel_type`),
|
||||
KEY `idx_message_source_system_channel_id` (`channel_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Per source system default channels';
|
||||
@@ -1,7 +1,7 @@
|
||||
const PROVIDERS = {
|
||||
SMS: {
|
||||
SPUG: {
|
||||
label: "Spug短信",
|
||||
label: "Spug 短信",
|
||||
configFields: [
|
||||
{ key: "baseUrl", label: "基础地址", placeholder: "https://push.spug.cc", required: true }
|
||||
],
|
||||
@@ -10,7 +10,7 @@ const PROVIDERS = {
|
||||
]
|
||||
},
|
||||
MOCK_SMS: {
|
||||
label: "开发Mock短信",
|
||||
label: "开发 Mock 短信",
|
||||
configFields: [],
|
||||
secretFields: []
|
||||
}
|
||||
@@ -32,7 +32,7 @@ const PROVIDERS = {
|
||||
]
|
||||
},
|
||||
QQMAIL: {
|
||||
label: "QQ邮箱 SMTP",
|
||||
label: "QQ 邮箱 SMTP",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.qq.com", required: true, defaultValue: "smtp.qq.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
@@ -47,7 +47,7 @@ const PROVIDERS = {
|
||||
]
|
||||
},
|
||||
MOCK_EMAIL: {
|
||||
label: "开发Mock邮件",
|
||||
label: "开发 Mock 邮件",
|
||||
configFields: [
|
||||
{ key: "fromAddress", label: "模拟发件地址", placeholder: "mock@messagehub.local", defaultValue: "mock@messagehub.local" }
|
||||
],
|
||||
@@ -58,15 +58,32 @@ const PROVIDERS = {
|
||||
|
||||
const state = {
|
||||
channels: [],
|
||||
editingChannel: null
|
||||
sourceSystems: [],
|
||||
editingChannel: null,
|
||||
editingSourceSystem: null
|
||||
};
|
||||
|
||||
const elements = {
|
||||
channelTableBody: document.getElementById("channelTableBody"),
|
||||
channelEmptyState: document.getElementById("channelEmptyState"),
|
||||
refreshButton: document.getElementById("refreshButton"),
|
||||
createButton: document.getElementById("createButton"),
|
||||
resetButton: document.getElementById("resetButton"),
|
||||
createSourceButton: document.getElementById("createSourceButton"),
|
||||
|
||||
sourceSystemTableBody: document.getElementById("sourceSystemTableBody"),
|
||||
sourceSystemEmptyState: document.getElementById("sourceSystemEmptyState"),
|
||||
sourceSystemForm: document.getElementById("sourceSystemForm"),
|
||||
sourceSystemId: document.getElementById("sourceSystemId"),
|
||||
sourceSystemCode: document.getElementById("sourceSystemCode"),
|
||||
sourceSystemName: document.getElementById("sourceSystemName"),
|
||||
sourceSystemRemark: document.getElementById("sourceSystemRemark"),
|
||||
sourceSystemEnabled: document.getElementById("sourceSystemEnabled"),
|
||||
defaultSmsChannelId: document.getElementById("defaultSmsChannelId"),
|
||||
defaultEmailChannelId: document.getElementById("defaultEmailChannelId"),
|
||||
sourceFormTitle: document.getElementById("sourceFormTitle"),
|
||||
sourceFormSubtitle: document.getElementById("sourceFormSubtitle"),
|
||||
sourceResetButton: document.getElementById("sourceResetButton"),
|
||||
|
||||
channelTableBody: document.getElementById("channelTableBody"),
|
||||
channelEmptyState: document.getElementById("channelEmptyState"),
|
||||
channelForm: document.getElementById("channelForm"),
|
||||
channelId: document.getElementById("channelId"),
|
||||
channelType: document.getElementById("channelType"),
|
||||
@@ -78,6 +95,8 @@ const elements = {
|
||||
dynamicFields: document.getElementById("dynamicFields"),
|
||||
formTitle: document.getElementById("formTitle"),
|
||||
formSubtitle: document.getElementById("formSubtitle"),
|
||||
resetButton: document.getElementById("resetButton"),
|
||||
|
||||
testForm: document.getElementById("testForm"),
|
||||
testChannelId: document.getElementById("testChannelId"),
|
||||
testReceiver: document.getElementById("testReceiver"),
|
||||
@@ -85,6 +104,7 @@ const elements = {
|
||||
testTemplateCode: document.getElementById("testTemplateCode"),
|
||||
testContent: document.getElementById("testContent"),
|
||||
testTemplateParams: document.getElementById("testTemplateParams"),
|
||||
|
||||
toast: document.getElementById("toast")
|
||||
};
|
||||
|
||||
@@ -120,6 +140,161 @@ function providerSchema(channelType, providerCode) {
|
||||
return PROVIDERS[channelType][providerCode];
|
||||
}
|
||||
|
||||
function formatDateTime(value) {
|
||||
if (!value) {
|
||||
return "-";
|
||||
}
|
||||
return new Date(value).toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function buildChannelOptions(channelType, selectedId = "") {
|
||||
const enabledChannels = state.channels.filter((channel) => channel.channelType === channelType && channel.enabled);
|
||||
const selectedChannel = state.channels.find((channel) => String(channel.id) === String(selectedId));
|
||||
const items = [...enabledChannels];
|
||||
|
||||
if (selectedChannel && !items.some((channel) => channel.id === selectedChannel.id)) {
|
||||
items.unshift(selectedChannel);
|
||||
}
|
||||
|
||||
const defaultLabel = channelType === "SMS" ? "跟随全局默认短信通道" : "跟随全局默认邮件通道";
|
||||
const options = [`<option value="">${defaultLabel}</option>`];
|
||||
|
||||
items.forEach((channel) => {
|
||||
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
|
||||
const disabledTag = channel.enabled ? "" : "(当前已停用)";
|
||||
options.push(
|
||||
`<option value="${channel.id}" ${selected}>${channel.channelName} / ID:${channel.id}${disabledTag}</option>`
|
||||
);
|
||||
});
|
||||
|
||||
return options.join("");
|
||||
}
|
||||
|
||||
function fillSourceChannelOptions(sourceSystem = state.editingSourceSystem) {
|
||||
elements.defaultSmsChannelId.innerHTML = buildChannelOptions("SMS", sourceSystem?.defaultSmsChannelId || "");
|
||||
elements.defaultEmailChannelId.innerHTML = buildChannelOptions("EMAIL", sourceSystem?.defaultEmailChannelId || "");
|
||||
}
|
||||
|
||||
function resetSourceSystemForm(sourceSystem = null) {
|
||||
state.editingSourceSystem = sourceSystem;
|
||||
elements.sourceSystemId.value = sourceSystem?.id || "";
|
||||
elements.sourceSystemCode.value = sourceSystem?.systemCode || "";
|
||||
elements.sourceSystemName.value = sourceSystem?.systemName || "";
|
||||
elements.sourceSystemRemark.value = sourceSystem?.remark || "";
|
||||
elements.sourceSystemEnabled.checked = sourceSystem?.enabled ?? true;
|
||||
fillSourceChannelOptions(sourceSystem);
|
||||
elements.sourceFormTitle.textContent = sourceSystem ? "编辑来源系统" : "新增来源系统";
|
||||
elements.sourceFormSubtitle.textContent = sourceSystem
|
||||
? `当前来源系统 ID:${sourceSystem.id}。不指定默认通道时,将回退到全局默认通道。`
|
||||
: "系统标识会统一转成小写保存。不指定默认通道时,会回退到全局默认通道。";
|
||||
}
|
||||
|
||||
function sourceStatusBadge(sourceSystem) {
|
||||
return sourceSystem.enabled
|
||||
? `<span class="badge good">已启用</span>`
|
||||
: `<span class="badge bad">已停用</span>`;
|
||||
}
|
||||
|
||||
function defaultChannelText(channelId, channelName) {
|
||||
if (!channelId) {
|
||||
return `<span class="table-note">跟随全局默认通道</span>`;
|
||||
}
|
||||
return `<strong>${channelName || "未知通道"}</strong><div class="table-note">ID:${channelId}</div>`;
|
||||
}
|
||||
|
||||
function renderSourceSystemTable() {
|
||||
elements.sourceSystemTableBody.innerHTML = "";
|
||||
elements.sourceSystemEmptyState.hidden = state.sourceSystems.length > 0;
|
||||
|
||||
state.sourceSystems.forEach((sourceSystem) => {
|
||||
const row = document.createElement("tr");
|
||||
row.innerHTML = `
|
||||
<td>
|
||||
<strong>${sourceSystem.systemName}</strong>
|
||||
<div class="table-note">系统标识:<code>${sourceSystem.systemCode}</code></div>
|
||||
${sourceSystem.remark ? `<div class="table-note">${sourceSystem.remark}</div>` : ""}
|
||||
</td>
|
||||
<td>${sourceStatusBadge(sourceSystem)}</td>
|
||||
<td>${defaultChannelText(sourceSystem.defaultSmsChannelId, sourceSystem.defaultSmsChannelName)}</td>
|
||||
<td>${defaultChannelText(sourceSystem.defaultEmailChannelId, sourceSystem.defaultEmailChannelName)}</td>
|
||||
<td>${formatDateTime(sourceSystem.updateTime)}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button class="ghost-button small" data-action="edit" data-id="${sourceSystem.id}">编辑</button>
|
||||
<button class="ghost-button small" data-action="status" data-id="${sourceSystem.id}">
|
||||
${sourceSystem.enabled ? "停用" : "启用"}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
elements.sourceSystemTableBody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadSourceSystems() {
|
||||
state.sourceSystems = await request("/admin/api/source-systems");
|
||||
const editingId = state.editingSourceSystem?.id;
|
||||
if (editingId) {
|
||||
state.editingSourceSystem = state.sourceSystems.find((item) => item.id === editingId) || null;
|
||||
}
|
||||
renderSourceSystemTable();
|
||||
resetSourceSystemForm(state.editingSourceSystem);
|
||||
}
|
||||
|
||||
async function onSourceSystemSubmit(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const payload = {
|
||||
systemCode: elements.sourceSystemCode.value.trim(),
|
||||
systemName: elements.sourceSystemName.value.trim(),
|
||||
remark: elements.sourceSystemRemark.value.trim(),
|
||||
enabled: elements.sourceSystemEnabled.checked,
|
||||
defaultSmsChannelId: elements.defaultSmsChannelId.value ? Number(elements.defaultSmsChannelId.value) : null,
|
||||
defaultEmailChannelId: elements.defaultEmailChannelId.value ? Number(elements.defaultEmailChannelId.value) : null
|
||||
};
|
||||
|
||||
const sourceSystemId = elements.sourceSystemId.value;
|
||||
const saved = sourceSystemId
|
||||
? await request(`/admin/api/source-systems/${sourceSystemId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
: await request("/admin/api/source-systems", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
showToast(`来源系统已保存:${saved.systemCode}`);
|
||||
state.editingSourceSystem = saved;
|
||||
await loadSourceSystems();
|
||||
}
|
||||
|
||||
async function onSourceSystemTableClick(event) {
|
||||
const target = event.target.closest("button[data-action]");
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
const id = target.dataset.id;
|
||||
const action = target.dataset.action;
|
||||
|
||||
if (action === "edit") {
|
||||
const detail = await request(`/admin/api/source-systems/${id}`);
|
||||
resetSourceSystemForm(detail);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "status") {
|
||||
const sourceSystem = state.sourceSystems.find((item) => String(item.id) === String(id));
|
||||
await request(`/admin/api/source-systems/${id}/status`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ enabled: !sourceSystem.enabled })
|
||||
});
|
||||
showToast(sourceSystem.enabled ? `来源系统已停用:${sourceSystem.systemCode}` : `来源系统已启用:${sourceSystem.systemCode}`);
|
||||
await loadSourceSystems();
|
||||
}
|
||||
}
|
||||
|
||||
function fillProviderOptions() {
|
||||
const channelType = elements.channelType.value;
|
||||
const providerOptions = Object.entries(PROVIDERS[channelType]).map(([code, schema]) => {
|
||||
@@ -186,7 +361,7 @@ function renderDynamicFields() {
|
||||
elements.dynamicFields.innerHTML = [...configFields, ...secretFields].join("");
|
||||
}
|
||||
|
||||
function resetForm(channel = null) {
|
||||
function resetChannelForm(channel = null) {
|
||||
state.editingChannel = channel;
|
||||
elements.channelId.value = channel?.id || "";
|
||||
elements.channelType.value = channel?.channelType || "SMS";
|
||||
@@ -198,8 +373,8 @@ function resetForm(channel = null) {
|
||||
elements.isDefault.checked = channel?.isDefault ?? false;
|
||||
elements.formTitle.textContent = channel ? "编辑通道" : "新增通道";
|
||||
elements.formSubtitle.textContent = channel
|
||||
? `当前通道 ID:${channel.id}。外围系统可在消息体中传 channelId 指定使用该通道。`
|
||||
: "保存后会生成通道 ID,外围系统可在消息体中通过 channelId 指定该通道。";
|
||||
? `当前通道 ID:${channel.id}。来源系统可将它设为默认通道,外围系统也可以在消息体中显式传入该 ID。`
|
||||
: "保存后会生成通道 ID。来源系统可配置默认通道,外围系统也可以在消息体中显式传入该 ID。";
|
||||
renderDynamicFields();
|
||||
}
|
||||
|
||||
@@ -208,7 +383,7 @@ function statusBadge(channel) {
|
||||
return `<span class="badge warn">已停用</span>`;
|
||||
}
|
||||
return channel.isDefault
|
||||
? `<span class="badge good">已启用 / 默认</span>`
|
||||
? `<span class="badge good">已启用 / 全局默认</span>`
|
||||
: `<span class="badge warn">已启用</span>`;
|
||||
}
|
||||
|
||||
@@ -241,7 +416,7 @@ function renderChannelTable() {
|
||||
${healthBadge(channel)}
|
||||
${channel.healthMessage ? `<div class="table-note">${channel.healthMessage}</div>` : ""}
|
||||
</td>
|
||||
<td>${channel.lastHealthCheckTime ? new Date(channel.lastHealthCheckTime).toLocaleString() : "-"}</td>
|
||||
<td>${formatDateTime(channel.lastHealthCheckTime)}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button class="ghost-button small" data-action="edit" data-id="${channel.id}">编辑</button>
|
||||
@@ -288,12 +463,22 @@ function collectDynamicValues(role) {
|
||||
}
|
||||
|
||||
async function loadChannels() {
|
||||
const channels = await request("/admin/api/channels");
|
||||
state.channels = channels;
|
||||
state.channels = await request("/admin/api/channels");
|
||||
const editingId = state.editingChannel?.id;
|
||||
if (editingId) {
|
||||
state.editingChannel = state.channels.find((item) => item.id === editingId) || null;
|
||||
}
|
||||
renderChannelTable();
|
||||
resetChannelForm(state.editingChannel);
|
||||
fillSourceChannelOptions();
|
||||
}
|
||||
|
||||
async function onTableClick(event) {
|
||||
async function reloadAll() {
|
||||
await loadChannels();
|
||||
await loadSourceSystems();
|
||||
}
|
||||
|
||||
async function onChannelTableClick(event) {
|
||||
const target = event.target.closest("button[data-action]");
|
||||
if (!target) {
|
||||
return;
|
||||
@@ -304,7 +489,7 @@ async function onTableClick(event) {
|
||||
|
||||
if (action === "edit") {
|
||||
const detail = await request(`/admin/api/channels/${channelId}`);
|
||||
resetForm(detail);
|
||||
resetChannelForm(detail);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -314,15 +499,15 @@ async function onTableClick(event) {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ enabled: !channel.enabled })
|
||||
});
|
||||
showToast(channel.enabled ? `通道已停用,ID: ${channelId}` : `通道已启用,ID: ${channelId}`);
|
||||
await loadChannels();
|
||||
showToast(channel.enabled ? `通道已停用,ID:${channelId}` : `通道已启用,ID:${channelId}`);
|
||||
await reloadAll();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "health") {
|
||||
await request(`/admin/api/channels/${channelId}/health-check`, { method: "POST" });
|
||||
showToast(`健康检查已完成,ID: ${channelId}`);
|
||||
await loadChannels();
|
||||
showToast(`健康检查已完成,ID:${channelId}`);
|
||||
await reloadAll();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -332,7 +517,7 @@ async function onTableClick(event) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmitForm(event) {
|
||||
async function onSubmitChannelForm(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const payload = {
|
||||
@@ -347,22 +532,19 @@ async function onSubmitForm(event) {
|
||||
};
|
||||
|
||||
const channelId = elements.channelId.value;
|
||||
let savedChannel;
|
||||
if (channelId) {
|
||||
savedChannel = await request(`/admin/api/channels/${channelId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
} else {
|
||||
savedChannel = await request("/admin/api/channels", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
const savedChannel = channelId
|
||||
? await request(`/admin/api/channels/${channelId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
: await request("/admin/api/channels", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
showToast(`通道已保存,ID: ${savedChannel.id}`);
|
||||
resetForm(savedChannel);
|
||||
await loadChannels();
|
||||
showToast(`通道已保存,ID:${savedChannel.id}`);
|
||||
state.editingChannel = savedChannel;
|
||||
await reloadAll();
|
||||
}
|
||||
|
||||
function syncTestFormVisibility() {
|
||||
@@ -413,13 +595,19 @@ async function onSubmitTest(event) {
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
elements.refreshButton.addEventListener("click", () => loadChannels().catch(handleError));
|
||||
elements.createButton.addEventListener("click", () => resetForm());
|
||||
elements.resetButton.addEventListener("click", () => resetForm());
|
||||
elements.refreshButton.addEventListener("click", () => reloadAll().catch(handleError));
|
||||
elements.createButton.addEventListener("click", () => resetChannelForm());
|
||||
elements.createSourceButton.addEventListener("click", () => resetSourceSystemForm());
|
||||
elements.resetButton.addEventListener("click", () => resetChannelForm());
|
||||
elements.sourceResetButton.addEventListener("click", () => resetSourceSystemForm());
|
||||
|
||||
elements.sourceSystemForm.addEventListener("submit", (event) => onSourceSystemSubmit(event).catch(handleError));
|
||||
elements.sourceSystemTableBody.addEventListener("click", (event) => onSourceSystemTableClick(event).catch(handleError));
|
||||
|
||||
elements.channelType.addEventListener("change", fillProviderOptions);
|
||||
elements.providerCode.addEventListener("change", renderDynamicFields);
|
||||
elements.channelForm.addEventListener("submit", (event) => onSubmitForm(event).catch(handleError));
|
||||
elements.channelTableBody.addEventListener("click", (event) => onTableClick(event).catch(handleError));
|
||||
elements.channelForm.addEventListener("submit", (event) => onSubmitChannelForm(event).catch(handleError));
|
||||
elements.channelTableBody.addEventListener("click", (event) => onChannelTableClick(event).catch(handleError));
|
||||
elements.testChannelId.addEventListener("change", syncTestFormVisibility);
|
||||
elements.testForm.addEventListener("submit", (event) => onSubmitTest(event).catch(handleError));
|
||||
}
|
||||
@@ -431,8 +619,9 @@ function handleError(error) {
|
||||
|
||||
async function bootstrap() {
|
||||
bindEvents();
|
||||
resetForm();
|
||||
await loadChannels();
|
||||
resetChannelForm();
|
||||
resetSourceSystemForm();
|
||||
await reloadAll();
|
||||
}
|
||||
|
||||
bootstrap().catch(handleError);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>MessageHub 通道管理</title>
|
||||
<title>MessageHub 通道与来源系统管理</title>
|
||||
<link rel="stylesheet" href="./styles.css">
|
||||
</head>
|
||||
<body>
|
||||
@@ -11,127 +11,205 @@
|
||||
<header class="hero">
|
||||
<div>
|
||||
<p class="eyebrow">MessageHub Admin</p>
|
||||
<h1>短信 / 邮件通道管理</h1>
|
||||
<p class="subtitle">在这里维护数据库通道配置、执行健康检查,并直接发送测试消息。保存后会生成通道 ID,外围系统可在消息体中传入 `channelId` 指定通道。</p>
|
||||
<h1>来源系统与消息通道管理</h1>
|
||||
<p class="subtitle">
|
||||
外围系统发送到 MQ 时必须携带 <code>sourceSystem</code>。如果消息里不传 <code>channelId</code>,
|
||||
MessageHub 会优先走该来源系统配置的默认通道;若该系统未配置,再回退到全局默认通道。
|
||||
</p>
|
||||
</div>
|
||||
<div class="hero-actions">
|
||||
<button id="refreshButton" class="ghost-button">刷新列表</button>
|
||||
<button id="refreshButton" class="ghost-button">刷新数据</button>
|
||||
<button id="createSourceButton" class="ghost-button">新增来源系统</button>
|
||||
<button id="createButton" class="primary-button">新增通道</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="content-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>通道列表</h2>
|
||||
<p>支持启停、切换默认通道、执行健康检查,并直接查看每条通道对应的通道 ID。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="channelEmptyState" class="empty-state" hidden>暂无通道数据。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>类型</th>
|
||||
<th>提供方</th>
|
||||
<th>状态</th>
|
||||
<th>健康检查</th>
|
||||
<th>最近检测</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="channelTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="side-stack">
|
||||
<main class="section-stack">
|
||||
<section class="section-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="formTitle">新增通道</h2>
|
||||
<p id="formSubtitle">保存后会生成通道 ID,外围系统可在消息体中通过 channelId 指定该通道。</p>
|
||||
<h2>来源系统列表</h2>
|
||||
<p>这里维护允许接入 MessageHub 的系统白名单,以及各系统在短信/邮件上的默认通道。</p>
|
||||
</div>
|
||||
<button id="resetButton" class="ghost-button small">重置</button>
|
||||
</div>
|
||||
<form id="channelForm" class="form-grid">
|
||||
<input type="hidden" id="channelId">
|
||||
<div class="hint-box">
|
||||
未登记或已停用的 <code>sourceSystem</code> 请求会在消费阶段被直接拒绝,并写入失败日志。
|
||||
</div>
|
||||
<div id="sourceSystemEmptyState" class="empty-state" hidden>暂无来源系统,请先新增。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>系统</th>
|
||||
<th>状态</th>
|
||||
<th>默认短信通道</th>
|
||||
<th>默认邮件通道</th>
|
||||
<th>最后更新</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="sourceSystemTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="sourceFormTitle">新增来源系统</h2>
|
||||
<p id="sourceFormSubtitle">系统标识会统一转成小写保存。不指定默认通道时,会回退到全局默认通道。</p>
|
||||
</div>
|
||||
<button id="sourceResetButton" class="ghost-button small">重置</button>
|
||||
</div>
|
||||
<form id="sourceSystemForm" class="form-grid">
|
||||
<input type="hidden" id="sourceSystemId">
|
||||
<label>
|
||||
<span>通道类型</span>
|
||||
<select id="channelType" required>
|
||||
<option value="SMS">短信</option>
|
||||
<option value="EMAIL">邮件</option>
|
||||
</select>
|
||||
<span>系统标识</span>
|
||||
<input id="sourceSystemCode" type="text" maxlength="64" required placeholder="例如:yuminail">
|
||||
</label>
|
||||
<label>
|
||||
<span>提供方</span>
|
||||
<select id="providerCode" required></select>
|
||||
<span>系统名称</span>
|
||||
<input id="sourceSystemName" type="text" maxlength="100" required placeholder="例如:玉米甲主站">
|
||||
</label>
|
||||
<label>
|
||||
<span>通道名称</span>
|
||||
<input id="channelName" type="text" maxlength="100" required placeholder="例如:生产验证码短信通道">
|
||||
<span>默认短信通道</span>
|
||||
<select id="defaultSmsChannelId"></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>默认邮件通道</span>
|
||||
<select id="defaultEmailChannelId"></select>
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>备注</span>
|
||||
<input id="remark" type="text" maxlength="255" placeholder="可选">
|
||||
<input id="sourceSystemRemark" type="text" maxlength="255" placeholder="可选,用于说明该来源系统的用途">
|
||||
</label>
|
||||
<div class="inline-checks">
|
||||
<label class="checkbox">
|
||||
<input id="enabled" type="checkbox" checked>
|
||||
<input id="sourceSystemEnabled" type="checkbox" checked>
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input id="isDefault" type="checkbox">
|
||||
<span>设为默认</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="dynamicFields" class="dynamic-fields"></div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">保存通道</button>
|
||||
<button type="submit" class="primary-button">保存来源系统</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="section-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>测试发送</h2>
|
||||
<p>支持按通道 ID 定向测试短信或邮件。业务系统正常发送时,不传 channelId 就会自动走默认通道。</p>
|
||||
<h2>通道列表</h2>
|
||||
<p>支持新增、编辑、启停、健康检查。保存后会生成通道 ID,外围系统也可以显式传入 <code>channelId</code> 指定通道。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="testForm" class="form-grid">
|
||||
<label>
|
||||
<span>选择通道</span>
|
||||
<select id="testChannelId" required></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>接收目标</span>
|
||||
<input id="testReceiver" type="text" required placeholder="手机号或邮箱">
|
||||
</label>
|
||||
<label class="test-only-email">
|
||||
<span>邮件主题</span>
|
||||
<input id="testSubject" type="text" placeholder="留空则使用默认主题">
|
||||
</label>
|
||||
<label class="test-only-sms">
|
||||
<span>模板编码</span>
|
||||
<input id="testTemplateCode" type="text" placeholder="Spug 短信测试时必填">
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>消息内容 / 说明</span>
|
||||
<textarea id="testContent" rows="4" placeholder="短信 Mock 会直接记录这里的内容;邮件会作为正文"></textarea>
|
||||
</label>
|
||||
<label class="full-width test-only-sms">
|
||||
<span>模板参数 JSON</span>
|
||||
<textarea id="testTemplateParams" rows="4" placeholder='例如:{"code":"123456","minutes":"5"}'></textarea>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">发送测试消息</button>
|
||||
</div>
|
||||
</form>
|
||||
<div id="channelEmptyState" class="empty-state" hidden>暂无通道数据。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>类型</th>
|
||||
<th>提供商</th>
|
||||
<th>状态</th>
|
||||
<th>健康检查</th>
|
||||
<th>最后检测</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="channelTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
<aside class="side-stack">
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="formTitle">新增通道</h2>
|
||||
<p id="formSubtitle">保存后会生成通道 ID。来源系统可配置默认通道,外围系统也可以在消息体中显式传入该 ID。</p>
|
||||
</div>
|
||||
<button id="resetButton" class="ghost-button small">重置</button>
|
||||
</div>
|
||||
<form id="channelForm" class="form-grid">
|
||||
<input type="hidden" id="channelId">
|
||||
<label>
|
||||
<span>通道类型</span>
|
||||
<select id="channelType" required>
|
||||
<option value="SMS">短信</option>
|
||||
<option value="EMAIL">邮件</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>提供商</span>
|
||||
<select id="providerCode" required></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>通道名称</span>
|
||||
<input id="channelName" type="text" maxlength="100" required placeholder="例如:生产验证码短信通道">
|
||||
</label>
|
||||
<label>
|
||||
<span>备注</span>
|
||||
<input id="remark" type="text" maxlength="255" placeholder="可选">
|
||||
</label>
|
||||
<div class="inline-checks">
|
||||
<label class="checkbox">
|
||||
<input id="enabled" type="checkbox" checked>
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input id="isDefault" type="checkbox">
|
||||
<span>设为全局默认</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="dynamicFields" class="dynamic-fields"></div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">保存通道</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>测试发送</h2>
|
||||
<p>这里会直接按所选通道发送测试消息,用于验证账号、密钥和通道连通性。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="testForm" class="form-grid">
|
||||
<label>
|
||||
<span>测试通道</span>
|
||||
<select id="testChannelId" required></select>
|
||||
</label>
|
||||
<label>
|
||||
<span>接收目标</span>
|
||||
<input id="testReceiver" type="text" required placeholder="手机号或邮箱">
|
||||
</label>
|
||||
<label class="test-only-email">
|
||||
<span>邮件主题</span>
|
||||
<input id="testSubject" type="text" placeholder="留空则使用默认主题">
|
||||
</label>
|
||||
<label class="test-only-sms">
|
||||
<span>模板编码</span>
|
||||
<input id="testTemplateCode" type="text" placeholder="Spug 短信测试时必填">
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>消息内容 / 说明</span>
|
||||
<textarea id="testContent" rows="4" placeholder="短信 Mock 会直接记录这里的内容;邮件会作为正文"></textarea>
|
||||
</label>
|
||||
<label class="full-width test-only-sms">
|
||||
<span>模板参数 JSON</span>
|
||||
<textarea id="testTemplateParams" rows="4" placeholder='例如:{"code":"123456","minutes":"5"}'></textarea>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">发送测试消息</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</aside>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -29,8 +29,15 @@ body {
|
||||
linear-gradient(180deg, #efe7d7 0%, #f7f2e7 54%, #f3ede2 100%);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 2px 6px;
|
||||
border-radius: 8px;
|
||||
background: rgba(114, 83, 38, 0.08);
|
||||
font-family: "Consolas", "Courier New", monospace;
|
||||
}
|
||||
|
||||
.page-shell {
|
||||
width: min(1440px, calc(100vw - 32px));
|
||||
width: min(1480px, calc(100vw - 32px));
|
||||
margin: 0 auto;
|
||||
padding: 24px 0 40px;
|
||||
}
|
||||
@@ -62,9 +69,9 @@ body {
|
||||
|
||||
.subtitle {
|
||||
margin: 10px 0 0;
|
||||
max-width: 760px;
|
||||
max-width: 820px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
@@ -73,11 +80,16 @@ body {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.content-grid {
|
||||
.section-stack {
|
||||
display: grid;
|
||||
gap: 24px;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.section-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.35fr 0.95fr;
|
||||
gap: 24px;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.side-stack {
|
||||
@@ -112,6 +124,16 @@ body {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.hint-box {
|
||||
margin-bottom: 16px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 18px;
|
||||
border: 1px dashed rgba(184, 91, 47, 0.28);
|
||||
background: rgba(255, 247, 237, 0.9);
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
@@ -298,8 +320,8 @@ textarea {
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.content-grid {
|
||||
@media (max-width: 1180px) {
|
||||
.section-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# MessageHub 来源系统白名单与系统默认通道变更记录
|
||||
|
||||
## 日期
|
||||
|
||||
2026-03-23
|
||||
|
||||
## 本轮完成内容
|
||||
|
||||
### 1. 来源系统白名单
|
||||
|
||||
- 新增来源系统管理后端接口
|
||||
- 新增来源系统后台管理页面
|
||||
- 所有 MQ 消费消息都要求 `sourceSystem` 已登记且启用
|
||||
- 未登记来源系统的请求会被拒绝并写入失败日志
|
||||
|
||||
### 2. 来源系统默认通道
|
||||
|
||||
- 后台可按来源系统分别配置默认短信通道和默认邮件通道
|
||||
- 消息不传 `channelId` 时:
|
||||
- 先取来源系统默认通道
|
||||
- 没配时回退到全局默认通道
|
||||
- 消息传了 `channelId` 时,仍以显式指定为准
|
||||
|
||||
### 3. 消费链路修正
|
||||
|
||||
- 短信监听器改为走统一消息校验与日志落库入口
|
||||
- 邮件监听器补齐失败日志回写
|
||||
- 成功发送后会将推送日志状态更新为成功
|
||||
- 邮件正文模板渲染改为读取模板内容,而不是误用模板编码
|
||||
|
||||
### 4. 后台页面调整
|
||||
|
||||
- 管理页合并成两块:
|
||||
- 来源系统管理
|
||||
- 通道管理与测试发送
|
||||
- 来源系统表单可直接选择默认短信/邮件通道
|
||||
- 通道列表继续展示通道 ID,便于外围系统显式指定
|
||||
|
||||
### 5. 中文提示与异常说明
|
||||
|
||||
- 新增接口和页面提示统一改为中文
|
||||
- 缺少来源系统相关表时,接口会提示先执行:
|
||||
- `2026-03-23_message_source_system_patch.sql`
|
||||
|
||||
## 本轮涉及 SQL
|
||||
|
||||
需要手工执行:
|
||||
|
||||
1. [2026-03-23_message_channel_management_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_channel_management_patch.sql)
|
||||
2. [2026-03-23_message_source_system_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_source_system_patch.sql)
|
||||
|
||||
## 外围系统调用口径
|
||||
|
||||
外围系统仍然发送到原有队列:
|
||||
|
||||
- `smsQueue`
|
||||
- `emailQueue`
|
||||
|
||||
消息体要求:
|
||||
|
||||
- 必传 `sourceSystem`
|
||||
- 可选传 `channelId`
|
||||
|
||||
分发顺序:
|
||||
|
||||
1. 显式 `channelId`
|
||||
2. 该 `sourceSystem` 对应类型的默认通道
|
||||
3. 该类型的全局默认通道
|
||||
|
||||
## 主要文件
|
||||
|
||||
- [MessageChannelService.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/service/channel/MessageChannelService.java)
|
||||
- [MessageSourceSystemService.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/service/source/MessageSourceSystemService.java)
|
||||
- [SmsQueueListener.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java)
|
||||
- [EmailQueueListener.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/listener/EmailQueueListener.java)
|
||||
- [index.html](/E:/code/xiaowang/MessageHub/src/main/resources/static/messagehub-admin/index.html)
|
||||
- [app.js](/E:/code/xiaowang/MessageHub/src/main/resources/static/messagehub-admin/app.js)
|
||||
- [2026-03-23_message_source_system_patch.sql](/E:/code/xiaowang/MessageHub/src/main/resources/sql/2026-03-23_message_source_system_patch.sql)
|
||||
|
||||
## 备注
|
||||
|
||||
- 本轮没有自动执行数据库迁移
|
||||
- 其余未归属本任务的工作区改动未处理
|
||||
Reference in New Issue
Block a user