using Khaemhat.Application.Documents;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Items;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Inventory;
///
/// The warehouse on a real instance (issue #59): receipts load at their cost, deliveries unload at the average,
/// cancelling gives the stock back, transfers move between warehouses, orders hold committed and ordered quantities.
///
[TestClass]
public sealed class InventoryFlowTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task Documents_MoveTheStock_AndTheAverageCost()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService();
var stock = app.Services.GetRequiredService();
var tables = app.Services.GetRequiredService();
var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
var item = await ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", minimum: 5m);
var day = new DateOnly(DateTime.Now.Year, 2, 1);
// 10 pieces at 10 euro, then 10 at 13: the average is 11.5.
var first = await ReceiptAsync(engine, company, supplier, item, day, 10m, 10m);
await ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m);
var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual(20m, row.OnHand);
Assert.AreEqual(11.5m, row.AverageCost);
Assert.AreEqual(230m, row.Value);
// A delivery note unloads at the average.
var note = await engine.NewAsync(Root, company, "DDT");
note.Header.PartyId = customer;
note.Header.DocumentDate = day.AddDays(2);
note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola a sfera 1/2", Quantity = 16m, Price = 20m });
note = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id);
var moves = await stock.MovementsAsync(Root, company, item, null, null, null);
Assert.HasCount(3, moves);
Assert.AreEqual(-16m, moves[2].Quantity);
Assert.AreEqual(11.5m, moves[2].UnitCost);
Assert.AreEqual(4m, moves[2].Balance);
Assert.AreEqual(note.Header.DocumentNumber, moves[2].Number);
Assert.AreEqual("Rossi Impianti S.r.l.", moves[2].PartyName);
row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual(StockLevel.Understock, row.Level, "4 left, 5 the minimum.");
Assert.AreEqual(item, (await stock.UnderstockAsync(Root, company)).Single().ItemId);
// Cancelling the first receipt re-runs the history: the average is that of the second.
await engine.CancelAsync(Root, company, DocumentFamily.PurchaseDocument, first.Header.Id, null);
row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual(-6m, row.OnHand);
Assert.AreEqual(13m, row.AverageCost);
Assert.AreEqual(StockLevel.Out, row.Level);
// The value at a date before the cancelled history.
var valuation = await stock.ValuationAsync(Root, company, day.AddDays(1), null, StockValuationMethod.WeightedAverage);
Assert.AreEqual((10m, 13m, 130m, 'A'), (valuation.Single().Quantity, valuation[0].UnitCost, valuation[0].Value, valuation[0].AbcClass));
// A transfer moves the quantity, not the value.
var other = await tables.SaveAsync(Root, company, new Warehouse { Code = "FURG", Description = "Furgone" });
var transfer = await engine.NewAsync(Root, company, "MM");
transfer.Header.DocumentDate = day.AddDays(3);
transfer.Header.InventoryReasonId = (await tables.ActiveAsync(Root, company)).Single(r => r.Code == "TRA").Id;
transfer.Header.ToWarehouseId = other.Id;
transfer.Lines.Add(new InventoryDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola", Quantity = 2m });
await engine.ConfirmAsync(Root, company, DocumentFamily.InventoryDocument, (await engine.SaveAsync(Root, company, transfer)).Header.Id);
var balances = await stock.BalancesAsync(Root, company, item);
Assert.AreEqual(2m, balances.Single(b => b.WarehouseId == other.Id).OnHand);
Assert.AreEqual(-8m, balances.Single(b => b.WarehouseId != other.Id).OnHand);
Assert.AreEqual(-6m, balances.Sum(b => b.OnHand));
await app.StopAsync();
}
}
[TestMethod]
public async Task Orders_HoldCommittedAndOrderedQuantities_UntilTheyAreFulfilled()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService();
var copies = app.Services.GetRequiredService();
var stock = app.Services.GetRequiredService();
var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
var item = await ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", minimum: null);
var day = new DateOnly(DateTime.Now.Year, 3, 1);
var order = await engine.NewAsync(Root, company, "OC");
order.Header.PartyId = customer;
order.Header.DocumentDate = day;
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 50m, Price = 2m });
order = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleOrder, (await engine.SaveAsync(Root, company, order)).Header.Id);
var purchase = await engine.NewAsync(Root, company, "OF");
purchase.Header.PartyId = supplier;
purchase.Header.DocumentDate = day;
purchase.Lines.Add(new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 100m, Price = 1m });
purchase = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, (await engine.SaveAsync(Root, company, purchase)).Header.Id);
var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual((0m, 50m, 100m, -50m), (row.OnHand, row.Committed, row.Ordered, row.Available));
// Receiving 60 of the order: 60 on hand, 40 still ordered.
var receipt = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseOrder, [purchase.Header.Id], "DDTF", day.AddDays(5));
receipt.Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity = 60m;
await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, receipt)).Header.Id);
row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual((60m, 50m, 40m, 10m), (row.OnHand, row.Committed, row.Ordered, row.Available));
Assert.AreEqual(1m, row.AverageCost, "The cost of the receipt comes from the order price.");
// Closing the customer order frees what it committed.
await engine.CloseAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id);
row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual(0m, row.Committed);
await app.StopAsync();
}
}
internal static async Task ReceiptAsync(DocumentEngine engine, string company, long supplier, long item, DateOnly date, decimal quantity, decimal price)
{
var receipt = await engine.NewAsync(Root, company, "DDTF");
receipt.Header.PartyId = supplier;
receipt.Header.DocumentDate = date;
receipt.Header.ExternalReference = "B" + date.DayNumber.ToString(System.Globalization.CultureInfo.InvariantCulture);
receipt.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Carico", Quantity = quantity, Price = price });
receipt = await engine.SaveAsync(Root, company, receipt);
return await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, receipt.Header.Id);
}
internal static async Task ItemAsync(WebApplication app, string company, string code, string description, decimal? minimum)
{
var items = app.Services.GetRequiredService();
var record = await items.NewAsync(Root, company);
record.Item.Code = code;
record.Item.Description = description;
record.Item.MinimumStock = minimum;
return (await items.SaveAsync(Root, company, record)).Item.Id;
}
internal static async Task PartyAsync(WebApplication app, string company, PartyKind kind, string name, string vatNumber)
{
var parties = app.Services.GetRequiredService();
var record = await parties.NewAsync(Root, company, kind);
record.Party.Name = name;
record.Party.VatNumber = vatNumber;
return (await parties.SaveAsync(Root, company, record)).Party.Id;
}
}