using Khaemhat.Application.Items; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Documents; using Khaemhat.Core.Inventory; using Khaemhat.Core.Items; using Khaemhat.Core.Parties; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.Inventory; /// What the stock screen asks (mockup 036). public sealed record StockFilter { /// Code, description or brand. public string? Search { get; init; } /// One warehouse, or all together. public long? WarehouseId { get; init; } /// One category. public long? CategoryId { get; init; } /// Only the items under their minimum stock or reorder point. public bool UnderstockOnly { get; init; } /// Also the items with nothing on hand, committed or ordered. public bool IncludeEmpty { get; init; } } /// The state of an item under its thresholds. public enum StockLevel { /// Enough. Ok = 0, /// The available quantity reached the reorder point. Reorder = 1, /// The available quantity is under the minimum stock. Understock = 2, /// Nothing left, or less than nothing. Out = 3, } /// A row of the stock screen: an item in one warehouse or in all. /// The item. /// Its code. /// Its description. /// Its category. /// Its base unit. /// On hand. /// Committed to customers. /// Ordered from suppliers. /// On hand less committed. /// The minimum stock. /// The reorder point. /// The weighted average cost (none without the permission on costs). /// The value at the average (none without the permission). /// The last load. /// The last unload. /// The state under the thresholds. public sealed record StockRow( long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available, decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level); /// A movement of an item, with the balance after it. /// The movement. /// The date. /// The family of the document. /// The document. /// Its kind. /// Its number. /// The warehouse reason. /// The customer or supplier. /// The warehouse. /// Positive loads, negative unloads. /// The cost (none without the permission). /// The value (none without the permission). /// The balance after the movement, in the warehouses shown. public sealed record MovementRow( long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId, decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance); /// The value of an item at a date (closing stock, libro inventari). /// The item. /// Its code. /// Its description. /// On hand at the date. /// The cost of the method. /// Quantity times cost. /// A (the first 80% of the value), B (up to 95%) or C. public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass); /// /// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item, /// the value at a date. The balances are kept by ; this service only reads them. /// /// Permission inventory.stock.read, movements inventory.entry.read; costs only with items.cost.read. public sealed class InventoryService { /// Permission to read the stock. public const string StockPermission = "inventory.stock.read"; /// Permission to read the movements. public const string EntryReadPermission = "inventory.entry.read"; /// Permission to post movements, stock takes and the rebuild. public const string PostPermission = "inventory.entry.post"; private readonly IUnitOfWorkFactory _factory; private readonly PermissionService _permissions; /// Creates the service. /// The units of work. /// The permissions. public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(permissions); _factory = factory; _permissions = permissions; } /// The stock of the items, in a warehouse or in all. /// Who reads. /// The company. /// What to show. /// Cancellation. /// The rows, by code. public async Task> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(filter); var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var query = Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled); if (filter.CategoryId is { } category) { query = query.Where(i => i.CategoryId == category); } if (filter.Search?.Trim() is { Length: > 0 } text) { query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text))); } var items = (await uow.Repository().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items; var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false); var rows = new List(); foreach (var item in items) { var mine = balances.GetValueOrDefault(item.Id) ?? []; var row = RowOf(item, mine, costs); if (!filter.IncludeEmpty && mine.Count == 0) { // No movement and no order: shown only when asked, or when it has a minimum to keep. if (row.Level == StockLevel.Ok) { continue; } } if (filter.UnderstockOnly && row.Level == StockLevel.Ok) { continue; } rows.Add(row); } return rows; } /// The balances of an item in each warehouse. /// Who reads. /// The company. /// The item. /// Cancellation. /// The balances, costs hidden without the permission. public async Task> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var rows = (await uow.Repository().ListAsync(Query.For().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items; if (!costs) { foreach (var row in rows) { row.AverageCost = 0m; row.Value = 0m; row.LastCost = null; } } return rows; } /// The movements of an item in a period, with the running balance (mockup 036, dialog of the item). /// Who reads. /// The company. /// The item. /// One warehouse, or all. /// The first day, or the beginning. /// The last day, or today. /// Cancellation. /// The movements, oldest first; the balance starts from what was on hand before . public async Task> MovementsAsync( Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false); var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var query = Query.For().Where(l => l.ItemId == itemId); if (warehouseId is { } warehouse) { query = query.Where(l => l.WarehouseId == warehouse); } var lines = (await uow.Repository().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) .ConfigureAwait(false)).Items; var entryIds = lines.Select(l => l.EntryId).Distinct().ToList(); var entries = entryIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(e => entryIds.Contains(e.Id)), cancellationToken) .ConfigureAwait(false)).Items.ToDictionary(e => e.Id); var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code); var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList(); var parties = partyIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken) .ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name); var result = new List(); var balance = 0m; foreach (var line in lines) { balance += line.Quantity; if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last)) { continue; } var entry = entries.GetValueOrDefault(line.EntryId); result.Add(new MovementRow( line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber, entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null, entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null, line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance)); } return result; } /// /// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day, /// valued with a method, with its ABC class by value. /// /// Who reads: needs the permission on costs too. /// The company. /// The day. /// One warehouse, or all. /// The cost used. /// Cancellation. /// The items with something on hand, by value. public async Task> ValuationAsync( Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); return await ValuationAsync(uow, date, warehouseId, method, cancellationToken).ConfigureAwait(false); } /// The value of the stock at a date inside a unit of work (the closing values the inventory with it). internal static async Task> ValuationAsync( IUnitOfWork uow, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken) { var lines = (await uow.Repository().ListAsync( Query.For().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) .ConfigureAwait(false)).Items; var itemIds = lines.Select(l => l.ItemId).Distinct().ToList(); var items = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) .ConfigureAwait(false)).Items.ToDictionary(i => i.Id); var rows = new List(); foreach (var group in lines.GroupBy(l => l.ItemId)) { if (!items.TryGetValue(group.Key, out var item)) { continue; } // The costs written on the movements are those of the last run: the history up to the day gives the average then. var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m); var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand; if (quantity == 0m) { continue; } var cost = method switch { StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost, StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost, _ => history.AverageCost, }; rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C')); } return Classify(rows); } /// The items under their thresholds, the most urgent first (dashboard widget and reorder). /// Who reads. /// The company. /// How many. /// Cancellation. /// The rows. public async Task> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default) { var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false); return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)]; } /// /// 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. /// /// On hand less committed. /// Ordered from suppliers. /// The minimum stock. /// The reorder point. /// The level. public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint) { var watched = minimum is not null || reorderPoint is not null; if (available < 0m || (watched && available <= 0m)) { return StockLevel.Out; } if (minimum is { } min && available < min) { return StockLevel.Understock; } return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok; } /// Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest. /// The rows. /// The rows by value, with their class. public static IReadOnlyList Classify(IEnumerable rows) { ArgumentNullException.ThrowIfNull(rows); var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList(); var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value); var running = 0m; var result = new List(sorted.Count); foreach (var row in sorted) { // The class of an item is where its value starts: the first item is always A. var share = total <= 0m ? 1m : running / total; running += Math.Max(row.Value, 0m); result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' }); } return result; } internal static StockRow RowOf(Item item, IReadOnlyList balances, bool costs) { var onHand = balances.Sum(b => b.OnHand); var committed = balances.Sum(b => b.Committed); var ordered = balances.Sum(b => b.Ordered); var available = onHand - committed; var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m; return new StockRow( item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint, costs ? average : null, costs ? balances.Sum(b => b.Value) : null, balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate), LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint)); } internal static async Task>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken) { var query = Query.For(); if (warehouseId is { } warehouse) { query = query.Where(b => b.WarehouseId == warehouse); } return (await uow.Repository().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items .GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList()); } private async Task CostsAsync(Actor actor, CancellationToken cancellationToken) => (await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed; }