From 7b43017c5270beee61e32ad0aa74455221bb28ba Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Mon, 9 Nov 2026 14:41:04 +0600 Subject: [PATCH] Virtual Scroll Grid --- DiscontinueEmployeeReport_DB_Changes.sql | 27 + HRM.BO/Employee/Employee.cs | 3 + .../Report/DiscontinueEmployeeDetailInfo.cs | 14 + HRM.BO/VirtualGrid/VirtualGrid.cs | 110 ++++ HRM.DA/DA/Employee/EmployeeDA.cs | 16 + HRM.DA/DA/VirtualGrid/VirtualGridDA.cs | 110 ++++ HRM.DA/Service/Employee/EmployeeService.cs | 154 +++++ .../DiscontinueEmployeeVirtualGrid.cs | 103 +++ HRM.DA/Service/VirtualGrid/README.md | 88 +++ .../VirtualGrid/VirtualGridDefinition.cs | 271 ++++++++ .../VirtualGrid/VirtualGridRegistry.cs | 27 + .../Service/VirtualGrid/VirtualGridService.cs | 591 ++++++++++++++++++ .../src/app/_models/common/virtual-grid.ts | 63 ++ .../_services/common/virtual-grid.service.ts | 30 + .../_services/employee/employee.service.ts | 6 - .../virtual-grid/virtual-grid.component.html | 46 ++ .../virtual-grid/virtual-grid.component.scss | 48 ++ .../virtual-grid/virtual-grid.component.ts | 290 +++++++++ .../virtual-grid/virtual-grid.module.ts | 15 + ...iscontinue-employee-details.component.html | 33 +- ...iscontinue-employee-details.component.scss | 12 +- .../discontinue-employee-details.component.ts | 149 +---- .../src/app/reports/reports.module.ts | 4 +- .../DI/ServiceCollectionExtensions.cs | 1 + .../CommonInterface/VirtualGridController.cs | 97 +++ 25 files changed, 2134 insertions(+), 174 deletions(-) create mode 100644 DiscontinueEmployeeReport_DB_Changes.sql create mode 100644 HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs create mode 100644 HRM.BO/VirtualGrid/VirtualGrid.cs create mode 100644 HRM.DA/DA/VirtualGrid/VirtualGridDA.cs create mode 100644 HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs create mode 100644 HRM.DA/Service/VirtualGrid/README.md create mode 100644 HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs create mode 100644 HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs create mode 100644 HRM.DA/Service/VirtualGrid/VirtualGridService.cs create mode 100644 HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts create mode 100644 HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts create mode 100644 HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html create mode 100644 HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.scss create mode 100644 HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts create mode 100644 HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts create mode 100644 HRM.UI/Controllers/CommonInterface/VirtualGridController.cs diff --git a/DiscontinueEmployeeReport_DB_Changes.sql b/DiscontinueEmployeeReport_DB_Changes.sql new file mode 100644 index 0000000..6034db6 --- /dev/null +++ b/DiscontinueEmployeeReport_DB_Changes.sql @@ -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 diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index 4ddf416..1bd8cd2 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -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 GetDiscontinuedEmployeeDetails(DateTime fromDate, DateTime toDate, int payrollTypeID); int GetCurrentHeadCount(int departmentId, int designationId, int gradeId); List GetbyDepartment(int deptId); List NotYetAssigned(int payrollTypeID); diff --git a/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs b/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs new file mode 100644 index 0000000..ce6c286 --- /dev/null +++ b/HRM.BO/Report/DiscontinueEmployeeDetailInfo.cs @@ -0,0 +1,14 @@ +using System; + +namespace HRM.BO.Report +{ + /// + /// One row of the Discontinue Employee Details report (Manage Employee › Report): the same fields as + /// Employee Details () plus the date the employee was discontinued + /// (Employee.ENDOFCONTRACTDATE). Loaded by IEmployeeService.GetDiscontinuedEmployeeDetails. + /// + public class DiscontinueEmployeeDetailInfo : EmployeeDetailInfo + { + public DateTime? DiscontinueDate { get; set; } + } +} diff --git a/HRM.BO/VirtualGrid/VirtualGrid.cs b/HRM.BO/VirtualGrid/VirtualGrid.cs new file mode 100644 index 0000000..d423bc5 --- /dev/null +++ b/HRM.BO/VirtualGrid/VirtualGrid.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + /// + /// Common virtual-scrolling grid ("virtual grid") contracts. + /// + /// Every large list screen shares ONE BO / DA / Service / Controller: a screen is just a registered + /// grid definition (HRM.DA/Service/VirtualGrid/Definitions) identified by . + /// The server pages, sorts, searches and exports; the browser only ever holds one window of rows. + /// See HRM.DA/Service/VirtualGrid/README.md for how to add a grid. + /// + public enum EnumVirtualGridColumnType + { + Text = 1, + Number = 2, + Money = 3, + Date = 4, + DateTime = 5 + } + + /// A column as the screen sees it (from the layout endpoint). + public class VirtualGridColumnInfo + { + public string Field { get; set; } + public string Title { get; set; } + public int Width { get; set; } + public EnumVirtualGridColumnType Type { get; set; } + public bool Sortable { get; set; } + } + + /// Everything the screen needs to draw an empty grid before any data is requested. + public class VirtualGridLayout + { + public string GridKey { get; set; } + public string Title { get; set; } + public string DefaultSortField { get; set; } + public string DefaultSortDir { get; set; } + public int MaxPageSize { get; set; } + public List Columns { get; set; } = new List(); + } + + /// One window request: which grid, its filters, and the grid's skip/take, sort and search. + public class VirtualGridRequest + { + public string GridKey { get; set; } + + /// + /// Screen-specific filters (e.g. fromDate / toDate as "yyyy-MM-dd"). Each grid definition reads and + /// validates the ones it needs; values are never spliced into SQL. + /// + public Dictionary Filters { get; set; } = new Dictionary(); + + public int Skip { get; set; } + public int Take { get; set; } = 100; + public string Search { get; set; } + public string SortField { get; set; } + public string SortDir { get; set; } + + /// + /// True on Preview: reload the data instead of using the copy kept in server memory (list grids). + /// Scrolling, sorting and searching send false and are answered from that copy. + /// + public bool Refresh { get; set; } + } + + /// Excel export: the same request plus the grid's visible columns, in order. + public class VirtualGridExportRequest : VirtualGridRequest + { + /// Fields of the columns to export, in grid order. Empty = every column of the grid. + public List Fields { get; set; } = new List(); + } + + public class VirtualGridPage + { + /// Rows matching the filters and the search. + public int Total { get; set; } + + /// Rows matching the filters alone (equals Total when there is no search). + public int TotalWithoutSearch { get; set; } + + /// One row per entry, keyed by column field. Values are raw (dates, numbers); the screen formats them. + public List> Data { get; set; } = new List>(); + } + + /// A generated file (Excel export). + public class VirtualGridFile + { + public string FileName { get; set; } + public string ContentType { get; set; } + public byte[] Content { get; set; } + } + + /// The signed-in user, as the grid definitions need it for scoping (payroll type) and access. + public class VirtualGridContext + { + public int UserID { get; set; } + public int? EmployeeID { get; set; } + public int? PayrollTypeID { get; set; } + public EnumUserType UserType { get; set; } + } + + public interface IVirtualGridService + { + VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context); + VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context); + VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context); + } +} diff --git a/HRM.DA/DA/Employee/EmployeeDA.cs b/HRM.DA/DA/Employee/EmployeeDA.cs index 6adbd52..4f290b5 100644 --- a/HRM.DA/DA/Employee/EmployeeDA.cs +++ b/HRM.DA/DA/Employee/EmployeeDA.cs @@ -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(); diff --git a/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs b/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs new file mode 100644 index 0000000..24fd9fb --- /dev/null +++ b/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs @@ -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 +{ + /// + /// Everything VirtualGridDA needs to build a grid's SQL. Built by VirtualGridService from a grid + /// definition; all SQL fragments in it are code-produced (definition expressions, whitelisted sort, + /// integer lists), and all user values are parameters. + /// + internal sealed class VirtualGridQuery + { + /// "sqlExpression AS [alias]" entries. + public List Select { get; } = new List(); + + public VirtualGridSource Source { get; set; } + + /// Columns searched with LIKE, with the type that decides how each is rendered as text. + public List> SearchColumns { get; } = + new List>(); + + /// Extra OR-branches of the search (code-produced, e.g. "e.DEPARTMENTID IN (1,2)"). + public List SearchPredicates { get; } = new List(); + + /// The escaped LIKE pattern ("%text%"), or null for no search. + public string SearchPattern { get; set; } + + /// Whitelisted sort expression including ASC/DESC. + public string OrderBy { get; set; } + + public string TieBreaker { get; set; } + } + + /// + /// The one data-access class behind every virtual grid: a COUNT and an OFFSET/FETCH window (or every + /// row, for Excel) over the grid's source, with search and sort done by SQL Server. + /// + internal static class VirtualGridDA + { + internal static int Count(TransactionContext tc, VirtualGridQuery query, bool withSearch) + { + string sql = "SELECT COUNT(*) " + query.Source.FromWhere + SearchClause(query, withSearch); + object value = tc.ExecuteScalar(CommandType.Text, sql, Parameters(query, withSearch, null, null)); + return value == null || value == DBNull.Value ? 0 : Convert.ToInt32(value); + } + + /// One window of rows; with null, every row (Excel export). + internal static IDataReader GetRows(TransactionContext tc, VirtualGridQuery query, int skip, int? take) + { + string sql = "SELECT " + string.Join(", ", query.Select) + " " + + query.Source.FromWhere + SearchClause(query, true) + + " ORDER BY " + query.OrderBy + ", " + query.TieBreaker + " ASC"; + if (take.HasValue) + sql += " OFFSET @__Skip ROWS FETCH NEXT @__Take ROWS ONLY"; + return tc.ExecuteReader(CommandType.Text, sql, Parameters(query, true, skip, take)); + } + + /// A column as the screen displays it, so the user can search what they see. + private static string AsDisplayText(string sql, EnumVirtualGridColumnType type) + { + switch (type) + { + case EnumVirtualGridColumnType.Date: + return "CONVERT(varchar(11), " + sql + ", 106)"; // 13 Feb 2025 + case EnumVirtualGridColumnType.DateTime: + return "(CONVERT(varchar(11), " + sql + ", 106) + ' ' + CONVERT(varchar(5), " + sql + ", 108))"; + case EnumVirtualGridColumnType.Money: + return "CONVERT(varchar(30), CAST(" + sql + " AS money), 1)"; // 1,234.56 + case EnumVirtualGridColumnType.Number: + return "CONVERT(varchar(40), " + sql + ")"; + default: + return sql; + } + } + + private static string SearchClause(VirtualGridQuery query, bool withSearch) + { + if (!withSearch || string.IsNullOrEmpty(query.SearchPattern)) + return string.Empty; + + List parts = query.SearchColumns + .Select(c => AsDisplayText(c.Key, c.Value) + @" LIKE @__Search ESCAPE '\'") + .Concat(query.SearchPredicates) + .ToList(); + return parts.Count == 0 ? " AND 1 = 0" : " AND (" + string.Join(" OR ", parts) + ")"; + } + + private static IDataParameter[] Parameters(VirtualGridQuery query, bool withSearch, int? skip, int? take) + { + // Clones: a SqlParameter cannot belong to two commands, and one query runs several. + var list = query.Source.Parameters + .Select(p => (SqlParameter)((ICloneable)p).Clone()) + .ToList(); + if (withSearch && !string.IsNullOrEmpty(query.SearchPattern)) + list.Add(SqlHelperExtension.CreateInParam("@__Search", SqlDbType.NVarChar, query.SearchPattern, 400)); + if (take.HasValue) + { + list.Add(SqlHelperExtension.CreateInParam("@__Skip", SqlDbType.Int, skip ?? 0)); + list.Add(SqlHelperExtension.CreateInParam("@__Take", SqlDbType.Int, take.Value)); + } + return list.ToArray(); + } + } +} diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index f0d72a9..cb05a7e 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -2730,6 +2730,160 @@ namespace HRM.DA return oEmpDetails; } + #region Discontinue Employee Details + + /// + /// Employees discontinued between fromDate and toDate (by discontinue date) in one payroll type, with + /// the same fields, null handling and department tiers as the Employee Details report. + /// One query for all rows; departments are loaded once and looked up by ID. + /// + public List GetDiscontinuedEmployeeDetails(DateTime fromDate, + DateTime toDate, int payrollTypeID) + { + var items = new List(); + Dictionary departments = new DepartmentService().GetAll() + .GroupBy(d => d.ID) + .ToDictionary(g => g.Key, g => g.First()); + + 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 departments) + { + var item = new HRM.BO.Report.DiscontinueEmployeeDetailInfo(); + item.EmployeeId = dr.GetInt32("EmployeeId") ?? 0; + item.EmployeeNo = dr.GetString("EMPLOYEENO"); + item.Name = dr.GetString("NAME"); + item.BasicSalary = dr.GetDecimal("BASICSALARY") ?? 0; + item.GrossSalary = dr.GetDecimal("GrossSalary") ?? 0; + item.TaxAmount = dr.GetDecimal("TAXAMOUNT") ?? 0; + item.FatherName = dr.GetString("Fathername"); + item.FatherOccupation = dr.GetString("FatherOccupation"); + item.MotherOccupation = dr.GetString("MotherOccupation"); + item.MotherName = dr.GetString("MotherName"); + item.Gender = dr.GetString("Gender"); + item.BirthDate = dr.GetDateTime("BIRTHDATE"); + item.BirthPlace = dr.GetString("BIRTHPlace"); + item.TinNo = dr.GetString("TINNO"); + item.JoiningDate = dr.GetDateTime("JOININGDATE"); + item.EmailAddress = dr.GetString("EMAILADDRESS"); + item.Category = dr.GetString("Category"); + item.Status = dr.GetString("Status"); + item.Location = dr.GetString("Location"); + item.Division = dr.GetString("Division"); + item.Company = dr.GetString("Company"); + item.Department = dr.GetString("Department"); + item.Section = dr.GetString("Section"); + item.Designation = dr.GetString("DESIGNATION"); + item.Grade = dr.GetString("GRADE"); + item.Religion = dr.GetString("RELIGION"); + item.MaritalStatus = dr.GetString("MaritalStatus"); + item.MobileNo = dr.GetString("MOBILENO"); + item.DateOfConfirmation = dr.GetDateTime("DATEOFCONFIRMATION"); + item.NationalId = dr.GetString("NATIONALID"); + item.PassportNo = dr.GetString("PassPortNo"); + item.PhotoPath = dr.GetString("PhotoPath"); + int? bloodGroup = dr.GetInt32("bloodgroup"); + item.BloodGroup = ((EnumBloodGroup)(bloodGroup ?? (int)EnumBloodGroup.None)).BloodGroupToFriendlyName(); + item.LineManagerNo = dr.GetString("LineManagerNo"); + item.LineManagerName = dr.GetString("LineManagerName"); + item.LineManagerEmail = dr.GetString("LineManagerEmail"); + item.LineManagerDes = dr.GetString("LineManagerDes"); + item.LmDivision = dr.GetString("lmDivision"); + item.LmDepartment = dr.GetString("lmDepartment"); + item.EmpStatus = dr.GetString("EmpStatus"); + item.Nationality = dr.GetString("NATIONALITY"); + item.OutPayBank = dr.GetString("OUTPayBank"); + item.OutPayBranch = dr.GetString("OUTPayBranch"); + item.OutPayAccountNo = dr.GetString("OutPayAccountNo"); + // Bank / Branch / Account No fall back to the out-pay values when empty, as Employee Details shows them. + string accountNo = dr.GetString("ACCOUNTNO"); + string bank = dr.GetString("Bank"); + string branch = dr.GetString("Branch"); + item.AccountNo = string.IsNullOrEmpty(accountNo) ? item.OutPayAccountNo : accountNo; + item.Bank = string.IsNullOrEmpty(bank) ? item.OutPayBank : bank; + item.Branch = string.IsNullOrEmpty(branch) ? item.OutPayBranch : branch; + item.DiscontinueDate = dr.GetDateTime("DiscontinueDate"); + + int? departmentID = dr.GetInt32("EmpDepartmentID"); + Department department = null; + if (departmentID.HasValue) + departments.TryGetValue(departmentID.Value, out department); + string[] tiers = GetDepartmentTierNames(department, departments); + if (tiers != null) + { + item.deptireOne = tiers[0]; + item.deptireTwo = tiers[1]; + item.deptireThree = tiers[2]; + item.deptireFour = tiers[3]; + item.deptireFive = tiers[4]; + } + return item; + } + + /// + /// The five department tier names (tier 1 = top), worked out exactly as the Employee Details report + /// (EmployeeController.GetEmpDetailInfo) does. Null when there is no department. + /// + private static string[] GetDepartmentTierNames(Department dept, Dictionary departments) + { + if (dept == null) + return null; + + Func find = id => + { + Department d = null; + if (id.HasValue) + departments.TryGetValue(id.Value, out d); + return d; + }; + + Department tire5 = null, tire4 = null, tire3 = null, tire2 = null, tire1 = null; + if (dept.ParentID != null) + { + for (int i = dept.Tier; i > 0; i--) + { + if (i == 5) tire5 = find(dept.ID); + if (i == 4) tire4 = tire5 != null ? find(tire5.ParentID) : find(dept.ID); + if (i == 3) tire3 = tire4 != null ? find(tire4.ParentID) : find(dept.ID); + if (i == 2) tire2 = tire3 != null ? find(tire3.ParentID) : find(dept.ID); + if (i == 1) tire1 = tire2 != null ? find(tire2.ParentID) : find(dept.ID); + } + } + + return new[] + { + tire1 == null ? "" : tire1.Name, + tire2 == null ? "" : tire2.Name, + tire3 == null ? "" : tire3.Name, + tire4 == null ? "" : tire4.Name, + tire5 == null ? "" : tire5.Name, + }; + } + + #endregion + public DataSet GetEmpDetailsView() { DataSet oEmpDetails = new DataSet(); diff --git a/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs b/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs new file mode 100644 index 0000000..c65bc77 --- /dev/null +++ b/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using HRM.BO; +using HRM.BO.Report; + +namespace HRM.DA +{ + /// + /// Discontinue Employee Details (Manage Employee › Report, /reports/discontinue-employee-details): + /// employees discontinued inside a date range, with the same columns as Employee Details plus the + /// Discontinue Date. + /// + /// The data comes the usual way — EmployeeService.GetDiscontinuedEmployeeDetails returns a + /// List<DiscontinueEmployeeDetailInfo> (query in EmployeeDA) — and the common virtual grid pages it. + /// Filters: fromDate, toDate ("yyyy-MM-dd", both required). Scoped to the user's payroll type. + /// + internal sealed class DiscontinueEmployeeVirtualGrid : VirtualGridListDefinition + { + public const string GridKey = "discontinue-employee"; + + public override string Key => GridKey; + public override string Title => "Discontinue Employee Details"; + public override string DefaultSortField => "employeeNo"; + public override string ExcelFileName => "DiscontinueEmployeeDetails.xlsx"; + + /// Each Field is a property of DiscontinueEmployeeDetailInfo. + public override List GetColumns(VirtualGridContext context) + { + var columns = new List + { + new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 }, + new VirtualGridColumn { Field = "name", Title = "Employee Name", Width = 220 }, + new VirtualGridColumn { Field = "gender", Title = "Gender", Width = 100 }, + new VirtualGridColumn { Field = "birthDate", Title = "Birth Date", Width = 120, Type = EnumVirtualGridColumnType.Date }, + new VirtualGridColumn { Field = "joiningDate", Title = "Joining Date", Width = 120, Type = EnumVirtualGridColumnType.Date }, + new VirtualGridColumn { Field = "discontinueDate", Title = "Discontinue Date", Width = 140, Type = EnumVirtualGridColumnType.Date }, + new VirtualGridColumn { Field = "mobileNo", Title = "Mobile No", Width = 130 }, + new VirtualGridColumn { Field = "emailAddress", Title = "Email Address", Width = 200 }, + new VirtualGridColumn { Field = "designation", Title = "Designation", Width = 160 }, + new VirtualGridColumn { Field = "grade", Title = "Grade", Width = 120 }, + new VirtualGridColumn { Field = "category", Title = "Category", Width = 120 }, + new VirtualGridColumn { Field = "status", Title = "Status", Width = 120 }, + }; + + // Department tier headings come from the Logic configuration, as in Employee Details. + string[] tierFields = { "deptireOne", "deptireTwo", "deptireThree", "deptireFour", "deptireFive" }; + List configs = new SystemConfigarationService() + .GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department") ?? new List(); + int tier = 0; + foreach (SystemConfigaration c in configs) + { + if (!string.Equals(c.Node, "text", StringComparison.OrdinalIgnoreCase)) + continue; + if (tier < tierFields.Length) + columns.Add(new VirtualGridColumn { Field = tierFields[tier], Title = c.Value, Width = 150 }); + tier++; + } + + columns.AddRange(new[] + { + new VirtualGridColumn { Field = "location", Title = "Location", Width = 130 }, + new VirtualGridColumn { Field = "religion", Title = "Religion", Width = 110 }, + new VirtualGridColumn { Field = "maritalStatus", Title = "Marital Status", Width = 120 }, + new VirtualGridColumn { Field = "dateOfConfirmation", Title = "Confirmation", Width = 120, Type = EnumVirtualGridColumnType.Date }, + new VirtualGridColumn { Field = "basicSalary", Title = "Basic Salary", Width = 120, Type = EnumVirtualGridColumnType.Money }, + new VirtualGridColumn { Field = "grossSalary", Title = "Gross Salary", Width = 120, Type = EnumVirtualGridColumnType.Money }, + new VirtualGridColumn { Field = "passportNo", Title = "Passport No", Width = 120 }, + new VirtualGridColumn { Field = "bloodGroup", Title = "Blood Group", Width = 110 }, + new VirtualGridColumn { Field = "lineManagerNo", Title = "LineManager No", Width = 130 }, + new VirtualGridColumn { Field = "lineManagerName", Title = "LineManager Name", Width = 180 }, + new VirtualGridColumn { Field = "lineManagerEmail", Title = "LineManager Email", Width = 200 }, + new VirtualGridColumn { Field = "empStatus", Title = "Employee Status", Width = 130 }, + new VirtualGridColumn { Field = "bank", Title = "Bank", Width = 150 }, + new VirtualGridColumn { Field = "branch", Title = "Branch", Width = 150 }, + new VirtualGridColumn { Field = "accountNo", Title = "Account No", Width = 150 }, + new VirtualGridColumn { Field = "nationalId", Title = "National ID/NID", Width = 150 }, + new VirtualGridColumn { Field = "tinNo", Title = "TIN", Width = 120 }, + }); + return columns; + } + + protected override List LoadData(VirtualGridFilters filters, VirtualGridContext context) + { + DateTime fromDate = filters.GetDate("fromDate", "From Date", true).Value; + DateTime toDate = filters.GetDate("toDate", "To Date", true).Value; + if (fromDate > toDate) + throw new ArgumentException("From Date cannot be after To Date."); + if (!context.PayrollTypeID.HasValue) + throw new ArgumentException("No payroll type is selected for your login."); + + return new EmployeeService().GetDiscontinuedEmployeeDetails(fromDate, toDate, context.PayrollTypeID.Value); + } + + public override string DescribeFilters(VirtualGridFilters filters) + { + DateTime? fromDate = filters.GetDate("fromDate", "From Date", false); + DateTime? toDate = filters.GetDate("toDate", "To Date", false); + return "Discontinued from " + fromDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) + + " to " + toDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture); + } + } +} diff --git a/HRM.DA/Service/VirtualGrid/README.md b/HRM.DA/Service/VirtualGrid/README.md new file mode 100644 index 0000000..0ad94e6 --- /dev/null +++ b/HRM.DA/Service/VirtualGrid/README.md @@ -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` (query in the module's DA). A grid +only says *which* service method to call and *which* columns to show. + +| Layer | File | Role | +|---|---|---| +| BO | `HRM.BO/VirtualGrid/VirtualGrid.cs` | Request/page/layout DTOs, `EnumVirtualGridColumnType`, `IVirtualGridService` | +| Service | `HRM.DA/Service/VirtualGrid/VirtualGridService.cs` | Access check, keeps the loaded list in memory, search/sort/page, Excel | +| Grids | `HRM.DA/Service/VirtualGrid/Definitions/*.cs` | **One small class per grid**: columns + which service to call | +| Registry | `HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs` | Key → grid. Unlisted keys cannot be queried | +| Controller | `HRM.UI/Controllers/CommonInterface/VirtualGridController.cs` | `GET api/virtualGrid/layout/{key}`, `POST page`, `POST export-excel` | +| Angular | `custom-components/virtual-grid/` (`VirtualGridModule`, ``) | Virtual scrolling, search box, sort, total, Excel button | + +## How it works + +1. Screen opens → the component asks for the grid's columns (`layout`). +2. **Preview** → `grid.load(filters)` → `page` with `refresh: true` → the grid's `LoadData` calls the + service (e.g. `EmployeeService.GetDiscontinuedEmployeeDetails`) → the whole `List` is kept in + server memory (per user + filters, 10 min sliding / 30 min max) → the first 100 rows go back. +3. **Scroll / sort / search** → `page` with `refresh: false` → answered from the kept list: search, + sort, `Skip/Take` 100. The service is not called again. +4. **Export to Excel** → every matching row of the kept list, same order, as `.xlsx`. + +The browser only ever holds ~100 rows, however long the list is. + +## Adding a grid (existing screen with a service that already returns a list) + +1. **Grid class** — `Definitions/VirtualGrid.cs`: + ```csharp + internal sealed class LeaveHistoryVirtualGrid : VirtualGridListDefinition + { + public const string GridKey = "leave-history"; + public override string Key => GridKey; + public override string Title => "Leave History"; + + public override List GetColumns(VirtualGridContext context) => new List + { + // Field = a property of LeaveEntry (camelCase) + new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 }, + new VirtualGridColumn { Field = "fromDate", Title = "From", Width = 120, Type = EnumVirtualGridColumnType.Date }, + new VirtualGridColumn { Field = "amount", Title = "Amount", Width = 120, Type = EnumVirtualGridColumnType.Money }, + }; + + protected override List LoadData(VirtualGridFilters filters, VirtualGridContext context) + { + DateTime from = filters.GetDate("fromDate", "From Date", true).Value; // user-facing errors + DateTime to = filters.GetDate("toDate", "To Date", true).Value; + return new LeaveEntryService().Get(from, to, context.PayrollTypeID.Value); // the existing service + } + } + ``` +2. **Registry** — `{ LeaveHistoryVirtualGrid.GridKey, () => new LeaveHistoryVirtualGrid() }`. +3. **Screen** — import `VirtualGridModule`, then: + ```html + + ``` + ```ts + this.grid.load({ fromDate: '2025-01-01', toDate: '2025-12-31' }); // filters as strings + ``` + +No new controller, Angular service or model. For a brand-new screen, write its query in the module's +DA and a service method returning `List` (as always), then steps 1–3. + +Worked example: `Definitions/DiscontinueEmployeeVirtualGrid.cs` → +`EmployeeService.GetDiscontinuedEmployeeDetails` → `EmployeeDA.GetDiscontinuedEmployeeDetails`. + +## Column types + +`Text` (default), `Number`, `Money` (`1,234.56`), `Date` (`dd MMM yyyy`), `DateTime` (`dd MMM yyyy HH:mm`). +The screen shows values in that format and the search box searches that same text, so users find what +they see. Set `Sortable = false` / `Searchable = false` on a column to turn either off. + +## Very large lists: `VirtualGridSqlDefinition` (advanced) + +A list grid loads the whole list once per Preview — fine up to tens of thousands of rows. When even +that is too slow, derive from `VirtualGridSqlDefinition` instead: give each column a `Sql` expression +and a `BuildSource` returning `FROM … WHERE …` with parameters, and SQL Server pages each request +(`OFFSET/FETCH`, `HRM.DA/DA/VirtualGrid/VirtualGridDA.cs`). User values reach SQL only as parameters; +spliced text is code-produced only. + +## Rules + +- A service a grid calls must not run one query per row; load lookups once (see `GetDiscontinuedEmployeeDetails`). +- Self-service (ESS) logins are refused unless the grid sets `AllowSelfServiceUsers`. Authorization in + this app is menu-driven, so add any further check a grid needs in `LoadData`. +- The kept list is per user, payroll type, grid and filter values; Preview always reloads it. diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs b/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs new file mode 100644 index 0000000..02f8de1 --- /dev/null +++ b/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs @@ -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 +{ + /// + /// One column of a virtual grid. Field is the name the screen uses. In a list grid it is a property + /// of the business object; in a SQL grid it is the alias of Sql, the expression the column selects, + /// sorts and searches by (null = filled in code, not sorted or searched by SQL). + /// + internal sealed class VirtualGridColumn + { + public string Field { get; set; } + public string Title { get; set; } + public int Width { get; set; } = 130; + public EnumVirtualGridColumnType Type { get; set; } = EnumVirtualGridColumnType.Text; + public string Sql { get; set; } + public bool Sortable { get; set; } = true; + public bool Searchable { get; set; } = true; + + } + + /// + /// The rows a grid is built on: a "FROM ... WHERE ..." clause plus its parameters. + /// Filter values must only ever reach SQL through . + /// + internal sealed class VirtualGridSource + { + public string FromWhere { get; set; } + public List Parameters { get; } = new List(); + + /// Human-readable filter summary, printed at the top of the Excel file. + public string FilterDescription { get; set; } + } + + /// + /// Extra search conditions a definition adds for values that are worked out in code (e.g. department + /// tier names): each becomes one more OR branch of the search. Only code-produced SQL goes here. + /// + internal sealed class VirtualGridSearchExtras + { + internal List Predicates { get; } = new List(); + + /// Adds "sqlExpression IN (v1, v2, …)" — the values are integers, so they are safe to splice. + public void AddIntIn(string sqlExpression, IEnumerable values) + { + List list = (values ?? Enumerable.Empty()).Distinct().ToList(); + if (list.Count > 0) + Predicates.Add(sqlExpression + " IN (" + string.Join(",", list.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ")"); + } + } + + /// + /// Typed, validated access to . Every problem is an + /// ArgumentException with a message fit to show the user (the controller returns it as 400). + /// + internal sealed class VirtualGridFilters + { + private readonly Dictionary _values; + + public VirtualGridFilters(Dictionary values) + { + _values = new Dictionary(values ?? new Dictionary(), StringComparer.OrdinalIgnoreCase); + } + + public string GetString(string name) + { + string value; + return _values.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value) ? value.Trim() : null; + } + + /// A "yyyy-MM-dd" date. is the name the user sees ("From Date"). + public DateTime? GetDate(string name, string label, bool required) + { + string text = GetString(name); + if (text == null) + { + if (required) + throw new ArgumentException("Please select " + label + "."); + return null; + } + DateTime value; + if (!DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) + throw new ArgumentException("Please select a valid " + label + "."); + return value; + } + + public int? GetInt(string name, string label, bool required) + { + string text = GetString(name); + if (text == null) + { + if (required) + throw new ArgumentException("Please select " + label + "."); + return null; + } + int value; + if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) + throw new ArgumentException("Please select a valid " + label + "."); + return value; + } + } + + /// + /// Base class of every virtual grid: what the grid is called, its columns and its limits. + /// A grid derives from one of the two kinds below, never from this class directly: + /// + /// - VirtualGridListDefinition<T> (the usual choice): LoadData calls an ordinary service method + /// that returns a List of business objects, exactly as screens always get their data. The common + /// service keeps that list in memory and pages, sorts, searches and exports it on the server. + /// - VirtualGridSqlDefinition (for very large lists): the grid gives a FROM/WHERE and SQL Server + /// does the paging, so only one window of rows is ever read. + /// + /// A new instance is created for every call, so a definition may keep per-call state. + /// + internal abstract class VirtualGridDefinition + { + private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); + + /// The key the screen sends (e.g. "discontinue-employee"). + public abstract string Key { get; } + + public abstract string Title { get; } + + public virtual string DefaultSortField => null; // null = first sortable column + public virtual string DefaultSortDir => "asc"; + + /// Self-service (ESS) logins are refused unless a grid opts in. + public virtual bool AllowSelfServiceUsers => false; + + public virtual int MaxPageSize => 500; + + /// Largest Excel export allowed; past it the user is asked to narrow the filters. + public virtual int ExportRowLimit => 200000; + + public virtual string ExcelFileName => Regex.Replace(Title, "[^A-Za-z0-9]+", "") + ".xlsx"; + + /// The grid's columns, in display order. May depend on configuration (e.g. department tier names). + public abstract List GetColumns(VirtualGridContext context); + + /// Whether the user can sort by this column. + internal virtual bool CanSort(VirtualGridColumn column) => column.Sortable; + + /// Whether the search box looks in this column. + internal virtual bool CanSearch(VirtualGridColumn column) => column.Searchable; + + internal static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); + } + + /// + /// A grid filled from an ordinary service method that returns a list of business objects, the way + /// screens have always loaded their data: + /// + /// protected override List<LeaveEntry> LoadData(VirtualGridFilters filters, VirtualGridContext context) + /// => new LeaveEntryService().Get(...); + /// + /// Each column's Field is the name of a property of T (camelCase, matched case-insensitively); + /// Sql is not used. + /// + /// The list is loaded on Preview and kept in server memory for a few minutes, so scrolling, sorting + /// and searching do not call the service again. Suits lists up to tens of thousands of rows; for + /// larger ones use VirtualGridSqlDefinition. + /// + internal abstract class VirtualGridListDefinition : VirtualGridDefinition, IVirtualGridListSource where T : class + { + /// Reads/validates the filters and returns the rows, usually with one call to an existing service. + protected abstract List LoadData(VirtualGridFilters filters, VirtualGridContext context); + + /// Human-readable filter summary, printed at the top of the Excel file. Optional. + public virtual string DescribeFilters(VirtualGridFilters filters) => null; + + /// Calls LoadData and turns each object into a row holding just the grid's columns. + List> IVirtualGridListSource.LoadRows( + VirtualGridFilters filters, VirtualGridContext context, List columns) + { + var properties = new List>(); + foreach (VirtualGridColumn c in columns) + { + PropertyInfo property = FindProperty(c.Field); + if (property == null || !property.CanRead) + throw new InvalidOperationException("Virtual grid '" + Key + "': " + typeof(T).Name + + " has no readable property for column '" + c.Field + "'."); + properties.Add(new KeyValuePair(c.Field, property)); + } + + List items = LoadData(filters, context) ?? new List(); + var rows = new List>(items.Count); + foreach (T item in items) + { + if (item == null) + continue; + var row = new Dictionary(properties.Count, StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair p in properties) + row[p.Key] = p.Value.GetValue(item); + rows.Add(row); + } + return rows; + } + + /// + /// The public property named (case-insensitive). When a class hides a base + /// property with "new" (e.g. EmployeeDetailInfo.Status over the base Status), the most derived one — + /// the one the business object itself shows — wins. + /// + private static PropertyInfo FindProperty(string field) + { + PropertyInfo best = null; + int bestDepth = int.MaxValue; + foreach (PropertyInfo p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (!string.Equals(p.Name, field, StringComparison.OrdinalIgnoreCase) || p.GetIndexParameters().Length > 0) + continue; + int depth = 0; + for (Type t = typeof(T); t != null && t != p.DeclaringType; t = t.BaseType) + depth++; + if (depth < bestDepth) + { + best = p; + bestDepth = depth; + } + } + return best; + } + } + + /// Non-generic view of a list grid, used by VirtualGridService. + internal interface IVirtualGridListSource + { + List> LoadRows(VirtualGridFilters filters, VirtualGridContext context, List columns); + string DescribeFilters(VirtualGridFilters filters); + } + + /// + /// A grid whose paging, sorting and searching run in SQL Server: for very large lists, where loading + /// every row (even once) is too slow. Each column's Sql is the expression it selects, sorts and searches + /// by; a column with Sql = null is filled in OnRowsLoaded. + /// + internal abstract class VirtualGridSqlDefinition : VirtualGridDefinition + { + /// A unique, stable SQL expression (usually the primary key) used as the last sort key so pages never overlap. + public abstract string TieBreakerSql { get; } + + /// + /// Extra values selected for OnRowsLoaded only, as "sqlExpression AS _alias". + /// Aliases must start with '_'; they are removed from the rows before they leave the server. + /// + public virtual IEnumerable HiddenSelect => Enumerable.Empty(); + + /// Reads/validates the filters and returns the FROM/WHERE the grid is built on. + public abstract VirtualGridSource BuildSource(VirtualGridFilters filters, VirtualGridContext context); + + /// Adds OR-conditions for code-computed values matching the search text. Optional. + public virtual void AddSearchExtras(string term, VirtualGridSearchExtras extras, VirtualGridContext context) + { + } + + /// Fills code-computed columns (and reformats values) on one loaded window of rows. Optional. + public virtual void OnRowsLoaded(List> rows, VirtualGridContext context) + { + } + + internal override bool CanSort(VirtualGridColumn column) => column.Sortable && !string.IsNullOrEmpty(column.Sql); + internal override bool CanSearch(VirtualGridColumn column) => column.Searchable && !string.IsNullOrEmpty(column.Sql); + } +} diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs b/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs new file mode 100644 index 0000000..e1357d4 --- /dev/null +++ b/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; + +namespace HRM.DA +{ + /// + /// Every virtual grid the application serves, by key. Adding a grid = one definition class in + /// Definitions/ and one line here. A key that is not listed here cannot be queried. + /// + internal static class VirtualGridRegistry + { + private static readonly Dictionary> Grids = + new Dictionary>(StringComparer.OrdinalIgnoreCase) + { + { DiscontinueEmployeeVirtualGrid.GridKey, () => new DiscontinueEmployeeVirtualGrid() }, + }; + + /// A fresh definition instance for one call. Throws ArgumentException for an unknown key. + internal static VirtualGridDefinition Create(string gridKey) + { + Func factory; + if (string.IsNullOrWhiteSpace(gridKey) || !Grids.TryGetValue(gridKey.Trim(), out factory)) + throw new ArgumentException("Unknown grid: " + gridKey); + return factory(); + } + } +} diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridService.cs b/HRM.DA/Service/VirtualGrid/VirtualGridService.cs new file mode 100644 index 0000000..a5a3863 --- /dev/null +++ b/HRM.DA/Service/VirtualGrid/VirtualGridService.cs @@ -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 +{ + /// + /// The one service behind every virtual-scrolling grid (api/virtualGrid). It looks the grid up in + /// and serves it in one of two ways: + /// + /// - List grid (): the grid's existing service returns a + /// List of business objects; that list is kept in server memory for a few minutes and every scroll, + /// sort, search and Excel export is answered from it. + /// - SQL grid (): SQL Server counts, sorts, searches and returns + /// one OFFSET/FETCH window per request (VirtualGridDA). + /// + /// Shared work for both: access check, column validation, paging limits, sort whitelist, the Excel file. + /// + public class VirtualGridService : ServiceTemplate, IVirtualGridService + { + private const int ExportCommandTimeoutSeconds = 600; + private const int MaxSearchLength = 200; + private const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + // List grids: loaded lists, per user + grid + filters. Size = rows, so at most ~1,000,000 rows are + // held in total; the least recently used lists are dropped first. + private static readonly MemoryCache ListCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000000 }); + private static readonly TimeSpan ListCacheSliding = TimeSpan.FromMinutes(10); + private static readonly TimeSpan ListCacheAbsolute = TimeSpan.FromMinutes(30); + + #region Public API + + public VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context) + { + VirtualGridDefinition grid = Open(gridKey, context); + List columns = GetValidatedColumns(grid, context); + VirtualGridColumn defaultSort = DefaultSortColumn(grid, columns); + + var layout = new VirtualGridLayout + { + GridKey = grid.Key, + Title = grid.Title, + DefaultSortField = defaultSort?.Field, + DefaultSortDir = NormalizeDir(grid.DefaultSortDir), + MaxPageSize = grid.MaxPageSize, + }; + layout.Columns.AddRange(columns.Select(c => new VirtualGridColumnInfo + { + Field = c.Field, + Title = c.Title, + Width = c.Width, + Type = c.Type, + Sortable = grid.CanSort(c), + })); + return layout; + } + + public VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context) + { + if (request == null) + throw new ArgumentException("Invalid request."); + VirtualGridDefinition grid = Open(request.GridKey, context); + List columns = GetValidatedColumns(grid, context); + int skip = Math.Max(0, request.Skip); + int take = Math.Min(Math.Max(1, request.Take), grid.MaxPageSize); + + var listSource = grid as IVirtualGridListSource; + if (listSource != null) + { + CachedList list = GetList(grid, listSource, columns, request, context); + List matches = Search(list, request.Search); + List ordered = Sort(grid, columns, list, matches, request); + return new VirtualGridPage + { + Total = ordered.Count, + TotalWithoutSearch = list.Rows.Count, + Data = ordered.Skip(skip).Take(take).Select(i => list.Rows[i]).ToList(), + }; + } + + var sqlGrid = (VirtualGridSqlDefinition)grid; + VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context); + var page = new VirtualGridPage(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + page.Total = VirtualGridDA.Count(tc, query, true); + page.TotalWithoutSearch = query.SearchPattern == null ? page.Total : VirtualGridDA.Count(tc, query, false); + if (page.Total > skip) + page.Data = ReadRows(VirtualGridDA.GetRows(tc, query, skip, take)); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + + // After the transaction: definitions may call other services that open their own. + FinishRows(sqlGrid, page.Data, context); + return page; + } + + public VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context) + { + if (request == null) + throw new ArgumentException("Invalid request."); + VirtualGridDefinition grid = Open(request.GridKey, context); + List columns = GetValidatedColumns(grid, context); + List exportColumns = ResolveExportColumns(columns, request.Fields); + + List> rows; + string filterDescription; + + var listSource = grid as IVirtualGridListSource; + if (listSource != null) + { + CachedList list = GetList(grid, listSource, columns, request, context); + List ordered = Sort(grid, columns, list, Search(list, request.Search), request); + CheckExportLimit(grid, ordered.Count); + rows = ordered.Select(i => list.Rows[i]).ToList(); + filterDescription = listSource.DescribeFilters(new VirtualGridFilters(request.Filters)); + } + else + { + var sqlGrid = (VirtualGridSqlDefinition)grid; + VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + tc.CommandTimeOut = ExportCommandTimeoutSeconds; + CheckExportLimit(grid, VirtualGridDA.Count(tc, query, true)); + rows = ReadRows(VirtualGridDA.GetRows(tc, query, 0, null)); + tc.End(); + } + catch (ArgumentException) + { + if (tc != null) + tc.HandleError(); + throw; + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + FinishRows(sqlGrid, rows, context); + filterDescription = query.Source.FilterDescription; + } + + return new VirtualGridFile + { + FileName = grid.ExcelFileName, + ContentType = ExcelContentType, + Content = BuildWorkbook(grid, exportColumns, rows, filterDescription, request.Search), + }; + } + + #endregion + + #region Shared helpers + + /// Finds the grid and checks the user may use it. Unknown key → ArgumentException. + private static VirtualGridDefinition Open(string gridKey, VirtualGridContext context) + { + if (context == null) + throw new UnauthorizedAccessException("Not signed in."); + VirtualGridDefinition grid = VirtualGridRegistry.Create(gridKey); + if (!(grid is IVirtualGridListSource) && !(grid is VirtualGridSqlDefinition)) + throw new InvalidOperationException("Virtual grid '" + grid.Key + + "' must derive from VirtualGridListDefinition or VirtualGridSqlDefinition."); + if (context.UserType == EnumUserType.Employee && !grid.AllowSelfServiceUsers) + throw new UnauthorizedAccessException("You do not have access to " + grid.Title + "."); + return grid; + } + + /// The definition's columns, checked so a bad definition fails loudly. + private static List GetValidatedColumns(VirtualGridDefinition grid, VirtualGridContext context) + { + List columns = grid.GetColumns(context) ?? new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (VirtualGridColumn c in columns) + { + if (!VirtualGridDefinition.IsIdentifier(c.Field) || c.Field.StartsWith("_") || !seen.Add(c.Field)) + throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has an invalid or duplicate column field: " + c.Field); + } + if (columns.Count == 0) + throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has no columns."); + return columns; + } + + private static VirtualGridColumn DefaultSortColumn(VirtualGridDefinition grid, List columns) + { + VirtualGridColumn byName = columns.FirstOrDefault(c => grid.CanSort(c) + && string.Equals(c.Field, grid.DefaultSortField, StringComparison.OrdinalIgnoreCase)); + return byName ?? columns.FirstOrDefault(c => grid.CanSort(c)); + } + + /// The column to sort by and its direction: a sortable column the user picked, else the grid's default. + private static VirtualGridColumn ResolveSort(VirtualGridDefinition grid, List columns, + VirtualGridRequest request, out bool descending) + { + VirtualGridColumn picked = columns.FirstOrDefault(c => grid.CanSort(c) + && string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase)); + descending = NormalizeDir(picked != null ? request.SortDir : grid.DefaultSortDir) == "desc"; + return picked ?? DefaultSortColumn(grid, columns); + } + + private static string NormalizeDir(string dir) => + string.Equals(dir, "desc", StringComparison.OrdinalIgnoreCase) ? "desc" : "asc"; + + private static string CleanSearch(string search) + { + string term = (search ?? string.Empty).Trim(); + return term.Length > MaxSearchLength ? term.Substring(0, MaxSearchLength) : term; + } + + private static void CheckExportLimit(VirtualGridDefinition grid, int total) + { + if (total > grid.ExportRowLimit) + throw new ArgumentException("There are " + total.ToString("N0", CultureInfo.InvariantCulture) + + " rows; Excel export is limited to " + grid.ExportRowLimit.ToString("N0", CultureInfo.InvariantCulture) + + ". Please narrow the filters or the search."); + } + + /// + /// A value as the screen shows it (dates "dd MMM yyyy", money "1,234.56"), so the search box finds + /// what the user sees. Mirrors the formatting in <app-virtual-grid>. + /// + private static string DisplayText(object value, EnumVirtualGridColumnType type) + { + if (value == null) + return string.Empty; + switch (type) + { + case EnumVirtualGridColumnType.Date: + if (value is DateTime d) return d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture); + break; + case EnumVirtualGridColumnType.DateTime: + if (value is DateTime dt) return dt.ToString("dd MMM yyyy HH:mm", CultureInfo.InvariantCulture); + break; + case EnumVirtualGridColumnType.Money: + if (value is IConvertible && !(value is string)) + return Convert.ToDecimal(value, CultureInfo.InvariantCulture).ToString("N2", CultureInfo.InvariantCulture); + break; + } + return Convert.ToString(value, CultureInfo.InvariantCulture); + } + + #endregion + + #region List grids (existing service + in-memory paging) + + /// A loaded list plus, per row, the text the search box looks in. + private sealed class CachedList + { + public List> Rows; + public List SearchText; + } + + /// + /// The grid's list for this user and these filters: from the cache, or — on Preview (Refresh) or + /// when the cache has expired — freshly from the grid's service. + /// + private static CachedList GetList(VirtualGridDefinition grid, IVirtualGridListSource source, + List columns, VirtualGridRequest request, VirtualGridContext context) + { + string key = CacheKey(grid, columns, request, context); + CachedList list; + if (!request.Refresh && ListCache.TryGetValue(key, out list)) + return list; + + List> rows = source.LoadRows(new VirtualGridFilters(request.Filters), context, columns); + + List searchable = columns.Where(c => grid.CanSearch(c)).ToList(); + var searchText = new List(rows.Count); + var sb = new StringBuilder(); + foreach (Dictionary row in rows) + { + sb.Clear(); + foreach (VirtualGridColumn c in searchable) + { + object value; + row.TryGetValue(c.Field, out value); + sb.Append(DisplayText(value, c.Type)).Append('\u0001'); // separator: no match across two columns + } + searchText.Add(sb.ToString()); + } + + list = new CachedList { Rows = rows, SearchText = searchText }; + ListCache.Set(key, list, new MemoryCacheEntryOptions + { + Size = Math.Max(1, rows.Count), + SlidingExpiration = ListCacheSliding, + AbsoluteExpirationRelativeToNow = ListCacheAbsolute, + }); + return list; + } + + /// One list per user, payroll type, grid and filter values (and column set, in case configuration changes). + private static string CacheKey(VirtualGridDefinition grid, List columns, + VirtualGridRequest request, VirtualGridContext context) + { + var sb = new StringBuilder(); + sb.Append(grid.Key.ToLowerInvariant()) + .Append('|').Append(context.UserID) + .Append('|').Append(context.PayrollTypeID) + .Append('|').Append((int)context.UserType) + .Append('|').Append(string.Join(",", columns.Select(c => c.Field))); + foreach (KeyValuePair f in (request.Filters ?? new Dictionary()) + .OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase)) + sb.Append('|').Append(f.Key.ToLowerInvariant()).Append('=').Append(f.Value); + return sb.ToString(); + } + + /// Indexes of the rows whose shown text contains the search (case-insensitive); all rows when there is none. + private static List Search(CachedList list, string search) + { + string term = CleanSearch(search); + var result = new List(term.Length == 0 ? list.Rows.Count : 64); + for (int i = 0; i < list.Rows.Count; i++) + { + if (term.Length == 0 || list.SearchText[i].IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0) + result.Add(i); + } + return result; + } + + /// Sorts row indexes by the chosen column (stable, so equal values keep the service's order). + private static List Sort(VirtualGridDefinition grid, List columns, CachedList list, + List indexes, VirtualGridRequest request) + { + bool descending; + VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending); + if (sortColumn == null) + return indexes; + + string field = sortColumn.Field; + Func keyOf = i => + { + object value; + list.Rows[i].TryGetValue(field, out value); + return value; + }; + return (descending + ? indexes.OrderByDescending(keyOf, ValueComparer.Instance) + : indexes.OrderBy(keyOf, ValueComparer.Instance)) + .ToList(); + } + + /// Compares cell values: empty first, numbers as numbers, dates as dates, text case-insensitively. + private sealed class ValueComparer : IComparer + { + public static readonly ValueComparer Instance = new ValueComparer(); + + public int Compare(object x, object y) + { + bool xEmpty = x == null || (x is string xs && xs.Length == 0); + bool yEmpty = y == null || (y is string ys && ys.Length == 0); + if (xEmpty || yEmpty) + return xEmpty == yEmpty ? 0 : (xEmpty ? -1 : 1); + + if (x is string a && y is string b) + return StringComparer.InvariantCultureIgnoreCase.Compare(a, b); + if (IsNumber(x) && IsNumber(y)) + return Convert.ToDecimal(x, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(y, CultureInfo.InvariantCulture)); + if (x.GetType() == y.GetType() && x is IComparable comparable) + return comparable.CompareTo(y); + return StringComparer.InvariantCultureIgnoreCase.Compare( + Convert.ToString(x, CultureInfo.InvariantCulture), Convert.ToString(y, CultureInfo.InvariantCulture)); + } + + private static bool IsNumber(object v) => + v is decimal || v is double || v is float || v is int || v is long || v is short || v is byte; + } + + #endregion + + #region SQL grids (VirtualGridDA) + + private static VirtualGridQuery BuildQuery(VirtualGridSqlDefinition grid, List columns, + VirtualGridRequest request, VirtualGridContext context) + { + VirtualGridSource source = grid.BuildSource(new VirtualGridFilters(request.Filters), context); + if (source == null || string.IsNullOrWhiteSpace(source.FromWhere)) + throw new InvalidOperationException("Virtual grid '" + grid.Key + "' returned no source."); + + var query = new VirtualGridQuery { Source = source, TieBreaker = grid.TieBreakerSql }; + + foreach (VirtualGridColumn c in columns.Where(c => !string.IsNullOrEmpty(c.Sql))) + query.Select.Add(c.Sql + " AS [" + c.Field + "]"); + foreach (string hidden in grid.HiddenSelect) + query.Select.Add(hidden); + + // Sort: only a sortable column of this grid; anything else falls back to the default. + bool descending; + VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending); + query.OrderBy = (sortColumn != null ? sortColumn.Sql : grid.TieBreakerSql) + (descending ? " DESC" : " ASC"); + + // Search: the user's text is a parameter; only LIKE wildcards are escaped. + string term = CleanSearch(request.Search); + if (term.Length > 0) + { + query.SearchPattern = "%" + term.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_").Replace("[", @"\[") + "%"; + foreach (VirtualGridColumn c in columns.Where(c => grid.CanSearch(c))) + query.SearchColumns.Add(new KeyValuePair(c.Sql, c.Type)); + var extras = new VirtualGridSearchExtras(); + grid.AddSearchExtras(term, extras, context); + query.SearchPredicates.AddRange(extras.Predicates); + } + + return query; + } + + private static List> ReadRows(IDataReader reader) + { + var rows = new List>(); + try + { + int count = reader.FieldCount; + var names = new string[count]; + for (int i = 0; i < count; i++) + names[i] = reader.GetName(i); + while (reader.Read()) + { + var row = new Dictionary(count, StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < count; i++) + row[names[i]] = reader.IsDBNull(i) ? null : reader.GetValue(i); + rows.Add(row); + } + } + finally + { + reader.Close(); + } + return rows; + } + + /// Lets the definition fill computed columns, then drops the hidden "_" helper values. + private static void FinishRows(VirtualGridSqlDefinition grid, List> rows, VirtualGridContext context) + { + if (rows.Count == 0) + return; + grid.OnRowsLoaded(rows, context); + foreach (Dictionary row in rows) + { + foreach (string key in row.Keys.Where(k => k.StartsWith("_")).ToList()) + row.Remove(key); + } + } + + #endregion + + #region Excel + + /// The requested fields that are columns of this grid, in the requested order (all columns when none are given). + private static List ResolveExportColumns(List columns, List fields) + { + if (fields == null || fields.Count == 0) + return columns; + var byField = columns.ToDictionary(c => c.Field, StringComparer.OrdinalIgnoreCase); + var result = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string field in fields) + { + VirtualGridColumn c; + if (field != null && byField.TryGetValue(field.Trim(), out c) && seen.Add(c.Field)) + result.Add(c); + } + if (result.Count == 0) + throw new ArgumentException("No columns to export."); + return result; + } + + private static byte[] BuildWorkbook(VirtualGridDefinition grid, List columns, + List> rows, string filterDescription, string searchText) + { + const int headerRow = 5; + using (var workbook = new XLWorkbook()) + { + string sheetName = grid.Title.Length > 31 ? grid.Title.Substring(0, 31) : grid.Title; + foreach (char ch in new[] { ':', '\\', '/', '?', '*', '[', ']' }) + sheetName = sheetName.Replace(ch, ' '); + IXLWorksheet ws = workbook.Worksheets.Add(sheetName); + + ws.Cell(1, 1).Value = grid.Title; + ws.Cell(1, 1).Style.Font.Bold = true; + ws.Cell(1, 1).Style.Font.FontSize = 14; + string line2 = filterDescription ?? string.Empty; + if (!string.IsNullOrWhiteSpace(searchText)) + line2 += (line2.Length > 0 ? " | " : "") + "Search: " + searchText.Trim(); + ws.Cell(2, 1).Value = line2; + ws.Cell(3, 1).Value = "Total: " + rows.Count.ToString("N0", CultureInfo.InvariantCulture); + + for (int c = 0; c < columns.Count; c++) + { + ws.Cell(headerRow, c + 1).Value = columns[c].Title; + switch (columns[c].Type) + { + case EnumVirtualGridColumnType.Date: + ws.Column(c + 1).Style.DateFormat.Format = "dd MMM yyyy"; + break; + case EnumVirtualGridColumnType.DateTime: + ws.Column(c + 1).Style.DateFormat.Format = "dd MMM yyyy HH:mm"; + break; + case EnumVirtualGridColumnType.Money: + ws.Column(c + 1).Style.NumberFormat.Format = "#,##0.00"; + break; + } + } + IXLRange header = ws.Range(headerRow, 1, headerRow, columns.Count); + header.Style.Font.Bold = true; + header.Style.Fill.BackgroundColor = XLColor.FromHtml("#E7ECF3"); + header.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; + header.Style.Border.InsideBorder = XLBorderStyleValues.Thin; + + int r = headerRow + 1; + foreach (Dictionary row in rows) + { + for (int c = 0; c < columns.Count; c++) + { + object value; + if (!row.TryGetValue(columns[c].Field, out value) || value == null) + continue; + SetCell(ws.Cell(r, c + 1), value, columns[c].Type); + } + r++; + } + + int lastRow = Math.Max(headerRow, r - 1); + ws.Range(headerRow, 1, lastRow, columns.Count).SetAutoFilter(); + ws.SheetView.FreezeRows(headerRow); + // Measure the header and the first rows only: measuring every row is slow on large files. + ws.Columns(1, columns.Count).AdjustToContents(headerRow, Math.Min(lastRow, headerRow + 300), 8, 60); + + using (var stream = new MemoryStream()) + { + workbook.SaveAs(stream); + return stream.ToArray(); + } + } + } + + private static void SetCell(IXLCell cell, object value, EnumVirtualGridColumnType type) + { + switch (type) + { + case EnumVirtualGridColumnType.Date: + case EnumVirtualGridColumnType.DateTime: + if (value is DateTime dt) { cell.Value = dt; return; } + break; + case EnumVirtualGridColumnType.Money: + case EnumVirtualGridColumnType.Number: + if (value is IConvertible && !(value is string) && !(value is DateTime)) + { + cell.Value = Convert.ToDecimal(value, CultureInfo.InvariantCulture); + return; + } + break; + } + cell.Value = Convert.ToString(value, CultureInfo.InvariantCulture); // text: no formulas, keeps leading zeros + } + + #endregion + + protected override T CreateObject(DataReader dr) + { + throw new NotSupportedException("VirtualGridService reads rows generically."); + } + } +} diff --git a/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts new file mode 100644 index 0000000..36e6f86 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts @@ -0,0 +1,63 @@ +/** + * Common virtual-scrolling grid (api/virtualGrid) — matches HRM.BO/VirtualGrid/VirtualGrid.cs. + * Screens use (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 after every window it loads. */ +export interface VirtualGridLoadedEvent { + total: number; + totalWithoutSearch: number; + /** True for the first window after load(filters). */ + firstLoad: boolean; +} diff --git a/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts b/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts new file mode 100644 index 0000000..844a1b9 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_services/common/virtual-grid.service.ts @@ -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 { + return this.apiService.httpGet('/virtualGrid/layout/' + encodeURIComponent(gridKey)); + } + + getPage(request: VirtualGridRequest): Observable { + return this.apiService.httpPost('/virtualGrid/page', request); + } + + exportExcel(request: VirtualGridExportRequest): Observable { + return this.apiService.httpDownloadFile('/virtualGrid/export-excel', request); + } +} diff --git a/HRM.UI/ClientApp/src/app/_services/employee/employee.service.ts b/HRM.UI/ClientApp/src/app/_services/employee/employee.service.ts index 6eb58a8..87e80c1 100644 --- a/HRM.UI/ClientApp/src/app/_services/employee/employee.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/employee/employee.service.ts @@ -326,12 +326,6 @@ export class EmployeeServices { return this.apiService.httpPost('/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('/Employee/getDiscontinueEmpDetailInfo', { fromDate: fromDate, toDate: toDate }); - } - getCurrentHeadCount(departmentId: number, designationId: number, gradeId: number) { return this.apiService.httpGet('/Employee/getCurrentHeadCount' + '/' + departmentId + '/' + designationId + '/' + gradeId); } diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html new file mode 100644 index 0000000..eed4e8e --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html @@ -0,0 +1,46 @@ +@if (layoutError) { +
{{ layoutError }}
+} +@if (started && layout) { + + + @if (showSearch) { + + + } + + + @if (showExport) { + + } + + @for (column of layout.columns; track column.field) { + + + } + + {{ noRecordsText }} + + +} diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.scss b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.scss new file mode 100644 index 0000000..cd5b7ee --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.scss @@ -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%; + } +} diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts new file mode 100644 index 0000000..29a6536 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts @@ -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(); + + 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(); + private readonly search$ = new Subject(); + private readonly subscriptions = new Subscription(); + private readonly money = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + + constructor(public apiService: ApiService, + private virtualGridService: VirtualGridService, + @Inject(LOCALE_ID) private locale: string, + @Optional() private notificationService: HRMNotificationService, + @Optional() private loadingPanel: loadingPanelService) { + } + + ngOnInit(): void { + this.subscriptions.add( + this.virtualGridService.getLayout(this.gridKey).subscribe( + (layout) => { + layout.columns = (layout.columns || []).map(c => ({ ...c, width: this.fitWidth(c) })); + this.layout = layout; + this.resetSort(); + if (this.pendingFilters) { + const filters = this.pendingFilters; + this.pendingFilters = null; + this.load(filters); + } + }, + (err) => { + this.layoutError = this.errorText(err, 'Failed to load the grid.'); + this.showError(this.layoutError); + } + ) + ); + + // A newer request (scroll, sort, search) cancels an older one still in flight, + // so a slow response can never overwrite newer rows. + 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)); + } + } +} diff --git a/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts new file mode 100644 index 0000000..9b59add --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.module.ts @@ -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 (common server-paged virtual-scrolling grid). */ +@NgModule({ + declarations: [VirtualGridComponent], + imports: [CommonModule, FormsModule, GridModule, ButtonsModule, TextBoxModule], + exports: [VirtualGridComponent] +}) +export class VirtualGridModule {} diff --git a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html index fe546dc..4a62400 100644 --- a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html @@ -17,28 +17,11 @@ -@if (showGrid) { -
- - - - - - - - - @for (column of columns; track column.field) { - - - } - - -
-} + +
+ + +
diff --git a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.scss b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.scss index 778804b..7779367 100644 --- a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.scss +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.scss @@ -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%; } diff --git a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts index 8472e09..9cea443 100644 --- a/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts @@ -1,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 (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; } } diff --git a/HRM.UI/ClientApp/src/app/reports/reports.module.ts b/HRM.UI/ClientApp/src/app/reports/reports.module.ts index 5101ad7..cfa6876 100644 --- a/HRM.UI/ClientApp/src/app/reports/reports.module.ts +++ b/HRM.UI/ClientApp/src/app/reports/reports.module.ts @@ -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, diff --git a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs index 3904c74..3838dab 100644 --- a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs +++ b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs @@ -48,6 +48,7 @@ namespace HRM.UI.Configuration.DI services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs b/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs new file mode 100644 index 0000000..a8a216c --- /dev/null +++ b/HRM.UI/Controllers/CommonInterface/VirtualGridController.cs @@ -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, + }; + } + } +}