using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed partial class MdpPurchaseHandoffService { internal async Task ProveRelationalPageAsync(PurchaseHandoffPackage package, CancellationToken token) { using var db = OpenBusinessDatabase(); db.Ado.CancellationToken = token; var batchId = package.BatchId.ToString("D"); var stored = await db.Ado.SqlQuerySingleAsync(""" SELECT payload_sha256 AS Digest,receipt_json AS Receipt,line_results AS LineResults FROM mdp_ingest_handoff_receipt WHERE batch_id=@batchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId AND dataset_id=@DatasetId AND package_code=@PackageCode AND package_version=@PackageVersion AND digest_format=2 """, new { batchId, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, package.PackageCode, package.PackageVersion }); if (stored is null || stored.Digest != package.ComputeDigest()) return new(0, "HANDOFF_DIGEST_MISMATCH"); try { var receipt = JsonSerializer.Deserialize(stored.Receipt, WireJson); var received = JsonSerializer.Deserialize(stored.LineResults, WireJson); var expected = package.Items.Select(line => line.RawEventId).ToArray(); if (receipt is null || receipt.BatchId != package.BatchId || receipt.Conflicts is null || receipt.Conflicts.Count != 0 || receipt.AcceptedCount != expected.Length || received is null || !RelationalCutover.HasExactLines(expected, received.Select(line => line.RawEventId).ToArray())) return new(0, "HANDOFF_LINE_SET_MISMATCH"); var receiptsByEvent = received.ToDictionary(line => line.RawEventId); var keys = JsonSerializer.Serialize(package.Items.GroupBy(line => (line.PoNo, line.PoLine)).Select(group => new { group.Key.PoNo, group.Key.PoLine, stageId = receiptsByEvent[group.First().RawEventId].StageId }), WireJson); var rows = await db.Ado.SqlQueryAsync(""" SELECT k.po_no AS PoNo,k.po_line AS PoLine,s.id AS StandardId,a.id AS ActiveId, s.source_system AS StandardSource,s.source_biz_key AS StandardKey,s.item_code AS ItemCode, s.supplier_code AS SupplierCode,s.order_qty AS OrderQty,s.due_date AS DueDate, s.order_date AS OrderDate,s.status AS Status, t.id AS StageId,t.raw_data AS StageRaw,t.source_system AS StageSource,t.source_biz_key AS StageKey, v.source_id AS VersionSourceId,v.dataset_id AS VersionDatasetId,v.source_system AS VersionSource, v.standard_id AS VersionStandardId,v.source_generation AS Generation,v.source_version AS Version, v.is_deleted AS Deleted,current_receipt.batch_id AS VersionBatch FROM JSON_TABLE(@keys, '$[*]' COLUMNS ( po_no VARCHAR(100) PATH '$.poNo',po_line VARCHAR(50) PATH '$.poLine',stage_id BIGINT PATH '$.stageId' )) k LEFT JOIN mdp_std_purchase_order_version v ON v.tenant_id=@TenantId AND v.factory_id=@FactoryId AND v.po_no=k.po_no AND v.po_line=k.po_line LEFT JOIN mdp_std_purchase_order s ON s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.po_no=k.po_no AND s.po_line=k.po_line LEFT JOIN mdp_std_purchase_order_active a ON a.id=s.id LEFT JOIN mdp_stg_purchase_order t ON t.id=COALESCE(v.stage_id,k.stage_id) AND t.tenant_id=@TenantId AND t.factory_id=@FactoryId AND t.source_table='S3_PURCHASE_ORDER' LEFT JOIN mdp_ingest_handoff_receipt current_receipt ON current_receipt.batch_id=v.batch_id AND current_receipt.tenant_id=@TenantId AND current_receipt.factory_id=@FactoryId AND current_receipt.dataset_id=@DatasetId AND current_receipt.source_id=@SourceId """, new { keys, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId }); var byKey = rows.ToLookup(row => (row.PoNo, row.PoLine)); var proven = 0; foreach (var line in package.Items) { token.ThrowIfCancellationRequested(); var actual = byKey[(line.PoNo, line.PoLine)].ToArray(); var issue = actual.Length == 1 ? VerifyLine(package, line, receiptsByEvent[line.RawEventId], actual[0]) : "STANDARD_KEY_MISMATCH"; if (issue is not null) return new(proven, issue, line.BusinessKey); proven++; } return new(proven); } catch (JsonException) { return new(0, "HANDOFF_JSON_MISMATCH"); } } private static string? VerifyLine(PurchaseHandoffPackage package, PurchaseHandoffLine line, LineResult receipt, CutoverOrder row) { if (receipt.Status is not ("WRITTEN" or "REUSED" or "STALE" or "DELETED")) return "HANDOFF_LINE_STATUS"; var sameVersion = true; if (line.SourceChange is { } change) { if (row.VersionSourceId != package.SourceId || row.VersionDatasetId != package.DatasetId || row.VersionSource != package.SourceCode || row.VersionBatch is null || row.Generation is null || row.Version is null || row.VersionStandardId != row.StandardId || row.Generation < change.Generation || (row.Generation == change.Generation && row.Version < change.Version)) return "STANDARD_VERSION_MISMATCH"; sameVersion = row.Generation == change.Generation && row.Version == change.Version; if (sameVersion && (row.Deleted != change.Deleted || receipt.Status == "STALE")) return "STANDARD_VERSION_MISMATCH"; if (row.Deleted) return row.ActiveId is null ? null : "DELETED_ORDER_VISIBLE"; } else if (receipt.Status is "STALE" or "DELETED") return "HANDOFF_LINE_STATUS"; if (row.ActiveId is null || row.ActiveId != row.StandardId || row.StageId is null || row.StageSource != package.SourceCode || row.StandardSource != package.SourceCode || row.StageKey != row.StandardKey || row.StageRaw is null || (sameVersion && (row.StageId != receipt.StageId || row.StandardId != receipt.StandardId))) return "STAGE_STANDARD_SCOPE_MISMATCH"; var stage = JsonSerializer.Deserialize(row.StageRaw, WireJson); if (stage is null || stage.PoNo != line.PoNo || stage.PoLine != line.PoLine || (sameVersion && stage != new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt))) return "STAGE_LINE_MISMATCH"; return row.ItemCode == stage.ItemCode && row.SupplierCode == stage.SupplierCode && row.OrderQty == stage.OrderQty && row.DueDate == stage.DueDate && row.OrderDate == stage.OrderDate && row.Status == stage.Status ? null : "STANDARD_LINE_MISMATCH"; } private sealed class StoredCutoverReceipt { public string Digest { get; set; } = ""; public string Receipt { get; set; } = ""; public string LineResults { get; set; } = ""; } private sealed class CutoverOrder { public string PoNo { get; set; } = ""; public string PoLine { get; set; } = ""; public long? StandardId { get; set; } public long? ActiveId { get; set; } public long? StageId { get; set; } public string? StandardSource { get; set; } public string? StandardKey { get; set; } public string? StageRaw { get; set; } public string? StageSource { get; set; } public string? StageKey { get; set; } public string? ItemCode { get; set; } public string? SupplierCode { get; set; } public decimal? OrderQty { get; set; } public DateTime? DueDate { get; set; } public DateTime? OrderDate { get; set; } public string? Status { get; set; } public long? VersionSourceId { get; set; } public long? VersionDatasetId { get; set; } public string? VersionSource { get; set; } public long? VersionStandardId { get; set; } public long? Generation { get; set; } public long? Version { get; set; } public bool Deleted { get; set; } public string? VersionBatch { get; set; } } }