AidopKanbanController.Generic.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. using Admin.NET.Plugin.AiDOP.Entity;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure;
  3. using Admin.NET.Plugin.AiDOP.SmartOps;
  4. using SqlSugar;
  5. namespace Admin.NET.Plugin.AiDOP.Controllers;
  6. public partial class AidopKanbanController
  7. {
  8. // S4.cs 中的 FormatGapLabel / ResolveMaxBizDateAsync 是 private,在同一 partial 类里可直接复用
  9. /// <summary>
  10. /// 通用运营布局(L1/L2/L3/L4)。moduleCode 指定模块;S4 也可走这个端点。
  11. /// </summary>
  12. [HttpGet("operation-layout/{moduleCode}")]
  13. public async Task<IActionResult> GetOperationLayoutGeneric(string moduleCode, [FromQuery] long factoryId = 1)
  14. {
  15. var mc = (moduleCode ?? "").ToUpperInvariant();
  16. if (string.IsNullOrWhiteSpace(mc)) return BadRequest(new { message = "moduleCode 必填" });
  17. var tenantId = AidopTenantHelper.GetTenantId(HttpContext);
  18. var hm = (await _db.Queryable<AdoSmartOpsHomeModule>()
  19. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc)
  20. .ToListAsync()).FirstOrDefault();
  21. var items = await _db.Queryable<AdoSmartOpsLayoutItem>()
  22. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc && x.IsEnabled == 1)
  23. .OrderBy(x => x.SortNo)
  24. .ToListAsync();
  25. var kpi = await _db.Queryable<AdoSmartOpsKpiMaster>()
  26. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc)
  27. .ToListAsync();
  28. var kpiByCode = kpi.ToDictionary(x => x.MetricCode, StringComparer.OrdinalIgnoreCase);
  29. object Row(AdoSmartOpsLayoutItem r)
  30. {
  31. kpiByCode.TryGetValue(r.MetricCode, out var k);
  32. return new
  33. {
  34. rowId = r.RowId,
  35. metricCode = r.MetricCode,
  36. metricLevel = r.MetricLevel,
  37. displayName = string.IsNullOrWhiteSpace(r.DisplayName) ? k?.MetricName : r.DisplayName,
  38. sortNo = r.SortNo,
  39. parentRowId = r.ParentRowId,
  40. formulaText = r.FormulaText,
  41. panelZone = r.PanelZone,
  42. unit = k?.Unit,
  43. direction = k?.Direction
  44. };
  45. }
  46. return Ok(new
  47. {
  48. moduleCode = mc,
  49. layoutPattern = hm?.LayoutPattern ?? "card_grid",
  50. l1 = items.Where(x => x.MetricLevel == 1).Select(Row).ToList(),
  51. l2 = items.Where(x => x.MetricLevel >= 2).Select(Row).ToList()
  52. });
  53. }
  54. /// <summary>
  55. /// 通用九宫格/首页(L1 合并日表)。moduleCode 指定模块。
  56. /// </summary>
  57. [HttpGet("home-grid/{moduleCode}")]
  58. public async Task<IActionResult> GetHomeGridGeneric(
  59. string moduleCode,
  60. [FromQuery] long factoryId = 1,
  61. [FromQuery] string? dateStart = null,
  62. [FromQuery] string? dateEnd = null,
  63. [FromQuery] string? product = null,
  64. [FromQuery] string? orderNo = null,
  65. [FromQuery] string? productionLine = null)
  66. {
  67. var mc = (moduleCode ?? "").ToUpperInvariant();
  68. if (string.IsNullOrWhiteSpace(mc)) return BadRequest(new { message = "moduleCode 必填" });
  69. var tenantId = AidopTenantHelper.GetTenantId(HttpContext);
  70. if (mc == "S8")
  71. await _s8KpiSnapshot.RefreshAsync(tenantId, factoryId);
  72. var filter = SmartOpsDashboardFilter.FromQuery(
  73. dateStart, dateEnd, product, orderNo, productionLine,
  74. null, null, null, null, null, null, null, null);
  75. var layout = await _db.Queryable<AdoSmartOpsLayoutItem>()
  76. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc && x.IsEnabled == 1 && x.MetricLevel == 1)
  77. .OrderBy(x => x.SortNo)
  78. .ToListAsync();
  79. var kpi = await _db.Queryable<AdoSmartOpsKpiMaster>()
  80. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc)
  81. .ToListAsync();
  82. var kpiBy = kpi.ToDictionary(x => x.MetricCode, StringComparer.OrdinalIgnoreCase);
  83. var bizDate = await ResolveMaxBizDateGenericAsync("ado_s9_kpi_value_l1_day", tenantId, factoryId, mc, filter.DateStart, filter.DateEnd);
  84. const string valSql = """
  85. SELECT v.metric_code AS MetricCode, v.metric_value AS MetricValue, v.target_value AS TargetValue
  86. FROM ado_s9_kpi_value_l1_day v
  87. WHERE v.tenant_id=@t AND v.factory_id=@f AND v.module_code=@m AND v.is_deleted=0
  88. AND v.biz_date=(
  89. SELECT MAX(v2.biz_date)
  90. FROM ado_s9_kpi_value_l1_day v2
  91. WHERE v2.tenant_id=v.tenant_id AND v2.factory_id=v.factory_id
  92. AND v2.module_code=v.module_code AND v2.metric_code=v.metric_code AND v2.is_deleted=0
  93. AND (@ds IS NULL OR v2.biz_date >= @ds)
  94. AND (@de IS NULL OR v2.biz_date <= @de)
  95. )
  96. """;
  97. var vals = await _db.Ado.SqlQueryAsync<S4ValRow>(valSql, new
  98. {
  99. t = tenantId,
  100. f = factoryId,
  101. m = mc,
  102. ds = filter.DateStart,
  103. de = filter.DateEnd
  104. });
  105. var valBy = vals.ToDictionary(x => x.MetricCode ?? "", StringComparer.OrdinalIgnoreCase);
  106. DashboardValuesBundle? filteredBundle = null;
  107. if (filter.HasBusinessDimension)
  108. filteredBundle = await ResolveDashboardValuesBundleAsync(tenantId, factoryId, mc, filter, kpi);
  109. var hm = (await _db.Queryable<AdoSmartOpsHomeModule>()
  110. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc)
  111. .ToListAsync()).FirstOrDefault();
  112. var items = new List<object>();
  113. foreach (var row in layout)
  114. {
  115. kpiBy.TryGetValue(row.MetricCode, out var k);
  116. valBy.TryGetValue(row.MetricCode, out var v);
  117. decimal? cur = v?.MetricValue;
  118. var tgt = v?.TargetValue;
  119. if (filteredBundle != null)
  120. {
  121. filteredBundle.Values.TryGetValue(row.MetricCode, out var fv);
  122. cur = fv?.MetricValue;
  123. tgt ??= fv?.TargetValue;
  124. }
  125. var dir = k?.Direction ?? "higher_is_better";
  126. var level = AidopS4KpiMerge.AchievementLevel(cur, tgt, dir, k?.YellowThreshold, k?.RedThreshold);
  127. var gap = AidopS4KpiMerge.GapValue(cur, tgt);
  128. var arrow = AidopS4KpiMerge.GapArrow(gap);
  129. var label = FormatGapLabelGeneric(gap, k?.Unit);
  130. items.Add(new
  131. {
  132. rowId = row.RowId,
  133. metricCode = row.MetricCode,
  134. displayName = string.IsNullOrWhiteSpace(row.DisplayName) ? k?.MetricName : row.DisplayName,
  135. unit = k?.Unit ?? "",
  136. currentValue = cur,
  137. targetValue = tgt,
  138. gapValue = gap,
  139. gapLabel = label,
  140. gapArrow = arrow,
  141. achievementLevel = level,
  142. formulaText = row.FormulaText
  143. });
  144. }
  145. return Ok(new
  146. {
  147. moduleCode = mc,
  148. layoutPattern = hm?.LayoutPattern ?? "card_grid",
  149. bizDate = bizDate.ToString("yyyy-MM-dd"),
  150. items
  151. });
  152. }
  153. /// <summary>
  154. /// 通用详情 KPI(L2/L3/L4 合并日表),可按 panelZone 过滤。
  155. /// </summary>
  156. [HttpGet("detail-kpis/{moduleCode}")]
  157. public async Task<IActionResult> GetDetailKpisGeneric(string moduleCode, [FromQuery] long factoryId = 1, [FromQuery] string? panelZone = null)
  158. {
  159. var mc = (moduleCode ?? "").ToUpperInvariant();
  160. if (string.IsNullOrWhiteSpace(mc)) return BadRequest(new { message = "moduleCode 必填" });
  161. var tenantId = AidopTenantHelper.GetTenantId(HttpContext);
  162. if (mc == "S8")
  163. await _s8KpiSnapshot.RefreshAsync(tenantId, factoryId);
  164. var q = _db.Queryable<AdoSmartOpsLayoutItem>()
  165. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc && x.IsEnabled == 1 && x.MetricLevel >= 2);
  166. if (!string.IsNullOrWhiteSpace(panelZone))
  167. q = q.Where(x => x.PanelZone == panelZone);
  168. var layout = await q.OrderBy(x => x.SortNo).ToListAsync();
  169. var kpi = await _db.Queryable<AdoSmartOpsKpiMaster>()
  170. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc)
  171. .ToListAsync();
  172. var kpiBy = kpi.ToDictionary(x => x.MetricCode, StringComparer.OrdinalIgnoreCase);
  173. var bizDateL2 = await ResolveMaxBizDateGenericAsync("ado_s9_kpi_value_l2_day", tenantId, factoryId, mc);
  174. var bizDateL3 = await ResolveMaxBizDateGenericAsync("ado_s9_kpi_value_l3_day", tenantId, factoryId, mc);
  175. AidopTenantMigration.EnsureKpiValueL4Table(_db);
  176. var bizDateL4 = await ResolveMaxBizDateGenericAsync("ado_s9_kpi_value_l4_day", tenantId, factoryId, mc);
  177. var bizDate = new[] { bizDateL2, bizDateL3, bizDateL4 }.Max();
  178. const string valSqlL2 = """
  179. SELECT v.metric_code AS MetricCode, v.metric_value AS MetricValue, v.target_value AS TargetValue
  180. FROM ado_s9_kpi_value_l2_day v
  181. WHERE v.tenant_id=@t AND v.factory_id=@f AND v.module_code=@m AND v.is_deleted=0
  182. AND v.biz_date=(SELECT MAX(v2.biz_date) FROM ado_s9_kpi_value_l2_day v2
  183. WHERE v2.tenant_id=v.tenant_id AND v2.factory_id=v.factory_id
  184. AND v2.module_code=v.module_code AND v2.metric_code=v.metric_code AND v2.is_deleted=0)
  185. """;
  186. const string valSqlL3 = """
  187. SELECT v.metric_code AS MetricCode, v.metric_value AS MetricValue, v.target_value AS TargetValue
  188. FROM ado_s9_kpi_value_l3_day v
  189. WHERE v.tenant_id=@t AND v.factory_id=@f AND v.module_code=@m AND v.is_deleted=0
  190. AND v.biz_date=(SELECT MAX(v2.biz_date) FROM ado_s9_kpi_value_l3_day v2
  191. WHERE v2.tenant_id=v.tenant_id AND v2.factory_id=v.factory_id
  192. AND v2.module_code=v.module_code AND v2.metric_code=v.metric_code AND v2.is_deleted=0)
  193. """;
  194. const string valSqlL4 = """
  195. SELECT v.metric_code AS MetricCode, v.metric_value AS MetricValue, v.target_value AS TargetValue
  196. FROM ado_s9_kpi_value_l4_day v
  197. WHERE v.tenant_id=@t AND v.factory_id=@f AND v.module_code=@m AND v.is_deleted=0
  198. AND v.biz_date=(SELECT MAX(v2.biz_date) FROM ado_s9_kpi_value_l4_day v2
  199. WHERE v2.tenant_id=v.tenant_id AND v2.factory_id=v.factory_id
  200. AND v2.module_code=v.module_code AND v2.metric_code=v.metric_code AND v2.is_deleted=0)
  201. """;
  202. var valsL2 = await _db.Ado.SqlQueryAsync<S4ValRow>(valSqlL2, new { t = tenantId, f = factoryId, m = mc });
  203. var valsL3 = await _db.Ado.SqlQueryAsync<S4ValRow>(valSqlL3, new { t = tenantId, f = factoryId, m = mc });
  204. var valsL4 = await _db.Ado.SqlQueryAsync<S4ValRow>(valSqlL4, new { t = tenantId, f = factoryId, m = mc });
  205. var valBy = new Dictionary<string, S4ValRow>(StringComparer.OrdinalIgnoreCase);
  206. foreach (var r in valsL2)
  207. if (!string.IsNullOrEmpty(r.MetricCode))
  208. valBy[r.MetricCode] = r;
  209. foreach (var r in valsL3)
  210. if (!string.IsNullOrEmpty(r.MetricCode))
  211. valBy[r.MetricCode] = r;
  212. foreach (var r in valsL4)
  213. if (!string.IsNullOrEmpty(r.MetricCode))
  214. valBy[r.MetricCode] = r;
  215. var items = new List<object>();
  216. foreach (var row in layout)
  217. {
  218. kpiBy.TryGetValue(row.MetricCode, out var k);
  219. valBy.TryGetValue(row.MetricCode, out var v);
  220. var cur = v?.MetricValue;
  221. var tgt = v?.TargetValue;
  222. var dir = k?.Direction ?? "higher_is_better";
  223. var level = AidopS4KpiMerge.AchievementLevel(cur, tgt, dir, k?.YellowThreshold, k?.RedThreshold);
  224. var gap = AidopS4KpiMerge.GapValue(cur, tgt);
  225. var arrow = AidopS4KpiMerge.GapArrow(gap);
  226. items.Add(new
  227. {
  228. rowId = row.RowId,
  229. metricCode = row.MetricCode,
  230. displayName = string.IsNullOrWhiteSpace(row.DisplayName) ? k?.MetricName : row.DisplayName,
  231. unit = k?.Unit ?? "",
  232. currentValue = cur,
  233. targetValue = tgt,
  234. gapValue = gap,
  235. gapLabel = FormatGapLabelGeneric(gap, k?.Unit),
  236. gapArrow = arrow,
  237. achievementLevel = level,
  238. formulaText = row.FormulaText,
  239. parentRowId = row.ParentRowId,
  240. panelZone = row.PanelZone
  241. });
  242. }
  243. return Ok(new { moduleCode = mc, bizDate = bizDate.ToString("yyyy-MM-dd"), items });
  244. }
  245. private async Task<DateTime> ResolveMaxBizDateGenericAsync(
  246. string table, long tenantId, long factoryId, string moduleCode,
  247. DateTime? dateStart = null, DateTime? dateEnd = null)
  248. {
  249. var sql = $"""
  250. SELECT MAX(biz_date) AS MaxBiz FROM {table}
  251. WHERE tenant_id=@t AND module_code=@m AND is_deleted=0
  252. AND (factory_id IS NULL OR factory_id=0 OR factory_id=1 OR factory_id=@f)
  253. AND (factory_id IS NULL OR factory_id<>@t)
  254. AND (@ds IS NULL OR biz_date >= @ds)
  255. AND (@de IS NULL OR biz_date <= @de)
  256. """;
  257. var rows = await _db.Ado.SqlQueryAsync<GenericMaxDateRow>(sql, new
  258. {
  259. t = tenantId,
  260. f = factoryId,
  261. m = moduleCode,
  262. ds = dateStart,
  263. de = dateEnd
  264. });
  265. return rows.FirstOrDefault()?.MaxBiz ?? DateTime.Today;
  266. }
  267. private static string FormatGapLabelGeneric(decimal? gap, string? unit)
  268. {
  269. if (gap == null) return "—";
  270. var g = gap.Value;
  271. var sign = g >= 0 ? "+" : "";
  272. var s = $"{sign}{Math.Round(g, 2)}";
  273. if (unit == "%")
  274. return s + "%";
  275. return s;
  276. }
  277. private sealed class GenericMaxDateRow
  278. {
  279. public DateTime? MaxBiz { get; set; }
  280. }
  281. /// <summary>
  282. /// 通用指标字典(按模块)。与 s4-metric-catalog 等价,moduleCode 必填。
  283. /// </summary>
  284. [HttpGet("metric-catalog/{moduleCode}")]
  285. public async Task<IActionResult> GetMetricCatalogGeneric(string moduleCode, [FromQuery] int? metricLevel = null)
  286. {
  287. var mc = (moduleCode ?? "").ToUpperInvariant();
  288. if (string.IsNullOrWhiteSpace(mc)) return BadRequest(new { message = "moduleCode 必填" });
  289. var tenantId = AidopTenantHelper.GetTenantId(HttpContext);
  290. var q = _db.Queryable<AdoSmartOpsKpiMaster>()
  291. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc && x.IsEnabled);
  292. if (metricLevel is > 0)
  293. q = q.Where(x => x.MetricLevel == metricLevel);
  294. var list = await q.OrderBy(x => x.SortNo).ToListAsync();
  295. return Ok(list.Select(x => new
  296. {
  297. id = x.Id,
  298. metricCode = x.MetricCode,
  299. moduleCode = x.ModuleCode,
  300. metricLevel = x.MetricLevel,
  301. defaultName = x.MetricName,
  302. unit = x.Unit,
  303. direction = x.Direction,
  304. sortHint = x.SortNo,
  305. parentId = x.ParentId,
  306. description = x.Description,
  307. formula = x.Formula,
  308. formulaExpr = x.FormulaExpr,
  309. formulaPreview = x.FormulaPreview,
  310. calcRule = x.CalcRule,
  311. dataSource = x.DataSource,
  312. statFrequency = x.StatFrequency,
  313. department = x.Department
  314. }));
  315. }
  316. public class GenericLayoutSaveDto
  317. {
  318. public List<GenericLayoutL1Dto>? L1 { get; set; }
  319. public List<GenericLayoutL2Dto>? L2 { get; set; }
  320. /// <summary>
  321. /// 九宫格首页模块卡呈现样式(card_grid | table_list | 未来新增)。
  322. /// 可选:未传或空值时保持 HomeModule 当前值;首次无记录时回落默认 card_grid。
  323. /// </summary>
  324. public string? LayoutPattern { get; set; }
  325. }
  326. /// <summary>
  327. /// 允许的 LayoutPattern 白名单。新增样式时在此增加条目(与前端 homeCardStyles.ts 注册表保持一致)。
  328. /// </summary>
  329. private static readonly HashSet<string> AllowedLayoutPatterns = new(StringComparer.OrdinalIgnoreCase)
  330. {
  331. "card_grid",
  332. "table_list",
  333. "tile_cards",
  334. };
  335. public class GenericLayoutL1Dto
  336. {
  337. public string? RowId { get; set; }
  338. public string? MetricCode { get; set; }
  339. public string? DisplayName { get; set; }
  340. public int SortNo { get; set; }
  341. public string? FormulaText { get; set; }
  342. }
  343. public class GenericLayoutL2Dto
  344. {
  345. public string? RowId { get; set; }
  346. public string? MetricCode { get; set; }
  347. public string? DisplayName { get; set; }
  348. public int SortNo { get; set; }
  349. public string? ParentRowId { get; set; }
  350. public string? FormulaText { get; set; }
  351. public string? PanelZone { get; set; }
  352. }
  353. /// <summary>
  354. /// 通用保存运营布局:按 moduleCode 保存 L1/L2 到 LayoutItem;同步 KpiMaster.DisplayName。
  355. /// 约束:L1 最多 MaxL1PerModule;必须命中该 moduleCode 的字典项。
  356. /// </summary>
  357. [HttpPut("operation-layout/{moduleCode}")]
  358. public async Task<IActionResult> PutOperationLayoutGeneric(string moduleCode, [FromBody] GenericLayoutSaveDto? body, [FromQuery] long factoryId = 1)
  359. {
  360. var mc = (moduleCode ?? "").ToUpperInvariant();
  361. if (string.IsNullOrWhiteSpace(mc)) return BadRequest(new { message = "moduleCode 必填" });
  362. var tenantId = AidopTenantHelper.GetTenantId(HttpContext);
  363. if (body?.L1 == null || body.L2 == null)
  364. return BadRequest(new { message = "L1/L2 不能为空" });
  365. if (body.L1.Count > MaxL1PerModule)
  366. return BadRequest(new { message = $"L1 最多 {MaxL1PerModule} 个" });
  367. var kpiAll = await _db.Queryable<AdoSmartOpsKpiMaster>()
  368. .Where(x => x.TenantId == tenantId && x.ModuleCode == mc && x.IsEnabled)
  369. .ToListAsync();
  370. var kpiByCode = kpiAll.ToDictionary(x => x.MetricCode, StringComparer.OrdinalIgnoreCase);
  371. foreach (var r in body.L1)
  372. {
  373. if (string.IsNullOrWhiteSpace(r.MetricCode) || !kpiByCode.TryGetValue(r.MetricCode.Trim(), out var k) || k.MetricLevel != 1)
  374. return BadRequest(new { message = $"无效的 L1 指标: {r.MetricCode}" });
  375. }
  376. var l1Ids = new HashSet<string>(StringComparer.Ordinal);
  377. foreach (var r in body.L1)
  378. {
  379. var rid = string.IsNullOrWhiteSpace(r.RowId) ? $"{mc}-L1-{r.MetricCode!.Trim()}" : r.RowId.Trim();
  380. if (!l1Ids.Add(rid))
  381. return BadRequest(new { message = $"重复的 L1 RowId: {rid}" });
  382. }
  383. foreach (var r in body.L2)
  384. {
  385. if (string.IsNullOrWhiteSpace(r.MetricCode) || !kpiByCode.TryGetValue(r.MetricCode.Trim(), out var k) || k.MetricLevel < 2)
  386. return BadRequest(new { message = $"无效的 L2/L3/L4 指标: {r.MetricCode}" });
  387. }
  388. var now = DateTime.Now;
  389. try
  390. {
  391. _db.Ado.BeginTran();
  392. await _db.Deleteable<AdoSmartOpsLayoutItem>()
  393. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc)
  394. .ExecuteCommandAsync();
  395. var rows = new List<AdoSmartOpsLayoutItem>();
  396. foreach (var r in body.L1)
  397. {
  398. var rid = string.IsNullOrWhiteSpace(r.RowId) ? $"{mc}-L1-{r.MetricCode!.Trim()}" : r.RowId.Trim();
  399. rows.Add(new AdoSmartOpsLayoutItem
  400. {
  401. TenantId = tenantId, FactoryId = factoryId, ModuleCode = mc,
  402. RowId = rid, MetricLevel = 1, MetricCode = r.MetricCode!.Trim(),
  403. DisplayName = string.IsNullOrWhiteSpace(r.DisplayName) ? null : r.DisplayName.Trim(),
  404. SortNo = r.SortNo, ParentRowId = null,
  405. FormulaText = string.IsNullOrWhiteSpace(r.FormulaText) ? null : r.FormulaText.Trim(),
  406. PanelZone = null, IsEnabled = 1, UpdateTime = now
  407. });
  408. }
  409. foreach (var r in body.L2)
  410. {
  411. var code = r.MetricCode!.Trim();
  412. var level = kpiByCode.TryGetValue(code, out var kk) ? kk.MetricLevel : 2;
  413. var prefix = $"{mc}-L{level}-";
  414. var rid = string.IsNullOrWhiteSpace(r.RowId) ? $"{prefix}{code}" : r.RowId.Trim();
  415. var p = string.IsNullOrWhiteSpace(r.ParentRowId) ? null : r.ParentRowId.Trim();
  416. rows.Add(new AdoSmartOpsLayoutItem
  417. {
  418. TenantId = tenantId, FactoryId = factoryId, ModuleCode = mc,
  419. RowId = rid, MetricLevel = level, MetricCode = code,
  420. DisplayName = string.IsNullOrWhiteSpace(r.DisplayName) ? null : r.DisplayName.Trim(),
  421. SortNo = r.SortNo, ParentRowId = p,
  422. FormulaText = string.IsNullOrWhiteSpace(r.FormulaText) ? null : r.FormulaText,
  423. PanelZone = string.IsNullOrWhiteSpace(r.PanelZone) ? null : r.PanelZone.Trim(),
  424. IsEnabled = 1, UpdateTime = now
  425. });
  426. }
  427. if (rows.Count > 0)
  428. await _db.Insertable(rows).ExecuteCommandAsync();
  429. foreach (var r in body.L1.Concat<object>(body.L2).Cast<dynamic>())
  430. {
  431. string? code = (string?)r.MetricCode?.Trim();
  432. string? dn = (string?)r.DisplayName?.Trim();
  433. if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(dn)) continue;
  434. if (!kpiByCode.TryGetValue(code, out var kpi)) continue;
  435. if (!string.Equals(kpi.MetricName, dn, StringComparison.Ordinal))
  436. {
  437. await _db.Updateable<AdoSmartOpsKpiMaster>()
  438. .SetColumns(x => new AdoSmartOpsKpiMaster { MetricName = dn, UpdatedAt = now })
  439. .Where(x => x.Id == kpi.Id)
  440. .ExecuteCommandAsync();
  441. }
  442. }
  443. var lp = (body.LayoutPattern ?? "").Trim();
  444. if (!string.IsNullOrEmpty(lp) && !AllowedLayoutPatterns.Contains(lp))
  445. return BadRequest(new { message = $"无效的 LayoutPattern: {body.LayoutPattern}" });
  446. var lpNormalized = string.IsNullOrEmpty(lp) ? null : lp.ToLowerInvariant();
  447. int hmRows;
  448. if (lpNormalized != null)
  449. {
  450. hmRows = await _db.Updateable<AdoSmartOpsHomeModule>()
  451. .SetColumns(x => new AdoSmartOpsHomeModule { LayoutPattern = lpNormalized, UpdateTime = now })
  452. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc)
  453. .ExecuteCommandAsync();
  454. }
  455. else
  456. {
  457. hmRows = await _db.Updateable<AdoSmartOpsHomeModule>()
  458. .SetColumns(x => new AdoSmartOpsHomeModule { UpdateTime = now })
  459. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.ModuleCode == mc)
  460. .ExecuteCommandAsync();
  461. }
  462. if (hmRows == 0)
  463. {
  464. await _db.Insertable(new AdoSmartOpsHomeModule
  465. {
  466. TenantId = tenantId, FactoryId = factoryId, ModuleCode = mc,
  467. LayoutPattern = lpNormalized ?? "card_grid", UpdateTime = now
  468. }).ExecuteCommandAsync();
  469. }
  470. _db.Ado.CommitTran();
  471. }
  472. catch (Exception ex)
  473. {
  474. _db.Ado.RollbackTran();
  475. return BadRequest(new { message = ex.Message });
  476. }
  477. return Ok(new { ok = true });
  478. }
  479. }