MdpPurchaseMigrationService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System.Runtime.ExceptionServices;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  3. using Microsoft.AspNetCore.Http;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. public sealed record PurchaseMigrationRegistration(
  6. long DatasetId, long NewSourceId, string LegacySourceCode, string LogicalSourceCode, string ApprovalRef);
  7. public sealed record PurchaseMigrationChange(long Revision, string PrimaryWriter, bool Frozen,
  8. string? AcceptedWatermark = null, string? StandardWatermark = null);
  9. public sealed record PurchaseMigrationState(long Id, string PrimaryWriter, bool Frozen, long Revision,
  10. string AcceptedWatermark, string StandardWatermark, int Unfinished);
  11. public sealed class MdpPurchaseMigrationService(ISqlSugarClient host)
  12. {
  13. private sealed class DatasetConfiguration
  14. {
  15. public long FactoryId { get; set; }
  16. public string DatasetKey { get; set; } = "";
  17. }
  18. public Task<PurchaseMigrationState> RegisterAsync(long tenant, long factory, long actor, PurchaseMigrationRegistration input) =>
  19. InTransactionAsync(async db =>
  20. {
  21. if (tenant <= 0 || factory <= 0 || actor <= 0 || !IsText(input.LegacySourceCode, 50)
  22. || !IsText(input.LogicalSourceCode, 50) || !IsText(input.ApprovalRef, 128))
  23. throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
  24. var configuration = await db.Ado.SqlQuerySingleAsync<DatasetConfiguration>(
  25. """
  26. SELECT d.factory_id AS FactoryId,d.dataset_key AS DatasetKey FROM mdp_ingest_dataset d
  27. WHERE d.id=@DatasetId AND d.tenant_id=@Tenant AND d.enabled=1 AND
  28. (d.factory_id=@Factory OR EXISTS (
  29. SELECT 1 FROM mdp_ingest_access_grant g JOIN mdp_purchase_active_factory f
  30. ON f.tenant_id=g.tenant_id AND f.factory_id=@Factory
  31. WHERE g.tenant_id=d.tenant_id AND g.factory_id=d.factory_id AND g.dataset_key=d.dataset_key
  32. AND g.source_id=@NewSourceId AND g.enabled=1 AND g.use_batch_factory=1))
  33. FOR UPDATE
  34. """, new { input.DatasetId, input.NewSourceId, Tenant = tenant, Factory = factory });
  35. if (configuration == null)
  36. throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
  37. var registry = new MdpIngestDatasetRegistry(db);
  38. var dataset = configuration.DatasetKey;
  39. var newBinding = await registry.ResolveActiveBindingAsync(tenant, configuration.FactoryId, input.NewSourceId, dataset);
  40. if (newBinding == null || newBinding.DatasetId != input.DatasetId || !IsText(newBinding.SourceCode, 50))
  41. throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
  42. var builtIn = new PurchaseOrderSchemaRegistry().Find(dataset, newBinding.SourceSchemaVersion);
  43. if (builtIn == null && await registry.ReadPublishedMapping(newBinding) == null)
  44. throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
  45. var oldSource = await db.Ado.GetIntAsync(
  46. """
  47. SELECT COUNT(*) FROM mdp_inbound_grant
  48. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_code=@LegacySourceCode
  49. AND entity_code='S3_PURCHASE_ORDER' AND status=1
  50. """, new { TenantId = tenant, FactoryId = factory, input.LegacySourceCode });
  51. if (oldSource == 0)
  52. throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
  53. var sameLegacy = await MdpPurchaseMigrationStore.LockLegacyAsync(db, tenant, factory, input.LegacySourceCode);
  54. var sameNew = await MdpPurchaseMigrationStore.LockNewAsync(db, tenant, factory, input.DatasetId, input.NewSourceId);
  55. if (sameLegacy is not null || sameNew is not null)
  56. throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_ALREADY_REGISTERED");
  57. await db.Ado.ExecuteCommandAsync(
  58. """
  59. INSERT INTO mdp_purchase_migration_scope
  60. (tenant_id,factory_id,legacy_source_code,new_source_id,new_source_code,dataset_id,
  61. logical_source_code,approval_ref,updated_by,updated_at)
  62. VALUES (@TenantId,@FactoryId,@LegacySourceCode,@NewSourceId,@NewSourceCode,@DatasetId,
  63. @LogicalSourceCode,@ApprovalRef,@Actor,UTC_TIMESTAMP(6))
  64. """, new { TenantId = tenant, FactoryId = factory, input.LegacySourceCode, input.NewSourceId,
  65. NewSourceCode = newBinding.SourceCode, input.DatasetId, input.LogicalSourceCode, input.ApprovalRef, Actor = actor });
  66. var id = await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
  67. var scope = await GetScopeAsync(db, tenant, factory, id);
  68. var checkpoint = await ReadStateAsync(db, scope);
  69. if (await PendingNewAsync(db, scope) != 0 || await PendingSnapshotsAsync(db, scope) != 0)
  70. throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_DRAIN_REQUIRED");
  71. await AuditAsync(db, scope.Id, scope.PrimaryWriter, actor, checkpoint);
  72. return checkpoint;
  73. });
  74. public Task<PurchaseMigrationState> ReadAsync(long tenant, long factory, long id) =>
  75. InTransactionAsync(async db => await ReadStateAsync(db, await GetScopeAsync(db, tenant, factory, id)));
  76. public Task<PurchaseMigrationState> ChangeAsync(long tenant, long factory, long actor, long id, PurchaseMigrationChange input) =>
  77. InTransactionAsync(async db =>
  78. {
  79. if (actor <= 0 || input.PrimaryWriter is not (MdpPurchaseMigrationStore.Legacy or MdpPurchaseMigrationStore.Unified))
  80. throw Invalid("INVALID_PURCHASE_MIGRATION_TRANSITION");
  81. var scope = await GetScopeAsync(db, tenant, factory, id);
  82. if (scope.Revision != input.Revision)
  83. throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_REVISION_CHANGED");
  84. var before = await ReadStateAsync(db, scope);
  85. if (input.PrimaryWriter != scope.PrimaryWriter)
  86. {
  87. if (!scope.Frozen || before.Unfinished != 0)
  88. throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_DRAIN_REQUIRED");
  89. if (input.AcceptedWatermark != before.AcceptedWatermark || input.StandardWatermark != before.StandardWatermark)
  90. throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_WATERMARK_CHANGED");
  91. }
  92. if (scope.PrimaryWriter == input.PrimaryWriter && scope.Frozen == input.Frozen)
  93. return before;
  94. await db.Ado.ExecuteCommandAsync(
  95. """
  96. UPDATE mdp_purchase_migration_scope
  97. SET primary_writer=@PrimaryWriter,frozen=@Frozen,revision=revision+1,updated_by=@Actor,updated_at=UTC_TIMESTAMP(6)
  98. WHERE id=@Id AND tenant_id=@Tenant AND factory_id=@Factory AND revision=@Revision
  99. """, new { input.PrimaryWriter, input.Frozen, Actor = actor, Id = id, Tenant = tenant, Factory = factory, input.Revision });
  100. var after = before with { PrimaryWriter = input.PrimaryWriter, Frozen = input.Frozen, Revision = before.Revision + 1 };
  101. await AuditAsync(db, scope.Id, scope.PrimaryWriter, actor, after);
  102. return after;
  103. });
  104. private static async Task<PurchaseMigrationState> ReadStateAsync(ISqlSugarClient db, PurchaseMigrationScope scope)
  105. {
  106. var legacy = new { scope.TenantId, scope.FactoryId, scope.LegacySourceCode };
  107. var unified = new { scope.TenantId, scope.FactoryId, scope.DatasetId, SourceId = scope.NewSourceId };
  108. const string oldReceipts = """
  109. FROM mdp_inbound_request r INNER JOIN mdp_inbound_grant g
  110. ON g.tenant_id=r.tenant_id AND g.entity_code=r.entity_code AND g.access_key=r.access_key
  111. WHERE r.tenant_id=@TenantId AND g.factory_id=@FactoryId AND g.source_code=@LegacySourceCode
  112. AND r.entity_code='S3_PURCHASE_ORDER'
  113. """;
  114. const string newScope = " WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId";
  115. var oldAccepted = await db.Ado.GetLongAsync("SELECT COALESCE(MAX(r.id),0) " + oldReceipts + " AND r.status='COMMITTED'", legacy);
  116. var newAccepted = await db.Ado.GetStringAsync(
  117. "SELECT batch_id FROM mdp_ingest_raw_batch" + newScope + " AND accepted_record_count>0 ORDER BY received_at DESC,batch_id DESC LIMIT 1", unified);
  118. var oldStandard = await db.Ado.GetLongAsync(
  119. """
  120. SELECT COALESCE(MAX(p.id),0) FROM mdp_std_purchase_order p
  121. JOIN mdp_stg_purchase_order s ON s.tenant_id=p.tenant_id AND s.source_system=p.source_system
  122. AND s.source_biz_key=p.source_biz_key AND s.sync_batch_id=p.sync_batch_id
  123. WHERE p.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_table='S3_PURCHASE_ORDER'
  124. AND s.source_system=@LegacySourceCode AND (p.factory_id=1 OR p.factory_id=@FactoryId)
  125. """, legacy);
  126. var newStandard = await db.Ado.GetStringAsync(
  127. "SELECT batch_id FROM mdp_ingest_handoff_receipt" + newScope + " ORDER BY created_at DESC,batch_id DESC LIMIT 1", unified);
  128. var observation = await db.Ado.GetLongAsync(
  129. "SELECT COALESCE(MAX(id),0) FROM mdp_purchase_migration_observation WHERE scope_id=@Id AND standard_id IS NOT NULL",
  130. new { scope.Id });
  131. var pending = await db.Ado.GetIntAsync("SELECT COUNT(*) " + oldReceipts + " AND r.status='RECEIVED'", legacy)
  132. + await PendingNewAsync(db, scope)
  133. + await db.Ado.GetIntAsync(
  134. """
  135. SELECT COUNT(*) FROM mdp_stg_purchase_order s LEFT JOIN mdp_std_purchase_order p
  136. ON p.tenant_id=s.tenant_id AND p.source_system=s.source_system AND p.source_biz_key=s.source_biz_key
  137. AND p.sync_batch_id=s.sync_batch_id AND (p.factory_id=1 OR p.factory_id=@FactoryId)
  138. WHERE s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_table='S3_PURCHASE_ORDER'
  139. AND s.source_system=@LegacySourceCode AND p.id IS NULL
  140. """, legacy);
  141. pending += await PendingSnapshotsAsync(db, scope);
  142. if (await db.Ado.GetIntAsync(
  143. "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='ado_module_dashboard_rebuild_job'") == 1)
  144. pending += await db.Ado.GetIntAsync(
  145. """
  146. SELECT COUNT(*) FROM ado_module_dashboard_rebuild_job
  147. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code='S3'
  148. AND status IN ('QUEUED','RUNNING')
  149. """, legacy);
  150. return new(scope.Id, scope.PrimaryWriter, scope.Frozen, scope.Revision,
  151. FormattableString.Invariant($"{oldAccepted}/{newAccepted ?? "-"}"),
  152. FormattableString.Invariant($"{oldStandard}/{newStandard ?? "-"}/{observation}"), pending);
  153. }
  154. private static async Task<PurchaseMigrationScope> GetScopeAsync(ISqlSugarClient db, long tenant, long factory, long id) =>
  155. await MdpPurchaseMigrationStore.LockByIdAsync(db, tenant, factory, id)
  156. ?? throw new MdpIngestHttpException(StatusCodes.Status404NotFound, "PURCHASE_MIGRATION_SCOPE_NOT_FOUND");
  157. private static Task<int> PendingNewAsync(ISqlSugarClient db, PurchaseMigrationScope scope) =>
  158. db.Ado.GetIntAsync(
  159. """
  160. SELECT COUNT(*) FROM mdp_ingest_receive_task
  161. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  162. AND status IN ('PENDING','PROCESSING','RETRY_PENDING','HANDOFF_READY','FAILED')
  163. """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, SourceId = scope.NewSourceId });
  164. private static Task<int> PendingSnapshotsAsync(ISqlSugarClient db, PurchaseMigrationScope scope) =>
  165. db.Ado.GetIntAsync(
  166. """
  167. SELECT COUNT(*) FROM mdp_inbound_snapshot s
  168. JOIN mdp_inbound_grant g ON g.tenant_id=s.tenant_id AND g.access_key=s.access_key AND g.entity_code=s.entity_code
  169. WHERE s.tenant_id=@TenantId AND g.factory_id=@FactoryId AND g.source_code=@LegacySourceCode
  170. AND s.entity_code='S3_PURCHASE_ORDER' AND s.status IN ('OPEN','DIFF_BLOCKED')
  171. AND s.expire_at>NOW()
  172. """, new { scope.TenantId, scope.FactoryId, scope.LegacySourceCode });
  173. private static Task<int> AuditAsync(ISqlSugarClient db, long id, string previous, long actor, PurchaseMigrationState after) =>
  174. db.Ado.ExecuteCommandAsync(
  175. """
  176. INSERT INTO mdp_purchase_migration_transition
  177. (scope_id,revision,old_primary,new_primary,frozen,accepted_watermark,standard_watermark,approval_ref,actor_id,changed_at)
  178. SELECT id,@Revision,@Previous,@PrimaryWriter,@Frozen,@AcceptedWatermark,@StandardWatermark,approval_ref,@Actor,UTC_TIMESTAMP(6)
  179. FROM mdp_purchase_migration_scope WHERE id=@Id
  180. """, new { Id = id, after.Revision, Previous = previous, after.PrimaryWriter, after.Frozen,
  181. after.AcceptedWatermark, after.StandardWatermark, Actor = actor });
  182. private async Task<PurchaseMigrationState> InTransactionAsync(Func<ISqlSugarClient, Task<PurchaseMigrationState>> action)
  183. {
  184. using var db = MdpIngestDatabase.Open(host);
  185. if (!await MdpPurchaseMigrationStore.HasScopeTableAsync(db))
  186. throw new MdpIngestHttpException(StatusCodes.Status503ServiceUnavailable, "PURCHASE_MIGRATION_SCHEMA_REQUIRED");
  187. var result = await db.Ado.UseTranAsync(() => action(db));
  188. if (result.IsSuccess)
  189. return result.Data;
  190. if (result.ErrorException is not null)
  191. ExceptionDispatchInfo.Throw(result.ErrorException);
  192. throw new MdpIngestHttpException(StatusCodes.Status503ServiceUnavailable, "PURCHASE_MIGRATION_UNAVAILABLE");
  193. }
  194. private static bool IsText(string? value, int max) => !string.IsNullOrWhiteSpace(value) && value.Length <= max && value.Trim() == value;
  195. private static MdpIngestHttpException Invalid(string code) => new(StatusCodes.Status400BadRequest, code);
  196. }