MdpPurchaseMigrationWriter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System.Globalization;
  2. using System.Security.Cryptography;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. internal sealed record PurchaseMigrationLineResult(string Status, long? StageId, long? StandardId);
  7. /// <summary>在调用方持有范围行锁的事务中,用同一份业务对照处理两个入口。</summary>
  8. internal static class MdpPurchaseMigrationWriter
  9. {
  10. private static readonly string[] LocalDateFormats =
  11. ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", "yyyy-MM-dd HH:mm:ss.FFFFFFF"];
  12. private static readonly string[] OffsetDateFormats =
  13. ["yyyy-MM-dd'T'HH:mm:sszzz", "yyyy-MM-dd HH:mm:sszzz", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFzzz", "yyyy-MM-dd HH:mm:ss.FFFFFFFzzz"];
  14. internal static async Task<PurchaseMigrationLineResult> WriteAsync(
  15. ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId)
  16. {
  17. MdpPurchaseMigrationStore.RequireWriter(scope, writer);
  18. var identity = new { ScopeId = scope.Id, line.PoNo, line.PoLine };
  19. var content = OrderContent.From(line);
  20. var digest = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(content))).ToLowerInvariant();
  21. var existing = await db.Ado.SqlQuerySingleAsync<LedgerRow>(
  22. """
  23. SELECT content_sha256 AS Digest, stage_id AS StageId, standard_id AS StandardId
  24. FROM mdp_purchase_migration_line WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
  25. """, identity);
  26. var result = existing is not null && existing.Digest != digest
  27. ? new PurchaseMigrationLineResult("CONFLICT", null, null)
  28. : await ResolveAsync(db, scope, writer, line, batchId, traceId, content, existing);
  29. if (result.StageId is long stageId && result.StandardId is long standardId)
  30. {
  31. if (existing is null)
  32. await db.Ado.ExecuteCommandAsync(
  33. """
  34. INSERT INTO mdp_purchase_migration_line
  35. (scope_id, po_no, po_line, content_sha256, stage_id, standard_id, created_at)
  36. VALUES (@ScopeId, @PoNo, @PoLine, @Digest, @StageId, @StandardId, UTC_TIMESTAMP(6))
  37. """, new { identity.ScopeId, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
  38. else if (existing.StandardId != standardId)
  39. await db.Ado.ExecuteCommandAsync(
  40. """
  41. UPDATE mdp_purchase_migration_line SET standard_id=@StandardId
  42. WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine AND stage_id=@StageId
  43. """, new { identity.ScopeId, line.PoNo, line.PoLine, StageId = stageId, StandardId = standardId });
  44. }
  45. await db.Ado.ExecuteCommandAsync(
  46. """
  47. INSERT INTO mdp_purchase_migration_observation
  48. (scope_id, writer, trace_id, batch_id, po_no, po_line, content_sha256, resolution, stage_id, standard_id, created_at)
  49. VALUES (@ScopeId,@Writer,@TraceId,@BatchId,@PoNo,@PoLine,@Digest,@Status,@StageId,@StandardId,UTC_TIMESTAMP(6))
  50. """, new { identity.ScopeId, Writer = writer, TraceId = traceId, BatchId = batchId, line.PoNo, line.PoLine,
  51. Digest = digest, result.Status, result.StageId, result.StandardId });
  52. return result;
  53. }
  54. private static async Task<PurchaseMigrationLineResult> ResolveAsync(
  55. ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId,
  56. OrderContent content, LedgerRow? existing)
  57. {
  58. var scopedKey = FormattableString.Invariant($"{scope.TenantId}#{scope.FactoryId}#{line.BusinessKey}");
  59. var stageCandidates = await db.Ado.SqlQueryAsync<StoredStage>(
  60. """
  61. SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
  62. sync_batch_id AS BatchId, raw_data AS RawData
  63. FROM mdp_stg_purchase_order
  64. WHERE tenant_id=@TenantId AND source_table='S3_PURCHASE_ORDER'
  65. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
  66. AND source_biz_key IN (@LegacyKey,@ScopedKey)
  67. FOR SHARE
  68. """, new { scope.TenantId, scope.FactoryId, LegacyKey = line.BusinessKey, ScopedKey = scopedKey });
  69. var standards = await db.Ado.SqlQueryAsync<StoredStandard>(
  70. """
  71. SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
  72. sync_batch_id AS BatchId, po_no AS PoNo, po_line AS PoLine, item_code AS ItemCode, supplier_code AS SupplierCode,
  73. order_qty AS OrderQty, order_date AS OrderDate, due_date AS DueDate, status AS Status
  74. FROM mdp_std_purchase_order WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine
  75. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0
  76. OR (factory_id=1 AND source_system=@LegacySourceCode AND source_biz_key=@LegacyKey AND sync_batch_id=@StageBatch))
  77. FOR UPDATE
  78. """, new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine, scope.LegacySourceCode,
  79. LegacyKey = line.BusinessKey, StageBatch = stageCandidates.Count == 1 ? stageCandidates[0].BatchId : null });
  80. if (standards.Count > 1)
  81. return new("CONFLICT", null, null);
  82. var standard = standards.SingleOrDefault();
  83. if (stageCandidates.Count == 0 && standard is null && existing is null)
  84. {
  85. var legacy = writer == MdpPurchaseMigrationStore.Legacy;
  86. var package = new PurchaseHandoffPackage(Guid.Empty, string.Empty, scope.TenantId, scope.FactoryId, scope.NewSourceId,
  87. scope.DatasetId, PurchaseOrderSchemaRegistry.DatasetKey, legacy ? scope.LegacySourceCode : scope.NewSourceCode,
  88. PurchaseHandoffPackage.Version, PurchaseOrderSchemaRegistry.SourceVersion, "po-map-v1", [line]);
  89. return await MdpPurchaseHandoffService.WriteLineAsync(db, package, batchId, line, scopedKey, traceId);
  90. }
  91. var conflict = new PurchaseMigrationLineResult("CONFLICT", null, null);
  92. if (stageCandidates is not [var stage] || stage.FactoryId != scope.FactoryId
  93. || (stage.SourceCode != scope.LegacySourceCode && stage.SourceCode != scope.NewSourceCode)
  94. || (existing is not null && stage.Id != existing.StageId) || !stage.Matches(content))
  95. return conflict;
  96. var oldStage = string.Equals(stage.SourceCode, scope.LegacySourceCode, StringComparison.Ordinal);
  97. if (existing is null && !await HasCustodyEvidenceAsync(db, scope, stage, oldStage, writer))
  98. return conflict;
  99. if (standard is null)
  100. {
  101. var standardId = await MdpPurchaseHandoffService.InsertStandardAsync(db, scope.TenantId, scope.FactoryId,
  102. stage.SourceCode, stage.BusinessKey, stage.BatchId, line);
  103. return standardId.HasValue ? new("WRITTEN", stage.Id, standardId) : conflict;
  104. }
  105. if ((existing is not null && standard.Id != existing.StandardId)
  106. || standard.SourceCode != stage.SourceCode || standard.BusinessKey != stage.BusinessKey
  107. || standard.BatchId != stage.BatchId || standard.Content() != content)
  108. return conflict;
  109. if (standard.FactoryId != scope.FactoryId)
  110. {
  111. // 老投影用过默认工厂。只有证据已证明同一授权、贴源行及原批次时才认领。
  112. if (!oldStage || standard.FactoryId != 1)
  113. return conflict;
  114. await db.Ado.ExecuteCommandAsync(
  115. """
  116. UPDATE mdp_std_purchase_order SET factory_id=@FactoryId
  117. WHERE id=@Id AND tenant_id=@TenantId AND factory_id=1
  118. AND source_system=@SourceCode AND sync_batch_id=@BatchId
  119. """, new { scope.FactoryId, standard.Id, scope.TenantId, stage.SourceCode, stage.BatchId });
  120. }
  121. return new("REUSED", stage.Id, standard.Id);
  122. }
  123. private static async Task<bool> HasCustodyEvidenceAsync(
  124. ISqlSugarClient db, PurchaseMigrationScope scope, StoredStage stage, bool legacy, string writer)
  125. {
  126. if (legacy && writer == MdpPurchaseMigrationStore.Unified)
  127. return await db.Ado.GetIntAsync(
  128. """
  129. SELECT COUNT(*) FROM mdp_purchase_legacy_custody
  130. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_code=@SourceCode AND sync_batch_id=@BatchId
  131. """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
  132. if (legacy)
  133. return await db.Ado.GetIntAsync(
  134. """
  135. SELECT COUNT(*)
  136. FROM mdp_inbound_request r
  137. JOIN mdp_inbound_grant g ON g.tenant_id=r.tenant_id AND g.access_key=r.access_key
  138. AND g.entity_code=r.entity_code AND g.source_code=@SourceCode AND g.factory_id=@FactoryId
  139. WHERE r.tenant_id=@TenantId AND r.entity_code='S3_PURCHASE_ORDER'
  140. AND r.sync_batch_id=@BatchId AND r.status='COMMITTED' AND r.accepted>0
  141. """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
  142. return await db.Ado.GetIntAsync(
  143. """
  144. SELECT COUNT(*)
  145. FROM mdp_ingest_handoff_receipt r
  146. JOIN JSON_TABLE(r.line_results, '$[*]' COLUMNS (stage_id BIGINT PATH '$.stageId' NULL ON EMPTY NULL ON ERROR)) line
  147. ON line.stage_id=@StageId
  148. WHERE r.batch_id=@BatchId AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId
  149. AND r.dataset_id=@DatasetId AND r.source_id=@NewSourceId
  150. """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, scope.NewSourceId, StageId = stage.Id, stage.BatchId }) == 1;
  151. }
  152. internal static bool TryParseBusinessDate(string? text, out DateTime? result)
  153. {
  154. result = null;
  155. if (string.IsNullOrWhiteSpace(text))
  156. return true;
  157. DateTime date;
  158. if (text.EndsWith('Z'))
  159. text = text[..^1] + "+00:00";
  160. if (DateTimeOffset.TryParseExact(text, OffsetDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var offset))
  161. {
  162. var ticks = offset.UtcTicks + TimeSpan.FromHours(8).Ticks;
  163. if (ticks > DateTime.MaxValue.Ticks)
  164. return false;
  165. date = new DateTime(ticks);
  166. }
  167. else if (!DateTime.TryParseExact(text, LocalDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
  168. return false;
  169. if (date.Year < 1000)
  170. return false;
  171. result = new DateTime(date.Ticks - date.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
  172. return true;
  173. }
  174. private sealed record OrderContent(string PoNo, string PoLine, string ItemCode, string? SupplierCode,
  175. string Quantity, DateTime? OrderDate, DateTime? DueDate, string? Status)
  176. {
  177. public static OrderContent From(PurchaseHandoffLine line) =>
  178. new(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, QuantityOf(line.OrderQty),
  179. Clock(line.OrderDate), Clock(line.DueDate), line.Status);
  180. public static string QuantityOf(decimal quantity) => quantity.ToString("0.############################", CultureInfo.InvariantCulture);
  181. private static DateTime? Clock(DateTime? date) =>
  182. date.HasValue ? DateTime.SpecifyKind(date.Value, DateTimeKind.Unspecified) : null;
  183. }
  184. private sealed class LedgerRow
  185. {
  186. public string Digest { get; set; } = string.Empty;
  187. public long StageId { get; set; }
  188. public long StandardId { get; set; }
  189. }
  190. private sealed class StoredStage
  191. {
  192. public long Id { get; set; }
  193. public long? FactoryId { get; set; }
  194. public string SourceCode { get; set; } = string.Empty;
  195. public string BusinessKey { get; set; } = string.Empty;
  196. public string BatchId { get; set; } = string.Empty;
  197. public string RawData { get; set; } = string.Empty;
  198. public bool Matches(OrderContent expected)
  199. {
  200. try
  201. {
  202. using var json = JsonDocument.Parse(RawData);
  203. var row = json.RootElement;
  204. if (!row.TryGetProperty("OrderQty", out var qty)
  205. || !decimal.TryParse(qty.ValueKind == JsonValueKind.String ? qty.GetString() : qty.GetRawText(),
  206. NumberStyles.Float, CultureInfo.InvariantCulture, out var quantity)
  207. || !TryParseBusinessDate(Text("OrderDate"), out var orderDate)
  208. || !TryParseBusinessDate(Text("DueDate"), out var dueDate))
  209. return false;
  210. return new OrderContent(Text("PoNo") ?? "", Text("PoLine") ?? "", Text("ItemCode") ?? "", Text("SupplierCode"),
  211. OrderContent.QuantityOf(quantity), orderDate, dueDate, Text("Status")) == expected;
  212. string? Text(string name) => row.TryGetProperty(name, out var item) && item.ValueKind == JsonValueKind.String
  213. ? item.GetString() : null;
  214. }
  215. catch (JsonException)
  216. {
  217. return false;
  218. }
  219. }
  220. }
  221. private sealed class StoredStandard
  222. {
  223. public long Id { get; set; }
  224. public long? FactoryId { get; set; }
  225. public string SourceCode { get; set; } = string.Empty;
  226. public string BusinessKey { get; set; } = string.Empty;
  227. public string BatchId { get; set; } = string.Empty;
  228. public string PoNo { get; set; } = string.Empty;
  229. public string PoLine { get; set; } = string.Empty;
  230. public string ItemCode { get; set; } = string.Empty;
  231. public string? SupplierCode { get; set; }
  232. public decimal? OrderQty { get; set; }
  233. public DateTime? OrderDate { get; set; }
  234. public DateTime? DueDate { get; set; }
  235. public string? Status { get; set; }
  236. public OrderContent? Content() => OrderQty.HasValue
  237. ? new(PoNo, PoLine, ItemCode, SupplierCode, OrderContent.QuantityOf(OrderQty.Value), OrderDate, DueDate, Status)
  238. : null;
  239. }
  240. }