@page "/magazzino/inventario" @page "/magazzino/inventario/{Id:long}" @attribute [Authorize] @using Khaemhat.Application.Documents @using Khaemhat.Application.Inventory @using Khaemhat.Application.Items @using Khaemhat.Application.Security @using Khaemhat.Application.Tables @using Khaemhat.Core.Documents @using Khaemhat.Core.Inventory @using Khaemhat.Core.Tables @using Khaemhat.Web.Documents @using Khaemhat.Web.Items @using Khaemhat.Web.Parties @using Khaemhat.Web.Tables @inject ShellSession Session @inject StockTakeService StockTakes @inject ItemService Items @inject TableService Tables @inject ToastService Toasts @inject DialogService Dialogs @inject NavigationManager Navigation @inject TimeProvider Clock @* The physical stock take (SPEC §11.6, mockup 038): opened on a warehouse at a date (and perhaps a category), it freezes the book quantity and cost of each item; the counts are typed on the list or read from a scanner file; posting turns the differences into gain and loss movements at the date of the count. *@ @if (!_loaded) {

@T["Common.Loading"]

} else if (Session.Company is null) {

@T["Inventory.NoCompany"]

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

@T["Pages.AccessDenied.Title"]

@T["Pages.AccessDenied.Lead"]

} else if (Id is null) {
@if (CanWrite) {
}

@T["Inventory.StockTake.Hint"]

@if (_takes.Count == 0) {

@T["Inventory.StockTake.None"]

} else {
@foreach (var take in _takes) { }
@T["Inventory.StockTake.Date"] @T["Inventory.StockTake.Description"] @T["Inventory.Fields.Warehouse"] @T["Items.Radar.State"]
@T.Date(take.TakeDate) @take.Description @PartyScreens.Describe(_warehouses, take.WarehouseId) @T["Inventory.StockTake.States." + take.Status]
}
} else if (_view is null) {

@T["Inventory.StockTake.Missing"]

@T["Inventory.StockTake.List"]

} else { var take = _view.Take;
@T["Inventory.Fields.Warehouse"]
@PartyScreens.Describe(_warehouses, take.WarehouseId)
@T["Inventory.StockTake.Date"]
@T.Date(take.TakeDate)
@T["Items.Radar.Category"]
@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])
@T["Items.Radar.State"]
@T["Inventory.StockTake.States." + take.Status]
@if (take.Status == StockTakeStatus.Posted) {
@T["Inventory.StockTake.Movements"]
@if (take.AdjustmentDocumentId is { } gain) { @StockTakeService.GainReason } @if (take.LossDocumentId is { } loss) { @StockTakeService.LossReason }
}
@if (IsOpen && CanWrite) {
}
@if (IsOpen && CanWrite) { @if (Session.Permissions.Allows(InventoryService.PostPermission)) { } }
@if (_costs) { } @foreach (var line in Shown) { var id = line.Line.Id; var counted = CountOf(line); var difference = counted is { } c ? c - line.Line.BookQuantity : 0m; @if (_costs) { } }
@T["Items.Fields.Code"] @T["Items.Fields.Description"] @T["Items.Radar.Unit"] @T["Inventory.StockTake.Book"] @T["Inventory.StockTake.Counted"] @T["Inventory.StockTake.Difference"]@T["Inventory.Movements.UnitCost"] @T["Inventory.StockTake.DifferenceValue"]@T["Items.Radar.State"]
@line.Code @line.Description @PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId) @Qty(line.Line.BookQuantity) @if (IsOpen && CanWrite) { } else { @(counted is { } v ? Qty(v) : "—") } 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))@T.Money(line.Line.UnitCost) @(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2))) @if (counted is null) { @T["Inventory.StockTake.ToCount"] } else if (difference == 0m) { @T["Inventory.StockTake.Matches"] } else { @T["Inventory.StockTake.Differs"] }
} @code { private readonly KhValidation _validation = new(); private readonly Dictionary _counts = []; private IReadOnlyList _takes = []; private IReadOnlyList> _warehouses = []; private ItemLookups _lookups = ItemLookups.Empty; private StockTakeView? _view; private long? _warehouse; private long? _category; private DateOnly? _date; private string? _description; private string? _search; private string _show = string.Empty; private bool _costs; private bool _loaded; private bool _busy; /// The stock take shown, or none for the list. [Parameter] public long? Id { get; set; } private string Title => _view?.Take.Description is { } description && Id is not null ? description : T["Inventory.StockTake.Title"]; private bool CanWrite => Session.Permissions.Allows("inventory.entry.write"); private bool IsOpen => _view?.Take.Status == StockTakeStatus.Open; private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); private IReadOnlyList Steps => [ new(T["Inventory.StockTake.Steps.Open"], T["Inventory.StockTake.Steps.OpenDetail"]), new(T["Inventory.StockTake.Steps.Count"], T["Inventory.StockTake.Steps.CountDetail"]), new(T["Inventory.StockTake.Steps.Check"], T["Inventory.StockTake.Steps.CheckDetail"]), new(T["Inventory.StockTake.Steps.Post"], T["Inventory.StockTake.Steps.PostDetail"]), ]; private int Step => _view is null ? 0 : _view.Take.Status != StockTakeStatus.Open ? 4 : Counted == 0 ? 1 : Counted < _view.Lines.Count ? 1 : 2; private int Counted => _view?.Lines.Count(l => CountOf(l) is not null) ?? 0; private IReadOnlyList Stats { get { if (_view is null) { return []; } var counted = _view.Lines.Where(l => CountOf(l) is not null).ToList(); var differences = counted.Where(l => CountOf(l) != l.Line.BookQuantity).ToList(); var value = differences.Sum(l => Math.Round((CountOf(l)!.Value - l.Line.BookQuantity) * l.Line.UnitCost, 2)); return [ new(T["Inventory.StockTake.Items"], T.Number(_view.Lines.Count)), new(T["Inventory.StockTake.CountedItems"], T.Number(counted.Count), counted.Count == _view.Lines.Count ? KhTone.Ok : KhTone.Neutral), new(T["Inventory.StockTake.Differences"], T.Number(differences.Count), differences.Count > 0 ? KhTone.Warning : KhTone.Neutral), .. _costs ? [new KhStat(T["Inventory.StockTake.DifferenceValue"], T.Money(value), value < 0m ? KhTone.Error : KhTone.Neutral)] : Array.Empty(), ]; } } private IEnumerable Shown => (_view?.Lines ?? []).Where(l => (string.IsNullOrWhiteSpace(_search) || l.Code.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase) || l.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase)) && _show switch { "todo" => CountOf(l) is null, "diff" => CountOf(l) is { } c && c != l.Line.BookQuantity, _ => true, }); /// protected override async Task OnParametersSetAsync() { await Session.EnsureLoadedAsync(); if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.EntryReadPermission)) { if (!_loaded) { _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))]; _warehouse = await DefaultWarehouseAsync(actor, company); _costs = await Items.CanSeeCostsAsync(actor, company); _date = Today; } _counts.Clear(); if (Id is { } id) { _view = await StockTakes.GetAsync(actor, company, id); } else { _view = null; _takes = await StockTakes.ListAsync(actor, company); } } _loaded = true; } private async Task DefaultWarehouseAsync(Actor actor, string company) => (await Tables.ActiveAsync(actor, company)).OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; private decimal? CountOf(StockTakeLineView line) => _counts.TryGetValue(line.Line.Id, out var count) ? count : line.Line.CountedQuantity; private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); private static KhTone ToneOf(StockTakeStatus status) => status switch { StockTakeStatus.Posted => KhTone.Ok, StockTakeStatus.Cancelled => KhTone.Neutral, _ => KhTone.Info, }; private void SetCount(long lineId, string? text) { if (string.IsNullOrWhiteSpace(text)) { _counts[lineId] = null; return; } if (decimal.TryParse(text.Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) && value >= 0m) { _counts[lineId] = value; } else { Toasts.Show(ToastKind.Error, T["inventory.stock-take.negative"]); } } private async Task CreateAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _warehouse is not { } warehouse || _date is not { } date) { return; } _busy = true; try { var view = await StockTakes.CreateAsync(actor, company, warehouse, date, _category, _description); Toasts.Show(ToastKind.Success, T.Format("Inventory.StockTake.Opened", view.Lines.Count)); Navigation.NavigateTo("magazzino/inventario/" + view.Take.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); } catch (ValidationFailedException ex) { ShowErrors(ex); } finally { _busy = false; } } private async Task SaveAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id || _counts.Count == 0) { return; } _busy = true; try { _view = await StockTakes.SaveCountsAsync(actor, company, id, _counts); _counts.Clear(); Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Saved"]); } catch (ValidationFailedException ex) { ShowErrors(ex); } finally { _busy = false; } } private async Task ImportAsync(InputFileChangeEventArgs e) { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) { return; } _busy = true; try { if (_counts.Count > 0) { await StockTakes.SaveCountsAsync(actor, company, id, _counts); _counts.Clear(); } using var buffer = new MemoryStream(); await using (var stream = e.File.OpenReadStream(5 * 1024 * 1024)) { await stream.CopyToAsync(buffer); } buffer.Position = 0; var result = await StockTakes.ImportCountsAsync(actor, company, id, buffer); _view = await StockTakes.GetAsync(actor, company, id); Toasts.Show(result.Unknown.Count == 0 ? ToastKind.Success : ToastKind.Warning, T.Format("Inventory.StockTake.Imported", result.Applied, result.Unknown.Count) + (result.Unknown.Count == 0 ? string.Empty : " " + string.Join(", ", result.Unknown.Take(5)))); } catch (ValidationFailedException ex) { ShowErrors(ex); } catch (IOException) { Toasts.Show(ToastKind.Error, T["Inventory.StockTake.FileTooLarge"]); } finally { _busy = false; } } private async Task PostAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) { return; } if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.PostTitle"], T["Inventory.StockTake.PostText"], T["Inventory.StockTake.Post"], T["Common.Cancel"]))) { return; } _busy = true; try { if (_counts.Count > 0) { await StockTakes.SaveCountsAsync(actor, company, id, _counts); _counts.Clear(); } _view = await StockTakes.PostAsync(actor, company, id); Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Posted"]); } catch (ValidationFailedException ex) { ShowErrors(ex); } catch (InvalidDocumentActionException) { Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); } finally { _busy = false; } } private async Task CancelAsync() { if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) { return; } if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.CancelTitle"], T["Inventory.StockTake.CancelText"], T["Inventory.StockTake.Cancel"], T["Common.Back"], Danger: true))) { return; } await StockTakes.CancelAsync(actor, company, id); _view = await StockTakes.GetAsync(actor, company, id); } private void ShowErrors(ValidationFailedException ex) => Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); }