From eb301fa570a08521aa5f7a4dced2f6144c6fe0a0 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 12 Nov 2026 21:35:34 +0100 Subject: [PATCH] feat: stock take, reorder proposal and warehouse rebuild (#60) A physical stock take freezes the book quantity and cost of a warehouse at a date, takes counts typed or read from a scanner file, and posts the gains and losses as INVP/INVN movements at that date. The reorder proposal lists the items whose available and ordered quantity no longer covers the reorder point and turns the accepted lines into draft supplier orders, one per supplier. The warehouse can be rebuilt from its documents on demand and every Sunday night, as a safety net after imports or corrections. Co-Authored-By: Claude Opus 5.5 --- .../Documents/DocumentStores.cs | 11 + .../Inventory/InventoryPoster.cs | 71 +++ .../Inventory/InventoryRebuildJob.cs | 42 ++ .../Inventory/InventoryService.cs | 31 ++ .../Inventory/ReorderService.cs | 183 ++++++++ .../Inventory/StockTakeService.cs | 405 ++++++++++++++++++ src/Khaemhat.Application/Jobs/JobScheduler.cs | 3 +- src/Khaemhat.Core/Inventory/Inventory.cs | 5 +- .../M20261113_001_CreateInventory.cs | 1 + src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 3 + .../Resources/it-IT/Inventory.json | 14 + .../Resources/it-IT/Purchases.json | 11 + .../Inventory/StockTakeAndReorderTests.cs | 197 +++++++++ 13 files changed, 975 insertions(+), 2 deletions(-) create mode 100644 src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs create mode 100644 src/Khaemhat.Application/Inventory/ReorderService.cs create mode 100644 src/Khaemhat.Application/Inventory/StockTakeService.cs create mode 100644 tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs diff --git a/src/Khaemhat.Application/Documents/DocumentStores.cs b/src/Khaemhat.Application/Documents/DocumentStores.cs index aa55ea5..3f6a94c 100644 --- a/src/Khaemhat.Application/Documents/DocumentStores.cs +++ b/src/Khaemhat.Application/Documents/DocumentStores.cs @@ -40,6 +40,12 @@ internal interface IDocumentStore /// The lines. Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken); + /// Reads the headers of the documents in force (neither drafts nor cancelled). + /// The unit of work. + /// Cancellation. + /// The headers. + Task> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken); + /// Reads a line. /// The unit of work. /// The line. @@ -136,6 +142,11 @@ internal sealed class DocumentStore(DocumentFamily family, strin public async Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + /// + public async Task> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + [.. (await uow.Repository().ListAsync( + Query.For().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items]; + /// public async Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken) { diff --git a/src/Khaemhat.Application/Inventory/InventoryPoster.cs b/src/Khaemhat.Application/Inventory/InventoryPoster.cs index 876f849..db0a381 100644 --- a/src/Khaemhat.Application/Inventory/InventoryPoster.cs +++ b/src/Khaemhat.Application/Inventory/InventoryPoster.cs @@ -52,6 +52,61 @@ public static class InventoryPoster await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false); } + /// + /// Rebuilds the warehouse from the documents (SPEC §11.6, ricostruzione): removes every movement, posts + /// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of + /// the same day, then runs the history of every item. + /// + /// The unit of work of the company, in a transaction. + /// Receives the documents posted and the total, then the items and their total. + /// Cancellation. + /// The documents posted and the items computed. + public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false); + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false); + var documents = new List<(DocumentFamily Family, DocumentHeader Header)>(); + foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument }) + { + foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false)) + { + if (StockEffectMatrix.MovesStock(header.Kind)) + { + documents.Add((family, header)); + } + } + } + + // Delivery notes and receipts first: their invoices then find the goods already moved. + var ordered = documents + .OrderBy(d => d.Header.DocumentDate) + .ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1) + .ThenBy(d => d.Header.ConfirmedAt) + .ThenBy(d => d.Header.Id) + .ToList(); + var items = new HashSet(); + for (var i = 0; i < ordered.Count; i++) + { + var (family, header) = ordered[i]; + var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false); + await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false); + progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count)); + } + + // Every stocked item, also those with only orders or with no movement left. + var all = (await uow.Repository().ListAsync(Query.For().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id); + var balanced = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId); + var ids = items.Concat(all).Concat(balanced).Distinct().ToList(); + for (var i = 0; i < ids.Count; i += 50) + { + await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false); + progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count)); + } + + return (ordered.Count, ids.Count); + } + /// /// 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. @@ -480,3 +535,19 @@ public static class InventoryPoster private static Task StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken); } + +/// The step of a rebuild. +public enum RebuildPhase +{ + /// Posting the documents. + Documents = 0, + + /// Computing the items. + Items = 1, +} + +/// How far a rebuild is. +/// The step. +/// How many done. +/// How many in all. +public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total); diff --git a/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs b/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs new file mode 100644 index 0000000..ffc2537 --- /dev/null +++ b/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs @@ -0,0 +1,42 @@ +using System.Globalization; +using Khaemhat.Application.Jobs; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Inventory; + +/// +/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net +/// that brings balances and costs back in line after imports or corrections made outside the screens. +/// +/// The units of work. +/// The companies. +public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob +{ + /// The job type. + public const string JobType = "inventory.rebuild"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + int documents = 0, items = 0, done = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is CompanyStatus.Disabled) + { + continue; + } + + var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false); + documents += d; + items += i; + done++; + } + + return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati."); + } +} diff --git a/src/Khaemhat.Application/Inventory/InventoryService.cs b/src/Khaemhat.Application/Inventory/InventoryService.cs index 22f7a15..dae909c 100644 --- a/src/Khaemhat.Application/Inventory/InventoryService.cs +++ b/src/Khaemhat.Application/Inventory/InventoryService.cs @@ -314,6 +314,37 @@ public sealed class InventoryService return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)]; } + /// + /// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every + /// item computed again, in one transaction. + /// + /// Who rebuilds: needs inventory.entry.post. + /// The company. + /// How far it is. + /// Cancellation. + /// The documents posted and the items computed. + public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress? progress = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false); + return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false); + } + + /// Rebuilds the warehouse of a company, without checks (the scheduled job). + /// The units of work. + /// The company. + /// How far it is. + /// Cancellation. + /// The documents posted and the items computed. + internal static async Task<(int Documents, int Items)> RebuildCompanyAsync( + IUnitOfWorkFactory factory, string company, IProgress? progress, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + /// /// 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. diff --git a/src/Khaemhat.Application/Inventory/ReorderService.cs b/src/Khaemhat.Application/Inventory/ReorderService.cs new file mode 100644 index 0000000..e395470 --- /dev/null +++ b/src/Khaemhat.Application/Inventory/ReorderService.cs @@ -0,0 +1,183 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Inventory; + +/// An item to reorder (mockup 039). +/// The item. +/// Its code. +/// Its description. +/// Its unit. +/// On hand less committed. +/// Already ordered. +/// The minimum stock. +/// The reorder point. +/// The quantity proposed. +/// The usual supplier, if any. +/// Its name. +/// Its price. +/// When it would arrive, from the lead time. +public sealed record ReorderProposal( + long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint, + decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate); + +/// A proposal the user accepts, perhaps with another quantity or supplier. +/// The item. +/// The supplier. +/// The quantity. +public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity); + +/// +/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the +/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at +/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders, +/// one per supplier. +/// +public sealed class ReorderService +{ + /// Error: a chosen line without a supplier or a quantity. + public const string ChoiceInvalid = "inventory.reorder.choice-invalid"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly DocumentEngine _engine; + private readonly DocumentEditor _editor; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The document engine. + /// The editor (prices and terms of the supplier). + /// The clock. + public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _engine = engine; + _editor = editor; + _clock = clock; + } + + /// The items to reorder, by supplier and code. + /// Who reads. + /// The company. + /// Cancellation. + /// The proposals. + public async Task> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync( + Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken) + .ConfigureAwait(false)).Items; + if (items.Count == 0) + { + return []; + } + + var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false); + var ids = items.Select(i => i.Id).ToList(); + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.ItemId)), cancellationToken) + .ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First()); + var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList(); + var names = partyIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + var result = new List(); + foreach (var item in items) + { + var mine = balances.GetValueOrDefault(item.Id) ?? []; + var available = mine.Sum(b => b.OnHand - b.Committed); + var ordered = mine.Sum(b => b.Ordered); + var supplier = suppliers.GetValueOrDefault(item.Id); + var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity); + if (quantity <= 0m) + { + continue; + } + + result.Add(new ReorderProposal( + item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity, + supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost, + supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null)); + } + + return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)]; + } + + /// + /// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum); + /// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum + /// quantity of the supplier. + /// + /// Available plus ordered. + /// The minimum stock. + /// The reorder point. + /// The reorder lot. + /// The minimum of the supplier. + /// The quantity. + public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum) + { + var threshold = reorderPoint ?? minimum; + if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point)) + { + return 0m; + } + + var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m); + var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m); + if (lot is > 0m && cover + quantity < target) + { + // One lot is not enough: as many lots as it takes. + quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value; + } + + return Math.Max(quantity, supplierMinimum ?? 0m); + } + + /// Creates the draft supplier orders of the chosen proposals, one per supplier. + /// Who orders: needs purchases.order.write. + /// The company. + /// The proposals accepted. + /// Cancellation. + /// The orders, saved as drafts. + public async Task> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList choices, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(choices); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false); + if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0)) + { + throw new ValidationFailedException([":" + ChoiceInvalid]); + } + + var result = new List(); + foreach (var group in choices.GroupBy(c => c.SupplierId)) + { + var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false); + await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false); + foreach (var choice in group) + { + var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity }; + order.Lines.Add(line); + await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false); + line.Quantity = choice.Quantity; + } + + result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false)); + } + + return result; + } +} diff --git a/src/Khaemhat.Application/Inventory/StockTakeService.cs b/src/Khaemhat.Application/Inventory/StockTakeService.cs new file mode 100644 index 0000000..e58b5bc --- /dev/null +++ b/src/Khaemhat.Application/Inventory/StockTakeService.cs @@ -0,0 +1,405 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +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; + +/// A line of a stock take with its item. +/// The line. +/// The code of the item. +/// Its description. +/// Its base unit. +public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId); + +/// A stock take with its lines. +/// The stock take. +/// Its lines, by code. +public sealed record StockTakeView(StockTake Take, IReadOnlyList Lines) +{ + /// How many lines are counted. + public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null); + + /// The value of the differences at the cost of the lines. + public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost)); +} + +/// What the import of the counts found. +/// The lines counted. +/// The codes not on the list, with their row. +public sealed record StockCountImport(int Applied, IReadOnlyList Unknown); + +/// +/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the +/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements +/// (gains with reason INVP, losses with INVN) through the document engine. +/// +/// Permissions inventory.entry.read, write (lists and counts) and post. +public sealed class StockTakeService +{ + /// Error: the stock take is no longer open. + public const string NotOpen = "inventory.stock-take.not-open"; + + /// Error: nothing is counted. + public const string NothingCounted = "inventory.stock-take.nothing-counted"; + + /// Error: a counted quantity below zero. + public const string NegativeCount = "inventory.stock-take.negative"; + + /// Error: the reasons of the adjustments are missing from the base tables. + public const string ReasonMissing = "inventory.stock-take.reason-missing"; + + /// The reason of the gains. + public const string GainReason = "INVP"; + + /// The reason of the losses. + public const string LossReason = "INVN"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly DocumentEngine _engine; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The document engine, for the adjustments. + /// The clock. + public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _engine = engine; + _clock = clock; + } + + /// The stock takes, the latest first. + /// Who reads. + /// The company. + /// Cancellation. + /// The stock takes. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken) + .ConfigureAwait(false)).Items; + } + + /// A stock take with its lines. + /// Who reads. + /// The company. + /// The stock take. + /// Cancellation. + /// The stock take, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books + /// give at the date and the average cost. + /// + /// Who opens it. + /// The company. + /// The warehouse. + /// The day of the count. + /// Only a category. + /// A description; the warehouse and date when empty. + /// Cancellation. + /// The new stock take. + public async Task CreateAsync( + Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var warehouse = await uow.Repository().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]); + var query = Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled); + if (categoryId is { } category) + { + query = query.Where(i => i.CategoryId == category); + } + + var items = (await uow.Repository().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items; + var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false); + var balances = (await uow.Repository().ListAsync(Query.For().Where(b => b.WarehouseId == warehouseId), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId); + var take = new StockTake + { + TakeDate = date, + WarehouseId = warehouseId, + CategoryId = categoryId, + Description = string.IsNullOrWhiteSpace(description) + ? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + : description.Trim()[..Math.Min(description.Trim().Length, 100)], + Status = StockTakeStatus.Open, + }; + await uow.Repository().InsertAsync(take, cancellationToken).ConfigureAwait(false); + var lines = uow.Repository(); + var order = 0; + foreach (var item in items) + { + await lines.InsertAsync( + new StockTakeLine + { + StockTakeId = take.Id, + ItemId = item.Id, + BookQuantity = book.GetValueOrDefault(item.Id), + UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m, + SortOrder = ++order, + }, + cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!; + } + + /// Writes the counts typed on the list; an empty count means not counted yet. + /// Who counts. + /// The company. + /// The stock take. + /// The counted quantity of each line, by line. + /// Cancellation. + /// The stock take. + public async Task SaveCountsAsync( + Actor actor, string companyCode, long id, IReadOnlyDictionary counts, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(counts); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + if (counts.Values.Any(v => v < 0m)) + { + throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + foreach (var line in (await repository.ListAsync(Query.For().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items) + { + if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity) + { + line.CountedQuantity = counted; + await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + } + + /// + /// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the + /// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up. + /// + /// Who counts. + /// The company. + /// The stock take. + /// The file. + /// Cancellation. + /// How many lines were counted and the codes not on the list. + public async Task ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen); + var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase); + var counts = new Dictionary(); + var unknown = new List(); + using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + var row = 0; + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text) + { + row++; + if (ParseCount(text) is not { } parsed) + { + continue; + } + + var (code, quantity) = parsed; + + if (byCode.TryGetValue(code, out var lineId)) + { + counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity; + } + else + { + unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code); + } + } + + if (counts.Count > 0) + { + await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false); + } + + return new StockCountImport(counts.Count, unknown); + } + + /// + /// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost + /// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as + /// they are. + /// + /// Who posts: needs inventory.entry.post. + /// The company. + /// The stock take. + /// Cancellation. + /// The stock take as posted. + public async Task PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false); + StockTakeView view; + long? gainReason, lossReason; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id; + lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id; + } + + if (view.Counted == 0) + { + throw new ValidationFailedException([":" + NothingCounted]); + } + + if (gainReason is null || lossReason is null) + { + throw new ValidationFailedException([":" + ReasonMissing]); + } + + var take = view.Take; + var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList(); + var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList(); + take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false); + take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false); + take.Status = StockTakeStatus.Posted; + take.PostedAt = _clock.GetUtcNow().UtcDateTime; + take.PostedBy = actor.UserName; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.Repository().UpdateAsync(take, cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + } + } + + /// Cancels an open stock take; its counts stay for the record. + /// Who cancels. + /// The company. + /// The stock take. + /// Cancellation. + /// A task. + public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + take.Status = StockTakeStatus.Cancelled; + await uow.Repository().UpdateAsync(take, cancellationToken).ConfigureAwait(false); + } + + /// A code and a quantity from a row of a count file, or none for a header or an empty row. + /// The row. + /// The code and the quantity. + public static (string Code, decimal Quantity)? ParseCount(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ','; + var parts = text.Split(separator, StringSplitOptions.TrimEntries); + if (parts.Length < 2 || parts[0].Length == 0) + { + return null; + } + + var number = parts[1].Trim('"'); + + // With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too. + var parsed = separator == ',' + ? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value) + : decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value); + return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null; + } + + // The quantity of each item in a warehouse at the end of a day. + internal static async Task> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync( + Query.For().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity)); + + private async Task AdjustAsync( + Actor actor, string company, StockTake take, long reasonId, List lines, CancellationToken cancellationToken) + { + if (lines.Count == 0) + { + return null; + } + + var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false); + entry.Header.DocumentDate = take.TakeDate; + entry.Header.InventoryReasonId = reasonId; + entry.Header.WarehouseId = take.WarehouseId; + entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description; + entry.Header.IsDemo = take.IsDemo; + foreach (var line in lines) + { + entry.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = line.Line.ItemId, + Description = line.Description, + UnitOfMeasureId = line.UnitOfMeasureId, + Quantity = Math.Abs(line.Line.Difference), + Price = line.Line.UnitCost, + WarehouseId = take.WarehouseId, + }); + } + + entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false); + return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id; + } + + private static async Task OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + var take = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen); + return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]); + } + + private static async Task ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take) + { + return null; + } + + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + var ids = lines.Select(l => l.ItemId).Distinct().ToList(); + var items = ids.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(i => i.Id); + return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item) + ? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId) + : new StockTakeLineView(l, "?", string.Empty, null))]); + } +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index ab6a824..f4ef55c 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy /// public sealed class JobScheduler { - /// The system tasks (M2, attachments trash from M3, ECB rates from M4). + /// The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6). public static readonly IReadOnlyList SystemTasks = [ new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), @@ -58,6 +58,7 @@ public sealed class JobScheduler new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800), new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true), + new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Core/Inventory/Inventory.cs b/src/Khaemhat.Core/Inventory/Inventory.cs index 506ea2e..c014963 100644 --- a/src/Khaemhat.Core/Inventory/Inventory.cs +++ b/src/Khaemhat.Core/Inventory/Inventory.cs @@ -148,9 +148,12 @@ public sealed class StockTake : Entity, IDemoMarkable /// The state. public StockTakeStatus Status { get; set; } - /// The warehouse entry with the adjustments, once posted. + /// The warehouse entry that loads what was found more than the books, once posted. public long? AdjustmentDocumentId { get; set; } + /// The warehouse entry that unloads what was found less than the books, once posted. + public long? LossDocumentId { get; set; } + /// When it was posted. public DateTime? PostedAt { get; set; } diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs index 10e1af3..c9952b8 100644 --- a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs @@ -106,6 +106,7 @@ public sealed class M20261113_001_CreateInventory : IMigration t.Int64("category_id"); t.String("status", 40).NotNull(); t.Int64("adjustment_document_id"); + t.Int64("loss_document_id"); t.DateTimeUtc("posted_at"); t.String("posted_by", 100); t.Text("notes"); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 5648763..d1de147 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -148,6 +148,9 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // The document engine (ADR 0032): one engine, the copies, a typed service per family. diff --git a/src/Khaemhat.Web/Resources/it-IT/Inventory.json b/src/Khaemhat.Web/Resources/it-IT/Inventory.json index 56c77ec..3fd6ec1 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Inventory.json +++ b/src/Khaemhat.Web/Resources/it-IT/Inventory.json @@ -13,5 +13,19 @@ "Hints": { "Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo." } + }, + "inventory": { + "stock-take": { + "not-open": "L'inventario è già stato registrato o annullato: non si può più modificare.", + "nothing-counted": "Non hai contato nessun articolo: inserisci almeno una quantità prima di registrare.", + "negative": "Una quantità contata non può essere negativa.", + "reason-missing": "Mancano le causali di rettifica inventariale INVP e INVN: aggiornale da Tabelle azienda, Aggiorna tabelle di base." + }, + "warehouse": { + "missing": "Il deposito non esiste più." + }, + "reorder": { + "choice-invalid": "Ogni riga da ordinare deve avere un fornitore e una quantità maggiore di zero." + } } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Purchases.json b/src/Khaemhat.Web/Resources/it-IT/Purchases.json index c79660a..faef5c5 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Purchases.json +++ b/src/Khaemhat.Web/Resources/it-IT/Purchases.json @@ -11,5 +11,16 @@ "SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.", "VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione." } + }, + "purchase": { + "self-invoice": { + "not-needed": "Per questa fattura non serve un'autofattura: il fornitore applica già l'IVA italiana." + } + }, + "incoming": { + "not-readable": "Il file non è una fattura elettronica leggibile: carica un XML FatturaPA, un file firmato .p7m o uno ZIP che li contiene.", + "not-invoice": "Il file XML non è una FatturaPA.", + "signature-broken": "La firma del file .p7m non è valida: il contenuto potrebbe essere stato alterato.", + "invalid": "La fattura elettronica non è conforme al tracciato FatturaPA." } } diff --git a/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs b/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs new file mode 100644 index 0000000..ffaf434 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs @@ -0,0 +1,197 @@ +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); + } +}