MdpPurchaseHandoffService.Cutover.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. public sealed partial class MdpPurchaseHandoffService
  6. {
  7. internal async Task<RelationalPageProof> ProveRelationalPageAsync(PurchaseHandoffPackage package, CancellationToken token)
  8. {
  9. using var db = OpenBusinessDatabase();
  10. db.Ado.CancellationToken = token;
  11. var batchId = package.BatchId.ToString("D");
  12. var stored = await db.Ado.SqlQuerySingleAsync<StoredCutoverReceipt>("""
  13. SELECT payload_sha256 AS Digest,receipt_json AS Receipt,line_results AS LineResults
  14. FROM mdp_ingest_handoff_receipt
  15. WHERE batch_id=@batchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
  16. AND dataset_id=@DatasetId AND package_code=@PackageCode AND package_version=@PackageVersion AND digest_format=2
  17. """, new { batchId, package.TenantId, package.FactoryId, package.SourceId,
  18. package.DatasetId, package.PackageCode, package.PackageVersion });
  19. if (stored is null || stored.Digest != package.ComputeDigest()) return new(0, "HANDOFF_DIGEST_MISMATCH");
  20. try
  21. {
  22. var receipt = JsonSerializer.Deserialize<PurchaseHandoffReceipt>(stored.Receipt, WireJson);
  23. var received = JsonSerializer.Deserialize<LineResult[]>(stored.LineResults, WireJson);
  24. var expected = package.Items.Select(line => line.RawEventId).ToArray();
  25. if (receipt is null || receipt.BatchId != package.BatchId || receipt.Conflicts is null
  26. || receipt.Conflicts.Count != 0 || receipt.AcceptedCount != expected.Length || received is null
  27. || !RelationalCutover.HasExactLines(expected, received.Select(line => line.RawEventId).ToArray()))
  28. return new(0, "HANDOFF_LINE_SET_MISMATCH");
  29. var receiptsByEvent = received.ToDictionary(line => line.RawEventId);
  30. var keys = JsonSerializer.Serialize(package.Items.GroupBy(line => (line.PoNo, line.PoLine)).Select(group =>
  31. new { group.Key.PoNo, group.Key.PoLine, stageId = receiptsByEvent[group.First().RawEventId].StageId }), WireJson);
  32. var rows = await db.Ado.SqlQueryAsync<CutoverOrder>("""
  33. SELECT k.po_no AS PoNo,k.po_line AS PoLine,s.id AS StandardId,a.id AS ActiveId,
  34. s.source_system AS StandardSource,s.source_biz_key AS StandardKey,s.item_code AS ItemCode,
  35. s.supplier_code AS SupplierCode,s.order_qty AS OrderQty,s.due_date AS DueDate,
  36. s.order_date AS OrderDate,s.status AS Status,
  37. t.id AS StageId,t.raw_data AS StageRaw,t.source_system AS StageSource,t.source_biz_key AS StageKey,
  38. v.source_id AS VersionSourceId,v.dataset_id AS VersionDatasetId,v.source_system AS VersionSource,
  39. v.standard_id AS VersionStandardId,v.source_generation AS Generation,v.source_version AS Version,
  40. v.is_deleted AS Deleted,current_receipt.batch_id AS VersionBatch
  41. FROM JSON_TABLE(@keys, '$[*]' COLUMNS (
  42. po_no VARCHAR(100) PATH '$.poNo',po_line VARCHAR(50) PATH '$.poLine',stage_id BIGINT PATH '$.stageId'
  43. )) k
  44. LEFT JOIN mdp_std_purchase_order_version v ON v.tenant_id=@TenantId AND v.factory_id=@FactoryId
  45. AND v.po_no=k.po_no AND v.po_line=k.po_line
  46. LEFT JOIN mdp_std_purchase_order s ON s.tenant_id=@TenantId AND s.factory_id=@FactoryId
  47. AND s.po_no=k.po_no AND s.po_line=k.po_line
  48. LEFT JOIN mdp_std_purchase_order_active a ON a.id=s.id
  49. LEFT JOIN mdp_stg_purchase_order t ON t.id=COALESCE(v.stage_id,k.stage_id)
  50. AND t.tenant_id=@TenantId AND t.factory_id=@FactoryId AND t.source_table='S3_PURCHASE_ORDER'
  51. LEFT JOIN mdp_ingest_handoff_receipt current_receipt ON current_receipt.batch_id=v.batch_id
  52. AND current_receipt.tenant_id=@TenantId AND current_receipt.factory_id=@FactoryId
  53. AND current_receipt.dataset_id=@DatasetId AND current_receipt.source_id=@SourceId
  54. """, new { keys, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId });
  55. var byKey = rows.ToLookup(row => (row.PoNo, row.PoLine));
  56. var proven = 0;
  57. foreach (var line in package.Items)
  58. {
  59. token.ThrowIfCancellationRequested();
  60. var actual = byKey[(line.PoNo, line.PoLine)].ToArray();
  61. var issue = actual.Length == 1 ? VerifyLine(package, line, receiptsByEvent[line.RawEventId], actual[0])
  62. : "STANDARD_KEY_MISMATCH";
  63. if (issue is not null) return new(proven, issue, line.BusinessKey);
  64. proven++;
  65. }
  66. return new(proven);
  67. }
  68. catch (JsonException)
  69. {
  70. return new(0, "HANDOFF_JSON_MISMATCH");
  71. }
  72. }
  73. private static string? VerifyLine(PurchaseHandoffPackage package, PurchaseHandoffLine line, LineResult receipt, CutoverOrder row)
  74. {
  75. if (receipt.Status is not ("WRITTEN" or "REUSED" or "STALE" or "DELETED")) return "HANDOFF_LINE_STATUS";
  76. var sameVersion = true;
  77. if (line.SourceChange is { } change)
  78. {
  79. if (row.VersionSourceId != package.SourceId || row.VersionDatasetId != package.DatasetId
  80. || row.VersionSource != package.SourceCode || row.VersionBatch is null
  81. || row.Generation is null || row.Version is null || row.VersionStandardId != row.StandardId
  82. || row.Generation < change.Generation || (row.Generation == change.Generation && row.Version < change.Version))
  83. return "STANDARD_VERSION_MISMATCH";
  84. sameVersion = row.Generation == change.Generation && row.Version == change.Version;
  85. if (sameVersion && (row.Deleted != change.Deleted || receipt.Status == "STALE"))
  86. return "STANDARD_VERSION_MISMATCH";
  87. if (row.Deleted)
  88. return row.ActiveId is null ? null : "DELETED_ORDER_VISIBLE";
  89. }
  90. else if (receipt.Status is "STALE" or "DELETED")
  91. return "HANDOFF_LINE_STATUS";
  92. if (row.ActiveId is null || row.ActiveId != row.StandardId || row.StageId is null
  93. || row.StageSource != package.SourceCode || row.StandardSource != package.SourceCode
  94. || row.StageKey != row.StandardKey || row.StageRaw is null
  95. || (sameVersion && (row.StageId != receipt.StageId || row.StandardId != receipt.StandardId)))
  96. return "STAGE_STANDARD_SCOPE_MISMATCH";
  97. var stage = JsonSerializer.Deserialize<StageFields>(row.StageRaw, WireJson);
  98. if (stage is null || stage.PoNo != line.PoNo || stage.PoLine != line.PoLine
  99. || (sameVersion && stage != new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode,
  100. line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt)))
  101. return "STAGE_LINE_MISMATCH";
  102. return row.ItemCode == stage.ItemCode && row.SupplierCode == stage.SupplierCode && row.OrderQty == stage.OrderQty
  103. && row.DueDate == stage.DueDate && row.OrderDate == stage.OrderDate && row.Status == stage.Status
  104. ? null : "STANDARD_LINE_MISMATCH";
  105. }
  106. private sealed class StoredCutoverReceipt
  107. {
  108. public string Digest { get; set; } = "";
  109. public string Receipt { get; set; } = "";
  110. public string LineResults { get; set; } = "";
  111. }
  112. private sealed class CutoverOrder
  113. {
  114. public string PoNo { get; set; } = "";
  115. public string PoLine { get; set; } = "";
  116. public long? StandardId { get; set; }
  117. public long? ActiveId { get; set; }
  118. public long? StageId { get; set; }
  119. public string? StandardSource { get; set; }
  120. public string? StandardKey { get; set; }
  121. public string? StageRaw { get; set; }
  122. public string? StageSource { get; set; }
  123. public string? StageKey { get; set; }
  124. public string? ItemCode { get; set; }
  125. public string? SupplierCode { get; set; }
  126. public decimal? OrderQty { get; set; }
  127. public DateTime? DueDate { get; set; }
  128. public DateTime? OrderDate { get; set; }
  129. public string? Status { get; set; }
  130. public long? VersionSourceId { get; set; }
  131. public long? VersionDatasetId { get; set; }
  132. public string? VersionSource { get; set; }
  133. public long? VersionStandardId { get; set; }
  134. public long? Generation { get; set; }
  135. public long? Version { get; set; }
  136. public bool Deleted { get; set; }
  137. public string? VersionBatch { get; set; }
  138. }
  139. }