using FoodLabeling.Domain.Shared.MultiTenancy;
using Volo.Abp;
using Volo.Abp.Data;
using Volo.Abp.MultiTenancy;
using Yi.Framework.TenantManagement.Domain;
namespace FoodLabeling.Th.Application.MultiTenancy;
///
/// 平台主库解析租户配置(供泰额登录/Web 登录共用)
///
public static class TenantResolveHelper
{
///
/// 按租户 Id 或租户名称解析配置;二者至少提供一个
///
public static async Task ResolveTenantAsync(
ITenantStore tenantStore,
ICurrentTenant currentTenant,
Guid? tenantId,
string? tenantName)
{
if (tenantId.HasValue && tenantId.Value != Guid.Empty)
{
return await ResolveTenantAsync(tenantStore, currentTenant, tenantId.Value);
}
if (!string.IsNullOrWhiteSpace(tenantName))
{
var name = tenantName.Trim();
TenantConfiguration? config;
using (currentTenant.Change(null))
{
config = await tenantStore.FindAsync(name);
// 配置注入的宿主 Default(Id=Empty) 会遮蔽库里同名业务租户,登录按名时改查库
if (config is not null
&& config.Id == Guid.Empty
&& string.Equals(
config.Name,
ConnectionStrings.DefaultConnectionStringName,
StringComparison.OrdinalIgnoreCase)
&& tenantStore is SqlSugarAndConfigurationTenantStore sqlStore)
{
var fromDb = await sqlStore.FindFromDatabaseByNameAsync(name);
if (fromDb is not null)
{
config = fromDb;
}
}
}
if (config is null || config.Id == Guid.Empty)
{
throw new UserFriendlyException("租户不存在或已停用");
}
if (string.IsNullOrWhiteSpace(config.ConnectionStrings?.Default))
{
throw new UserFriendlyException("租户未配置业务库连接串");
}
return config;
}
throw new UserFriendlyException("请指定租户 Id 或租户名称");
}
public static async Task ResolveTenantAsync(
ITenantStore tenantStore,
ICurrentTenant currentTenant,
Guid tenantId)
{
if (tenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
TenantConfiguration? config;
using (currentTenant.Change(null))
{
config = await tenantStore.FindAsync(tenantId);
}
if (config is null)
{
throw new UserFriendlyException("租户不存在或已停用");
}
if (string.IsNullOrWhiteSpace(config.ConnectionStrings?.Default))
{
throw new UserFriendlyException("租户未配置业务库连接串");
}
return config;
}
public static bool IsSeparateDatabaseMode(string? mode) =>
string.Equals(
mode?.Trim(),
FoodLabelingMultiTenancyConsts.SeparateDatabaseMode,
StringComparison.OrdinalIgnoreCase);
}