using Connected.Logistics.Documents.Receive; using Connected.Middleware.Annotations; using Connected.Notifications; using Connected.Notifications.Events; using Connected.ServiceModel; using Microsoft.Extensions.Logging; namespace Connected.Logistics.Documents.Listeners; [Middleware(nameof(IReceivePostingDocumentService.PlannedItemUpdated))] internal sealed class PlannedItemListener : EventListener> { public PlannedItemListener(ILogger logger, IReceivePostingDocumentService documents, IReceiveDocumentService receiveDocuments) { Logger = logger; Documents = documents; ReceiveDocuments = receiveDocuments; } private ILogger Logger { get; } private IReceivePostingDocumentService Documents { get; } private IReceiveDocumentService ReceiveDocuments { get; } protected override async Task OnInvoke() { if (await Documents.SelectPlannedItem(Arguments.Id) is not IReceivePlannedItem item) { Logger.LogWarning("The IReceivePlannedItem not found ({id}}.", Arguments.Id); return; } if (await ReceiveDocuments.SelectItem(item.Item) is not IReceiveItem receiveItem) { Logger.LogWarning("The IReceiveItem not found ({id}}.", item.Item); return; } if (await Documents.Select(item.Document) is not IReceivePostingDocument document) { Logger.LogWarning("The IReceivePostingDocument not found ({id}}.", item.Document); return; } await UpdateOpenItems(document); await UpdatePostedQuantity(receiveItem); } private async Task UpdateOpenItems(IReceivePostingDocument document) { var items = await Documents.QueryPlannedItems(new PrimaryKeyArgs { Id = document.Id }); await Documents.Patch(new PatchArgs { Id = document.Id, Properties = new Dictionary { {nameof(IReceivePostingDocument.OpenItemCount), items.Count(f => f.PostedQuantity < f.Quantity) } } }); } private async Task UpdatePostedQuantity(IReceiveItem item) { var items = await Documents.QueryPlannedItems(new PrimaryKeyArgs { Id = item.Id }); await Documents.PatchPlanedItem(new PatchArgs { Id = item.Id, Properties = new Dictionary { {nameof(IReceiveItem.PostedQuantity), items.Sum(f => f.PostedQuantity) } } }); } }