feat: 订单通知加固(邮件订阅、统一日志、Outbox 重试与系统 SMTP)
All checks were successful
Build and Deploy / deploy (push) Successful in 1m19s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m19s
合并微信/邮件通知日志,支持 H5 双通道订阅、系统发信与操作日志摘要;上线前执行 sql/migrate_order_notify_all_20261121.sql。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
569efca710
commit
7940b50edf
36
db.sql
36
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 '主键',
|
||||
|
||||
175
sql/migrate_order_notify_all_20261121.sql
Normal file
175
sql/migrate_order_notify_all_20261121.sql
Normal file
@ -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;
|
||||
@ -1,11 +1,14 @@
|
||||
namespace Oms.Application.Dtos.Customers;
|
||||
|
||||
/// <summary>客户微信通知前置状态 + 订阅项。</summary>
|
||||
/// <summary>客户订单通知前置状态 + 订阅项(微信 / 邮件)。</summary>
|
||||
public class CustomerWechatNotifyStatusOutput
|
||||
{
|
||||
/// <summary>是否已绑定微信 OpenId。</summary>
|
||||
public bool HasOpenId { get; set; }
|
||||
|
||||
/// <summary>是否已配置客户邮箱。</summary>
|
||||
public bool HasEmail { get; set; }
|
||||
|
||||
/// <summary>是否已配置公众号关注跳转(仅提示用)。</summary>
|
||||
public bool HasFollowUrl { get; set; }
|
||||
|
||||
@ -20,11 +23,17 @@ public class CustomerWechatNotifyPrefItemOutput
|
||||
|
||||
public string EventName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>运营是否已启用该事件模板。</summary>
|
||||
/// <summary>运营是否已启用微信模板。</summary>
|
||||
public bool OpsEnabled { get; set; }
|
||||
|
||||
/// <summary>客户是否订阅。</summary>
|
||||
/// <summary>运营是否已启用邮件。</summary>
|
||||
public bool OpsEmailEnabled { get; set; }
|
||||
|
||||
/// <summary>客户是否订阅微信。</summary>
|
||||
public bool IsSubscribed { get; set; }
|
||||
|
||||
/// <summary>客户是否订阅邮件。</summary>
|
||||
public bool IsEmailSubscribed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存客户订阅。</summary>
|
||||
@ -38,4 +47,6 @@ public class SaveCustomerWechatNotifyPrefItemInput
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
public bool IsSubscribed { get; set; }
|
||||
|
||||
public bool IsEmailSubscribed { get; set; }
|
||||
}
|
||||
|
||||
49
src/Oms.Application/Dtos/Orders/OrderNotifyLogDtos.cs
Normal file
49
src/Oms.Application/Dtos/Orders/OrderNotifyLogDtos.cs
Normal file
@ -0,0 +1,49 @@
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
/// <summary>订单通知日志条目(微信 / 邮件)。</summary>
|
||||
public class OrderNotifyLogOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
/// <summary>wechat / email。</summary>
|
||||
public string Channel { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>微信 / 邮件。</summary>
|
||||
public string ChannelName { get; set; } = string.Empty;
|
||||
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
public string EventName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>OpenId 或邮箱。</summary>
|
||||
public string? Recipient { get; set; }
|
||||
|
||||
public string? TemplateRef { get; set; }
|
||||
|
||||
public string? Subject { get; set; }
|
||||
|
||||
/// <summary>sent / failed / skipped。</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>列表「内容」摘要。</summary>
|
||||
public string Summary { get; set; } = string.Empty;
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
}
|
||||
|
||||
public class OrderNotifyLogListOutput
|
||||
{
|
||||
public List<OrderNotifyLogOutput> Items { get; set; } = [];
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>微信订单通知模板配置输出。</summary>
|
||||
/// <summary>订单通知模板配置输出(微信 + 邮件)。</summary>
|
||||
public class WechatOrderNotifyTemplateOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
@ -20,14 +20,29 @@ public class WechatOrderNotifyTemplateOutput
|
||||
/// <summary>字段映射 JSON。</summary>
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
/// <summary>是否启用微信推送。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>是否启用邮件通知。</summary>
|
||||
public bool EmailEnabled { get; set; }
|
||||
|
||||
/// <summary>batch-email 模板名称。</summary>
|
||||
public string? EmailTemplateName { get; set; }
|
||||
|
||||
/// <summary>batch-email 模板所属用户。</summary>
|
||||
public int? EmailTemplateOwnerUserId { get; set; }
|
||||
|
||||
/// <summary>发信 SMTP 所属用户;0 表示系统发信账号。</summary>
|
||||
public int? EmailSmtpOwnerUserId { get; set; }
|
||||
|
||||
/// <summary>是否使用系统发信 SMTP。</summary>
|
||||
public bool EmailUseSystemSmtp { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存微信订单通知模板。</summary>
|
||||
/// <summary>保存订单通知模板。</summary>
|
||||
public class SaveWechatOrderNotifyTemplateInput
|
||||
{
|
||||
/// <summary>事件码。</summary>
|
||||
@ -42,13 +57,35 @@ public class SaveWechatOrderNotifyTemplateInput
|
||||
/// <summary>字段映射 JSON。</summary>
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
/// <summary>是否启用微信推送。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>是否启用邮件通知。</summary>
|
||||
public bool EmailEnabled { get; set; }
|
||||
|
||||
/// <summary>batch-email 模板名称(启用邮件时必填)。</summary>
|
||||
public string? EmailTemplateName { get; set; }
|
||||
|
||||
/// <summary>是否使用系统发信 SMTP(OwnerUserId=0)。</summary>
|
||||
public bool EmailUseSystemSmtp { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>系统发信 SMTP 状态。</summary>
|
||||
public class OrderNotifySystemSmtpStatusOutput
|
||||
{
|
||||
/// <summary>是否已配置系统 SMTP(OwnerUserId=0)。</summary>
|
||||
public bool Configured { get; set; }
|
||||
|
||||
/// <summary>发件账号(脱敏场景仍返回用户名)。</summary>
|
||||
public string? SmtpUsername { get; set; }
|
||||
|
||||
/// <summary>发件人显示名。</summary>
|
||||
public string? FromName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>试发入参。</summary>
|
||||
public class TrialWechatOrderNotifyInput
|
||||
{
|
||||
@ -62,10 +99,10 @@ public class TrialWechatOrderNotifyInput
|
||||
public string? ServiceNo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>试发结果(含请求/响应明细,供运营排查)。</summary>
|
||||
/// <summary>试发结果(含微信/邮件请求响应明细)。</summary>
|
||||
public class TrialWechatOrderNotifyResultOutput
|
||||
{
|
||||
/// <summary>是否最终发送成功。</summary>
|
||||
/// <summary>是否最终发送成功(微信成功即 true;邮件结果见 Email)。</summary>
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>是否跳过发送(未启用/未绑 OpenId 等)。</summary>
|
||||
@ -112,4 +149,38 @@ public class TrialWechatOrderNotifyResultOutput
|
||||
|
||||
/// <summary>微信 errcode。</summary>
|
||||
public int? ErrCode { get; set; }
|
||||
|
||||
/// <summary>邮件通道试发结果。</summary>
|
||||
public TrialOrderNotifyEmailResultOutput? Email { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>订单通知邮件试发明细。</summary>
|
||||
public class TrialOrderNotifyEmailResultOutput
|
||||
{
|
||||
/// <summary>是否发送成功。</summary>
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>是否跳过。</summary>
|
||||
public bool Skipped { get; set; }
|
||||
|
||||
/// <summary>状态:sent / failed / skipped。</summary>
|
||||
public string Status { get; set; } = "skipped";
|
||||
|
||||
/// <summary>说明。</summary>
|
||||
public string? Message { get; set; }
|
||||
|
||||
/// <summary>收件邮箱。</summary>
|
||||
public string? ToEmail { get; set; }
|
||||
|
||||
/// <summary>模板名称。</summary>
|
||||
public string? TemplateName { get; set; }
|
||||
|
||||
/// <summary>替换后主题。</summary>
|
||||
public string? Subject { get; set; }
|
||||
|
||||
/// <summary>替换后正文。</summary>
|
||||
public string? Body { get; set; }
|
||||
|
||||
/// <summary>发件 SMTP 账号。</summary>
|
||||
public string? SmtpUsername { get; set; }
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
/// <summary>消费订单通知异步任务(微信 + 邮件)。</summary>
|
||||
public sealed class OrderNotifyEventHandler(
|
||||
IOrderRepository orderRepository,
|
||||
WechatOrderNotifyDispatcher notifyDispatcher,
|
||||
IUnitOfWorkManager unitOfWorkManager,
|
||||
ILogger<OrderNotifyEventHandler> logger)
|
||||
: IEventHandler<OrderNotifyIntegrationEvent>, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
using Fake.EventBus.Distributed;
|
||||
|
||||
namespace Oms.Application.Messaging.OrderSideEffects;
|
||||
|
||||
/// <summary>
|
||||
/// 订单状态通知(微信模板 + 邮件),走 Fake.EventBus Outbox。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class OrderNotifyIntegrationEvent : IntegrationEvent
|
||||
{
|
||||
public int OrderId { get; set; }
|
||||
|
||||
/// <summary>事件码,见 <see cref="Domain.SystemAggregate.Consts.WechatOrderNotifyEventCodes"/>。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>可选备注(问题件说明等)。</summary>
|
||||
public string? Remark { get; set; }
|
||||
|
||||
/// <summary>试发/强制:跳过客户订阅与去重(微信)。</summary>
|
||||
public bool Force { get; set; }
|
||||
}
|
||||
@ -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,
|
||||
|
||||
@ -10,7 +10,7 @@ using Oms.Domain.SystemAggregate.Repositories;
|
||||
namespace Oms.Application.Services.Customers;
|
||||
|
||||
/// <summary>
|
||||
/// 客户微信订单通知订阅(H5/门户)。
|
||||
/// 客户订单通知订阅(微信 / 邮件;H5/门户)。
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
@ -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<InboundRecord, InboundRecordOutput>(savedEntity);
|
||||
|
||||
@ -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<OutboundRecord, OutboundRecordOutput>(savedEntity);
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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<IOrderNotifyLogRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 运单通知日志列表(微信 / 邮件;按时间倒序)。
|
||||
/// </summary>
|
||||
/// <param name="orderId">订单 Id。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
[HttpGet("/order/notify-log/list")]
|
||||
public async Task<OrderNotifyLogListOutput> 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<string> { $"{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()
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1356,7 +1356,7 @@ public partial class OrderService
|
||||
|
||||
if (becamePendingPayment)
|
||||
{
|
||||
await WechatOrderNotifyDispatcher.TryNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
|
||||
await WechatOrderNotifyDispatcher.EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单通知模板配置(系统其他配置入口使用)。
|
||||
/// 订单通知模板配置(微信 + 邮件;系统其他配置入口使用)。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-System")]
|
||||
public class WechatOrderNotifyConfigService : ApplicationService
|
||||
{
|
||||
/// <summary>系统发信 SMTP 的 OwnerUserId。</summary>
|
||||
public const int SystemSmtpOwnerUserId = 0;
|
||||
|
||||
private IWechatNotifyTemplateRepository TemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWechatNotifyTemplateRepository>();
|
||||
|
||||
private ISystemBatchEmailTemplateRepository BatchEmailTemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISystemBatchEmailTemplateRepository>();
|
||||
|
||||
private ISystemBatchEmailAccountRepository BatchEmailAccountRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISystemBatchEmailAccountRepository>();
|
||||
|
||||
private IOrderRepository OrderRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||||
|
||||
@ -62,6 +72,41 @@ public class WechatOrderNotifyConfigService : ApplicationService
|
||||
var name = WechatOrderNotifyEventCodes.GetName(code) ?? code;
|
||||
await EnsureSeedAsync(cancellationToken);
|
||||
|
||||
var ownerUserId = CurrentUser.GetId<int>();
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId);返回请求/响应明细。
|
||||
/// 查询系统发信 SMTP 是否已配置。
|
||||
/// </summary>
|
||||
[HttpGet("/system/wechat-order-notify/system-smtp")]
|
||||
public async Task<OrderNotifySystemSmtpStatusOutput> 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存系统发信 SMTP(OwnerUserId=0,与配置操作人解耦)。
|
||||
/// </summary>
|
||||
[HttpPost("/system/wechat-order-notify/system-smtp/save")]
|
||||
public async Task<OrderNotifySystemSmtpStatusOutput> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按订单试发(微信 + 邮件);跳过客户订阅与去重,返回请求/响应明细。
|
||||
/// </summary>
|
||||
[HttpPost("/system/wechat-order-notify/trial-send")]
|
||||
public async Task<TrialWechatOrderNotifyResultOutput> 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();
|
||||
}
|
||||
|
||||
@ -0,0 +1,12 @@
|
||||
namespace Oms.Application.Services.WeChatNotify;
|
||||
|
||||
/// <summary>
|
||||
/// 订单通知可重试失败(token/SMTP 临时故障等);Outbox 消费者应 Nack/重投。
|
||||
/// </summary>
|
||||
public sealed class OrderNotifyRetryableException : Exception
|
||||
{
|
||||
public OrderNotifyRetryableException(string message, Exception? inner = null)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单状态通知调度:校验运营启用 + 客户订阅 + openid,组包发送并写日志。
|
||||
/// 订单状态通知调度:微信模板消息 + batch-email 邮件;业务侧优先 Outbox 异步投递。
|
||||
/// </summary>
|
||||
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<WechatOrderNotifyDispatcher> logger) : IScopedDependency
|
||||
{
|
||||
private const string WechatTemplateSendUrl =
|
||||
@ -29,19 +46,107 @@ public class WechatOrderNotifyDispatcher(
|
||||
|
||||
private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30);
|
||||
|
||||
/// <summary>微信侧可重试 errcode(token/系统繁忙等)。</summary>
|
||||
private static readonly HashSet<int> WechatRetryableErrCodes =
|
||||
[
|
||||
-1,
|
||||
40001,
|
||||
42001,
|
||||
45009,
|
||||
45011
|
||||
];
|
||||
|
||||
/// <summary>未关注 / 拒收模板等业务失败(勿重试)。</summary>
|
||||
private static readonly HashSet<int> WechatUnfollowErrCodes =
|
||||
[
|
||||
43004,
|
||||
43101
|
||||
];
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 尝试按事件发送;任何失败只记日志,不抛给业务主流程。
|
||||
/// 投递订单通知(微信 + 邮件)。有事务 UoW 时写 Outbox;否则同步兜底。
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 出库通知统一入口(扫码出库 / 装袋出库共用;幂等靠 30 分钟 sent 去重)。
|
||||
/// </summary>
|
||||
public Task EnqueueOutboundNotifyAsync(
|
||||
Order order,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.Outbound, cancellationToken: cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 按 OrderId 投递(消费者/无实体场景)。
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步发送(试发 / Outbox 消费者 / 无队列兜底);失败只记日志。
|
||||
/// </summary>
|
||||
/// <param name="order">订单。</param>
|
||||
/// <param name="eventCode">事件码。</param>
|
||||
/// <param name="remark">可选备注(问题件说明等)。</param>
|
||||
/// <param name="force">试发时跳过订阅与去重。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运营试发:返回请求/响应明细;业务跳过/失败不抛,异常仍向上抛。
|
||||
/// 运营试发 / 明细发送:微信 + 邮件;业务跳过/失败写入结果。
|
||||
/// 可重试失败抛 <see cref="OrderNotifyRetryableException"/>(force 试发除外)。
|
||||
/// </summary>
|
||||
public Task<TrialWechatOrderNotifyResultOutput> NotifyDetailedAsync(
|
||||
public async Task<TrialWechatOrderNotifyResultOutput> 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<TrialWechatOrderNotifyResultOutput> NotifyCoreAsync(
|
||||
if (!force && IsRetryableTransport(ex))
|
||||
{
|
||||
throw new OrderNotifyRetryableException($"邮件发送临时失败:{ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (!force)
|
||||
{
|
||||
ThrowIfRetryableWechatFailure(result);
|
||||
ThrowIfRetryableEmailFailure(result.Email);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<TrialWechatOrderNotifyResultOutput> 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<TrialOrderNotifyEmailResultOutput> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅 sent/failed 写入订单操作日志(skipped 不写,避免刷屏)。
|
||||
/// </summary>
|
||||
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<string>
|
||||
{
|
||||
$"{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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 替换邮件占位符:支持 batch-email 中文词 + OMS 英文字段。
|
||||
/// </summary>
|
||||
private static string ApplyEmailPlaceholders(
|
||||
string template,
|
||||
IReadOnlyDictionary<string, string> 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<string, string> BuildPlaceholders(
|
||||
private async Task<Dictionary<string, string>> 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<string, string>(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<string> 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<OpenApiTrackEventDto> 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -22,6 +22,12 @@ public static class OrderOperationActionCodes
|
||||
/// <summary>轨迹中心状态同步(TrackChange D03/D09/D11)。</summary>
|
||||
public const string TrackStatusSync = "trackStatusSync";
|
||||
|
||||
/// <summary>微信订单状态通知(模板消息)。</summary>
|
||||
public const string NotifyWechat = "notifyWechat";
|
||||
|
||||
/// <summary>邮件订单状态通知。</summary>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
19
src/Oms.Domain/SystemAggregate/Consts/OrderNotifyChannels.cs
Normal file
19
src/Oms.Domain/SystemAggregate/Consts/OrderNotifyChannels.cs
Normal file
@ -0,0 +1,19 @@
|
||||
namespace Oms.Domain.SystemAggregate.Consts;
|
||||
|
||||
/// <summary>订单通知通道。</summary>
|
||||
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) ? "邮件" : "微信";
|
||||
}
|
||||
@ -15,6 +15,9 @@ public class CustomerWechatNotifyPref : OmsAuditedAggregateRoot
|
||||
/// <summary>事件码。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否订阅。</summary>
|
||||
/// <summary>是否订阅微信。</summary>
|
||||
public bool IsSubscribed { get; set; }
|
||||
|
||||
/// <summary>是否订阅邮件。</summary>
|
||||
public bool IsEmailSubscribed { get; set; }
|
||||
}
|
||||
|
||||
54
src/Oms.Domain/SystemAggregate/Entities/OrderNotifyLog.cs
Normal file
54
src/Oms.Domain/SystemAggregate/Entities/OrderNotifyLog.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 订单通知发送日志(微信 / 邮件统一表)。
|
||||
/// </summary>
|
||||
[SugarTable("t_order_notify_log")]
|
||||
public class OrderNotifyLog : OmsAuditedAggregateRoot
|
||||
{
|
||||
public int CustomerId { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
/// <summary>wechat / email。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string Channel { get; set; } = "wechat";
|
||||
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>OpenId 或收件邮箱。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 256)]
|
||||
public string? Recipient { get; set; }
|
||||
|
||||
/// <summary>微信 TemplateId 或邮件模板名。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 128)]
|
||||
public string? TemplateRef { get; set; }
|
||||
|
||||
/// <summary>邮件主题(微信可空)。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 512)]
|
||||
public string? Subject { get; set; }
|
||||
|
||||
/// <summary>sent / failed / skipped。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string Status { get; set; } = "skipped";
|
||||
|
||||
/// <summary>微信 msgid 等通道回执。</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>发件 SMTP 账号(邮件)。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 256)]
|
||||
public string? SmtpUsername { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? PayloadJson { get; set; }
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单通知发送日志。
|
||||
/// </summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>sent / failed / skipped。</summary>
|
||||
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; }
|
||||
}
|
||||
@ -27,9 +27,24 @@ public class WechatNotifyTemplate : OmsAuditedAggregateRoot
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
/// <summary>是否启用微信推送。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>是否启用邮件通知。</summary>
|
||||
public bool EmailEnabled { get; set; }
|
||||
|
||||
/// <summary>关联的 batch-email 模板名称。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 128)]
|
||||
public string? EmailTemplateName { get; set; }
|
||||
|
||||
/// <summary>batch-email 模板所属用户。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? EmailTemplateOwnerUserId { get; set; }
|
||||
|
||||
/// <summary>发信 SMTP 所属用户;0 表示系统发信账号。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? EmailSmtpOwnerUserId { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 512)]
|
||||
public string? Remark { get; set; }
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
public interface IOrderNotifyLogRepository : IRepository<OrderNotifyLog>
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否存在近期同订单同事件同通道的成功发送(用于去重;不含 failed)。
|
||||
/// </summary>
|
||||
Task<bool> ExistsRecentSentAsync(
|
||||
int orderId,
|
||||
string eventCode,
|
||||
string channel,
|
||||
DateTime since,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 按订单查询通知日志(时间倒序)。
|
||||
/// </summary>
|
||||
Task<List<OrderNotifyLog>> ListByOrderIdAsync(
|
||||
int orderId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
public interface IWechatNotifyLogRepository : IRepository<WechatNotifyLog>
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否存在近期同订单同事件的成功/进行中记录(用于去重)。
|
||||
/// </summary>
|
||||
Task<bool> ExistsRecentAsync(
|
||||
int orderId,
|
||||
string eventCode,
|
||||
DateTime since,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
41
src/Oms.SqlSugarCore/System/OrderNotifyLogRepository.cs
Normal file
41
src/Oms.SqlSugarCore/System/OrderNotifyLogRepository.cs
Normal file
@ -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<OrderNotifyLog>,
|
||||
IOrderNotifyLogRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
public async Task<bool> 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<List<OrderNotifyLog>> 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();
|
||||
}
|
||||
}
|
||||
@ -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<WechatNotifyLog>,
|
||||
IWechatNotifyLogRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
public async Task<bool> 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);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user