using System.Net.Mail; using System.Net.Sockets; using System.Text.Json; using Fake.DependencyInjection; using Fake.EventBus.Distributed; using Fake.UnitOfWork; using Microsoft.Extensions.Logging; using Oms.Application.Dtos.OpenApi; using Oms.Application.Dtos.System; using Oms.Application.Integrations.SmallBagTrack; using Oms.Application.Integrations.WeChat; using Oms.Application.Messaging; using Oms.Application.Messaging.OrderSideEffects; using Oms.Application.Services.Orders; using Oms.Application.Services.System; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.SystemAggregate.Consts; using Oms.Domain.SystemAggregate.Entities; using Oms.Domain.SystemAggregate.Repositories; namespace Oms.Application.Services.WeChatNotify; /// /// 订单状态通知调度:微信模板消息 + batch-email 邮件;业务侧优先 Outbox 异步投递。 /// public class WechatOrderNotifyDispatcher( IWechatNotifyTemplateRepository templateRepository, ICustomerWechatNotifyPrefRepository prefRepository, IOrderNotifyLogRepository notifyLogRepository, ICustomerRepository customerRepository, ISystemOtherConfigRepository otherConfigRepository, ISystemBatchEmailTemplateRepository batchEmailTemplateRepository, ISystemBatchEmailAccountRepository batchEmailAccountRepository, ISmallBagTrackOrderClient trackOrderClient, IWeChatMpTemplateSender templateSender, OrderOperationLogWriter operationLogWriter, IDistributedEventBus eventBus, IUnitOfWorkManager unitOfWorkManager, ILogger logger) : IScopedDependency { private const string WechatTemplateSendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send"; private static readonly TimeSpan DedupWindow = TimeSpan.FromMinutes(30); /// 微信侧可重试 errcode(token/系统繁忙等)。 private static readonly HashSet WechatRetryableErrCodes = [ -1, 40001, 42001, 45009, 45011 ]; /// 未关注 / 拒收模板等业务失败(勿重试)。 private static readonly HashSet WechatUnfollowErrCodes = [ 43004, 43101 ]; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; /// /// 投递订单通知(微信 + 邮件)。有事务 UoW 时写 Outbox;否则同步兜底。 /// public async Task EnqueueNotifyAsync( Order order, string eventCode, string? remark = null, bool force = false, CancellationToken cancellationToken = default) { if (order.Id <= 0 || string.IsNullOrWhiteSpace(eventCode)) { return; } if (OmsOutboxUnitOfWork.IsAmbientTransactional(unitOfWorkManager)) { await eventBus.PublishAsync(new OrderNotifyIntegrationEvent { OrderId = order.Id, EventCode = eventCode.Trim(), Remark = remark, Force = force }); return; } await TryNotifyAsync(order, eventCode, remark, force, cancellationToken); } /// /// 出库通知统一入口(扫码出库 / 装袋出库共用;幂等靠 30 分钟 sent 去重)。 /// public Task EnqueueOutboundNotifyAsync( Order order, CancellationToken cancellationToken = default) => EnqueueNotifyAsync(order, WechatOrderNotifyEventCodes.Outbound, cancellationToken: cancellationToken); /// /// 按 OrderId 投递(消费者/无实体场景)。 /// public async Task EnqueueNotifyByOrderIdAsync( int orderId, string eventCode, string? remark = null, bool force = false, CancellationToken cancellationToken = default) { if (orderId <= 0 || string.IsNullOrWhiteSpace(eventCode)) { return; } if (OmsOutboxUnitOfWork.IsAmbientTransactional(unitOfWorkManager)) { await eventBus.PublishAsync(new OrderNotifyIntegrationEvent { OrderId = orderId, EventCode = eventCode.Trim(), Remark = remark, Force = force }); return; } using var unitOfWork = unitOfWorkManager.Begin(OmsOutboxUnitOfWork.Independent()); await eventBus.PublishAsync(new OrderNotifyIntegrationEvent { OrderId = orderId, EventCode = eventCode.Trim(), Remark = remark, Force = force }); await unitOfWork.CompleteAsync(cancellationToken); } /// /// 同步发送(试发 / Outbox 消费者 / 无队列兜底);失败只记日志。 /// public async Task TryNotifyAsync( Order order, string eventCode, string? remark = null, bool force = false, CancellationToken cancellationToken = default) { try { await NotifyDetailedAsync(order, eventCode, remark, force, cancellationToken); } catch (OrderNotifyRetryableException) { throw; } catch (Exception ex) { logger.LogWarning( ex, "订单通知异常 OrderId={OrderId} Event={EventCode}", order.Id, eventCode); } } /// /// 运营试发 / 明细发送:微信 + 邮件;业务跳过/失败写入结果。 /// 可重试失败抛 (force 试发除外)。 /// public async Task NotifyDetailedAsync( Order order, string eventCode, string? remark = null, bool force = false, CancellationToken cancellationToken = default) { var result = await NotifyWechatCoreAsync(order, eventCode, remark, force, cancellationToken); try { result.Email = await NotifyEmailCoreAsync(order, eventCode, remark, force, cancellationToken); } catch (OrderNotifyRetryableException) { throw; } catch (Exception ex) { logger.LogWarning( ex, "订单邮件通知异常 OrderId={OrderId} Event={EventCode}", order.Id, eventCode); result.Email = new TrialOrderNotifyEmailResultOutput { Success = false, Skipped = false, Status = "failed", Message = ex.Message }; if (!force && IsRetryableTransport(ex)) { throw new OrderNotifyRetryableException($"邮件发送临时失败:{ex.Message}", ex); } } if (!force) { ThrowIfRetryableWechatFailure(result); ThrowIfRetryableEmailFailure(result.Email); } return result; } private async Task NotifyWechatCoreAsync( Order order, string eventCode, string? remark, bool force, CancellationToken cancellationToken) { var result = new TrialWechatOrderNotifyResultOutput { OrderId = order.Id, ServiceNo = order.ServiceNo, EventCode = eventCode, Status = "skipped", Skipped = true }; if (!WechatOrderNotifyEventCodes.IsKnown(eventCode)) { result.Message = "未知事件码"; return result; } var normalized = WechatOrderNotifyEventCodes.Normalize(eventCode); var eventName = WechatOrderNotifyEventCodes.GetName(normalized) ?? normalized; result.EventCode = normalized; result.EventName = eventName; if (!force && string.Equals(normalized, WechatOrderNotifyEventCodes.PendingPayment, StringComparison.OrdinalIgnoreCase) && !string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase)) { result.Message = "订单已非待支付,跳过待支付通知"; await WriteWechatLogAsync( order, customerId: order.CustomerId ?? 0, normalized, openId: null, templateId: null, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken); if (template == null || !template.IsEnabled) { result.TemplateId = template?.TemplateId; result.Message = "运营未启用该事件模板"; await WriteWechatLogAsync( order, customerId: order.CustomerId ?? 0, normalized, openId: null, templateId: template?.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } result.TemplateId = template.TemplateId; if (string.IsNullOrWhiteSpace(template.TemplateId)) { result.Message = "未配置微信 TemplateId"; await WriteWechatLogAsync( order, customerId: order.CustomerId ?? 0, normalized, openId: null, templateId: null, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } if (order.CustomerId is not int customerId || customerId <= 0) { result.Message = "订单无客户"; await WriteWechatLogAsync( order, customerId: 0, normalized, openId: null, templateId: template.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } if (!force) { var pref = await prefRepository.GetByCustomerAndEventAsync(customerId, normalized, cancellationToken); if (pref is not { IsSubscribed: true }) { result.Message = "客户未订阅该事件"; await WriteWechatLogAsync( order, customerId, normalized, openId: null, templateId: template.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } var since = DateTime.Now.Subtract(DedupWindow); if (await notifyLogRepository.ExistsRecentSentAsync( order.Id, normalized, OrderNotifyChannels.Wechat, since, cancellationToken)) { result.Message = $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过"; await WriteWechatLogAsync( order, customerId, normalized, openId: null, templateId: template.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } } var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId, cancellationToken); var openId = customer?.WechatOpenid?.Trim(); if (string.IsNullOrWhiteSpace(openId)) { result.Message = "客户未绑定微信 OpenId"; await WriteWechatLogAsync( order, customerId, normalized, openId: null, templateId: template.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } result.OpenId = openId; var placeholders = await BuildPlaceholdersAsync( order, eventName, remark, customer?.CustomerName, cancellationToken); var data = BuildTemplateData(template.FieldMappingJson, placeholders); if (data.Count == 0) { result.Message = "字段映射为空或无效"; await WriteWechatLogAsync( order, customerId, normalized, openId, template.TemplateId, status: "skipped", errMsg: result.Message, cancellationToken: cancellationToken); return result; } var url = await BuildUrlAsync(template.UrlTemplate, order, cancellationToken); result.Url = url; result.RequestUrl = WechatTemplateSendUrl; var wechatRequest = BuildWechatRequestBody(openId, template.TemplateId.Trim(), url, data); result.RequestBody = OmsDocHelper.SerializeJson(wechatRequest); var payloadJson = OmsDocHelper.SerializeJson(new { openId, templateId = template.TemplateId, url, data }); var sendResult = await templateSender.SendAsync( openId, template.TemplateId.Trim(), url, data, cancellationToken); result.Skipped = false; result.Success = sendResult.Success; result.Status = sendResult.Success ? "sent" : "failed"; result.WxMsgId = sendResult.MsgId; result.ErrCode = sendResult.ErrCode == 0 ? null : sendResult.ErrCode; result.Message = sendResult.Success ? "发送成功" : MapWechatErrMsg(sendResult.ErrCode, sendResult.ErrMsg); result.ResponseBody = BuildWechatResponseBody(sendResult); await WriteWechatLogAsync( order, customerId, normalized, openId, template.TemplateId, status: result.Status, errCode: sendResult.ErrCode == 0 ? null : sendResult.ErrCode, errMsg: sendResult.Success ? null : result.Message, wxMsgId: sendResult.MsgId, payloadJson: payloadJson, cancellationToken: cancellationToken); await WriteOpsNotifySummaryAsync( order, OrderOperationActionCodes.NotifyWechat, eventName, result.Status, result.Message, force, detail: sendResult.Success ? (string.IsNullOrWhiteSpace(sendResult.MsgId) ? null : $"msgid={sendResult.MsgId}") : (result.ErrCode is int ec ? $"errcode={ec}" : null)); if (!sendResult.Success) { logger.LogWarning( "微信订单通知失败 OrderId={OrderId} Event={Event} Err={ErrCode} {ErrMsg}", order.Id, normalized, sendResult.ErrCode, result.Message); } return result; } private async Task NotifyEmailCoreAsync( Order order, string eventCode, string? remark, bool force, CancellationToken cancellationToken) { var result = new TrialOrderNotifyEmailResultOutput { Status = "skipped", Skipped = true }; if (!WechatOrderNotifyEventCodes.IsKnown(eventCode)) { result.Message = "未知事件码"; return result; } var normalized = WechatOrderNotifyEventCodes.Normalize(eventCode); var eventName = WechatOrderNotifyEventCodes.GetName(normalized) ?? normalized; if (!force && string.Equals(normalized, WechatOrderNotifyEventCodes.PendingPayment, StringComparison.OrdinalIgnoreCase) && !string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase)) { result.Message = "订单已非待支付,跳过待支付通知"; await WriteEmailLogAsync( order, customerId: order.CustomerId ?? 0, normalized, toEmail: null, templateName: null, subject: null, status: "skipped", errMsg: result.Message, smtpUsername: null, payloadJson: null, cancellationToken); return result; } var template = await templateRepository.GetByEventCodeAsync(normalized, cancellationToken); if (template is not { EmailEnabled: true }) { result.Message = "运营未启用邮件通知"; return result; } var tplName = template.EmailTemplateName?.Trim(); var templateOwner = template.EmailTemplateOwnerUserId ?? (template.EmailSmtpOwnerUserId is > 0 ? template.EmailSmtpOwnerUserId : null); var smtpOwner = template.EmailSmtpOwnerUserId ?? template.EmailTemplateOwnerUserId; if (string.IsNullOrWhiteSpace(tplName) || templateOwner is not int tplOwner || tplOwner <= 0 || smtpOwner is not int smtpId || smtpId < 0) { result.Message = "未绑定邮件模板或发信账号"; return result; } result.TemplateName = tplName; var batchTpl = await batchEmailTemplateRepository.GetByOwnerAndNameAsync( tplOwner, tplName, cancellationToken); if (batchTpl == null) { result.Message = $"邮件模板不存在:{tplName}"; return result; } var account = await batchEmailAccountRepository.GetByOwnerAsync(smtpId, cancellationToken); if (account == null || string.IsNullOrWhiteSpace(account.SmtpPassword)) { result.Message = smtpId == WechatOrderNotifyConfigService.SystemSmtpOwnerUserId ? "系统发信 SMTP 未配置" : "发信人未配置 SMTP(请到「批量邮件」保存邮箱账号)"; return result; } result.SmtpUsername = account.SmtpUsername; if (order.CustomerId is not int customerId || customerId <= 0) { result.Message = "订单无客户"; return result; } if (!force) { var pref = await prefRepository.GetByCustomerAndEventAsync(customerId, normalized, cancellationToken); if (pref is not { IsEmailSubscribed: true }) { result.Message = "客户未订阅邮件通知"; await WriteEmailLogAsync( order, customerId, normalized, toEmail: null, templateName: tplName, subject: null, status: "skipped", errMsg: result.Message, smtpUsername: account.SmtpUsername, payloadJson: null, cancellationToken); return result; } var since = DateTime.Now.Subtract(DedupWindow); if (await notifyLogRepository.ExistsRecentSentAsync( order.Id, normalized, OrderNotifyChannels.Email, since, cancellationToken)) { result.Message = $"去重:{DedupWindow.TotalMinutes:0} 分钟内已发送过"; await WriteEmailLogAsync( order, customerId, normalized, toEmail: null, templateName: tplName, subject: null, status: "skipped", errMsg: result.Message, smtpUsername: account.SmtpUsername, payloadJson: null, cancellationToken); return result; } } var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId, cancellationToken); var toEmail = customer?.Email?.Trim(); if (string.IsNullOrWhiteSpace(toEmail) || !toEmail.Contains('@')) { result.Message = "客户邮箱无效"; await WriteEmailLogAsync( order, customerId, normalized, toEmail: toEmail, templateName: tplName, subject: null, status: "skipped", errMsg: result.Message, smtpUsername: account.SmtpUsername, payloadJson: null, cancellationToken); return result; } result.ToEmail = toEmail; var placeholders = await BuildPlaceholdersAsync( order, eventName, remark, customer?.CustomerName, cancellationToken); var subject = ApplyEmailPlaceholders(batchTpl.Subject, placeholders); var body = ApplyEmailPlaceholders(batchTpl.Content ?? string.Empty, placeholders); result.Subject = subject; result.Body = body; var payloadJson = OmsDocHelper.SerializeJson(new { toEmail, templateName = tplName, subject, smtpOwner = smtpId }); try { await BatchEmailSmtpHelper.SendAsync( account.SmtpUsername, account.SmtpPassword, account.ServerType, toEmail, subject, body, "text", account.FromName, cancellationToken); } catch (Exception ex) when (!force && IsRetryableTransport(ex)) { await WriteEmailLogAsync( order, customerId, normalized, toEmail, tplName, subject, status: "failed", errMsg: Truncate(ex.Message, 512), smtpUsername: account.SmtpUsername, payloadJson: payloadJson, cancellationToken); await WriteOpsNotifySummaryAsync( order, OrderOperationActionCodes.NotifyEmail, eventName, "failed", Truncate(ex.Message, 200), force, detail: $"to={toEmail}"); throw new OrderNotifyRetryableException($"邮件发送临时失败:{ex.Message}", ex); } catch (Exception ex) { result.Skipped = false; result.Success = false; result.Status = "failed"; result.Message = ex.Message; await WriteEmailLogAsync( order, customerId, normalized, toEmail, tplName, subject, status: "failed", errMsg: Truncate(ex.Message, 512), smtpUsername: account.SmtpUsername, payloadJson: payloadJson, cancellationToken); await WriteOpsNotifySummaryAsync( order, OrderOperationActionCodes.NotifyEmail, eventName, "failed", Truncate(ex.Message, 200), force, detail: $"to={toEmail}"); return result; } result.Skipped = false; result.Success = true; result.Status = "sent"; result.Message = "发送成功"; await WriteEmailLogAsync( order, customerId, normalized, toEmail, tplName, subject, status: "sent", errMsg: null, smtpUsername: account.SmtpUsername, payloadJson: payloadJson, cancellationToken); await WriteOpsNotifySummaryAsync( order, OrderOperationActionCodes.NotifyEmail, eventName, "sent", "发送成功", force, detail: $"to={toEmail}"); return result; } /// /// 仅 sent/failed 写入订单操作日志(skipped 不写,避免刷屏)。 /// private async Task WriteOpsNotifySummaryAsync( Order order, string action, string eventName, string status, string? message, bool force, string? detail = null) { if (!string.Equals(status, "sent", StringComparison.OrdinalIgnoreCase) && !string.Equals(status, "failed", StringComparison.OrdinalIgnoreCase)) { return; } var statusText = string.Equals(status, "sent", StringComparison.OrdinalIgnoreCase) ? "成功" : "失败"; var parts = new List { $"{eventName}:{statusText}" }; if (!string.IsNullOrWhiteSpace(message) && !string.Equals(message, "发送成功", StringComparison.Ordinal)) { parts.Add(message.Trim()); } if (!string.IsNullOrWhiteSpace(detail)) { parts.Add(detail.Trim()); } if (force) { parts.Add("试发"); } await operationLogWriter.TryWriteSimpleAsync( order, action, string.Join(";", parts), operatorId: 0, operatorName: "系统通知", operatorType: "system", source: "notify"); } private static void ThrowIfRetryableWechatFailure(TrialWechatOrderNotifyResultOutput result) { if (result.Skipped || result.Success || result.ErrCode is not int code) { return; } if (WechatRetryableErrCodes.Contains(code)) { throw new OrderNotifyRetryableException( $"微信发送可重试失败 errcode={code}: {result.Message}"); } } private static void ThrowIfRetryableEmailFailure(TrialOrderNotifyEmailResultOutput? email) { if (email is not { Skipped: false, Success: false }) { return; } // 非临时失败已在 catch 中分类;此处兜底:无明确业务文案时不重试 } private static bool IsRetryableTransport(Exception ex) => ex is SocketException or TimeoutException or IOException or SmtpException or HttpRequestException || (ex.InnerException != null && IsRetryableTransport(ex.InnerException)); private static string MapWechatErrMsg(int errCode, string? errMsg) { if (WechatUnfollowErrCodes.Contains(errCode)) { return "用户未关注公众号或未接受模板消息,请引导客户关注后再推"; } return string.IsNullOrWhiteSpace(errMsg) ? $"发送失败(errcode={errCode})" : errMsg.Trim(); } /// /// 替换邮件占位符:支持 batch-email 中文词 + OMS 英文字段。 /// private static string ApplyEmailPlaceholders( string template, IReadOnlyDictionary placeholders) { if (string.IsNullOrEmpty(template)) { return string.Empty; } var value = template; foreach (var (key, replacement) in placeholders) { value = value.Replace($"{{{key}}}", replacement ?? string.Empty, StringComparison.OrdinalIgnoreCase); } value = value .Replace("{客户单号}", placeholders.GetValueOrDefault("clientNo") ?? string.Empty, StringComparison.Ordinal) .Replace("{运单号}", placeholders.GetValueOrDefault("serviceNo") ?? string.Empty, StringComparison.Ordinal) .Replace("{换单号}", placeholders.GetValueOrDefault("serviceNo") ?? string.Empty, StringComparison.Ordinal) .Replace("{最新轨迹}", placeholders.GetValueOrDefault("latestTrack") ?? string.Empty, StringComparison.Ordinal) .Replace("{客户名称}", placeholders.GetValueOrDefault("customerName") ?? string.Empty, StringComparison.Ordinal) .Replace("{收件国家}", placeholders.GetValueOrDefault("consigneeCountry") ?? string.Empty, StringComparison.Ordinal) .Replace("{应付金额}", placeholders.GetValueOrDefault("payableAmount") ?? string.Empty, StringComparison.Ordinal) .Replace("{问题内容}", placeholders.GetValueOrDefault("issueContent") ?? string.Empty, StringComparison.Ordinal) .Replace("{入库时间}", placeholders.GetValueOrDefault("inboundTime") ?? string.Empty, StringComparison.Ordinal) .Replace("{出库时间}", placeholders.GetValueOrDefault("outboundTime") ?? string.Empty, StringComparison.Ordinal) .Replace("{签收时间}", placeholders.GetValueOrDefault("signTime") ?? string.Empty, StringComparison.Ordinal) .Replace("{支付时间}", placeholders.GetValueOrDefault("payTime") ?? string.Empty, StringComparison.Ordinal) .Replace("{事件名}", placeholders.GetValueOrDefault("eventName") ?? string.Empty, StringComparison.Ordinal) .Replace("{事件时间}", placeholders.GetValueOrDefault("eventTime") ?? string.Empty, StringComparison.Ordinal); return value; } private static object BuildWechatRequestBody( string openId, string templateId, string? url, IReadOnlyDictionary data) { 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 }; } return string.IsNullOrWhiteSpace(url) ? new { touser = openId, template_id = templateId, data = dataPayload } : new { touser = openId, template_id = templateId, url, data = dataPayload }; } private static string BuildWechatResponseBody(WeChatMpTemplateSendResult sendResult) { if (sendResult.Success) { return OmsDocHelper.SerializeJson(new { errcode = 0, errmsg = "ok", msgid = sendResult.MsgId }) ?? "{}"; } return OmsDocHelper.SerializeJson(new { errcode = sendResult.ErrCode, errmsg = sendResult.ErrMsg ?? "failed" }) ?? "{}"; } private async Task> BuildPlaceholdersAsync( Order order, string eventName, string? remark, string? customerName, CancellationToken cancellationToken) { var statusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) ?? order.OrderStatus; var issueContent = FirstNonEmpty(order.IssueContent, order.IssueTitle, remark); var latestTrack = await ResolveLatestTrackAsync(order, statusName, remark, issueContent, cancellationToken); return new Dictionary(StringComparer.OrdinalIgnoreCase) { ["serviceNo"] = order.ServiceNo ?? string.Empty, ["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, ["payableAmount"] = FormatAmount(order.PayableAmount), ["issueContent"] = issueContent, ["issueTitle"] = order.IssueTitle?.Trim() ?? string.Empty, ["issueRemark"] = order.IssueRemark?.Trim() ?? string.Empty, ["inboundTime"] = FormatDateTime(order.ReceiveTime), ["outboundTime"] = FormatDateTime(order.ShipTime), ["signTime"] = FormatDateTime(order.SignTime), ["payTime"] = FormatDateTime(order.PayTime), ["latestTrack"] = latestTrack, }; } private async Task ResolveLatestTrackAsync( Order order, string statusName, string? remark, string issueContent, CancellationToken cancellationToken) { if (!string.IsNullOrWhiteSpace(order.ServiceNo)) { try { var events = await trackOrderClient.QuerySmallBagTracksAsync( order.ServiceNo, cancellationToken); var latest = PickLatestTrack(events); if (!string.IsNullOrWhiteSpace(latest)) { return latest; } } catch (Exception ex) { logger.LogDebug( ex, "查询最新轨迹失败,回退占位 OrderId={OrderId}", order.Id); } } return FirstNonEmpty(remark, issueContent, statusName); } private static string? PickLatestTrack(IReadOnlyList events) { if (events == null || events.Count == 0) { return null; } var ordered = events .OrderByDescending(x => x.Time ?? DateTime.MinValue) .ThenByDescending(x => x.Content) .ToList(); var hit = ordered.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Content)); if (hit == null) { return null; } var time = hit.Time.HasValue ? hit.Time.Value.ToString("yyyy-MM-dd HH:mm") + " " : string.Empty; return $"{time}{hit.Content!.Trim()}"; } private static string FormatAmount(decimal? amount) => amount.HasValue ? amount.Value.ToString("0.00") : string.Empty; private static string FormatDateTime(DateTime? value) => value.HasValue ? value.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty; private static string FirstNonEmpty(params string?[] values) { foreach (var value in values) { if (!string.IsNullOrWhiteSpace(value)) { return value.Trim(); } } return string.Empty; } private static Dictionary BuildTemplateData( string? fieldMappingJson, IReadOnlyDictionary placeholders) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrWhiteSpace(fieldMappingJson)) { 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 Task WriteWechatLogAsync( 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) => WriteNotifyLogAsync( order, customerId, OrderNotifyChannels.Wechat, eventCode, recipient: openId, templateRef: templateId, subject: null, status, errMsg, errCode, providerMsgId: wxMsgId, smtpUsername: null, payloadJson, cancellationToken); private Task WriteEmailLogAsync( Order order, int customerId, string eventCode, string? toEmail, string? templateName, string? subject, string status, string? errMsg, string? smtpUsername, string? payloadJson, CancellationToken cancellationToken) => WriteNotifyLogAsync( order, customerId, OrderNotifyChannels.Email, eventCode, recipient: toEmail, templateRef: templateName, subject, status, errMsg, errCode: null, providerMsgId: null, smtpUsername, payloadJson, cancellationToken); private async Task WriteNotifyLogAsync( Order order, int customerId, string channel, string eventCode, string? recipient, string? templateRef, string? subject, string status, string? errMsg, int? errCode, string? providerMsgId, string? smtpUsername, string? payloadJson, CancellationToken cancellationToken) { try { await notifyLogRepository.InsertAsync( new OrderNotifyLog { CustomerId = customerId, OrderId = order.Id, Channel = channel, EventCode = eventCode, Recipient = Truncate(recipient, 256), TemplateRef = Truncate(templateRef, 128), Subject = Truncate(subject, 512), Status = status, ProviderMsgId = Truncate(providerMsgId, 64), ErrCode = errCode, ErrMsg = Truncate(errMsg, 512), SmtpUsername = Truncate(smtpUsername, 256), PayloadJson = payloadJson }, cancellationToken: cancellationToken); } catch (Exception ex) { logger.LogWarning( ex, "写订单通知日志失败 OrderId={OrderId} Channel={Channel}", order.Id, channel); } } 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; } } }