S8NotificationLayerResolver.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using Admin.NET.Plugin.AiDOP.Entity.S8;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  4. using Admin.NET.Plugin.ApprovalFlow.Service;
  5. using Microsoft.Extensions.Logging;
  6. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  7. /// <summary>
  8. /// S8 通知分层路由解析器(S8-NOTIFY-LAYER-RESOLVE-1)
  9. ///
  10. /// 职责链:
  11. /// (tenantId, factoryId, sceneCode, severity)
  12. /// → 命中 ado_s8_notification_layer 行(多行 OK)
  13. /// → 解析 target_role_ids(dual-format)
  14. /// → 解析 notify_channel(IgnoreCase, ',' / ';' 分隔)
  15. /// → S8RoleResolver → userIds
  16. /// → S8NotificationPushAdapter.PushAsync
  17. /// → 由 PushAdapter 落 AdoS8NotificationLog(**每个「已注册且被选中」的渠道**一条)
  18. ///
  19. /// 不接入 watch / scheduler / task 主链路;不写 ApprovalFlowNotifyLog;
  20. /// 不修改任何 schema;任何分支异常仅 LogWarning,不向上抛。
  21. ///
  22. /// S8-LEGACY-NOTIFY-DECOMMISSION-1:**LEGACY 分层已从 Runtime 退役。**
  23. /// 本类不再读取 <c>ado_s8_notification_layer</c>,收件人唯一来源是
  24. /// <c>ado_s8_notification_recipient</c>(Rule + Event + RecipientType)。
  25. /// 类名保留 "Layer" 只为不牵动全部调用方;它现在是<b>通知派发入口</b>,与分层无关。
  26. /// 旧表 / Entity / CRUD / Seed 类仍存在但已无 Runtime 消费者,物理清理见 P1-C3。
  27. /// </summary>
  28. public class S8NotificationLayerResolver : ITransient
  29. {
  30. private readonly IS8NotificationRecipientResolver _recipientResolver;
  31. private readonly Admin.NET.Core.Service.SysNoticeService _noticeService;
  32. private readonly S8NotificationPushAdapter _pushAdapter;
  33. private readonly ILogger<S8NotificationLayerResolver> _logger;
  34. public S8NotificationLayerResolver(
  35. IS8NotificationRecipientResolver recipientResolver,
  36. Admin.NET.Core.Service.SysNoticeService noticeService,
  37. S8NotificationPushAdapter pushAdapter,
  38. ILogger<S8NotificationLayerResolver> logger)
  39. {
  40. _recipientResolver = recipientResolver;
  41. _noticeService = noticeService;
  42. _pushAdapter = pushAdapter;
  43. _logger = logger;
  44. }
  45. public class DispatchByLayerInput
  46. {
  47. public long TenantId { get; set; }
  48. public long? ExceptionId { get; set; }
  49. public string? ExceptionNo { get; set; }
  50. public string SceneCode { get; set; } = string.Empty;
  51. public string Severity { get; set; } = string.Empty;
  52. public string Title { get; set; } = string.Empty;
  53. public string Content { get; set; } = string.Empty;
  54. public string? Status { get; set; }
  55. public string? SourceRuleCode { get; set; }
  56. /// <summary>
  57. /// S8-NOTIFY-RECIPIENT-1:本次派发对应的事件码(<c>S8NotifyEventCode</c>)。
  58. /// <para>为空表示调用方尚未接入新收件人模型,本次直接走 LEGACY 分层。</para>
  59. /// </summary>
  60. public string? EventCode { get; set; }
  61. /// <summary>
  62. /// 触发本次派发的异常单本体。新模型要靠它解析 ASSIGNEE / REVIEWER / HANDLER_POOL。
  63. /// 为 null 时同样退回 LEGACY 分层。
  64. /// </summary>
  65. public Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8Exception? ExceptionRef { get; set; }
  66. public string? JumpUrl { get; set; }
  67. /// <summary>
  68. /// S8-NOTIFY-WIRE-RECOVERED-1:true 表示恢复事件,BuildNotification 会在 Context 中追加
  69. /// "recovered"="true"。默认 false,保持 CREATED 路径载荷向后兼容。
  70. /// </summary>
  71. public bool Recovered { get; set; }
  72. // ============================================================
  73. // S8-DEMO-IMPACT-SORT-NOTICE-1:影响统计字段(可选;CREATED 路径透传,RECOVERED 路径置空)。
  74. // 由 S8WatchSchedulerService.TryDispatchLayerNotificationAsync 调 S8ImpactMetricsService 计算后传入。
  75. // ============================================================
  76. public int? RepeatCount30d { get; set; }
  77. public decimal? CumulativeLossHours30d { get; set; }
  78. public string? SuggestedAttentionLevel { get; set; }
  79. public string? SuggestedAttentionLabel { get; set; }
  80. public string? ImpactReason { get; set; }
  81. // ============================================================
  82. // S8-R03-OVERDUE-CLOSE-NOTICE-1:关闭超时独立预警字段(可选;仅 CloseAsync 命中 closedAt > slaDeadline 时传入)。
  83. // 语义与 TimeoutFlag 运行时口径分离:TimeoutFlag 仅看未关闭超时;OverdueClosed 是已关闭后的闭环及时性提醒。
  84. // ============================================================
  85. public bool? OverdueClosed { get; set; }
  86. public DateTime? ClosedAt { get; set; }
  87. public DateTime? SlaDeadlineRef { get; set; }
  88. public decimal? OverdueCloseHours { get; set; }
  89. }
  90. /// <summary>
  91. /// 调用方:watch/scheduler/task 在拿到 sceneCode + severity 后调用本方法(本轮不接入主链路)。
  92. /// </summary>
  93. public async Task DispatchByLayerAsync(DispatchByLayerInput input)
  94. {
  95. if (input == null)
  96. {
  97. _logger.LogWarning("S8LayerDispatch: input null");
  98. return;
  99. }
  100. if (string.IsNullOrWhiteSpace(input.SceneCode) || string.IsNullOrWhiteSpace(input.Severity))
  101. {
  102. _logger.LogInformation("S8LayerDispatch skip: empty sceneCode or severity (exceptionId={ExceptionId})", input.ExceptionId);
  103. return;
  104. }
  105. // ── S8-LEGACY-NOTIFY-DECOMMISSION-1:LEGACY 分层已从 Runtime 彻底退役 ──
  106. //
  107. // **本方法不再读取 ado_s8_notification_layer。** 通知收件人的唯一来源是
  108. // Rule-centric 新模型(ado_s8_notification_recipient):
  109. // Event → RecipientType → 责任池 / 当前处理人 / 当前复核人 → SysUser
  110. //
  111. // 为什么整段删掉而不是留个开关:旧链路按 (scene, severity, level) 选人,
  112. // 与新模型的 (rule, event, responsibility) 是两套互不相干的维度。留着它,
  113. // 「新模型没配」就会静默走另一套语义,而管理员在规则弹窗里根本看不到那批人 ——
  114. // 这正是本模块反复出现的失败形态。退役后语义变成:**没配就是没配**,
  115. // 缺口会以 0 收件人的形式暴露出来,而不是被旧配置悄悄兜住。
  116. //
  117. // 刻意<b>不动</b>既有的 fail-loud 语义:新模型查到配置但解析出 0 人时,
  118. // 仍由 DispatchToUsersAsync 落 Warning 后返回,不做任何回落。
  119. //
  120. // 已知缺口(本批明确不修,见 P0-C2 回执):人工主动提报的异常
  121. // SourceRuleCode 为 NULL,新模型会以 rule_code='*' 为键查找,而 '*' 目前
  122. // 没有任何业务写入路径 —— 这类异常的后续事件通知暂时无收件人来源。
  123. // 该缺口由「主动提报通知契约」独立梳理,**不以恢复 LEGACY 的方式兜底**。
  124. if (string.IsNullOrWhiteSpace(input.EventCode) || input.ExceptionRef == null)
  125. {
  126. _logger.LogInformation(
  127. "S8NotifyDispatch skip: 缺少 eventCode 或 exception 引用,无法解析新模型收件人 (exceptionId={ExceptionId} event={Event})",
  128. input.ExceptionId, input.EventCode);
  129. return;
  130. }
  131. var resolution = await _recipientResolver.ResolveAsync(input.TenantId, input.EventCode!, input.ExceptionRef);
  132. if (resolution.Source == "NONE")
  133. {
  134. // 没有配置就是没有配置 —— 不再有第二套语义接管。
  135. _logger.LogInformation(
  136. "S8NotifyDispatch skip: 该 (租户,规则,事件) 未配置收件人,不发送 (tenant={Tenant} rule={Rule} event={Event} exceptionId={ExceptionId})",
  137. input.TenantId, input.ExceptionRef.SourceRuleCode, input.EventCode, input.ExceptionId);
  138. return;
  139. }
  140. await DispatchToUsersAsync(input, resolution);
  141. }
  142. /// <summary>
  143. /// 新收件人模型的投递。复用与 LEGACY 完全相同的 <see cref="BuildNotification"/> 与
  144. /// PushAdapter —— 两条路径只在"收件人怎么来"上不同,通知内容与投递方式必须一致,
  145. /// 否则同一条异常会因为配置来源不同而呈现出不同的消息。
  146. /// </summary>
  147. private async Task DispatchToUsersAsync(DispatchByLayerInput input, S8RecipientResolution resolution)
  148. {
  149. if (resolution.UserIds.Count == 0)
  150. {
  151. // 0 收件人必须可观测:配了却发不出去,与"没配置"是两回事。
  152. // 绝不静默返回让调用方以为发送成功 —— 那正是本模块反复出现的失败形态。
  153. _logger.LogWarning(
  154. "S8RecipientDispatch: resolved 0 recipients (tenant={Tenant} event={Event} exceptionId={ExceptionId} perType={PerType})",
  155. input.TenantId, input.EventCode, input.ExceptionId,
  156. string.Join(',', resolution.PerType.Select(kv => $"{kv.Key}={kv.Value}")));
  157. return;
  158. }
  159. _logger.LogInformation(
  160. "S8RecipientDispatch: source={Source} recipients={Count} (tenant={Tenant} event={Event} exceptionId={ExceptionId} perType={PerType})",
  161. resolution.Source, resolution.UserIds.Count, input.TenantId, input.EventCode, input.ExceptionId,
  162. string.Join(',', resolution.PerType.Select(kv => $"{kv.Key}={kv.Value}")));
  163. // ① 站内信:这是本部署里**唯一会为用户留下一条可见消息**的通道。
  164. //
  165. // 已注册的 pusher 只有 DingTalk / WorkWeixin / SignalR / Sms —— 没有站内信。
  166. // 旧的分层派发因此从来只推 SignalR(用户不在线就等于没发过),
  167. // 而认领 / 转派的站内信是靠一段写死收件人的代码单独发的。
  168. // 新模型把两者合并:所有事件都先落站内信,再推实时通道。
  169. // 少了这一步,本次重构会静默丢掉认领 / 转派原本有的站内信(本地实测已发生)。
  170. try
  171. {
  172. await _noticeService.PublishToUsersAsync(
  173. input.Title,
  174. BuildNoticeContent(input),
  175. resolution.UserIds.ToArray(),
  176. 0,
  177. "S8异常监控");
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.LogWarning(ex, "S8RecipientDispatch: notice publish throw (event={Event})", input.EventCode);
  182. }
  183. // ② 实时通道:在线用户即时可见;不在线也不影响①已经留下的站内信。
  184. try
  185. {
  186. await _pushAdapter.PushAsync(
  187. tenantId: input.TenantId,
  188. factoryId: S8ConfigScope.GlobalFactoryId,
  189. exceptionId: input.ExceptionId,
  190. userIds: resolution.UserIds,
  191. notification: BuildNotification(input),
  192. channels: DefaultChannels);
  193. }
  194. catch (Exception ex)
  195. {
  196. _logger.LogWarning(ex, "S8RecipientDispatch: push throw (event={Event})", input.EventCode);
  197. }
  198. }
  199. /// <summary>站内信正文:内容 + 一个能点回异常详情的链接。</summary>
  200. private static string BuildNoticeContent(DispatchByLayerInput input)
  201. {
  202. var jump = string.IsNullOrWhiteSpace(input.JumpUrl) ? null : $"/#{input.JumpUrl}";
  203. return $"<p>{input.ExceptionNo} {input.Content}</p>"
  204. + (jump == null ? string.Empty : $"<p><a href=\"{jump}\">查看异常详情</a></p>");
  205. }
  206. /// <summary>
  207. /// 新模型的投递渠道。只列<b>真实可用</b>的两个 —— 站内信与 SignalR,
  208. /// 与旧分层表里实际在用的 <c>notify_channel='log,SignalR'</c> 同源。
  209. /// 不为了 UI 看起来完整而虚构短信 / 邮件之类当前根本没有实现的渠道。
  210. /// </summary>
  211. private static readonly List<string> DefaultChannels = new() { "log", "SignalR" };
  212. private static FlowNotification BuildNotification(DispatchByLayerInput input)
  213. {
  214. // 注意:FlowNotificationTypeEnum 不含 S8_EXCEPTION 值;BizType 字段承载 "S8_EXCEPTION" 语义。
  215. // InstanceId 仅作为载荷字段(PushAdapter 不写 ApprovalFlowNotifyLog,不会脏写该列)。
  216. var ctx = new Dictionary<string, string?>
  217. {
  218. ["exceptionId"] = input.ExceptionId?.ToString(),
  219. ["exceptionNo"] = input.ExceptionNo,
  220. ["sceneCode"] = input.SceneCode,
  221. ["severity"] = input.Severity,
  222. ["status"] = input.Status,
  223. ["sourceRuleCode"] = input.SourceRuleCode,
  224. ["jumpUrl"] = input.JumpUrl,
  225. };
  226. if (input.Recovered) ctx["recovered"] = "true";
  227. // S8-DEMO-IMPACT-SORT-NOTICE-1:影响统计 5 字段,仅 CREATED 路径携带,RECOVERED 路径不传入。
  228. if (input.RepeatCount30d.HasValue)
  229. ctx["repeatCount30d"] = input.RepeatCount30d.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
  230. if (input.CumulativeLossHours30d.HasValue)
  231. ctx["cumulativeLossHours30d"] = input.CumulativeLossHours30d.Value.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture);
  232. if (!string.IsNullOrWhiteSpace(input.SuggestedAttentionLevel))
  233. ctx["suggestedAttentionLevel"] = input.SuggestedAttentionLevel;
  234. if (!string.IsNullOrWhiteSpace(input.SuggestedAttentionLabel))
  235. ctx["suggestedAttentionLabel"] = input.SuggestedAttentionLabel;
  236. if (!string.IsNullOrWhiteSpace(input.ImpactReason))
  237. ctx["impactReason"] = input.ImpactReason;
  238. // S8-R03-OVERDUE-CLOSE-NOTICE-1:关闭超时独立预警 4 字段,仅 CloseAsync 命中 closedAt > slaDeadline 时携带。
  239. if (input.OverdueClosed == true)
  240. ctx["overdueClosed"] = "true";
  241. if (input.ClosedAt.HasValue)
  242. ctx["closedAt"] = input.ClosedAt.Value.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
  243. if (input.SlaDeadlineRef.HasValue)
  244. ctx["slaDeadline"] = input.SlaDeadlineRef.Value.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
  245. if (input.OverdueCloseHours.HasValue)
  246. ctx["overdueCloseHours"] = input.OverdueCloseHours.Value.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture);
  247. return new FlowNotification
  248. {
  249. Type = FlowNotificationTypeEnum.NewTask,
  250. BizType = "S8_EXCEPTION",
  251. InstanceId = input.ExceptionId ?? 0,
  252. Title = input.Title ?? string.Empty,
  253. Content = input.Content ?? string.Empty,
  254. Context = ctx,
  255. };
  256. }
  257. public static List<string> ParseChannels(string? csv)
  258. {
  259. if (string.IsNullOrWhiteSpace(csv)) return new List<string>();
  260. return csv.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
  261. }
  262. }