HRM-10/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs

272 lines
13 KiB
C#
Raw Normal View History

2026-11-09 14:41:04 +06:00
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using HRM.BO;
using Microsoft.Data.SqlClient;
namespace HRM.DA
{
/// <summary>
/// One column of a virtual grid. Field is the name the screen uses. In a list grid it is a property
/// of the business object; in a SQL grid it is the alias of Sql, the expression the column selects,
/// sorts and searches by (null = filled in code, not sorted or searched by SQL).
/// </summary>
internal sealed class VirtualGridColumn
{
public string Field { get; set; }
public string Title { get; set; }
public int Width { get; set; } = 130;
public EnumVirtualGridColumnType Type { get; set; } = EnumVirtualGridColumnType.Text;
public string Sql { get; set; }
public bool Sortable { get; set; } = true;
public bool Searchable { get; set; } = true;
}
/// <summary>
/// The rows a grid is built on: a "FROM ... WHERE ..." clause plus its parameters.
/// Filter values must only ever reach SQL through <see cref="Parameters"/>.
/// </summary>
internal sealed class VirtualGridSource
{
public string FromWhere { get; set; }
public List<SqlParameter> Parameters { get; } = new List<SqlParameter>();
/// <summary>Human-readable filter summary, printed at the top of the Excel file.</summary>
public string FilterDescription { get; set; }
}
/// <summary>
/// Extra search conditions a definition adds for values that are worked out in code (e.g. department
/// tier names): each becomes one more OR branch of the search. Only code-produced SQL goes here.
/// </summary>
internal sealed class VirtualGridSearchExtras
{
internal List<string> Predicates { get; } = new List<string>();
/// <summary>Adds "sqlExpression IN (v1, v2, …)" — the values are integers, so they are safe to splice.</summary>
public void AddIntIn(string sqlExpression, IEnumerable<int> values)
{
List<int> list = (values ?? Enumerable.Empty<int>()).Distinct().ToList();
if (list.Count > 0)
Predicates.Add(sqlExpression + " IN (" + string.Join(",", list.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ")");
}
}
/// <summary>
/// Typed, validated access to <see cref="VirtualGridRequest.Filters"/>. Every problem is an
/// ArgumentException with a message fit to show the user (the controller returns it as 400).
/// </summary>
internal sealed class VirtualGridFilters
{
private readonly Dictionary<string, string> _values;
public VirtualGridFilters(Dictionary<string, string> values)
{
_values = new Dictionary<string, string>(values ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
}
public string GetString(string name)
{
string value;
return _values.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value) ? value.Trim() : null;
}
/// <summary>A "yyyy-MM-dd" date. <paramref name="label"/> is the name the user sees ("From Date").</summary>
public DateTime? GetDate(string name, string label, bool required)
{
string text = GetString(name);
if (text == null)
{
if (required)
throw new ArgumentException("Please select " + label + ".");
return null;
}
DateTime value;
if (!DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
throw new ArgumentException("Please select a valid " + label + ".");
return value;
}
public int? GetInt(string name, string label, bool required)
{
string text = GetString(name);
if (text == null)
{
if (required)
throw new ArgumentException("Please select " + label + ".");
return null;
}
int value;
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
throw new ArgumentException("Please select a valid " + label + ".");
return value;
}
}
/// <summary>
/// Base class of every virtual grid: what the grid is called, its columns and its limits.
/// A grid derives from one of the two kinds below, never from this class directly:
///
/// - VirtualGridListDefinition&lt;T&gt; (the usual choice): LoadData calls an ordinary service method
/// that returns a List of business objects, exactly as screens always get their data. The common
/// service keeps that list in memory and pages, sorts, searches and exports it on the server.
/// - VirtualGridSqlDefinition (for very large lists): the grid gives a FROM/WHERE and SQL Server
/// does the paging, so only one window of rows is ever read.
///
/// A new instance is created for every call, so a definition may keep per-call state.
/// </summary>
internal abstract class VirtualGridDefinition
{
private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled);
/// <summary>The key the screen sends (e.g. "discontinue-employee").</summary>
public abstract string Key { get; }
public abstract string Title { get; }
public virtual string DefaultSortField => null; // null = first sortable column
public virtual string DefaultSortDir => "asc";
/// <summary>Self-service (ESS) logins are refused unless a grid opts in.</summary>
public virtual bool AllowSelfServiceUsers => false;
public virtual int MaxPageSize => 500;
/// <summary>Largest Excel export allowed; past it the user is asked to narrow the filters.</summary>
public virtual int ExportRowLimit => 200000;
public virtual string ExcelFileName => Regex.Replace(Title, "[^A-Za-z0-9]+", "") + ".xlsx";
/// <summary>The grid's columns, in display order. May depend on configuration (e.g. department tier names).</summary>
public abstract List<VirtualGridColumn> GetColumns(VirtualGridContext context);
/// <summary>Whether the user can sort by this column.</summary>
internal virtual bool CanSort(VirtualGridColumn column) => column.Sortable;
/// <summary>Whether the search box looks in this column.</summary>
internal virtual bool CanSearch(VirtualGridColumn column) => column.Searchable;
internal static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name);
}
/// <summary>
/// A grid filled from an ordinary service method that returns a list of business objects, the way
/// screens have always loaded their data:
///
/// protected override List&lt;LeaveEntry&gt; LoadData(VirtualGridFilters filters, VirtualGridContext context)
/// =&gt; new LeaveEntryService().Get(...);
///
/// Each column's Field is the name of a property of T (camelCase, matched case-insensitively);
/// Sql is not used.
///
/// The list is loaded on Preview and kept in server memory for a few minutes, so scrolling, sorting
/// and searching do not call the service again. Suits lists up to tens of thousands of rows; for
/// larger ones use VirtualGridSqlDefinition.
/// </summary>
internal abstract class VirtualGridListDefinition<T> : VirtualGridDefinition, IVirtualGridListSource where T : class
{
/// <summary>Reads/validates the filters and returns the rows, usually with one call to an existing service.</summary>
protected abstract List<T> LoadData(VirtualGridFilters filters, VirtualGridContext context);
/// <summary>Human-readable filter summary, printed at the top of the Excel file. Optional.</summary>
public virtual string DescribeFilters(VirtualGridFilters filters) => null;
/// <summary>Calls LoadData and turns each object into a row holding just the grid's columns.</summary>
List<Dictionary<string, object>> IVirtualGridListSource.LoadRows(
VirtualGridFilters filters, VirtualGridContext context, List<VirtualGridColumn> columns)
{
var properties = new List<KeyValuePair<string, PropertyInfo>>();
foreach (VirtualGridColumn c in columns)
{
PropertyInfo property = FindProperty(c.Field);
if (property == null || !property.CanRead)
throw new InvalidOperationException("Virtual grid '" + Key + "': " + typeof(T).Name
+ " has no readable property for column '" + c.Field + "'.");
properties.Add(new KeyValuePair<string, PropertyInfo>(c.Field, property));
}
List<T> items = LoadData(filters, context) ?? new List<T>();
var rows = new List<Dictionary<string, object>>(items.Count);
foreach (T item in items)
{
if (item == null)
continue;
var row = new Dictionary<string, object>(properties.Count, StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, PropertyInfo> p in properties)
row[p.Key] = p.Value.GetValue(item);
rows.Add(row);
}
return rows;
}
/// <summary>
/// The public property named <paramref name="field"/> (case-insensitive). When a class hides a base
/// property with "new" (e.g. EmployeeDetailInfo.Status over the base Status), the most derived one —
/// the one the business object itself shows — wins.
/// </summary>
private static PropertyInfo FindProperty(string field)
{
PropertyInfo best = null;
int bestDepth = int.MaxValue;
foreach (PropertyInfo p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!string.Equals(p.Name, field, StringComparison.OrdinalIgnoreCase) || p.GetIndexParameters().Length > 0)
continue;
int depth = 0;
for (Type t = typeof(T); t != null && t != p.DeclaringType; t = t.BaseType)
depth++;
if (depth < bestDepth)
{
best = p;
bestDepth = depth;
}
}
return best;
}
}
/// <summary>Non-generic view of a list grid, used by VirtualGridService.</summary>
internal interface IVirtualGridListSource
{
List<Dictionary<string, object>> LoadRows(VirtualGridFilters filters, VirtualGridContext context, List<VirtualGridColumn> columns);
string DescribeFilters(VirtualGridFilters filters);
}
/// <summary>
/// A grid whose paging, sorting and searching run in SQL Server: for very large lists, where loading
/// every row (even once) is too slow. Each column's Sql is the expression it selects, sorts and searches
/// by; a column with Sql = null is filled in OnRowsLoaded.
/// </summary>
internal abstract class VirtualGridSqlDefinition : VirtualGridDefinition
{
/// <summary>A unique, stable SQL expression (usually the primary key) used as the last sort key so pages never overlap.</summary>
public abstract string TieBreakerSql { get; }
/// <summary>
/// Extra values selected for OnRowsLoaded only, as "sqlExpression AS _alias".
/// Aliases must start with '_'; they are removed from the rows before they leave the server.
/// </summary>
public virtual IEnumerable<string> HiddenSelect => Enumerable.Empty<string>();
/// <summary>Reads/validates the filters and returns the FROM/WHERE the grid is built on.</summary>
public abstract VirtualGridSource BuildSource(VirtualGridFilters filters, VirtualGridContext context);
/// <summary>Adds OR-conditions for code-computed values matching the search text. Optional.</summary>
public virtual void AddSearchExtras(string term, VirtualGridSearchExtras extras, VirtualGridContext context)
{
}
/// <summary>Fills code-computed columns (and reformats values) on one loaded window of rows. Optional.</summary>
public virtual void OnRowsLoaded(List<Dictionary<string, object>> rows, VirtualGridContext context)
{
}
internal override bool CanSort(VirtualGridColumn column) => column.Sortable && !string.IsNullOrEmpty(column.Sql);
internal override bool CanSearch(VirtualGridColumn column) => column.Searchable && !string.IsNullOrEmpty(column.Sql);
}
}