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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 22:01:32 +01:00
1 parent eb301fa570
commit ced689b297
31 files changed
+3478 -110

No files matched your search

@@ -0,0 +1,450 @@
@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. *@
<KhPageTitle Text="@T["Inventory.Stock.Title"]" Icon="box" />
@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.StockPermission))
{
<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
{
<KhStrip Items="Stats" Label="@T["Inventory.Stock.Title"]" />
<KhForm Layout="KhFormLayout.Grid" Class="kh-pagefilters">
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="Warehouse" Options="_warehouses" Empty="@T["Inventory.Stock.AllWarehouses"]"
Value="@PartyScreens.Text(_warehouse)" ValueChanged="SetWarehouseAsync" Span="4" />
<KhCheck Label="@T["Inventory.Stock.IncludeEmpty"]" Name="IncludeEmpty" Value="_includeEmpty" ValueChanged="SetIncludeEmptyAsync" Span="4" />
</KhForm>
<KhRadar TItem="StockRow" @ref="_radar" Id="stock" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="false" OnOpen="OpenMovementsAsync"
QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Inventory.Stock.Search"]" ExportName="giacenze" Label="@T["Inventory.Stock.Title"]">
<Toolbar>
<a class="btn" href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Shell.Menu.Inventory.Reorder"]</a>
<a class="btn" href="magazzino/inventario"><KhIcon Name="file-check" /> @T["Shell.Menu.Inventory.StockTake"]</a>
@if (_costs)
{
<button type="button" class="btn" @onclick="OpenValuation"><KhIcon Name="euro" /> @T["Inventory.Valuation.Title"]</button>
}
@if (Session.Permissions.Allows(InventoryService.PostPermission))
{
<button type="button" class="btn" disabled="@_busy" @onclick="RebuildAsync"><KhIcon Name="layers" /> @T["Inventory.Rebuild.Action"]</button>
}
</Toolbar>
</KhRadar>
@if (_rebuild is { } progress)
{
<div class="callout info kh-pad" role="status">
<KhIcon Name="layers" />
<span>@T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total))</span>
</div>
}
<KhDialog Open="_item is not null" Title="@MovementsTitle" Icon="layers" Size="lg" OnClose="() => _item = null">
<ChildContent>
@if (_balances is { Count: > 1 })
{
<KhStrip Items="BalanceStats" Label="@T["Inventory.Movements.ByWarehouse"]" />
}
@if (_movements is null)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (_movements.Count == 0)
{
<p class="muted kh-pad">@T["Inventory.Movements.None"]</p>
}
else
{
<div class="gridwrap kh-dialoggrid">
<table class="grid" aria-label="@T["Inventory.Movements.Title"]">
<thead>
<tr>
<th scope="col">@T["Inventory.Movements.Date"]</th>
<th scope="col">@T["Inventory.Movements.Document"]</th>
<th scope="col">@T["Inventory.Fields.Reason"]</th>
<th scope="col">@T["Inventory.Movements.Party"]</th>
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
@if (_costs)
{
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
}
<th scope="col" class="num">@T["Inventory.Movements.Balance"]</th>
</tr>
</thead>
<tbody>
@foreach (var move in _movements)
{
<tr>
<td>@T.Date(move.Date)</td>
<td class="code">
@if (move.Kind is { } kind && move.DocumentId is { } document)
{
<a href="@SalesScreens.RecordUrl(kind, document)">@T["Sales.Kinds." + kind] @move.Number</a>
}
</td>
<td class="code">@move.ReasonCode</td>
<td>@move.PartyName</td>
<td>@PartyScreens.Describe(_warehouses, move.WarehouseId)</td>
<td class="num @(move.Quantity < 0m ? "err" : "ok")">@Qty(move.Quantity)</td>
@if (_costs)
{
<td class="num">@Cost(move.UnitCost)</td>
}
<td class="num"><b>@Qty(move.Balance)</b></td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
<Footer>
@if (_item is { } item)
{
<a class="btn" href="@ItemScreens.RecordUrl(item.ItemId)"><KhIcon Name="box" /> @T["Inventory.Movements.OpenItem"]</a>
}
<button type="button" class="btn primary" @onclick="() => _item = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_valuationOpen" Title="@T["Inventory.Valuation.Title"]" Icon="euro" Size="lg" OnClose="() => _valuationOpen = false">
<ChildContent>
<KhForm Layout="KhFormLayout.Grid">
<KhDateBox Label="@T["Inventory.Valuation.Date"]" Name="ValuationDate" Value="_valuationDate" ValueChanged="v => _valuationDate = v" Span="4" Required="true" />
<KhSelect TValue="string" Label="@T["Inventory.Valuation.Method"]" Name="Method" Options="Methods" Value="@_method.ToString()" Span="4"
ValueChanged="SetMethod" />
<div class="c4 kh-endrow">
<button type="button" class="btn primary" disabled="@_busy" @onclick="ValueAsync"><KhIcon Name="chart" /> @T["Inventory.Valuation.Compute"]</button>
</div>
</KhForm>
@if (_valuation is { } rows)
{
<KhStrip Items="ValuationStats" Label="@T["Inventory.Valuation.Title"]" />
<div class="gridwrap kh-dialoggrid">
<table class="grid" aria-label="@T["Inventory.Valuation.Title"]">
<thead>
<tr>
<th scope="col">@T["Items.Fields.Code"]</th>
<th scope="col">@T["Items.Fields.Description"]</th>
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
<th scope="col" class="num">@T["Inventory.Stock.Value"]</th>
<th scope="col">@T["Inventory.Valuation.Class"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in rows)
{
<tr>
<td class="code">@row.Code</td>
<td>@row.Description</td>
<td class="num">@Qty(row.Quantity)</td>
<td class="num">@T.Money(row.UnitCost)</td>
<td class="num">@T.Money(row.Value)</td>
<td><KhBadge Tone="@(row.AbcClass switch { 'A' => KhTone.Ok, 'B' => KhTone.Info, _ => KhTone.Neutral })">@row.AbcClass</KhBadge></td>
</tr>
}
</tbody>
</table>
</div>
}
<p class="muted sm">@T["Inventory.Valuation.Hint"]</p>
</ChildContent>
<Footer>
<button type="button" class="btn primary" @onclick="() => _valuationOpen = false">@T["Common.Close"]</button>
</Footer>
</KhDialog>
}
@code {
private static readonly ListFields<StockRow> Fields = new ListFields<StockRow>()
.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<StockRow> _source = new([], Fields);
private IReadOnlyList<StockRow> _rows = [];
private ItemLookups _lookups = ItemLookups.Empty;
private IReadOnlyList<KhOption<string>> _warehouses = [];
private KhRadar<StockRow>? _radar;
private long? _warehouse;
private bool _includeEmpty;
private bool _costs;
private bool _loaded;
private bool _busy;
private RebuildProgress? _rebuild;
private StockRow? _item;
private IReadOnlyList<MovementRow>? _movements;
private IReadOnlyList<ItemBalance>? _balances;
private bool _valuationOpen;
private DateOnly? _valuationDate;
private StockValuationMethod _method = StockValuationMethod.WeightedAverage;
private IReadOnlyList<ValuationRow>? _valuation;
/// <summary>An item to open at once, from the dashboard.</summary>
[SupplyParameterFromQuery(Name = "articolo")]
public long? ItemId { get; set; }
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStat> 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<KhStat>(),
];
private IReadOnlyList<KhStat> BalanceStats => _balances is null ? [] :
[.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))];
private IReadOnlyList<KhStat> 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<KhOption<string>> 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<KhColumn<StockRow>> 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 => @<KhBadge Tone="ToneOf(r.Level)">@T["Inventory.Levels." + r.Level]</KhBadge>,
},
];
private IReadOnlyList<KhQuickFilter> 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<StockLevel>().Select(l => new KhOption<string>(l.ToString(), T["Inventory.Levels." + l])),
]),
];
/// <inheritdoc />
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<StockRow>(_rows, Fields);
}
private Task<ListPage<StockRow>> 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<StockValuationMethod>(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<RebuildProgress>(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;
}
}
}