using F9WebAiTest.Application.Common.Exceptions;
using F9WebAiTest.Application.Interfaces.SnowflakeID;
using F9WebAiTest.Application.Interfaces.UOW;
using F9WebAiTest.Domain.Entities.SYS.Departments;
using F9WebAiTest.Domain.Interfaces.SYS.Departments;
using F9WebAiTest.Domain.Interfaces.SYS.RBAC.Users;
using MediatR;
namespace F9WebAiTest.Application.CQRS.SYS.RBAC.Users.Commands;
/// 命令定义
public record User_UpdateCommand(long Id, string UserName, string PhoneNumber, string LoginName, long DepartmentId, int SortOrder) : IRequest;
/// 命令处理器
public class User_UpdateCommandHandler(
IUnitOfWork_F9 unitOfWork,
ISnowflakeIdGenerator snowflakeIdGenerator,
IUserWriteRepository userWriteRepository,
IDepartmentUserRepository departmentUserRepository) : IRequestHandler
{
public async Task Handle(User_UpdateCommand command, CancellationToken cancellationToken)
{
if (command.Id <= 0) throw new F9OperationException("用户ID不能为空");
if (string.IsNullOrWhiteSpace(command.UserName)) throw new F9OperationException("用户名不能为空");
if (command.DepartmentId <= 0) throw new F9OperationException("部门不能为空");
return await unitOfWork.ExecuteWithUow(async () =>
{
// 获取数据库用户
var dbUser = await userWriteRepository.GetByIdAsync(command.Id);
if (dbUser == null) throw new F9NotFoundException("用户", command.Id);
// 移除原部门关系
await departmentUserRepository.RemoveAsync(dbUser.DepartmentId, dbUser.Id);
// 领域更新
dbUser.Update(command.UserName, command.PhoneNumber, command.LoginName, command.DepartmentId, command.SortOrder);
// 持久化
var result = await userWriteRepository.UpdateAsync(dbUser);
// 添加新部门关系
await departmentUserRepository.AssignAsync(new DepartmentUser(
snowflakeIdGenerator.CreateId(), dbUser.DepartmentId, dbUser.Id));
return result;
});
}
}