using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Items;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Inventory;
///
/// The physical stock take, the reorder proposal and the rebuild of the warehouse on a real instance (issue #60).
///
[TestClass]
public sealed class StockTakeAndReorderTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task StockTake_PostsGainsAndLosses_AtTheDateOfTheCount()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService();
var stock = app.Services.GetRequiredService();
var takes = app.Services.GetRequiredService();
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null);
var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", null);
var day = new DateOnly(DateTime.Now.Year, 6, 1);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 10m, 4m);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, pipe, day, 100m, 1.5m);
var warehouse = (await stock.BalancesAsync(Root, company, valve)).Single().WarehouseId;
var take = await takes.CreateAsync(Root, company, warehouse, day.AddDays(1), null, null);
Assert.AreEqual(10m, take.Lines.Single(l => l.Code == "VALV-01").Line.BookQuantity);
Assert.AreEqual(4m, take.Lines.Single(l => l.Code == "VALV-01").Line.UnitCost);
// Nothing counted, nothing to post.
var empty = await Assert.ThrowsExactlyAsync(() => takes.PostAsync(Root, company, take.Take.Id));
CollectionAssert.Contains(empty.Errors.ToArray(), ":" + StockTakeService.NothingCounted);
// The counts come from a reader file: 12 valves (2 more), 95 pipes (5 less), an unknown code.
using var file = new MemoryStream(Encoding.UTF8.GetBytes("Codice;Quantità \nVALV-01;12\nTUBO-16;90\nTUBO-16;5\nXX-99;1\n"));
var imported = await takes.ImportCountsAsync(Root, company, take.Take.Id, file);
Assert.AreEqual(2, imported.Applied);
Assert.AreEqual("5: XX-99", imported.Unknown.Single());
take = (await takes.GetAsync(Root, company, take.Take.Id))!;
Assert.AreEqual(2, take.Counted);
Assert.AreEqual(2m * 4m - 5m * 1.5m, take.DifferenceValue);
take = await takes.PostAsync(Root, company, take.Take.Id);
Assert.AreEqual(StockTakeStatus.Posted, take.Take.Status);
Assert.IsNotNull(take.Take.AdjustmentDocumentId);
Assert.IsNotNull(take.Take.LossDocumentId);
var rows = await stock.StockAsync(Root, company, new StockFilter());
Assert.AreEqual(12m, rows.Single(r => r.ItemId == valve).OnHand);
Assert.AreEqual(95m, rows.Single(r => r.ItemId == pipe).OnHand);
var moves = await stock.MovementsAsync(Root, company, pipe, null, null, null);
Assert.AreEqual((-5m, day.AddDays(1)), (moves[^1].Quantity, moves[^1].Date));
// A posted take is closed.
var closed = await Assert.ThrowsExactlyAsync(() => takes.SaveCountsAsync(Root, company, take.Take.Id, new Dictionary()));
CollectionAssert.Contains(closed.Errors.ToArray(), ":" + StockTakeService.NotOpen);
await app.StopAsync();
}
}
[TestMethod]
public void CountRows_AcceptItalianAndInvariantNumbers()
{
Assert.AreEqual(("A-1", 1234.5m), StockTakeService.ParseCount("A-1;1.234,5"));
Assert.AreEqual(("A-1", 3m), StockTakeService.ParseCount("A-1\t3"));
Assert.AreEqual(("A-1", 2.5m), StockTakeService.ParseCount("\"A-1\",2.5"));
Assert.IsNull(StockTakeService.ParseCount("Codice;Quantità "));
Assert.IsNull(StockTakeService.ParseCount("A-1;-3"));
Assert.IsNull(StockTakeService.ParseCount(" "));
}
[TestMethod]
public void ReorderQuantity_UsesTheLotAndTheSupplierMinimum()
{
Assert.AreEqual(0m, ReorderService.Quantity(11m, 5m, 10m, null, null), "Covered above the reorder point.");
Assert.AreEqual(4m, ReorderService.Quantity(6m, 5m, 10m, null, null), "Back to the reorder point.");
Assert.AreEqual(25m, ReorderService.Quantity(6m, 5m, 10m, 25m, null), "One lot.");
Assert.AreEqual(30m, ReorderService.Quantity(-12m, 5m, 10m, 10m, null), "As many lots as it takes: 22 missing, three lots.");
Assert.AreEqual(50m, ReorderService.Quantity(6m, 5m, 10m, null, 50m), "At least the supplier minimum.");
Assert.AreEqual(0m, ReorderService.Quantity(5m, 5m, null, null, null), "At the minimum, without a reorder point.");
Assert.AreEqual(1m, ReorderService.Quantity(4m, 5m, null, null, null));
Assert.AreEqual(0m, ReorderService.Quantity(-3m, null, null, null, null), "No thresholds, no proposal.");
}
[TestMethod]
public async Task Reorder_ProposesTheItemsUnderTheirPoint_AndOrdersThemBySupplier()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService();
var reorder = app.Services.GetRequiredService();
var items = app.Services.GetRequiredService();
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var other = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Ferramenta Sud S.p.A.", "00743110157");
var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", 5m);
var record = await items.GetAsync(Root, company, valve);
record!.Item.ReorderPoint = 10m;
record.Item.ReorderLot = 24m;
record.Suppliers.Add(new ItemSupplier { PartyId = supplier, SupplierCode = "VS-12", Price = 3.8m, LeadTimeDays = 7, IsDefault = true });
await items.SaveAsync(Root, company, record);
var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", 50m);
var plenty = await InventoryFlowTests.ItemAsync(app, company, "RACC-20", "Raccordo 20 mm", 5m);
var day = new DateOnly(DateTime.Now.Year, 7, 1);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 6m, 4m);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, plenty, day, 30m, 1m);
var proposals = await reorder.ProposalsAsync(Root, company);
Assert.HasCount(2, proposals);
var first = proposals[0];
Assert.AreEqual((valve, 24m, supplier, 3.8m), (first.ItemId, first.Quantity, first.SupplierId, first.Price));
Assert.IsNotNull(first.ExpectedDate);
Assert.AreEqual((pipe, 50m), (proposals[1].ItemId, proposals[1].Quantity), "No supplier: last, to be chosen.");
Assert.IsNull(proposals[1].SupplierId);
var invalid = await Assert.ThrowsExactlyAsync(() => reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(pipe, 0, 50m)]));
CollectionAssert.Contains(invalid.Errors.ToArray(), ":" + ReorderService.ChoiceInvalid);
var orders = await reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(valve, supplier, 24m), new ReorderChoice(pipe, other, 60m)]);
Assert.HasCount(2, orders);
Assert.IsTrue(orders.All(o => o.Header.Kind == DocumentKind.PurchaseOrder && o.Header.Status == DocumentStatus.Draft));
var valveLine = orders.Single(o => o.Header.PartyId == supplier).Lines.Single(l => l.Kind == DocumentLineKind.Item);
Assert.AreEqual((valve, 24m, 3.8m), (valveLine.ItemId, valveLine.Quantity, valveLine.Price));
Assert.AreEqual(60m, orders.Single(o => o.Header.PartyId == other).Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity);
// Confirmed, the order covers the valve: it is no longer proposed.
await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, orders.Single(o => o.Header.PartyId == supplier).Header.Id);
Assert.IsFalse((await reorder.ProposalsAsync(Root, company)).Any(p => p.ItemId == valve));
await app.StopAsync();
}
}
[TestMethod]
public async Task Rebuild_WritesTheSameStockAgain_AndTheJobRunsForEveryCompany()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService();
var stock = app.Services.GetRequiredService();
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var customer = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null);
var day = new DateOnly(DateTime.Now.Year, 8, 1);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day, 10m, 10m);
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m);
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", Quantity = 4m, Price = 20m });
await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id);
var before = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
var movesBefore = await stock.MovementsAsync(Root, company, item, null, null, null);
var phases = new List();
var (documents, items) = await stock.RebuildAsync(Root, company, new SyncProgress(p => phases.Add(p.Phase)));
Assert.AreEqual(3, documents);
Assert.IsGreaterThanOrEqualTo(1, items);
CollectionAssert.Contains(phases, RebuildPhase.Documents);
CollectionAssert.Contains(phases, RebuildPhase.Items);
var after = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual((before.OnHand, before.AverageCost, before.Value), (after.OnHand, after.AverageCost, after.Value));
var movesAfter = await stock.MovementsAsync(Root, company, item, null, null, null);
CollectionAssert.AreEqual(movesBefore.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList(), movesAfter.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList());
// Without the right to post, no rebuild.
var reader = new Actor("lucia", UserLevel.Standard, null, 999, company);
await Assert.ThrowsExactlyAsync(() => stock.RebuildAsync(reader, company));
var job = app.Services.GetServices().Single(j => j.Type == InventoryRebuildJob.JobType);
var summary = await job.RunAsync(null!, CancellationToken.None);
StringAssert.Contains(summary, "3 documenti");
Assert.AreEqual(after.OnHand, (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item).OnHand);
await app.StopAsync();
}
}
// Reports at once, unlike Progress which posts to the thread pool.
private sealed class SyncProgress(Action report) : IProgress
{
public void Report(RebuildProgress value) => report(value);
}
}