diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs
index a13a8c6..4de5c8c 100644
--- a/src/Khaemhat.Application/Documents/DocumentEngine.cs
+++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs
@@ -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);
}
diff --git a/src/Khaemhat.Application/Inventory/InventoryPoster.cs b/src/Khaemhat.Application/Inventory/InventoryPoster.cs
new file mode 100644
index 0000000..e183cba
--- /dev/null
+++ b/src/Khaemhat.Application/Inventory/InventoryPoster.cs
@@ -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;
+
+///
+/// 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.
+///
+public static class InventoryPoster
+{
+ /// Writes again the movements of a document from its current state and refreshes its items.
+ /// The unit of work of the company, in a transaction.
+ /// The family of the document.
+ /// The document.
+ /// Cancellation.
+ /// A task.
+ public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(uow);
+ var items = new HashSet();
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The unit of work of the company, in a transaction.
+ /// The items.
+ /// Cancellation.
+ /// A task.
+ public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable itemIds, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(uow);
+ ArgumentNullException.ThrowIfNull(itemIds);
+ var ids = itemIds.Distinct().ToList();
+ if (ids.Count == 0)
+ {
+ return;
+ }
+
+ var committed = await OpenQuantitiesAsync(uow, ids, cancellationToken).ConfigureAwait(false);
+ var ordered = await OpenQuantitiesAsync(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);
+ }
+ }
+
+ /// The default warehouse of the company: the one marked as such, or the first.
+ /// The unit of work.
+ /// Cancellation.
+ /// The warehouse, if any.
+ public static async Task DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(uow);
+ var warehouses = uow.Repository();
+ var marked = await warehouses.FindAsync(Query.For().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
+ return marked?.Id ?? (await warehouses.FindAsync(Query.For().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
+ }
+
+ /// The quantity of a line in the base unit of its item.
+ /// The quantity on the line.
+ /// The unit of the line.
+ /// The item.
+ /// The alternative units of the item.
+ /// The quantity in the base unit.
+ public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable 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 items, CancellationToken cancellationToken)
+ {
+ var entries = uow.Repository();
+ var lines = uow.Repository();
+ foreach (var entry in (await entries.ListAsync(Query.For().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
+ .ConfigureAwait(false)).Items)
+ {
+ foreach (var line in (await lines.ListAsync(Query.For().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 lines, HashSet items, CancellationToken cancellationToken)
+ {
+ if (header.InventoryReasonId is not { } reasonId
+ || await uow.Repository().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().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
+ var repository = uow.Repository();
+ 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> StockLinesAsync(IUnitOfWork uow, DocumentHeader header, IReadOnlyList lines, CancellationToken cancellationToken)
+ {
+ var result = new List();
+ 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- ().ListAsync(Query.For
- ().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
+ .ToDictionary(i => i.Id);
+ var ids = catalog.Keys.ToList();
+ var units = (await uow.Repository().ListAsync(Query.For().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>();
+ 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 AlreadyMovedAsync(
+ IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), HashSet> 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()
+ .ListAsync(Query.For().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()
+ .ListAsync(Query.For().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
- ().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
+ {
+ return;
+ }
+
+ var repository = uow.Repository();
+ var lines = (await repository.ListAsync(
+ Query.For().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())
+ .Distinct();
+ var balances = uow.Repository();
+ 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> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList lines, CancellationToken cancellationToken)
+ {
+ var result = new Dictionary();
+ 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()
+ .ListAsync(Query.For().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().ListAsync(
+ Query.For().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> OpenQuantitiesAsync(IUnitOfWork uow, List 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().ListAsync(
+ Query.For().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().ListAsync(
+ Query.For().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
- ().ListAsync(Query.For
- ().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
+ .ToDictionary(i => i.Id);
+ var units = (await uow.Repository().ListAsync(Query.For().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 HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
+ Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
+
+ private static Task
> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
+ Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
+
+ private static Task StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
+ Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
+}
diff --git a/src/Khaemhat.Application/Inventory/InventoryService.cs b/src/Khaemhat.Application/Inventory/InventoryService.cs
new file mode 100644
index 0000000..22f7a15
--- /dev/null
+++ b/src/Khaemhat.Application/Inventory/InventoryService.cs
@@ -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;
+
+/// What the stock screen asks (mockup 036).
+public sealed record StockFilter
+{
+ /// Code, description or brand.
+ public string? Search { get; init; }
+
+ /// One warehouse, or all together.
+ public long? WarehouseId { get; init; }
+
+ /// One category.
+ public long? CategoryId { get; init; }
+
+ /// Only the items under their minimum stock or reorder point.
+ public bool UnderstockOnly { get; init; }
+
+ /// Also the items with nothing on hand, committed or ordered.
+ public bool IncludeEmpty { get; init; }
+}
+
+/// The state of an item under its thresholds.
+public enum StockLevel
+{
+ /// Enough.
+ Ok = 0,
+
+ /// The available quantity reached the reorder point.
+ Reorder = 1,
+
+ /// The available quantity is under the minimum stock.
+ Understock = 2,
+
+ /// Nothing left, or less than nothing.
+ Out = 3,
+}
+
+/// A row of the stock screen: an item in one warehouse or in all.
+/// The item.
+/// Its code.
+/// Its description.
+/// Its category.
+/// Its base unit.
+/// On hand.
+/// Committed to customers.
+/// Ordered from suppliers.
+/// On hand less committed.
+/// The minimum stock.
+/// The reorder point.
+/// The weighted average cost (none without the permission on costs).
+/// The value at the average (none without the permission).
+/// The last load.
+/// The last unload.
+/// The state under the thresholds.
+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);
+
+/// A movement of an item, with the balance after it.
+/// The movement.
+/// The date.
+/// The family of the document.
+/// The document.
+/// Its kind.
+/// Its number.
+/// The warehouse reason.
+/// The customer or supplier.
+/// The warehouse.
+/// Positive loads, negative unloads.
+/// The cost (none without the permission).
+/// The value (none without the permission).
+/// The balance after the movement, in the warehouses shown.
+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);
+
+/// The value of an item at a date (closing stock, libro inventari).
+/// The item.
+/// Its code.
+/// Its description.
+/// On hand at the date.
+/// The cost of the method.
+/// Quantity times cost.
+/// A (the first 80% of the value), B (up to 95%) or C.
+public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
+
+///
+/// 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 ; this service only reads them.
+///
+/// Permission inventory.stock.read, movements inventory.entry.read; costs only with items.cost.read.
+public sealed class InventoryService
+{
+ /// Permission to read the stock.
+ public const string StockPermission = "inventory.stock.read";
+
+ /// Permission to read the movements.
+ public const string EntryReadPermission = "inventory.entry.read";
+
+ /// Permission to post movements, stock takes and the rebuild.
+ public const string PostPermission = "inventory.entry.post";
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ _factory = factory;
+ _permissions = permissions;
+ }
+
+ /// The stock of the items, in a warehouse or in all.
+ /// Who reads.
+ /// The company.
+ /// What to show.
+ /// Cancellation.
+ /// The rows, by code.
+ public async Task> 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- ().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
- ().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
+ var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
+ var rows = new List();
+ 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;
+ }
+
+ /// The balances of an item in each warehouse.
+ /// Who reads.
+ /// The company.
+ /// The item.
+ /// Cancellation.
+ /// The balances, costs hidden without the permission.
+ public async Task> 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().ListAsync(Query.For().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;
+ }
+
+ /// The movements of an item in a period, with the running balance (mockup 036, dialog of the item).
+ /// Who reads.
+ /// The company.
+ /// The item.
+ /// One warehouse, or all.
+ /// The first day, or the beginning.
+ /// The last day, or today.
+ /// Cancellation.
+ /// The movements, oldest first; the balance starts from what was on hand before .
+ public async Task> 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().Where(l => l.ItemId == itemId);
+ if (warehouseId is { } warehouse)
+ {
+ query = query.Where(l => l.WarehouseId == warehouse);
+ }
+
+ var lines = (await uow.Repository().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().ListAsync(Query.For().Where(e => entryIds.Contains(e.Id)), cancellationToken)
+ .ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
+ var reasons = (await uow.Repository().ListAsync(Query.For(), 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().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken)
+ .ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
+ var result = new List();
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who reads: needs the permission on costs too.
+ /// The company.
+ /// The day.
+ /// One warehouse, or all.
+ /// The cost used.
+ /// Cancellation.
+ /// The items with something on hand, by value.
+ public async Task> 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().ListAsync(
+ Query.For().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
- ().ListAsync(Query.For
- ().Where(i => itemIds.Contains(i.Id)), cancellationToken)
+ .ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
+ var rows = new List();
+ 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);
+ }
+
+ /// The items under their thresholds, the most urgent first (dashboard widget and reorder).
+ /// Who reads.
+ /// The company.
+ /// How many.
+ /// Cancellation.
+ /// The rows.
+ public async Task> 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)];
+ }
+
+ ///
+ /// 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.
+ ///
+ /// On hand less committed.
+ /// Ordered from suppliers.
+ /// The minimum stock.
+ /// The reorder point.
+ /// The level.
+ 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;
+ }
+
+ /// Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.
+ /// The rows.
+ /// The rows by value, with their class.
+ public static IReadOnlyList Classify(IEnumerable 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(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 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>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
+ {
+ var query = Query.For();
+ if (warehouseId is { } warehouse)
+ {
+ query = query.Where(b => b.WarehouseId == warehouse);
+ }
+
+ return (await uow.Repository().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
+ .GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
+ }
+
+ private async Task CostsAsync(Actor actor, CancellationToken cancellationToken) =>
+ (await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
+}
diff --git a/src/Khaemhat.Core/Documents/Documents.cs b/src/Khaemhat.Core/Documents/Documents.cs
index cf8cbc9..749b7aa 100644
--- a/src/Khaemhat.Core/Documents/Documents.cs
+++ b/src/Khaemhat.Core/Documents/Documents.cs
@@ -73,6 +73,9 @@ public abstract class DocumentHeader : Entity, IDemoMarkable
/// The warehouse.
public long? WarehouseId { get; set; }
+ /// The destination warehouse of a transfer.
+ public long? ToWarehouseId { get; set; }
+
/// The warehouse reason.
public long? InventoryReasonId { get; set; }
@@ -220,9 +223,15 @@ public abstract class DocumentHeader : Entity, IDemoMarkable
/// The ledger entry, once posted (M7).
public long? GlEntryId { get; set; }
- /// The VAT protocol of a supplier invoice.
+ /// The VAT protocol of a supplier invoice: its progressive number in the purchase register of the year.
public long? VatProtocol { get; set; }
+ ///
+ /// The date the VAT of a supplier invoice counts from (competenza IVA): the registration date by default, an
+ /// earlier one when the invoice is received late but deducted in its period.
+ ///
+ public DateOnly? VatDate { get; set; }
+
/// When the document was confirmed or issued.
public DateTime? ConfirmedAt { get; set; }
diff --git a/src/Khaemhat.Core/Inventory/Inventory.cs b/src/Khaemhat.Core/Inventory/Inventory.cs
new file mode 100644
index 0000000..506ea2e
--- /dev/null
+++ b/src/Khaemhat.Core/Inventory/Inventory.cs
@@ -0,0 +1,206 @@
+using Khaemhat.Core.Documents;
+using Khaemhat.Core.Entities;
+
+namespace Khaemhat.Core.Inventory;
+
+///
+/// A posting to the stock (SPEC §11.6, ADR 0035, inventory_entries): the movements one confirmed document wrote.
+/// Cancelling the document removes its entry; the balances are then computed again from the movements left.
+///
+public sealed class InventoryEntry : Entity, IDemoMarkable
+{
+ /// The date of the movements: the date of the document.
+ public DateOnly EntryDate { get; set; }
+
+ /// The family of the document that posted it.
+ public DocumentFamily? SourceFamily { get; set; }
+
+ /// The document that posted it.
+ public long? SourceDocumentId { get; set; }
+
+ /// The kind of that document.
+ public DocumentKind? SourceKind { get; set; }
+
+ /// The number of that document, as printed.
+ public string? SourceNumber { get; set; }
+
+ /// The warehouse reason.
+ public long? InventoryReasonId { get; set; }
+
+ /// The customer or supplier of the document.
+ public long? PartyId { get; set; }
+
+ ///
+ public bool IsDemo { get; set; }
+}
+
+///
+/// A movement of one item in one warehouse (inventory_entry_lines), in the base unit of the item: positive
+/// loads, negative unloads. A transfer writes two lines.
+///
+public sealed class InventoryEntryLine : Entity
+{
+ /// The entry.
+ public long EntryId { get; set; }
+
+ /// The date, as the entry (kept here to read the history of an item without joins).
+ public DateOnly EntryDate { get; set; }
+
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The warehouse.
+ public long WarehouseId { get; set; }
+
+ /// The quantity in the base unit: positive for loads, negative for unloads.
+ public decimal Quantity { get; set; }
+
+ ///
+ /// The cost comes from the document (purchases, opening stock, adjustments with a cost) and moves the average; when
+ /// false the line is valued at the average of its moment (sales, returns, transfers).
+ ///
+ public bool Valued { get; set; }
+
+ /// The unit cost in euro.
+ public decimal UnitCost { get; set; }
+
+ /// The value of the movement in euro, with the sign of the quantity.
+ public decimal Value { get; set; }
+
+ /// The document line that wrote it.
+ public long? SourceLineId { get; set; }
+
+ /// The order of the lines in the entry.
+ public int SortOrder { get; set; }
+}
+
+///
+/// What an item has in a warehouse (item_balances), kept in step with the movements and the open orders:
+/// on hand, committed to customers, ordered from suppliers, average cost and value.
+///
+public sealed class ItemBalance : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The warehouse.
+ public long WarehouseId { get; set; }
+
+ /// The quantity on hand.
+ public decimal OnHand { get; set; }
+
+ /// The quantity in the confirmed customer orders still to deliver.
+ public decimal Committed { get; set; }
+
+ /// The quantity in the confirmed supplier orders still to receive.
+ public decimal Ordered { get; set; }
+
+ /// The quantity sent towards this warehouse and not yet arrived (transfers are immediate: kept for later).
+ public decimal InTransit { get; set; }
+
+ /// The weighted average cost of the item.
+ public decimal AverageCost { get; set; }
+
+ /// The value of the quantity on hand at the average cost.
+ public decimal Value { get; set; }
+
+ /// The last purchase cost.
+ public decimal? LastCost { get; set; }
+
+ /// The date of the last load.
+ public DateOnly? LastLoadDate { get; set; }
+
+ /// The date of the last unload.
+ public DateOnly? LastUnloadDate { get; set; }
+
+ /// What can be promised: on hand less committed.
+ public decimal Available => OnHand - Committed;
+}
+
+/// The state of a physical inventory.
+public enum StockTakeStatus
+{
+ /// Counting: the quantities can be entered.
+ Open = 0,
+
+ /// Posted: the differences became adjustments.
+ Posted = 1,
+
+ /// Abandoned.
+ Cancelled = 2,
+}
+
+/// A physical inventory of a warehouse (SPEC §11.6, mockup 038, stock_takes).
+public sealed class StockTake : Entity, IDemoMarkable
+{
+ /// The date the count refers to: the book quantities are those of the evening of that day.
+ public DateOnly TakeDate { get; set; }
+
+ /// The warehouse counted.
+ public long WarehouseId { get; set; }
+
+ /// A description, such as Inventario di fine anno.
+ public string Description { get; set; } = string.Empty;
+
+ /// The item category counted; every stocked item when empty.
+ public long? CategoryId { get; set; }
+
+ /// The state.
+ public StockTakeStatus Status { get; set; }
+
+ /// The warehouse entry with the adjustments, once posted.
+ public long? AdjustmentDocumentId { get; set; }
+
+ /// When it was posted.
+ public DateTime? PostedAt { get; set; }
+
+ /// Who posted it.
+ public string? PostedBy { get; set; }
+
+ /// Notes.
+ public string? Notes { get; set; }
+
+ ///
+ public bool IsDemo { get; set; }
+}
+
+/// A line of a physical inventory (stock_take_lines).
+public sealed class StockTakeLine : Entity
+{
+ /// The inventory.
+ public long StockTakeId { get; set; }
+
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The quantity the books say at the date of the count.
+ public decimal BookQuantity { get; set; }
+
+ /// The quantity counted; empty until counted.
+ public decimal? CountedQuantity { get; set; }
+
+ /// The unit cost used for the adjustment: the average cost at the date.
+ public decimal UnitCost { get; set; }
+
+ /// Notes of the counter.
+ public string? Notes { get; set; }
+
+ /// The order on the list (by item code).
+ public int SortOrder { get; set; }
+
+ /// The difference to adjust: counted less book, zero while not counted.
+ public decimal Difference => CountedQuantity is { } counted ? counted - BookQuantity : 0m;
+}
+
+/// How the stock is valued at a date (SPEC §11.6).
+public enum StockValuationMethod
+{
+ /// Weighted average cost, moved by every purchase (the one the balances keep).
+ WeightedAverage = 0,
+
+ /// The last purchase cost.
+ LastCost = 1,
+
+ /// The standard cost of the item.
+ StandardCost = 2,
+}
diff --git a/src/Khaemhat.Core/Inventory/StockCostCalculator.cs b/src/Khaemhat.Core/Inventory/StockCostCalculator.cs
new file mode 100644
index 0000000..0499559
--- /dev/null
+++ b/src/Khaemhat.Core/Inventory/StockCostCalculator.cs
@@ -0,0 +1,85 @@
+namespace Khaemhat.Core.Inventory;
+
+/// A movement of one item, in the order of the history.
+/// The movement.
+/// The date.
+/// The warehouse.
+/// Positive loads, negative unloads, in the base unit.
+/// The cost comes from the document.
+/// The cost of a valued movement.
+public sealed record CostedMovement(long Id, DateOnly Date, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
+
+/// What one warehouse holds after the history.
+/// The quantity on hand.
+/// The date of the last load.
+/// The date of the last unload.
+public sealed record WarehouseStock(decimal OnHand, DateOnly? LastLoad, DateOnly? LastUnload);
+
+/// The history of an item run through the weighted average.
+/// The unit cost of each movement: its own when valued, the average of its moment otherwise.
+/// What each warehouse holds.
+/// The average cost at the end.
+/// The cost of the last valued load.
+/// The quantity on hand in every warehouse together.
+public sealed record CostedHistory(
+ IReadOnlyDictionary UnitCosts, IReadOnlyDictionary Warehouses, decimal AverageCost, decimal? LastCost, decimal OnHand);
+
+///
+/// The weighted average cost of an item over its movements (SPEC §11.6, ADR 0035): every valued load (purchase,
+/// opening stock, adjustment with a cost) moves the average of the item across its warehouses; every other movement is
+/// valued at the average of its moment. When the stock was zero or below, the next valued load sets the average.
+///
+public static class StockCostCalculator
+{
+ /// The decimals of unit costs.
+ public const int CostDecimals = 4;
+
+ /// Runs the history of an item.
+ /// The movements, in date and posting order.
+ /// The cost used before the first valued load (the standard cost of the item, or zero).
+ /// The costs and the stock.
+ public static CostedHistory Run(IEnumerable movements, decimal initialCost = 0m)
+ {
+ ArgumentNullException.ThrowIfNull(movements);
+ var costs = new Dictionary();
+ var warehouses = new Dictionary();
+ var total = 0m;
+ var average = initialCost;
+ decimal? last = null;
+ foreach (var m in movements)
+ {
+ decimal cost;
+ if (m.Valued && m.Quantity > 0m)
+ {
+ cost = m.UnitCost;
+ var after = total + m.Quantity;
+ average = total <= 0m || after <= 0m ? cost : Math.Round(((total * average) + (m.Quantity * cost)) / after, CostDecimals, MidpointRounding.AwayFromZero);
+ last = cost;
+ }
+ else
+ {
+ cost = average;
+ }
+
+ costs[m.Id] = cost;
+ total += m.Quantity;
+ var stock = warehouses.TryGetValue(m.WarehouseId, out var s) ? s : new WarehouseStock(0m, null, null);
+ warehouses[m.WarehouseId] = stock with
+ {
+ OnHand = stock.OnHand + m.Quantity,
+ LastLoad = m.Quantity > 0m ? Later(stock.LastLoad, m.Date) : stock.LastLoad,
+ LastUnload = m.Quantity < 0m ? Later(stock.LastUnload, m.Date) : stock.LastUnload,
+ };
+ }
+
+ return new CostedHistory(costs, warehouses, average, last, total);
+ }
+
+ /// The value of a quantity at a unit cost, in euro to the cent.
+ /// The quantity.
+ /// The unit cost.
+ /// The value.
+ public static decimal Value(decimal quantity, decimal unitCost) => Math.Round(quantity * unitCost, 2, MidpointRounding.AwayFromZero);
+
+ private static DateOnly Later(DateOnly? a, DateOnly b) => a is { } x && x > b ? x : b;
+}
diff --git a/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs b/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs
new file mode 100644
index 0000000..8f6f2ff
--- /dev/null
+++ b/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs
@@ -0,0 +1,122 @@
+using Khaemhat.Core.Documents;
+using Khaemhat.Core.Tables;
+
+namespace Khaemhat.Core.Inventory;
+
+/// A document line as the stock sees it: an item, a quantity in its base unit, a warehouse, a cost.
+/// The document line.
+/// The item.
+/// The quantity in the base unit of the item (positive).
+/// The warehouse of the line.
+/// The cost per base unit in euro written on the document, if any.
+public sealed record StockLineInput(long LineId, long ItemId, decimal Quantity, long WarehouseId, decimal? UnitCost);
+
+/// A movement to write: one item, one warehouse, a signed quantity.
+/// The document line.
+/// The item.
+/// The warehouse.
+/// Positive loads, negative unloads.
+/// The cost comes from the document and moves the average.
+/// The cost of a valued movement; zero for the others (valued at the average).
+public sealed record StockMovement(long? SourceLineId, long ItemId, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
+
+/// What the warehouse reason of a document does.
+/// Load, unload or nothing on the quantity.
+/// Purchases and sales move the value; transfers and goods on approval only quantities.
+/// A transfer between two warehouses.
+public sealed record StockReason(StockEffect Effect, bool AffectsValue, bool IsTransfer)
+{
+ /// The reason of a row of inventory_reasons.
+ /// The row.
+ /// The reason.
+ public static StockReason Of(InventoryReason reason)
+ {
+ ArgumentNullException.ThrowIfNull(reason);
+ return new StockReason(reason.Effect, reason.AffectsValue, reason.IsTransfer);
+ }
+}
+
+///
+/// Which documents move the stock and how (SPEC §11.6, ADR 0035): the warehouse reason of the document decides load,
+/// unload or transfer; the kind decides whether the reason counts at all and whether the cost on the lines is a
+/// purchase cost that moves the average. Orders do not move the stock: their residuals are the committed and ordered
+/// quantities.
+///
+public static class StockEffectMatrix
+{
+ private static readonly HashSet Moving =
+ [
+ DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice,
+ DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice,
+ DocumentKind.PurchaseCreditNote, DocumentKind.InventoryEntry,
+ ];
+
+ // The kinds whose costs are purchase costs: they move the average when the reason loads with value.
+ private static readonly HashSet Costing =
+ [DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, DocumentKind.InventoryEntry];
+
+ /// Whether documents of a kind move the stock when their reason says so.
+ /// The kind.
+ /// Whether they do.
+ public static bool MovesStock(DocumentKind kind) => Moving.Contains(kind);
+
+ /// Whether the open lines of a kind are committed to customers.
+ /// The kind.
+ /// Whether they are.
+ public static bool Commits(DocumentKind kind) => kind == DocumentKind.SalesOrder;
+
+ /// Whether the open lines of a kind are ordered from suppliers.
+ /// The kind.
+ /// Whether they are.
+ public static bool Orders(DocumentKind kind) => kind == DocumentKind.PurchaseOrder;
+
+ /// Whether a document in a state still holds quantities committed or ordered.
+ /// The state.
+ /// Whether it is open.
+ public static bool IsOpenOrder(DocumentStatus status) => status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled;
+
+ /// The movements of a document.
+ /// The kind of the document.
+ /// Its warehouse reason.
+ /// The destination of a transfer.
+ /// The stocked lines.
+ /// The movements; none when the kind or the reason does not move the stock.
+ /// A transfer without a destination different from the origin.
+ public static IReadOnlyList Movements(DocumentKind kind, StockReason? reason, long? toWarehouseId, IEnumerable lines)
+ {
+ ArgumentNullException.ThrowIfNull(lines);
+ if (reason is null || !MovesStock(kind))
+ {
+ return [];
+ }
+
+ var result = new List();
+ foreach (var line in lines.Where(l => l.Quantity != 0m))
+ {
+ if (reason.IsTransfer)
+ {
+ if (toWarehouseId is not { } to || to == line.WarehouseId)
+ {
+ throw new InvalidOperationException("A transfer needs a destination warehouse different from the origin.");
+ }
+
+ result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m));
+ result.Add(new StockMovement(line.LineId, line.ItemId, to, line.Quantity, false, 0m));
+ continue;
+ }
+
+ switch (reason.Effect)
+ {
+ case StockEffect.Load:
+ var valued = reason.AffectsValue && Costing.Contains(kind) && line.UnitCost is > 0m;
+ result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, line.Quantity, valued, valued ? line.UnitCost!.Value : 0m));
+ break;
+ case StockEffect.Unload:
+ result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m));
+ break;
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs b/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs
new file mode 100644
index 0000000..20ada1d
--- /dev/null
+++ b/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs
@@ -0,0 +1,52 @@
+using Khaemhat.Core.Inventory;
+using Khaemhat.Data.Mapping;
+
+namespace Khaemhat.Data.CompanyDatabase;
+
+/// Map of to inventory_entries.
+public sealed class InventoryEntryMap : EntityMap
+{
+ /// Creates the map.
+ public InventoryEntryMap()
+ {
+ ToTable("inventory_entries");
+ Map(x => x.SourceNumber).MaxLength(30);
+ }
+}
+
+/// Map of to inventory_entry_lines.
+public sealed class InventoryEntryLineMap : EntityMap
+{
+ /// Creates the map.
+ public InventoryEntryLineMap() => ToTable("inventory_entry_lines");
+}
+
+/// Map of to item_balances.
+public sealed class ItemBalanceMap : EntityMap
+{
+ /// Creates the map.
+ public ItemBalanceMap() => ToTable("item_balances");
+}
+
+/// Map of to stock_takes.
+public sealed class StockTakeMap : EntityMap
+{
+ /// Creates the map.
+ public StockTakeMap()
+ {
+ ToTable("stock_takes");
+ Map(x => x.Description).MaxLength(100);
+ Map(x => x.PostedBy).MaxLength(100);
+ }
+}
+
+/// Map of to stock_take_lines.
+public sealed class StockTakeLineMap : EntityMap
+{
+ /// Creates the map.
+ public StockTakeLineMap()
+ {
+ ToTable("stock_take_lines");
+ Map(x => x.Notes).MaxLength(200);
+ }
+}
diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs
new file mode 100644
index 0000000..10e1af3
--- /dev/null
+++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs
@@ -0,0 +1,135 @@
+using Khaemhat.Data.Migrations;
+using Khaemhat.Data.Schema;
+
+namespace Khaemhat.Data.CompanyDatabase.Migrations;
+
+///
+/// The warehouse (SPEC §11.6, ADR 0035, issues #59 and #60): the movements posted by the documents, the balance of
+/// each item in each warehouse, the physical inventories; on the documents the destination of a transfer and the VAT
+/// date of a supplier invoice (#56). Immediate invoices unload, supplier invoices load and supplier credit notes give
+/// back, like the delivery notes: the reason of the document type decides it and can be removed.
+///
+[Migration(20261113_001, "create_inventory")]
+public sealed class M20261113_001_CreateInventory : IMigration
+{
+ private static readonly string[] Headers =
+ ["sale_quotations", "sale_orders", "sale_documents", "purchase_orders", "purchase_documents", "inventory_documents"];
+
+ // The reasons given to the document types of the base tables that had none (ItalianBaseTables has them from now on).
+ private static readonly (string Type, string Reason)[] Reasons = [("FI", "SCA"), ("FF", "CAR"), ("NCF", "RESF")];
+
+ ///
+ public void Up(ISchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ foreach (var table in Headers)
+ {
+ schema.AlterTable(table, t =>
+ {
+ t.Int64("to_warehouse_id");
+ t.Date("vat_date");
+ });
+ }
+
+ foreach (var (type, reason) in Reasons)
+ {
+ schema.Sql(_ => "UPDATE document_types SET inventory_reason_id = (SELECT r.id FROM inventory_reasons r WHERE r.code = '" + reason
+ + "') WHERE code = '" + type + "' AND inventory_reason_id IS NULL");
+ }
+
+ schema.CreateTable("inventory_entries", t =>
+ {
+ t.Id();
+ t.Date("entry_date").NotNull();
+ t.String("source_family", 40);
+ t.Int64("source_document_id");
+ t.String("source_kind", 40);
+ t.String("source_number", 30);
+ t.Int64("inventory_reason_id");
+ t.Int64("party_id");
+ t.DemoColumn();
+ t.AuditColumns();
+ t.Index("ix_inventory_entries_source", "source_family", "source_document_id");
+ t.Index("ix_inventory_entries_date", "entry_date");
+ t.ForeignKey("fk_inventory_entries_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
+ });
+
+ schema.CreateTable("inventory_entry_lines", t =>
+ {
+ t.Id();
+ t.Int64("entry_id").NotNull();
+ t.Date("entry_date").NotNull();
+ t.Int64("item_id").NotNull();
+ t.Int64("warehouse_id").NotNull();
+ t.Decimal("quantity").NotNull();
+ t.Bool("valued").NotNull().Default(false);
+ t.Decimal("unit_cost").NotNull().Default(0m);
+ t.Decimal("value").NotNull().Default(0m);
+ t.Int64("source_line_id");
+ t.Int32("sort_order").NotNull().Default(0);
+ t.AuditColumns();
+ t.Index("ix_inventory_entry_lines_entry", "entry_id");
+ t.Index("ix_inventory_entry_lines_item", "item_id", "entry_date");
+ t.Index("ix_inventory_entry_lines_warehouse", "warehouse_id", "item_id");
+ t.ForeignKey("fk_inventory_entry_lines_entry", "entry_id", "inventory_entries", ReferentialAction.Cascade);
+ t.ForeignKey("fk_inventory_entry_lines_item", "item_id", "items", ReferentialAction.Restrict);
+ t.ForeignKey("fk_inventory_entry_lines_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
+ });
+
+ schema.CreateTable("item_balances", t =>
+ {
+ t.Id();
+ t.Int64("item_id").NotNull();
+ t.Int64("warehouse_id").NotNull();
+ t.Decimal("on_hand").NotNull().Default(0m);
+ t.Decimal("committed").NotNull().Default(0m);
+ t.Decimal("ordered").NotNull().Default(0m);
+ t.Decimal("in_transit").NotNull().Default(0m);
+ t.Decimal("average_cost").NotNull().Default(0m);
+ t.Decimal("value").NotNull().Default(0m);
+ t.Decimal("last_cost");
+ t.Date("last_load_date");
+ t.Date("last_unload_date");
+ t.AuditColumns();
+ t.Unique("ux_item_balances_item_warehouse", "item_id", "warehouse_id");
+ t.Index("ix_item_balances_warehouse", "warehouse_id");
+ t.ForeignKey("fk_item_balances_item", "item_id", "items", ReferentialAction.Cascade);
+ t.ForeignKey("fk_item_balances_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
+ });
+
+ schema.CreateTable("stock_takes", t =>
+ {
+ t.Id();
+ t.Date("take_date").NotNull();
+ t.Int64("warehouse_id").NotNull();
+ t.String("description", 100).NotNull();
+ t.Int64("category_id");
+ t.String("status", 40).NotNull();
+ t.Int64("adjustment_document_id");
+ t.DateTimeUtc("posted_at");
+ t.String("posted_by", 100);
+ t.Text("notes");
+ t.DemoColumn();
+ t.AuditColumns();
+ t.Index("ix_stock_takes_date", "take_date");
+ t.ForeignKey("fk_stock_takes_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
+ t.ForeignKey("fk_stock_takes_category", "category_id", "item_categories", ReferentialAction.Restrict);
+ });
+
+ schema.CreateTable("stock_take_lines", t =>
+ {
+ t.Id();
+ t.Int64("stock_take_id").NotNull();
+ t.Int64("item_id").NotNull();
+ t.Decimal("book_quantity").NotNull().Default(0m);
+ t.Decimal("counted_quantity");
+ t.Decimal("unit_cost").NotNull().Default(0m);
+ t.String("notes", 200);
+ t.Int32("sort_order").NotNull().Default(0);
+ t.AuditColumns();
+ t.Unique("ux_stock_take_lines_item", "stock_take_id", "item_id");
+ t.ForeignKey("fk_stock_take_lines_take", "stock_take_id", "stock_takes", ReferentialAction.Cascade);
+ t.ForeignKey("fk_stock_take_lines_item", "item_id", "items", ReferentialAction.Restrict);
+ });
+ }
+}
diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs
index e015538..9f9c379 100644
--- a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs
+++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs
@@ -50,7 +50,7 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote),
- new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice),
+ new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.ImmediateInvoice),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice),
@@ -62,10 +62,16 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice),
+ new("AF20", "Autofattura per regolarizzazione", NumeratorKind.SalesInvoice, "AUT", null, "TD20", DocumentKind.SelfInvoice),
+ new("AF21", "Autofattura per splafonamento", NumeratorKind.SalesInvoice, "AUT", null, "TD21", DocumentKind.SelfInvoice),
+ new("AF22", "Estrazione beni da deposito IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD22", DocumentKind.SelfInvoice),
+ new("AF23", "Estrazione beni da deposito IVA con versamento", NumeratorKind.SalesInvoice, "AUT", null, "TD23", DocumentKind.SelfInvoice),
+ new("AF28", "Acquisti da San Marino con IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD28", DocumentKind.SelfInvoice),
+ new("AF29", "Comunicazione per omessa o irregolare fatturazione", NumeratorKind.SalesInvoice, "AUT", null, "TD29", DocumentKind.SelfInvoice),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote),
- new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice),
- new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote),
+ new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", "CAR", null, DocumentKind.PurchaseInvoice),
+ new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", "RESF", null, DocumentKind.PurchaseCreditNote),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry),
];
}
diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
index 142c091..80f3772 100644
--- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
+++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
@@ -146,6 +146,7 @@ internal static class KhaemhatServices
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
diff --git a/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs b/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs
new file mode 100644
index 0000000..0b5b77e
--- /dev/null
+++ b/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs
@@ -0,0 +1,104 @@
+using Khaemhat.Core.Documents;
+using Khaemhat.Core.Inventory;
+using Khaemhat.Core.Tables;
+
+namespace Khaemhat.Core.Tests.Inventory;
+
+/// Which documents move the stock and how the weighted average values it (issue #59, ADR 0035).
+[TestClass]
+public sealed class StockRulesTests
+{
+ private static readonly StockReason Load = new(StockEffect.Load, AffectsValue: true, IsTransfer: false);
+ private static readonly StockReason Unload = new(StockEffect.Unload, AffectsValue: true, IsTransfer: false);
+ private static readonly StockReason Transfer = new(StockEffect.None, AffectsValue: false, IsTransfer: true);
+
+ [TestMethod]
+ public void Movements_FollowTheReason_AndOnlyPurchasesCarryTheirCost()
+ {
+ var line = new StockLineInput(7, 100, 5m, 1, 12.5m);
+
+ var receipt = StockEffectMatrix.Movements(DocumentKind.PurchaseDeliveryNote, Load, null, [line]).Single();
+ Assert.AreEqual(5m, receipt.Quantity);
+ Assert.IsTrue(receipt.Valued);
+ Assert.AreEqual(12.5m, receipt.UnitCost);
+
+ var delivery = StockEffectMatrix.Movements(DocumentKind.DeliveryNote, Unload, null, [line]).Single();
+ Assert.AreEqual(-5m, delivery.Quantity);
+ Assert.IsFalse(delivery.Valued, "A sale is valued at the average, not at its price.");
+
+ // A customer return loads, at the average.
+ var back = StockEffectMatrix.Movements(DocumentKind.CreditNote, Load, null, [line]).Single();
+ Assert.AreEqual(5m, back.Quantity);
+ Assert.IsFalse(back.Valued);
+
+ // Orders and quotations never move the stock; without a reason nothing moves.
+ Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.PurchaseOrder, Load, null, [line]));
+ Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.Quotation, Unload, null, [line]));
+ Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.ImmediateInvoice, null, null, [line]));
+ Assert.IsTrue(StockEffectMatrix.Commits(DocumentKind.SalesOrder));
+ Assert.IsTrue(StockEffectMatrix.Orders(DocumentKind.PurchaseOrder));
+ Assert.IsTrue(StockEffectMatrix.IsOpenOrder(DocumentStatus.PartiallyFulfilled));
+ Assert.IsFalse(StockEffectMatrix.IsOpenOrder(DocumentStatus.Closed));
+ }
+
+ [TestMethod]
+ public void Transfer_UnloadsTheOriginAndLoadsTheDestination_WithoutValue()
+ {
+ var moves = StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, 2, [new StockLineInput(1, 100, 3m, 1, 10m)]);
+ Assert.HasCount(2, moves);
+ Assert.AreEqual((1L, -3m), (moves[0].WarehouseId, moves[0].Quantity));
+ Assert.AreEqual((2L, 3m), (moves[1].WarehouseId, moves[1].Quantity));
+ Assert.IsFalse(moves.Any(m => m.Valued));
+
+ Assert.ThrowsExactly(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, null, [new StockLineInput(1, 100, 3m, 1, null)]));
+ Assert.ThrowsExactly(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, 1, [new StockLineInput(1, 100, 3m, 1, null)]));
+ }
+
+ [TestMethod]
+ public void WeightedAverage_MovesWithEveryValuedLoad_AndValuesTheRestAtItsMoment()
+ {
+ var day = new DateOnly(2026, 3, 1);
+ var history = StockCostCalculator.Run(
+ [
+ new CostedMovement(1, day, 1, 10m, true, 10m),
+ new CostedMovement(2, day.AddDays(1), 1, -4m, false, 0m),
+ new CostedMovement(3, day.AddDays(2), 2, 6m, true, 13m),
+ new CostedMovement(4, day.AddDays(3), 1, -2m, false, 0m),
+ ]);
+
+ // 6 left at 10, then 6 more at 13: (60 + 78) / 12 = 11.5.
+ Assert.AreEqual(10m, history.UnitCosts[2]);
+ Assert.AreEqual(11.5m, history.UnitCosts[4]);
+ Assert.AreEqual(11.5m, history.AverageCost);
+ Assert.AreEqual(13m, history.LastCost);
+ Assert.AreEqual(10m, history.OnHand);
+ Assert.AreEqual(4m, history.Warehouses[1].OnHand);
+ Assert.AreEqual(6m, history.Warehouses[2].OnHand);
+ Assert.AreEqual(day.AddDays(3), history.Warehouses[1].LastUnload);
+ Assert.AreEqual(day, history.Warehouses[1].LastLoad);
+ Assert.AreEqual(-23m, StockCostCalculator.Value(-2m, 11.5m));
+ }
+
+ [TestMethod]
+ public void WeightedAverage_RestartsFromTheLoad_WhenTheStockWasNegative()
+ {
+ var day = new DateOnly(2026, 3, 1);
+ var history = StockCostCalculator.Run(
+ [
+ new CostedMovement(1, day, 1, -3m, false, 0m),
+ new CostedMovement(2, day, 1, 5m, true, 8m),
+ ],
+ initialCost: 7m);
+
+ Assert.AreEqual(7m, history.UnitCosts[1], "Before any purchase the standard cost values the unload.");
+ Assert.AreEqual(8m, history.AverageCost);
+ Assert.AreEqual(2m, history.OnHand);
+ }
+
+ [TestMethod]
+ public void Reason_ComesFromTheRowOfTheTable()
+ {
+ var reason = StockReason.Of(new InventoryReason { Code = "TRA", Description = "Trasferimento", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true });
+ Assert.AreEqual(Transfer, reason);
+ }
+}
diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs
index 6171280..392fff4 100644
--- a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs
+++ b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs
@@ -125,7 +125,7 @@ public sealed class DocumentEngineTests
var year = DateTime.Now.Year;
var definitions = await engine.DefinitionsAsync(Root, company);
- Assert.HasCount(20, definitions, "Every seeded type has its kind.");
+ Assert.HasCount(26, definitions, "Every seeded type has its kind.");
Assert.AreEqual(DocumentKind.DeferredInvoice, definitions.Single(d => d.Code == "FD").Kind);
Assert.AreEqual(DocumentAction.Issue, definitions.Single(d => d.Code == "FI").ConfirmAction);
await Assert.ThrowsExactlyAsync(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document.");
diff --git a/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs b/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs
new file mode 100644
index 0000000..d07617f
--- /dev/null
+++ b/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs
@@ -0,0 +1,167 @@
+using Khaemhat.Application.Documents;
+using Khaemhat.Application.Inventory;
+using Khaemhat.Application.Items;
+using Khaemhat.Application.Parties;
+using Khaemhat.Application.Security;
+using Khaemhat.Application.Tables;
+using Khaemhat.Core.Documents;
+using Khaemhat.Core.Inventory;
+using Khaemhat.Core.Parties;
+using Khaemhat.Core.Security;
+using Khaemhat.Core.Tables;
+using Khaemhat.Web.Tests.Hosting;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Khaemhat.Web.Tests.Inventory;
+
+///
+/// The warehouse on a real instance (issue #59): receipts load at their cost, deliveries unload at the average,
+/// cancelling gives the stock back, transfers move between warehouses, orders hold committed and ordered quantities.
+///
+[TestClass]
+public sealed class InventoryFlowTests
+{
+ private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
+
+ [TestMethod]
+ public async Task Documents_MoveTheStock_AndTheAverageCost()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ var engine = app.Services.GetRequiredService();
+ var stock = app.Services.GetRequiredService();
+ var tables = app.Services.GetRequiredService();
+ var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
+ var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
+ var item = await ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", minimum: 5m);
+ var day = new DateOnly(DateTime.Now.Year, 2, 1);
+
+ // 10 pieces at 10 euro, then 10 at 13: the average is 11.5.
+ var first = await ReceiptAsync(engine, company, supplier, item, day, 10m, 10m);
+ await ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m);
+ var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual(20m, row.OnHand);
+ Assert.AreEqual(11.5m, row.AverageCost);
+ Assert.AreEqual(230m, row.Value);
+
+ // A delivery note unloads at the average.
+ var note = await engine.NewAsync(Root, company, "DDT");
+ note.Header.PartyId = customer;
+ note.Header.DocumentDate = day.AddDays(2);
+ note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola a sfera 1/2", Quantity = 16m, Price = 20m });
+ note = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id);
+ var moves = await stock.MovementsAsync(Root, company, item, null, null, null);
+ Assert.HasCount(3, moves);
+ Assert.AreEqual(-16m, moves[2].Quantity);
+ Assert.AreEqual(11.5m, moves[2].UnitCost);
+ Assert.AreEqual(4m, moves[2].Balance);
+ Assert.AreEqual(note.Header.DocumentNumber, moves[2].Number);
+ Assert.AreEqual("Rossi Impianti S.r.l.", moves[2].PartyName);
+ row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual(StockLevel.Understock, row.Level, "4 left, 5 the minimum.");
+ Assert.AreEqual(item, (await stock.UnderstockAsync(Root, company)).Single().ItemId);
+
+ // Cancelling the first receipt re-runs the history: the average is that of the second.
+ await engine.CancelAsync(Root, company, DocumentFamily.PurchaseDocument, first.Header.Id, null);
+ row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual(-6m, row.OnHand);
+ Assert.AreEqual(13m, row.AverageCost);
+ Assert.AreEqual(StockLevel.Out, row.Level);
+
+ // The value at a date before the cancelled history.
+ var valuation = await stock.ValuationAsync(Root, company, day.AddDays(1), null, StockValuationMethod.WeightedAverage);
+ Assert.AreEqual((10m, 13m, 130m, 'A'), (valuation.Single().Quantity, valuation[0].UnitCost, valuation[0].Value, valuation[0].AbcClass));
+
+ // A transfer moves the quantity, not the value.
+ var other = await tables.SaveAsync(Root, company, new Warehouse { Code = "FURG", Description = "Furgone" });
+ var transfer = await engine.NewAsync(Root, company, "MM");
+ transfer.Header.DocumentDate = day.AddDays(3);
+ transfer.Header.InventoryReasonId = (await tables.ActiveAsync(Root, company)).Single(r => r.Code == "TRA").Id;
+ transfer.Header.ToWarehouseId = other.Id;
+ transfer.Lines.Add(new InventoryDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola", Quantity = 2m });
+ await engine.ConfirmAsync(Root, company, DocumentFamily.InventoryDocument, (await engine.SaveAsync(Root, company, transfer)).Header.Id);
+ var balances = await stock.BalancesAsync(Root, company, item);
+ Assert.AreEqual(2m, balances.Single(b => b.WarehouseId == other.Id).OnHand);
+ Assert.AreEqual(-8m, balances.Single(b => b.WarehouseId != other.Id).OnHand);
+ Assert.AreEqual(-6m, balances.Sum(b => b.OnHand));
+ await app.StopAsync();
+ }
+ }
+
+ [TestMethod]
+ public async Task Orders_HoldCommittedAndOrderedQuantities_UntilTheyAreFulfilled()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ var engine = app.Services.GetRequiredService();
+ var copies = app.Services.GetRequiredService();
+ var stock = app.Services.GetRequiredService();
+ var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
+ var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
+ var item = await ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", minimum: null);
+ var day = new DateOnly(DateTime.Now.Year, 3, 1);
+
+ var order = await engine.NewAsync(Root, company, "OC");
+ order.Header.PartyId = customer;
+ order.Header.DocumentDate = day;
+ order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 50m, Price = 2m });
+ order = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleOrder, (await engine.SaveAsync(Root, company, order)).Header.Id);
+
+ var purchase = await engine.NewAsync(Root, company, "OF");
+ purchase.Header.PartyId = supplier;
+ purchase.Header.DocumentDate = day;
+ purchase.Lines.Add(new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 100m, Price = 1m });
+ purchase = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, (await engine.SaveAsync(Root, company, purchase)).Header.Id);
+
+ var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual((0m, 50m, 100m, -50m), (row.OnHand, row.Committed, row.Ordered, row.Available));
+
+ // Receiving 60 of the order: 60 on hand, 40 still ordered.
+ var receipt = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseOrder, [purchase.Header.Id], "DDTF", day.AddDays(5));
+ receipt.Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity = 60m;
+ await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, receipt)).Header.Id);
+ row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual((60m, 50m, 40m, 10m), (row.OnHand, row.Committed, row.Ordered, row.Available));
+ Assert.AreEqual(1m, row.AverageCost, "The cost of the receipt comes from the order price.");
+
+ // Closing the customer order frees what it committed.
+ await engine.CloseAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id);
+ row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
+ Assert.AreEqual(0m, row.Committed);
+ await app.StopAsync();
+ }
+ }
+
+ internal static async Task ReceiptAsync(DocumentEngine engine, string company, long supplier, long item, DateOnly date, decimal quantity, decimal price)
+ {
+ var receipt = await engine.NewAsync(Root, company, "DDTF");
+ receipt.Header.PartyId = supplier;
+ receipt.Header.DocumentDate = date;
+ receipt.Header.ExternalReference = "B" + date.DayNumber.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ receipt.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Carico", Quantity = quantity, Price = price });
+ receipt = await engine.SaveAsync(Root, company, receipt);
+ return await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, receipt.Header.Id);
+ }
+
+ internal static async Task ItemAsync(WebApplication app, string company, string code, string description, decimal? minimum)
+ {
+ var items = app.Services.GetRequiredService();
+ var record = await items.NewAsync(Root, company);
+ record.Item.Code = code;
+ record.Item.Description = description;
+ record.Item.MinimumStock = minimum;
+ return (await items.SaveAsync(Root, company, record)).Item.Id;
+ }
+
+ internal static async Task PartyAsync(WebApplication app, string company, PartyKind kind, string name, string vatNumber)
+ {
+ var parties = app.Services.GetRequiredService();
+ var record = await parties.NewAsync(Root, company, kind);
+ record.Party.Name = name;
+ record.Party.VatNumber = vatNumber;
+ return (await parties.SaveAsync(Root, company, record)).Party.Id;
+ }
+}