AidopKanbanController.Diagnosis.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using Admin.NET.Plugin.AiDOP.Entity;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure;
  3. namespace Admin.NET.Plugin.AiDOP.Controllers;
  4. public partial class AidopKanbanController
  5. {
  6. /// <summary>
  7. /// 智慧诊断:按模块和当前 L1 指标返回 L2/L3/L4 诊断矩阵。
  8. /// </summary>
  9. [HttpGet("smart-diagnosis/{moduleCode}")]
  10. public async Task<IActionResult> GetSmartDiagnosis(
  11. string moduleCode,
  12. [FromQuery] string? metricCode = null,
  13. [FromQuery] long factoryId = 1,
  14. [FromQuery] string? dateStart = null,
  15. [FromQuery] string? dateEnd = null,
  16. [FromQuery] string? product = null,
  17. [FromQuery] string? orderNo = null,
  18. [FromQuery] string? productionLine = null,
  19. [FromQuery] string? customer = null,
  20. [FromQuery] string? supplier = null,
  21. [FromQuery] string? material = null,
  22. [FromQuery] string? poNo = null,
  23. [FromQuery] string? warehouse = null,
  24. [FromQuery] string? workOrder = null,
  25. [FromQuery] string? equipment = null,
  26. [FromQuery] string? outboundNo = null)
  27. {
  28. var requested = (moduleCode ?? "").Trim().ToUpperInvariant();
  29. if (requested == "S8")
  30. return await GetSmartDiagnosisFromS8ExceptionsAsync(factoryId, dateStart, dateEnd, orderNo);
  31. var mc = NormalizeDynamicDashboardModule(moduleCode);
  32. if (mc == null) return BadRequest(new { message = "moduleCode 仅支持 S1/S2/S3/S4/S5/S6/S7/S8/S9" });
  33. var scope = await _trustedScope.ResolveAsync(factoryId);
  34. var tenantId = scope.TenantId;
  35. factoryId = scope.FactoryId;
  36. var filter = ParseDashboardFilter(
  37. dateStart, dateEnd, product, orderNo, productionLine,
  38. customer, supplier, material, poNo, warehouse, workOrder, equipment, outboundNo);
  39. var kpis = await _db.Queryable<AdoSmartOpsKpiMaster>()
  40. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc && x.IsEnabled)
  41. .OrderBy(x => x.MetricLevel)
  42. .OrderBy(x => x.SortNo)
  43. .ToListAsync();
  44. var valueBundle = await ResolveDashboardValuesBundleAsync(tenantId, factoryId, mc, filter, kpis);
  45. var values = valueBundle.Values;
  46. var snaps = values.ToDictionary(
  47. x => x.Key,
  48. x => new SmartDiagnosisTree.ValueSnap(x.Value.MetricValue, x.Value.TargetValue),
  49. StringComparer.OrdinalIgnoreCase);
  50. var l1Metrics = kpis.Where(x => x.MetricLevel == 1).OrderBy(x => x.SortNo).ToList();
  51. var resolved = SmartDiagnosisTree.ResolveRoot(l1Metrics, snaps, metricCode);
  52. if (resolved.Error != null)
  53. return BadRequest(new { message = resolved.Error });
  54. var root = resolved.Root;
  55. if (root == null)
  56. return Ok(new { moduleCode = mc, metricCode, title = $"{mc} 智慧诊断", stages = Array.Empty<object>(), hasChildren = false });
  57. var children = SmartDiagnosisTree.DirectChildren(kpis, root.Id, 2);
  58. var stagePayload = children.Select((kpi, index) =>
  59. {
  60. var current = BuildDiagnosisValue(kpi, values);
  61. var l3Rows = SmartDiagnosisTree.DirectChildren(kpis, kpi.Id, 3);
  62. var l4Rows = l3Rows.ToDictionary(
  63. x => x.MetricCode,
  64. x => SmartDiagnosisTree.DirectChildren(kpis, x.Id, 4)
  65. .Select(y => BuildDiagnosisNode(y, values))
  66. .ToList(),
  67. StringComparer.OrdinalIgnoreCase);
  68. return new
  69. {
  70. key = kpi.MetricCode,
  71. name = kpi.MetricName,
  72. flowCaption = kpi.MetricName,
  73. dept = string.IsNullOrWhiteSpace(kpi.Department) ? "未配置" : kpi.Department,
  74. kpi = FormatDiagnosisValue(current.Target, kpi.Unit),
  75. actualDays = FormatDiagnosisValue(current.Current, kpi.Unit),
  76. actualRate = SmartDiagnosisTree.BuildDiagnosisRate(current.Current, current.Target, kpi.Direction),
  77. status = current.Status,
  78. callout = BuildDiagnosisCallout(kpi.MetricName, current.Status, current.GapLabel),
  79. calloutTone = current.Status,
  80. sortNo = kpi.SortNo > 0 ? kpi.SortNo : index + 1,
  81. tier1 = l3Rows.Select(x => BuildDiagnosisNode(x, values)).ToList(),
  82. tier2 = l4Rows
  83. };
  84. }).ToList();
  85. var rootValue = BuildDiagnosisValue(root, values);
  86. var worstStage = stagePayload
  87. .OrderByDescending(x => SmartDiagnosisTree.DiagnosisSeverity(x.status))
  88. .ThenBy(x => x.sortNo)
  89. .FirstOrDefault();
  90. var selectionLabel = resolved.SelectionMode == SmartDiagnosisTree.SelectionGlobalWorst
  91. ? $"全局自动选择:{root.MetricName}"
  92. : $"当前指标:{root.MetricName}";
  93. var evidence = await _evidence.QueryAsync(tenantId, factoryId, mc, filter);
  94. return Ok(new
  95. {
  96. moduleCode = mc,
  97. metricCode = root.MetricCode,
  98. metricName = root.MetricName,
  99. title = $"{mc} {ResolveDashboardModuleName(mc)} · 智慧诊断",
  100. subtitle = selectionLabel,
  101. selectionMode = resolved.SelectionMode,
  102. hasChildren = children.Count > 0,
  103. dataSource = BuildDataSourcePayload(valueBundle),
  104. evidence,
  105. root = new
  106. {
  107. metricCode = root.MetricCode,
  108. metricName = root.MetricName,
  109. currentValue = rootValue.Current,
  110. targetValue = rootValue.Target,
  111. unit = root.Unit ?? "",
  112. status = rootValue.Status,
  113. gapLabel = rootValue.GapLabel,
  114. department = string.IsNullOrWhiteSpace(root.Department) ? "未配置" : root.Department
  115. },
  116. pmSummary = new
  117. {
  118. node = worstStage?.name ?? root.MetricName,
  119. leadDelta = rootValue.GapLabel ?? "0"
  120. },
  121. stages = stagePayload
  122. });
  123. }
  124. private async Task<IActionResult> GetSmartDiagnosisFromS8ExceptionsAsync(
  125. long factoryId,
  126. string? dateStart,
  127. string? dateEnd,
  128. string? orderNo)
  129. {
  130. var scope = await _trustedScope.ResolveAsync(factoryId);
  131. var filter = ParseDashboardFilter(
  132. dateStart, dateEnd, null, orderNo, null,
  133. null, null, null, null, null, null, null, null);
  134. var evidence = await _evidence.QueryAsync(scope.TenantId, scope.FactoryId, "S8", filter);
  135. var first = evidence.Items.FirstOrDefault();
  136. return Ok(new
  137. {
  138. moduleCode = "S8",
  139. metricCode = first == null ? null : "S8_EXCEPTION",
  140. metricName = first?.Title,
  141. title = "S8 异常监控 · 智慧诊断",
  142. subtitle = first == null ? "无可用 S8 异常佐证" : $"依据已存在异常:{first.ObjectCode}",
  143. selectionMode = "s8_exception",
  144. hasChildren = false,
  145. evidence,
  146. root = first == null ? null : new
  147. {
  148. metricCode = "S8_EXCEPTION",
  149. metricName = first.Title,
  150. currentValue = first.Contribution,
  151. targetValue = (decimal?)null,
  152. unit = "",
  153. status = first.Status,
  154. gapLabel = first.ObjectCode,
  155. department = "异常监控"
  156. },
  157. stages = Array.Empty<object>()
  158. });
  159. }
  160. private static object BuildDiagnosisNode(AdoSmartOpsKpiMaster kpi, Dictionary<string, DashboardMetricValueModel> values)
  161. {
  162. var v = BuildDiagnosisValue(kpi, values);
  163. return new
  164. {
  165. key = kpi.MetricCode,
  166. name = kpi.MetricName,
  167. plan = FormatDiagnosisValue(v.Target, kpi.Unit),
  168. actual = FormatDiagnosisValue(v.Current, kpi.Unit),
  169. status = v.Status,
  170. dept = string.IsNullOrWhiteSpace(kpi.Department) ? "未配置" : kpi.Department
  171. };
  172. }
  173. private static DiagnosisValue BuildDiagnosisValue(AdoSmartOpsKpiMaster kpi, Dictionary<string, DashboardMetricValueModel> values)
  174. {
  175. values.TryGetValue(kpi.MetricCode, out var value);
  176. var status = AidopS4KpiMerge.AchievementLevel(
  177. value?.MetricValue,
  178. value?.TargetValue,
  179. kpi.Direction ?? "higher_is_better",
  180. kpi.YellowThreshold,
  181. kpi.RedThreshold);
  182. var gap = AidopS4KpiMerge.GapValue(value?.MetricValue, value?.TargetValue);
  183. return new DiagnosisValue(value?.MetricValue, value?.TargetValue, status, FormatGapLabelGeneric(gap, kpi.Unit));
  184. }
  185. private static string FormatDiagnosisValue(decimal? value, string? unit)
  186. {
  187. if (value == null) return "-";
  188. var rounded = decimal.Round(value.Value, 2);
  189. return $"{rounded:0.##}{unit ?? ""}";
  190. }
  191. private static string BuildDiagnosisCallout(string? metricName, string status, string? gapLabel)
  192. {
  193. var name = string.IsNullOrWhiteSpace(metricName) ? "当前指标" : metricName;
  194. return status switch
  195. {
  196. "red" => $"{name} 未达标,期量差 {gapLabel ?? "-"},建议优先定位责任环节。",
  197. "yellow" => $"{name} 存在预警,期量差 {gapLabel ?? "-"},建议持续跟踪。",
  198. "green" => $"{name} 达标,可作为后续环节输入。",
  199. _ => $"{name} 暂无完整诊断数据。"
  200. };
  201. }
  202. private sealed record DiagnosisValue(decimal? Current, decimal? Target, string Status, string? GapLabel);
  203. }