|
|
@@ -0,0 +1,256 @@
|
|
|
+using Admin.NET.Core.Service;
|
|
|
+using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
|
|
|
+using MySqlConnector;
|
|
|
+using System.Text.Json.Serialization;
|
|
|
+
|
|
|
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
|
|
|
+
|
|
|
+[ApiController]
|
|
|
+[Authorize]
|
|
|
+[RequirePcMenuPath("/aidop/data-platform/sources")]
|
|
|
+[Route("api/DataPlatform/ingest-datasets")]
|
|
|
+[NonUnify]
|
|
|
+public sealed partial class MdpIngestDatasetController(ISqlSugarClient db, UserManager user, SysOrgService organizations) : ControllerBase
|
|
|
+{
|
|
|
+ [HttpGet]
|
|
|
+ [DisplayName("查询接收数据集")]
|
|
|
+ public Task<IActionResult> List([FromQuery] long? factoryId) => WithScope(factoryId, async scope =>
|
|
|
+ {
|
|
|
+ var datasets = await Datasets(scope).OrderBy(x => x.DatasetKey).ToListAsync();
|
|
|
+ var sources = await db.Queryable<MdpSource>()
|
|
|
+ .Where(x => x.TenantId == scope.TenantId)
|
|
|
+ .OrderBy(x => x.SourceCode).ToListAsync();
|
|
|
+ var sourceById = sources.ToDictionary(x => x.Id);
|
|
|
+ var bindings = (await db.Queryable<MdpIngestDatasetSource>()
|
|
|
+ .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Enabled)
|
|
|
+ .ToListAsync()).ToLookup(x => x.DatasetId);
|
|
|
+ var versions = (await db.Queryable<MdpIngestDatasetVersion>()
|
|
|
+ .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
|
|
|
+ .OrderByDescending(x => x.Id).ToListAsync()).ToLookup(x => x.DatasetId);
|
|
|
+
|
|
|
+ var stopped = (await db.Ado.SqlQueryAsync<long>("""
|
|
|
+ SELECT d.id FROM mdp_ingest_dataset d JOIN mdp_ingest_lifecycle l ON l.dataset_id=d.id
|
|
|
+ WHERE d.tenant_id=@tenant AND d.factory_id=@factory AND l.state IN ('PAUSED','RETIRED')
|
|
|
+ """, new { tenant = scope.TenantId, factory = scope.FactoryId })).ToHashSet();
|
|
|
+ return Ok(new
|
|
|
+ {
|
|
|
+ factoryId = scope.FactoryId.ToString(),
|
|
|
+ factoryName = scope.FactoryName,
|
|
|
+ sources = sources.Select(x => new { id = x.Id.ToString(), x.SourceCode, x.SourceName, enabled = x.Status == 1 }),
|
|
|
+ list = datasets.Select(x => new
|
|
|
+ {
|
|
|
+ id = x.Id.ToString(),
|
|
|
+ x.DatasetKey,
|
|
|
+ x.Name,
|
|
|
+ enabled = x.Enabled && !stopped.Contains(x.Id),
|
|
|
+ x.ActiveSchemaVersion,
|
|
|
+ x.Revision,
|
|
|
+ versions = versions[x.Id].Select(version => version.SchemaVersion),
|
|
|
+ bindings = bindings[x.Id].Select(binding => new
|
|
|
+ {
|
|
|
+ sourceId = binding.SourceId.ToString(),
|
|
|
+ sourceName = sourceById.GetValueOrDefault(binding.SourceId)?.SourceName,
|
|
|
+ sourceEnabled = sourceById.GetValueOrDefault(binding.SourceId)?.Status == 1
|
|
|
+ })
|
|
|
+ })
|
|
|
+ });
|
|
|
+ });
|
|
|
+
|
|
|
+ [HttpPost]
|
|
|
+ [DisplayName("创建接收数据集")]
|
|
|
+ public Task<IActionResult> Create([FromBody] MdpCreateDatasetInput input, [FromQuery] long? factoryId) =>
|
|
|
+ WithScope(factoryId, async scope =>
|
|
|
+ {
|
|
|
+ var key = input.DatasetKey.Trim().ToLowerInvariant();
|
|
|
+ var name = input.Name.Trim();
|
|
|
+ if (name.Length == 0)
|
|
|
+ return BadRequest(new { message = "请输入数据集名称" });
|
|
|
+ var now = DateTime.UtcNow;
|
|
|
+ var dataset = new MdpIngestDataset
|
|
|
+ {
|
|
|
+ TenantId = scope.TenantId,
|
|
|
+ FactoryId = scope.FactoryId,
|
|
|
+ DatasetKey = key,
|
|
|
+ Name = name,
|
|
|
+ CreatedBy = user.UserId,
|
|
|
+ UpdatedBy = user.UserId,
|
|
|
+ CreatedAt = now,
|
|
|
+ UpdatedAt = now
|
|
|
+ };
|
|
|
+
|
|
|
+ try
|
|
|
+ {
|
|
|
+ var id = await db.Insertable(dataset).ExecuteReturnBigIdentityAsync();
|
|
|
+ return StatusCode(201, new { id = id.ToString() });
|
|
|
+ }
|
|
|
+ catch (Exception ex) when (ex is MySqlException { Number: 1062 } || ex.InnerException is MySqlException { Number: 1062 })
|
|
|
+ {
|
|
|
+ return Conflict(new { message = "当前工厂已存在该数据集编码" });
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ [HttpPut("{id:long}/sources/{sourceId:long}")]
|
|
|
+ [DisplayName("变更接收数据集来源绑定")]
|
|
|
+ public Task<IActionResult> SetSource(long id, long sourceId, [FromBody] MdpDatasetBindingInput input, [FromQuery] long? factoryId) =>
|
|
|
+ WithScope(factoryId, async scope =>
|
|
|
+ {
|
|
|
+ if (!await Datasets(scope).AnyAsync(x => x.Id == id))
|
|
|
+ return NotFound(new { message = "数据集不存在或不可访问" });
|
|
|
+
|
|
|
+ var now = DateTime.UtcNow;
|
|
|
+ var result = await db.Ado.UseTranAsync(async () =>
|
|
|
+ {
|
|
|
+ if (!await AdvanceRevision(scope, id, input.Revision, now))
|
|
|
+ return ChangeResult.Conflict;
|
|
|
+
|
|
|
+ if (await db.Ado.SqlQuerySingleAsync<string>("SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id }) == "RETIRED")
|
|
|
+ throw new DatasetChangeException("数据集已退役");
|
|
|
+ if (input.Enabled && !await db.Queryable<MdpSource>()
|
|
|
+ .AnyAsync(x => x.Id == sourceId && x.TenantId == scope.TenantId && x.Status == 1))
|
|
|
+ throw new DatasetChangeException("来源不存在、已停用或不在当前租户范围内");
|
|
|
+
|
|
|
+ var row = await db.Queryable<MdpIngestDatasetSource>()
|
|
|
+ .FirstAsync(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId
|
|
|
+ && x.DatasetId == id && x.SourceId == sourceId);
|
|
|
+ if (row == null && input.Enabled)
|
|
|
+ {
|
|
|
+ await db.Insertable(new MdpIngestDatasetSource
|
|
|
+ {
|
|
|
+ TenantId = scope.TenantId,
|
|
|
+ FactoryId = scope.FactoryId,
|
|
|
+ DatasetId = id,
|
|
|
+ SourceId = sourceId,
|
|
|
+ Enabled = true,
|
|
|
+ UpdatedBy = user.UserId,
|
|
|
+ UpdatedAt = now
|
|
|
+ }).ExecuteCommandAsync();
|
|
|
+ }
|
|
|
+ else if (row != null)
|
|
|
+ {
|
|
|
+ row.Enabled = input.Enabled;
|
|
|
+ row.UpdatedBy = user.UserId;
|
|
|
+ row.UpdatedAt = now;
|
|
|
+ await db.Updateable(row).ExecuteCommandAsync();
|
|
|
+ }
|
|
|
+
|
|
|
+ return ChangeResult.Saved;
|
|
|
+ });
|
|
|
+ return ChangeResponse(result);
|
|
|
+ });
|
|
|
+
|
|
|
+ private async Task<IActionResult> WithScope(long? requestedFactoryId, Func<DatasetScope, Task<IActionResult>> action)
|
|
|
+ {
|
|
|
+ var tenantId = AidopTenantScope.ResolveOrThrow(user);
|
|
|
+ var factories = await AuthorizedFactories(tenantId);
|
|
|
+ var factory = requestedFactoryId.HasValue
|
|
|
+ ? factories.SingleOrDefault(x => x.Id == requestedFactoryId)
|
|
|
+ : factories.FirstOrDefault(x => x.IsDefault) ?? (factories.Count == 1 ? factories[0] : null);
|
|
|
+ if (factory == null)
|
|
|
+ return StatusCode(requestedFactoryId.HasValue || factories.Count == 0 ? 403 : 400,
|
|
|
+ new { message = "请选择账号已获授权的有效工厂" });
|
|
|
+ return await action(new DatasetScope(tenantId, factory.Id, factory.Name));
|
|
|
+ }
|
|
|
+
|
|
|
+ private sealed class FactoryOption
|
|
|
+ {
|
|
|
+ public long Id { get; set; }
|
|
|
+ public string Name { get; set; } = "";
|
|
|
+ public bool IsDefault { get; set; }
|
|
|
+ }
|
|
|
+
|
|
|
+ private async Task<List<FactoryOption>> AuthorizedFactories(long tenant)
|
|
|
+ {
|
|
|
+ var rows = await db.Ado.SqlQueryAsync<FactoryOption>(
|
|
|
+ """
|
|
|
+ SELECT f.factory_id AS Id,o.Name,(f.factory_id=t.OrgId) AS IsDefault
|
|
|
+ FROM mdp_purchase_active_factory f JOIN SysOrg o ON o.Id=f.factory_id AND o.TenantId=f.tenant_id
|
|
|
+ JOIN SysTenant t ON t.Id=f.tenant_id WHERE f.tenant_id=@tenant ORDER BY o.Name,o.Id
|
|
|
+ """, new { tenant });
|
|
|
+ if (user.SuperAdmin) return rows;
|
|
|
+ var allowed = (await organizations.GetUserOrgIdList()).ToHashSet();
|
|
|
+ return rows.Where(x => allowed.Contains(x.Id)).ToList();
|
|
|
+ }
|
|
|
+
|
|
|
+ [HttpGet("factories")]
|
|
|
+ public async Task<IActionResult> Factories()
|
|
|
+ {
|
|
|
+ var rows = await AuthorizedFactories(AidopTenantScope.ResolveOrThrow(user));
|
|
|
+ return Ok(rows.Select(f => new { id = f.Id.ToString(), name = f.Name, isDefault = f.IsDefault }));
|
|
|
+ }
|
|
|
+
|
|
|
+ [HttpGet("factories/available")]
|
|
|
+ public async Task<IActionResult> AvailableFactoryOrganizations()
|
|
|
+ {
|
|
|
+ if (!user.SysAdmin && !user.SuperAdmin) return Ok(Array.Empty<object>());
|
|
|
+ var tenant = AidopTenantScope.ResolveOrThrow(user);
|
|
|
+ var options = await db.Ado.SqlQueryAsync<FactoryOption>("""
|
|
|
+ SELECT o.Id,o.Name FROM SysOrg o JOIN SysTenant t ON t.Id=o.TenantId AND t.Status=1
|
|
|
+ WHERE t.Id=@tenant AND o.Status=1 AND NOT EXISTS (SELECT 1 FROM mdp_purchase_active_factory f
|
|
|
+ WHERE f.tenant_id=t.Id AND f.factory_id=o.Id) ORDER BY o.Name,o.Id
|
|
|
+ """,new { tenant });
|
|
|
+ var allowed = user.SuperAdmin ? null : (await organizations.GetUserOrgIdList()).ToHashSet();
|
|
|
+ return Ok(options.Where(o => allowed == null || allowed.Contains(o.Id)).Select(o => new { id=o.Id.ToString(),o.Name }));
|
|
|
+ }
|
|
|
+
|
|
|
+ [HttpPost("factories/{id:long}")]
|
|
|
+ public async Task<IActionResult> RegisterFactory(long id)
|
|
|
+ {
|
|
|
+ if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
|
|
|
+ var tenant = AidopTenantScope.ResolveOrThrow(user);
|
|
|
+ if (!user.SuperAdmin && !(await organizations.GetUserOrgIdList()).Contains(id)) return Forbid();
|
|
|
+ var org = await db.Queryable<SysOrg>().FirstAsync(o => o.Id == id && o.TenantId == tenant && o.Status == StatusEnum.Enable);
|
|
|
+ if (org == null) return NotFound();
|
|
|
+ await db.Ado.ExecuteCommandAsync("""
|
|
|
+ INSERT INTO mdp_ingest_factory(tenant_id,factory_id,registered_by,registered_at)
|
|
|
+ VALUES (@tenant,@id,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE factory_id=VALUES(factory_id)
|
|
|
+ """, new { tenant, id, actor = user.UserId });
|
|
|
+ return NoContent();
|
|
|
+ }
|
|
|
+
|
|
|
+ private ISugarQueryable<MdpIngestDataset> Datasets(DatasetScope scope) =>
|
|
|
+ db.Queryable<MdpIngestDataset>().Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId);
|
|
|
+
|
|
|
+ private async Task<bool> AdvanceRevision(DatasetScope scope, long id, int revision, DateTime now)
|
|
|
+ {
|
|
|
+ var actor = user.UserId;
|
|
|
+ return await db.Updateable<MdpIngestDataset>()
|
|
|
+ .SetColumns(x => x.Revision == x.Revision + 1)
|
|
|
+ .SetColumns(x => x.UpdatedBy == actor)
|
|
|
+ .SetColumns(x => x.UpdatedAt == now)
|
|
|
+ .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Revision == revision)
|
|
|
+ .ExecuteCommandAsync() == 1;
|
|
|
+ }
|
|
|
+
|
|
|
+ private IActionResult ChangeResponse(DbResult<ChangeResult> result)
|
|
|
+ {
|
|
|
+ if (result.ErrorException is DatasetChangeException validation)
|
|
|
+ return BadRequest(new { message = validation.Message });
|
|
|
+ if (!result.IsSuccess)
|
|
|
+ throw result.ErrorException ?? Oops.Oh("保存接收数据集失败");
|
|
|
+ return result.Data == ChangeResult.Conflict
|
|
|
+ ? Conflict(new { message = "数据集已变更,请刷新后重试" })
|
|
|
+ : NoContent();
|
|
|
+ }
|
|
|
+
|
|
|
+ private sealed record DatasetScope(long TenantId, long FactoryId, string FactoryName);
|
|
|
+ private enum ChangeResult { Saved, Conflict }
|
|
|
+ private sealed class DatasetChangeException(string message) : Exception(message);
|
|
|
+}
|
|
|
+
|
|
|
+public sealed class MdpCreateDatasetInput
|
|
|
+{
|
|
|
+ [Required, StringLength(80), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
|
|
|
+ public string DatasetKey { get; set; } = string.Empty;
|
|
|
+
|
|
|
+ [Required, StringLength(120)]
|
|
|
+ public string Name { get; set; } = string.Empty;
|
|
|
+}
|
|
|
+
|
|
|
+public sealed class MdpDatasetBindingInput
|
|
|
+{
|
|
|
+ [Range(1, int.MaxValue)]
|
|
|
+ public int Revision { get; set; }
|
|
|
+
|
|
|
+ [JsonRequired, Newtonsoft.Json.JsonRequired]
|
|
|
+ public bool Enabled { get; set; }
|
|
|
+}
|