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..10219f7 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -606,6 +606,10 @@ 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. + VirtualPageResult GetEmpDetailInfoPage(VirtualPageRequest request, List employeeIds, int payrollTypeID); + VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID); int GetCurrentHeadCount(int departmentId, int designationId, int gradeId); List GetbyDepartment(int deptId); List NotYetAssigned(int payrollTypeID); diff --git a/HRM.BO/VirtualPaging/VirtualPaging.cs b/HRM.BO/VirtualPaging/VirtualPaging.cs new file mode 100644 index 0000000..3d673b1 --- /dev/null +++ b/HRM.BO/VirtualPaging/VirtualPaging.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace HRM.BO +{ + /// + /// What <app-virtual-grid> sends to a page endpoint: the page's own filters plus the grid's columns, + /// scroll position, search text and sort. The same class is used by every page, so no page needs a + /// request class of its own. See HRM.DA/DA/VirtualPaging/README.md. + /// + public class VirtualPageRequest + { + /// The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString. + public Dictionary Filters { get; set; } = new Dictionary(); + + /// The grid's columns. Only these are selected, searched and sortable. + public List Columns { get; set; } = new List(); + + public int Skip { get; set; } + + /// Rows wanted. 0 = all rows (used by Export to Excel). + public int Take { get; set; } = 100; + + public string Search { get; set; } + public string SortField { get; set; } + + /// "asc" or "desc". + public string SortDir { get; set; } + + /// + /// True when the totals must be counted (Preview, new search). Scrolling and sorting do not change + /// the totals, so they send false and the COUNT is skipped. + /// + public bool CountTotal { get; set; } + + /// + /// True for Export to Excel: every row matching the search, in the grid's sort, comes back as an .xlsx + /// file (VirtualPageResult.ExcelFile) instead of JSON. + /// + public bool ExportExcel { get; set; } + + /// A filter as text, or null when it was not sent. + public string GetString(string name) + { + string value; + if (Filters != null && Filters.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value)) + return value.Trim(); + return null; + } + + /// A "yyyy-MM-dd" filter. Throws a message fit for the user when it is missing or invalid. + public DateTime GetDate(string name, string label = null) + { + DateTime value; + if (!DateTime.TryParseExact(GetString(name), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) + throw new ArgumentException("Please select a valid " + (label ?? name) + "."); + return value; + } + + /// + /// A comma-separated list of whole numbers (e.g. selected employee IDs "12,15,40"), without duplicates. + /// Throws a message fit for the user when it is missing, empty or holds anything but numbers. + /// + public List GetIntList(string name, string label = null) + { + var values = new List(); + var seen = new HashSet(); + foreach (string part in (GetString(name) ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + { + int value; + if (!int.TryParse(part.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) + throw new ArgumentException("Please select a valid " + (label ?? name) + "."); + if (seen.Add(value)) + values.Add(value); + } + if (values.Count == 0) + throw new ArgumentException("Please select " + (label ?? name) + "."); + return values; + } + + /// A whole-number filter. Throws a message fit for the user when it is missing or invalid. + public int GetInt(string name, string label = null) + { + int value; + if (!int.TryParse(GetString(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) + throw new ArgumentException("Please select a valid " + (label ?? name) + "."); + return value; + } + } + + /// One grid column: Field = a column alias of the page's query; Type = how it is shown. + public class VirtualPageColumn + { + public string Field { get; set; } + + /// "text" (default), "number", "money", "date" or "datetime". + public string Type { get; set; } + + /// Header text in the Excel file. + public string Title { get; set; } + + /// Column width in the grid (px); the Excel column gets a matching width. + public int Width { get; set; } + } + + /// One window of rows for the grid. + public class VirtualPageResult + { + /// Rows matching the search (all rows when there is no search). Null when not counted (CountTotal = false). + public int? Total { get; set; } + + /// All rows, ignoring the search. Null when not counted. + public int? TotalWithoutSearch { get; set; } + + /// The rows of this window, holding only the requested columns. + public List> Data { get; set; } = new List>(); + + /// The .xlsx file, set only for ExportExcel requests. The controller returns it as a file. + public byte[] ExcelFile { get; set; } + + public const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + } +} diff --git a/HRM.DA/DA/Employee/EmployeeDA.cs b/HRM.DA/DA/Employee/EmployeeDA.cs index 6adbd52..dab0422 100644 --- a/HRM.DA/DA/Employee/EmployeeDA.cs +++ b/HRM.DA/DA/Employee/EmployeeDA.cs @@ -1597,6 +1597,95 @@ namespace HRM.DA return oEmpDetails; } + #region Employee Details grids (virtual paging) + + // The columns of the Employee Details report, for the virtual-paging grids (Employee Detail + // Information, Discontinue Employee Details). Each alias is a grid field name. Values the old + // reports worked out in C# are worked out here, so the grid can search and sort by them: + // - department tiers: the employee's department sits at its own tier (TIRE) and its parents fill + // the tiers above it (no tiers for a department without a parent), as GetEmpDetailInfo did; + // - blood group name; bank / branch / account no falling back to the out-pay values. + // Used with EmployeeDetailFromSql, which defines the aliases v, e, d0..d4 and t. + private const string EmployeeDetailColumnsSql = @" + e.EMPLOYEEID AS employeeId, + v.EMPLOYEENO AS employeeNo, + v.NAME AS name, + v.Gender AS gender, + v.BIRTHDATE AS birthDate, + v.JOININGDATE AS joiningDate, + v.MOBILENO AS mobileNo, + v.EMAILADDRESS AS emailAddress, + v.DESIGNATION AS designation, + v.GRADE AS grade, + v.Category AS category, + v.Status AS status, + ISNULL(CASE t.Tier WHEN 1 THEN d0.DESCRIPTION WHEN 2 THEN d1.DESCRIPTION WHEN 3 THEN d2.DESCRIPTION + WHEN 4 THEN d3.DESCRIPTION WHEN 5 THEN d4.DESCRIPTION END, '') AS deptireOne, + ISNULL(CASE t.Tier WHEN 2 THEN d0.DESCRIPTION WHEN 3 THEN d1.DESCRIPTION WHEN 4 THEN d2.DESCRIPTION + WHEN 5 THEN d3.DESCRIPTION END, '') AS deptireTwo, + ISNULL(CASE t.Tier WHEN 3 THEN d0.DESCRIPTION WHEN 4 THEN d1.DESCRIPTION WHEN 5 THEN d2.DESCRIPTION END, '') AS deptireThree, + ISNULL(CASE t.Tier WHEN 4 THEN d0.DESCRIPTION WHEN 5 THEN d1.DESCRIPTION END, '') AS deptireFour, + ISNULL(CASE t.Tier WHEN 5 THEN d0.DESCRIPTION END, '') AS deptireFive, + v.Location AS location, + v.RELIGION AS religion, + v.MaritalStatus AS maritalStatus, + v.DATEOFCONFIRMATION AS dateOfConfirmation, + ISNULL(v.BASICSALARY, 0) AS basicSalary, + ISNULL(v.GrossSalary, 0) AS grossSalary, + v.PassPortNo AS passportNo, + CASE ISNULL(v.bloodgroup, 0) WHEN 0 THEN 'NA' WHEN 1 THEN 'A+' WHEN 2 THEN 'A-' WHEN 3 THEN 'B+' + WHEN 4 THEN 'B-' WHEN 5 THEN 'O+' WHEN 6 THEN 'O-' WHEN 7 THEN 'AB+' WHEN 8 THEN 'AB-' ELSE '' END AS bloodGroup, + v.LineManagerNo AS lineManagerNo, + v.LineManagerName AS lineManagerName, + v.LineManagerEmail AS lineManagerEmail, + v.EmpStatus AS empStatus, + ISNULL(NULLIF(v.Bank, ''), v.OUTPayBank) AS bank, + ISNULL(NULLIF(v.Branch, ''), v.OUTPayBranch) AS branch, + ISNULL(NULLIF(v.ACCOUNTNO, ''), v.OutPayAccountNo) AS accountNo, + v.NATIONALID AS nationalId, + v.TINNO AS tinNo"; + + private const string EmployeeDetailFromSql = @" +FROM VW_EMPLOYEEBASIC v +INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId +LEFT JOIN DEPARTMENT d0 ON d0.DEPARTMENTID = e.DEPARTMENTID +LEFT JOIN DEPARTMENT d1 ON d1.DEPARTMENTID = d0.PARENTID +LEFT JOIN DEPARTMENT d2 ON d2.DEPARTMENTID = d1.PARENTID +LEFT JOIN DEPARTMENT d3 ON d3.DEPARTMENTID = d2.PARENTID +LEFT JOIN DEPARTMENT d4 ON d4.DEPARTMENTID = d3.PARENTID +CROSS APPLY (SELECT CASE WHEN d0.PARENTID IS NULL THEN 0 WHEN d0.TIRE > 5 THEN 5 ELSE d0.TIRE END AS Tier) t"; + + /// + /// Employee Detail Information (/reports/report-viewer/empDetailInfo): the employees selected on the + /// screen, in one payroll type. The selected IDs are in the temp table #empIds, filled by + /// VirtualPagingDA.IdList, so any number of employees is one short SQL text and a good plan. + /// VirtualPagingDA adds the search, sort and paging, so there is no ORDER BY here. + /// + internal static string GetEmpDetailInfoQuery(int payrollTypeID) + { + return SQLParser.MakeSQL("SELECT" + EmployeeDetailColumnsSql + EmployeeDetailFromSql + @" +WHERE e.PAYROLLTYPEID = %n + AND e.EMPLOYEEID IN (SELECT ID FROM #empIds)", + payrollTypeID); + } + + /// + /// Discontinue Employee Details (Manage Employee › Report): employees discontinued (STATUS = + /// Discontinued) between fromDate and toDate in one payroll type: the Employee Details columns plus + /// the discontinue date. The end date is exclusive (toDate + 1 day) so a time part never drops the + /// last day. VirtualPagingDA adds the search, sort and paging, so there is no ORDER BY here. + /// + internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) + { + return SQLParser.MakeSQL("SELECT" + EmployeeDetailColumnsSql + @", + e.ENDOFCONTRACTDATE AS discontinueDate" + EmployeeDetailFromSql + @" +WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n + AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d", + (int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1)); + } + + #endregion + internal static DataSet GetEmpDetailsView(TransactionContext tc) { DataSet oEmpDetails = new DataSet(); diff --git a/HRM.DA/DA/VirtualPaging/README.md b/HRM.DA/DA/VirtualPaging/README.md new file mode 100644 index 0000000..be6cfe6 --- /dev/null +++ b/HRM.DA/DA/VirtualPaging/README.md @@ -0,0 +1,140 @@ +# Virtual paging: large lists with virtual scrolling + +SQL Server does the paging. Each request reads only the rows the grid needs (100 at a time) with +`OFFSET … FETCH`, and the search, sort and total count run in the same SQL. Nothing is kept in server +memory, so it works the same for 1,000 or 1,000,000 rows and always shows the latest data. + +| Piece | File | What it does | +|---|---|---| +| Request / result | `HRM.BO/VirtualPaging/VirtualPaging.cs` | `VirtualPageRequest` (filters, columns, skip/take, search, sort) and `VirtualPageResult`, shared by every page | +| Paging SQL | `HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs` | Wraps a page's query with search, sort, `OFFSET/FETCH` and the totals | +| Excel | `HRM.DA/DA/VirtualPaging/VirtualPagingExcel.cs` | Streams the rows from SQL Server straight into an `.xlsx` (Open XML SAX writer) | +| Grid | `ClientApp/src/app/custom-components/virtual-grid/` (`VirtualGridModule`) | ``: virtual scrolling, search box, total, Export to Excel | + +## A new page: 4 small steps (worked example: Discontinue Employee Details) + +**1. DA: the query.** An ordinary `SELECT` built with `MakeSQL`. Each column alias is a grid field name. +No `ORDER BY` and no `WITH` (the query is used as a derived table). + +```csharp +internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) +{ + return SQLParser.MakeSQL(@" +SELECT v.EMPLOYEENO AS employeeNo, + v.NAME AS name, + v.JOININGDATE AS joiningDate, + ISNULL(v.BASICSALARY, 0) AS basicSalary +FROM VW_EMPLOYEEBASIC v +INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId +WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n + AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d", + (int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1)); +} +``` + +**2. Service: one method** (canonical try/catch) + its line in the module's `I…Service` interface: + +```csharp +public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID) +{ + VirtualPageResult result = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId"); // fields that together are unique + tc.End(); + } + catch (Exception e) + { + if (tc != null) tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + } + return result; +} +``` + +**3. Controller: one endpoint** in the module's own controller. Read the page's filters from the request: + +```csharp +[HttpPost("getDiscontinueEmployeePage")] +public ActionResult GetDiscontinueEmployeePage(VirtualPageRequest request) +{ + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see this report."); + + DateTime fromDate = request.GetDate("fromDate", "From Date"); // also GetInt / GetString + DateTime toDate = request.GetDate("toDate", "To Date"); + VirtualPageResult result = _EmployeeService.GetDiscontinuedEmployeePage(request, fromDate, toDate, currentUser.PayrollTypeID ?? 0); + if (result.ExcelFile != null) // Export to Excel + return File(result.ExcelFile, VirtualPageResult.ExcelContentType, "DiscontinueEmployeeDetails.xlsx"); + return Ok(result); + } + catch (ArgumentException ex) { return BadRequest(ex.Message); } + catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } +} +``` + +**4. Screen**: import `VirtualGridModule`, then: + +```html + +``` +```ts +columns: VirtualGridColumn[] = [ + { field: 'employeeNo', title: 'Employee No', width: 110 }, + { field: 'joiningDate', title: 'Joining Date', type: 'date' }, + { field: 'basicSalary', title: 'Basic Salary', type: 'money' }, +]; + +preview() { + this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); // any filters; Dates go as yyyy-MM-dd +} +``` + +`field` = the column alias in the query. Column `type`: `text` (default), `number`, `money` (1,234.56), +`date` (dd MMM yyyy), `datetime`. `sortable: false` turns sorting off for a column. + +## How one request runs + +| User action | Request | SQL | +|---|---|---| +| Preview | `skip 0, take 100, countTotal true` | `COUNT` + first 100 rows, one round trip | +| Scroll | `skip 100, 200, …` | next 100 rows only (no `COUNT`) | +| Sort | `sortField`, `sortDir` | `ORDER BY` that column, then the unique field | +| Search (after 400 ms) | `search`, `countTotal true` | `WHERE` every column `LIKE @vpSearch`, new `COUNT` | +| Export to Excel | `exportExcel true` | every matching row, same search and sort, written row by row into an `.xlsx` on the server; the browser only downloads the file | + +## Rules + +- **Speed**: the page query's `WHERE` must use an index (see `DiscontinueEmployeeReport_DB_Changes.sql`). + Values computed in C# cannot be searched or sorted, so compute them in the query (see the department + tiers and blood group in `GetDiscontinuedEmployeeQuery`). +- **Safety**: the query is built by code with `MakeSQL` from typed values (dates, ints). The search text, + skip and take are SQL parameters; field names must be plain identifiers and are bracketed. +- **Access**: authorization in this app is menu-driven, so every page endpoint checks who may call it + (self-service logins are refused above). +- The key fields passed to `GetPage` must together be unique (`"employeeNo,employeeId"`: two employees can + share an Employee No), so pages never overlap or skip rows. The first one is the default sort. + +## Selected IDs (e.g. "employees picked on the screen") + +Send them as one filter (`employeeIds: "12,15,40"`), read them with `request.GetIntList("employeeIds")`, and +pass them as an ID list. `GetPage` loads them into a temp table with a primary key (one parameter, any +number of IDs, and a good plan); the query reads the temp table: + +```csharp +// DA +WHERE e.PAYROLLTYPEID = %n AND e.EMPLOYEEID IN (SELECT ID FROM #empIds) +// Service +result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId", VirtualPagingDA.IdList("#empIds", employeeIds)); +``` + +Worked example: Employee Detail Information (`EmployeeController.GetEmpDetailInfoPage`, +`EmployeeDA.GetEmpDetailInfoQuery`). Needs SQL Server 2016+ (`STRING_SPLIT`). diff --git a/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs b/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs new file mode 100644 index 0000000..636c0ab --- /dev/null +++ b/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Ease.Core.DataAccess; +using Ease.Core.DataAccess.SQL; +using HRM.BO; +using Microsoft.Data.SqlClient; + +namespace HRM.DA +{ + /// + /// Server side of <app-virtual-grid>: SQL Server does the paging. Each call reads only one window + /// of rows (OFFSET/FETCH), with the search and sort in the same SQL and the totals counted only when + /// they can change. A page's service calls it with its own query: + /// + /// string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + /// return VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId"); + /// + /// The query is an ordinary SELECT whose column aliases are the grid's field names, with no ORDER BY + /// and no WITH (it is used as a derived table). See README.md next to this file. + /// + /// Safety: the page query is built by code with MakeSQL; user input (search text, skip, take, ID lists) + /// reaches SQL only as parameters; field names are checked to be plain identifiers and bracketed. + /// + internal static class VirtualPagingDA + { + private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); + private static readonly Regex TempTableName = new Regex("^#[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); + private const int MaxRowsPerPage = 1000; + private const int MaxSearchLength = 200; + + /// The page's SELECT (column aliases = grid fields, no ORDER BY). + /// + /// Comma-separated fields that together are unique, e.g. "employeeNo,employeeId". The first is the + /// default sort; all of them end every ORDER BY, so pages never overlap or skip a row. + /// + /// ID lists the query reads as temp tables, e.g. IdList("#empIds", ids). Optional. + internal static VirtualPageResult GetPage(TransactionContext tc, string query, VirtualPageRequest request, string keyFields, + params VirtualPagingIdList[] idLists) + { + if (request == null) + throw new ArgumentException("Invalid request."); + List keys = (keyFields ?? "").Split(',').Select(k => k.Trim()).ToList(); + if (keys.Count == 0 || !keys.All(IsIdentifier)) + throw new ArgumentException("Invalid key fields."); + idLists = idLists ?? new VirtualPagingIdList[0]; + + List columns = GetColumns(request.Columns); + string search = (request.Search ?? "").Trim(); + if (search.Length > MaxSearchLength) + search = search.Substring(0, MaxSearchLength); + + string source = " FROM (" + query + ") AS vp"; + string searchCondition = search.Length > 0 ? SearchCondition(columns) : null; + bool export = request.ExportExcel; // every matching row, written straight into an .xlsx + bool paged = !export && request.Take > 0; + bool countTotal = !export && request.CountTotal; + + var sql = new StringBuilder("SET NOCOUNT ON;\n"); + var parameters = new List(); // SqlHelper expects a SqlParameter[] + + // 0. ID lists → temp tables with a primary key: SQL Server then knows how many rows there are and + // picks a good plan (a STRING_SPLIT inside the query is guessed at 50 rows and can be 10x slower). + for (int i = 0; i < idLists.Length; i++) + { + string table = idLists[i].TableName, name = "@vpIds" + i; + sql.Append("IF OBJECT_ID('tempdb..").Append(table).Append("') IS NOT NULL DROP TABLE ").Append(table).Append(";\n") + .Append("CREATE TABLE ").Append(table).Append(" (ID int NOT NULL PRIMARY KEY);\n") + .Append("INSERT INTO ").Append(table).Append(" (ID) SELECT DISTINCT CONVERT(int, value) FROM STRING_SPLIT(") + .Append(name).Append(", ',');\n"); + parameters.Add(SqlHelperExtension.CreateInParam(name, SqlDbType.VarChar, idLists[i].ToText(), -1)); // varchar(max) + } + + // 1. Totals, only on Preview / new search (scroll and sort do not change them). One scan for both. + if (countTotal) + { + sql.Append("SELECT COUNT(*) AS TotalWithoutSearch, ") + .Append(searchCondition == null ? "COUNT(*)" : "ISNULL(SUM(CASE WHEN " + searchCondition + " THEN 1 ELSE 0 END), 0)") + .Append(" AS Total").Append(source).Append(";\n"); + } + + // 2. The window of rows. + sql.Append("SELECT ") + .Append(columns.Count == 0 ? "*" : string.Join(", ", columns.Select(c => "[" + c.Field + "]"))) + .Append(source) + .Append(searchCondition == null ? "" : " WHERE " + searchCondition) + .Append(" ORDER BY ").Append(OrderBy(columns, request, keys)); + if (paged) + sql.Append(" OFFSET @vpSkip ROWS FETCH NEXT @vpTake ROWS ONLY"); + sql.Append(";\n"); + + foreach (VirtualPagingIdList list in idLists) + sql.Append("DROP TABLE ").Append(list.TableName).Append(";\n"); + + if (searchCondition != null) + parameters.Add(SqlHelperExtension.CreateInParam("@vpSearch", SqlDbType.NVarChar, "%" + EscapeLike(search) + "%", 400)); + if (paged) + { + parameters.Add(SqlHelperExtension.CreateInParam("@vpSkip", SqlDbType.Int, Math.Max(0, request.Skip))); + parameters.Add(SqlHelperExtension.CreateInParam("@vpTake", SqlDbType.Int, Math.Min(request.Take, MaxRowsPerPage))); + } + + var result = new VirtualPageResult(); + using (IDataReader reader = tc.ExecuteReader(CommandType.Text, sql.ToString(), parameters.ToArray())) + { + // Export to Excel: rows go from SQL Server into the file one by one, never all held in memory. + if (export) + { + result.ExcelFile = VirtualPagingExcel.Create(reader, columns); + return result; + } + + if (countTotal) + { + if (reader.Read()) + { + result.TotalWithoutSearch = Convert.ToInt32(reader["TotalWithoutSearch"]); + result.Total = Convert.ToInt32(reader["Total"]); + } + reader.NextResult(); + } + + while (reader.Read()) + { + var row = new Dictionary(reader.FieldCount); + for (int i = 0; i < reader.FieldCount; i++) + row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); + result.Data.Add(row); + } + } + return result; + } + + /// + /// A list of IDs (e.g. the employees selected on the screen), however many there are. GetPage loads it + /// into the temp table (one parameter, then a primary key) and the query + /// reads it with: e.EMPLOYEEID IN (SELECT ID FROM #empIds). Needs SQL Server 2016+ (STRING_SPLIT). + /// + internal static VirtualPagingIdList IdList(string tableName, IEnumerable ids) + { + if (tableName == null || !TempTableName.IsMatch(tableName)) + throw new ArgumentException("Invalid temp table name."); + return new VirtualPagingIdList(tableName, (ids ?? Enumerable.Empty()).ToList()); + } + + /// The requested columns; every field must be a plain identifier (it is put in the SQL in brackets). + private static List GetColumns(List requested) + { + var columns = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (VirtualPageColumn c in requested ?? new List()) + { + if (c == null || !IsIdentifier(c.Field)) + throw new ArgumentException("Invalid column: " + c?.Field); + if (seen.Add(c.Field)) + columns.Add(c); + } + return columns; + } + + /// + /// "column LIKE @vpSearch" for every column, OR-ed, on the text the grid shows: + /// dates "13 Feb 2025", money "1,234.56" (or "1234.56"). + /// + private static string SearchCondition(List columns) + { + const string like = " LIKE @vpSearch ESCAPE '\\'"; + var parts = new List(); + foreach (VirtualPageColumn c in columns) + { + string f = "[" + c.Field + "]"; + switch ((c.Type ?? "").ToLowerInvariant()) + { + case "date": + parts.Add("CONVERT(varchar(11), " + f + ", 106)" + like); + break; + case "datetime": + parts.Add("(CONVERT(varchar(11), " + f + ", 106) + ' ' + CONVERT(varchar(5), " + f + ", 108))" + like); + break; + case "money": + parts.Add("CONVERT(varchar(30), CAST(" + f + " AS money), 1)" + like); + parts.Add("CONVERT(varchar(30), CAST(" + f + " AS money), 0)" + like); + break; + default: + parts.Add("CONVERT(nvarchar(4000), " + f + ")" + like); + break; + } + } + return parts.Count == 0 ? "1 = 0" : "(" + string.Join(" OR ", parts) + ")"; + } + + /// + /// The grid's sort (only by one of its columns), then the key fields so the order is always the same. + /// No sort = the key fields (the first one is the default sort). + /// + private static string OrderBy(List columns, VirtualPageRequest request, List keys) + { + VirtualPageColumn sort = columns.FirstOrDefault(c => string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase)); + string dir = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase) ? " DESC" : " ASC"; + + var parts = new List(); + if (sort != null) + parts.Add("[" + sort.Field + "]" + dir); + foreach (string key in keys) + { + if (sort == null || !string.Equals(key, sort.Field, StringComparison.OrdinalIgnoreCase)) + parts.Add("[" + key + "] ASC"); + } + return string.Join(", ", parts); + } + + /// Makes %, _, [ and \ in the search text match themselves. + private static string EscapeLike(string text) => + text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_").Replace("[", "\\["); + + private static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); + } + + /// An ID list for a virtual-paging query (made by VirtualPagingDA.IdList). + internal sealed class VirtualPagingIdList + { + internal VirtualPagingIdList(string tableName, List ids) + { + TableName = tableName; + Ids = ids; + } + + internal string TableName { get; } + internal List Ids { get; } + + internal string ToText() => string.Join(",", Ids.Select(id => id.ToString(CultureInfo.InvariantCulture))); + } +} diff --git a/HRM.DA/DA/VirtualPaging/VirtualPagingExcel.cs b/HRM.DA/DA/VirtualPaging/VirtualPagingExcel.cs new file mode 100644 index 0000000..0191b18 --- /dev/null +++ b/HRM.DA/DA/VirtualPaging/VirtualPagingExcel.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.IO; +using System.Text; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using HRM.BO; + +namespace HRM.DA +{ + /// + /// Export to Excel for <app-virtual-grid>: writes the rows of a data reader straight into an .xlsx + /// with the Open XML SAX writer (OpenXmlWriter), one row at a time. Fast and light on memory even for + /// very long lists, unlike building the workbook in the browser or as a full object model. + /// + /// The file: a bold, frozen header row with filters, the grid's column titles and widths, dates as real + /// Excel dates ("dd mmm yyyy") and money as numbers ("#,##0.00"). Text is written as text, never as a formula. + /// + internal static class VirtualPagingExcel + { + private const int MaxRows = 1000000; // Excel's limit is 1,048,576 + + // Style indexes in the stylesheet below. + private const uint StyleHeader = 1, StyleDate = 2, StyleDateTime = 3, StyleMoney = 4; + + internal static byte[] Create(IDataReader reader, List columns) + { + // Columns to write: the grid's, or every field of the query when none were sent. + var fields = new List(); + if (columns.Count == 0) + { + for (int i = 0; i < reader.FieldCount; i++) + fields.Add(new ExcelColumn { Ordinal = i, Title = reader.GetName(i), Type = "text", Width = 15 }); + } + else + { + foreach (VirtualPageColumn c in columns) + { + fields.Add(new ExcelColumn + { + Ordinal = reader.GetOrdinal(c.Field), + Title = string.IsNullOrWhiteSpace(c.Title) ? c.Field : c.Title, + Type = (c.Type ?? "text").ToLowerInvariant(), + Width = Math.Max(10, Math.Min(60, (c.Width > 0 ? c.Width : 130) / 7.0)), + }); + } + } + + using (var stream = new MemoryStream()) + { + using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)) + { + WorkbookPart workbookPart = document.AddWorkbookPart(); + workbookPart.Workbook = new Workbook(); + + WorkbookStylesPart stylesPart = workbookPart.AddNewPart(); + stylesPart.Stylesheet = CreateStylesheet(); + stylesPart.Stylesheet.Save(); + + WorksheetPart sheetPart = workbookPart.AddNewPart(); + int lastRow = WriteSheet(sheetPart, reader, fields); + + string range = "$A$1:$" + ColumnName(fields.Count) + "$" + lastRow; + workbookPart.Workbook.AppendChild(new Sheets( + new Sheet { Id = workbookPart.GetIdOfPart(sheetPart), SheetId = 1U, Name = "Sheet1" })); + workbookPart.Workbook.AppendChild(new DefinedNames( + new DefinedName("'Sheet1'!" + range) { Name = "_xlnm._FilterDatabase", LocalSheetId = 0U, Hidden = true })); + workbookPart.Workbook.Save(); + } + return stream.ToArray(); + } + } + + /// Header + every row, streamed. Returns the last row number. + private static int WriteSheet(WorksheetPart sheetPart, IDataReader reader, List fields) + { + int rowIndex = 1; + using (OpenXmlWriter writer = OpenXmlWriter.Create(sheetPart)) + { + writer.WriteStartElement(new Worksheet()); + + // Header row stays visible while scrolling. + writer.WriteElement(new SheetViews(new SheetView( + new Pane { VerticalSplit = 1D, TopLeftCell = "A2", ActivePane = PaneValues.BottomLeft, State = PaneStateValues.Frozen }) + { WorkbookViewId = 0U })); + + writer.WriteStartElement(new Columns()); + for (int i = 0; i < fields.Count; i++) + writer.WriteElement(new Column { Min = (uint)(i + 1), Max = (uint)(i + 1), Width = fields[i].Width, CustomWidth = true }); + writer.WriteEndElement(); + + writer.WriteStartElement(new SheetData()); + + writer.WriteStartElement(new Row { RowIndex = 1U }); + foreach (ExcelColumn f in fields) + writer.WriteElement(TextCell(f.Title, StyleHeader)); + writer.WriteEndElement(); + + while (rowIndex <= MaxRows && reader.Read()) + { + rowIndex++; + writer.WriteStartElement(new Row { RowIndex = (uint)rowIndex }); + foreach (ExcelColumn f in fields) + writer.WriteElement(ValueCell(reader.IsDBNull(f.Ordinal) ? null : reader.GetValue(f.Ordinal), f.Type)); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); // SheetData + writer.WriteElement(new AutoFilter { Reference = "A1:" + ColumnName(fields.Count) + rowIndex }); + writer.WriteEndElement(); // Worksheet + } + return rowIndex; + } + + private static Cell ValueCell(object value, string type) + { + if (value == null) + return new Cell(); + + if (value is DateTime date && (type == "date" || type == "datetime")) + return new Cell { CellValue = new CellValue(date.ToOADate()), StyleIndex = type == "date" ? StyleDate : StyleDateTime }; + + if (IsNumber(value) && (type == "money" || type == "number")) + { + var cell = new Cell { CellValue = new CellValue(Convert.ToDecimal(value, CultureInfo.InvariantCulture)) }; + if (type == "money") + cell.StyleIndex = StyleMoney; + return cell; + } + + string text = value is DateTime d ? d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) + : Convert.ToString(value, CultureInfo.InvariantCulture); + return TextCell(text, 0); + } + + /// An inline text cell (never a formula). Characters XML cannot hold are dropped. + private static Cell TextCell(string text, uint style) + { + var cell = new Cell + { + DataType = CellValues.InlineString, + InlineString = new InlineString(new Text(CleanText(text)) { Space = SpaceProcessingModeValues.Preserve }), + }; + if (style != 0) + cell.StyleIndex = style; + return cell; + } + + private static Stylesheet CreateStylesheet() + { + return new Stylesheet( + new NumberingFormats( + new NumberingFormat { NumberFormatId = 164U, FormatCode = "dd mmm yyyy" }, + new NumberingFormat { NumberFormatId = 165U, FormatCode = "dd mmm yyyy hh:mm" }) { Count = 2U }, + new Fonts( + new Font(new FontSize { Val = 11D }, new FontName { Val = "Calibri" }), + new Font(new Bold(), new FontSize { Val = 11D }, new FontName { Val = "Calibri" })) { Count = 2U }, + new Fills( + new Fill(new PatternFill { PatternType = PatternValues.None }), + new Fill(new PatternFill { PatternType = PatternValues.Gray125 }), + new Fill(new PatternFill(new ForegroundColor { Rgb = "FFE8ECF2" }) { PatternType = PatternValues.Solid })) { Count = 3U }, + new Borders(new Border()) { Count = 1U }, + new CellFormats( + new CellFormat(), // 0 default + new CellFormat { FontId = 1U, FillId = 2U, ApplyFont = true, ApplyFill = true }, // 1 header + new CellFormat { NumberFormatId = 164U, ApplyNumberFormat = true }, // 2 date + new CellFormat { NumberFormatId = 165U, ApplyNumberFormat = true }, // 3 date + time + new CellFormat { NumberFormatId = 4U, ApplyNumberFormat = true }) { Count = 5U }); // 4 money #,##0.00 + } + + 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; + + private static string CleanText(string text) + { + if (string.IsNullOrEmpty(text)) + return string.Empty; + var sb = new StringBuilder(text.Length); + foreach (char ch in text) + { + if (ch == '\t' || ch == '\n' || ch == '\r' || ch >= 0x20 && ch != 0xFFFE && ch != 0xFFFF) + sb.Append(ch); + } + return sb.ToString(); + } + + /// 1 → A, 27 → AA. + private static string ColumnName(int number) + { + string name = string.Empty; + while (number > 0) + { + int m = (number - 1) % 26; + name = (char)('A' + m) + name; + number = (number - 1) / 26; + } + return name; + } + + private sealed class ExcelColumn + { + public int Ordinal; + public string Title; + public string Type; + public double Width; + } + } +} diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index f0d72a9..295b305 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -2730,6 +2730,73 @@ namespace HRM.DA return oEmpDetails; } + #region Employee Detail Information + + /// + /// Employee Detail Information (/reports/report-viewer/empDetailInfo): one window of rows for the grid, + /// for the employees selected on the screen. SQL Server pages, searches and sorts (VirtualPagingDA); + /// the query is EmployeeDA.GetEmpDetailInfoQuery and the selected IDs go in as one ID list (#empIds). + /// + public VirtualPageResult GetEmpDetailInfoPage(VirtualPageRequest request, List employeeIds, int payrollTypeID) + { + VirtualPageResult result = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + string query = EmployeeDA.GetEmpDetailInfoQuery(payrollTypeID); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId", + VirtualPagingDA.IdList("#empIds", employeeIds)); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + + return result; + } + + #endregion + + #region Discontinue Employee Details + + /// + /// Discontinue Employee Details: one window of rows for the grid. SQL Server pages, searches and + /// sorts (VirtualPagingDA); the query is EmployeeDA.GetDiscontinuedEmployeeQuery. + /// + public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, + DateTime toDate, int payrollTypeID) + { + VirtualPageResult result = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId"); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + + return result; + } + + #endregion + public DataSet GetEmpDetailsView() { DataSet oEmpDetails = new DataSet(); 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..3b5c1f2 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/common/virtual-grid.ts @@ -0,0 +1,44 @@ +/** + * (custom-components/virtual-grid) and its server side + * (HRM.BO/VirtualPaging/VirtualPaging.cs, HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs). + */ + +/** How a column's values are shown (and exported to Excel). */ +export type VirtualGridColumnType = 'text' | 'number' | 'money' | 'date' | 'datetime'; + +/** One grid column. field = the property name of the server object, camelCase. */ +export interface VirtualGridColumn { + field: string; + title: string; + width?: number; + type?: VirtualGridColumnType; // default 'text' + sortable?: boolean; // default true +} + +/** What the grid posts to the page endpoint (VirtualPageRequest on the server). */ +export interface VirtualPageRequest { + filters: { [name: string]: string }; + columns: { field: string; type: VirtualGridColumnType; title: string; width: number }[]; + skip: number; + take: number; // 0 = all rows (Export to Excel) + search?: string; + sortField?: string; + sortDir?: 'asc' | 'desc'; + countTotal: boolean; // true on Preview and on a new search; scroll/sort keep the totals + exportExcel?: boolean; // true: the server returns every matching row as an .xlsx file +} + +/** What the page endpoint returns (VirtualPageResult on the server). */ +export interface VirtualPageResult { + total: number | null; // null when not counted (countTotal = false) + totalWithoutSearch: number | null; + 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/app.topbar.component.html b/HRM.UI/ClientApp/src/app/app.topbar.component.html index 2833eb5..4e79543 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.html +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.html @@ -98,6 +98,12 @@ } + + @if (payrollTypeName) { +
  • + {{payrollTypeName}} +
  • + } @if (apiService.menuItems !== null) { diff --git a/HRM.UI/ClientApp/src/app/app.topbar.component.scss b/HRM.UI/ClientApp/src/app/app.topbar.component.scss index 6760b0f..ff2701c 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.scss +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.scss @@ -409,3 +409,27 @@ border-left: 1px solid $topbar-accent-purple-light; margin-left: 12px; } + +// Current payroll type label (admin logins), left of the Pending Jobs icon. +// Sits on the dark admin topbar, so it uses the same white as .topbar-icon. +.topbar-payroll-type-item { + display: flex; + align-items: center; + height: 36px; +} +.topbar-payroll-type { + display: inline-block; + max-width: 260px; + padding: 4px 12px; + border: 1px solid rgba($color-white, 0.35); + border-radius: 999px; + background: rgba($color-white, 0.12); + color: $color-white; + font-size: 13px; + font-weight: 600; + line-height: 18px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + cursor: default; +} diff --git a/HRM.UI/ClientApp/src/app/app.topbar.component.ts b/HRM.UI/ClientApp/src/app/app.topbar.component.ts index bec2e2c..3bac07b 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.ts +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.ts @@ -54,6 +54,13 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { private notifPanelWasOpen = false; private subscriptions: Subscription[] = []; + // Current payroll type's description, shown left of the Pending Jobs icon for admin + // (EnumUserType.User) logins only. Re-read whenever the stored token changes + // (login, user switch, payroll-type switch, logout). + payrollTypeName: string = ''; + private payrollTypeToken: string | null | undefined = undefined; + private payrollTypeSub: Subscription | null = null; + isScrolled: boolean = false; @HostListener('window:scroll', []) onWindowScroll() { @@ -159,6 +166,46 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { this.onNotificationPanelClosed(); } this.notifPanelWasOpen = isOpen; + + this.syncPayrollTypeName(); + } + + /** + * Shows the current payroll type's description for admin logins. Cheap on every + * change-detection pass: it only does work when the token in localStorage changed. + * The name comes from the server (GetPayrollTypeByLoginID), so it is the payroll + * type the API actually scopes data by. + */ + private syncPayrollTypeName(): void { + const token = localStorage.getItem('token'); + if (token === this.payrollTypeToken) { + return; + } + this.payrollTypeToken = token; + if (this.payrollTypeSub) { + this.payrollTypeSub.unsubscribe(); + this.payrollTypeSub = null; + } + + let user: any = null; + try { + user = token ? new JwtHelperService().decodeToken(token) : null; + } catch { + user = null; + } + if (!user || user.UserType != EnumUserType.User || !user.PayrollTypeID) { + this.payrollTypeName = ''; + return; + } + + this.payrollTypeSub = this.authService.GetPayrollTypeByLoginID().subscribe({ + next: (payrollType) => { + this.payrollTypeName = payrollType?.description ?? ''; + }, + error: () => { + this.payrollTypeName = ''; + }, + }); } /** @@ -176,6 +223,9 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { ngOnDestroy(): void { this.subscriptions.forEach(s => s.unsubscribe()); + if (this.payrollTypeSub) { + this.payrollTypeSub.unsubscribe(); + } } loadBookmark() { 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..ee2de8e --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.html @@ -0,0 +1,46 @@ +@if (started) { + + + @if (showSearch) { + + + } + + + @if (showExport) { + + } + + + @for (column of 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..24d80e1 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts @@ -0,0 +1,265 @@ +import { + ChangeDetectionStrategy, Component, EventEmitter, Input, 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 { + VirtualGridColumn, + VirtualGridLoadedEvent, + VirtualPageRequest, + VirtualPageResult +} from 'src/app/_models/common/virtual-grid'; + +/** + * Common virtual-scrolling grid. The page gives it an endpoint and the columns: + * + * + * this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); + * + * The grid asks for 100 rows at a time while the user scrolls; SQL Server reads just those rows and does + * the search, sort and total count (VirtualPagingDA). Export to Excel downloads every matching row. + */ +@Component({ + selector: 'app-virtual-grid', + templateUrl: './virtual-grid.component.html', + styleUrls: ['./virtual-grid.component.scss'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false, +}) +export class VirtualGridComponent implements OnInit, OnDestroy { + /** The page endpoint, e.g. '/Employee/getDiscontinueEmployeePage'. Required. */ + @Input() url: string; + /** The columns. field = a column alias of the page's SQL query (camelCase). Required. */ + @Input() columns: VirtualGridColumn[] = []; + @Input() height = 600; + @Input() pageSize = 100; + /** Minimum row height; rows with wrapped text grow. */ + @Input() rowHeight = 36; + @Input() searchPlaceholder = 'Search in all columns...'; + @Input() noRecordsText = 'No records found.'; + @Input() exportFileName = 'Export.xlsx'; + @Input() showSearch = true; + @Input() showExport = true; + + /** After every loaded window. */ + @Output() loaded = new EventEmitter(); + + started = false; + gridView: GridDataResult = { data: [], total: 0 }; + totalWithoutSearch = 0; + gridLoading = false; + skip = 0; + sort: SortDescriptor[] = []; + searchText = ''; + appliedSearch = ''; + exporting = false; + + private filters: { [name: string]: string } = {}; + private firstLoad = false; + private totalsPending = false; + private readonly load$ = new Subject(); + private readonly search$ = new Subject(); + private readonly subscriptions = new Subscription(); + + constructor(public apiService: ApiService, + @Optional() private notificationService: HRMNotificationService, + @Optional() private loadingPanel: loadingPanelService) { + } + + ngOnInit(): void { + // A newer request (scroll, sort, search) cancels an older one, so old rows never overwrite new ones. + this.subscriptions.add( + this.load$.pipe( + switchMap(request => { + this.gridLoading = true; + return this.apiService.httpPost(this.url, request).pipe( + catchError(err => { + this.showError(this.errorText(err, 'Failed to load data.')); + return of(null as VirtualPageResult); + }), + finalize(() => this.gridLoading = false) + ); + }) + ).subscribe(result => this.onPageLoaded(result)) + ); + + // Search only once the user stops typing. + this.subscriptions.add( + this.search$.pipe(debounceTime(400), distinctUntilChanged()).subscribe(text => { + this.appliedSearch = text; + this.skip = 0; + this.requestPage(true); // a new search changes the total + }) + ); + } + + ngOnDestroy(): void { + this.subscriptions.unsubscribe(); + } + + /** Preview: shows the grid for these filters (Date values are sent as 'yyyy-MM-dd'). */ + load(filters: { [name: string]: any }): void { + this.filters = {}; + Object.keys(filters || {}).forEach(name => { + const value = filters[name]; + if (value !== null && value !== undefined && value !== '') { + this.filters[name] = value instanceof Date ? formatDate(value, 'yyyy-MM-dd', 'en-US') : String(value); + } + }); + this.searchText = ''; + this.appliedSearch = ''; + this.search$.next(''); + this.skip = 0; + this.sort = []; + this.gridView = { data: [], total: 0 }; + this.totalWithoutSearch = 0; + this.started = true; + this.firstLoad = true; + this.requestPage(true); + } + + onPageChange(event: PageChangeEvent): void { + this.skip = event.skip; + this.requestPage(false); + } + + onSortChange(sort: SortDescriptor[]): void { + this.sort = sort; + this.skip = 0; + this.requestPage(false); + } + + onSearchChange(text: string): void { + this.search$.next((text || '').trim()); + } + + /** + * The server builds the .xlsx (every row matching the search, in the grid's sort) and the browser + * only downloads it, so a long list never has to be loaded or processed in the page. + */ + exportExcel(): void { + if (!this.started || this.gridView.total === 0 || this.exporting) { + return; + } + this.setExporting(true); + const request: VirtualPageRequest = { ...this.buildRequest(0, 0, false), exportExcel: true }; + this.apiService.httpDownloadFile(this.url, request).pipe( + finalize(() => this.setExporting(false)) + ).subscribe( + (file: Blob) => saveAs(file, this.exportFileName), + (err) => this.showDownloadError(err, 'Failed to export to Excel.') + ); + } + + /** Grid display format by column type. */ + displayFormat(column: VirtualGridColumn): string { + switch (column.type) { + case 'date': return '{0:dd MMM yyyy}'; + case 'datetime': return '{0:dd MMM yyyy HH:mm}'; + case 'money': return '{0:n2}'; + default: return undefined; + } + } + + isNumber(column: VirtualGridColumn): boolean { + return column.type === 'money' || column.type === 'number'; + } + + /** At least wide enough for the header title on one line (~8px per character + sort icon/padding). */ + columnWidth(column: VirtualGridColumn): number { + return Math.max(column.width || 130, (column.title || '').length * 8 + 48); + } + + /** countTotal: true on Preview and a new search (the total can change); scroll and sort keep the totals. */ + private requestPage(countTotal: boolean): void { + if (this.started && this.url) { + // Keep asking for the totals until a response brings them (a newer request cancels an older one). + this.totalsPending = this.totalsPending || countTotal; + this.load$.next(this.buildRequest(this.skip, this.pageSize, this.totalsPending)); + } + } + + private buildRequest(skip: number, take: number, countTotal: boolean): VirtualPageRequest { + const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null; + return { + filters: this.filters, + columns: this.columns.map(c => ({ field: c.field, type: c.type || 'text', title: c.title, width: this.columnWidth(c) })), + skip: skip, + take: take, + search: this.appliedSearch || undefined, + sortField: sort ? sort.field : undefined, + sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined, + countTotal: countTotal, + }; + } + + private onPageLoaded(result: VirtualPageResult): void { + if (!result) { + return; + } + // Totals come only when they were counted; otherwise keep the ones we have. + const counted = result.total !== null && result.total !== undefined; + if (counted) { + this.totalsPending = false; + } + const total = counted ? result.total : this.gridView.total; + if (result.totalWithoutSearch !== null && result.totalWithoutSearch !== undefined) { + this.totalWithoutSearch = result.totalWithoutSearch; + } + this.gridView = { data: (result.data || []).map(row => this.prepareRow(row)), total: total }; + this.loaded.emit({ total: total, totalWithoutSearch: this.totalWithoutSearch, firstLoad: this.firstLoad }); + this.firstLoad = false; + } + + /** Dates arrive as text; turn them into Date so the grid and Excel format them. */ + private prepareRow(row: { [field: string]: any }): { [field: string]: any } { + for (const column of this.columns) { + if ((column.type === 'date' || column.type === 'datetime') && row[column.field]) { + row[column.field] = new Date(row[column.field]); + } + } + return row; + } + + private setExporting(value: boolean): void { + this.exporting = value; + if (this.loadingPanel) { + this.loadingPanel.ShowLoadingPanel = value; + } + } + + 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; + } + + /** A failed download returns its error message as a Blob; read it before showing it. */ + private showDownloadError(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)); + } + } + + private showError(message: string): void { + if (this.notificationService) { + this.notificationService.showError(message); + } else { + console.error(message); + } + } +} 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..3479021 --- /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 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 new file mode 100644 index 0000000..6da365f --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.html @@ -0,0 +1,27 @@ + +
    +Search Criteria +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    + + +
    + + +
    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 new file mode 100644 index 0000000..7779367 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.scss @@ -0,0 +1,50 @@ +// Bordered box around the search criteria. +.filter-box { + border: 1px solid #d0d5dd; + border-radius: 6px; + padding: 4px 16px 16px; + margin: 0 0.5rem 14px; + + legend { + padding: 0 6px; + font-weight: 600; + width: auto; + } +} + +// Labels sit above their date pickers; the Preview button lines up with the pickers' bottom edge. +.filter-bar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px 24px; +} + +.filter-field { + display: flex; + flex-direction: column; + gap: 4px; + width: 280px; + + label { + font-weight: 600; + } + + kendo-datepicker { + width: 100%; + } +} + +.filter-action { + margin-left: auto; +} + +@media (max-width: 600px) { + .filter-field { + width: 100%; + } + + .filter-action { + margin-left: 0; + } +} 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 new file mode 100644 index 0000000..22da6e7 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reports/discontinue-employee-details/discontinue-employee-details.component.ts @@ -0,0 +1,108 @@ +import { Component, ChangeDetectionStrategy, OnInit, ViewChild } from '@angular/core'; +import { ApiService } from 'src/app/app.api.service'; +import { HRMNotificationService } from 'src/app/app.notification.service'; +import { VirtualGridComponent } from 'src/app/custom-components/virtual-grid/virtual-grid.component'; +import { VirtualGridColumn, VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid'; +import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service'; +import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration'; +import { EnumConfigurationType } from 'src/app/_models/enums'; + +/** + * Discontinue Employee Details: employees discontinued inside a date range, with the same columns as + * Employee Details (/reports/report-viewer/empDetailInfo) plus the Discontinue Date. + * + * Data: EmployeeController.GetDiscontinueEmployeePage → EmployeeService.GetDiscontinuedEmployeePage + * → EmployeeDA.GetDiscontinuedEmployeeQuery (SQL) + VirtualPagingDA (paging in SQL Server). + * The common does virtual scrolling, search, sort, total and Excel. + */ +@Component({ + selector: 'app-discontinue-employee-details', + templateUrl: './discontinue-employee-details.component.html', + styleUrls: ['./discontinue-employee-details.component.scss'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false, +}) +export class DiscontinueEmployeeDetailsComponent implements OnInit { + @ViewChild('grid') grid: VirtualGridComponent; + + fromDate: Date = new Date(new Date().getFullYear(), new Date().getMonth(), 1); + toDate: Date = new Date(); + dateFormat = 'dd-MMM-yyyy'; + + /** Grid columns. field = a column alias in EmployeeDA.GetDiscontinuedEmployeeQuery. */ + columns: VirtualGridColumn[] = []; + + constructor(public apiService: ApiService, + public notificationService: HRMNotificationService, + private systemConfigService: SystemConfigurationService) { + this.apiService.selectedMenuName = 'Discontinue Employee Details'; + } + + ngOnInit(): void { + // Department tier headings come from the Logic configuration, as in Employee Details. + this.systemConfigService.GetAllChildrenByParentNode(EnumConfigurationType.Logic, 'department').subscribe( + (configs: SystemConfigaration[]) => this.columns = this.buildColumns(configs || []), + () => this.columns = this.buildColumns([]) + ); + } + + preview(): void { + if (!this.fromDate || !this.toDate) { + this.notificationService.showWarning('Please select From Date and To Date.', 'Warning'); + return; + } + if (this.fromDate > this.toDate) { + this.notificationService.showWarning('From Date cannot be after To Date.', 'Warning'); + return; + } + debugger; + this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); + } + + onLoaded(event: VirtualGridLoadedEvent): void { + if (event.firstLoad && event.total === 0) { + this.notificationService.showWarning('No employee was discontinued in the selected date range.', 'Warning'); + } + } + + private buildColumns(configs: SystemConfigaration[]): VirtualGridColumn[] { + const tierFields = ['deptireOne', 'deptireTwo', 'deptireThree', 'deptireFour', 'deptireFive']; + const tierColumns: VirtualGridColumn[] = configs + .filter(c => (c.node || '').toLowerCase() === 'text') + .slice(0, tierFields.length) + .map((c, i) => ({ field: tierFields[i], title: c.value, width: 150 })); + + return [ + { field: 'employeeNo', title: 'Employee No', width: 110 }, + { field: 'name', title: 'Employee Name', width: 220 }, + { field: 'gender', title: 'Gender', width: 100 }, + { field: 'birthDate', title: 'Birth Date', width: 120, type: 'date' }, + { field: 'joiningDate', title: 'Joining Date', width: 120, type: 'date' }, + { field: 'discontinueDate', title: 'Discontinue Date', width: 140, type: 'date' }, + { field: 'mobileNo', title: 'Mobile No', width: 130 }, + { field: 'emailAddress', title: 'Email Address', width: 200 }, + { field: 'designation', title: 'Designation', width: 160 }, + { field: 'grade', title: 'Grade', width: 120 }, + { field: 'category', title: 'Category', width: 120 }, + { field: 'status', title: 'Status', width: 120 }, + ...tierColumns, + { field: 'location', title: 'Location', width: 130 }, + { field: 'religion', title: 'Religion', width: 110 }, + { field: 'maritalStatus', title: 'Marital Status', width: 120 }, + { field: 'dateOfConfirmation', title: 'Confirmation', width: 120, type: 'date' }, + { field: 'basicSalary', title: 'Basic Salary', width: 120, type: 'money' }, + { field: 'grossSalary', title: 'Gross Salary', width: 120, type: 'money' }, + { field: 'passportNo', title: 'Passport No', width: 120 }, + { field: 'bloodGroup', title: 'Blood Group', width: 110 }, + { field: 'lineManagerNo', title: 'LineManager No', width: 130 }, + { field: 'lineManagerName', title: 'LineManager Name', width: 180 }, + { field: 'lineManagerEmail', title: 'LineManager Email', width: 200 }, + { field: 'empStatus', title: 'Employee Status', width: 130 }, + { field: 'bank', title: 'Bank', width: 150 }, + { field: 'branch', title: 'Branch', width: 150 }, + { field: 'accountNo', title: 'Account No', width: 150 }, + { field: 'nationalId', title: 'National ID/NID', width: 150 }, + { field: 'tinNo', title: 'TIN', width: 120 }, + ]; + } +} diff --git a/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.html b/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.html index be01999..2c54ef9 100644 --- a/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.html +++ b/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.html @@ -357,6 +357,16 @@ --> + @if (reportType === 'empDetailInfo') { + +
    + + +
    + } @if (showAny) {