using Admin.NET.Core.Service; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Admin.NET.Plugin.AiDOP.Entity.DataPlatform; using Admin.NET.Plugin.ApprovalFlow; using Admin.NET.Plugin.ApprovalFlow.Service; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed record MdpCandidateInput(long SourceId, string Version, string MappingJson, int Revision); public sealed record MdpLifecycleInput(int Revision, string Reason); public sealed partial class MdpIngestDatasetController { private const string FlowType = "MDP_DATASET_RELEASE"; private const string TrialPermission = "mdpRelease:trial"; private const string PublishPermission = "mdpRelease:publish"; private IConfiguration Settings => HttpContext.RequestServices.GetRequiredService(); private string TargetEnvironment => Settings["MDP_RELEASE_ENVIRONMENT"] ?? HttpContext.RequestServices.GetRequiredService().EnvironmentName; private async Task Can(string permission) => (await HttpContext.RequestServices.GetRequiredService().GetOwnBtnPermList()).Contains(permission); private sealed class Release { public long Id { get; set; } public long SourceId { get; set; } public string SourceCode { get; set; } = ""; public string Version { get; set; } = ""; public string MappingJson { get; set; } = ""; public string State { get; set; } = ""; public string EnvironmentKey { get; set; } = ""; public int BaseRevision { get; set; } public string? TrialJson { get; set; } public long? FlowId { get; set; } } private sealed class ReleaseEvent { public string Action { get; set; } = ""; public string Detail { get; set; } = ""; public string Actor { get; set; } = ""; public DateTime CreatedAt { get; set; } public string? ReleaseId { get; set; } } private const string ReleaseSelect = """ SELECT id,source_id AS SourceId,source_code AS SourceCode,schema_version AS Version,mapping_json AS MappingJson,state, environment_key AS EnvironmentKey,base_revision AS BaseRevision,trial_json AS TrialJson,flow_id AS FlowId FROM mdp_ingest_release WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@id """; private sealed class HandoffEvidence { public long ReleaseId { get; set; } public string BatchId { get; set; } = ""; public string FactoryId { get; set; } = ""; public int Accepted { get; set; } public int Isolated { get; set; } public DateTime AcknowledgedAt { get; set; } } private async Task> HandoffEvidenceByRelease(long datasetId, long tenant) { var allowed = await AuthorizedFactories(tenant); var rows = await db.Ado.SqlQueryAsync(""" SELECT ReleaseId,BatchId,FactoryId,Accepted,Isolated,AcknowledgedAt FROM ( SELECT e.release_id AS ReleaseId,e.batch_id AS BatchId,CAST(e.factory_id AS CHAR) AS FactoryId, e.accepted_count AS Accepted,e.isolated_count AS Isolated,e.acknowledged_at AS AcknowledgedAt, ROW_NUMBER() OVER (PARTITION BY e.release_id ORDER BY (e.accepted_count>0) DESC, e.acknowledged_at,e.batch_id) AS receipt_rank FROM mdp_ingest_release_batch e JOIN JSON_TABLE(@visible,'$[*]' COLUMNS (factory BIGINT PATH '$')) f ON f.factory=e.factory_id WHERE e.tenant_id=@tenant AND e.dataset_id=@datasetId AND e.acknowledged_at IS NOT NULL ) evidence WHERE receipt_rank=1 """, new { tenant, datasetId, visible = JsonSerializer.Serialize(allowed.Select(f => f.Id)) }); return rows.ToDictionary(row => row.ReleaseId); } private Task Lifecycle(long id) => db.Ado.SqlQuerySingleAsync( "SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id }); private Task Log(long id, long? release, string action, string detail) => db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_release_log(dataset_id,release_id,action,actor,detail,created_at) VALUES (@id,@release,@action,@actor,@detail,UTC_TIMESTAMP(6)) """, new { id, release, action, actor = user.UserId, detail }); [HttpGet("{id:long}/releases")] public Task Releases(long id, [FromQuery] long? factoryId) => WithScope(factoryId, async scope => { if (!await Datasets(scope).AnyAsync(x => x.Id == id)) return NotFound(); var releases = await db.Ado.SqlQueryAsync(ReleaseSelect + " ORDER BY id DESC", new { tenant = scope.TenantId, factory = scope.FactoryId, id }); var lifecycle = await Lifecycle(id); var current = (await db.Ado.SqlQueryAsync(""" SELECT p.release_id FROM mdp_ingest_published_source p JOIN mdp_ingest_dataset d ON d.id=p.dataset_id AND d.tenant_id=p.tenant_id AND d.factory_id=p.factory_id AND d.active_schema_version=p.schema_version WHERE d.id=@id AND d.tenant_id=@tenant AND d.factory_id=@factory """, new { id, tenant=scope.TenantId, factory=scope.FactoryId })).ToHashSet(); var evidence = await HandoffEvidenceByRelease(id, scope.TenantId); var history = new List(); foreach (var item in releases) { var approval = item.FlowId.HasValue ? await Approval(item) : null; var handoff = evidence.GetValueOrDefault(item.Id); history.Add(new { id = item.Id.ToString(), sourceId = item.SourceId.ToString(), item.Version, item.MappingJson, item.State, projectState = item.State switch { "PUBLISHED" when current.Contains(item.Id) && lifecycle is "PAUSED" or "RETIRED" => lifecycle, "PUBLISHED" => handoff?.Accepted > 0 ? "HANDED_OVER" : "AWAITING_HANDOFF", _ => item.State }, handoff = handoff == null ? null : new { handoff.BatchId, handoff.FactoryId, handoff.Accepted, handoff.Isolated, handoff.AcknowledgedAt }, item.EnvironmentKey, item.BaseRevision, item.TrialJson, approval = approval?.Status.ToString(), flowId = item.FlowId?.ToString() }); } var timeline = await db.Ado.SqlQueryAsync(""" SELECT action,detail,CAST(actor AS CHAR) AS Actor,created_at AS CreatedAt,CAST(release_id AS CHAR) AS ReleaseId FROM mdp_ingest_release_log WHERE dataset_id=@id ORDER BY id DESC """, new { id }); return Ok(new { history, timeline, environment = TargetEnvironment, lifecycle, canTrial = await Can(TrialPermission), canPublish = await Can(PublishPermission) }); }); private Task Approval(Release row) => db.Queryable().ClearFilter().FirstAsync(f => f.Id == row.FlowId && f.BizType == FlowType && f.BizId == row.Id); [HttpPost("{id:long}/releases")] public Task Draft(long id, [FromQuery] long? factoryId, MdpCandidateInput input) => Locked(id, factoryId, async (dataset, scope) => { Require(dataset.Revision == input.Revision, "配置已更新,请刷新"); Require(await Lifecycle(id) != "RETIRED", "数据集已退役"); var source = await BoundSource(dataset, input.SourceId); Require(source != null, "所选来源未授权或已停用"); var config = new PurchaseVersionConfiguration(dataset.DatasetKey, input.Version, input.MappingJson); await CheckArchived(dataset, input.Version, config.MappingJson); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_release(tenant_id,factory_id,dataset_id,source_id,source_code,schema_version,environment_key, mapping_json,base_revision,state,created_by,created_at) VALUES (@tenant,@factory,@id,@source,@code,@version,@env,@json,@revision,'DRAFT',@actor,UTC_TIMESTAMP(6)) """, new { tenant = scope.TenantId, factory = scope.FactoryId, id, source = input.SourceId, code = source!.SourceCode, version = input.Version, env = TargetEnvironment, json = config.MappingJson, revision = dataset.Revision, actor = user.UserId }); var created = await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()"); await Log(id, created, "DRAFT", input.Version); return Ok(new { id = created.ToString() }); }); [HttpPost("{id:long}/releases/{release:long}/{actionName}")] public Task Transition(long id, long release, string actionName, [FromQuery] long? factoryId, [FromBody] MdpTrialInput? trial) => Locked(id, factoryId, async (dataset, scope) => { Require(await Lifecycle(id) != "RETIRED", "数据集已退役"); var row = await db.Ado.SqlQuerySingleAsync(ReleaseSelect + " AND id=@release FOR UPDATE", new { tenant = scope.TenantId, factory = scope.FactoryId, id, release }); Require(row != null && row.EnvironmentKey == TargetEnvironment, "候选版本不属于当前环境"); Require(row!.BaseRevision == dataset.Revision, "配置或绑定已变更,请基于当前修订创建新候选"); var source = await BoundSource(dataset, row.SourceId); Require(source != null && source.SourceCode == row.SourceCode, "候选来源已停用、解绑或更名,请核对后重新创建候选"); var config = new PurchaseVersionConfiguration(dataset.DatasetKey, row.Version, row.MappingJson); await CheckArchived(dataset, row.Version, config.MappingJson); string next; switch (actionName) { case "precheck": Require(row.State == "DRAFT", "只有草稿可以预检"); await CheckReceiver(dataset, source!, row); await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted); next = "PREFLIGHT"; break; case "trial": if (!await Can(TrialPermission)) return Forbid(); Require(row.State is "PREFLIGHT" or "RECONCILING" && trial != null, "请先预检并提供试跑样本"); var result = await MdpDatasetSandbox.Run(Settings, new(scope.TenantId, scope.FactoryId, row.SourceId, id, source!.SourceCode, dataset.DatasetKey), row.Version, config, trial!, HttpContext.RequestAborted); var json = JsonSerializer.Serialize(result.Evidence, JsonSerializerOptions.Web); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_release_trial(batch_id,release_id,payload,evidence_json,manifest_json,actor,created_at) VALUES (@batch,@release,@payload,@json,@manifest,@actor,UTC_TIMESTAMP(6)) """, new { batch = result.Evidence.BatchId.ToString("D"), release, payload = result.Prepared.Batch.Payload.ToArray(), json, manifest = JsonSerializer.Serialize(new { result.Prepared.Batch.Versions, result.Prepared.Events, trial!.ExpectedValid, trial.ExpectedIsolated, trial.ExpectedQuantity }, JsonSerializerOptions.Web), actor = user.UserId }); await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET trial_json=@evidence WHERE id=@release", new { evidence = json, release }); next = "RECONCILING"; break; case "submit": if (!await Can(TrialPermission)) return Forbid(); Require(row.State == "RECONCILING" && row.TrialJson != null, "请先试跑对账"); var proof = JsonSerializer.Deserialize(row.TrialJson!, JsonSerializerOptions.Web); Require(proof?.Matched == true, "试跑差额尚未核对通过"); var defined = await db.Queryable().ClearFilter() .AnyAsync(f => f.BizType == FlowType && f.IsPublished && !f.IsDelete && (f.TenantId == scope.TenantId || f.TenantId == null)); Require(defined, "请先在审批流程设计器中发布“接收数据集版本发布”的人工审批流程"); var flow = HttpContext.RequestServices.GetRequiredService(); var flowId = await flow.StartFlow(new StartFlowInput { BizType = FlowType, BizId = row.Id, BizNo = $"MDP-{row.Id}/{row.Version}", Title = $"{scope.FactoryName} · {dataset.Name} · {row.Version}", Comment = $"{TargetEnvironment},批次 {proof!.BatchId},有效 {proof.Valid},隔离 {proof.Isolated},数量 {proof.StandardQuantity}。来源 {source!.SourceCode},配置修订 {row.BaseRevision},映射版本 {config.Find(dataset.DatasetKey, row.Version)!.MappingVersion}" }, scope.TenantId); await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET flow_id=@flowId WHERE id=@release", new { flowId, release }); next = "REVIEW"; break; case "publish": if (!await Can(PublishPermission)) return Forbid(); Require(row.State == "REVIEW" && row.FlowId.HasValue, "请先提交审批"); var approved = await Approval(row); Require(approved?.Status == FlowInstanceStatusEnum.Approved && await HasFactoryApproval(approved.Id, scope), "尚未取得人工审批通过记录"); await CheckReceiver(dataset, source!, row); await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted); await Publish(dataset, row); next = "PUBLISHED"; break; default: return BadRequest(new { message = "未知版本操作" }); } await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET state=@next WHERE id=@release", new { next, release }); await Log(id, release, actionName, row.Version); return NoContent(); }); private async Task CheckReceiver(MdpIngestDataset dataset, MdpSource source, Release candidate) { // Read through the receiver's own connection so a stale deployment, wrong database or missing view grant blocks publication. var receiverConnection = Settings["MDP_PURCHASE_RECEIVER_MYSQL"]; Require(!string.IsNullOrWhiteSpace(receiverConnection), "请先配置采购接收库连接"); using var receiver = new SqlSugarClient(new ConnectionConfig { DbType = SqlSugar.DbType.MySql, ConnectionString = receiverConnection, IsAutoCloseConnection = true }); try { var visible = await receiver.Ado.GetIntAsync(""" SELECT COUNT(*) FROM mdp_purchase_release_probe p LEFT JOIN mdp_purchase_contract_version a ON a.dataset_id=p.dataset_id AND a.tenant_id=p.tenant_id AND a.factory_id=p.factory_id AND a.schema_version=p.schema_version WHERE p.id=@Id AND p.tenant_id=@TenantId AND p.factory_id=@FactoryId AND p.dataset_id=@datasetId AND p.source_id=@SourceId AND p.environment_key=@EnvironmentKey AND p.schema_version=@Version AND p.mapping_hash=SHA2(@MappingJson,256) AND (a.dataset_id IS NULL OR SHA2(a.mapping_json,256)=p.mapping_hash) """, new { candidate.Id, dataset.TenantId, dataset.FactoryId, datasetId = dataset.Id, candidate.SourceId, candidate.EnvironmentKey, candidate.Version, candidate.MappingJson }); Require(visible == 1, "采购接收库尚未识别此环境的候选配置"); } catch (Exception e) when (e is System.Data.Common.DbException or SqlSugarException) { throw new DatasetChangeException("采购接收库无法读取版本视图,请核对连接、迁移和读取权限"); } var migration = await MdpPurchaseMigrationStore.LockNewAsync(db, dataset.TenantId, dataset.FactoryId, dataset.Id, source.Id); if (migration != null) { Require(!migration.Frozen && migration.PrimaryWriter == MdpPurchaseMigrationStore.Unified && migration.NewSourceCode == source.SourceCode, "采购迁移范围尚未授权统一入口写入"); return; } var authorized = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(dataset.TenantId, "PURCHASE"); Require(string.Equals(authorized?.SourceSystem, source.SourceCode, StringComparison.OrdinalIgnoreCase), "此来源尚未取得采购标准层写入权"); } private async Task HasFactoryApproval(long flowId, DatasetScope scope) { var decision = await db.Queryable().ClearFilter() .Where(x => x.InstanceId == flowId && x.Action == FlowLogActionEnum.Approve && x.OperatorId > 0) .OrderByDescending(x => x.Id).FirstAsync(); if (decision == null || await db.Queryable().ClearFilter() .AnyAsync(x => x.InstanceId == flowId && x.Action == FlowLogActionEnum.AutoTimeout)) return false; var approver = await db.Queryable().ClearFilter().FirstAsync(x => x.Id == decision.OperatorId && x.TenantId == scope.TenantId && x.Status == StatusEnum.Enable); return approver != null && (await organizations.GetUserOrgIdList(approver.Id, approver.OrgId)).Contains(scope.FactoryId); } private async Task Publish(MdpIngestDataset dataset, Release row) { var id = dataset.Id; var args = new { tenant = dataset.TenantId, factory = dataset.FactoryId, id, version = row.Version, json = row.MappingJson, source = row.SourceId, release = row.Id, actor = user.UserId }; await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_contract_archive(tenant_id,factory_id,dataset_id,schema_version,mapping_json,release_id) VALUES (@tenant,@factory,@id,@version,@json,@release) ON DUPLICATE KEY UPDATE release_id=release_id """, args); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_published_source(tenant_id,factory_id,dataset_id,schema_version,source_id,release_id) VALUES (@tenant,@factory,@id,@version,@source,@release) ON DUPLICATE KEY UPDATE release_id=VALUES(release_id) """, args); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_dataset_version(tenant_id,factory_id,dataset_id,schema_version,registered_by,registered_at) VALUES (@tenant,@factory,@id,@version,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE id=id """, args); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_ingest_dataset SET enabled=1,active_schema_version=@version,revision=revision+1, updated_by=@actor,updated_at=UTC_TIMESTAMP(6) WHERE id=@id """, args); await db.Ado.ExecuteCommandAsync("UPDATE mdp_ingest_release SET published_by=@actor,published_at=UTC_TIMESTAMP(6) WHERE id=@release", args); await SetLifecycle(id, "ACTIVE", "批准版本 " + row.Version, dataset.Revision + 1); } private async Task CheckArchived(MdpIngestDataset dataset, string version, string mapping) { var archived = await db.Ado.SqlQuerySingleAsync(""" SELECT mapping_json FROM mdp_ingest_contract_archive WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@Id AND schema_version=@version """, new { dataset.TenantId, dataset.FactoryId, dataset.Id, version }); Require(archived == null || archived == mapping, "版本号已归档,请使用新版本号"); } private Task BoundSource(MdpIngestDataset ds, long source) => db.Queryable().Where(s => s.Id == source && s.TenantId == ds.TenantId && s.Status == 1 && SqlFunc.Subqueryable().Where(b => b.SourceId == s.Id && b.DatasetId == ds.Id && b.FactoryId == ds.FactoryId && b.TenantId == ds.TenantId && b.Enabled).Any()).FirstAsync(); private Task SetLifecycle(long id, string state, string reason, int revision) => db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_lifecycle(dataset_id,state,reason,revision,updated_by,updated_at) VALUES (@id,@state,@reason,@revision,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE state=VALUES(state),reason=VALUES(reason),revision=VALUES(revision),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at) """, new { id, state, reason, revision, actor = user.UserId }); [HttpPost("{id:long}/lifecycle/{operation}")] public Task LifecycleAction(long id, string operation, [FromQuery] long? factoryId, MdpLifecycleInput input) => Locked(id, factoryId, async (dataset, _) => { if (!await Can(PublishPermission)) return Forbid(); Require(input.Revision == dataset.Revision && !string.IsNullOrWhiteSpace(input.Reason) && input.Reason.Length <= 500, "请刷新修订号并填写操作原因"); var state = await Lifecycle(id); Require(state != "RETIRED", "数据集已退役"); if (operation == "retire") { Require(state == "PAUSED", "须先暂停接收"); var outstanding = await db.Ado.SqlQuerySingleAsync(""" SELECT COUNT(*) FROM mdp_ingest_receive_task WHERE dataset_id=@id AND status NOT IN ('SUCCEEDED','PARTIAL','QUARANTINED') """, new { id }); Require(outstanding == 0, "存在在途或待处置批次"); } else if (operation == "resume") { Require(state == "PAUSED" && dataset.ActiveSchemaVersion != null, "只有已暂停的数据集可以恢复"); var pausedAt = await db.Ado.GetIntAsync("SELECT revision FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id }); Require(pausedAt == dataset.Revision, "暂停后配置已修改,请重新走候选版本审批"); } else Require(operation == "pause" && state != "PAUSED" && dataset.Enabled, "只有已启用的数据集可以暂停"); await SetLifecycle(id, operation switch { "pause" => "PAUSED", "resume" => "ACTIVE", _ => "RETIRED" }, input.Reason, dataset.Revision + 1); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_ingest_dataset SET enabled=@processing,revision=revision+1,updated_by=@actor,updated_at=UTC_TIMESTAMP(6) WHERE id=@id """, new { id, processing = operation == "retire" ? 0 : 1, actor = user.UserId }); await Log(id, null, operation, input.Reason); return NoContent(); }); private Task Locked(long id, long? factoryId, Func> work) => WithScope(factoryId, async scope => { var tx = await db.Ado.UseTranAsync(async () => { var locked = await db.Ado.SqlQuerySingleAsync(""" SELECT id FROM mdp_ingest_dataset WHERE id=@id AND tenant_id=@tenant AND factory_id=@factory FOR UPDATE """, new { id, tenant = scope.TenantId, factory = scope.FactoryId }); if (locked == null) return (IActionResult)NotFound(); return await work(await Datasets(scope).FirstAsync(x => x.Id == id), scope); }); if (tx.IsSuccess) return tx.Data; return tx.ErrorException switch { DatasetChangeException e => Conflict(new { message = e.Message }), ArgumentException e => BadRequest(new { message = e.Message }), JsonException => BadRequest(new { message = "请输入有效 JSON" }), IngestContractException e => BadRequest(new { message = e.Code.ToString() }), _ => throw tx.ErrorException ?? new InvalidOperationException("版本操作失败") }; }); private static void Require(bool condition, string message) { if (!condition) throw new DatasetChangeException(message); } }