S8WatchSchedulerService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using Admin.NET.Plugin.AiDOP.Entity.S8;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  3. using SqlSugar;
  4. using System.Data;
  5. using System.Globalization;
  6. using System.Text.Json;
  7. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  8. /// <summary>
  9. /// 监视规则轮询调度服务(首轮存根)。
  10. /// 后续接入 Admin.NET 定时任务机制后,由调度器周期调用 <see cref="RunOnceAsync"/>,
  11. /// 按各规则的 PollIntervalSeconds 逐条评估并生成异常记录。
  12. /// </summary>
  13. public class S8WatchSchedulerService : ITransient
  14. {
  15. private readonly SqlSugarRepository<AdoS8WatchRule> _ruleRep;
  16. private readonly SqlSugarRepository<AdoS8AlertRule> _alertRuleRep;
  17. private readonly SqlSugarRepository<AdoS8DataSource> _dataSourceRep;
  18. private readonly SqlSugarRepository<AdoS8Exception> _exceptionRep;
  19. private readonly S8NotificationService _notificationService;
  20. private readonly S8ManualReportService _manualReportService;
  21. private const string DefaultTriggerType = "VALUE_DEVIATION";
  22. private const string SqlDataSourceType = "SQL";
  23. // G01-05 未闭环状态集合:复用自 S8ExceptionService 当前 pendingStatuses 事实口径
  24. // (见 S8ExceptionService.GetPagedAsync 中 pendingStatuses 的定义,两处必须保持一致)。
  25. // 这不是“自定义未闭环集合”;若现有口径调整,两处需同步修改。
  26. private static readonly string[] UnclosedExceptionStatuses =
  27. { "NEW", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION" };
  28. public S8WatchSchedulerService(
  29. SqlSugarRepository<AdoS8WatchRule> ruleRep,
  30. SqlSugarRepository<AdoS8AlertRule> alertRuleRep,
  31. SqlSugarRepository<AdoS8DataSource> dataSourceRep,
  32. SqlSugarRepository<AdoS8Exception> exceptionRep,
  33. S8NotificationService notificationService,
  34. S8ManualReportService manualReportService)
  35. {
  36. _ruleRep = ruleRep;
  37. _alertRuleRep = alertRuleRep;
  38. _dataSourceRep = dataSourceRep;
  39. _exceptionRep = exceptionRep;
  40. _notificationService = notificationService;
  41. _manualReportService = manualReportService;
  42. }
  43. public async Task<List<S8WatchExecutionRule>> LoadExecutionRulesAsync(long tenantId, long factoryId)
  44. {
  45. var watchRules = await _ruleRep.AsQueryable()
  46. .Where(x => x.TenantId == tenantId
  47. && x.FactoryId == factoryId
  48. && x.Enabled
  49. && x.SceneCode == S8SceneCode.S2S6Production)
  50. .ToListAsync();
  51. var deviceRules = watchRules
  52. .Where(x => IsDeviceWatchObjectType(x.WatchObjectType))
  53. .ToList();
  54. if (deviceRules.Count == 0) return new();
  55. var dataSourceIds = deviceRules
  56. .Select(x => x.DataSourceId)
  57. .Distinct()
  58. .ToList();
  59. var dataSources = await _dataSourceRep.AsQueryable()
  60. .Where(x => x.TenantId == tenantId
  61. && x.FactoryId == factoryId
  62. && x.Enabled
  63. && dataSourceIds.Contains(x.Id))
  64. .ToListAsync();
  65. var dataSourceMap = dataSources.ToDictionary(x => x.Id);
  66. if (dataSourceMap.Count == 0) return new();
  67. var alertRules = (await _alertRuleRep.AsQueryable()
  68. .Where(x => x.TenantId == tenantId
  69. && x.FactoryId == factoryId
  70. && x.SceneCode == S8SceneCode.S2S6Production)
  71. .ToListAsync())
  72. .Where(IsSupportedAlertRule)
  73. .ToList();
  74. // G-01 首版 AlertRule 冲突口径(C 收口):
  75. // 当前场景存在多条可运行 AlertRule 时,视为“当前规则配置冲突”并跳过该规则,
  76. // 不按“首条”继续运行,也不扩大为“整场景停摆”。
  77. // 当前模型下所有 device watchRule 共享同场景 AlertRule,故冲突态下所有 device 规则均跳过,
  78. // 但此处按“逐规则跳过”的语义实现,避免被误读为“整场景 return empty 停摆”。
  79. var alertRule = alertRules.Count == 1 ? alertRules[0] : null;
  80. var executionRules = new List<S8WatchExecutionRule>();
  81. foreach (var watchRule in deviceRules.OrderBy(x => x.Id))
  82. {
  83. // 配置冲突:当前规则跳过(不停摆其他规则)。
  84. if (alertRule == null)
  85. continue;
  86. if (!dataSourceMap.TryGetValue(watchRule.DataSourceId, out var dataSource))
  87. continue;
  88. if (!IsSupportedSqlDataSource(dataSource))
  89. continue;
  90. executionRules.Add(new S8WatchExecutionRule
  91. {
  92. WatchRuleId = watchRule.Id,
  93. WatchRuleCode = watchRule.RuleCode,
  94. SceneCode = watchRule.SceneCode,
  95. TriggerType = DefaultTriggerType,
  96. WatchObjectType = watchRule.WatchObjectType.Trim(),
  97. DataSourceId = dataSource.Id,
  98. DataSourceCode = dataSource.DataSourceCode,
  99. DataSourceType = dataSource.Type,
  100. DataSourceConnection = dataSource.Endpoint?.Trim() ?? string.Empty,
  101. QueryExpression = watchRule.Expression?.Trim() ?? string.Empty,
  102. PollIntervalSeconds = watchRule.PollIntervalSeconds,
  103. AlertRuleId = alertRule.Id,
  104. AlertRuleCode = alertRule.RuleCode,
  105. TriggerCondition = alertRule.TriggerCondition!.Trim(),
  106. ThresholdValue = alertRule.ThresholdVal!.Trim(),
  107. Severity = alertRule.Severity
  108. });
  109. }
  110. return executionRules;
  111. }
  112. public async Task<List<S8WatchDeviceQueryResult>> QueryDeviceRowsAsync(long tenantId, long factoryId)
  113. {
  114. var executionRules = await LoadExecutionRulesAsync(tenantId, factoryId);
  115. var results = new List<S8WatchDeviceQueryResult>();
  116. foreach (var rule in executionRules)
  117. results.Add(await QueryDeviceRowsAsync(rule));
  118. return results;
  119. }
  120. public async Task<S8WatchDeviceQueryResult> QueryDeviceRowsAsync(S8WatchExecutionRule rule)
  121. {
  122. if (!string.Equals(rule.DataSourceType, SqlDataSourceType, StringComparison.OrdinalIgnoreCase))
  123. return S8WatchDeviceQueryResult.Fail(rule, "数据源类型不是 SQL,已跳过");
  124. if (string.IsNullOrWhiteSpace(rule.QueryExpression))
  125. return S8WatchDeviceQueryResult.Fail(rule, "查询表达式为空,已跳过");
  126. try
  127. {
  128. using var db = CreateSqlQueryScope(rule.DataSourceConnection);
  129. var table = await db.Ado.GetDataTableAsync(rule.QueryExpression);
  130. if (!HasRequiredColumns(table))
  131. return S8WatchDeviceQueryResult.Fail(rule, "查询结果缺少 required columns: related_object_code/current_value");
  132. var rows = table.Rows.Cast<DataRow>()
  133. .Select(MapDeviceRow)
  134. .Where(x => !string.IsNullOrWhiteSpace(x.RelatedObjectCode))
  135. .ToList();
  136. return S8WatchDeviceQueryResult.Ok(rule, rows);
  137. }
  138. catch (Exception ex)
  139. {
  140. return S8WatchDeviceQueryResult.Fail(rule, $"查询执行失败: {ex.Message}");
  141. }
  142. }
  143. /// <summary>
  144. /// G01-04:基于设备级结果行集做首版 VALUE_DEVIATION 单阈值判定,
  145. /// 产出命中结果对象列表,供 G01-05 去重与 G01-06 建单消费。
  146. /// 本方法不做去重、不做建单、不做严重度重算、不做时间线。
  147. /// </summary>
  148. public async Task<List<S8WatchHitResult>> EvaluateHitsAsync(long tenantId, long factoryId)
  149. {
  150. var executionRules = await LoadExecutionRulesAsync(tenantId, factoryId);
  151. var ruleMap = executionRules.ToDictionary(x => x.WatchRuleId);
  152. var queryResults = new List<S8WatchDeviceQueryResult>();
  153. foreach (var rule in executionRules)
  154. queryResults.Add(await QueryDeviceRowsAsync(rule));
  155. var hits = new List<S8WatchHitResult>();
  156. foreach (var queryResult in queryResults)
  157. {
  158. // G01-03 查询失败:跳过,不进入判定。
  159. if (!queryResult.Success) continue;
  160. if (!ruleMap.TryGetValue(queryResult.WatchRuleId, out var rule)) continue;
  161. // 判定参数缺失:跳过当前规则。
  162. if (string.IsNullOrWhiteSpace(rule.TriggerCondition)
  163. || string.IsNullOrWhiteSpace(rule.ThresholdValue))
  164. continue;
  165. // 比较符非法:跳过当前规则。
  166. var op = TryParseTriggerCondition(rule.TriggerCondition);
  167. if (op == null) continue;
  168. // ThresholdValue 非法:跳过当前规则。
  169. if (!TryParseDecimal(rule.ThresholdValue, out var threshold)) continue;
  170. foreach (var row in queryResult.Rows)
  171. {
  172. // CurrentValue 非法(null / 无法解析数值):跳过当前行,不进入判定。
  173. if (row.CurrentValue == null) continue;
  174. // 未命中:不进入后续链路。
  175. if (!EvaluateHit(row.CurrentValue.Value, op, threshold)) continue;
  176. hits.Add(new S8WatchHitResult
  177. {
  178. SourceRuleId = rule.WatchRuleId,
  179. SourceRuleCode = rule.WatchRuleCode,
  180. AlertRuleId = rule.AlertRuleId,
  181. DataSourceId = rule.DataSourceId,
  182. RelatedObjectCode = row.RelatedObjectCode,
  183. CurrentValue = row.CurrentValue.Value,
  184. ThresholdValue = threshold,
  185. TriggerCondition = op,
  186. Severity = rule.Severity,
  187. OccurrenceDeptId = row.OccurrenceDeptId,
  188. ResponsibleDeptId = row.ResponsibleDeptId,
  189. SourcePayload = row.SourcePayload
  190. });
  191. }
  192. }
  193. return hits;
  194. }
  195. /// <summary>
  196. /// G01-05:未闭环异常去重最小实现。
  197. /// 消费 G01-04 产出的 <see cref="S8WatchHitResult"/>,按 (SourceRuleId + RelatedObjectCode)
  198. /// 在未闭环状态集合内判重,只回答“是否允许建单”。
  199. /// 首版明确不做:原单刷新 / 时间线追加 / payload 更新 / 次数累计 / 严重度重算 / 状态修复。
  200. /// </summary>
  201. public async Task<List<S8WatchDedupResult>> EvaluateDedupAsync(long tenantId, long factoryId)
  202. {
  203. var hits = await EvaluateHitsAsync(tenantId, factoryId);
  204. var results = new List<S8WatchDedupResult>(hits.Count);
  205. foreach (var hit in hits)
  206. {
  207. // 防御性分支:正常情况下 SourceRuleId 与 RelatedObjectCode 已由上游
  208. // (G01-02 规则装配 + G01-03 查询结果列校验)保证;此处仅作兜底,
  209. // 不是首版正常路径。
  210. if (hit.SourceRuleId <= 0 || string.IsNullOrWhiteSpace(hit.RelatedObjectCode))
  211. {
  212. results.Add(new S8WatchDedupResult
  213. {
  214. Hit = hit,
  215. CanCreate = false,
  216. MatchedExceptionId = null,
  217. Reason = "missing_dedup_key"
  218. });
  219. continue;
  220. }
  221. long matchedId;
  222. try
  223. {
  224. matchedId = await FindPendingExceptionIdAsync(
  225. tenantId, factoryId, hit.SourceRuleId, hit.RelatedObjectCode);
  226. }
  227. catch
  228. {
  229. // 去重查询失败:首版偏保守,宁可阻止也不重复建单,不扩展为补偿。
  230. results.Add(new S8WatchDedupResult
  231. {
  232. Hit = hit,
  233. CanCreate = false,
  234. MatchedExceptionId = null,
  235. Reason = "query_failed"
  236. });
  237. continue;
  238. }
  239. if (matchedId > 0)
  240. {
  241. // 命中已有未闭环异常 → 阻止建单。
  242. results.Add(new S8WatchDedupResult
  243. {
  244. Hit = hit,
  245. CanCreate = false,
  246. MatchedExceptionId = matchedId,
  247. Reason = "duplicate_pending"
  248. });
  249. }
  250. else
  251. {
  252. // 未命中 → 允许建单,交 G01-06 消费。
  253. results.Add(new S8WatchDedupResult
  254. {
  255. Hit = hit,
  256. CanCreate = true,
  257. MatchedExceptionId = null,
  258. Reason = "no_pending"
  259. });
  260. }
  261. }
  262. return results;
  263. }
  264. // 取任意一条匹配的未闭环异常 Id 作为“是否存在重复单”的拦截依据。
  265. // 首版只需要“存在性”,不关心“最早 / 最新”;不在 G01-05 处理排序语义。
  266. private async Task<long> FindPendingExceptionIdAsync(
  267. long tenantId, long factoryId, long sourceRuleId, string relatedObjectCode)
  268. {
  269. // SqlSugar 表达式翻译要求 Contains 数组变量必须可访问;此处将类级常量
  270. // 承接到方法内局部变量,仅为表达式翻译服务,值与 UnclosedExceptionStatuses 一致。
  271. var statuses = UnclosedExceptionStatuses;
  272. var ids = await _exceptionRep.AsQueryable()
  273. .Where(x => x.TenantId == tenantId
  274. && x.FactoryId == factoryId
  275. && !x.IsDeleted
  276. && x.SourceRuleId == sourceRuleId
  277. && x.RelatedObjectCode == relatedObjectCode
  278. && statuses.Contains(x.Status))
  279. .Select(x => x.Id)
  280. .Take(1)
  281. .ToListAsync();
  282. return ids.Count > 0 ? ids[0] : 0L;
  283. }
  284. /// <summary>
  285. /// G01-06:自动建单入口。消费 G01-05 去重结果,对 CanCreate==true 的命中
  286. /// 复用 S8ManualReportService.CreateFromWatchAsync(同一主链的自动建单分支)落成标准 AdoS8Exception。
  287. /// CanCreate==false 直接跳过;创建失败返回最小失败结果,不补偿、不重试、不对账。
  288. /// </summary>
  289. public async Task<List<S8WatchCreationResult>> CreateExceptionsAsync(long tenantId, long factoryId)
  290. {
  291. var dedupResults = await EvaluateDedupAsync(tenantId, factoryId);
  292. var results = new List<S8WatchCreationResult>(dedupResults.Count);
  293. foreach (var dedup in dedupResults)
  294. {
  295. if (!dedup.CanCreate)
  296. {
  297. results.Add(new S8WatchCreationResult
  298. {
  299. DedupResult = dedup,
  300. Created = false,
  301. Skipped = true,
  302. CreatedExceptionId = null,
  303. Reason = dedup.Reason,
  304. ErrorMessage = null
  305. });
  306. continue;
  307. }
  308. try
  309. {
  310. var entity = await _manualReportService.CreateFromWatchAsync(dedup.Hit);
  311. results.Add(new S8WatchCreationResult
  312. {
  313. DedupResult = dedup,
  314. Created = true,
  315. Skipped = false,
  316. CreatedExceptionId = entity.Id,
  317. Reason = "auto_created",
  318. ErrorMessage = null
  319. });
  320. }
  321. catch (Exception ex)
  322. {
  323. results.Add(new S8WatchCreationResult
  324. {
  325. DedupResult = dedup,
  326. Created = false,
  327. Skipped = false,
  328. CreatedExceptionId = null,
  329. Reason = "create_failed",
  330. ErrorMessage = ex.Message
  331. });
  332. }
  333. }
  334. return results;
  335. }
  336. /// <summary>
  337. /// 单次轮询入口。当前仅完成规则读取与组装,返回可执行规则数量,不做实际数据采集。
  338. /// </summary>
  339. public async Task<int> RunOnceAsync()
  340. {
  341. var executionRules = await LoadExecutionRulesAsync(1, 1);
  342. return executionRules.Count;
  343. }
  344. // G01-04 首版最小比较符集合:>, >=, <, <=。
  345. // 允许首尾空格;非此集合的一律视为“比较符非法”,由调用方跳过。
  346. private static string? TryParseTriggerCondition(string raw)
  347. {
  348. var normalized = raw.Trim();
  349. return normalized switch
  350. {
  351. ">" => ">",
  352. ">=" => ">=",
  353. "<" => "<",
  354. "<=" => "<=",
  355. _ => null
  356. };
  357. }
  358. private static bool TryParseDecimal(string raw, out decimal value) =>
  359. decimal.TryParse(raw.Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out value);
  360. private static bool EvaluateHit(decimal current, string op, decimal threshold) => op switch
  361. {
  362. ">" => current > threshold,
  363. ">=" => current >= threshold,
  364. "<" => current < threshold,
  365. "<=" => current <= threshold,
  366. _ => false
  367. };
  368. private static bool IsSupportedAlertRule(AdoS8AlertRule alertRule) =>
  369. !string.IsNullOrWhiteSpace(alertRule.TriggerCondition)
  370. && !string.IsNullOrWhiteSpace(alertRule.ThresholdVal);
  371. private static bool IsSupportedSqlDataSource(AdoS8DataSource dataSource) =>
  372. dataSource.Enabled
  373. && string.Equals(dataSource.Type?.Trim(), SqlDataSourceType, StringComparison.OrdinalIgnoreCase)
  374. && !string.IsNullOrWhiteSpace(dataSource.Endpoint);
  375. private static bool IsDeviceWatchObjectType(string? watchObjectType)
  376. {
  377. if (string.IsNullOrWhiteSpace(watchObjectType)) return false;
  378. var normalized = watchObjectType.Trim().ToUpperInvariant();
  379. return normalized is "DEVICE" or "EQUIPMENT" || watchObjectType.Trim() == "设备";
  380. }
  381. private SqlSugarScope CreateSqlQueryScope(string connectionString)
  382. {
  383. var dbType = _ruleRep.Context.CurrentConnectionConfig.DbType;
  384. return new SqlSugarScope(new ConnectionConfig
  385. {
  386. ConfigId = $"s8-watch-sql-{Guid.NewGuid():N}",
  387. DbType = dbType,
  388. ConnectionString = connectionString,
  389. InitKeyType = InitKeyType.Attribute,
  390. IsAutoCloseConnection = true
  391. });
  392. }
  393. private static bool HasRequiredColumns(DataTable table) =>
  394. TryGetColumnName(table.Columns, "related_object_code") != null
  395. && TryGetColumnName(table.Columns, "current_value") != null;
  396. private static S8WatchDeviceRow MapDeviceRow(DataRow row)
  397. {
  398. var columns = row.Table.Columns;
  399. var relatedObjectCodeColumn = TryGetColumnName(columns, "related_object_code");
  400. var currentValueColumn = TryGetColumnName(columns, "current_value");
  401. var occurrenceDeptIdColumn = TryGetColumnName(columns, "occurrence_dept_id");
  402. var responsibleDeptIdColumn = TryGetColumnName(columns, "responsible_dept_id");
  403. return new S8WatchDeviceRow
  404. {
  405. RelatedObjectCode = ReadString(row, relatedObjectCodeColumn),
  406. CurrentValue = ReadDecimal(row, currentValueColumn),
  407. OccurrenceDeptId = ReadLong(row, occurrenceDeptIdColumn),
  408. ResponsibleDeptId = ReadLong(row, responsibleDeptIdColumn),
  409. SourcePayload = BuildSourcePayload(row)
  410. };
  411. }
  412. private static string? TryGetColumnName(DataColumnCollection columns, string expectedName)
  413. {
  414. var normalizedExpected = NormalizeColumnName(expectedName);
  415. foreach (DataColumn column in columns)
  416. {
  417. if (NormalizeColumnName(column.ColumnName) == normalizedExpected)
  418. return column.ColumnName;
  419. }
  420. return null;
  421. }
  422. private static string NormalizeColumnName(string columnName) =>
  423. columnName.Replace("_", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
  424. private static string ReadString(DataRow row, string? columnName)
  425. {
  426. if (string.IsNullOrWhiteSpace(columnName)) return string.Empty;
  427. var value = row[columnName];
  428. return value == DBNull.Value ? string.Empty : Convert.ToString(value)?.Trim() ?? string.Empty;
  429. }
  430. private static long? ReadLong(DataRow row, string? columnName)
  431. {
  432. if (string.IsNullOrWhiteSpace(columnName)) return null;
  433. var value = row[columnName];
  434. if (value == DBNull.Value) return null;
  435. return long.TryParse(Convert.ToString(value, CultureInfo.InvariantCulture), out var result) ? result : null;
  436. }
  437. private static decimal? ReadDecimal(DataRow row, string? columnName)
  438. {
  439. if (string.IsNullOrWhiteSpace(columnName)) return null;
  440. var value = row[columnName];
  441. if (value == DBNull.Value) return null;
  442. return decimal.TryParse(Convert.ToString(value, CultureInfo.InvariantCulture), NumberStyles.Any, CultureInfo.InvariantCulture, out var result)
  443. ? result
  444. : null;
  445. }
  446. private static string BuildSourcePayload(DataRow row)
  447. {
  448. var payload = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  449. foreach (DataColumn column in row.Table.Columns)
  450. {
  451. var value = row[column];
  452. payload[column.ColumnName] = value == DBNull.Value ? null : value;
  453. }
  454. return JsonSerializer.Serialize(payload);
  455. }
  456. }
  457. public sealed class S8WatchExecutionRule
  458. {
  459. public long WatchRuleId { get; set; }
  460. public string WatchRuleCode { get; set; } = string.Empty;
  461. public string SceneCode { get; set; } = string.Empty;
  462. public string TriggerType { get; set; } = string.Empty;
  463. public string WatchObjectType { get; set; } = string.Empty;
  464. public long DataSourceId { get; set; }
  465. public string DataSourceCode { get; set; } = string.Empty;
  466. public string DataSourceType { get; set; } = string.Empty;
  467. public string DataSourceConnection { get; set; } = string.Empty;
  468. public string QueryExpression { get; set; } = string.Empty;
  469. public int PollIntervalSeconds { get; set; }
  470. public long AlertRuleId { get; set; }
  471. public string AlertRuleCode { get; set; } = string.Empty;
  472. public string TriggerCondition { get; set; } = string.Empty;
  473. public string ThresholdValue { get; set; } = string.Empty;
  474. public string Severity { get; set; } = string.Empty;
  475. }
  476. public sealed class S8WatchDeviceQueryResult
  477. {
  478. public long WatchRuleId { get; set; }
  479. public string WatchRuleCode { get; set; } = string.Empty;
  480. public bool Success { get; set; }
  481. public string? FailureReason { get; set; }
  482. public List<S8WatchDeviceRow> Rows { get; set; } = new();
  483. public static S8WatchDeviceQueryResult Ok(S8WatchExecutionRule rule, List<S8WatchDeviceRow> rows) =>
  484. new()
  485. {
  486. WatchRuleId = rule.WatchRuleId,
  487. WatchRuleCode = rule.WatchRuleCode,
  488. Success = true,
  489. Rows = rows
  490. };
  491. public static S8WatchDeviceQueryResult Fail(S8WatchExecutionRule rule, string reason) =>
  492. new()
  493. {
  494. WatchRuleId = rule.WatchRuleId,
  495. WatchRuleCode = rule.WatchRuleCode,
  496. Success = false,
  497. FailureReason = reason
  498. };
  499. }
  500. public sealed class S8WatchDeviceRow
  501. {
  502. public string RelatedObjectCode { get; set; } = string.Empty;
  503. public decimal? CurrentValue { get; set; }
  504. public long? OccurrenceDeptId { get; set; }
  505. public long? ResponsibleDeptId { get; set; }
  506. public string SourcePayload { get; set; } = string.Empty;
  507. }
  508. /// <summary>
  509. /// G01-05 去重结果对象。仅服务 G01-06 建单前拦截,由 CanCreate 单决策位决定是否建单。
  510. /// 只服务首版唯一场景 S2S6_PRODUCTION + 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  511. /// 不预留多 trigger_type / 平台化去重扩展结构。
  512. /// Reason 值域:no_pending / duplicate_pending / missing_dedup_key / query_failed。
  513. /// </summary>
  514. public sealed class S8WatchDedupResult
  515. {
  516. public S8WatchHitResult Hit { get; set; } = new();
  517. public bool CanCreate { get; set; }
  518. public long? MatchedExceptionId { get; set; }
  519. public string Reason { get; set; } = string.Empty;
  520. }
  521. /// <summary>
  522. /// G01-06 建单结果对象。仅服务 G-01 首版主线验收,由 Created / Skipped 两位决定结局。
  523. /// 只服务首版唯一场景 S2S6_PRODUCTION + 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  524. /// 不预留多 trigger_type / 平台化工单扩展结构。
  525. /// Reason 值域:auto_created / create_failed / 透传自 DedupResult.Reason。
  526. /// </summary>
  527. public sealed class S8WatchCreationResult
  528. {
  529. public S8WatchDedupResult DedupResult { get; set; } = new();
  530. public bool Created { get; set; }
  531. public bool Skipped { get; set; }
  532. public long? CreatedExceptionId { get; set; }
  533. public string Reason { get; set; } = string.Empty;
  534. public string? ErrorMessage { get; set; }
  535. }
  536. /// <summary>
  537. /// G01-04 命中结果对象。承载 G01-05 去重与 G01-06 建单所需最小追溯字段,
  538. /// 仅服务首版唯一场景 S2S6_PRODUCTION + 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  539. /// 不预留多 trigger_type / 多场景 / 平台化扩展结构。
  540. /// </summary>
  541. public sealed class S8WatchHitResult
  542. {
  543. public long SourceRuleId { get; set; }
  544. public string SourceRuleCode { get; set; } = string.Empty;
  545. public long AlertRuleId { get; set; }
  546. public long DataSourceId { get; set; }
  547. public string RelatedObjectCode { get; set; } = string.Empty;
  548. public decimal CurrentValue { get; set; }
  549. public decimal ThresholdValue { get; set; }
  550. public string TriggerCondition { get; set; } = string.Empty;
  551. public string Severity { get; set; } = string.Empty;
  552. public long? OccurrenceDeptId { get; set; }
  553. public long? ResponsibleDeptId { get; set; }
  554. public string SourcePayload { get; set; } = string.Empty;
  555. }