using System.Globalization; 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, PurchaseHandoffPackage.ApiChangeVersion => package.Items.Count > 0 && package.Items.All(line => line.SourceChange is { Generation: 0, Version: > 0, Deleted: false } change && TrySourceTime(line.SourceUpdatedAt, out var instant) && change.Version == instant.UtcTicks), _ => 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 isApi = package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion; var digest = VersionedDigest(fields, change.Deleted, isApi); 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) { // API time and relational log offsets describe distinct version spaces. if (isApi != (state.Generation == 0)) return new("CONFLICT", null, null); 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; // Adopt already delivered unversioned API orders using the frozen history for this exact scope. if (isApi && state is null && standard!.SourceSystem == package.SourceCode && stage is long priorStageId) { var prior = await ReadApiBaselineAsync(db, package, standardId.Value, priorStageId); if (prior is null) return new("CONFLICT", null, null); if (Compare(prior, change, digest) is { } outcome) return outcome; } 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 bool TrySourceTime(string? text, out DateTimeOffset instant) { instant = default; return text is { Length: >= 6 } && (text.EndsWith('Z') || text[^6] is '+' or '-') && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out instant); } private static string VersionedDigest(StageFields fields, bool deleted, bool isApi) { if (isApi && TrySourceTime(fields.SourceUpdatedAt, out var time)) { fields = fields with { SourceUpdatedAt = time.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture), OrderQty = decimal.Parse(fields.OrderQty.ToString("G29", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture) }; } 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 static async Task ReadApiBaselineAsync( ISqlSugarClient db, PurchaseHandoffPackage package, long standardId, long stageId) { var raw = await db.Ado.SqlQuerySingleAsync(""" SELECT s.raw_data FROM mdp_stg_purchase_order s JOIN mdp_std_purchase_order p ON p.id=@standardId AND p.sync_batch_id=s.sync_batch_id AND p.tenant_id=s.tenant_id AND p.factory_id=s.factory_id AND p.source_system=s.source_system AND p.source_biz_key=s.source_biz_key JOIN mdp_ingest_handoff_receipt r ON r.batch_id=s.sync_batch_id AND r.tenant_id=s.tenant_id AND r.factory_id=s.factory_id AND r.source_id=@SourceId AND r.dataset_id=@DatasetId AND r.package_version=@Unversioned WHERE s.id=@stageId AND s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_system=@SourceCode AND s.source_table='S3_PURCHASE_ORDER' """, new { standardId, stageId, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, package.SourceCode, Unversioned = PurchaseHandoffPackage.Version }); if (raw is null) return null; try { var fields = JsonSerializer.Deserialize(raw, WireJson); return fields is not null && TrySourceTime(fields.SourceUpdatedAt, out var original) && original.UtcTicks > 0 ? new PurchaseLineVersion { StandardId = standardId, StageId = stageId, Version = original.UtcTicks, Digest = VersionedDigest(fields, false, true) } : null; } catch (JsonException) { return null; } } 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; } } }