using Kean.Domain.Stock.Commands; using Kean.Domain.Stock.Models; using Kean.Domain.Stock.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Kean.Domain.Stock.CommandHandlers { /// /// 盘点命令处理程序 /// public sealed class InventoryCommandHandler : CommandHandler { private readonly ICommandBus _commandBus; // 命令总线 private readonly INotification _notifications; // 总线通知 private readonly IStockRepository _stockRepository; // 存储仓库 /// /// 依赖注入 /// public InventoryCommandHandler( ICommandBus commandBus, INotification notifications, IStockRepository stockRepository) { _commandBus = commandBus; _notifications = notifications; _stockRepository = stockRepository; } /// /// 处理程序 /// public override async Task Handle(InventoryCommand command, CancellationToken cancellationToken) { if (command.ValidationResult.IsValid) { // 时间戳 command.Timestamp ??= DateTime.Now; // 标签 var innerTag = string.IsNullOrWhiteSpace(command.Tag) ? InventoryCommand.Feature : $"{InventoryCommand.Feature},{command.Tag}"; // 拆分盈亏 var profit = new List(); var loss = new List(); foreach (var item in await _stockRepository.TakeStock(command.Lines)) { if (item.Quantity > 0) { loss.Add(item); } else if (item.Quantity < 0) { profit.Add(item); } } if (profit.Count > 0) { // 盘盈出库 await _commandBus.Execute(new OutboundCommand { Barcode = command.Barcode, Lines = profit, Operator = command.Operator, Tag = innerTag, Timestamp = command.Timestamp }, cancellationToken); } if (!_notifications.Any() && loss.Count > 0) { // 盘亏入库 await _commandBus.Execute(new InboundCommand { Barcode = command.Barcode, Lines = loss, Operator = command.Operator, Tag = innerTag, Timestamp = command.Timestamp }, cancellationToken); } } else { await _commandBus.Notify(command.ValidationResult, cancellationToken: cancellationToken); } } } }