using System.Security.Cryptography; 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 { private static bool ValidPurchasePackageVersion(PurchaseHandoffPackage package) => package.PackageVersion switch { PurchaseHandoffPackage.Version => package.Items.All(line => line.SourceChange is null), PurchaseHandoffPackage.RelationalChangeVersion => package.Items.Count > 0 && package.Items.All(line => line.SourceChange is { Generation: > 0, Version: > 0 }) && package.Items.Select(line => line.SourceChange!.Generation).Distinct().Count() == 1, _ => false, }; internal static async Task WriteVersionedLineAsync( ISqlSugarClient db, PurchaseHandoffPackage package, string batchId, PurchaseHandoffLine line, PurchaseMigrationScope? migration = null) { var change = line.SourceChange!; var scope = new { package.TenantId, package.FactoryId, line.PoNo, line.PoLine }; var state = 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); var fields = new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt); var digest = VersionedDigest(fields, change.Deleted); var switchingSource = state is not null && (state.SourceId != package.SourceId || state.DatasetId != package.DatasetId || !string.Equals(state.SourceSystem, package.SourceCode, StringComparison.Ordinal)); if (switchingSource && (migration is null || state!.SourceSystem != migration.LegacySourceCode)) return new("CONFLICT", null, null); if (state is not null && !switchingSource) { if (change.Generation < state.Generation) return new("STALE", state.StageId, state.StandardId); if (change.Generation == state.Generation && Compare(state, change, digest) is { } outcome) return outcome; } var scopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{line.BusinessKey}"); var args = new { package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, SourceSystem = package.SourceCode, ScopedKey = scopedKey, line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty, line.DueDate, line.OrderDate, line.Status, RawData = JsonSerializer.Serialize(fields), RawEventId = line.RawEventId.ToString("D"), batchId, }; var current = await db.Ado.SqlQueryAsync(""" SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey FROM mdp_std_purchase_order WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0) FOR UPDATE """, args); if (current.Count > 1 || current.Any(row => row.FactoryId != package.FactoryId)) return new("CONFLICT", null, null); var standard = current.SingleOrDefault(); var standardId = standard?.Id; if ((state?.StandardId is { } pinned && standardId != pinned) || (switchingSource && standard is null)) return new("CONFLICT", null, null); var stageId = state?.StageId; if (standard is not null && (standard.SourceSystem != package.SourceCode || standard.SourceBizKey != scopedKey)) { if (migration is null || standard.SourceSystem != migration.LegacySourceCode) return new("CONFLICT", null, null); stageId = await MdpPurchaseMigrationWriter.TakeVersionedCustodyAsync(db, migration, line, standard.Id, standard.SourceBizKey, scopedKey, stageId, state?.SourceId, state?.DatasetId); if (stageId is null) return new("CONFLICT", null, null); } else if (switchingSource) return new("CONFLICT", null, null); if (standardId is null) { if (!change.Deleted) { var insert = await WriteLineAsync(db, package, batchId, line); if (insert.Status == "CONFLICT") return insert; standardId = insert.StandardId; stageId = insert.StageId; } } else { var stage = await db.Ado.SqlQuerySingleAsync(""" SELECT id FROM mdp_stg_purchase_order WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE """, args); if (stageId.HasValue && stageId != stage) return new("CONFLICT", null, null); stageId = stage; if (!change.Deleted) { if (stage is null) return new("CONFLICT", null, null); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_stg_purchase_order SET raw_data=@RawData,source_row_id=@RawEventId,sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP() WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey """, args); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_std_purchase_order SET item_code=@ItemCode,supplier_code=@SupplierCode, order_qty=@OrderQty,due_date=@DueDate,order_date=@OrderDate,status=@Status, sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP() WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine AND source_system=@SourceSystem AND source_biz_key=@ScopedKey """, args); } } const string insertState = """ INSERT INTO mdp_std_purchase_order_version (tenant_id,factory_id,po_no,po_line,source_id,dataset_id,source_system,source_generation, source_version,is_deleted,content_sha256,standard_id,stage_id,raw_event_id,batch_id,changed_at) VALUES (@TenantId,@FactoryId,@PoNo,@PoLine,@SourceId,@DatasetId,@SourceSystem,@Generation, @Version,@Deleted,@digest,@standardId,@stageId,@RawEventId,@batchId,UTC_TIMESTAMP(6)) """; // A missing row must use INSERT. A concurrent first writer must retry the entire transaction. const string updateLockedState = """ ON DUPLICATE KEY UPDATE source_id=VALUES(source_id),dataset_id=VALUES(dataset_id),source_system=VALUES(source_system), source_generation=VALUES(source_generation),source_version=VALUES(source_version), is_deleted=VALUES(is_deleted),content_sha256=VALUES(content_sha256),standard_id=VALUES(standard_id), stage_id=VALUES(stage_id),raw_event_id=VALUES(raw_event_id),batch_id=VALUES(batch_id),changed_at=VALUES(changed_at) """; await db.Ado.ExecuteCommandAsync(insertState + (state is null ? "" : "\n" + updateLockedState), new { args.TenantId, args.FactoryId, args.PoNo, args.PoLine, args.SourceId, args.DatasetId, args.SourceSystem, change.Generation, change.Version, change.Deleted, digest, standardId, stageId, args.RawEventId, batchId }); var result = new PurchaseMigrationLineResult(change.Deleted ? "DELETED" : "WRITTEN", stageId, standardId); if (migration is not null) await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line, batchId, result); return result; } private static string VersionedDigest(StageFields fields, bool deleted) { var content = deleted ? "DELETE"u8.ToArray() : JsonSerializer.SerializeToUtf8Bytes(fields, WireJson); return Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant(); } private static PurchaseMigrationLineResult? Compare(PurchaseLineVersion state, PurchaseSourceChange change, string digest) => new RelationalVersionedRow(state.Version, state.Deleted, state.Digest).Decide(new(change.Version, change.Deleted, digest)) switch { RelationalChangeDecision.Apply => null, RelationalChangeDecision.Duplicate => new("REUSED", state.StageId, state.StandardId), RelationalChangeDecision.Stale => new("STALE", state.StageId, state.StandardId), _ => new("CONFLICT", state.StageId, state.StandardId) }; private sealed class PurchaseLineVersion { public long SourceId { get; set; } public long DatasetId { get; set; } public string SourceSystem { get; set; } = ""; public long Generation { get; set; } public long Version { get; set; } public bool Deleted { get; set; } public string Digest { get; set; } = ""; public long? StandardId { get; set; } public long? StageId { get; set; } } }