feat: 接入微信公众号订单状态模板通知
All checks were successful
Build and Deploy / deploy (push) Successful in 1m21s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m21s
支持入库/出库/签收/派送失败/问题件推送,客户默认可选订阅,运营可配模板并试发。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
79ebe77666
commit
2014ec3065
63
db.sql
63
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',
|
||||
|
||||
103
sql/migrate_wechat_order_notify_20261115.sql
Normal file
103
sql/migrate_wechat_order_notify_20261115.sql
Normal file
@ -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;
|
||||
@ -0,0 +1,41 @@
|
||||
namespace Oms.Application.Dtos.Customers;
|
||||
|
||||
/// <summary>客户微信通知前置状态 + 订阅项。</summary>
|
||||
public class CustomerWechatNotifyStatusOutput
|
||||
{
|
||||
/// <summary>是否已绑定微信 OpenId。</summary>
|
||||
public bool HasOpenId { get; set; }
|
||||
|
||||
/// <summary>是否已配置公众号关注跳转(仅提示用)。</summary>
|
||||
public bool HasFollowUrl { get; set; }
|
||||
|
||||
/// <summary>各事件订阅状态(默认未订阅)。</summary>
|
||||
public List<CustomerWechatNotifyPrefItemOutput> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>单事件订阅项。</summary>
|
||||
public class CustomerWechatNotifyPrefItemOutput
|
||||
{
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
public string EventName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>运营是否已启用该事件模板。</summary>
|
||||
public bool OpsEnabled { get; set; }
|
||||
|
||||
/// <summary>客户是否订阅。</summary>
|
||||
public bool IsSubscribed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存客户订阅。</summary>
|
||||
public class SaveCustomerWechatNotifyPrefInput
|
||||
{
|
||||
public List<SaveCustomerWechatNotifyPrefItemInput> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
public class SaveCustomerWechatNotifyPrefItemInput
|
||||
{
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
public bool IsSubscribed { get; set; }
|
||||
}
|
||||
63
src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs
Normal file
63
src/Oms.Application/Dtos/System/WechatOrderNotifyDtos.cs
Normal file
@ -0,0 +1,63 @@
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>微信订单通知模板配置输出。</summary>
|
||||
public class WechatOrderNotifyTemplateOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>事件码。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>事件名。</summary>
|
||||
public string EventName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>微信模板 ID。</summary>
|
||||
public string? TemplateId { get; set; }
|
||||
|
||||
/// <summary>跳转 URL 模板。</summary>
|
||||
public string? UrlTemplate { get; set; }
|
||||
|
||||
/// <summary>字段映射 JSON。</summary>
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存微信订单通知模板。</summary>
|
||||
public class SaveWechatOrderNotifyTemplateInput
|
||||
{
|
||||
/// <summary>事件码。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>微信模板 ID。</summary>
|
||||
public string? TemplateId { get; set; }
|
||||
|
||||
/// <summary>跳转 URL 模板。</summary>
|
||||
public string? UrlTemplate { get; set; }
|
||||
|
||||
/// <summary>字段映射 JSON。</summary>
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>试发入参。</summary>
|
||||
public class TrialWechatOrderNotifyInput
|
||||
{
|
||||
/// <summary>事件码。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>订单 Id(优先)。</summary>
|
||||
public int? OrderId { get; set; }
|
||||
|
||||
/// <summary>运单号(OrderId 为空时使用)。</summary>
|
||||
public string? ServiceNo { get; set; }
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
namespace Oms.Application.Integrations.WeChat;
|
||||
|
||||
/// <summary>
|
||||
/// 公众号模板消息发送(由 Api 宿主实现,复用 access_token)。
|
||||
/// </summary>
|
||||
public interface IWeChatMpTemplateSender
|
||||
{
|
||||
/// <summary>
|
||||
/// 发送模板消息;失败不抛,返回 errcode/errmsg。
|
||||
/// </summary>
|
||||
Task<WeChatMpTemplateSendResult> SendAsync(
|
||||
string openId,
|
||||
string templateId,
|
||||
string? url,
|
||||
IReadOnlyDictionary<string, WeChatMpTemplateDataItem> 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);
|
||||
@ -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<TrackChangeOrderStatusApplier> 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,
|
||||
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 客户微信订单通知订阅(H5/门户)。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Customer")]
|
||||
public class CustomerWechatNotifyService : ApplicationService
|
||||
{
|
||||
private ICustomerRepository CustomerRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ICustomerRepository>();
|
||||
|
||||
private ICustomerWechatNotifyPrefRepository PrefRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ICustomerWechatNotifyPrefRepository>();
|
||||
|
||||
private IWechatNotifyTemplateRepository TemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWechatNotifyTemplateRepository>();
|
||||
|
||||
private ISystemOtherConfigRepository OtherConfigRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISystemOtherConfigRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 当前客户订阅状态与前置条件。
|
||||
/// </summary>
|
||||
[HttpGet("/customer/wechat-notify/status")]
|
||||
public async Task<CustomerWechatNotifyStatusOutput> 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()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存当前客户订阅开关(默认全关,仅显式 true 为订阅)。
|
||||
/// </summary>
|
||||
[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<Customer> GetCurrentCustomerOrThrowAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = CurrentUser.GetId<int>();
|
||||
if (userId <= 0)
|
||||
{
|
||||
throw new BusinessException("客户未登录");
|
||||
}
|
||||
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
|
||||
if (customer == null)
|
||||
{
|
||||
throw new BusinessException("客户不存在");
|
||||
}
|
||||
|
||||
return customer;
|
||||
}
|
||||
}
|
||||
@ -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<AutoTriggerRuntimeService>();
|
||||
private IDocNumberExtractService DocNumberExtractService =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>();
|
||||
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
|
||||
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
|
||||
|
||||
/// <summary>
|
||||
/// 按单号查询订单(入库扫描展示销售产品、目的国,只读)。
|
||||
@ -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<InboundRecord, InboundRecordOutput>(savedEntity);
|
||||
ApplyOrderStatusToInboundOutput(output, refreshed);
|
||||
return output;
|
||||
|
||||
@ -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<AutoTriggerRuntimeService>();
|
||||
private IDocNumberExtractService DocNumberExtractService =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>();
|
||||
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
|
||||
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
|
||||
|
||||
/// <summary>
|
||||
/// 按单号查询订单(出库扫描展示销售产品、目的国、服务渠道,只读)。
|
||||
@ -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<OutboundRecord, OutboundRecordOutput>(savedEntity);
|
||||
}
|
||||
|
||||
|
||||
@ -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<IDocNumberGenerator>();
|
||||
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
|
||||
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
|
||||
private IDocNumberExtractService DocNumberExtractService =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>();
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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<OrderIssueNotificationService> 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(
|
||||
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单通知模板配置(系统其他配置入口使用)。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-System")]
|
||||
public class WechatOrderNotifyConfigService : ApplicationService
|
||||
{
|
||||
private IWechatNotifyTemplateRepository TemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWechatNotifyTemplateRepository>();
|
||||
|
||||
private IOrderRepository OrderRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||||
|
||||
private WechatOrderNotifyDispatcher Dispatcher =>
|
||||
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
|
||||
|
||||
/// <summary>
|
||||
/// 列出全部事件模板(缺省自动种子未启用行)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/wechat-order-notify/templates")]
|
||||
public async Task<OmsItemsResult<WechatOrderNotifyTemplateOutput>> 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<WechatOrderNotifyTemplateOutput> { Items = items };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存单个事件模板配置。
|
||||
/// </summary>
|
||||
[HttpPost("/system/wechat-order-notify/templates/save")]
|
||||
public async Task<WechatOrderNotifyTemplateOutput> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按订单试发一条模板消息(跳过客户订阅与去重,仍要求客户有 OpenId)。
|
||||
/// </summary>
|
||||
[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<Domain.OrdersAggregate.Entities.Order?> 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
|
||||
};
|
||||
}
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单状态通知调度:校验运营启用 + 客户订阅 + openid,组包发送并写日志。
|
||||
/// </summary>
|
||||
public class WechatOrderNotifyDispatcher(
|
||||
IWechatNotifyTemplateRepository templateRepository,
|
||||
ICustomerWechatNotifyPrefRepository prefRepository,
|
||||
IWechatNotifyLogRepository logRepository,
|
||||
ICustomerRepository customerRepository,
|
||||
ISystemOtherConfigRepository otherConfigRepository,
|
||||
IWeChatMpTemplateSender templateSender,
|
||||
ILogger<WechatOrderNotifyDispatcher> logger) : IScopedDependency
|
||||
{
|
||||
private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30);
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 尝试按事件发送;任何失败只记日志,不抛给业务主流程。
|
||||
/// </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,
|
||||
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<string, string> BuildPlaceholders(
|
||||
Order order,
|
||||
string eventName,
|
||||
string? remark,
|
||||
string? customerName)
|
||||
{
|
||||
var statusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) ?? order.OrderStatus;
|
||||
return new Dictionary<string, string>(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<string, WeChatMpTemplateDataItem> BuildTemplateData(
|
||||
string? fieldMappingJson,
|
||||
IReadOnlyDictionary<string, string> placeholders)
|
||||
{
|
||||
var result = new Dictionary<string, WeChatMpTemplateDataItem>(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<List<FieldMappingItem>>(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<string, string> 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<string?> 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; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
namespace Oms.Domain.SystemAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 微信公众号订单状态通知事件码(与客户订阅、运营模板配置共用)。
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 客户微信订单通知订阅偏好(默认未订阅)。
|
||||
/// </summary>
|
||||
[SugarTable("t_customer_wechat_notify_pref")]
|
||||
public class CustomerWechatNotifyPref : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>客户 Id。</summary>
|
||||
public int CustomerId { get; set; }
|
||||
|
||||
/// <summary>事件码。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否订阅。</summary>
|
||||
public bool IsSubscribed { get; set; }
|
||||
}
|
||||
38
src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs
Normal file
38
src/Oms.Domain/SystemAggregate/Entities/WechatNotifyLog.cs
Normal file
@ -0,0 +1,38 @@
|
||||
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; }
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单通知模板配置(按事件一条)。
|
||||
/// </summary>
|
||||
[SugarTable("t_wechat_notify_template")]
|
||||
public class WechatNotifyTemplate : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>事件码,见 <see cref="Consts.WechatOrderNotifyEventCodes"/>。</summary>
|
||||
public string EventCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>事件显示名。</summary>
|
||||
public string EventName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>微信公众号模板 ID。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 128)]
|
||||
public string? TemplateId { get; set; }
|
||||
|
||||
/// <summary>跳转 URL 模板,支持 {baseUrl}/{orderId}/{serviceNo}。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 512)]
|
||||
public string? UrlTemplate { get; set; }
|
||||
|
||||
/// <summary>字段映射 JSON:[{key,placeholder,color?}]。</summary>
|
||||
[SugarColumn(ColumnDataType = "text", IsNullable = true)]
|
||||
public string? FieldMappingJson { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
[SugarColumn(IsNullable = true, Length = 512)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
public interface ICustomerWechatNotifyPrefRepository : IRepository<CustomerWechatNotifyPref>
|
||||
{
|
||||
Task<List<CustomerWechatNotifyPref>> ListByCustomerIdAsync(
|
||||
int customerId,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<CustomerWechatNotifyPref?> GetByCustomerAndEventAsync(
|
||||
int customerId,
|
||||
string eventCode,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
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);
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
public interface IWechatNotifyTemplateRepository : IRepository<WechatNotifyTemplate>
|
||||
{
|
||||
Task<WechatNotifyTemplate?> GetByEventCodeAsync(string eventCode, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<WechatNotifyTemplate>> GetAllAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -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<CustomerWechatNotifyPref>,
|
||||
ICustomerWechatNotifyPrefRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
public Task<List<CustomerWechatNotifyPref>> ListByCustomerIdAsync(
|
||||
int customerId,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
GetListAsync(x => x.CustomerId == customerId, cancellationToken: cancellationToken);
|
||||
|
||||
public async Task<CustomerWechatNotifyPref?> GetByCustomerAndEventAsync(
|
||||
int customerId,
|
||||
string eventCode,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var code = eventCode.Trim();
|
||||
return await FirstOrDefaultAsync(
|
||||
x => x.CustomerId == customerId && x.EventCode == code,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
27
src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs
Normal file
27
src/Oms.SqlSugarCore/System/WechatNotifyLogRepository.cs
Normal file
@ -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<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);
|
||||
}
|
||||
}
|
||||
@ -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<WechatNotifyTemplate>,
|
||||
IWechatNotifyTemplateRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
public async Task<WechatNotifyTemplate?> GetByEventCodeAsync(
|
||||
string eventCode,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var code = eventCode.Trim();
|
||||
return await FirstOrDefaultAsync(
|
||||
x => x.EventCode == code,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
public Task<List<WechatNotifyTemplate>> GetAllAsync(CancellationToken cancellationToken = default) =>
|
||||
GetListAsync(cancellationToken: cancellationToken);
|
||||
}
|
||||
@ -30,8 +30,22 @@ public interface IWeChatMpApiClient
|
||||
/// 清空数据库中缓存的公众号 access_token。
|
||||
/// </summary>
|
||||
Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 发送公众号模板消息(message/template/send)。
|
||||
/// </summary>
|
||||
Task<WeChatTemplateSendResult> SendTemplateMessageAsync(
|
||||
string openId,
|
||||
string templateId,
|
||||
string? url,
|
||||
IReadOnlyDictionary<string, WeChatTemplateDataValue> 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<WeChatTemplateSendResult> SendTemplateMessageAsync(
|
||||
string openId,
|
||||
string templateId,
|
||||
string? url,
|
||||
IReadOnlyDictionary<string, WeChatTemplateDataValue> 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<WeChatTemplateSendResult> SendTemplateMessageCoreAsync(
|
||||
string openId,
|
||||
string templateId,
|
||||
string? url,
|
||||
IReadOnlyDictionary<string, WeChatTemplateDataValue> 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<string, object>(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<WeChatTemplateSendResponse>(
|
||||
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<string> 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")]
|
||||
|
||||
@ -0,0 +1,31 @@
|
||||
using Oms.Application.Integrations.WeChat;
|
||||
|
||||
namespace SimpleAdmin.Api.WeChat.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 将 <see cref="IWeChatMpApiClient"/> 适配为 Application 层模板发送接口。
|
||||
/// </summary>
|
||||
internal sealed class WeChatMpTemplateSenderAdapter(IWeChatMpApiClient apiClient) : IWeChatMpTemplateSender
|
||||
{
|
||||
public async Task<WeChatMpTemplateSendResult> SendAsync(
|
||||
string openId,
|
||||
string templateId,
|
||||
string? url,
|
||||
IReadOnlyDictionary<string, WeChatMpTemplateDataItem> 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);
|
||||
}
|
||||
}
|
||||
@ -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<IWeChatMpApiClient, WeChatMpApiClient>();
|
||||
services.AddScoped<IWeChatMpTemplateSender, WeChatMpTemplateSenderAdapter>();
|
||||
services.AddSingleton<IWeChatLoginSessionStore, WeChatLoginSessionStore>();
|
||||
services.AddSingleton<IWeChatOpenidMigrateTicketStore, WeChatOpenidMigrateTicketStore>();
|
||||
services.AddTransient<IWeChatEventHandler, WeChatEventHandler>();
|
||||
|
||||
Loading…
Reference in New Issue
Block a user