MdpIngestDatasetController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. [HttpPost("purchase-migrations")]
  144. [DisplayName("登记采购迁移范围")]
  145. public Task<IActionResult> RegisterPurchaseMigration([FromBody] PurchaseMigrationRegistration input, [FromQuery] long? factoryId) =>
  146. WithMigrationScope(factoryId, (service, scope) => service.RegisterAsync(scope.TenantId, scope.FactoryId, user.UserId, input));
  147. [HttpGet("purchase-migrations/{id:long}")]
  148. [DisplayName("查询采购迁移水位")]
  149. public Task<IActionResult> GetPurchaseMigration(long id, [FromQuery] long? factoryId) =>
  150. WithMigrationScope(factoryId, (service, scope) => service.ReadAsync(scope.TenantId, scope.FactoryId, id));
  151. [HttpPut("purchase-migrations/{id:long}/state")]
  152. [DisplayName("冻结或切换采购写入权")]
  153. public Task<IActionResult> ChangePurchaseMigration(long id, [FromBody] PurchaseMigrationChange input, [FromQuery] long? factoryId) =>
  154. WithMigrationScope(factoryId, (service, scope) => service.ChangeAsync(scope.TenantId, scope.FactoryId, user.UserId, id, input));
  155. private Task<IActionResult> WithMigrationScope(long? factoryId, Func<MdpPurchaseMigrationService, DatasetScope, Task<PurchaseMigrationState>> action) =>
  156. WithScope(factoryId, async scope =>
  157. {
  158. if (!user.SuperAdmin && !user.SysAdmin)
  159. return StatusCode(403, new { code = "PURCHASE_MIGRATION_ADMIN_REQUIRED" });
  160. try
  161. {
  162. var state = await action(new MdpPurchaseMigrationService(db), scope);
  163. return Ok(state);
  164. }
  165. catch (MdpIngestHttpException error)
  166. {
  167. return StatusCode(error.StatusCode, new { code = error.Code });
  168. }
  169. catch (MySqlException error) when (error.Number == 1062)
  170. {
  171. return Conflict(new { code = "PURCHASE_MIGRATION_ALREADY_REGISTERED" });
  172. }
  173. });
  174. private async Task<IActionResult> WithScope(long? requestedFactoryId, Func<DatasetScope, Task<IActionResult>> action)
  175. {
  176. var tenantId = AidopTenantScope.ResolveOrThrow(user);
  177. var factories = await AuthorizedFactories(tenantId);
  178. var factory = requestedFactoryId.HasValue
  179. ? factories.SingleOrDefault(x => x.Id == requestedFactoryId)
  180. : factories.FirstOrDefault(x => x.IsDefault) ?? (factories.Count == 1 ? factories[0] : null);
  181. if (factory == null)
  182. return StatusCode(requestedFactoryId.HasValue || factories.Count == 0 ? 403 : 400,
  183. new { message = "请选择账号已获授权的有效工厂" });
  184. return await action(new DatasetScope(tenantId, factory.Id, factory.Name));
  185. }
  186. private sealed class FactoryOption
  187. {
  188. public long Id { get; set; }
  189. public string Name { get; set; } = "";
  190. public bool IsDefault { get; set; }
  191. }
  192. private async Task<List<FactoryOption>> AuthorizedFactories(long tenant)
  193. {
  194. var rows = await db.Ado.SqlQueryAsync<FactoryOption>(
  195. """
  196. SELECT f.factory_id AS Id,o.Name,(f.factory_id=t.OrgId) AS IsDefault
  197. FROM mdp_purchase_active_factory f JOIN SysOrg o ON o.Id=f.factory_id AND o.TenantId=f.tenant_id
  198. JOIN SysTenant t ON t.Id=f.tenant_id WHERE f.tenant_id=@tenant ORDER BY o.Name,o.Id
  199. """, new { tenant });
  200. if (user.SuperAdmin) return rows;
  201. var allowed = (await organizations.GetUserOrgIdList()).ToHashSet();
  202. return rows.Where(x => allowed.Contains(x.Id)).ToList();
  203. }
  204. [HttpGet("factories")]
  205. public async Task<IActionResult> Factories()
  206. {
  207. var rows = await AuthorizedFactories(AidopTenantScope.ResolveOrThrow(user));
  208. return Ok(rows.Select(f => new { id = f.Id.ToString(), name = f.Name, isDefault = f.IsDefault }));
  209. }
  210. [HttpGet("factories/available")]
  211. public async Task<IActionResult> AvailableFactoryOrganizations()
  212. {
  213. if (!user.SysAdmin && !user.SuperAdmin) return Ok(Array.Empty<object>());
  214. var tenant = AidopTenantScope.ResolveOrThrow(user);
  215. var options = await db.Ado.SqlQueryAsync<FactoryOption>("""
  216. SELECT o.Id,o.Name FROM SysOrg o JOIN SysTenant t ON t.Id=o.TenantId AND t.Status=1
  217. WHERE t.Id=@tenant AND o.Status=1 AND NOT EXISTS (SELECT 1 FROM mdp_purchase_active_factory f
  218. WHERE f.tenant_id=t.Id AND f.factory_id=o.Id) ORDER BY o.Name,o.Id
  219. """,new { tenant });
  220. var allowed = user.SuperAdmin ? null : (await organizations.GetUserOrgIdList()).ToHashSet();
  221. return Ok(options.Where(o => allowed == null || allowed.Contains(o.Id)).Select(o => new { id=o.Id.ToString(),o.Name }));
  222. }
  223. [HttpPost("factories/{id:long}")]
  224. public async Task<IActionResult> RegisterFactory(long id)
  225. {
  226. if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
  227. var tenant = AidopTenantScope.ResolveOrThrow(user);
  228. if (!user.SuperAdmin && !(await organizations.GetUserOrgIdList()).Contains(id)) return Forbid();
  229. var org = await db.Queryable<SysOrg>().FirstAsync(o => o.Id == id && o.TenantId == tenant && o.Status == StatusEnum.Enable);
  230. if (org == null) return NotFound();
  231. await db.Ado.ExecuteCommandAsync("""
  232. INSERT INTO mdp_ingest_factory(tenant_id,factory_id,registered_by,registered_at)
  233. VALUES (@tenant,@id,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE factory_id=VALUES(factory_id)
  234. """, new { tenant, id, actor = user.UserId });
  235. return NoContent();
  236. }
  237. private ISugarQueryable<MdpIngestDataset> Datasets(DatasetScope scope) =>
  238. db.Queryable<MdpIngestDataset>().Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId);
  239. private async Task<bool> AdvanceRevision(DatasetScope scope, long id, int revision, DateTime now)
  240. {
  241. var actor = user.UserId;
  242. return await db.Updateable<MdpIngestDataset>()
  243. .SetColumns(x => x.Revision == x.Revision + 1)
  244. .SetColumns(x => x.UpdatedBy == actor)
  245. .SetColumns(x => x.UpdatedAt == now)
  246. .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Revision == revision)
  247. .ExecuteCommandAsync() == 1;
  248. }
  249. private IActionResult ChangeResponse(DbResult<ChangeResult> result)
  250. {
  251. if (result.ErrorException is DatasetChangeException validation)
  252. return BadRequest(new { message = validation.Message });
  253. if (!result.IsSuccess)
  254. throw result.ErrorException ?? Oops.Oh("保存接收数据集失败");
  255. return result.Data == ChangeResult.Conflict
  256. ? Conflict(new { message = "数据集已变更,请刷新后重试" })
  257. : NoContent();
  258. }
  259. private sealed record DatasetScope(long TenantId, long FactoryId, string FactoryName);
  260. private enum ChangeResult { Saved, Conflict }
  261. private sealed class DatasetChangeException(string message) : Exception(message);
  262. }
  263. public sealed class MdpCreateDatasetInput
  264. {
  265. [Required, StringLength(80), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
  266. public string DatasetKey { get; set; } = string.Empty;
  267. [Required, StringLength(120)]
  268. public string Name { get; set; } = string.Empty;
  269. }
  270. public sealed class MdpDatasetBindingInput
  271. {
  272. [Range(1, int.MaxValue)]
  273. public int Revision { get; set; }
  274. [JsonRequired, Newtonsoft.Json.JsonRequired]
  275. public bool Enabled { get; set; }
  276. }
  277. public sealed class MdpDatasetStateInput
  278. {
  279. [Range(1, int.MaxValue)]
  280. public int Revision { get; set; }
  281. [JsonRequired, Newtonsoft.Json.JsonRequired]
  282. public bool Enabled { get; set; }
  283. [StringLength(64), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
  284. public string? SchemaVersion { get; set; }
  285. }