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:
1 parent
d0f9d0e651
commit
75d60ee4c4
18 files changed
+3776
-28
No files matched your search
@@ -0,0 +1,54 @@
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="ListSource{T}"/> over rows kept in memory (small tables, catalogs, tests). The rows a request selects
|
||||
/// are kept until the search, filters or ordering change, so scrolling through the pages of 100,000 rows only cuts
|
||||
/// slices.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="fields">The fields.</param>
|
||||
public sealed class InMemoryListSource<T>(IReadOnlyList<T> rows, ListFields<T> fields)
|
||||
where T : class
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private (ListQuery Query, IReadOnlyList<T> Rows)? _last;
|
||||
|
||||
/// <summary>The fields.</summary>
|
||||
public ListFields<T> Fields => fields;
|
||||
|
||||
/// <summary>Answers a request.</summary>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public Task<ListPage<T>> QueryAsync(ListQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(fields.Page(Selected(query), query));
|
||||
}
|
||||
|
||||
/// <summary>Every row a request selects, in order, for exports.</summary>
|
||||
/// <param name="query">The request; its page is ignored.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> All(ListQuery query) => Selected(query);
|
||||
|
||||
private IReadOnlyList<T> Selected(ListQuery query)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_last is { } last && last.Query.SameRows(query))
|
||||
{
|
||||
return last.Rows;
|
||||
}
|
||||
}
|
||||
|
||||
var selected = fields.Select(rows, query);
|
||||
lock (_lock)
|
||||
{
|
||||
_last = (query, selected);
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
using System.Globalization;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// The fields a list can search, filter, order and total, each bound to a property of the row. One description serves
|
||||
/// both sides: <see cref="Apply(Query{T}, ListQuery)"/> adds conditions, ordering and page to a repository query (SQL,
|
||||
/// case-insensitive LIKE for texts), <see cref="Apply(IEnumerable{T}, ListQuery)"/> runs the same request on rows in
|
||||
/// memory.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public sealed class ListFields<T>
|
||||
where T : class
|
||||
{
|
||||
private readonly Dictionary<string, ListField<T>> _fields = new(StringComparer.Ordinal);
|
||||
private readonly List<ListField<T>> _ordered = [];
|
||||
|
||||
/// <summary>The fields, in the order added.</summary>
|
||||
public IReadOnlyList<ListField<T>> Fields => _ordered;
|
||||
|
||||
/// <summary>The ordering used when the request has none, so that pages do not overlap.</summary>
|
||||
public IReadOnlyList<ListSort> DefaultSort { get; private set; } = [];
|
||||
|
||||
/// <summary>Adds a field.</summary>
|
||||
/// <typeparam name="TValue">The type of the property.</typeparam>
|
||||
/// <param name="id">The id used in filters and orderings.</param>
|
||||
/// <param name="selector">The property.</param>
|
||||
/// <param name="searchable">Whether the search box looks in it (texts only).</param>
|
||||
/// <param name="total">Whether the page carries its sum (numbers only).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> Add<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false, bool total = false)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
||||
ArgumentNullException.ThrowIfNull(selector);
|
||||
if (searchable && typeof(TValue) != typeof(string))
|
||||
{
|
||||
throw new ArgumentException($"Only text fields can be searched: {id}.", nameof(searchable));
|
||||
}
|
||||
|
||||
if (total && ListField<T, TValue>.Numeric is null)
|
||||
{
|
||||
throw new ArgumentException($"Only number fields can be totalled: {id}.", nameof(total));
|
||||
}
|
||||
|
||||
var field = new ListField<T, TValue>(id, selector, searchable, total);
|
||||
_fields.Add(id, field);
|
||||
_ordered.Add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Sets the ordering used when the request has none.</summary>
|
||||
/// <param name="sort">The ordering; the last field should be unique (the code or the id).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> OrderByDefault(params ListSort[] sort)
|
||||
{
|
||||
foreach (var item in sort)
|
||||
{
|
||||
_ = Get(item.Field);
|
||||
}
|
||||
|
||||
DefaultSort = sort;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>A field by id.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The field, or <see langword="null"/>.</returns>
|
||||
public ListField<T>? Find(string id) => _fields.GetValueOrDefault(id);
|
||||
|
||||
/// <summary>Whether a filter can be applied: known field, operator fit for its type, readable values.</summary>
|
||||
/// <param name="filter">The filter, for example one read from the saved filters.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public bool IsValid(ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = Condition(Expression.Parameter(typeof(T), "x"), filter, inMemory: true);
|
||||
return true;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the conditions, the ordering and the page of a request to a repository query.</summary>
|
||||
/// <param name="query">The query, possibly with conditions of its own (the company, the state...).</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The query.</returns>
|
||||
public Query<T> Apply(Query<T> query, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: false) is { } predicate)
|
||||
{
|
||||
query = query.Where(predicate);
|
||||
}
|
||||
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
query = Get(sort.Field).OrderQuery(query, sort.Descending);
|
||||
}
|
||||
|
||||
return query.Page(Math.Max(0, list.Offset), Math.Clamp(list.Limit, 1, ListQuery.MaxLimit));
|
||||
}
|
||||
|
||||
/// <summary>Runs a request on rows in memory: filters, totals, ordering and page.</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Apply(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
var rows = Select(source, list);
|
||||
return Page(rows, list);
|
||||
}
|
||||
|
||||
/// <summary>The rows a request selects, filtered and ordered, without paging (for exports and caches).</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> Select(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: true) is { } predicate)
|
||||
{
|
||||
source = source.Where(predicate.Compile());
|
||||
}
|
||||
|
||||
IOrderedEnumerable<T>? ordered = null;
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
ordered = Get(sort.Field).OrderMemory(source, ordered, sort.Descending);
|
||||
}
|
||||
|
||||
return [.. ordered ?? source];
|
||||
}
|
||||
|
||||
/// <summary>A page of rows already selected and ordered by <see cref="Select"/>, with the totals.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Page(IReadOnlyList<T> rows, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var totals = _ordered.Where(f => f.Total).ToDictionary(f => f.Id, f => f.Sum(rows), StringComparer.Ordinal);
|
||||
var limit = Math.Clamp(list.Limit, 1, ListQuery.MaxLimit);
|
||||
IReadOnlyList<T> items = [.. rows.Skip(Math.Max(0, list.Offset)).Take(limit)];
|
||||
return new ListPage<T>(items, rows.Count, totals);
|
||||
}
|
||||
|
||||
/// <summary>The condition of a request (search and filters), or <see langword="null"/> when it selects everything.</summary>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <param name="inMemory">Whether for rows in memory (texts compared ignoring case) or for SQL.</param>
|
||||
/// <returns>The predicate.</returns>
|
||||
public Expression<Func<T, bool>>? Predicate(ListQuery list, bool inMemory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var row = Expression.Parameter(typeof(T), "x");
|
||||
var parts = new List<Expression>();
|
||||
|
||||
var search = list.Search?.Trim();
|
||||
if (!string.IsNullOrEmpty(search))
|
||||
{
|
||||
// Every word must appear in some searchable field: "rossi torino" finds Rossi of Torino.
|
||||
foreach (var word in search.Split(' ', StringSplitOptions.RemoveEmptyEntries).Take(8))
|
||||
{
|
||||
var any = _ordered.Where(f => f.Searchable).Select(f => f.Search(row, word, inMemory)).Aggregate((Expression?)null, (a, b) => a is null ? b : Expression.OrElse(a, b));
|
||||
if (any is not null)
|
||||
{
|
||||
parts.Add(any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parts.AddRange(list.Filters.Select(filter => Condition(row, filter, inMemory)));
|
||||
return parts.Count == 0 ? null : Expression.Lambda<Func<T, bool>>(parts.Aggregate(Expression.AndAlso), row);
|
||||
}
|
||||
|
||||
private Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory) =>
|
||||
(Find(filter.Field) ?? throw new ArgumentException($"Unknown field: {filter.Field}.", nameof(filter))).Condition(row, filter, inMemory);
|
||||
|
||||
private ListField<T> Get(string id) => Find(id) ?? throw new ArgumentException($"Unknown field: {id}.", nameof(id));
|
||||
|
||||
private List<ListSort> SortOf(ListQuery list)
|
||||
{
|
||||
var sort = list.Sort.Where(s => _fields.ContainsKey(s.Field)).ToList();
|
||||
foreach (var fallback in DefaultSort)
|
||||
{
|
||||
if (!sort.Any(s => s.Field == fallback.Field))
|
||||
{
|
||||
sort.Add(fallback);
|
||||
}
|
||||
}
|
||||
|
||||
return sort;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A field of a <see cref="ListFields{T}"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public abstract class ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private protected ListField(string id, Type valueType, bool searchable, bool total)
|
||||
{
|
||||
Id = id;
|
||||
ValueType = valueType;
|
||||
Searchable = searchable;
|
||||
Total = total;
|
||||
}
|
||||
|
||||
/// <summary>The id.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
/// <summary>The type of the property (nullable included).</summary>
|
||||
public Type ValueType { get; }
|
||||
|
||||
/// <summary>Whether the search box looks in it.</summary>
|
||||
public bool Searchable { get; }
|
||||
|
||||
/// <summary>Whether the page carries its sum.</summary>
|
||||
public bool Total { get; }
|
||||
|
||||
/// <summary>The value of the field in a row.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>The value.</returns>
|
||||
public abstract object? ValueOf(T row);
|
||||
|
||||
internal abstract Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory);
|
||||
|
||||
internal abstract Expression Search(ParameterExpression row, string text, bool inMemory);
|
||||
|
||||
internal abstract Query<T> OrderQuery(Query<T> query, bool descending);
|
||||
|
||||
internal abstract IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending);
|
||||
|
||||
internal abstract decimal Sum(IEnumerable<T> rows);
|
||||
}
|
||||
|
||||
/// <summary>A field bound to a property of type <typeparamref name="TValue"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <typeparam name="TValue">The property type.</typeparam>
|
||||
internal sealed class ListField<T, TValue> : ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private static readonly MethodInfo ContainsIgnoreCase = typeof(string).GetMethod(nameof(string.Contains), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo StartsIgnoreCase = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo ContainsText = typeof(string).GetMethod(nameof(string.Contains), [typeof(string)])!;
|
||||
private static readonly MethodInfo StartsText = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
|
||||
private static readonly MethodInfo EnumerableContains = typeof(Enumerable).GetMethods()
|
||||
.Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2).MakeGenericMethod(typeof(TValue));
|
||||
|
||||
private static readonly Type Underlying = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
|
||||
private readonly Expression<Func<T, TValue>> _selector;
|
||||
private readonly Func<T, TValue> _compiled;
|
||||
|
||||
public ListField(string id, Expression<Func<T, TValue>> selector, bool searchable, bool total)
|
||||
: base(id, typeof(TValue), searchable, total)
|
||||
{
|
||||
_selector = selector;
|
||||
_compiled = selector.Compile();
|
||||
}
|
||||
|
||||
/// <summary>Converts a value to decimal for the totals, or <see langword="null"/> when the type is not a number.</summary>
|
||||
public static Func<TValue, decimal?>? Numeric { get; } = Underlying switch
|
||||
{
|
||||
var t when t == typeof(decimal) => v => v is null ? null : (decimal)(object)v,
|
||||
var t when t == typeof(int) => v => v is null ? null : (int)(object)v,
|
||||
var t when t == typeof(long) => v => v is null ? null : (long)(object)v,
|
||||
var t when t == typeof(double) => v => v is null ? null : (decimal)(double)(object)v,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static bool IsText => typeof(TValue) == typeof(string);
|
||||
|
||||
private static bool IsOrdered => !IsText && Underlying != typeof(bool) && !Underlying.IsEnum && typeof(IComparable).IsAssignableFrom(Underlying);
|
||||
|
||||
public override object? ValueOf(T row) => _compiled(row);
|
||||
|
||||
internal override Expression Search(ParameterExpression row, string text, bool inMemory) =>
|
||||
TextCall(Member(row), inMemory ? ContainsIgnoreCase : ContainsText, text, inMemory);
|
||||
|
||||
internal override Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory)
|
||||
{
|
||||
var member = Member(row);
|
||||
var values = filter.Values ?? [];
|
||||
switch (filter.Operator)
|
||||
{
|
||||
case ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty:
|
||||
Expression empty = IsText
|
||||
? Expression.Call(typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!, member)
|
||||
: typeof(TValue).IsValueType && Nullable.GetUnderlyingType(typeof(TValue)) is null
|
||||
? Expression.Constant(false)
|
||||
: Expression.Equal(member, Expression.Constant(null, typeof(TValue)));
|
||||
return filter.Operator == ListFilterOperator.IsEmpty ? empty : Expression.Not(empty);
|
||||
|
||||
case ListFilterOperator.Contains or ListFilterOperator.StartsWith:
|
||||
Require(IsText, filter);
|
||||
var method = filter.Operator == ListFilterOperator.Contains
|
||||
? (inMemory ? ContainsIgnoreCase : ContainsText)
|
||||
: (inMemory ? StartsIgnoreCase : StartsText);
|
||||
return TextCall(member, method, Single(values, filter), inMemory);
|
||||
|
||||
case ListFilterOperator.In:
|
||||
Require(values.Count > 0, filter);
|
||||
var array = values.Select(v => Convert(v, filter)).ToArray();
|
||||
return Expression.Call(EnumerableContains, Expression.Constant(array, typeof(TValue[])), member);
|
||||
|
||||
case ListFilterOperator.Between:
|
||||
Require(IsOrdered && values.Count == 2, filter);
|
||||
return Expression.AndAlso(
|
||||
Expression.GreaterThanOrEqual(member, Value(values[0], filter)),
|
||||
Expression.LessThanOrEqual(member, Value(values[1], filter)));
|
||||
|
||||
case ListFilterOperator.Equals:
|
||||
return Equal(member, Single(values, filter), filter, inMemory);
|
||||
|
||||
case ListFilterOperator.NotEquals:
|
||||
return Expression.Not(Equal(member, Single(values, filter), filter, inMemory));
|
||||
|
||||
case ListFilterOperator.GreaterThan or ListFilterOperator.GreaterOrEqual or ListFilterOperator.LessThan or ListFilterOperator.LessOrEqual:
|
||||
Require(IsOrdered, filter);
|
||||
var value = Value(Single(values, filter), filter);
|
||||
return filter.Operator switch
|
||||
{
|
||||
ListFilterOperator.GreaterThan => Expression.GreaterThan(member, value),
|
||||
ListFilterOperator.GreaterOrEqual => Expression.GreaterThanOrEqual(member, value),
|
||||
ListFilterOperator.LessThan => Expression.LessThan(member, value),
|
||||
_ => Expression.LessThanOrEqual(member, value),
|
||||
};
|
||||
|
||||
default:
|
||||
throw new ArgumentException($"Unknown operator {filter.Operator} on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
internal override Query<T> OrderQuery(Query<T> query, bool descending) =>
|
||||
descending ? query.OrderByDescending(_selector) : query.OrderBy(_selector);
|
||||
|
||||
internal override IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending)
|
||||
{
|
||||
var comparer = IsText ? (IComparer<TValue>)(object)StringComparer.CurrentCultureIgnoreCase : Comparer<TValue>.Default;
|
||||
return (ordered, descending) switch
|
||||
{
|
||||
(null, false) => source.OrderBy(_compiled, comparer),
|
||||
(null, true) => source.OrderByDescending(_compiled, comparer),
|
||||
(_, false) => ordered.ThenBy(_compiled, comparer),
|
||||
_ => ordered.ThenByDescending(_compiled, comparer),
|
||||
};
|
||||
}
|
||||
|
||||
internal override decimal Sum(IEnumerable<T> rows)
|
||||
{
|
||||
var numeric = Numeric ?? throw new InvalidOperationException($"{Id} is not a number.");
|
||||
return rows.Sum(r => numeric(_compiled(r)) ?? 0m);
|
||||
}
|
||||
|
||||
private static object? ConvertText(string text)
|
||||
{
|
||||
if (IsText)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
var c = CultureInfo.InvariantCulture;
|
||||
return Underlying switch
|
||||
{
|
||||
var t when t == typeof(bool) => bool.Parse(text),
|
||||
var t when t == typeof(int) => int.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(long) => long.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(decimal) => decimal.Parse(text, NumberStyles.Number, c),
|
||||
var t when t == typeof(double) => double.Parse(text, NumberStyles.Float, c),
|
||||
var t when t == typeof(DateOnly) => DateOnly.ParseExact(text, "yyyy-MM-dd", c),
|
||||
var t when t == typeof(DateTime) => DateTime.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(DateTimeOffset) => DateTimeOffset.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(Guid) => Guid.Parse(text),
|
||||
var t when t.IsEnum => Enum.Parse(t, text, ignoreCase: false),
|
||||
_ => throw new FormatException("Unsupported type " + Underlying.Name),
|
||||
};
|
||||
}
|
||||
|
||||
private Expression Member(ParameterExpression row) => new Rebind(_selector.Parameters[0], row).Visit(_selector.Body);
|
||||
|
||||
private Expression Equal(Expression member, string text, ListFilter filter, bool inMemory)
|
||||
{
|
||||
if (IsText && inMemory)
|
||||
{
|
||||
// Texts are equal ignoring case, as LIKE without wildcards would be.
|
||||
var equals = typeof(string).GetMethod(nameof(string.Equals), [typeof(string), typeof(string), typeof(StringComparison)])!;
|
||||
return Expression.Call(equals, member, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
return Expression.Equal(member, Value(text, filter));
|
||||
}
|
||||
|
||||
private static Expression TextCall(Expression member, MethodInfo method, string text, bool inMemory)
|
||||
{
|
||||
if (!inMemory)
|
||||
{
|
||||
return Expression.Call(member, method, Expression.Constant(text));
|
||||
}
|
||||
|
||||
// Null texts never match in memory, as in SQL.
|
||||
return Expression.AndAlso(
|
||||
Expression.NotEqual(member, Expression.Constant(null, typeof(string))),
|
||||
Expression.Call(member, method, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
private ConstantExpression Value(string text, ListFilter filter) => Expression.Constant(Convert(text, filter), typeof(TValue));
|
||||
|
||||
private TValue Convert(string text, ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (TValue)ConvertText(text)!;
|
||||
}
|
||||
catch (Exception e) when (e is FormatException or OverflowException or ArgumentException or InvalidCastException)
|
||||
{
|
||||
throw new ArgumentException($"Value '{text}' is not valid for {Id}.", nameof(filter), e);
|
||||
}
|
||||
}
|
||||
|
||||
private string Single(IReadOnlyList<string> values, ListFilter filter)
|
||||
{
|
||||
Require(values.Count == 1, filter);
|
||||
return values[0];
|
||||
}
|
||||
|
||||
private void Require(bool condition, ListFilter filter)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
throw new ArgumentException($"{filter.Operator} with {filter.Values?.Count ?? 0} values is not valid on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Rebind(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
|
||||
{
|
||||
protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>How a filter compares a field with its values (SPEC §10.7 <c>KhGrid</c>, <c>KhRadar</c>).</summary>
|
||||
public enum ListFilterOperator
|
||||
{
|
||||
/// <summary>Equal to the value.</summary>
|
||||
Equals = 0,
|
||||
|
||||
/// <summary>Different from the value.</summary>
|
||||
NotEquals = 1,
|
||||
|
||||
/// <summary>Text containing the value, ignoring case.</summary>
|
||||
Contains = 2,
|
||||
|
||||
/// <summary>Text starting with the value, ignoring case.</summary>
|
||||
StartsWith = 3,
|
||||
|
||||
/// <summary>Greater than the value.</summary>
|
||||
GreaterThan = 4,
|
||||
|
||||
/// <summary>Greater than or equal to the value.</summary>
|
||||
GreaterOrEqual = 5,
|
||||
|
||||
/// <summary>Less than the value.</summary>
|
||||
LessThan = 6,
|
||||
|
||||
/// <summary>Less than or equal to the value.</summary>
|
||||
LessOrEqual = 7,
|
||||
|
||||
/// <summary>Between the first and the second value, both included.</summary>
|
||||
Between = 8,
|
||||
|
||||
/// <summary>One of the values.</summary>
|
||||
In = 9,
|
||||
|
||||
/// <summary>Empty (null, or an empty text).</summary>
|
||||
IsEmpty = 10,
|
||||
|
||||
/// <summary>Not empty.</summary>
|
||||
IsNotEmpty = 11,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A filter on a field. The values are invariant texts (<c>2026-11-30</c>, <c>1234.5</c>, <c>true</c>, the name of an
|
||||
/// enum value), so a filter can be saved in the user settings and read back unchanged.
|
||||
/// </summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Operator">The comparison.</param>
|
||||
/// <param name="Values">The values: none for the empty checks, two for <see cref="ListFilterOperator.Between"/>.</param>
|
||||
public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList<string> Values)
|
||||
{
|
||||
/// <summary>A filter with its values.</summary>
|
||||
/// <param name="field">The field id.</param>
|
||||
/// <param name="op">The comparison.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
/// <returns>The filter.</returns>
|
||||
public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values);
|
||||
|
||||
/// <summary>The invariant text of a value, as filters keep it.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Text(object? value) => value switch
|
||||
{
|
||||
null => string.Empty,
|
||||
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
bool b => b ? "true" : "false",
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => value.ToString() ?? string.Empty,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(ListFilter? other) =>
|
||||
other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = new HashCode();
|
||||
hash.Add(Field);
|
||||
hash.Add(Operator);
|
||||
foreach (var value in Values)
|
||||
{
|
||||
hash.Add(value);
|
||||
}
|
||||
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An ordering on a field.</summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Descending">Whether from the largest.</param>
|
||||
public sealed record ListSort(string Field, bool Descending = false);
|
||||
|
||||
/// <summary>
|
||||
/// What a list or radar asks its source: the text typed in the search box, the filters, the ordering and the page.
|
||||
/// The source answers with a <see cref="ListPage{T}"/>; with <see cref="ListFields{T}"/> the same request becomes SQL for
|
||||
/// a repository or runs on rows in memory.
|
||||
/// </summary>
|
||||
public sealed record ListQuery
|
||||
{
|
||||
/// <summary>The largest page a source returns.</summary>
|
||||
public const int MaxLimit = 1000;
|
||||
|
||||
/// <summary>The text of the search box: every searchable field is checked.</summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>The filters, all of which must hold.</summary>
|
||||
public IReadOnlyList<ListFilter> Filters { get; init; } = [];
|
||||
|
||||
/// <summary>The ordering, first field first.</summary>
|
||||
public IReadOnlyList<ListSort> Sort { get; init; } = [];
|
||||
|
||||
/// <summary>The rows to skip.</summary>
|
||||
public int Offset { get; init; }
|
||||
|
||||
/// <summary>The rows to return, at most <see cref="MaxLimit"/>.</summary>
|
||||
public int Limit { get; init; } = 50;
|
||||
|
||||
/// <summary>The same request for another page.</summary>
|
||||
/// <param name="offset">The rows to skip.</param>
|
||||
/// <param name="limit">The rows to return.</param>
|
||||
/// <returns>The request.</returns>
|
||||
public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) };
|
||||
|
||||
/// <summary>Whether two requests select and order the same rows, whatever the page.</summary>
|
||||
/// <param name="other">The other request.</param>
|
||||
/// <returns>Whether they match.</returns>
|
||||
public bool SameRows(ListQuery? other) =>
|
||||
other is not null && string.Equals(Search?.Trim(), other.Search?.Trim(), StringComparison.OrdinalIgnoreCase)
|
||||
&& Filters.SequenceEqual(other.Filters) && Sort.SequenceEqual(other.Sort);
|
||||
}
|
||||
|
||||
/// <summary>A page of rows with the count and the totals of every row the request selects (not only the page).</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="Items">The rows of the page.</param>
|
||||
/// <param name="Total">The rows selected.</param>
|
||||
/// <param name="Totals">The sums by field id, for the totals row of the grid.</param>
|
||||
public sealed record ListPage<T>(IReadOnlyList<T> Items, long Total, IReadOnlyDictionary<string, decimal> Totals)
|
||||
{
|
||||
/// <summary>No rows.</summary>
|
||||
#pragma warning disable CA1000 // An empty page of the same row type is the natural default.
|
||||
public static ListPage<T> Empty { get; } = new([], 0, new Dictionary<string, decimal>());
|
||||
#pragma warning restore CA1000
|
||||
}
|
||||
|
||||
/// <summary>Where a grid or radar reads its rows.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation, when a newer request replaces this one.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public delegate Task<ListPage<T>> ListSource<T>(ListQuery query, CancellationToken cancellationToken);
|
||||
Reference in new issue
Block a user