MdpPurchaseMigrationWriter.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System.Globalization;
  2. using System.Security.Cryptography;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. internal sealed record PurchaseMigrationLineResult(string Status, long? StageId, long? StandardId);
  7. /// <summary>在调用方持有范围行锁的事务中,用同一份业务对照处理两个入口。</summary>
  8. internal static class MdpPurchaseMigrationWriter
  9. {
  10. private static readonly string[] LocalDateFormats =
  11. ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", "yyyy-MM-dd HH:mm:ss.FFFFFFF"];
  12. private static readonly string[] OffsetDateFormats =
  13. ["yyyy-MM-dd'T'HH:mm:sszzz", "yyyy-MM-dd HH:mm:sszzz", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFzzz", "yyyy-MM-dd HH:mm:ss.FFFFFFFzzz"];
  14. internal static async Task<PurchaseMigrationLineResult> WriteAsync(
  15. ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId)
  16. {
  17. MdpPurchaseMigrationStore.RequireWriter(scope, writer);
  18. var identity = new { ScopeId = scope.Id, line.PoNo, line.PoLine };
  19. var content = OrderContent.From(line);
  20. var digest = Hash(content);
  21. var deleted = await db.Ado.GetIntAsync("""
  22. SELECT COUNT(*) FROM mdp_std_purchase_order_version
  23. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine AND is_deleted=1
  24. """, new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine }) > 0;
  25. var existing = await db.Ado.SqlQuerySingleAsync<LedgerRow>(
  26. """
  27. SELECT content_sha256 AS Digest, stage_id AS StageId, standard_id AS StandardId
  28. FROM mdp_purchase_migration_line WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
  29. """, identity);
  30. var result = deleted || (existing is not null && existing.Digest != digest)
  31. ? new PurchaseMigrationLineResult("CONFLICT", null, null)
  32. : await ResolveAsync(db, scope, writer, line, batchId, traceId, content, existing);
  33. if (result.StageId is long stageId && result.StandardId is long standardId)
  34. {
  35. if (existing is null)
  36. await db.Ado.ExecuteCommandAsync(
  37. """
  38. INSERT INTO mdp_purchase_migration_line
  39. (scope_id, po_no, po_line, content_sha256, stage_id, standard_id, created_at)
  40. VALUES (@ScopeId, @PoNo, @PoLine, @Digest, @StageId, @StandardId, UTC_TIMESTAMP(6))
  41. """, new { identity.ScopeId, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
  42. else if (existing.StandardId != standardId)
  43. await db.Ado.ExecuteCommandAsync(
  44. """
  45. UPDATE mdp_purchase_migration_line SET standard_id=@StandardId
  46. WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine AND stage_id=@StageId
  47. """, new { identity.ScopeId, line.PoNo, line.PoLine, StageId = stageId, StandardId = standardId });
  48. }
  49. await ObserveAsync(db, scope, writer, line, batchId, traceId, digest, result);
  50. return result;
  51. }
  52. internal static async Task<long?> TakeVersionedCustodyAsync(ISqlSugarClient db, PurchaseMigrationScope scope,
  53. PurchaseHandoffLine line, long standardId, string previousKey, string nextKey, long? pinnedStageId,
  54. long? previousSourceId, long? previousDatasetId)
  55. {
  56. var args = new { scope.Id, scope.TenantId, scope.FactoryId, scope.LegacySourceCode, scope.NewSourceCode,
  57. line.PoNo, line.PoLine, StandardId = standardId, PreviousKey = previousKey, NextKey = nextKey };
  58. var previous = await db.Ado.SqlQuerySingleAsync<StoredStage>("""
  59. SELECT s.id AS Id,s.source_system AS SourceCode,s.sync_batch_id AS BatchId
  60. FROM mdp_stg_purchase_order s JOIN mdp_std_purchase_order p
  61. ON p.tenant_id=s.tenant_id AND p.factory_id=s.factory_id AND p.source_system=s.source_system
  62. AND p.source_biz_key=s.source_biz_key AND p.id=@StandardId
  63. WHERE s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_system=@LegacySourceCode
  64. AND s.source_table='S3_PURCHASE_ORDER' AND s.source_biz_key=@PreviousKey
  65. FOR UPDATE
  66. """, args);
  67. if (previous is null || (pinnedStageId.HasValue && previous.Id != pinnedStageId.Value))
  68. return null;
  69. var inherited = await db.Ado.GetIntAsync("""
  70. SELECT COUNT(*) FROM mdp_purchase_migration_line WHERE scope_id=@Id
  71. AND po_no=@PoNo AND po_line=@PoLine AND stage_id=@StageId AND standard_id=@StandardId
  72. """, new { scope.Id, line.PoNo, line.PoLine, StageId = previous.Id, StandardId = standardId }) == 1;
  73. if (!inherited && previousSourceId.HasValue && previousDatasetId.HasValue)
  74. {
  75. inherited = await db.Ado.GetIntAsync("""
  76. SELECT COUNT(*) FROM mdp_std_purchase_order_version v JOIN mdp_ingest_handoff_receipt r
  77. ON r.batch_id=v.batch_id AND r.tenant_id=v.tenant_id AND r.factory_id=v.factory_id
  78. AND r.dataset_id=v.dataset_id AND r.source_id=v.source_id
  79. WHERE v.tenant_id=@TenantId AND v.factory_id=@FactoryId AND v.po_no=@PoNo AND v.po_line=@PoLine
  80. AND v.stage_id=@StageId AND v.standard_id=@StandardId AND v.source_system=@LegacySourceCode
  81. AND v.source_id=@SourceId AND v.dataset_id=@DatasetId
  82. """, new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine, StageId = previous.Id,
  83. StandardId = standardId, scope.LegacySourceCode, SourceId = previousSourceId, DatasetId = previousDatasetId }) == 1;
  84. }
  85. if (!inherited && !await HasCustodyEvidenceAsync(db, scope, previous, legacy: true, MdpPurchaseMigrationStore.Unified))
  86. return null;
  87. var occupied = await db.Ado.GetIntAsync("""
  88. SELECT COUNT(*) FROM mdp_stg_purchase_order WHERE tenant_id=@TenantId AND factory_id=@FactoryId
  89. AND source_system=@NewSourceCode AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@NextKey
  90. """, args);
  91. if (occupied != 0)
  92. return null;
  93. await db.Ado.ExecuteCommandAsync("""
  94. UPDATE mdp_stg_purchase_order SET source_system=@NewSourceCode,source_biz_key=@NextKey
  95. WHERE id=@StageId AND tenant_id=@TenantId AND factory_id=@FactoryId
  96. """, new { scope.NewSourceCode, NextKey = nextKey, StageId = previous.Id, scope.TenantId, scope.FactoryId });
  97. await db.Ado.ExecuteCommandAsync("""
  98. UPDATE mdp_std_purchase_order SET source_system=@NewSourceCode,source_biz_key=@NextKey
  99. WHERE id=@StandardId AND tenant_id=@TenantId AND factory_id=@FactoryId
  100. """, args);
  101. return previous.Id;
  102. }
  103. internal static async Task RecordVersionedAsync(ISqlSugarClient db, PurchaseMigrationScope scope, PurchaseHandoffLine line,
  104. string batchId, PurchaseMigrationLineResult result)
  105. {
  106. var digest = Hash(OrderContent.From(line));
  107. if (result.Status == "WRITTEN" && result.StageId is long stageId && result.StandardId is long standardId)
  108. {
  109. await db.Ado.ExecuteCommandAsync("""
  110. INSERT INTO mdp_purchase_migration_line (scope_id,po_no,po_line,content_sha256,stage_id,standard_id,created_at)
  111. VALUES (@ScopeId,@PoNo,@PoLine,@Digest,@StageId,@StandardId,UTC_TIMESTAMP(6))
  112. ON DUPLICATE KEY UPDATE content_sha256=VALUES(content_sha256),stage_id=VALUES(stage_id),standard_id=VALUES(standard_id)
  113. """, new { ScopeId = scope.Id, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
  114. }
  115. await ObserveAsync(db, scope, MdpPurchaseMigrationStore.Unified, line, batchId, line.RawEventId.ToString("D"),
  116. digest, result);
  117. }
  118. private static string Hash(OrderContent content) =>
  119. Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(content))).ToLowerInvariant();
  120. private static Task<int> ObserveAsync(ISqlSugarClient db, PurchaseMigrationScope scope, string writer,
  121. PurchaseHandoffLine line, string batchId, string traceId, string digest, PurchaseMigrationLineResult result) =>
  122. db.Ado.ExecuteCommandAsync(
  123. """
  124. INSERT INTO mdp_purchase_migration_observation
  125. (scope_id, writer, trace_id, batch_id, po_no, po_line, content_sha256, resolution, stage_id, standard_id, created_at)
  126. VALUES (@ScopeId,@Writer,@TraceId,@BatchId,@PoNo,@PoLine,@Digest,@Status,@StageId,@StandardId,UTC_TIMESTAMP(6))
  127. """, new { ScopeId = scope.Id, Writer = writer, TraceId = traceId, BatchId = batchId, line.PoNo, line.PoLine,
  128. Digest = digest, result.Status, result.StageId, result.StandardId });
  129. private static async Task<PurchaseMigrationLineResult> ResolveAsync(
  130. ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId,
  131. OrderContent content, LedgerRow? existing)
  132. {
  133. var scopedKey = FormattableString.Invariant($"{scope.TenantId}#{scope.FactoryId}#{line.BusinessKey}");
  134. var stageCandidates = await db.Ado.SqlQueryAsync<StoredStage>(
  135. """
  136. SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
  137. sync_batch_id AS BatchId, raw_data AS RawData
  138. FROM mdp_stg_purchase_order
  139. WHERE tenant_id=@TenantId AND source_table='S3_PURCHASE_ORDER'
  140. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
  141. AND source_biz_key IN (@LegacyKey,@ScopedKey)
  142. FOR SHARE
  143. """, new { scope.TenantId, scope.FactoryId, LegacyKey = line.BusinessKey, ScopedKey = scopedKey });
  144. var standards = await db.Ado.SqlQueryAsync<StoredStandard>(
  145. """
  146. SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
  147. sync_batch_id AS BatchId, po_no AS PoNo, po_line AS PoLine, item_code AS ItemCode, supplier_code AS SupplierCode,
  148. order_qty AS OrderQty, order_date AS OrderDate, due_date AS DueDate, status AS Status
  149. FROM mdp_std_purchase_order WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine
  150. AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0
  151. OR (factory_id=1 AND source_system=@LegacySourceCode AND source_biz_key=@LegacyKey AND sync_batch_id=@StageBatch))
  152. FOR UPDATE
  153. """, new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine, scope.LegacySourceCode,
  154. LegacyKey = line.BusinessKey, StageBatch = stageCandidates.Count == 1 ? stageCandidates[0].BatchId : null });
  155. if (standards.Count > 1)
  156. return new("CONFLICT", null, null);
  157. var standard = standards.SingleOrDefault();
  158. if (stageCandidates.Count == 0 && standard is null && existing is null)
  159. {
  160. var legacy = writer == MdpPurchaseMigrationStore.Legacy;
  161. var package = new PurchaseHandoffPackage(Guid.Empty, string.Empty, scope.TenantId, scope.FactoryId, scope.NewSourceId,
  162. scope.DatasetId, PurchaseOrderSchemaRegistry.DatasetKey, legacy ? scope.LegacySourceCode : scope.NewSourceCode,
  163. PurchaseHandoffPackage.Version, PurchaseOrderSchemaRegistry.SourceVersion, "po-map-v1", [line]);
  164. return await MdpPurchaseHandoffService.WriteLineAsync(db, package, batchId, line, scopedKey, traceId);
  165. }
  166. var conflict = new PurchaseMigrationLineResult("CONFLICT", null, null);
  167. if (stageCandidates is not [var stage] || stage.FactoryId != scope.FactoryId
  168. || (stage.SourceCode != scope.LegacySourceCode && stage.SourceCode != scope.NewSourceCode)
  169. || (existing is not null && stage.Id != existing.StageId) || !stage.Matches(content))
  170. return conflict;
  171. var oldStage = string.Equals(stage.SourceCode, scope.LegacySourceCode, StringComparison.Ordinal);
  172. if (existing is null && !await HasCustodyEvidenceAsync(db, scope, stage, oldStage, writer))
  173. return conflict;
  174. if (standard is null)
  175. {
  176. var standardId = await MdpPurchaseHandoffService.InsertStandardAsync(db, scope.TenantId, scope.FactoryId,
  177. stage.SourceCode, stage.BusinessKey, stage.BatchId, line);
  178. return standardId.HasValue ? new("WRITTEN", stage.Id, standardId) : conflict;
  179. }
  180. if ((existing is not null && standard.Id != existing.StandardId)
  181. || standard.SourceCode != stage.SourceCode || standard.BusinessKey != stage.BusinessKey
  182. || standard.BatchId != stage.BatchId || standard.Content() != content)
  183. return conflict;
  184. if (standard.FactoryId != scope.FactoryId)
  185. {
  186. // 老投影用过默认工厂。只有证据已证明同一授权、贴源行及原批次时才认领。
  187. if (!oldStage || standard.FactoryId != 1)
  188. return conflict;
  189. await db.Ado.ExecuteCommandAsync(
  190. """
  191. UPDATE mdp_std_purchase_order SET factory_id=@FactoryId
  192. WHERE id=@Id AND tenant_id=@TenantId AND factory_id=1
  193. AND source_system=@SourceCode AND sync_batch_id=@BatchId
  194. """, new { scope.FactoryId, standard.Id, scope.TenantId, stage.SourceCode, stage.BatchId });
  195. }
  196. return new("REUSED", stage.Id, standard.Id);
  197. }
  198. private static async Task<bool> HasCustodyEvidenceAsync(
  199. ISqlSugarClient db, PurchaseMigrationScope scope, StoredStage stage, bool legacy, string writer)
  200. {
  201. if (legacy && writer == MdpPurchaseMigrationStore.Unified)
  202. return await db.Ado.GetIntAsync(
  203. """
  204. SELECT COUNT(*) FROM mdp_purchase_legacy_custody
  205. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_code=@SourceCode AND sync_batch_id=@BatchId
  206. """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
  207. if (legacy)
  208. return await db.Ado.GetIntAsync(
  209. """
  210. SELECT COUNT(*)
  211. FROM mdp_inbound_request r
  212. JOIN mdp_inbound_grant g ON g.tenant_id=r.tenant_id AND g.access_key=r.access_key
  213. AND g.entity_code=r.entity_code AND g.source_code=@SourceCode AND g.factory_id=@FactoryId
  214. WHERE r.tenant_id=@TenantId AND r.entity_code='S3_PURCHASE_ORDER'
  215. AND r.sync_batch_id=@BatchId AND r.status='COMMITTED' AND r.accepted>0
  216. """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
  217. return await db.Ado.GetIntAsync(
  218. """
  219. SELECT COUNT(*)
  220. FROM mdp_ingest_handoff_receipt r
  221. JOIN JSON_TABLE(r.line_results, '$[*]' COLUMNS (stage_id BIGINT PATH '$.stageId' NULL ON EMPTY NULL ON ERROR)) line
  222. ON line.stage_id=@StageId
  223. WHERE r.batch_id=@BatchId AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId
  224. AND r.dataset_id=@DatasetId AND r.source_id=@NewSourceId
  225. """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, scope.NewSourceId, StageId = stage.Id, stage.BatchId }) == 1;
  226. }
  227. internal static bool TryParseBusinessDate(string? text, out DateTime? result)
  228. {
  229. result = null;
  230. if (string.IsNullOrWhiteSpace(text))
  231. return true;
  232. DateTime date;
  233. if (text.EndsWith('Z'))
  234. text = text[..^1] + "+00:00";
  235. if (DateTimeOffset.TryParseExact(text, OffsetDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var offset))
  236. {
  237. var ticks = offset.UtcTicks + TimeSpan.FromHours(8).Ticks;
  238. if (ticks > DateTime.MaxValue.Ticks)
  239. return false;
  240. date = new DateTime(ticks);
  241. }
  242. else if (!DateTime.TryParseExact(text, LocalDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
  243. return false;
  244. if (date.Year < 1000)
  245. return false;
  246. result = new DateTime(date.Ticks - date.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
  247. return true;
  248. }
  249. private sealed record OrderContent(string PoNo, string PoLine, string ItemCode, string? SupplierCode,
  250. string Quantity, DateTime? OrderDate, DateTime? DueDate, string? Status)
  251. {
  252. public static OrderContent From(PurchaseHandoffLine line) =>
  253. new(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, QuantityOf(line.OrderQty),
  254. Clock(line.OrderDate), Clock(line.DueDate), line.Status);
  255. public static string QuantityOf(decimal quantity) => quantity.ToString("0.############################", CultureInfo.InvariantCulture);
  256. private static DateTime? Clock(DateTime? date) =>
  257. date.HasValue ? DateTime.SpecifyKind(date.Value, DateTimeKind.Unspecified) : null;
  258. }
  259. private sealed class LedgerRow
  260. {
  261. public string Digest { get; set; } = string.Empty;
  262. public long StageId { get; set; }
  263. public long StandardId { get; set; }
  264. }
  265. private sealed class StoredStage
  266. {
  267. public long Id { get; set; }
  268. public long? FactoryId { get; set; }
  269. public string SourceCode { get; set; } = string.Empty;
  270. public string BusinessKey { get; set; } = string.Empty;
  271. public string BatchId { get; set; } = string.Empty;
  272. public string RawData { get; set; } = string.Empty;
  273. public bool Matches(OrderContent expected)
  274. {
  275. try
  276. {
  277. using var json = JsonDocument.Parse(RawData);
  278. var row = json.RootElement;
  279. if (!row.TryGetProperty("OrderQty", out var qty)
  280. || !decimal.TryParse(qty.ValueKind == JsonValueKind.String ? qty.GetString() : qty.GetRawText(),
  281. NumberStyles.Float, CultureInfo.InvariantCulture, out var quantity)
  282. || !TryParseBusinessDate(Text("OrderDate"), out var orderDate)
  283. || !TryParseBusinessDate(Text("DueDate"), out var dueDate))
  284. return false;
  285. return new OrderContent(Text("PoNo") ?? "", Text("PoLine") ?? "", Text("ItemCode") ?? "", Text("SupplierCode"),
  286. OrderContent.QuantityOf(quantity), orderDate, dueDate, Text("Status")) == expected;
  287. string? Text(string name) => row.TryGetProperty(name, out var item) && item.ValueKind == JsonValueKind.String
  288. ? item.GetString() : null;
  289. }
  290. catch (JsonException)
  291. {
  292. return false;
  293. }
  294. }
  295. }
  296. private sealed class StoredStandard
  297. {
  298. public long Id { get; set; }
  299. public long? FactoryId { get; set; }
  300. public string SourceCode { get; set; } = string.Empty;
  301. public string BusinessKey { get; set; } = string.Empty;
  302. public string BatchId { get; set; } = string.Empty;
  303. public string PoNo { get; set; } = string.Empty;
  304. public string PoLine { get; set; } = string.Empty;
  305. public string ItemCode { get; set; } = string.Empty;
  306. public string? SupplierCode { get; set; }
  307. public decimal? OrderQty { get; set; }
  308. public DateTime? OrderDate { get; set; }
  309. public DateTime? DueDate { get; set; }
  310. public string? Status { get; set; }
  311. public OrderContent? Content() => OrderQty.HasValue
  312. ? new(PoNo, PoLine, ItemCode, SupplierCode, OrderContent.QuantityOf(OrderQty.Value), OrderDate, DueDate, Status)
  313. : null;
  314. }
  315. }