SourceDomainTenantResolver.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using SqlSugar;
  2. namespace Admin.NET.Plugin.AiDOP.Infrastructure;
  3. /// <summary>
  4. /// 165 Domain ↔ Ai-DOP tenant 显式映射。映射缺失或多行一律抛错,禁止回落 8010/0/主租户。
  5. /// </summary>
  6. public sealed class SourceDomainTenantResolver : ITransient
  7. {
  8. private readonly ISqlSugarClient _db;
  9. public SourceDomainTenantResolver(ISqlSugarClient db) => _db = db;
  10. public async Task<long> ResolveTenantIdAsync(
  11. string sourceCode,
  12. string domain,
  13. CancellationToken cancellationToken = default)
  14. {
  15. if (string.IsNullOrWhiteSpace(sourceCode) || string.IsNullOrWhiteSpace(domain))
  16. throw new InvalidOperationException("sourceCode/domain 不能为空");
  17. var rows = await _db.Ado.SqlQueryAsync<MapRow>(
  18. """
  19. SELECT tenant_id AS TenantId
  20. FROM ado_source_domain_tenant_map
  21. WHERE source_code=@SourceCode AND domain=@Domain AND status=1
  22. """,
  23. new List<SugarParameter>
  24. {
  25. new("@SourceCode", sourceCode.Trim()),
  26. new("@Domain", domain.Trim())
  27. });
  28. if (rows.Count == 0)
  29. throw new InvalidOperationException(
  30. $"未找到启用的 Domain 映射:source={sourceCode}, domain={domain}");
  31. if (rows.Count > 1)
  32. throw new InvalidOperationException(
  33. $"Domain 映射不唯一:source={sourceCode}, domain={domain}, count={rows.Count}");
  34. if (rows[0].TenantId <= 0)
  35. throw new InvalidOperationException(
  36. $"Domain 映射 tenant_id 非法:source={sourceCode}, domain={domain}");
  37. return rows[0].TenantId;
  38. }
  39. public async Task<string> ResolveDomainAsync(
  40. string sourceCode,
  41. long tenantId,
  42. CancellationToken cancellationToken = default)
  43. {
  44. if (string.IsNullOrWhiteSpace(sourceCode) || tenantId <= 0)
  45. throw new InvalidOperationException("sourceCode/tenantId 非法");
  46. var rows = await _db.Ado.SqlQueryAsync<DomainRow>(
  47. """
  48. SELECT domain AS Domain
  49. FROM ado_source_domain_tenant_map
  50. WHERE source_code=@SourceCode AND tenant_id=@TenantId AND status=1
  51. """,
  52. new List<SugarParameter>
  53. {
  54. new("@SourceCode", sourceCode.Trim()),
  55. new("@TenantId", tenantId)
  56. });
  57. if (rows.Count == 0)
  58. throw new InvalidOperationException(
  59. $"未找到启用的租户 Domain 映射:source={sourceCode}, tenant={tenantId}");
  60. if (rows.Count > 1)
  61. throw new InvalidOperationException(
  62. $"租户 Domain 映射不唯一:source={sourceCode}, tenant={tenantId}, count={rows.Count}");
  63. if (string.IsNullOrWhiteSpace(rows[0].Domain))
  64. throw new InvalidOperationException("Domain 映射值为空");
  65. return rows[0].Domain!.Trim();
  66. }
  67. private sealed class MapRow
  68. {
  69. public long TenantId { get; set; }
  70. }
  71. private sealed class DomainRow
  72. {
  73. public string? Domain { get; set; }
  74. }
  75. }