using F9WebAiTest.Application.Common.Exceptions;
using F9WebAiTest.Domain.Interfaces.SYS.Departments;
using MediatR;
namespace F9WebAiTest.Application.CQRS.SYS.Departments.Commands;
/// 命令定义
public record Department_ActiveOrDeactivateCommand(long Id, bool Active) : IRequest;
/// 命令处理器
public class ActiveOrDeactivateDepartmentCommandHandler(
IDepartmentWriteRepository departmentWriteRepository,
IPublisher eventBus) : IRequestHandler
{
public async Task Handle(Department_ActiveOrDeactivateCommand command, CancellationToken cancellationToken)
{
var dep = await departmentWriteRepository.GetByIdAsync(command.Id, CancellationToken.None);
if (dep == null) throw new F9NotFoundException("部门", command.Id);
if (command.Active) dep.Activate();
else dep.Deactivate();
var result = await departmentWriteRepository.ActiveOrDeactive(command.Id, dep.IsActive);
if (result == false) throw new F9OperationException("启用/禁用", "操作");
foreach (var de in dep.DomainEvents) await eventBus.Publish(de, cancellationToken);
dep.ClearDomainEvents();
return result;
}
}