using System.Globalization; using System.Security.Cryptography; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed partial class MdpPurchaseHandoffService { private const string RecoveryReceiptSql = """ SELECT payload_sha256 AS PayloadSha256,digest_format AS DigestFormat,line_results AS LineResults, package_version AS PackageVersion,created_at AS CreatedAt FROM mdp_ingest_handoff_receipt WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId """; internal async Task ReadTraceAsync(StoredIngestBatch batch, CancellationToken token) { if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"])) return null; using var db = OpenBusinessDatabase(); db.Ado.CancellationToken = token; var receipt = await db.Ado.SqlQuerySingleAsync(RecoveryReceiptSql, batch.SqlArguments); if (receipt is null) return null; var history = await db.Ado.SqlQueryAsync(""" SELECT CAST(actor_id AS CHAR) AS Actor,reason AS Reason,line_results AS LineResults,created_at AS CreatedAt FROM mdp_ingest_purchase_recovery WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId ORDER BY id DESC LIMIT 100 """, batch.SqlArguments); return new(receipt.PackageVersion, receipt.PayloadSha256, Utc(receipt.CreatedAt), ReceiptLines(receipt).Select(ToTrace).ToList(), history.Select(row => new PurchaseRecoveryTrace(row.Actor, row.Reason, Utc(row.CreatedAt), (JsonSerializer.Deserialize>(row.LineResults, WireJson) ?? []).Select(ToTrace).ToList())).ToList()); } internal async Task PreviewRestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package, CancellationToken token) { if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"])) return null; using var db = OpenBusinessDatabase(); db.Ado.CancellationToken = token; var tx = await db.Ado.UseTranAsync(async () => { var receipt = await db.Ado.SqlQuerySingleAsync(RecoveryReceiptSql + " FOR SHARE", batch.SqlArguments); if (receipt is null) return null; VerifyRecoveryReceipt(package, receipt); var lines = await InspectRecoveryAsync(db, package, receipt, token); return Preview(package, lines, await RecoveryRevisionAsync(db, batch)); }); if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable(); return tx.Data; } internal async Task RestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package, string previewDigest, string reason, long actor, CancellationToken token) { using var db = OpenBusinessDatabase(); db.Ado.CancellationToken = token; var tx = await db.Ado.UseTranAsync(async () => { var receipt = await db.Ado.SqlQuerySingleAsync(RecoveryReceiptSql + " FOR UPDATE", batch.SqlArguments) ?? throw Error(409, "RAW_REPLAY_RECEIPT_MISSING"); VerifyRecoveryReceipt(package, receipt); var prior = await db.Ado.SqlQuerySingleAsync(""" SELECT line_results FROM mdp_ingest_purchase_recovery WHERE batch_id=@BatchId AND preview_digest=@PreviewDigest AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, previewDigest }); if (prior is not null) return Result(prior); // Lock the original source authority before taking business row locks (same order as ordinary handoff). var migration = await ValidateWriterAsync(db, package); MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified); var lines = await InspectRecoveryAsync(db, package, receipt, token); var preview = Preview(package, lines, await RecoveryRevisionAsync(db, batch)); if (preview.Digest != previewDigest || !preview.CanRestore) throw Error(409, "RAW_REPLAY_PREVIEW_CHANGED"); var restored = new List(); foreach (var line in lines.Where(row => row.NeedsRestore)) { token.ThrowIfCancellationRequested(); var outcome = await WriteLineAsync(db, package, batch.BatchId, line.Item); if (outcome.Status != "WRITTEN" || outcome.StageId is null || outcome.StandardId is null) throw Error(409, "RAW_REPLAY_TARGET_CONFLICT"); if (line.Item.SourceChange is { } change) { var updated = await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_std_purchase_order_version SET stage_id=@StageId,standard_id=@StandardId WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine AND source_id=@SourceId AND dataset_id=@DatasetId AND source_generation=@Generation AND source_version=@Version AND is_deleted=0 """, new { outcome.StageId, outcome.StandardId, package.TenantId, package.FactoryId, line.Item.PoNo, line.Item.PoLine, package.SourceId, package.DatasetId, change.Generation, change.Version }); if (updated != 1) throw Error(409, "RAW_REPLAY_VERSION_CHANGED"); } if (migration is not null) { var traceKey = "restore-" + Convert.ToHexString(SHA256.HashData( System.Text.Encoding.UTF8.GetBytes(previewDigest + line.Item.RawEventId.ToString("D")))).ToLowerInvariant(); await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line.Item, batch.BatchId, outcome, traceKey); } restored.Add(new(line.Item.RawEventId, "RESTORED", outcome.StageId, outcome.StandardId)); } var json = JsonSerializer.Serialize(restored, WireJson); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_purchase_recovery (batch_id,tenant_id,factory_id,dataset_id,source_id,actor_id,preview_digest,reason,line_results,created_at) VALUES (@BatchId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Actor,@PreviewDigest,@Reason,@Json,UTC_TIMESTAMP(6)) """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, actor, previewDigest, reason, json }); token.ThrowIfCancellationRequested(); return Result(json); }); if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable(); return tx.Data; } private void VerifyRecoveryReceipt(PurchaseHandoffPackage package, RecoveryReceipt receipt) { if (receipt.PackageVersion != package.PackageVersion || (receipt.PayloadSha256 != package.ComputeDigest() && !(receipt.DigestFormat == 1 && MatchesLegacyReceipt(package, receipt.PayloadSha256)))) throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH"); } private static async Task> InspectRecoveryAsync(ISqlSugarClient db, PurchaseHandoffPackage package, RecoveryReceipt receipt, CancellationToken token) { var originals = ReceiptLines(receipt).ToDictionary(row => row.RawEventId); if (!package.Items.All(item => originals.ContainsKey(item.RawEventId)) || originals.Count != package.Items.Count) throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH"); var result = new List(package.Items.Count); foreach (var item in package.Items.OrderBy(row => row.PoNo, StringComparer.Ordinal) .ThenBy(row => row.PoLine, StringComparer.Ordinal).ThenBy(row => row.SourceChange?.Version)) { token.ThrowIfCancellationRequested(); var original = originals[item.RawEventId]; if (original.Status is not ("WRITTEN" or "REUSED") || item.SourceChange is { Deleted: true }) { result.Add(new(item, "EXCLUDED", null, null)); continue; } var scope = new { package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, package.SourceCode, item.PoNo, item.PoLine, ScopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{item.BusinessKey}") }; var fields = new StageFields(item.PoNo, item.PoLine, item.ItemCode, item.SupplierCode, item.OrderQty, item.DueDate, item.OrderDate, item.Status, item.SourceUpdatedAt); var version = await db.Ado.SqlQuerySingleAsync(""" SELECT source_id AS SourceId,dataset_id AS DatasetId,source_system AS SourceSystem, source_generation AS Generation,source_version AS Version,is_deleted AS Deleted, content_sha256 AS Digest,standard_id AS StandardId,stage_id AS StageId FROM mdp_std_purchase_order_version WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE """, scope); if (item.SourceChange is { } change) { var expected = VersionedDigest(fields, false, package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion); if (version is null || version.SourceId != package.SourceId || version.DatasetId != package.DatasetId || version.SourceSystem != package.SourceCode || version.Deleted || version.Generation != change.Generation || version.Version != change.Version || version.Digest != expected) { result.Add(new(item, "VERSION_CHANGED", null, null)); continue; } } else if (version is not null) { result.Add(new(item, "VERSION_CHANGED", null, null)); continue; } var standard = await db.Ado.SqlQueryAsync(""" SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey, po_no AS PoNo,po_line AS PoLine,item_code AS ItemCode,supplier_code AS SupplierCode, order_qty AS OrderQty,due_date AS DueDate,order_date AS OrderDate,status AS Status FROM mdp_std_purchase_order WHERE tenant_id=@TenantId AND (((factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0) AND po_no=@PoNo AND po_line=@PoLine) OR (source_system=@SourceCode AND source_biz_key=@ScopedKey)) FOR UPDATE """, scope); var stage = await db.Ado.SqlQuerySingleAsync(""" SELECT id AS Id,tenant_id AS TenantId,factory_id AS FactoryId,source_system AS SourceSystem, source_biz_key AS SourceBizKey,raw_data AS RawData FROM mdp_stg_purchase_order WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceCode AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE """, scope); var currentStandard = standard.FirstOrDefault(); var conflict = standard.Count > 1 || currentStandard is not null && !currentStandard.Matches(package, item, scope.ScopedKey) || stage is not null && !stage.Matches(package, scope.ScopedKey, fields) || version?.StandardId is long expectedStandard && currentStandard is not null && expectedStandard != currentStandard.Id || version?.StageId is long expectedStage && stage is not null && expectedStage != stage.Id; var status = conflict ? "CONFLICT" : stage is null && currentStandard is null ? "MISSING_BOTH" : stage is null ? "MISSING_STAGE" : currentStandard is null ? "MISSING_STANDARD" : "COMPLETE"; result.Add(new(item, status, stage?.Id, currentStandard?.Id)); } return result; } private static Task RecoveryRevisionAsync(ISqlSugarClient db, StoredIngestBatch batch) => db.Ado.GetLongAsync(""" SELECT COALESCE(MAX(id),0) FROM mdp_ingest_purchase_recovery WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId """, batch.SqlArguments); private static PurchaseRecoveryPreview Preview(PurchaseHandoffPackage package, List rows, long revision) { var lines = rows.Select(row => ToTrace(new(row.Item.RawEventId, row.Status, row.StageId, row.StandardId))).ToList(); var digest = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { Package = package.ComputeDigest(), Revision = revision, Lines = lines }, WireJson))).ToLowerInvariant(); return new(digest, rows.Any(row => row.NeedsRestore) && rows.All(row => row.Status is not ("CONFLICT" or "VERSION_CHANGED")), lines); } private static List ReceiptLines(RecoveryReceipt row) => JsonSerializer.Deserialize>(row.LineResults, WireJson) ?? throw Unavailable(); private static PurchaseRecoveryResult Result(string json) => new( (JsonSerializer.Deserialize>(json, WireJson) ?? throw Unavailable()).Select(ToTrace).ToList()); private static PurchaseLineTrace ToTrace(LineResult row) => new(row.RawEventId, row.Status, row.StageId?.ToString(CultureInfo.InvariantCulture), row.StandardId?.ToString(CultureInfo.InvariantCulture)); private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); private sealed record RecoveryLine(PurchaseHandoffLine Item, string Status, long? StageId, long? StandardId) { public bool NeedsRestore => Status is "MISSING_BOTH" or "MISSING_STAGE" or "MISSING_STANDARD"; } private sealed class RecoveryReceipt { public string PayloadSha256 { get; set; } = ""; public int DigestFormat { get; set; } public string LineResults { get; set; } = ""; public string PackageVersion { get; set; } = ""; public DateTime CreatedAt { get; set; } } private sealed class RecoveryAudit { public string Actor { get; set; } = ""; public string Reason { get; set; } = ""; public string LineResults { get; set; } = ""; public DateTime CreatedAt { get; set; } } } internal sealed record PurchaseLineTrace(Guid RawEventId, string Status, string? StageId, string? StandardId); internal sealed record PurchaseTrace(string PackageVersion, string Digest, DateTime CreatedAt, List Lines, List Recoveries); internal sealed record PurchaseRecoveryTrace(string Actor, string Reason, DateTime CreatedAt, List Lines); internal sealed record PurchaseRecoveryPreview(string Digest, bool CanRestore, List Lines); internal sealed record PurchaseRecoveryResult(List Restored);