Virtual Pagination

This commit is contained in:
Mohaimen Hasan 2026-11-09 14:54:13 +06:00
parent 7b43017c52
commit ae428ff452
20 changed files with 593 additions and 1633 deletions

View File

@ -1,110 +0,0 @@
using System;
using System.Collections.Generic;
namespace HRM.BO
{
/// <summary>
/// Common virtual-scrolling grid ("virtual grid") contracts.
///
/// Every large list screen shares ONE BO / DA / Service / Controller: a screen is just a registered
/// grid definition (HRM.DA/Service/VirtualGrid/Definitions) identified by <see cref="VirtualGridRequest.GridKey"/>.
/// The server pages, sorts, searches and exports; the browser only ever holds one window of rows.
/// See HRM.DA/Service/VirtualGrid/README.md for how to add a grid.
/// </summary>
public enum EnumVirtualGridColumnType
{
Text = 1,
Number = 2,
Money = 3,
Date = 4,
DateTime = 5
}
/// <summary>A column as the screen sees it (from the layout endpoint).</summary>
public class VirtualGridColumnInfo
{
public string Field { get; set; }
public string Title { get; set; }
public int Width { get; set; }
public EnumVirtualGridColumnType Type { get; set; }
public bool Sortable { get; set; }
}
/// <summary>Everything the screen needs to draw an empty grid before any data is requested.</summary>
public class VirtualGridLayout
{
public string GridKey { get; set; }
public string Title { get; set; }
public string DefaultSortField { get; set; }
public string DefaultSortDir { get; set; }
public int MaxPageSize { get; set; }
public List<VirtualGridColumnInfo> Columns { get; set; } = new List<VirtualGridColumnInfo>();
}
/// <summary>One window request: which grid, its filters, and the grid's skip/take, sort and search.</summary>
public class VirtualGridRequest
{
public string GridKey { get; set; }
/// <summary>
/// Screen-specific filters (e.g. fromDate / toDate as "yyyy-MM-dd"). Each grid definition reads and
/// validates the ones it needs; values are never spliced into SQL.
/// </summary>
public Dictionary<string, string> Filters { get; set; } = new Dictionary<string, string>();
public int Skip { get; set; }
public int Take { get; set; } = 100;
public string Search { get; set; }
public string SortField { get; set; }
public string SortDir { get; set; }
/// <summary>
/// True on Preview: reload the data instead of using the copy kept in server memory (list grids).
/// Scrolling, sorting and searching send false and are answered from that copy.
/// </summary>
public bool Refresh { get; set; }
}
/// <summary>Excel export: the same request plus the grid's visible columns, in order.</summary>
public class VirtualGridExportRequest : VirtualGridRequest
{
/// <summary>Fields of the columns to export, in grid order. Empty = every column of the grid.</summary>
public List<string> Fields { get; set; } = new List<string>();
}
public class VirtualGridPage
{
/// <summary>Rows matching the filters and the search.</summary>
public int Total { get; set; }
/// <summary>Rows matching the filters alone (equals Total when there is no search).</summary>
public int TotalWithoutSearch { get; set; }
/// <summary>One row per entry, keyed by column field. Values are raw (dates, numbers); the screen formats them.</summary>
public List<Dictionary<string, object>> Data { get; set; } = new List<Dictionary<string, object>>();
}
/// <summary>A generated file (Excel export).</summary>
public class VirtualGridFile
{
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
}
/// <summary>The signed-in user, as the grid definitions need it for scoping (payroll type) and access.</summary>
public class VirtualGridContext
{
public int UserID { get; set; }
public int? EmployeeID { get; set; }
public int? PayrollTypeID { get; set; }
public EnumUserType UserType { get; set; }
}
public interface IVirtualGridService
{
VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context);
VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context);
VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context);
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace HRM.BO
{
/// <summary>
/// What &lt;app-virtual-grid&gt; sends to a page endpoint: the page's own filters plus the grid's
/// scroll position, search text and sort. The same class is used by every page, so no page needs a
/// request class of its own. See HRM.DA/Service/VirtualPaging/README.md.
/// </summary>
public class VirtualPageRequest
{
/// <summary>The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString.</summary>
public Dictionary<string, string> Filters { get; set; } = new Dictionary<string, string>();
/// <summary>The grid's columns (property names). Only these are sent back and searched.</summary>
public List<string> Fields { get; set; } = new List<string>();
public int Skip { get; set; }
/// <summary>Rows wanted. 0 = all rows (used by Export to Excel).</summary>
public int Take { get; set; } = 100;
public string Search { get; set; }
public string SortField { get; set; }
/// <summary>"asc" or "desc".</summary>
public string SortDir { get; set; }
/// <summary>True on Preview: load the data again. False on scroll/sort/search/export: use the kept copy.</summary>
public bool Refresh { get; set; }
/// <summary>A filter as text, or null when it was not sent.</summary>
public string GetString(string name)
{
string value;
if (Filters != null && Filters.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value))
return value.Trim();
return null;
}
/// <summary>A "yyyy-MM-dd" filter. Throws a message fit for the user when it is missing or invalid.</summary>
public DateTime GetDate(string name, string label = null)
{
DateTime value;
if (!DateTime.TryParseExact(GetString(name), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
throw new ArgumentException("Please select a valid " + (label ?? name) + ".");
return value;
}
/// <summary>A whole-number filter. Throws a message fit for the user when it is missing or invalid.</summary>
public int GetInt(string name, string label = null)
{
int value;
if (!int.TryParse(GetString(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
throw new ArgumentException("Please select a valid " + (label ?? name) + ".");
return value;
}
}
/// <summary>One window of rows for the grid.</summary>
public class VirtualPageResult
{
/// <summary>Rows matching the search (all rows when there is no search).</summary>
public int Total { get; set; }
/// <summary>All rows, ignoring the search.</summary>
public int TotalWithoutSearch { get; set; }
/// <summary>The rows of this window, holding only the requested fields.</summary>
public List<Dictionary<string, object>> Data { get; set; } = new List<Dictionary<string, object>>();
}
}

View File

@ -1,110 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Ease.Core.DataAccess;
using Ease.Core.DataAccess.SQL;
using HRM.BO;
using Microsoft.Data.SqlClient;
namespace HRM.DA
{
/// <summary>
/// Everything VirtualGridDA needs to build a grid's SQL. Built by VirtualGridService from a grid
/// definition; all SQL fragments in it are code-produced (definition expressions, whitelisted sort,
/// integer lists), and all user values are parameters.
/// </summary>
internal sealed class VirtualGridQuery
{
/// <summary>"sqlExpression AS [alias]" entries.</summary>
public List<string> Select { get; } = new List<string>();
public VirtualGridSource Source { get; set; }
/// <summary>Columns searched with LIKE, with the type that decides how each is rendered as text.</summary>
public List<KeyValuePair<string, EnumVirtualGridColumnType>> SearchColumns { get; } =
new List<KeyValuePair<string, EnumVirtualGridColumnType>>();
/// <summary>Extra OR-branches of the search (code-produced, e.g. "e.DEPARTMENTID IN (1,2)").</summary>
public List<string> SearchPredicates { get; } = new List<string>();
/// <summary>The escaped LIKE pattern ("%text%"), or null for no search.</summary>
public string SearchPattern { get; set; }
/// <summary>Whitelisted sort expression including ASC/DESC.</summary>
public string OrderBy { get; set; }
public string TieBreaker { get; set; }
}
/// <summary>
/// The one data-access class behind every virtual grid: a COUNT and an OFFSET/FETCH window (or every
/// row, for Excel) over the grid's source, with search and sort done by SQL Server.
/// </summary>
internal static class VirtualGridDA
{
internal static int Count(TransactionContext tc, VirtualGridQuery query, bool withSearch)
{
string sql = "SELECT COUNT(*) " + query.Source.FromWhere + SearchClause(query, withSearch);
object value = tc.ExecuteScalar(CommandType.Text, sql, Parameters(query, withSearch, null, null));
return value == null || value == DBNull.Value ? 0 : Convert.ToInt32(value);
}
/// <summary>One window of rows; with <paramref name="take"/> null, every row (Excel export).</summary>
internal static IDataReader GetRows(TransactionContext tc, VirtualGridQuery query, int skip, int? take)
{
string sql = "SELECT " + string.Join(", ", query.Select) + " "
+ query.Source.FromWhere + SearchClause(query, true)
+ " ORDER BY " + query.OrderBy + ", " + query.TieBreaker + " ASC";
if (take.HasValue)
sql += " OFFSET @__Skip ROWS FETCH NEXT @__Take ROWS ONLY";
return tc.ExecuteReader(CommandType.Text, sql, Parameters(query, true, skip, take));
}
/// <summary>A column as the screen displays it, so the user can search what they see.</summary>
private static string AsDisplayText(string sql, EnumVirtualGridColumnType type)
{
switch (type)
{
case EnumVirtualGridColumnType.Date:
return "CONVERT(varchar(11), " + sql + ", 106)"; // 13 Feb 2025
case EnumVirtualGridColumnType.DateTime:
return "(CONVERT(varchar(11), " + sql + ", 106) + ' ' + CONVERT(varchar(5), " + sql + ", 108))";
case EnumVirtualGridColumnType.Money:
return "CONVERT(varchar(30), CAST(" + sql + " AS money), 1)"; // 1,234.56
case EnumVirtualGridColumnType.Number:
return "CONVERT(varchar(40), " + sql + ")";
default:
return sql;
}
}
private static string SearchClause(VirtualGridQuery query, bool withSearch)
{
if (!withSearch || string.IsNullOrEmpty(query.SearchPattern))
return string.Empty;
List<string> parts = query.SearchColumns
.Select(c => AsDisplayText(c.Key, c.Value) + @" LIKE @__Search ESCAPE '\'")
.Concat(query.SearchPredicates)
.ToList();
return parts.Count == 0 ? " AND 1 = 0" : " AND (" + string.Join(" OR ", parts) + ")";
}
private static IDataParameter[] Parameters(VirtualGridQuery query, bool withSearch, int? skip, int? take)
{
// Clones: a SqlParameter cannot belong to two commands, and one query runs several.
var list = query.Source.Parameters
.Select(p => (SqlParameter)((ICloneable)p).Clone())
.ToList();
if (withSearch && !string.IsNullOrEmpty(query.SearchPattern))
list.Add(SqlHelperExtension.CreateInParam("@__Search", SqlDbType.NVarChar, query.SearchPattern, 400));
if (take.HasValue)
{
list.Add(SqlHelperExtension.CreateInParam("@__Skip", SqlDbType.Int, skip ?? 0));
list.Add(SqlHelperExtension.CreateInParam("@__Take", SqlDbType.Int, take.Value));
}
return list.ToArray();
}
}
}

View File

@ -1,103 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using HRM.BO;
using HRM.BO.Report;
namespace HRM.DA
{
/// <summary>
/// Discontinue Employee Details (Manage Employee › Report, /reports/discontinue-employee-details):
/// employees discontinued inside a date range, with the same columns as Employee Details plus the
/// Discontinue Date.
///
/// The data comes the usual way — EmployeeService.GetDiscontinuedEmployeeDetails returns a
/// List&lt;DiscontinueEmployeeDetailInfo&gt; (query in EmployeeDA) — and the common virtual grid pages it.
/// Filters: fromDate, toDate ("yyyy-MM-dd", both required). Scoped to the user's payroll type.
/// </summary>
internal sealed class DiscontinueEmployeeVirtualGrid : VirtualGridListDefinition<DiscontinueEmployeeDetailInfo>
{
public const string GridKey = "discontinue-employee";
public override string Key => GridKey;
public override string Title => "Discontinue Employee Details";
public override string DefaultSortField => "employeeNo";
public override string ExcelFileName => "DiscontinueEmployeeDetails.xlsx";
/// <summary>Each Field is a property of DiscontinueEmployeeDetailInfo.</summary>
public override List<VirtualGridColumn> GetColumns(VirtualGridContext context)
{
var columns = new List<VirtualGridColumn>
{
new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 },
new VirtualGridColumn { Field = "name", Title = "Employee Name", Width = 220 },
new VirtualGridColumn { Field = "gender", Title = "Gender", Width = 100 },
new VirtualGridColumn { Field = "birthDate", Title = "Birth Date", Width = 120, Type = EnumVirtualGridColumnType.Date },
new VirtualGridColumn { Field = "joiningDate", Title = "Joining Date", Width = 120, Type = EnumVirtualGridColumnType.Date },
new VirtualGridColumn { Field = "discontinueDate", Title = "Discontinue Date", Width = 140, Type = EnumVirtualGridColumnType.Date },
new VirtualGridColumn { Field = "mobileNo", Title = "Mobile No", Width = 130 },
new VirtualGridColumn { Field = "emailAddress", Title = "Email Address", Width = 200 },
new VirtualGridColumn { Field = "designation", Title = "Designation", Width = 160 },
new VirtualGridColumn { Field = "grade", Title = "Grade", Width = 120 },
new VirtualGridColumn { Field = "category", Title = "Category", Width = 120 },
new VirtualGridColumn { Field = "status", Title = "Status", Width = 120 },
};
// Department tier headings come from the Logic configuration, as in Employee Details.
string[] tierFields = { "deptireOne", "deptireTwo", "deptireThree", "deptireFour", "deptireFive" };
List<SystemConfigaration> configs = new SystemConfigarationService()
.GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department") ?? new List<SystemConfigaration>();
int tier = 0;
foreach (SystemConfigaration c in configs)
{
if (!string.Equals(c.Node, "text", StringComparison.OrdinalIgnoreCase))
continue;
if (tier < tierFields.Length)
columns.Add(new VirtualGridColumn { Field = tierFields[tier], Title = c.Value, Width = 150 });
tier++;
}
columns.AddRange(new[]
{
new VirtualGridColumn { Field = "location", Title = "Location", Width = 130 },
new VirtualGridColumn { Field = "religion", Title = "Religion", Width = 110 },
new VirtualGridColumn { Field = "maritalStatus", Title = "Marital Status", Width = 120 },
new VirtualGridColumn { Field = "dateOfConfirmation", Title = "Confirmation", Width = 120, Type = EnumVirtualGridColumnType.Date },
new VirtualGridColumn { Field = "basicSalary", Title = "Basic Salary", Width = 120, Type = EnumVirtualGridColumnType.Money },
new VirtualGridColumn { Field = "grossSalary", Title = "Gross Salary", Width = 120, Type = EnumVirtualGridColumnType.Money },
new VirtualGridColumn { Field = "passportNo", Title = "Passport No", Width = 120 },
new VirtualGridColumn { Field = "bloodGroup", Title = "Blood Group", Width = 110 },
new VirtualGridColumn { Field = "lineManagerNo", Title = "LineManager No", Width = 130 },
new VirtualGridColumn { Field = "lineManagerName", Title = "LineManager Name", Width = 180 },
new VirtualGridColumn { Field = "lineManagerEmail", Title = "LineManager Email", Width = 200 },
new VirtualGridColumn { Field = "empStatus", Title = "Employee Status", Width = 130 },
new VirtualGridColumn { Field = "bank", Title = "Bank", Width = 150 },
new VirtualGridColumn { Field = "branch", Title = "Branch", Width = 150 },
new VirtualGridColumn { Field = "accountNo", Title = "Account No", Width = 150 },
new VirtualGridColumn { Field = "nationalId", Title = "National ID/NID", Width = 150 },
new VirtualGridColumn { Field = "tinNo", Title = "TIN", Width = 120 },
});
return columns;
}
protected override List<DiscontinueEmployeeDetailInfo> LoadData(VirtualGridFilters filters, VirtualGridContext context)
{
DateTime fromDate = filters.GetDate("fromDate", "From Date", true).Value;
DateTime toDate = filters.GetDate("toDate", "To Date", true).Value;
if (fromDate > toDate)
throw new ArgumentException("From Date cannot be after To Date.");
if (!context.PayrollTypeID.HasValue)
throw new ArgumentException("No payroll type is selected for your login.");
return new EmployeeService().GetDiscontinuedEmployeeDetails(fromDate, toDate, context.PayrollTypeID.Value);
}
public override string DescribeFilters(VirtualGridFilters filters)
{
DateTime? fromDate = filters.GetDate("fromDate", "From Date", false);
DateTime? toDate = filters.GetDate("toDate", "To Date", false);
return "Discontinued from " + fromDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)
+ " to " + toDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
}
}
}

View File

@ -1,88 +0,0 @@
# Virtual grid — common virtual-scrolling grid for large lists
One common controller, service and Angular component serve every virtual-scrolling list. The data
still comes **the usual way**: a service method returns a `List<BO>` (query in the module's DA). A grid
only says *which* service method to call and *which* columns to show.
| Layer | File | Role |
|---|---|---|
| BO | `HRM.BO/VirtualGrid/VirtualGrid.cs` | Request/page/layout DTOs, `EnumVirtualGridColumnType`, `IVirtualGridService` |
| Service | `HRM.DA/Service/VirtualGrid/VirtualGridService.cs` | Access check, keeps the loaded list in memory, search/sort/page, Excel |
| Grids | `HRM.DA/Service/VirtualGrid/Definitions/*.cs` | **One small class per grid**: columns + which service to call |
| Registry | `HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs` | Key → grid. Unlisted keys cannot be queried |
| Controller | `HRM.UI/Controllers/CommonInterface/VirtualGridController.cs` | `GET api/virtualGrid/layout/{key}`, `POST page`, `POST export-excel` |
| Angular | `custom-components/virtual-grid/` (`VirtualGridModule`, `<app-virtual-grid>`) | Virtual scrolling, search box, sort, total, Excel button |
## How it works
1. Screen opens → the component asks for the grid's columns (`layout`).
2. **Preview** → `grid.load(filters)` → `page` with `refresh: true` → the grid's `LoadData` calls the
service (e.g. `EmployeeService.GetDiscontinuedEmployeeDetails`) → the whole `List<BO>` is kept in
server memory (per user + filters, 10 min sliding / 30 min max) → the first 100 rows go back.
3. **Scroll / sort / search** → `page` with `refresh: false` → answered from the kept list: search,
sort, `Skip/Take` 100. The service is not called again.
4. **Export to Excel** → every matching row of the kept list, same order, as `.xlsx`.
The browser only ever holds ~100 rows, however long the list is.
## Adding a grid (existing screen with a service that already returns a list)
1. **Grid class** — `Definitions/<Name>VirtualGrid.cs`:
```csharp
internal sealed class LeaveHistoryVirtualGrid : VirtualGridListDefinition<LeaveEntry>
{
public const string GridKey = "leave-history";
public override string Key => GridKey;
public override string Title => "Leave History";
public override List<VirtualGridColumn> GetColumns(VirtualGridContext context) => new List<VirtualGridColumn>
{
// Field = a property of LeaveEntry (camelCase)
new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 },
new VirtualGridColumn { Field = "fromDate", Title = "From", Width = 120, Type = EnumVirtualGridColumnType.Date },
new VirtualGridColumn { Field = "amount", Title = "Amount", Width = 120, Type = EnumVirtualGridColumnType.Money },
};
protected override List<LeaveEntry> LoadData(VirtualGridFilters filters, VirtualGridContext context)
{
DateTime from = filters.GetDate("fromDate", "From Date", true).Value; // user-facing errors
DateTime to = filters.GetDate("toDate", "To Date", true).Value;
return new LeaveEntryService().Get(from, to, context.PayrollTypeID.Value); // the existing service
}
}
```
2. **Registry** — `{ LeaveHistoryVirtualGrid.GridKey, () => new LeaveHistoryVirtualGrid() }`.
3. **Screen** — import `VirtualGridModule`, then:
```html
<app-virtual-grid #grid gridKey="leave-history" [height]="600"></app-virtual-grid>
```
```ts
this.grid.load({ fromDate: '2025-01-01', toDate: '2025-12-31' }); // filters as strings
```
No new controller, Angular service or model. For a brand-new screen, write its query in the module's
DA and a service method returning `List<BO>` (as always), then steps 1–3.
Worked example: `Definitions/DiscontinueEmployeeVirtualGrid.cs` →
`EmployeeService.GetDiscontinuedEmployeeDetails` → `EmployeeDA.GetDiscontinuedEmployeeDetails`.
## Column types
`Text` (default), `Number`, `Money` (`1,234.56`), `Date` (`dd MMM yyyy`), `DateTime` (`dd MMM yyyy HH:mm`).
The screen shows values in that format and the search box searches that same text, so users find what
they see. Set `Sortable = false` / `Searchable = false` on a column to turn either off.
## Very large lists: `VirtualGridSqlDefinition` (advanced)
A list grid loads the whole list once per Preview — fine up to tens of thousands of rows. When even
that is too slow, derive from `VirtualGridSqlDefinition` instead: give each column a `Sql` expression
and a `BuildSource` returning `FROM … WHERE …` with parameters, and SQL Server pages each request
(`OFFSET/FETCH`, `HRM.DA/DA/VirtualGrid/VirtualGridDA.cs`). User values reach SQL only as parameters;
spliced text is code-produced only.
## Rules
- A service a grid calls must not run one query per row; load lookups once (see `GetDiscontinuedEmployeeDetails`).
- Self-service (ESS) logins are refused unless the grid sets `AllowSelfServiceUsers`. Authorization in
this app is menu-driven, so add any further check a grid needs in `LoadData`.
- The kept list is per user, payroll type, grid and filter values; Preview always reloads it.

View File

@ -1,271 +0,0 @@
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);
}
}

View File

@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
namespace HRM.DA
{
/// <summary>
/// Every virtual grid the application serves, by key. Adding a grid = one definition class in
/// Definitions/ and one line here. A key that is not listed here cannot be queried.
/// </summary>
internal static class VirtualGridRegistry
{
private static readonly Dictionary<string, Func<VirtualGridDefinition>> Grids =
new Dictionary<string, Func<VirtualGridDefinition>>(StringComparer.OrdinalIgnoreCase)
{
{ DiscontinueEmployeeVirtualGrid.GridKey, () => new DiscontinueEmployeeVirtualGrid() },
};
/// <summary>A fresh definition instance for one call. Throws ArgumentException for an unknown key.</summary>
internal static VirtualGridDefinition Create(string gridKey)
{
Func<VirtualGridDefinition> factory;
if (string.IsNullOrWhiteSpace(gridKey) || !Grids.TryGetValue(gridKey.Trim(), out factory))
throw new ArgumentException("Unknown grid: " + gridKey);
return factory();
}
}
}

View File

@ -1,591 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using ClosedXML.Excel;
using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using HRM.BO;
using Microsoft.Extensions.Caching.Memory;
namespace HRM.DA
{
/// <summary>
/// The one service behind every virtual-scrolling grid (api/virtualGrid). It looks the grid up in
/// <see cref="VirtualGridRegistry"/> and serves it in one of two ways:
///
/// - List grid (<see cref="VirtualGridListDefinition{T}"/>): the grid's existing service returns a
/// List of business objects; that list is kept in server memory for a few minutes and every scroll,
/// sort, search and Excel export is answered from it.
/// - SQL grid (<see cref="VirtualGridSqlDefinition"/>): SQL Server counts, sorts, searches and returns
/// one OFFSET/FETCH window per request (VirtualGridDA).
///
/// Shared work for both: access check, column validation, paging limits, sort whitelist, the Excel file.
/// </summary>
public class VirtualGridService : ServiceTemplate, IVirtualGridService
{
private const int ExportCommandTimeoutSeconds = 600;
private const int MaxSearchLength = 200;
private const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// List grids: loaded lists, per user + grid + filters. Size = rows, so at most ~1,000,000 rows are
// held in total; the least recently used lists are dropped first.
private static readonly MemoryCache ListCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000000 });
private static readonly TimeSpan ListCacheSliding = TimeSpan.FromMinutes(10);
private static readonly TimeSpan ListCacheAbsolute = TimeSpan.FromMinutes(30);
#region Public API
public VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context)
{
VirtualGridDefinition grid = Open(gridKey, context);
List<VirtualGridColumn> columns = GetValidatedColumns(grid, context);
VirtualGridColumn defaultSort = DefaultSortColumn(grid, columns);
var layout = new VirtualGridLayout
{
GridKey = grid.Key,
Title = grid.Title,
DefaultSortField = defaultSort?.Field,
DefaultSortDir = NormalizeDir(grid.DefaultSortDir),
MaxPageSize = grid.MaxPageSize,
};
layout.Columns.AddRange(columns.Select(c => new VirtualGridColumnInfo
{
Field = c.Field,
Title = c.Title,
Width = c.Width,
Type = c.Type,
Sortable = grid.CanSort(c),
}));
return layout;
}
public VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context)
{
if (request == null)
throw new ArgumentException("Invalid request.");
VirtualGridDefinition grid = Open(request.GridKey, context);
List<VirtualGridColumn> columns = GetValidatedColumns(grid, context);
int skip = Math.Max(0, request.Skip);
int take = Math.Min(Math.Max(1, request.Take), grid.MaxPageSize);
var listSource = grid as IVirtualGridListSource;
if (listSource != null)
{
CachedList list = GetList(grid, listSource, columns, request, context);
List<int> matches = Search(list, request.Search);
List<int> ordered = Sort(grid, columns, list, matches, request);
return new VirtualGridPage
{
Total = ordered.Count,
TotalWithoutSearch = list.Rows.Count,
Data = ordered.Skip(skip).Take(take).Select(i => list.Rows[i]).ToList(),
};
}
var sqlGrid = (VirtualGridSqlDefinition)grid;
VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context);
var page = new VirtualGridPage();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
page.Total = VirtualGridDA.Count(tc, query, true);
page.TotalWithoutSearch = query.SearchPattern == null ? page.Total : VirtualGridDA.Count(tc, query, false);
if (page.Total > skip)
page.Data = ReadRows(VirtualGridDA.GetRows(tc, query, skip, take));
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
// After the transaction: definitions may call other services that open their own.
FinishRows(sqlGrid, page.Data, context);
return page;
}
public VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context)
{
if (request == null)
throw new ArgumentException("Invalid request.");
VirtualGridDefinition grid = Open(request.GridKey, context);
List<VirtualGridColumn> columns = GetValidatedColumns(grid, context);
List<VirtualGridColumn> exportColumns = ResolveExportColumns(columns, request.Fields);
List<Dictionary<string, object>> rows;
string filterDescription;
var listSource = grid as IVirtualGridListSource;
if (listSource != null)
{
CachedList list = GetList(grid, listSource, columns, request, context);
List<int> ordered = Sort(grid, columns, list, Search(list, request.Search), request);
CheckExportLimit(grid, ordered.Count);
rows = ordered.Select(i => list.Rows[i]).ToList();
filterDescription = listSource.DescribeFilters(new VirtualGridFilters(request.Filters));
}
else
{
var sqlGrid = (VirtualGridSqlDefinition)grid;
VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context);
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
tc.CommandTimeOut = ExportCommandTimeoutSeconds;
CheckExportLimit(grid, VirtualGridDA.Count(tc, query, true));
rows = ReadRows(VirtualGridDA.GetRows(tc, query, 0, null));
tc.End();
}
catch (ArgumentException)
{
if (tc != null)
tc.HandleError();
throw;
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
FinishRows(sqlGrid, rows, context);
filterDescription = query.Source.FilterDescription;
}
return new VirtualGridFile
{
FileName = grid.ExcelFileName,
ContentType = ExcelContentType,
Content = BuildWorkbook(grid, exportColumns, rows, filterDescription, request.Search),
};
}
#endregion
#region Shared helpers
/// <summary>Finds the grid and checks the user may use it. Unknown key → ArgumentException.</summary>
private static VirtualGridDefinition Open(string gridKey, VirtualGridContext context)
{
if (context == null)
throw new UnauthorizedAccessException("Not signed in.");
VirtualGridDefinition grid = VirtualGridRegistry.Create(gridKey);
if (!(grid is IVirtualGridListSource) && !(grid is VirtualGridSqlDefinition))
throw new InvalidOperationException("Virtual grid '" + grid.Key
+ "' must derive from VirtualGridListDefinition<T> or VirtualGridSqlDefinition.");
if (context.UserType == EnumUserType.Employee && !grid.AllowSelfServiceUsers)
throw new UnauthorizedAccessException("You do not have access to " + grid.Title + ".");
return grid;
}
/// <summary>The definition's columns, checked so a bad definition fails loudly.</summary>
private static List<VirtualGridColumn> GetValidatedColumns(VirtualGridDefinition grid, VirtualGridContext context)
{
List<VirtualGridColumn> columns = grid.GetColumns(context) ?? new List<VirtualGridColumn>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (VirtualGridColumn c in columns)
{
if (!VirtualGridDefinition.IsIdentifier(c.Field) || c.Field.StartsWith("_") || !seen.Add(c.Field))
throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has an invalid or duplicate column field: " + c.Field);
}
if (columns.Count == 0)
throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has no columns.");
return columns;
}
private static VirtualGridColumn DefaultSortColumn(VirtualGridDefinition grid, List<VirtualGridColumn> columns)
{
VirtualGridColumn byName = columns.FirstOrDefault(c => grid.CanSort(c)
&& string.Equals(c.Field, grid.DefaultSortField, StringComparison.OrdinalIgnoreCase));
return byName ?? columns.FirstOrDefault(c => grid.CanSort(c));
}
/// <summary>The column to sort by and its direction: a sortable column the user picked, else the grid's default.</summary>
private static VirtualGridColumn ResolveSort(VirtualGridDefinition grid, List<VirtualGridColumn> columns,
VirtualGridRequest request, out bool descending)
{
VirtualGridColumn picked = columns.FirstOrDefault(c => grid.CanSort(c)
&& string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase));
descending = NormalizeDir(picked != null ? request.SortDir : grid.DefaultSortDir) == "desc";
return picked ?? DefaultSortColumn(grid, columns);
}
private static string NormalizeDir(string dir) =>
string.Equals(dir, "desc", StringComparison.OrdinalIgnoreCase) ? "desc" : "asc";
private static string CleanSearch(string search)
{
string term = (search ?? string.Empty).Trim();
return term.Length > MaxSearchLength ? term.Substring(0, MaxSearchLength) : term;
}
private static void CheckExportLimit(VirtualGridDefinition grid, int total)
{
if (total > grid.ExportRowLimit)
throw new ArgumentException("There are " + total.ToString("N0", CultureInfo.InvariantCulture)
+ " rows; Excel export is limited to " + grid.ExportRowLimit.ToString("N0", CultureInfo.InvariantCulture)
+ ". Please narrow the filters or the search.");
}
/// <summary>
/// A value as the screen shows it (dates "dd MMM yyyy", money "1,234.56"), so the search box finds
/// what the user sees. Mirrors the formatting in &lt;app-virtual-grid&gt;.
/// </summary>
private static string DisplayText(object value, EnumVirtualGridColumnType type)
{
if (value == null)
return string.Empty;
switch (type)
{
case EnumVirtualGridColumnType.Date:
if (value is DateTime d) return d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
break;
case EnumVirtualGridColumnType.DateTime:
if (value is DateTime dt) return dt.ToString("dd MMM yyyy HH:mm", CultureInfo.InvariantCulture);
break;
case EnumVirtualGridColumnType.Money:
if (value is IConvertible && !(value is string))
return Convert.ToDecimal(value, CultureInfo.InvariantCulture).ToString("N2", CultureInfo.InvariantCulture);
break;
}
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
#endregion
#region List grids (existing service + in-memory paging)
/// <summary>A loaded list plus, per row, the text the search box looks in.</summary>
private sealed class CachedList
{
public List<Dictionary<string, object>> Rows;
public List<string> SearchText;
}
/// <summary>
/// The grid's list for this user and these filters: from the cache, or — on Preview (Refresh) or
/// when the cache has expired — freshly from the grid's service.
/// </summary>
private static CachedList GetList(VirtualGridDefinition grid, IVirtualGridListSource source,
List<VirtualGridColumn> columns, VirtualGridRequest request, VirtualGridContext context)
{
string key = CacheKey(grid, columns, request, context);
CachedList list;
if (!request.Refresh && ListCache.TryGetValue(key, out list))
return list;
List<Dictionary<string, object>> rows = source.LoadRows(new VirtualGridFilters(request.Filters), context, columns);
List<VirtualGridColumn> searchable = columns.Where(c => grid.CanSearch(c)).ToList();
var searchText = new List<string>(rows.Count);
var sb = new StringBuilder();
foreach (Dictionary<string, object> row in rows)
{
sb.Clear();
foreach (VirtualGridColumn c in searchable)
{
object value;
row.TryGetValue(c.Field, out value);
sb.Append(DisplayText(value, c.Type)).Append('\u0001'); // separator: no match across two columns
}
searchText.Add(sb.ToString());
}
list = new CachedList { Rows = rows, SearchText = searchText };
ListCache.Set(key, list, new MemoryCacheEntryOptions
{
Size = Math.Max(1, rows.Count),
SlidingExpiration = ListCacheSliding,
AbsoluteExpirationRelativeToNow = ListCacheAbsolute,
});
return list;
}
/// <summary>One list per user, payroll type, grid and filter values (and column set, in case configuration changes).</summary>
private static string CacheKey(VirtualGridDefinition grid, List<VirtualGridColumn> columns,
VirtualGridRequest request, VirtualGridContext context)
{
var sb = new StringBuilder();
sb.Append(grid.Key.ToLowerInvariant())
.Append('|').Append(context.UserID)
.Append('|').Append(context.PayrollTypeID)
.Append('|').Append((int)context.UserType)
.Append('|').Append(string.Join(",", columns.Select(c => c.Field)));
foreach (KeyValuePair<string, string> f in (request.Filters ?? new Dictionary<string, string>())
.OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase))
sb.Append('|').Append(f.Key.ToLowerInvariant()).Append('=').Append(f.Value);
return sb.ToString();
}
/// <summary>Indexes of the rows whose shown text contains the search (case-insensitive); all rows when there is none.</summary>
private static List<int> Search(CachedList list, string search)
{
string term = CleanSearch(search);
var result = new List<int>(term.Length == 0 ? list.Rows.Count : 64);
for (int i = 0; i < list.Rows.Count; i++)
{
if (term.Length == 0 || list.SearchText[i].IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
result.Add(i);
}
return result;
}
/// <summary>Sorts row indexes by the chosen column (stable, so equal values keep the service's order).</summary>
private static List<int> Sort(VirtualGridDefinition grid, List<VirtualGridColumn> columns, CachedList list,
List<int> indexes, VirtualGridRequest request)
{
bool descending;
VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending);
if (sortColumn == null)
return indexes;
string field = sortColumn.Field;
Func<int, object> keyOf = i =>
{
object value;
list.Rows[i].TryGetValue(field, out value);
return value;
};
return (descending
? indexes.OrderByDescending(keyOf, ValueComparer.Instance)
: indexes.OrderBy(keyOf, ValueComparer.Instance))
.ToList();
}
/// <summary>Compares cell values: empty first, numbers as numbers, dates as dates, text case-insensitively.</summary>
private sealed class ValueComparer : IComparer<object>
{
public static readonly ValueComparer Instance = new ValueComparer();
public int Compare(object x, object y)
{
bool xEmpty = x == null || (x is string xs && xs.Length == 0);
bool yEmpty = y == null || (y is string ys && ys.Length == 0);
if (xEmpty || yEmpty)
return xEmpty == yEmpty ? 0 : (xEmpty ? -1 : 1);
if (x is string a && y is string b)
return StringComparer.InvariantCultureIgnoreCase.Compare(a, b);
if (IsNumber(x) && IsNumber(y))
return Convert.ToDecimal(x, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(y, CultureInfo.InvariantCulture));
if (x.GetType() == y.GetType() && x is IComparable comparable)
return comparable.CompareTo(y);
return StringComparer.InvariantCultureIgnoreCase.Compare(
Convert.ToString(x, CultureInfo.InvariantCulture), Convert.ToString(y, CultureInfo.InvariantCulture));
}
private static bool IsNumber(object v) =>
v is decimal || v is double || v is float || v is int || v is long || v is short || v is byte;
}
#endregion
#region SQL grids (VirtualGridDA)
private static VirtualGridQuery BuildQuery(VirtualGridSqlDefinition grid, List<VirtualGridColumn> columns,
VirtualGridRequest request, VirtualGridContext context)
{
VirtualGridSource source = grid.BuildSource(new VirtualGridFilters(request.Filters), context);
if (source == null || string.IsNullOrWhiteSpace(source.FromWhere))
throw new InvalidOperationException("Virtual grid '" + grid.Key + "' returned no source.");
var query = new VirtualGridQuery { Source = source, TieBreaker = grid.TieBreakerSql };
foreach (VirtualGridColumn c in columns.Where(c => !string.IsNullOrEmpty(c.Sql)))
query.Select.Add(c.Sql + " AS [" + c.Field + "]");
foreach (string hidden in grid.HiddenSelect)
query.Select.Add(hidden);
// Sort: only a sortable column of this grid; anything else falls back to the default.
bool descending;
VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending);
query.OrderBy = (sortColumn != null ? sortColumn.Sql : grid.TieBreakerSql) + (descending ? " DESC" : " ASC");
// Search: the user's text is a parameter; only LIKE wildcards are escaped.
string term = CleanSearch(request.Search);
if (term.Length > 0)
{
query.SearchPattern = "%" + term.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_").Replace("[", @"\[") + "%";
foreach (VirtualGridColumn c in columns.Where(c => grid.CanSearch(c)))
query.SearchColumns.Add(new KeyValuePair<string, EnumVirtualGridColumnType>(c.Sql, c.Type));
var extras = new VirtualGridSearchExtras();
grid.AddSearchExtras(term, extras, context);
query.SearchPredicates.AddRange(extras.Predicates);
}
return query;
}
private static List<Dictionary<string, object>> ReadRows(IDataReader reader)
{
var rows = new List<Dictionary<string, object>>();
try
{
int count = reader.FieldCount;
var names = new string[count];
for (int i = 0; i < count; i++)
names[i] = reader.GetName(i);
while (reader.Read())
{
var row = new Dictionary<string, object>(count, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < count; i++)
row[names[i]] = reader.IsDBNull(i) ? null : reader.GetValue(i);
rows.Add(row);
}
}
finally
{
reader.Close();
}
return rows;
}
/// <summary>Lets the definition fill computed columns, then drops the hidden "_" helper values.</summary>
private static void FinishRows(VirtualGridSqlDefinition grid, List<Dictionary<string, object>> rows, VirtualGridContext context)
{
if (rows.Count == 0)
return;
grid.OnRowsLoaded(rows, context);
foreach (Dictionary<string, object> row in rows)
{
foreach (string key in row.Keys.Where(k => k.StartsWith("_")).ToList())
row.Remove(key);
}
}
#endregion
#region Excel
/// <summary>The requested fields that are columns of this grid, in the requested order (all columns when none are given).</summary>
private static List<VirtualGridColumn> ResolveExportColumns(List<VirtualGridColumn> columns, List<string> fields)
{
if (fields == null || fields.Count == 0)
return columns;
var byField = columns.ToDictionary(c => c.Field, StringComparer.OrdinalIgnoreCase);
var result = new List<VirtualGridColumn>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string field in fields)
{
VirtualGridColumn c;
if (field != null && byField.TryGetValue(field.Trim(), out c) && seen.Add(c.Field))
result.Add(c);
}
if (result.Count == 0)
throw new ArgumentException("No columns to export.");
return result;
}
private static byte[] BuildWorkbook(VirtualGridDefinition grid, List<VirtualGridColumn> columns,
List<Dictionary<string, object>> rows, string filterDescription, string searchText)
{
const int headerRow = 5;
using (var workbook = new XLWorkbook())
{
string sheetName = grid.Title.Length > 31 ? grid.Title.Substring(0, 31) : grid.Title;
foreach (char ch in new[] { ':', '\\', '/', '?', '*', '[', ']' })
sheetName = sheetName.Replace(ch, ' ');
IXLWorksheet ws = workbook.Worksheets.Add(sheetName);
ws.Cell(1, 1).Value = grid.Title;
ws.Cell(1, 1).Style.Font.Bold = true;
ws.Cell(1, 1).Style.Font.FontSize = 14;
string line2 = filterDescription ?? string.Empty;
if (!string.IsNullOrWhiteSpace(searchText))
line2 += (line2.Length > 0 ? " | " : "") + "Search: " + searchText.Trim();
ws.Cell(2, 1).Value = line2;
ws.Cell(3, 1).Value = "Total: " + rows.Count.ToString("N0", CultureInfo.InvariantCulture);
for (int c = 0; c < columns.Count; c++)
{
ws.Cell(headerRow, c + 1).Value = columns[c].Title;
switch (columns[c].Type)
{
case EnumVirtualGridColumnType.Date:
ws.Column(c + 1).Style.DateFormat.Format = "dd MMM yyyy";
break;
case EnumVirtualGridColumnType.DateTime:
ws.Column(c + 1).Style.DateFormat.Format = "dd MMM yyyy HH:mm";
break;
case EnumVirtualGridColumnType.Money:
ws.Column(c + 1).Style.NumberFormat.Format = "#,##0.00";
break;
}
}
IXLRange header = ws.Range(headerRow, 1, headerRow, columns.Count);
header.Style.Font.Bold = true;
header.Style.Fill.BackgroundColor = XLColor.FromHtml("#E7ECF3");
header.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
header.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
int r = headerRow + 1;
foreach (Dictionary<string, object> row in rows)
{
for (int c = 0; c < columns.Count; c++)
{
object value;
if (!row.TryGetValue(columns[c].Field, out value) || value == null)
continue;
SetCell(ws.Cell(r, c + 1), value, columns[c].Type);
}
r++;
}
int lastRow = Math.Max(headerRow, r - 1);
ws.Range(headerRow, 1, lastRow, columns.Count).SetAutoFilter();
ws.SheetView.FreezeRows(headerRow);
// Measure the header and the first rows only: measuring every row is slow on large files.
ws.Columns(1, columns.Count).AdjustToContents(headerRow, Math.Min(lastRow, headerRow + 300), 8, 60);
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
return stream.ToArray();
}
}
}
private static void SetCell(IXLCell cell, object value, EnumVirtualGridColumnType type)
{
switch (type)
{
case EnumVirtualGridColumnType.Date:
case EnumVirtualGridColumnType.DateTime:
if (value is DateTime dt) { cell.Value = dt; return; }
break;
case EnumVirtualGridColumnType.Money:
case EnumVirtualGridColumnType.Number:
if (value is IConvertible && !(value is string) && !(value is DateTime))
{
cell.Value = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
return;
}
break;
}
cell.Value = Convert.ToString(value, CultureInfo.InvariantCulture); // text: no formulas, keeps leading zeros
}
#endregion
protected override T CreateObject<T>(DataReader dr)
{
throw new NotSupportedException("VirtualGridService reads rows generically.");
}
}
}

View File

@ -0,0 +1,77 @@
# Virtual paging: large lists with virtual scrolling
Data loads **the usual way**: DA query → service returns `List<BO>` → controller endpoint.
Only two common pieces are added:
| Piece | File | What it does |
|---|---|---|
| `VirtualPaging.Page(...)` | `HRM.DA/Service/VirtualPaging/VirtualPaging.cs` | Keeps the list in memory for a few minutes, then search, sort, 100 rows at a time and the total count |
| `<app-virtual-grid>` | `ClientApp/src/app/custom-components/virtual-grid/` (`VirtualGridModule`) | Virtual scrolling, search box, total, Export to Excel |
`VirtualPageRequest` / `VirtualPageResult` (`HRM.BO/VirtualPaging/VirtualPaging.cs`) are shared by every
page, so a page never needs its own request class.
## A new page: 2 steps
**1. Endpoint** in the module's own controller, calling the existing service:
```csharp
[HttpPost("getDiscontinueEmployeePage")]
public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DateTime fromDate = request.GetDate("fromDate", "From Date"); // the page's own filters
DateTime toDate = request.GetDate("toDate", "To Date");
return Ok(VirtualPaging.Page(request, currentUser,
() => _EmployeeService.GetDiscontinuedEmployeeDetails(fromDate, toDate, currentUser.PayrollTypeID ?? 0)));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
```
Read filters with `request.GetDate(name)`, `request.GetInt(name)` or `request.GetString(name)` (null when not sent).
**2. Screen**: import `VirtualGridModule`, then:
```html
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"
exportFileName="DiscontinueEmployeeDetails.xlsx"></app-virtual-grid>
```
```ts
columns: VirtualGridColumn[] = [
{ field: 'employeeNo', title: 'Employee No', width: 110 },
{ field: 'joiningDate', title: 'Joining Date', type: 'date' },
{ field: 'grossSalary', title: 'Gross Salary', type: 'money' },
];
preview() {
this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); // any filters; Dates are sent as yyyy-MM-dd
}
```
`field` is the property name of the BO (camelCase). Column `type`: `text` (default), `number`,
`money` (1,234.56), `date` (dd MMM yyyy), `datetime`. `sortable: false` turns sorting off for a column.
That is all. No registry, no extra service, no extra Angular service.
## How it runs
1. **Preview** → `grid.load(filters)` → the endpoint with `refresh: true` → the service is called once,
the list is kept in server memory (per user + endpoint + filters, 10 min since last use, 30 min at
most) → the first 100 rows and the total go back.
2. **Scroll / sort / search** → same endpoint, `refresh: false` → answered from the kept list.
3. **Export to Excel** → same endpoint with `take: 0` → every matching row → Kendo builds the `.xlsx`.
The browser shows ~100 rows at a time, however long the list is.
## Rules
- The service must not run one query per row; load lookups once (see `GetDiscontinuedEmployeeDetails`).
- Search looks in the text the grid shows (dates `dd MMM yyyy`, money `1,234.56`).
- Authorization is menu-driven in this app: put any extra check the page needs in its endpoint.

View File

@ -0,0 +1,200 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using HRM.BO;
using Microsoft.Extensions.Caching.Memory;
namespace HRM.DA
{
/// <summary>
/// Server side of &lt;app-virtual-grid&gt;: turns any List&lt;T&gt; into one window of rows (search, sort,
/// skip/take, total count). A page endpoint calls it with its existing service method:
///
/// [HttpPost("getDiscontinueEmployeePage")]
/// public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request)
/// {
/// CurrentUser user = CurrentUser.GetCurrentUser(HttpContext.User);
/// DateTime fromDate = request.GetDate("fromDate", "From Date");
/// DateTime toDate = request.GetDate("toDate", "To Date");
/// return Ok(VirtualPaging.Page(request, user,
/// () =&gt; _employeeService.GetDiscontinuedEmployeeDetails(fromDate, toDate, user.PayrollTypeID.Value)));
/// }
///
/// The list is loaded on Preview (request.Refresh) and kept in memory for a few minutes, per user,
/// endpoint and filters, so scrolling, sorting, searching and Export to Excel do not call the
/// service again. See README.md next to this file.
/// </summary>
public static class VirtualPaging
{
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000000 }); // max rows kept, all users together
private static readonly TimeSpan KeepFor = TimeSpan.FromMinutes(10); // since last use
private static readonly TimeSpan KeepAtMost = TimeSpan.FromMinutes(30); // since loaded
private const int MaxRowsPerPage = 1000;
public static VirtualPageResult Page<T>(VirtualPageRequest request, CurrentUser user, Func<List<T>> loadData,
[CallerFilePath] string callerFile = "", [CallerMemberName] string callerName = "") where T : class
{
if (request == null)
throw new ArgumentException("Invalid request.");
// 1. The list: from memory, or from the service on Preview / when it has expired.
string key = CacheKey(request, user, callerFile + "|" + callerName + "|" + typeof(T).FullName);
KeptList<T> kept;
if (request.Refresh || !Cache.TryGetValue(key, out kept))
{
kept = new KeptList<T>(loadData() ?? new List<T>());
Cache.Set(key, kept, new MemoryCacheEntryOptions
{
Size = Math.Max(1, kept.Items.Count),
SlidingExpiration = KeepFor,
AbsoluteExpirationRelativeToNow = KeepAtMost,
});
}
List<PropertyInfo> fields = GetFields<T>(request.Fields);
IEnumerable<int> rows = Enumerable.Range(0, kept.Items.Count);
// 2. Search: the text the grid shows, in any of the grid's columns.
string search = (request.Search ?? "").Trim();
if (search.Length > 0)
{
List<string> texts = kept.SearchTexts(fields);
rows = rows.Where(i => texts[i].IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0);
}
List<int> matched = rows.ToList();
// 3. Sort: only by one of the grid's columns.
PropertyInfo sortBy = fields.FirstOrDefault(p => string.Equals(p.Name, request.SortField, StringComparison.OrdinalIgnoreCase));
if (sortBy != null)
{
bool desc = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase);
matched = desc
? matched.OrderByDescending(i => sortBy.GetValue(kept.Items[i]), ValueComparer.Instance).ToList()
: matched.OrderBy(i => sortBy.GetValue(kept.Items[i]), ValueComparer.Instance).ToList();
}
// 4. The window: Take 0 = every row (Export to Excel).
int skip = Math.Max(0, request.Skip);
int take = request.Take <= 0 ? matched.Count : Math.Min(request.Take, MaxRowsPerPage);
var result = new VirtualPageResult { Total = matched.Count, TotalWithoutSearch = kept.Items.Count };
foreach (int i in matched.Skip(skip).Take(take))
{
var row = new Dictionary<string, object>(fields.Count);
foreach (PropertyInfo p in fields)
row[CamelCase(p.Name)] = p.GetValue(kept.Items[i]);
result.Data.Add(row);
}
return result;
}
#region Helpers
/// <summary>A loaded list, plus the search text of each row (worked out once, on the first search).</summary>
private sealed class KeptList<T>
{
private readonly ConcurrentDictionary<string, List<string>> _searchTexts = new ConcurrentDictionary<string, List<string>>();
public KeptList(List<T> items)
{
Items = items.Where(x => x != null).ToList();
}
public List<T> Items { get; }
public List<string> SearchTexts(List<PropertyInfo> fields)
{
string key = string.Join(",", fields.Select(p => p.Name));
return _searchTexts.GetOrAdd(key, _ => Items
.Select(item => string.Join("\u0001", fields.Select(p => DisplayText(p.GetValue(item)))))
.ToList());
}
}
/// <summary>The requested fields that are readable properties of T (unknown names are ignored). None requested = all.</summary>
private static List<PropertyInfo> GetFields<T>(List<string> names)
{
// When a class hides a base property with "new", keep the most derived one.
var properties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
for (Type t = typeof(T); t != null && t != typeof(object); t = t.BaseType)
{
foreach (PropertyInfo p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (p.CanRead && p.GetIndexParameters().Length == 0 && !properties.ContainsKey(p.Name))
properties[p.Name] = p;
}
}
if (names == null || names.Count == 0)
return properties.Values.ToList();
var result = new List<PropertyInfo>();
foreach (string name in names.Distinct(StringComparer.OrdinalIgnoreCase))
{
PropertyInfo p;
if (name != null && properties.TryGetValue(name, out p))
result.Add(p);
}
return result;
}
/// <summary>The text the grid shows for a value: dates "dd MMM yyyy", decimals "1,234.56".</summary>
private static string DisplayText(object value)
{
if (value == null)
return string.Empty;
if (value is DateTime d)
return d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
if (value is decimal || value is double || value is float)
{
decimal number = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
return number.ToString("N2", CultureInfo.InvariantCulture) + "\u0001" + number.ToString(CultureInfo.InvariantCulture);
}
if (value is Enum)
return value + "\u0001" + Convert.ToInt32(value, CultureInfo.InvariantCulture);
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
private static string CacheKey(VirtualPageRequest request, CurrentUser user, string endpoint)
{
string filters = string.Join("&", (request.Filters ?? new Dictionary<string, string>())
.OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase)
.Select(f => f.Key.ToLowerInvariant() + "=" + f.Value));
return endpoint + "|" + user?.UserID + "|" + user?.PayrollTypeID + "|" + filters;
}
private static string CamelCase(string name) =>
string.IsNullOrEmpty(name) ? name : char.ToLowerInvariant(name[0]) + name.Substring(1);
/// <summary>Empty values first; numbers, dates and text compared as such (text ignoring case).</summary>
private sealed class ValueComparer : IComparer<object>
{
public static readonly ValueComparer Instance = new ValueComparer();
public int Compare(object x, object y)
{
bool xEmpty = x == null || (x is string xs && xs.Length == 0);
bool yEmpty = y == null || (y is string ys && ys.Length == 0);
if (xEmpty || yEmpty)
return xEmpty == yEmpty ? 0 : (xEmpty ? -1 : 1);
if (x is string a && y is string b)
return StringComparer.InvariantCultureIgnoreCase.Compare(a, b);
if (IsNumber(x) && IsNumber(y))
return Convert.ToDecimal(x, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(y, CultureInfo.InvariantCulture));
if (x.GetType() == y.GetType() && x is IComparable comparable)
return comparable.CompareTo(y);
return StringComparer.InvariantCultureIgnoreCase.Compare(
Convert.ToString(x, CultureInfo.InvariantCulture), Convert.ToString(y, CultureInfo.InvariantCulture));
}
private static bool IsNumber(object v) =>
v is decimal || v is double || v is float || v is int || v is long || v is short || v is byte;
}
#endregion
}
}

View File

@ -1,54 +1,34 @@
/**
* Common virtual-scrolling grid (api/virtualGrid) — matches HRM.BO/VirtualGrid/VirtualGrid.cs.
* Screens use <app-virtual-grid gridKey="..."> (custom-components/virtual-grid) rather than these directly.
* <app-virtual-grid> (custom-components/virtual-grid) and its server side
* (HRM.BO/VirtualPaging/VirtualPaging.cs, HRM.DA/Service/VirtualPaging/VirtualPaging.cs).
*/
/** EnumVirtualGridColumnType on the server. */
export enum EnumVirtualGridColumnType {
Text = 1,
Number = 2,
Money = 3,
Date = 4,
DateTime = 5
}
/** How a column's values are shown (and exported to Excel). */
export type VirtualGridColumnType = 'text' | 'number' | 'money' | 'date' | 'datetime';
export interface VirtualGridColumnInfo {
/** One grid column. field = the property name of the server object, camelCase. */
export interface VirtualGridColumn {
field: string;
title: string;
width: number;
type: EnumVirtualGridColumnType;
sortable: boolean;
width?: number;
type?: VirtualGridColumnType; // default 'text'
sortable?: boolean; // default true
}
export interface VirtualGridLayout {
gridKey: string;
title: string;
defaultSortField: string;
defaultSortDir: 'asc' | 'desc';
maxPageSize: number;
columns: VirtualGridColumnInfo[];
}
/** Screen-specific filters, e.g. { fromDate: '2025-01-01', toDate: '2025-12-31' }. Dates as 'yyyy-MM-dd'. */
export type VirtualGridFilters = { [name: string]: string };
export interface VirtualGridRequest {
gridKey: string;
filters: VirtualGridFilters;
/** What the grid posts to the page endpoint (VirtualPageRequest on the server). */
export interface VirtualPageRequest {
filters: { [name: string]: string };
fields: string[];
skip: number;
take: number;
take: number; // 0 = all rows (Export to Excel)
search?: string;
sortField?: string;
sortDir?: 'asc' | 'desc';
/** True on Preview: reload the data instead of using the copy the server keeps for scrolling. */
refresh?: boolean;
refresh: boolean; // true on Preview
}
export interface VirtualGridExportRequest extends VirtualGridRequest {
fields: string[];
}
export interface VirtualGridPage {
/** What the page endpoint returns (VirtualPageResult on the server). */
export interface VirtualPageResult {
total: number;
totalWithoutSearch: number;
data: { [field: string]: any }[];

View File

@ -1,30 +0,0 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from 'src/app/app.api.service';
import {
VirtualGridExportRequest,
VirtualGridLayout,
VirtualGridPage,
VirtualGridRequest
} from 'src/app/_models/common/virtual-grid';
/** The one API for every virtual-scrolling grid (api/virtualGrid). */
@Injectable({
providedIn: 'root'
})
export class VirtualGridService {
constructor(private apiService: ApiService) {
}
getLayout(gridKey: string): Observable<VirtualGridLayout> {
return this.apiService.httpGet<VirtualGridLayout>('/virtualGrid/layout/' + encodeURIComponent(gridKey));
}
getPage(request: VirtualGridRequest): Observable<VirtualGridPage> {
return this.apiService.httpPost<VirtualGridPage>('/virtualGrid/page', request);
}
exportExcel(request: VirtualGridExportRequest): Observable<Blob> {
return this.apiService.httpDownloadFile('/virtualGrid/export-excel', request);
}
}

View File

@ -1,7 +1,4 @@
@if (layoutError) {
<div class="virtual-grid-message">{{ layoutError }}</div>
}
@if (started && layout) {
@if (started) {
<kendo-grid class="virtual-grid"
[data]="gridView"
[loading]="gridLoading"
@ -10,7 +7,7 @@
[pageSize]="pageSize"
[skip]="skip"
(pageChange)="onPageChange($event)"
[sortable]="{ mode: 'single', allowUnsort: false }"
[sortable]="{ mode: 'single', allowUnsort: true }"
[sort]="sort"
(sortChange)="onSortChange($event)"
[resizable]="true"
@ -32,13 +29,25 @@
</button>
}
</ng-template>
@for (column of layout.columns; track column.field) {
<kendo-grid-column [field]="column.field" [title]="column.title" [width]="column.width"
[sortable]="column.sortable"
[class]="{ 'virtual-grid-number': column.type === columnType.Money || column.type === columnType.Number }"
[headerClass]="{ 'virtual-grid-number': column.type === columnType.Money || column.type === columnType.Number }">
@for (column of columns; track column.field) {
<kendo-grid-column [field]="column.field" [title]="column.title" [width]="columnWidth(column)"
[format]="displayFormat(column)"
[sortable]="column.sortable !== false"
[class]="{ 'virtual-grid-number': isNumber(column) }"
[headerClass]="{ 'virtual-grid-number': isNumber(column) }">
</kendo-grid-column>
}
<!-- Excel: every matching row, loaded by exportExcel() -->
<kendo-grid-excel [fileName]="exportFileName" [fetchData]="excelData" (fileCreated)="onExcelCreated()">
@for (column of columns; track column.field) {
<kendo-excelexport-column [field]="column.field" [title]="column.title" [width]="columnWidth(column)"
[cellOptions]="excelOptions(column)">
</kendo-excelexport-column>
}
</kendo-grid-excel>
<ng-template kendoGridNoRecordsTemplate>
{{ noRecordsText }}
</ng-template>

View File

@ -1,25 +1,31 @@
import {
ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, LOCALE_ID, OnDestroy, OnInit, Optional, Output
ChangeDetectionStrategy, Component, EventEmitter, Input, OnDestroy, OnInit, Optional, Output, ViewChild
} from '@angular/core';
import { formatDate } from '@angular/common';
import { of, Subject, Subscription } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, finalize, switchMap } from 'rxjs/operators';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { ExcelExportData } from '@progress/kendo-angular-excel-export';
import { GridComponent, GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { SortDescriptor } from '@progress/kendo-data-query';
import { saveAs } from 'file-saver';
import { ApiService } from 'src/app/app.api.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { VirtualGridService } from 'src/app/_services/common/virtual-grid.service';
import {
EnumVirtualGridColumnType,
VirtualGridFilters,
VirtualGridLayout,
VirtualGridColumn,
VirtualGridLoadedEvent,
VirtualGridPage,
VirtualGridRequest
VirtualPageRequest,
VirtualPageResult
} from 'src/app/_models/common/virtual-grid';
/**
* Common virtual-scrolling grid. The page gives it an endpoint and the columns:
*
* <app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"></app-virtual-grid>
* this.grid.load({ fromDate: this.fromDate, toDate: this.toDate });
*
* The grid loads 100 rows at a time while the user scrolls; search, sort and the total count are done
* on the server (VirtualPaging.Page). Export to Excel downloads every matching row.
*/
@Component({
selector: 'app-virtual-grid',
templateUrl: './virtual-grid.component.html',
@ -28,26 +34,25 @@ import {
standalone: false,
})
export class VirtualGridComponent implements OnInit, OnDestroy {
/** Server grid key (VirtualGridRegistry). Required. */
@Input() gridKey: string;
/** Grid height in px. */
/** The page endpoint, e.g. '/Employee/getDiscontinueEmployeePage'. Required. */
@Input() url: string;
/** The columns. field = property name of the server object (camelCase). Required. */
@Input() columns: VirtualGridColumn[] = [];
@Input() height = 600;
/** Rows fetched per window. */
@Input() pageSize = 100;
/** Minimum (estimated) row height in px. Rows with wrapped text grow; Kendo measures the real heights while scrolling. */
/** Minimum row height; rows with wrapped text grow. */
@Input() rowHeight = 36;
@Input() searchPlaceholder = 'Search in all columns...';
@Input() noRecordsText = 'No records found.';
/** Excel file name; defaults to the grid title. */
@Input() exportFileName: string;
@Input() exportFileName = 'Export.xlsx';
@Input() showSearch = true;
@Input() showExport = true;
/** After every loaded window. */
@Output() loaded = new EventEmitter<VirtualGridLoadedEvent>();
layout: VirtualGridLayout;
layoutError = '';
@ViewChild(GridComponent) kendoGrid: GridComponent;
started = false;
gridView: GridDataResult = { data: [], total: 0 };
totalWithoutSearch = 0;
@ -57,67 +62,42 @@ export class VirtualGridComponent implements OnInit, OnDestroy {
searchText = '';
appliedSearch = '';
exporting = false;
exportRows: any[] = [];
readonly columnType = EnumVirtualGridColumnType;
private filters: VirtualGridFilters = {};
private pendingFilters: VirtualGridFilters = null;
private filters: { [name: string]: string } = {};
private firstLoad = false;
private readonly load$ = new Subject<VirtualGridRequest>();
private readonly load$ = new Subject<VirtualPageRequest>();
private readonly search$ = new Subject<string>();
private readonly subscriptions = new Subscription();
private readonly money = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
constructor(public apiService: ApiService,
private virtualGridService: VirtualGridService,
@Inject(LOCALE_ID) private locale: string,
@Optional() private notificationService: HRMNotificationService,
@Optional() private loadingPanel: loadingPanelService) {
}
ngOnInit(): void {
this.subscriptions.add(
this.virtualGridService.getLayout(this.gridKey).subscribe(
(layout) => {
layout.columns = (layout.columns || []).map(c => ({ ...c, width: this.fitWidth(c) }));
this.layout = layout;
this.resetSort();
if (this.pendingFilters) {
const filters = this.pendingFilters;
this.pendingFilters = null;
this.load(filters);
}
},
(err) => {
this.layoutError = this.errorText(err, 'Failed to load the grid.');
this.showError(this.layoutError);
}
)
);
// A newer request (scroll, sort, search) cancels an older one still in flight,
// so a slow response can never overwrite newer rows.
// A newer request (scroll, sort, search) cancels an older one, so old rows never overwrite new ones.
this.subscriptions.add(
this.load$.pipe(
switchMap(request => {
this.gridLoading = true;
return this.virtualGridService.getPage(request).pipe(
return this.apiService.httpPost<VirtualPageResult>(this.url, request).pipe(
catchError(err => {
this.showError(this.errorText(err, 'Failed to load data.'));
return of(null as VirtualGridPage);
return of(null as VirtualPageResult);
}),
finalize(() => this.gridLoading = false)
);
})
).subscribe(page => this.onPageLoaded(page))
).subscribe(result => this.onPageLoaded(result))
);
// Ask the server only once the user stops typing.
// Search only once the user stops typing.
this.subscriptions.add(
this.search$.pipe(debounceTime(400), distinctUntilChanged()).subscribe(text => {
this.appliedSearch = text;
this.skip = 0;
this.requestPage();
this.requestPage(false);
})
);
}
@ -126,138 +106,143 @@ export class VirtualGridComponent implements OnInit, OnDestroy {
this.subscriptions.unsubscribe();
}
/** Shows the grid for these filters, from the first row, with the search cleared and the default sort. */
load(filters: VirtualGridFilters): void {
if (!this.layout) {
this.pendingFilters = filters || {}; // runs as soon as the layout arrives
return;
}
this.filters = { ...(filters || {}) };
/** Preview: shows the grid for these filters (Date values are sent as 'yyyy-MM-dd'). */
load(filters: { [name: string]: any }): void {
this.filters = {};
Object.keys(filters || {}).forEach(name => {
const value = filters[name];
if (value !== null && value !== undefined && value !== '') {
this.filters[name] = value instanceof Date ? formatDate(value, 'yyyy-MM-dd', 'en-US') : String(value);
}
});
this.searchText = '';
this.appliedSearch = '';
this.search$.next(''); // keeps distinctUntilChanged in step with the cleared box
this.search$.next('');
this.skip = 0;
this.resetSort();
this.sort = [];
this.gridView = { data: [], total: 0 };
this.totalWithoutSearch = 0;
this.started = true;
this.firstLoad = true;
this.requestPage(true); // Preview: the server reloads the data instead of using its kept copy
}
/** Reloads the current window, keeping filters, search and sort. */
reload(): void {
this.requestPage();
this.requestPage(true);
}
onPageChange(event: PageChangeEvent): void {
this.skip = event.skip;
this.requestPage();
this.requestPage(false);
}
onSortChange(sort: SortDescriptor[]): void {
this.sort = sort;
this.skip = 0;
this.requestPage();
this.requestPage(false);
}
onSearchChange(text: string): void {
this.search$.next((text || '').trim());
}
/** Loads every matching row (same search and sort), then lets Kendo build the Excel file. */
exportExcel(): void {
if (!this.started || this.gridView.total === 0 || this.exporting) {
return;
}
this.exporting = true;
if (this.loadingPanel) {
this.loadingPanel.ShowLoadingPanel = true;
}
const request = { ...this.buildRequest(0, 0), fields: this.layout.columns.map(c => c.field) };
const fileName = this.exportFileName || (this.layout.title || this.gridKey).replace(/[^A-Za-z0-9]+/g, '') + '.xlsx';
this.virtualGridService.exportExcel(request).pipe(
finalize(() => {
this.exporting = false;
if (this.loadingPanel) {
this.loadingPanel.ShowLoadingPanel = false;
}
})
).subscribe(
(blob: Blob) => saveAs(blob, fileName),
(err) => this.showBlobError(err, 'Failed to export to Excel.')
this.setExporting(true);
this.apiService.httpPost<VirtualPageResult>(this.url, this.buildRequest(0, 0, false)).subscribe(
(result) => {
this.exportRows = (result.data || []).map(row => this.prepareRow(row));
setTimeout(() => this.kendoGrid.saveAsExcel());
},
(err) => {
this.setExporting(false);
this.showError(this.errorText(err, 'Failed to export to Excel.'));
}
);
}
/**
* At least wide enough for the header title on one line plus the sort icon and cell padding,
* so no grid ever needs a wrapped or cut-off header (~8px per character + 48px).
*/
private fitWidth(column: { title: string; width: number }): number {
const titleWidth = (column.title || '').length * 8 + 48;
return Math.max(column.width || 0, titleWidth);
/** Kendo asks for the rows to put in the Excel file. */
excelData = (): ExcelExportData => ({ data: this.exportRows });
onExcelCreated(): void {
this.exportRows = [];
this.setExporting(false);
}
private resetSort(): void {
this.sort = this.layout && this.layout.defaultSortField
? [{ field: this.layout.defaultSortField, dir: this.layout.defaultSortDir || 'asc' }]
: [];
}
private requestPage(refresh = false): void {
if (!this.started || !this.layout) {
return;
/** Grid display format by column type. */
displayFormat(column: VirtualGridColumn): string {
switch (column.type) {
case 'date': return '{0:dd MMM yyyy}';
case 'datetime': return '{0:dd MMM yyyy HH:mm}';
case 'money': return '{0:n2}';
default: return undefined;
}
this.load$.next({ ...this.buildRequest(this.skip, this.pageSize), refresh: refresh });
}
private buildRequest(skip: number, take: number): VirtualGridRequest {
/** Excel cell format by column type. */
excelOptions(column: VirtualGridColumn): any {
switch (column.type) {
case 'date': return { format: 'dd MMM yyyy' };
case 'datetime': return { format: 'dd MMM yyyy HH:mm' };
case 'money': return { format: '#,##0.00', textAlign: 'right' };
case 'number': return { textAlign: 'right' };
default: return {};
}
}
isNumber(column: VirtualGridColumn): boolean {
return column.type === 'money' || column.type === 'number';
}
/** At least wide enough for the header title on one line (~8px per character + sort icon/padding). */
columnWidth(column: VirtualGridColumn): number {
return Math.max(column.width || 130, (column.title || '').length * 8 + 48);
}
private requestPage(refresh: boolean): void {
if (this.started && this.url) {
this.load$.next(this.buildRequest(this.skip, this.pageSize, refresh));
}
}
private buildRequest(skip: number, take: number, refresh: boolean): VirtualPageRequest {
const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null;
return {
gridKey: this.gridKey,
filters: this.filters,
fields: this.columns.map(c => c.field),
skip: skip,
take: take,
search: this.appliedSearch || undefined,
sortField: sort ? sort.field : undefined,
sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined,
refresh: refresh,
};
}
private onPageLoaded(page: VirtualGridPage): void {
if (!page) {
private onPageLoaded(result: VirtualPageResult): void {
if (!result) {
return;
}
this.gridView = { data: (page.data || []).map(row => this.formatRow(row)), total: page.total };
this.totalWithoutSearch = page.totalWithoutSearch;
this.loaded.emit({ total: page.total, totalWithoutSearch: page.totalWithoutSearch, firstLoad: this.firstLoad });
this.gridView = { data: (result.data || []).map(row => this.prepareRow(row)), total: result.total };
this.totalWithoutSearch = result.totalWithoutSearch;
this.loaded.emit({ total: result.total, totalWithoutSearch: result.totalWithoutSearch, firstLoad: this.firstLoad });
this.firstLoad = false;
}
/** Display formatting by column type: dates 'dd MMM yyyy', money with 2 decimals — the same text the server searches. */
private formatRow(row: { [field: string]: any }): { [field: string]: any } {
const result: { [field: string]: any } = { ...row };
for (const column of this.layout.columns) {
const value = row[column.field];
if (value === null || value === undefined || value === '') {
result[column.field] = '';
continue;
}
switch (column.type) {
case EnumVirtualGridColumnType.Date:
result[column.field] = formatDate(value, 'dd MMM yyyy', this.locale);
break;
case EnumVirtualGridColumnType.DateTime:
result[column.field] = formatDate(value, 'dd MMM yyyy HH:mm', this.locale);
break;
case EnumVirtualGridColumnType.Money:
result[column.field] = this.money.format(Number(value));
break;
default:
result[column.field] = String(value);
/** Dates arrive as text; turn them into Date so the grid and Excel format them. */
private prepareRow(row: { [field: string]: any }): { [field: string]: any } {
for (const column of this.columns) {
if ((column.type === 'date' || column.type === 'datetime') && row[column.field]) {
row[column.field] = new Date(row[column.field]);
}
}
return result;
return row;
}
private setExporting(value: boolean): void {
this.exporting = value;
if (this.loadingPanel) {
this.loadingPanel.ShowLoadingPanel = value;
}
}
private errorText(err: any, fallback: string): string {
@ -277,14 +262,4 @@ export class VirtualGridComponent implements OnInit, OnDestroy {
console.error(message);
}
}
/** A failed file download returns its error message as a Blob; read it before showing it. */
private showBlobError(err: any, fallback: string): void {
const blob: Blob = err instanceof Blob ? err : (err && err.error instanceof Blob ? err.error : null);
if (blob) {
blob.text().then(text => this.showError(text || fallback), () => this.showError(fallback));
} else {
this.showError(this.errorText(err, fallback));
}
}
}

View File

@ -1,15 +1,16 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule } from '@progress/kendo-angular-grid';
import { ExcelModule, GridModule } from '@progress/kendo-angular-grid';
import { ExcelExportModule } from '@progress/kendo-angular-excel-export';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { TextBoxModule } from '@progress/kendo-angular-inputs';
import { VirtualGridComponent } from './virtual-grid.component';
/** Import this module to use <app-virtual-grid> (common server-paged virtual-scrolling grid). */
/** Import this module to use <app-virtual-grid> (common virtual-scrolling grid). */
@NgModule({
declarations: [VirtualGridComponent],
imports: [CommonModule, FormsModule, GridModule, ButtonsModule, TextBoxModule],
imports: [CommonModule, FormsModule, GridModule, ExcelModule, ExcelExportModule, ButtonsModule, TextBoxModule],
exports: [VirtualGridComponent]
})
export class VirtualGridModule {}

View File

@ -17,9 +17,9 @@
</div>
</fieldset>
<!-- Common server-paged virtual-scrolling grid; columns come from the server grid definition. -->
<!-- Common virtual-scrolling grid: data from the endpoint, columns from this page. -->
<div class="col-12">
<app-virtual-grid #grid gridKey="discontinue-employee" [height]="660"
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns" [height]="660"
exportFileName="DiscontinueEmployeeDetails.xlsx"
noRecordsText="No employee was discontinued in the selected date range."
(loaded)="onLoaded($event)">

View File

@ -1,16 +1,18 @@
import { Component, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Component, ChangeDetectionStrategy, OnInit, ViewChild } from '@angular/core';
import { ApiService } from 'src/app/app.api.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { VirtualGridComponent } from 'src/app/custom-components/virtual-grid/virtual-grid.component';
import { VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid';
import { VirtualGridColumn, VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid';
import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service';
import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration';
import { EnumConfigurationType } from 'src/app/_models/enums';
/**
* Discontinue Employee Details: employees discontinued inside a date range, with the same columns as
* Employee Details (/reports/report-viewer/empDetailInfo) plus the Discontinue Date.
*
* The grid is the common <app-virtual-grid> (server grid "discontinue-employee",
* HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs); this screen only owns its filters.
* Data: EmployeeController.GetDiscontinueEmployeePage → EmployeeService.GetDiscontinuedEmployeeDetails.
* The common <app-virtual-grid> does virtual scrolling, search, sort, total and Excel.
*/
@Component({
selector: 'app-discontinue-employee-details',
@ -19,19 +21,30 @@ import { VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid';
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class DiscontinueEmployeeDetailsComponent {
export class DiscontinueEmployeeDetailsComponent implements OnInit {
@ViewChild('grid') grid: VirtualGridComponent;
fromDate: Date = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
toDate: Date = new Date();
dateFormat = 'dd-MMM-yyyy';
/** Grid columns. field = property of DiscontinueEmployeeDetailInfo (camelCase). */
columns: VirtualGridColumn[] = [];
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
private datePipe: DatePipe) {
private systemConfigService: SystemConfigurationService) {
this.apiService.selectedMenuName = 'Discontinue Employee Details';
}
ngOnInit(): void {
// Department tier headings come from the Logic configuration, as in Employee Details.
this.systemConfigService.GetAllChildrenByParentNode(EnumConfigurationType.Logic, 'department').subscribe(
(configs: SystemConfigaration[]) => this.columns = this.buildColumns(configs || []),
() => this.columns = this.buildColumns([])
);
}
preview(): void {
if (!this.fromDate || !this.toDate) {
this.notificationService.showWarning('Please select From Date and To Date.', 'Warning');
@ -41,10 +54,7 @@ export class DiscontinueEmployeeDetailsComponent {
this.notificationService.showWarning('From Date cannot be after To Date.', 'Warning');
return;
}
this.grid.load({
fromDate: this.datePipe.transform(this.fromDate, 'yyyy-MM-dd'),
toDate: this.datePipe.transform(this.toDate, 'yyyy-MM-dd'),
});
this.grid.load({ fromDate: this.fromDate, toDate: this.toDate });
}
onLoaded(event: VirtualGridLoadedEvent): void {
@ -52,4 +62,45 @@ export class DiscontinueEmployeeDetailsComponent {
this.notificationService.showWarning('No employee was discontinued in the selected date range.', 'Warning');
}
}
private buildColumns(configs: SystemConfigaration[]): VirtualGridColumn[] {
const tierFields = ['deptireOne', 'deptireTwo', 'deptireThree', 'deptireFour', 'deptireFive'];
const tierColumns: VirtualGridColumn[] = configs
.filter(c => (c.node || '').toLowerCase() === 'text')
.slice(0, tierFields.length)
.map((c, i) => ({ field: tierFields[i], title: c.value, width: 150 }));
return [
{ field: 'employeeNo', title: 'Employee No', width: 110 },
{ field: 'name', title: 'Employee Name', width: 220 },
{ field: 'gender', title: 'Gender', width: 100 },
{ field: 'birthDate', title: 'Birth Date', width: 120, type: 'date' },
{ field: 'joiningDate', title: 'Joining Date', width: 120, type: 'date' },
{ field: 'discontinueDate', title: 'Discontinue Date', width: 140, type: 'date' },
{ field: 'mobileNo', title: 'Mobile No', width: 130 },
{ field: 'emailAddress', title: 'Email Address', width: 200 },
{ field: 'designation', title: 'Designation', width: 160 },
{ field: 'grade', title: 'Grade', width: 120 },
{ field: 'category', title: 'Category', width: 120 },
{ field: 'status', title: 'Status', width: 120 },
...tierColumns,
{ field: 'location', title: 'Location', width: 130 },
{ field: 'religion', title: 'Religion', width: 110 },
{ field: 'maritalStatus', title: 'Marital Status', width: 120 },
{ field: 'dateOfConfirmation', title: 'Confirmation', width: 120, type: 'date' },
{ field: 'basicSalary', title: 'Basic Salary', width: 120, type: 'money' },
{ field: 'grossSalary', title: 'Gross Salary', width: 120, type: 'money' },
{ field: 'passportNo', title: 'Passport No', width: 120 },
{ field: 'bloodGroup', title: 'Blood Group', width: 110 },
{ field: 'lineManagerNo', title: 'LineManager No', width: 130 },
{ field: 'lineManagerName', title: 'LineManager Name', width: 180 },
{ field: 'lineManagerEmail', title: 'LineManager Email', width: 200 },
{ field: 'empStatus', title: 'Employee Status', width: 130 },
{ field: 'bank', title: 'Bank', width: 150 },
{ field: 'branch', title: 'Branch', width: 150 },
{ field: 'accountNo', title: 'Account No', width: 150 },
{ field: 'nationalId', title: 'National ID/NID', width: 150 },
{ field: 'tinNo', title: 'TIN', width: 120 },
];
}
}

View File

@ -48,7 +48,6 @@ namespace HRM.UI.Configuration.DI
services.AddTransient<ILeaveEntryService, LeaveEntryService>();
services.AddTransient<IMaternityLeaveService, MaternityLeaveService>();
services.AddTransient<IEmployeeService, EmployeeService>();
services.AddTransient<IVirtualGridService, VirtualGridService>();
services.AddTransient<IADParameterService, ADParameterService>();
services.AddTransient<IADParameterEmployeeService, ADParameterEmployeeService>();
services.AddTransient<IApproveFinantialDataService, ApproveFinantialDataService>();

View File

@ -1,97 +0,0 @@
using System;
using HRM.BO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HRM.UI.Controllers.CommonInterface
{
[ApiController]
[Route("api/virtualGrid")]
[Authorize]
public class VirtualGridController : ControllerBase
{
private readonly IVirtualGridService _virtualGridService;
public VirtualGridController(IVirtualGridService virtualGridService)
{
_virtualGridService = virtualGridService;
}
[HttpGet("layout/{gridKey}")]
public ActionResult GetLayout(string gridKey)
{
try
{
return Ok(_virtualGridService.GetLayout(gridKey, GetContext()));
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
catch (UnauthorizedAccessException e)
{
return StatusCode(StatusCodes.Status403Forbidden, e.Message);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
[HttpPost("page")]
public ActionResult GetPage(VirtualGridRequest request)
{
try
{
return Ok(_virtualGridService.GetPage(request, GetContext()));
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
catch (UnauthorizedAccessException e)
{
return StatusCode(StatusCodes.Status403Forbidden, e.Message);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
[HttpPost("export-excel")]
public ActionResult ExportExcel(VirtualGridExportRequest request)
{
try
{
VirtualGridFile file = _virtualGridService.ExportExcel(request, GetContext());
return File(file.Content, file.ContentType, file.FileName);
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
catch (UnauthorizedAccessException e)
{
return StatusCode(StatusCodes.Status403Forbidden, e.Message);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
private VirtualGridContext GetContext()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
return new VirtualGridContext
{
UserID = currentUser.UserID,
EmployeeID = currentUser.EmployeeID,
PayrollTypeID = currentUser.PayrollTypeID,
UserType = currentUser.UserType,
};
}
}
}

View File

@ -3410,5 +3410,26 @@ namespace HRM.UI.Controllers
/// <summary>
/// Discontinue Employee Details (Manage Employee › Report): one window of rows for &lt;app-virtual-grid&gt;.
/// Filters: fromDate, toDate ("yyyy-MM-dd"). VirtualPaging does the search, sort and paging.
/// </summary>
[HttpPost("getDiscontinueEmployeePage")]
public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DateTime fromDate = request.GetDate("fromDate", "From Date");
DateTime toDate = request.GetDate("toDate", "To Date");
return Ok(VirtualPaging.Page(request, currentUser,
() => _EmployeeService.GetDiscontinuedEmployeeDetails(fromDate, toDate, currentUser.PayrollTypeID ?? 0)));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}