Files
Khaemhat/src/Khaemhat.Application/Inventory/InventoryPoster.cs
T
Alby96andClaude Opus 5.5 eb301fa570 feat: stock take, reorder proposal and warehouse rebuild (#60)
A physical stock take freezes the book quantity and cost of a warehouse at a
date, takes counts typed or read from a scanner file, and posts the gains and
losses as INVP/INVN movements at that date. The reorder proposal lists the
items whose available and ordered quantity no longer covers the reorder point
and turns the accepted lines into draft supplier orders, one per supplier.
The warehouse can be rebuilt from its documents on demand and every Sunday
night, as a safety net after imports or corrections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:35:34 +01:00

554 lines
28 KiB
C#

using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>
/// Posts the documents to the warehouse (SPEC §11.6, ADR 0035) inside the transaction of the document engine: a
/// confirmed document that moves the stock writes one movement per stocked line; a cancelled one loses it. After every
/// change the history of the items touched runs again through the weighted average and gives the balances of each
/// warehouse, the committed and ordered quantities of the open orders and the costs on the item card.
/// </summary>
public static class InventoryPoster
{
/// <summary>A transfer needs a destination different from the origin.</summary>
public const string TransferDestination = "document.transfer.destination";
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family of the document.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var items = new HashSet<long>();
await RemoveAsync(uow, family, documentId, items, cancellationToken).ConfigureAwait(false);
var header = await HeaderAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is null)
{
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
return;
}
var lines = await LinesAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
foreach (var line in lines.Where(l => l.ItemId is not null))
{
// Orders hold committed and ordered quantities; every state change of theirs moves the balances.
items.Add(line.ItemId!.Value);
}
if (DocumentStateMachine.IsInForce(header.Status) && StockEffectMatrix.MovesStock(header.Kind))
{
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
}
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): removes every movement, posts
/// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of
/// the same day, then runs the history of every item.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false);
var documents = new List<(DocumentFamily Family, DocumentHeader Header)>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
{
foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false))
{
if (StockEffectMatrix.MovesStock(header.Kind))
{
documents.Add((family, header));
}
}
}
// Delivery notes and receipts first: their invoices then find the goods already moved.
var ordered = documents
.OrderBy(d => d.Header.DocumentDate)
.ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1)
.ThenBy(d => d.Header.ConfirmedAt)
.ThenBy(d => d.Header.Id)
.ToList();
var items = new HashSet<long>();
for (var i = 0; i < ordered.Count; i++)
{
var (family, header) = ordered[i];
var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count));
}
// Every stocked item, also those with only orders or with no movement left.
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId);
var ids = items.Concat(all).Concat(balanced).Distinct().ToList();
for (var i = 0; i < ids.Count; i += 50)
{
await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count));
}
return (ordered.Count, ids.Count);
}
/// <summary>
/// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and
/// ordered quantities, the average and last cost on the item card.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="itemIds">The items.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable<long> itemIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
ArgumentNullException.ThrowIfNull(itemIds);
var ids = itemIds.Distinct().ToList();
if (ids.Count == 0)
{
return;
}
var committed = await OpenQuantitiesAsync<SaleOrder, SaleOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var ordered = await OpenQuantitiesAsync<PurchaseOrder, PurchaseOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var defaultWarehouse = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
foreach (var itemId in ids)
{
await RecomputeItemAsync(uow, itemId, committed, ordered, defaultWarehouse, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The default warehouse of the company: the one marked as such, or the first.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The warehouse, if any.</returns>
public static async Task<long?> DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var warehouses = uow.Repository<Warehouse, long>();
var marked = await warehouses.FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
return marked?.Id ?? (await warehouses.FindAsync(Query.For<Warehouse>().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
}
/// <summary>The quantity of a line in the base unit of its item.</summary>
/// <param name="quantity">The quantity on the line.</param>
/// <param name="lineUnit">The unit of the line.</param>
/// <param name="item">The item.</param>
/// <param name="units">The alternative units of the item.</param>
/// <returns>The quantity in the base unit.</returns>
public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable<ItemUnit> units)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(units);
if (lineUnit is null || lineUnit == item.UnitOfMeasureId)
{
return quantity;
}
var unit = units.FirstOrDefault(u => u.ItemId == item.Id && u.UnitOfMeasureId == lineUnit);
return unit is null || unit.Factor <= 0m ? quantity : quantity * unit.Factor;
}
private static async Task RemoveAsync(IUnitOfWork uow, DocumentFamily family, long documentId, HashSet<long> items, CancellationToken cancellationToken)
{
var entries = uow.Repository<InventoryEntry, long>();
var lines = uow.Repository<InventoryEntryLine, long>();
foreach (var entry in (await entries.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
.ConfigureAwait(false)).Items)
{
foreach (var line in (await lines.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
items.Add(line.ItemId);
await lines.DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
}
await entries.DeleteAsync(entry.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task PostAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, IReadOnlyList<DocumentLine> lines, HashSet<long> items, CancellationToken cancellationToken)
{
if (header.InventoryReasonId is not { } reasonId
|| await uow.Repository<InventoryReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) is not { } reason)
{
return;
}
// A line that comes from a document that already moved its goods the same way (the invoice of a delivery note)
// does not move them again; a credit note of an invoice moves them back.
var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 };
var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false);
IReadOnlyList<StockMovement> movements;
try
{
movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines);
}
catch (InvalidOperationException)
{
throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]);
}
if (movements.Count == 0)
{
return;
}
var entry = new InventoryEntry
{
EntryDate = header.DocumentDate,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
SourceNumber = header.DocumentNumber,
InventoryReasonId = reason.Id,
PartyId = header.PartyId,
IsDemo = header.IsDemo,
};
await uow.Repository<InventoryEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<InventoryEntryLine, long>();
var order = 0;
foreach (var m in movements)
{
items.Add(m.ItemId);
await repository.InsertAsync(
new InventoryEntryLine
{
EntryId = entry.Id,
EntryDate = entry.EntryDate,
ItemId = m.ItemId,
WarehouseId = m.WarehouseId,
Quantity = m.Quantity,
Valued = m.Valued,
UnitCost = m.UnitCost,
Value = StockCostCalculator.Value(m.Quantity, m.UnitCost),
SourceLineId = m.SourceLineId,
SortOrder = ++order,
},
cancellationToken).ConfigureAwait(false);
}
}
// The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a
// document that already moved the stock (the invoice of a delivery note) are left out.
private static async Task<List<StockLineInput>> StockLinesAsync(
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
{
var result = new List<StockLineInput>();
var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList();
if (itemIds.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var ids = catalog.Keys.ToList();
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
var moved = new Dictionary<(DocumentFamily, long), Dictionary<long, int>>();
foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m))
{
if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods)
{
continue;
}
if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId
&& await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign)
{
continue;
}
var warehouse = line.WarehouseId ?? header.WarehouseId ?? item.WarehouseId ?? fallback;
if (warehouse is null)
{
continue;
}
var quantity = ToBase(Math.Abs(line.Quantity), line.UnitOfMeasureId, item, units);
result.Add(new StockLineInput(line.Id, item.Id, quantity, warehouse.Value, UnitCost(header, line, quantity)));
}
return result;
}
// The cost per base unit in euro of a line: its taxable amount over the quantity, at the exchange rate of the document.
private static decimal? UnitCost(DocumentHeader header, DocumentLine line, decimal baseQuantity)
{
if (baseQuantity == 0m || line.TaxableAmount == 0m)
{
return null;
}
var amount = Math.Abs(line.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
amount /= header.ExchangeRate;
}
return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
// How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all.
private static async Task<int> MovedSignAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> moved, CancellationToken cancellationToken)
{
var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
return 0;
}
var key = (sourceFamily, source.DocumentId);
if (!moved.TryGetValue(key, out var lines))
{
lines = [];
var entries = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == sourceFamily && e.SourceDocumentId == source.DocumentId), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entry in entries)
{
foreach (var line in (await uow.Repository<InventoryEntryLine, long>()
.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
if (line.SourceLineId is { } id)
{
lines[id] = Math.Sign(line.Quantity);
}
}
}
moved[key] = lines;
}
return lines.GetValueOrDefault(sourceLineId);
}
private static async Task RecomputeItemAsync(
IUnitOfWork uow, long itemId, IReadOnlyDictionary<(long, long?), decimal> committed, IReadOnlyDictionary<(long, long?), decimal> ordered, long? defaultWarehouse,
CancellationToken cancellationToken)
{
if (await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
{
return;
}
var repository = uow.Repository<InventoryEntryLine, long>();
var lines = (await repository.ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var invoiced = await InvoicedCostsAsync(uow, lines, cancellationToken).ConfigureAwait(false);
var history = StockCostCalculator.Run(
lines.Select(l => new CostedMovement(
l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued || invoiced.ContainsKey(l.Id), invoiced.TryGetValue(l.Id, out var cost) ? cost : l.UnitCost)),
item.StandardCost ?? 0m);
foreach (var line in lines)
{
var unitCost = history.UnitCosts[line.Id];
var value = StockCostCalculator.Value(line.Quantity, unitCost);
if (line.UnitCost != unitCost || line.Value != value)
{
line.UnitCost = unitCost;
line.Value = value;
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM item_balances WHERE item_id = {itemId}"), cancellationToken).ConfigureAwait(false);
var warehouses = history.Warehouses.Keys
.Concat(committed.Keys.Concat(ordered.Keys).Where(k => k.Item1 == itemId).Select(k => k.Item2 ?? item.WarehouseId ?? defaultWarehouse).OfType<long>())
.Distinct();
var balances = uow.Repository<ItemBalance, long>();
foreach (var warehouseId in warehouses)
{
var stock = history.Warehouses.GetValueOrDefault(warehouseId) ?? new WarehouseStock(0m, null, null);
await balances.InsertAsync(
new ItemBalance
{
ItemId = itemId,
WarehouseId = warehouseId,
OnHand = stock.OnHand,
Committed = Open(committed, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
Ordered = Open(ordered, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
AverageCost = history.AverageCost,
Value = StockCostCalculator.Value(stock.OnHand, history.AverageCost),
LastCost = history.LastCost,
LastLoadDate = stock.LastLoad,
LastUnloadDate = stock.LastUnload,
},
cancellationToken).ConfigureAwait(false);
}
// Only the costs: the card keeps its version, so whoever is editing it does not collide with a posting.
decimal? average = lines.Count == 0 ? item.AverageCost : history.AverageCost;
var last = history.LastCost ?? item.LastCost;
if (average != item.AverageCost || last != item.LastCost)
{
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE items SET average_cost = {average}, last_cost = {last} WHERE id = {itemId}"), cancellationToken).ConfigureAwait(false);
}
}
// The quantity still open of an item in a warehouse; the lines without a warehouse count in the usual one.
private static decimal Open(IReadOnlyDictionary<(long, long?), decimal> open, long itemId, long warehouseId, long? usual)
{
var total = open.GetValueOrDefault((itemId, warehouseId));
if (usual == warehouseId)
{
total += open.GetValueOrDefault((itemId, null));
}
return total;
}
// The cost a supplier invoice gives to the loads of the delivery notes it invoices (the difference of price, §11.5).
private static async Task<Dictionary<long, decimal>> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList<InventoryEntryLine> lines, CancellationToken cancellationToken)
{
var result = new Dictionary<long, decimal>();
var loads = lines.Where(l => l.Quantity > 0m && l.SourceLineId is not null).ToList();
if (loads.Count == 0)
{
return result;
}
var entryIds = loads.Select(l => l.EntryId).Distinct().ToList();
var receipts = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id) && e.SourceKind == DocumentKind.PurchaseDeliveryNote), cancellationToken).ConfigureAwait(false))
.Items.Select(e => e.Id).ToHashSet();
var receiptLines = loads.Where(l => receipts.Contains(l.EntryId)).ToList();
if (receiptLines.Count == 0)
{
return result;
}
var sourceIds = receiptLines.Select(l => l.SourceLineId!.Value).Distinct().ToList();
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(k => k.SourceFamily == DocumentFamily.PurchaseDocument && k.TargetFamily == DocumentFamily.PurchaseDocument && sourceIds.Contains(k.SourceLineId)),
cancellationToken).ConfigureAwait(false)).Items;
foreach (var load in receiptLines)
{
decimal amount = 0m, quantity = 0m;
foreach (var link in links.Where(k => k.SourceLineId == load.SourceLineId))
{
var target = await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, link.TargetLineId, cancellationToken).ConfigureAwait(false);
var header = target is null ? null : await HeaderAsync(uow, DocumentFamily.PurchaseDocument, target.DocumentId, cancellationToken).ConfigureAwait(false);
if (target is null || header is null || header.Kind != DocumentKind.PurchaseInvoice || !DocumentStateMachine.IsInForce(header.Status) || target.Quantity == 0m)
{
continue;
}
var lineAmount = Math.Abs(target.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
lineAmount /= header.ExchangeRate;
}
// The invoice line in the unit of the delivery note: its share of the load is the linked quantity.
var share = Math.Abs(link.Quantity / target.Quantity);
amount += lineAmount * share;
quantity += Math.Abs(link.Quantity);
}
var source = quantity == 0m ? null : await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, load.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
if (source is null || source.Quantity == 0m)
{
continue;
}
// The load is in the base unit; the invoiced part of the delivery line is quantity / source.Quantity of it.
var baseQuantity = load.Quantity * (quantity / Math.Abs(source.Quantity));
if (baseQuantity > 0m && amount > 0m)
{
result[load.Id] = Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
}
return result;
}
// The quantities still to deliver of the open orders of a family, by item and warehouse of the line.
private static async Task<Dictionary<(long, long?), decimal>> OpenQuantitiesAsync<THeader, TLine>(IUnitOfWork uow, List<long> itemIds, CancellationToken cancellationToken)
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
var result = new Dictionary<(long, long?), decimal>();
var ids = itemIds.Select(i => (long?)i).ToList();
var lines = (await uow.Repository<TLine, long>().ListAsync(
Query.For<TLine>().Where(l => ids.Contains(l.ItemId) && !l.FulfillmentClosed), cancellationToken).ConfigureAwait(false)).Items;
if (lines.Count == 0)
{
return result;
}
var documentIds = lines.Select(l => l.DocumentId).Distinct().ToList();
var open = (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(h => documentIds.Contains(h.Id) && (h.Status == DocumentStatus.Confirmed || h.Status == DocumentStatus.PartiallyFulfilled)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(h => h.Id);
if (open.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => itemIds.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
foreach (var line in lines)
{
if (!open.TryGetValue(line.DocumentId, out var header) || !catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked)
{
continue;
}
var residual = line.Quantity - line.FulfilledQuantity;
if (residual <= 0m)
{
continue;
}
var key = (item.Id, line.WarehouseId ?? header.WarehouseId);
result[key] = result.GetValueOrDefault(key) + ToBase(residual, line.UnitOfMeasureId, item, units);
}
return result;
}
private static Task<DocumentHeader?> HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
private static Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
}
/// <summary>The step of a rebuild.</summary>
public enum RebuildPhase
{
/// <summary>Posting the documents.</summary>
Documents = 0,
/// <summary>Computing the items.</summary>
Items = 1,
}
/// <summary>How far a rebuild is.</summary>
/// <param name="Phase">The step.</param>
/// <param name="Done">How many done.</param>
/// <param name="Total">How many in all.</param>
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);