Virtual Scroll Grid

This commit is contained in:
Mohaimen Hasan 2026-11-09 14:41:04 +06:00
parent 78747c0674
commit 7b43017c52
25 changed files with 2134 additions and 174 deletions

View File

@ -0,0 +1,27 @@
/* ============================================================================
Discontinue Employee Details report - supporting index (OPTIONAL)
----------------------------------------------------------------------------
The report (Manage Employee > Report > Discontinue Employee Details,
DiscontinueEmployeeReportDA) filters dbo.EMPLOYEE by
STATUS = 2 (Discontinued) AND PAYROLLTYPEID = @x
AND ENDOFCONTRACTDATE >= @FromDate AND ENDOFCONTRACTDATE < @ToDate+1
The report works without this index (no code depends on it). The index
lets SQL Server seek straight to the discontinued employees of one payroll
type in the date range instead of scanning every employee, which keeps the
count and each 100-row page fast as the EMPLOYEE table grows.
Run order: any time, before or after the code deploys. Guarded, safe to
re-run. It only adds an index: no table, column or data is changed.
============================================================================ */
IF NOT EXISTS (SELECT 1 FROM sys.indexes
WHERE object_id = OBJECT_ID('dbo.EMPLOYEE')
AND name = 'IX_Employee_Status_PayrollType_EndOfContract')
BEGIN
CREATE NONCLUSTERED INDEX IX_Employee_Status_PayrollType_EndOfContract
ON dbo.EMPLOYEE (STATUS, PAYROLLTYPEID, ENDOFCONTRACTDATE)
INCLUDE (DEPARTMENTID);
END;
GO

View File

@ -606,6 +606,9 @@ namespace HRM.BO
DataTable GetDFSL();
DataSet GetEmpDetailsView(string sEmpID);
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);
int GetCurrentHeadCount(int departmentId, int designationId, int gradeId);
List<Employee> GetbyDepartment(int deptId);
List<Employee> NotYetAssigned(int payrollTypeID);

View File

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

View File

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

View File

@ -1597,6 +1597,22 @@ 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)
{
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",
(int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1));
return tc.ExecuteReader(sql);
}
internal static DataSet GetEmpDetailsView(TransactionContext tc)
{
DataSet oEmpDetails = new DataSet();

View File

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

View File

@ -2730,6 +2730,160 @@ namespace HRM.DA
return oEmpDetails;
}
#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.
/// </summary>
public List<HRM.BO.Report.DiscontinueEmployeeDetailInfo> GetDiscontinuedEmployeeDetails(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());
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();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#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,
};
}
#endregion
public DataSet GetEmpDetailsView()
{
DataSet oEmpDetails = new DataSet();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,63 @@
/**
* Common virtual-scrolling grid (api/virtualGrid) — matches HRM.BO/VirtualGrid/VirtualGrid.cs.
* Screens use <app-virtual-grid gridKey="..."> (custom-components/virtual-grid) rather than these directly.
*/
/** EnumVirtualGridColumnType on the server. */
export enum EnumVirtualGridColumnType {
Text = 1,
Number = 2,
Money = 3,
Date = 4,
DateTime = 5
}
export interface VirtualGridColumnInfo {
field: string;
title: string;
width: number;
type: EnumVirtualGridColumnType;
sortable: boolean;
}
export interface VirtualGridLayout {
gridKey: string;
title: string;
defaultSortField: string;
defaultSortDir: 'asc' | 'desc';
maxPageSize: number;
columns: VirtualGridColumnInfo[];
}
/** Screen-specific filters, e.g. { fromDate: '2025-01-01', toDate: '2025-12-31' }. Dates as 'yyyy-MM-dd'. */
export type VirtualGridFilters = { [name: string]: string };
export interface VirtualGridRequest {
gridKey: string;
filters: VirtualGridFilters;
skip: number;
take: number;
search?: string;
sortField?: string;
sortDir?: 'asc' | 'desc';
/** True on Preview: reload the data instead of using the copy the server keeps for scrolling. */
refresh?: boolean;
}
export interface VirtualGridExportRequest extends VirtualGridRequest {
fields: string[];
}
export interface VirtualGridPage {
total: number;
totalWithoutSearch: number;
data: { [field: string]: any }[];
}
/** Emitted by <app-virtual-grid> after every window it loads. */
export interface VirtualGridLoadedEvent {
total: number;
totalWithoutSearch: number;
/** True for the first window after load(filters). */
firstLoad: boolean;
}

View File

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

View File

@ -326,12 +326,6 @@ export class EmployeeServices {
return this.apiService.httpPost<EmployeeDetailInfo[]>('/Employee/getEmpDetailInfo', emps);
}
// Discontinue Employee Details report: same rows as getEmpDetailInfo plus discontinueDate,
// for employees discontinued between fromDate and toDate (both 'yyyy-MM-dd').
getDiscontinueEmpDetailInfo(fromDate: string, toDate: string) {
return this.apiService.httpPost<any[]>('/Employee/getDiscontinueEmpDetailInfo', { fromDate: fromDate, toDate: toDate });
}
getCurrentHeadCount(departmentId: number, designationId: number, gradeId: number) {
return this.apiService.httpGet<number>('/Employee/getCurrentHeadCount' + '/' + departmentId + '/' + designationId + '/' + gradeId);
}

View File

@ -0,0 +1,46 @@
@if (layoutError) {
<div class="virtual-grid-message">{{ layoutError }}</div>
}
@if (started && layout) {
<kendo-grid class="virtual-grid"
[data]="gridView"
[loading]="gridLoading"
scrollable="virtual"
[rowHeight]="rowHeight"
[pageSize]="pageSize"
[skip]="skip"
(pageChange)="onPageChange($event)"
[sortable]="{ mode: 'single', allowUnsort: false }"
[sort]="sort"
(sortChange)="onSortChange($event)"
[resizable]="true"
[style.height.px]="height">
<ng-template kendoGridToolbarTemplate>
@if (showSearch) {
<kendo-textbox class="virtual-grid-search" [placeholder]="searchPlaceholder" [clearButton]="true"
[(ngModel)]="searchText" (valueChange)="onSearchChange($event)">
</kendo-textbox>
}
<label class="virtual-grid-count">
Total: {{ gridView.total | number }}@if (appliedSearch) { <span> of {{ totalWithoutSearch | number }}</span> }
</label>
<kendo-grid-spacer></kendo-grid-spacer>
@if (showExport) {
<button type="button" kendoButton [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
[disabled]="gridView.total === 0 || exporting" (click)="exportExcel()">
{{ exporting ? 'Exporting…' : 'Export to Excel' }}
</button>
}
</ng-template>
@for (column of layout.columns; track column.field) {
<kendo-grid-column [field]="column.field" [title]="column.title" [width]="column.width"
[sortable]="column.sortable"
[class]="{ 'virtual-grid-number': column.type === columnType.Money || column.type === columnType.Number }"
[headerClass]="{ 'virtual-grid-number': column.type === columnType.Money || column.type === columnType.Number }">
</kendo-grid-column>
}
<ng-template kendoGridNoRecordsTemplate>
{{ noRecordsText }}
</ng-template>
</kendo-grid>
}

View File

@ -0,0 +1,48 @@
:host {
display: block;
}
.virtual-grid-search {
width: 280px;
}
.virtual-grid-count {
margin-left: 12px;
white-space: nowrap;
}
.virtual-grid-message {
padding: 12px;
color: #b42318;
}
// Text that does not fit its column wraps onto more lines, so the full value is always readable
// (no "…"). [rowHeight] is the minimum row height; Kendo measures each rendered row's real height
// for virtual scrolling, so taller wrapped rows still scroll correctly. Long unbroken values
// (e-mail addresses, account numbers) break inside the word rather than overflow the cell.
:host ::ng-deep .virtual-grid .k-grid-content td {
white-space: normal;
overflow-wrap: anywhere;
vertical-align: top;
padding-top: 8px;
padding-bottom: 8px;
line-height: 1.35;
}
// Header titles on one line (the app-wide _header.scss lets .k-column-title wrap). Column widths are
// widened in the component so every title fits; ellipsis is only a fallback after a manual resize.
:host ::ng-deep .virtual-grid .k-grid-header .k-column-title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .virtual-grid .virtual-grid-number {
text-align: right;
}
@media (max-width: 600px) {
.virtual-grid-search {
width: 100%;
}
}

View File

@ -0,0 +1,290 @@
import {
ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, LOCALE_ID, OnDestroy, OnInit, Optional, Output
} from '@angular/core';
import { formatDate } from '@angular/common';
import { of, Subject, Subscription } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, finalize, switchMap } from 'rxjs/operators';
import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
import { SortDescriptor } from '@progress/kendo-data-query';
import { saveAs } from 'file-saver';
import { ApiService } from 'src/app/app.api.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { VirtualGridService } from 'src/app/_services/common/virtual-grid.service';
import {
EnumVirtualGridColumnType,
VirtualGridFilters,
VirtualGridLayout,
VirtualGridLoadedEvent,
VirtualGridPage,
VirtualGridRequest
} from 'src/app/_models/common/virtual-grid';
@Component({
selector: 'app-virtual-grid',
templateUrl: './virtual-grid.component.html',
styleUrls: ['./virtual-grid.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class VirtualGridComponent implements OnInit, OnDestroy {
/** Server grid key (VirtualGridRegistry). Required. */
@Input() gridKey: string;
/** Grid height in px. */
@Input() height = 600;
/** Rows fetched per window. */
@Input() pageSize = 100;
/** Minimum (estimated) row height in px. Rows with wrapped text grow; Kendo measures the real heights while scrolling. */
@Input() rowHeight = 36;
@Input() searchPlaceholder = 'Search in all columns...';
@Input() noRecordsText = 'No records found.';
/** Excel file name; defaults to the grid title. */
@Input() exportFileName: string;
@Input() showSearch = true;
@Input() showExport = true;
/** After every loaded window. */
@Output() loaded = new EventEmitter<VirtualGridLoadedEvent>();
layout: VirtualGridLayout;
layoutError = '';
started = false;
gridView: GridDataResult = { data: [], total: 0 };
totalWithoutSearch = 0;
gridLoading = false;
skip = 0;
sort: SortDescriptor[] = [];
searchText = '';
appliedSearch = '';
exporting = false;
readonly columnType = EnumVirtualGridColumnType;
private filters: VirtualGridFilters = {};
private pendingFilters: VirtualGridFilters = null;
private firstLoad = false;
private readonly load$ = new Subject<VirtualGridRequest>();
private readonly search$ = new Subject<string>();
private readonly subscriptions = new Subscription();
private readonly money = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
constructor(public apiService: ApiService,
private virtualGridService: VirtualGridService,
@Inject(LOCALE_ID) private locale: string,
@Optional() private notificationService: HRMNotificationService,
@Optional() private loadingPanel: loadingPanelService) {
}
ngOnInit(): void {
this.subscriptions.add(
this.virtualGridService.getLayout(this.gridKey).subscribe(
(layout) => {
layout.columns = (layout.columns || []).map(c => ({ ...c, width: this.fitWidth(c) }));
this.layout = layout;
this.resetSort();
if (this.pendingFilters) {
const filters = this.pendingFilters;
this.pendingFilters = null;
this.load(filters);
}
},
(err) => {
this.layoutError = this.errorText(err, 'Failed to load the grid.');
this.showError(this.layoutError);
}
)
);
// A newer request (scroll, sort, search) cancels an older one still in flight,
// so a slow response can never overwrite newer rows.
this.subscriptions.add(
this.load$.pipe(
switchMap(request => {
this.gridLoading = true;
return this.virtualGridService.getPage(request).pipe(
catchError(err => {
this.showError(this.errorText(err, 'Failed to load data.'));
return of(null as VirtualGridPage);
}),
finalize(() => this.gridLoading = false)
);
})
).subscribe(page => this.onPageLoaded(page))
);
// Ask the server only once the user stops typing.
this.subscriptions.add(
this.search$.pipe(debounceTime(400), distinctUntilChanged()).subscribe(text => {
this.appliedSearch = text;
this.skip = 0;
this.requestPage();
})
);
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
/** Shows the grid for these filters, from the first row, with the search cleared and the default sort. */
load(filters: VirtualGridFilters): void {
if (!this.layout) {
this.pendingFilters = filters || {}; // runs as soon as the layout arrives
return;
}
this.filters = { ...(filters || {}) };
this.searchText = '';
this.appliedSearch = '';
this.search$.next(''); // keeps distinctUntilChanged in step with the cleared box
this.skip = 0;
this.resetSort();
this.gridView = { data: [], total: 0 };
this.totalWithoutSearch = 0;
this.started = true;
this.firstLoad = true;
this.requestPage(true); // Preview: the server reloads the data instead of using its kept copy
}
/** Reloads the current window, keeping filters, search and sort. */
reload(): void {
this.requestPage();
}
onPageChange(event: PageChangeEvent): void {
this.skip = event.skip;
this.requestPage();
}
onSortChange(sort: SortDescriptor[]): void {
this.sort = sort;
this.skip = 0;
this.requestPage();
}
onSearchChange(text: string): void {
this.search$.next((text || '').trim());
}
exportExcel(): void {
if (!this.started || this.gridView.total === 0 || this.exporting) {
return;
}
this.exporting = true;
if (this.loadingPanel) {
this.loadingPanel.ShowLoadingPanel = true;
}
const request = { ...this.buildRequest(0, 0), fields: this.layout.columns.map(c => c.field) };
const fileName = this.exportFileName || (this.layout.title || this.gridKey).replace(/[^A-Za-z0-9]+/g, '') + '.xlsx';
this.virtualGridService.exportExcel(request).pipe(
finalize(() => {
this.exporting = false;
if (this.loadingPanel) {
this.loadingPanel.ShowLoadingPanel = false;
}
})
).subscribe(
(blob: Blob) => saveAs(blob, fileName),
(err) => this.showBlobError(err, 'Failed to export to Excel.')
);
}
/**
* At least wide enough for the header title on one line plus the sort icon and cell padding,
* so no grid ever needs a wrapped or cut-off header (~8px per character + 48px).
*/
private fitWidth(column: { title: string; width: number }): number {
const titleWidth = (column.title || '').length * 8 + 48;
return Math.max(column.width || 0, titleWidth);
}
private resetSort(): void {
this.sort = this.layout && this.layout.defaultSortField
? [{ field: this.layout.defaultSortField, dir: this.layout.defaultSortDir || 'asc' }]
: [];
}
private requestPage(refresh = false): void {
if (!this.started || !this.layout) {
return;
}
this.load$.next({ ...this.buildRequest(this.skip, this.pageSize), refresh: refresh });
}
private buildRequest(skip: number, take: number): VirtualGridRequest {
const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null;
return {
gridKey: this.gridKey,
filters: this.filters,
skip: skip,
take: take,
search: this.appliedSearch || undefined,
sortField: sort ? sort.field : undefined,
sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined,
};
}
private onPageLoaded(page: VirtualGridPage): void {
if (!page) {
return;
}
this.gridView = { data: (page.data || []).map(row => this.formatRow(row)), total: page.total };
this.totalWithoutSearch = page.totalWithoutSearch;
this.loaded.emit({ total: page.total, totalWithoutSearch: page.totalWithoutSearch, firstLoad: this.firstLoad });
this.firstLoad = false;
}
/** Display formatting by column type: dates 'dd MMM yyyy', money with 2 decimals — the same text the server searches. */
private formatRow(row: { [field: string]: any }): { [field: string]: any } {
const result: { [field: string]: any } = { ...row };
for (const column of this.layout.columns) {
const value = row[column.field];
if (value === null || value === undefined || value === '') {
result[column.field] = '';
continue;
}
switch (column.type) {
case EnumVirtualGridColumnType.Date:
result[column.field] = formatDate(value, 'dd MMM yyyy', this.locale);
break;
case EnumVirtualGridColumnType.DateTime:
result[column.field] = formatDate(value, 'dd MMM yyyy HH:mm', this.locale);
break;
case EnumVirtualGridColumnType.Money:
result[column.field] = this.money.format(Number(value));
break;
default:
result[column.field] = String(value);
}
}
return result;
}
private errorText(err: any, fallback: string): string {
if (typeof err === 'string' && err) {
return err;
}
if (err && typeof err.error === 'string' && err.error) {
return err.error;
}
return fallback;
}
private showError(message: string): void {
if (this.notificationService) {
this.notificationService.showError(message);
} else {
console.error(message);
}
}
/** A failed file download returns its error message as a Blob; read it before showing it. */
private showBlobError(err: any, fallback: string): void {
const blob: Blob = err instanceof Blob ? err : (err && err.error instanceof Blob ? err.error : null);
if (blob) {
blob.text().then(text => this.showError(text || fallback), () => this.showError(fallback));
} else {
this.showError(this.errorText(err, fallback));
}
}
}

View File

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

View File

@ -17,28 +17,11 @@
</div>
</fieldset>
@if (showGrid) {
<div class="col-12">
<kendo-grid [kendoGridBinding]="filteredData" [sortable]="true" [resizable]="true" [pageable]="false"
[style.height]="'500px'">
<ng-template kendoGridToolbarTemplate>
<kendo-textbox class="grid-search" placeholder="Search in all columns..." [clearButton]="true"
[(ngModel)]="searchText" (valueChange)="onSearch($event)">
</kendo-textbox>
<label class="grid-count">
Total: {{ filteredData.length }}@if (searchText) { <span> of {{ data.length }}</span> }
</label>
<kendo-grid-spacer></kendo-grid-spacer>
<button type="button" kendoGridExcelCommand [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
[disabled]="filteredData.length === 0">
Export to Excel
</button>
</ng-template>
@for (column of columns; track column.field) {
<kendo-grid-column [field]="column.field" [title]="column.title" [width]="column.width">
</kendo-grid-column>
}
<kendo-grid-excel [fileName]="excelFileName"></kendo-grid-excel>
</kendo-grid>
</div>
}
<!-- Common server-paged virtual-scrolling grid; columns come from the server grid definition. -->
<div class="col-12">
<app-virtual-grid #grid gridKey="discontinue-employee" [height]="660"
exportFileName="DiscontinueEmployeeDetails.xlsx"
noRecordsText="No employee was discontinued in the selected date range."
(loaded)="onLoaded($event)">
</app-virtual-grid>
</div>

View File

@ -39,18 +39,8 @@
margin-left: auto;
}
.grid-search {
width: 280px;
}
.grid-count {
margin-left: 12px;
white-space: nowrap;
}
@media (max-width: 600px) {
.filter-field,
.grid-search {
.filter-field {
width: 100%;
}

View File

@ -1,23 +1,16 @@
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Component, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ApiService } from 'src/app/app.api.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { EmployeeServices } from 'src/app/_services/employee/employee.service';
import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service';
import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration';
import { EnumConfigurationType } from 'src/app/_models/enums';
interface GridColumn {
field: string;
title: string;
width: number;
}
import { VirtualGridComponent } from 'src/app/custom-components/virtual-grid/virtual-grid.component';
import { VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid';
/**
* Discontinue Employee Details: the same columns as Employee Details
* (/reports/report-viewer/empDetailInfo), but only for the employees discontinued
* inside a date range, plus their Discontinue Date. Export to Excel from the grid.
* Discontinue Employee Details: employees discontinued inside a date range, with the same columns as
* Employee Details (/reports/report-viewer/empDetailInfo) plus the Discontinue Date.
*
* The grid is the common <app-virtual-grid> (server grid "discontinue-employee",
* HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs); this screen only owns its filters.
*/
@Component({
selector: 'app-discontinue-employee-details',
@ -26,86 +19,19 @@ interface GridColumn {
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class DiscontinueEmployeeDetailsComponent implements OnInit {
export class DiscontinueEmployeeDetailsComponent {
@ViewChild('grid') grid: VirtualGridComponent;
fromDate: Date = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
toDate: Date = new Date();
dateFormat = 'dd-MMM-yyyy';
data: any[] = [];
filteredData: any[] = [];
searchText = '';
showGrid = false;
columns: GridColumn[] = [];
excelFileName = 'DiscontinueEmployeeDetails.xlsx';
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
public loadingPanel: loadingPanelService,
private employeeService: EmployeeServices,
private systemConfigService: SystemConfigurationService,
private datePipe: DatePipe) {
this.apiService.selectedMenuName = 'Discontinue Employee Details';
}
ngOnInit(): void {
this.buildColumns([]);
this.systemConfigService.GetAllChildrenByParentNode(EnumConfigurationType.Logic, 'department').subscribe(
(configs: SystemConfigaration[]) => this.buildColumns(configs || []),
() => this.buildColumns([])
);
}
/** Same columns, in the same order, as the Employee Details report, plus Discontinue Date. */
private buildColumns(departmentConfigs: SystemConfigaration[]): void {
const cols: GridColumn[] = [
{ field: 'employeeNo', title: 'Employee No', width: 110 },
{ field: 'name', title: 'Employee Name', width: 220 },
{ field: 'gender', title: 'Gender', width: 100 },
{ field: 'birthDate', title: 'Birth Date', width: 120 },
{ field: 'joiningDate', title: 'Joining Date', width: 120 },
{ field: 'discontinueDate', title: 'Discontinue Date', width: 130 },
{ field: 'mobileNo', title: 'Mobile No', width: 130 },
{ field: 'emailAddress', title: 'Email Address', width: 200 },
{ field: 'designation', title: 'Designation', width: 160 },
{ field: 'grade', title: 'Grade', width: 120 },
{ field: 'category', title: 'Category', width: 120 },
{ field: 'status', title: 'Status', width: 120 },
];
// Department tier headings come from the Logic configuration, exactly as in Employee Details.
const tierFields = ['deptireOne', 'deptireTwo', 'deptireThree', 'deptireFour', 'deptireFive'];
let ind = 0;
departmentConfigs.forEach(c => {
if (c.node && c.node.toLocaleLowerCase() === 'text') {
if (ind < tierFields.length) {
cols.push({ field: tierFields[ind], title: c.value, width: 150 });
}
ind++;
}
});
cols.push(
{ field: 'location', title: 'Location', width: 130 },
{ field: 'religion', title: 'Religion', width: 110 },
{ field: 'maritalStatus', title: 'Marital Status', width: 120 },
{ field: 'dateOfConfirmation', title: 'Confirmation', width: 120 },
{ field: 'basicSalary', title: 'Basic Salary', width: 120 },
{ field: 'grossSalary', title: 'Gross Salary', width: 120 },
{ field: 'passportNo', title: 'Passport No', width: 120 },
{ field: 'bloodGroup', title: 'Blood Group', width: 110 },
{ field: 'lineManagerNo', title: 'LineManager No', width: 130 },
{ field: 'lineManagerName', title: 'LineManager Name', width: 180 },
{ field: 'lineManagerEmail', title: 'LineManager Email', width: 200 },
{ field: 'empStatus', title: 'Employee Status', width: 130 },
{ field: 'bank', title: 'Bank', width: 150 },
{ field: 'branch', title: 'Branch', width: 150 },
{ field: 'accountNo', title: 'Account No', width: 150 },
{ field: 'nationalId', title: 'National ID/NID', width: 150 },
{ field: 'tinNo', title: 'TIN', width: 120 },
);
this.columns = cols;
}
preview(): void {
if (!this.fromDate || !this.toDate) {
this.notificationService.showWarning('Please select From Date and To Date.', 'Warning');
@ -115,54 +41,15 @@ export class DiscontinueEmployeeDetailsComponent implements OnInit {
this.notificationService.showWarning('From Date cannot be after To Date.', 'Warning');
return;
}
const from = this.datePipe.transform(this.fromDate, 'yyyy-MM-dd');
const to = this.datePipe.transform(this.toDate, 'yyyy-MM-dd');
this.excelFileName = 'DiscontinueEmployeeDetails_' + from + '_to_' + to + '.xlsx';
this.loadingPanel.ShowLoadingPanel = true;
this.showGrid = false;
this.searchText = '';
this.employeeService.getDiscontinueEmpDetailInfo(from, to).subscribe(
(resp: any[]) => {
this.data = (resp || []).map(row => this.formatRow(row));
this.filteredData = this.data;
},
(err) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showError(err && err.error ? err.error : 'Failed to load discontinued employees.');
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.showGrid = true;
if (this.data.length === 0) {
this.notificationService.showWarning('No employee was discontinued in the selected date range.', 'Warning');
}
}
);
this.grid.load({
fromDate: this.datePipe.transform(this.fromDate, 'yyyy-MM-dd'),
toDate: this.datePipe.transform(this.toDate, 'yyyy-MM-dd'),
});
}
/** Keeps the rows where any shown column contains the search text (case-insensitive). */
onSearch(value: string): void {
const term = (value || '').trim().toLowerCase();
if (!term) {
this.filteredData = this.data;
return;
onLoaded(event: VirtualGridLoadedEvent): void {
if (event.firstLoad && event.total === 0) {
this.notificationService.showWarning('No employee was discontinued in the selected date range.', 'Warning');
}
const fields = this.columns.map(c => c.field);
this.filteredData = this.data.filter(row =>
fields.some(f => row[f] != null && String(row[f]).toLowerCase().includes(term)));
}
/** Same display formatting as Employee Details: dates as 'dd MMM yyyy', salaries with 2 decimals. */
private formatRow(row: any): any {
['birthDate', 'joiningDate', 'dateOfConfirmation', 'discontinueDate'].forEach(f => {
row[f] = row[f] != null ? this.datePipe.transform(row[f], 'dd MMM yyyy') : '';
});
const money = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
['basicSalary', 'grossSalary'].forEach(f => {
row[f] = row[f] != null ? money.format(row[f]) : '0.00';
});
return row;
}
}

View File

@ -57,6 +57,7 @@ import { EssTaxCertificateComponent } from './ess-tax-certificate/ess-tax-certif
import { EmpCommonInformationModule } from '../ess/emp-common-information/EmpCommonInformationModule';
import { JvReportComponent } from './jv-report/jv-report.component';
import { DiscontinueEmployeeDetailsComponent } from './discontinue-employee-details/discontinue-employee-details.component';
import { VirtualGridModule } from '../custom-components/virtual-grid/virtual-grid.module';
@NgModule({
declarations: [
@ -114,7 +115,8 @@ import { DiscontinueEmployeeDetailsComponent } from './discontinue-employee-deta
CardModule,
BackgroundCanvasModule,
TabViewCompatModule,
EmpCommonInformationModule
EmpCommonInformationModule,
VirtualGridModule
],
providers: [
EmployeeServices,

View File

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

View File

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