refactor: 重构项目基础架构与实体体系
- 替换原有自定义生命周期接口为通用基础服务体系 - 将所有实体基类替换为带雪花ID的SqlSugarBaseEntity - 迁移DTO到Models项目并统一管理 - 移除冗余的Repository层实现,改用通用基础服务 - 添加Yitter.IdGenerator雪花ID生成支持 - 重构SqlSugar数据库上下文与依赖注入配置 - 新增微信用户、用户勋章、背包等实体与配套服务 - 整理分页查询与结果封装类 - 优化WebApi控制器结构
This commit is contained in:
@ -6,31 +6,23 @@ using QYZH.InteractiveMagazine.Infrastructure.Cache;
|
||||
using QYZH.InteractiveMagazine.IService;
|
||||
using QYZH.InteractiveMagazine.IService.Dto;
|
||||
using QYZH.InteractiveMagazine.Models.Common;
|
||||
using QYZH.InteractiveMagazine.Models.Dto;
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
using QYZH.InteractiveMagazine.Models.Settings;
|
||||
using QYZH.InteractiveMagazine.Repository;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Service;
|
||||
|
||||
public class AdminAuthService : IAdminAuthService
|
||||
public class AdminAuthService(BaseRepository<AdminUser> adminUserRepository, IConfiguration configuration, ILogger<AdminAuthService> logger) : BaseRepository<AdminUser>, IAdminAuthService
|
||||
{
|
||||
private readonly IAdminUserRepository _adminUserRepository;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<AdminAuthService> _logger;
|
||||
|
||||
private const string TokenKeyPrefix = "InteractiveMagazine:AdminAuth:Token";
|
||||
private const string UserInfoKeyPrefix = "InteractiveMagazine:AdminAuth:UserInfo";
|
||||
|
||||
public AdminAuthService(IAdminUserRepository adminUserRepository, IConfiguration configuration, ILogger<AdminAuthService> logger)
|
||||
{
|
||||
_adminUserRepository = adminUserRepository;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<AdminLoginOutput> LoginAsync(AdminLoginInput input)
|
||||
{
|
||||
_logger.LogInformation("管理员登录尝试,用户名: {UserName}", input.UserName);
|
||||
logger.LogInformation("管理员登录尝试,用户名: {UserName}", input.UserName);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.UserName))
|
||||
{
|
||||
@ -42,22 +34,22 @@ public class AdminAuthService : IAdminAuthService
|
||||
throw new BusinessException("密码不能为空", 400);
|
||||
}
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByUserNameAsync(input.UserName);
|
||||
var adminUser = await adminUserRepository.GetFirstAsync(a => a.UserName == input.UserName);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("管理员登录失败,用户名不存在: {UserName}", input.UserName);
|
||||
logger.LogWarning("管理员登录失败,用户名不存在: {UserName}", input.UserName);
|
||||
throw new BusinessException("用户名或密码错误", 401);
|
||||
}
|
||||
|
||||
if (!BCrypt.Net.BCrypt.Verify(input.Password, adminUser.PasswordHash))
|
||||
{
|
||||
_logger.LogWarning("管理员登录失败,密码错误: {UserName}", input.UserName);
|
||||
logger.LogWarning("管理员登录失败,密码错误: {UserName}", input.UserName);
|
||||
throw new BusinessException("用户名或密码错误", 401);
|
||||
}
|
||||
|
||||
if (adminUser.Status != "Active")
|
||||
{
|
||||
_logger.LogWarning("管理员登录失败,账号已禁用: {UserName}", input.UserName);
|
||||
logger.LogWarning("管理员登录失败,账号已禁用: {UserName}", input.UserName);
|
||||
throw new BusinessException("账号已被禁用,请联系系统管理员", 403);
|
||||
}
|
||||
|
||||
@ -67,7 +59,7 @@ public class AdminAuthService : IAdminAuthService
|
||||
|
||||
await RedisHelper.StringSetAsync($"{TokenKeyPrefix}:{adminUser.Id}", token, TimeSpan.FromMinutes(jwtSettings.ExpiryMinutes));
|
||||
|
||||
_logger.LogInformation("管理员登录成功,用户名: {UserName}, ID: {UserId}", input.UserName, adminUser.Id);
|
||||
logger.LogInformation("管理员登录成功,用户名: {UserName}, ID: {UserId}", input.UserName, adminUser.Id);
|
||||
|
||||
return new AdminLoginOutput
|
||||
{
|
||||
@ -80,21 +72,21 @@ public class AdminAuthService : IAdminAuthService
|
||||
|
||||
public async Task LogoutAsync(long userId)
|
||||
{
|
||||
_logger.LogInformation("管理员登出,ID: {UserId}", userId);
|
||||
logger.LogInformation("管理员登出,ID: {UserId}", userId);
|
||||
|
||||
await RedisHelper.KeyDeleteAsync($"{TokenKeyPrefix}:{userId}");
|
||||
|
||||
_logger.LogInformation("管理员登出成功,ID: {UserId}", userId);
|
||||
logger.LogInformation("管理员登出成功,ID: {UserId}", userId);
|
||||
}
|
||||
|
||||
public async Task<AdminUserInfoOutput> GetAdminInfoAsync(long userId)
|
||||
{
|
||||
_logger.LogInformation("获取管理员信息,ID: {UserId}", userId);
|
||||
logger.LogInformation("获取管理员信息,ID: {UserId}", userId);
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByIdAsync(userId);
|
||||
var adminUser = await adminUserRepository.GetByIdAsync(userId);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到管理员,ID: {UserId}", userId);
|
||||
logger.LogWarning("未找到管理员,ID: {UserId}", userId);
|
||||
throw new BusinessException("用户不存在", 404);
|
||||
}
|
||||
|
||||
@ -109,7 +101,7 @@ public class AdminAuthService : IAdminAuthService
|
||||
|
||||
public async Task ChangePasswordAsync(long userId, string oldPassword, string newPassword)
|
||||
{
|
||||
_logger.LogInformation("管理员修改密码尝试,ID: {UserId}", userId);
|
||||
logger.LogInformation("管理员修改密码尝试,ID: {UserId}", userId);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(oldPassword))
|
||||
{
|
||||
@ -121,22 +113,22 @@ public class AdminAuthService : IAdminAuthService
|
||||
throw new BusinessException("新密码不能为空", 400);
|
||||
}
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByIdAsync(userId);
|
||||
var adminUser = await adminUserRepository.GetByIdAsync(userId);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到管理员,ID: {UserId}", userId);
|
||||
logger.LogWarning("未找到管理员,ID: {UserId}", userId);
|
||||
throw new BusinessException("用户不存在", 404);
|
||||
}
|
||||
|
||||
if (!BCrypt.Net.BCrypt.Verify(oldPassword, adminUser.PasswordHash))
|
||||
{
|
||||
_logger.LogWarning("管理员修改密码失败,原密码错误,ID: {UserId}", userId);
|
||||
logger.LogWarning("管理员修改密码失败,原密码错误,ID: {UserId}", userId);
|
||||
throw new BusinessException("原密码错误", 400);
|
||||
}
|
||||
|
||||
adminUser.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword);
|
||||
|
||||
var result = await _adminUserRepository.UpdateAsync(adminUser);
|
||||
var result = await adminUserRepository.UpdateAsync(adminUser);
|
||||
if (!result)
|
||||
{
|
||||
throw new BusinessException("修改密码失败", 500);
|
||||
@ -144,12 +136,12 @@ public class AdminAuthService : IAdminAuthService
|
||||
|
||||
await RedisHelper.KeyDeleteAsync($"{TokenKeyPrefix}:{userId}");
|
||||
|
||||
_logger.LogInformation("管理员修改密码成功,ID: {UserId}", userId);
|
||||
logger.LogInformation("管理员修改密码成功,ID: {UserId}", userId);
|
||||
}
|
||||
|
||||
private JwtSettings GetJwtSettings()
|
||||
{
|
||||
var jwtSettings = _configuration.GetSection("JwtSettings").Get<JwtSettings>()
|
||||
var jwtSettings = configuration.GetSection("JwtSettings").Get<JwtSettings>()
|
||||
?? new JwtSettings
|
||||
{
|
||||
Issuer = "QYZH.InteractiveMagazine",
|
||||
|
||||
@ -7,29 +7,22 @@ using QYZH.InteractiveMagazine.Models.Common;
|
||||
using QYZH.InteractiveMagazine.Models.Dto;
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
using QYZH.InteractiveMagazine.Repository;
|
||||
using SqlSugar;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Service;
|
||||
|
||||
/// <summary>
|
||||
/// 管理员用户服务实现
|
||||
/// </summary>
|
||||
public class AdminUserService : IAdminUserService
|
||||
public class AdminUserService(BaseRepository<AdminUser> adminUserRepository, ILogger<AdminUserService> logger) : BaseRepository<AdminUser>, IAdminUserService
|
||||
{
|
||||
private readonly IAdminUserRepository _adminUserRepository;
|
||||
private readonly ILogger<AdminUserService> _logger;
|
||||
|
||||
public AdminUserService(IAdminUserRepository adminUserRepository, ILogger<AdminUserService> logger)
|
||||
{
|
||||
_adminUserRepository = adminUserRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建管理员
|
||||
/// </summary>
|
||||
public async Task<AdminUserOutput> CreateAsync(AdminUserInput input)
|
||||
{
|
||||
_logger.LogInformation("正在创建管理员,用户名: {UserName}", input.UserName);
|
||||
logger.LogInformation("正在创建管理员,用户名: {UserName}", input.UserName);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.UserName))
|
||||
{
|
||||
@ -42,10 +35,10 @@ public class AdminUserService : IAdminUserService
|
||||
}
|
||||
|
||||
// 检查用户名是否已存在
|
||||
var existingUser = await _adminUserRepository.GetByUserNameAsync(input.UserName);
|
||||
var existingUser = await adminUserRepository.GetFirstAsync(a => a.UserName == input.UserName);
|
||||
if (existingUser != null)
|
||||
{
|
||||
_logger.LogWarning("创建管理员失败,用户名已存在: {UserName}", input.UserName);
|
||||
logger.LogWarning("创建管理员失败,用户名已存在: {UserName}", input.UserName);
|
||||
throw new BusinessException("用户名已存在", 400);
|
||||
}
|
||||
|
||||
@ -62,14 +55,14 @@ public class AdminUserService : IAdminUserService
|
||||
IsDeleted = false
|
||||
};
|
||||
|
||||
var result = await _adminUserRepository.InsertAsync(adminUser);
|
||||
var result = await adminUserRepository.InsertAsync(adminUser);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("管理员创建失败,用户名: {UserName}", input.UserName);
|
||||
logger.LogError("管理员创建失败,用户名: {UserName}", input.UserName);
|
||||
throw new BusinessException("创建管理员失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("管理员创建成功,用户名: {UserName}, ID: {Id}", input.UserName, adminUser.Id);
|
||||
logger.LogInformation("管理员创建成功,用户名: {UserName}, ID: {Id}", input.UserName, adminUser.Id);
|
||||
|
||||
return MapToOutput(adminUser);
|
||||
}
|
||||
@ -79,22 +72,22 @@ public class AdminUserService : IAdminUserService
|
||||
/// </summary>
|
||||
public async Task<AdminUserOutput> UpdateAsync(long id, AdminUserInput input)
|
||||
{
|
||||
_logger.LogInformation("正在更新管理员,ID: {Id}", id);
|
||||
logger.LogInformation("正在更新管理员,ID: {Id}", id);
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByIdAsync(id);
|
||||
var adminUser = await adminUserRepository.GetByIdAsync(id);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到要更新的管理员,ID: {Id}", id);
|
||||
logger.LogWarning("未找到要更新的管理员,ID: {Id}", id);
|
||||
throw new BusinessException("管理员不存在", 404);
|
||||
}
|
||||
|
||||
// 如果用户名有变更,检查是否与其他用户重复
|
||||
if (!string.IsNullOrWhiteSpace(input.UserName) && input.UserName != adminUser.UserName)
|
||||
{
|
||||
var existingUser = await _adminUserRepository.GetByUserNameAsync(input.UserName.Trim());
|
||||
var existingUser = await adminUserRepository.GetFirstAsync(a => a.UserName == input.UserName.Trim());
|
||||
if (existingUser != null && existingUser.Id != id)
|
||||
{
|
||||
_logger.LogWarning("更新管理员失败,用户名已存在: {UserName}", input.UserName);
|
||||
logger.LogWarning("更新管理员失败,用户名已存在: {UserName}", input.UserName);
|
||||
throw new BusinessException("用户名已存在", 400);
|
||||
}
|
||||
|
||||
@ -120,14 +113,14 @@ public class AdminUserService : IAdminUserService
|
||||
adminUser.UpdatedBy = "System";
|
||||
adminUser.UpdatedAt = DateTime.Now;
|
||||
|
||||
var result = await _adminUserRepository.UpdateAsync(adminUser);
|
||||
var result = await adminUserRepository.UpdateAsync(adminUser);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("管理员更新失败,ID: {Id}", id);
|
||||
logger.LogError("管理员更新失败,ID: {Id}", id);
|
||||
throw new BusinessException("更新管理员失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("管理员更新成功,ID: {Id}", id);
|
||||
logger.LogInformation("管理员更新成功,ID: {Id}", id);
|
||||
|
||||
return MapToOutput(adminUser);
|
||||
}
|
||||
@ -137,23 +130,23 @@ public class AdminUserService : IAdminUserService
|
||||
/// </summary>
|
||||
public async Task DeleteAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在删除管理员,ID: {Id}", id);
|
||||
logger.LogInformation("正在删除管理员,ID: {Id}", id);
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByIdAsync(id);
|
||||
var adminUser = await adminUserRepository.GetByIdAsync(id);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到要删除的管理员,ID: {Id}", id);
|
||||
logger.LogWarning("未找到要删除的管理员,ID: {Id}", id);
|
||||
throw new BusinessException("管理员不存在", 404);
|
||||
}
|
||||
|
||||
var result = await _adminUserRepository.DeleteByIdAsync(id);
|
||||
var result = await adminUserRepository.DeleteByIdAsync(id);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("管理员删除失败,ID: {Id}", id);
|
||||
logger.LogError("管理员删除失败,ID: {Id}", id);
|
||||
throw new BusinessException("删除管理员失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("管理员删除成功,ID: {Id}", id);
|
||||
logger.LogInformation("管理员删除成功,ID: {Id}", id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -161,12 +154,12 @@ public class AdminUserService : IAdminUserService
|
||||
/// </summary>
|
||||
public async Task<AdminUserOutput> GetByIdAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在获取管理员信息,ID: {Id}", id);
|
||||
logger.LogInformation("正在获取管理员信息,ID: {Id}", id);
|
||||
|
||||
var adminUser = await _adminUserRepository.GetByIdAsync(id);
|
||||
var adminUser = await adminUserRepository.GetByIdAsync(id);
|
||||
if (adminUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到管理员,ID: {Id}", id);
|
||||
logger.LogWarning("未找到管理员,ID: {Id}", id);
|
||||
throw new BusinessException("管理员不存在", 404);
|
||||
}
|
||||
|
||||
@ -178,7 +171,7 @@ public class AdminUserService : IAdminUserService
|
||||
/// </summary>
|
||||
public async Task<PageListModel<AdminUserOutput>> GetListAsync(AdminUserQueryInput input)
|
||||
{
|
||||
_logger.LogInformation("正在查询管理员列表,页码: {PageIndex}, 每页条数: {PageSize}", input.PageIndex, input.PageSize);
|
||||
logger.LogInformation("正在查询管理员列表,页码: {PageIndex}, 每页条数: {PageSize}", input.PageIndex, input.PageSize);
|
||||
|
||||
if (input.PageIndex <= 0)
|
||||
{
|
||||
@ -189,62 +182,13 @@ public class AdminUserService : IAdminUserService
|
||||
{
|
||||
throw new BusinessException("每页条数必须在1-100之间", 400);
|
||||
}
|
||||
|
||||
var pageResult = await _adminUserRepository.GetPageListAsync(
|
||||
BuildQueryExpression(input),
|
||||
input
|
||||
);
|
||||
|
||||
// 转换为输出DTO
|
||||
var outputList = pageResult.List?.Select(MapToOutput).ToList() ?? new List<AdminUserOutput>();
|
||||
|
||||
return new PageListModel<AdminUserOutput>
|
||||
{
|
||||
List = outputList,
|
||||
TotalCount = pageResult.TotalCount,
|
||||
PageIndex = pageResult.PageIndex,
|
||||
PageSize = pageResult.PageSize
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建查询表达式
|
||||
/// </summary>
|
||||
private static Expression<Func<AdminUser, bool>> BuildQueryExpression(AdminUserQueryInput input)
|
||||
{
|
||||
Expression<Func<AdminUser, bool>> where = x => !x.IsDeleted;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.UserName))
|
||||
{
|
||||
var userName = input.UserName;
|
||||
Expression<Func<AdminUser, bool>> userNameCondition = x => x.UserName.Contains(userName);
|
||||
where = Expression.Lambda<Func<AdminUser, bool>>(
|
||||
Expression.AndAlso(where.Body,
|
||||
Expression.Invoke(userNameCondition, where.Parameters[0])),
|
||||
where.Parameters);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.Type))
|
||||
{
|
||||
var type = input.Type;
|
||||
Expression<Func<AdminUser, bool>> typeCondition = x => x.Type == type;
|
||||
where = Expression.Lambda<Func<AdminUser, bool>>(
|
||||
Expression.AndAlso(where.Body,
|
||||
Expression.Invoke(typeCondition, where.Parameters[0])),
|
||||
where.Parameters);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.Status))
|
||||
{
|
||||
var status = input.Status;
|
||||
Expression<Func<AdminUser, bool>> statusCondition = x => x.Status == status;
|
||||
where = Expression.Lambda<Func<AdminUser, bool>>(
|
||||
Expression.AndAlso(where.Body,
|
||||
Expression.Invoke(statusCondition, where.Parameters[0])),
|
||||
where.Parameters);
|
||||
}
|
||||
|
||||
return where;
|
||||
RefAsync<int> totalNumber = 0;
|
||||
var pageResult = await adminUserRepository.Queryable()
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.UserName), a => a.UserName == input.UserName)
|
||||
.OrderByDescending(a => a.CreatedAt)
|
||||
.Select(a => MapToOutput(a), true)
|
||||
.ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);
|
||||
return new PageListModel<AdminUserOutput>(pageResult, input.PageIndex, input.PageSize, totalNumber);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -1,201 +0,0 @@
|
||||
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.Repository;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Service;
|
||||
|
||||
/// <summary>
|
||||
/// 基础服务实现
|
||||
/// </summary>
|
||||
/// <typeparam name="T">实体类型</typeparam>
|
||||
public class BaseService<T> : IBaseService<T> where T : class, new()
|
||||
{
|
||||
protected readonly IBaseRepository<T> _repository;
|
||||
protected readonly ILogger<BaseService<T>> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="repository">基础仓储</param>
|
||||
/// <param name="logger">日志记录器</param>
|
||||
public BaseService(IBaseRepository<T> repository, ILogger<BaseService<T>> logger)
|
||||
{
|
||||
_repository = repository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID获取实体
|
||||
/// </summary>
|
||||
/// <param name="id">实体ID</param>
|
||||
/// <returns>实体对象</returns>
|
||||
public async Task<T?> GetByIdAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在获取实体,ID: {Id}", id);
|
||||
|
||||
var entity = await _repository.GetByIdAsync(id);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
_logger.LogWarning("未找到实体,ID: {Id}", id);
|
||||
throw new BusinessException($"未找到ID为{id}的记录", 404);
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有实体列表
|
||||
/// </summary>
|
||||
/// <returns>实体列表</returns>
|
||||
public async Task<List<T>> GetListAsync()
|
||||
{
|
||||
_logger.LogInformation("正在获取所有实体列表");
|
||||
return await _repository.GetListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取分页列表
|
||||
/// </summary>
|
||||
/// <param name="pageQuery">分页查询参数</param>
|
||||
/// <returns>分页数据</returns>
|
||||
public async Task<PageListModel<T>> GetPageListAsync(PageQueryModel pageQuery)
|
||||
{
|
||||
_logger.LogInformation("正在获取分页列表,页码: {PageIndex}, 每页条数: {PageSize}", pageQuery.PageIndex, pageQuery.PageSize);
|
||||
|
||||
if (pageQuery.PageIndex <= 0)
|
||||
{
|
||||
throw new BusinessException("页码必须大于0", 400);
|
||||
}
|
||||
|
||||
if (pageQuery.PageSize <= 0 || pageQuery.PageSize > 100)
|
||||
{
|
||||
throw new BusinessException("每页条数必须在1-100之间", 400);
|
||||
}
|
||||
|
||||
return await _repository.GetPageListAsync(x => true, pageQuery);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增实体
|
||||
/// </summary>
|
||||
/// <param name="entity">实体对象</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public async Task<bool> InsertAsync(T entity)
|
||||
{
|
||||
if (entity == null)
|
||||
{
|
||||
throw new BusinessException("实体对象不能为空", 400);
|
||||
}
|
||||
|
||||
_logger.LogInformation("正在新增实体,类型: {EntityType}", typeof(T).Name);
|
||||
|
||||
SetAuditFieldsOnInsert(entity);
|
||||
|
||||
var result = await _repository.InsertAsync(entity);
|
||||
|
||||
if (result)
|
||||
{
|
||||
_logger.LogInformation("实体新增成功");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("实体新增失败");
|
||||
throw new BusinessException("新增记录失败", 500);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新实体
|
||||
/// </summary>
|
||||
/// <param name="entity">实体对象</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public async Task<bool> UpdateAsync(T entity)
|
||||
{
|
||||
if (entity == null)
|
||||
{
|
||||
throw new BusinessException("实体对象不能为空", 400);
|
||||
}
|
||||
|
||||
_logger.LogInformation("正在更新实体,类型: {EntityType}", typeof(T).Name);
|
||||
|
||||
SetAuditFieldsOnUpdate(entity);
|
||||
|
||||
var result = await _repository.UpdateAsync(entity);
|
||||
|
||||
if (result)
|
||||
{
|
||||
_logger.LogInformation("实体更新成功");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("实体更新失败");
|
||||
throw new BusinessException("更新记录失败", 500);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID删除实体
|
||||
/// </summary>
|
||||
/// <param name="id">实体ID</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public async Task<bool> DeleteByIdAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在删除实体,ID: {Id}", id);
|
||||
|
||||
var entity = await _repository.GetByIdAsync(id);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
_logger.LogWarning("未找到要删除的实体,ID: {Id}", id);
|
||||
throw new BusinessException($"未找到ID为{id}的记录", 404);
|
||||
}
|
||||
|
||||
var result = await _repository.DeleteByIdAsync(id);
|
||||
|
||||
if (result)
|
||||
{
|
||||
_logger.LogInformation("实体删除成功,ID: {Id}", id);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("实体删除失败,ID: {Id}", id);
|
||||
throw new BusinessException("删除记录失败", 500);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置插入时的审计字段
|
||||
/// </summary>
|
||||
/// <param name="entity">实体对象</param>
|
||||
private static void SetAuditFieldsOnInsert(T entity)
|
||||
{
|
||||
if (entity is BaseEntity baseEntity)
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
baseEntity.CreatedAt = now;
|
||||
baseEntity.UpdatedAt = now;
|
||||
baseEntity.CreatedBy = baseEntity.CreatedBy ?? "system";
|
||||
baseEntity.UpdatedBy = baseEntity.UpdatedBy ?? "system";
|
||||
baseEntity.IsDeleted = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetAuditFieldsOnUpdate(T entity)
|
||||
{
|
||||
if (entity is BaseEntity baseEntity)
|
||||
{
|
||||
baseEntity.UpdatedAt = DateTime.Now;
|
||||
baseEntity.UpdatedBy = baseEntity.UpdatedBy ?? "system";
|
||||
}
|
||||
}
|
||||
}
|
||||
191
QYZH.InteractiveMagazine.Service/WxUserService.cs
Normal file
191
QYZH.InteractiveMagazine.Service/WxUserService.cs
Normal file
@ -0,0 +1,191 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using QYZH.InteractiveMagazine.IService;
|
||||
using QYZH.InteractiveMagazine.IService.Dto;
|
||||
using QYZH.InteractiveMagazine.Models.Common;
|
||||
using QYZH.InteractiveMagazine.Models.Dto;
|
||||
using QYZH.InteractiveMagazine.Models.Entity;
|
||||
using QYZH.InteractiveMagazine.Repository;
|
||||
using SqlSugar;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace QYZH.InteractiveMagazine.Service;
|
||||
|
||||
public class WxUserService(BaseRepository<WxUser> wxUserRepository, ILogger<WxUserService> _logger) : BaseRepository<WxUser>, IWxUserService
|
||||
{
|
||||
|
||||
public async Task<WxUserOutput> CreateAsync(WxUserInput input)
|
||||
{
|
||||
_logger.LogInformation("正在创建微信用户,OpenId: {OpenId}", input.OpenId);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.OpenId))
|
||||
{
|
||||
throw new BusinessException("OpenId不能为空", 400);
|
||||
}
|
||||
|
||||
var existingUser = await wxUserRepository.GetFirstAsync(a => a.OpenId == input.OpenId);
|
||||
if (existingUser != null)
|
||||
{
|
||||
_logger.LogWarning("创建微信用户失败,OpenId已存在: {OpenId}", input.OpenId);
|
||||
throw new BusinessException("OpenId已存在", 400);
|
||||
}
|
||||
|
||||
var wxUser = new WxUser
|
||||
{
|
||||
|
||||
OpenId = input.OpenId.Trim(),
|
||||
UnionId = input.UnionId,
|
||||
NickName = input.NickName,
|
||||
AvatarUrl = input.AvatarUrl,
|
||||
Phone = input.Phone,
|
||||
Points = input.Points,
|
||||
Type = input.Type,
|
||||
Status = input.Status,
|
||||
Pwd = input.Pwd ?? string.Empty,
|
||||
GrowthPoints = input.GrowthPoints,
|
||||
CreatedBy = "System",
|
||||
UpdatedBy = "System",
|
||||
CreatedAt = DateTime.Now,
|
||||
UpdatedAt = DateTime.Now,
|
||||
IsDeleted = false
|
||||
};
|
||||
|
||||
var result = await wxUserRepository.InsertAsync(wxUser);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("微信用户创建失败,OpenId: {OpenId}", input.OpenId);
|
||||
throw new BusinessException("创建微信用户失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("微信用户创建成功,OpenId: {OpenId}, ID: {Id}", input.OpenId, wxUser.Id);
|
||||
|
||||
return MapToOutput(wxUser);
|
||||
}
|
||||
|
||||
public async Task<WxUserOutput> UpdateAsync(long id, WxUserInput input)
|
||||
{
|
||||
_logger.LogInformation("正在更新微信用户,ID: {Id}", id);
|
||||
|
||||
var wxUser = await wxUserRepository.GetByIdAsync(id);
|
||||
if (wxUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到要更新的微信用户,ID: {Id}", id);
|
||||
throw new BusinessException("微信用户不存在", 404);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(input.OpenId) && input.OpenId != wxUser.OpenId)
|
||||
{
|
||||
var existingUser = await wxUserRepository.GetFirstAsync(a => a.OpenId == input.OpenId.Trim());
|
||||
if (existingUser != null && existingUser.Id != id)
|
||||
{
|
||||
_logger.LogWarning("更新微信用户失败,OpenId已存在: {OpenId}", input.OpenId);
|
||||
throw new BusinessException("OpenId已存在", 400);
|
||||
}
|
||||
|
||||
wxUser.OpenId = input.OpenId.Trim();
|
||||
}
|
||||
|
||||
wxUser.UnionId = input.UnionId ?? wxUser.UnionId;
|
||||
wxUser.NickName = input.NickName ?? wxUser.NickName;
|
||||
wxUser.AvatarUrl = input.AvatarUrl ?? wxUser.AvatarUrl;
|
||||
wxUser.Phone = input.Phone ?? wxUser.Phone;
|
||||
wxUser.Points = input.Points;
|
||||
wxUser.Type = input.Type ?? wxUser.Type;
|
||||
wxUser.Status = input.Status ?? wxUser.Status;
|
||||
wxUser.Pwd = input.Pwd ?? wxUser.Pwd;
|
||||
wxUser.GrowthPoints = input.GrowthPoints;
|
||||
|
||||
wxUser.UpdatedBy = "System";
|
||||
wxUser.UpdatedAt = DateTime.Now;
|
||||
|
||||
var result = await wxUserRepository.UpdateAsync(wxUser);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("微信用户更新失败,ID: {Id}", id);
|
||||
throw new BusinessException("更新微信用户失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("微信用户更新成功,ID: {Id}", id);
|
||||
|
||||
return MapToOutput(wxUser);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在删除微信用户,ID: {Id}", id);
|
||||
|
||||
var wxUser = await wxUserRepository.GetByIdAsync(id);
|
||||
if (wxUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到要删除的微信用户,ID: {Id}", id);
|
||||
throw new BusinessException("微信用户不存在", 404);
|
||||
}
|
||||
|
||||
var result = await wxUserRepository.DeleteByIdAsync(id);
|
||||
if (!result)
|
||||
{
|
||||
_logger.LogError("微信用户删除失败,ID: {Id}", id);
|
||||
throw new BusinessException("删除微信用户失败", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("微信用户删除成功,ID: {Id}", id);
|
||||
}
|
||||
|
||||
public async Task<WxUserOutput> GetByIdAsync(long id)
|
||||
{
|
||||
_logger.LogInformation("正在获取微信用户信息,ID: {Id}", id);
|
||||
|
||||
var wxUser = await wxUserRepository.GetByIdAsync(id);
|
||||
if (wxUser == null)
|
||||
{
|
||||
_logger.LogWarning("未找到微信用户,ID: {Id}", id);
|
||||
throw new BusinessException("微信用户不存在", 404);
|
||||
}
|
||||
|
||||
return MapToOutput(wxUser);
|
||||
}
|
||||
|
||||
public async Task<PageListModel<WxUserOutput>> GetListAsync(WxUserQueryInput input)
|
||||
{
|
||||
_logger.LogInformation("正在查询微信用户列表,页码: {PageIndex}, 每页条数: {PageSize}", input.PageIndex, input.PageSize);
|
||||
|
||||
if (input.PageIndex <= 0)
|
||||
{
|
||||
throw new BusinessException("页码必须大于0", 400);
|
||||
}
|
||||
|
||||
if (input.PageSize <= 0 || input.PageSize > 100)
|
||||
{
|
||||
throw new BusinessException("每页条数必须在1-100之间", 400);
|
||||
}
|
||||
RefAsync<int> totalNumber = 0;
|
||||
|
||||
var pageResult = await wxUserRepository.Queryable()
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.NickName), a => a.NickName == input.NickName)
|
||||
.OrderByDescending(a => a.CreatedAt)
|
||||
.Select(a => MapToOutput(a), true)
|
||||
.ToPageListAsync(input.PageIndex, input.PageSize, totalNumber);
|
||||
|
||||
return new PageListModel<WxUserOutput>(pageResult, input.PageIndex, input.PageSize, totalNumber);
|
||||
}
|
||||
|
||||
private static WxUserOutput MapToOutput(WxUser wxUser)
|
||||
{
|
||||
return new WxUserOutput
|
||||
{
|
||||
Id = wxUser.Id,
|
||||
OpenId = wxUser.OpenId,
|
||||
UnionId = wxUser.UnionId,
|
||||
NickName = wxUser.NickName,
|
||||
AvatarUrl = wxUser.AvatarUrl,
|
||||
Phone = wxUser.Phone,
|
||||
Points = wxUser.Points,
|
||||
Type = wxUser.Type,
|
||||
Status = wxUser.Status,
|
||||
GrowthPoints = wxUser.GrowthPoints,
|
||||
CreatedBy = wxUser.CreatedBy,
|
||||
CreatedAt = wxUser.CreatedAt,
|
||||
UpdatedBy = wxUser.UpdatedBy,
|
||||
UpdatedAt = wxUser.UpdatedAt
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user