M6 · Acquisti e Magazzino (v0.6.0) #125
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;
|
||||
}
|
||||
@@ -73,6 +73,9 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The destination warehouse of a transfer.</summary>
|
||||
public long? ToWarehouseId { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
@@ -220,9 +223,15 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
/// <summary>The ledger entry, once posted (M7).</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>The VAT protocol of a supplier invoice.</summary>
|
||||
/// <summary>The VAT protocol of a supplier invoice: its progressive number in the purchase register of the year.</summary>
|
||||
public long? VatProtocol { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public DateOnly? VatDate { get; set; }
|
||||
|
||||
/// <summary>When the document was confirmed or issued.</summary>
|
||||
public DateTime? ConfirmedAt { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// A posting to the stock (SPEC §11.6, ADR 0035, <c>inventory_entries</c>): the movements one confirmed document wrote.
|
||||
/// Cancelling the document removes its entry; the balances are then computed again from the movements left.
|
||||
/// </summary>
|
||||
public sealed class InventoryEntry : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The date of the movements: the date of the document.</summary>
|
||||
public DateOnly EntryDate { get; set; }
|
||||
|
||||
/// <summary>The family of the document that posted it.</summary>
|
||||
public DocumentFamily? SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The document that posted it.</summary>
|
||||
public long? SourceDocumentId { get; set; }
|
||||
|
||||
/// <summary>The kind of that document.</summary>
|
||||
public DocumentKind? SourceKind { get; set; }
|
||||
|
||||
/// <summary>The number of that document, as printed.</summary>
|
||||
public string? SourceNumber { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier of the document.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A movement of one item in one warehouse (<c>inventory_entry_lines</c>), in the base unit of the item: positive
|
||||
/// loads, negative unloads. A transfer writes two lines.
|
||||
/// </summary>
|
||||
public sealed class InventoryEntryLine : Entity<long>
|
||||
{
|
||||
/// <summary>The entry.</summary>
|
||||
public long EntryId { get; set; }
|
||||
|
||||
/// <summary>The date, as the entry (kept here to read the history of an item without joins).</summary>
|
||||
public DateOnly EntryDate { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The quantity in the base unit: positive for loads, negative for unloads.</summary>
|
||||
public decimal Quantity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool Valued { get; set; }
|
||||
|
||||
/// <summary>The unit cost in euro.</summary>
|
||||
public decimal UnitCost { get; set; }
|
||||
|
||||
/// <summary>The value of the movement in euro, with the sign of the quantity.</summary>
|
||||
public decimal Value { get; set; }
|
||||
|
||||
/// <summary>The document line that wrote it.</summary>
|
||||
public long? SourceLineId { get; set; }
|
||||
|
||||
/// <summary>The order of the lines in the entry.</summary>
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What an item has in a warehouse (<c>item_balances</c>), kept in step with the movements and the open orders:
|
||||
/// on hand, committed to customers, ordered from suppliers, average cost and value.
|
||||
/// </summary>
|
||||
public sealed class ItemBalance : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The quantity on hand.</summary>
|
||||
public decimal OnHand { get; set; }
|
||||
|
||||
/// <summary>The quantity in the confirmed customer orders still to deliver.</summary>
|
||||
public decimal Committed { get; set; }
|
||||
|
||||
/// <summary>The quantity in the confirmed supplier orders still to receive.</summary>
|
||||
public decimal Ordered { get; set; }
|
||||
|
||||
/// <summary>The quantity sent towards this warehouse and not yet arrived (transfers are immediate: kept for later).</summary>
|
||||
public decimal InTransit { get; set; }
|
||||
|
||||
/// <summary>The weighted average cost of the item.</summary>
|
||||
public decimal AverageCost { get; set; }
|
||||
|
||||
/// <summary>The value of the quantity on hand at the average cost.</summary>
|
||||
public decimal Value { get; set; }
|
||||
|
||||
/// <summary>The last purchase cost.</summary>
|
||||
public decimal? LastCost { get; set; }
|
||||
|
||||
/// <summary>The date of the last load.</summary>
|
||||
public DateOnly? LastLoadDate { get; set; }
|
||||
|
||||
/// <summary>The date of the last unload.</summary>
|
||||
public DateOnly? LastUnloadDate { get; set; }
|
||||
|
||||
/// <summary>What can be promised: on hand less committed.</summary>
|
||||
public decimal Available => OnHand - Committed;
|
||||
}
|
||||
|
||||
/// <summary>The state of a physical inventory.</summary>
|
||||
public enum StockTakeStatus
|
||||
{
|
||||
/// <summary>Counting: the quantities can be entered.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Posted: the differences became adjustments.</summary>
|
||||
Posted = 1,
|
||||
|
||||
/// <summary>Abandoned.</summary>
|
||||
Cancelled = 2,
|
||||
}
|
||||
|
||||
/// <summary>A physical inventory of a warehouse (SPEC §11.6, mockup 038, <c>stock_takes</c>).</summary>
|
||||
public sealed class StockTake : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The date the count refers to: the book quantities are those of the evening of that day.</summary>
|
||||
public DateOnly TakeDate { get; set; }
|
||||
|
||||
/// <summary>The warehouse counted.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>A description, such as <c>Inventario di fine anno</c>.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The item category counted; every stocked item when empty.</summary>
|
||||
public long? CategoryId { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public StockTakeStatus Status { get; set; }
|
||||
|
||||
/// <summary>The warehouse entry with the adjustments, once posted.</summary>
|
||||
public long? AdjustmentDocumentId { get; set; }
|
||||
|
||||
/// <summary>When it was posted.</summary>
|
||||
public DateTime? PostedAt { get; set; }
|
||||
|
||||
/// <summary>Who posted it.</summary>
|
||||
public string? PostedBy { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A line of a physical inventory (<c>stock_take_lines</c>).</summary>
|
||||
public sealed class StockTakeLine : Entity<long>
|
||||
{
|
||||
/// <summary>The inventory.</summary>
|
||||
public long StockTakeId { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The quantity the books say at the date of the count.</summary>
|
||||
public decimal BookQuantity { get; set; }
|
||||
|
||||
/// <summary>The quantity counted; empty until counted.</summary>
|
||||
public decimal? CountedQuantity { get; set; }
|
||||
|
||||
/// <summary>The unit cost used for the adjustment: the average cost at the date.</summary>
|
||||
public decimal UnitCost { get; set; }
|
||||
|
||||
/// <summary>Notes of the counter.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>The order on the list (by item code).</summary>
|
||||
public int SortOrder { get; set; }
|
||||
|
||||
/// <summary>The difference to adjust: counted less book, zero while not counted.</summary>
|
||||
public decimal Difference => CountedQuantity is { } counted ? counted - BookQuantity : 0m;
|
||||
}
|
||||
|
||||
/// <summary>How the stock is valued at a date (SPEC §11.6).</summary>
|
||||
public enum StockValuationMethod
|
||||
{
|
||||
/// <summary>Weighted average cost, moved by every purchase (the one the balances keep).</summary>
|
||||
WeightedAverage = 0,
|
||||
|
||||
/// <summary>The last purchase cost.</summary>
|
||||
LastCost = 1,
|
||||
|
||||
/// <summary>The standard cost of the item.</summary>
|
||||
StandardCost = 2,
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>A movement of one item, in the order of the history.</summary>
|
||||
/// <param name="Id">The movement.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads, in the base unit.</param>
|
||||
/// <param name="Valued">The cost comes from the document.</param>
|
||||
/// <param name="UnitCost">The cost of a valued movement.</param>
|
||||
public sealed record CostedMovement(long Id, DateOnly Date, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
|
||||
|
||||
/// <summary>What one warehouse holds after the history.</summary>
|
||||
/// <param name="OnHand">The quantity on hand.</param>
|
||||
/// <param name="LastLoad">The date of the last load.</param>
|
||||
/// <param name="LastUnload">The date of the last unload.</param>
|
||||
public sealed record WarehouseStock(decimal OnHand, DateOnly? LastLoad, DateOnly? LastUnload);
|
||||
|
||||
/// <summary>The history of an item run through the weighted average.</summary>
|
||||
/// <param name="UnitCosts">The unit cost of each movement: its own when valued, the average of its moment otherwise.</param>
|
||||
/// <param name="Warehouses">What each warehouse holds.</param>
|
||||
/// <param name="AverageCost">The average cost at the end.</param>
|
||||
/// <param name="LastCost">The cost of the last valued load.</param>
|
||||
/// <param name="OnHand">The quantity on hand in every warehouse together.</param>
|
||||
public sealed record CostedHistory(
|
||||
IReadOnlyDictionary<long, decimal> UnitCosts, IReadOnlyDictionary<long, WarehouseStock> Warehouses, decimal AverageCost, decimal? LastCost, decimal OnHand);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class StockCostCalculator
|
||||
{
|
||||
/// <summary>The decimals of unit costs.</summary>
|
||||
public const int CostDecimals = 4;
|
||||
|
||||
/// <summary>Runs the history of an item.</summary>
|
||||
/// <param name="movements">The movements, in date and posting order.</param>
|
||||
/// <param name="initialCost">The cost used before the first valued load (the standard cost of the item, or zero).</param>
|
||||
/// <returns>The costs and the stock.</returns>
|
||||
public static CostedHistory Run(IEnumerable<CostedMovement> movements, decimal initialCost = 0m)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movements);
|
||||
var costs = new Dictionary<long, decimal>();
|
||||
var warehouses = new Dictionary<long, WarehouseStock>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The value of a quantity at a unit cost, in euro to the cent.</summary>
|
||||
/// <param name="quantity">The quantity.</param>
|
||||
/// <param name="unitCost">The unit cost.</param>
|
||||
/// <returns>The value.</returns>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>A document line as the stock sees it: an item, a quantity in its base unit, a warehouse, a cost.</summary>
|
||||
/// <param name="LineId">The document line.</param>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Quantity">The quantity in the base unit of the item (positive).</param>
|
||||
/// <param name="WarehouseId">The warehouse of the line.</param>
|
||||
/// <param name="UnitCost">The cost per base unit in euro written on the document, if any.</param>
|
||||
public sealed record StockLineInput(long LineId, long ItemId, decimal Quantity, long WarehouseId, decimal? UnitCost);
|
||||
|
||||
/// <summary>A movement to write: one item, one warehouse, a signed quantity.</summary>
|
||||
/// <param name="SourceLineId">The document line.</param>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads.</param>
|
||||
/// <param name="Valued">The cost comes from the document and moves the average.</param>
|
||||
/// <param name="UnitCost">The cost of a valued movement; zero for the others (valued at the average).</param>
|
||||
public sealed record StockMovement(long? SourceLineId, long ItemId, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
|
||||
|
||||
/// <summary>What the warehouse reason of a document does.</summary>
|
||||
/// <param name="Effect">Load, unload or nothing on the quantity.</param>
|
||||
/// <param name="AffectsValue">Purchases and sales move the value; transfers and goods on approval only quantities.</param>
|
||||
/// <param name="IsTransfer">A transfer between two warehouses.</param>
|
||||
public sealed record StockReason(StockEffect Effect, bool AffectsValue, bool IsTransfer)
|
||||
{
|
||||
/// <summary>The reason of a row of <c>inventory_reasons</c>.</summary>
|
||||
/// <param name="reason">The row.</param>
|
||||
/// <returns>The reason.</returns>
|
||||
public static StockReason Of(InventoryReason reason)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(reason);
|
||||
return new StockReason(reason.Effect, reason.AffectsValue, reason.IsTransfer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class StockEffectMatrix
|
||||
{
|
||||
private static readonly HashSet<DocumentKind> 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<DocumentKind> Costing =
|
||||
[DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, DocumentKind.InventoryEntry];
|
||||
|
||||
/// <summary>Whether documents of a kind move the stock when their reason says so.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they do.</returns>
|
||||
public static bool MovesStock(DocumentKind kind) => Moving.Contains(kind);
|
||||
|
||||
/// <summary>Whether the open lines of a kind are committed to customers.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they are.</returns>
|
||||
public static bool Commits(DocumentKind kind) => kind == DocumentKind.SalesOrder;
|
||||
|
||||
/// <summary>Whether the open lines of a kind are ordered from suppliers.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they are.</returns>
|
||||
public static bool Orders(DocumentKind kind) => kind == DocumentKind.PurchaseOrder;
|
||||
|
||||
/// <summary>Whether a document in a state still holds quantities committed or ordered.</summary>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>Whether it is open.</returns>
|
||||
public static bool IsOpenOrder(DocumentStatus status) => status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled;
|
||||
|
||||
/// <summary>The movements of a document.</summary>
|
||||
/// <param name="kind">The kind of the document.</param>
|
||||
/// <param name="reason">Its warehouse reason.</param>
|
||||
/// <param name="toWarehouseId">The destination of a transfer.</param>
|
||||
/// <param name="lines">The stocked lines.</param>
|
||||
/// <returns>The movements; none when the kind or the reason does not move the stock.</returns>
|
||||
/// <exception cref="InvalidOperationException">A transfer without a destination different from the origin.</exception>
|
||||
public static IReadOnlyList<StockMovement> Movements(DocumentKind kind, StockReason? reason, long? toWarehouseId, IEnumerable<StockLineInput> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
if (reason is null || !MovesStock(kind))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<StockMovement>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="InventoryEntry"/> to <c>inventory_entries</c>.</summary>
|
||||
public sealed class InventoryEntryMap : EntityMap<InventoryEntry>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryEntryMap()
|
||||
{
|
||||
ToTable("inventory_entries");
|
||||
Map(x => x.SourceNumber).MaxLength(30);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="InventoryEntryLine"/> to <c>inventory_entry_lines</c>.</summary>
|
||||
public sealed class InventoryEntryLineMap : EntityMap<InventoryEntryLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryEntryLineMap() => ToTable("inventory_entry_lines");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemBalance"/> to <c>item_balances</c>.</summary>
|
||||
public sealed class ItemBalanceMap : EntityMap<ItemBalance>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemBalanceMap() => ToTable("item_balances");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="StockTake"/> to <c>stock_takes</c>.</summary>
|
||||
public sealed class StockTakeMap : EntityMap<StockTake>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public StockTakeMap()
|
||||
{
|
||||
ToTable("stock_takes");
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.PostedBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="StockTakeLine"/> to <c>stock_take_lines</c>.</summary>
|
||||
public sealed class StockTakeLineMap : EntityMap<StockTakeLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public StockTakeLineMap()
|
||||
{
|
||||
ToTable("stock_take_lines");
|
||||
Map(x => x.Notes).MaxLength(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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")];
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
@@ -146,6 +146,7 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<AutoFillService>();
|
||||
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
|
||||
|
||||
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Inventory;
|
||||
|
||||
/// <summary>Which documents move the stock and how the weighted average values it (issue #59, ADR 0035).</summary>
|
||||
[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<InvalidOperationException>(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, null, [new StockLineInput(1, 100, 3m, 1, null)]));
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => 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);
|
||||
}
|
||||
}
|
||||
@@ -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<ValidationFailedException>(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document.");
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
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<InventoryReason>(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<DocumentEngine>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
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<DocumentRecord> 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<long> ItemAsync(WebApplication app, string company, string code, string description, decimal? minimum)
|
||||
{
|
||||
var items = app.Services.GetRequiredService<ItemService>();
|
||||
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<long> PartyAsync(WebApplication app, string company, PartyKind kind, string name, string vatNumber)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user