using F9WebAiTest.Application.Common.Exceptions;
using F9WebAiTest.Application.Interfaces.SnowflakeID;
using F9WebAiTest.Domain.Entities.SYS.Departments;
using F9WebAiTest.Domain.Enums.SYS.Departments;
using F9WebAiTest.Domain.Interfaces.SYS.Departments;
using MediatR;
namespace F9WebAiTest.Application.CQRS.SYS.Departments.Commands;
/// 命令定义
public record Department_CreateCommand(string Code, string Name, long ParentId, Department_ManageType_Enum ManageType, Department_DutyType_Enum DutyType, int SortOrder, string Description) : IRequest;
/// 命令处理器
public class CreateDepartmentCommandHandler(
IDepartmentWriteRepository departmentRepository,
ISnowflakeIdGenerator snowflakeIdGenerator,
IPublisher eventBus) : IRequestHandler
{
public async Task Handle(Department_CreateCommand command, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(command.Code)) throw new F9OperationException("部门编码不能为空");
if (string.IsNullOrWhiteSpace(command.Name)) throw new F9OperationException("部门名称不能为空");
var dep = new Department(snowflakeIdGenerator.CreateId(), command.Code, command.Name, command.ParentId,
command.ManageType, command.DutyType, command.SortOrder, command.Description);
var result = await departmentRepository.AddAsync(dep);
if (result == false) throw new F9OperationException("部门", "新增");
foreach (var de in dep.DomainEvents) await eventBus.Publish(de, cancellationToken);
dep.ClearDomainEvents();
return dep.Id;
}
}