diff --git a/db.sql b/db.sql
index 385d306..0ab1ce1 100644
--- a/db.sql
+++ b/db.sql
@@ -62,6 +62,8 @@ DROP TABLE IF EXISTS `t_customer_account_flow`;
DROP TABLE IF EXISTS `t_system_batch_email_record`;
DROP TABLE IF EXISTS `t_system_batch_email_account`;
DROP TABLE IF EXISTS `t_system_batch_email_template`;
+DROP TABLE IF EXISTS `t_order_notify_log`;
+DROP TABLE IF EXISTS `t_order_notify_email_log`;
DROP TABLE IF EXISTS `t_wechat_notify_log`;
DROP TABLE IF EXISTS `t_customer_wechat_notify_pref`;
DROP TABLE IF EXISTS `t_wechat_notify_template`;
@@ -1215,7 +1217,11 @@ CREATE TABLE `t_wechat_notify_template` (
`TemplateId` VARCHAR(128) NULL COMMENT '微信公众号模板 ID',
`UrlTemplate` VARCHAR(512) NULL COMMENT '跳转 URL 模板,支持 {baseUrl}/{orderId}/{serviceNo}',
`FieldMappingJson` TEXT NULL COMMENT '字段映射 JSON:[{key,placeholder,color?}]',
- `IsEnabled` TINYINT NOT NULL DEFAULT 0 COMMENT '是否启用:0-否,1-是',
+ `IsEnabled` TINYINT NOT NULL DEFAULT 0 COMMENT '是否启用微信推送:0-否,1-是',
+ `EmailEnabled` TINYINT NOT NULL DEFAULT 0 COMMENT '是否启用邮件通知:0-否,1-是',
+ `EmailTemplateName` VARCHAR(128) NULL COMMENT 'batch-email 模板名称',
+ `EmailTemplateOwnerUserId` INT NULL COMMENT 'batch-email 模板所属用户',
+ `EmailSmtpOwnerUserId` INT NULL COMMENT '发信 SMTP 所属用户;0 表示系统发信账号',
`Remark` VARCHAR(512) NULL COMMENT '备注',
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
@@ -1226,13 +1232,14 @@ CREATE TABLE `t_wechat_notify_template` (
PRIMARY KEY (`Id`),
KEY `ix_wechat_notify_tpl_event` (`EventCode`),
KEY `ix_wechat_notify_tpl_enabled` (`IsEnabled`, `Id`)
-) COMMENT='微信订单通知模板配置';
+) COMMENT='订单通知模板配置(微信 + 邮件)';
CREATE TABLE `t_customer_wechat_notify_pref` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
`CustomerId` INT NOT NULL COMMENT '客户 Id',
`EventCode` VARCHAR(32) NOT NULL COMMENT '事件码',
- `IsSubscribed` TINYINT NOT NULL DEFAULT 0 COMMENT '是否订阅:0-否,1-是',
+ `IsSubscribed` TINYINT NOT NULL DEFAULT 0 COMMENT '是否订阅微信:0-否,1-是',
+ `IsEmailSubscribed` TINYINT NOT NULL DEFAULT 0 COMMENT '是否订阅邮件:0-否,1-是',
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
@@ -1242,19 +1249,22 @@ CREATE TABLE `t_customer_wechat_notify_pref` (
PRIMARY KEY (`Id`),
KEY `ix_cus_wechat_notify_pref_cus` (`CustomerId`, `EventCode`),
KEY `ix_cus_wechat_notify_pref_event` (`EventCode`, `IsSubscribed`)
-) COMMENT='客户微信订单通知订阅偏好';
+) COMMENT='客户订单通知订阅偏好(微信 / 邮件)';
-CREATE TABLE `t_wechat_notify_log` (
+CREATE TABLE `t_order_notify_log` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
`CustomerId` INT NOT NULL DEFAULT 0 COMMENT '客户 Id',
`OrderId` INT NOT NULL DEFAULT 0 COMMENT '订单 Id',
+ `Channel` VARCHAR(16) NOT NULL COMMENT 'wechat/email',
`EventCode` VARCHAR(32) NOT NULL COMMENT '事件码',
- `OpenId` VARCHAR(64) NULL COMMENT '接收 openid',
- `TemplateId` VARCHAR(128) NULL COMMENT '模板 Id',
+ `Recipient` VARCHAR(256) NULL COMMENT 'OpenId 或收件邮箱',
+ `TemplateRef` VARCHAR(128) NULL COMMENT '微信 TemplateId 或邮件模板名',
+ `Subject` VARCHAR(512) NULL COMMENT '邮件主题',
`Status` VARCHAR(16) NOT NULL DEFAULT 'skipped' COMMENT 'sent/failed/skipped',
- `WxMsgId` VARCHAR(64) NULL COMMENT '微信 msgid',
- `ErrCode` INT NULL COMMENT '微信/业务错误码',
+ `ProviderMsgId` VARCHAR(64) NULL COMMENT '通道回执 msgid',
+ `ErrCode` INT NULL COMMENT '错误码',
`ErrMsg` VARCHAR(512) NULL COMMENT '错误或跳过原因',
+ `SmtpUsername` VARCHAR(256) NULL COMMENT '发件 SMTP',
`PayloadJson` TEXT NULL COMMENT '发送快照',
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
@@ -1263,10 +1273,10 @@ CREATE TABLE `t_wechat_notify_log` (
`UpdateUserId` INT NULL COMMENT '更新人',
`UpdateTime` DATETIME NULL COMMENT '更新时间',
PRIMARY KEY (`Id`),
- KEY `ix_wechat_notify_log_order_event` (`OrderId`, `EventCode`, `CreateTime`),
- KEY `ix_wechat_notify_log_cus_time` (`CustomerId`, `CreateTime`),
- KEY `ix_wechat_notify_log_status` (`Status`, `Id`)
-) COMMENT='微信订单通知发送日志';
+ KEY `ix_order_notify_log_order_ch_event` (`OrderId`, `Channel`, `EventCode`, `CreateTime`),
+ KEY `ix_order_notify_log_cus_time` (`CustomerId`, `CreateTime`),
+ KEY `ix_order_notify_log_status` (`Status`, `Id`)
+) COMMENT='订单通知发送日志(微信/邮件)';
CREATE TABLE `t_system_batch_email_template` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
diff --git a/sql/migrate_order_notify_all_20261121.sql b/sql/migrate_order_notify_all_20261121.sql
new file mode 100644
index 0000000..6baf558
--- /dev/null
+++ b/sql/migrate_order_notify_all_20261121.sql
@@ -0,0 +1,175 @@
+-- =============================================================================
+-- 订单通知(微信 + 邮件)一次升级脚本
+-- 前提:已有 t_wechat_notify_template / t_customer_wechat_notify_pref / t_wechat_notify_log
+-- 可重复执行
+-- =============================================================================
+
+SET NAMES utf8mb4;
+SET @db := DATABASE();
+
+-- ---------------------------------------------------------------------------
+-- 1) 模板表:邮件通道字段
+-- ---------------------------------------------------------------------------
+SET @sql := (
+ SELECT IF(
+ EXISTS(
+ SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = @db
+ AND TABLE_NAME = 't_wechat_notify_template'
+ AND COLUMN_NAME = 'EmailEnabled'
+ ),
+ 'SELECT ''EmailEnabled already exists'' AS info',
+ 'ALTER TABLE `t_wechat_notify_template`
+ ADD COLUMN `EmailEnabled` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否启用邮件通知:0-否,1-是'' AFTER `IsEnabled`,
+ ADD COLUMN `EmailTemplateName` VARCHAR(128) NULL COMMENT ''batch-email 模板名称'' AFTER `EmailEnabled`,
+ ADD COLUMN `EmailSmtpOwnerUserId` INT NULL COMMENT ''发信 SMTP 所属用户;0 表示系统发信账号'' AFTER `EmailTemplateName`'
+ )
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+-- ---------------------------------------------------------------------------
+-- 2) 模板表:模板归属用户(与 SMTP 解耦)
+-- ---------------------------------------------------------------------------
+SET @sql := (
+ SELECT IF(
+ EXISTS(
+ SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = @db
+ AND TABLE_NAME = 't_wechat_notify_template'
+ AND COLUMN_NAME = 'EmailTemplateOwnerUserId'
+ ),
+ 'SELECT ''EmailTemplateOwnerUserId already exists'' AS info',
+ 'ALTER TABLE `t_wechat_notify_template`
+ ADD COLUMN `EmailTemplateOwnerUserId` INT NULL COMMENT ''batch-email 模板所属用户'' AFTER `EmailTemplateName`'
+ )
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+UPDATE `t_wechat_notify_template`
+SET `EmailTemplateOwnerUserId` = `EmailSmtpOwnerUserId`
+WHERE `EmailTemplateOwnerUserId` IS NULL
+ AND `EmailSmtpOwnerUserId` IS NOT NULL
+ AND `EmailSmtpOwnerUserId` > 0;
+
+-- ---------------------------------------------------------------------------
+-- 3) 客户偏好:邮件订阅
+-- ---------------------------------------------------------------------------
+SET @sql := (
+ SELECT IF(
+ EXISTS(
+ SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = @db
+ AND TABLE_NAME = 't_customer_wechat_notify_pref'
+ AND COLUMN_NAME = 'IsEmailSubscribed'
+ ),
+ 'SELECT ''IsEmailSubscribed already exists'' AS info',
+ 'ALTER TABLE `t_customer_wechat_notify_pref`
+ ADD COLUMN `IsEmailSubscribed` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否订阅邮件:0-否,1-是'' AFTER `IsSubscribed`'
+ )
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+-- ---------------------------------------------------------------------------
+-- 4) 统一通知日志表 t_order_notify_log(微信 / 邮件)
+-- ---------------------------------------------------------------------------
+SET @sql := (
+ SELECT IF(
+ EXISTS(
+ SELECT 1 FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_order_notify_log'
+ ),
+ 'SELECT ''t_order_notify_log already exists'' AS info',
+ 'CREATE TABLE `t_order_notify_log` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
+ `CustomerId` INT NOT NULL DEFAULT 0 COMMENT ''客户 Id'',
+ `OrderId` INT NOT NULL DEFAULT 0 COMMENT ''订单 Id'',
+ `Channel` VARCHAR(16) NOT NULL COMMENT ''wechat/email'',
+ `EventCode` VARCHAR(32) NOT NULL COMMENT ''事件码'',
+ `Recipient` VARCHAR(256) NULL COMMENT ''OpenId 或收件邮箱'',
+ `TemplateRef` VARCHAR(128) NULL COMMENT ''微信 TemplateId 或邮件模板名'',
+ `Subject` VARCHAR(512) NULL COMMENT ''邮件主题'',
+ `Status` VARCHAR(16) NOT NULL DEFAULT ''skipped'' COMMENT ''sent/failed/skipped'',
+ `ProviderMsgId` VARCHAR(64) NULL COMMENT ''通道回执 msgid'',
+ `ErrCode` INT NULL COMMENT ''错误码'',
+ `ErrMsg` VARCHAR(512) NULL COMMENT ''错误或跳过原因'',
+ `SmtpUsername` VARCHAR(256) NULL COMMENT ''发件 SMTP'',
+ `PayloadJson` TEXT NULL COMMENT ''发送快照'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
+ `UpdateUserId` INT NULL COMMENT ''更新人'',
+ `UpdateTime` DATETIME NULL COMMENT ''更新时间'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_order_notify_log_order_ch_event` (`OrderId`, `Channel`, `EventCode`, `CreateTime`),
+ KEY `ix_order_notify_log_cus_time` (`CustomerId`, `CreateTime`),
+ KEY `ix_order_notify_log_status` (`Status`, `Id`)
+ ) COMMENT=''订单通知发送日志(微信/邮件)'''
+ )
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+-- ---------------------------------------------------------------------------
+-- 5) 若线上已有旧微信日志,灌入统一表(无则跳过;可重复)
+-- ---------------------------------------------------------------------------
+SET @has_wx := (
+ SELECT COUNT(*) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_wechat_notify_log'
+);
+SET @sql := IF(
+ @has_wx > 0,
+ 'INSERT INTO `t_order_notify_log` (
+ `CustomerId`, `OrderId`, `Channel`, `EventCode`, `Recipient`, `TemplateRef`, `Subject`,
+ `Status`, `ProviderMsgId`, `ErrCode`, `ErrMsg`, `SmtpUsername`, `PayloadJson`,
+ `IsDeleted`, `ConcurrencyStamp`, `CreateUserId`, `CreateTime`, `UpdateUserId`, `UpdateTime`
+ )
+ SELECT
+ w.`CustomerId`, w.`OrderId`, ''wechat'', w.`EventCode`, w.`OpenId`, w.`TemplateId`, NULL,
+ w.`Status`, w.`WxMsgId`, w.`ErrCode`, w.`ErrMsg`, NULL, w.`PayloadJson`,
+ w.`IsDeleted`, UUID(), w.`CreateUserId`, w.`CreateTime`, w.`UpdateUserId`, w.`UpdateTime`
+ FROM `t_wechat_notify_log` w
+ WHERE NOT EXISTS (
+ SELECT 1 FROM `t_order_notify_log` n
+ WHERE n.`Channel` = ''wechat''
+ AND n.`OrderId` = w.`OrderId`
+ AND n.`EventCode` = w.`EventCode`
+ AND n.`CreateTime` = w.`CreateTime`
+ AND IFNULL(n.`Status`, '''') = IFNULL(w.`Status`, '''')
+ AND IFNULL(n.`Recipient`, '''') = IFNULL(w.`OpenId`, '''')
+ )',
+ 'SELECT ''skip wechat migrate'' AS info'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+-- 若曾建过邮件专用日志表,一并灌入(多数环境无此表)
+SET @has_mail := (
+ SELECT COUNT(*) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_order_notify_email_log'
+);
+SET @sql := IF(
+ @has_mail > 0,
+ 'INSERT INTO `t_order_notify_log` (
+ `CustomerId`, `OrderId`, `Channel`, `EventCode`, `Recipient`, `TemplateRef`, `Subject`,
+ `Status`, `ProviderMsgId`, `ErrCode`, `ErrMsg`, `SmtpUsername`, `PayloadJson`,
+ `IsDeleted`, `ConcurrencyStamp`, `CreateUserId`, `CreateTime`, `UpdateUserId`, `UpdateTime`
+ )
+ SELECT
+ e.`CustomerId`, e.`OrderId`, ''email'', e.`EventCode`, e.`ToEmail`, e.`TemplateName`, e.`Subject`,
+ e.`Status`, NULL, NULL, e.`ErrMsg`, e.`SmtpUsername`, e.`PayloadJson`,
+ e.`IsDeleted`, UUID(), e.`CreateUserId`, e.`CreateTime`, e.`UpdateUserId`, e.`UpdateTime`
+ FROM `t_order_notify_email_log` e
+ WHERE NOT EXISTS (
+ SELECT 1 FROM `t_order_notify_log` n
+ WHERE n.`Channel` = ''email''
+ AND n.`OrderId` = e.`OrderId`
+ AND n.`EventCode` = e.`EventCode`
+ AND n.`CreateTime` = e.`CreateTime`
+ AND IFNULL(n.`Status`, '''') = IFNULL(e.`Status`, '''')
+ AND IFNULL(n.`Recipient`, '''') = IFNULL(e.`ToEmail`, '''')
+ )',
+ 'SELECT ''skip email migrate'' AS info'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+-- 旧表 t_wechat_notify_log / t_order_notify_email_log 可保留只读;确认无流量后再手工 DROP
+SELECT 'migrate_order_notify_all_20261121 done' AS info;
diff --git a/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs b/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs
index d1f8723..5aa01fd 100644
--- a/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs
+++ b/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs
@@ -1,11 +1,14 @@
namespace Oms.Application.Dtos.Customers;
-/// 客户微信通知前置状态 + 订阅项。
+/// 客户订单通知前置状态 + 订阅项(微信 / 邮件)。
public class CustomerWechatNotifyStatusOutput
{
/// 是否已绑定微信 OpenId。
public bool HasOpenId { get; set; }
+ /// 是否已配置客户邮箱。
+ public bool HasEmail { get; set; }
+
/// 是否已配置公众号关注跳转(仅提示用)。
public bool HasFollowUrl { get; set; }
@@ -20,11 +23,17 @@ public class CustomerWechatNotifyPrefItemOutput
public string EventName { get; set; } = string.Empty;
- /// 运营是否已启用该事件模板。
+ /// 运营是否已启用微信模板。
public bool OpsEnabled { get; set; }
- /// 客户是否订阅。
+ /// 运营是否已启用邮件。
+ public bool OpsEmailEnabled { get; set; }
+
+ /// 客户是否订阅微信。
public bool IsSubscribed { get; set; }
+
+ /// 客户是否订阅邮件。
+ public bool IsEmailSubscribed { get; set; }
}
/// 保存客户订阅。
@@ -38,4 +47,6 @@ public class SaveCustomerWechatNotifyPrefItemInput
public string EventCode { get; set; } = string.Empty;
public bool IsSubscribed { get; set; }
+
+ public bool IsEmailSubscribed { get; set; }
}
diff --git a/src/Oms.Application/Dtos/Orders/OrderNotifyLogDtos.cs b/src/Oms.Application/Dtos/Orders/OrderNotifyLogDtos.cs
new file mode 100644
index 0000000..b71e433
--- /dev/null
+++ b/src/Oms.Application/Dtos/Orders/OrderNotifyLogDtos.cs
@@ -0,0 +1,49 @@
+namespace Oms.Application.Dtos.Orders;
+
+/// 订单通知日志条目(微信 / 邮件)。
+public class OrderNotifyLogOutput
+{
+ public int Id { get; set; }
+
+ public int OrderId { get; set; }
+
+ /// wechat / email。
+ public string Channel { get; set; } = string.Empty;
+
+ /// 微信 / 邮件。
+ public string ChannelName { get; set; } = string.Empty;
+
+ public string EventCode { get; set; } = string.Empty;
+
+ public string EventName { get; set; } = string.Empty;
+
+ /// OpenId 或邮箱。
+ public string? Recipient { get; set; }
+
+ public string? TemplateRef { get; set; }
+
+ public string? Subject { get; set; }
+
+ /// sent / failed / skipped。
+ public string Status { get; set; } = string.Empty;
+
+ public string? ProviderMsgId { get; set; }
+
+ public int? ErrCode { get; set; }
+
+ public string? ErrMsg { get; set; }
+
+ public string? SmtpUsername { get; set; }
+
+ /// 列表「内容」摘要。
+ public string Summary { get; set; } = string.Empty;
+
+ public string? PayloadJson { get; set; }
+
+ public DateTime CreateTime { get; set; }
+}
+
+public class OrderNotifyLogListOutput
+{
+ public List Items { get; set; } = [];
+}
diff --git a/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs
index c78fe82..774c7b7 100644
--- a/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs
+++ b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs
@@ -1,6 +1,6 @@
namespace Oms.Application.Dtos.System;
-/// 微信订单通知模板配置输出。
+/// 订单通知模板配置输出(微信 + 邮件)。
public class WechatOrderNotifyTemplateOutput
{
public int Id { get; set; }
@@ -20,14 +20,29 @@ public class WechatOrderNotifyTemplateOutput
/// 字段映射 JSON。
public string? FieldMappingJson { get; set; }
- /// 是否启用。
+ /// 是否启用微信推送。
public bool IsEnabled { get; set; }
+ /// 是否启用邮件通知。
+ public bool EmailEnabled { get; set; }
+
+ /// batch-email 模板名称。
+ public string? EmailTemplateName { get; set; }
+
+ /// batch-email 模板所属用户。
+ public int? EmailTemplateOwnerUserId { get; set; }
+
+ /// 发信 SMTP 所属用户;0 表示系统发信账号。
+ public int? EmailSmtpOwnerUserId { get; set; }
+
+ /// 是否使用系统发信 SMTP。
+ public bool EmailUseSystemSmtp { get; set; }
+
/// 备注。
public string? Remark { get; set; }
}
-/// 保存微信订单通知模板。
+/// 保存订单通知模板。
public class SaveWechatOrderNotifyTemplateInput
{
/// 事件码。
@@ -42,13 +57,35 @@ public class SaveWechatOrderNotifyTemplateInput
/// 字段映射 JSON。
public string? FieldMappingJson { get; set; }
- /// 是否启用。
+ /// 是否启用微信推送。
public bool IsEnabled { get; set; }
+ /// 是否启用邮件通知。
+ public bool EmailEnabled { get; set; }
+
+ /// batch-email 模板名称(启用邮件时必填)。
+ public string? EmailTemplateName { get; set; }
+
+ /// 是否使用系统发信 SMTP(OwnerUserId=0)。
+ public bool EmailUseSystemSmtp { get; set; }
+
/// 备注。
public string? Remark { get; set; }
}
+/// 系统发信 SMTP 状态。
+public class OrderNotifySystemSmtpStatusOutput
+{
+ /// 是否已配置系统 SMTP(OwnerUserId=0)。
+ public bool Configured { get; set; }
+
+ /// 发件账号(脱敏场景仍返回用户名)。
+ public string? SmtpUsername { get; set; }
+
+ /// 发件人显示名。
+ public string? FromName { get; set; }
+}
+
/// 试发入参。
public class TrialWechatOrderNotifyInput
{
@@ -62,10 +99,10 @@ public class TrialWechatOrderNotifyInput
public string? ServiceNo { get; set; }
}
-/// 试发结果(含请求/响应明细,供运营排查)。
+/// 试发结果(含微信/邮件请求响应明细)。
public class TrialWechatOrderNotifyResultOutput
{
- /// 是否最终发送成功。
+ /// 是否最终发送成功(微信成功即 true;邮件结果见 Email)。
public bool Success { get; set; }
/// 是否跳过发送(未启用/未绑 OpenId 等)。
@@ -112,4 +149,38 @@ public class TrialWechatOrderNotifyResultOutput
/// 微信 errcode。
public int? ErrCode { get; set; }
+
+ /// 邮件通道试发结果。
+ public TrialOrderNotifyEmailResultOutput? Email { get; set; }
+}
+
+/// 订单通知邮件试发明细。
+public class TrialOrderNotifyEmailResultOutput
+{
+ /// 是否发送成功。
+ public bool Success { get; set; }
+
+ /// 是否跳过。
+ public bool Skipped { get; set; }
+
+ /// 状态:sent / failed / skipped。
+ public string Status { get; set; } = "skipped";
+
+ /// 说明。
+ public string? Message { get; set; }
+
+ /// 收件邮箱。
+ public string? ToEmail { get; set; }
+
+ /// 模板名称。
+ public string? TemplateName { get; set; }
+
+ /// 替换后主题。
+ public string? Subject { get; set; }
+
+ /// 替换后正文。
+ public string? Body { get; set; }
+
+ /// 发件 SMTP 账号。
+ public string? SmtpUsername { get; set; }
}
diff --git a/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyEventHandler.cs b/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyEventHandler.cs
new file mode 100644
index 0000000..4bb72f6
--- /dev/null
+++ b/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyEventHandler.cs
@@ -0,0 +1,77 @@
+using Fake.DependencyInjection;
+using Fake.EventBus;
+using Fake.UnitOfWork;
+using Microsoft.Extensions.Logging;
+using Oms.Application.Services.WeChatNotify;
+using Oms.Domain.OrdersAggregate.Repositories;
+
+namespace Oms.Application.Messaging.OrderSideEffects;
+
+/// 消费订单通知异步任务(微信 + 邮件)。
+public sealed class OrderNotifyEventHandler(
+ IOrderRepository orderRepository,
+ WechatOrderNotifyDispatcher notifyDispatcher,
+ IUnitOfWorkManager unitOfWorkManager,
+ ILogger logger)
+ : IEventHandler, ITransientDependency
+{
+ public async Task HandleAsync(
+ OrderNotifyIntegrationEvent @event,
+ CancellationToken cancellationToken)
+ {
+ if (@event.OrderId <= 0 || string.IsNullOrWhiteSpace(@event.EventCode))
+ {
+ logger.LogWarning(
+ "OrderNotify skipped invalid payload OrderId={OrderId} Event={EventCode}",
+ @event.OrderId,
+ @event.EventCode);
+ return;
+ }
+
+ using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Transactional());
+ try
+ {
+ var order = await orderRepository.FirstOrDefaultAsync(
+ x => x.Id == @event.OrderId,
+ cancellationToken);
+ if (order == null)
+ {
+ logger.LogWarning(
+ "OrderNotify order not found OrderId={OrderId} Event={EventCode}",
+ @event.OrderId,
+ @event.EventCode);
+ }
+ else
+ {
+ await notifyDispatcher.NotifyDetailedAsync(
+ order,
+ @event.EventCode,
+ @event.Remark,
+ @event.Force,
+ cancellationToken);
+ }
+
+ await unitOfWork.CompleteAsync(cancellationToken);
+ }
+ catch (OrderNotifyRetryableException ex)
+ {
+ // 不 Complete:外层 Outbox/MQ 可重试
+ logger.LogWarning(
+ ex,
+ "OrderNotify retryable OrderId={OrderId} Event={EventCode}",
+ @event.OrderId,
+ @event.EventCode);
+ throw;
+ }
+ catch (Exception ex)
+ {
+ // 业务跳过 / 不可重试:Ack,避免打满队列
+ logger.LogWarning(
+ ex,
+ "OrderNotify failed(non-retry) OrderId={OrderId} Event={EventCode}",
+ @event.OrderId,
+ @event.EventCode);
+ await unitOfWork.CompleteAsync(cancellationToken);
+ }
+ }
+}
diff --git a/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyIntegrationEvent.cs b/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyIntegrationEvent.cs
new file mode 100644
index 0000000..318c354
--- /dev/null
+++ b/src/Oms.Application/Messaging/OrderSideEffects/OrderNotifyIntegrationEvent.cs
@@ -0,0 +1,21 @@
+using Fake.EventBus.Distributed;
+
+namespace Oms.Application.Messaging.OrderSideEffects;
+
+///
+/// 订单状态通知(微信模板 + 邮件),走 Fake.EventBus Outbox。
+///
+[Serializable]
+public class OrderNotifyIntegrationEvent : IntegrationEvent
+{
+ public int OrderId { get; set; }
+
+ /// 事件码,见 。
+ public string EventCode { get; set; } = string.Empty;
+
+ /// 可选备注(问题件说明等)。
+ public string? Remark { get; set; }
+
+ /// 试发/强制:跳过客户订阅与去重(微信)。
+ public bool Force { get; set; }
+}
diff --git a/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs b/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs
index 0ca24e8..ee615e7 100644
--- a/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs
+++ b/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs
@@ -173,23 +173,24 @@ public sealed class TrackChangeOrderStatusApplier(
operatorType: "system",
source: "trackCenter");
- await unitOfWork.CompleteAsync(cancellationToken);
-
+ // 与返佣等同事务写入 Outbox,Commit 后异步发微信/邮件
if (string.Equals(targetStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase))
{
- await wechatOrderNotifyDispatcher.TryNotifyAsync(
+ await wechatOrderNotifyDispatcher.EnqueueNotifyAsync(
order,
WechatOrderNotifyEventCodes.DeliverySuccess,
cancellationToken: cancellationToken);
}
else if (string.Equals(targetStatus, OrderStatusCodes.DeliveryFailed, StringComparison.OrdinalIgnoreCase))
{
- await wechatOrderNotifyDispatcher.TryNotifyAsync(
+ await wechatOrderNotifyDispatcher.EnqueueNotifyAsync(
order,
WechatOrderNotifyEventCodes.DeliveryFailed,
cancellationToken: cancellationToken);
}
+ await unitOfWork.CompleteAsync(cancellationToken);
+
logger.LogInformation(
"TrackChange applied OrderId={OrderId} ServiceNo={ServiceNo} {From} → {To} TrackStatusCode={TrackStatusCode}",
order.Id,
diff --git a/src/Oms.Application/Services/Customers/CustomerWechatNotifyService.cs b/src/Oms.Application/Services/Customers/CustomerWechatNotifyService.cs
index f82ce9e..3c0cd0c 100644
--- a/src/Oms.Application/Services/Customers/CustomerWechatNotifyService.cs
+++ b/src/Oms.Application/Services/Customers/CustomerWechatNotifyService.cs
@@ -10,7 +10,7 @@ using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.Customers;
///
-/// 客户微信订单通知订阅(H5/门户)。
+/// 客户订单通知订阅(微信 / 邮件;H5/门户)。
///
[ApiExplorerSettings(GroupName = "OMS-Customer")]
public class CustomerWechatNotifyService : ApplicationService
@@ -44,9 +44,12 @@ public class CustomerWechatNotifyService : ApplicationService
SystemOtherConfigCodes.WeChatMpFollow,
cancellationToken);
+ var hasEmail = !string.IsNullOrWhiteSpace(customer.Email) && customer.Email.Contains('@');
+
return new CustomerWechatNotifyStatusOutput
{
HasOpenId = !string.IsNullOrWhiteSpace(customer.WechatOpenid),
+ HasEmail = hasEmail,
HasFollowUrl = !string.IsNullOrWhiteSpace(follow?.BaseUrl),
Items = WechatOrderNotifyEventCodes.All.Select(e =>
{
@@ -57,7 +60,10 @@ public class CustomerWechatNotifyService : ApplicationService
EventCode = e.Code,
EventName = e.Name,
OpsEnabled = tpl is { IsEnabled: true } && !string.IsNullOrWhiteSpace(tpl.TemplateId),
- IsSubscribed = pref?.IsSubscribed == true
+ OpsEmailEnabled = tpl is { EmailEnabled: true }
+ && !string.IsNullOrWhiteSpace(tpl.EmailTemplateName),
+ IsSubscribed = pref?.IsSubscribed == true,
+ IsEmailSubscribed = pref?.IsEmailSubscribed == true
};
}).ToList()
};
@@ -93,13 +99,15 @@ public class CustomerWechatNotifyService : ApplicationService
{
CustomerId = customer.Id,
EventCode = code,
- IsSubscribed = item.IsSubscribed
+ IsSubscribed = item.IsSubscribed,
+ IsEmailSubscribed = item.IsEmailSubscribed
},
cancellationToken: cancellationToken);
}
else
{
entity.IsSubscribed = item.IsSubscribed;
+ entity.IsEmailSubscribed = item.IsEmailSubscribed;
entity.UpdateTime = DateTime.Now;
await PrefRepository.UpdateAsync(entity, cancellationToken: cancellationToken);
}
diff --git a/src/Oms.Application/Services/Operations/InboundRecordService.cs b/src/Oms.Application/Services/Operations/InboundRecordService.cs
index e3d8586..bded441 100644
--- a/src/Oms.Application/Services/Operations/InboundRecordService.cs
+++ b/src/Oms.Application/Services/Operations/InboundRecordService.cs
@@ -137,7 +137,7 @@ public class InboundRecordService : ApplicationService
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Inbound, operatorId);
var refreshed = await OrderRepository.GetByWaybillNoAsync(waybillNo);
- await WechatOrderNotifyDispatcher.TryNotifyAsync(
+ await WechatOrderNotifyDispatcher.EnqueueNotifyAsync(
refreshed ?? order,
WechatOrderNotifyEventCodes.Inbound);
var output = ObjectMapper.Map(savedEntity);
diff --git a/src/Oms.Application/Services/Operations/OutboundRecordService.cs b/src/Oms.Application/Services/Operations/OutboundRecordService.cs
index 611b291..f22b97a 100644
--- a/src/Oms.Application/Services/Operations/OutboundRecordService.cs
+++ b/src/Oms.Application/Services/Operations/OutboundRecordService.cs
@@ -147,9 +147,8 @@ public class OutboundRecordService : ApplicationService
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId);
var refreshed = await OrderRepository.GetByWaybillNoAsync(waybillNo);
- await WechatOrderNotifyDispatcher.TryNotifyAsync(
- refreshed ?? order,
- WechatOrderNotifyEventCodes.Outbound);
+ // 与装袋出库共用入口;30 分钟 sent 去重防双通道重复
+ await WechatOrderNotifyDispatcher.EnqueueOutboundNotifyAsync(refreshed ?? order);
return ObjectMapper.Map(savedEntity);
}
diff --git a/src/Oms.Application/Services/Operations/ShipBagService.cs b/src/Oms.Application/Services/Operations/ShipBagService.cs
index 5b8374c..ce79528 100644
--- a/src/Oms.Application/Services/Operations/ShipBagService.cs
+++ b/src/Oms.Application/Services/Operations/ShipBagService.cs
@@ -369,7 +369,7 @@ public class ShipBagService : ApplicationService
});
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId);
var refreshed = await OrderRepository.GetByServiceNoAsync(order.ServiceNo) ?? order;
- await WechatOrderNotifyDispatcher.TryNotifyAsync(refreshed, WechatOrderNotifyEventCodes.Outbound);
+ await WechatOrderNotifyDispatcher.EnqueueOutboundNotifyAsync(refreshed);
}
bag.Status = ShipBagStatusCodes.Shipped;
diff --git a/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs b/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs
index 646a194..7072abe 100644
--- a/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs
+++ b/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs
@@ -80,7 +80,7 @@ public class OrderIssueNotificationService(
// 仅问题件状态时投递客户订阅的微信通知(自动触发警告等不发)
if (string.Equals(order.OrderStatus, OrderStatusCodes.Problematic, StringComparison.OrdinalIgnoreCase))
{
- await wechatOrderNotifyDispatcher.TryNotifyAsync(
+ await wechatOrderNotifyDispatcher.EnqueueNotifyAsync(
order,
WechatOrderNotifyEventCodes.Problematic,
remark: string.IsNullOrWhiteSpace(content) ? title : content);
diff --git a/src/Oms.Application/Services/Orders/OrderService.NotifyLog.cs b/src/Oms.Application/Services/Orders/OrderService.NotifyLog.cs
new file mode 100644
index 0000000..b6530a9
--- /dev/null
+++ b/src/Oms.Application/Services/Orders/OrderService.NotifyLog.cs
@@ -0,0 +1,85 @@
+using Microsoft.AspNetCore.Mvc;
+using Oms.Application.Dtos.Orders;
+using Oms.Domain.SystemAggregate.Consts;
+using Oms.Domain.SystemAggregate.Repositories;
+
+namespace Oms.Application.Services.Orders;
+
+public partial class OrderService
+{
+ private IOrderNotifyLogRepository OrderNotifyLogRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ ///
+ /// 运单通知日志列表(微信 / 邮件;按时间倒序)。
+ ///
+ /// 订单 Id。
+ /// 取消令牌。
+ [HttpGet("/order/notify-log/list")]
+ public async Task GetNotifyLogListAsync(
+ [FromQuery] int orderId,
+ CancellationToken cancellationToken = default)
+ {
+ await GetOrderOrThrowAsync(orderId);
+ var rows = await OrderNotifyLogRepository.ListByOrderIdAsync(orderId, cancellationToken);
+ return new OrderNotifyLogListOutput
+ {
+ Items = rows.Select(x =>
+ {
+ var eventName = WechatOrderNotifyEventCodes.GetName(x.EventCode) ?? x.EventCode;
+ var channelName = OrderNotifyChannels.GetName(x.Channel);
+ var statusText = x.Status switch
+ {
+ "sent" => "成功",
+ "failed" => "失败",
+ "skipped" => "跳过",
+ _ => x.Status
+ };
+ var parts = new List { $"{eventName}:{statusText}" };
+ if (!string.IsNullOrWhiteSpace(x.ErrMsg)
+ && !string.Equals(x.ErrMsg, "发送成功", StringComparison.Ordinal))
+ {
+ parts.Add(x.ErrMsg.Trim());
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.Recipient))
+ {
+ parts.Add(x.Channel == OrderNotifyChannels.Email
+ ? $"收件={x.Recipient}"
+ : $"OpenId={x.Recipient}");
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.ProviderMsgId))
+ {
+ parts.Add($"msgid={x.ProviderMsgId}");
+ }
+
+ if (x.ErrCode is int code and not 0)
+ {
+ parts.Add($"errcode={code}");
+ }
+
+ return new OrderNotifyLogOutput
+ {
+ Id = x.Id,
+ OrderId = x.OrderId,
+ Channel = x.Channel,
+ ChannelName = channelName,
+ EventCode = x.EventCode,
+ EventName = eventName,
+ Recipient = x.Recipient,
+ TemplateRef = x.TemplateRef,
+ Subject = x.Subject,
+ Status = x.Status,
+ ProviderMsgId = x.ProviderMsgId,
+ ErrCode = x.ErrCode,
+ ErrMsg = x.ErrMsg,
+ SmtpUsername = x.SmtpUsername,
+ Summary = string.Join(";", parts),
+ PayloadJson = x.PayloadJson,
+ CreateTime = x.CreateTime
+ };
+ }).ToList()
+ };
+ }
+}
diff --git a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
index 475d4fb..095d3cd 100644
--- a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
@@ -1356,7 +1356,7 @@ public partial class OrderService
if (becamePendingPayment)
{
- await WechatOrderNotifyDispatcher.TryNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
+ await WechatOrderNotifyDispatcher.EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
}
}
diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
index 30c5b45..438651d 100644
--- a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
@@ -2748,7 +2748,7 @@ public partial class OrderService
if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase))
{
- await WechatOrderNotifyDispatcher.TryNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
+ await WechatOrderNotifyDispatcher.EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
}
if (allocated)
diff --git a/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs
index 8a4edb4..fd73ecc 100644
--- a/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs
+++ b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Shared;
using Oms.Application.Dtos.System;
using Oms.Application.Services.WeChatNotify;
+using Oms.Application.Shared;
using Oms.Domain.OrdersAggregate.Repositories;
using Oms.Domain.SystemAggregate.Consts;
using Oms.Domain.SystemAggregate.Entities;
@@ -11,14 +12,23 @@ using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.System;
///
-/// 微信订单通知模板配置(系统其他配置入口使用)。
+/// 订单通知模板配置(微信 + 邮件;系统其他配置入口使用)。
///
[ApiExplorerSettings(GroupName = "OMS-System")]
public class WechatOrderNotifyConfigService : ApplicationService
{
+ /// 系统发信 SMTP 的 OwnerUserId。
+ public const int SystemSmtpOwnerUserId = 0;
+
private IWechatNotifyTemplateRepository TemplateRepository =>
LazyServiceProvider.GetRequiredService();
+ private ISystemBatchEmailTemplateRepository BatchEmailTemplateRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ private ISystemBatchEmailAccountRepository BatchEmailAccountRepository =>
+ LazyServiceProvider.GetRequiredService();
+
private IOrderRepository OrderRepository =>
LazyServiceProvider.GetRequiredService();
@@ -62,6 +72,41 @@ public class WechatOrderNotifyConfigService : ApplicationService
var name = WechatOrderNotifyEventCodes.GetName(code) ?? code;
await EnsureSeedAsync(cancellationToken);
+ var ownerUserId = CurrentUser.GetId();
+ if (input.EmailEnabled)
+ {
+ if (ownerUserId <= 0)
+ {
+ throw new BusinessException("未登录,无法绑定邮件模板");
+ }
+
+ var tplName = input.EmailTemplateName?.Trim() ?? string.Empty;
+ if (string.IsNullOrWhiteSpace(tplName))
+ {
+ throw new BusinessException("启用邮件时请选择 batch-email 模板");
+ }
+
+ var batchTpl = await BatchEmailTemplateRepository.GetByOwnerAndNameAsync(
+ ownerUserId,
+ tplName,
+ cancellationToken);
+ if (batchTpl == null)
+ {
+ throw new BusinessException($"邮件模板不存在:{tplName}(请先在「批量邮件」中创建)");
+ }
+
+ if (input.EmailUseSystemSmtp)
+ {
+ var systemAccount = await BatchEmailAccountRepository.GetByOwnerAsync(
+ SystemSmtpOwnerUserId,
+ cancellationToken);
+ if (systemAccount == null || string.IsNullOrWhiteSpace(systemAccount.SmtpPassword))
+ {
+ throw new BusinessException("尚未配置系统发信 SMTP,请先在本页保存系统发信账号");
+ }
+ }
+ }
+
var entity = await TemplateRepository.GetByEventCodeAsync(code, cancellationToken);
if (entity == null)
{
@@ -70,12 +115,12 @@ public class WechatOrderNotifyConfigService : ApplicationService
EventCode = code,
EventName = name
};
- ApplyInput(entity, input, name);
+ ApplyInput(entity, input, name, ownerUserId);
await TemplateRepository.InsertAsync(entity, cancellationToken: cancellationToken);
}
else
{
- ApplyInput(entity, input, name);
+ ApplyInput(entity, input, name, ownerUserId);
entity.UpdateTime = DateTime.Now;
await TemplateRepository.UpdateAsync(entity, cancellationToken: cancellationToken);
}
@@ -84,7 +129,80 @@ public class WechatOrderNotifyConfigService : ApplicationService
}
///
- /// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId);返回请求/响应明细。
+ /// 查询系统发信 SMTP 是否已配置。
+ ///
+ [HttpGet("/system/wechat-order-notify/system-smtp")]
+ public async Task GetSystemSmtpAsync(
+ CancellationToken cancellationToken = default)
+ {
+ var entity = await BatchEmailAccountRepository.GetByOwnerAsync(
+ SystemSmtpOwnerUserId,
+ cancellationToken);
+ return new OrderNotifySystemSmtpStatusOutput
+ {
+ Configured = entity != null && !string.IsNullOrWhiteSpace(entity.SmtpPassword),
+ SmtpUsername = entity?.SmtpUsername,
+ FromName = entity?.FromName
+ };
+ }
+
+ ///
+ /// 保存系统发信 SMTP(OwnerUserId=0,与配置操作人解耦)。
+ ///
+ [HttpPost("/system/wechat-order-notify/system-smtp/save")]
+ public async Task SaveSystemSmtpAsync(
+ [FromBody] BatchEmailAccountSaveInput input,
+ CancellationToken cancellationToken = default)
+ {
+ var username = input.SmtpUsername?.Trim() ?? string.Empty;
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ throw new BusinessException("SMTP 账号不能为空");
+ }
+
+ var password = input.SmtpPassword ?? string.Empty;
+ var entity = await BatchEmailAccountRepository.GetByOwnerAsync(
+ SystemSmtpOwnerUserId,
+ cancellationToken);
+ if (string.IsNullOrWhiteSpace(password)
+ || (BatchEmailSmtpHelper.IsSecretMask(password) && entity == null))
+ {
+ throw new BusinessException("SMTP 密码不能为空");
+ }
+
+ var serverType = NormalizeServerType(input.ServerType);
+ if (entity == null)
+ {
+ await BatchEmailAccountRepository.InsertAsync(
+ new SystemBatchEmailAccount
+ {
+ OwnerUserId = SystemSmtpOwnerUserId,
+ SmtpUsername = username,
+ SmtpPassword = password,
+ ServerType = serverType,
+ FromName = NormalizeOptional(input.FromName)
+ },
+ cancellationToken: cancellationToken);
+ }
+ else
+ {
+ entity.SmtpUsername = username;
+ if (!BatchEmailSmtpHelper.IsSecretMask(password))
+ {
+ entity.SmtpPassword = password;
+ }
+
+ entity.ServerType = serverType;
+ entity.FromName = NormalizeOptional(input.FromName);
+ entity.UpdateTime = DateTime.Now;
+ await BatchEmailAccountRepository.UpdateAsync(entity, cancellationToken: cancellationToken);
+ }
+
+ return await GetSystemSmtpAsync(cancellationToken);
+ }
+
+ ///
+ /// 按订单试发(微信 + 邮件);跳过客户订阅与去重,返回请求/响应明细。
///
[HttpPost("/system/wechat-order-notify/trial-send")]
public async Task TrialSendAsync(
@@ -153,7 +271,11 @@ public class WechatOrderNotifyConfigService : ApplicationService
return null;
}
- private static void ApplyInput(WechatNotifyTemplate entity, SaveWechatOrderNotifyTemplateInput input, string name)
+ private static void ApplyInput(
+ WechatNotifyTemplate entity,
+ SaveWechatOrderNotifyTemplateInput input,
+ string name,
+ int ownerUserId)
{
entity.EventName = name;
entity.TemplateId = string.IsNullOrWhiteSpace(input.TemplateId) ? null : input.TemplateId.Trim();
@@ -162,6 +284,23 @@ public class WechatOrderNotifyConfigService : ApplicationService
? null
: input.FieldMappingJson.Trim();
entity.IsEnabled = input.IsEnabled;
+ entity.EmailEnabled = input.EmailEnabled;
+ if (input.EmailEnabled)
+ {
+ entity.EmailTemplateName = input.EmailTemplateName!.Trim();
+ entity.EmailTemplateOwnerUserId = ownerUserId;
+ entity.EmailSmtpOwnerUserId = input.EmailUseSystemSmtp
+ ? SystemSmtpOwnerUserId
+ : ownerUserId;
+ }
+ else
+ {
+ entity.EmailTemplateName = string.IsNullOrWhiteSpace(input.EmailTemplateName)
+ ? null
+ : input.EmailTemplateName.Trim();
+ // 关闭邮件时保留上次绑定,便于再开
+ }
+
entity.Remark = string.IsNullOrWhiteSpace(input.Remark) ? null : input.Remark.Trim();
}
@@ -178,6 +317,20 @@ public class WechatOrderNotifyConfigService : ApplicationService
UrlTemplate = entity?.UrlTemplate,
FieldMappingJson = entity?.FieldMappingJson,
IsEnabled = entity?.IsEnabled ?? false,
+ EmailEnabled = entity?.EmailEnabled ?? false,
+ EmailTemplateName = entity?.EmailTemplateName,
+ EmailTemplateOwnerUserId = entity?.EmailTemplateOwnerUserId,
+ EmailSmtpOwnerUserId = entity?.EmailSmtpOwnerUserId,
+ EmailUseSystemSmtp = entity?.EmailSmtpOwnerUserId == SystemSmtpOwnerUserId,
Remark = entity?.Remark
};
+
+ private static string NormalizeServerType(string? serverType)
+ {
+ var value = (serverType ?? string.Empty).Trim().ToLowerInvariant();
+ return value is "qiye" or "163" or "qq" or "gmail" or "outlook" ? value : "qiye";
+ }
+
+ private static string? NormalizeOptional(string? value) =>
+ string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
diff --git a/src/Oms.Application/Services/WeChatNotify/OrderNotifyRetryableException.cs b/src/Oms.Application/Services/WeChatNotify/OrderNotifyRetryableException.cs
new file mode 100644
index 0000000..05793c2
--- /dev/null
+++ b/src/Oms.Application/Services/WeChatNotify/OrderNotifyRetryableException.cs
@@ -0,0 +1,12 @@
+namespace Oms.Application.Services.WeChatNotify;
+
+///
+/// 订单通知可重试失败(token/SMTP 临时故障等);Outbox 消费者应 Nack/重投。
+///
+public sealed class OrderNotifyRetryableException : Exception
+{
+ public OrderNotifyRetryableException(string message, Exception? inner = null)
+ : base(message, inner)
+ {
+ }
+}
diff --git a/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs
index 9189a3f..35d08d9 100644
--- a/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs
+++ b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs
@@ -1,10 +1,21 @@
+using System.Net.Mail;
+using System.Net.Sockets;
using System.Text.Json;
using Fake.DependencyInjection;
+using Fake.EventBus.Distributed;
+using Fake.UnitOfWork;
using Microsoft.Extensions.Logging;
+using Oms.Application.Dtos.OpenApi;
using Oms.Application.Dtos.System;
+using Oms.Application.Integrations.SmallBagTrack;
using Oms.Application.Integrations.WeChat;
+using Oms.Application.Messaging;
+using Oms.Application.Messaging.OrderSideEffects;
+using Oms.Application.Services.Orders;
+using Oms.Application.Services.System;
using Oms.Application.Shared;
using Oms.Domain.CustomersAggregate.Repositories;
+using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.SystemAggregate.Consts;
using Oms.Domain.SystemAggregate.Entities;
@@ -13,15 +24,21 @@ using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.WeChatNotify;
///
-/// 微信订单状态通知调度:校验运营启用 + 客户订阅 + openid,组包发送并写日志。
+/// 订单状态通知调度:微信模板消息 + batch-email 邮件;业务侧优先 Outbox 异步投递。
///
public class WechatOrderNotifyDispatcher(
IWechatNotifyTemplateRepository templateRepository,
ICustomerWechatNotifyPrefRepository prefRepository,
- IWechatNotifyLogRepository logRepository,
+ IOrderNotifyLogRepository notifyLogRepository,
ICustomerRepository customerRepository,
ISystemOtherConfigRepository otherConfigRepository,
+ ISystemBatchEmailTemplateRepository batchEmailTemplateRepository,
+ ISystemBatchEmailAccountRepository batchEmailAccountRepository,
+ ISmallBagTrackOrderClient trackOrderClient,
IWeChatMpTemplateSender templateSender,
+ OrderOperationLogWriter operationLogWriter,
+ IDistributedEventBus eventBus,
+ IUnitOfWorkManager unitOfWorkManager,
ILogger logger) : IScopedDependency
{
private const string WechatTemplateSendUrl =
@@ -29,19 +46,107 @@ public class WechatOrderNotifyDispatcher(
private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30);
+ /// 微信侧可重试 errcode(token/系统繁忙等)。
+ private static readonly HashSet WechatRetryableErrCodes =
+ [
+ -1,
+ 40001,
+ 42001,
+ 45009,
+ 45011
+ ];
+
+ /// 未关注 / 拒收模板等业务失败(勿重试)。
+ private static readonly HashSet WechatUnfollowErrCodes =
+ [
+ 43004,
+ 43101
+ ];
+
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
///
- /// 尝试按事件发送;任何失败只记日志,不抛给业务主流程。
+ /// 投递订单通知(微信 + 邮件)。有事务 UoW 时写 Outbox;否则同步兜底。
+ ///
+ public async Task EnqueueNotifyAsync(
+ Order order,
+ string eventCode,
+ string? remark = null,
+ bool force = false,
+ CancellationToken cancellationToken = default)
+ {
+ if (order.Id <= 0 || string.IsNullOrWhiteSpace(eventCode))
+ {
+ return;
+ }
+
+ if (OmsOutboxUnitOfWork.IsAmbientTransactional(unitOfWorkManager))
+ {
+ await eventBus.PublishAsync(new OrderNotifyIntegrationEvent
+ {
+ OrderId = order.Id,
+ EventCode = eventCode.Trim(),
+ Remark = remark,
+ Force = force
+ });
+ return;
+ }
+
+ await TryNotifyAsync(order, eventCode, remark, force, cancellationToken);
+ }
+
+ ///
+ /// 出库通知统一入口(扫码出库 / 装袋出库共用;幂等靠 30 分钟 sent 去重)。
+ ///
+ public Task EnqueueOutboundNotifyAsync(
+ Order order,
+ CancellationToken cancellationToken = default) =>
+ EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.Outbound, cancellationToken: cancellationToken);
+
+ ///
+ /// 按 OrderId 投递(消费者/无实体场景)。
+ ///
+ public async Task EnqueueNotifyByOrderIdAsync(
+ int orderId,
+ string eventCode,
+ string? remark = null,
+ bool force = false,
+ CancellationToken cancellationToken = default)
+ {
+ if (orderId <= 0 || string.IsNullOrWhiteSpace(eventCode))
+ {
+ return;
+ }
+
+ if (OmsOutboxUnitOfWork.IsAmbientTransactional(unitOfWorkManager))
+ {
+ await eventBus.PublishAsync(new OrderNotifyIntegrationEvent
+ {
+ OrderId = orderId,
+ EventCode = eventCode.Trim(),
+ Remark = remark,
+ Force = force
+ });
+ return;
+ }
+
+ using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Independent());
+ await eventBus.PublishAsync(new OrderNotifyIntegrationEvent
+ {
+ OrderId = orderId,
+ EventCode = eventCode.Trim(),
+ Remark = remark,
+ Force = force
+ });
+ await unitOfWork.CompleteAsync(cancellationToken);
+ }
+
+ ///
+ /// 同步发送(试发 / Outbox 消费者 / 无队列兜底);失败只记日志。
///
- /// 订单。
- /// 事件码。
- /// 可选备注(问题件说明等)。
- /// 试发时跳过订阅与去重。
- /// 取消令牌。
public async Task TryNotifyAsync(
Order order,
string eventCode,
@@ -53,28 +158,71 @@ public class WechatOrderNotifyDispatcher(
{
await NotifyDetailedAsync(order, eventCode, remark, force, cancellationToken);
}
+ catch (OrderNotifyRetryableException)
+ {
+ throw;
+ }
catch (Exception ex)
{
logger.LogWarning(
ex,
- "微信订单通知异常 OrderId={OrderId} Event={EventCode}",
+ "订单通知异常 OrderId={OrderId} Event={EventCode}",
order.Id,
eventCode);
}
}
///
- /// 运营试发:返回请求/响应明细;业务跳过/失败不抛,异常仍向上抛。
+ /// 运营试发 / 明细发送:微信 + 邮件;业务跳过/失败写入结果。
+ /// 可重试失败抛 (force 试发除外)。
///
- public Task NotifyDetailedAsync(
+ public async Task NotifyDetailedAsync(
Order order,
string eventCode,
string? remark = null,
bool force = false,
- CancellationToken cancellationToken = default) =>
- NotifyCoreAsync(order, eventCode, remark, force, cancellationToken);
+ CancellationToken cancellationToken = default)
+ {
+ var result = await NotifyWechatCoreAsync(order, eventCode, remark, force, cancellationToken);
+ try
+ {
+ result.Email = await NotifyEmailCoreAsync(order, eventCode, remark, force, cancellationToken);
+ }
+ catch (OrderNotifyRetryableException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(
+ ex,
+ "订单邮件通知异常 OrderId={OrderId} Event={EventCode}",
+ order.Id,
+ eventCode);
+ result.Email = new TrialOrderNotifyEmailResultOutput
+ {
+ Success = false,
+ Skipped = false,
+ Status = "failed",
+ Message = ex.Message
+ };
- private async Task NotifyCoreAsync(
+ if (!force && IsRetryableTransport(ex))
+ {
+ throw new OrderNotifyRetryableException($"邮件发送临时失败:{ex.Message}", ex);
+ }
+ }
+
+ if (!force)
+ {
+ ThrowIfRetryableWechatFailure(result);
+ ThrowIfRetryableEmailFailure(result.Email);
+ }
+
+ return result;
+ }
+
+ private async Task NotifyWechatCoreAsync(
Order order,
string eventCode,
string? remark,
@@ -101,12 +249,29 @@ public class WechatOrderNotifyDispatcher(
result.EventCode = normalized;
result.EventName = eventName;
+ if (!force
+ && string.Equals(normalized, WechatOrderNotifyEventCodes.PendingPayment, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase))
+ {
+ result.Message = "订单已非待支付,跳过待支付通知";
+ await WriteWechatLogAsync(
+ order,
+ customerId: order.CustomerId ?? 0,
+ normalized,
+ openId: null,
+ templateId: null,
+ status: "skipped",
+ errMsg: result.Message,
+ cancellationToken: cancellationToken);
+ return result;
+ }
+
var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken);
if (template == null || !template.IsEnabled)
{
result.TemplateId = template?.TemplateId;
result.Message = "运营未启用该事件模板";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId: order.CustomerId ?? 0,
normalized,
@@ -123,7 +288,7 @@ public class WechatOrderNotifyDispatcher(
if (string.IsNullOrWhiteSpace(template.TemplateId))
{
result.Message = "未配置微信 TemplateId";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId: order.CustomerId ?? 0,
normalized,
@@ -138,7 +303,7 @@ public class WechatOrderNotifyDispatcher(
if (order.CustomerId is not int customerId || customerId <= 0)
{
result.Message = "订单无客户";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId: 0,
normalized,
@@ -156,7 +321,7 @@ public class WechatOrderNotifyDispatcher(
if (pref is not { IsSubscribed: true })
{
result.Message = "客户未订阅该事件";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId,
normalized,
@@ -169,10 +334,15 @@ public class WechatOrderNotifyDispatcher(
}
var since = DateTime.Now.Subtract(DedupWindow);
- if (await logRepository.ExistsRecentAsync(order.Id, normalized, since, cancellationToken))
+ if (await notifyLogRepository.ExistsRecentSentAsync(
+ order.Id,
+ normalized,
+ OrderNotifyChannels.Wechat,
+ since,
+ cancellationToken))
{
result.Message = $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId,
normalized,
@@ -190,7 +360,7 @@ public class WechatOrderNotifyDispatcher(
if (string.IsNullOrWhiteSpace(openId))
{
result.Message = "客户未绑定微信 OpenId";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId,
normalized,
@@ -204,12 +374,17 @@ public class WechatOrderNotifyDispatcher(
result.OpenId = openId;
- var placeholders = BuildPlaceholders(order, eventName, remark, customer?.CustomerName);
+ var placeholders = await BuildPlaceholdersAsync(
+ order,
+ eventName,
+ remark,
+ customer?.CustomerName,
+ cancellationToken);
var data = BuildTemplateData(template.FieldMappingJson, placeholders);
if (data.Count == 0)
{
result.Message = "字段映射为空或无效";
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId,
normalized,
@@ -248,10 +423,12 @@ public class WechatOrderNotifyDispatcher(
result.Status = sendResult.Success ? "sent" : "failed";
result.WxMsgId = sendResult.MsgId;
result.ErrCode = sendResult.ErrCode == 0 ? null : sendResult.ErrCode;
- result.Message = sendResult.Success ? "发送成功" : (sendResult.ErrMsg ?? "发送失败");
+ result.Message = sendResult.Success
+ ? "发送成功"
+ : MapWechatErrMsg(sendResult.ErrCode, sendResult.ErrMsg);
result.ResponseBody = BuildWechatResponseBody(sendResult);
- await WriteLogAsync(
+ await WriteWechatLogAsync(
order,
customerId,
normalized,
@@ -259,11 +436,22 @@ public class WechatOrderNotifyDispatcher(
template.TemplateId,
status: result.Status,
errCode: sendResult.ErrCode == 0 ? null : sendResult.ErrCode,
- errMsg: sendResult.Success ? null : sendResult.ErrMsg,
+ errMsg: sendResult.Success ? null : result.Message,
wxMsgId: sendResult.MsgId,
payloadJson: payloadJson,
cancellationToken: cancellationToken);
+ await WriteOpsNotifySummaryAsync(
+ order,
+ OrderOperationActionCodes.NotifyWechat,
+ eventName,
+ result.Status,
+ result.Message,
+ force,
+ detail: sendResult.Success
+ ? (string.IsNullOrWhiteSpace(sendResult.MsgId) ? null : $"msgid={sendResult.MsgId}")
+ : (result.ErrCode is int ec ? $"errcode={ec}" : null));
+
if (!sendResult.Success)
{
logger.LogWarning(
@@ -271,12 +459,414 @@ public class WechatOrderNotifyDispatcher(
order.Id,
normalized,
sendResult.ErrCode,
- sendResult.ErrMsg);
+ result.Message);
}
return result;
}
+ private async Task NotifyEmailCoreAsync(
+ Order order,
+ string eventCode,
+ string? remark,
+ bool force,
+ CancellationToken cancellationToken)
+ {
+ var result = new TrialOrderNotifyEmailResultOutput
+ {
+ Status = "skipped",
+ Skipped = true
+ };
+
+ if (!WechatOrderNotifyEventCodes.IsKnown(eventCode))
+ {
+ result.Message = "未知事件码";
+ return result;
+ }
+
+ var normalized = WechatOrderNotifyEventCodes.Normalize(eventCode);
+ var eventName = WechatOrderNotifyEventCodes.GetName(normalized) ?? normalized;
+
+ if (!force
+ && string.Equals(normalized, WechatOrderNotifyEventCodes.PendingPayment, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase))
+ {
+ result.Message = "订单已非待支付,跳过待支付通知";
+ await WriteEmailLogAsync(
+ order,
+ customerId: order.CustomerId ?? 0,
+ normalized,
+ toEmail: null,
+ templateName: null,
+ subject: null,
+ status: "skipped",
+ errMsg: result.Message,
+ smtpUsername: null,
+ payloadJson: null,
+ cancellationToken);
+ return result;
+ }
+
+ var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken);
+ if (template is not { EmailEnabled: true })
+ {
+ result.Message = "运营未启用邮件通知";
+ return result;
+ }
+
+ var tplName = template.EmailTemplateName?.Trim();
+ var templateOwner = template.EmailTemplateOwnerUserId
+ ?? (template.EmailSmtpOwnerUserId is > 0 ? template.EmailSmtpOwnerUserId : null);
+ var smtpOwner = template.EmailSmtpOwnerUserId
+ ?? template.EmailTemplateOwnerUserId;
+
+ if (string.IsNullOrWhiteSpace(tplName)
+ || templateOwner is not int tplOwner
+ || tplOwner <= 0
+ || smtpOwner is not int smtpId
+ || smtpId < 0)
+ {
+ result.Message = "未绑定邮件模板或发信账号";
+ return result;
+ }
+
+ result.TemplateName = tplName;
+
+ var batchTpl = await batchEmailTemplateRepository.GetByOwnerAndNameAsync(
+ tplOwner,
+ tplName,
+ cancellationToken);
+ if (batchTpl == null)
+ {
+ result.Message = $"邮件模板不存在:{tplName}";
+ return result;
+ }
+
+ var account = await batchEmailAccountRepository.GetByOwnerAsync(smtpId, cancellationToken);
+ if (account == null || string.IsNullOrWhiteSpace(account.SmtpPassword))
+ {
+ result.Message = smtpId == WechatOrderNotifyConfigService.SystemSmtpOwnerUserId
+ ? "系统发信 SMTP 未配置"
+ : "发信人未配置 SMTP(请到「批量邮件」保存邮箱账号)";
+ return result;
+ }
+
+ result.SmtpUsername = account.SmtpUsername;
+
+ if (order.CustomerId is not int customerId || customerId <= 0)
+ {
+ result.Message = "订单无客户";
+ return result;
+ }
+
+ if (!force)
+ {
+ var pref = await prefRepository.GetByCustomerAndEventAsync(customerId, normalized, cancellationToken);
+ if (pref is not { IsEmailSubscribed: true })
+ {
+ result.Message = "客户未订阅邮件通知";
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail: null,
+ templateName: tplName,
+ subject: null,
+ status: "skipped",
+ errMsg: result.Message,
+ smtpUsername: account.SmtpUsername,
+ payloadJson: null,
+ cancellationToken);
+ return result;
+ }
+
+ var since = DateTime.Now.Subtract(DedupWindow);
+ if (await notifyLogRepository.ExistsRecentSentAsync(
+ order.Id,
+ normalized,
+ OrderNotifyChannels.Email,
+ since,
+ cancellationToken))
+ {
+ result.Message = $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过";
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail: null,
+ templateName: tplName,
+ subject: null,
+ status: "skipped",
+ errMsg: result.Message,
+ smtpUsername: account.SmtpUsername,
+ payloadJson: null,
+ cancellationToken);
+ return result;
+ }
+ }
+
+ var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId, cancellationToken);
+ var toEmail = customer?.Email?.Trim();
+ if (string.IsNullOrWhiteSpace(toEmail) || !toEmail.Contains('@'))
+ {
+ result.Message = "客户邮箱无效";
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail: toEmail,
+ templateName: tplName,
+ subject: null,
+ status: "skipped",
+ errMsg: result.Message,
+ smtpUsername: account.SmtpUsername,
+ payloadJson: null,
+ cancellationToken);
+ return result;
+ }
+
+ result.ToEmail = toEmail;
+
+ var placeholders = await BuildPlaceholdersAsync(
+ order,
+ eventName,
+ remark,
+ customer?.CustomerName,
+ cancellationToken);
+ var subject = ApplyEmailPlaceholders(batchTpl.Subject, placeholders);
+ var body = ApplyEmailPlaceholders(batchTpl.Content ?? string.Empty, placeholders);
+ result.Subject = subject;
+ result.Body = body;
+
+ var payloadJson = OmsDocHelper.SerializeJson(new
+ {
+ toEmail,
+ templateName = tplName,
+ subject,
+ smtpOwner = smtpId
+ });
+
+ try
+ {
+ await BatchEmailSmtpHelper.SendAsync(
+ account.SmtpUsername,
+ account.SmtpPassword,
+ account.ServerType,
+ toEmail,
+ subject,
+ body,
+ "text",
+ account.FromName,
+ cancellationToken);
+ }
+ catch (Exception ex) when (!force && IsRetryableTransport(ex))
+ {
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail,
+ tplName,
+ subject,
+ status: "failed",
+ errMsg: Truncate(ex.Message, 512),
+ smtpUsername: account.SmtpUsername,
+ payloadJson: payloadJson,
+ cancellationToken);
+ await WriteOpsNotifySummaryAsync(
+ order,
+ OrderOperationActionCodes.NotifyEmail,
+ eventName,
+ "failed",
+ Truncate(ex.Message, 200),
+ force,
+ detail: $"to={toEmail}");
+ throw new OrderNotifyRetryableException($"邮件发送临时失败:{ex.Message}", ex);
+ }
+ catch (Exception ex)
+ {
+ result.Skipped = false;
+ result.Success = false;
+ result.Status = "failed";
+ result.Message = ex.Message;
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail,
+ tplName,
+ subject,
+ status: "failed",
+ errMsg: Truncate(ex.Message, 512),
+ smtpUsername: account.SmtpUsername,
+ payloadJson: payloadJson,
+ cancellationToken);
+ await WriteOpsNotifySummaryAsync(
+ order,
+ OrderOperationActionCodes.NotifyEmail,
+ eventName,
+ "failed",
+ Truncate(ex.Message, 200),
+ force,
+ detail: $"to={toEmail}");
+ return result;
+ }
+
+ result.Skipped = false;
+ result.Success = true;
+ result.Status = "sent";
+ result.Message = "发送成功";
+ await WriteEmailLogAsync(
+ order,
+ customerId,
+ normalized,
+ toEmail,
+ tplName,
+ subject,
+ status: "sent",
+ errMsg: null,
+ smtpUsername: account.SmtpUsername,
+ payloadJson: payloadJson,
+ cancellationToken);
+ await WriteOpsNotifySummaryAsync(
+ order,
+ OrderOperationActionCodes.NotifyEmail,
+ eventName,
+ "sent",
+ "发送成功",
+ force,
+ detail: $"to={toEmail}");
+ return result;
+ }
+
+ ///
+ /// 仅 sent/failed 写入订单操作日志(skipped 不写,避免刷屏)。
+ ///
+ private async Task WriteOpsNotifySummaryAsync(
+ Order order,
+ string action,
+ string eventName,
+ string status,
+ string? message,
+ bool force,
+ string? detail = null)
+ {
+ if (!string.Equals(status, "sent", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(status, "failed", StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ var statusText = string.Equals(status, "sent", StringComparison.OrdinalIgnoreCase) ? "成功" : "失败";
+ var parts = new List
+ {
+ $"{eventName}:{statusText}"
+ };
+ if (!string.IsNullOrWhiteSpace(message)
+ && !string.Equals(message, "发送成功", StringComparison.Ordinal))
+ {
+ parts.Add(message.Trim());
+ }
+
+ if (!string.IsNullOrWhiteSpace(detail))
+ {
+ parts.Add(detail.Trim());
+ }
+
+ if (force)
+ {
+ parts.Add("试发");
+ }
+
+ await operationLogWriter.TryWriteSimpleAsync(
+ order,
+ action,
+ string.Join(";", parts),
+ operatorId: 0,
+ operatorName: "系统通知",
+ operatorType: "system",
+ source: "notify");
+ }
+
+ private static void ThrowIfRetryableWechatFailure(TrialWechatOrderNotifyResultOutput result)
+ {
+ if (result.Skipped || result.Success || result.ErrCode is not int code)
+ {
+ return;
+ }
+
+ if (WechatRetryableErrCodes.Contains(code))
+ {
+ throw new OrderNotifyRetryableException(
+ $"微信发送可重试失败 errcode={code}: {result.Message}");
+ }
+ }
+
+ private static void ThrowIfRetryableEmailFailure(TrialOrderNotifyEmailResultOutput? email)
+ {
+ if (email is not { Skipped: false, Success: false })
+ {
+ return;
+ }
+
+ // 非临时失败已在 catch 中分类;此处兜底:无明确业务文案时不重试
+ }
+
+ private static bool IsRetryableTransport(Exception ex) =>
+ ex is SocketException
+ or TimeoutException
+ or IOException
+ or SmtpException
+ or HttpRequestException
+ || (ex.InnerException != null && IsRetryableTransport(ex.InnerException));
+
+ private static string MapWechatErrMsg(int errCode, string? errMsg)
+ {
+ if (WechatUnfollowErrCodes.Contains(errCode))
+ {
+ return "用户未关注公众号或未接受模板消息,请引导客户关注后再推";
+ }
+
+ return string.IsNullOrWhiteSpace(errMsg) ? $"发送失败(errcode={errCode})" : errMsg.Trim();
+ }
+
+ ///
+ /// 替换邮件占位符:支持 batch-email 中文词 + OMS 英文字段。
+ ///
+ private static string ApplyEmailPlaceholders(
+ string template,
+ IReadOnlyDictionary placeholders)
+ {
+ if (string.IsNullOrEmpty(template))
+ {
+ return string.Empty;
+ }
+
+ var value = template;
+ foreach (var (key, replacement) in placeholders)
+ {
+ value = value.Replace($"{{{key}}}", replacement ?? string.Empty, StringComparison.OrdinalIgnoreCase);
+ }
+
+ value = value
+ .Replace("{客户单号}", placeholders.GetValueOrDefault("clientNo") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{运单号}", placeholders.GetValueOrDefault("serviceNo") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{换单号}", placeholders.GetValueOrDefault("serviceNo") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{最新轨迹}", placeholders.GetValueOrDefault("latestTrack") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{客户名称}", placeholders.GetValueOrDefault("customerName") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{收件国家}", placeholders.GetValueOrDefault("consigneeCountry") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{应付金额}", placeholders.GetValueOrDefault("payableAmount") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{问题内容}", placeholders.GetValueOrDefault("issueContent") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{入库时间}", placeholders.GetValueOrDefault("inboundTime") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{出库时间}", placeholders.GetValueOrDefault("outboundTime") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{签收时间}", placeholders.GetValueOrDefault("signTime") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{支付时间}", placeholders.GetValueOrDefault("payTime") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{事件名}", placeholders.GetValueOrDefault("eventName") ?? string.Empty, StringComparison.Ordinal)
+ .Replace("{事件时间}", placeholders.GetValueOrDefault("eventTime") ?? string.Empty, StringComparison.Ordinal);
+
+ return value;
+ }
+
private static object BuildWechatRequestBody(
string openId,
string templateId,
@@ -331,14 +921,17 @@ public class WechatOrderNotifyDispatcher(
}) ?? "{}";
}
- private static Dictionary BuildPlaceholders(
+ private async Task> BuildPlaceholdersAsync(
Order order,
string eventName,
string? remark,
- string? customerName)
+ string? customerName,
+ CancellationToken cancellationToken)
{
var statusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) ?? order.OrderStatus;
var issueContent = FirstNonEmpty(order.IssueContent, order.IssueTitle, remark);
+ var latestTrack = await ResolveLatestTrackAsync(order, statusName, remark, issueContent, cancellationToken);
+
return new Dictionary(StringComparer.OrdinalIgnoreCase)
{
["serviceNo"] = order.ServiceNo ?? string.Empty,
@@ -351,20 +944,71 @@ public class WechatOrderNotifyDispatcher(
["remark"] = string.IsNullOrWhiteSpace(remark) ? eventName : remark.Trim(),
["customerName"] = customerName ?? string.Empty,
["consigneeCountry"] = order.ConsigneeCountry ?? string.Empty,
- // 待支付:客户应付金额(两位小数)
["payableAmount"] = FormatAmount(order.PayableAmount),
- // 问题件:内容 / 标题
["issueContent"] = issueContent,
["issueTitle"] = order.IssueTitle?.Trim() ?? string.Empty,
["issueRemark"] = order.IssueRemark?.Trim() ?? string.Empty,
- // 关键节点时间(订单字段:ReceiveTime / ShipTime / SignTime)
["inboundTime"] = FormatDateTime(order.ReceiveTime),
["outboundTime"] = FormatDateTime(order.ShipTime),
["signTime"] = FormatDateTime(order.SignTime),
["payTime"] = FormatDateTime(order.PayTime),
+ ["latestTrack"] = latestTrack,
};
}
+ private async Task ResolveLatestTrackAsync(
+ Order order,
+ string statusName,
+ string? remark,
+ string issueContent,
+ CancellationToken cancellationToken)
+ {
+ if (!string.IsNullOrWhiteSpace(order.ServiceNo))
+ {
+ try
+ {
+ var events = await trackOrderClient.QuerySmallBagTracksAsync(
+ order.ServiceNo,
+ cancellationToken);
+ var latest = PickLatestTrack(events);
+ if (!string.IsNullOrWhiteSpace(latest))
+ {
+ return latest;
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.LogDebug(
+ ex,
+ "查询最新轨迹失败,回退占位 OrderId={OrderId}",
+ order.Id);
+ }
+ }
+
+ return FirstNonEmpty(remark, issueContent, statusName);
+ }
+
+ private static string? PickLatestTrack(IReadOnlyList events)
+ {
+ if (events == null || events.Count == 0)
+ {
+ return null;
+ }
+
+ var ordered = events
+ .OrderByDescending(x => x.Time ?? DateTime.MinValue)
+ .ThenByDescending(x => x.Content)
+ .ToList();
+ var hit = ordered.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Content));
+ if (hit == null)
+ {
+ return null;
+ }
+
+ var time = hit.Time.HasValue ? hit.Time.Value.ToString("yyyy-MM-dd HH:mm") + " " : string.Empty;
+ return $"{time}{hit.Content!.Trim()}";
+ }
+
private static string FormatAmount(decimal? amount) =>
amount.HasValue ? amount.Value.ToString("0.00") : string.Empty;
@@ -469,7 +1113,7 @@ public class WechatOrderNotifyDispatcher(
.Replace("{serviceNo}", Uri.EscapeDataString(order.ServiceNo ?? string.Empty), StringComparison.OrdinalIgnoreCase);
}
- private async Task WriteLogAsync(
+ private Task WriteWechatLogAsync(
Order order,
int customerId,
string eventCode,
@@ -480,29 +1124,95 @@ public class WechatOrderNotifyDispatcher(
int? errCode = null,
string? wxMsgId = null,
string? payloadJson = null,
- CancellationToken cancellationToken = default)
+ CancellationToken cancellationToken = default) =>
+ WriteNotifyLogAsync(
+ order,
+ customerId,
+ OrderNotifyChannels.Wechat,
+ eventCode,
+ recipient: openId,
+ templateRef: templateId,
+ subject: null,
+ status,
+ errMsg,
+ errCode,
+ providerMsgId: wxMsgId,
+ smtpUsername: null,
+ payloadJson,
+ cancellationToken);
+
+ private Task WriteEmailLogAsync(
+ Order order,
+ int customerId,
+ string eventCode,
+ string? toEmail,
+ string? templateName,
+ string? subject,
+ string status,
+ string? errMsg,
+ string? smtpUsername,
+ string? payloadJson,
+ CancellationToken cancellationToken) =>
+ WriteNotifyLogAsync(
+ order,
+ customerId,
+ OrderNotifyChannels.Email,
+ eventCode,
+ recipient: toEmail,
+ templateRef: templateName,
+ subject,
+ status,
+ errMsg,
+ errCode: null,
+ providerMsgId: null,
+ smtpUsername,
+ payloadJson,
+ cancellationToken);
+
+ private async Task WriteNotifyLogAsync(
+ Order order,
+ int customerId,
+ string channel,
+ string eventCode,
+ string? recipient,
+ string? templateRef,
+ string? subject,
+ string status,
+ string? errMsg,
+ int? errCode,
+ string? providerMsgId,
+ string? smtpUsername,
+ string? payloadJson,
+ CancellationToken cancellationToken)
{
try
{
- await logRepository.InsertAsync(
- new WechatNotifyLog
+ await notifyLogRepository.InsertAsync(
+ new OrderNotifyLog
{
CustomerId = customerId,
OrderId = order.Id,
+ Channel = channel,
EventCode = eventCode,
- OpenId = openId,
- TemplateId = templateId,
+ Recipient = Truncate(recipient, 256),
+ TemplateRef = Truncate(templateRef, 128),
+ Subject = Truncate(subject, 512),
Status = status,
- ErrMsg = Truncate(errMsg, 512),
+ ProviderMsgId = Truncate(providerMsgId, 64),
ErrCode = errCode,
- WxMsgId = wxMsgId,
+ ErrMsg = Truncate(errMsg, 512),
+ SmtpUsername = Truncate(smtpUsername, 256),
PayloadJson = payloadJson
},
cancellationToken: cancellationToken);
}
catch (Exception ex)
{
- logger.LogWarning(ex, "写微信通知日志失败 OrderId={OrderId}", order.Id);
+ logger.LogWarning(
+ ex,
+ "写订单通知日志失败 OrderId={OrderId} Channel={Channel}",
+ order.Id,
+ channel);
}
}
diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderOperationActionCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderOperationActionCodes.cs
index 12fded3..0cf26a9 100644
--- a/src/Oms.Domain/OrdersAggregate/Consts/OrderOperationActionCodes.cs
+++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderOperationActionCodes.cs
@@ -22,6 +22,12 @@ public static class OrderOperationActionCodes
/// 轨迹中心状态同步(TrackChange D03/D09/D11)。
public const string TrackStatusSync = "trackStatusSync";
+ /// 微信订单状态通知(模板消息)。
+ public const string NotifyWechat = "notifyWechat";
+
+ /// 邮件订单状态通知。
+ public const string NotifyEmail = "notifyEmail";
+
public static string GetActionName(string action) => action switch
{
EditBasic => "编辑订单详情",
@@ -41,6 +47,8 @@ public static class OrderOperationActionCodes
Outbound => "出库",
ChangePostShipStatus => "修改出库后状态",
TrackStatusSync => "轨迹状态同步",
+ NotifyWechat => "微信通知",
+ NotifyEmail => "邮件通知",
_ => action
};
}
diff --git a/src/Oms.Domain/SystemAggregate/Consts/OrderNotifyChannels.cs b/src/Oms.Domain/SystemAggregate/Consts/OrderNotifyChannels.cs
new file mode 100644
index 0000000..5c2e1ef
--- /dev/null
+++ b/src/Oms.Domain/SystemAggregate/Consts/OrderNotifyChannels.cs
@@ -0,0 +1,19 @@
+namespace Oms.Domain.SystemAggregate.Consts;
+
+/// 订单通知通道。
+public static class OrderNotifyChannels
+{
+ public const string Wechat = "wechat";
+
+ public const string Email = "email";
+
+ public static bool IsKnown(string? channel) =>
+ string.Equals(channel, Wechat, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(channel, Email, StringComparison.OrdinalIgnoreCase);
+
+ public static string Normalize(string channel) =>
+ string.Equals(channel, Email, StringComparison.OrdinalIgnoreCase) ? Email : Wechat;
+
+ public static string GetName(string channel) =>
+ string.Equals(Normalize(channel), Email, StringComparison.OrdinalIgnoreCase) ? "邮件" : "微信";
+}
diff --git a/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs b/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs
index 2ad9c7d..f2ac353 100644
--- a/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs
+++ b/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs
@@ -15,6 +15,9 @@ public class CustomerWechatNotifyPref : OmsAuditedAggregateRoot
/// 事件码。
public string EventCode { get; set; } = string.Empty;
- /// 是否订阅。
+ /// 是否订阅微信。
public bool IsSubscribed { get; set; }
+
+ /// 是否订阅邮件。
+ public bool IsEmailSubscribed { get; set; }
}
diff --git a/src/Oms.Domain/SystemAggregate/Entities/OrderNotifyLog.cs b/src/Oms.Domain/SystemAggregate/Entities/OrderNotifyLog.cs
new file mode 100644
index 0000000..34de21b
--- /dev/null
+++ b/src/Oms.Domain/SystemAggregate/Entities/OrderNotifyLog.cs
@@ -0,0 +1,54 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.SystemAggregate.Entities;
+
+///
+/// 订单通知发送日志(微信 / 邮件统一表)。
+///
+[SugarTable("t_order_notify_log")]
+public class OrderNotifyLog : OmsAuditedAggregateRoot
+{
+ public int CustomerId { get; set; }
+
+ public int OrderId { get; set; }
+
+ /// wechat / email。
+ [SugarColumn(Length = 16)]
+ public string Channel { get; set; } = "wechat";
+
+ public string EventCode { get; set; } = string.Empty;
+
+ /// OpenId 或收件邮箱。
+ [SugarColumn(IsNullable = true, Length = 256)]
+ public string? Recipient { get; set; }
+
+ /// 微信 TemplateId 或邮件模板名。
+ [SugarColumn(IsNullable = true, Length = 128)]
+ public string? TemplateRef { get; set; }
+
+ /// 邮件主题(微信可空)。
+ [SugarColumn(IsNullable = true, Length = 512)]
+ public string? Subject { get; set; }
+
+ /// sent / failed / skipped。
+ [SugarColumn(Length = 16)]
+ public string Status { get; set; } = "skipped";
+
+ /// 微信 msgid 等通道回执。
+ [SugarColumn(IsNullable = true, Length = 64)]
+ public string? ProviderMsgId { get; set; }
+
+ [SugarColumn(IsNullable = true)]
+ public int? ErrCode { get; set; }
+
+ [SugarColumn(IsNullable = true, Length = 512)]
+ public string? ErrMsg { get; set; }
+
+ /// 发件 SMTP 账号(邮件)。
+ [SugarColumn(IsNullable = true, Length = 256)]
+ public string? SmtpUsername { get; set; }
+
+ [SugarColumn(ColumnDataType = "text", IsNullable = true)]
+ public string? PayloadJson { get; set; }
+}
diff --git a/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs
deleted file mode 100644
index 43fbf6b..0000000
--- a/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Oms.Domain.Shared;
-using SqlSugar;
-
-namespace Oms.Domain.SystemAggregate.Entities;
-
-///
-/// 微信订单通知发送日志。
-///
-[SugarTable("t_wechat_notify_log")]
-public class WechatNotifyLog : OmsAuditedAggregateRoot
-{
- public int CustomerId { get; set; }
-
- public int OrderId { get; set; }
-
- public string EventCode { get; set; } = string.Empty;
-
- [SugarColumn(IsNullable = true, Length = 64)]
- public string? OpenId { get; set; }
-
- [SugarColumn(IsNullable = true, Length = 128)]
- public string? TemplateId { get; set; }
-
- /// sent / failed / skipped。
- public string Status { get; set; } = "skipped";
-
- [SugarColumn(IsNullable = true, Length = 64)]
- public string? WxMsgId { get; set; }
-
- [SugarColumn(IsNullable = true)]
- public int? ErrCode { get; set; }
-
- [SugarColumn(IsNullable = true, Length = 512)]
- public string? ErrMsg { get; set; }
-
- [SugarColumn(ColumnDataType = "text", IsNullable = true)]
- public string? PayloadJson { get; set; }
-}
diff --git a/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyTemplate.cs b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyTemplate.cs
index d48031d..d76bc44 100644
--- a/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyTemplate.cs
+++ b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyTemplate.cs
@@ -27,9 +27,24 @@ public class WechatNotifyTemplate : OmsAuditedAggregateRoot
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
public string? FieldMappingJson { get; set; }
- /// 是否启用。
+ /// 是否启用微信推送。
public bool IsEnabled { get; set; }
+ /// 是否启用邮件通知。
+ public bool EmailEnabled { get; set; }
+
+ /// 关联的 batch-email 模板名称。
+ [SugarColumn(IsNullable = true, Length = 128)]
+ public string? EmailTemplateName { get; set; }
+
+ /// batch-email 模板所属用户。
+ [SugarColumn(IsNullable = true)]
+ public int? EmailTemplateOwnerUserId { get; set; }
+
+ /// 发信 SMTP 所属用户;0 表示系统发信账号。
+ [SugarColumn(IsNullable = true)]
+ public int? EmailSmtpOwnerUserId { get; set; }
+
/// 备注。
[SugarColumn(IsNullable = true, Length = 512)]
public string? Remark { get; set; }
diff --git a/src/Oms.Domain/SystemAggregate/Repositories/IOrderNotifyLogRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/IOrderNotifyLogRepository.cs
new file mode 100644
index 0000000..d5bf951
--- /dev/null
+++ b/src/Oms.Domain/SystemAggregate/Repositories/IOrderNotifyLogRepository.cs
@@ -0,0 +1,24 @@
+using Fake.Domain.Repositories;
+using Oms.Domain.SystemAggregate.Entities;
+
+namespace Oms.Domain.SystemAggregate.Repositories;
+
+public interface IOrderNotifyLogRepository : IRepository
+{
+ ///
+ /// 是否存在近期同订单同事件同通道的成功发送(用于去重;不含 failed)。
+ ///
+ Task ExistsRecentSentAsync(
+ int orderId,
+ string eventCode,
+ string channel,
+ DateTime since,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// 按订单查询通知日志(时间倒序)。
+ ///
+ Task> ListByOrderIdAsync(
+ int orderId,
+ CancellationToken cancellationToken = default);
+}
diff --git a/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs
deleted file mode 100644
index 7394695..0000000
--- a/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using Fake.Domain.Repositories;
-using Oms.Domain.SystemAggregate.Entities;
-
-namespace Oms.Domain.SystemAggregate.Repositories;
-
-public interface IWechatNotifyLogRepository : IRepository
-{
- ///
- /// 是否存在近期同订单同事件的成功/进行中记录(用于去重)。
- ///
- Task ExistsRecentAsync(
- int orderId,
- string eventCode,
- DateTime since,
- CancellationToken cancellationToken = default);
-}
diff --git a/src/Oms.SqlSugarCore/System/OrderNotifyLogRepository.cs b/src/Oms.SqlSugarCore/System/OrderNotifyLogRepository.cs
new file mode 100644
index 0000000..300cf77
--- /dev/null
+++ b/src/Oms.SqlSugarCore/System/OrderNotifyLogRepository.cs
@@ -0,0 +1,41 @@
+using Fake.DependencyInjection;
+using Oms.Domain.SystemAggregate.Entities;
+using Oms.Domain.SystemAggregate.Repositories;
+using Oms.SqlSugarCore.Repositories;
+
+namespace Oms.SqlSugarCore.System;
+
+public class OrderNotifyLogRepository
+ : OmsSqlSugarRepository,
+ IOrderNotifyLogRepository,
+ IScopedDependency
+{
+ public async Task ExistsRecentSentAsync(
+ int orderId,
+ string eventCode,
+ string channel,
+ DateTime since,
+ CancellationToken cancellationToken = default)
+ {
+ var code = eventCode.Trim();
+ var ch = channel.Trim();
+ return await AnyAsync(
+ x => x.OrderId == orderId
+ && x.EventCode == code
+ && x.Channel == ch
+ && x.CreateTime >= since
+ && x.Status == "sent",
+ cancellationToken);
+ }
+
+ public async Task> ListByOrderIdAsync(
+ int orderId,
+ CancellationToken cancellationToken = default)
+ {
+ var list = await GetListAsync(x => x.OrderId == orderId, cancellationToken: cancellationToken);
+ return list
+ .OrderByDescending(x => x.CreateTime)
+ .ThenByDescending(x => x.Id)
+ .ToList();
+ }
+}
diff --git a/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs b/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs
deleted file mode 100644
index ccf989c..0000000
--- a/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using Fake.DependencyInjection;
-using Oms.Domain.SystemAggregate.Entities;
-using Oms.Domain.SystemAggregate.Repositories;
-using Oms.SqlSugarCore.Repositories;
-
-namespace Oms.SqlSugarCore.System;
-
-public class WechatNotifyLogRepository
- : OmsSqlSugarRepository,
- IWechatNotifyLogRepository,
- IScopedDependency
-{
- public async Task ExistsRecentAsync(
- int orderId,
- string eventCode,
- DateTime since,
- CancellationToken cancellationToken = default)
- {
- var code = eventCode.Trim();
- return await AnyAsync(
- x => x.OrderId == orderId
- && x.EventCode == code
- && x.CreateTime >= since
- && (x.Status == "sent" || x.Status == "failed"),
- cancellationToken);
- }
-}