Commit e41dfa098fa19322bcdc42c4c488d26b7dd51a6c

Authored by 李曜臣
1 parent a60a45f4

泰鄂版菜单;租户列表

Showing 37 changed files with 3068 additions and 97 deletions
泰额版/Food Labeling Management Code/Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore/TenantConfigurationWrapper.cs
... ... @@ -67,8 +67,31 @@ public class TenantConfigurationWrapper : ITransientDependency
67 67 return config;
68 68 }
69 69  
70   - // 返回默认配置
71   - return await TenantStoreService.FindAsync(ConnectionStrings.DefaultConnectionStringName);
  70 + // 无租户上下文 = 平台主库(DbConnOptions.Url),不查库内名为 Default 的租户记录
  71 + return CreateHostTenantConfiguration();
  72 + }
  73 +
  74 + /// <summary>
  75 + /// 平台主库租户配置(CurrentTenant 为空时使用 DbConnOptions.Url)。
  76 + /// </summary>
  77 + private TenantConfiguration CreateHostTenantConfiguration()
  78 + {
  79 + if (string.IsNullOrWhiteSpace(DbConnectionOptions.Url))
  80 + {
  81 + throw new ApplicationException("未配置主库连接字符串 DbConnOptions.Url");
  82 + }
  83 +
  84 + return new TenantConfiguration
  85 + {
  86 + Id = Guid.Empty,
  87 + Name = ConnectionStrings.DefaultConnectionStringName,
  88 + NormalizedName = ConnectionStrings.DefaultConnectionStringName,
  89 + ConnectionStrings = new ConnectionStrings
  90 + {
  91 + { ConnectionStrings.DefaultConnectionStringName, DbConnectionOptions.Url }
  92 + },
  93 + IsActive = true
  94 + };
72 95 }
73 96  
74 97 /// <summary>
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/FoodLabelingApplicationModule.cs
1 1 using FoodLabeling.Application.Contracts;
  2 +using FoodLabeling.Application.Filters;
2 3 using FoodLabeling.Application.Options;
3 4 using FoodLabeling.Domain;
  5 +using Microsoft.AspNetCore.Mvc;
4 6 using Microsoft.Extensions.DependencyInjection;
5 7 using Volo.Abp.Modularity;
6 8 using Yi.Framework.Ddd.Application;
... ... @@ -21,6 +23,12 @@ public class FoodLabelingApplicationModule : AbpModule
21 23 {
22 24 Configure<FoodLabelingBatchImportOptions>(
23 25 context.Services.GetConfiguration().GetSection(FoodLabelingBatchImportOptions.SectionName));
  26 +
  27 + // 任意业务写接口成功后刷新系统编辑时间戳,供 my-menus.lastUpdated 使用
  28 + Configure<MvcOptions>(options =>
  29 + {
  30 + options.Filters.AddService<SystemEditStampGlobalFilter>();
  31 + });
24 32 }
25 33 }
26 34  
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/AuthSessionAppService.cs
... ... @@ -21,17 +21,20 @@ namespace FoodLabeling.Application.Services;
21 21 public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
22 22 {
23 23 private readonly IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> _userCache;
  24 + private readonly IDistributedCache<SystemEditStampCacheItem, SystemEditStampCacheKey> _systemEditStampCache;
24 25 private readonly ISqlSugarDbContext _dbContext;
25 26 private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
26 27  
27 28 public AuthSessionAppService(
28 29 ISqlSugarDbContext dbContext,
29 30 ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
30   - IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> userCache)
  31 + IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> userCache,
  32 + IDistributedCache<SystemEditStampCacheItem, SystemEditStampCacheKey> systemEditStampCache)
31 33 {
32 34 _dbContext = dbContext;
33 35 _userRepository = userRepository;
34 36 _userCache = userCache;
  37 + _systemEditStampCache = systemEditStampCache;
35 38 }
36 39  
37 40 /// <inheritdoc />
... ... @@ -110,6 +113,12 @@ public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
110 113 .OrderBy(x => x)
111 114 .ToList();
112 115  
  116 + // 优先系统编辑全局时间戳(任意写接口成功联动);无戳时回退「业务表最近修改」再回退用户时间
  117 + var systemEditAt = await SystemEditStampCacheHelper.GetAsync(_systemEditStampCache);
  118 + var lastUpdated = systemEditAt
  119 + ?? await ResolveRecentBusinessEditTimeAsync()
  120 + ?? user.LastModificationTime;
  121 +
113 122 return new CurrentUserMenuPermissionsOutputDto
114 123 {
115 124 User = new CurrentUserBriefDto
... ... @@ -124,12 +133,49 @@ public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
124 133 PermissionCodes = permissionCodes,
125 134 AccessPermissionCodes = accessPermissionCodes,
126 135 Menus = BuildMenuTree(menuNodes),
127   - LastUpdated = user.LastModificationTime,
  136 + LastUpdated = lastUpdated,
128 137 Role = roleDisplay,
129 138 FullName = BuildFullName(user)
130 139 };
131 140 }
132 141  
  142 + /// <summary>
  143 + /// 缓存未命中时,取主要业务表最近修改时间,避免 Last Updated 长期停在用户资料时间。
  144 + /// </summary>
  145 + private async Task<DateTime?> ResolveRecentBusinessEditTimeAsync()
  146 + {
  147 + var db = _dbContext.SqlSugarClient;
  148 + DateTime? max = null;
  149 +
  150 + async Task ConsiderAsync(Task<DateTime?> query)
  151 + {
  152 + try
  153 + {
  154 + var t = await query;
  155 + if (t.HasValue && (!max.HasValue || t.Value > max.Value))
  156 + {
  157 + max = t;
  158 + }
  159 + }
  160 + catch
  161 + {
  162 + // 表/列缺失时忽略,继续其它表
  163 + }
  164 + }
  165 +
  166 + await ConsiderAsync(db.Queryable<FlLabelDbEntity>()
  167 + .Where(x => !x.IsDeleted)
  168 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  169 + await ConsiderAsync(db.Queryable<FlLabelTemplateDbEntity>()
  170 + .Where(x => !x.IsDeleted)
  171 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  172 + await ConsiderAsync(db.Queryable<FlLabelCategoryDbEntity>()
  173 + .Where(x => !x.IsDeleted)
  174 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  175 +
  176 + return max;
  177 + }
  178 +
133 179 /// <inheritdoc />
134 180 [HttpPost]
135 181 public virtual async Task<bool> LogoutAsync()
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyListInput.cs 0 → 100644
  1 +using Yi.Framework.Ddd.Application.Contracts;
  2 +
  3 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  4 +
  5 +/// <summary>
  6 +/// 平台公司(租户)列表分页查询
  7 +/// </summary>
  8 +public class ThCompanyListInput : PagedAllResultRequestDto
  9 +{
  10 + /// <summary>名称关键字(模糊匹配租户名)</summary>
  11 + public string? Keyword { get; set; }
  12 +
  13 + /// <summary>租户名称(与 Keyword 等效,兼容旧参)</summary>
  14 + public string? Name { get; set; }
  15 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyListItemDto.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 平台公司(租户)列表项(含可回显加密凭据)
  5 +/// </summary>
  6 +public class ThCompanyListItemDto
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid Id { get; set; }
  10 +
  11 + /// <summary>租户名称</summary>
  12 + public string Name { get; set; } = string.Empty;
  13 +
  14 + /// <summary>租户创建时间</summary>
  15 + public DateTime CreationTime { get; set; }
  16 +
  17 + /// <summary>管理员登录账号</summary>
  18 + public string LoginAccount { get; set; } = string.Empty;
  19 +
  20 + /// <summary>AES-CBC 加密后的管理员密码(Base64 密文)</summary>
  21 + public string Password { get; set; } = string.Empty;
  22 +
  23 + /// <summary>AES IV(Base64),前端解密 password 时使用</summary>
  24 + public string PasswordSalt { get; set; } = string.Empty;
  25 +
  26 + /// <summary>已分配的 SaaS 菜单权限 Key 列表</summary>
  27 + public List<string> MenuPermissionKeys { get; set; } = new();
  28 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyMenusDto.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 公司(租户)已分配的 SaaS 菜单权限
  5 +/// </summary>
  6 +public class ThCompanyMenusDto
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid TenantId { get; set; }
  10 +
  11 + /// <summary>已分配的菜单权限 Key 列表</summary>
  12 + public List<string> MenuPermissionKeys { get; set; } = new();
  13 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyRoleItemDto.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 租户内角色及已绑定菜单 Id
  5 +/// </summary>
  6 +public class ThCompanyRoleItemDto
  7 +{
  8 + /// <summary>角色 Id</summary>
  9 + public Guid Id { get; set; }
  10 +
  11 + /// <summary>角色名称</summary>
  12 + public string RoleName { get; set; } = string.Empty;
  13 +
  14 + /// <summary>角色编码</summary>
  15 + public string RoleCode { get; set; } = string.Empty;
  16 +
  17 + /// <summary>启用状态</summary>
  18 + public bool State { get; set; }
  19 +
  20 + /// <summary>已绑定菜单 Id 列表</summary>
  21 + public List<string> MenuIds { get; set; } = new();
  22 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThDeleteCompanyResultDto.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 删除公司(租户)及可选 DROP 业务库的执行结果
  5 +/// </summary>
  6 +public class ThDeleteCompanyResultDto
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid TenantId { get; set; }
  10 +
  11 + /// <summary>租户名称</summary>
  12 + public string Name { get; set; } = string.Empty;
  13 +
  14 + /// <summary>从连接串解析出的业务库名;解析失败时为 null</summary>
  15 + public string? DatabaseName { get; set; }
  16 +
  17 + /// <summary>是否已成功执行 DROP DATABASE</summary>
  18 + public bool DatabaseDropped { get; set; }
  19 +
  20 + /// <summary>是否已删除 YiTenant 记录(软删)</summary>
  21 + public bool TenantDeleted { get; set; }
  22 +
  23 + /// <summary>操作说明(如跳过 DROP 的原因)</summary>
  24 + public string? Message { get; set; }
  25 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThSaasMenuPermissionTreeNodeDto.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// SaaS 菜单权限树节点
  5 +/// </summary>
  6 +public class ThSaasMenuPermissionTreeNodeDto
  7 +{
  8 + /// <summary>权限 Key(如 labeling:labels)</summary>
  9 + public string Key { get; set; } = string.Empty;
  10 +
  11 + /// <summary>中文标题</summary>
  12 + public string Title { get; set; } = string.Empty;
  13 +
  14 + /// <summary>子节点</summary>
  15 + public List<ThSaasMenuPermissionTreeNodeDto>? Children { get; set; }
  16 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyAdminInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 修改公司(租户)默认管理员账号/密码
  5 +/// </summary>
  6 +public class ThUpdateCompanyAdminInputVo
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid TenantId { get; set; }
  10 +
  11 + /// <summary>新登录账号(可选,空则不改)</summary>
  12 + public string? LoginAccount { get; set; }
  13 +
  14 + /// <summary>AES 加密后的新密码(可选,空则不改)</summary>
  15 + public string? Password { get; set; }
  16 +
  17 + /// <summary>AES IV(修改密码时必填)</summary>
  18 + public string? PasswordSalt { get; set; }
  19 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyMenusInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 覆盖式设置公司(租户)SaaS 菜单权限
  5 +/// </summary>
  6 +public class ThUpdateCompanyMenusInputVo
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid TenantId { get; set; }
  10 +
  11 + /// <summary>菜单权限 Key 列表(覆盖式)</summary>
  12 + public List<string> MenuPermissionKeys { get; set; } = new();
  13 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyRoleMenusInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +/// <summary>
  4 +/// 覆盖式设置租户内角色的菜单绑定
  5 +/// </summary>
  6 +public class ThUpdateCompanyRoleMenusInputVo
  7 +{
  8 + /// <summary>租户 Id</summary>
  9 + public Guid TenantId { get; set; }
  10 +
  11 + /// <summary>角色 Id</summary>
  12 + public Guid RoleId { get; set; }
  13 +
  14 + /// <summary>菜单 Id 列表(覆盖式)</summary>
  15 + public List<string> MenuIds { get; set; } = new();
  16 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/RbacMenu/ThRbacMenuCreateInputVo.cs 0 → 100644
  1 +using Yi.Framework.Rbac.Domain.Shared.Enums;
  2 +
  3 +namespace FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  4 +
  5 +/// <summary>
  6 +/// 泰额版新增菜单入参
  7 +/// </summary>
  8 +public class ThRbacMenuCreateInputVo
  9 +{
  10 + public string MenuName { get; set; } = string.Empty;
  11 +
  12 + /// <summary>
  13 + /// 父级 Id(menu 表为字符串;根节点为 0)
  14 + /// </summary>
  15 + public string ParentId { get; set; } = "0";
  16 +
  17 + public MenuTypeEnum MenuType { get; set; }
  18 +
  19 + public MenuSourceEnum MenuSource { get; set; }
  20 +
  21 + public string? PermissionCode { get; set; }
  22 +
  23 + public string? Router { get; set; }
  24 +
  25 + public string? Component { get; set; }
  26 +
  27 + public string? RouterName { get; set; }
  28 +
  29 + public string? MenuIcon { get; set; }
  30 +
  31 + public int OrderNum { get; set; }
  32 +
  33 + public bool State { get; set; } = true;
  34 +
  35 + public bool IsShow { get; set; } = true;
  36 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/RbacMenu/ThRbacMenuGetListInputVo.cs 0 → 100644
  1 +using Volo.Abp.Application.Dtos;
  2 +using Yi.Framework.Rbac.Domain.Shared.Enums;
  3 +
  4 +namespace FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  5 +
  6 +/// <summary>
  7 +/// 泰额版菜单分页查询入参
  8 +/// </summary>
  9 +public class ThRbacMenuGetListInputVo : PagedAndSortedResultRequestDto
  10 +{
  11 + /// <summary>
  12 + /// 菜单名称(模糊匹配)
  13 + /// </summary>
  14 + public string? MenuName { get; set; }
  15 +
  16 + /// <summary>
  17 + /// 启用状态
  18 + /// </summary>
  19 + public bool? State { get; set; }
  20 +
  21 + /// <summary>
  22 + /// 菜单来源
  23 + /// </summary>
  24 + public MenuSourceEnum? MenuSource { get; set; }
  25 +
  26 + /// <summary>
  27 + /// 菜单类型
  28 + /// </summary>
  29 + public MenuTypeEnum? MenuType { get; set; }
  30 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/RbacMenu/ThRbacMenuGetListOutputDto.cs 0 → 100644
  1 +using Yi.Framework.Rbac.Domain.Shared.Enums;
  2 +
  3 +namespace FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  4 +
  5 +/// <summary>
  6 +/// 泰额版菜单列表/详情输出
  7 +/// </summary>
  8 +public class ThRbacMenuGetListOutputDto
  9 +{
  10 + public string Id { get; set; } = string.Empty;
  11 +
  12 + public string ParentId { get; set; } = string.Empty;
  13 +
  14 + public string MenuName { get; set; } = string.Empty;
  15 +
  16 + public string? RouterName { get; set; }
  17 +
  18 + public string? Router { get; set; }
  19 +
  20 + public string? PermissionCode { get; set; }
  21 +
  22 + public MenuTypeEnum MenuType { get; set; }
  23 +
  24 + public MenuSourceEnum MenuSource { get; set; }
  25 +
  26 + public int OrderNum { get; set; }
  27 +
  28 + public bool State { get; set; }
  29 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/RbacMenu/ThRbacMenuTreeDto.cs 0 → 100644
  1 +using Yi.Framework.Rbac.Domain.Shared.Enums;
  2 +
  3 +namespace FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  4 +
  5 +/// <summary>
  6 +/// 泰额版菜单树节点(含 menu 表主要字段)
  7 +/// </summary>
  8 +public class ThRbacMenuTreeDto
  9 +{
  10 + public string Id { get; set; } = string.Empty;
  11 +
  12 + public bool IsDeleted { get; set; }
  13 +
  14 + public DateTime CreationTime { get; set; }
  15 +
  16 + public string? CreatorId { get; set; }
  17 +
  18 + public string? LastModifierId { get; set; }
  19 +
  20 + public DateTime? LastModificationTime { get; set; }
  21 +
  22 + public int OrderNum { get; set; }
  23 +
  24 + public bool State { get; set; }
  25 +
  26 + public string MenuName { get; set; } = string.Empty;
  27 +
  28 + public string? RouterName { get; set; }
  29 +
  30 + public MenuTypeEnum MenuType { get; set; }
  31 +
  32 + public string? PermissionCode { get; set; }
  33 +
  34 + public string ParentId { get; set; } = string.Empty;
  35 +
  36 + public string? MenuIcon { get; set; }
  37 +
  38 + public string? Router { get; set; }
  39 +
  40 + public bool IsLink { get; set; }
  41 +
  42 + public bool IsCache { get; set; }
  43 +
  44 + public bool IsShow { get; set; }
  45 +
  46 + public string? Remark { get; set; }
  47 +
  48 + public string? Component { get; set; }
  49 +
  50 + public MenuSourceEnum MenuSource { get; set; }
  51 +
  52 + public string? Query { get; set; }
  53 +
  54 + public string? ConcurrencyStamp { get; set; }
  55 +
  56 + public List<ThRbacMenuTreeDto>? Children { get; set; }
  57 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/RbacMenu/ThRbacMenuUpdateInputVo.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  2 +
  3 +/// <summary>
  4 +/// 泰额版编辑菜单入参
  5 +/// </summary>
  6 +public class ThRbacMenuUpdateInputVo : ThRbacMenuCreateInputVo
  7 +{
  8 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/FoodLabeling.Th.Application.Contracts.csproj
... ... @@ -4,6 +4,7 @@
4 4 <ItemGroup>
5 5 <ProjectReference Include="..\..\..\framework\Yi.Framework.Ddd.Application.Contracts\Yi.Framework.Ddd.Application.Contracts.csproj" />
6 6 <ProjectReference Include="..\..\food-labeling-us\FoodLabeling.Application.Contracts\FoodLabeling.Application.Contracts.csproj" />
  7 + <ProjectReference Include="..\..\rbac\Yi.Framework.Rbac.Domain.Shared\Yi.Framework.Rbac.Domain.Shared.csproj" />
7 8 <ProjectReference Include="..\FoodLabeling.Th.Domain.Shared\FoodLabeling.Th.Domain.Shared.csproj" />
8 9 </ItemGroup>
9 10  
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/IServices/IThMultiTenancyAppService.cs
1 1 using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +using Volo.Abp.Application.Dtos;
  4 +
2 5 using Volo.Abp.Application.Services;
3 6  
  7 +
  8 +
4 9 namespace FoodLabeling.Th.Application.Contracts.IServices;
5 10  
  11 +
  12 +
6 13 /// <summary>
  14 +
7 15 /// 泰额版多租户辅助接口(租户列表、当前租户信息)
  16 +
8 17 /// </summary>
  18 +
9 19 public interface IThMultiTenancyAppService : IApplicationService
  20 +
10 21 {
  22 +
11 23 /// <summary>
  24 +
12 25 /// 获取可选租户列表(平台管理员创建租户后供登录选择)
  26 +
13 27 /// </summary>
  28 +
14 29 Task<List<ThTenantSelectDto>> GetTenantSelectAsync();
15 30  
  31 +
  32 +
16 33 /// <summary>
  34 +
17 35 /// 获取当前请求上下文解析到的租户 Id
  36 +
18 37 /// </summary>
  38 +
19 39 Task<ThCurrentTenantDto> GetCurrentTenantAsync();
  40 +
  41 +
  42 +
  43 + /// <summary>
  44 +
  45 + /// 平台级管理员:分页获取公司(租户)列表及可回显加密凭据
  46 +
  47 + /// </summary>
  48 +
  49 + Task<PagedResultDto<ThCompanyListItemDto>> GetCompanyListAsync(ThCompanyListInput input);
  50 +
  51 +
  52 +
  53 + /// <summary>
  54 +
  55 + /// 平台级管理员:修改公司默认管理员账号/密码
  56 +
  57 + /// </summary>
  58 +
  59 + Task UpdateCompanyAdminAsync(ThUpdateCompanyAdminInputVo input);
  60 +
  61 +
  62 +
  63 + /// <summary>
  64 +
  65 + /// 平台级管理员:获取 SaaS 菜单权限树
  66 +
  67 + /// </summary>
  68 +
  69 + Task<List<ThSaasMenuPermissionTreeNodeDto>> GetMenuPermissionTreeAsync();
  70 +
  71 +
  72 +
  73 + /// <summary>
  74 +
  75 + /// 平台级管理员:获取公司(租户)已分配菜单权限
  76 +
  77 + /// </summary>
  78 +
  79 + Task<ThCompanyMenusDto> GetCompanyMenusAsync(Guid tenantId);
  80 +
  81 +
  82 +
  83 + /// <summary>
  84 +
  85 + /// 平台级管理员:覆盖式设置公司(租户)菜单权限
  86 +
  87 + /// </summary>
  88 +
  89 + Task UpdateCompanyMenusAsync(ThUpdateCompanyMenusInputVo input);
  90 +
  91 +
  92 +
  93 + /// <summary>
  94 +
  95 + /// 平台级管理员:获取租户内角色及已绑定菜单
  96 +
  97 + /// </summary>
  98 +
  99 + Task<List<ThCompanyRoleItemDto>> GetCompanyRolesAsync(Guid tenantId);
  100 +
  101 +
  102 +
  103 + /// <summary>
  104 +
  105 + /// 平台级管理员:覆盖式设置租户内角色菜单绑定
  106 +
  107 + /// </summary>
  108 +
  109 + Task UpdateCompanyRoleMenusAsync(ThUpdateCompanyRoleMenusInputVo input);
  110 +
  111 +
  112 +
  113 + /// <summary>
  114 +
  115 + /// 平台级管理员:删除公司(租户),可选 DROP 对应业务库
  116 +
  117 + /// </summary>
  118 +
  119 + Task<ThDeleteCompanyResultDto> DeleteCompanyAsync(Guid tenantId, bool dropDatabase = true);
  120 +
20 121 }
  122 +
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/IServices/IThRbacMenuAppService.cs 0 → 100644
  1 +using FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  2 +using Volo.Abp.Application.Dtos;
  3 +using Volo.Abp.Application.Services;
  4 +
  5 +namespace FoodLabeling.Th.Application.Contracts.IServices;
  6 +
  7 +/// <summary>
  8 +/// 泰额版租户业务库 menu 表 CRUD
  9 +/// </summary>
  10 +public interface IThRbacMenuAppService : IApplicationService
  11 +{
  12 + Task<PagedResultDto<ThRbacMenuGetListOutputDto>> GetListAsync(ThRbacMenuGetListInputVo input);
  13 +
  14 + Task<ThRbacMenuGetListOutputDto> GetAsync(string id);
  15 +
  16 + Task<ThRbacMenuGetListOutputDto> CreateAsync(ThRbacMenuCreateInputVo input);
  17 +
  18 + Task<ThRbacMenuGetListOutputDto> UpdateAsync(string id, ThRbacMenuUpdateInputVo input);
  19 +
  20 + Task DeleteAsync(List<string> ids);
  21 +
  22 + Task<List<ThRbacMenuTreeDto>> GetTreeAsync();
  23 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantBusinessDatabaseAccessor.cs 0 → 100644
  1 +using FoodLabeling.Th.Application.Contracts.Options;
  2 +using SqlSugar;
  3 +using Volo.Abp;
  4 +using Yi.Framework.TenantManagement.Domain;
  5 +
  6 +namespace FoodLabeling.Th.Application.MultiTenancy;
  7 +
  8 +/// <summary>
  9 +/// 跨租户操作业务库:解析/回填连接串并用独立 SqlSugarClient 直连,避免 CurrentTenant.Change 解析空连接串。
  10 +/// </summary>
  11 +public static class TenantBusinessDatabaseAccessor
  12 +{
  13 + private const string InitializeTenantDatabaseHintTemplate =
  14 + "请先调用 POST /api/app/th-tenant-provisioning/initialize-tenant-database/{0} 初始化业务库";
  15 +
  16 + /// <summary>
  17 + /// 解析租户业务库连接串;为空时按配置回填并写回主库 YiTenant。
  18 + /// </summary>
  19 + public static async Task<(string ConnectionString, DbType DbType)> ResolveConnectionAsync(
  20 + TenantAggregateRoot tenant,
  21 + FoodLabelingThTenantDatabaseOptions dbOptions,
  22 + Func<TenantAggregateRoot, Task> persistTenantAsync)
  23 + {
  24 + var connectionString = tenant.TenantConnectionString?.Trim();
  25 + if (!string.IsNullOrWhiteSpace(connectionString))
  26 + {
  27 + return (connectionString, ResolveDbType(tenant.DbType));
  28 + }
  29 +
  30 + connectionString = TenantDatabaseConnectionStringBuilder.BuildMySqlConnectionString(
  31 + dbOptions,
  32 + tenant.Name);
  33 +
  34 + if (string.IsNullOrWhiteSpace(connectionString))
  35 + {
  36 + throw BuildMissingConnectionStringException(tenant.Name);
  37 + }
  38 +
  39 + var dbType = DbType.MySql;
  40 + tenant.SetConnectionString(dbType, connectionString);
  41 + await persistTenantAsync(tenant);
  42 +
  43 + return (connectionString, dbType);
  44 + }
  45 +
  46 + /// <summary>
  47 + /// 创建直连租户业务库的 SqlSugar 客户端(调用方 using 释放)。
  48 + /// </summary>
  49 + public static SqlSugarClient CreateClient(string connectionString, DbType dbType)
  50 + {
  51 + if (string.IsNullOrWhiteSpace(connectionString))
  52 + {
  53 + throw new UserFriendlyException("租户业务库连接串不能为空");
  54 + }
  55 +
  56 + return new SqlSugarClient(new ConnectionConfig
  57 + {
  58 + ConfigId = $"th-tenant-direct-{Guid.NewGuid():N}",
  59 + DbType = dbType,
  60 + ConnectionString = connectionString,
  61 + IsAutoCloseConnection = true
  62 + });
  63 + }
  64 +
  65 + /// <summary>
  66 + /// 探测业务库是否可连;库不存在时给出初始化引导。
  67 + /// </summary>
  68 + public static void EnsureDatabaseReachable(ISqlSugarClient db, Guid tenantId)
  69 + {
  70 + try
  71 + {
  72 + db.Ado.ExecuteCommand("SELECT 1");
  73 + }
  74 + catch (Exception ex) when (IsDatabaseNotExistError(ex))
  75 + {
  76 + throw new UserFriendlyException(
  77 + string.Format(InitializeTenantDatabaseHintTemplate, tenantId));
  78 + }
  79 + }
  80 +
  81 + public static UserFriendlyException BuildMissingConnectionStringException(string tenantName)
  82 + {
  83 + return new UserFriendlyException(
  84 + $"租户「{tenantName}」未配置业务库连接串,请先在租户管理完善连接串或调用开通/初始化接口");
  85 + }
  86 +
  87 + private static DbType ResolveDbType(DbType tenantDbType)
  88 + {
  89 + return tenantDbType == default ? DbType.MySql : tenantDbType;
  90 + }
  91 +
  92 + private static bool IsDatabaseNotExistError(Exception ex)
  93 + {
  94 + var message = ex.Message;
  95 + var current = ex;
  96 + while (current.InnerException != null)
  97 + {
  98 + current = current.InnerException;
  99 + message += " " + current.Message;
  100 + }
  101 +
  102 + return message.Contains("Unknown database", StringComparison.OrdinalIgnoreCase)
  103 + || message.Contains("doesn't exist", StringComparison.OrdinalIgnoreCase)
  104 + || message.Contains("1049", StringComparison.Ordinal);
  105 + }
  106 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantDatabaseBootstrapper.cs 0 → 100644
  1 +using System.Text.RegularExpressions;
  2 +using SqlSugar;
  3 +using Volo.Abp;
  4 +using Yi.Framework.SqlSugarCore.Abstractions;
  5 +
  6 +namespace FoodLabeling.Th.Application.MultiTenancy;
  7 +
  8 +/// <summary>
  9 +/// 租户业务库同步建库与 GRANT(建库候选优先级与 TenantService.CodeFirstForTenantAsync 一致)。
  10 +/// </summary>
  11 +public static class TenantDatabaseBootstrapper
  12 +{
  13 + private static readonly Regex SafeDatabaseNameRegex =
  14 + new(@"^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,63}$", RegexOptions.Compiled);
  15 +
  16 + /// <summary>
  17 + /// 同步执行 CREATE DATABASE IF NOT EXISTS 并对业务账号 GRANT;失败抛 <see cref="UserFriendlyException"/>。
  18 + /// </summary>
  19 + public static void EnsureDatabaseCreated(
  20 + DbConnOptions dbConnOptions,
  21 + DbType dbType,
  22 + string tenantConnectionString,
  23 + string databaseName)
  24 + {
  25 + if (string.IsNullOrWhiteSpace(databaseName) || !SafeDatabaseNameRegex.IsMatch(databaseName))
  26 + {
  27 + throw new UserFriendlyException("租户连接串中的数据库名无效,无法建库");
  28 + }
  29 +
  30 + var createCandidates = BuildCreateDatabaseCandidates(dbConnOptions, tenantConnectionString);
  31 + if (createCandidates.Count == 0)
  32 + {
  33 + throw new UserFriendlyException("未配置可用的数据库连接串,无法创建租户库");
  34 + }
  35 +
  36 + var createErrors = new List<string>();
  37 + string? privilegedConnectionString = null;
  38 + foreach (var candidate in createCandidates)
  39 + {
  40 + try
  41 + {
  42 + ExecuteCreateDatabase(dbType, candidate.ConnectionString, databaseName);
  43 + privilegedConnectionString = candidate.ConnectionString;
  44 + break;
  45 + }
  46 + catch (Exception ex)
  47 + {
  48 + createErrors.Add($"{candidate.Label}: {GetRootMessage(ex)}");
  49 + }
  50 + }
  51 +
  52 + if (privilegedConnectionString == null)
  53 + {
  54 + var userId = ExtractConnectionValue(tenantConnectionString, "uid") ?? "netteam";
  55 + throw new UserFriendlyException(
  56 + $"创建租户库失败(库={databaseName})。尝试结果:{string.Join(" | ", createErrors)}。" +
  57 + $"说明:MySQL 报 Access denied to database 新建库名时,通常是账号没有 CREATE 权限(与能否连上主库无关)。" +
  58 + $"请在 appsettings 的 DbConnOptions.AdminConnectionString 配置高权限账号连接串后重试;或手动执行:" +
  59 + $"CREATE DATABASE IF NOT EXISTS `{databaseName}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; " +
  60 + $"GRANT ALL PRIVILEGES ON `{databaseName}`.* TO '{userId}'@'%'; " +
  61 + $"再调用 initialize-tenant-database 补跑建表与 Seed");
  62 + }
  63 +
  64 + TryGrantTenantDatabaseAccess(
  65 + dbType,
  66 + privilegedConnectionString,
  67 + databaseName,
  68 + tenantConnectionString);
  69 + }
  70 +
  71 + /// <summary>
  72 + /// 建库连接候选(按优先级,互不相同才尝试下一条)。
  73 + /// </summary>
  74 + internal static List<(string Label, string ConnectionString)> BuildCreateDatabaseCandidates(
  75 + DbConnOptions dbConnOptions,
  76 + string tenantConnectionString)
  77 + {
  78 + var createCandidates = new List<(string Label, string ConnectionString)>();
  79 + void AddCandidate(string label, string? conn)
  80 + {
  81 + if (string.IsNullOrWhiteSpace(conn))
  82 + {
  83 + return;
  84 + }
  85 +
  86 + if (createCandidates.Any(x =>
  87 + string.Equals(x.ConnectionString, conn, StringComparison.OrdinalIgnoreCase)))
  88 + {
  89 + return;
  90 + }
  91 +
  92 + createCandidates.Add((label, conn));
  93 + }
  94 +
  95 + AddCandidate("AdminConnectionString", dbConnOptions.AdminConnectionString);
  96 + AddCandidate("DbConnOptions.Url(主库)", dbConnOptions.Url);
  97 + AddCandidate(
  98 + "实例级(无database)",
  99 + BuildServerLevelConnectionString(
  100 + !string.IsNullOrWhiteSpace(dbConnOptions.Url)
  101 + ? dbConnOptions.Url!
  102 + : tenantConnectionString));
  103 +
  104 + return createCandidates;
  105 + }
  106 +
  107 + private static void ExecuteCreateDatabase(DbType dbType, string connectionString, string databaseName)
  108 + {
  109 + using var createDb = new SqlSugarClient(new ConnectionConfig
  110 + {
  111 + ConfigId = $"tenant-create-db-{databaseName}-{Guid.NewGuid():N}",
  112 + DbType = dbType,
  113 + ConnectionString = connectionString,
  114 + IsAutoCloseConnection = true
  115 + });
  116 +
  117 + createDb.Ado.ExecuteCommand(
  118 + $"CREATE DATABASE IF NOT EXISTS `{databaseName}` " +
  119 + "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
  120 + }
  121 +
  122 + /// <summary>
  123 + /// 授权业务账号访问新租户库;失败不抛(建表阶段仍可用高权限连接)。
  124 + /// </summary>
  125 + private static void TryGrantTenantDatabaseAccess(
  126 + DbType dbType,
  127 + string privilegedConnectionString,
  128 + string databaseName,
  129 + string tenantConnectionString)
  130 + {
  131 + var appUserId = ExtractConnectionValue(tenantConnectionString, "uid");
  132 + var privilegedUserId = ExtractConnectionValue(privilegedConnectionString, "uid");
  133 + if (string.IsNullOrWhiteSpace(appUserId))
  134 + {
  135 + return;
  136 + }
  137 +
  138 + if (string.Equals(appUserId, privilegedUserId, StringComparison.OrdinalIgnoreCase))
  139 + {
  140 + return;
  141 + }
  142 +
  143 + try
  144 + {
  145 + using var grantDb = new SqlSugarClient(new ConnectionConfig
  146 + {
  147 + ConfigId = $"tenant-grant-{databaseName}-{Guid.NewGuid():N}",
  148 + DbType = dbType,
  149 + ConnectionString = privilegedConnectionString,
  150 + IsAutoCloseConnection = true
  151 + });
  152 +
  153 + grantDb.Ado.ExecuteCommand(
  154 + $"GRANT ALL PRIVILEGES ON `{databaseName}`.* TO '{EscapeSqlLiteral(appUserId)}'@'%'");
  155 + }
  156 + catch
  157 + {
  158 + // GRANT 失败不阻断:后续 Init 仍可用高权限连接建表
  159 + }
  160 + }
  161 +
  162 + private static string BuildServerLevelConnectionString(string connectionString)
  163 + {
  164 + var segments = connectionString
  165 + .Split(';', StringSplitOptions.RemoveEmptyEntries)
  166 + .Select(x => x.Trim())
  167 + .Where(x => !x.StartsWith("database=", StringComparison.OrdinalIgnoreCase)
  168 + && !x.StartsWith("initial catalog=", StringComparison.OrdinalIgnoreCase))
  169 + .ToList();
  170 + return string.Join(';', segments) + ";";
  171 + }
  172 +
  173 + private static string GetRootMessage(Exception ex)
  174 + {
  175 + var current = ex;
  176 + while (current.InnerException != null)
  177 + {
  178 + current = current.InnerException;
  179 + }
  180 +
  181 + return current.Message;
  182 + }
  183 +
  184 + private static string EscapeSqlLiteral(string value)
  185 + => value.Replace("'", "''", StringComparison.Ordinal);
  186 +
  187 + private static string? ExtractConnectionValue(string connectionString, string key)
  188 + {
  189 + if (string.IsNullOrWhiteSpace(connectionString))
  190 + {
  191 + return null;
  192 + }
  193 +
  194 + var prefix = key + "=";
  195 + foreach (var segment in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries))
  196 + {
  197 + var part = segment.Trim();
  198 + if (part.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  199 + {
  200 + return part[prefix.Length..].Trim();
  201 + }
  202 + }
  203 +
  204 + return null;
  205 + }
  206 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantSelectCredentialCipher.cs
... ... @@ -48,4 +48,35 @@ public class TenantSelectCredentialCipher : ITransientDependency
48 48  
49 49 return (Convert.ToBase64String(cipherBytes), Convert.ToBase64String(iv));
50 50 }
  51 +
  52 + /// <summary>
  53 + /// 解密前端传入的 AES-CBC 密码(Base64 密文 + Base64 IV)
  54 + /// </summary>
  55 + public string DecryptPassword(string password, string passwordSalt)
  56 + {
  57 + if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(passwordSalt))
  58 + {
  59 + throw new UserFriendlyException("密码解密失败");
  60 + }
  61 +
  62 + try
  63 + {
  64 + var cipherBytes = Convert.FromBase64String(password);
  65 + var iv = Convert.FromBase64String(passwordSalt);
  66 +
  67 + using var aes = Aes.Create();
  68 + aes.Key = _key;
  69 + aes.IV = iv;
  70 + aes.Mode = CipherMode.CBC;
  71 + aes.Padding = PaddingMode.PKCS7;
  72 +
  73 + using var decryptor = aes.CreateDecryptor();
  74 + var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
  75 + return Encoding.UTF8.GetString(plainBytes);
  76 + }
  77 + catch (Exception ex) when (ex is not UserFriendlyException)
  78 + {
  79 + throw new UserFriendlyException("密码解密失败");
  80 + }
  81 + }
51 82 }
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/ThSaasMenuPermissionCatalog.cs 0 → 100644
  1 +using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
  2 +
  3 +namespace FoodLabeling.Th.Application.MultiTenancy;
  4 +
  5 +/// <summary>
  6 +/// 泰额版 SaaS 菜单权限目录(与前端 saas-menu-tree 一致)
  7 +/// </summary>
  8 +public static class ThSaasMenuPermissionCatalog
  9 +{
  10 + private static readonly Lazy<IReadOnlyList<ThSaasMenuPermissionTreeNodeDto>> TreeLazy =
  11 + new(BuildTree);
  12 +
  13 + private static readonly Lazy<HashSet<string>> AllKeysLazy =
  14 + new(() => new HashSet<string>(CollectAllKeys(TreeLazy.Value), StringComparer.OrdinalIgnoreCase));
  15 +
  16 + /// <summary>
  17 + /// 菜单权限树
  18 + /// </summary>
  19 + public static IReadOnlyList<ThSaasMenuPermissionTreeNodeDto> Tree => TreeLazy.Value;
  20 +
  21 + /// <summary>
  22 + /// 全部合法 permission key(含父节点)
  23 + /// </summary>
  24 + public static IReadOnlySet<string> AllKeys => AllKeysLazy.Value;
  25 +
  26 + /// <summary>
  27 + /// 校验 key 是否合法;返回非法 key 列表
  28 + /// </summary>
  29 + public static List<string> FindInvalidKeys(IEnumerable<string>? keys)
  30 + {
  31 + if (keys == null)
  32 + {
  33 + return new List<string>();
  34 + }
  35 +
  36 + return keys
  37 + .Where(x => !string.IsNullOrWhiteSpace(x))
  38 + .Select(x => x.Trim())
  39 + .Distinct(StringComparer.OrdinalIgnoreCase)
  40 + .Where(x => !AllKeys.Contains(x))
  41 + .ToList();
  42 + }
  43 +
  44 + private static IReadOnlyList<ThSaasMenuPermissionTreeNodeDto> BuildTree() =>
  45 + new List<ThSaasMenuPermissionTreeNodeDto>
  46 + {
  47 + Node("dashboard", "仪表盘", Node("dashboard:analytics", "数据分析")),
  48 + Node(
  49 + "labeling",
  50 + "标签管理",
  51 + Node("labeling:labels", "标签列表"),
  52 + Node("labeling:categories", "标签分类"),
  53 + Node("labeling:types", "标签类型"),
  54 + Node("labeling:templates", "标签模板"),
  55 + Node("labeling:multiple-options", "多选项")),
  56 + Node(
  57 + "modules",
  58 + "功能模块",
  59 + Node("modules:training", "培训"),
  60 + Node("modules:alerts", "告警"),
  61 + Node("modules:tasks", "任务"),
  62 + Node("modules:food-waste", "食物浪费"),
  63 + Node("modules:e-label", "电子标签")),
  64 + Node(
  65 + "management",
  66 + "系统管理",
  67 + Node("management:account", "账号管理"),
  68 + Node("management:menu", "菜单管理"),
  69 + Node("management:devices", "设备管理"),
  70 + Node("management:reports", "报表"),
  71 + Node("management:invoices", "发票"),
  72 + Node("management:qr-codes", "二维码"),
  73 + Node("management:support", "支持"),
  74 + Node("management:api", "API"))
  75 + };
  76 +
  77 + private static ThSaasMenuPermissionTreeNodeDto Node(
  78 + string key,
  79 + string title,
  80 + params ThSaasMenuPermissionTreeNodeDto[] children)
  81 + {
  82 + return new ThSaasMenuPermissionTreeNodeDto
  83 + {
  84 + Key = key,
  85 + Title = title,
  86 + Children = children.Length == 0 ? null : children.ToList()
  87 + };
  88 + }
  89 +
  90 + private static IEnumerable<string> CollectAllKeys(IEnumerable<ThSaasMenuPermissionTreeNodeDto> nodes)
  91 + {
  92 + foreach (var node in nodes)
  93 + {
  94 + yield return node.Key;
  95 + if (node.Children == null)
  96 + {
  97 + continue;
  98 + }
  99 +
  100 + foreach (var childKey in CollectAllKeys(node.Children))
  101 + {
  102 + yield return childKey;
  103 + }
  104 + }
  105 + }
  106 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/ThTenantDatabaseBackgroundInitializer.cs
... ... @@ -2,6 +2,7 @@ using System.Collections.Concurrent;
2 2 using Microsoft.Extensions.DependencyInjection;
3 3 using Microsoft.Extensions.Logging;
4 4 using Volo.Abp.DependencyInjection;
  5 +using Volo.Abp.Uow;
5 6 using Yi.Framework.TenantManagement.Application.Contracts;
6 7  
7 8 namespace FoodLabeling.Th.Application.MultiTenancy;
... ... @@ -43,8 +44,12 @@ public class ThTenantDatabaseBackgroundInitializer
43 44 _logger.LogInformation("租户 {TenantId} 业务库后台初始化开始", tenantId);
44 45  
45 46 using var scope = _scopeFactory.CreateScope();
  47 + var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
46 48 var tenantService = scope.ServiceProvider.GetRequiredService<ITenantService>();
  49 +
  50 + using var uow = uowManager.Begin(requiresNew: true, isTransactional: false);
47 51 await tenantService.InitAsync(tenantId);
  52 + await uow.CompleteAsync();
48 53  
49 54 _logger.LogInformation("租户 {TenantId} 业务库后台初始化完成", tenantId);
50 55 }
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThMultiTenancyAppService.cs
  1 +using System.Text.RegularExpressions;
1 2 using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
2   -
3 3 using FoodLabeling.Th.Application.Contracts.IServices;
4   -
  4 +using FoodLabeling.Th.Application.Contracts.Options;
5 5 using FoodLabeling.Th.Application.MultiTenancy;
6   -
  6 +using FoodLabeling.Th.Domain.Entities;
  7 +using FoodLabeling.Th.Domain.Shared.Helpers;
7 8 using Microsoft.AspNetCore.Authorization;
8   -
  9 +using Microsoft.AspNetCore.Mvc;
9 10 using Microsoft.Extensions.Options;
10   -
  11 +using SqlSugar;
  12 +using Volo.Abp;
  13 +using Volo.Abp.Application.Dtos;
11 14 using Volo.Abp.Application.Services;
12   -
  15 +using Volo.Abp.Caching;
  16 +using Volo.Abp.Domain.Entities;
13 17 using Volo.Abp.MultiTenancy;
14   -
  18 +using Volo.Abp.Uow;
  19 +using Yi.Framework.Rbac.Domain.Entities;
  20 +using Yi.Framework.Rbac.Domain.Helpers;
  21 +using Yi.Framework.Rbac.Domain.Shared.Consts;
15 22 using Yi.Framework.Rbac.Domain.Shared.Options;
16   -
  23 +using Yi.Framework.SqlSugarCore.Abstractions;
17 24 using Yi.Framework.TenantManagement.Application.Contracts;
18   -
19 25 using Yi.Framework.TenantManagement.Application.Contracts.Dtos;
20   -
21   -
  26 +using Yi.Framework.TenantManagement.Domain;
22 27  
23 28 namespace FoodLabeling.Th.Application.Services;
24 29  
25   -
26   -
27 30 /// <summary>
28   -
29   -/// 泰额版多租户:租户下拉与当前租户上下文
30   -
  31 +/// 泰额版多租户:租户下拉、公司列表与管理员凭据管理
31 32 /// </summary>
32   -
33 33 public class ThMultiTenancyAppService : ApplicationService, IThMultiTenancyAppService
34   -
35 34 {
  35 + private static readonly Guid ProtectedDefaultTenantId = Guid.Parse("11111111-1111-1111-1111-111111111111");
  36 + private const string ProtectedDefaultTenantName = "Default";
  37 + private static readonly HashSet<string> ProtectedDatabaseNames = new(StringComparer.OrdinalIgnoreCase)
  38 + {
  39 + "antis-foodlabeling-host",
  40 + "antis-foodlabeling-us"
  41 + };
  42 + private static readonly Regex SafeDatabaseNameRegex =
  43 + new(@"^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,63}$", RegexOptions.Compiled);
36 44  
37 45 private readonly ITenantService _tenantService;
38   -
  46 + private readonly ISqlSugarRepository<TenantAggregateRoot, Guid> _tenantRepository;
  47 + private readonly ISqlSugarRepository<ThTenantAdminCredentialEntity, Guid> _credentialRepository;
  48 + private readonly ISqlSugarRepository<ThTenantMenuPermissionEntity, string> _menuPermissionRepository;
39 49 private readonly TenantSelectCredentialCipher _credentialCipher;
40   -
41 50 private readonly RbacOptions _rbacOptions;
42   -
43   -
  51 + private readonly FoodLabelingThTenantDatabaseOptions _tenantDatabaseOptions;
  52 + private readonly DbConnOptions _dbConnOptions;
  53 + private readonly IDistributedCache<TenantCacheItem> _tenantCache;
44 54  
45 55 public ThMultiTenancyAppService(
46   -
47 56 ITenantService tenantService,
48   -
  57 + ISqlSugarRepository<TenantAggregateRoot, Guid> tenantRepository,
  58 + ISqlSugarRepository<ThTenantAdminCredentialEntity, Guid> credentialRepository,
  59 + ISqlSugarRepository<ThTenantMenuPermissionEntity, string> menuPermissionRepository,
49 60 TenantSelectCredentialCipher credentialCipher,
50   -
51   - IOptions<RbacOptions> rbacOptions)
52   -
  61 + IOptions<RbacOptions> rbacOptions,
  62 + IOptions<FoodLabelingThTenantDatabaseOptions> tenantDatabaseOptions,
  63 + IOptions<DbConnOptions> dbConnOptions,
  64 + IDistributedCache<TenantCacheItem> tenantCache)
53 65 {
54   -
55 66 _tenantService = tenantService;
56   -
  67 + _tenantRepository = tenantRepository;
  68 + _credentialRepository = credentialRepository;
  69 + _menuPermissionRepository = menuPermissionRepository;
57 70 _credentialCipher = credentialCipher;
58   -
59 71 _rbacOptions = rbacOptions.Value;
60   -
  72 + _tenantDatabaseOptions = tenantDatabaseOptions.Value;
  73 + _dbConnOptions = dbConnOptions.Value;
  74 + _tenantCache = tenantCache;
61 75 }
62 76  
63   -
64   -
65 77 /// <summary>
  78 + /// 主库表(DefaultTenantTable)读写须将 CurrentTenant 置空
  79 + /// </summary>
  80 + private IDisposable UseHostTenantScope() => CurrentTenant.Change(null);
66 81  
  82 + /// <summary>
67 83 /// 获取登录页可选租户列表(含默认管理员加密凭据)
68   -
69 84 /// </summary>
70   -
71 85 /// <remarks>
72   -
73 86 /// 供 Web 登录页租户下拉使用;匿名可访问。不返回租户 Id 与数据库连接串。
74   -
75 87 ///
  88 + /// 示例响应:
  89 + /// ```json
  90 + /// [
  91 + /// {
  92 + /// "name": "Default",
  93 + /// "creationTime": "2026-01-01T08:00:00",
  94 + /// "loginAccount": "admin",
  95 + /// "password": "Base64CipherText",
  96 + /// "passwordSalt": "Base64Iv"
  97 + /// }
  98 + /// ]
  99 + /// ```
  100 + ///
  101 + /// 字段说明:
  102 + /// - name: 租户名称,登录时可传 tenantName
  103 + /// - creationTime: 租户创建时间
  104 + /// - loginAccount: 管理员登录账号,优先读凭据表,否则为 admin
  105 + /// - password: 优先读凭据表 AES 密文,否则 RbacOptions.AdminPassword 加密后返回
  106 + /// - passwordSalt: AES IV(Base64),前端解密时使用
  107 + /// </remarks>
  108 + /// <returns>租户下拉列表</returns>
  109 + /// <response code="200">成功返回租户列表</response>
  110 + /// <response code="500">加密配置缺失或服务器错误</response>
  111 + [AllowAnonymous]
  112 + public virtual async Task<List<ThTenantSelectDto>> GetTenantSelectAsync()
  113 + {
  114 + var page = await _tenantService.GetListAsync(new TenantGetListInput
  115 + {
  116 + SkipCount = 0,
  117 + MaxResultCount = 500
  118 + });
  119 +
  120 + var credentialMap = await LoadCredentialMapAsync(page.Items.Select(x => x.Id).ToList());
76 121  
  122 + return page.Items
  123 + .Select(x =>
  124 + {
  125 + credentialMap.TryGetValue(x.Id, out var credential);
  126 + var resolved = ResolveEncryptedCredential(credential);
  127 + return new ThTenantSelectDto
  128 + {
  129 + Name = x.Name,
  130 + CreationTime = x.CreationTime,
  131 + LoginAccount = resolved.LoginAccount,
  132 + Password = resolved.Password,
  133 + PasswordSalt = resolved.PasswordSalt
  134 + };
  135 + })
  136 + .OrderBy(x => x.Name)
  137 + .ToList();
  138 + }
  139 +
  140 + /// <summary>
  141 + /// 平台管理员分页获取公司(租户)列表及可回显加密凭据
  142 + /// </summary>
  143 + /// <remarks>
  144 + /// 需登录;查询主库 YiTenant,密码优先读 fl_th_tenant_admin_credential,否则回退 RbacOptions.AdminPassword 再 AES 加密返回。
  145 + ///
  146 + /// 示例请求(GET,query/data):
  147 + /// ```json
  148 + /// {
  149 + /// "keyword": "测试",
  150 + /// "skipCount": 0,
  151 + /// "maxResultCount": 20
  152 + /// }
  153 + /// ```
  154 + ///
77 155 /// 示例响应:
  156 + /// ```json
  157 + /// {
  158 + /// "totalCount": 1,
  159 + /// "items": [
  160 + /// {
  161 + /// "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  162 + /// "name": "测试公司",
  163 + /// "creationTime": "2026-01-01T08:00:00",
  164 + /// "loginAccount": "admin",
  165 + /// "password": "Base64CipherText",
  166 + /// "passwordSalt": "Base64Iv"
  167 + /// }
  168 + /// ]
  169 + /// }
  170 + /// ```
  171 + ///
  172 + /// 参数说明:
  173 + /// - keyword/name: 租户名称模糊匹配(keyword 优先)
  174 + /// - skipCount: 跳过条数
  175 + /// - maxResultCount: 每页条数
  176 + /// </remarks>
  177 + /// <param name="input">分页与筛选条件</param>
  178 + /// <returns>分页公司列表</returns>
  179 + /// <response code="200">成功返回分页列表</response>
  180 + /// <response code="401">未登录</response>
  181 + /// <response code="500">服务器错误</response>
  182 + [Authorize]
  183 + [HttpGet("th-multi-tenancy/company-list")]
  184 + public virtual async Task<PagedResultDto<ThCompanyListItemDto>> GetCompanyListAsync(ThCompanyListInput input)
  185 + {
  186 + var nameFilter = !string.IsNullOrWhiteSpace(input.Keyword) ? input.Keyword : input.Name;
  187 +
  188 + var page = await _tenantService.GetListAsync(new TenantGetListInput
  189 + {
  190 + Name = nameFilter,
  191 + SkipCount = input.SkipCount,
  192 + MaxResultCount = input.MaxResultCount
  193 + });
  194 +
  195 + var tenantIds = page.Items.Select(x => x.Id).ToList();
  196 + var credentialMap = await LoadCredentialMapAsync(tenantIds);
  197 + var menuPermissionMap = await LoadMenuPermissionMapAsync(tenantIds);
78 198  
  199 + var items = page.Items.Select(x =>
  200 + {
  201 + credentialMap.TryGetValue(x.Id, out var credential);
  202 + var resolved = ResolveEncryptedCredential(credential);
  203 + menuPermissionMap.TryGetValue(x.Id, out var menuKeys);
  204 + return new ThCompanyListItemDto
  205 + {
  206 + Id = x.Id,
  207 + Name = x.Name,
  208 + CreationTime = x.CreationTime,
  209 + LoginAccount = resolved.LoginAccount,
  210 + Password = resolved.Password,
  211 + PasswordSalt = resolved.PasswordSalt,
  212 + MenuPermissionKeys = menuKeys ?? new List<string>()
  213 + };
  214 + }).ToList();
  215 +
  216 + return new PagedResultDto<ThCompanyListItemDto>(page.TotalCount, items);
  217 + }
  218 +
  219 + /// <summary>
  220 + /// 修改公司(租户)默认管理员登录账号与/或密码
  221 + /// </summary>
  222 + /// <remarks>
  223 + /// 需登录。password/passwordSalt 均为空时不改密码;有 password 时必须带 passwordSalt,后端解密后再写入租户库 User 哈希。
  224 + ///
  225 + /// 示例请求:
79 226 /// ```json
  227 + /// {
  228 + /// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  229 + /// "loginAccount": "admin",
  230 + /// "password": "Base64CipherText",
  231 + /// "passwordSalt": "Base64Iv"
  232 + /// }
  233 + /// ```
  234 + ///
  235 + /// 参数说明:
  236 + /// - tenantId: 租户 Id(必填)
  237 + /// - loginAccount: 新登录账号(可选)
  238 + /// - password: AES 加密新密码(可选)
  239 + /// - passwordSalt: AES IV(改密时必填)
  240 + /// </remarks>
  241 + /// <param name="input">租户 Id 与待修改凭据</param>
  242 + /// <returns>无内容</returns>
  243 + /// <response code="200">修改成功</response>
  244 + /// <response code="400">参数错误或账号重复</response>
  245 + /// <response code="401">未登录</response>
  246 + /// <response code="404">租户或管理员不存在</response>
  247 + /// <response code="500">服务器错误</response>
  248 + [Authorize]
  249 + [HttpPut("th-multi-tenancy/company-admin")]
  250 + public virtual async Task UpdateCompanyAdminAsync(ThUpdateCompanyAdminInputVo input)
  251 + {
  252 + if (input.TenantId == Guid.Empty)
  253 + {
  254 + throw new UserFriendlyException("租户 Id 不能为空");
  255 + }
80 256  
81   - /// [
  257 + var hasPassword = !string.IsNullOrWhiteSpace(input.Password);
  258 + if (hasPassword && string.IsNullOrWhiteSpace(input.PasswordSalt))
  259 + {
  260 + throw new UserFriendlyException("修改密码时必须提供 passwordSalt");
  261 + }
82 262  
83   - /// {
  263 + TenantAggregateRoot tenant;
  264 + ThTenantAdminCredentialEntity? existingCredential;
  265 + using (UseHostTenantScope())
  266 + {
  267 + tenant = await _tenantRepository.FindAsync(input.TenantId)
  268 + ?? throw new UserFriendlyException("租户不存在");
  269 + // 主键列 TenantId 映射到实体 Id,用 Queryable 按 Id 查询
  270 + var credentials = await _credentialRepository._DbQueryable
  271 + .Where(c => c.Id == input.TenantId)
  272 + .Take(1)
  273 + .ToListAsync();
  274 + existingCredential = credentials.FirstOrDefault();
  275 + }
  276 +
  277 + var currentLoginAccount = existingCredential?.LoginAccount?.Trim()
  278 + ?? ThTenantSelectConsts.DefaultAdminLoginAccount;
  279 + var newLoginAccount = !string.IsNullOrWhiteSpace(input.LoginAccount)
  280 + ? input.LoginAccount.Trim()
  281 + : currentLoginAccount;
  282 +
  283 + string? plainPassword = null;
  284 + if (hasPassword)
  285 + {
  286 + plainPassword = _credentialCipher.DecryptPassword(input.Password!, input.PasswordSalt!);
  287 + }
84 288  
85   - /// "name": "Default",
  289 + var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
  290 + using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
  291 + TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, input.TenantId);
86 292  
87   - /// "creationTime": "2026-01-01T08:00:00",
  293 + var adminUsers = await tenantDb.Queryable<UserAggregateRoot>()
  294 + .Where(u => u.UserName == currentLoginAccount && !u.IsDeleted)
  295 + .Take(1)
  296 + .ToListAsync();
  297 + var adminUser = adminUsers.FirstOrDefault()
  298 + ?? throw new UserFriendlyException("未找到租户管理员账号");
88 299  
89   - /// "loginAccount": "admin",
  300 + if (!string.Equals(newLoginAccount, currentLoginAccount, StringComparison.OrdinalIgnoreCase))
  301 + {
  302 + if (await tenantDb.Queryable<UserAggregateRoot>().AnyAsync(u =>
  303 + u.UserName == newLoginAccount && u.Id != adminUser.Id && !u.IsDeleted))
  304 + {
  305 + throw new UserFriendlyException(UserConst.Exist);
  306 + }
90 307  
91   - /// "password": "Base64CipherText",
  308 + await tenantDb.Updateable<UserAggregateRoot>()
  309 + .SetColumns(u => u.UserName == newLoginAccount)
  310 + .Where(u => u.Id == adminUser.Id)
  311 + .ExecuteCommandAsync();
  312 + }
92 313  
93   - /// "passwordSalt": "Base64Iv"
  314 + if (plainPassword != null)
  315 + {
  316 + UserPasswordHelper.ApplyPlainPassword(adminUser, plainPassword);
  317 + await tenantDb.Updateable<UserAggregateRoot>()
  318 + .SetColumns(u => u.EncryPassword.Password == adminUser.EncryPassword.Password)
  319 + .SetColumns(u => u.EncryPassword.Salt == adminUser.EncryPassword.Salt)
  320 + .Where(u => u.Id == adminUser.Id)
  321 + .ExecuteCommandAsync();
  322 + }
  323 +
  324 + await UpsertCredentialAsync(
  325 + input.TenantId,
  326 + newLoginAccount,
  327 + passwordChanged: plainPassword != null,
  328 + plainPassword,
  329 + existingCredential);
  330 + }
94 331  
  332 + /// <summary>
  333 + /// 获取 SaaS 菜单权限树
  334 + /// </summary>
  335 + /// <remarks>
  336 + /// 供平台管理员配置租户菜单权限时使用;Key 与前端 saas-menu-tree 一致。
  337 + ///
  338 + /// 示例响应:
  339 + /// ```json
  340 + /// [
  341 + /// {
  342 + /// "key": "dashboard",
  343 + /// "title": "仪表盘",
  344 + /// "children": [
  345 + /// { "key": "dashboard:analytics", "title": "数据分析" }
  346 + /// ]
95 347 /// }
96   -
97 348 /// ]
98   -
99 349 /// ```
  350 + /// </remarks>
  351 + /// <returns>SaaS 菜单权限树</returns>
  352 + /// <response code="200">成功返回权限树</response>
  353 + /// <response code="401">未登录</response>
  354 + /// <response code="500">服务器错误</response>
  355 + [Authorize]
  356 + [HttpGet("th-multi-tenancy/menu-permission-tree")]
  357 + public virtual Task<List<ThSaasMenuPermissionTreeNodeDto>> GetMenuPermissionTreeAsync()
  358 + {
  359 + return Task.FromResult(CloneTree(ThSaasMenuPermissionCatalog.Tree));
  360 + }
100 361  
  362 + /// <summary>
  363 + /// 获取公司(租户)已分配的 SaaS 菜单权限
  364 + /// </summary>
  365 + /// <remarks>
  366 + /// 需登录;读取主库 fl_th_tenant_menu_permission。
101 367 ///
  368 + /// 示例请求(GET,query/data):
  369 + /// ```json
  370 + /// { "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" }
  371 + /// ```
  372 + ///
  373 + /// 示例响应:
  374 + /// ```json
  375 + /// {
  376 + /// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  377 + /// "menuPermissionKeys": ["dashboard", "labeling:labels"]
  378 + /// }
  379 + /// ```
  380 + ///
  381 + /// 参数说明:
  382 + /// - tenantId: 租户 Id(必填)
  383 + /// </remarks>
  384 + /// <param name="tenantId">租户 Id</param>
  385 + /// <returns>租户菜单权限</returns>
  386 + /// <response code="200">成功返回菜单权限</response>
  387 + /// <response code="400">租户 Id 无效</response>
  388 + /// <response code="401">未登录</response>
  389 + /// <response code="404">租户不存在</response>
  390 + /// <response code="500">服务器错误</response>
  391 + [Authorize]
  392 + [HttpGet("th-multi-tenancy/company-menus")]
  393 + public virtual async Task<ThCompanyMenusDto> GetCompanyMenusAsync([FromQuery] Guid tenantId)
  394 + {
  395 + await EnsureTenantExistsAsync(tenantId);
  396 + var keys = await LoadMenuPermissionKeysAsync(tenantId);
  397 + return new ThCompanyMenusDto
  398 + {
  399 + TenantId = tenantId,
  400 + MenuPermissionKeys = keys
  401 + };
  402 + }
102 403  
103   - /// 字段说明:
  404 + /// <summary>
  405 + /// 覆盖式设置公司(租户)SaaS 菜单权限
  406 + /// </summary>
  407 + /// <remarks>
  408 + /// 需登录;写入主库 fl_th_tenant_menu_permission(先删后插)。非法 permission key 将报错。
  409 + ///
  410 + /// 示例请求:
  411 + /// ```json
  412 + /// {
  413 + /// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  414 + /// "menuPermissionKeys": ["dashboard", "labeling:labels"]
  415 + /// }
  416 + /// ```
  417 + ///
  418 + /// 参数说明:
  419 + /// - tenantId: 租户 Id(必填)
  420 + /// - menuPermissionKeys: 菜单权限 Key 列表(覆盖式,可为空表示清空)
  421 + /// </remarks>
  422 + /// <param name="input">租户 Id 与菜单权限 Key 列表</param>
  423 + /// <returns>无内容</returns>
  424 + /// <response code="200">设置成功</response>
  425 + /// <response code="400">参数错误或存在非法 permission key</response>
  426 + /// <response code="401">未登录</response>
  427 + /// <response code="404">租户不存在</response>
  428 + /// <response code="500">服务器错误</response>
  429 + [Authorize]
  430 + [HttpPut("th-multi-tenancy/company-menus")]
  431 + [UnitOfWork]
  432 + public virtual async Task UpdateCompanyMenusAsync([FromBody] ThUpdateCompanyMenusInputVo input)
  433 + {
  434 + if (input.TenantId == Guid.Empty)
  435 + {
  436 + throw new UserFriendlyException("租户 Id 不能为空");
  437 + }
104 438  
105   - /// - name: 租户名称,登录时可传 tenantName
  439 + await EnsureTenantExistsAsync(input.TenantId);
106 440  
107   - /// - creationTime: 租户创建时间
  441 + var normalizedKeys = NormalizePermissionKeys(input.MenuPermissionKeys);
  442 + var invalidKeys = ThSaasMenuPermissionCatalog.FindInvalidKeys(normalizedKeys);
  443 + if (invalidKeys.Count > 0)
  444 + {
  445 + throw new UserFriendlyException($"存在非法菜单权限 Key:{string.Join(", ", invalidKeys)}");
  446 + }
108 447  
109   - /// - loginAccount: 种子管理员账号(UserName=admin,亦可用 admin@example.com 登录)
  448 + using (UseHostTenantScope())
  449 + {
  450 + await _menuPermissionRepository.DeleteAsync(x => x.TenantId == input.TenantId);
110 451  
111   - /// - password: RbacOptions.AdminPassword 经 AES-CBC 加密后的 Base64 密文
  452 + if (normalizedKeys.Count == 0)
  453 + {
  454 + return;
  455 + }
112 456  
113   - /// - passwordSalt: AES IV(Base64),前端解密时使用
  457 + var now = DateTime.Now;
  458 + var entities = normalizedKeys.Select(key => new ThTenantMenuPermissionEntity
  459 + {
  460 + Id = YitIdHelper.NextId().ToString(),
  461 + TenantId = input.TenantId,
  462 + PermissionKey = key,
  463 + CreationTime = now
  464 + }).ToList();
  465 +
  466 + await _menuPermissionRepository.InsertRangeAsync(entities);
  467 + }
  468 + }
114 469  
  470 + /// <summary>
  471 + /// 获取租户内角色及已绑定菜单 Id
  472 + /// </summary>
  473 + /// <remarks>
  474 + /// 需登录;在指定租户业务库查询 Role / RoleMenu。
  475 + ///
  476 + /// 示例请求(GET,query/data):
  477 + /// ```json
  478 + /// { "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" }
  479 + /// ```
  480 + ///
  481 + /// 示例响应:
  482 + /// ```json
  483 + /// [
  484 + /// {
  485 + /// "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  486 + /// "roleName": "管理员",
  487 + /// "roleCode": "admin",
  488 + /// "state": true,
  489 + /// "menuIds": ["11111111-1111-1111-1111-111111111111"]
  490 + /// }
  491 + /// ]
  492 + /// ```
  493 + ///
  494 + /// 参数说明:
  495 + /// - tenantId: 租户 Id(必填)
115 496 /// </remarks>
  497 + /// <param name="tenantId">租户 Id</param>
  498 + /// <returns>角色及菜单绑定列表</returns>
  499 + /// <response code="200">成功返回角色列表</response>
  500 + /// <response code="400">租户 Id 无效</response>
  501 + /// <response code="401">未登录</response>
  502 + /// <response code="404">租户不存在</response>
  503 + /// <response code="500">服务器错误</response>
  504 + [Authorize]
  505 + [HttpGet("th-multi-tenancy/company-roles")]
  506 + public virtual async Task<List<ThCompanyRoleItemDto>> GetCompanyRolesAsync([FromQuery] Guid tenantId)
  507 + {
  508 + var tenant = await EnsureTenantExistsAsync(tenantId);
  509 + var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
  510 + using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
  511 + TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, tenantId);
116 512  
117   - /// <returns>租户下拉列表</returns>
  513 + var roles = await tenantDb.Queryable<RoleAggregateRoot>()
  514 + .Where(r => !r.IsDeleted)
  515 + .OrderBy(r => r.OrderNum)
  516 + .ToListAsync();
118 517  
119   - /// <response code="200">成功返回租户列表</response>
  518 + if (roles.Count == 0)
  519 + {
  520 + return new List<ThCompanyRoleItemDto>();
  521 + }
120 522  
121   - /// <response code="500">加密配置缺失或服务器错误</response>
  523 + var roleIds = roles.Select(r => r.Id).ToList();
  524 + var roleMenuLinks = await tenantDb.Queryable<RoleMenuEntity>()
  525 + .Where(rm => roleIds.Contains(rm.RoleId))
  526 + .ToListAsync();
122 527  
123   - [AllowAnonymous]
  528 + var menuIdsByRole = roleMenuLinks
  529 + .GroupBy(x => x.RoleId)
  530 + .ToDictionary(
  531 + g => g.Key,
  532 + g => g.Select(x => x.MenuId.ToString()).ToList());
124 533  
125   - public virtual async Task<List<ThTenantSelectDto>> GetTenantSelectAsync()
  534 + return roles.Select(role => new ThCompanyRoleItemDto
  535 + {
  536 + Id = role.Id,
  537 + RoleName = role.RoleName,
  538 + RoleCode = role.RoleCode,
  539 + State = role.State,
  540 + MenuIds = menuIdsByRole.TryGetValue(role.Id, out var menuIds)
  541 + ? menuIds
  542 + : new List<string>()
  543 + }).ToList();
  544 + }
126 545  
  546 + /// <summary>
  547 + /// 覆盖式设置租户内角色的菜单绑定
  548 + /// </summary>
  549 + /// <remarks>
  550 + /// 需登录;在指定租户业务库覆盖写入 RoleMenu,逻辑对齐 RbacRoleMenuAppService.Set。
  551 + ///
  552 + /// 示例请求:
  553 + /// ```json
  554 + /// {
  555 + /// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  556 + /// "roleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  557 + /// "menuIds": ["11111111-1111-1111-1111-111111111111"]
  558 + /// }
  559 + /// ```
  560 + ///
  561 + /// 参数说明:
  562 + /// - tenantId: 租户 Id(必填)
  563 + /// - roleId: 角色 Id(必填)
  564 + /// - menuIds: 菜单 Id 列表(覆盖式,可为空表示清空)
  565 + /// </remarks>
  566 + /// <param name="input">租户、角色与菜单 Id 列表</param>
  567 + /// <returns>无内容</returns>
  568 + /// <response code="200">设置成功</response>
  569 + /// <response code="400">参数错误或菜单 Id 无效</response>
  570 + /// <response code="401">未登录</response>
  571 + /// <response code="404">租户或角色不存在</response>
  572 + /// <response code="500">服务器错误</response>
  573 + [Authorize]
  574 + [HttpPut("th-multi-tenancy/company-role-menus")]
  575 + [UnitOfWork]
  576 + public virtual async Task UpdateCompanyRoleMenusAsync([FromBody] ThUpdateCompanyRoleMenusInputVo input)
127 577 {
  578 + if (input.TenantId == Guid.Empty)
  579 + {
  580 + throw new UserFriendlyException("租户 Id 不能为空");
  581 + }
128 582  
129   - var page = await _tenantService.GetListAsync(new TenantGetListInput
130   -
  583 + if (input.RoleId == Guid.Empty)
  584 + {
  585 + throw new UserFriendlyException("角色 Id 不能为空");
  586 + }
  587 +
  588 + var tenant = await EnsureTenantExistsAsync(input.TenantId);
  589 + var menuIds = ParseMenuIds(input.MenuIds);
  590 + var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
  591 + using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
  592 + TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, input.TenantId);
  593 +
  594 + var roles = await tenantDb.Queryable<RoleAggregateRoot>()
  595 + .Where(x => x.Id == input.RoleId && !x.IsDeleted)
  596 + .Take(1)
  597 + .ToListAsync();
  598 + var role = roles.FirstOrDefault();
  599 + if (role is null)
131 600 {
  601 + throw new UserFriendlyException("角色不存在");
  602 + }
132 603  
133   - SkipCount = 1,
  604 + if (menuIds.Count == 0)
  605 + {
  606 + await tenantDb.Deleteable<RoleMenuEntity>()
  607 + .Where(x => x.RoleId == input.RoleId)
  608 + .ExecuteCommandAsync();
  609 + return;
  610 + }
  611 +
  612 + var existMenuIds = await tenantDb.Queryable<MenuAggregateRoot>()
  613 + .Where(x => !x.IsDeleted)
  614 + .Where(x => menuIds.Contains(x.Id))
  615 + .Select(x => x.Id)
  616 + .ToListAsync();
  617 +
  618 + var missingMenuIds = menuIds.Except(existMenuIds).ToList();
  619 + if (missingMenuIds.Count > 0)
  620 + {
  621 + throw new UserFriendlyException(
  622 + $"存在无效或未删除的菜单 Id:{string.Join(", ", missingMenuIds)}");
  623 + }
134 624  
135   - MaxResultCount = 500
  625 + await tenantDb.Deleteable<RoleMenuEntity>()
  626 + .Where(x => x.RoleId == input.RoleId)
  627 + .ExecuteCommandAsync();
136 628  
137   - });
  629 + var entities = existMenuIds.Select(menuId =>
  630 + {
  631 + var entity = new RoleMenuEntity
  632 + {
  633 + RoleId = input.RoleId,
  634 + MenuId = menuId
  635 + };
  636 + EntityHelper.TrySetId(entity, () => GuidGenerator.Create());
  637 + return entity;
  638 + }).ToList();
  639 +
  640 + if (entities.Count > 0)
  641 + {
  642 + await tenantDb.Insertable(entities).ExecuteCommandAsync();
  643 + }
  644 + }
138 645  
  646 + /// <summary>
  647 + /// 删除公司(租户),可选 DROP 对应业务库
  648 + /// </summary>
  649 + /// <remarks>
  650 + /// 需登录。在主库 scope 执行:校验非 Default 租户后,按 dropDatabase 决定是否 DROP 业务库;
  651 + /// 删除 YiTenant(软删)及 fl_th_tenant_admin_credential、fl_th_tenant_menu_permission 附属记录,并清理租户缓存。
  652 + ///
  653 + /// 受保护规则:禁止删除 Name=Default 或 Id=11111111-1111-1111-1111-111111111111;
  654 + /// 禁止 DROP antis-foodlabeling-host、antis-foodlabeling-us;
  655 + /// 连接串为空或库名解析/校验失败时仅删主库记录,不 DROP。
  656 + ///
  657 + /// 示例请求(DELETE):
  658 + /// ```
  659 + /// DELETE /api/app/th-multi-tenancy/company/3a227b24-3d9b-ea2d-81f3-6c4fedccb1d2?dropDatabase=true
  660 + /// ```
  661 + ///
  662 + /// 示例响应:
  663 + /// ```json
  664 + /// {
  665 + /// "tenantId": "3a227b24-3d9b-ea2d-81f3-6c4fedccb1d2",
  666 + /// "name": "中国麦当劳公司",
  667 + /// "databaseName": "antis-foodlabeling-t46d56528",
  668 + /// "databaseDropped": true,
  669 + /// "tenantDeleted": true,
  670 + /// "message": null
  671 + /// }
  672 + /// ```
  673 + ///
  674 + /// 参数说明:
  675 + /// - tenantId: 租户 Id(路径参数,必填)
  676 + /// - dropDatabase: 是否 DROP 业务库,默认 true
  677 + /// </remarks>
  678 + /// <param name="tenantId">租户 Id</param>
  679 + /// <param name="dropDatabase">是否 DROP 业务库</param>
  680 + /// <returns>删除执行结果</returns>
  681 + /// <response code="200">删除成功或部分跳过 DROP 时返回结果</response>
  682 + /// <response code="400">租户 Id 无效或受保护租户</response>
  683 + /// <response code="401">未登录</response>
  684 + /// <response code="404">租户不存在</response>
  685 + /// <response code="500">DROP 或删除失败</response>
  686 + [Authorize]
  687 + [HttpDelete("th-multi-tenancy/company/{tenantId}")]
  688 + [UnitOfWork]
  689 + public virtual async Task<ThDeleteCompanyResultDto> DeleteCompanyAsync(
  690 + [FromRoute] Guid tenantId,
  691 + [FromQuery] bool dropDatabase = true)
  692 + {
  693 + if (tenantId == Guid.Empty)
  694 + {
  695 + throw new UserFriendlyException("租户 Id 不能为空");
  696 + }
139 697  
  698 + EnsureTenantDeletable(tenantId, null);
140 699  
141   - var adminPlainPassword = _rbacOptions.AdminPassword ?? string.Empty;
  700 + TenantAggregateRoot tenant;
  701 + using (UseHostTenantScope())
  702 + {
  703 + tenant = await _tenantRepository.FindAsync(tenantId)
  704 + ?? throw new UserFriendlyException("租户不存在");
  705 + }
142 706  
143   - return page.Items
  707 + EnsureTenantDeletable(tenant.Id, tenant.Name);
144 708  
145   - .Select(x =>
  709 + var databaseName = ExtractConnectionValue(tenant.TenantConnectionString, "database");
  710 + var result = new ThDeleteCompanyResultDto
  711 + {
  712 + TenantId = tenant.Id,
  713 + Name = tenant.Name,
  714 + DatabaseName = databaseName
  715 + };
146 716  
  717 + if (dropDatabase)
  718 + {
  719 + var dropDecision = EvaluateDatabaseDrop(databaseName);
  720 + if (dropDecision.CanDrop)
147 721 {
  722 + ExecuteDropDatabase(tenant.DbType, dropDecision.PrivilegedConnectionString!, databaseName!);
  723 + result.DatabaseDropped = true;
  724 + }
  725 + else
  726 + {
  727 + result.Message = dropDecision.SkipReason;
  728 + }
  729 + }
  730 + else
  731 + {
  732 + result.Message = "dropDatabase=false,已跳过 DROP DATABASE";
  733 + }
148 734  
149   - var encrypted = _credentialCipher.EncryptPassword(adminPlainPassword);
  735 + await _tenantService.DeleteAsync(new[] { tenantId });
  736 + result.TenantDeleted = true;
150 737  
151   - return new ThTenantSelectDto
  738 + using (UseHostTenantScope())
  739 + {
  740 + await _credentialRepository._Db.Ado.ExecuteCommandAsync(
  741 + "DELETE FROM `fl_th_tenant_admin_credential` WHERE `TenantId` = @TenantId",
  742 + new List<SugarParameter> { new("@TenantId", tenantId.ToString()) });
  743 +
  744 + await _menuPermissionRepository.DeleteAsync(x => x.TenantId == tenantId);
  745 + }
  746 +
  747 + await RemoveTenantCacheAsync(tenant.Id, tenant.Name);
  748 +
  749 + return result;
  750 + }
152 751  
  752 + /// <inheritdoc />
  753 + public virtual Task<ThCurrentTenantDto> GetCurrentTenantAsync()
  754 + {
  755 + return Task.FromResult(new ThCurrentTenantDto
  756 + {
  757 + TenantId = CurrentTenant.Id,
  758 + TenantName = CurrentTenant.Name
  759 + });
  760 + }
  761 +
  762 + private async Task<Dictionary<Guid, ThTenantAdminCredentialEntity>> LoadCredentialMapAsync(
  763 + IReadOnlyCollection<Guid> tenantIds)
  764 + {
  765 + if (tenantIds.Count == 0)
  766 + {
  767 + return new Dictionary<Guid, ThTenantAdminCredentialEntity>();
  768 + }
  769 +
  770 + using (UseHostTenantScope())
  771 + {
  772 + var list = await _credentialRepository._DbQueryable
  773 + .Where(c => tenantIds.Contains(c.Id))
  774 + .ToListAsync();
  775 + return list.ToDictionary(c => c.Id);
  776 + }
  777 + }
  778 +
  779 + private (string LoginAccount, string Password, string PasswordSalt) ResolveEncryptedCredential(
  780 + ThTenantAdminCredentialEntity? credential)
  781 + {
  782 + if (credential != null
  783 + && !string.IsNullOrEmpty(credential.PasswordCipher)
  784 + && !string.IsNullOrEmpty(credential.PasswordIv))
  785 + {
  786 + var loginAccount = string.IsNullOrWhiteSpace(credential.LoginAccount)
  787 + ? ThTenantSelectConsts.DefaultAdminLoginAccount
  788 + : credential.LoginAccount;
  789 + return (loginAccount, credential.PasswordCipher, credential.PasswordIv);
  790 + }
  791 +
  792 + var plainPassword = _rbacOptions.AdminPassword ?? string.Empty;
  793 + var encrypted = _credentialCipher.EncryptPassword(plainPassword);
  794 + var account = string.IsNullOrWhiteSpace(credential?.LoginAccount)
  795 + ? ThTenantSelectConsts.DefaultAdminLoginAccount
  796 + : credential!.LoginAccount;
  797 + return (account, encrypted.Password, encrypted.PasswordSalt);
  798 + }
  799 +
  800 + private async Task UpsertCredentialAsync(
  801 + Guid tenantId,
  802 + string loginAccount,
  803 + bool passwordChanged,
  804 + string? plainPassword,
  805 + ThTenantAdminCredentialEntity? existingCredential)
  806 + {
  807 + string passwordCipher;
  808 + string passwordIv;
  809 +
  810 + if (passwordChanged)
  811 + {
  812 + var encrypted = _credentialCipher.EncryptPassword(plainPassword!);
  813 + passwordCipher = encrypted.Password;
  814 + passwordIv = encrypted.PasswordSalt;
  815 + }
  816 + else if (existingCredential != null
  817 + && !string.IsNullOrEmpty(existingCredential.PasswordCipher)
  818 + && !string.IsNullOrEmpty(existingCredential.PasswordIv))
  819 + {
  820 + passwordCipher = existingCredential.PasswordCipher;
  821 + passwordIv = existingCredential.PasswordIv;
  822 + }
  823 + else
  824 + {
  825 + var encrypted = _credentialCipher.EncryptPassword(_rbacOptions.AdminPassword ?? string.Empty);
  826 + passwordCipher = encrypted.Password;
  827 + passwordIv = encrypted.PasswordSalt;
  828 + }
  829 +
  830 + using (UseHostTenantScope())
  831 + {
  832 + var now = DateTime.Now;
  833 + // 使用 Ado 参数化写入,避免实体映射差异导致 Insertable NRE
  834 + if (existingCredential == null)
  835 + {
  836 + await _credentialRepository._Db.Ado.ExecuteCommandAsync(
  837 + @"INSERT INTO `fl_th_tenant_admin_credential`
  838 + (`TenantId`, `LoginAccount`, `PasswordCipher`, `PasswordIv`, `LastModificationTime`)
  839 + VALUES (@TenantId, @LoginAccount, @PasswordCipher, @PasswordIv, @LastModificationTime)",
  840 + new List<SugarParameter>
  841 + {
  842 + new("@TenantId", tenantId.ToString()),
  843 + new("@LoginAccount", loginAccount),
  844 + new("@PasswordCipher", passwordCipher),
  845 + new("@PasswordIv", passwordIv),
  846 + new("@LastModificationTime", now)
  847 + });
  848 + return;
  849 + }
  850 +
  851 + await _credentialRepository._Db.Ado.ExecuteCommandAsync(
  852 + @"UPDATE `fl_th_tenant_admin_credential`
  853 + SET `LoginAccount` = @LoginAccount,
  854 + `PasswordCipher` = @PasswordCipher,
  855 + `PasswordIv` = @PasswordIv,
  856 + `LastModificationTime` = @LastModificationTime
  857 + WHERE `TenantId` = @TenantId",
  858 + new List<SugarParameter>
153 859 {
  860 + new("@TenantId", tenantId.ToString()),
  861 + new("@LoginAccount", loginAccount),
  862 + new("@PasswordCipher", passwordCipher),
  863 + new("@PasswordIv", passwordIv),
  864 + new("@LastModificationTime", now)
  865 + });
  866 + }
  867 + }
154 868  
155   - Name = x.Name,
  869 + private async Task<TenantAggregateRoot> EnsureTenantExistsAsync(Guid tenantId)
  870 + {
  871 + if (tenantId == Guid.Empty)
  872 + {
  873 + throw new UserFriendlyException("租户 Id 不能为空");
  874 + }
156 875  
157   - CreationTime = x.CreationTime,
  876 + using (UseHostTenantScope())
  877 + {
  878 + return await _tenantRepository.FindAsync(tenantId)
  879 + ?? throw new UserFriendlyException("租户不存在");
  880 + }
  881 + }
158 882  
159   - LoginAccount = ThTenantSelectConsts.DefaultAdminLoginAccount,
  883 + /// <summary>
  884 + /// 解析租户业务库连接串(必要时按配置回填主库 YiTenant),供直连 SqlSugar 使用。
  885 + /// </summary>
  886 + private Task<(string ConnectionString, DbType DbType)> ResolveTenantBusinessConnectionAsync(
  887 + TenantAggregateRoot tenant)
  888 + {
  889 + return TenantBusinessDatabaseAccessor.ResolveConnectionAsync(
  890 + tenant,
  891 + _tenantDatabaseOptions,
  892 + PersistTenantConnectionStringAsync);
  893 + }
160 894  
161   - Password = encrypted.Password,
  895 + private async Task PersistTenantConnectionStringAsync(TenantAggregateRoot tenant)
  896 + {
  897 + using (UseHostTenantScope())
  898 + {
  899 + await _tenantRepository.UpdateAsync(tenant);
  900 + }
  901 + }
162 902  
163   - PasswordSalt = encrypted.PasswordSalt
  903 + private async Task<List<string>> LoadMenuPermissionKeysAsync(Guid tenantId)
  904 + {
  905 + using (UseHostTenantScope())
  906 + {
  907 + return await _menuPermissionRepository._DbQueryable
  908 + .Where(x => x.TenantId == tenantId)
  909 + .OrderBy(x => x.CreationTime)
  910 + .Select(x => x.PermissionKey)
  911 + .ToListAsync();
  912 + }
  913 + }
164 914  
165   - };
  915 + private async Task<Dictionary<Guid, List<string>>> LoadMenuPermissionMapAsync(
  916 + IReadOnlyCollection<Guid> tenantIds)
  917 + {
  918 + if (tenantIds.Count == 0)
  919 + {
  920 + return new Dictionary<Guid, List<string>>();
  921 + }
166 922  
167   - })
  923 + using (UseHostTenantScope())
  924 + {
  925 + var list = await _menuPermissionRepository._DbQueryable
  926 + .Where(x => tenantIds.Contains(x.TenantId))
  927 + .ToListAsync();
  928 +
  929 + return list
  930 + .GroupBy(x => x.TenantId)
  931 + .ToDictionary(
  932 + g => g.Key,
  933 + g => g.Select(x => x.PermissionKey).Distinct(StringComparer.OrdinalIgnoreCase).ToList());
  934 + }
  935 + }
168 936  
169   - .OrderBy(x => x.Name)
  937 + private static List<string> NormalizePermissionKeys(IEnumerable<string>? keys)
  938 + {
  939 + if (keys == null)
  940 + {
  941 + return new List<string>();
  942 + }
170 943  
  944 + return keys
  945 + .Where(x => !string.IsNullOrWhiteSpace(x))
  946 + .Select(x => x.Trim())
  947 + .Distinct(StringComparer.OrdinalIgnoreCase)
171 948 .ToList();
172   -
173 949 }
174 950  
  951 + private static List<Guid> ParseMenuIds(IEnumerable<string>? menuIds)
  952 + {
  953 + if (menuIds == null)
  954 + {
  955 + return new List<Guid>();
  956 + }
175 957  
  958 + var result = new List<Guid>();
  959 + var invalid = new List<string>();
176 960  
177   - /// <inheritdoc />
  961 + foreach (var raw in menuIds.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct())
  962 + {
  963 + if (Guid.TryParse(raw, out var id))
  964 + {
  965 + result.Add(id);
  966 + }
  967 + else
  968 + {
  969 + invalid.Add(raw);
  970 + }
  971 + }
178 972  
179   - public virtual Task<ThCurrentTenantDto> GetCurrentTenantAsync()
  973 + if (invalid.Count > 0)
  974 + {
  975 + throw new UserFriendlyException($"菜单 Id 格式无效:{string.Join(", ", invalid)}");
  976 + }
180 977  
  978 + return result;
  979 + }
  980 +
  981 + private static List<ThSaasMenuPermissionTreeNodeDto> CloneTree(
  982 + IEnumerable<ThSaasMenuPermissionTreeNodeDto> nodes)
181 983 {
  984 + return nodes.Select(node => new ThSaasMenuPermissionTreeNodeDto
  985 + {
  986 + Key = node.Key,
  987 + Title = node.Title,
  988 + Children = node.Children == null ? null : CloneTree(node.Children)
  989 + }).ToList();
  990 + }
182 991  
183   - return Task.FromResult(new ThCurrentTenantDto
  992 + private static void EnsureTenantDeletable(Guid tenantId, string? tenantName)
  993 + {
  994 + if (tenantId == ProtectedDefaultTenantId)
  995 + {
  996 + throw new UserFriendlyException("禁止删除 Default 租户");
  997 + }
184 998  
  999 + if (string.Equals(tenantName, ProtectedDefaultTenantName, StringComparison.Ordinal))
185 1000 {
  1001 + throw new UserFriendlyException("禁止删除 Default 租户");
  1002 + }
  1003 + }
186 1004  
187   - TenantId = CurrentTenant.Id,
  1005 + private (bool CanDrop, string? PrivilegedConnectionString, string? SkipReason) EvaluateDatabaseDrop(
  1006 + string? databaseName)
  1007 + {
  1008 + if (string.IsNullOrWhiteSpace(databaseName))
  1009 + {
  1010 + return (false, null, "连接串为空或库名解析失败,已跳过 DROP DATABASE,仅删除主库记录");
  1011 + }
188 1012  
189   - TenantName = CurrentTenant.Name
  1013 + if (!SafeDatabaseNameRegex.IsMatch(databaseName))
  1014 + {
  1015 + return (false, null, "库名格式不符合安全规则,已跳过 DROP DATABASE,仅删除主库记录");
  1016 + }
  1017 +
  1018 + if (ProtectedDatabaseNames.Contains(databaseName))
  1019 + {
  1020 + return (false, null, $"库名 {databaseName} 为受保护库,已跳过 DROP DATABASE,仅删除主库记录");
  1021 + }
  1022 +
  1023 + var privilegedConnectionString = ResolvePrivilegedConnectionString();
  1024 + if (string.IsNullOrWhiteSpace(privilegedConnectionString))
  1025 + {
  1026 + return (false, null, "未配置高权限连接串,已跳过 DROP DATABASE,仅删除主库记录");
  1027 + }
  1028 +
  1029 + return (true, privilegedConnectionString, null);
  1030 + }
  1031 +
  1032 + private string? ResolvePrivilegedConnectionString()
  1033 + {
  1034 + if (!string.IsNullOrWhiteSpace(_dbConnOptions.AdminConnectionString))
  1035 + {
  1036 + return _dbConnOptions.AdminConnectionString;
  1037 + }
190 1038  
  1039 + return _dbConnOptions.Url;
  1040 + }
  1041 +
  1042 + private static void ExecuteDropDatabase(DbType dbType, string connectionString, string databaseName)
  1043 + {
  1044 + using var db = new SqlSugarClient(new ConnectionConfig
  1045 + {
  1046 + ConfigId = $"tenant-drop-db-{databaseName}-{Guid.NewGuid():N}",
  1047 + DbType = dbType,
  1048 + ConnectionString = connectionString,
  1049 + IsAutoCloseConnection = true
191 1050 });
192 1051  
  1052 + db.Ado.ExecuteCommand($"DROP DATABASE IF EXISTS `{databaseName}`");
193 1053 }
194 1054  
195   -}
  1055 + private async Task RemoveTenantCacheAsync(Guid tenantId, string tenantName)
  1056 + {
  1057 + await _tenantCache.RemoveAsync(TenantCacheItem.CalculateCacheKey(tenantId, null!));
  1058 + if (!string.IsNullOrWhiteSpace(tenantName))
  1059 + {
  1060 + await _tenantCache.RemoveAsync(TenantCacheItem.CalculateCacheKey(null, tenantName));
  1061 + }
  1062 + }
  1063 +
  1064 + private static string? ExtractConnectionValue(string connectionString, string key)
  1065 + {
  1066 + if (string.IsNullOrWhiteSpace(connectionString))
  1067 + {
  1068 + return null;
  1069 + }
196 1070  
  1071 + var prefix = key + "=";
  1072 + foreach (var segment in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries))
  1073 + {
  1074 + var part = segment.Trim();
  1075 + if (part.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  1076 + {
  1077 + return part[prefix.Length..].Trim();
  1078 + }
  1079 + }
197 1080  
  1081 + return null;
  1082 + }
  1083 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThRbacMenuAppService.cs 0 → 100644
  1 +using FoodLabeling.Application.Services.DbModels;
  2 +using FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
  3 +using FoodLabeling.Th.Application.Contracts.IServices;
  4 +using FoodLabeling.Th.Domain.Shared.Helpers;
  5 +using Microsoft.AspNetCore.Authorization;
  6 +using Microsoft.AspNetCore.Mvc;
  7 +using SqlSugar;
  8 +using Volo.Abp;
  9 +using Volo.Abp.Application.Dtos;
  10 +using Volo.Abp.Application.Services;
  11 +using Yi.Framework.Rbac.Domain.Shared.Enums;
  12 +using Yi.Framework.SqlSugarCore.Abstractions;
  13 +
  14 +namespace FoodLabeling.Th.Application.Services;
  15 +
  16 +/// <summary>
  17 +/// 泰额版租户业务库 menu 表 CRUD(字符串 Id/ParentId,不使用 TreeHelper)
  18 +/// </summary>
  19 +[Authorize]
  20 +public class ThRbacMenuAppService : ApplicationService, IThRbacMenuAppService
  21 +{
  22 + private readonly ISqlSugarDbContext _dbContext;
  23 +
  24 + public ThRbacMenuAppService(ISqlSugarDbContext dbContext)
  25 + {
  26 + _dbContext = dbContext;
  27 + }
  28 +
  29 + /// <summary>
  30 + /// 分页查询菜单列表
  31 + /// </summary>
  32 + /// <remarks>
  33 + /// 在当前租户业务库 `menu` 表查询,过滤逻辑删除数据。
  34 + ///
  35 + /// 示例请求:
  36 + /// ```json
  37 + /// {
  38 + /// "skipCount": 0,
  39 + /// "maxResultCount": 20,
  40 + /// "menuName": "Label",
  41 + /// "state": true,
  42 + /// "menuSource": 1
  43 + /// }
  44 + /// ```
  45 + ///
  46 + /// 参数说明:
  47 + /// - skipCount: 跳过条数
  48 + /// - maxResultCount: 每页条数
  49 + /// - menuName: 菜单名称模糊匹配
  50 + /// - state: 启用状态
  51 + /// - menuSource: 菜单来源(MenuSourceEnum)
  52 + /// - menuType: 菜单类型(MenuTypeEnum)
  53 + /// </remarks>
  54 + /// <param name="input">分页与筛选条件</param>
  55 + /// <returns>分页菜单列表</returns>
  56 + /// <response code="200">成功返回分页列表</response>
  57 + /// <response code="401">未登录</response>
  58 + /// <response code="500">服务器错误</response>
  59 + [HttpGet("th-rbac-menu/list")]
  60 + public virtual async Task<PagedResultDto<ThRbacMenuGetListOutputDto>> GetListAsync([FromQuery] ThRbacMenuGetListInputVo input)
  61 + {
  62 + RefAsync<int> total = 0;
  63 + var query = BuildFilteredQuery(input)
  64 + .OrderBy(x => x.OrderNum, OrderByType.Desc);
  65 +
  66 + var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
  67 + var items = entities.Select(MapToListDto).ToList();
  68 + return new PagedResultDto<ThRbacMenuGetListOutputDto>(total, items);
  69 + }
  70 +
  71 + /// <summary>
  72 + /// 根据 Id 获取菜单详情
  73 + /// </summary>
  74 + /// <remarks>
  75 + /// 在当前租户业务库按主键查询未删除菜单。
  76 + /// </remarks>
  77 + /// <param name="id">菜单 Id(字符串)</param>
  78 + /// <returns>菜单详情</returns>
  79 + /// <response code="200">成功返回菜单</response>
  80 + /// <response code="400">菜单不存在</response>
  81 + /// <response code="401">未登录</response>
  82 + /// <response code="500">服务器错误</response>
  83 + [HttpGet("th-rbac-menu/{id}")]
  84 + public virtual async Task<ThRbacMenuGetListOutputDto> GetAsync(string id)
  85 + {
  86 + var entity = await FindActiveMenuAsync(id);
  87 + return MapToListDto(entity);
  88 + }
  89 +
  90 + /// <summary>
  91 + /// 新增菜单
  92 + /// </summary>
  93 + /// <remarks>
  94 + /// 写入当前租户业务库 `menu` 表;Id 使用雪花算法字符串。
  95 + ///
  96 + /// 示例请求:
  97 + /// ```json
  98 + /// {
  99 + /// "menuName": "Settings",
  100 + /// "parentId": "0",
  101 + /// "menuType": 1,
  102 + /// "menuSource": 2,
  103 + /// "router": "/settings",
  104 + /// "orderNum": 10,
  105 + /// "state": true
  106 + /// }
  107 + /// ```
  108 + ///
  109 + /// 参数说明:
  110 + /// - menuName: 菜单名称(必填)
  111 + /// - parentId: 父级 Id,根节点为 0
  112 + /// - menuType: 菜单类型(MenuTypeEnum)
  113 + /// - menuSource: 菜单来源(MenuSourceEnum)
  114 + /// </remarks>
  115 + /// <param name="input">新增菜单入参</param>
  116 + /// <returns>新建菜单详情</returns>
  117 + /// <response code="200">创建成功</response>
  118 + /// <response code="400">参数校验失败</response>
  119 + /// <response code="401">未登录</response>
  120 + /// <response code="500">服务器错误</response>
  121 + [HttpPost("th-rbac-menu")]
  122 + public virtual async Task<ThRbacMenuGetListOutputDto> CreateAsync([FromBody] ThRbacMenuCreateInputVo input)
  123 + {
  124 + var name = input.MenuName?.Trim();
  125 + if (string.IsNullOrWhiteSpace(name))
  126 + {
  127 + throw new UserFriendlyException("菜单名称不能为空");
  128 + }
  129 +
  130 + var parentId = NormalizeParentId(input.ParentId);
  131 + await EnsureParentExistsAsync(parentId);
  132 +
  133 + var entity = new MenuDbEntity
  134 + {
  135 + Id = YitIdHelper.NextId().ToString(),
  136 + MenuName = name,
  137 + ParentId = parentId,
  138 + MenuType = (int)input.MenuType,
  139 + MenuSource = (int)input.MenuSource,
  140 + PermissionCode = input.PermissionCode?.Trim(),
  141 + Router = input.Router?.Trim(),
  142 + RouterName = input.RouterName?.Trim(),
  143 + Component = input.Component?.Trim(),
  144 + MenuIcon = input.MenuIcon?.Trim(),
  145 + OrderNum = input.OrderNum,
  146 + State = input.State,
  147 + IsDeleted = false,
  148 + CreationTime = DateTime.Now,
  149 + IsCache = false,
  150 + IsLink = false,
  151 + IsShow = input.IsShow,
  152 + ConcurrencyStamp = string.Empty
  153 + };
  154 +
  155 + await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
  156 + return await GetAsync(entity.Id);
  157 + }
  158 +
  159 + /// <summary>
  160 + /// 编辑菜单
  161 + /// </summary>
  162 + /// <remarks>
  163 + /// 更新当前租户业务库中指定 Id 的菜单;禁止将 ParentId 设为自身。
  164 + ///
  165 + /// 示例请求:
  166 + /// ```json
  167 + /// {
  168 + /// "menuName": "Settings",
  169 + /// "parentId": "0",
  170 + /// "menuType": 1,
  171 + /// "menuSource": 2,
  172 + /// "orderNum": 20,
  173 + /// "state": true
  174 + /// }
  175 + /// ```
  176 + /// </remarks>
  177 + /// <param name="id">菜单 Id</param>
  178 + /// <param name="input">编辑入参</param>
  179 + /// <returns>更新后的菜单详情</returns>
  180 + /// <response code="200">更新成功</response>
  181 + /// <response code="400">参数错误或菜单不存在</response>
  182 + /// <response code="401">未登录</response>
  183 + /// <response code="500">服务器错误</response>
  184 + [HttpPut("th-rbac-menu/{id}")]
  185 + public virtual async Task<ThRbacMenuGetListOutputDto> UpdateAsync(string id, [FromBody] ThRbacMenuUpdateInputVo input)
  186 + {
  187 + var entity = await FindActiveMenuAsync(id);
  188 +
  189 + var name = input.MenuName?.Trim();
  190 + if (string.IsNullOrWhiteSpace(name))
  191 + {
  192 + throw new UserFriendlyException("菜单名称不能为空");
  193 + }
  194 +
  195 + var parentId = NormalizeParentId(input.ParentId);
  196 + if (string.Equals(parentId, id, StringComparison.Ordinal))
  197 + {
  198 + throw new UserFriendlyException("父级菜单不能为自身");
  199 + }
  200 +
  201 + await EnsureParentExistsAsync(parentId, id);
  202 +
  203 + entity.MenuName = name;
  204 + entity.ParentId = parentId;
  205 + entity.MenuType = (int)input.MenuType;
  206 + entity.MenuSource = (int)input.MenuSource;
  207 + entity.PermissionCode = input.PermissionCode?.Trim();
  208 + entity.Router = input.Router?.Trim();
  209 + entity.RouterName = input.RouterName?.Trim();
  210 + entity.Component = input.Component?.Trim();
  211 + entity.MenuIcon = input.MenuIcon?.Trim();
  212 + entity.OrderNum = input.OrderNum;
  213 + entity.State = input.State;
  214 + entity.IsShow = input.IsShow;
  215 + entity.LastModificationTime = DateTime.Now;
  216 +
  217 + await _dbContext.SqlSugarClient.Updateable(entity)
  218 + .Where(x => x.Id == entity.Id)
  219 + .ExecuteCommandAsync();
  220 +
  221 + return await GetAsync(entity.Id);
  222 + }
  223 +
  224 + /// <summary>
  225 + /// 批量删除菜单(逻辑删除)
  226 + /// </summary>
  227 + /// <remarks>
  228 + /// 将指定 Id 列表对应菜单标记为 IsDeleted=true。
  229 + ///
  230 + /// 示例请求:
  231 + /// ```json
  232 + /// ["1234567890123456789", "9876543210987654321"]
  233 + /// ```
  234 + ///
  235 + /// 参数说明:
  236 + /// - ids: 待删除菜单 Id 数组
  237 + /// </remarks>
  238 + /// <param name="ids">菜单 Id 列表</param>
  239 + /// <returns>无内容</returns>
  240 + /// <response code="200">删除成功</response>
  241 + /// <response code="401">未登录</response>
  242 + /// <response code="500">服务器错误</response>
  243 + [HttpDelete("th-rbac-menu")]
  244 + public virtual async Task DeleteAsync([FromBody] List<string> ids)
  245 + {
  246 + var idList = ids?
  247 + .Where(x => !string.IsNullOrWhiteSpace(x))
  248 + .Select(x => x.Trim())
  249 + .Distinct(StringComparer.Ordinal)
  250 + .ToList() ?? new List<string>();
  251 +
  252 + if (idList.Count == 0)
  253 + {
  254 + return;
  255 + }
  256 +
  257 + await _dbContext.SqlSugarClient.Updateable<MenuDbEntity>()
  258 + .SetColumns(x => new MenuDbEntity { IsDeleted = true, LastModificationTime = DateTime.Now })
  259 + .Where(x => idList.Contains(x.Id) && x.IsDeleted == false)
  260 + .ExecuteCommandAsync();
  261 + }
  262 +
  263 + /// <summary>
  264 + /// 获取全部菜单树
  265 + /// </summary>
  266 + /// <remarks>
  267 + /// 返回当前租户业务库全部未删除菜单,按 ParentId 字符串组树(不使用 Guid TreeHelper)。
  268 + /// 树节点按 OrderNum 降序排序。
  269 + /// </remarks>
  270 + /// <returns>根节点菜单树</returns>
  271 + /// <response code="200">成功返回菜单树</response>
  272 + /// <response code="401">未登录</response>
  273 + /// <response code="500">服务器错误</response>
  274 + [HttpGet("th-rbac-menu/tree")]
  275 + public virtual async Task<List<ThRbacMenuTreeDto>> GetTreeAsync()
  276 + {
  277 + var menus = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
  278 + .Where(x => x.IsDeleted == false)
  279 + .OrderBy(x => x.OrderNum, OrderByType.Desc)
  280 + .ToListAsync();
  281 +
  282 + var nodes = menus.Select(MapToTreeDto).ToList();
  283 + return BuildMenuTree(nodes);
  284 + }
  285 +
  286 + private ISugarQueryable<MenuDbEntity> BuildFilteredQuery(ThRbacMenuGetListInputVo input)
  287 + {
  288 + return _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
  289 + .Where(x => x.IsDeleted == false)
  290 + .WhereIF(!string.IsNullOrWhiteSpace(input.MenuName), x => x.MenuName.Contains(input.MenuName!.Trim()))
  291 + .WhereIF(input.State is not null, x => x.State == input.State)
  292 + .WhereIF(input.MenuSource is not null, x => x.MenuSource == (int)input.MenuSource!.Value)
  293 + .WhereIF(input.MenuType is not null, x => x.MenuType == (int)input.MenuType!.Value);
  294 + }
  295 +
  296 + private async Task<MenuDbEntity> FindActiveMenuAsync(string id)
  297 + {
  298 + if (string.IsNullOrWhiteSpace(id))
  299 + {
  300 + throw new UserFriendlyException("菜单 Id 不能为空");
  301 + }
  302 +
  303 + var entity = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
  304 + .Where(x => x.Id == id.Trim() && x.IsDeleted == false)
  305 + .SingleAsync();
  306 +
  307 + if (entity is null)
  308 + {
  309 + throw new UserFriendlyException("菜单不存在");
  310 + }
  311 +
  312 + return entity;
  313 + }
  314 +
  315 + private async Task EnsureParentExistsAsync(string parentId, string? currentId = null)
  316 + {
  317 + if (IsRootParentId(parentId))
  318 + {
  319 + return;
  320 + }
  321 +
  322 + var parent = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
  323 + .Where(x => x.Id == parentId && x.IsDeleted == false)
  324 + .SingleAsync();
  325 +
  326 + if (parent is null)
  327 + {
  328 + throw new UserFriendlyException("父级菜单不存在");
  329 + }
  330 +
  331 + if (currentId is not null && string.Equals(parent.ParentId, currentId, StringComparison.Ordinal))
  332 + {
  333 + throw new UserFriendlyException("不能将菜单移动到其子节点下");
  334 + }
  335 + }
  336 +
  337 + private static string NormalizeParentId(string? parentId)
  338 + {
  339 + return string.IsNullOrWhiteSpace(parentId) ? "0" : parentId.Trim();
  340 + }
  341 +
  342 + private static bool IsRootParentId(string parentId)
  343 + {
  344 + return parentId == "0" || parentId == "00000000-0000-0000-0000-000000000000";
  345 + }
  346 +
  347 + private static ThRbacMenuGetListOutputDto MapToListDto(MenuDbEntity x)
  348 + {
  349 + return new ThRbacMenuGetListOutputDto
  350 + {
  351 + Id = x.Id,
  352 + ParentId = x.ParentId,
  353 + MenuName = x.MenuName ?? string.Empty,
  354 + RouterName = x.RouterName,
  355 + Router = x.Router,
  356 + PermissionCode = x.PermissionCode,
  357 + MenuType = (MenuTypeEnum)x.MenuType,
  358 + MenuSource = (MenuSourceEnum)x.MenuSource,
  359 + OrderNum = x.OrderNum,
  360 + State = x.State
  361 + };
  362 + }
  363 +
  364 + private static ThRbacMenuTreeDto MapToTreeDto(MenuDbEntity m)
  365 + {
  366 + return new ThRbacMenuTreeDto
  367 + {
  368 + Id = m.Id,
  369 + IsDeleted = m.IsDeleted,
  370 + CreationTime = m.CreationTime,
  371 + CreatorId = m.CreatorId,
  372 + LastModifierId = m.LastModifierId,
  373 + LastModificationTime = m.LastModificationTime,
  374 + OrderNum = m.OrderNum,
  375 + State = m.State,
  376 + MenuName = m.MenuName ?? string.Empty,
  377 + RouterName = m.RouterName,
  378 + MenuType = (MenuTypeEnum)m.MenuType,
  379 + PermissionCode = m.PermissionCode,
  380 + ParentId = m.ParentId,
  381 + MenuIcon = m.MenuIcon,
  382 + Router = m.Router,
  383 + IsLink = m.IsLink,
  384 + IsCache = m.IsCache,
  385 + IsShow = m.IsShow,
  386 + Remark = m.Remark,
  387 + Component = m.Component,
  388 + MenuSource = (MenuSourceEnum)m.MenuSource,
  389 + Query = m.Query,
  390 + ConcurrencyStamp = m.ConcurrencyStamp,
  391 + Children = new List<ThRbacMenuTreeDto>()
  392 + };
  393 + }
  394 +
  395 + private static List<ThRbacMenuTreeDto> BuildMenuTree(List<ThRbacMenuTreeDto> nodes)
  396 + {
  397 + var nodeById = nodes
  398 + .Where(x => !string.IsNullOrWhiteSpace(x.Id))
  399 + .GroupBy(x => x.Id)
  400 + .ToDictionary(g => g.Key, g => g.First());
  401 +
  402 + foreach (var node in nodes)
  403 + {
  404 + node.Children ??= new List<ThRbacMenuTreeDto>();
  405 + var parentId = NormalizeParentId(node.ParentId);
  406 + if (IsRootParentId(parentId))
  407 + {
  408 + continue;
  409 + }
  410 +
  411 + if (nodeById.TryGetValue(parentId, out var parent))
  412 + {
  413 + parent.Children ??= new List<ThRbacMenuTreeDto>();
  414 + parent.Children.Add(node);
  415 + }
  416 + }
  417 +
  418 + var roots = nodes
  419 + .Where(n =>
  420 + {
  421 + var pid = NormalizeParentId(n.ParentId);
  422 + return IsRootParentId(pid) || !nodeById.ContainsKey(pid);
  423 + })
  424 + .ToList();
  425 +
  426 + SortTree(roots);
  427 + return roots;
  428 + }
  429 +
  430 + private static void SortTree(List<ThRbacMenuTreeDto> nodes)
  431 + {
  432 + nodes.Sort((a, b) => b.OrderNum.CompareTo(a.OrderNum));
  433 + foreach (var node in nodes)
  434 + {
  435 + if (node.Children is { Count: > 0 })
  436 + {
  437 + SortTree(node.Children);
  438 + }
  439 + }
  440 + }
  441 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThTenantProvisioningAppService.cs
... ... @@ -10,6 +10,7 @@ using Volo.Abp;
10 10 using Volo.Abp.Application.Services;
11 11 using Volo.Abp.MultiTenancy;
12 12 using Volo.Abp.Uow;
  13 +using Yi.Framework.SqlSugarCore.Abstractions;
13 14 using Yi.Framework.TenantManagement.Application.Contracts;
14 15 using Yi.Framework.TenantManagement.Application.Contracts.Dtos;
15 16  
... ... @@ -46,15 +47,18 @@ public class ThTenantProvisioningAppService : ApplicationService, IThTenantProvi
46 47 private readonly ITenantService _tenantService;
47 48 private readonly IThTenantDatabaseBackgroundInitializer _backgroundInitializer;
48 49 private readonly FoodLabelingThTenantDatabaseOptions _dbOptions;
  50 + private readonly DbConnOptions _dbConnOptions;
49 51  
50 52 public ThTenantProvisioningAppService(
51 53 ITenantService tenantService,
52 54 IThTenantDatabaseBackgroundInitializer backgroundInitializer,
53   - IOptions<FoodLabelingThTenantDatabaseOptions> dbOptions)
  55 + IOptions<FoodLabelingThTenantDatabaseOptions> dbOptions,
  56 + IOptions<DbConnOptions> dbConnOptions)
54 57 {
55 58 _tenantService = tenantService;
56 59 _backgroundInitializer = backgroundInitializer;
57 60 _dbOptions = dbOptions.Value;
  61 + _dbConnOptions = dbConnOptions.Value;
58 62 }
59 63  
60 64 /// <inheritdoc />
... ... @@ -100,6 +104,13 @@ public class ThTenantProvisioningAppService : ApplicationService, IThTenantProvi
100 104 var initializing = false;
101 105 if (input.InitializeDatabase)
102 106 {
  107 + // 同步建库 + GRANT,避免仅入队后台 Init 时库不存在导致静默失败
  108 + TenantDatabaseBootstrapper.EnsureDatabaseCreated(
  109 + _dbConnOptions,
  110 + dbType,
  111 + connectionString,
  112 + databaseName);
  113 +
103 114 _backgroundInitializer.Enqueue(created.Id);
104 115 initializing = true;
105 116 }
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Domain.Shared/Helpers/YitIdHelper.cs 0 → 100644
  1 +namespace FoodLabeling.Th.Domain.Shared.Helpers;
  2 +
  3 +/// <summary>
  4 +/// 雪花 Id 生成器(项目规范:实体 string Id 使用 NextId().ToString())
  5 +/// </summary>
  6 +public static class YitIdHelper
  7 +{
  8 + private const long Epoch = 1_609_459_200_000L;
  9 + private const int WorkerIdBits = 5;
  10 + private const int SequenceBits = 12;
  11 + private const long MaxSequence = (1L << SequenceBits) - 1;
  12 + private const int WorkerIdShift = SequenceBits;
  13 + private const int TimestampShift = SequenceBits + WorkerIdBits;
  14 + private const long WorkerId = 1;
  15 +
  16 + private static long _lastTimestamp = -1L;
  17 + private static long _sequence;
  18 + private static readonly object SyncRoot = new();
  19 +
  20 + /// <summary>
  21 + /// 生成下一个雪花 Id
  22 + /// </summary>
  23 + public static long NextId()
  24 + {
  25 + lock (SyncRoot)
  26 + {
  27 + var timestamp = CurrentTimestamp();
  28 + if (timestamp < _lastTimestamp)
  29 + {
  30 + timestamp = WaitNextMillis(_lastTimestamp);
  31 + }
  32 +
  33 + if (_lastTimestamp == timestamp)
  34 + {
  35 + _sequence = (_sequence + 1) & MaxSequence;
  36 + if (_sequence == 0)
  37 + {
  38 + timestamp = WaitNextMillis(_lastTimestamp);
  39 + }
  40 + }
  41 + else
  42 + {
  43 + _sequence = 0;
  44 + }
  45 +
  46 + _lastTimestamp = timestamp;
  47 + return ((timestamp - Epoch) << TimestampShift) | (WorkerId << WorkerIdShift) | _sequence;
  48 + }
  49 + }
  50 +
  51 + private static long CurrentTimestamp() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  52 +
  53 + private static long WaitNextMillis(long lastTimestamp)
  54 + {
  55 + var timestamp = CurrentTimestamp();
  56 + while (timestamp <= lastTimestamp)
  57 + {
  58 + timestamp = CurrentTimestamp();
  59 + }
  60 +
  61 + return timestamp;
  62 + }
  63 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Domain/Entities/ThTenantAdminCredentialEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +using Volo.Abp.Domain.Entities;
  3 +using Yi.Framework.SqlSugarCore.Abstractions;
  4 +
  5 +namespace FoodLabeling.Th.Domain.Entities;
  6 +
  7 +/// <summary>
  8 +/// 平台主库:租户默认管理员可回显凭据(AES 密文,非登录哈希)
  9 +/// </summary>
  10 +/// <remarks>
  11 +/// 主键列名为 TenantId;仓储泛型键仍用 Guid(映射到 Id)。
  12 +/// 勿再对 Id 使用 IsIgnore 别名,否则 SqlSugar Insertable 会 NRE。
  13 +/// </remarks>
  14 +[SugarTable("fl_th_tenant_admin_credential")]
  15 +[DefaultTenantTable]
  16 +public class ThTenantAdminCredentialEntity : Entity<Guid>
  17 +{
  18 + /// <summary>
  19 + /// 租户 Id(主键,对应 YiTenant.Id;列名 TenantId)
  20 + /// </summary>
  21 + [SugarColumn(IsPrimaryKey = true, ColumnName = "TenantId")]
  22 + public override Guid Id { get; protected set; }
  23 +
  24 + /// <summary>
  25 + /// 管理员登录账号(UserName)
  26 + /// </summary>
  27 + [SugarColumn(Length = 64)]
  28 + public string LoginAccount { get; set; } = string.Empty;
  29 +
  30 + /// <summary>
  31 + /// AES-CBC 加密后的可回显密码(Base64 密文)
  32 + /// </summary>
  33 + [SugarColumn(Length = 512)]
  34 + public string PasswordCipher { get; set; } = string.Empty;
  35 +
  36 + /// <summary>
  37 + /// AES IV(Base64)
  38 + /// </summary>
  39 + [SugarColumn(Length = 64)]
  40 + public string PasswordIv { get; set; } = string.Empty;
  41 +
  42 + /// <summary>
  43 + /// 最后修改时间
  44 + /// </summary>
  45 + public DateTime? LastModificationTime { get; set; }
  46 +
  47 + public void SetTenantId(Guid tenantId) => Id = tenantId;
  48 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Domain/Entities/ThTenantMenuPermissionEntity.cs 0 → 100644
  1 +using SqlSugar;
  2 +using Volo.Abp.Domain.Entities;
  3 +using Yi.Framework.SqlSugarCore.Abstractions;
  4 +
  5 +namespace FoodLabeling.Th.Domain.Entities;
  6 +
  7 +/// <summary>
  8 +/// 平台主库:租户 SaaS 菜单权限 Key
  9 +/// </summary>
  10 +[SugarTable("fl_th_tenant_menu_permission")]
  11 +[DefaultTenantTable]
  12 +[SugarIndex(
  13 + "uk_fl_th_tenant_menu_permission_tenant_key",
  14 + nameof(TenantId),
  15 + OrderByType.Asc,
  16 + nameof(PermissionKey),
  17 + OrderByType.Asc,
  18 + IsUnique = true)]
  19 +public class ThTenantMenuPermissionEntity : IEntity<string>
  20 +{
  21 + /// <summary>
  22 + /// 主键(雪花 Id 字符串)
  23 + /// </summary>
  24 + [SugarColumn(IsPrimaryKey = true, Length = 32)]
  25 + public string Id { get; set; } = string.Empty;
  26 +
  27 + /// <summary>
  28 + /// 租户 Id(对应 YiTenant.Id)
  29 + /// </summary>
  30 + public Guid TenantId { get; set; }
  31 +
  32 + /// <summary>
  33 + /// SaaS 菜单权限 Key(如 labeling:labels)
  34 + /// </summary>
  35 + [SugarColumn(Length = 128)]
  36 + public string PermissionKey { get; set; } = string.Empty;
  37 +
  38 + /// <summary>
  39 + /// 创建时间
  40 + /// </summary>
  41 + public DateTime CreationTime { get; set; } = DateTime.Now;
  42 +
  43 + /// <inheritdoc />
  44 + public object[] GetKeys() => new object[] { Id };
  45 +}
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/tenant-management/Yi.Framework.TenantManagement.Application/TenantService.cs
... ... @@ -48,6 +48,29 @@ namespace Yi.Framework.TenantManagement.Application
48 48 private IDisposable UseHostTenantScope() => CurrentTenant.Change(null);
49 49  
50 50 /// <summary>
  51 + /// 用主库连接串直连读取 YiTenant,避免 UoW 事务 + IsAutoCloseConnection 在后台 Init 时 NRE。
  52 + /// </summary>
  53 + private async Task<TenantAggregateRoot?> LoadTenantFromHostAsync(Guid id)
  54 + {
  55 + if (string.IsNullOrWhiteSpace(_dbConnOptions.Url))
  56 + {
  57 + throw new UserFriendlyException("未配置主库连接字符串 DbConnOptions.Url");
  58 + }
  59 +
  60 + var dbType = _dbConnOptions.DbType ?? DbType.MySql;
  61 + using var client = new SqlSugarClient(new ConnectionConfig
  62 + {
  63 + ConfigId = $"host-yitenant-read-{Guid.NewGuid():N}",
  64 + DbType = dbType,
  65 + ConnectionString = _dbConnOptions.Url,
  66 + IsAutoCloseConnection = true
  67 + });
  68 +
  69 + var tenant = await client.Queryable<TenantAggregateRoot>().InSingleAsync(id);
  70 + return tenant is { IsDeleted: true } ? null : tenant;
  71 + }
  72 +
  73 + /// <summary>
51 74 /// 租户单查
52 75 /// </summary>
53 76 /// <param name="id"></param>
... ... @@ -153,17 +176,13 @@ namespace Yi.Framework.TenantManagement.Application
153 176 /// <returns></returns>
154 177 [HttpPut("tenant/init/{id}")]
155 178 [RequestTimeout("ThTenantDatabaseInit")]
  179 + [UnitOfWork(isTransactional: false)]
156 180 public async Task InitAsync([FromRoute] Guid id)
157 181 {
158 182 TenantAggregateRoot tenant;
159 183 using (UseHostTenantScope())
160 184 {
161   - if (CurrentUnitOfWork != null)
162   - {
163   - await CurrentUnitOfWork.SaveChangesAsync();
164   - }
165   -
166   - tenant = await _repository.FindAsync(id);
  185 + tenant = await LoadTenantFromHostAsync(id);
167 186 if (tenant == null)
168 187 {
169 188 throw new UserFriendlyException("未找到租户信息");
... ...
泰额版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
... ... @@ -20,7 +20,7 @@
20 20 },
21 21 //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049)
22 22 "App": {
23   - "SelfUrl": "http://192.168.31.89:19002",
  23 + "SelfUrl": "http://192.168.31.248:19002",
24 24 "CorsOrigins": "http://localhost:19002;http://localhost:18000;http://localhost:5666;http://localhost:5173;http://localhost:5174;http://localhost:3000;http://127.0.0.1:19002"
25 25 },
26 26 //配置
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/FoodLabelingApplicationModule.cs
1 1 using FoodLabeling.Application.Contracts;
  2 +using FoodLabeling.Application.Filters;
2 3 using FoodLabeling.Application.Options;
3 4 using FoodLabeling.Domain;
  5 +using Microsoft.AspNetCore.Mvc;
4 6 using Microsoft.Extensions.DependencyInjection;
5 7 using Volo.Abp.Modularity;
6 8 using Yi.Framework.Ddd.Application;
... ... @@ -21,6 +23,12 @@ public class FoodLabelingApplicationModule : AbpModule
21 23 {
22 24 Configure<FoodLabelingBatchImportOptions>(
23 25 context.Services.GetConfiguration().GetSection(FoodLabelingBatchImportOptions.SectionName));
  26 +
  27 + // 任意业务写接口成功后刷新系统编辑时间戳,供 my-menus.lastUpdated 使用
  28 + Configure<MvcOptions>(options =>
  29 + {
  30 + options.Filters.AddService<SystemEditStampGlobalFilter>();
  31 + });
24 32 }
25 33 }
26 34  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/AuthSessionAppService.cs
... ... @@ -21,17 +21,20 @@ namespace FoodLabeling.Application.Services;
21 21 public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
22 22 {
23 23 private readonly IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> _userCache;
  24 + private readonly IDistributedCache<SystemEditStampCacheItem, SystemEditStampCacheKey> _systemEditStampCache;
24 25 private readonly ISqlSugarDbContext _dbContext;
25 26 private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
26 27  
27 28 public AuthSessionAppService(
28 29 ISqlSugarDbContext dbContext,
29 30 ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
30   - IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> userCache)
  31 + IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> userCache,
  32 + IDistributedCache<SystemEditStampCacheItem, SystemEditStampCacheKey> systemEditStampCache)
31 33 {
32 34 _dbContext = dbContext;
33 35 _userRepository = userRepository;
34 36 _userCache = userCache;
  37 + _systemEditStampCache = systemEditStampCache;
35 38 }
36 39  
37 40 /// <inheritdoc />
... ... @@ -109,6 +112,12 @@ public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
109 112 .OrderBy(x => x)
110 113 .ToList();
111 114  
  115 + // 优先系统编辑全局时间戳(任意写接口成功联动);无戳时回退「业务表最近修改」再回退用户时间
  116 + var systemEditAt = await SystemEditStampCacheHelper.GetAsync(_systemEditStampCache);
  117 + var lastUpdated = systemEditAt
  118 + ?? await ResolveRecentBusinessEditTimeAsync()
  119 + ?? user.LastModificationTime;
  120 +
112 121 return new CurrentUserMenuPermissionsOutputDto
113 122 {
114 123 User = new CurrentUserBriefDto
... ... @@ -123,12 +132,49 @@ public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
123 132 PermissionCodes = permissionCodes,
124 133 AccessPermissionCodes = accessPermissionCodes,
125 134 Menus = BuildMenuTree(menuNodes),
126   - LastUpdated = user.LastModificationTime,
  135 + LastUpdated = lastUpdated,
127 136 Role = roleDisplay,
128 137 FullName = BuildFullName(user)
129 138 };
130 139 }
131 140  
  141 + /// <summary>
  142 + /// 缓存未命中时,取主要业务表最近修改时间,避免 Last Updated 长期停在用户资料时间。
  143 + /// </summary>
  144 + private async Task<DateTime?> ResolveRecentBusinessEditTimeAsync()
  145 + {
  146 + var db = _dbContext.SqlSugarClient;
  147 + DateTime? max = null;
  148 +
  149 + async Task ConsiderAsync(Task<DateTime?> query)
  150 + {
  151 + try
  152 + {
  153 + var t = await query;
  154 + if (t.HasValue && (!max.HasValue || t.Value > max.Value))
  155 + {
  156 + max = t;
  157 + }
  158 + }
  159 + catch
  160 + {
  161 + // 表/列缺失时忽略,继续其它表
  162 + }
  163 + }
  164 +
  165 + await ConsiderAsync(db.Queryable<FlLabelDbEntity>()
  166 + .Where(x => !x.IsDeleted)
  167 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  168 + await ConsiderAsync(db.Queryable<FlLabelTemplateDbEntity>()
  169 + .Where(x => !x.IsDeleted)
  170 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  171 + await ConsiderAsync(db.Queryable<FlLabelCategoryDbEntity>()
  172 + .Where(x => !x.IsDeleted)
  173 + .MaxAsync(x => (DateTime?)(x.LastModificationTime ?? x.CreationTime)));
  174 +
  175 + return max;
  176 + }
  177 +
132 178 /// <inheritdoc />
133 179 [HttpPost]
134 180 public virtual async Task<bool> LogoutAsync()
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
... ... @@ -20,7 +20,7 @@
20 20 },
21 21 //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049)
22 22 "App": {
23   - "SelfUrl": "http://192.168.31.89:19001",
  23 + "SelfUrl": "http://192.168.31.88:19001",
24 24 "CorsOrigins": "http://localhost:19001;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:5173;http://localhost:3000"
25 25 },
26 26 //配置
... ...
项目相关文档/2026-07-21代码优化.md 0 → 100644
  1 +# 2026-07-21 代码优化
  2 +
  3 +本文档说明 **2026-07-21** 后端改动。重点为 **泰额版** 平台级管理员:
  4 +
  5 +1. 「公司列表」返回账号密码、支持修改(前端密码 AES 加盐)
  6 +2. **菜单权限分配**、**角色菜单分配**
  7 +
  8 +另含美国版/泰额版 Dashboard `Last Updated` 修复。前端本次不改。
  9 +
  10 +---
  11 +
  12 +## 一、变更概述
  13 +
  14 +| 项 | 说明 |
  15 +|----|------|
  16 +| 范围 | 泰额版 `Yi.Abp.Net8`(主);美国版 `Last Updated` 同步修复 |
  17 +| 公司 = 租户 | 平台主库 `YiTenant`;前端常把 `name` 映射为 `companyName` |
  18 +| 账号密码 | `GET company-list`、`PUT company-admin` |
  19 +| 菜单/角色 | `menu-permission-tree`、`company-menus`、`company-roles`、`company-role-menus` |
  20 +| 凭据存储 | 主库表 `fl_th_tenant_admin_credential`(可回显 AES 密文,非登录哈希) |
  21 +| 菜单存储 | 主库表 `fl_th_tenant_menu_permission`(SaaS `menuPermissionKeys`) |
  22 +| 传输加盐 | 与 `FoodLabeling:TenantSelectCrypto` 一致(AES-CBC + `passwordSalt`=IV) |
  23 +| 落库哈希 | 租户业务库 `User`:`MD5Helper.GenerateSalt` + `SHA2Encode`(`UserPasswordHelper`) |
  24 +
  25 +---
  26 +
  27 +## 二、平台公司列表(返账号密码)
  28 +
  29 +### 2.1 接口
  30 +
  31 +| 项 | 值 |
  32 +|----|------|
  33 +| 方法 / 路径 | `GET /api/app/th-multi-tenancy/company-list` |
  34 +| 鉴权 | 需登录(Bearer) |
  35 +| 说明 | 分页查询主库租户,并返回可解密的管理员账号/密码 |
  36 +
  37 +> **路由说明**:ABP 常规控制器 RootPath 为 `api/app`;自定义 `[HttpGet(...)]` / `[HttpPut(...)]` 必须带 `th-multi-tenancy/` 前缀,完整路径才是 `/api/app/th-multi-tenancy/...`。此前误写为 `[HttpGet("company-list")]` 时实际注册在 `/api/app/company-list`(404 于文档路径);已纠正。
  38 +
  39 +### 2.2 入参
  40 +
  41 +| 字段 | 说明 |
  42 +|------|------|
  43 +| `keyword` / `name` | 租户名称模糊匹配(`keyword` 优先) |
  44 +| `skipCount` | 跳过条数 |
  45 +| `maxResultCount` | 每页条数 |
  46 +
  47 +### 2.3 出参示例
  48 +
  49 +```json
  50 +{
  51 + "totalCount": 1,
  52 + "items": [
  53 + {
  54 + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  55 + "name": "测试公司",
  56 + "creationTime": "2026-01-01T08:00:00",
  57 + "loginAccount": "admin",
  58 + "password": "Base64CipherText",
  59 + "passwordSalt": "Base64Iv",
  60 + "menuPermissionKeys": ["dashboard", "labeling:labels"]
  61 + }
  62 + ]
  63 +}
  64 +```
  65 +
  66 +### 2.4 密码来源优先级
  67 +
  68 +1. 主库 `fl_th_tenant_admin_credential` 中已保存的 AES 密文 / IV
  69 +2. 无记录时回退 `RbacOptions.AdminPassword`,再经 AES 加密返回
  70 +
  71 +默认账号:`admin`(与 `UserDataSeed` / `ThTenantSelectConsts.DefaultAdminLoginAccount` 一致)。
  72 +
  73 +---
  74 +
  75 +## 三、修改公司管理员账号/密码
  76 +
  77 +### 3.1 接口
  78 +
  79 +| 项 | 值 |
  80 +|----|------|
  81 +| 方法 / 路径 | `PUT /api/app/th-multi-tenancy/company-admin` |
  82 +| 鉴权 | 需登录(Bearer) |
  83 +
  84 +### 3.2 入参
  85 +
  86 +```json
  87 +{
  88 + "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  89 + "loginAccount": "admin",
  90 + "password": "Base64CipherText",
  91 + "passwordSalt": "Base64Iv"
  92 +}
  93 +```
  94 +
  95 +| 字段 | 必填 | 说明 |
  96 +|------|------|------|
  97 +| `tenantId` | 是 | 租户 Guid |
  98 +| `loginAccount` | 否 | 新登录账号;空则不改账号 |
  99 +| `password` | 否 | AES 密文;与 `passwordSalt` 都空则不改密码 |
  100 +| `passwordSalt` | 改密时必填 | AES IV(Base64) |
  101 +
  102 +### 3.3 处理流程
  103 +
  104 +1. 主库校验租户存在,读取凭据表当前账号
  105 +2. `CurrentTenant.Change(tenantId)` 定位租户库管理员用户
  106 +3. 若改账号:校验 UserName 不重复后更新
  107 +4. 若改密码:`TenantSelectCredentialCipher.DecryptPassword` → `UserPasswordHelper.ApplyPlainPassword` + `EnsurePasswordColumnsPersistedAsync`
  108 +5. Upsert 主库凭据表(可回显 AES 密文),供列表再次返回
  109 +
  110 +### 3.4 curl 示例
  111 +
  112 +```bash
  113 +# 1) 登录拿 Token(按环境改 host / 账号)
  114 +curl -X POST "http://127.0.0.1:19002/api/app/th-web-auth/login" \
  115 + -H "Content-Type: application/json" \
  116 + -d "{\"tenantName\":\"Default\",\"userName\":\"admin\",\"password\":\"123456\"}"
  117 +
  118 +# 2) 公司列表
  119 +curl -X GET "http://127.0.0.1:19002/api/app/th-multi-tenancy/company-list?skipCount=0&maxResultCount=20" \
  120 + -H "Authorization: Bearer <token>"
  121 +
  122 +# 3) 修改管理员(password / passwordSalt 须为前端 AES 加密结果)
  123 +curl -X PUT "http://127.0.0.1:19002/api/app/th-multi-tenancy/company-admin" \
  124 + -H "Authorization: Bearer <token>" \
  125 + -H "Content-Type: application/json" \
  126 + -d "{\"tenantId\":\"<租户Guid>\",\"loginAccount\":\"admin\",\"password\":\"<密文>\",\"passwordSalt\":\"<IV>\"}"
  127 +```
  128 +
  129 +---
  130 +
  131 +## 四、AES 加盐约定(与 07-16 一致)
  132 +
  133 +| 项 | 值 |
  134 +|----|------|
  135 +| 算法 | AES-256-CBC |
  136 +| 填充 | PKCS7 |
  137 +| Key | `SHA256(UTF8(SecretKey))` → 32 字节 |
  138 +| IV | 随机 16 字节,Base64 → `passwordSalt` |
  139 +| 密文 | Base64 → `password` |
  140 +| 配置 | `FoodLabeling:TenantSelectCrypto:SecretKey` |
  141 +
  142 +```json
  143 +"FoodLabeling": {
  144 + "TenantSelectCrypto": {
  145 + "SecretKey": "FoodLabelingThTenantSelect2026Key!"
  146 + }
  147 +}
  148 +```
  149 +
  150 +- **出参**:后端加密,前端用同一 SecretKey + `passwordSalt` 解密展示
  151 +- **入参(改密)**:前端加密后传 `password` + `passwordSalt`,后端 `DecryptPassword` 后再做登录哈希落库
  152 +
  153 +解密失败统一:`UserFriendlyException("密码解密失败")`。
  154 +
  155 +---
  156 +
  157 +## 五、主库凭据表
  158 +
  159 +表名:`fl_th_tenant_admin_credential`(实体带 `[DefaultTenantTable]`,走平台主库;CodeFirst 开启时随主库启动建表)
  160 +
  161 +| 字段 | 说明 |
  162 +|------|------|
  163 +| `TenantId` | PK,对应 `YiTenant.Id` |
  164 +| `LoginAccount` | 管理员登录账号 |
  165 +| `PasswordCipher` | AES 可回显密文 |
  166 +| `PasswordIv` | AES IV |
  167 +| `LastModificationTime` | 最后修改时间 |
  168 +
  169 +说明:此表存的是**可逆展示密文**,不是 `User.EncryPassword` 的不可逆哈希。
  170 +
  171 +---
  172 +
  173 +## 六、平台菜单权限分配
  174 +
  175 +平台管理员可为每个公司(租户)勾选可用 SaaS 菜单模块;Key 与前端 `saas-menu-tree` / `tenant-menu-drawer` 的 `menuPermissionKeys` 对齐。
  176 +
  177 +### 6.1 菜单权限目录树
  178 +
  179 +| 项 | 值 |
  180 +|----|------|
  181 +| 方法 / 路径 | `GET /api/app/th-multi-tenancy/menu-permission-tree` |
  182 +| 鉴权 | 需登录 |
  183 +| 说明 | 返回可分配的 SaaS 菜单树(`key` / `title` / `children`) |
  184 +
  185 +出参示例:
  186 +
  187 +```json
  188 +[
  189 + {
  190 + "key": "dashboard",
  191 + "title": "仪表盘",
  192 + "children": [{ "key": "dashboard:analytics", "title": "数据分析" }]
  193 + },
  194 + {
  195 + "key": "labeling",
  196 + "title": "标签管理",
  197 + "children": [
  198 + { "key": "labeling:labels", "title": "标签列表" },
  199 + { "key": "labeling:categories", "title": "标签分类" },
  200 + { "key": "labeling:types", "title": "标签类型" },
  201 + { "key": "labeling:templates", "title": "标签模板" },
  202 + { "key": "labeling:multiple-options", "title": "多选项" }
  203 + ]
  204 + },
  205 + {
  206 + "key": "management",
  207 + "title": "管理",
  208 + "children": [
  209 + { "key": "management:account", "title": "账号管理" },
  210 + { "key": "management:menu", "title": "菜单管理" },
  211 + { "key": "management:reports", "title": "报表" }
  212 + ]
  213 + }
  214 +]
  215 +```
  216 +
  217 +完整 Key 目录(与前端一致):
  218 +
  219 +| 分组 | Key |
  220 +|------|-----|
  221 +| dashboard | `dashboard`、`dashboard:analytics` |
  222 +| labeling | `labeling`、`labeling:labels`、`labeling:categories`、`labeling:types`、`labeling:templates`、`labeling:multiple-options` |
  223 +| modules | `modules`、`modules:training`、`modules:alerts`、`modules:tasks`、`modules:food-waste`、`modules:e-label` |
  224 +| management | `management`、`management:account`、`management:menu`、`management:devices`、`management:reports`、`management:invoices`、`management:qr-codes`、`management:support`、`management:api` |
  225 +
  226 +### 6.2 获取 / 设置公司菜单
  227 +
  228 +| 操作 | 方法 / 路径 |
  229 +|------|-------------|
  230 +| 获取 | `GET /api/app/th-multi-tenancy/company-menus?tenantId={guid}` |
  231 +| 设置 | `PUT /api/app/th-multi-tenancy/company-menus`(覆盖式) |
  232 +
  233 +设置入参:
  234 +
  235 +```json
  236 +{
  237 + "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  238 + "menuPermissionKeys": ["dashboard", "labeling:labels", "management:account"]
  239 +}
  240 +```
  241 +
  242 +- 非法 Key → `400`,提示非法项
  243 +- `menuPermissionKeys` 为空数组 → 清空该公司全部菜单权限
  244 +- `company-list` 出参已增加 `menuPermissionKeys`
  245 +
  246 +### 6.3 主库表 `fl_th_tenant_menu_permission`
  247 +
  248 +| 字段 | 说明 |
  249 +|------|------|
  250 +| `Id` | 主键,`YitIdHelper.NextId().ToString()` |
  251 +| `TenantId` | 租户 Guid |
  252 +| `PermissionKey` | SaaS 菜单 Key |
  253 +| `CreationTime` | 创建时间 |
  254 +
  255 +唯一逻辑:同一 `TenantId + PermissionKey` 不重复;写接口覆盖式先清后插。
  256 +
  257 +---
  258 +
  259 +## 七、平台角色菜单分配
  260 +
  261 +平台管理员可跨租户业务库,查看该公司角色并为角色绑定菜单(`Role` / `RoleMenu` / `Menu`)。
  262 +
  263 +### 7.1 租户角色列表
  264 +
  265 +| 项 | 值 |
  266 +|----|------|
  267 +| 方法 / 路径 | `GET /api/app/th-multi-tenancy/company-roles?tenantId={guid}` |
  268 +| 鉴权 | 需登录 |
  269 +
  270 +出参示例:
  271 +
  272 +```json
  273 +[
  274 + {
  275 + "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  276 + "roleName": "管理员",
  277 + "roleCode": "admin",
  278 + "state": true,
  279 + "menuIds": ["11111111-1111-1111-1111-111111111111"]
  280 + }
  281 +]
  282 +```
  283 +
  284 +### 7.2 设置角色菜单(覆盖式)
  285 +
  286 +| 项 | 值 |
  287 +|----|------|
  288 +| 方法 / 路径 | `PUT /api/app/th-multi-tenancy/company-role-menus` |
  289 +| 鉴权 | 需登录 |
  290 +
  291 +入参:
  292 +
  293 +```json
  294 +{
  295 + "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  296 + "roleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  297 + "menuIds": ["11111111-1111-1111-1111-111111111111"]
  298 +}
  299 +```
  300 +
  301 +逻辑:`CurrentTenant.Change(tenantId)` 后覆盖写 `RoleMenu`(对齐 `RbacRoleMenuAppService.Set`);校验角色/菜单属于该租户库且未删除。
  302 +
  303 +---
  304 +
  305 +## 八、tenant-select 同步
  306 +
  307 +`GET /api/app/th-multi-tenancy/tenant-select`(匿名,登录页):
  308 +
  309 +| 项 | 说明 |
  310 +|----|------|
  311 +| `SkipCount` | 由错误的 `1` 修正为 `0` |
  312 +| 账号/密码 | 与公司列表相同:优先凭据表,否则 `AdminPassword` |
  313 +| `id` | 仍不返回(保持 `ThTenantSelectDto`) |
  314 +
  315 +---
  316 +
  317 +## 九、Dashboard Last Updated(同日附带)
  318 +
  319 +| 项 | 说明 |
  320 +|----|------|
  321 +| 接口 | `GET /api/app/auth-session/my-menus` |
  322 +| 问题 | `lastUpdated` 误用用户 `LastModificationTime`,相对时间与业务编辑不符 |
  323 +| 修复 | 优先系统编辑 stamp → 业务表最近修改 → 用户资料时间 |
  324 +| 过滤器 | `SystemEditStampGlobalFilter` 注册到 MVC;写接口成功刷新 stamp |
  325 +| 范围 | 美国版 + 泰额版 `food-labeling-us` 同步 |
  326 +
  327 +---
  328 +
  329 +## 十、改动文件列表
  330 +
  331 +### 泰额版 — 公司账号密码
  332 +
  333 +| 文件 | 变更 |
  334 +|------|------|
  335 +| `FoodLabeling.Th.Domain/Entities/ThTenantAdminCredentialEntity.cs` | 新建主库凭据实体 |
  336 +| `FoodLabeling.Th.Application/MultiTenancy/TenantSelectCredentialCipher.cs` | 新增 `DecryptPassword` |
  337 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyListInput.cs` | 新建 |
  338 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyListItemDto.cs` | 新建(含 `menuPermissionKeys`) |
  339 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyAdminInputVo.cs` | 新建 |
  340 +| `FoodLabeling.Th.Application.Contracts/IServices/IThMultiTenancyAppService.cs` | 公司列表/改密/菜单/角色接口 |
  341 +| `FoodLabeling.Th.Application/Services/ThMultiTenancyAppService.cs` | 全部实现 + 修复 tenant-select |
  342 +
  343 +### 泰额版 — 菜单 / 角色分配
  344 +
  345 +| 文件 | 变更 |
  346 +|------|------|
  347 +| `FoodLabeling.Th.Domain/Entities/ThTenantMenuPermissionEntity.cs` | 主库菜单权限表实体 |
  348 +| `FoodLabeling.Th.Domain.Shared/Helpers/YitIdHelper.cs` | 雪花 Id(若新建) |
  349 +| `FoodLabeling.Th.Application/MultiTenancy/ThSaasMenuPermissionCatalog.cs` | SaaS 菜单 Key 目录 |
  350 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThSaasMenuPermissionTreeNodeDto.cs` | 权限树节点 |
  351 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyMenusDto.cs` | 公司菜单出参 |
  352 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyMenusInputVo.cs` | 设置公司菜单入参 |
  353 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThCompanyRoleItemDto.cs` | 租户角色列表项 |
  354 +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThUpdateCompanyRoleMenusInputVo.cs` | 设置角色菜单入参 |
  355 +
  356 +### 美国版 / 泰额版 — Last Updated
  357 +
  358 +| 文件 | 变更 |
  359 +|------|------|
  360 +| `FoodLabeling.Application/Services/AuthSessionAppService.cs` | `lastUpdated` 取值顺序调整 |
  361 +| `FoodLabeling.Application/FoodLabelingApplicationModule.cs` | 注册 `SystemEditStampGlobalFilter` |
  362 +| (既有)`SystemEditStampGlobalFilter.cs` / `SystemEditStampCache.cs` | 写成功刷新全局 stamp |
  363 +
  364 +---
  365 +
  366 +## 十一、前端对接说明(本次未改前端)
  367 +
  368 +- 平台公司列表请对接 **`company-list`**(含 `id`、加密凭据、`menuPermissionKeys`),勿仅依赖匿名 `tenant-select`(无 `id`)。
  369 +- 改密时密码须按第四节 AES 约定加密后再提交,**不要**直接传明文。
  370 +- `tenant-admin-modal`:对接 `PUT company-admin`。
  371 +- `tenant-menu-drawer`:树数据用 `menu-permission-tree`;回显/保存用 `company-menus`(字段 `menuPermissionKeys`)。
  372 +- 角色菜单:列表用 `company-roles`,保存用 `company-role-menus`(`menuIds` 为租户库 Menu.Id)。
  373 +
  374 +---
  375 +
  376 +## 十二、自检清单
  377 +
  378 +- [ ] 主库已建表 `fl_th_tenant_admin_credential`、`fl_th_tenant_menu_permission`(或 CodeFirst 已开启并重启成功)
  379 +- [ ] `TenantSelectCrypto:SecretKey` 已配置且与前端一致
  380 +- [ ] 自定义 HttpGet/HttpPut 已带 `th-multi-tenancy/` 前缀(勿访问误路由 `/api/app/company-list` 等短路径)
  381 +- [ ] `GET company-list` 返回 `loginAccount` / `password` / `passwordSalt` / `menuPermissionKeys`
  382 +- [ ] `PUT company-admin` 改密后可用新密码登录该租户
  383 +- [ ] 再次拉列表能解出与改密后一致的明文
  384 +- [ ] `GET menu-permission-tree` 返回 SaaS 菜单树
  385 +- [ ] `PUT company-menus` 后 `GET company-menus` / `company-list` 一致
  386 +- [ ] `GET company-roles` 能列出租户角色及 `menuIds`
  387 +- [ ] `PUT company-role-menus` 后该角色菜单绑定已覆盖更新
  388 +- [ ] `tenant-select` 分页从第一条开始(不再 Skip 掉首条)
  389 +- [ ] (可选)改业务数据后 `my-menus.lastUpdated` 接近当前时间
  390 +
  391 +---
  392 +
  393 +## 十三、主库建表 DDL(缺表报错时执行)
  394 +
  395 +环境:`antis-foodlabeling-host`。若接口报 `Table '...fl_th_tenant_admin_credential' doesn't exist`,在主库执行:
  396 +
  397 +```sql
  398 +CREATE TABLE IF NOT EXISTS `fl_th_tenant_admin_credential` (
  399 + `TenantId` char(36) NOT NULL COMMENT '租户Id,对应 YiTenant.Id',
  400 + `LoginAccount` varchar(64) NOT NULL DEFAULT '' COMMENT '管理员登录账号',
  401 + `PasswordCipher` varchar(512) NOT NULL DEFAULT '' COMMENT 'AES可回显密文',
  402 + `PasswordIv` varchar(64) NOT NULL DEFAULT '' COMMENT 'AES IV Base64',
  403 + `LastModificationTime` datetime(6) NULL COMMENT '最后修改时间',
  404 + PRIMARY KEY (`TenantId`)
  405 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  406 + COMMENT='平台主库-租户管理员可回显凭据';
  407 +
  408 +CREATE TABLE IF NOT EXISTS `fl_th_tenant_menu_permission` (
  409 + `Id` varchar(32) NOT NULL COMMENT '雪花Id',
  410 + `TenantId` char(36) NOT NULL COMMENT '租户Id',
  411 + `PermissionKey` varchar(128) NOT NULL COMMENT 'SaaS菜单权限Key',
  412 + `CreationTime` datetime(6) NOT NULL COMMENT '创建时间',
  413 + PRIMARY KEY (`Id`),
  414 + UNIQUE KEY `uk_fl_th_tenant_menu_permission_tenant_key` (`TenantId`, `PermissionKey`),
  415 + KEY `IX_fl_th_tenant_menu_permission_TenantId` (`TenantId`)
  416 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  417 + COMMENT='平台主库-租户SaaS菜单权限';
  418 +```
  419 +
  420 +> 2026-07-21 已在 `antis-foodlabeling-host` 执行上述 DDL(两表已存在)。
... ...