Files
Khaemhat/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor
T
Alby96andClaude Opus 5.5 ced689b297 feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)
Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:01:32 +01:00

525 lines
24 KiB
Plaintext

@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. *@
<KhPageTitle Text="@Title" Icon="file-check" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else if (Id is null)
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Inventory.StockTake.New"]" Icon="plus">
@if (CanWrite)
{
<KhForm Layout="KhFormLayout.Grid" Validation="_validation" Class="kh-import-options">
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_warehouses" Value="@PartyScreens.Text(_warehouse)"
ValueChanged="v => _warehouse = PartyScreens.Id(v)" Span="12" Required="true" />
<KhDateBox Label="@T["Inventory.StockTake.Date"]" Name="TakeDate" Value="_date" ValueChanged="v => _date = v" Span="6" Required="true" />
<KhSelect TValue="string" Label="@T["Items.Radar.Category"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Inventory.StockTake.AllCategories"]"
Value="@PartyScreens.Text(_category)" ValueChanged="v => _category = PartyScreens.Id(v)" Span="6" />
<KhTextBox Label="@T["Inventory.StockTake.Description"]" Name="Description" Value="@_description" ValueChanged="v => _description = v" Span="12"
Hint="@T["Inventory.StockTake.DescriptionHint"]" />
<div class="c12 kh-endrow">
<button type="button" class="btn primary" disabled="@(_busy || _warehouse is null || _date is null)" @onclick="CreateAsync">
<KhIcon Name="file-check" /> @T["Inventory.StockTake.Open"]
</button>
</div>
</KhForm>
}
<p class="muted sm kh-pad">@T["Inventory.StockTake.Hint"]</p>
</KhPanel>
</div>
<div class="kh-import-main">
<KhPanel Title="@T["Inventory.StockTake.List"]" Icon="list">
@if (_takes.Count == 0)
{
<p class="muted kh-pad">@T["Inventory.StockTake.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Inventory.StockTake.List"]">
<thead>
<tr>
<th scope="col">@T["Inventory.StockTake.Date"]</th>
<th scope="col">@T["Inventory.StockTake.Description"]</th>
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
<th scope="col">@T["Items.Radar.State"]</th>
</tr>
</thead>
<tbody>
@foreach (var take in _takes)
{
<tr>
<td>@T.Date(take.TakeDate)</td>
<td><a href="magazzino/inventario/@take.Id">@take.Description</a></td>
<td>@PartyScreens.Describe(_warehouses, take.WarehouseId)</td>
<td><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
</div>
</div>
}
else if (_view is null)
{
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Inventory.StockTake.Missing"]</h1><p><a href="magazzino/inventario">@T["Inventory.StockTake.List"]</a></p></div>
}
else
{
var take = _view.Take;
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@take.Description" Icon="file-check">
<KhVSteps Items="Steps" Current="Step" Label="@T["Inventory.StockTake.Procedure"]" />
<dl class="kh-facts">
<dt>@T["Inventory.Fields.Warehouse"]</dt><dd>@PartyScreens.Describe(_warehouses, take.WarehouseId)</dd>
<dt>@T["Inventory.StockTake.Date"]</dt><dd>@T.Date(take.TakeDate)</dd>
<dt>@T["Items.Radar.Category"]</dt><dd>@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])</dd>
<dt>@T["Items.Radar.State"]</dt><dd><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></dd>
@if (take.Status == StockTakeStatus.Posted)
{
<dt>@T["Inventory.StockTake.Movements"]</dt>
<dd>
@if (take.AdjustmentDocumentId is { } gain)
{
<a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, gain)">@StockTakeService.GainReason</a>
}
@if (take.LossDocumentId is { } loss)
{
<span> </span><a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, loss)">@StockTakeService.LossReason</a>
}
</dd>
}
</dl>
@if (IsOpen && CanWrite)
{
<div class="kh-endrow kh-pad">
<button type="button" class="btn" disabled="@_busy" @onclick="CancelAsync"><KhIcon Name="x-circle" /> @T["Inventory.StockTake.Cancel"]</button>
</div>
}
</KhPanel>
</div>
<div class="kh-import-main">
<KhStrip Items="Stats" Label="@T["Inventory.StockTake.Procedure"]" />
<KhPanel Title="@T["Inventory.StockTake.Lines"]" Icon="list">
<Actions>
<input type="search" class="in kh-searchbox" placeholder="@T["Inventory.Stock.Search"]" aria-label="@T["Inventory.Stock.Search"]"
value="@_search" @oninput="e => _search = e.Value?.ToString()" />
<select class="in" aria-label="@T["Inventory.StockTake.Show"]" @onchange="e => _show = e.Value?.ToString() ?? string.Empty">
<option value="" selected="@(_show.Length == 0)">@T["Inventory.StockTake.ShowAll"]</option>
<option value="todo" selected="@(_show == "todo")">@T["Inventory.StockTake.ShowToCount"]</option>
<option value="diff" selected="@(_show == "diff")">@T["Inventory.StockTake.ShowDifferences"]</option>
</select>
@if (IsOpen && CanWrite)
{
<label class="btn kh-filebtn">
<KhIcon Name="upload" /> @T["Inventory.StockTake.Import"]
<InputFile OnChange="ImportAsync" accept=".csv,.txt,text/csv,text/plain" disabled="@_busy" />
</label>
<button type="button" class="btn" disabled="@(_busy || _counts.Count == 0)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Inventory.StockTake.Save"]</button>
@if (Session.Permissions.Allows(InventoryService.PostPermission))
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="PostAsync"><KhIcon Name="check-circle" /> @T["Inventory.StockTake.Post"]</button>
}
}
</Actions>
<ChildContent>
<div class="gridwrap kh-taketable">
<table class="grid" aria-label="@T["Inventory.StockTake.Lines"]">
<thead>
<tr>
<th scope="col">@T["Items.Fields.Code"]</th>
<th scope="col">@T["Items.Fields.Description"]</th>
<th scope="col">@T["Items.Radar.Unit"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Book"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Counted"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Difference"]</th>
@if (_costs)
{
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.DifferenceValue"]</th>
}
<th scope="col">@T["Items.Radar.State"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in Shown)
{
var id = line.Line.Id;
var counted = CountOf(line);
var difference = counted is { } c ? c - line.Line.BookQuantity : 0m;
<tr class="@(counted is not null && difference != 0m ? "hl" : null)">
<td class="code">@line.Code</td>
<td>@line.Description</td>
<td>@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)</td>
<td class="num">@Qty(line.Line.BookQuantity)</td>
<td class="num">
@if (IsOpen && CanWrite)
{
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.StockTake.Counted"] + " " + line.Code)"
value="@(counted is { } v ? Qty(v) : null)" @onchange="e => SetCount(id, e.Value?.ToString())" />
}
else
{
@(counted is { } v ? Qty(v) : "—")
}
</td>
<td class="num @(difference < 0m ? "err" : difference > 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))</td>
@if (_costs)
{
<td class="num">@T.Money(line.Line.UnitCost)</td>
<td class="num">@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2)))</td>
}
<td>
@if (counted is null)
{
<KhBadge Tone="KhTone.Neutral">@T["Inventory.StockTake.ToCount"]</KhBadge>
}
else if (difference == 0m)
{
<KhBadge Tone="KhTone.Ok">@T["Inventory.StockTake.Matches"]</KhBadge>
}
else
{
<KhBadge Tone="KhTone.Warning">@T["Inventory.StockTake.Differs"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</ChildContent>
</KhPanel>
</div>
</div>
}
@code {
private readonly KhValidation _validation = new();
private readonly Dictionary<long, decimal?> _counts = [];
private IReadOnlyList<StockTake> _takes = [];
private IReadOnlyList<KhOption<string>> _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;
/// <summary>The stock take shown, or none for the list.</summary>
[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<KhStep> 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<KhStat> 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<KhStat>(),
];
}
}
private IEnumerable<StockTakeLineView> 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,
});
/// <inheritdoc />
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<long?> DefaultWarehouseAsync(Actor actor, string company) =>
(await Tables.ActiveAsync<Warehouse>(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)));
}