MdpPurchaseHandoffService.Versioned.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. using System.Security.Cryptography;
  2. using System.Text.Json;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed partial class MdpPurchaseHandoffService
  7. {
  8. private static bool ValidPurchasePackageVersion(PurchaseHandoffPackage package) =>
  9. package.PackageVersion switch
  10. {
  11. PurchaseHandoffPackage.Version => package.Items.All(line => line.SourceChange is null),
  12. PurchaseHandoffPackage.RelationalChangeVersion => package.Items.Count > 0
  13. && package.Items.All(line => line.SourceChange is { Generation: > 0, Version: > 0 })
  14. && package.Items.Select(line => line.SourceChange!.Generation).Distinct().Count() == 1,
  15. _ => false,
  16. };
  17. internal static async Task<PurchaseMigrationLineResult> WriteVersionedLineAsync(
  18. ISqlSugarClient db, PurchaseHandoffPackage package, string batchId, PurchaseHandoffLine line,
  19. PurchaseMigrationScope? migration = null)
  20. {
  21. var change = line.SourceChange!;
  22. var scope = new { package.TenantId, package.FactoryId, line.PoNo, line.PoLine };
  23. var state = await db.Ado.SqlQuerySingleAsync<PurchaseLineVersion>("""
  24. SELECT source_id AS SourceId,dataset_id AS DatasetId,source_system AS SourceSystem,
  25. source_generation AS Generation,source_version AS Version,is_deleted AS Deleted,
  26. content_sha256 AS Digest,standard_id AS StandardId,stage_id AS StageId
  27. FROM mdp_std_purchase_order_version
  28. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
  29. FOR UPDATE
  30. """, scope);
  31. var fields = new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode,
  32. line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt);
  33. var digest = VersionedDigest(fields, change.Deleted);
  34. var switchingSource = state is not null && (state.SourceId != package.SourceId || state.DatasetId != package.DatasetId
  35. || !string.Equals(state.SourceSystem, package.SourceCode, StringComparison.Ordinal));
  36. if (switchingSource && (migration is null || state!.SourceSystem != migration.LegacySourceCode))
  37. return new("CONFLICT", null, null);
  38. if (state is not null && !switchingSource)
  39. {
  40. if (change.Generation < state.Generation)
  41. return new("STALE", state.StageId, state.StandardId);
  42. if (change.Generation == state.Generation && Compare(state, change, digest) is { } outcome)
  43. return outcome;
  44. }
  45. var scopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{line.BusinessKey}");
  46. var args = new
  47. {
  48. package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, SourceSystem = package.SourceCode,
  49. ScopedKey = scopedKey, line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty,
  50. line.DueDate, line.OrderDate, line.Status, RawData = JsonSerializer.Serialize(fields),
  51. RawEventId = line.RawEventId.ToString("D"), batchId,
  52. };
  53. var current = await db.Ado.SqlQueryAsync<StandardRow>("""
  54. SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey
  55. FROM mdp_std_purchase_order
  56. WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine
  57. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
  58. FOR UPDATE
  59. """, args);
  60. if (current.Count > 1 || current.Any(row => row.FactoryId != package.FactoryId))
  61. return new("CONFLICT", null, null);
  62. var standard = current.SingleOrDefault();
  63. var standardId = standard?.Id;
  64. if ((state?.StandardId is { } pinned && standardId != pinned) || (switchingSource && standard is null))
  65. return new("CONFLICT", null, null);
  66. var stageId = state?.StageId;
  67. if (standard is not null && (standard.SourceSystem != package.SourceCode || standard.SourceBizKey != scopedKey))
  68. {
  69. if (migration is null || standard.SourceSystem != migration.LegacySourceCode)
  70. return new("CONFLICT", null, null);
  71. stageId = await MdpPurchaseMigrationWriter.TakeVersionedCustodyAsync(db, migration, line,
  72. standard.Id, standard.SourceBizKey, scopedKey, stageId, state?.SourceId, state?.DatasetId);
  73. if (stageId is null)
  74. return new("CONFLICT", null, null);
  75. }
  76. else if (switchingSource)
  77. return new("CONFLICT", null, null);
  78. if (standardId is null)
  79. {
  80. if (!change.Deleted)
  81. {
  82. var insert = await WriteLineAsync(db, package, batchId, line);
  83. if (insert.Status == "CONFLICT") return insert;
  84. standardId = insert.StandardId;
  85. stageId = insert.StageId;
  86. }
  87. }
  88. else
  89. {
  90. var stage = await db.Ado.SqlQuerySingleAsync<long?>("""
  91. SELECT id FROM mdp_stg_purchase_order
  92. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem
  93. AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE
  94. """, args);
  95. if (stageId.HasValue && stageId != stage)
  96. return new("CONFLICT", null, null);
  97. stageId = stage;
  98. if (!change.Deleted)
  99. {
  100. if (stage is null)
  101. return new("CONFLICT", null, null);
  102. await db.Ado.ExecuteCommandAsync("""
  103. UPDATE mdp_stg_purchase_order
  104. SET raw_data=@RawData,source_row_id=@RawEventId,sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP()
  105. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem
  106. AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey
  107. """, args);
  108. await db.Ado.ExecuteCommandAsync("""
  109. UPDATE mdp_std_purchase_order SET item_code=@ItemCode,supplier_code=@SupplierCode,
  110. order_qty=@OrderQty,due_date=@DueDate,order_date=@OrderDate,status=@Status,
  111. sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP()
  112. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
  113. AND source_system=@SourceSystem AND source_biz_key=@ScopedKey
  114. """, args);
  115. }
  116. }
  117. const string insertState = """
  118. INSERT INTO mdp_std_purchase_order_version
  119. (tenant_id,factory_id,po_no,po_line,source_id,dataset_id,source_system,source_generation,
  120. source_version,is_deleted,content_sha256,standard_id,stage_id,raw_event_id,batch_id,changed_at)
  121. VALUES (@TenantId,@FactoryId,@PoNo,@PoLine,@SourceId,@DatasetId,@SourceSystem,@Generation,
  122. @Version,@Deleted,@digest,@standardId,@stageId,@RawEventId,@batchId,UTC_TIMESTAMP(6))
  123. """;
  124. // A missing row must use INSERT. A concurrent first writer must retry the entire transaction.
  125. const string updateLockedState = """
  126. ON DUPLICATE KEY UPDATE source_id=VALUES(source_id),dataset_id=VALUES(dataset_id),source_system=VALUES(source_system),
  127. source_generation=VALUES(source_generation),source_version=VALUES(source_version),
  128. is_deleted=VALUES(is_deleted),content_sha256=VALUES(content_sha256),standard_id=VALUES(standard_id),
  129. stage_id=VALUES(stage_id),raw_event_id=VALUES(raw_event_id),batch_id=VALUES(batch_id),changed_at=VALUES(changed_at)
  130. """;
  131. await db.Ado.ExecuteCommandAsync(insertState + (state is null ? "" : "\n" + updateLockedState),
  132. new { args.TenantId, args.FactoryId, args.PoNo, args.PoLine, args.SourceId, args.DatasetId, args.SourceSystem,
  133. change.Generation, change.Version, change.Deleted, digest, standardId, stageId, args.RawEventId, batchId });
  134. var result = new PurchaseMigrationLineResult(change.Deleted ? "DELETED" : "WRITTEN", stageId, standardId);
  135. if (migration is not null)
  136. await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line, batchId, result);
  137. return result;
  138. }
  139. private static string VersionedDigest(StageFields fields, bool deleted)
  140. {
  141. var content = deleted ? "DELETE"u8.ToArray() : JsonSerializer.SerializeToUtf8Bytes(fields, WireJson);
  142. return Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant();
  143. }
  144. private static PurchaseMigrationLineResult? Compare(PurchaseLineVersion state, PurchaseSourceChange change, string digest) =>
  145. new RelationalVersionedRow(state.Version, state.Deleted, state.Digest).Decide(new(change.Version, change.Deleted, digest)) switch
  146. {
  147. RelationalChangeDecision.Apply => null,
  148. RelationalChangeDecision.Duplicate => new("REUSED", state.StageId, state.StandardId),
  149. RelationalChangeDecision.Stale => new("STALE", state.StageId, state.StandardId),
  150. _ => new("CONFLICT", state.StageId, state.StandardId)
  151. };
  152. private sealed class PurchaseLineVersion
  153. {
  154. public long SourceId { get; set; }
  155. public long DatasetId { get; set; }
  156. public string SourceSystem { get; set; } = "";
  157. public long Generation { get; set; }
  158. public long Version { get; set; }
  159. public bool Deleted { get; set; }
  160. public string Digest { get; set; } = "";
  161. public long? StandardId { get; set; }
  162. public long? StageId { get; set; }
  163. }
  164. }