MdpNeutralSourceCleanup.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using Microsoft.Extensions.Logging;
  2. namespace Admin.NET.Plugin.AiDOP.DataPlatform;
  3. /// <summary>
  4. /// 删除某租户某标准对象里来源与登记不一致的中立行。不删贴源,不删目录之外的表。
  5. /// </summary>
  6. public sealed class MdpNeutralSourceCleanup : ITransient
  7. {
  8. private readonly ISqlSugarClient _db;
  9. private readonly ILogger _logger;
  10. public MdpNeutralSourceCleanup(ISqlSugarClient db, ILoggerFactory loggerFactory)
  11. {
  12. _db = db;
  13. _logger = loggerFactory.CreateLogger(nameof(MdpNeutralSourceCleanup));
  14. }
  15. public async Task<int> PurgeModuleAsync(long tenantId, string moduleCode, CancellationToken cancellationToken = default)
  16. {
  17. var total = 0;
  18. foreach (var def in MdpStdObjectCatalog.All.Where(d => d.Module == moduleCode))
  19. {
  20. cancellationToken.ThrowIfCancellationRequested();
  21. total += await PurgeObjectAsync(tenantId, def.Code, cancellationToken);
  22. }
  23. return total;
  24. }
  25. public async Task<int> PurgeObjectAsync(long tenantId, string stdObject, CancellationToken cancellationToken = default)
  26. {
  27. var def = MdpStdObjectCatalog.Find(stdObject);
  28. if (def == null || tenantId <= 0)
  29. return 0;
  30. var total = 0;
  31. foreach (var table in def.Tables)
  32. {
  33. cancellationToken.ThrowIfCancellationRequested();
  34. // 采购订单由 S3 按工厂、来源和成功全量批次清理。租户级来源登记不能删除订单。
  35. if (table == "mdp_std_purchase_order")
  36. continue;
  37. if (!await TableReadyAsync(table))
  38. continue;
  39. var docFilter = string.IsNullOrEmpty(def.DocType) || !await ColumnExistsAsync(table, "doc_type")
  40. ? ""
  41. : " AND t.doc_type=@doc";
  42. if (!await RegisteredSourceHasRowsAsync(tenantId, def.Code, table, docFilter, cancellationToken))
  43. continue;
  44. var sql = $"""
  45. DELETE t FROM `{table}` t
  46. INNER JOIN mdp_tenant_std_source s
  47. ON s.tenant_id=t.tenant_id AND s.std_object=@obj
  48. WHERE t.tenant_id=@tenant
  49. AND t.source_system<>s.source_system
  50. {docFilter}
  51. """;
  52. var n = await _db.Ado.ExecuteCommandAsync(sql, new { tenant = tenantId, obj = def.Code, doc = def.DocType });
  53. if (n > 0)
  54. _logger.LogWarning(
  55. "中立层来源清理 tenant={Tenant} object={Object} table={Table} deleted={Deleted}",
  56. tenantId, def.Code, table, n);
  57. total += n;
  58. }
  59. return total;
  60. }
  61. /// <summary>
  62. /// 登记来源在该表一行都没有时,不执行清理。
  63. /// <para>
  64. /// 清理是「按登记收口」,不是「清空对象」。若登记来源尚未产出任何行,删掉非登记来源就等于
  65. /// 把该对象整片清空:指标随即算出 NO_DATA 且全程不报错,看板一夜之间没数(S6/S7 就是这么掉的)。
  66. /// 这种情况下真正的问题是登记与数据不一致,须人工核对登记,不能靠重算去「修正」。
  67. /// 故此处保留存量并按 <c>PURGE_SKIPPED_EMPTY_SOURCE</c> 告警,宁可留旧数据也不静默清空。
  68. /// </para>
  69. /// </summary>
  70. private async Task<bool> RegisteredSourceHasRowsAsync(
  71. long tenantId, string stdObject, string table, string docFilter, CancellationToken cancellationToken)
  72. {
  73. cancellationToken.ThrowIfCancellationRequested();
  74. var rows = await _db.Ado.SqlQueryAsync<SourceRowCount>(
  75. $"""
  76. SELECT MAX(s.source_system) AS RegisteredSource,
  77. SUM(t.source_system=s.source_system) AS RegisteredRows,
  78. SUM(t.source_system<>s.source_system) AS ForeignRows
  79. FROM `{table}` t
  80. INNER JOIN mdp_tenant_std_source s
  81. ON s.tenant_id=t.tenant_id AND s.std_object=@obj
  82. WHERE t.tenant_id=@tenant
  83. {docFilter}
  84. """,
  85. new { tenant = tenantId, obj = stdObject, doc = MdpStdObjectCatalog.Find(stdObject)?.DocType });
  86. var stat = rows.FirstOrDefault();
  87. if (stat == null || stat.ForeignRows <= 0)
  88. return true;
  89. if (stat.RegisteredRows > 0)
  90. return true;
  91. _logger.LogError(
  92. "中立层来源清理已跳过:登记来源无数据 tenant={Tenant} object={Object} table={Table} 登记来源={Source} 待清理行={Foreign}",
  93. tenantId, stdObject, table, stat.RegisteredSource, stat.ForeignRows);
  94. await _db.Ado.ExecuteCommandAsync(
  95. """
  96. INSERT INTO mdp_source_gate_log
  97. (tenant_id, std_object, source_system, gate_reason, row_count, sample_keys, sync_batch_id)
  98. VALUES (@tenant, @obj, @src, 'PURGE_SKIPPED_EMPTY_SOURCE', @rows, @sample, '')
  99. """,
  100. new
  101. {
  102. tenant = tenantId,
  103. obj = stdObject,
  104. src = stat.RegisteredSource ?? "",
  105. rows = stat.ForeignRows,
  106. sample = table
  107. });
  108. return false;
  109. }
  110. private sealed class SourceRowCount
  111. {
  112. public string? RegisteredSource { get; set; }
  113. public long RegisteredRows { get; set; }
  114. public long ForeignRows { get; set; }
  115. }
  116. private async Task<bool> TableReadyAsync(string table)
  117. {
  118. var n = await _db.Ado.SqlQueryAsync<int>(
  119. """
  120. SELECT COUNT(*) FROM information_schema.COLUMNS
  121. WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=@table AND COLUMN_NAME='source_system'
  122. """,
  123. new { table });
  124. return n.FirstOrDefault() > 0;
  125. }
  126. private async Task<bool> ColumnExistsAsync(string table, string column)
  127. {
  128. var n = await _db.Ado.SqlQueryAsync<int>(
  129. """
  130. SELECT COUNT(*) FROM information_schema.COLUMNS
  131. WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=@table AND COLUMN_NAME=@column
  132. """,
  133. new { table, column });
  134. return n.FirstOrDefault() > 0;
  135. }
  136. }