MdpSourceMappingService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. using Admin.NET.Core;
  2. using Admin.NET.Core.Service;
  3. using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
  4. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  5. using Yitter.IdGenerator;
  6. namespace Admin.NET.Plugin.AiDOP.DataPlatform;
  7. /// <summary>
  8. /// 来源映射维护:归属、库位角色、岗位、事务类型、来源能力、推送授权。
  9. /// 页面写入库位角色和岗位时 role_source 固定为 MANUAL,避免被自动分类冲掉。
  10. /// </summary>
  11. [ApiDescriptionSettings(Order = 326, Description = "来源映射维护")]
  12. [Route("api/DataPlatform")]
  13. [NonUnify]
  14. public class MdpSourceMappingService : IDynamicApiController, ITransient
  15. {
  16. private readonly ISqlSugarClient _db;
  17. private readonly UserManager _user;
  18. private readonly SysCacheService _cache;
  19. public MdpSourceMappingService(ISqlSugarClient db, UserManager user, SysCacheService cache)
  20. {
  21. _db = db;
  22. _user = user;
  23. _cache = cache;
  24. }
  25. private long ScopeTenant(long? requested)
  26. {
  27. if (_user.SuperAdmin || _user.SysAdmin)
  28. return requested is > 0 ? requested.Value : _user.TenantId;
  29. if (requested is > 0 && requested.Value != _user.TenantId)
  30. throw Oops.Oh("不能查看或修改其他租户的对接配置");
  31. return _user.TenantId;
  32. }
  33. [HttpGet("source-domain-maps")]
  34. public Task<List<dynamic>> ListDomainMaps([FromQuery] long? tenantId)
  35. {
  36. var tenant = ScopeTenant(tenantId);
  37. return _db.Ado.SqlQueryAsync<dynamic>(
  38. """
  39. SELECT id, system_code AS systemCode, source_code AS sourceCode, domain, tenant_id AS tenantId, status, remark
  40. FROM ado_source_domain_tenant_map
  41. WHERE tenant_id=@tenant
  42. ORDER BY system_code, domain
  43. """,
  44. new { tenant });
  45. }
  46. [HttpPut("source-domain-maps")]
  47. public async Task<object> SaveDomainMap([FromBody] DomainMapInput input)
  48. {
  49. var tenant = ScopeTenant(input.TenantId);
  50. if (string.IsNullOrWhiteSpace(input.SystemCode) || string.IsNullOrWhiteSpace(input.Domain))
  51. throw Oops.Oh("systemCode 与 domain 必填");
  52. var clash = await _db.Ado.SqlQueryAsync<long>(
  53. """
  54. SELECT tenant_id FROM ado_source_domain_tenant_map
  55. WHERE system_code=@sys AND domain=@dom AND status=1 AND tenant_id<>@tenant
  56. LIMIT 1
  57. """,
  58. new { sys = input.SystemCode.Trim(), dom = input.Domain.Trim(), tenant });
  59. if (clash.Count > 0)
  60. throw Oops.Oh($"该来源范围已归属租户 {clash[0]}。多个租户共享同一范围时按库位划分,不要改这里。");
  61. await _db.Ado.ExecuteCommandAsync(
  62. """
  63. INSERT INTO ado_source_domain_tenant_map (system_code, source_code, domain, tenant_id, status, remark)
  64. VALUES (@sys, @src, @dom, @tenant, 1, @remark)
  65. ON DUPLICATE KEY UPDATE source_code=VALUES(source_code), status=1, remark=VALUES(remark), tenant_id=VALUES(tenant_id)
  66. """,
  67. new
  68. {
  69. sys = input.SystemCode.Trim(),
  70. src = string.IsNullOrWhiteSpace(input.SourceCode) ? input.SystemCode.Trim() : input.SourceCode.Trim(),
  71. dom = input.Domain.Trim(),
  72. tenant,
  73. remark = input.Remark
  74. });
  75. return new { ok = true };
  76. }
  77. [HttpGet("location-roles")]
  78. public Task<List<dynamic>> ListLocations([FromQuery] long? tenantId, [FromQuery] string? domain, [FromQuery] bool unknownOnly = false)
  79. {
  80. var tenant = ScopeTenant(tenantId);
  81. return _db.Ado.SqlQueryAsync<dynamic>(
  82. """
  83. SELECT id, tenant_id AS tenantId, domain, location, location_role AS locationRole, role_source AS roleSource, remark
  84. FROM mdp_location_role
  85. WHERE tenant_id=@tenant
  86. AND (@dom = '' OR domain=@dom)
  87. AND (@unk = 0 OR location_role='UNKNOWN')
  88. ORDER BY domain, location
  89. LIMIT 500
  90. """,
  91. new { tenant, dom = domain?.Trim() ?? "", unk = unknownOnly ? 1 : 0 });
  92. }
  93. [HttpPut("location-roles")]
  94. public async Task<object> SaveLocations([FromBody] LocationRoleInput input)
  95. {
  96. var tenant = ScopeTenant(input.TenantId);
  97. if (input.Rows == null || input.Rows.Count == 0)
  98. throw Oops.Oh("没有要保存的行");
  99. var n = 0;
  100. foreach (var row in input.Rows)
  101. {
  102. if (string.IsNullOrWhiteSpace(row.Location) || string.IsNullOrWhiteSpace(row.LocationRole))
  103. continue;
  104. // 库位角色写错不会报错,只会让 LocationRules 的组合永远判不出阶段码,流水静默落进未映射隔离。
  105. var role = NeutralTransTypeCodes.NormalizeLocationRole(row.LocationRole)
  106. ?? throw Oops.Oh($"库位角色 {row.LocationRole} 不合法,只能是 {string.Join(" / ", NeutralTransTypeCodes.AllLocationRoles)}");
  107. n += await _db.Ado.ExecuteCommandAsync(
  108. """
  109. INSERT INTO mdp_location_role (tenant_id, domain, location, location_role, role_source, remark)
  110. VALUES (@tenant, @dom, @loc, @role, 'MANUAL', @remark)
  111. ON DUPLICATE KEY UPDATE location_role=VALUES(location_role), role_source='MANUAL', remark=VALUES(remark)
  112. """,
  113. new
  114. {
  115. tenant,
  116. dom = row.Domain?.Trim() ?? "",
  117. loc = row.Location.Trim(),
  118. role,
  119. remark = row.Remark
  120. });
  121. }
  122. return new { saved = n };
  123. }
  124. [HttpGet("position-maps")]
  125. public Task<List<dynamic>> ListPositions([FromQuery] long? tenantId, [FromQuery] bool unknownOnly = false)
  126. {
  127. var tenant = ScopeTenant(tenantId);
  128. return _db.Ado.SqlQueryAsync<dynamic>(
  129. """
  130. SELECT id, tenant_id AS tenantId, source_system AS sourceSystem, domain,
  131. src_position_raw AS srcPositionRaw, src_position_field AS srcPositionField,
  132. position_code AS positionCode, role_source AS roleSource, remark
  133. FROM mdp_employee_position_map
  134. WHERE tenant_id=@tenant AND (@unk = 0 OR position_code='UNKNOWN')
  135. ORDER BY source_system, src_position_raw
  136. LIMIT 500
  137. """,
  138. new { tenant, unk = unknownOnly ? 1 : 0 });
  139. }
  140. [HttpPut("position-maps")]
  141. public async Task<object> SavePositions([FromBody] PositionMapInput input)
  142. {
  143. var tenant = ScopeTenant(input.TenantId);
  144. if (input.Rows == null || input.Rows.Count == 0)
  145. throw Oops.Oh("没有要保存的行");
  146. var n = 0;
  147. foreach (var row in input.Rows)
  148. {
  149. if (string.IsNullOrWhiteSpace(row.SourceSystem) || string.IsNullOrWhiteSpace(row.SrcPositionRaw) || string.IsNullOrWhiteSpace(row.PositionCode))
  150. continue;
  151. // 岗位码写错不会报错,只会变成永远匹配不上 KPI 等值过滤的死值,故在入库前挡掉并归一化大小写。
  152. var code = EmployeePositionRules.Normalize(row.PositionCode)
  153. ?? throw Oops.Oh($"岗位码 {row.PositionCode} 不合法,只能是 {string.Join(" / ", EmployeePositionRules.AllowedCodes)}");
  154. n += await _db.Ado.ExecuteCommandAsync(
  155. """
  156. INSERT INTO mdp_employee_position_map
  157. (tenant_id, source_system, domain, src_position_raw, src_position_field, position_code, role_source, remark)
  158. VALUES (@tenant, @sys, @dom, @raw, @field, @code, 'MANUAL', @remark)
  159. ON DUPLICATE KEY UPDATE position_code=VALUES(position_code), role_source='MANUAL', remark=VALUES(remark)
  160. """,
  161. new
  162. {
  163. tenant,
  164. sys = row.SourceSystem.Trim(),
  165. dom = row.Domain?.Trim() ?? "",
  166. raw = row.SrcPositionRaw.Trim(),
  167. field = string.IsNullOrWhiteSpace(row.SrcPositionField) ? "Position" : row.SrcPositionField.Trim(),
  168. code,
  169. remark = row.Remark
  170. });
  171. }
  172. return new { saved = n };
  173. }
  174. [HttpGet("trans-type-maps")]
  175. public Task<List<dynamic>> ListTransTypes([FromQuery] string? systemCode)
  176. {
  177. return _db.Ado.SqlQueryAsync<dynamic>(
  178. """
  179. SELECT id, system_code AS systemCode, src_trans_code AS srcTransCode, qty_sign AS qtySign,
  180. location_role AS locationRole, stage_code AS stageCode, biz_doc_type AS bizDocType, is_stage AS isStage
  181. FROM mdp_trans_type_map
  182. WHERE tenant_id=0 AND (@sys = '' OR system_code=@sys)
  183. ORDER BY system_code, src_trans_code
  184. LIMIT 500
  185. """,
  186. new { sys = systemCode?.Trim() ?? "" });
  187. }
  188. [HttpPut("trans-type-maps")]
  189. public async Task<object> SaveTransType([FromBody] TransTypeInput input)
  190. {
  191. if (!_user.SuperAdmin && !_user.SysAdmin)
  192. throw Oops.Oh("事务类型全局行只有管理员可以改");
  193. if (string.IsNullOrWhiteSpace(input.SystemCode) || string.IsNullOrWhiteSpace(input.SrcTransCode))
  194. throw Oops.Oh("systemCode 与 srcTransCode 必填");
  195. await _db.Ado.ExecuteCommandAsync(
  196. """
  197. INSERT INTO mdp_trans_type_map
  198. (tenant_id, system_code, src_trans_code, qty_sign, location_role, stage_code, biz_doc_type, is_stage, excluded_by_location)
  199. VALUES (0, @sys, @src, @sgn, @role, @stage, @biz, @isStage, 0)
  200. ON DUPLICATE KEY UPDATE stage_code=VALUES(stage_code), biz_doc_type=VALUES(biz_doc_type), is_stage=VALUES(is_stage)
  201. """,
  202. new
  203. {
  204. sys = input.SystemCode.Trim(),
  205. src = input.SrcTransCode.Trim(),
  206. sgn = input.QtySign,
  207. role = input.LocationRole?.Trim() ?? "",
  208. stage = input.StageCode,
  209. biz = input.BizDocType,
  210. isStage = input.IsStage
  211. });
  212. return new { ok = true };
  213. }
  214. [HttpGet("source-capabilities")]
  215. public Task<List<dynamic>> ListCapabilities([FromQuery] string systemCode)
  216. {
  217. if (string.IsNullOrWhiteSpace(systemCode))
  218. throw Oops.Oh("systemCode 必填");
  219. return _db.Ado.SqlQueryAsync<dynamic>(
  220. """
  221. SELECT semantic_code AS semanticCode, supported, reason, evidence
  222. FROM mdp_source_capability
  223. WHERE source_system=@sys
  224. ORDER BY semantic_code
  225. """,
  226. new { sys = systemCode.Trim() });
  227. }
  228. [HttpPut("source-capabilities")]
  229. public async Task<object> SaveCapability([FromBody] CapabilityInput input)
  230. {
  231. if (string.IsNullOrWhiteSpace(input.SystemCode) || string.IsNullOrWhiteSpace(input.SemanticCode))
  232. throw Oops.Oh("systemCode 与 semanticCode 必填");
  233. await _db.Ado.ExecuteCommandAsync(
  234. """
  235. INSERT INTO mdp_source_capability (source_system, semantic_code, supported, reason, evidence, verified_at)
  236. VALUES (@sys, @code, @sup, @reason, @evidence, NOW())
  237. ON DUPLICATE KEY UPDATE supported=VALUES(supported), reason=VALUES(reason), evidence=VALUES(evidence), verified_at=NOW()
  238. """,
  239. new
  240. {
  241. sys = input.SystemCode.Trim(),
  242. code = input.SemanticCode.Trim(),
  243. sup = input.Supported ? 1 : 0,
  244. reason = input.Reason ?? "",
  245. evidence = input.Evidence
  246. });
  247. return new { ok = true };
  248. }
  249. [HttpGet("inbound-grants")]
  250. public async Task<List<dynamic>> ListGrants([FromQuery] long? tenantId, [FromQuery] string? sourceCode)
  251. {
  252. var tenant = ScopeTenant(tenantId);
  253. var rows = await _db.Ado.SqlQueryAsync<dynamic>(
  254. """
  255. SELECT id, entity_code AS entityCode, source_code AS sourceCode, rate_limit_per_min AS rateLimitPerMin,
  256. status, CONCAT(LEFT(access_key, 4), '…') AS accessKeyMask
  257. FROM mdp_inbound_grant
  258. WHERE tenant_id=@tenant AND (@src = '' OR source_code=@src)
  259. ORDER BY source_code, entity_code
  260. """,
  261. new { tenant, src = sourceCode?.Trim() ?? "" });
  262. return rows;
  263. }
  264. [HttpGet("required-columns")]
  265. public object RequiredColumns([FromQuery] string stdObject)
  266. {
  267. var def = MdpStdObjectCatalog.Find(stdObject);
  268. if (def == null)
  269. throw Oops.Oh($"未知标准对象 {stdObject}");
  270. return new
  271. {
  272. stdObject = def.Code,
  273. targetTable = def.Tables.FirstOrDefault(),
  274. columns = NeutralRequiredColumns.For(def.Code).Select(c => new { name = c.Name, semanticCode = c.SemanticCode })
  275. };
  276. }
  277. [HttpGet("semantic-codes")]
  278. public object SemanticCodes() =>
  279. Admin.NET.Plugin.AiDOP.SmartOps.KpiSemanticDependency.DistinctSemantics();
  280. [HttpPost("inbound-grants")]
  281. public async Task<object> CreateGrant([FromBody] GrantCreateInput input)
  282. {
  283. var tenant = ScopeTenant(input.TenantId);
  284. if (string.IsNullOrWhiteSpace(input.SourceCode) || string.IsNullOrWhiteSpace(input.EntityCode))
  285. throw Oops.Oh("sourceCode 与 entityCode 必填");
  286. var source = await _db.Queryable<MdpSource>()
  287. .Where(s => s.SourceCode == input.SourceCode.Trim())
  288. .FirstAsync() ?? throw Oops.Oh("来源不存在");
  289. if (!string.Equals(source.SourceType, "API_INBOUND", StringComparison.OrdinalIgnoreCase))
  290. throw Oops.Oh("只有对方推送来源可以发授权");
  291. var requestedKey = input.AccessKey?.Trim() ?? "";
  292. var identity = string.IsNullOrEmpty(requestedKey)
  293. ? null
  294. : await _db.Queryable<SysOpenAccess>().FirstAsync(x => x.AccessKey == requestedKey);
  295. var plan = InboundGrantIssuance.Plan(
  296. requestedKey,
  297. tenant,
  298. identity?.BindTenantId ?? 0,
  299. identity != null,
  300. NewToken,
  301. NewToken);
  302. var entityCode = input.EntityCode.Trim();
  303. switch (plan.Kind)
  304. {
  305. case InboundGrantIssuanceKind.RejectUnknownKey:
  306. throw Oops.Oh("访问标识不存在。留空将新建一套凭据,或先在开放接口身份中建立该标识");
  307. case InboundGrantIssuanceKind.RejectCrossTenant:
  308. throw Oops.Oh("该访问标识属于其他租户,不能用于本租户的推送授权");
  309. }
  310. var duplicated = await _db.Queryable<MdpInboundGrant>()
  311. .AnyAsync(x => x.AccessKey == plan.AccessKey && x.EntityCode == entityCode);
  312. if (duplicated)
  313. throw Oops.Oh("该访问标识已经授权过这个业务对象");
  314. long bindUserId = 0;
  315. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  316. {
  317. bindUserId = await _db.Queryable<SysTenant>()
  318. .Where(t => t.Id == tenant)
  319. .Select(t => t.UserId)
  320. .FirstAsync();
  321. if (bindUserId <= 0)
  322. throw Oops.Oh("租户尚未生成租管用户,无法签发推送身份");
  323. }
  324. var now = DateTime.Now;
  325. try
  326. {
  327. _db.Ado.BeginTran();
  328. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  329. {
  330. await _db.Insertable(new SysOpenAccess
  331. {
  332. Id = YitIdHelper.NextId(),
  333. AccessKey = plan.AccessKey,
  334. AccessSecret = plan.AccessSecret,
  335. BindTenantId = tenant,
  336. BindUserId = bindUserId,
  337. CreateTime = now,
  338. }).ExecuteCommandAsync();
  339. }
  340. await _db.Insertable(new MdpInboundGrant
  341. {
  342. TenantId = tenant,
  343. AccessKey = plan.AccessKey,
  344. EntityCode = entityCode,
  345. SourceCode = source.SourceCode,
  346. RateLimitPerMin = input.RateLimitPerMin <= 0 ? 60 : input.RateLimitPerMin,
  347. BatchRowLimit = 500,
  348. Status = 1,
  349. CreateTime = now,
  350. UpdateTime = now
  351. }).ExecuteCommandAsync();
  352. _db.Ado.CommitTran();
  353. }
  354. catch
  355. {
  356. _db.Ado.RollbackTran();
  357. throw;
  358. }
  359. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  360. _cache.Remove(CacheConst.KeyOpenAccess + plan.AccessKey);
  361. // 密钥只在新建时回显一次。复用已有标识时调用方本就持有密钥,不再返回。
  362. return plan.Kind == InboundGrantIssuanceKind.CreateIdentity
  363. ? new { accessKey = plan.AccessKey, accessSecret = plan.AccessSecret, entityCode, secretShownOnce = true }
  364. : (object)new { accessKey = plan.AccessKey, entityCode, secretShownOnce = false };
  365. }
  366. private static string NewToken() =>
  367. Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
  368. }
  369. public sealed class DomainMapInput
  370. {
  371. public long TenantId { get; set; }
  372. public string SystemCode { get; set; } = "";
  373. public string? SourceCode { get; set; }
  374. public string Domain { get; set; } = "";
  375. public string? Remark { get; set; }
  376. }
  377. public sealed class LocationRoleInput
  378. {
  379. public long TenantId { get; set; }
  380. public List<LocationRoleRow> Rows { get; set; } = [];
  381. }
  382. public sealed class LocationRoleRow
  383. {
  384. public string? Domain { get; set; }
  385. public string Location { get; set; } = "";
  386. public string LocationRole { get; set; } = "";
  387. public string? Remark { get; set; }
  388. }
  389. public sealed class PositionMapInput
  390. {
  391. public long TenantId { get; set; }
  392. public List<PositionMapRow> Rows { get; set; } = [];
  393. }
  394. public sealed class PositionMapRow
  395. {
  396. public string SourceSystem { get; set; } = "";
  397. public string? Domain { get; set; }
  398. public string SrcPositionRaw { get; set; } = "";
  399. public string? SrcPositionField { get; set; }
  400. public string PositionCode { get; set; } = "";
  401. public string? Remark { get; set; }
  402. }
  403. public sealed class TransTypeInput
  404. {
  405. public string SystemCode { get; set; } = "";
  406. public string SrcTransCode { get; set; } = "";
  407. public int QtySign { get; set; }
  408. public string? LocationRole { get; set; }
  409. public string? StageCode { get; set; }
  410. public string? BizDocType { get; set; }
  411. public int IsStage { get; set; } = 1;
  412. }
  413. public sealed class CapabilityInput
  414. {
  415. public string SystemCode { get; set; } = "";
  416. public string SemanticCode { get; set; } = "";
  417. public bool Supported { get; set; }
  418. public string? Reason { get; set; }
  419. public string? Evidence { get; set; }
  420. }
  421. public sealed class GrantCreateInput
  422. {
  423. public long TenantId { get; set; }
  424. public string SourceCode { get; set; } = "";
  425. public string EntityCode { get; set; } = "";
  426. public int RateLimitPerMin { get; set; } = 60;
  427. /// <summary>留空则新建开放接口身份并回显密钥;传入则复用该身份,且必须属于目标租户。</summary>
  428. public string AccessKey { get; set; }
  429. }