Discontinue Virtual pagination
This commit is contained in:
parent
1895b2faa7
commit
0ce82ae791
|
|
@ -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<HRM.BO.Report.DiscontinueEmployeeDetailInfo> 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<Employee> GetbyDepartment(int deptId);
|
||||
List<Employee> NotYetAssigned(int payrollTypeID);
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
using System;
|
||||
|
||||
namespace HRM.BO.Report
|
||||
{
|
||||
/// <summary>
|
||||
/// One row of the Discontinue Employee Details report (Manage Employee › Report): the same fields as
|
||||
/// Employee Details (<see cref="EmployeeDetailInfo"/>) plus the date the employee was discontinued
|
||||
/// (Employee.ENDOFCONTRACTDATE). Loaded by IEmployeeService.GetDiscontinuedEmployeeDetails.
|
||||
/// </summary>
|
||||
public class DiscontinueEmployeeDetailInfo : EmployeeDetailInfo
|
||||
{
|
||||
public DateTime? DiscontinueDate { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -5,17 +5,17 @@ using System.Globalization;
|
|||
namespace HRM.BO
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class VirtualPageRequest
|
||||
{
|
||||
/// <summary>The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString.</summary>
|
||||
public Dictionary<string, string> Filters { get; set; } = new Dictionary<string, string>();
|
||||
|
||||
/// <summary>The grid's columns (property names). Only these are sent back and searched.</summary>
|
||||
public List<string> Fields { get; set; } = new List<string>();
|
||||
/// <summary>The grid's columns. Only these are selected, searched and sortable.</summary>
|
||||
public List<VirtualPageColumn> Columns { get; set; } = new List<VirtualPageColumn>();
|
||||
|
||||
public int Skip { get; set; }
|
||||
|
||||
|
|
@ -28,8 +28,11 @@ namespace HRM.BO
|
|||
/// <summary>"asc" or "desc".</summary>
|
||||
public string SortDir { get; set; }
|
||||
|
||||
/// <summary>True on Preview: load the data again. False on scroll/sort/search/export: use the kept copy.</summary>
|
||||
public bool Refresh { get; set; }
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool CountTotal { get; set; }
|
||||
|
||||
/// <summary>A filter as text, or null when it was not sent.</summary>
|
||||
public string GetString(string name)
|
||||
|
|
@ -59,16 +62,25 @@ namespace HRM.BO
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>One grid column: Field = a column alias of the page's query; Type = how it is shown.</summary>
|
||||
public class VirtualPageColumn
|
||||
{
|
||||
public string Field { get; set; }
|
||||
|
||||
/// <summary>"text" (default), "number", "money", "date" or "datetime".</summary>
|
||||
public string Type { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One window of rows for the grid.</summary>
|
||||
public class VirtualPageResult
|
||||
{
|
||||
/// <summary>Rows matching the search (all rows when there is no search).</summary>
|
||||
public int Total { get; set; }
|
||||
/// <summary>Rows matching the search (all rows when there is no search). Null when not counted (CountTotal = false).</summary>
|
||||
public int? Total { get; set; }
|
||||
|
||||
/// <summary>All rows, ignoring the search.</summary>
|
||||
public int TotalWithoutSearch { get; set; }
|
||||
/// <summary>All rows, ignoring the search. Null when not counted.</summary>
|
||||
public int? TotalWithoutSearch { get; set; }
|
||||
|
||||
/// <summary>The rows of this window, holding only the requested fields.</summary>
|
||||
/// <summary>The rows of this window, holding only the requested columns.</summary>
|
||||
public List<Dictionary<string, object>> Data { get; set; } = new List<Dictionary<string, object>>();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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)
|
||||
|
|
|
|||
119
HRM.DA/DA/VirtualPaging/README.md
Normal file
119
HRM.DA/DA/VirtualPaging/README.md
Normal file
|
|
@ -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`) | `<app-virtual-grid>`: 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
|
||||
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"
|
||||
exportFileName="DiscontinueEmployeeDetails.xlsx"></app-virtual-grid>
|
||||
```
|
||||
```ts
|
||||
columns: VirtualGridColumn[] = [
|
||||
{ field: 'employeeNo', title: 'Employee No', width: 110 },
|
||||
{ field: 'joiningDate', title: 'Joining Date', type: 'date' },
|
||||
{ field: '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.
|
||||
169
HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs
Normal file
169
HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <param name="query">The page's SELECT (column aliases = grid fields, no ORDER BY).</param>
|
||||
/// <param name="keyField">A unique field (e.g. employeeNo): the default sort and the tie-breaker that keeps pages from overlapping.</param>
|
||||
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<VirtualPageColumn> 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<SqlParameter>(); // 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<string, object>(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;
|
||||
}
|
||||
|
||||
/// <summary>The requested columns; every field must be a plain identifier (it is put in the SQL in brackets).</summary>
|
||||
private static List<VirtualPageColumn> GetColumns(List<VirtualPageColumn> requested)
|
||||
{
|
||||
var columns = new List<VirtualPageColumn>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (VirtualPageColumn c in requested ?? new List<VirtualPageColumn>())
|
||||
{
|
||||
if (c == null || !IsIdentifier(c.Field))
|
||||
throw new ArgumentException("Invalid column: " + c?.Field);
|
||||
if (seen.Add(c.Field))
|
||||
columns.Add(c);
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "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").
|
||||
/// </summary>
|
||||
private static string SearchCondition(List<VirtualPageColumn> columns)
|
||||
{
|
||||
const string like = " LIKE @vpSearch ESCAPE '\\'";
|
||||
var parts = new List<string>();
|
||||
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) + ")";
|
||||
}
|
||||
|
||||
/// <summary>The grid's sort (only by one of its columns), then the key field so the order is always the same.</summary>
|
||||
private static string OrderBy(List<VirtualPageColumn> 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";
|
||||
}
|
||||
|
||||
/// <summary>Makes %, _, [ and \ in the search text match themselves.</summary>
|
||||
private static string EscapeLike(string text) =>
|
||||
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_").Replace("[", "\\[");
|
||||
|
||||
private static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name);
|
||||
}
|
||||
}
|
||||
|
|
@ -2733,26 +2733,19 @@ namespace HRM.DA
|
|||
#region Discontinue Employee Details
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public List<HRM.BO.Report.DiscontinueEmployeeDetailInfo> GetDiscontinuedEmployeeDetails(DateTime fromDate,
|
||||
public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate,
|
||||
DateTime toDate, int payrollTypeID)
|
||||
{
|
||||
var items = new List<HRM.BO.Report.DiscontinueEmployeeDetailInfo>();
|
||||
Dictionary<int, Department> 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<int, Department> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static string[] GetDepartmentTierNames(Department dept, Dictionary<int, Department> departments)
|
||||
{
|
||||
if (dept == null)
|
||||
return null;
|
||||
|
||||
Func<int?, Department> 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
|
||||
|
|
|
|||
|
|
@ -1,77 +0,0 @@
|
|||
# Virtual paging: large lists with virtual scrolling
|
||||
|
||||
Data loads **the usual way**: DA query → service returns `List<BO>` → controller endpoint.
|
||||
Only two common pieces are added:
|
||||
|
||||
| Piece | File | What it does |
|
||||
|---|---|---|
|
||||
| `VirtualPaging.Page(...)` | `HRM.DA/Service/VirtualPaging/VirtualPaging.cs` | Keeps the list in memory for a few minutes, then search, sort, 100 rows at a time and the total count |
|
||||
| `<app-virtual-grid>` | `ClientApp/src/app/custom-components/virtual-grid/` (`VirtualGridModule`) | Virtual scrolling, search box, total, Export to Excel |
|
||||
|
||||
`VirtualPageRequest` / `VirtualPageResult` (`HRM.BO/VirtualPaging/VirtualPaging.cs`) are shared by every
|
||||
page, so a page never needs its own request class.
|
||||
|
||||
## A new page: 2 steps
|
||||
|
||||
**1. Endpoint** in the module's own controller, calling the existing service:
|
||||
|
||||
```csharp
|
||||
[HttpPost("getDiscontinueEmployeePage")]
|
||||
public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
|
||||
DateTime fromDate = request.GetDate("fromDate", "From Date"); // the page's own filters
|
||||
DateTime toDate = request.GetDate("toDate", "To Date");
|
||||
|
||||
return Ok(VirtualPaging.Page(request, currentUser,
|
||||
() => _EmployeeService.GetDiscontinuedEmployeeDetails(fromDate, toDate, currentUser.PayrollTypeID ?? 0)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Read filters with `request.GetDate(name)`, `request.GetInt(name)` or `request.GetString(name)` (null when not sent).
|
||||
|
||||
**2. Screen**: import `VirtualGridModule`, then:
|
||||
|
||||
```html
|
||||
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"
|
||||
exportFileName="DiscontinueEmployeeDetails.xlsx"></app-virtual-grid>
|
||||
```
|
||||
```ts
|
||||
columns: VirtualGridColumn[] = [
|
||||
{ field: 'employeeNo', title: 'Employee No', width: 110 },
|
||||
{ field: 'joiningDate', title: 'Joining Date', type: 'date' },
|
||||
{ field: 'grossSalary', title: 'Gross Salary', type: 'money' },
|
||||
];
|
||||
|
||||
preview() {
|
||||
this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); // any filters; Dates are sent as yyyy-MM-dd
|
||||
}
|
||||
```
|
||||
|
||||
`field` is the property name of the BO (camelCase). Column `type`: `text` (default), `number`,
|
||||
`money` (1,234.56), `date` (dd MMM yyyy), `datetime`. `sortable: false` turns sorting off for a column.
|
||||
|
||||
That is all. No registry, no extra service, no extra Angular service.
|
||||
|
||||
## How it runs
|
||||
|
||||
1. **Preview** → `grid.load(filters)` → the endpoint with `refresh: true` → the service is called once,
|
||||
the list is kept in server memory (per user + endpoint + filters, 10 min since last use, 30 min at
|
||||
most) → the first 100 rows and the total go back.
|
||||
2. **Scroll / sort / search** → same endpoint, `refresh: false` → answered from the kept list.
|
||||
3. **Export to Excel** → same endpoint with `take: 0` → every matching row → Kendo builds the `.xlsx`.
|
||||
|
||||
The browser shows ~100 rows at a time, however long the list is.
|
||||
|
||||
## Rules
|
||||
|
||||
- The service must not run one query per row; load lookups once (see `GetDiscontinuedEmployeeDetails`).
|
||||
- Search looks in the text the grid shows (dates `dd MMM yyyy`, money `1,234.56`).
|
||||
- Authorization is menu-driven in this app: put any extra check the page needs in its endpoint.
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class VirtualPaging
|
||||
{
|
||||
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000000 }); // max rows kept, all users together
|
||||
private static readonly TimeSpan KeepFor = TimeSpan.FromMinutes(10); // since last use
|
||||
private static readonly TimeSpan KeepAtMost = TimeSpan.FromMinutes(30); // since loaded
|
||||
private const int MaxRowsPerPage = 1000;
|
||||
|
||||
public static VirtualPageResult Page<T>(VirtualPageRequest request, CurrentUser user, Func<List<T>> loadData,
|
||||
[CallerFilePath] string callerFile = "", [CallerMemberName] string callerName = "") where T : class
|
||||
{
|
||||
if (request == null)
|
||||
throw new ArgumentException("Invalid request.");
|
||||
|
||||
// 1. The list: from memory, or from the service on Preview / when it has expired.
|
||||
string key = CacheKey(request, user, callerFile + "|" + callerName + "|" + typeof(T).FullName);
|
||||
KeptList<T> kept;
|
||||
if (request.Refresh || !Cache.TryGetValue(key, out kept))
|
||||
{
|
||||
kept = new KeptList<T>(loadData() ?? new List<T>());
|
||||
Cache.Set(key, kept, new MemoryCacheEntryOptions
|
||||
{
|
||||
Size = Math.Max(1, kept.Items.Count),
|
||||
SlidingExpiration = KeepFor,
|
||||
AbsoluteExpirationRelativeToNow = KeepAtMost,
|
||||
});
|
||||
}
|
||||
|
||||
List<PropertyInfo> fields = GetFields<T>(request.Fields);
|
||||
IEnumerable<int> rows = Enumerable.Range(0, kept.Items.Count);
|
||||
|
||||
// 2. Search: the text the grid shows, in any of the grid's columns.
|
||||
string search = (request.Search ?? "").Trim();
|
||||
if (search.Length > 0)
|
||||
{
|
||||
List<string> texts = kept.SearchTexts(fields);
|
||||
rows = rows.Where(i => texts[i].IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
}
|
||||
List<int> matched = rows.ToList();
|
||||
|
||||
// 3. Sort: only by one of the grid's columns.
|
||||
PropertyInfo sortBy = fields.FirstOrDefault(p => string.Equals(p.Name, request.SortField, StringComparison.OrdinalIgnoreCase));
|
||||
if (sortBy != null)
|
||||
{
|
||||
bool desc = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase);
|
||||
matched = desc
|
||||
? matched.OrderByDescending(i => sortBy.GetValue(kept.Items[i]), ValueComparer.Instance).ToList()
|
||||
: matched.OrderBy(i => sortBy.GetValue(kept.Items[i]), ValueComparer.Instance).ToList();
|
||||
}
|
||||
|
||||
// 4. The window: Take 0 = every row (Export to Excel).
|
||||
int skip = Math.Max(0, request.Skip);
|
||||
int take = request.Take <= 0 ? matched.Count : Math.Min(request.Take, MaxRowsPerPage);
|
||||
|
||||
var result = new VirtualPageResult { Total = matched.Count, TotalWithoutSearch = kept.Items.Count };
|
||||
foreach (int i in matched.Skip(skip).Take(take))
|
||||
{
|
||||
var row = new Dictionary<string, object>(fields.Count);
|
||||
foreach (PropertyInfo p in fields)
|
||||
row[CamelCase(p.Name)] = p.GetValue(kept.Items[i]);
|
||||
result.Data.Add(row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>A loaded list, plus the search text of each row (worked out once, on the first search).</summary>
|
||||
private sealed class KeptList<T>
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, List<string>> _searchTexts = new ConcurrentDictionary<string, List<string>>();
|
||||
|
||||
public KeptList(List<T> items)
|
||||
{
|
||||
Items = items.Where(x => x != null).ToList();
|
||||
}
|
||||
|
||||
public List<T> Items { get; }
|
||||
|
||||
public List<string> SearchTexts(List<PropertyInfo> fields)
|
||||
{
|
||||
string key = string.Join(",", fields.Select(p => p.Name));
|
||||
return _searchTexts.GetOrAdd(key, _ => Items
|
||||
.Select(item => string.Join("\u0001", fields.Select(p => DisplayText(p.GetValue(item)))))
|
||||
.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The requested fields that are readable properties of T (unknown names are ignored). None requested = all.</summary>
|
||||
private static List<PropertyInfo> GetFields<T>(List<string> names)
|
||||
{
|
||||
// When a class hides a base property with "new", keep the most derived one.
|
||||
var properties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
|
||||
for (Type t = typeof(T); t != null && t != typeof(object); t = t.BaseType)
|
||||
{
|
||||
foreach (PropertyInfo p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
|
||||
{
|
||||
if (p.CanRead && p.GetIndexParameters().Length == 0 && !properties.ContainsKey(p.Name))
|
||||
properties[p.Name] = p;
|
||||
}
|
||||
}
|
||||
|
||||
if (names == null || names.Count == 0)
|
||||
return properties.Values.ToList();
|
||||
|
||||
var result = new List<PropertyInfo>();
|
||||
foreach (string name in names.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
PropertyInfo p;
|
||||
if (name != null && properties.TryGetValue(name, out p))
|
||||
result.Add(p);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The text the grid shows for a value: dates "dd MMM yyyy", decimals "1,234.56".</summary>
|
||||
private static string DisplayText(object value)
|
||||
{
|
||||
if (value == null)
|
||||
return string.Empty;
|
||||
if (value is DateTime d)
|
||||
return d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
|
||||
if (value is decimal || value is double || value is float)
|
||||
{
|
||||
decimal number = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
|
||||
return number.ToString("N2", CultureInfo.InvariantCulture) + "\u0001" + number.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
if (value is Enum)
|
||||
return value + "\u0001" + Convert.ToInt32(value, CultureInfo.InvariantCulture);
|
||||
return Convert.ToString(value, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static string CacheKey(VirtualPageRequest request, CurrentUser user, string endpoint)
|
||||
{
|
||||
string filters = string.Join("&", (request.Filters ?? new Dictionary<string, string>())
|
||||
.OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(f => f.Key.ToLowerInvariant() + "=" + f.Value));
|
||||
return endpoint + "|" + user?.UserID + "|" + user?.PayrollTypeID + "|" + filters;
|
||||
}
|
||||
|
||||
private static string CamelCase(string name) =>
|
||||
string.IsNullOrEmpty(name) ? name : char.ToLowerInvariant(name[0]) + name.Substring(1);
|
||||
|
||||
/// <summary>Empty values first; numbers, dates and text compared as such (text ignoring case).</summary>
|
||||
private sealed class ValueComparer : IComparer<object>
|
||||
{
|
||||
public static readonly ValueComparer Instance = new ValueComparer();
|
||||
|
||||
public int Compare(object x, object y)
|
||||
{
|
||||
bool xEmpty = x == null || (x is string xs && xs.Length == 0);
|
||||
bool yEmpty = y == null || (y is string ys && ys.Length == 0);
|
||||
if (xEmpty || yEmpty)
|
||||
return xEmpty == yEmpty ? 0 : (xEmpty ? -1 : 1);
|
||||
if (x is string a && y is string b)
|
||||
return StringComparer.InvariantCultureIgnoreCase.Compare(a, b);
|
||||
if (IsNumber(x) && IsNumber(y))
|
||||
return Convert.ToDecimal(x, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(y, CultureInfo.InvariantCulture));
|
||||
if (x.GetType() == y.GetType() && x is IComparable comparable)
|
||||
return comparable.CompareTo(y);
|
||||
return StringComparer.InvariantCultureIgnoreCase.Compare(
|
||||
Convert.ToString(x, CultureInfo.InvariantCulture), Convert.ToString(y, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
private static bool IsNumber(object v) =>
|
||||
v is decimal || v is double || v is float || v is int || v is long || v is short || v is byte;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
/**
|
||||
* <app-virtual-grid> (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 }[];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,8 +23,8 @@ import {
|
|||
* <app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"></app-virtual-grid>
|
||||
* this.grid.load({ fromDate: this.fromDate, toDate: this.toDate });
|
||||
*
|
||||
* The grid loads 100 rows at a time while the user scrolls; search, sort and the total count are done
|
||||
* on the server (VirtualPaging.Page). Export to Excel downloads every matching row.
|
||||
* 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<VirtualPageRequest>();
|
||||
private readonly search$ = new Subject<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 <app-virtual-grid> 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,
|
||||
|
|
|
|||
|
|
@ -3412,7 +3412,7 @@ namespace HRM.UI.Controllers
|
|||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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)
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user