S8WatchSchedulerService.cs 33 KB

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