diff --git a/HRM.BO/VirtualGrid/VirtualGrid.cs b/HRM.BO/VirtualGrid/VirtualGrid.cs deleted file mode 100644 index d423bc5..0000000 --- a/HRM.BO/VirtualGrid/VirtualGrid.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace HRM.BO -{ - /// - /// 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 . - /// 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. - /// - public enum EnumVirtualGridColumnType - { - Text = 1, - Number = 2, - Money = 3, - Date = 4, - DateTime = 5 - } - - /// A column as the screen sees it (from the layout endpoint). - 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; } - } - - /// Everything the screen needs to draw an empty grid before any data is requested. - 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 Columns { get; set; } = new List(); - } - - /// One window request: which grid, its filters, and the grid's skip/take, sort and search. - public class VirtualGridRequest - { - public string GridKey { get; set; } - - /// - /// 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. - /// - public Dictionary Filters { get; set; } = new Dictionary(); - - 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; } - - /// - /// 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. - /// - public bool Refresh { get; set; } - } - - /// Excel export: the same request plus the grid's visible columns, in order. - public class VirtualGridExportRequest : VirtualGridRequest - { - /// Fields of the columns to export, in grid order. Empty = every column of the grid. - public List Fields { get; set; } = new List(); - } - - public class VirtualGridPage - { - /// Rows matching the filters and the search. - public int Total { get; set; } - - /// Rows matching the filters alone (equals Total when there is no search). - public int TotalWithoutSearch { get; set; } - - /// One row per entry, keyed by column field. Values are raw (dates, numbers); the screen formats them. - public List> Data { get; set; } = new List>(); - } - - /// A generated file (Excel export). - public class VirtualGridFile - { - public string FileName { get; set; } - public string ContentType { get; set; } - public byte[] Content { get; set; } - } - - /// The signed-in user, as the grid definitions need it for scoping (payroll type) and access. - 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); - } -} diff --git a/HRM.BO/VirtualPaging/VirtualPaging.cs b/HRM.BO/VirtualPaging/VirtualPaging.cs new file mode 100644 index 0000000..85e9cbf --- /dev/null +++ b/HRM.BO/VirtualPaging/VirtualPaging.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace HRM.BO +{ + /// + /// What <app-virtual-grid> 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. + /// + public class VirtualPageRequest + { + /// The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString. + public Dictionary Filters { get; set; } = new Dictionary(); + + /// The grid's columns (property names). Only these are sent back and searched. + public List Fields { get; set; } = new List(); + + public int Skip { get; set; } + + /// Rows wanted. 0 = all rows (used by Export to Excel). + public int Take { get; set; } = 100; + + public string Search { get; set; } + public string SortField { get; set; } + + /// "asc" or "desc". + public string SortDir { get; set; } + + /// True on Preview: load the data again. False on scroll/sort/search/export: use the kept copy. + public bool Refresh { get; set; } + + /// A filter as text, or null when it was not sent. + public string GetString(string name) + { + string value; + if (Filters != null && Filters.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value)) + return value.Trim(); + return null; + } + + /// A "yyyy-MM-dd" filter. Throws a message fit for the user when it is missing or invalid. + 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; + } + + /// A whole-number filter. Throws a message fit for the user when it is missing or invalid. + 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; + } + } + + /// One window of rows for the grid. + public class VirtualPageResult + { + /// Rows matching the search (all rows when there is no search). + public int Total { get; set; } + + /// All rows, ignoring the search. + public int TotalWithoutSearch { get; set; } + + /// The rows of this window, holding only the requested fields. + public List> Data { get; set; } = new List>(); + } +} diff --git a/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs b/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs deleted file mode 100644 index 24fd9fb..0000000 --- a/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs +++ /dev/null @@ -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 -{ - /// - /// 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. - /// - internal sealed class VirtualGridQuery - { - /// "sqlExpression AS [alias]" entries. - public List Select { get; } = new List(); - - public VirtualGridSource Source { get; set; } - - /// Columns searched with LIKE, with the type that decides how each is rendered as text. - public List> SearchColumns { get; } = - new List>(); - - /// Extra OR-branches of the search (code-produced, e.g. "e.DEPARTMENTID IN (1,2)"). - public List SearchPredicates { get; } = new List(); - - /// The escaped LIKE pattern ("%text%"), or null for no search. - public string SearchPattern { get; set; } - - /// Whitelisted sort expression including ASC/DESC. - public string OrderBy { get; set; } - - public string TieBreaker { get; set; } - } - - /// - /// 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. - /// - 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); - } - - /// One window of rows; with null, every row (Excel export). - 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)); - } - - /// A column as the screen displays it, so the user can search what they see. - 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 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(); - } - } -} diff --git a/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs b/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs deleted file mode 100644 index c65bc77..0000000 --- a/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using HRM.BO; -using HRM.BO.Report; - -namespace HRM.DA -{ - /// - /// 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<DiscontinueEmployeeDetailInfo> (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. - /// - internal sealed class DiscontinueEmployeeVirtualGrid : VirtualGridListDefinition - { - 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"; - - /// Each Field is a property of DiscontinueEmployeeDetailInfo. - public override List GetColumns(VirtualGridContext context) - { - var columns = new List - { - 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 configs = new SystemConfigarationService() - .GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department") ?? new List(); - 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 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); - } - } -} diff --git a/HRM.DA/Service/VirtualGrid/README.md b/HRM.DA/Service/VirtualGrid/README.md deleted file mode 100644 index 0ad94e6..0000000 --- a/HRM.DA/Service/VirtualGrid/README.md +++ /dev/null @@ -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` (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`, ``) | 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` 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/VirtualGrid.cs`: - ```csharp - internal sealed class LeaveHistoryVirtualGrid : VirtualGridListDefinition - { - public const string GridKey = "leave-history"; - public override string Key => GridKey; - public override string Title => "Leave History"; - - public override List GetColumns(VirtualGridContext context) => new List - { - // 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 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 - - ``` - ```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` (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. diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs b/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs deleted file mode 100644 index 02f8de1..0000000 --- a/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs +++ /dev/null @@ -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 -{ - /// - /// 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). - /// - 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; - - } - - /// - /// The rows a grid is built on: a "FROM ... WHERE ..." clause plus its parameters. - /// Filter values must only ever reach SQL through . - /// - internal sealed class VirtualGridSource - { - public string FromWhere { get; set; } - public List Parameters { get; } = new List(); - - /// Human-readable filter summary, printed at the top of the Excel file. - public string FilterDescription { get; set; } - } - - /// - /// 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. - /// - internal sealed class VirtualGridSearchExtras - { - internal List Predicates { get; } = new List(); - - /// Adds "sqlExpression IN (v1, v2, …)" — the values are integers, so they are safe to splice. - public void AddIntIn(string sqlExpression, IEnumerable values) - { - List list = (values ?? Enumerable.Empty()).Distinct().ToList(); - if (list.Count > 0) - Predicates.Add(sqlExpression + " IN (" + string.Join(",", list.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ")"); - } - } - - /// - /// Typed, validated access to . Every problem is an - /// ArgumentException with a message fit to show the user (the controller returns it as 400). - /// - internal sealed class VirtualGridFilters - { - private readonly Dictionary _values; - - public VirtualGridFilters(Dictionary values) - { - _values = new Dictionary(values ?? new Dictionary(), StringComparer.OrdinalIgnoreCase); - } - - public string GetString(string name) - { - string value; - return _values.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value) ? value.Trim() : null; - } - - /// A "yyyy-MM-dd" date. is the name the user sees ("From Date"). - 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; - } - } - - /// - /// 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<T> (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. - /// - internal abstract class VirtualGridDefinition - { - private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); - - /// The key the screen sends (e.g. "discontinue-employee"). - public abstract string Key { get; } - - public abstract string Title { get; } - - public virtual string DefaultSortField => null; // null = first sortable column - public virtual string DefaultSortDir => "asc"; - - /// Self-service (ESS) logins are refused unless a grid opts in. - public virtual bool AllowSelfServiceUsers => false; - - public virtual int MaxPageSize => 500; - - /// Largest Excel export allowed; past it the user is asked to narrow the filters. - public virtual int ExportRowLimit => 200000; - - public virtual string ExcelFileName => Regex.Replace(Title, "[^A-Za-z0-9]+", "") + ".xlsx"; - - /// The grid's columns, in display order. May depend on configuration (e.g. department tier names). - public abstract List GetColumns(VirtualGridContext context); - - /// Whether the user can sort by this column. - internal virtual bool CanSort(VirtualGridColumn column) => column.Sortable; - - /// Whether the search box looks in this column. - internal virtual bool CanSearch(VirtualGridColumn column) => column.Searchable; - - internal static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); - } - - /// - /// 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<LeaveEntry> LoadData(VirtualGridFilters filters, VirtualGridContext context) - /// => 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. - /// - internal abstract class VirtualGridListDefinition : VirtualGridDefinition, IVirtualGridListSource where T : class - { - /// Reads/validates the filters and returns the rows, usually with one call to an existing service. - protected abstract List LoadData(VirtualGridFilters filters, VirtualGridContext context); - - /// Human-readable filter summary, printed at the top of the Excel file. Optional. - public virtual string DescribeFilters(VirtualGridFilters filters) => null; - - /// Calls LoadData and turns each object into a row holding just the grid's columns. - List> IVirtualGridListSource.LoadRows( - VirtualGridFilters filters, VirtualGridContext context, List columns) - { - var properties = new List>(); - 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(c.Field, property)); - } - - List items = LoadData(filters, context) ?? new List(); - var rows = new List>(items.Count); - foreach (T item in items) - { - if (item == null) - continue; - var row = new Dictionary(properties.Count, StringComparer.OrdinalIgnoreCase); - foreach (KeyValuePair p in properties) - row[p.Key] = p.Value.GetValue(item); - rows.Add(row); - } - return rows; - } - - /// - /// The public property named (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. - /// - 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; - } - } - - /// Non-generic view of a list grid, used by VirtualGridService. - internal interface IVirtualGridListSource - { - List> LoadRows(VirtualGridFilters filters, VirtualGridContext context, List columns); - string DescribeFilters(VirtualGridFilters filters); - } - - /// - /// 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. - /// - internal abstract class VirtualGridSqlDefinition : VirtualGridDefinition - { - /// A unique, stable SQL expression (usually the primary key) used as the last sort key so pages never overlap. - public abstract string TieBreakerSql { get; } - - /// - /// 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. - /// - public virtual IEnumerable HiddenSelect => Enumerable.Empty(); - - /// Reads/validates the filters and returns the FROM/WHERE the grid is built on. - public abstract VirtualGridSource BuildSource(VirtualGridFilters filters, VirtualGridContext context); - - /// Adds OR-conditions for code-computed values matching the search text. Optional. - public virtual void AddSearchExtras(string term, VirtualGridSearchExtras extras, VirtualGridContext context) - { - } - - /// Fills code-computed columns (and reformats values) on one loaded window of rows. Optional. - public virtual void OnRowsLoaded(List> 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); - } -} diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs b/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs deleted file mode 100644 index e1357d4..0000000 --- a/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace HRM.DA -{ - /// - /// 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. - /// - internal static class VirtualGridRegistry - { - private static readonly Dictionary> Grids = - new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { DiscontinueEmployeeVirtualGrid.GridKey, () => new DiscontinueEmployeeVirtualGrid() }, - }; - - /// A fresh definition instance for one call. Throws ArgumentException for an unknown key. - internal static VirtualGridDefinition Create(string gridKey) - { - Func factory; - if (string.IsNullOrWhiteSpace(gridKey) || !Grids.TryGetValue(gridKey.Trim(), out factory)) - throw new ArgumentException("Unknown grid: " + gridKey); - return factory(); - } - } -} diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridService.cs b/HRM.DA/Service/VirtualGrid/VirtualGridService.cs deleted file mode 100644 index a5a3863..0000000 --- a/HRM.DA/Service/VirtualGrid/VirtualGridService.cs +++ /dev/null @@ -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 -{ - /// - /// The one service behind every virtual-scrolling grid (api/virtualGrid). It looks the grid up in - /// and serves it in one of two ways: - /// - /// - List grid (): 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 (): 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. - /// - 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 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 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 matches = Search(list, request.Search); - List 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 columns = GetValidatedColumns(grid, context); - List exportColumns = ResolveExportColumns(columns, request.Fields); - - List> rows; - string filterDescription; - - var listSource = grid as IVirtualGridListSource; - if (listSource != null) - { - CachedList list = GetList(grid, listSource, columns, request, context); - List 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 - - /// Finds the grid and checks the user may use it. Unknown key → ArgumentException. - 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 or VirtualGridSqlDefinition."); - if (context.UserType == EnumUserType.Employee && !grid.AllowSelfServiceUsers) - throw new UnauthorizedAccessException("You do not have access to " + grid.Title + "."); - return grid; - } - - /// The definition's columns, checked so a bad definition fails loudly. - private static List GetValidatedColumns(VirtualGridDefinition grid, VirtualGridContext context) - { - List columns = grid.GetColumns(context) ?? new List(); - var seen = new HashSet(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 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)); - } - - /// The column to sort by and its direction: a sortable column the user picked, else the grid's default. - private static VirtualGridColumn ResolveSort(VirtualGridDefinition grid, List 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."); - } - - /// - /// 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 <app-virtual-grid>. - /// - 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) - - /// A loaded list plus, per row, the text the search box looks in. - private sealed class CachedList - { - public List> Rows; - public List SearchText; - } - - /// - /// 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. - /// - private static CachedList GetList(VirtualGridDefinition grid, IVirtualGridListSource source, - List 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> rows = source.LoadRows(new VirtualGridFilters(request.Filters), context, columns); - - List searchable = columns.Where(c => grid.CanSearch(c)).ToList(); - var searchText = new List(rows.Count); - var sb = new StringBuilder(); - foreach (Dictionary 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; - } - - /// One list per user, payroll type, grid and filter values (and column set, in case configuration changes). - private static string CacheKey(VirtualGridDefinition grid, List 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 f in (request.Filters ?? new Dictionary()) - .OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase)) - sb.Append('|').Append(f.Key.ToLowerInvariant()).Append('=').Append(f.Value); - return sb.ToString(); - } - - /// Indexes of the rows whose shown text contains the search (case-insensitive); all rows when there is none. - private static List Search(CachedList list, string search) - { - string term = CleanSearch(search); - var result = new List(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; - } - - /// Sorts row indexes by the chosen column (stable, so equal values keep the service's order). - private static List Sort(VirtualGridDefinition grid, List columns, CachedList list, - List indexes, VirtualGridRequest request) - { - bool descending; - VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending); - if (sortColumn == null) - return indexes; - - string field = sortColumn.Field; - Func 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(); - } - - /// Compares cell values: empty first, numbers as numbers, dates as dates, text case-insensitively. - private sealed class ValueComparer : IComparer - { - 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 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(c.Sql, c.Type)); - var extras = new VirtualGridSearchExtras(); - grid.AddSearchExtras(term, extras, context); - query.SearchPredicates.AddRange(extras.Predicates); - } - - return query; - } - - private static List> ReadRows(IDataReader reader) - { - var rows = new List>(); - 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(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; - } - - /// Lets the definition fill computed columns, then drops the hidden "_" helper values. - private static void FinishRows(VirtualGridSqlDefinition grid, List> rows, VirtualGridContext context) - { - if (rows.Count == 0) - return; - grid.OnRowsLoaded(rows, context); - foreach (Dictionary row in rows) - { - foreach (string key in row.Keys.Where(k => k.StartsWith("_")).ToList()) - row.Remove(key); - } - } - - #endregion - - #region Excel - - /// The requested fields that are columns of this grid, in the requested order (all columns when none are given). - private static List ResolveExportColumns(List columns, List fields) - { - if (fields == null || fields.Count == 0) - return columns; - var byField = columns.ToDictionary(c => c.Field, StringComparer.OrdinalIgnoreCase); - var result = new List(); - var seen = new HashSet(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 columns, - List> 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 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(DataReader dr) - { - throw new NotSupportedException("VirtualGridService reads rows generically."); - } - } -} diff --git a/HRM.DA/Service/VirtualPaging/README.md b/HRM.DA/Service/VirtualPaging/README.md new file mode 100644 index 0000000..bde5940 --- /dev/null +++ b/HRM.DA/Service/VirtualPaging/README.md @@ -0,0 +1,77 @@ +# Virtual paging: large lists with virtual scrolling + +Data loads **the usual way**: DA query → service returns `List` → 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 | +| `` | `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 + +``` +```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. diff --git a/HRM.DA/Service/VirtualPaging/VirtualPaging.cs b/HRM.DA/Service/VirtualPaging/VirtualPaging.cs new file mode 100644 index 0000000..e9f7f1e --- /dev/null +++ b/HRM.DA/Service/VirtualPaging/VirtualPaging.cs @@ -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 +{ + /// + /// Server side of <app-virtual-grid>: turns any List<T> 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, + /// () => _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. + /// + 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(VirtualPageRequest request, CurrentUser user, Func> 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 kept; + if (request.Refresh || !Cache.TryGetValue(key, out kept)) + { + kept = new KeptList(loadData() ?? new List()); + Cache.Set(key, kept, new MemoryCacheEntryOptions + { + Size = Math.Max(1, kept.Items.Count), + SlidingExpiration = KeepFor, + AbsoluteExpirationRelativeToNow = KeepAtMost, + }); + } + + List fields = GetFields(request.Fields); + IEnumerable 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 texts = kept.SearchTexts(fields); + rows = rows.Where(i => texts[i].IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0); + } + List 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(fields.Count); + foreach (PropertyInfo p in fields) + row[CamelCase(p.Name)] = p.GetValue(kept.Items[i]); + result.Data.Add(row); + } + return result; + } + + #region Helpers + + /// A loaded list, plus the search text of each row (worked out once, on the first search). + private sealed class KeptList + { + private readonly ConcurrentDictionary> _searchTexts = new ConcurrentDictionary>(); + + public KeptList(List items) + { + Items = items.Where(x => x != null).ToList(); + } + + public List Items { get; } + + public List SearchTexts(List 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()); + } + } + + /// The requested fields that are readable properties of T (unknown names are ignored). None requested = all. + private static List GetFields(List names) + { + // When a class hides a base property with "new", keep the most derived one. + var properties = new Dictionary(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(); + foreach (string name in names.Distinct(StringComparer.OrdinalIgnoreCase)) + { + PropertyInfo p; + if (name != null && properties.TryGetValue(name, out p)) + result.Add(p); + } + return result; + } + + /// The text the grid shows for a value: dates "dd MMM yyyy", decimals "1,234.56". + 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()) + .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); + + /// Empty values first; numbers, dates and text compared as such (text ignoring case). + private sealed class ValueComparer : IComparer + { + 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 + } +} diff --git a/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts index 36e6f86..9b53a8f 100644 --- a/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts +++ b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts @@ -1,54 +1,34 @@ /** - * Common virtual-scrolling grid (api/virtualGrid) — matches HRM.BO/VirtualGrid/VirtualGrid.cs. - * Screens use (custom-components/virtual-grid) rather than these directly. + * (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 }[]; diff --git a/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts b/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts deleted file mode 100644 index 844a1b9..0000000 --- a/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts +++ /dev/null @@ -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 { - return this.apiService.httpGet('/virtualGrid/layout/' + encodeURIComponent(gridKey)); - } - - getPage(request: VirtualGridRequest): Observable { - return this.apiService.httpPost('/virtualGrid/page', request); - } - - exportExcel(request: VirtualGridExportRequest): Observable { - return this.apiService.httpDownloadFile('/virtualGrid/export-excel', request); - } -} diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html index eed4e8e..5609f05 100644 --- a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html @@ -1,7 +1,4 @@ -@if (layoutError) { -
{{ layoutError }}
-} -@if (started && layout) { +@if (started) { } - @for (column of layout.columns; track column.field) { - + + @for (column of columns; track column.field) { + } + + + + @for (column of columns; track column.field) { + + + } + + {{ noRecordsText }} diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts index 29a6536..3ded9a0 100644 --- a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts @@ -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: + * + * + * 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(); - 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(); + private readonly load$ = new Subject(); private readonly search$ = new Subject(); 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(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(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)); - } - } } diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts index 9b59add..8ba6e01 100644 --- a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts @@ -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 (common server-paged virtual-scrolling grid). */ +/** Import this module to use (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 {} diff --git a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html index 4a62400..6da365f 100644 --- a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html @@ -17,9 +17,9 @@ - +
- diff --git a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts index 9cea443..b12e45a 100644 --- a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts @@ -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 (server grid "discontinue-employee", - * HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs); this screen only owns its filters. + * Data: EmployeeController.GetDiscontinueEmployeePage → EmployeeService.GetDiscontinuedEmployeeDetails. + * The common 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 }, + ]; + } } diff --git a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs index 3838dab..3904c74 100644 --- a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs +++ b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs @@ -48,7 +48,6 @@ namespace HRM.UI.Configuration.DI services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs b/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs deleted file mode 100644 index a8a216c..0000000 --- a/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs +++ /dev/null @@ -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, - }; - } - } -} diff --git a/HRM.UI/Controllers/Employee/EmployeeController.cs b/HRM.UI/Controllers/Employee/EmployeeController.cs index 9dd96d8..174fea6 100644 --- a/HRM.UI/Controllers/Employee/EmployeeController.cs +++ b/HRM.UI/Controllers/Employee/EmployeeController.cs @@ -3410,5 +3410,26 @@ namespace HRM.UI.Controllers + /// + /// Discontinue Employee Details (Manage Employee › Report): one window of rows for <app-virtual-grid>. + /// Filters: fromDate, toDate ("yyyy-MM-dd"). VirtualPaging does the search, sort and paging. + /// + [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); + } + } } } \ No newline at end of file