MdpIngestDatasetController.cs 16 KB

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