using Connected.Middleware.Annotations;
using Connected.Notifications;
using Connected.Notifications.Events;
using Logistics.Documents.Receive;
using Logistics.Stock;
using Logistics.Types.Serials;
using Microsoft.Extensions.Logging;
namespace Logistics.Documents.Listeners;
///
/// Represents the event listener to the Updated event.
///
///
/// This middleware reacts when the item is inserted and updates the .
///
[Middleware(nameof(IReceivePostingDocumentService.ItemInserted))]
internal sealed class PostingItemListener : EventListener>
{
///
/// Creates a new instance of the
///
public PostingItemListener(ILogger logger, IStockService stock, IReceivePostingDocumentService documents, ISerialService serials)
{
Logger = logger;
Stock = stock;
Documents = documents;
Serials = serials;
}
private ILogger Logger { get; }
private IStockService Stock { get; }
private IReceivePostingDocumentService Documents { get; }
private ISerialService Serials { get; }
protected override async Task OnInvoke()
{
/*
* Stage 1 is to prepare all data neede to perform operation
*
* Load posting item
*/
if (await Documents.SelectItem(Arguments.Id) is not IReceivePostingItem item)
{
Logger.LogWarning("The IReceivePostingItem not found ({id}}.", Arguments.Id);
return;
}
/*
* Now load the serial number
*/
if (await Serials.Select(item.Serial) is not ISerial serial)
{
Logger.LogWarning("The ISerial not found ({id}}.", item.Serial);
return;
}
/*
* Now load the serial number
*/
if (await Documents.SelectPlannedItem(new SelectReceivePlannedItemArgs
{
Document = item.Document,
Entity = serial.Entity,
EntityId = serial.EntityId
}) is not ISerial plannedItem)
{
Logger.LogWarning("The IReceivePlannedItem not found ({entity}, {entityId}).", serial.Entity, serial.EntityId);
return;
}
/*
* The idea here is simple:
* update (increase) the stock for the specified item
* and posted quantity and update the statictics for
* the immediate parents.
*/
await Stock.Update(new UpdateStockArgs
{
Location = item.Location,
Quantity = item.Quantity,
Serial = item.Serial
});
/*
* Now update the planned item with posted quantity
*/
await Documents.UpdatePlannedItem(new UpdateReceivePlannedItemArgs
{
Id = plannedItem.Id,
PostedQuantity = item.Quantity
});
}
}