MdpSourceMappingService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. n += await _db.Ado.ExecuteCommandAsync(
  105. """
  106. INSERT INTO mdp_location_role (tenant_id, domain, location, location_role, role_source, remark)
  107. VALUES (@tenant, @dom, @loc, @role, 'MANUAL', @remark)
  108. ON DUPLICATE KEY UPDATE location_role=VALUES(location_role), role_source='MANUAL', remark=VALUES(remark)
  109. """,
  110. new
  111. {
  112. tenant,
  113. dom = row.Domain?.Trim() ?? "",
  114. loc = row.Location.Trim(),
  115. role = row.LocationRole.Trim(),
  116. remark = row.Remark
  117. });
  118. }
  119. return new { saved = n };
  120. }
  121. [HttpGet("position-maps")]
  122. public Task<List<dynamic>> ListPositions([FromQuery] long? tenantId, [FromQuery] bool unknownOnly = false)
  123. {
  124. var tenant = ScopeTenant(tenantId);
  125. return _db.Ado.SqlQueryAsync<dynamic>(
  126. """
  127. SELECT id, tenant_id AS tenantId, source_system AS sourceSystem, domain,
  128. src_position_raw AS srcPositionRaw, src_position_field AS srcPositionField,
  129. position_code AS positionCode, role_source AS roleSource, remark
  130. FROM mdp_employee_position_map
  131. WHERE tenant_id=@tenant AND (@unk = 0 OR position_code='UNKNOWN')
  132. ORDER BY source_system, src_position_raw
  133. LIMIT 500
  134. """,
  135. new { tenant, unk = unknownOnly ? 1 : 0 });
  136. }
  137. [HttpPut("position-maps")]
  138. public async Task<object> SavePositions([FromBody] PositionMapInput input)
  139. {
  140. var tenant = ScopeTenant(input.TenantId);
  141. if (input.Rows == null || input.Rows.Count == 0)
  142. throw Oops.Oh("没有要保存的行");
  143. var n = 0;
  144. foreach (var row in input.Rows)
  145. {
  146. if (string.IsNullOrWhiteSpace(row.SourceSystem) || string.IsNullOrWhiteSpace(row.SrcPositionRaw) || string.IsNullOrWhiteSpace(row.PositionCode))
  147. continue;
  148. // 岗位码写错不会报错,只会变成永远匹配不上 KPI 等值过滤的死值,故在入库前挡掉并归一化大小写。
  149. var code = EmployeePositionRules.Normalize(row.PositionCode)
  150. ?? throw Oops.Oh($"岗位码 {row.PositionCode} 不合法,只能是 {string.Join(" / ", EmployeePositionRules.AllowedCodes)}");
  151. n += await _db.Ado.ExecuteCommandAsync(
  152. """
  153. INSERT INTO mdp_employee_position_map
  154. (tenant_id, source_system, domain, src_position_raw, src_position_field, position_code, role_source, remark)
  155. VALUES (@tenant, @sys, @dom, @raw, @field, @code, 'MANUAL', @remark)
  156. ON DUPLICATE KEY UPDATE position_code=VALUES(position_code), role_source='MANUAL', remark=VALUES(remark)
  157. """,
  158. new
  159. {
  160. tenant,
  161. sys = row.SourceSystem.Trim(),
  162. dom = row.Domain?.Trim() ?? "",
  163. raw = row.SrcPositionRaw.Trim(),
  164. field = string.IsNullOrWhiteSpace(row.SrcPositionField) ? "Position" : row.SrcPositionField.Trim(),
  165. code,
  166. remark = row.Remark
  167. });
  168. }
  169. return new { saved = n };
  170. }
  171. [HttpGet("trans-type-maps")]
  172. public Task<List<dynamic>> ListTransTypes([FromQuery] string? systemCode)
  173. {
  174. return _db.Ado.SqlQueryAsync<dynamic>(
  175. """
  176. SELECT id, system_code AS systemCode, src_trans_code AS srcTransCode, qty_sign AS qtySign,
  177. location_role AS locationRole, stage_code AS stageCode, biz_doc_type AS bizDocType, is_stage AS isStage
  178. FROM mdp_trans_type_map
  179. WHERE tenant_id=0 AND (@sys = '' OR system_code=@sys)
  180. ORDER BY system_code, src_trans_code
  181. LIMIT 500
  182. """,
  183. new { sys = systemCode?.Trim() ?? "" });
  184. }
  185. [HttpPut("trans-type-maps")]
  186. public async Task<object> SaveTransType([FromBody] TransTypeInput input)
  187. {
  188. if (!_user.SuperAdmin && !_user.SysAdmin)
  189. throw Oops.Oh("事务类型全局行只有管理员可以改");
  190. if (string.IsNullOrWhiteSpace(input.SystemCode) || string.IsNullOrWhiteSpace(input.SrcTransCode))
  191. throw Oops.Oh("systemCode 与 srcTransCode 必填");
  192. await _db.Ado.ExecuteCommandAsync(
  193. """
  194. INSERT INTO mdp_trans_type_map
  195. (tenant_id, system_code, src_trans_code, qty_sign, location_role, stage_code, biz_doc_type, is_stage, excluded_by_location)
  196. VALUES (0, @sys, @src, @sgn, @role, @stage, @biz, @isStage, 0)
  197. ON DUPLICATE KEY UPDATE stage_code=VALUES(stage_code), biz_doc_type=VALUES(biz_doc_type), is_stage=VALUES(is_stage)
  198. """,
  199. new
  200. {
  201. sys = input.SystemCode.Trim(),
  202. src = input.SrcTransCode.Trim(),
  203. sgn = input.QtySign,
  204. role = input.LocationRole?.Trim() ?? "",
  205. stage = input.StageCode,
  206. biz = input.BizDocType,
  207. isStage = input.IsStage
  208. });
  209. return new { ok = true };
  210. }
  211. [HttpGet("source-capabilities")]
  212. public Task<List<dynamic>> ListCapabilities([FromQuery] string systemCode)
  213. {
  214. if (string.IsNullOrWhiteSpace(systemCode))
  215. throw Oops.Oh("systemCode 必填");
  216. return _db.Ado.SqlQueryAsync<dynamic>(
  217. """
  218. SELECT semantic_code AS semanticCode, supported, reason, evidence
  219. FROM mdp_source_capability
  220. WHERE source_system=@sys
  221. ORDER BY semantic_code
  222. """,
  223. new { sys = systemCode.Trim() });
  224. }
  225. [HttpPut("source-capabilities")]
  226. public async Task<object> SaveCapability([FromBody] CapabilityInput input)
  227. {
  228. if (string.IsNullOrWhiteSpace(input.SystemCode) || string.IsNullOrWhiteSpace(input.SemanticCode))
  229. throw Oops.Oh("systemCode 与 semanticCode 必填");
  230. await _db.Ado.ExecuteCommandAsync(
  231. """
  232. INSERT INTO mdp_source_capability (source_system, semantic_code, supported, reason, evidence, verified_at)
  233. VALUES (@sys, @code, @sup, @reason, @evidence, NOW())
  234. ON DUPLICATE KEY UPDATE supported=VALUES(supported), reason=VALUES(reason), evidence=VALUES(evidence), verified_at=NOW()
  235. """,
  236. new
  237. {
  238. sys = input.SystemCode.Trim(),
  239. code = input.SemanticCode.Trim(),
  240. sup = input.Supported ? 1 : 0,
  241. reason = input.Reason ?? "",
  242. evidence = input.Evidence
  243. });
  244. return new { ok = true };
  245. }
  246. [HttpGet("inbound-grants")]
  247. public async Task<List<dynamic>> ListGrants([FromQuery] long? tenantId, [FromQuery] string? sourceCode)
  248. {
  249. var tenant = ScopeTenant(tenantId);
  250. var rows = await _db.Ado.SqlQueryAsync<dynamic>(
  251. """
  252. SELECT id, entity_code AS entityCode, source_code AS sourceCode, rate_limit_per_min AS rateLimitPerMin,
  253. status, CONCAT(LEFT(access_key, 4), '…') AS accessKeyMask
  254. FROM mdp_inbound_grant
  255. WHERE tenant_id=@tenant AND (@src = '' OR source_code=@src)
  256. ORDER BY source_code, entity_code
  257. """,
  258. new { tenant, src = sourceCode?.Trim() ?? "" });
  259. return rows;
  260. }
  261. [HttpGet("required-columns")]
  262. public object RequiredColumns([FromQuery] string stdObject)
  263. {
  264. var def = MdpStdObjectCatalog.Find(stdObject);
  265. if (def == null)
  266. throw Oops.Oh($"未知标准对象 {stdObject}");
  267. return new
  268. {
  269. stdObject = def.Code,
  270. targetTable = def.Tables.FirstOrDefault(),
  271. columns = NeutralRequiredColumns.For(def.Code).Select(c => new { name = c.Name, semanticCode = c.SemanticCode })
  272. };
  273. }
  274. [HttpGet("semantic-codes")]
  275. public object SemanticCodes() =>
  276. Admin.NET.Plugin.AiDOP.SmartOps.KpiSemanticDependency.DistinctSemantics();
  277. [HttpPost("inbound-grants")]
  278. public async Task<object> CreateGrant([FromBody] GrantCreateInput input)
  279. {
  280. var tenant = ScopeTenant(input.TenantId);
  281. if (string.IsNullOrWhiteSpace(input.SourceCode) || string.IsNullOrWhiteSpace(input.EntityCode))
  282. throw Oops.Oh("sourceCode 与 entityCode 必填");
  283. var source = await _db.Queryable<MdpSource>()
  284. .Where(s => s.SourceCode == input.SourceCode.Trim())
  285. .FirstAsync() ?? throw Oops.Oh("来源不存在");
  286. if (!string.Equals(source.SourceType, "API_INBOUND", StringComparison.OrdinalIgnoreCase))
  287. throw Oops.Oh("只有对方推送来源可以发授权");
  288. var requestedKey = input.AccessKey?.Trim() ?? "";
  289. var identity = string.IsNullOrEmpty(requestedKey)
  290. ? null
  291. : await _db.Queryable<SysOpenAccess>().FirstAsync(x => x.AccessKey == requestedKey);
  292. var plan = InboundGrantIssuance.Plan(
  293. requestedKey,
  294. tenant,
  295. identity?.BindTenantId ?? 0,
  296. identity != null,
  297. NewToken,
  298. NewToken);
  299. var entityCode = input.EntityCode.Trim();
  300. switch (plan.Kind)
  301. {
  302. case InboundGrantIssuanceKind.RejectUnknownKey:
  303. throw Oops.Oh("访问标识不存在。留空将新建一套凭据,或先在开放接口身份中建立该标识");
  304. case InboundGrantIssuanceKind.RejectCrossTenant:
  305. throw Oops.Oh("该访问标识属于其他租户,不能用于本租户的推送授权");
  306. }
  307. var duplicated = await _db.Queryable<MdpInboundGrant>()
  308. .AnyAsync(x => x.AccessKey == plan.AccessKey && x.EntityCode == entityCode);
  309. if (duplicated)
  310. throw Oops.Oh("该访问标识已经授权过这个业务对象");
  311. long bindUserId = 0;
  312. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  313. {
  314. bindUserId = await _db.Queryable<SysTenant>()
  315. .Where(t => t.Id == tenant)
  316. .Select(t => t.UserId)
  317. .FirstAsync();
  318. if (bindUserId <= 0)
  319. throw Oops.Oh("租户尚未生成租管用户,无法签发推送身份");
  320. }
  321. var now = DateTime.Now;
  322. try
  323. {
  324. _db.Ado.BeginTran();
  325. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  326. {
  327. await _db.Insertable(new SysOpenAccess
  328. {
  329. Id = YitIdHelper.NextId(),
  330. AccessKey = plan.AccessKey,
  331. AccessSecret = plan.AccessSecret,
  332. BindTenantId = tenant,
  333. BindUserId = bindUserId,
  334. CreateTime = now,
  335. }).ExecuteCommandAsync();
  336. }
  337. await _db.Insertable(new MdpInboundGrant
  338. {
  339. TenantId = tenant,
  340. AccessKey = plan.AccessKey,
  341. EntityCode = entityCode,
  342. SourceCode = source.SourceCode,
  343. RateLimitPerMin = input.RateLimitPerMin <= 0 ? 60 : input.RateLimitPerMin,
  344. BatchRowLimit = 500,
  345. Status = 1,
  346. CreateTime = now,
  347. UpdateTime = now
  348. }).ExecuteCommandAsync();
  349. _db.Ado.CommitTran();
  350. }
  351. catch
  352. {
  353. _db.Ado.RollbackTran();
  354. throw;
  355. }
  356. if (plan.Kind == InboundGrantIssuanceKind.CreateIdentity)
  357. _cache.Remove(CacheConst.KeyOpenAccess + plan.AccessKey);
  358. // 密钥只在新建时回显一次。复用已有标识时调用方本就持有密钥,不再返回。
  359. return plan.Kind == InboundGrantIssuanceKind.CreateIdentity
  360. ? new { accessKey = plan.AccessKey, accessSecret = plan.AccessSecret, entityCode, secretShownOnce = true }
  361. : (object)new { accessKey = plan.AccessKey, entityCode, secretShownOnce = false };
  362. }
  363. private static string NewToken() =>
  364. Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
  365. }
  366. public sealed class DomainMapInput
  367. {
  368. public long TenantId { get; set; }
  369. public string SystemCode { get; set; } = "";
  370. public string? SourceCode { get; set; }
  371. public string Domain { get; set; } = "";
  372. public string? Remark { get; set; }
  373. }
  374. public sealed class LocationRoleInput
  375. {
  376. public long TenantId { get; set; }
  377. public List<LocationRoleRow> Rows { get; set; } = [];
  378. }
  379. public sealed class LocationRoleRow
  380. {
  381. public string? Domain { get; set; }
  382. public string Location { get; set; } = "";
  383. public string LocationRole { get; set; } = "";
  384. public string? Remark { get; set; }
  385. }
  386. public sealed class PositionMapInput
  387. {
  388. public long TenantId { get; set; }
  389. public List<PositionMapRow> Rows { get; set; } = [];
  390. }
  391. public sealed class PositionMapRow
  392. {
  393. public string SourceSystem { get; set; } = "";
  394. public string? Domain { get; set; }
  395. public string SrcPositionRaw { get; set; } = "";
  396. public string? SrcPositionField { get; set; }
  397. public string PositionCode { get; set; } = "";
  398. public string? Remark { get; set; }
  399. }
  400. public sealed class TransTypeInput
  401. {
  402. public string SystemCode { get; set; } = "";
  403. public string SrcTransCode { get; set; } = "";
  404. public int QtySign { get; set; }
  405. public string? LocationRole { get; set; }
  406. public string? StageCode { get; set; }
  407. public string? BizDocType { get; set; }
  408. public int IsStage { get; set; } = 1;
  409. }
  410. public sealed class CapabilityInput
  411. {
  412. public string SystemCode { get; set; } = "";
  413. public string SemanticCode { get; set; } = "";
  414. public bool Supported { get; set; }
  415. public string? Reason { get; set; }
  416. public string? Evidence { get; set; }
  417. }
  418. public sealed class GrantCreateInput
  419. {
  420. public long TenantId { get; set; }
  421. public string SourceCode { get; set; } = "";
  422. public string EntityCode { get; set; } = "";
  423. public int RateLimitPerMin { get; set; } = 60;
  424. /// <summary>留空则新建开放接口身份并回显密钥;传入则复用该身份,且必须属于目标租户。</summary>
  425. public string AccessKey { get; set; }
  426. }