MdpIngestDatasetController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. if (await db.Ado.SqlQuerySingleAsync<string>("SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id }) == "RETIRED")
  99. throw new DatasetChangeException("数据集已退役");
  100. if (input.Enabled && !await db.Queryable<MdpSource>()
  101. .AnyAsync(x => x.Id == sourceId && x.TenantId == scope.TenantId && x.Status == 1))
  102. throw new DatasetChangeException("来源不存在、已停用或不在当前租户范围内");
  103. var row = await db.Queryable<MdpIngestDatasetSource>()
  104. .FirstAsync(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId
  105. && x.DatasetId == id && x.SourceId == sourceId);
  106. if (row == null && input.Enabled)
  107. {
  108. await db.Insertable(new MdpIngestDatasetSource
  109. {
  110. TenantId = scope.TenantId,
  111. FactoryId = scope.FactoryId,
  112. DatasetId = id,
  113. SourceId = sourceId,
  114. Enabled = true,
  115. UpdatedBy = user.UserId,
  116. UpdatedAt = now
  117. }).ExecuteCommandAsync();
  118. }
  119. else if (row != null)
  120. {
  121. row.Enabled = input.Enabled;
  122. row.UpdatedBy = user.UserId;
  123. row.UpdatedAt = now;
  124. await db.Updateable(row).ExecuteCommandAsync();
  125. }
  126. return ChangeResult.Saved;
  127. });
  128. return ChangeResponse(result);
  129. });
  130. private async Task<IActionResult> WithScope(long? requestedFactoryId, Func<DatasetScope, Task<IActionResult>> action)
  131. {
  132. var tenantId = AidopTenantScope.ResolveOrThrow(user);
  133. var factories = await AuthorizedFactories(tenantId);
  134. var factory = requestedFactoryId.HasValue
  135. ? factories.SingleOrDefault(x => x.Id == requestedFactoryId)
  136. : factories.FirstOrDefault(x => x.IsDefault) ?? (factories.Count == 1 ? factories[0] : null);
  137. if (factory == null)
  138. return StatusCode(requestedFactoryId.HasValue || factories.Count == 0 ? 403 : 400,
  139. new { message = "请选择账号已获授权的有效工厂" });
  140. return await action(new DatasetScope(tenantId, factory.Id, factory.Name));
  141. }
  142. private sealed class FactoryOption
  143. {
  144. public long Id { get; set; }
  145. public string Name { get; set; } = "";
  146. public bool IsDefault { get; set; }
  147. }
  148. private async Task<List<FactoryOption>> AuthorizedFactories(long tenant)
  149. {
  150. var rows = await db.Ado.SqlQueryAsync<FactoryOption>(
  151. """
  152. SELECT f.factory_id AS Id,o.Name,(f.factory_id=t.OrgId) AS IsDefault
  153. FROM mdp_purchase_active_factory f JOIN SysOrg o ON o.Id=f.factory_id AND o.TenantId=f.tenant_id
  154. JOIN SysTenant t ON t.Id=f.tenant_id WHERE f.tenant_id=@tenant ORDER BY o.Name,o.Id
  155. """, new { tenant });
  156. if (user.SuperAdmin) return rows;
  157. var allowed = (await organizations.GetUserOrgIdList()).ToHashSet();
  158. return rows.Where(x => allowed.Contains(x.Id)).ToList();
  159. }
  160. [HttpGet("factories")]
  161. public async Task<IActionResult> Factories()
  162. {
  163. var rows = await AuthorizedFactories(AidopTenantScope.ResolveOrThrow(user));
  164. return Ok(rows.Select(f => new { id = f.Id.ToString(), name = f.Name, isDefault = f.IsDefault }));
  165. }
  166. [HttpGet("factories/available")]
  167. public async Task<IActionResult> AvailableFactoryOrganizations()
  168. {
  169. if (!user.SysAdmin && !user.SuperAdmin) return Ok(Array.Empty<object>());
  170. var tenant = AidopTenantScope.ResolveOrThrow(user);
  171. var options = await db.Ado.SqlQueryAsync<FactoryOption>("""
  172. SELECT o.Id,o.Name FROM SysOrg o JOIN SysTenant t ON t.Id=o.TenantId AND t.Status=1
  173. WHERE t.Id=@tenant AND o.Status=1 AND NOT EXISTS (SELECT 1 FROM mdp_purchase_active_factory f
  174. WHERE f.tenant_id=t.Id AND f.factory_id=o.Id) ORDER BY o.Name,o.Id
  175. """,new { tenant });
  176. var allowed = user.SuperAdmin ? null : (await organizations.GetUserOrgIdList()).ToHashSet();
  177. return Ok(options.Where(o => allowed == null || allowed.Contains(o.Id)).Select(o => new { id=o.Id.ToString(),o.Name }));
  178. }
  179. [HttpPost("factories/{id:long}")]
  180. public async Task<IActionResult> RegisterFactory(long id)
  181. {
  182. if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
  183. var tenant = AidopTenantScope.ResolveOrThrow(user);
  184. if (!user.SuperAdmin && !(await organizations.GetUserOrgIdList()).Contains(id)) return Forbid();
  185. var org = await db.Queryable<SysOrg>().FirstAsync(o => o.Id == id && o.TenantId == tenant && o.Status == StatusEnum.Enable);
  186. if (org == null) return NotFound();
  187. await db.Ado.ExecuteCommandAsync("""
  188. INSERT INTO mdp_ingest_factory(tenant_id,factory_id,registered_by,registered_at)
  189. VALUES (@tenant,@id,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE factory_id=VALUES(factory_id)
  190. """, new { tenant, id, actor = user.UserId });
  191. return NoContent();
  192. }
  193. private ISugarQueryable<MdpIngestDataset> Datasets(DatasetScope scope) =>
  194. db.Queryable<MdpIngestDataset>().Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId);
  195. private async Task<bool> AdvanceRevision(DatasetScope scope, long id, int revision, DateTime now)
  196. {
  197. var actor = user.UserId;
  198. return await db.Updateable<MdpIngestDataset>()
  199. .SetColumns(x => x.Revision == x.Revision + 1)
  200. .SetColumns(x => x.UpdatedBy == actor)
  201. .SetColumns(x => x.UpdatedAt == now)
  202. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Revision == revision)
  203. .ExecuteCommandAsync() == 1;
  204. }
  205. private IActionResult ChangeResponse(DbResult<ChangeResult> result)
  206. {
  207. if (result.ErrorException is DatasetChangeException validation)
  208. return BadRequest(new { message = validation.Message });
  209. if (!result.IsSuccess)
  210. throw result.ErrorException ?? Oops.Oh("保存接收数据集失败");
  211. return result.Data == ChangeResult.Conflict
  212. ? Conflict(new { message = "数据集已变更,请刷新后重试" })
  213. : NoContent();
  214. }
  215. private sealed record DatasetScope(long TenantId, long FactoryId, string FactoryName);
  216. private enum ChangeResult { Saved, Conflict }
  217. private sealed class DatasetChangeException(string message) : Exception(message);
  218. }
  219. public sealed class MdpCreateDatasetInput
  220. {
  221. [Required, StringLength(80), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
  222. public string DatasetKey { get; set; } = string.Empty;
  223. [Required, StringLength(120)]
  224. public string Name { get; set; } = string.Empty;
  225. }
  226. public sealed class MdpDatasetBindingInput
  227. {
  228. [Range(1, int.MaxValue)]
  229. public int Revision { get; set; }
  230. [JsonRequired, Newtonsoft.Json.JsonRequired]
  231. public bool Enabled { get; set; }
  232. }