MdpPurchaseHandoffService.Versioned.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using System.Globalization;
  2. using System.Security.Cryptography;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  6. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  7. public sealed partial class MdpPurchaseHandoffService
  8. {
  9. private static bool ValidPurchasePackageVersion(PurchaseHandoffPackage package) =>
  10. package.PackageVersion switch
  11. {
  12. PurchaseHandoffPackage.Version => package.Items.All(line => line.SourceChange is null),
  13. PurchaseHandoffPackage.RelationalChangeVersion => package.Items.Count > 0
  14. && package.Items.All(line => line.SourceChange is { Generation: > 0, Version: > 0 })
  15. && package.Items.Select(line => line.SourceChange!.Generation).Distinct().Count() == 1,
  16. PurchaseHandoffPackage.ApiChangeVersion => package.Items.Count > 0
  17. && package.Items.All(line => line.SourceChange is { Generation: 0, Version: > 0, Deleted: false } change
  18. && TrySourceTime(line.SourceUpdatedAt, out var instant) && change.Version == instant.UtcTicks),
  19. _ => false,
  20. };
  21. internal static async Task<PurchaseMigrationLineResult> WriteVersionedLineAsync(
  22. ISqlSugarClient db, PurchaseHandoffPackage package, string batchId, PurchaseHandoffLine line,
  23. PurchaseMigrationScope? migration = null)
  24. {
  25. var change = line.SourceChange!;
  26. var scope = new { package.TenantId, package.FactoryId, line.PoNo, line.PoLine };
  27. var state = await db.Ado.SqlQuerySingleAsync<PurchaseLineVersion>("""
  28. SELECT source_id AS SourceId,dataset_id AS DatasetId,source_system AS SourceSystem,
  29. source_generation AS Generation,source_version AS Version,is_deleted AS Deleted,
  30. content_sha256 AS Digest,standard_id AS StandardId,stage_id AS StageId
  31. FROM mdp_std_purchase_order_version
  32. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
  33. FOR UPDATE
  34. """, scope);
  35. var fields = new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode,
  36. line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt);
  37. var isApi = package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion;
  38. var digest = VersionedDigest(fields, change.Deleted, isApi);
  39. var switchingSource = state is not null && (state.SourceId != package.SourceId || state.DatasetId != package.DatasetId
  40. || !string.Equals(state.SourceSystem, package.SourceCode, StringComparison.Ordinal));
  41. if (switchingSource && (migration is null || state!.SourceSystem != migration.LegacySourceCode))
  42. return new("CONFLICT", null, null);
  43. if (state is not null && !switchingSource)
  44. {
  45. // API time and relational log offsets describe distinct version spaces.
  46. if (isApi != (state.Generation == 0))
  47. return new("CONFLICT", null, null);
  48. if (change.Generation < state.Generation)
  49. return new("STALE", state.StageId, state.StandardId);
  50. if (change.Generation == state.Generation && Compare(state, change, digest) is { } outcome)
  51. return outcome;
  52. }
  53. var scopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{line.BusinessKey}");
  54. var args = new
  55. {
  56. package.TenantId, package.FactoryId, package.SourceId, package.DatasetId, SourceSystem = package.SourceCode,
  57. ScopedKey = scopedKey, line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty,
  58. line.DueDate, line.OrderDate, line.Status, RawData = JsonSerializer.Serialize(fields),
  59. RawEventId = line.RawEventId.ToString("D"), batchId,
  60. };
  61. var current = await db.Ado.SqlQueryAsync<StandardRow>("""
  62. SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey
  63. FROM mdp_std_purchase_order
  64. WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine
  65. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
  66. FOR UPDATE
  67. """, args);
  68. if (current.Count > 1 || current.Any(row => row.FactoryId != package.FactoryId))
  69. return new("CONFLICT", null, null);
  70. var standard = current.SingleOrDefault();
  71. var standardId = standard?.Id;
  72. if ((state?.StandardId is { } pinned && standardId != pinned) || (switchingSource && standard is null))
  73. return new("CONFLICT", null, null);
  74. var stageId = state?.StageId;
  75. if (standard is not null && (standard.SourceSystem != package.SourceCode || standard.SourceBizKey != scopedKey))
  76. {
  77. if (migration is null || standard.SourceSystem != migration.LegacySourceCode)
  78. return new("CONFLICT", null, null);
  79. stageId = await MdpPurchaseMigrationWriter.TakeVersionedCustodyAsync(db, migration, line,
  80. standard.Id, standard.SourceBizKey, scopedKey, stageId, state?.SourceId, state?.DatasetId);
  81. if (stageId is null)
  82. return new("CONFLICT", null, null);
  83. }
  84. else if (switchingSource)
  85. return new("CONFLICT", null, null);
  86. if (standardId is null)
  87. {
  88. if (!change.Deleted)
  89. {
  90. var insert = await WriteLineAsync(db, package, batchId, line);
  91. if (insert.Status == "CONFLICT") return insert;
  92. standardId = insert.StandardId;
  93. stageId = insert.StageId;
  94. }
  95. }
  96. else
  97. {
  98. var stage = await db.Ado.SqlQuerySingleAsync<long?>("""
  99. SELECT id FROM mdp_stg_purchase_order
  100. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem
  101. AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE
  102. """, args);
  103. if (stageId.HasValue && stageId != stage)
  104. return new("CONFLICT", null, null);
  105. stageId = stage;
  106. // Adopt already delivered unversioned API orders using the frozen history for this exact scope.
  107. if (isApi && state is null && standard!.SourceSystem == package.SourceCode && stage is long priorStageId)
  108. {
  109. var prior = await ReadApiBaselineAsync(db, package, standardId.Value, priorStageId);
  110. if (prior is null)
  111. return new("CONFLICT", null, null);
  112. if (Compare(prior, change, digest) is { } outcome)
  113. return outcome;
  114. }
  115. if (!change.Deleted)
  116. {
  117. if (stage is null)
  118. return new("CONFLICT", null, null);
  119. await db.Ado.ExecuteCommandAsync("""
  120. UPDATE mdp_stg_purchase_order
  121. SET raw_data=@RawData,source_row_id=@RawEventId,sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP()
  122. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceSystem
  123. AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey
  124. """, args);
  125. await db.Ado.ExecuteCommandAsync("""
  126. UPDATE mdp_std_purchase_order SET item_code=@ItemCode,supplier_code=@SupplierCode,
  127. order_qty=@OrderQty,due_date=@DueDate,order_date=@OrderDate,status=@Status,
  128. sync_batch_id=@batchId,sync_time=UTC_TIMESTAMP()
  129. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
  130. AND source_system=@SourceSystem AND source_biz_key=@ScopedKey
  131. """, args);
  132. }
  133. }
  134. const string insertState = """
  135. INSERT INTO mdp_std_purchase_order_version
  136. (tenant_id,factory_id,po_no,po_line,source_id,dataset_id,source_system,source_generation,
  137. source_version,is_deleted,content_sha256,standard_id,stage_id,raw_event_id,batch_id,changed_at)
  138. VALUES (@TenantId,@FactoryId,@PoNo,@PoLine,@SourceId,@DatasetId,@SourceSystem,@Generation,
  139. @Version,@Deleted,@digest,@standardId,@stageId,@RawEventId,@batchId,UTC_TIMESTAMP(6))
  140. """;
  141. // A missing row must use INSERT. A concurrent first writer must retry the entire transaction.
  142. const string updateLockedState = """
  143. ON DUPLICATE KEY UPDATE source_id=VALUES(source_id),dataset_id=VALUES(dataset_id),source_system=VALUES(source_system),
  144. source_generation=VALUES(source_generation),source_version=VALUES(source_version),
  145. is_deleted=VALUES(is_deleted),content_sha256=VALUES(content_sha256),standard_id=VALUES(standard_id),
  146. stage_id=VALUES(stage_id),raw_event_id=VALUES(raw_event_id),batch_id=VALUES(batch_id),changed_at=VALUES(changed_at)
  147. """;
  148. await db.Ado.ExecuteCommandAsync(insertState + (state is null ? "" : "\n" + updateLockedState),
  149. new { args.TenantId, args.FactoryId, args.PoNo, args.PoLine, args.SourceId, args.DatasetId, args.SourceSystem,
  150. change.Generation, change.Version, change.Deleted, digest, standardId, stageId, args.RawEventId, batchId });
  151. var result = new PurchaseMigrationLineResult(change.Deleted ? "DELETED" : "WRITTEN", stageId, standardId);
  152. if (migration is not null)
  153. await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line, batchId, result);
  154. return result;
  155. }
  156. private static bool TrySourceTime(string? text, out DateTimeOffset instant)
  157. {
  158. instant = default;
  159. return text is { Length: >= 6 } && (text.EndsWith('Z') || text[^6] is '+' or '-')
  160. && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out instant);
  161. }
  162. private static string VersionedDigest(StageFields fields, bool deleted, bool isApi)
  163. {
  164. if (isApi && TrySourceTime(fields.SourceUpdatedAt, out var time))
  165. {
  166. fields = fields with
  167. {
  168. SourceUpdatedAt = time.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
  169. OrderQty = decimal.Parse(fields.OrderQty.ToString("G29", CultureInfo.InvariantCulture),
  170. NumberStyles.Float, CultureInfo.InvariantCulture)
  171. };
  172. }
  173. var content = deleted ? "DELETE"u8.ToArray() : JsonSerializer.SerializeToUtf8Bytes(fields, WireJson);
  174. return Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant();
  175. }
  176. private static PurchaseMigrationLineResult? Compare(PurchaseLineVersion state, PurchaseSourceChange change, string digest) =>
  177. new RelationalVersionedRow(state.Version, state.Deleted, state.Digest).Decide(new(change.Version, change.Deleted, digest)) switch
  178. {
  179. RelationalChangeDecision.Apply => null,
  180. RelationalChangeDecision.Duplicate => new("REUSED", state.StageId, state.StandardId),
  181. RelationalChangeDecision.Stale => new("STALE", state.StageId, state.StandardId),
  182. _ => new("CONFLICT", state.StageId, state.StandardId)
  183. };
  184. private static async Task<PurchaseLineVersion?> ReadApiBaselineAsync(
  185. ISqlSugarClient db, PurchaseHandoffPackage package, long standardId, long stageId)
  186. {
  187. var raw = await db.Ado.SqlQuerySingleAsync<string>("""
  188. SELECT s.raw_data FROM mdp_stg_purchase_order s
  189. JOIN mdp_std_purchase_order p ON p.id=@standardId AND p.sync_batch_id=s.sync_batch_id
  190. AND p.tenant_id=s.tenant_id AND p.factory_id=s.factory_id AND p.source_system=s.source_system
  191. AND p.source_biz_key=s.source_biz_key
  192. JOIN mdp_ingest_handoff_receipt r ON r.batch_id=s.sync_batch_id AND r.tenant_id=s.tenant_id
  193. AND r.factory_id=s.factory_id AND r.source_id=@SourceId AND r.dataset_id=@DatasetId
  194. AND r.package_version=@Unversioned
  195. WHERE s.id=@stageId AND s.tenant_id=@TenantId AND s.factory_id=@FactoryId
  196. AND s.source_system=@SourceCode AND s.source_table='S3_PURCHASE_ORDER'
  197. """, new { standardId, stageId, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId,
  198. package.SourceCode, Unversioned = PurchaseHandoffPackage.Version });
  199. if (raw is null)
  200. return null;
  201. try
  202. {
  203. var fields = JsonSerializer.Deserialize<StageFields>(raw, WireJson);
  204. return fields is not null && TrySourceTime(fields.SourceUpdatedAt, out var original) && original.UtcTicks > 0
  205. ? new PurchaseLineVersion
  206. {
  207. StandardId = standardId, StageId = stageId, Version = original.UtcTicks,
  208. Digest = VersionedDigest(fields, false, true)
  209. }
  210. : null;
  211. }
  212. catch (JsonException)
  213. {
  214. return null;
  215. }
  216. }
  217. private sealed class PurchaseLineVersion
  218. {
  219. public long SourceId { get; set; }
  220. public long DatasetId { get; set; }
  221. public string SourceSystem { get; set; } = "";
  222. public long Generation { get; set; }
  223. public long Version { get; set; }
  224. public bool Deleted { get; set; }
  225. public string Digest { get; set; } = "";
  226. public long? StandardId { get; set; }
  227. public long? StageId { get; set; }
  228. }
  229. }