临时数据

This commit is contained in:
2026-07-06 14:27:56 +08:00
54 changed files with 3228 additions and 421 deletions

View File

@ -12,7 +12,11 @@ using QYZH.InteractiveMagazine.Repository;
namespace QYZH.InteractiveMagazine.Service;
public class AdminAuthService(BaseRepository<AdminUser> adminUserRepository, IConfiguration configuration, ILogger<AdminAuthService> logger) : BaseRepository<AdminUser>, IAdminAuthService
public class AdminAuthService(
BaseRepository<AdminUser> adminUserRepository,
IAdminPermissionService adminPermissionService,
IConfiguration configuration,
ILogger<AdminAuthService> logger) : BaseRepository<AdminUser>, IAdminAuthService
{
private const string TokenKeyPrefix = "InteractiveMagazine:AdminAuth:Token";
@ -60,12 +64,20 @@ public class AdminAuthService(BaseRepository<AdminUser> adminUserRepository, ICo
logger.LogInformation("管理员登录成功,用户名: {UserName}, ID: {UserId}", input.UserName, adminUser.Id);
var roles = await adminPermissionService.GetAdminUserRolesAsync(adminUser.Id);
var menus = await adminPermissionService.GetAdminUserMenuTreeAsync(adminUser.Id);
var permissionCodes = await adminPermissionService.GetAdminUserPermissionCodesAsync(adminUser.Id);
return new AdminLoginOutput
{
Token = token,
UserId = (long)adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type.ToString(),
RoleIds = roles.Select(x => x.Id).ToList(),
Roles = roles,
Menus = menus,
PermissionCodes = permissionCodes
};
}
@ -89,12 +101,20 @@ public class AdminAuthService(BaseRepository<AdminUser> adminUserRepository, ICo
throw new BusinessException("用户不存在", ResultCode.NOT_FOUND);
}
var roles = await adminPermissionService.GetAdminUserRolesAsync(adminUser.Id);
var menus = await adminPermissionService.GetAdminUserMenuTreeAsync(adminUser.Id);
var permissionCodes = await adminPermissionService.GetAdminUserPermissionCodesAsync(adminUser.Id);
return new AdminUserInfoOutput
{
UserId = adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type.ToString(),
Status = adminUser.Status
Status = adminUser.Status,
RoleIds = roles.Select(x => x.Id).ToList(),
Roles = roles,
Menus = menus,
PermissionCodes = permissionCodes
};
}

View File

@ -0,0 +1,495 @@
using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Entity;
using QYZH.InteractiveMagazine.Models.Enum;
using QYZH.InteractiveMagazine.Repository;
using SqlSugar;
namespace QYZH.InteractiveMagazine.Service;
/// <summary>
/// 后台权限管理服务实现
/// </summary>
public class AdminPermissionService(
BaseRepository<AdminRole> adminRoleRepository,
BaseRepository<AdminMenu> adminMenuRepository,
BaseRepository<AdminRoleMenu> adminRoleMenuRepository,
BaseRepository<AdminUserRole> adminUserRoleRepository,
BaseRepository<AdminUser> adminUserRepository,
ILogger<AdminPermissionService> logger) : BaseRepository<AdminRole>, IAdminPermissionService
{
/// <summary>
/// 创建菜单
/// </summary>
public async Task<AdminMenuOutput> CreateMenuAsync(AdminMenuInput input)
{
await ValidateMenuInputAsync(input);
var menu = new AdminMenu
{
ParentId = input.ParentId,
Name = input.Name.Trim(),
Code = input.Code.Trim(),
Path = input.Path?.Trim(),
Component = input.Component?.Trim(),
Icon = input.Icon?.Trim(),
Sort = input.Sort,
IsVisible = input.IsVisible,
Status = input.Status,
CreatedBy = "System",
CreatedAt = DateTime.Now,
UpdatedBy = "System",
UpdatedAt = DateTime.Now,
IsDeleted = false
};
var result = await adminMenuRepository.InsertAsync(menu);
BusinessException.ThrowIf(!result, "创建菜单失败", ResultCode.GLOBAL_ERROR);
logger.LogInformation("创建后台菜单成功:{Code}ID{Id}", menu.Code, menu.Id);
return ToMenuOutput(menu);
}
/// <summary>
/// 更新菜单
/// </summary>
public async Task<AdminMenuOutput> UpdateMenuAsync(long id, AdminMenuInput input)
{
var menu = await adminMenuRepository.GetByIdAsync(id);
BusinessException.ThrowIf(menu == null, "菜单不存在", ResultCode.NOT_FOUND);
BusinessException.ThrowIf(input.ParentId == id, "父级菜单不能选择自身", ResultCode.BAD_REQUEST);
await ValidateMenuInputAsync(input, id);
menu!.ParentId = input.ParentId;
menu.Name = input.Name.Trim();
menu.Code = input.Code.Trim();
menu.Path = input.Path?.Trim();
menu.Component = input.Component?.Trim();
menu.Icon = input.Icon?.Trim();
menu.Sort = input.Sort;
menu.IsVisible = input.IsVisible;
menu.Status = input.Status;
menu.UpdatedBy = "System";
menu.UpdatedAt = DateTime.Now;
var result = await adminMenuRepository.UpdateAsync(menu);
BusinessException.ThrowIf(!result, "更新菜单失败", ResultCode.GLOBAL_ERROR);
logger.LogInformation("更新后台菜单成功:{Code}ID{Id}", menu.Code, menu.Id);
return ToMenuOutput(menu);
}
/// <summary>
/// 删除菜单
/// </summary>
public async Task DeleteMenuAsync(long id)
{
var menu = await adminMenuRepository.GetByIdAsync(id);
BusinessException.ThrowIf(menu == null, "菜单不存在", ResultCode.NOT_FOUND);
var hasChildren = await adminMenuRepository.Queryable().AnyAsync(x => x.ParentId == id && !x.IsDeleted);
BusinessException.ThrowIf(hasChildren, "请先删除子菜单", ResultCode.CONFLICT);
var usedByRole = await adminRoleMenuRepository.Queryable().AnyAsync(x => x.MenuId == id && !x.IsDeleted);
BusinessException.ThrowIf(usedByRole, "菜单已被角色使用,不能删除", ResultCode.CONFLICT);
var result = await adminMenuRepository.DeleteByIdAsync(id);
BusinessException.ThrowIf(!result, "删除菜单失败", ResultCode.GLOBAL_ERROR);
}
/// <summary>
/// 获取菜单树
/// </summary>
public async Task<List<AdminMenuOutput>> GetMenuTreeAsync(AdminMenuQueryInput input)
{
var menus = await adminMenuRepository.Queryable()
.Where(x => !x.IsDeleted)
.WhereIF(!string.IsNullOrWhiteSpace(input.Name), x => x.Name.Contains(input.Name!))
.WhereIF(!string.IsNullOrWhiteSpace(input.Code), x => x.Code.Contains(input.Code!))
.WhereIF(input.Status.HasValue, x => x.Status == input.Status!.Value)
.OrderBy(x => x.Sort)
.OrderBy(x => x.Id)
.ToListAsync();
return BuildMenuTree(menus);
}
/// <summary>
/// 创建角色
/// </summary>
public async Task<AdminRoleOutput> CreateRoleAsync(AdminRoleInput input)
{
await ValidateRoleInputAsync(input);
var role = new AdminRole
{
Name = input.Name.Trim(),
Code = input.Code.Trim(),
Remark = input.Remark?.Trim(),
Status = input.Status,
CreatedBy = "System",
CreatedAt = DateTime.Now,
UpdatedBy = "System",
UpdatedAt = DateTime.Now,
IsDeleted = false
};
await UseTranAsync(async () =>
{
var inserted = await adminRoleRepository.InsertAsync(role);
BusinessException.ThrowIf(!inserted, "创建角色失败", ResultCode.GLOBAL_ERROR);
await ReplaceRoleMenusAsync(role.Id, input.MenuIds);
});
logger.LogInformation("创建后台角色成功:{Code}ID{Id}", role.Code, role.Id);
return await GetRoleByIdAsync(role.Id);
}
/// <summary>
/// 更新角色
/// </summary>
public async Task<AdminRoleOutput> UpdateRoleAsync(long id, AdminRoleInput input)
{
var role = await adminRoleRepository.GetByIdAsync(id);
BusinessException.ThrowIf(role == null, "角色不存在", ResultCode.NOT_FOUND);
await ValidateRoleInputAsync(input, id);
role!.Name = input.Name.Trim();
role.Code = input.Code.Trim();
role.Remark = input.Remark?.Trim();
role.Status = input.Status;
role.UpdatedBy = "System";
role.UpdatedAt = DateTime.Now;
await UseTranAsync(async () =>
{
var updated = await adminRoleRepository.UpdateAsync(role);
BusinessException.ThrowIf(!updated, "更新角色失败", ResultCode.GLOBAL_ERROR);
await ReplaceRoleMenusAsync(role.Id, input.MenuIds);
});
logger.LogInformation("更新后台角色成功:{Code}ID{Id}", role.Code, role.Id);
return await GetRoleByIdAsync(role.Id);
}
/// <summary>
/// 删除角色
/// </summary>
public async Task DeleteRoleAsync(long id)
{
var role = await adminRoleRepository.GetByIdAsync(id);
BusinessException.ThrowIf(role == null, "角色不存在", ResultCode.NOT_FOUND);
var usedByUser = await adminUserRoleRepository.Queryable().AnyAsync(x => x.RoleId == id && !x.IsDeleted);
BusinessException.ThrowIf(usedByUser, "角色已分配给管理员,不能删除", ResultCode.CONFLICT);
await UseTranAsync(async () =>
{
await adminRoleMenuRepository.Deleteable().Where(x => x.RoleId == id).ExecuteCommandAsync();
var deleted = await adminRoleRepository.DeleteByIdAsync(id);
BusinessException.ThrowIf(!deleted, "删除角色失败", ResultCode.GLOBAL_ERROR);
});
}
/// <summary>
/// 获取角色详情
/// </summary>
public async Task<AdminRoleOutput> GetRoleByIdAsync(long id)
{
var role = await adminRoleRepository.GetByIdAsync(id);
BusinessException.ThrowIf(role == null, "角色不存在", ResultCode.NOT_FOUND);
var menuIds = await adminRoleMenuRepository.Queryable()
.Where(x => x.RoleId == id && !x.IsDeleted)
.Select(x => x.MenuId)
.ToListAsync();
return ToRoleOutput(role!, menuIds);
}
/// <summary>
/// 获取角色分页列表
/// </summary>
public async Task<PageListModel<AdminRoleOutput>> GetRoleListAsync(AdminRoleQueryInput input)
{
RefAsync<int> totalNumber = 0;
var roles = await adminRoleRepository.Queryable()
.Where(x => !x.IsDeleted)
.WhereIF(!string.IsNullOrWhiteSpace(input.Name), x => x.Name.Contains(input.Name!))
.WhereIF(!string.IsNullOrWhiteSpace(input.Code), x => x.Code.Contains(input.Code!))
.WhereIF(input.Status.HasValue, x => x.Status == input.Status!.Value)
.OrderByDescending(x => x.CreatedAt)
.ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);
var roleIds = roles.Select(x => x.Id).ToList();
var roleMenus = roleIds.Count == 0
? []
: await adminRoleMenuRepository.Queryable()
.Where(x => roleIds.Contains(x.RoleId) && !x.IsDeleted)
.ToListAsync();
var outputs = roles
.Select(x => ToRoleOutput(x, roleMenus.Where(rm => rm.RoleId == x.Id).Select(rm => rm.MenuId).ToList()))
.ToList();
return new PageListModel<AdminRoleOutput>(outputs, input.PageIndex, input.PageSize, totalNumber);
}
/// <summary>
/// 分配角色菜单
/// </summary>
public async Task AssignRoleMenusAsync(long roleId, AssignRoleMenusInput input)
{
var role = await adminRoleRepository.GetByIdAsync(roleId);
BusinessException.ThrowIf(role == null, "角色不存在", ResultCode.NOT_FOUND);
await ValidateMenuIdsAsync(input.MenuIds);
await UseTranAsync(async () => await ReplaceRoleMenusAsync(roleId, input.MenuIds));
}
/// <summary>
/// 分配管理员角色
/// </summary>
public async Task AssignAdminUserRolesAsync(long adminUserId, AssignAdminUserRolesInput input)
{
await ReplaceAdminUserRolesAsync(adminUserId, input.RoleIds);
}
/// <summary>
/// 获取管理员菜单树
/// </summary>
public async Task<List<AdminMenuOutput>> GetAdminUserMenuTreeAsync(long adminUserId)
{
var menus = await GetAdminUserMenusAsync(adminUserId, true);
return BuildMenuTree(menus);
}
/// <summary>
/// 获取管理员角色
/// </summary>
public async Task<List<AdminRoleSimpleOutput>> GetAdminUserRolesAsync(long adminUserId)
{
var adminUser = await adminUserRepository.GetByIdAsync(adminUserId);
BusinessException.ThrowIf(adminUser == null, "管理员不存在", ResultCode.NOT_FOUND);
return await adminRoleRepository.Queryable()
.InnerJoin<AdminUserRole>((role, userRole) => role.Id == userRole.RoleId)
.Where((role, userRole) => userRole.AdminUserId == adminUserId && !role.IsDeleted && !userRole.IsDeleted)
.Select((role, userRole) => new AdminRoleSimpleOutput
{
Id = role.Id,
Name = role.Name,
Code = role.Code
})
.ToListAsync();
}
/// <summary>
/// 获取管理员权限编码
/// </summary>
public async Task<List<string>> GetAdminUserPermissionCodesAsync(long adminUserId)
{
var menus = await GetAdminUserMenusAsync(adminUserId, false);
return menus.Select(x => x.Code).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
}
private async Task ValidateMenuInputAsync(AdminMenuInput input, long? id = null)
{
BusinessException.ThrowIf(string.IsNullOrWhiteSpace(input.Name), "菜单名称不能为空", ResultCode.BAD_REQUEST);
BusinessException.ThrowIf(string.IsNullOrWhiteSpace(input.Code), "权限编码不能为空", ResultCode.BAD_REQUEST);
if (input.ParentId > 0)
{
var parentExists = await adminMenuRepository.Queryable().AnyAsync(x => x.Id == input.ParentId && !x.IsDeleted);
BusinessException.ThrowIf(!parentExists, "父级菜单不存在", ResultCode.NOT_FOUND);
}
var code = input.Code.Trim();
var codeExists = await adminMenuRepository.Queryable()
.AnyAsync(x => x.Code == code && !x.IsDeleted && (!id.HasValue || x.Id != id.Value));
BusinessException.ThrowIf(codeExists, "权限编码已存在", ResultCode.CONFLICT);
}
private async Task ValidateRoleInputAsync(AdminRoleInput input, long? id = null)
{
BusinessException.ThrowIf(string.IsNullOrWhiteSpace(input.Name), "角色名称不能为空", ResultCode.BAD_REQUEST);
BusinessException.ThrowIf(string.IsNullOrWhiteSpace(input.Code), "角色编码不能为空", ResultCode.BAD_REQUEST);
var code = input.Code.Trim();
var codeExists = await adminRoleRepository.Queryable()
.AnyAsync(x => x.Code == code && !x.IsDeleted && (!id.HasValue || x.Id != id.Value));
BusinessException.ThrowIf(codeExists, "角色编码已存在", ResultCode.CONFLICT);
await ValidateMenuIdsAsync(input.MenuIds);
}
private async Task ValidateMenuIdsAsync(List<long> menuIds)
{
var ids = menuIds.Distinct().ToList();
if (ids.Count == 0)
{
return;
}
var existsCount = await adminMenuRepository.Queryable()
.Where(x => ids.Contains(x.Id) && !x.IsDeleted)
.CountAsync();
BusinessException.ThrowIf(existsCount != ids.Count, "包含不存在的菜单", ResultCode.BAD_REQUEST);
}
private async Task ValidateRoleIdsAsync(List<long> roleIds)
{
var ids = roleIds.Distinct().ToList();
if (ids.Count == 0)
{
return;
}
var existsCount = await adminRoleRepository.Queryable()
.Where(x => ids.Contains(x.Id) && !x.IsDeleted)
.CountAsync();
BusinessException.ThrowIf(existsCount != ids.Count, "包含不存在的角色", ResultCode.BAD_REQUEST);
}
private async Task ReplaceRoleMenusAsync(long roleId, List<long> menuIds)
{
await adminRoleMenuRepository.Deleteable().Where(x => x.RoleId == roleId).ExecuteCommandAsync();
var now = DateTime.Now;
var items = menuIds.Distinct().Select(menuId => new AdminRoleMenu
{
RoleId = roleId,
MenuId = menuId,
Status = (int)DefaultStatusEnum.Active,
CreatedBy = "System",
CreatedAt = now,
UpdatedBy = "System",
UpdatedAt = now,
IsDeleted = false
}).ToList();
if (items.Count > 0)
{
await adminRoleMenuRepository.Context.Insertable(items).ExecuteCommandAsync();
}
}
private async Task ReplaceAdminUserRolesAsync(long adminUserId, List<long> roleIds)
{
var adminUser = await adminUserRepository.GetByIdAsync(adminUserId);
BusinessException.ThrowIf(adminUser == null, "管理员不存在", ResultCode.NOT_FOUND);
await ValidateRoleIdsAsync(roleIds);
await UseTranAsync(async () =>
{
await adminUserRoleRepository.Deleteable().Where(x => x.AdminUserId == adminUserId).ExecuteCommandAsync();
var now = DateTime.Now;
var items = roleIds.Distinct().Select(roleId => new AdminUserRole
{
AdminUserId = adminUserId,
RoleId = roleId,
Status = (int)DefaultStatusEnum.Active,
CreatedBy = "System",
CreatedAt = now,
UpdatedBy = "System",
UpdatedAt = now,
IsDeleted = false
}).ToList();
if (items.Count > 0)
{
await adminUserRoleRepository.Context.Insertable(items).ExecuteCommandAsync();
}
});
}
private async Task<List<AdminMenu>> GetAdminUserMenusAsync(long adminUserId, bool visibleOnly)
{
var adminUser = await adminUserRepository.GetByIdAsync(adminUserId);
BusinessException.ThrowIf(adminUser == null, "管理员不存在", ResultCode.NOT_FOUND);
if (adminUser!.Type == AdminUserTypeEnum.SuperAdmin)
{
return await adminMenuRepository.Queryable()
.Where(x => !x.IsDeleted && x.Status == (int)DefaultStatusEnum.Active)
.WhereIF(visibleOnly, x => x.IsVisible)
.OrderBy(x => x.Sort)
.OrderBy(x => x.Id)
.ToListAsync();
}
var menus = await adminMenuRepository.Queryable()
.InnerJoin<AdminRoleMenu>((menu, roleMenu) => menu.Id == roleMenu.MenuId)
.InnerJoin<AdminRole>((menu, roleMenu, role) => roleMenu.RoleId == role.Id)
.InnerJoin<AdminUserRole>((menu, roleMenu, role, userRole) => role.Id == userRole.RoleId)
.Where((menu, roleMenu, role, userRole) =>
userRole.AdminUserId == adminUserId
&& !menu.IsDeleted
&& !roleMenu.IsDeleted
&& !role.IsDeleted
&& !userRole.IsDeleted
&& menu.Status == (int)DefaultStatusEnum.Active
&& role.Status == (int)DefaultStatusEnum.Active)
.WhereIF(visibleOnly, (menu, roleMenu, role, userRole) => menu.IsVisible)
.OrderBy((menu, roleMenu, role, userRole) => menu.Sort)
.OrderBy((menu, roleMenu, role, userRole) => menu.Id)
.Select((menu, roleMenu, role, userRole) => menu)
.ToListAsync();
return menus.DistinctBy(x => x.Id).OrderBy(x => x.Sort).ThenBy(x => x.Id).ToList();
}
private static List<AdminMenuOutput> BuildMenuTree(List<AdminMenu> menus)
{
var outputs = menus.Select(ToMenuOutput).ToList();
var lookup = outputs.ToLookup(x => x.ParentId);
foreach (var item in outputs)
{
item.Children = lookup[item.Id].OrderBy(x => x.Sort).ThenBy(x => x.Id).ToList();
}
return outputs
.Where(x => x.ParentId == 0 || outputs.All(item => item.Id != x.ParentId))
.OrderBy(x => x.Sort)
.ThenBy(x => x.Id)
.ToList();
}
private static AdminMenuOutput ToMenuOutput(AdminMenu menu)
{
return new AdminMenuOutput
{
Id = menu.Id,
ParentId = menu.ParentId,
Name = menu.Name,
Code = menu.Code,
Path = menu.Path,
Component = menu.Component,
Icon = menu.Icon,
Sort = menu.Sort,
IsVisible = menu.IsVisible,
Status = menu.Status
};
}
private static AdminRoleOutput ToRoleOutput(AdminRole role, List<long> menuIds)
{
return new AdminRoleOutput
{
Id = role.Id,
Name = role.Name,
Code = role.Code,
Remark = role.Remark,
Status = role.Status,
MenuIds = menuIds,
CreatedAt = role.CreatedAt
};
}
}

View File

@ -15,7 +15,10 @@ namespace QYZH.InteractiveMagazine.Service;
/// <summary>
/// 管理员用户服务实现
/// </summary>
public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILogger<AdminUserService> logger) : BaseRepository<AdminUser>, IAdminUserService
public class AdminUserService(
BaseRepository<AdminUser> adminUserRepository,
IAdminPermissionService adminPermissionService,
ILogger<AdminUserService> logger) : BaseRepository<AdminUser>, IAdminUserService
{
/// <summary>
@ -63,9 +66,14 @@ public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILo
throw new BusinessException("创建管理员失败", ResultCode.GLOBAL_ERROR);
}
if (input.RoleIds != null)
{
await adminPermissionService.AssignAdminUserRolesAsync(adminUser.Id, new AssignAdminUserRolesInput { RoleIds = input.RoleIds });
}
logger.LogInformation("管理员创建成功,用户名: {UserName}, ID: {Id}", input.UserName, adminUser.Id);
return new AdminUserOutput { Id = adminUser.Id, UserName = adminUser.UserName, Type = adminUser.Type.ToString(), Status = adminUser.Status, CreatedBy = adminUser.CreatedBy, CreatedAt = adminUser.CreatedAt, UpdatedBy = adminUser.UpdatedBy, UpdatedAt = adminUser.UpdatedAt };
return await ToAdminUserOutputAsync(adminUser);
}
/// <summary>
@ -114,9 +122,14 @@ public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILo
throw new BusinessException("更新管理员失败", ResultCode.GLOBAL_ERROR);
}
if (input.RoleIds != null)
{
await adminPermissionService.AssignAdminUserRolesAsync(adminUser.Id, new AssignAdminUserRolesInput { RoleIds = input.RoleIds });
}
logger.LogInformation("管理员更新成功ID: {Id}", id);
return new AdminUserOutput { Id = adminUser.Id, UserName = adminUser.UserName, Type = adminUser.Type.ToString(), Status = adminUser.Status, CreatedBy = adminUser.CreatedBy, CreatedAt = adminUser.CreatedAt, UpdatedBy = adminUser.UpdatedBy, UpdatedAt = adminUser.UpdatedAt };
return await ToAdminUserOutputAsync(adminUser);
}
/// <summary>
@ -156,17 +169,7 @@ public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILo
logger.LogWarning("未找到管理员ID: {Id}", id);
throw new BusinessException("管理员不存在", ResultCode.NOT_FOUND);
}
return new AdminUserOutput
{
Id = adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type.ToString(),
Status = adminUser.Status,
CreatedBy = adminUser.CreatedBy,
CreatedAt = adminUser.CreatedAt,
UpdatedBy = adminUser.UpdatedBy,
UpdatedAt = adminUser.UpdatedAt
};
return await ToAdminUserOutputAsync(adminUser);
}
/// <summary>
@ -201,6 +204,12 @@ public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILo
UpdatedAt = a.UpdatedAt
}, true)
.ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);
foreach (var item in pageResult)
{
item.Roles = await adminPermissionService.GetAdminUserRolesAsync(item.Id);
item.RoleIds = item.Roles.Select(x => x.Id).ToList();
}
return new PageListModel<AdminUserOutput>(pageResult, input.PageIndex, input.PageSize, totalNumber);
}
@ -231,4 +240,22 @@ public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILo
logger.LogInformation("管理员状态更新成功ID: {Id}", id);
}
private async Task<AdminUserOutput> ToAdminUserOutputAsync(AdminUser adminUser)
{
var roles = await adminPermissionService.GetAdminUserRolesAsync(adminUser.Id);
return new AdminUserOutput
{
Id = adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type.ToString(),
Status = adminUser.Status,
CreatedBy = adminUser.CreatedBy,
CreatedAt = adminUser.CreatedAt,
UpdatedBy = adminUser.UpdatedBy,
UpdatedAt = adminUser.UpdatedAt,
RoleIds = roles.Select(x => x.Id).ToList(),
Roles = roles
};
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.Common.Helpers;
using QYZH.InteractiveMagazine.Infrastructure.OSS;
using QYZH.InteractiveMagazine.Infrastructure.RabbitMQ;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
@ -20,20 +22,23 @@ public class UserJournalService(
BaseRepository<Journal> journalRepository,
ILogger<UserJournalService> logger,
IRabbitMQService rabbitMqService,
OssService ossService,
IPetService petService)
: BaseRepository<UserJournal>, IUserJournalService
{
private const string JournalExchange = "ex.journal";
private const string BindJournalQueue = "mq.journal.bindUser";
private const string BindJournalRoutingKey = "rk.journal.bindUser";
private const string QrCodeGenerateQueue = "mq.journal.qrcode.generate";
private const string QrCodeGenerateRoutingKey = "rk.journal.qrcode.generate";
private const int MaxBatchQrCodeCount = 500;
private const int MaxRandomIdGenerateRetryCount = 5;
/// <summary>
/// 用户绑定期刊(扫码绑定)
/// </summary>
public async Task<BindJournalOutput> BindJournalAsync(long userId, BindJournalInput input)
{
logger.LogInformation("用户绑定期刊UserId: {UserId}, JournalId: {JournalId}, Id: {Id}, Type: {Type}",
userId, input.JournalId, input.Id, input.Type);
// 校验参数
if (input.JournalId <= 0|| input.Id <= 0)
@ -41,7 +46,12 @@ public class UserJournalService(
throw new BusinessException("参数错误,未获取到期刊", ResultCode.BAD_REQUEST);
}
// 校验用户是否存在
var user = await usersRepository.GetByIdAsync(userId);
var activeStatus = (int)UserJournalStatusEnum.Active;
var boundAt = DateTime.Now;
var user = await usersRepository.Queryable()
.Where(u => u.Id == userId && !u.IsDeleted)
.FirstAsync();
if (user == null || user.IsDeleted)
{
logger.LogWarning("绑定期刊失败用户不存在UserId: {UserId}", userId);
@ -63,24 +73,17 @@ public class UserJournalService(
throw new BusinessException("该期刊暂未发布,无法绑定", ResultCode.UNPROCESSABLE_ENTITY);
}
// 防重复绑定:同一用户 + 期刊 + 实例 + 类型
if (!Enum.TryParse<UserJournalTypeEnum>(input.Type, true, out var bindType))
{
throw new BusinessException("关联类型不正确", ResultCode.BAD_REQUEST);
}
var userJournal = await userJournalRepository.Queryable()
.Where(uj => uj.Id == input.Id && uj.JournalId == input.JournalId && !uj.IsDeleted)
.FirstAsync();
// 检查是否为首次绑定期刊(用于激活宠物)
if (userJournal == null)
{
logger.LogWarning("绑定期刊失败二维码记录不存在UserId: {UserId}, JournalId: {JournalId}, Id: {Id}", userId, input.JournalId, input.Id);
throw new BusinessException("二维码不存在或已失效", ResultCode.NOT_FOUND);
}
if (userJournal.Status != (int)UserJournalStatusEnum.Active)
if (userJournal.Status != activeStatus)
{
throw new BusinessException("二维码已失效", ResultCode.UNPROCESSABLE_ENTITY);
}
@ -91,29 +94,47 @@ public class UserJournalService(
throw new BusinessException("该期刊已被绑定", ResultCode.BAD_REQUEST);
}
var isFirstBind = !userJournalRepository.Context.Queryable<UserJournal>()
.Any(uj => uj.UserId == userId);
// 创建绑定记录
var updateCount = await userJournalRepository.Updateable()
.SetColumns(uj => uj.UserId == userId)
.SetColumns(uj => uj.Type == bindType)
.SetColumns(uj => uj.UpdatedBy == userId.ToString())
.SetColumns(uj => uj.UpdatedAt == DateTime.Now)
.Where(uj => uj.Id == input.Id && !uj.IsDeleted && (uj.UserId == null || uj.UserId == 0))
.ExecuteCommandAsync();
if (updateCount <= 0)
var isFirstBind = false;
await userJournalRepository.UseTranAsync(async () =>
{
logger.LogError("绑定期刊失败写入数据库失败UserId: {UserId}, JournalId: {JournalId}", userId, input.JournalId);
throw new BusinessException("绑定期刊失败,请稍后重试", ResultCode.GLOBAL_ERROR);
}
var boundJournalIds = await userJournalRepository.Queryable()
.Where(uj => uj.UserId == userId && !uj.IsDeleted && uj.Status == activeStatus)
.Select(uj => uj.JournalId)
.ToListAsync();
if (boundJournalIds.Contains(input.JournalId))
{
logger.LogWarning("用户重复绑定同一期刊UserId: {UserId}, JournalId: {JournalId}, Id: {Id}", userId, input.JournalId, input.Id);
throw new BusinessException("该用户已绑定过该期刊", ResultCode.BAD_REQUEST);
}
isFirstBind = boundJournalIds.Count == 0;
boundAt = DateTime.Now;
// 创建绑定记录
var updateCount = await userJournalRepository.Updateable()
.SetColumns(uj => uj.UserId == userId)
.SetColumns(uj => uj.UpdatedBy == userId.ToString())
.SetColumns(uj => uj.UpdatedAt == boundAt)
.Where(uj => uj.Id == input.Id
&& uj.JournalId == input.JournalId
&& !uj.IsDeleted
&& uj.Status == activeStatus
&& (uj.UserId == null || uj.UserId == 0))
.ExecuteCommandAsync();
if (updateCount <= 0)
{
logger.LogError("绑定期刊失败写入数据库失败UserId: {UserId}, JournalId: {JournalId}", userId, input.JournalId);
throw new BusinessException("绑定期刊失败,请稍后重试", ResultCode.GLOBAL_ERROR);
}
});
logger.LogInformation("用户绑定期刊成功UserId: {UserId}, JournalId: {JournalId}, Id: {Id}", userId, input.JournalId, userJournal.Id);
userJournal.UserId = userId;
userJournal.Type = bindType;
userJournal.UpdatedBy = userId.ToString();
userJournal.UpdatedAt = DateTime.Now;
userJournal.UpdatedAt = boundAt;
await SendBindJournalMessageAsync(user, journal);
@ -145,16 +166,16 @@ public class UserJournalService(
/// <summary>
/// 生成期刊二维码记录
/// </summary>
public async Task<UserJournalQrCodeOutput> CreateQrCodeAsync(CreateUserJournalQrCodeInput input, long operatorId)
public async Task<CreateUserJournalQrCodeOutput> CreateQrCodesAsync(CreateUserJournalQrCodeInput input, string operatorName)
{
if (input.JournalId <= 0)
{
throw new BusinessException("期刊Id不能为空", ResultCode.BAD_REQUEST);
}
if (!Enum.TryParse<UserJournalTypeEnum>(input.Type, true, out var type))
if (input.Count <= 0 || input.Count > MaxBatchQrCodeCount)
{
throw new BusinessException("关联类型不正确", ResultCode.BAD_REQUEST);
throw new BusinessException($"生成数量必须在1-{MaxBatchQrCodeCount}之间", ResultCode.BAD_REQUEST);
}
var journal = await journalRepository.GetByIdAsync(input.JournalId);
@ -168,31 +189,67 @@ public class UserJournalService(
throw new BusinessException("该期刊暂未发布,无法生成二维码", ResultCode.UNPROCESSABLE_ENTITY);
}
var record = new UserJournal
{
UserId = null,
JournalId = input.JournalId,
Type = type,
Status = (int)UserJournalStatusEnum.Active,
IsDeleted = false,
CreatedBy = operatorId.ToString(),
CreatedAt = DateTime.Now,
UpdatedBy = operatorId.ToString(),
UpdatedAt = DateTime.Now
};
var now = DateTime.Now;
var randomIds = await GenerateUniqueQrCodeIdsAsync(input.Count);
var records = randomIds
.Select(id => new UserJournal
{
Id = id,
UserId = null,
JournalId = input.JournalId,
Type = 0,
Status = (int)UserJournalStatusEnum.Generating,
IsDeleted = false,
CreatedBy = operatorName,
CreatedAt = now,
UpdatedBy = operatorName,
UpdatedAt = now
})
.ToList();
var result = await userJournalRepository.InsertAsync(record);
if (!result)
var insertCount = await userJournalRepository.Context.Insertable(records).ExecuteCommandAsync();
if (insertCount <= 0)
{
throw new BusinessException("生成二维码失败,请稍后重试", ResultCode.GLOBAL_ERROR);
throw new BusinessException("提交二维码生成任务失败,请稍后重试", ResultCode.GLOBAL_ERROR);
}
return MapQrCodeOutput(record, journal, null);
var recordIds = records.Select(r => r.Id).ToList();
var messageSent = await rabbitMqService.SendAsync(new RabbitMQSendParam
{
Exchange = JournalExchange,
Queue = QrCodeGenerateQueue,
RoutingKey = QrCodeGenerateRoutingKey,
Data = new GenerateUserJournalQrCodeMessage
{
RecordIds = recordIds,
OperatorName = operatorName
}
});
if (!messageSent)
{
await userJournalRepository.Updateable()
.SetColumns(uj => uj.Status == (int)UserJournalStatusEnum.Failed)
.SetColumns(uj => uj.UpdatedBy == operatorName)
.SetColumns(uj => uj.UpdatedAt == DateTime.Now)
.Where(uj => recordIds.Contains(uj.Id) && !uj.IsDeleted && uj.Status == (int)UserJournalStatusEnum.Generating)
.ExecuteCommandAsync();
logger.LogError("发送期刊二维码生成消息失败RecordIds: {RecordIds}", string.Join(",", recordIds));
throw new BusinessException("二维码生成任务提交失败,请稍后重试", ResultCode.GLOBAL_ERROR);
}
return new CreateUserJournalQrCodeOutput
{
JournalId = input.JournalId,
RequestedCount = input.Count,
AcceptedCount = insertCount,
RecordIds = recordIds,
IsAsync = true,
Message = "二维码生成任务已提交,请稍后查询未绑定二维码列表"
};
}
/// <summary>
/// 分页查询期刊二维码记录
/// </summary>
public async Task<PageListModel<UserJournalQrCodeOutput>> GetQrCodePageListAsync(UserJournalQrCodeQueryInput input)
{
if (input.PageIndex <= 0)
@ -239,7 +296,7 @@ public class UserJournalService(
/// <summary>
/// 删除未绑定的期刊二维码记录
/// </summary>
public async Task<bool> DeleteQrCodeAsync(DeleteUserJournalQrCodeInput input, long operatorId)
public async Task<bool> DeleteQrCodeAsync(DeleteUserJournalQrCodeInput input, string operatorName)
{
if (input.Ids == null || input.Ids.Count == 0)
{
@ -264,7 +321,7 @@ public class UserJournalService(
var updateCount = await userJournalRepository.Updateable()
.SetColumns(uj => uj.IsDeleted == true)
.SetColumns(uj => uj.Status == (int)UserJournalStatusEnum.Inactive)
.SetColumns(uj => uj.UpdatedBy == operatorId.ToString())
.SetColumns(uj => uj.UpdatedBy == operatorName)
.SetColumns(uj => uj.UpdatedAt == DateTime.Now)
.Where(uj => ids.Contains(uj.Id) && !uj.IsDeleted && (uj.UserId == null || uj.UserId == 0))
.ExecuteCommandAsync();
@ -272,6 +329,24 @@ public class UserJournalService(
return updateCount == ids.Count;
}
public async Task<List<UserJournalQrCodeOutput>> GetUnboundQrCodesByJournalIdAsync(long journalId)
{
if (journalId <= 0)
{
throw new BusinessException("期刊Id不能为空", ResultCode.BAD_REQUEST);
}
var records = await userJournalRepository.Queryable()
.Where(uj => uj.JournalId == journalId && !uj.IsDeleted)
.Where(uj => uj.UserId == null || uj.UserId == 0)
.Where(uj => uj.Status == (int)UserJournalStatusEnum.Active)
.Where(uj => !string.IsNullOrEmpty(uj.QrCodeUrl))
.OrderByDescending(uj => uj.CreatedAt)
.ToListAsync();
return await BuildQrCodeOutputsAsync(records);
}
private async Task<List<UserJournalQrCodeOutput>> BuildQrCodeOutputsAsync(List<UserJournal> records)
{
if (records.Count == 0)
@ -322,7 +397,7 @@ public class UserJournalService(
Type = record.Type.ToString(),
Status = record.Status.ToString(),
IsBound = record.UserId.HasValue && record.UserId.Value > 0,
QrCodeContent = BuildQrCodeContent(record.JournalId, record.Id),
QrCodeUrl = DomainHelper.OssFullUrl(record.QrCodeUrl ?? string.Empty),
CreatedAt = record.CreatedAt,
BoundAt = record.UserId.HasValue && record.UserId.Value > 0 ? record.UpdatedAt : null
};
@ -330,7 +405,52 @@ public class UserJournalService(
private static string BuildQrCodeContent(long journalId, long id)
{
return JsonSerializer.Serialize(new { JournalId = journalId, Id = id });
return JsonSerializer.Serialize(new { JournalId = journalId.ToString(), Id = id.ToString() });
}
private async Task<long> GenerateUniqueQrCodeIdAsync()
{
for (var i = 0; i < MaxRandomIdGenerateRetryCount; i++)
{
var id = RandomIdHelper.GenerateLongId();
var exists = await userJournalRepository.Queryable()
.AnyAsync(uj => uj.Id == id);
if (!exists)
{
return id;
}
}
throw new BusinessException("生成二维码ID失败请稍后重试", ResultCode.GLOBAL_ERROR);
}
private async Task<List<long>> GenerateUniqueQrCodeIdsAsync(int count)
{
var ids = new HashSet<long>();
for (var i = 0; i < MaxRandomIdGenerateRetryCount && ids.Count < count; i++)
{
while (ids.Count < count)
{
ids.Add(RandomIdHelper.GenerateLongId());
}
var candidateIds = ids.ToList();
var existingIds = await userJournalRepository.Queryable()
.Where(uj => candidateIds.Contains(uj.Id))
.Select(uj => uj.Id)
.ToListAsync();
if (existingIds.Count == 0)
{
return candidateIds;
}
ids.ExceptWith(existingIds);
}
throw new BusinessException("生成二维码ID失败请稍后重试", ResultCode.GLOBAL_ERROR);
}
private async Task SendBindJournalMessageAsync(Users user, Journal journal)
@ -384,7 +504,6 @@ public class UserJournalService(
RefAsync<int> totalNumber = 0;
var pageResult = await userJournalRepository.Queryable()
.Where(uj => uj.UserId == userId)
.WhereIF(!string.IsNullOrWhiteSpace(input.Type), uj => uj.Type.ToString() == input.Type)
.OrderByDescending(uj => uj.CreatedAt)
.Select(uj => new BindJournalOutput
{

View File

@ -28,10 +28,27 @@ public class UsersService(
/// </summary>
public async Task<BaseResponse<PageListModel<UsersOutput>>> GetListAsync(UsersQueryInput input)
{
var page = Queryable()
.WhereIF(!string.IsNullOrEmpty(input.WxUserId), u => u.WxUserId.ToString() == input.WxUserId)
.OrderBy(u => u.Id, OrderByType.Desc)
.ToPage<Users, UsersOutput>(input);
RefAsync<int> totalNumber = 0;
var list = await Queryable()
.LeftJoin<WxUser>((u, w) => u.WxUserId == w.Id && !w.IsDeleted)
.WhereIF(!string.IsNullOrEmpty(input.WxUserId), (u, w) => u.WxUserId.ToString() == input.WxUserId)
.OrderBy((u, w) => u.Id, OrderByType.Desc)
.Select((u, w) => new UsersOutput
{
Id = u.Id,
WxUserId = u.WxUserId.ToString(),
WxUserName = w.Name,
Name = u.Name,
AvatarUrl = u.AvatarUrl,
Points = u.Points,
Type = u.Type.ToString(),
Status = u.Status.ToString(),
GrowthPoints = u.GrowthPoints,
UploadDomain = u.UploadDomain
})
.ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);
var page = new PageListModel<UsersOutput>(list, input.PageIndex, input.PageSize, totalNumber);
return BaseResponse<PageListModel<UsersOutput>>.Success(page);
}
@ -41,7 +58,23 @@ public class UsersService(
/// </summary>
public async Task<BaseResponse<UserDetailOutput>> GetDetailAsync(long id)
{
var user = await GetByIdAsync<UsersOutput>(u => u.Id == id);
var user = await Queryable()
.LeftJoin<WxUser>((u, w) => u.WxUserId == w.Id && !w.IsDeleted)
.Where((u, w) => u.Id == id)
.Select((u, w) => new UsersOutput
{
Id = u.Id,
WxUserId = u.WxUserId.ToString(),
WxUserName = w.Name,
Name = u.Name,
AvatarUrl = u.AvatarUrl,
Points = u.Points,
Type = u.Type.ToString(),
Status = u.Status.ToString(),
GrowthPoints = u.GrowthPoints,
UploadDomain = u.UploadDomain
})
.FirstAsync();
if (user == null)
{
return BaseResponse<UserDetailOutput>.Fail("用户不存在");