feat: grids, radar and document lines (#28)

Lists need one component for the whole app (SPEC §10.6-§10.7): a list
query model that turns search, filters, sort and paging into SQL or runs
over rows in memory, a KhGrid that pages 100,000 rows while scrolling
(or in pages) with sort, selection, keyboard, inline edit, totals, row
menu, saved column layout and CSV/XLSX export, the KhRadar around it
with search, quick filters, a filter builder and saved filters, a radar
window for F4 lookups, and KhLinesGrid for document lines typed from the
keyboard.

Checked in the browser on the component catalog and the sample document.
Fixed on the way: the grid height lost to the flex basis, a new search
kept the old scroll position, Save of a filter needed a second click,
page shortcuts (Ctrl+Canc) reached the record behind a modal window,
Escape did nothing once focus left a dialog, totals did not follow an
inline edit, and amounts exported as 0 instead of 0,00.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:47:38 +01:00
1 parent d0f9d0e651
commit 75d60ee4c4
18 files changed
+3776 -28

No files matched your search

+181 -4
View File
@@ -1,3 +1,5 @@
using Khaemhat.Application.Querying;
namespace Khaemhat.Web.Ui;
/// <summary>A customer of the component catalog: fake data for the development page only.</summary>
@@ -20,10 +22,73 @@ public sealed class SampleLine
/// <summary>The unit price.</summary>
public decimal? Price { get; set; }
/// <summary>The unit of measure.</summary>
public string? Unit { get; set; }
/// <summary>The discount in percent.</summary>
public decimal? Discount { get; set; }
/// <summary>Whether the line is only a text.</summary>
public bool Descriptive { get; set; }
/// <summary>The amount.</summary>
public decimal Amount => Math.Round((Quantity ?? 0) * (Price ?? 0), 2, MidpointRounding.AwayFromZero);
public decimal Amount => Descriptive ? 0 : Math.Round((Quantity ?? 0) * (Price ?? 0) * (1 - ((Discount ?? 0) / 100)), 2, MidpointRounding.AwayFromZero);
/// <summary>Whether nothing was typed yet.</summary>
public bool IsEmpty => string.IsNullOrEmpty(Code) && string.IsNullOrEmpty(Description) && Quantity is null && Price is null;
}
/// <summary>A customer of the radar of the component catalog: fake data.</summary>
public sealed class SampleCustomer
{
/// <summary>The id.</summary>
public long Id { get; init; }
/// <summary>The code.</summary>
public string Code { get; init; } = string.Empty;
/// <summary>The name.</summary>
public string Name { get; init; } = string.Empty;
/// <summary>The city.</summary>
public string City { get; init; } = string.Empty;
/// <summary>The province.</summary>
public string Province { get; init; } = string.Empty;
/// <summary>The agent, if any.</summary>
public string? Agent { get; init; }
/// <summary>The kind: company, person, public.</summary>
public string Kind { get; init; } = "company";
/// <summary>The revenue of the year.</summary>
public decimal Revenue { get; init; }
/// <summary>The amount overdue.</summary>
public decimal Overdue { get; init; }
/// <summary>The credit limit (editable in the catalog).</summary>
public decimal Credit { get; set; }
/// <summary>Customer since.</summary>
public DateOnly Since { get; init; }
/// <summary>The state: active, blocked, disabled.</summary>
public string State { get; init; } = "active";
/// <summary>Whether marked as preferred.</summary>
public bool Vip { get; init; }
}
/// <summary>An item for the lookup of the document lines in the catalog: fake data.</summary>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Unit">The unit.</param>
/// <param name="Price">The price.</param>
/// <param name="Stock">The stock.</param>
public sealed record SampleItem(string Code, string Description, string Unit, decimal Price, decimal Stock);
/// <summary>The sample document of the component catalog.</summary>
public sealed class SampleDocument
{
@@ -82,15 +147,127 @@ public static class CatalogSamples
return Task.FromResult(hits);
}
/// <summary>The fields of the customer radar.</summary>
public static ListFields<SampleCustomer> CustomerFields { get; } = new ListFields<SampleCustomer>()
.Add("code", c => c.Code, searchable: true)
.Add("name", c => c.Name, searchable: true)
.Add("city", c => c.City, searchable: true)
.Add("province", c => c.Province)
.Add("agent", c => c.Agent)
.Add("kind", c => c.Kind)
.Add("revenue", c => c.Revenue, total: true)
.Add("overdue", c => c.Overdue, total: true)
.Add("credit", c => c.Credit, total: true)
.Add("since", c => c.Since)
.Add("state", c => c.State)
.Add("vip", c => c.Vip)
.OrderByDefault(new ListSort("code"));
/// <summary>The fields of the item lookup.</summary>
public static ListFields<SampleItem> ItemFields { get; } = new ListFields<SampleItem>()
.Add("code", i => i.Code, searchable: true)
.Add("description", i => i.Description, searchable: true)
.Add("unit", i => i.Unit)
.Add("price", i => i.Price)
.Add("stock", i => i.Stock)
.OrderByDefault(new ListSort("code"));
private static readonly Lazy<InMemoryListSource<SampleCustomer>> CustomerSource = new(() => new(MakeCustomers(100_000), CustomerFields));
private static readonly Lazy<InMemoryListSource<SampleItem>> ItemSource = new(() => new(MakeItems(), ItemFields));
/// <summary>The 100,000 customers of the radar.</summary>
/// <param name="query">The request.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public static Task<ListPage<SampleCustomer>> CustomersAsync(ListQuery query, CancellationToken cancellationToken) =>
CustomerSource.Value.QueryAsync(query, cancellationToken);
/// <summary>The items of the lookup.</summary>
/// <param name="query">The request.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public static Task<ListPage<SampleItem>> ItemsAsync(ListQuery query, CancellationToken cancellationToken) =>
ItemSource.Value.QueryAsync(query, cancellationToken);
/// <summary>Finds an item by its exact code.</summary>
/// <param name="code">The code.</param>
/// <returns>The item, or <see langword="null"/>.</returns>
public static SampleItem? ItemByCode(string? code) =>
code is null ? null : ItemSource.Value.All(new ListQuery()).FirstOrDefault(i => string.Equals(i.Code, code.Trim(), StringComparison.OrdinalIgnoreCase));
/// <summary>Makes fake customers, always the same ones.</summary>
/// <param name="count">How many.</param>
/// <returns>The customers.</returns>
public static IReadOnlyList<SampleCustomer> MakeCustomers(int count)
{
string[] first = ["Esempio", "Prova", "Demo", "Fittizia", "Campione", "Modello", "Simulata", "Test"];
string[] second = ["Impianti", "Costruzioni", "Commerciale", "Servizi", "Forniture", "Meccanica", "Elettrica", "Logistica", "Studio", "Officine"];
string[] forms = ["Srl", "Spa", "Snc", "Sas", "Srls"];
(string City, string Province)[] cities = [("Torino", "TO"), ("Alba", "CN"), ("Cuneo", "CN"), ("Asti", "AT"), ("Milano", "MI"), ("Bra", "CN"), ("Novara", "NO"), ("Genova", "GE"), ("Alessandria", "AL"), ("Biella", "BI")];
string?[] agents = ["M. Verdi", "L. Neri", "A. Bianchi", null];
var random = new Random(20261111);
var customers = new List<SampleCustomer>(count);
for (var i = 1; i <= count; i++)
{
var (city, province) = cities[random.Next(cities.Length)];
var kind = random.Next(20) switch { 0 => "public", < 4 => "person", _ => "company" };
var name = kind == "person"
? "Persona di prova " + random.Next(1, 99_999).ToString(System.Globalization.CultureInfo.InvariantCulture)
: first[random.Next(first.Length)] + " " + second[random.Next(second.Length)] + " " + forms[random.Next(forms.Length)];
var revenue = Math.Round((decimal)(random.NextDouble() * random.NextDouble()) * 250_000m, 2);
customers.Add(new SampleCustomer
{
Id = i,
Code = "C" + i.ToString("D6", System.Globalization.CultureInfo.InvariantCulture),
Name = name,
City = city,
Province = province,
Agent = agents[random.Next(agents.Length)],
Kind = kind,
Revenue = revenue,
Overdue = random.Next(8) == 0 ? Math.Round(revenue * (decimal)random.NextDouble() * 0.3m, 2) : 0m,
Credit = random.Next(5) * 10_000m,
Since = new DateOnly(2005, 1, 1).AddDays(random.Next(7600)),
State = random.Next(25) switch { 0 => "blocked", 1 => "disabled", _ => "active" },
Vip = random.Next(12) == 0,
});
}
return customers;
}
/// <summary>Makes the fake items.</summary>
/// <returns>The items.</returns>
public static IReadOnlyList<SampleItem> MakeItems()
{
string[] names = ["Valvola a sfera", "Raccordo a T", "Tubo multistrato", "Guarnizione", "Manometro", "Collettore", "Termostato", "Filtro a Y", "Pompa di prova", "Staffa zincata"];
string[] sizes = ["1/2 pollice", "3/4 pollice", "1 pollice", "16 mm", "20 mm", "26 mm"];
var random = new Random(1123);
var items = new List<SampleItem>();
var n = 1;
foreach (var name in names)
{
foreach (var size in sizes)
{
items.Add(new SampleItem("ART-" + n.ToString("D4", System.Globalization.CultureInfo.InvariantCulture), name + " " + size, n % 3 == 0 ? "MT" : "PZ",
Math.Round(1m + ((decimal)random.NextDouble() * 120m), 2), random.Next(0, 500)));
n++;
}
}
return items;
}
/// <summary>A new sample document.</summary>
/// <param name="today">Today.</param>
/// <returns>The document.</returns>
public static SampleDocument Document(DateOnly today)
{
var document = new SampleDocument { Number = "2026/000123", Date = today, Party = Parties[0], Discount = 0 };
document.Lines.Add(new SampleLine { Code = "ART-001", Description = "Articolo di prova", Quantity = 10, Price = 12.5m });
document.Lines.Add(new SampleLine { Code = "ART-002", Description = "Servizio dimostrativo", Quantity = 1, Price = 340m });
document.Lines.Add(new SampleLine { Code = "ART-003", Description = "Materiale fittizio", Quantity = 4.5m, Price = 8.9m });
document.Lines.Add(new SampleLine { Code = "ART-0001", Description = "Valvola a sfera 1/2 pollice", Unit = "PZ", Quantity = 10, Price = 12.5m });
document.Lines.Add(new SampleLine { Code = "ART-0002", Description = "Valvola a sfera 3/4 pollice", Unit = "PZ", Quantity = 1, Price = 340m });
document.Lines.Add(new SampleLine { Descriptive = true, Description = "Consegna al cantiere di prova, piano terra" });
document.Lines.Add(new SampleLine { Code = "ART-0003", Description = "Tubo multistrato 16 mm", Unit = "MT", Quantity = 4.5m, Price = 8.9m, Discount = 10 });
return document;
}
}
+265
View File
@@ -0,0 +1,265 @@
using System.Globalization;
using System.Text.Json;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Querying;
using Microsoft.AspNetCore.Components;
namespace Khaemhat.Web.Ui;
/// <summary>How a grid column shows its value (SPEC §10.7 <c>KhGrid</c>: typed columns).</summary>
public enum KhColumnKind
{
/// <summary>Text.</summary>
Text = 0,
/// <summary>A code: monospace, accent colour.</summary>
Code = 1,
/// <summary>A number with <see cref="KhColumn{TItem}.Decimals"/> decimals, right-aligned.</summary>
Number = 2,
/// <summary>An amount in euro, right-aligned.</summary>
Money = 3,
/// <summary>A date.</summary>
Date = 4,
/// <summary>Yes or no.</summary>
Bool = 5,
}
/// <summary>
/// A column of a <c>KhGrid</c> or <c>KhRadar</c>. <see cref="Id"/> is also the field of <see cref="ListFields{T}"/> that
/// sorts and filters it (when <see cref="Sortable"/>), and the key of its total in <see cref="ListPage{T}.Totals"/>.
/// </summary>
/// <typeparam name="TItem">The row type.</typeparam>
/// <param name="id">The id.</param>
/// <param name="title">The title (a text from the resources).</param>
/// <param name="value">The value of a row, used for display, export and editing.</param>
public sealed class KhColumn<TItem>(string id, string title, Func<TItem, object?> value)
{
/// <summary>The id.</summary>
public string Id { get; } = id;
/// <summary>The title.</summary>
public string Title { get; } = title;
/// <summary>The value of a row.</summary>
public Func<TItem, object?> Value { get; } = value;
/// <summary>How the value is shown.</summary>
public KhColumnKind Kind { get; init; }
/// <summary>The decimals of a <see cref="KhColumnKind.Number"/>.</summary>
public int Decimals { get; init; }
/// <summary>The width, as CSS (<c>110px</c>, <c>12ch</c>); none lets the table decide.</summary>
public string? Width { get; init; }
/// <summary>Whether the header sorts the rows.</summary>
public bool Sortable { get; init; } = true;
/// <summary>Whether the column is shown until the user changes the layout.</summary>
public bool Visible { get; init; } = true;
/// <summary>Whether the totals row shows the sum the source returned for this column.</summary>
public bool Total { get; init; }
/// <summary>Whether the column goes in the exported files.</summary>
public bool Export { get; init; } = true;
/// <summary>The cell content, instead of the formatted value (badges, links).</summary>
public RenderFragment<TItem>? Template { get; init; }
/// <summary>Extra classes of a cell, for highlights (<c>neg</c> for a red amount).</summary>
public Func<TItem, string?>? CellClass { get; init; }
/// <summary>
/// Makes the cell editable in place (double click or F2): receives the row and the text typed and returns an error
/// message, or <see langword="null"/> when the value was saved.
/// </summary>
public Func<TItem, string, Task<string?>>? Edit { get; init; }
/// <summary>The values a filter on this column can take (states, types); none for a free value.</summary>
public IReadOnlyList<KhOption<string>>? Choices { get; init; }
/// <summary>Whether the value is a number aligned right.</summary>
public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money;
/// <summary>The value of a row as text, in the culture of the texts.</summary>
/// <param name="item">The row.</param>
/// <param name="texts">The texts.</param>
/// <returns>The text.</returns>
public string Format(TItem item, ITexts texts) => FormatValue(Value(item), texts);
/// <summary>A value of this column as text.</summary>
/// <param name="value">The value.</param>
/// <param name="texts">The texts.</param>
/// <returns>The text.</returns>
public string FormatValue(object? value, ITexts texts)
{
ArgumentNullException.ThrowIfNull(texts);
return (Kind, value) switch
{
(_, null) => string.Empty,
(KhColumnKind.Money, _) => texts.Money(Convert.ToDecimal(value, CultureInfo.InvariantCulture)),
(KhColumnKind.Number, _) => texts.Number(Convert.ToDecimal(value, CultureInfo.InvariantCulture), Decimals),
(_, DateOnly date) => texts.Date(date),
(_, bool flag) => texts[flag ? "Ui.Grid.Yes" : "Ui.Grid.No"],
(_, IFormattable formattable) => formattable.ToString(null, texts.Culture),
_ => value.ToString() ?? string.Empty,
};
}
}
/// <summary>The columns a user keeps and their order, saved in the user settings per grid.</summary>
/// <param name="Order">The column ids in order.</param>
/// <param name="Hidden">The hidden column ids.</param>
public sealed record KhGridLayout(IReadOnlyList<string> Order, IReadOnlyList<string> Hidden)
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
/// <summary>The key of the setting of a grid.</summary>
/// <param name="grid">The grid id.</param>
/// <returns>The key.</returns>
public static string KeyOf(string grid) => "grid." + grid + ".layout";
/// <summary>Reads a saved layout; anything unreadable gives <see langword="null"/> (the default layout).</summary>
/// <param name="json">The setting.</param>
/// <returns>The layout.</returns>
public static KhGridLayout? Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
return JsonSerializer.Deserialize<KhGridLayout>(json, Json);
}
catch (JsonException)
{
return null;
}
}
/// <summary>The layout as JSON.</summary>
/// <returns>The JSON.</returns>
public string ToJson() => JsonSerializer.Serialize(this, Json);
/// <summary>The columns to show, in order: saved order first, columns added since then at their place.</summary>
/// <typeparam name="TItem">The row type.</typeparam>
/// <param name="columns">The columns of the grid.</param>
/// <param name="layout">The saved layout, or <see langword="null"/>.</param>
/// <returns>The visible columns.</returns>
public static IReadOnlyList<KhColumn<TItem>> Apply<TItem>(IReadOnlyList<KhColumn<TItem>> columns, KhGridLayout? layout)
{
ArgumentNullException.ThrowIfNull(columns);
if (layout is null)
{
return [.. columns.Where(c => c.Visible)];
}
var position = layout.Order.Select((id, i) => (id, i)).ToDictionary(p => p.id, p => p.i, StringComparer.Ordinal);
var hidden = layout.Hidden.ToHashSet(StringComparer.Ordinal);
return
[
.. columns
.Select((c, i) => (Column: c, Index: i))
.OrderBy(p => position.TryGetValue(p.Column.Id, out var at) ? at : p.Index + 0.5)
.Select(p => p.Column)
.Where(c => !hidden.Contains(c.Id) && (c.Visible || position.ContainsKey(c.Id))),
];
}
}
/// <summary>Filters, search and ordering a user saved on a radar under a name.</summary>
/// <param name="Name">The name.</param>
/// <param name="Search">The text of the search box.</param>
/// <param name="Filters">The filters.</param>
/// <param name="Sort">The ordering.</param>
public sealed record KhSavedFilter(string Name, string? Search, IReadOnlyList<ListFilter> Filters, IReadOnlyList<ListSort> Sort)
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
/// <summary>The most filters kept per radar.</summary>
public const int MaxCount = 30;
/// <summary>The key of the setting of a radar.</summary>
/// <param name="radar">The radar id.</param>
/// <returns>The key.</returns>
public static string KeyOf(string radar) => "radar." + radar + ".filters";
/// <summary>Reads the saved filters; anything unreadable gives none.</summary>
/// <param name="json">The setting.</param>
/// <returns>The filters.</returns>
public static IReadOnlyList<KhSavedFilter> ParseAll(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonSerializer.Deserialize<List<KhSavedFilter>>(json, Json) ?? [];
}
catch (JsonException)
{
return [];
}
}
/// <summary>The saved filters as JSON.</summary>
/// <param name="filters">The filters.</param>
/// <returns>The JSON.</returns>
public static string ToJson(IEnumerable<KhSavedFilter> filters) => JsonSerializer.Serialize(filters.Take(MaxCount).ToList(), Json);
}
/// <summary>A filter of the bar of a radar shown as a drop-down (Tipo, Agente, Stato in mockup 012).</summary>
/// <param name="Field">The field id.</param>
/// <param name="Label">The label.</param>
/// <param name="Options">The values (invariant text) and their labels; the first empty value means "all".</param>
public sealed record KhQuickFilter(string Field, string Label, IReadOnlyList<KhOption<string>> Options);
/// <summary>A column of a <c>KhLinesGrid</c> (the lines of a document, SPEC §10.5).</summary>
/// <typeparam name="TLine">The line type.</typeparam>
/// <param name="id">The id.</param>
/// <param name="title">The title.</param>
/// <param name="value">The value of a line.</param>
public sealed class KhLineColumn<TLine>(string id, string title, Func<TLine, object?> value)
{
/// <summary>The id.</summary>
public string Id { get; } = id;
/// <summary>The title.</summary>
public string Title { get; } = title;
/// <summary>The value of a line.</summary>
public Func<TLine, object?> Value { get; } = value;
/// <summary>How the value is shown and typed.</summary>
public KhColumnKind Kind { get; init; }
/// <summary>The decimals of a number (two for amounts).</summary>
public int Decimals { get; init; } = 2;
/// <summary>The width, as CSS.</summary>
public string? Width { get; init; }
/// <summary>Saves a text typed in the cell; none with <see cref="SetNumber"/> makes the cell read-only.</summary>
public Action<TLine, string?>? SetText { get; init; }
/// <summary>Saves a number typed in the cell (Italian format, inline calculation).</summary>
public Action<TLine, decimal?>? SetNumber { get; init; }
/// <summary>Opens the lookup of the cell (F4): the radar of the items for the code.</summary>
public Func<TLine, Task>? Lookup { get; init; }
/// <summary>Whether the cell can be typed in.</summary>
public bool IsEditable => SetText is not null || SetNumber is not null;
/// <summary>Whether the value is a number aligned right.</summary>
public bool IsNumeric => Kind is KhColumnKind.Number or KhColumnKind.Money;
}