logger)
{
_recipientResolver = recipientResolver;
_noticeService = noticeService;
_pushAdapter = pushAdapter;
_logger = logger;
}
public class DispatchByLayerInput
{
public long TenantId { get; set; }
public long? ExceptionId { get; set; }
public string? ExceptionNo { get; set; }
public string SceneCode { get; set; } = string.Empty;
public string Severity { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public string? Status { get; set; }
public string? SourceRuleCode { get; set; }
///
/// S8-NOTIFY-RECIPIENT-1:本次派发对应的事件码(S8NotifyEventCode)。
/// 为空表示调用方尚未接入新收件人模型,本次直接走 LEGACY 分层。
///
public string? EventCode { get; set; }
///
/// 触发本次派发的异常单本体。新模型要靠它解析 ASSIGNEE / REVIEWER / HANDLER_POOL。
/// 为 null 时同样退回 LEGACY 分层。
///
public Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8Exception? ExceptionRef { get; set; }
public string? JumpUrl { get; set; }
///
/// S8-NOTIFY-WIRE-RECOVERED-1:true 表示恢复事件,BuildNotification 会在 Context 中追加
/// "recovered"="true"。默认 false,保持 CREATED 路径载荷向后兼容。
///
public bool Recovered { get; set; }
// ============================================================
// S8-DEMO-IMPACT-SORT-NOTICE-1:影响统计字段(可选;CREATED 路径透传,RECOVERED 路径置空)。
// 由 S8WatchSchedulerService.TryDispatchLayerNotificationAsync 调 S8ImpactMetricsService 计算后传入。
// ============================================================
public int? RepeatCount30d { get; set; }
public decimal? CumulativeLossHours30d { get; set; }
public string? SuggestedAttentionLevel { get; set; }
public string? SuggestedAttentionLabel { get; set; }
public string? ImpactReason { get; set; }
// ============================================================
// S8-R03-OVERDUE-CLOSE-NOTICE-1:关闭超时独立预警字段(可选;仅 CloseAsync 命中 closedAt > slaDeadline 时传入)。
// 语义与 TimeoutFlag 运行时口径分离:TimeoutFlag 仅看未关闭超时;OverdueClosed 是已关闭后的闭环及时性提醒。
// ============================================================
public bool? OverdueClosed { get; set; }
public DateTime? ClosedAt { get; set; }
public DateTime? SlaDeadlineRef { get; set; }
public decimal? OverdueCloseHours { get; set; }
}
///
/// 调用方:watch/scheduler/task 在拿到 sceneCode + severity 后调用本方法(本轮不接入主链路)。
///
public async Task DispatchByLayerAsync(DispatchByLayerInput input)
{
if (input == null)
{
_logger.LogWarning("S8LayerDispatch: input null");
return;
}
if (string.IsNullOrWhiteSpace(input.SceneCode) || string.IsNullOrWhiteSpace(input.Severity))
{
_logger.LogInformation("S8LayerDispatch skip: empty sceneCode or severity (exceptionId={ExceptionId})", input.ExceptionId);
return;
}
// ── S8-LEGACY-NOTIFY-DECOMMISSION-1:LEGACY 分层已从 Runtime 彻底退役 ──
//
// **本方法不再读取 ado_s8_notification_layer。** 通知收件人的唯一来源是
// Rule-centric 新模型(ado_s8_notification_recipient):
// Event → RecipientType → 责任池 / 当前处理人 / 当前复核人 → SysUser
//
// 为什么整段删掉而不是留个开关:旧链路按 (scene, severity, level) 选人,
// 与新模型的 (rule, event, responsibility) 是两套互不相干的维度。留着它,
// 「新模型没配」就会静默走另一套语义,而管理员在规则弹窗里根本看不到那批人 ——
// 这正是本模块反复出现的失败形态。退役后语义变成:**没配就是没配**,
// 缺口会以 0 收件人的形式暴露出来,而不是被旧配置悄悄兜住。
//
// 刻意不动既有的 fail-loud 语义:新模型查到配置但解析出 0 人时,
// 仍由 DispatchToUsersAsync 落 Warning 后返回,不做任何回落。
//
// 已知缺口(本批明确不修,见 P0-C2 回执):人工主动提报的异常
// SourceRuleCode 为 NULL,新模型会以 rule_code='*' 为键查找,而 '*' 目前
// 没有任何业务写入路径 —— 这类异常的后续事件通知暂时无收件人来源。
// 该缺口由「主动提报通知契约」独立梳理,**不以恢复 LEGACY 的方式兜底**。
if (string.IsNullOrWhiteSpace(input.EventCode) || input.ExceptionRef == null)
{
_logger.LogInformation(
"S8NotifyDispatch skip: 缺少 eventCode 或 exception 引用,无法解析新模型收件人 (exceptionId={ExceptionId} event={Event})",
input.ExceptionId, input.EventCode);
return;
}
var resolution = await _recipientResolver.ResolveAsync(input.TenantId, input.EventCode!, input.ExceptionRef);
if (resolution.Source == "NONE")
{
// 没有配置就是没有配置 —— 不再有第二套语义接管。
_logger.LogInformation(
"S8NotifyDispatch skip: 该 (租户,规则,事件) 未配置收件人,不发送 (tenant={Tenant} rule={Rule} event={Event} exceptionId={ExceptionId})",
input.TenantId, input.ExceptionRef.SourceRuleCode, input.EventCode, input.ExceptionId);
return;
}
await DispatchToUsersAsync(input, resolution);
}
///
/// 新收件人模型的投递。复用与 LEGACY 完全相同的 与
/// PushAdapter —— 两条路径只在"收件人怎么来"上不同,通知内容与投递方式必须一致,
/// 否则同一条异常会因为配置来源不同而呈现出不同的消息。
///
private async Task DispatchToUsersAsync(DispatchByLayerInput input, S8RecipientResolution resolution)
{
if (resolution.UserIds.Count == 0)
{
// 0 收件人必须可观测:配了却发不出去,与"没配置"是两回事。
// 绝不静默返回让调用方以为发送成功 —— 那正是本模块反复出现的失败形态。
_logger.LogWarning(
"S8RecipientDispatch: resolved 0 recipients (tenant={Tenant} event={Event} exceptionId={ExceptionId} perType={PerType})",
input.TenantId, input.EventCode, input.ExceptionId,
string.Join(',', resolution.PerType.Select(kv => $"{kv.Key}={kv.Value}")));
return;
}
_logger.LogInformation(
"S8RecipientDispatch: source={Source} recipients={Count} (tenant={Tenant} event={Event} exceptionId={ExceptionId} perType={PerType})",
resolution.Source, resolution.UserIds.Count, input.TenantId, input.EventCode, input.ExceptionId,
string.Join(',', resolution.PerType.Select(kv => $"{kv.Key}={kv.Value}")));
// ① 站内信:这是本部署里**唯一会为用户留下一条可见消息**的通道。
//
// 已注册的 pusher 只有 DingTalk / WorkWeixin / SignalR / Sms —— 没有站内信。
// 旧的分层派发因此从来只推 SignalR(用户不在线就等于没发过),
// 而认领 / 转派的站内信是靠一段写死收件人的代码单独发的。
// 新模型把两者合并:所有事件都先落站内信,再推实时通道。
// 少了这一步,本次重构会静默丢掉认领 / 转派原本有的站内信(本地实测已发生)。
try
{
await _noticeService.PublishToUsersAsync(
input.Title,
BuildNoticeContent(input),
resolution.UserIds.ToArray(),
0,
"S8异常监控");
}
catch (Exception ex)
{
_logger.LogWarning(ex, "S8RecipientDispatch: notice publish throw (event={Event})", input.EventCode);
}
// ② 实时通道:在线用户即时可见;不在线也不影响①已经留下的站内信。
try
{
await _pushAdapter.PushAsync(
tenantId: input.TenantId,
factoryId: S8ConfigScope.GlobalFactoryId,
exceptionId: input.ExceptionId,
userIds: resolution.UserIds,
notification: BuildNotification(input),
channels: DefaultChannels);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "S8RecipientDispatch: push throw (event={Event})", input.EventCode);
}
}
/// 站内信正文:内容 + 一个能点回异常详情的链接。
private static string BuildNoticeContent(DispatchByLayerInput input)
{
var jump = string.IsNullOrWhiteSpace(input.JumpUrl) ? null : $"/#{input.JumpUrl}";
return $"{input.ExceptionNo} {input.Content}
"
+ (jump == null ? string.Empty : $"查看异常详情
");
}
///
/// 新模型的投递渠道。只列真实可用的两个 —— 站内信与 SignalR,
/// 与旧分层表里实际在用的 notify_channel='log,SignalR' 同源。
/// 不为了 UI 看起来完整而虚构短信 / 邮件之类当前根本没有实现的渠道。
///
private static readonly List DefaultChannels = new() { "log", "SignalR" };
private static FlowNotification BuildNotification(DispatchByLayerInput input)
{
// 注意:FlowNotificationTypeEnum 不含 S8_EXCEPTION 值;BizType 字段承载 "S8_EXCEPTION" 语义。
// InstanceId 仅作为载荷字段(PushAdapter 不写 ApprovalFlowNotifyLog,不会脏写该列)。
var ctx = new Dictionary
{
["exceptionId"] = input.ExceptionId?.ToString(),
["exceptionNo"] = input.ExceptionNo,
["sceneCode"] = input.SceneCode,
["severity"] = input.Severity,
["status"] = input.Status,
["sourceRuleCode"] = input.SourceRuleCode,
["jumpUrl"] = input.JumpUrl,
};
if (input.Recovered) ctx["recovered"] = "true";
// S8-DEMO-IMPACT-SORT-NOTICE-1:影响统计 5 字段,仅 CREATED 路径携带,RECOVERED 路径不传入。
if (input.RepeatCount30d.HasValue)
ctx["repeatCount30d"] = input.RepeatCount30d.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (input.CumulativeLossHours30d.HasValue)
ctx["cumulativeLossHours30d"] = input.CumulativeLossHours30d.Value.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture);
if (!string.IsNullOrWhiteSpace(input.SuggestedAttentionLevel))
ctx["suggestedAttentionLevel"] = input.SuggestedAttentionLevel;
if (!string.IsNullOrWhiteSpace(input.SuggestedAttentionLabel))
ctx["suggestedAttentionLabel"] = input.SuggestedAttentionLabel;
if (!string.IsNullOrWhiteSpace(input.ImpactReason))
ctx["impactReason"] = input.ImpactReason;
// S8-R03-OVERDUE-CLOSE-NOTICE-1:关闭超时独立预警 4 字段,仅 CloseAsync 命中 closedAt > slaDeadline 时携带。
if (input.OverdueClosed == true)
ctx["overdueClosed"] = "true";
if (input.ClosedAt.HasValue)
ctx["closedAt"] = input.ClosedAt.Value.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (input.SlaDeadlineRef.HasValue)
ctx["slaDeadline"] = input.SlaDeadlineRef.Value.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (input.OverdueCloseHours.HasValue)
ctx["overdueCloseHours"] = input.OverdueCloseHours.Value.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture);
return new FlowNotification
{
Type = FlowNotificationTypeEnum.NewTask,
BizType = "S8_EXCEPTION",
InstanceId = input.ExceptionId ?? 0,
Title = input.Title ?? string.Empty,
Content = input.Content ?? string.Empty,
Context = ctx,
};
}
public static List ParseChannels(string? csv)
{
if (string.IsNullOrWhiteSpace(csv)) return new List();
return csv.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
}