| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217 |
- using System.Runtime.ExceptionServices;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- using Microsoft.AspNetCore.Http;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed record PurchaseMigrationRegistration(
- long DatasetId, long NewSourceId, string LegacySourceCode, string LogicalSourceCode, string ApprovalRef);
- public sealed record PurchaseMigrationChange(long Revision, string PrimaryWriter, bool Frozen,
- string? AcceptedWatermark = null, string? StandardWatermark = null);
- public sealed record PurchaseMigrationState(long Id, string PrimaryWriter, bool Frozen, long Revision,
- string AcceptedWatermark, string StandardWatermark, int Unfinished);
- public sealed class MdpPurchaseMigrationService(ISqlSugarClient host)
- {
- private sealed class DatasetConfiguration
- {
- public long FactoryId { get; set; }
- public string DatasetKey { get; set; } = "";
- }
- public Task<PurchaseMigrationState> RegisterAsync(long tenant, long factory, long actor, PurchaseMigrationRegistration input) =>
- InTransactionAsync(async db =>
- {
- if (tenant <= 0 || factory <= 0 || actor <= 0 || !IsText(input.LegacySourceCode, 50)
- || !IsText(input.LogicalSourceCode, 50) || !IsText(input.ApprovalRef, 128))
- throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
- var configuration = await db.Ado.SqlQuerySingleAsync<DatasetConfiguration>(
- """
- SELECT d.factory_id AS FactoryId,d.dataset_key AS DatasetKey FROM mdp_ingest_dataset d
- WHERE d.id=@DatasetId AND d.tenant_id=@Tenant AND d.enabled=1 AND
- (d.factory_id=@Factory OR EXISTS (
- SELECT 1 FROM mdp_ingest_access_grant g JOIN mdp_purchase_active_factory f
- ON f.tenant_id=g.tenant_id AND f.factory_id=@Factory
- WHERE g.tenant_id=d.tenant_id AND g.factory_id=d.factory_id AND g.dataset_key=d.dataset_key
- AND g.source_id=@NewSourceId AND g.enabled=1 AND g.use_batch_factory=1))
- FOR UPDATE
- """, new { input.DatasetId, input.NewSourceId, Tenant = tenant, Factory = factory });
- if (configuration == null)
- throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
- var registry = new MdpIngestDatasetRegistry(db);
- var dataset = configuration.DatasetKey;
- var newBinding = await registry.ResolveActiveBindingAsync(tenant, configuration.FactoryId, input.NewSourceId, dataset);
- if (newBinding == null || newBinding.DatasetId != input.DatasetId || !IsText(newBinding.SourceCode, 50))
- throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
- var builtIn = new PurchaseOrderSchemaRegistry().Find(dataset, newBinding.SourceSchemaVersion);
- if (builtIn == null && await registry.ReadPublishedMapping(newBinding) == null)
- throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
- var oldSource = await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM mdp_inbound_grant
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_code=@LegacySourceCode
- AND entity_code='S3_PURCHASE_ORDER' AND status=1
- """, new { TenantId = tenant, FactoryId = factory, input.LegacySourceCode });
- if (oldSource == 0)
- throw Invalid("INVALID_PURCHASE_MIGRATION_BINDING");
- var sameLegacy = await MdpPurchaseMigrationStore.LockLegacyAsync(db, tenant, factory, input.LegacySourceCode);
- var sameNew = await MdpPurchaseMigrationStore.LockNewAsync(db, tenant, factory, input.DatasetId, input.NewSourceId);
- if (sameLegacy is not null || sameNew is not null)
- throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_ALREADY_REGISTERED");
- await db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_purchase_migration_scope
- (tenant_id,factory_id,legacy_source_code,new_source_id,new_source_code,dataset_id,
- logical_source_code,approval_ref,updated_by,updated_at)
- VALUES (@TenantId,@FactoryId,@LegacySourceCode,@NewSourceId,@NewSourceCode,@DatasetId,
- @LogicalSourceCode,@ApprovalRef,@Actor,UTC_TIMESTAMP(6))
- """, new { TenantId = tenant, FactoryId = factory, input.LegacySourceCode, input.NewSourceId,
- NewSourceCode = newBinding.SourceCode, input.DatasetId, input.LogicalSourceCode, input.ApprovalRef, Actor = actor });
- var id = await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
- var scope = await GetScopeAsync(db, tenant, factory, id);
- var checkpoint = await ReadStateAsync(db, scope);
- if (await PendingNewAsync(db, scope) != 0 || await PendingSnapshotsAsync(db, scope) != 0)
- throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_DRAIN_REQUIRED");
- await AuditAsync(db, scope.Id, scope.PrimaryWriter, actor, checkpoint);
- return checkpoint;
- });
- public Task<PurchaseMigrationState> ReadAsync(long tenant, long factory, long id) =>
- InTransactionAsync(async db => await ReadStateAsync(db, await GetScopeAsync(db, tenant, factory, id)));
- public Task<PurchaseMigrationState> ChangeAsync(long tenant, long factory, long actor, long id, PurchaseMigrationChange input) =>
- InTransactionAsync(async db =>
- {
- if (actor <= 0 || input.PrimaryWriter is not (MdpPurchaseMigrationStore.Legacy or MdpPurchaseMigrationStore.Unified))
- throw Invalid("INVALID_PURCHASE_MIGRATION_TRANSITION");
- var scope = await GetScopeAsync(db, tenant, factory, id);
- if (scope.Revision != input.Revision)
- throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_REVISION_CHANGED");
- var before = await ReadStateAsync(db, scope);
- if (input.PrimaryWriter != scope.PrimaryWriter)
- {
- if (!scope.Frozen || before.Unfinished != 0)
- throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_DRAIN_REQUIRED");
- if (input.AcceptedWatermark != before.AcceptedWatermark || input.StandardWatermark != before.StandardWatermark)
- throw MdpPurchaseMigrationStore.Conflict("PURCHASE_MIGRATION_WATERMARK_CHANGED");
- }
- if (scope.PrimaryWriter == input.PrimaryWriter && scope.Frozen == input.Frozen)
- return before;
- await db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_purchase_migration_scope
- SET primary_writer=@PrimaryWriter,frozen=@Frozen,revision=revision+1,updated_by=@Actor,updated_at=UTC_TIMESTAMP(6)
- WHERE id=@Id AND tenant_id=@Tenant AND factory_id=@Factory AND revision=@Revision
- """, new { input.PrimaryWriter, input.Frozen, Actor = actor, Id = id, Tenant = tenant, Factory = factory, input.Revision });
- var after = before with { PrimaryWriter = input.PrimaryWriter, Frozen = input.Frozen, Revision = before.Revision + 1 };
- await AuditAsync(db, scope.Id, scope.PrimaryWriter, actor, after);
- return after;
- });
- private static async Task<PurchaseMigrationState> ReadStateAsync(ISqlSugarClient db, PurchaseMigrationScope scope)
- {
- var legacy = new { scope.TenantId, scope.FactoryId, scope.LegacySourceCode };
- var unified = new { scope.TenantId, scope.FactoryId, scope.DatasetId, SourceId = scope.NewSourceId };
- const string oldReceipts = """
- FROM mdp_inbound_request r INNER JOIN mdp_inbound_grant g
- ON g.tenant_id=r.tenant_id AND g.entity_code=r.entity_code AND g.access_key=r.access_key
- WHERE r.tenant_id=@TenantId AND g.factory_id=@FactoryId AND g.source_code=@LegacySourceCode
- AND r.entity_code='S3_PURCHASE_ORDER'
- """;
- const string newScope = " WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId";
- var oldAccepted = await db.Ado.GetLongAsync("SELECT COALESCE(MAX(r.id),0) " + oldReceipts + " AND r.status='COMMITTED'", legacy);
- var newAccepted = await db.Ado.GetStringAsync(
- "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);
- var oldStandard = await db.Ado.GetLongAsync(
- """
- SELECT COALESCE(MAX(p.id),0) FROM mdp_std_purchase_order p
- JOIN mdp_stg_purchase_order s ON s.tenant_id=p.tenant_id AND s.source_system=p.source_system
- AND s.source_biz_key=p.source_biz_key AND s.sync_batch_id=p.sync_batch_id
- WHERE p.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_table='S3_PURCHASE_ORDER'
- AND s.source_system=@LegacySourceCode AND (p.factory_id=1 OR p.factory_id=@FactoryId)
- """, legacy);
- var newStandard = await db.Ado.GetStringAsync(
- "SELECT batch_id FROM mdp_ingest_handoff_receipt" + newScope + " ORDER BY created_at DESC,batch_id DESC LIMIT 1", unified);
- var observation = await db.Ado.GetLongAsync(
- "SELECT COALESCE(MAX(id),0) FROM mdp_purchase_migration_observation WHERE scope_id=@Id AND standard_id IS NOT NULL",
- new { scope.Id });
- var pending = await db.Ado.GetIntAsync("SELECT COUNT(*) " + oldReceipts + " AND r.status='RECEIVED'", legacy)
- + await PendingNewAsync(db, scope)
- + await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM mdp_stg_purchase_order s LEFT JOIN mdp_std_purchase_order p
- ON p.tenant_id=s.tenant_id AND p.source_system=s.source_system AND p.source_biz_key=s.source_biz_key
- AND p.sync_batch_id=s.sync_batch_id AND (p.factory_id=1 OR p.factory_id=@FactoryId)
- WHERE s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_table='S3_PURCHASE_ORDER'
- AND s.source_system=@LegacySourceCode AND p.id IS NULL
- """, legacy);
- pending += await PendingSnapshotsAsync(db, scope);
- if (await db.Ado.GetIntAsync(
- "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='ado_module_dashboard_rebuild_job'") == 1)
- pending += await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM ado_module_dashboard_rebuild_job
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code='S3'
- AND status IN ('QUEUED','RUNNING')
- """, legacy);
- return new(scope.Id, scope.PrimaryWriter, scope.Frozen, scope.Revision,
- FormattableString.Invariant($"{oldAccepted}/{newAccepted ?? "-"}"),
- FormattableString.Invariant($"{oldStandard}/{newStandard ?? "-"}/{observation}"), pending);
- }
- private static async Task<PurchaseMigrationScope> GetScopeAsync(ISqlSugarClient db, long tenant, long factory, long id) =>
- await MdpPurchaseMigrationStore.LockByIdAsync(db, tenant, factory, id)
- ?? throw new MdpIngestHttpException(StatusCodes.Status404NotFound, "PURCHASE_MIGRATION_SCOPE_NOT_FOUND");
- private static Task<int> PendingNewAsync(ISqlSugarClient db, PurchaseMigrationScope scope) =>
- db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM mdp_ingest_receive_task
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
- AND status IN ('PENDING','PROCESSING','RETRY_PENDING','HANDOFF_READY','FAILED')
- """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, SourceId = scope.NewSourceId });
- private static Task<int> PendingSnapshotsAsync(ISqlSugarClient db, PurchaseMigrationScope scope) =>
- db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM mdp_inbound_snapshot s
- 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
- WHERE s.tenant_id=@TenantId AND g.factory_id=@FactoryId AND g.source_code=@LegacySourceCode
- AND s.entity_code='S3_PURCHASE_ORDER' AND s.status IN ('OPEN','DIFF_BLOCKED')
- AND s.expire_at>NOW()
- """, new { scope.TenantId, scope.FactoryId, scope.LegacySourceCode });
- private static Task<int> AuditAsync(ISqlSugarClient db, long id, string previous, long actor, PurchaseMigrationState after) =>
- db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_purchase_migration_transition
- (scope_id,revision,old_primary,new_primary,frozen,accepted_watermark,standard_watermark,approval_ref,actor_id,changed_at)
- SELECT id,@Revision,@Previous,@PrimaryWriter,@Frozen,@AcceptedWatermark,@StandardWatermark,approval_ref,@Actor,UTC_TIMESTAMP(6)
- FROM mdp_purchase_migration_scope WHERE id=@Id
- """, new { Id = id, after.Revision, Previous = previous, after.PrimaryWriter, after.Frozen,
- after.AcceptedWatermark, after.StandardWatermark, Actor = actor });
- private async Task<PurchaseMigrationState> InTransactionAsync(Func<ISqlSugarClient, Task<PurchaseMigrationState>> action)
- {
- using var db = MdpIngestDatabase.Open(host);
- if (!await MdpPurchaseMigrationStore.HasScopeTableAsync(db))
- throw new MdpIngestHttpException(StatusCodes.Status503ServiceUnavailable, "PURCHASE_MIGRATION_SCHEMA_REQUIRED");
- var result = await db.Ado.UseTranAsync(() => action(db));
- if (result.IsSuccess)
- return result.Data;
- if (result.ErrorException is not null)
- ExceptionDispatchInfo.Throw(result.ErrorException);
- throw new MdpIngestHttpException(StatusCodes.Status503ServiceUnavailable, "PURCHASE_MIGRATION_UNAVAILABLE");
- }
- private static bool IsText(string? value, int max) => !string.IsNullOrWhiteSpace(value) && value.Length <= max && value.Trim() == value;
- private static MdpIngestHttpException Invalid(string code) => new(StatusCodes.Status400BadRequest, code);
- }
|