diff --git a/db.sql b/db.sql index e11855c..074a7ba 100644 --- a/db.sql +++ b/db.sql @@ -62,6 +62,9 @@ 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_wechat_notify_log`; +DROP TABLE IF EXISTS `t_customer_wechat_notify_pref`; +DROP TABLE IF EXISTS `t_wechat_notify_template`; DROP TABLE IF EXISTS `t_system_other_config`; DROP TABLE IF EXISTS `t_warehouse_address`; DROP TABLE IF EXISTS `t_notice_read`; @@ -1205,6 +1208,66 @@ CREATE TABLE `t_system_other_config` ( KEY `idx_system_other_config_enabled` (`Enabled`, `Id`) ) COMMENT='系统其他配置表'; +CREATE TABLE `t_wechat_notify_template` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1', + `EventCode` VARCHAR(32) NOT NULL COMMENT '事件码:inbound/outbound/deliverySuccess/deliveryFailed/problematic', + `EventName` VARCHAR(64) NOT NULL COMMENT '事件显示名', + `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-是', + `Remark` VARCHAR(512) 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_wechat_notify_tpl_event` (`EventCode`), + KEY `ix_wechat_notify_tpl_enabled` (`IsEnabled`, `Id`) +) 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-是', + `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_cus_wechat_notify_pref_cus` (`CustomerId`, `EventCode`), + KEY `ix_cus_wechat_notify_pref_event` (`EventCode`, `IsSubscribed`) +) COMMENT='客户微信订单通知订阅偏好'; + +CREATE TABLE `t_wechat_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', + `EventCode` VARCHAR(32) NOT NULL COMMENT '事件码', + `OpenId` VARCHAR(64) NULL COMMENT '接收 openid', + `TemplateId` VARCHAR(128) NULL COMMENT '模板 Id', + `Status` VARCHAR(16) NOT NULL DEFAULT 'skipped' COMMENT 'sent/failed/skipped', + `WxMsgId` VARCHAR(64) NULL COMMENT '微信 msgid', + `ErrCode` INT NULL COMMENT '微信/业务错误码', + `ErrMsg` VARCHAR(512) NULL COMMENT '错误或跳过原因', + `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_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='微信订单通知发送日志'; + CREATE TABLE `t_system_batch_email_template` ( `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', `OwnerUserId` INT NOT NULL DEFAULT 0 COMMENT '所属 RBAC 用户 Id', diff --git a/sql/migrate_wechat_order_notify_20261115.sql b/sql/migrate_wechat_order_notify_20261115.sql new file mode 100644 index 0000000..d9c1df8 --- /dev/null +++ b/sql/migrate_wechat_order_notify_20261115.sql @@ -0,0 +1,103 @@ +-- ============================================================================= +-- migrate_wechat_order_notify_20261115.sql +-- 微信公众号订单状态通知:模板配置 / 客户订阅偏好 / 发送日志 +-- 审计字段对齐 t_outbound_record(定死): +-- IsDeleted TINYINT NOT NULL DEFAULT 0 +-- ConcurrencyStamp CHAR(36) NOT NULL DEFAULT (UUID()) +-- CreateUserId INT NOT NULL DEFAULT 0 +-- CreateTime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +-- UpdateUserId INT NULL +-- UpdateTime DATETIME NULL +-- 禁止 UNIQUE KEY;唯一性业务侧校验。可重复执行。 +-- ============================================================================= +SET @db := DATABASE(); + +-- ---------- t_wechat_notify_template ---------- +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_wechat_notify_template' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_wechat_notify_template` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'', + `EventCode` VARCHAR(32) NOT NULL COMMENT ''事件码:inbound/outbound/deliverySuccess/deliveryFailed/problematic'', + `EventName` VARCHAR(64) NOT NULL COMMENT ''事件显示名'', + `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-是'', + `Remark` VARCHAR(512) 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_wechat_notify_tpl_event` (`EventCode`), + KEY `ix_wechat_notify_tpl_enabled` (`IsEnabled`, `Id`) + ) COMMENT=''微信订单通知模板配置''', + 'SELECT ''t_wechat_notify_template already exists'' AS info' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ---------- t_customer_wechat_notify_pref ---------- +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_customer_wechat_notify_pref' +); +SET @sql := IF( + @tbl = 0, + '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-是'', + `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_cus_wechat_notify_pref_cus` (`CustomerId`, `EventCode`), + KEY `ix_cus_wechat_notify_pref_event` (`EventCode`, `IsSubscribed`) + ) COMMENT=''客户微信订单通知订阅偏好''', + 'SELECT ''t_customer_wechat_notify_pref already exists'' AS info' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ---------- t_wechat_notify_log ---------- +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_wechat_notify_log' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_wechat_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'', + `EventCode` VARCHAR(32) NOT NULL COMMENT ''事件码'', + `OpenId` VARCHAR(64) NULL COMMENT ''接收 openid'', + `TemplateId` VARCHAR(128) NULL COMMENT ''模板 Id'', + `Status` VARCHAR(16) NOT NULL DEFAULT ''skipped'' COMMENT ''sent/failed/skipped'', + `WxMsgId` VARCHAR(64) NULL COMMENT ''微信 msgid'', + `ErrCode` INT NULL COMMENT ''微信/业务错误码'', + `ErrMsg` VARCHAR(512) NULL COMMENT ''错误或跳过原因'', + `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_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=''微信订单通知发送日志''', + 'SELECT ''t_wechat_notify_log already exists'' AS info' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs b/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs new file mode 100644 index 0000000..d1f8723 --- /dev/null +++ b/src/Oms.Application/Dtos/Customers/CustomerWechatNotifyDtos.cs @@ -0,0 +1,41 @@ +namespace Oms.Application.Dtos.Customers; + +/// 客户微信通知前置状态 + 订阅项。 +public class CustomerWechatNotifyStatusOutput +{ + /// 是否已绑定微信 OpenId。 + public bool HasOpenId { get; set; } + + /// 是否已配置公众号关注跳转(仅提示用)。 + public bool HasFollowUrl { get; set; } + + /// 各事件订阅状态(默认未订阅)。 + public List Items { get; set; } = []; +} + +/// 单事件订阅项。 +public class CustomerWechatNotifyPrefItemOutput +{ + public string EventCode { get; set; } = string.Empty; + + public string EventName { get; set; } = string.Empty; + + /// 运营是否已启用该事件模板。 + public bool OpsEnabled { get; set; } + + /// 客户是否订阅。 + public bool IsSubscribed { get; set; } +} + +/// 保存客户订阅。 +public class SaveCustomerWechatNotifyPrefInput +{ + public List Items { get; set; } = []; +} + +public class SaveCustomerWechatNotifyPrefItemInput +{ + public string EventCode { get; set; } = string.Empty; + + public bool IsSubscribed { get; set; } +} diff --git a/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs new file mode 100644 index 0000000..c285e2d --- /dev/null +++ b/src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs @@ -0,0 +1,63 @@ +namespace Oms.Application.Dtos.System; + +/// 微信订单通知模板配置输出。 +public class WechatOrderNotifyTemplateOutput +{ + public int Id { get; set; } + + /// 事件码。 + public string EventCode { get; set; } = string.Empty; + + /// 事件名。 + public string EventName { get; set; } = string.Empty; + + /// 微信模板 ID。 + public string? TemplateId { get; set; } + + /// 跳转 URL 模板。 + public string? UrlTemplate { get; set; } + + /// 字段映射 JSON。 + public string? FieldMappingJson { get; set; } + + /// 是否启用。 + public bool IsEnabled { get; set; } + + /// 备注。 + public string? Remark { get; set; } +} + +/// 保存微信订单通知模板。 +public class SaveWechatOrderNotifyTemplateInput +{ + /// 事件码。 + public string EventCode { get; set; } = string.Empty; + + /// 微信模板 ID。 + public string? TemplateId { get; set; } + + /// 跳转 URL 模板。 + public string? UrlTemplate { get; set; } + + /// 字段映射 JSON。 + public string? FieldMappingJson { get; set; } + + /// 是否启用。 + public bool IsEnabled { get; set; } + + /// 备注。 + public string? Remark { get; set; } +} + +/// 试发入参。 +public class TrialWechatOrderNotifyInput +{ + /// 事件码。 + public string EventCode { get; set; } = string.Empty; + + /// 订单 Id(优先)。 + public int? OrderId { get; set; } + + /// 运单号(OrderId 为空时使用)。 + public string? ServiceNo { get; set; } +} diff --git a/src/Oms.Application/Integrations/WeChat/IWeChatMpTemplateSender.cs b/src/Oms.Application/Integrations/WeChat/IWeChatMpTemplateSender.cs new file mode 100644 index 0000000..48a5f2f --- /dev/null +++ b/src/Oms.Application/Integrations/WeChat/IWeChatMpTemplateSender.cs @@ -0,0 +1,21 @@ +namespace Oms.Application.Integrations.WeChat; + +/// +/// 公众号模板消息发送(由 Api 宿主实现,复用 access_token)。 +/// +public interface IWeChatMpTemplateSender +{ + /// + /// 发送模板消息;失败不抛,返回 errcode/errmsg。 + /// + Task SendAsync( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data, + CancellationToken cancellationToken = default); +} + +public sealed record WeChatMpTemplateDataItem(string Value, string? Color = null); + +public sealed record WeChatMpTemplateSendResult(bool Success, string? MsgId, int ErrCode, string? ErrMsg); diff --git a/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs b/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs index 9a973e6..0ca24e8 100644 --- a/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs +++ b/src/Oms.Application/Messaging/TrackChange/TrackChangeOrderStatusApplier.cs @@ -4,9 +4,11 @@ using Fake.UnitOfWork; using Microsoft.Extensions.Logging; using Oms.Application.Messaging.Agents; using Oms.Application.Services.Orders; +using Oms.Application.Services.WeChatNotify; using Oms.Application.Shared; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; namespace Oms.Application.Messaging.TrackChange; @@ -20,6 +22,7 @@ public sealed class TrackChangeOrderStatusApplier( ReferralCommissionManager referralCommissionManager, IDistributedEventBus eventBus, MarketingCouponManager marketingCouponManager, + WechatOrderNotifyDispatcher wechatOrderNotifyDispatcher, IUnitOfWorkManager unitOfWorkManager, ILogger logger) : ITrackChangeOrderStatusApplier, IScopedDependency { @@ -172,6 +175,21 @@ public sealed class TrackChangeOrderStatusApplier( await unitOfWork.CompleteAsync(cancellationToken); + if (string.Equals(targetStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)) + { + await wechatOrderNotifyDispatcher.TryNotifyAsync( + order, + WechatOrderNotifyEventCodes.DeliverySuccess, + cancellationToken: cancellationToken); + } + else if (string.Equals(targetStatus, OrderStatusCodes.DeliveryFailed, StringComparison.OrdinalIgnoreCase)) + { + await wechatOrderNotifyDispatcher.TryNotifyAsync( + order, + WechatOrderNotifyEventCodes.DeliveryFailed, + cancellationToken: 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 new file mode 100644 index 0000000..f82ce9e --- /dev/null +++ b/src/Oms.Application/Services/Customers/CustomerWechatNotifyService.cs @@ -0,0 +1,125 @@ +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Customers; +using Oms.Domain.CustomersAggregate.Entities; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; +using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.Customers; + +/// +/// 客户微信订单通知订阅(H5/门户)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Customer")] +public class CustomerWechatNotifyService : ApplicationService +{ + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerWechatNotifyPrefRepository PrefRepository => + LazyServiceProvider.GetRequiredService(); + + private IWechatNotifyTemplateRepository TemplateRepository => + LazyServiceProvider.GetRequiredService(); + + private ISystemOtherConfigRepository OtherConfigRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 当前客户订阅状态与前置条件。 + /// + [HttpGet("/customer/wechat-notify/status")] + public async Task GetStatusAsync( + CancellationToken cancellationToken = default) + { + var customer = await GetCurrentCustomerOrThrowAsync(cancellationToken); + var prefs = await PrefRepository.ListByCustomerIdAsync(customer.Id, cancellationToken); + var prefMap = prefs.ToDictionary(x => x.EventCode, StringComparer.OrdinalIgnoreCase); + var templates = await TemplateRepository.GetAllAsync(cancellationToken); + var tplMap = templates.ToDictionary(x => x.EventCode, StringComparer.OrdinalIgnoreCase); + + var follow = await OtherConfigRepository.GetByConfigCodeAsync( + SystemOtherConfigCodes.WeChatMpFollow, + cancellationToken); + + return new CustomerWechatNotifyStatusOutput + { + HasOpenId = !string.IsNullOrWhiteSpace(customer.WechatOpenid), + HasFollowUrl = !string.IsNullOrWhiteSpace(follow?.BaseUrl), + Items = WechatOrderNotifyEventCodes.All.Select(e => + { + prefMap.TryGetValue(e.Code, out var pref); + tplMap.TryGetValue(e.Code, out var tpl); + return new CustomerWechatNotifyPrefItemOutput + { + EventCode = e.Code, + EventName = e.Name, + OpsEnabled = tpl is { IsEnabled: true } && !string.IsNullOrWhiteSpace(tpl.TemplateId), + IsSubscribed = pref?.IsSubscribed == true + }; + }).ToList() + }; + } + + /// + /// 保存当前客户订阅开关(默认全关,仅显式 true 为订阅)。 + /// + [HttpPost("/customer/wechat-notify/prefs")] + public async Task SavePrefsAsync( + [FromBody] SaveCustomerWechatNotifyPrefInput input, + CancellationToken cancellationToken = default) + { + var customer = await GetCurrentCustomerOrThrowAsync(cancellationToken); + if (input?.Items == null || input.Items.Count == 0) + { + throw new BusinessException("订阅项不能为空"); + } + + foreach (var item in input.Items) + { + if (string.IsNullOrWhiteSpace(item.EventCode)) + { + continue; + } + + var code = WechatOrderNotifyEventCodes.Normalize(item.EventCode); + var entity = await PrefRepository.GetByCustomerAndEventAsync(customer.Id, code, cancellationToken); + if (entity == null) + { + await PrefRepository.InsertAsync( + new CustomerWechatNotifyPref + { + CustomerId = customer.Id, + EventCode = code, + IsSubscribed = item.IsSubscribed + }, + cancellationToken: cancellationToken); + } + else + { + entity.IsSubscribed = item.IsSubscribed; + entity.UpdateTime = DateTime.Now; + await PrefRepository.UpdateAsync(entity, cancellationToken: cancellationToken); + } + } + } + + private async Task GetCurrentCustomerOrThrowAsync(CancellationToken cancellationToken) + { + var userId = CurrentUser.GetId(); + if (userId <= 0) + { + throw new BusinessException("客户未登录"); + } + + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken); + if (customer == null) + { + throw new BusinessException("客户不存在"); + } + + return customer; + } +} diff --git a/src/Oms.Application/Services/Operations/InboundRecordService.cs b/src/Oms.Application/Services/Operations/InboundRecordService.cs index 6b5851d..ecfdc52 100644 --- a/src/Oms.Application/Services/Operations/InboundRecordService.cs +++ b/src/Oms.Application/Services/Operations/InboundRecordService.cs @@ -6,6 +6,7 @@ using Oms.Application.Dtos.Operations; using Oms.Application.Dtos.Shared; using Oms.Application.Services.Orders; using Oms.Application.Services.Orders.Issues; +using Oms.Application.Services.WeChatNotify; using Oms.Application.Shared; using Oms.Application.Shared.DocNumbers; using Oms.Domain.ChannelsAggregate.Repositories; @@ -14,6 +15,7 @@ using Oms.Domain.OperationsAggregate.Repositories; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; using Oms.Domain.SystemAggregate.Repositories; namespace Oms.Application.Services.Operations; @@ -34,6 +36,8 @@ public class InboundRecordService : ApplicationService LazyServiceProvider.GetRequiredService(); private IDocNumberExtractService DocNumberExtractService => LazyServiceProvider.GetRequiredService(); + private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher => + LazyServiceProvider.GetRequiredService(); /// /// 按单号查询订单(入库扫描展示销售产品、目的国,只读)。 @@ -153,6 +157,9 @@ public class InboundRecordService : ApplicationService await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Inbound, operatorId); var refreshed = await OrderRepository.GetByWaybillNoAsync(waybillNo); + await WechatOrderNotifyDispatcher.TryNotifyAsync( + refreshed ?? order, + WechatOrderNotifyEventCodes.Inbound); var output = ObjectMapper.Map(savedEntity); ApplyOrderStatusToInboundOutput(output, refreshed); return output; diff --git a/src/Oms.Application/Services/Operations/OutboundRecordService.cs b/src/Oms.Application/Services/Operations/OutboundRecordService.cs index 79585dc..a3c6802 100644 --- a/src/Oms.Application/Services/Operations/OutboundRecordService.cs +++ b/src/Oms.Application/Services/Operations/OutboundRecordService.cs @@ -6,6 +6,7 @@ using Oms.Application.Dtos.Operations; using Oms.Application.Dtos.Shared; using Oms.Application.Services.Orders; using Oms.Application.Services.Orders.Issues; +using Oms.Application.Services.WeChatNotify; using Oms.Application.Shared; using Oms.Application.Shared.DocNumbers; using Oms.Domain.ChannelsAggregate.Repositories; @@ -14,6 +15,7 @@ using Oms.Domain.OperationsAggregate.Repositories; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; using Oms.Domain.SystemAggregate.Repositories; namespace Oms.Application.Services.Operations; @@ -36,6 +38,8 @@ public class OutboundRecordService : ApplicationService LazyServiceProvider.GetRequiredService(); private IDocNumberExtractService DocNumberExtractService => LazyServiceProvider.GetRequiredService(); + private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher => + LazyServiceProvider.GetRequiredService(); /// /// 按单号查询订单(出库扫描展示销售产品、目的国、服务渠道,只读)。 @@ -173,6 +177,11 @@ public class OutboundRecordService : ApplicationService // 自动触发走 Outbox,避免拉长出库扫码 RT await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId); + var refreshed = await OrderRepository.GetByWaybillNoAsync(waybillNo); + await WechatOrderNotifyDispatcher.TryNotifyAsync( + refreshed ?? order, + WechatOrderNotifyEventCodes.Outbound); + return ObjectMapper.Map(savedEntity); } diff --git a/src/Oms.Application/Services/Operations/ShipBagService.cs b/src/Oms.Application/Services/Operations/ShipBagService.cs index 3d87b9c..5b8374c 100644 --- a/src/Oms.Application/Services/Operations/ShipBagService.cs +++ b/src/Oms.Application/Services/Operations/ShipBagService.cs @@ -8,6 +8,7 @@ using Oms.Application.Dtos.Shared; using Oms.Application.Labeling; using Oms.Application.Services.Orders; using Oms.Application.Services.Orders.Issues; +using Oms.Application.Services.WeChatNotify; using Oms.Application.Shared; using Oms.Application.Shared.DocNumbers; using Oms.Application.Storage; @@ -20,6 +21,7 @@ using Oms.Domain.OperationsAggregate.Repositories; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; using Oms.Domain.SystemAggregate.Repositories; using OutboundRecord = Oms.Domain.OperationsAggregate.Entities.OutboundRecord; @@ -48,6 +50,8 @@ public class ShipBagService : ApplicationService private IDocNumberGenerator DocNumberGenerator => LazyServiceProvider.GetRequiredService(); + private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher => + LazyServiceProvider.GetRequiredService(); private IDocNumberExtractService DocNumberExtractService => LazyServiceProvider.GetRequiredService(); @@ -364,6 +368,8 @@ public class ShipBagService : ApplicationService OperatorId = operatorId, }); await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId); + var refreshed = await OrderRepository.GetByServiceNoAsync(order.ServiceNo) ?? order; + await WechatOrderNotifyDispatcher.TryNotifyAsync(refreshed, WechatOrderNotifyEventCodes.Outbound); } 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 7732dcd..646a194 100644 --- a/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs +++ b/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs @@ -1,13 +1,13 @@ -using System.Text.Json; using Fake.DependencyInjection; using Microsoft.Extensions.Logging; using Oms.Application.Services.System; +using Oms.Application.Services.WeChatNotify; using Oms.Domain.ChannelsAggregate.Consts; -using Oms.Domain.ChannelsAggregate.Entities; -using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.CustomersAggregate.Entities; 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; using Oms.Domain.SystemAggregate.Repositories; using Oms.Application.Shared; @@ -18,6 +18,7 @@ public class OrderIssueNotificationService( INoticeRepository noticeRepository, ICustomerRepository customerRepository, ISystemBatchEmailAccountRepository batchEmailAccountRepository, + WechatOrderNotifyDispatcher wechatOrderNotifyDispatcher, ILogger logger) : IScopedDependency { private const string NoticeTypeMessage = "message"; @@ -63,7 +64,7 @@ public class OrderIssueNotificationService( logger.LogInformation("订单 {OrderId} 问题件通知:飞书通道未接入,已跳过", order.Id); break; case IssueNotifyMethodCodes.Wechat: - logger.LogInformation("订单 {OrderId} 问题件通知:微信模板通道未接入,已跳过", order.Id); + // 客户订阅通道统一在下方按事件投递,避免与模板方法重复发送 break; default: logger.LogWarning("订单 {OrderId} 问题件通知:未知方式 {Method},已跳过", order.Id, method); @@ -75,6 +76,15 @@ public class OrderIssueNotificationService( logger.LogWarning(ex, "订单 {OrderId} 问题件通知发送失败,方式={Method}", order.Id, method); } } + + // 仅问题件状态时投递客户订阅的微信通知(自动触发警告等不发) + if (string.Equals(order.OrderStatus, OrderStatusCodes.Problematic, StringComparison.OrdinalIgnoreCase)) + { + await wechatOrderNotifyDispatcher.TryNotifyAsync( + order, + WechatOrderNotifyEventCodes.Problematic, + remark: string.IsNullOrWhiteSpace(content) ? title : content); + } } private async Task SendInAppAsync( diff --git a/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs new file mode 100644 index 0000000..1d31de0 --- /dev/null +++ b/src/Oms.Application/Services/System/WechatOrderNotifyConfigService.cs @@ -0,0 +1,183 @@ +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Shared; +using Oms.Application.Dtos.System; +using Oms.Application.Services.WeChatNotify; +using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Consts; +using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.System; + +/// +/// 微信订单通知模板配置(系统其他配置入口使用)。 +/// +[ApiExplorerSettings(GroupName = "OMS-System")] +public class WechatOrderNotifyConfigService : ApplicationService +{ + private IWechatNotifyTemplateRepository TemplateRepository => + LazyServiceProvider.GetRequiredService(); + + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private WechatOrderNotifyDispatcher Dispatcher => + LazyServiceProvider.GetRequiredService(); + + /// + /// 列出全部事件模板(缺省自动种子未启用行)。 + /// + [HttpGet("/system/wechat-order-notify/templates")] + public async Task> GetTemplatesAsync( + CancellationToken cancellationToken = default) + { + await EnsureSeedAsync(cancellationToken); + var list = await TemplateRepository.GetAllAsync(cancellationToken); + var map = list.ToDictionary(x => x.EventCode, StringComparer.OrdinalIgnoreCase); + var items = WechatOrderNotifyEventCodes.All + .Select(e => + { + map.TryGetValue(e.Code, out var entity); + return MapOutput(entity, e.Code, e.Name); + }) + .ToList(); + return new OmsItemsResult { Items = items }; + } + + /// + /// 保存单个事件模板配置。 + /// + [HttpPost("/system/wechat-order-notify/templates/save")] + public async Task SaveTemplateAsync( + [FromBody] SaveWechatOrderNotifyTemplateInput input, + CancellationToken cancellationToken = default) + { + if (input == null || string.IsNullOrWhiteSpace(input.EventCode)) + { + throw new BusinessException("事件码不能为空"); + } + + var code = WechatOrderNotifyEventCodes.Normalize(input.EventCode); + var name = WechatOrderNotifyEventCodes.GetName(code) ?? code; + await EnsureSeedAsync(cancellationToken); + + var entity = await TemplateRepository.GetByEventCodeAsync(code, cancellationToken); + if (entity == null) + { + entity = new WechatNotifyTemplate + { + EventCode = code, + EventName = name + }; + ApplyInput(entity, input, name); + await TemplateRepository.InsertAsync(entity, cancellationToken: cancellationToken); + } + else + { + ApplyInput(entity, input, name); + entity.UpdateTime = DateTime.Now; + await TemplateRepository.UpdateAsync(entity, cancellationToken: cancellationToken); + } + + return MapOutput(entity, code, name); + } + + /// + /// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId)。 + /// + [HttpPost("/system/wechat-order-notify/trial-send")] + public async Task TrialSendAsync( + [FromBody] TrialWechatOrderNotifyInput input, + CancellationToken cancellationToken = default) + { + if (input == null || string.IsNullOrWhiteSpace(input.EventCode)) + { + throw new BusinessException("事件码不能为空"); + } + + var code = WechatOrderNotifyEventCodes.Normalize(input.EventCode); + var order = await ResolveOrderAsync(input, cancellationToken) + ?? throw new BusinessException("未找到订单"); + + await Dispatcher.TryNotifyAsync( + order, + code, + remark: "运营试发", + force: true, + cancellationToken); + } + + private async Task EnsureSeedAsync(CancellationToken cancellationToken) + { + var existing = await TemplateRepository.GetAllAsync(cancellationToken); + var codes = existing + .Select(x => x.EventCode) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + foreach (var (code, name) in WechatOrderNotifyEventCodes.All) + { + if (codes.Contains(code)) + { + continue; + } + + await TemplateRepository.InsertAsync( + new WechatNotifyTemplate + { + EventCode = code, + EventName = name, + IsEnabled = false, + UrlTemplate = "{baseUrl}/h5/orders/detail?orderId={orderId}", + FieldMappingJson = + "[{\"key\":\"first\",\"placeholder\":\"eventName\"},{\"key\":\"keyword1\",\"placeholder\":\"serviceNo\"},{\"key\":\"keyword2\",\"placeholder\":\"orderStatusName\"},{\"key\":\"keyword3\",\"placeholder\":\"eventTime\"},{\"key\":\"remark\",\"placeholder\":\"remark\"}]" + }, + cancellationToken: cancellationToken); + } + } + + private async Task ResolveOrderAsync( + TrialWechatOrderNotifyInput input, + CancellationToken cancellationToken) + { + if (input.OrderId is int id && id > 0) + { + return await OrderRepository.FirstOrDefaultAsync(x => x.Id == id, cancellationToken); + } + + if (!string.IsNullOrWhiteSpace(input.ServiceNo)) + { + return await OrderRepository.GetByServiceNoAsync(input.ServiceNo.Trim(), cancellationToken); + } + + return null; + } + + private static void ApplyInput(WechatNotifyTemplate entity, SaveWechatOrderNotifyTemplateInput input, string name) + { + entity.EventName = name; + entity.TemplateId = string.IsNullOrWhiteSpace(input.TemplateId) ? null : input.TemplateId.Trim(); + entity.UrlTemplate = string.IsNullOrWhiteSpace(input.UrlTemplate) ? null : input.UrlTemplate.Trim(); + entity.FieldMappingJson = string.IsNullOrWhiteSpace(input.FieldMappingJson) + ? null + : input.FieldMappingJson.Trim(); + entity.IsEnabled = input.IsEnabled; + entity.Remark = string.IsNullOrWhiteSpace(input.Remark) ? null : input.Remark.Trim(); + } + + private static WechatOrderNotifyTemplateOutput MapOutput( + WechatNotifyTemplate? entity, + string code, + string name) => + new() + { + Id = entity?.Id ?? 0, + EventCode = code, + EventName = name, + TemplateId = entity?.TemplateId, + UrlTemplate = entity?.UrlTemplate, + FieldMappingJson = entity?.FieldMappingJson, + IsEnabled = entity?.IsEnabled ?? false, + Remark = entity?.Remark + }; +} diff --git a/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs new file mode 100644 index 0000000..a1e71c9 --- /dev/null +++ b/src/Oms.Application/Services/WeChatNotify/WechatOrderNotifyDispatcher.cs @@ -0,0 +1,379 @@ +using System.Text.Json; +using Fake.DependencyInjection; +using Microsoft.Extensions.Logging; +using Oms.Application.Integrations.WeChat; +using Oms.Application.Shared; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.SystemAggregate.Consts; +using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.WeChatNotify; + +/// +/// 微信订单状态通知调度:校验运营启用 + 客户订阅 + openid,组包发送并写日志。 +/// +public class WechatOrderNotifyDispatcher( + IWechatNotifyTemplateRepository templateRepository, + ICustomerWechatNotifyPrefRepository prefRepository, + IWechatNotifyLogRepository logRepository, + ICustomerRepository customerRepository, + ISystemOtherConfigRepository otherConfigRepository, + IWeChatMpTemplateSender templateSender, + ILogger logger) : IScopedDependency +{ + private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30); + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// 尝试按事件发送;任何失败只记日志,不抛给业务主流程。 + /// + /// 订单。 + /// 事件码。 + /// 可选备注(问题件说明等)。 + /// 试发时跳过订阅与去重。 + /// 取消令牌。 + public async Task TryNotifyAsync( + Order order, + string eventCode, + string? remark = null, + bool force = false, + CancellationToken cancellationToken = default) + { + try + { + await NotifyCoreAsync(order, eventCode, remark, force, cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning( + ex, + "微信订单通知异常 OrderId={OrderId} Event={EventCode}", + order.Id, + eventCode); + } + } + + private async Task NotifyCoreAsync( + Order order, + string eventCode, + string? remark, + bool force, + CancellationToken cancellationToken) + { + if (!WechatOrderNotifyEventCodes.IsKnown(eventCode)) + { + return; + } + + var normalized = WechatOrderNotifyEventCodes.Normalize(eventCode); + var eventName = WechatOrderNotifyEventCodes.GetName(normalized) ?? normalized; + + var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken); + if (template == null || !template.IsEnabled) + { + await WriteLogAsync( + order, + customerId: order.CustomerId ?? 0, + normalized, + openId: null, + templateId: template?.TemplateId, + status: "skipped", + errMsg: "运营未启用该事件模板", + cancellationToken: cancellationToken); + return; + } + + if (string.IsNullOrWhiteSpace(template.TemplateId)) + { + await WriteLogAsync( + order, + customerId: order.CustomerId ?? 0, + normalized, + openId: null, + templateId: null, + status: "skipped", + errMsg: "未配置微信 TemplateId", + cancellationToken: cancellationToken); + return; + } + + if (order.CustomerId is not int customerId || customerId <= 0) + { + await WriteLogAsync( + order, + customerId: 0, + normalized, + openId: null, + templateId: template.TemplateId, + status: "skipped", + errMsg: "订单无客户", + cancellationToken: cancellationToken); + return; + } + + if (!force) + { + var pref = await prefRepository.GetByCustomerAndEventAsync(customerId, normalized, cancellationToken); + if (pref is not { IsSubscribed: true }) + { + await WriteLogAsync( + order, + customerId, + normalized, + openId: null, + templateId: template.TemplateId, + status: "skipped", + errMsg: "客户未订阅该事件", + cancellationToken: cancellationToken); + return; + } + + var since = DateTime.Now.Subtract(DedupWindow); + if (await logRepository.ExistsRecentAsync(order.Id, normalized, since, cancellationToken)) + { + await WriteLogAsync( + order, + customerId, + normalized, + openId: null, + templateId: template.TemplateId, + status: "skipped", + errMsg: $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过", + cancellationToken: cancellationToken); + return; + } + } + + var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId, cancellationToken); + var openId = customer?.WechatOpenid?.Trim(); + if (string.IsNullOrWhiteSpace(openId)) + { + await WriteLogAsync( + order, + customerId, + normalized, + openId: null, + templateId: template.TemplateId, + status: "skipped", + errMsg: "客户未绑定微信 OpenId", + cancellationToken: cancellationToken); + return; + } + + var placeholders = BuildPlaceholders(order, eventName, remark, customer?.CustomerName); + var data = BuildTemplateData(template.FieldMappingJson, placeholders); + if (data.Count == 0) + { + await WriteLogAsync( + order, + customerId, + normalized, + openId, + template.TemplateId, + status: "skipped", + errMsg: "字段映射为空或无效", + cancellationToken: cancellationToken); + return; + } + + var url = await BuildUrlAsync(template.UrlTemplate, order, cancellationToken); + var payloadJson = OmsDocHelper.SerializeJson(new + { + openId, + templateId = template.TemplateId, + url, + data + }); + + var sendResult = await templateSender.SendAsync( + openId, + template.TemplateId.Trim(), + url, + data, + cancellationToken); + + await WriteLogAsync( + order, + customerId, + normalized, + openId, + template.TemplateId, + status: sendResult.Success ? "sent" : "failed", + errCode: sendResult.ErrCode == 0 ? null : sendResult.ErrCode, + errMsg: sendResult.Success ? null : sendResult.ErrMsg, + wxMsgId: sendResult.MsgId, + payloadJson: payloadJson, + cancellationToken: cancellationToken); + + if (!sendResult.Success) + { + logger.LogWarning( + "微信订单通知失败 OrderId={OrderId} Event={Event} Err={ErrCode} {ErrMsg}", + order.Id, + normalized, + sendResult.ErrCode, + sendResult.ErrMsg); + } + } + + private static Dictionary BuildPlaceholders( + Order order, + string eventName, + string? remark, + string? customerName) + { + var statusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) ?? order.OrderStatus; + return new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["serviceNo"] = order.ServiceNo ?? string.Empty, + ["clientNo"] = order.ClientNo ?? string.Empty, + ["orderId"] = order.Id.ToString(), + ["orderStatus"] = order.OrderStatus ?? string.Empty, + ["orderStatusName"] = statusName, + ["eventName"] = eventName, + ["eventTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + ["remark"] = string.IsNullOrWhiteSpace(remark) ? eventName : remark.Trim(), + ["customerName"] = customerName ?? string.Empty, // 客户名称,可空 + ["consigneeCountry"] = order.ConsigneeCountry ?? string.Empty, + }; + } + + private static Dictionary BuildTemplateData( + string? fieldMappingJson, + IReadOnlyDictionary placeholders) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (string.IsNullOrWhiteSpace(fieldMappingJson)) + { + // 缺省映射:兼容常见 first/keyword/remark 模板 + result["first"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("eventName") ?? ""); + result["keyword1"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("serviceNo") ?? ""); + result["keyword2"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("orderStatusName") ?? ""); + result["keyword3"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("eventTime") ?? ""); + result["remark"] = new WeChatMpTemplateDataItem(placeholders.GetValueOrDefault("remark") ?? ""); + return result; + } + + try + { + var items = JsonSerializer.Deserialize>(fieldMappingJson, JsonOptions); + if (items == null || items.Count == 0) + { + return result; + } + + foreach (var item in items) + { + if (string.IsNullOrWhiteSpace(item.Key)) + { + continue; + } + + var raw = item.Placeholder?.Trim() ?? string.Empty; + var value = placeholders.TryGetValue(raw, out var mapped) + ? mapped + : ResolveInline(raw, placeholders); + result[item.Key.Trim()] = new WeChatMpTemplateDataItem(value, item.Color); + } + } + catch (JsonException) + { + // 保持空,上层记 skipped + } + + return result; + } + + private static string ResolveInline(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, StringComparison.OrdinalIgnoreCase); + } + + return value; + } + + private async Task BuildUrlAsync( + string? urlTemplate, + Order order, + CancellationToken cancellationToken) + { + var baseUrl = string.Empty; + var mp = await otherConfigRepository.GetByConfigCodeAsync( + SystemOtherConfigCodes.WeChatMp, + cancellationToken); + if (!string.IsNullOrWhiteSpace(mp?.BaseUrl)) + { + baseUrl = mp.BaseUrl.Trim().TrimEnd('/'); + } + + var tpl = string.IsNullOrWhiteSpace(urlTemplate) + ? "{baseUrl}/h5/orders/detail?orderId={orderId}" + : urlTemplate.Trim(); + + return tpl + .Replace("{baseUrl}", baseUrl, StringComparison.OrdinalIgnoreCase) + .Replace("{orderId}", order.Id.ToString(), StringComparison.OrdinalIgnoreCase) + .Replace("{serviceNo}", Uri.EscapeDataString(order.ServiceNo ?? string.Empty), StringComparison.OrdinalIgnoreCase); + } + + private async Task WriteLogAsync( + Order order, + int customerId, + string eventCode, + string? openId, + string? templateId, + string status, + string? errMsg = null, + int? errCode = null, + string? wxMsgId = null, + string? payloadJson = null, + CancellationToken cancellationToken = default) + { + try + { + await logRepository.InsertAsync( + new WechatNotifyLog + { + CustomerId = customerId, + OrderId = order.Id, + EventCode = eventCode, + OpenId = openId, + TemplateId = templateId, + Status = status, + ErrMsg = Truncate(errMsg, 512), + ErrCode = errCode, + WxMsgId = wxMsgId, + PayloadJson = payloadJson + }, + cancellationToken: cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "写微信通知日志失败 OrderId={OrderId}", order.Id); + } + } + + private static string? Truncate(string? value, int max) => + string.IsNullOrEmpty(value) || value.Length <= max ? value : value[..max]; + + private sealed class FieldMappingItem + { + public string? Key { get; set; } + public string? Placeholder { get; set; } + public string? Color { get; set; } + } +} diff --git a/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs b/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs new file mode 100644 index 0000000..b30e5a4 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs @@ -0,0 +1,56 @@ +namespace Oms.Domain.SystemAggregate.Consts; + +/// +/// 微信公众号订单状态通知事件码(与客户订阅、运营模板配置共用)。 +/// +public static class WechatOrderNotifyEventCodes +{ + public const string Inbound = "inbound"; + public const string Outbound = "outbound"; + public const string DeliverySuccess = "deliverySuccess"; + public const string DeliveryFailed = "deliveryFailed"; + public const string Problematic = "problematic"; + + public static readonly IReadOnlyList<(string Code, string Name)> All = + [ + (Inbound, "入库"), + (Outbound, "出库"), + (DeliverySuccess, "签收"), + (DeliveryFailed, "派送失败"), + (Problematic, "问题件"), + ]; + + public static string? GetName(string? eventCode) + { + if (string.IsNullOrWhiteSpace(eventCode)) + { + return null; + } + + foreach (var (code, name) in All) + { + if (string.Equals(code, eventCode.Trim(), StringComparison.OrdinalIgnoreCase)) + { + return name; + } + } + + return null; + } + + public static bool IsKnown(string? eventCode) => GetName(eventCode) != null; + + public static string Normalize(string eventCode) + { + var trimmed = eventCode?.Trim() ?? string.Empty; + foreach (var (code, _) in All) + { + if (string.Equals(code, trimmed, StringComparison.OrdinalIgnoreCase)) + { + return code; + } + } + + throw new ArgumentException($"未知微信通知事件码: {eventCode}", nameof(eventCode)); + } +} diff --git a/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs b/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs new file mode 100644 index 0000000..2ad9c7d --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Entities/CustomerWechatNotifyPref.cs @@ -0,0 +1,20 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.SystemAggregate.Entities; + +/// +/// 客户微信订单通知订阅偏好(默认未订阅)。 +/// +[SugarTable("t_customer_wechat_notify_pref")] +public class CustomerWechatNotifyPref : OmsAuditedAggregateRoot +{ + /// 客户 Id。 + public int CustomerId { get; set; } + + /// 事件码。 + public string EventCode { get; set; } = string.Empty; + + /// 是否订阅。 + public bool IsSubscribed { get; set; } +} diff --git a/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs new file mode 100644 index 0000000..43fbf6b --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs @@ -0,0 +1,38 @@ +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 new file mode 100644 index 0000000..d48031d --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Entities/WechatNotifyTemplate.cs @@ -0,0 +1,36 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.SystemAggregate.Entities; + +/// +/// 微信订单通知模板配置(按事件一条)。 +/// +[SugarTable("t_wechat_notify_template")] +public class WechatNotifyTemplate : OmsAuditedAggregateRoot +{ + /// 事件码,见 。 + public string EventCode { get; set; } = string.Empty; + + /// 事件显示名。 + public string EventName { get; set; } = string.Empty; + + /// 微信公众号模板 ID。 + [SugarColumn(IsNullable = true, Length = 128)] + public string? TemplateId { get; set; } + + /// 跳转 URL 模板,支持 {baseUrl}/{orderId}/{serviceNo}。 + [SugarColumn(IsNullable = true, Length = 512)] + public string? UrlTemplate { get; set; } + + /// 字段映射 JSON:[{key,placeholder,color?}]。 + [SugarColumn(ColumnDataType = "text", IsNullable = true)] + public string? FieldMappingJson { get; set; } + + /// 是否启用。 + public bool IsEnabled { get; set; } + + /// 备注。 + [SugarColumn(IsNullable = true, Length = 512)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/SystemAggregate/Repositories/ICustomerWechatNotifyPrefRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/ICustomerWechatNotifyPrefRepository.cs new file mode 100644 index 0000000..6f3de10 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Repositories/ICustomerWechatNotifyPrefRepository.cs @@ -0,0 +1,16 @@ +using Fake.Domain.Repositories; +using Oms.Domain.SystemAggregate.Entities; + +namespace Oms.Domain.SystemAggregate.Repositories; + +public interface ICustomerWechatNotifyPrefRepository : IRepository +{ + Task> ListByCustomerIdAsync( + int customerId, + CancellationToken cancellationToken = default); + + Task GetByCustomerAndEventAsync( + int customerId, + string eventCode, + CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs new file mode 100644 index 0000000..7394695 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyLogRepository.cs @@ -0,0 +1,16 @@ +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.Domain/SystemAggregate/Repositories/IWechatNotifyTemplateRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyTemplateRepository.cs new file mode 100644 index 0000000..d58f85d --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Repositories/IWechatNotifyTemplateRepository.cs @@ -0,0 +1,11 @@ +using Fake.Domain.Repositories; +using Oms.Domain.SystemAggregate.Entities; + +namespace Oms.Domain.SystemAggregate.Repositories; + +public interface IWechatNotifyTemplateRepository : IRepository +{ + Task GetByEventCodeAsync(string eventCode, CancellationToken cancellationToken = default); + + Task> GetAllAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Oms.SqlSugarCore/System/CustomerWechatNotifyPrefRepository.cs b/src/Oms.SqlSugarCore/System/CustomerWechatNotifyPrefRepository.cs new file mode 100644 index 0000000..47b3835 --- /dev/null +++ b/src/Oms.SqlSugarCore/System/CustomerWechatNotifyPrefRepository.cs @@ -0,0 +1,28 @@ +using Fake.DependencyInjection; +using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.System; + +public class CustomerWechatNotifyPrefRepository + : OmsSqlSugarRepository, + ICustomerWechatNotifyPrefRepository, + IScopedDependency +{ + public Task> ListByCustomerIdAsync( + int customerId, + CancellationToken cancellationToken = default) => + GetListAsync(x => x.CustomerId == customerId, cancellationToken: cancellationToken); + + public async Task GetByCustomerAndEventAsync( + int customerId, + string eventCode, + CancellationToken cancellationToken = default) + { + var code = eventCode.Trim(); + return await FirstOrDefaultAsync( + x => x.CustomerId == customerId && x.EventCode == code, + cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs b/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs new file mode 100644 index 0000000..ccf989c --- /dev/null +++ b/src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs @@ -0,0 +1,27 @@ +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); + } +} diff --git a/src/Oms.SqlSugarCore/System/WechatNotifyTemplateRepository.cs b/src/Oms.SqlSugarCore/System/WechatNotifyTemplateRepository.cs new file mode 100644 index 0000000..4c0d776 --- /dev/null +++ b/src/Oms.SqlSugarCore/System/WechatNotifyTemplateRepository.cs @@ -0,0 +1,25 @@ +using Fake.DependencyInjection; +using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.System; + +public class WechatNotifyTemplateRepository + : OmsSqlSugarRepository, + IWechatNotifyTemplateRepository, + IScopedDependency +{ + public async Task GetByEventCodeAsync( + string eventCode, + CancellationToken cancellationToken = default) + { + var code = eventCode.Trim(); + return await FirstOrDefaultAsync( + x => x.EventCode == code, + cancellationToken); + } + + public Task> GetAllAsync(CancellationToken cancellationToken = default) => + GetListAsync(cancellationToken: cancellationToken); +} diff --git a/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs index d6d36b8..61aa0b9 100644 --- a/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs +++ b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs @@ -30,8 +30,22 @@ public interface IWeChatMpApiClient /// 清空数据库中缓存的公众号 access_token。 /// Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default); + + /// + /// 发送公众号模板消息(message/template/send)。 + /// + Task SendTemplateMessageAsync( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data, + CancellationToken cancellationToken = default); } +public sealed record WeChatTemplateDataValue(string Value, string? Color = null); + +public sealed record WeChatTemplateSendResult(bool Success, string? MsgId, int ErrCode, string? ErrMsg); + public sealed record WeChatOAuthTokenResult(string AccessToken, string OpenId, string? Unionid = null); public sealed record WeChatOAuthUserResult( @@ -56,6 +70,112 @@ internal sealed class WeChatMpApiClient( public Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default) => accessTokenStore.ClearAsync(cancellationToken); + public async Task SendTemplateMessageAsync( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(openId)) + { + return new WeChatTemplateSendResult(false, null, -1, "openid 为空"); + } + + if (string.IsNullOrWhiteSpace(templateId)) + { + return new WeChatTemplateSendResult(false, null, -1, "template_id 为空"); + } + + return await SendTemplateMessageCoreAsync( + openId.Trim(), + templateId.Trim(), + string.IsNullOrWhiteSpace(url) ? null : url.Trim(), + data, + retried: false, + cancellationToken); + } + + private async Task SendTemplateMessageCoreAsync( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data, + bool retried, + CancellationToken cancellationToken) + { + var mp = await configProvider.GetAsync(cancellationToken); + var accessToken = await GetAccessTokenAsync(mp, cancellationToken); + var client = httpClientFactory.CreateClient(nameof(WeChatMpApiClient)); + + var dataPayload = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (key, item) in data) + { + if (string.IsNullOrWhiteSpace(key)) + { + continue; + } + + dataPayload[key] = string.IsNullOrWhiteSpace(item.Color) + ? new { value = item.Value ?? string.Empty } + : new { value = item.Value ?? string.Empty, color = item.Color }; + } + + object payload = string.IsNullOrWhiteSpace(url) + ? new + { + touser = openId, + template_id = templateId, + data = dataPayload + } + : new + { + touser = openId, + template_id = templateId, + url, + data = dataPayload + }; + + var json = JsonSerializer.Serialize(payload); + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await client.PostAsync( + $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={Uri.EscapeDataString(accessToken)}", + content, + cancellationToken); + + var result = await ReadWeChatJsonAsync( + response, + "发送模板消息", + cancellationToken); + + if (result == null) + { + return new WeChatTemplateSendResult(false, null, -1, "微信返回空响应"); + } + + if (result.Errcode is > 0) + { + if (!retried && IsAccessTokenInvalidError(result.Errcode)) + { + logger.LogWarning( + "微信 access_token 失效(errcode={Errcode}),清空库内 token 后重试发送模板", + result.Errcode); + await accessTokenStore.ClearAsync(cancellationToken); + return await SendTemplateMessageCoreAsync( + openId, + templateId, + url, + data, + retried: true, + cancellationToken); + } + + return new WeChatTemplateSendResult(false, null, result.Errcode, result.Errmsg); + } + + return new WeChatTemplateSendResult(true, result.Msgid?.ToString(), 0, null); + } + public async Task CreateLoginQrCodeUrlAsync( string loginUuid, int expireSeconds, @@ -376,6 +496,18 @@ internal sealed class WeChatMpApiClient( public string? Errmsg { get; set; } } + private sealed class WeChatTemplateSendResponse + { + [JsonPropertyName("errcode")] + public int Errcode { get; set; } + + [JsonPropertyName("errmsg")] + public string? Errmsg { get; set; } + + [JsonPropertyName("msgid")] + public object? Msgid { get; set; } + } + private sealed class WeChatOAuthUserResponse { [JsonPropertyName("openid")] diff --git a/src/SimpleAdmin.Api/WeChat/Services/WeChatMpTemplateSenderAdapter.cs b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpTemplateSenderAdapter.cs new file mode 100644 index 0000000..7feb407 --- /dev/null +++ b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpTemplateSenderAdapter.cs @@ -0,0 +1,31 @@ +using Oms.Application.Integrations.WeChat; + +namespace SimpleAdmin.Api.WeChat.Services; + +/// +/// 将 适配为 Application 层模板发送接口。 +/// +internal sealed class WeChatMpTemplateSenderAdapter(IWeChatMpApiClient apiClient) : IWeChatMpTemplateSender +{ + public async Task SendAsync( + string openId, + string templateId, + string? url, + IReadOnlyDictionary data, + CancellationToken cancellationToken = default) + { + var mapped = data.ToDictionary( + x => x.Key, + x => new WeChatTemplateDataValue(x.Value.Value, x.Value.Color), + StringComparer.OrdinalIgnoreCase); + + var result = await apiClient.SendTemplateMessageAsync( + openId, + templateId, + url, + mapped, + cancellationToken); + + return new WeChatMpTemplateSendResult(result.Success, result.MsgId, result.ErrCode, result.ErrMsg); + } +} diff --git a/src/SimpleAdmin.Api/WeChat/WeChatServiceExtensions.cs b/src/SimpleAdmin.Api/WeChat/WeChatServiceExtensions.cs index 36f8641..897802c 100644 --- a/src/SimpleAdmin.Api/WeChat/WeChatServiceExtensions.cs +++ b/src/SimpleAdmin.Api/WeChat/WeChatServiceExtensions.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Oms.Application.Integrations.WeChat; using SimpleAdmin.Api.WeChat.Options; using SimpleAdmin.Api.WeChat.Services; @@ -14,6 +15,7 @@ public static class WeChatServiceExtensions services.AddMemoryCache(); services.AddScoped(); + services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddTransient();