山东雷驰
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

101 lines
3.7 KiB

using AutoMapper;
using Kean.Domain.Stock.Commands;
using Kean.Domain.Stock.Repositories;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Kean.Domain.Stock.CommandHandlers
{
/// <summary>
/// 合并命令处理程序
/// </summary>
public sealed class CombineCommandHandler : CommandHandler<CombineCommand>
{
private readonly ICommandBus _commandBus; // 命令总线
private readonly INotification _notifications; // 总线通知
private readonly IMapper _mapper; // 模型映射
private readonly IStockRepository _stockRepository; // 存储仓库
/// <summary>
/// 依赖注入
/// </summary>
public CombineCommandHandler(
ICommandBus commandBus,
INotification notifications,
IMapper mapper,
IStockRepository stockRepository)
{
_commandBus = commandBus;
_notifications = notifications;
_mapper = mapper;
_stockRepository = stockRepository;
}
/// <summary>
/// 处理程序
/// </summary>
public override async Task Handle(CombineCommand command, CancellationToken cancellationToken)
{
if (command.ValidationResult.IsValid)
{
// 时间戳
command.Timestamp ??= DateTime.Now;
// 标签
var innerTag = string.IsNullOrWhiteSpace(command.Tag) ? CombineCommand.Feature : $"{CombineCommand.Feature},{command.Tag}";
// 分割库存
var stocks = await _stockRepository.SplitStock(command.Lines).ContinueWith(task =>
{
if (task.Exception?.InnerException is RepositoryException ex)
{
task.Exception.Handle(_ => true);
_commandBus.Notify(ex.Member.Key, ex.Message, ex.Member.Value,
cancellationToken: cancellationToken).Wait();
return null;
}
return task.Result;
});
if (stocks != null)
{
foreach (var item in stocks)
{
// 转出
var outbound = _mapper.Map<OutboundCommand>(item);
outbound.Operator = command.Operator;
outbound.Tag = innerTag;
outbound.Timestamp = command.Timestamp;
foreach (var line in outbound.Lines)
{
line.Quantity = -line.Quantity;
}
await _commandBus.Execute(outbound, cancellationToken);
if (_notifications.Any())
{
break;
}
}
if (!_notifications.Any())
{
// 转入
var inbound = _mapper.Map<InboundCommand>(command);
inbound.Tag = innerTag;
inbound.Timestamp = command.Timestamp;
foreach (var line in inbound.Lines)
{
line.Id = 0;
line.Quantity = -line.Quantity;
}
await _commandBus.Execute(inbound, cancellationToken);
}
}
}
else
{
await _commandBus.Notify(command.ValidationResult,
cancellationToken: cancellationToken);
}
}
}
}