MdpIngestDatasetController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using Admin.NET.Core.Service;
  2. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  3. using MySqlConnector;
  4. using System.Text.Json.Serialization;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. [ApiController]
  7. [Authorize]
  8. [RequirePcMenuPath("/aidop/data-platform/sources")]
  9. [Route("api/DataPlatform/ingest-datasets")]
  10. [NonUnify]
  11. public sealed partial class MdpIngestDatasetController(ISqlSugarClient db, UserManager user, SysOrgService organizations) : ControllerBase
  12. {
  13. [HttpGet]
  14. [DisplayName("查询接收数据集")]
  15. public Task<IActionResult> List([FromQuery] long? factoryId) => WithScope(factoryId, async scope =>
  16. {
  17. var datasets = await Datasets(scope).OrderBy(x => x.DatasetKey).ToListAsync();
  18. var sources = await db.Queryable<MdpSource>()
  19. .Where(x => x.TenantId == scope.TenantId)
  20. .OrderBy(x => x.SourceCode).ToListAsync();
  21. var sourceById = sources.ToDictionary(x => x.Id);
  22. var bindings = (await db.Queryable<MdpIngestDatasetSource>()
  23. .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Enabled)
  24. .ToListAsync()).ToLookup(x => x.DatasetId);
  25. var versions = (await db.Queryable<MdpIngestDatasetVersion>()
  26. .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
  27. .OrderByDescending(x => x.Id).ToListAsync()).ToLookup(x => x.DatasetId);
  28. var stopped = (await db.Ado.SqlQueryAsync<long>("""
  29. SELECT d.id FROM mdp_ingest_dataset d JOIN mdp_ingest_lifecycle l ON l.dataset_id=d.id
  30. WHERE d.tenant_id=@tenant AND d.factory_id=@factory AND l.state IN ('PAUSED','RETIRED')
  31. """, new { tenant = scope.TenantId, factory = scope.FactoryId })).ToHashSet();
  32. return Ok(new
  33. {
  34. factoryId = scope.FactoryId.ToString(),
  35. factoryName = scope.FactoryName,
  36. sources = sources.Select(x => new { id = x.Id.ToString(), x.SourceCode, x.SourceName, enabled = x.Status == 1 }),
  37. list = datasets.Select(x => new
  38. {
  39. id = x.Id.ToString(),
  40. x.DatasetKey,
  41. x.Name,
  42. enabled = x.Enabled && !stopped.Contains(x.Id),
  43. x.ActiveSchemaVersion,
  44. x.Revision,
  45. versions = versions[x.Id].Select(version => version.SchemaVersion),
  46. bindings = bindings[x.Id].Select(binding => new
  47. {
  48. sourceId = binding.SourceId.ToString(),
  49. sourceName = sourceById.GetValueOrDefault(binding.SourceId)?.SourceName,
  50. sourceEnabled = sourceById.GetValueOrDefault(binding.SourceId)?.Status == 1
  51. })
  52. })
  53. });
  54. });
  55. [HttpPost]
  56. [DisplayName("创建接收数据集")]
  57. public Task<IActionResult> Create([FromBody] MdpCreateDatasetInput input, [FromQuery] long? factoryId) =>
  58. WithScope(factoryId, async scope =>
  59. {
  60. var key = input.DatasetKey.Trim().ToLowerInvariant();
  61. var name = input.Name.Trim();
  62. if (name.Length == 0)
  63. return BadRequest(new { message = "请输入数据集名称" });
  64. var now = DateTime.UtcNow;
  65. var dataset = new MdpIngestDataset
  66. {
  67. TenantId = scope.TenantId,
  68. FactoryId = scope.FactoryId,
  69. DatasetKey = key,
  70. Name = name,
  71. CreatedBy = user.UserId,
  72. UpdatedBy = user.UserId,
  73. CreatedAt = now,
  74. UpdatedAt = now
  75. };
  76. try
  77. {
  78. var id = await db.Insertable(dataset).ExecuteReturnBigIdentityAsync();
  79. return StatusCode(201, new { id = id.ToString() });
  80. }
  81. catch (Exception ex) when (ex is MySqlException { Number: 1062 } || ex.InnerException is MySqlException { Number: 1062 })
  82. {
  83. return Conflict(new { message = "当前工厂已存在该数据集编码" });
  84. }
  85. });
  86. [HttpPut("{id:long}/sources/{sourceId:long}")]
  87. [DisplayName("变更接收数据集来源绑定")]
  88. public Task<IActionResult> SetSource(long id, long sourceId, [FromBody] MdpDatasetBindingInput input, [FromQuery] long? factoryId) =>
  89. WithScope(factoryId, async scope =>
  90. {
  91. if (!await Datasets(scope).AnyAsync(x => x.Id == id))
  92. return NotFound(new { message = "数据集不存在或不可访问" });
  93. var now = DateTime.UtcNow;
  94. var result = await db.Ado.UseTranAsync(async () =>
  95. {
  96. if (!await AdvanceRevision(scope, id, input.Revision, now))
  97. return ChangeResult.Conflict;
  98. Require(await Lifecycle(id) != "RETIRED","数据集已退役");
  99. if (input.Enabled && !await db.Queryable<MdpSource>()
  100. .AnyAsync(x => x.Id == sourceId && x.TenantId == scope.TenantId && x.Status == 1))
  101. throw new DatasetChangeException("来源不存在、已停用或不在当前租户范围内");
  102. var row = await db.Queryable<MdpIngestDatasetSource>()
  103. .FirstAsync(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId
  104. && x.DatasetId == id && x.SourceId == sourceId);
  105. if (row == null && input.Enabled)
  106. {
  107. await db.Insertable(new MdpIngestDatasetSource
  108. {
  109. TenantId = scope.TenantId,
  110. FactoryId = scope.FactoryId,
  111. DatasetId = id,
  112. SourceId = sourceId,
  113. Enabled = true,
  114. UpdatedBy = user.UserId,
  115. UpdatedAt = now
  116. }).ExecuteCommandAsync();
  117. }
  118. else if (row != null)
  119. {
  120. row.Enabled = input.Enabled;
  121. row.UpdatedBy = user.UserId;
  122. row.UpdatedAt = now;
  123. await db.Updateable(row).ExecuteCommandAsync();
  124. }
  125. return ChangeResult.Saved;
  126. });
  127. return ChangeResponse(result);
  128. });
  129. [HttpPut("{id:long}/state")]
  130. [DisplayName("启停接收数据集或切换版本")]
  131. public Task<IActionResult> SetState(long id, [FromBody] MdpDatasetStateInput input, [FromQuery] long? factoryId) =>
  132. input.Enabled
  133. ? WithScope(factoryId, async scope =>
  134. {
  135. if (!await Can(PublishPermission)) return Forbid();
  136. var row = await Datasets(scope).FirstAsync(x => x.Id == id);
  137. if (row == null) return NotFound();
  138. if (row.Enabled && await Lifecycle(id) != "PAUSED" && row.ActiveSchemaVersion == input.SchemaVersion && row.Revision == input.Revision)
  139. return NoContent();
  140. return Conflict(new { message = "请在版本工作区完成试跑、对账、审批后启用" });
  141. })
  142. : LifecycleAction(id, "pause", factoryId, new(input.Revision, "通过接收数据集停用"));
  143. private async Task<IActionResult> WithScope(long? requestedFactoryId, Func<DatasetScope, Task<IActionResult>> action)
  144. {
  145. var tenantId = AidopTenantScope.ResolveOrThrow(user);
  146. var factories = await AuthorizedFactories(tenantId);
  147. var factory = requestedFactoryId.HasValue
  148. ? factories.SingleOrDefault(x => x.Id == requestedFactoryId)
  149. : factories.FirstOrDefault(x => x.IsDefault) ?? (factories.Count == 1 ? factories[0] : null);
  150. if (factory == null)
  151. return StatusCode(requestedFactoryId.HasValue || factories.Count == 0 ? 403 : 400,
  152. new { message = "请选择账号已获授权的有效工厂" });
  153. return await action(new DatasetScope(tenantId, factory.Id, factory.Name));
  154. }
  155. private sealed class FactoryOption
  156. {
  157. public long Id { get; set; }
  158. public string Name { get; set; } = "";
  159. public bool IsDefault { get; set; }
  160. }
  161. private async Task<List<FactoryOption>> AuthorizedFactories(long tenant)
  162. {
  163. var rows = await db.Ado.SqlQueryAsync<FactoryOption>(
  164. """
  165. SELECT f.factory_id AS Id,o.Name,(f.factory_id=t.OrgId) AS IsDefault
  166. FROM mdp_purchase_active_factory f JOIN SysOrg o ON o.Id=f.factory_id AND o.TenantId=f.tenant_id
  167. JOIN SysTenant t ON t.Id=f.tenant_id WHERE f.tenant_id=@tenant ORDER BY o.Name,o.Id
  168. """, new { tenant });
  169. if (user.SuperAdmin) return rows;
  170. var allowed = (await organizations.GetUserOrgIdList()).ToHashSet();
  171. return rows.Where(x => allowed.Contains(x.Id)).ToList();
  172. }
  173. [HttpGet("factories")]
  174. public async Task<IActionResult> Factories()
  175. {
  176. var rows = await AuthorizedFactories(AidopTenantScope.ResolveOrThrow(user));
  177. return Ok(rows.Select(f => new { id = f.Id.ToString(), name = f.Name, isDefault = f.IsDefault }));
  178. }
  179. [HttpGet("factories/available")]
  180. public async Task<IActionResult> AvailableFactoryOrganizations()
  181. {
  182. if (!user.SysAdmin && !user.SuperAdmin) return Ok(Array.Empty<object>());
  183. var tenant = AidopTenantScope.ResolveOrThrow(user);
  184. var options = await db.Ado.SqlQueryAsync<FactoryOption>("""
  185. SELECT o.Id,o.Name FROM SysOrg o JOIN SysTenant t ON t.Id=o.TenantId AND t.Status=1
  186. WHERE t.Id=@tenant AND o.Status=1 AND NOT EXISTS (SELECT 1 FROM mdp_purchase_active_factory f
  187. WHERE f.tenant_id=t.Id AND f.factory_id=o.Id) ORDER BY o.Name,o.Id
  188. """,new { tenant });
  189. var allowed = user.SuperAdmin ? null : (await organizations.GetUserOrgIdList()).ToHashSet();
  190. return Ok(options.Where(o => allowed == null || allowed.Contains(o.Id)).Select(o => new { id=o.Id.ToString(),o.Name }));
  191. }
  192. [HttpPost("factories/{id:long}")]
  193. public async Task<IActionResult> RegisterFactory(long id)
  194. {
  195. if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
  196. var tenant = AidopTenantScope.ResolveOrThrow(user);
  197. if (!user.SuperAdmin && !(await organizations.GetUserOrgIdList()).Contains(id)) return Forbid();
  198. var org = await db.Queryable<SysOrg>().FirstAsync(o => o.Id == id && o.TenantId == tenant && o.Status == StatusEnum.Enable);
  199. if (org == null) return NotFound();
  200. await db.Ado.ExecuteCommandAsync("""
  201. INSERT INTO mdp_ingest_factory(tenant_id,factory_id,registered_by,registered_at)
  202. VALUES (@tenant,@id,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE factory_id=VALUES(factory_id)
  203. """, new { tenant, id, actor = user.UserId });
  204. return NoContent();
  205. }
  206. private ISugarQueryable<MdpIngestDataset> Datasets(DatasetScope scope) =>
  207. db.Queryable<MdpIngestDataset>().Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId);
  208. private async Task<bool> AdvanceRevision(DatasetScope scope, long id, int revision, DateTime now)
  209. {
  210. var actor = user.UserId;
  211. return await db.Updateable<MdpIngestDataset>()
  212. .SetColumns(x => x.Revision == x.Revision + 1)
  213. .SetColumns(x => x.UpdatedBy == actor)
  214. .SetColumns(x => x.UpdatedAt == now)
  215. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Revision == revision)
  216. .ExecuteCommandAsync() == 1;
  217. }
  218. private IActionResult ChangeResponse(DbResult<ChangeResult> result)
  219. {
  220. if (result.ErrorException is DatasetChangeException validation)
  221. return BadRequest(new { message = validation.Message });
  222. if (!result.IsSuccess)
  223. throw result.ErrorException ?? Oops.Oh("保存接收数据集失败");
  224. return result.Data == ChangeResult.Conflict
  225. ? Conflict(new { message = "数据集已变更,请刷新后重试" })
  226. : NoContent();
  227. }
  228. private sealed record DatasetScope(long TenantId, long FactoryId, string FactoryName);
  229. private enum ChangeResult { Saved, Conflict }
  230. private sealed class DatasetChangeException(string message) : Exception(message);
  231. }
  232. public sealed class MdpCreateDatasetInput
  233. {
  234. [Required, StringLength(80), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
  235. public string DatasetKey { get; set; } = string.Empty;
  236. [Required, StringLength(120)]
  237. public string Name { get; set; } = string.Empty;
  238. }
  239. public sealed class MdpDatasetBindingInput
  240. {
  241. [Range(1, int.MaxValue)]
  242. public int Revision { get; set; }
  243. [JsonRequired, Newtonsoft.Json.JsonRequired]
  244. public bool Enabled { get; set; }
  245. }
  246. public sealed class MdpDatasetStateInput
  247. {
  248. [Range(1, int.MaxValue)]
  249. public int Revision { get; set; }
  250. [JsonRequired, Newtonsoft.Json.JsonRequired]
  251. public bool Enabled { get; set; }
  252. [StringLength(64), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
  253. public string? SchemaVersion { get; set; }
  254. }