@page "/magazzino/giacenze" @attribute [Authorize] @using Khaemhat.Application.Inventory @using Khaemhat.Application.Items @using Khaemhat.Application.Tables @using Khaemhat.Core.Inventory @using Khaemhat.Core.Tables @using Khaemhat.Web.Documents @using Khaemhat.Web.Items @using Khaemhat.Web.Parties @inject ShellSession Session @inject InventoryService Inventory @inject ItemService Items @inject TableService Tables @inject ToastService Toasts @inject DialogService Dialogs @inject TimeProvider Clock @* Stock and availability (SPEC §11.6, mockup 036): every stocked item with on hand, committed, ordered and available, its thresholds and, for who may see costs, the average cost and the value; the state under the thresholds. One warehouse or all together. The movements of an item with their running balance; the value at a date with the ABC classes; the rebuild of the warehouse from its documents. *@ @if (!_loaded) {

@T["Common.Loading"]

} else if (Session.Company is null) {

@T["Inventory.NoCompany"]

} else if (!Session.Permissions.Allows(InventoryService.StockPermission)) {

@T["Pages.AccessDenied.Title"]

@T["Pages.AccessDenied.Lead"]

} else { @T["Shell.Menu.Inventory.Reorder"] @T["Shell.Menu.Inventory.StockTake"] @if (_costs) { } @if (Session.Permissions.Allows(InventoryService.PostPermission)) { } @if (_rebuild is { } progress) {
@T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total))
} @if (_balances is { Count: > 1 }) { } @if (_movements is null) {

@T["Common.Loading"]

} else if (_movements.Count == 0) {

@T["Inventory.Movements.None"]

} else {
@if (_costs) { } @foreach (var move in _movements) { @if (_costs) { } }
@T["Inventory.Movements.Date"] @T["Inventory.Movements.Document"] @T["Inventory.Fields.Reason"] @T["Inventory.Movements.Party"] @T["Inventory.Fields.Warehouse"] @T["Inventory.Movements.Quantity"]@T["Inventory.Movements.UnitCost"]@T["Inventory.Movements.Balance"]
@T.Date(move.Date) @if (move.Kind is { } kind && move.DocumentId is { } document) { @T["Sales.Kinds." + kind] @move.Number } @move.ReasonCode @move.PartyName @PartyScreens.Describe(_warehouses, move.WarehouseId) @Qty(move.Quantity)@Cost(move.UnitCost)@Qty(move.Balance)
}
@if (_valuation is { } rows) {
@foreach (var row in rows) { }
@T["Items.Fields.Code"] @T["Items.Fields.Description"] @T["Inventory.Movements.Quantity"] @T["Inventory.Movements.UnitCost"] @T["Inventory.Stock.Value"] @T["Inventory.Valuation.Class"]
@row.Code @row.Description @Qty(row.Quantity) @T.Money(row.UnitCost) @T.Money(row.Value) @row.AbcClass
}

@T["Inventory.Valuation.Hint"]

} @code { private static readonly ListFields Fields = new ListFields() .Add("code", r => r.Code, searchable: true) .Add("description", r => r.Description, searchable: true) .Add("category", r => r.CategoryId) .Add("unit", r => r.UnitOfMeasureId) .Add("onHand", r => r.OnHand) .Add("committed", r => r.Committed) .Add("ordered", r => r.Ordered) .Add("available", r => r.Available) .Add("minimum", r => r.MinimumStock) .Add("reorderPoint", r => r.ReorderPoint) .Add("averageCost", r => r.AverageCost) .Add("value", r => r.Value, total: true) .Add("lastLoad", r => r.LastLoad) .Add("lastUnload", r => r.LastUnload) .Add("level", r => r.Level) .OrderByDefault(new ListSort("code")); private InMemoryListSource _source = new([], Fields); private IReadOnlyList _rows = []; private ItemLookups _lookups = ItemLookups.Empty; private IReadOnlyList> _warehouses = []; private KhRadar? _radar; private long? _warehouse; private bool _includeEmpty; private bool _costs; private bool _loaded; private bool _busy; private RebuildProgress? _rebuild; private StockRow? _item; private IReadOnlyList? _movements; private IReadOnlyList? _balances; private bool _valuationOpen; private DateOnly? _valuationDate; private StockValuationMethod _method = StockValuationMethod.WeightedAverage; private IReadOnlyList? _valuation; /// An item to open at once, from the dashboard. [SupplyParameterFromQuery(Name = "articolo")] public long? ItemId { get; set; } private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); private IReadOnlyList Stats => [ new(T["Inventory.Stock.Items"], T.Number(_rows.Count(r => r.OnHand != 0m))), new(T["Inventory.Stock.Understock"], T.Number(_rows.Count(r => r.Level is StockLevel.Understock or StockLevel.Reorder)), _rows.Any(r => r.Level is StockLevel.Understock or StockLevel.Reorder) ? KhTone.Warning : KhTone.Neutral), new(T["Inventory.Stock.Out"], T.Number(_rows.Count(r => r.Level == StockLevel.Out)), _rows.Any(r => r.Level == StockLevel.Out) ? KhTone.Error : KhTone.Neutral), new(T["Inventory.Stock.Ordered"], T.Number(_rows.Count(r => r.Ordered > 0m))), .. _costs ? [new KhStat(T["Inventory.Stock.TotalValue"], T.Money(_rows.Sum(r => r.Value ?? 0m)))] : Array.Empty(), ]; private IReadOnlyList BalanceStats => _balances is null ? [] : [.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))]; private IReadOnlyList ValuationStats => _valuation is null ? [] : [ new(T["Inventory.Stock.Items"], T.Number(_valuation.Count)), new(T["Inventory.Stock.TotalValue"], T.Money(_valuation.Sum(r => r.Value))), new(T["Inventory.Valuation.ClassA"], T.Number(_valuation.Count(r => r.AbcClass == 'A'))), new(T["Inventory.Valuation.ClassB"], T.Number(_valuation.Count(r => r.AbcClass == 'B'))), new(T["Inventory.Valuation.ClassC"], T.Number(_valuation.Count(r => r.AbcClass == 'C'))), ]; private IReadOnlyList> Methods => [ new(nameof(StockValuationMethod.WeightedAverage), T["Inventory.Valuation.Methods.WeightedAverage"]), new(nameof(StockValuationMethod.LastCost), T["Inventory.Valuation.Methods.LastCost"]), new(nameof(StockValuationMethod.StandardCost), T["Inventory.Valuation.Methods.StandardCost"]), ]; private string MovementsTitle => _item is { } item ? item.Code + " · " + item.Description : T["Inventory.Movements.Title"]; private IReadOnlyList> Columns => [ new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" }, new("description", T["Items.Fields.Description"], r => r.Description), new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" }, new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "50px" }, new("onHand", T["Inventory.Stock.OnHand"], r => r.OnHand) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, new("committed", T["Inventory.Stock.Committed"], r => r.Committed) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, new("ordered", T["Inventory.Stock.OrderedColumn"], r => r.Ordered) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, new("available", T["Inventory.Stock.Available"], r => r.Available) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px", CellClass = r => r.Available < 0m ? "err" : null, }, new("minimum", T["Inventory.Stock.Minimum"], r => r.MinimumStock) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px" }, new("reorderPoint", T["Inventory.Stock.ReorderPoint"], r => r.ReorderPoint) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px", Visible = false }, new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "100px", Visible = _costs, Export = _costs }, new("value", T["Inventory.Stock.Value"], r => r.Value) { Kind = KhColumnKind.Money, Width = "110px", Visible = _costs, Export = _costs, Total = _costs }, new("lastLoad", T["Inventory.Stock.LastLoad"], r => r.LastLoad) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, new("lastUnload", T["Inventory.Stock.LastUnload"], r => r.LastUnload) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, new("level", T["Items.Radar.State"], r => T["Inventory.Levels." + r.Level]) { Width = "120px", Template = r => @@T["Inventory.Levels." + r.Level], }, ]; private IReadOnlyList QuickFilters => [ new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]), new("level", T["Items.Radar.State"], [ new(string.Empty, T["Items.Radar.All"]), .. Enum.GetValues().Select(l => new KhOption(l.ToString(), T["Inventory.Levels." + l])), ]), ]; /// protected override async Task OnInitializedAsync() { await Session.EnsureLoadedAsync(); if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission)) { _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); _warehouses = [.. (await Tables.ActiveAsync(actor, company)).Select(w => new KhOption(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))]; _costs = await Items.CanSeeCostsAsync(actor, company); _valuationDate = Today; await LoadAsync(); if (ItemId is { } id && _rows.FirstOrDefault(r => r.ItemId == id) is { } row) { await OpenMovementsAsync(row); } } _loaded = true; } private async Task LoadAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) { return; } _rows = await Inventory.StockAsync(actor, company, new StockFilter { WarehouseId = _warehouse, IncludeEmpty = _includeEmpty }); _source = new InMemoryListSource(_rows, Fields); } private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => _source.QueryAsync(query, cancellationToken); private async Task ReloadAsync() { await LoadAsync(); if (_radar is not null) { await _radar.ReloadAsync(); } } private async Task SetWarehouseAsync(string? value) { _warehouse = PartyScreens.Id(value); await ReloadAsync(); } private async Task SetIncludeEmptyAsync(bool value) { _includeEmpty = value; await ReloadAsync(); } private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); private string Cost(decimal? value) => value is { } cost ? T.Money(cost) : string.Empty; private static KhTone ToneOf(StockLevel level) => level switch { StockLevel.Out => KhTone.Error, StockLevel.Understock => KhTone.Warning, StockLevel.Reorder => KhTone.Info, _ => KhTone.Ok, }; private static string? RowClassOf(StockRow row) => row.Level is StockLevel.Out or StockLevel.Understock ? "hl" : null; private async Task OpenMovementsAsync(StockRow row) { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) { return; } _item = row; _movements = null; _balances = null; if (!Session.Permissions.Allows(InventoryService.EntryReadPermission)) { _movements = []; return; } _balances = await Inventory.BalancesAsync(actor, company, row.ItemId); _movements = await Inventory.MovementsAsync(actor, company, row.ItemId, _warehouse, null, null); } private void OpenValuation() { _valuation = null; _valuationOpen = true; } private void SetMethod(string? value) => _method = Enum.TryParse(value, out var method) ? method : StockValuationMethod.WeightedAverage; private async Task ValueAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _valuationDate is not { } date) { return; } _busy = true; try { _valuation = await Inventory.ValuationAsync(actor, company, date, _warehouse, _method); } finally { _busy = false; } } private async Task RebuildAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) { return; } if (!await Dialogs.ConfirmAsync(new(T["Inventory.Rebuild.Title"], T["Inventory.Rebuild.Text"], T["Inventory.Rebuild.Action"], T["Common.Cancel"]))) { return; } _busy = true; var progress = new Progress(p => { _rebuild = p; _ = InvokeAsync(StateHasChanged); }); try { var (documents, items) = await Task.Run(() => Inventory.RebuildAsync(actor, company, progress)); Toasts.Show(ToastKind.Success, T.Format("Inventory.Rebuild.Done", T.Number(documents), T.Number(items))); await ReloadAsync(); } finally { _busy = false; _rebuild = null; } } }