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

@@ -19,6 +19,9 @@
case WidgetIds.SystemStatus:
<SystemStatusWidget Definition="Definition" />
break;
case WidgetIds.Understock:
<UnderstockWidget Definition="Definition" />
break;
default:
<ComingWidget Definition="Definition" />
break;
@@ -0,0 +1,74 @@
@using Khaemhat.Application.Inventory
@inject ShellSession Session
@inject InventoryService Inventory
@* Sottoscorta (SPEC §10.3, §11.6): the items under their minimum stock or reorder point, the most urgent first, with a
link to the reorder proposal. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_rows is { Count: > 0 })
{
<span class="badge @(_rows.Any(r => r.Level == StockLevel.Out) ? "red" : "amber")">@T.Number(_rows.Count)</span>
}
</Actions>
<ChildContent>
@if (_failed)
{
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
}
else if (_rows is null)
{
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (_rows.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Dashboard.Widgets.Understock.Empty"]</p>
}
else
{
<div class="list kh-wlist">
@foreach (var row in _rows)
{
<a class="li" href="magazzino/giacenze?articolo=@row.ItemId">
<span class="kh-tone @(row.Level == StockLevel.Out ? "err" : "warn")" aria-hidden="true"></span>
<div class="grow">
<div class="t"><span class="code">@row.Code</span> @row.Description</div>
<div class="s">@T.Format("Dashboard.Widgets.Understock.Line", T.Number(row.Available), T.Number(row.MinimumStock ?? row.ReorderPoint ?? 0m))</div>
</div>
<span class="badge @(row.Level == StockLevel.Out ? "red" : "amber")">@T["Inventory.Levels." + row.Level]</span>
</a>
}
</div>
<div class="kh-wfoot"><a href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Dashboard.Widgets.Understock.Reorder"]</a></div>
}
</ChildContent>
</KhWidget>
@code {
private IReadOnlyList<StockRow>? _rows;
private bool _failed;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(InventoryService.StockPermission))
{
_rows = [];
return;
}
try
{
_rows = await Inventory.UnderstockAsync(actor, company, 8);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_failed = true;
}
}
}
@@ -46,7 +46,7 @@ public partial class ImportExportPage
private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null;
private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6";
private static string CheckOnlyMilestone => "M7";
private IReadOnlyList<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
@@ -0,0 +1,247 @@
@page "/magazzino/riordino"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Inventory
@using Khaemhat.Application.Items
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Documents
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Items
@using Khaemhat.Web.Parties
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject ReorderService Reorder
@inject PartyService Parties
@inject TableService Tables
@inject ToastService Toasts
@* The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
reorder point or the minimum stock, with the quantity to order and the usual supplier; the lines chosen, perhaps with
another quantity or supplier, become draft supplier orders, one per supplier. *@
<KhPageTitle Text="@T["Inventory.Reorder.Title"]" Icon="refresh" />
@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.Reorder.Title"]" />
@if (_orders.Count > 0)
{
<div class="callout ok kh-pad" role="status">
<KhIcon Name="check-circle" />
<span>
@T.Format("Inventory.Reorder.Created", _orders.Count)
@foreach (var order in _orders)
{
<span> </span><a href="@SalesScreens.RecordUrl(order.Record.Header.Kind, order.Record.Header.Id)">@order.Supplier</a>
}
</span>
</div>
}
<KhPanel Title="@T["Inventory.Reorder.Lines"]" Icon="list">
<Actions>
<span class="muted sm">@T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue))</span>
<button type="button" class="btn" disabled="@_busy" @onclick="LoadAsync"><KhIcon Name="refresh" /> @T["Inventory.Reorder.Refresh"]</button>
@if (CanOrder)
{
<button type="button" class="btn primary" disabled="@(_busy || !Chosen.Any())" @onclick="CreateAsync"><KhIcon Name="truck" /> @T["Inventory.Reorder.Create"]</button>
}
</Actions>
<ChildContent>
@if (_lines.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Inventory.Reorder.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Inventory.Reorder.Lines"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@_lines.All(l => l.Chosen)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<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.Stock.Available"]</th>
<th scope="col" class="num">@T["Inventory.Stock.OrderedColumn"]</th>
<th scope="col" class="num">@T["Inventory.Stock.Minimum"]</th>
<th scope="col" class="num">@T["Inventory.Stock.ReorderPoint"]</th>
<th scope="col" class="num">@T["Inventory.Reorder.Quantity"]</th>
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
<th scope="col">@T["Inventory.Reorder.Expected"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in _lines)
{
var row = line.Proposal;
<tr class="@(line.Chosen ? "sel" : null)">
<td class="kh-check"><input type="checkbox" checked="@line.Chosen" aria-label="@row.Code" @onchange="e => line.Chosen = e.Value is true" /></td>
<td class="code">@row.Code</td>
<td>@row.Description</td>
<td>@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)</td>
<td class="num @(row.Available < 0m ? "err" : null)">@Qty(row.Available)</td>
<td class="num">@Qty(row.Ordered)</td>
<td class="num">@(row.MinimumStock is { } m ? Qty(m) : null)</td>
<td class="num">@(row.ReorderPoint is { } p ? Qty(p) : null)</td>
<td class="num">
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.Reorder.Quantity"] + " " + row.Code)"
value="@Qty(line.Quantity)" @onchange="e => SetQuantity(line, e.Value?.ToString())" />
</td>
<td class="kh-cellpick">
<KhHotlink TItem="PartyRow" Name="@("Supplier" + row.ItemId)" Value="line.Supplier" ValueChanged="v => line.Supplier = v" Span="12"
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Inventory.Reorder.ChooseSupplier"]" />
</td>
<td class="num">@(row.Price is { } price ? T.Money(price) : null)</td>
<td>@(row.ExpectedDate is { } date ? T.Date(date) : null)</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
<p class="muted sm kh-pad">@T["Inventory.Reorder.Hint"]</p>
}
@code {
private List<Line> _lines = [];
private List<(DocumentRecord Record, string Supplier)> _orders = [];
private ItemLookups _lookups = ItemLookups.Empty;
private bool _loaded;
private bool _busy;
private bool CanOrder => Session.Permissions.Allows("purchases.order.write");
private IEnumerable<Line> Chosen => _lines.Where(l => l.Chosen && l.Supplier is not null && l.Quantity > 0m);
private decimal ChosenValue => Chosen.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2));
private IReadOnlyList<KhStat> Stats =>
[
new(T["Inventory.Reorder.Items"], T.Number(_lines.Count), _lines.Count > 0 ? KhTone.Warning : KhTone.Ok),
new(T["Inventory.Reorder.Suppliers"], T.Number(_lines.Where(l => l.Supplier is not null).Select(l => l.Supplier!.Id).Distinct().Count())),
new(T["Inventory.Reorder.Value"], T.Money(_lines.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)))),
new(T["Inventory.Reorder.WithoutSupplier"], T.Number(_lines.Count(l => l.Supplier is null)), _lines.Any(l => l.Supplier is null) ? KhTone.Warning : KhTone.Neutral),
];
/// <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);
await LoadAsync();
}
_loaded = true;
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var proposals = await Reorder.ProposalsAsync(actor, company);
var supplierIds = proposals.Where(p => p.SupplierId is not null).Select(p => p.SupplierId!.Value).Distinct().ToList();
var suppliers = Session.Permissions.Allows(PartyService.ReadPermission)
? (await Parties.RowsAsync(actor, company, supplierIds)).ToDictionary(r => r.Id)
: [];
_lines = [.. proposals.Select(p => new Line(p)
{
Quantity = p.Quantity,
Supplier = p.SupplierId is { } s ? suppliers.GetValueOrDefault(s) : null,
Chosen = p.SupplierId is not null,
})];
}
private async Task<IReadOnlyList<PartyRow>> SearchAsync(string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken)
: [];
private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture);
private void SetQuantity(Line line, string? text)
{
if (decimal.TryParse((text ?? string.Empty).Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value)
&& value >= 0m)
{
line.Quantity = value;
}
}
private void ToggleAll(ChangeEventArgs e)
{
foreach (var line in _lines)
{
line.Chosen = e.Value is true;
}
}
private async Task CreateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (_lines.Any(l => l.Chosen && l.Supplier is null))
{
Toasts.Show(ToastKind.Warning, T["Inventory.Reorder.MissingSupplier"]);
}
_busy = true;
try
{
var names = Chosen.Select(l => l.Supplier!).DistinctBy(r => r.Id).ToDictionary(r => r.Id, r => r.Name);
var orders = await Reorder.CreateOrdersAsync(actor, company, [.. Chosen.Select(l => new ReorderChoice(l.Proposal.ItemId, l.Supplier!.Id, l.Quantity))]);
_orders = [.. orders.Select(o => (o, names.GetValueOrDefault(o.Header.PartyId ?? 0) ?? string.Empty))];
Toasts.Show(ToastKind.Success, T.Format("Inventory.Reorder.Created", _orders.Count));
await LoadAsync();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c)));
}
finally
{
_busy = false;
}
}
private sealed class Line(ReorderProposal proposal)
{
public ReorderProposal Proposal { get; } = proposal;
public decimal Quantity { get; set; }
public PartyRow? Supplier { get; set; }
public bool Chosen { get; set; }
}
}
@@ -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;
}
}
}
@@ -0,0 +1,524 @@
@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)));
}
@@ -0,0 +1,384 @@
@page "/acquisti/importa-fatture"
@attribute [Authorize]
@using Khaemhat.Application.Purchases
@using Khaemhat.Fiscal.Abstractions
@using Khaemhat.Web.Documents
@inject ShellSession Session
@inject PurchaseInvoiceImportService Import
@inject ToastService Toasts
@* The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files; each invoice shows its
supplier (known or to add), number, date, total and what to check; the chosen ones become draft supplier invoices or
credit notes with the file attached. The invoice can be read as a page before registering it. *@
<KhPageTitle Text="@T["Purchases.Import.Title"]" Icon="upload" />
@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(PurchaseService.WritePermission))
{
<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
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Purchases.Import.Procedure"]" Icon="upload">
<KhVSteps Items="Steps" Current="_step" Label="@T["Purchases.Import.Procedure"]" />
<div class="kh-import-options">
<div class="f c12">
<label for="kh-incoming-files">@T["Purchases.Import.Files"]</label>
<InputFile id="kh-incoming-files" class="in" OnChange="ReadAsync" multiple accept=".xml,.p7m,.zip" disabled="@_busy" />
<span class="muted sm">@T["Purchases.Import.FilesHint"]</span>
</div>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_results.Count > 0)
{
<KhPanel Title="@T["Purchases.Import.Results"]" Icon="check-circle">
<div class="gridwrap">
<table class="grid" aria-label="@T["Purchases.Import.Results"]">
<thead>
<tr>
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
<th scope="col">@T["Purchases.Import.Draft"]</th>
<th scope="col">@T["Purchases.Import.Check"]</th>
</tr>
</thead>
<tbody>
@foreach (var result in _results)
{
<tr>
<td>
@result.Candidate.File.Supplier.DisplayName
@if (result.SupplierCreated)
{
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
}
</td>
<td class="code">@result.Candidate.Invoice.Number</td>
@if (result.Record is { } record)
{
<td><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@T["Sales.Kinds." + record.Header.Kind] · @T.Money(record.Header.TotalAmount)</a></td>
<td>@string.Join(" ", result.Warnings.Select(w => T[w]))</td>
}
else
{
<td colspan="2" class="err"><KhIcon Name="alert-circle" /> @(T.Contains(result.Error ?? string.Empty) ? T[result.Error!] : result.Error)</td>
}
</tr>
}
</tbody>
</table>
</div>
<div class="kh-endrow kh-pad">
<a class="btn" href="acquisti/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.PurchaseInvoices.Title"]</a>
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Purchases.Import.Again"]</button>
</div>
</KhPanel>
}
else
{
@if (_rejected.Count > 0)
{
<div class="callout warn kh-pad" role="alert">
<KhIcon Name="alert" />
<div>
<b>@T.Format("Purchases.Import.Rejected", _rejected.Count)</b>
<ul class="kh-plainlist">
@foreach (var file in _rejected)
{
<li><span class="code">@file.FileName</span> · @(T.Contains(file.Error) ? T[file.Error] : file.Error)</li>
}
</ul>
</div>
</div>
}
<KhPanel Title="@T["Purchases.Import.Invoices"]" Icon="file">
<Actions>
<span class="muted sm">@T.Format("Purchases.Import.Selected", _selected.Count, T.Money(SelectedTotal))</span>
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy)" @onclick="ImportAsync">
<KhIcon Name="download" /> @T["Purchases.Import.Register"]
</button>
</Actions>
<ChildContent>
@if (_invoices.Count == 0)
{
<p class="muted kh-pad">@T["Purchases.Import.Start"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Purchases.Import.Invoices"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == Importable.Count() && _selected.Count > 0)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
<th scope="col">@T["Purchases.Import.VatNumber"]</th>
<th scope="col">@T["Purchases.Import.Type"]</th>
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
<th scope="col">@T["Purchases.Fields.SupplierDate"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
<th scope="col">@T["Purchases.Import.Check"]</th>
<th scope="col"><span class="sr-only">@T["Purchases.Import.View"]</span></th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < _invoices.Count; i++)
{
var index = i;
var invoice = _invoices[i];
<tr class="@(invoice.CanImport ? null : "muted")">
<td class="kh-check">
<input type="checkbox" checked="@_selected.Contains(index)" disabled="@(!invoice.CanImport)" aria-label="@invoice.Invoice.Number"
@onchange="e => Toggle(index, e.Value is true)" />
</td>
<td>
@invoice.File.Supplier.DisplayName
@if (invoice.SupplierId is null)
{
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
}
</td>
<td class="code">@(invoice.File.Supplier.CountryCode)@invoice.File.Supplier.VatNumber</td>
<td><span class="code">@invoice.Invoice.DocumentType</span> @(invoice.DocumentTypeCode is { } code ? "→ " + code : null)</td>
<td class="code">@invoice.Invoice.Number</td>
<td>@T.Date(invoice.Invoice.Date)</td>
<td class="num">@T.Money(invoice.Total)</td>
<td>
@if (invoice.Problems.Count == 0)
{
<KhBadge Tone="KhTone.Ok">@T["Purchases.Import.Ready"]</KhBadge>
}
@foreach (var problem in invoice.Problems)
{
<KhBadge Tone="@(invoice.CanImport ? KhTone.Warning : KhTone.Error)">@T[problem + ".short"]</KhBadge>
}
</td>
<td><button type="button" class="btn sm" @onclick="() => _shown = invoice"><KhIcon Name="eye" /> @T["Purchases.Import.View"]</button></td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
<KhDialog Open="_shown is not null" Title="@ShownTitle" Icon="file" Size="lg" OnClose="() => _shown = null">
<ChildContent>
@if (_shown is { } shown)
{
var supplier = shown.File.Supplier;
var invoice = shown.Invoice;
<div class="kh-einvoice">
<dl class="kh-facts">
<dt>@T["Purchases.Fields.Supplier"]</dt>
<dd><b>@supplier.DisplayName</b><br />@supplier.Address @supplier.StreetNumber, @supplier.PostalCode @supplier.City @(supplier.Province is null ? null : "(" + supplier.Province + ")")</dd>
<dt>@T["Purchases.Import.VatNumber"]</dt><dd class="code">@supplier.CountryCode@supplier.VatNumber @(supplier.TaxCode is null ? null : " · " + supplier.TaxCode)</dd>
<dt>@T["Purchases.Import.Type"]</dt><dd><span class="code">@invoice.DocumentType</span> · @invoice.Currency</dd>
<dt>@T["Purchases.Fields.SupplierNumber"]</dt><dd>@invoice.Number · @T.Date(invoice.Date)</dd>
@if (invoice.Causals.Count > 0)
{
<dt>@T["Purchases.Import.Causal"]</dt><dd>@string.Join(" ", invoice.Causals)</dd>
}
@if (shown.File.Signature is { } signature)
{
<dt>@T["Purchases.Import.Signature"]</dt>
<dd>
<KhBadge Tone="@(signature.Verified ? KhTone.Ok : KhTone.Warning)">@T[signature.Verified ? "Purchases.Import.SignatureOk" : "Purchases.Import.SignatureKo"]</KhBadge>
@signature.Signer
</dd>
}
</dl>
<div class="gridwrap kh-dialoggrid">
<table class="grid" aria-label="@T["Purchases.Import.Lines"]">
<thead>
<tr>
<th scope="col">#</th>
<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.Reorder.Price"]</th>
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
<th scope="col" class="num">@T["Purchases.Import.Rate"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in invoice.Lines)
{
<tr>
<td>@line.Number</td>
<td class="code">@string.Join(" ", line.Codes.Select(c => c.Value))</td>
<td>@line.Description</td>
<td class="num">@(line.Quantity is { } q ? q.ToString("#,##0.###", T.Culture) + " " + line.Unit : null)</td>
<td class="num">@T.Money(line.UnitPrice)</td>
<td class="num">@T.Money(line.TotalPrice)</td>
<td class="num">@(line.Nature ?? line.TaxRate.ToString("0.##", T.Culture) + "%")</td>
</tr>
}
</tbody>
</table>
</div>
<KhStrip Items="SummaryOf(invoice)" Label="@T["Purchases.Import.Summary"]" />
@if (invoice.Payments.Count > 0)
{
<ul class="kh-plainlist muted sm">
@foreach (var payment in invoice.Payments)
{
<li>@T["Purchases.Import.Payment"] @(payment.DueDate is { } due ? T.Date(due) : null) · @T.Money(payment.Amount) @(payment.Iban is null ? null : " · " + payment.Iban)</li>
}
</ul>
}
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn primary" @onclick="() => _shown = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
}
@code {
private readonly HashSet<int> _selected = [];
private List<IncomingCandidate> _invoices = [];
private List<IncomingRejected> _rejected = [];
private List<IncomingImported> _results = [];
private IncomingCandidate? _shown;
private bool _loaded;
private bool _busy;
private int _step;
private IReadOnlyList<KhStep> Steps =>
[
new(T["Purchases.Import.Steps.Load"], T["Purchases.Import.Steps.LoadDetail"]),
new(T["Purchases.Import.Steps.Check"], T["Purchases.Import.Steps.CheckDetail"]),
new(T["Purchases.Import.Steps.Register"], T["Purchases.Import.Steps.RegisterDetail"]),
];
private IEnumerable<int> Importable => Enumerable.Range(0, _invoices.Count).Where(i => _invoices[i].CanImport);
private decimal SelectedTotal => _selected.Sum(i => _invoices[i].Total);
private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"];
private IReadOnlyList<KhStat> SummaryOf(IncomingInvoice invoice) =>
[
new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))),
new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))),
new(T["Sales.Totals.Total"], T.Money(invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax))),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_loaded = true;
}
private async Task ReadAsync(InputFileChangeEventArgs e)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var files = new List<(string, byte[])>();
foreach (var file in e.GetMultipleFiles(200))
{
using var buffer = new MemoryStream();
await using (var stream = file.OpenReadStream(PurchaseInvoiceImportService.MaxFileSize))
{
await stream.CopyToAsync(buffer);
}
files.Add((file.Name, buffer.ToArray()));
}
var reading = await Import.ReadAsync(actor, company, files);
_invoices = [.. reading.Invoices];
_rejected = [.. reading.Rejected];
_results.Clear();
_selected.Clear();
_selected.UnionWith(Importable);
_step = _invoices.Count > 0 ? 1 : 0;
}
catch (IOException)
{
Toasts.Show(ToastKind.Error, T["Purchases.Import.TooLarge"]);
}
finally
{
_busy = false;
}
}
private void Toggle(int index, bool on)
{
if (on)
{
_selected.Add(index);
}
else
{
_selected.Remove(index);
}
}
private void ToggleAll(ChangeEventArgs e)
{
_selected.Clear();
if (e.Value is true)
{
_selected.UnionWith(Importable);
}
}
private async Task ImportAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
_results = [.. await Import.ImportAsync(actor, company, [.. _selected.Order().Select(i => _invoices[i])])];
_step = 2;
var made = _results.Count(r => r.Record is not null);
Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Purchases.Import.Done", made, _results.Count));
}
finally
{
_busy = false;
}
}
private void Restart()
{
_results.Clear();
_invoices.Clear();
_rejected.Clear();
_selected.Clear();
_step = 0;
}
}
@@ -6,6 +6,7 @@
@page "/magazzino/{Segment}/{Id:long}"
@attribute [Authorize]
@inherits DocumentPage<DocumentRecord, DocumentLine>
@using Khaemhat.Application.Purchases
@using Khaemhat.Application.Audit
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Items
@@ -109,6 +110,28 @@ else
@switch (ActiveTab)
{
case TabIds.Lines:
@if (_differences.Count > 0)
{
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" />
<span>@T.Format("Purchases.PriceDifferences.Summary", _differences.Count, T.Money(_differences.Sum(d => d.Amount)))
@foreach (var difference in _differences.Take(5))
{
<br /><span class="sm">@T.Format("Purchases.PriceDifferences.Line", difference.LineNumber, difference.Description, difference.SourceNumber ?? string.Empty,
T.Money(difference.SourcePrice), T.Money(difference.InvoicePrice))</span>
}
</span>
</div>
}
@if (_selfAdvice is { } advice)
{
<div class="callout info kh-doc-callout"><KhIcon Name="refresh" />
<span>@T.Format("Purchases.SelfInvoices.Advice", advice.DocumentTypeCode, advice.Reason, T.Date(advice.Deadline))</span>
@if (Session.Permissions.Allows(PurchaseService.WritePermission) && DocumentStateMachine.IsInForce(h.Status))
{
<button type="button" class="btn" @onclick="CreateSelfInvoiceAsync"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
}
</div>
}
@if (h.PartyId is null && !IsReadOnly && !IsInternal)
{
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
@@ -5,12 +5,14 @@ using Khaemhat.Application.Files;
using Khaemhat.Application.Items;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Purchases;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Common;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Components.Ui;
using Khaemhat.Web.Documents;
using Khaemhat.Web.Parties;
@@ -34,6 +36,8 @@ public sealed partial class SalesDocumentPage
private PartyRow? _party;
private IReadOnlyList<DocumentAction> _actions = [];
private IReadOnlyList<LinkedDocument> _links = [];
private IReadOnlyList<PriceDifference> _differences = [];
private SelfInvoiceAdvice? _selfAdvice;
private IReadOnlyList<AuditItem> _history = [];
private int _attachments;
private bool _loaded;
@@ -100,6 +104,9 @@ public sealed partial class SalesDocumentPage
[Inject]
private TimeProvider Clock { get; set; } = default!;
[Inject]
private PurchaseService Purchases { get; set; } = default!;
private DocumentHeader H => Record!.Header;
private DocumentBehavior Behavior => DocumentBehaviors.Of(Record!.Header.Kind);
@@ -315,16 +322,53 @@ public sealed partial class SalesDocumentPage
_links = [];
_history = [];
_attachments = 0;
_differences = [];
_selfAdvice = null;
return;
}
_links = await Editor.LinksAsync(actor, company, Record);
await LoadPurchaseChecksAsync(actor, company);
_history = await Audit.HistoryAsync(actor, company, Record.Header.GetType().Name, Record.Header.Id.ToString(CultureInfo.InvariantCulture), Behavior.ReadPermission);
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
? await Attachments.CountAsync(actor, company, AttachmentEntity, Record.Header.Id)
: 0;
}
// A supplier invoice: the prices that differ from its order or receipt, and the self-invoice it needs.
private async Task LoadPurchaseChecksAsync(Actor actor, string company)
{
_differences = [];
_selfAdvice = null;
if (Record is null || H.Kind != DocumentKind.PurchaseInvoice || !Session.Permissions.Allows(PurchaseService.ReadPermission))
{
return;
}
_differences = await Purchases.PriceDifferencesAsync(actor, company, Record);
_selfAdvice = _links.Any(l => l.Kind == DocumentKind.SelfInvoice && l.Status != DocumentStatus.Cancelled)
? null
: await Purchases.AdviseAsync(actor, company, Record);
}
private async Task CreateSelfInvoiceAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null || _selfAdvice is not { } advice)
{
return;
}
try
{
var self = await Purchases.CreateSelfInvoiceAsync(actor, company, H.Id, advice.DocumentTypeCode);
Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c)));
}
}
// ---- Head -------------------------------------------------------------------------------------------------------
private IReadOnlyList<string> PartyLines
@@ -39,6 +39,10 @@ else if (!CanRead)
}
else
{
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "autofatture")
{
<Khaemhat.Web.Components.Purchases.PendingSelfInvoicesPanel />
}
<KhRadar TItem="DocumentRow" @key="_section.Area + _section.Segment" Id="@(_section.Area == SalesScreens.BasePath ? "sales." + _section.Segment : _section.Area + "." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
Label="@Title">
@@ -51,6 +55,10 @@ else
{
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
}
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "fatture" && Session.Permissions.Allows("purchases.invoice.write"))
{
<a class="btn" href="acquisti/importa-fatture"><KhIcon Name="upload" /> @T["Shell.Menu.Purchases.Import"]</a>
}
</Toolbar>
</KhRadar>
@@ -0,0 +1,98 @@
@using Khaemhat.Application.Purchases
@using Khaemhat.Application.Security
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject PurchaseService Purchases
@inject ToastService Toasts
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The supplier invoices still waiting for their self-invoice (SPEC §11.5, mockup 035): reverse charge from Italian
suppliers, services and goods from abroad, San Marino; the type to issue, why, and the deadline. One click creates
the self-invoice as a draft. *@
@if (_pending is { Count: > 0 } pending)
{
<KhPanel Title="@T["Purchases.SelfInvoices.Pending"]" Icon="refresh" Class="kh-pendingself">
<Actions><span class="badge @(pending.Any(p => p.Advice.Deadline < Today) ? "red" : "amber")">@T.Number(pending.Count)</span></Actions>
<ChildContent>
<div class="gridwrap">
<table class="grid" aria-label="@T["Purchases.SelfInvoices.Pending"]">
<thead>
<tr>
<th scope="col">@T["Purchases.SelfInvoices.Invoice"]</th>
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
<th scope="col">@T["Purchases.SelfInvoices.Type"]</th>
<th scope="col">@T["Purchases.SelfInvoices.Reason"]</th>
<th scope="col">@T["Purchases.SelfInvoices.Deadline"]</th>
<th scope="col"><span class="sr-only">@T["Purchases.SelfInvoices.Create"]</span></th>
</tr>
</thead>
<tbody>
@foreach (var item in pending)
{
var row = item.Invoice;
<tr>
<td class="code"><a href="@SalesScreens.RecordUrl(row.Kind, row.Id)">@row.DocumentNumber</a> · @T.Date(row.Date)</td>
<td>@row.PartyName</td>
<td class="num">@T.Money(row.Taxable)</td>
<td class="code">@item.Advice.DocumentTypeCode</td>
<td>@item.Advice.Reason</td>
<td><KhBadge Tone="@(item.Advice.Deadline < Today ? KhTone.Error : item.Advice.Deadline <= Today.AddDays(5) ? KhTone.Warning : KhTone.Neutral)">@T.Date(item.Advice.Deadline)</KhBadge></td>
<td>
@if (CanWrite)
{
<button type="button" class="btn sm primary" disabled="@_busy" @onclick="() => CreateAsync(item)"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</ChildContent>
</KhPanel>
}
@code {
private IReadOnlyList<PendingSelfInvoice>? _pending;
private bool _busy;
private bool CanWrite => Session.Permissions.Allows(PurchaseService.WritePermission);
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PurchaseService.ReadPermission))
{
_pending = await Purchases.PendingSelfInvoicesAsync(actor, company);
}
}
private async Task CreateAsync(PendingSelfInvoice item)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var self = await Purchases.CreateSelfInvoiceAsync(actor, company, item.Invoice.Id, item.Advice.DocumentTypeCode);
Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c)));
}
finally
{
_busy = false;
}
}
}
@@ -148,6 +148,7 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseService>();
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseInvoiceImportService>();
services.AddSingleton<Khaemhat.Application.Inventory.StockTakeService>();
services.AddSingleton<Khaemhat.Application.Inventory.ReorderService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
@@ -183,6 +184,8 @@ internal static class KhaemhatServices
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
services.AddSingleton<DemoSalesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<DemoPurchasesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
+1
View File
@@ -132,6 +132,7 @@ public static class SeedCommand
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
@@ -125,7 +125,10 @@
},
"Understock": {
"Title": "Sottoscorta",
"Description": "Gli articoli sotto la scorta minima."
"Description": "Gli articoli sotto la scorta minima o il punto di riordino.",
"Empty": "Nessun articolo sotto scorta.",
"Line": "Disponibile {0}, scorta {1}",
"Reorder": "Apri la proposta di riordino"
},
"Pipeline": {
"Title": "Pipeline CRM",
@@ -220,7 +220,7 @@
"target": "Indica il listino oppure il cliente, non entrambi."
},
"stock": {
"not-stocked": "L'articolo {0} non è merce gestita a magazzino."
"reason-missing": "Manca la causale di magazzino APE (esistenza iniziale): aggiornala da Tabelle azienda, Aggiorna tabelle di base."
},
"write": {
"failed": "Riga non scritta: il dato è cambiato nel frattempo o una regola l'ha rifiutata."
@@ -12,6 +12,149 @@
},
"Hints": {
"Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo."
},
"NoCompany": "Scegli un'azienda per lavorare sul magazzino.",
"Levels": {
"Ok": "Disponibile",
"Reorder": "Da riordinare",
"Understock": "Sottoscorta",
"Out": "Esaurito"
},
"Stock": {
"Title": "Giacenze e disponibilità",
"Search": "Cerca per codice o descrizione",
"AllWarehouses": "Tutti i depositi",
"IncludeEmpty": "Anche gli articoli senza giacenza",
"Items": "Articoli in giacenza",
"Understock": "Sottoscorta",
"Out": "Esauriti",
"Ordered": "Articoli in arrivo",
"TotalValue": "Valore di magazzino",
"OnHand": "Giacenza",
"Committed": "Impegnato",
"OrderedColumn": "Ordinato",
"Available": "Disponibile",
"Minimum": "Scorta min.",
"ReorderPoint": "Punto riordino",
"Value": "Valore",
"LastLoad": "Ultimo carico",
"LastUnload": "Ultimo scarico"
},
"Movements": {
"Title": "Movimenti dell'articolo",
"ByWarehouse": "Giacenza per deposito",
"None": "Nessun movimento per questo articolo.",
"Date": "Data",
"Document": "Documento",
"Party": "Cliente o fornitore",
"Quantity": "Quantità",
"UnitCost": "Costo unitario",
"Balance": "Saldo",
"OpenItem": "Apri l'articolo"
},
"Valuation": {
"Title": "Valorizzazione",
"Date": "Alla data",
"Method": "Criterio",
"Compute": "Calcola",
"Class": "Classe ABC",
"ClassA": "Classe A",
"ClassB": "Classe B",
"ClassC": "Classe C",
"Methods": {
"WeightedAverage": "Costo medio ponderato",
"LastCost": "Ultimo costo",
"StandardCost": "Costo standard"
},
"Hint": "Classe A: gli articoli che fanno l'80% del valore; B fino al 95%; C il resto. FIFO e LIFO arriveranno con la contabilità di magazzino a lotti."
},
"Rebuild": {
"Action": "Ricostruisci",
"Title": "Ricostruire il magazzino?",
"Text": "Tutti i movimenti vengono riscritti dai documenti in vigore e costi e giacenze ricalcolati. Su molti documenti può richiedere qualche minuto; i dati restano consultabili.",
"Progress": "Ricostruzione in corso: {0} {1} di {2}",
"Phases": {
"Documents": "documenti",
"Items": "articoli"
},
"Done": "Magazzino ricostruito: {0} documenti, {1} articoli ricalcolati."
},
"StockTake": {
"Title": "Inventario fisico",
"New": "Nuovo inventario",
"Open": "Apri inventario",
"Opened": "Inventario aperto con {0} articoli da contare.",
"Date": "Data del conteggio",
"Description": "Descrizione",
"DescriptionHint": "Vuota: deposito e data.",
"AllCategories": "Tutte le categorie",
"Hint": "L'inventario fotografa la giacenza contabile del deposito alla data scelta. Conta gli articoli, scrivi le quantità o importa il file del lettore, poi registra: le differenze diventano movimenti di rettifica INVP e INVN alla data del conteggio.",
"List": "Inventari",
"None": "Nessun inventario ancora.",
"Missing": "Questo inventario non esiste più.",
"Procedure": "Procedura",
"Movements": "Rettifiche",
"Lines": "Articoli da contare",
"Show": "Mostra",
"ShowAll": "Tutti",
"ShowToCount": "Da contare",
"ShowDifferences": "Con differenze",
"Import": "Importa conteggi",
"Save": "Salva conteggi",
"Saved": "Conteggi salvati.",
"Imported": "{0} articoli contati dal file, {1} codici non in lista.",
"FileTooLarge": "Il file è troppo grande: al massimo 5 MB.",
"Post": "Registra rettifiche",
"PostTitle": "Registrare l'inventario?",
"PostText": "Le differenze contate diventano movimenti di magazzino alla data del conteggio e l'inventario si chiude. Gli articoli non contati restano come sono.",
"Posted": "Inventario registrato.",
"Cancel": "Annulla inventario",
"CancelTitle": "Annullare l'inventario?",
"CancelText": "L'inventario si chiude senza muovere il magazzino; i conteggi restano consultabili.",
"Book": "Contabile",
"Counted": "Contato",
"Difference": "Differenza",
"DifferenceValue": "Valore differenze",
"ToCount": "Da contare",
"Matches": "Corrisponde",
"Differs": "Differenza",
"Items": "Articoli",
"CountedItems": "Contati",
"Differences": "Con differenze",
"States": {
"Open": "Aperto",
"Posted": "Registrato",
"Cancelled": "Annullato"
},
"Steps": {
"Open": "Apertura",
"OpenDetail": "Deposito, data e categoria: giacenza contabile congelata.",
"Count": "Conteggio",
"CountDetail": "Quantità scritte o importate dal lettore.",
"Check": "Verifica differenze",
"CheckDetail": "Controlla gli scostamenti e il loro valore.",
"Post": "Registrazione",
"PostDetail": "Movimenti INVP e INVN alla data del conteggio."
}
},
"Reorder": {
"Title": "Proposta di riordino",
"Lines": "Articoli da riordinare",
"None": "Nessun articolo da riordinare: le disponibilità coprono scorte minime e punti di riordino.",
"Selected": "{0} righe scelte, {1}",
"Refresh": "Ricalcola",
"Create": "Genera ordini fornitore",
"Created": "Ordini fornitore creati in bozza: {0}.",
"Quantity": "Da ordinare",
"Price": "Prezzo",
"Expected": "Arrivo previsto",
"ChooseSupplier": "Scegli il fornitore",
"MissingSupplier": "Le righe senza fornitore non vengono ordinate.",
"Items": "Articoli sotto il punto di riordino",
"Suppliers": "Fornitori coinvolti",
"Value": "Valore stimato",
"WithoutSupplier": "Senza fornitore",
"Hint": "La quantità proposta è il lotto di riordino dell'articolo, oppure quanto riporta al punto di riordino o alla scorta minima, almeno il minimo d'ordine del fornitore. Gli ordini nascono in bozza: controllali e confermali da Acquisti, Ordini fornitore."
}
},
"inventory": {
@@ -10,11 +10,76 @@
"Hints": {
"SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.",
"VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione."
},
"Import": {
"Title": "Importa fatture passive",
"Procedure": "Procedura",
"Files": "File da importare",
"FilesHint": "XML FatturaPA, file firmati .p7m o archivi ZIP che li contengono; anche più file insieme.",
"Invoices": "Fatture nei file",
"Start": "Carica i file ricevuti dallo SDI o dal tuo intermediario: le fatture appaiono qui per il controllo.",
"Selected": "{0} fatture scelte, {1}",
"Register": "Registra in bozza",
"Results": "Fatture registrate",
"Draft": "Documento in bozza",
"Check": "Da controllare",
"NewSupplier": "Nuovo fornitore",
"VatNumber": "Partita IVA",
"Type": "Tipo",
"Ready": "Pronta",
"View": "Leggi",
"Causal": "Causale",
"Signature": "Firma",
"SignatureOk": "Firma verificata",
"SignatureKo": "Firma non verificata",
"Lines": "Righe della fattura",
"Rate": "IVA",
"Summary": "Riepilogo",
"Payment": "Pagamento",
"Rejected": "{0} file non letti",
"Done": "Registrate {0} fatture su {1}: controllale e confermale per protocollarle.",
"Again": "Importa altri file",
"TooLarge": "Un file supera la dimensione massima di 50 MB.",
"Steps": {
"Load": "Caricamento",
"LoadDetail": "XML, P7M o ZIP.",
"Check": "Controllo",
"CheckDetail": "Fornitore, duplicati e totali.",
"Register": "Registrazione",
"RegisterDetail": "Fatture in bozza con il file allegato."
}
},
"SelfInvoices": {
"Pending": "Integrazioni da emettere",
"Invoice": "Fattura fornitore",
"Type": "Tipo",
"Reason": "Motivo",
"Deadline": "Entro il",
"Create": "Crea autofattura",
"Advice": "Serve un'autofattura {0}: {1}. Da emettere entro il {2}."
},
"PriceDifferences": {
"Summary": "{0} righe hanno un prezzo diverso dall'ordine o dal ricevimento: differenza totale {1}.",
"Line": "Riga {0}, {1}: {2} a {3}, in fattura {4}."
}
},
"purchase": {
"self-invoice": {
"not-needed": "Per questa fattura non serve un'autofattura: il fornitore applica già l'IVA italiana."
},
"import": {
"unsupported-type": "Questo tipo di documento non è un acquisto da registrare (per esempio un'autofattura emessa dall'azienda).",
"duplicate": "Fattura già registrata: lo stesso fornitore ha un documento con questo numero nello stesso anno.",
"total-mismatch": "Il totale indicato nel file non corrisponde alle righe: controlla la bozza prima di confermarla.",
"signature": "La firma del file non è stata verificata: controlla la provenienza.",
"document-discount": "Il file contiene sconti o maggiorazioni sul totale: riportali a mano nella bozza.",
"tax-code": "Nessun codice IVA dell'azienda ha l'aliquota o la natura di una riga: aggiungilo in Tabelle azienda, Codici IVA.",
"empty": "Nei file non ci sono fatture elettroniche.",
"unsupported-type.short": "Non è un acquisto",
"duplicate.short": "Già registrata",
"total-mismatch.short": "Totale diverso",
"signature.short": "Firma non verificata",
"document-discount.short": "Sconto sul totale"
}
},
"incoming": {
+14
View File
@@ -159,6 +159,8 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.kh-tone { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--kh-text-3); }
.kh-tone.ok { background: var(--kh-ok); } .kh-tone.info { background: var(--kh-info, var(--kh-accent)); }
.kh-tone.warn { background: var(--kh-warn); } .kh-tone.err { background: var(--kh-err); }
.kh-wfoot { padding: 8px 12px; border-top: 1px solid var(--kh-border); font-size: 12.5px; }
.kh-wfoot a { display: inline-flex; align-items: center; gap: 6px; }
.kh-status .li { padding: 7px 12px; }
.kh-status .li .s { text-align: right; }
.chk-row input[type="checkbox"] { margin: 0; accent-color: var(--kh-accent); }
@@ -403,3 +405,15 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
/* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */
.kh-mail-form textarea.in { min-height: 190px; }
/* Warehouse (M6): filters above a radar, count boxes, file picker as a button, grids inside dialogs. */
.kh-pagefilters { margin: 10px 0 4px; }
.kh-searchbox { width: 220px; }
.in.kh-countbox { width: 96px; height: 26px; text-align: right; }
.kh-filebtn { position: relative; overflow: hidden; cursor: pointer; }
.kh-filebtn input[type=file] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
.kh-dialoggrid { max-height: 52vh; overflow: auto; margin-top: 10px; }
.kh-cellpick { min-width: 220px; }
.kh-cellpick .f > label:empty { display: none; }
.kh-plainlist { margin: 4px 0 0; padding-left: 18px; }
.kh-pendingself { margin-bottom: 12px; }