山东雷驰
 
 
 
 

73 lines
3.0 KiB

using AutoMapper;
using Kean.Domain.Material.Commands;
using Kean.Domain.Material.Events;
using Kean.Domain.Material.Repositories;
using System.Threading;
using System.Threading.Tasks;
namespace Kean.Domain.Material.CommandHandlers
{
/// <summary>
/// 修改物料命令处理程序
/// </summary>
public sealed class ModifyMaterialCommandHandler : CommandHandler<ModifyMaterialCommand>
{
private readonly ICommandBus _commandBus; // 命令总线
private readonly IMapper _mapper; // 模型映射
private readonly IMaterialRepository _materialRepository; // 角色仓库
/// <summary>
/// 依赖注入
/// </summary>
public ModifyMaterialCommandHandler(
ICommandBus commandBus,
IMapper mapper,
IMaterialRepository materialRepository)
{
_commandBus = commandBus;
_mapper = mapper;
_materialRepository = materialRepository;
}
/// <summary>
/// 处理程序
/// </summary>
public override async Task Handle(ModifyMaterialCommand command, CancellationToken cancellationToken)
{
if (command.ValidationResult.IsValid)
{
if (!await _materialRepository.IsMaterialExist(command.Id))
{
await _commandBus.Notify(nameof(command.Id), "物料不存在", command.Id, nameof(ErrorCode.Gone),
cancellationToken: cancellationToken);
return;
}
if (command.Category.HasValue && !await _materialRepository.IsCategoryExist(command.Category.Value))
{
await _commandBus.Notify(nameof(command.Category), "品类不存在", command.Category, nameof(ErrorCode.Gone),
cancellationToken: cancellationToken);
return;
}
if (await _materialRepository.IsMaterialCodeExist(command.Code, command.Id))
{
await _commandBus.Notify(nameof(command.Code), "料号重复", command.Code, nameof(ErrorCode.Conflict),
cancellationToken: cancellationToken);
return;
}
//if (await _materialRepository.IsMaterialNameExist(command.Name, command.Id))
//{
// await _commandBus.Notify(nameof(command.Name), "名称重复", command.Name, nameof(ErrorCode.Conflict),
// cancellationToken: cancellationToken);
// return;
//}
await _materialRepository.ModifyMaterial(_mapper.Map<Models.Material>(command));
await _commandBus.Trigger(_mapper.Map<ModifyMaterialSuccessEvent>(command), cancellationToken);
}
else
{
await _commandBus.Notify(command.ValidationResult,
cancellationToken: cancellationToken);
}
}
}
}