feat: post documents to the warehouse at weighted average cost (#59)

Confirmed delivery notes, invoices that move goods, supplier receipts and
warehouse movements now write stock movements in the same transaction;
cancelling removes them. Each change re-runs the history of the items
touched, so balances per warehouse, committed and ordered quantities and
the average and last cost stay consistent even when an old document is
cancelled. Supplier invoices give their cost to the receipts they invoice.
Immediate invoices, supplier invoices and credit notes get their warehouse
reasons; the self-invoice types TD20-TD29 join the base tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 21:13:27 +01:00
1 parent 20b2421eea
commit eeabb12f96
14 files changed
+1753 -5

No files matched your search

@@ -1,4 +1,5 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
@@ -257,6 +258,7 @@ public sealed partial class DocumentEngine
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
{
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -335,6 +337,7 @@ public sealed partial class DocumentEngine
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
}
@@ -679,6 +682,8 @@ public sealed partial class DocumentEngine
await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false);
}
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
}
@@ -0,0 +1,465 @@
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>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>
/// 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;
}
var stockLines = await StockLinesAsync(uow, header, lines, cancellationToken).ConfigureAwait(false);
var movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines);
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, 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), HashSet<long>>();
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 (line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId
&& await AlreadyMovedAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false))
{
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);
}
private static async Task<bool> AlreadyMovedAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), HashSet<long>> moved, CancellationToken cancellationToken)
{
var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
return false;
}
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.Add(id);
}
}
}
moved[key] = lines;
}
return lines.Contains(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);
}
@@ -0,0 +1,391 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>What the stock screen asks (mockup 036).</summary>
public sealed record StockFilter
{
/// <summary>Code, description or brand.</summary>
public string? Search { get; init; }
/// <summary>One warehouse, or all together.</summary>
public long? WarehouseId { get; init; }
/// <summary>One category.</summary>
public long? CategoryId { get; init; }
/// <summary>Only the items under their minimum stock or reorder point.</summary>
public bool UnderstockOnly { get; init; }
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
public bool IncludeEmpty { get; init; }
}
/// <summary>The state of an item under its thresholds.</summary>
public enum StockLevel
{
/// <summary>Enough.</summary>
Ok = 0,
/// <summary>The available quantity reached the reorder point.</summary>
Reorder = 1,
/// <summary>The available quantity is under the minimum stock.</summary>
Understock = 2,
/// <summary>Nothing left, or less than nothing.</summary>
Out = 3,
}
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="CategoryId">Its category.</param>
/// <param name="UnitOfMeasureId">Its base unit.</param>
/// <param name="OnHand">On hand.</param>
/// <param name="Committed">Committed to customers.</param>
/// <param name="Ordered">Ordered from suppliers.</param>
/// <param name="Available">On hand less committed.</param>
/// <param name="MinimumStock">The minimum stock.</param>
/// <param name="ReorderPoint">The reorder point.</param>
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
/// <param name="Value">The value at the average (none without the permission).</param>
/// <param name="LastLoad">The last load.</param>
/// <param name="LastUnload">The last unload.</param>
/// <param name="Level">The state under the thresholds.</param>
public sealed record StockRow(
long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available,
decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level);
/// <summary>A movement of an item, with the balance after it.</summary>
/// <param name="Id">The movement.</param>
/// <param name="Date">The date.</param>
/// <param name="Family">The family of the document.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">Its kind.</param>
/// <param name="Number">Its number.</param>
/// <param name="ReasonCode">The warehouse reason.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="WarehouseId">The warehouse.</param>
/// <param name="Quantity">Positive loads, negative unloads.</param>
/// <param name="UnitCost">The cost (none without the permission).</param>
/// <param name="Value">The value (none without the permission).</param>
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
public sealed record MovementRow(
long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId,
decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance);
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="Quantity">On hand at the date.</param>
/// <param name="UnitCost">The cost of the method.</param>
/// <param name="Value">Quantity times cost.</param>
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
/// <summary>
/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item,
/// the value at a date. The balances are kept by <see cref="InventoryPoster"/>; this service only reads them.
/// </summary>
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
public sealed class InventoryService
{
/// <summary>Permission to read the stock.</summary>
public const string StockPermission = "inventory.stock.read";
/// <summary>Permission to read the movements.</summary>
public const string EntryReadPermission = "inventory.entry.read";
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
public const string PostPermission = "inventory.entry.post";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The stock of the items, in a warehouse or in all.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">What to show.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, by code.</returns>
public async Task<IReadOnlyList<StockRow>> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
if (filter.CategoryId is { } category)
{
query = query.Where(i => i.CategoryId == category);
}
if (filter.Search?.Trim() is { Length: > 0 } text)
{
query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text)));
}
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
var rows = new List<StockRow>();
foreach (var item in items)
{
var mine = balances.GetValueOrDefault(item.Id) ?? [];
var row = RowOf(item, mine, costs);
if (!filter.IncludeEmpty && mine.Count == 0)
{
// No movement and no order: shown only when asked, or when it has a minimum to keep.
if (row.Level == StockLevel.Ok)
{
continue;
}
}
if (filter.UnderstockOnly && row.Level == StockLevel.Ok)
{
continue;
}
rows.Add(row);
}
return rows;
}
/// <summary>The balances of an item in each warehouse.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The balances, costs hidden without the permission.</returns>
public async Task<IReadOnlyList<ItemBalance>> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items;
if (!costs)
{
foreach (var row in rows)
{
row.AverageCost = 0m;
row.Value = 0m;
row.LastCost = null;
}
}
return rows;
}
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="from">The first day, or the beginning.</param>
/// <param name="to">The last day, or today.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
public async Task<IReadOnlyList<MovementRow>> MovementsAsync(
Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId);
if (warehouseId is { } warehouse)
{
query = query.Where(l => l.WarehouseId == warehouse);
}
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
var entries = entryIds.Count == 0 ? [] : (await uow.Repository<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code);
var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
var result = new List<MovementRow>();
var balance = 0m;
foreach (var line in lines)
{
balance += line.Quantity;
if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last))
{
continue;
}
var entry = entries.GetValueOrDefault(line.EntryId);
result.Add(new MovementRow(
line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber,
entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null,
entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance));
}
return result;
}
/// <summary>
/// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day,
/// valued with a method, with its ABC class by value.
/// </summary>
/// <param name="actor">Who reads: needs the permission on costs too.</param>
/// <param name="companyCode">The company.</param>
/// <param name="date">The day.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="method">The cost used.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items with something on hand, by value.</returns>
public async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var itemIds = lines.Select(l => l.ItemId).Distinct().ToList();
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
var rows = new List<ValuationRow>();
foreach (var group in lines.GroupBy(l => l.ItemId))
{
if (!items.TryGetValue(group.Key, out var item))
{
continue;
}
// The costs written on the movements are those of the last run: the history up to the day gives the average then.
var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m);
var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand;
if (quantity == 0m)
{
continue;
}
var cost = method switch
{
StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost,
StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost,
_ => history.AverageCost,
};
rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C'));
}
return Classify(rows);
}
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="limit">How many.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<StockRow>> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default)
{
var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false);
return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)];
}
/// <summary>
/// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum,
/// to reorder when what is available and on order no longer covers the reorder point.
/// </summary>
/// <param name="available">On hand less committed.</param>
/// <param name="ordered">Ordered from suppliers.</param>
/// <param name="minimum">The minimum stock.</param>
/// <param name="reorderPoint">The reorder point.</param>
/// <returns>The level.</returns>
public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint)
{
var watched = minimum is not null || reorderPoint is not null;
if (available < 0m || (watched && available <= 0m))
{
return StockLevel.Out;
}
if (minimum is { } min && available < min)
{
return StockLevel.Understock;
}
return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok;
}
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
/// <param name="rows">The rows.</param>
/// <returns>The rows by value, with their class.</returns>
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> rows)
{
ArgumentNullException.ThrowIfNull(rows);
var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList();
var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value);
var running = 0m;
var result = new List<ValuationRow>(sorted.Count);
foreach (var row in sorted)
{
// The class of an item is where its value starts: the first item is always A.
var share = total <= 0m ? 1m : running / total;
running += Math.Max(row.Value, 0m);
result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' });
}
return result;
}
internal static StockRow RowOf(Item item, IReadOnlyList<ItemBalance> balances, bool costs)
{
var onHand = balances.Sum(b => b.OnHand);
var committed = balances.Sum(b => b.Committed);
var ordered = balances.Sum(b => b.Ordered);
var available = onHand - committed;
var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m;
return new StockRow(
item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint,
costs ? average : null, costs ? balances.Sum(b => b.Value) : null,
balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate),
LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint));
}
internal static async Task<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
{
var query = Query.For<ItemBalance>();
if (warehouseId is { } warehouse)
{
query = query.Where(b => b.WarehouseId == warehouse);
}
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
}
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
}