diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index 1bd8cd2..14a1a81 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -608,7 +608,7 @@ namespace HRM.BO DataSet GetEmpDetailsView(); // Discontinue Employee Details report: employees discontinued (Status = Discontinued) whose // discontinue date (ENDOFCONTRACTDATE) falls inside the range, in one payroll type. - List GetDiscontinuedEmployeeDetails(DateTime fromDate, DateTime toDate, int payrollTypeID); + VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID); int GetCurrentHeadCount(int departmentId, int designationId, int gradeId); List GetbyDepartment(int deptId); List NotYetAssigned(int payrollTypeID); diff --git a/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs b/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs deleted file mode 100644 index ce6c286..0000000 --- a/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace HRM.BO.Report -{ - /// - /// One row of the Discontinue Employee Details report (Manage Employee › Report): the same fields as - /// Employee Details () plus the date the employee was discontinued - /// (Employee.ENDOFCONTRACTDATE). Loaded by IEmployeeService.GetDiscontinuedEmployeeDetails. - /// - public class DiscontinueEmployeeDetailInfo : EmployeeDetailInfo - { - public DateTime? DiscontinueDate { get; set; } - } -} diff --git a/HRM.BO/VirtualPaging/VirtualPaging.cs b/HRM.BO/VirtualPaging/VirtualPaging.cs index 85e9cbf..d4cd09b 100644 --- a/HRM.BO/VirtualPaging/VirtualPaging.cs +++ b/HRM.BO/VirtualPaging/VirtualPaging.cs @@ -5,17 +5,17 @@ using System.Globalization; namespace HRM.BO { /// - /// What <app-virtual-grid> sends to a page endpoint: the page's own filters plus the grid's + /// What <app-virtual-grid> sends to a page endpoint: the page's own filters plus the grid's columns, /// 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. + /// request class of its own. See HRM.DA/DA/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(); + /// The grid's columns. Only these are selected, searched and sortable. + public List Columns { get; set; } = new List(); public int Skip { get; set; } @@ -28,8 +28,11 @@ namespace HRM.BO /// "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; } + /// + /// True when the totals must be counted (Preview, new search). Scrolling and sorting do not change + /// the totals, so they send false and the COUNT is skipped. + /// + public bool CountTotal { get; set; } /// A filter as text, or null when it was not sent. public string GetString(string name) @@ -59,16 +62,25 @@ namespace HRM.BO } } + /// One grid column: Field = a column alias of the page's query; Type = how it is shown. + public class VirtualPageColumn + { + public string Field { get; set; } + + /// "text" (default), "number", "money", "date" or "datetime". + public string Type { get; set; } + } + /// 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; } + /// Rows matching the search (all rows when there is no search). Null when not counted (CountTotal = false). + public int? Total { get; set; } - /// All rows, ignoring the search. - public int TotalWithoutSearch { get; set; } + /// All rows, ignoring the search. Null when not counted. + public int? TotalWithoutSearch { get; set; } - /// The rows of this window, holding only the requested fields. + /// The rows of this window, holding only the requested columns. public List> Data { get; set; } = new List>(); } } diff --git a/HRM.DA/DA/Employee/EmployeeDA.cs b/HRM.DA/DA/Employee/EmployeeDA.cs index 4f290b5..5efc8aa 100644 --- a/HRM.DA/DA/Employee/EmployeeDA.cs +++ b/HRM.DA/DA/Employee/EmployeeDA.cs @@ -1597,20 +1597,68 @@ namespace HRM.DA return oEmpDetails; } - // Discontinue Employee Details report: the Employee Details view (VW_EMPLOYEEBASIC) for employees - // discontinued between fromDate and toDate (inclusive), plus their department and discontinue date. - // The end is exclusive (toDate + 1 day) so a time part on ENDOFCONTRACTDATE never drops the last day. - internal static IDataReader GetDiscontinuedEmployeeDetails(TransactionContext tc, DateTime fromDate, - DateTime toDate, int payrollTypeID) + /// + /// Discontinue Employee Details (Manage Employee › Report): one row per employee discontinued + /// (STATUS = Discontinued) between fromDate and toDate in one payroll type, with the same columns as + /// the Employee Details report. Column aliases are the grid's field names; VirtualPagingDA adds the + /// search, sort and paging, so there is no ORDER BY here. + /// + /// Department tiers: the employee's department sits at its own tier (TIRE) and its parents fill the + /// tiers above it, as EmployeeController.GetEmpDetailInfo works them out (no tiers for a department + /// without a parent). The end date is exclusive (toDate + 1 day) so a time part never drops the last day. + /// + internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) { - string sql = SQLParser.MakeSQL(@"SELECT v.*, e.DEPARTMENTID AS EmpDepartmentID, e.ENDOFCONTRACTDATE AS DiscontinueDate - FROM VW_EMPLOYEEBASIC v - INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId - WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n - AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d - ORDER BY v.EMPLOYEENO", + return SQLParser.MakeSQL(@" +SELECT + v.EMPLOYEENO AS employeeNo, + v.NAME AS name, + v.Gender AS gender, + v.BIRTHDATE AS birthDate, + v.JOININGDATE AS joiningDate, + e.ENDOFCONTRACTDATE AS discontinueDate, + v.MOBILENO AS mobileNo, + v.EMAILADDRESS AS emailAddress, + v.DESIGNATION AS designation, + v.GRADE AS grade, + v.Category AS category, + v.Status AS status, + ISNULL(CASE t.Tier WHEN 1 THEN d0.DESCRIPTION WHEN 2 THEN d1.DESCRIPTION WHEN 3 THEN d2.DESCRIPTION + WHEN 4 THEN d3.DESCRIPTION WHEN 5 THEN d4.DESCRIPTION END, '') AS deptireOne, + ISNULL(CASE t.Tier WHEN 2 THEN d0.DESCRIPTION WHEN 3 THEN d1.DESCRIPTION WHEN 4 THEN d2.DESCRIPTION + WHEN 5 THEN d3.DESCRIPTION END, '') AS deptireTwo, + ISNULL(CASE t.Tier WHEN 3 THEN d0.DESCRIPTION WHEN 4 THEN d1.DESCRIPTION WHEN 5 THEN d2.DESCRIPTION END, '') AS deptireThree, + ISNULL(CASE t.Tier WHEN 4 THEN d0.DESCRIPTION WHEN 5 THEN d1.DESCRIPTION END, '') AS deptireFour, + ISNULL(CASE t.Tier WHEN 5 THEN d0.DESCRIPTION END, '') AS deptireFive, + v.Location AS location, + v.RELIGION AS religion, + v.MaritalStatus AS maritalStatus, + v.DATEOFCONFIRMATION AS dateOfConfirmation, + ISNULL(v.BASICSALARY, 0) AS basicSalary, + ISNULL(v.GrossSalary, 0) AS grossSalary, + v.PassPortNo AS passportNo, + CASE ISNULL(v.bloodgroup, 0) WHEN 0 THEN 'NA' WHEN 1 THEN 'A+' WHEN 2 THEN 'A-' WHEN 3 THEN 'B+' + WHEN 4 THEN 'B-' WHEN 5 THEN 'O+' WHEN 6 THEN 'O-' WHEN 7 THEN 'AB+' WHEN 8 THEN 'AB-' ELSE '' END AS bloodGroup, + v.LineManagerNo AS lineManagerNo, + v.LineManagerName AS lineManagerName, + v.LineManagerEmail AS lineManagerEmail, + v.EmpStatus AS empStatus, + ISNULL(NULLIF(v.Bank, ''), v.OUTPayBank) AS bank, + ISNULL(NULLIF(v.Branch, ''), v.OUTPayBranch) AS branch, + ISNULL(NULLIF(v.ACCOUNTNO, ''), v.OutPayAccountNo) AS accountNo, + v.NATIONALID AS nationalId, + v.TINNO AS tinNo +FROM VW_EMPLOYEEBASIC v +INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId +LEFT JOIN DEPARTMENT d0 ON d0.DEPARTMENTID = e.DEPARTMENTID +LEFT JOIN DEPARTMENT d1 ON d1.DEPARTMENTID = d0.PARENTID +LEFT JOIN DEPARTMENT d2 ON d2.DEPARTMENTID = d1.PARENTID +LEFT JOIN DEPARTMENT d3 ON d3.DEPARTMENTID = d2.PARENTID +LEFT JOIN DEPARTMENT d4 ON d4.DEPARTMENTID = d3.PARENTID +CROSS APPLY (SELECT CASE WHEN d0.PARENTID IS NULL THEN 0 WHEN d0.TIRE > 5 THEN 5 ELSE d0.TIRE END AS Tier) t +WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n + AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d", (int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1)); - return tc.ExecuteReader(sql); } internal static DataSet GetEmpDetailsView(TransactionContext tc) diff --git a/HRM.DA/DA/VirtualPaging/README.md b/HRM.DA/DA/VirtualPaging/README.md new file mode 100644 index 0000000..439cd70 --- /dev/null +++ b/HRM.DA/DA/VirtualPaging/README.md @@ -0,0 +1,119 @@ +# Virtual paging: large lists with virtual scrolling + +SQL Server does the paging. Each request reads only the rows the grid needs (100 at a time) with +`OFFSET … FETCH`, and the search, sort and total count run in the same SQL. Nothing is kept in server +memory, so it works the same for 1,000 or 1,000,000 rows and always shows the latest data. + +| Piece | File | What it does | +|---|---|---| +| Request / result | `HRM.BO/VirtualPaging/VirtualPaging.cs` | `VirtualPageRequest` (filters, columns, skip/take, search, sort) and `VirtualPageResult`, shared by every page | +| Paging SQL | `HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs` | Wraps a page's query with search, sort, `OFFSET/FETCH` and the totals | +| Grid | `ClientApp/src/app/custom-components/virtual-grid/` (`VirtualGridModule`) | ``: virtual scrolling, search box, total, Export to Excel | + +## A new page: 4 small steps (worked example: Discontinue Employee Details) + +**1. DA: the query.** An ordinary `SELECT` built with `MakeSQL`. Each column alias is a grid field name. +No `ORDER BY` and no `WITH` (the query is used as a derived table). + +```csharp +internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) +{ + return SQLParser.MakeSQL(@" +SELECT v.EMPLOYEENO AS employeeNo, + v.NAME AS name, + v.JOININGDATE AS joiningDate, + ISNULL(v.BASICSALARY, 0) AS basicSalary +FROM VW_EMPLOYEEBASIC v +INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId +WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n + AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d", + (int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1)); +} +``` + +**2. Service: one method** (canonical try/catch) + its line in the module's `I…Service` interface: + +```csharp +public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID) +{ + VirtualPageResult result = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); // "employeeNo" = a unique field + tc.End(); + } + catch (Exception e) + { + if (tc != null) tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + } + return result; +} +``` + +**3. Controller: one endpoint** in the module's own controller. Read the page's filters from the request: + +```csharp +[HttpPost("getDiscontinueEmployeePage")] +public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request) +{ + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see this report."); + + DateTime fromDate = request.GetDate("fromDate", "From Date"); // also GetInt / GetString + DateTime toDate = request.GetDate("toDate", "To Date"); + return Ok(_EmployeeService.GetDiscontinuedEmployeePage(request, fromDate, toDate, currentUser.PayrollTypeID ?? 0)); + } + catch (ArgumentException ex) { return BadRequest(ex.Message); } + catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } +} +``` + +**4. Screen**: import `VirtualGridModule`, then: + +```html + +``` +```ts +columns: VirtualGridColumn[] = [ + { field: 'employeeNo', title: 'Employee No', width: 110 }, + { field: 'joiningDate', title: 'Joining Date', type: 'date' }, + { field: 'basicSalary', title: 'Basic Salary', type: 'money' }, +]; + +preview() { + this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); // any filters; Dates go as yyyy-MM-dd +} +``` + +`field` = the column alias in the query. Column `type`: `text` (default), `number`, `money` (1,234.56), +`date` (dd MMM yyyy), `datetime`. `sortable: false` turns sorting off for a column. + +## How one request runs + +| User action | Request | SQL | +|---|---|---| +| Preview | `skip 0, take 100, countTotal true` | `COUNT` + first 100 rows, one round trip | +| Scroll | `skip 100, 200, …` | next 100 rows only (no `COUNT`) | +| Sort | `sortField`, `sortDir` | `ORDER BY` that column, then the unique field | +| Search (after 400 ms) | `search`, `countTotal true` | `WHERE` every column `LIKE @vpSearch`, new `COUNT` | +| Export to Excel | `take 0` | every matching row, same search and sort; Kendo builds the `.xlsx` | + +## Rules + +- **Speed**: the page query's `WHERE` must use an index (see `DiscontinueEmployeeReport_DB_Changes.sql`). + Values computed in C# cannot be searched or sorted, so compute them in the query (see the department + tiers and blood group in `GetDiscontinuedEmployeeQuery`). +- **Safety**: the query is built by code with `MakeSQL` from typed values (dates, ints). The search text, + skip and take are SQL parameters; field names must be plain identifiers and are bracketed. +- **Access**: authorization in this app is menu-driven, so every page endpoint checks who may call it + (self-service logins are refused above). +- The key field passed to `GetPage` must be unique, so pages never overlap or skip rows. diff --git a/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs b/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs new file mode 100644 index 0000000..0b56d90 --- /dev/null +++ b/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Ease.Core.DataAccess; +using Ease.Core.DataAccess.SQL; +using HRM.BO; +using Microsoft.Data.SqlClient; + +namespace HRM.DA +{ + /// + /// Server side of <app-virtual-grid>: SQL Server does the paging. Each call reads only one window + /// of rows (OFFSET/FETCH), with the search and sort in the same SQL and the totals counted only when + /// they can change. A page's service calls it with its own query: + /// + /// string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + /// return VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); + /// + /// The query is an ordinary SELECT whose column aliases are the grid's field names, with no ORDER BY + /// and no WITH (it is used as a derived table). See README.md next to this file. + /// + /// Safety: the page query is built by code with MakeSQL; user input (search text, skip, take) reaches + /// SQL only as parameters; field names are checked to be plain identifiers and bracketed. + /// + internal static class VirtualPagingDA + { + private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); + private const int MaxRowsPerPage = 1000; + private const int MaxSearchLength = 200; + + /// The page's SELECT (column aliases = grid fields, no ORDER BY). + /// A unique field (e.g. employeeNo): the default sort and the tie-breaker that keeps pages from overlapping. + internal static VirtualPageResult GetPage(TransactionContext tc, string query, VirtualPageRequest request, string keyField) + { + if (request == null) + throw new ArgumentException("Invalid request."); + if (!IsIdentifier(keyField)) + throw new ArgumentException("Invalid key field."); + + List columns = GetColumns(request.Columns); + string search = (request.Search ?? "").Trim(); + if (search.Length > MaxSearchLength) + search = search.Substring(0, MaxSearchLength); + + string source = " FROM (" + query + ") AS vp"; + string searchCondition = search.Length > 0 ? SearchCondition(columns) : null; + bool paged = request.Take > 0; + + var sql = new StringBuilder(); + + // 1. Totals, only on Preview / new search (scroll and sort do not change them). One scan for both. + if (request.CountTotal) + { + sql.Append("SELECT COUNT(*) AS TotalWithoutSearch, ") + .Append(searchCondition == null ? "COUNT(*)" : "ISNULL(SUM(CASE WHEN " + searchCondition + " THEN 1 ELSE 0 END), 0)") + .Append(" AS Total").Append(source).Append(";\n"); + } + + // 2. The window of rows. + sql.Append("SELECT ") + .Append(columns.Count == 0 ? "*" : string.Join(", ", columns.Select(c => "[" + c.Field + "]"))) + .Append(source) + .Append(searchCondition == null ? "" : " WHERE " + searchCondition) + .Append(" ORDER BY ").Append(OrderBy(columns, request, keyField)); + if (paged) + sql.Append(" OFFSET @vpSkip ROWS FETCH NEXT @vpTake ROWS ONLY"); + + var parameters = new List(); // SqlHelper expects a SqlParameter[] + if (searchCondition != null) + parameters.Add(SqlHelperExtension.CreateInParam("@vpSearch", SqlDbType.NVarChar, "%" + EscapeLike(search) + "%", 400)); + if (paged) + { + parameters.Add(SqlHelperExtension.CreateInParam("@vpSkip", SqlDbType.Int, Math.Max(0, request.Skip))); + parameters.Add(SqlHelperExtension.CreateInParam("@vpTake", SqlDbType.Int, Math.Min(request.Take, MaxRowsPerPage))); + } + + var result = new VirtualPageResult(); + using (IDataReader reader = tc.ExecuteReader(CommandType.Text, sql.ToString(), parameters.ToArray())) + { + if (request.CountTotal) + { + if (reader.Read()) + { + result.TotalWithoutSearch = Convert.ToInt32(reader["TotalWithoutSearch"]); + result.Total = Convert.ToInt32(reader["Total"]); + } + reader.NextResult(); + } + + while (reader.Read()) + { + var row = new Dictionary(reader.FieldCount); + for (int i = 0; i < reader.FieldCount; i++) + row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); + result.Data.Add(row); + } + } + return result; + } + + /// The requested columns; every field must be a plain identifier (it is put in the SQL in brackets). + private static List GetColumns(List requested) + { + var columns = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (VirtualPageColumn c in requested ?? new List()) + { + if (c == null || !IsIdentifier(c.Field)) + throw new ArgumentException("Invalid column: " + c?.Field); + if (seen.Add(c.Field)) + columns.Add(c); + } + return columns; + } + + /// + /// "column LIKE @vpSearch" for every column, OR-ed, on the text the grid shows: + /// dates "13 Feb 2025", money "1,234.56" (or "1234.56"). + /// + private static string SearchCondition(List columns) + { + const string like = " LIKE @vpSearch ESCAPE '\\'"; + var parts = new List(); + foreach (VirtualPageColumn c in columns) + { + string f = "[" + c.Field + "]"; + switch ((c.Type ?? "").ToLowerInvariant()) + { + case "date": + parts.Add("CONVERT(varchar(11), " + f + ", 106)" + like); + break; + case "datetime": + parts.Add("(CONVERT(varchar(11), " + f + ", 106) + ' ' + CONVERT(varchar(5), " + f + ", 108))" + like); + break; + case "money": + parts.Add("CONVERT(varchar(30), CAST(" + f + " AS money), 1)" + like); + parts.Add("CONVERT(varchar(30), CAST(" + f + " AS money), 0)" + like); + break; + default: + parts.Add("CONVERT(nvarchar(4000), " + f + ")" + like); + break; + } + } + return parts.Count == 0 ? "1 = 0" : "(" + string.Join(" OR ", parts) + ")"; + } + + /// The grid's sort (only by one of its columns), then the key field so the order is always the same. + private static string OrderBy(List columns, VirtualPageRequest request, string keyField) + { + VirtualPageColumn sort = columns.FirstOrDefault(c => string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase)); + if (sort == null || string.Equals(sort.Field, keyField, StringComparison.OrdinalIgnoreCase)) + { + bool keyDesc = sort != null && string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); + return "[" + keyField + "]" + (keyDesc ? " DESC" : " ASC"); + } + bool desc = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); + return "[" + sort.Field + "]" + (desc ? " DESC" : " ASC") + ", [" + keyField + "] ASC"; + } + + /// Makes %, _, [ and \ in the search text match themselves. + private static string EscapeLike(string text) => + text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_").Replace("[", "\\["); + + private static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); + } +} diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index cb05a7e..a05ad4a 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -2733,26 +2733,19 @@ namespace HRM.DA #region Discontinue Employee Details /// - /// Employees discontinued between fromDate and toDate (by discontinue date) in one payroll type, with - /// the same fields, null handling and department tiers as the Employee Details report. - /// One query for all rows; departments are loaded once and looked up by ID. + /// Discontinue Employee Details: one window of rows for the grid. SQL Server pages, searches and + /// sorts (VirtualPagingDA); the query is EmployeeDA.GetDiscontinuedEmployeeQuery. /// - public List GetDiscontinuedEmployeeDetails(DateTime fromDate, + public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID) { - var items = new List(); - Dictionary departments = new DepartmentService().GetAll() - .GroupBy(d => d.ID) - .ToDictionary(g => g.Key, g => g.First()); - + VirtualPageResult result = null; TransactionContext tc = null; try { tc = TransactionContext.Begin(); - DataReader dr = new DataReader(EmployeeDA.GetDiscontinuedEmployeeDetails(tc, fromDate, toDate, payrollTypeID)); - while (dr.Read()) - items.Add(MapDiscontinuedEmployee(dr, departments)); - dr.Close(); + string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); tc.End(); } catch (Exception e) @@ -2765,121 +2758,7 @@ namespace HRM.DA #endregion } - return items; - } - - private static HRM.BO.Report.DiscontinueEmployeeDetailInfo MapDiscontinuedEmployee(DataReader dr, - Dictionary departments) - { - var item = new HRM.BO.Report.DiscontinueEmployeeDetailInfo(); - item.EmployeeId = dr.GetInt32("EmployeeId") ?? 0; - item.EmployeeNo = dr.GetString("EMPLOYEENO"); - item.Name = dr.GetString("NAME"); - item.BasicSalary = dr.GetDecimal("BASICSALARY") ?? 0; - item.GrossSalary = dr.GetDecimal("GrossSalary") ?? 0; - item.TaxAmount = dr.GetDecimal("TAXAMOUNT") ?? 0; - item.FatherName = dr.GetString("Fathername"); - item.FatherOccupation = dr.GetString("FatherOccupation"); - item.MotherOccupation = dr.GetString("MotherOccupation"); - item.MotherName = dr.GetString("MotherName"); - item.Gender = dr.GetString("Gender"); - item.BirthDate = dr.GetDateTime("BIRTHDATE"); - item.BirthPlace = dr.GetString("BIRTHPlace"); - item.TinNo = dr.GetString("TINNO"); - item.JoiningDate = dr.GetDateTime("JOININGDATE"); - item.EmailAddress = dr.GetString("EMAILADDRESS"); - item.Category = dr.GetString("Category"); - item.Status = dr.GetString("Status"); - item.Location = dr.GetString("Location"); - item.Division = dr.GetString("Division"); - item.Company = dr.GetString("Company"); - item.Department = dr.GetString("Department"); - item.Section = dr.GetString("Section"); - item.Designation = dr.GetString("DESIGNATION"); - item.Grade = dr.GetString("GRADE"); - item.Religion = dr.GetString("RELIGION"); - item.MaritalStatus = dr.GetString("MaritalStatus"); - item.MobileNo = dr.GetString("MOBILENO"); - item.DateOfConfirmation = dr.GetDateTime("DATEOFCONFIRMATION"); - item.NationalId = dr.GetString("NATIONALID"); - item.PassportNo = dr.GetString("PassPortNo"); - item.PhotoPath = dr.GetString("PhotoPath"); - int? bloodGroup = dr.GetInt32("bloodgroup"); - item.BloodGroup = ((EnumBloodGroup)(bloodGroup ?? (int)EnumBloodGroup.None)).BloodGroupToFriendlyName(); - item.LineManagerNo = dr.GetString("LineManagerNo"); - item.LineManagerName = dr.GetString("LineManagerName"); - item.LineManagerEmail = dr.GetString("LineManagerEmail"); - item.LineManagerDes = dr.GetString("LineManagerDes"); - item.LmDivision = dr.GetString("lmDivision"); - item.LmDepartment = dr.GetString("lmDepartment"); - item.EmpStatus = dr.GetString("EmpStatus"); - item.Nationality = dr.GetString("NATIONALITY"); - item.OutPayBank = dr.GetString("OUTPayBank"); - item.OutPayBranch = dr.GetString("OUTPayBranch"); - item.OutPayAccountNo = dr.GetString("OutPayAccountNo"); - // Bank / Branch / Account No fall back to the out-pay values when empty, as Employee Details shows them. - string accountNo = dr.GetString("ACCOUNTNO"); - string bank = dr.GetString("Bank"); - string branch = dr.GetString("Branch"); - item.AccountNo = string.IsNullOrEmpty(accountNo) ? item.OutPayAccountNo : accountNo; - item.Bank = string.IsNullOrEmpty(bank) ? item.OutPayBank : bank; - item.Branch = string.IsNullOrEmpty(branch) ? item.OutPayBranch : branch; - item.DiscontinueDate = dr.GetDateTime("DiscontinueDate"); - - int? departmentID = dr.GetInt32("EmpDepartmentID"); - Department department = null; - if (departmentID.HasValue) - departments.TryGetValue(departmentID.Value, out department); - string[] tiers = GetDepartmentTierNames(department, departments); - if (tiers != null) - { - item.deptireOne = tiers[0]; - item.deptireTwo = tiers[1]; - item.deptireThree = tiers[2]; - item.deptireFour = tiers[3]; - item.deptireFive = tiers[4]; - } - return item; - } - - /// - /// The five department tier names (tier 1 = top), worked out exactly as the Employee Details report - /// (EmployeeController.GetEmpDetailInfo) does. Null when there is no department. - /// - private static string[] GetDepartmentTierNames(Department dept, Dictionary departments) - { - if (dept == null) - return null; - - Func find = id => - { - Department d = null; - if (id.HasValue) - departments.TryGetValue(id.Value, out d); - return d; - }; - - Department tire5 = null, tire4 = null, tire3 = null, tire2 = null, tire1 = null; - if (dept.ParentID != null) - { - for (int i = dept.Tier; i > 0; i--) - { - if (i == 5) tire5 = find(dept.ID); - if (i == 4) tire4 = tire5 != null ? find(tire5.ParentID) : find(dept.ID); - if (i == 3) tire3 = tire4 != null ? find(tire4.ParentID) : find(dept.ID); - if (i == 2) tire2 = tire3 != null ? find(tire3.ParentID) : find(dept.ID); - if (i == 1) tire1 = tire2 != null ? find(tire2.ParentID) : find(dept.ID); - } - } - - return new[] - { - tire1 == null ? "" : tire1.Name, - tire2 == null ? "" : tire2.Name, - tire3 == null ? "" : tire3.Name, - tire4 == null ? "" : tire4.Name, - tire5 == null ? "" : tire5.Name, - }; + return result; } #endregion diff --git a/HRM.DA/Service/VirtualPaging/README.md b/HRM.DA/Service/VirtualPaging/README.md deleted file mode 100644 index bde5940..0000000 --- a/HRM.DA/Service/VirtualPaging/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# 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 deleted file mode 100644 index e9f7f1e..0000000 --- a/HRM.DA/Service/VirtualPaging/VirtualPaging.cs +++ /dev/null @@ -1,200 +0,0 @@ -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 9b53a8f..e4528f0 100644 --- a/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts +++ b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts @@ -1,6 +1,6 @@ /** * (custom-components/virtual-grid) and its server side - * (HRM.BO/VirtualPaging/VirtualPaging.cs, HRM.DA/Service/VirtualPaging/VirtualPaging.cs). + * (HRM.BO/VirtualPaging/VirtualPaging.cs, HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs). */ /** How a column's values are shown (and exported to Excel). */ @@ -18,19 +18,19 @@ export interface VirtualGridColumn { /** What the grid posts to the page endpoint (VirtualPageRequest on the server). */ export interface VirtualPageRequest { filters: { [name: string]: string }; - fields: string[]; + columns: { field: string; type: VirtualGridColumnType }[]; skip: number; take: number; // 0 = all rows (Export to Excel) search?: string; sortField?: string; sortDir?: 'asc' | 'desc'; - refresh: boolean; // true on Preview + countTotal: boolean; // true on Preview and on a new search; scroll/sort keep the totals } /** What the page endpoint returns (VirtualPageResult on the server). */ export interface VirtualPageResult { - total: number; - totalWithoutSearch: number; + total: number | null; // null when not counted (countTotal = false) + totalWithoutSearch: number | null; data: { [field: string]: any }[]; } 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 3ded9a0..781d4e8 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 @@ -23,8 +23,8 @@ import { * * 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. + * The grid asks for 100 rows at a time while the user scrolls; SQL Server reads just those rows and does + * the search, sort and total count (VirtualPagingDA). Export to Excel downloads every matching row. */ @Component({ selector: 'app-virtual-grid', @@ -36,7 +36,7 @@ import { export class VirtualGridComponent implements OnInit, OnDestroy { /** The page endpoint, e.g. '/Employee/getDiscontinueEmployeePage'. Required. */ @Input() url: string; - /** The columns. field = property name of the server object (camelCase). Required. */ + /** The columns. field = a column alias of the page's SQL query (camelCase). Required. */ @Input() columns: VirtualGridColumn[] = []; @Input() height = 600; @Input() pageSize = 100; @@ -66,6 +66,7 @@ export class VirtualGridComponent implements OnInit, OnDestroy { private filters: { [name: string]: string } = {}; private firstLoad = false; + private totalsPending = false; private readonly load$ = new Subject(); private readonly search$ = new Subject(); private readonly subscriptions = new Subscription(); @@ -97,7 +98,7 @@ export class VirtualGridComponent implements OnInit, OnDestroy { this.search$.pipe(debounceTime(400), distinctUntilChanged()).subscribe(text => { this.appliedSearch = text; this.skip = 0; - this.requestPage(false); + this.requestPage(true); // a new search changes the total }) ); } @@ -198,23 +199,26 @@ export class VirtualGridComponent implements OnInit, OnDestroy { return Math.max(column.width || 130, (column.title || '').length * 8 + 48); } - private requestPage(refresh: boolean): void { + /** countTotal: true on Preview and a new search (the total can change); scroll and sort keep the totals. */ + private requestPage(countTotal: boolean): void { if (this.started && this.url) { - this.load$.next(this.buildRequest(this.skip, this.pageSize, refresh)); + // Keep asking for the totals until a response brings them (a newer request cancels an older one). + this.totalsPending = this.totalsPending || countTotal; + this.load$.next(this.buildRequest(this.skip, this.pageSize, this.totalsPending)); } } - private buildRequest(skip: number, take: number, refresh: boolean): VirtualPageRequest { + private buildRequest(skip: number, take: number, countTotal: boolean): VirtualPageRequest { const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null; return { filters: this.filters, - fields: this.columns.map(c => c.field), + columns: this.columns.map(c => ({ field: c.field, type: c.type || 'text' })), skip: skip, take: take, search: this.appliedSearch || undefined, sortField: sort ? sort.field : undefined, sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined, - refresh: refresh, + countTotal: countTotal, }; } @@ -222,9 +226,17 @@ export class VirtualGridComponent implements OnInit, OnDestroy { if (!result) { return; } - 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 }); + // Totals come only when they were counted; otherwise keep the ones we have. + const counted = result.total !== null && result.total !== undefined; + if (counted) { + this.totalsPending = false; + } + const total = counted ? result.total : this.gridView.total; + if (result.totalWithoutSearch !== null && result.totalWithoutSearch !== undefined) { + this.totalWithoutSearch = result.totalWithoutSearch; + } + this.gridView = { data: (result.data || []).map(row => this.prepareRow(row)), total: total }; + this.loaded.emit({ total: total, totalWithoutSearch: this.totalWithoutSearch, firstLoad: this.firstLoad }); this.firstLoad = false; } 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 9e8623d..22da6e7 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 @@ -11,7 +11,8 @@ 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. * - * Data: EmployeeController.GetDiscontinueEmployeePage → EmployeeService.GetDiscontinuedEmployeeDetails. + * Data: EmployeeController.GetDiscontinueEmployeePage → EmployeeService.GetDiscontinuedEmployeePage + * → EmployeeDA.GetDiscontinuedEmployeeQuery (SQL) + VirtualPagingDA (paging in SQL Server). * The common does virtual scrolling, search, sort, total and Excel. */ @Component({ @@ -28,7 +29,7 @@ export class DiscontinueEmployeeDetailsComponent implements OnInit { toDate: Date = new Date(); dateFormat = 'dd-MMM-yyyy'; - /** Grid columns. field = property of DiscontinueEmployeeDetailInfo (camelCase). */ + /** Grid columns. field = a column alias in EmployeeDA.GetDiscontinuedEmployeeQuery. */ columns: VirtualGridColumn[] = []; constructor(public apiService: ApiService, diff --git a/HRM.UI/Controllers/Employee/EmployeeController.cs b/HRM.UI/Controllers/Employee/EmployeeController.cs index 174fea6..34e9e6b 100644 --- a/HRM.UI/Controllers/Employee/EmployeeController.cs +++ b/HRM.UI/Controllers/Employee/EmployeeController.cs @@ -3412,7 +3412,7 @@ 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. + /// Filters: fromDate, toDate ("yyyy-MM-dd"). SQL Server does the paging, search and sort (VirtualPagingDA). /// [HttpPost("getDiscontinueEmployeePage")] public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request) @@ -3420,11 +3420,19 @@ namespace HRM.UI.Controllers try { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) // self-service logins never see this report + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see this report."); + DateTime fromDate = request.GetDate("fromDate", "From Date"); DateTime toDate = request.GetDate("toDate", "To Date"); + if (fromDate > toDate) + return BadRequest("From Date cannot be after To Date."); - return Ok(VirtualPaging.Page(request, currentUser, - () => _EmployeeService.GetDiscontinuedEmployeeDetails(fromDate, toDate, currentUser.PayrollTypeID ?? 0))); + return Ok(_EmployeeService.GetDiscontinuedEmployeePage(request, fromDate, toDate, currentUser.PayrollTypeID ?? 0)); + } + catch (ArgumentException ex) + { + return BadRequest(ex.Message); } catch (Exception ex) {