S8ManualReportService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. using Admin.NET.Plugin.AiDOP.Dto.S8;
  2. using Admin.NET.Plugin.AiDOP.Entity.S0.Manufacturing;
  3. using Admin.NET.Plugin.AiDOP.Entity.S0.Warehouse;
  4. using Admin.NET.Plugin.AiDOP.Entity.S8;
  5. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  6. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  7. using Admin.NET.Plugin.ApprovalFlow.Service;
  8. using Microsoft.Extensions.Logging;
  9. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  10. public class S8ManualReportService : ITransient
  11. {
  12. // 合法严重度白名单(与 GetFormOptionsAsync.severities 同源);前端/后端默认值 MEDIUM。
  13. private static readonly HashSet<string> AllowedSeverities = new(StringComparer.Ordinal)
  14. {
  15. "CRITICAL", "HIGH", "MEDIUM", "LOW"
  16. };
  17. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  18. private readonly SqlSugarRepository<AdoS8ExceptionTimeline> _timelineRep;
  19. private readonly SqlSugarRepository<AdoS8Evidence> _evidenceRep;
  20. private readonly SqlSugarRepository<AdoS8SceneConfig> _sceneRep;
  21. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  22. private readonly SqlSugarRepository<AdoS0LineMaster> _lineRep;
  23. private readonly SqlSugarRepository<AdoS8ExceptionType> _typeRep;
  24. private readonly UserManager _userManager;
  25. private readonly FlowEngineService _flowEngine;
  26. private readonly ILogger<S8ManualReportService> _logger;
  27. public S8ManualReportService(
  28. SqlSugarRepository<AdoS8Exception> rep,
  29. SqlSugarRepository<AdoS8ExceptionTimeline> timelineRep,
  30. SqlSugarRepository<AdoS8Evidence> evidenceRep,
  31. SqlSugarRepository<AdoS8SceneConfig> sceneRep,
  32. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  33. SqlSugarRepository<AdoS0LineMaster> lineRep,
  34. SqlSugarRepository<AdoS8ExceptionType> typeRep,
  35. UserManager userManager,
  36. FlowEngineService flowEngine,
  37. ILogger<S8ManualReportService> logger)
  38. {
  39. _rep = rep;
  40. _timelineRep = timelineRep;
  41. _evidenceRep = evidenceRep;
  42. _sceneRep = sceneRep;
  43. _deptRep = deptRep;
  44. _lineRep = lineRep;
  45. _typeRep = typeRep;
  46. _userManager = userManager;
  47. _flowEngine = flowEngine;
  48. _logger = logger;
  49. }
  50. /// <summary>
  51. /// 主动提报推断 ExceptionTypeCode:场景下取启用且 SortNo 最小的一条。
  52. /// baseline 异常类型当前 tenant_id=0/factory_id=0(全局基线),所以匹配条件为
  53. /// (tenantId 命中 OR 0) AND (factoryId 命中 OR 0)。ClearFilter 兜底全局多租户过滤器。
  54. /// 找不到返回 null(保持兼容)。
  55. /// </summary>
  56. private async Task<string?> InferExceptionTypeCodeAsync(long tenantId, long factoryId, string sceneCode)
  57. {
  58. if (string.IsNullOrWhiteSpace(sceneCode)) return null;
  59. return await _typeRep.AsQueryable().ClearFilter()
  60. .Where(x => (x.TenantId == tenantId || x.TenantId == 0)
  61. && (x.FactoryId == factoryId || x.FactoryId == 0)
  62. && x.SceneCode == sceneCode && x.Enabled)
  63. .OrderBy(x => x.SortNo)
  64. .Select(x => x.TypeCode)
  65. .FirstAsync();
  66. }
  67. /// <summary>
  68. /// TB001 异常提报审批流:自动监控 + 主动提报后软触发,失败仅 warn 日志,不阻断建单。
  69. /// </summary>
  70. private async Task TryStartIntakeFlowAsync(AdoS8Exception entity)
  71. {
  72. try
  73. {
  74. await _flowEngine.StartFlow(new StartFlowInput
  75. {
  76. BizType = "EXCEPTION_REPORT",
  77. BizId = entity.Id,
  78. BizNo = entity.ExceptionCode,
  79. Title = $"异常提报 - {entity.ExceptionCode}",
  80. Comment = entity.SourceType == "AUTO_WATCH" ? "自动监控触发" : "主动提报触发",
  81. BizData = new Dictionary<string, object>
  82. {
  83. ["sceneCode"] = entity.SceneCode ?? "",
  84. ["exceptionTypeCode"] = entity.ExceptionTypeCode ?? "",
  85. ["sourceType"] = entity.SourceType ?? ""
  86. }
  87. });
  88. }
  89. catch (Exception ex)
  90. {
  91. _logger.LogWarning(ex, "TB001 异常提报审批流触发失败 ExceptionId={Id} ExceptionCode={Code}", entity.Id, entity.ExceptionCode);
  92. }
  93. }
  94. public async Task<object> GetFormOptionsAsync(long tenantId, long factoryId)
  95. {
  96. var scenes = await _sceneRep.AsQueryable()
  97. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.Enabled)
  98. .OrderBy(x => x.SortNo)
  99. .Select(x => new { value = x.SceneCode, label = x.SceneName })
  100. .ToListAsync();
  101. // ClearFilter:DepartmentMaster.tenant_id 属 S0 域租户,不与登录 token TenantId 一致;
  102. // 用 factory_ref_id 做硬边界,安全等价。同 BUG-S8-EMPLOYEES-TENANT-FILTER 协议。
  103. var departments = await _deptRep.AsQueryable().ClearFilter()
  104. .Where(x => x.FactoryRefId == factoryId)
  105. .OrderBy(x => x.Department)
  106. .Take(500)
  107. .Select(x => new { value = x.Id, label = x.Descr ?? x.Department })
  108. .ToListAsync();
  109. var lines = await _lineRep.AsQueryable().ClearFilter()
  110. .Where(x => x.FactoryRefId == factoryId)
  111. .OrderBy(x => x.Line)
  112. .Take(500)
  113. .Select(x => new { value = x.Id, label = x.Describe ?? x.Line })
  114. .ToListAsync();
  115. return new
  116. {
  117. scenes,
  118. severities = new[]
  119. {
  120. new { value = "CRITICAL", label = "紧急" },
  121. new { value = "HIGH", label = "高" },
  122. new { value = "MEDIUM", label = "中" },
  123. new { value = "LOW", label = "低" }
  124. },
  125. departments,
  126. lines,
  127. materials = Array.Empty<object>()
  128. };
  129. }
  130. public async Task<AdoS8ManualReportResultDto> CreateAsync(AdoS8ManualReportCreateDto dto)
  131. {
  132. if (string.IsNullOrWhiteSpace(dto.Title)) throw new S8BizException("标题必填");
  133. if (string.IsNullOrWhiteSpace(dto.SceneCode)) throw new S8BizException("场景必填");
  134. // 严重度白名单校验:空值兜底为 MEDIUM;非法值直接拒绝,避免 P3 等错位写入。
  135. var severity = string.IsNullOrWhiteSpace(dto.Severity) ? "MEDIUM" : dto.Severity.Trim();
  136. if (!AllowedSeverities.Contains(severity))
  137. throw new S8BizException($"严重度 {severity} 非法,仅允许 CRITICAL/HIGH/MEDIUM/LOW");
  138. // 提报人以服务端登录上下文为准,忽略前端传入;未登录上下文落 null。
  139. var currentUserId = _userManager.UserId > 0 ? _userManager.UserId : (long?)null;
  140. // 主动提报无前端 type 字段,按场景兜底推断;保证不进"未分类"桶。
  141. var inferredType = await InferExceptionTypeCodeAsync(dto.TenantId, dto.FactoryId, dto.SceneCode.Trim());
  142. var code = $"EX-{DateTime.Now:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}";
  143. var entity = new AdoS8Exception
  144. {
  145. TenantId = dto.TenantId,
  146. FactoryId = dto.FactoryId,
  147. ExceptionCode = code,
  148. Title = dto.Title.Trim(),
  149. Description = dto.Description,
  150. SceneCode = dto.SceneCode.Trim(),
  151. SourceType = "MANUAL",
  152. Status = "NEW",
  153. Severity = severity,
  154. PriorityScore = 0,
  155. PriorityLevel = "P3",
  156. OccurrenceDeptId = dto.OccurrenceDeptId,
  157. ResponsibleDeptId = dto.ResponsibleDeptId,
  158. ReporterId = currentUserId,
  159. ExceptionTypeCode = inferredType,
  160. CreatedAt = DateTime.Now,
  161. IsDeleted = false
  162. };
  163. await _rep.AsTenant().UseTranAsync(async () =>
  164. {
  165. entity = await _rep.AsInsertable(entity).ExecuteReturnEntityAsync();
  166. await _timelineRep.InsertAsync(new AdoS8ExceptionTimeline
  167. {
  168. ExceptionId = entity.Id,
  169. ActionCode = "CREATE",
  170. ActionLabel = "创建",
  171. FromStatus = null,
  172. ToStatus = "NEW",
  173. OperatorId = currentUserId,
  174. ActionRemark = "主动提报",
  175. CreatedAt = DateTime.Now
  176. });
  177. }, ex => throw ex);
  178. await TryStartIntakeFlowAsync(entity);
  179. return new AdoS8ManualReportResultDto
  180. {
  181. ExceptionId = entity.Id,
  182. ExceptionCode = entity.ExceptionCode,
  183. TaskId = entity.Id
  184. };
  185. }
  186. /// <summary>
  187. /// G01-06:自动建单分支(非第二套创建主链)。
  188. /// 这是本服务内的自动监控建单路径,与 <see cref="CreateAsync"/> 并列,
  189. /// 复用同一仓储(_rep / _timelineRep)、同一事务边界、同一 ExceptionCode 生成规则、
  190. /// 同一时间线主链(ActionCode="CREATE"、ToStatus="NEW");仅差异点:
  191. /// - SourceType 标识为自动监控来源
  192. /// - 填入 SourceRuleId / SourceDataSourceId / SourcePayload / RelatedObjectCode 追溯
  193. /// - ExceptionTypeCode 固定 EQUIP_FAULT(G-01 首版唯一映射)
  194. /// - SceneCode 固定 S2S6_PRODUCTION(G-01 首版唯一场景)
  195. /// 不做补偿、重试、对账;失败由调用方接住。
  196. /// </summary>
  197. public async Task<AdoS8Exception> CreateFromWatchAsync(S8WatchHitResult hit)
  198. {
  199. if (hit.SourceRuleId <= 0 || string.IsNullOrWhiteSpace(hit.RelatedObjectCode))
  200. throw new S8BizException("自动建单缺失追溯键");
  201. var code = $"EX-{DateTime.Now:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}";
  202. var title = $"[自动] 设备 {hit.RelatedObjectCode} {hit.TriggerCondition} {hit.ThresholdValue}(当前 {hit.CurrentValue})";
  203. var entity = new AdoS8Exception
  204. {
  205. // 租户/工厂:与 S8WatchSchedulerService.RunOnceAsync 当前固定上下文一致。
  206. TenantId = 1,
  207. FactoryId = 1,
  208. ExceptionCode = code,
  209. Title = title,
  210. Description = null,
  211. SceneCode = S8SceneCode.S2S6Production,
  212. // 首版自动监控建单来源标识(字符串值,先不抽常量类)。
  213. SourceType = "AUTO_WATCH",
  214. Status = "NEW",
  215. Severity = string.IsNullOrWhiteSpace(hit.Severity) ? "MEDIUM" : hit.Severity,
  216. PriorityScore = 0,
  217. PriorityLevel = "P3",
  218. // 首版兜底口径:Hit 未提供部门时置 0 仅为保证“能建成标准异常单并进入主链”,
  219. // 不是最终业务部门语义;后续需由上游查询结果提供,或在专项任务中补口径。
  220. OccurrenceDeptId = hit.OccurrenceDeptId ?? 0,
  221. ResponsibleDeptId = hit.ResponsibleDeptId ?? 0,
  222. ReporterId = null,
  223. CreatedAt = DateTime.Now,
  224. IsDeleted = false,
  225. // G-01 首版唯一异常类型映射(seed 已确认 EQUIP_FAULT 属 S2S6_PRODUCTION 场景)。
  226. ExceptionTypeCode = "EQUIP_FAULT",
  227. // ModuleCode:S2S6_PRODUCTION 场景对应 S2+S6 两个模块(见 S8ModuleCode.SceneOf),
  228. // 无稳定“scene → 单一 module”映射;首版置空,不靠经验写死。
  229. ModuleCode = null,
  230. ProcessNodeCode = null,
  231. // 追溯三件套(自动建单必填口径)。
  232. SourceRuleId = hit.SourceRuleId,
  233. SourceDataSourceId = hit.DataSourceId,
  234. SourcePayload = hit.SourcePayload,
  235. RelatedObjectCode = hit.RelatedObjectCode
  236. };
  237. await _rep.AsTenant().UseTranAsync(async () =>
  238. {
  239. entity = await _rep.AsInsertable(entity).ExecuteReturnEntityAsync();
  240. await _timelineRep.InsertAsync(new AdoS8ExceptionTimeline
  241. {
  242. ExceptionId = entity.Id,
  243. ActionCode = "CREATE",
  244. ActionLabel = "创建",
  245. FromStatus = null,
  246. ToStatus = "NEW",
  247. OperatorId = null,
  248. ActionRemark = "自动建单",
  249. CreatedAt = DateTime.Now
  250. });
  251. }, ex => throw ex);
  252. await TryStartIntakeFlowAsync(entity);
  253. return entity;
  254. }
  255. /// <summary>
  256. /// R2 自动建单分支(TIMEOUT 等新 evaluator 走此路径)。
  257. /// 与 <see cref="CreateFromWatchAsync"/> 并列:复用同一仓储 / 事务 / 时间线 ActionCode;
  258. /// 差异点:消费 <see cref="S8RuleHit"/> 一份命中模型,把 R2 新列(DedupKey / LastDetectedAt /
  259. /// SourceRuleCode / SourceObjectType / SourceObjectId)落齐;ExceptionTypeCode 由 hit 自带,
  260. /// 不再硬编码 EQUIP_FAULT。RecoveredAt 本轮不写。
  261. /// 调用方负责前置检查 ExceptionTypeCode 是否在 baseline;本方法不再二次校验。
  262. /// </summary>
  263. public async Task<AdoS8Exception> CreateFromHitAsync(S8RuleHit hit)
  264. {
  265. if (hit.SourceRuleId <= 0 || string.IsNullOrWhiteSpace(hit.RelatedObjectCode))
  266. throw new S8BizException("自动建单缺失追溯键");
  267. var code = $"EX-{DateTime.Now:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}";
  268. var entity = new AdoS8Exception
  269. {
  270. // 与 CreateFromWatchAsync 当前固定上下文一致;R2 不变更租户/工厂上下文语义。
  271. TenantId = 1,
  272. FactoryId = 1,
  273. ExceptionCode = code,
  274. Title = string.IsNullOrWhiteSpace(hit.Title)
  275. ? $"[自动] {hit.SourceObjectType} {hit.SourceObjectId}"
  276. : hit.Title,
  277. Description = null,
  278. SceneCode = string.IsNullOrWhiteSpace(hit.SceneCode) ? S8SceneCode.S2S6Production : hit.SceneCode,
  279. SourceType = "AUTO_WATCH",
  280. Status = "NEW",
  281. Severity = string.IsNullOrWhiteSpace(hit.Severity) ? "MEDIUM" : hit.Severity,
  282. PriorityScore = 0,
  283. PriorityLevel = "P3",
  284. OccurrenceDeptId = hit.OccurrenceDeptId ?? 0,
  285. ResponsibleDeptId = hit.ResponsibleDeptId ?? 0,
  286. ReporterId = null,
  287. CreatedAt = DateTime.Now,
  288. IsDeleted = false,
  289. ExceptionTypeCode = hit.ExceptionTypeCode,
  290. ModuleCode = null,
  291. ProcessNodeCode = null,
  292. SourceRuleId = hit.SourceRuleId,
  293. SourceDataSourceId = hit.DataSourceId == 0 ? null : hit.DataSourceId,
  294. SourcePayload = hit.SourcePayload,
  295. RelatedObjectCode = hit.RelatedObjectCode,
  296. // R2 新列回填
  297. DedupKey = hit.DedupKey,
  298. LastDetectedAt = hit.DetectedAt,
  299. RecoveredAt = null,
  300. SourceRuleCode = hit.SourceRuleCode,
  301. SourceObjectType = hit.SourceObjectType,
  302. SourceObjectId = hit.SourceObjectId
  303. };
  304. await _rep.AsTenant().UseTranAsync(async () =>
  305. {
  306. entity = await _rep.AsInsertable(entity).ExecuteReturnEntityAsync();
  307. await _timelineRep.InsertAsync(new AdoS8ExceptionTimeline
  308. {
  309. ExceptionId = entity.Id,
  310. ActionCode = "CREATE",
  311. ActionLabel = "创建",
  312. FromStatus = null,
  313. ToStatus = "NEW",
  314. OperatorId = null,
  315. ActionRemark = "自动建单(R2)",
  316. CreatedAt = DateTime.Now
  317. });
  318. }, ex => throw ex);
  319. await TryStartIntakeFlowAsync(entity);
  320. return entity;
  321. }
  322. public async Task<AdoS8Exception?> GetAsync(long id) =>
  323. await _rep.GetByIdAsync(id);
  324. public async Task<AdoS8Evidence> AddAttachmentAsync(long id, AdoS8AttachmentCreateDto dto)
  325. {
  326. var entity = await _rep.GetFirstAsync(x => x.Id == id && !x.IsDeleted)
  327. ?? throw new S8BizException("异常不存在");
  328. if (string.IsNullOrWhiteSpace(dto.FileName) || string.IsNullOrWhiteSpace(dto.FileUrl))
  329. throw new S8BizException("附件名称和地址必填");
  330. var evidence = new AdoS8Evidence
  331. {
  332. ExceptionId = id,
  333. EvidenceType = string.IsNullOrWhiteSpace(dto.EvidenceType) ? "file" : dto.EvidenceType,
  334. FileName = dto.FileName.Trim(),
  335. FileUrl = dto.FileUrl.Trim(),
  336. SourceSystem = dto.SourceSystem,
  337. UploadedBy = dto.UploadedBy,
  338. UploadedAt = DateTime.Now,
  339. IsDeleted = false
  340. };
  341. await _evidenceRep.InsertAsync(evidence);
  342. return evidence;
  343. }
  344. }