diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index 14a1a81..10219f7 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -608,6 +608,7 @@ namespace HRM.BO DataSet GetEmpDetailsView(); // Discontinue Employee Details report: employees discontinued (Status = Discontinued) whose // discontinue date (ENDOFCONTRACTDATE) falls inside the range, in one payroll type. + 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); diff --git a/HRM.BO/VirtualPaging/VirtualPaging.cs b/HRM.BO/VirtualPaging/VirtualPaging.cs index 4aef283..3d673b1 100644 --- a/HRM.BO/VirtualPaging/VirtualPaging.cs +++ b/HRM.BO/VirtualPaging/VirtualPaging.cs @@ -58,6 +58,27 @@ namespace HRM.BO 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) { diff --git a/HRM.DA/DA/Employee/EmployeeDA.cs b/HRM.DA/DA/Employee/EmployeeDA.cs index 5efc8aa..dab0422 100644 --- a/HRM.DA/DA/Employee/EmployeeDA.cs +++ b/HRM.DA/DA/Employee/EmployeeDA.cs @@ -1597,26 +1597,22 @@ namespace HRM.DA return oEmpDetails; } - /// - /// Discontinue Employee Details (Manage Employee › Report): one row per employee discontinued - /// (STATUS = Discontinued) between fromDate and toDate in one payroll type, with the same columns as - /// the Employee Details report. Column aliases are the grid's field names; VirtualPagingDA adds the - /// search, sort and paging, so there is no ORDER BY here. - /// - /// Department tiers: the employee's department sits at its own tier (TIRE) and its parents fill the - /// tiers above it, as EmployeeController.GetEmpDetailInfo works them out (no tiers for a department - /// without a parent). The end date is exclusive (toDate + 1 day) so a time part never drops the last day. - /// - internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) - { - return SQLParser.MakeSQL(@" -SELECT + #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, - e.ENDOFCONTRACTDATE AS discontinueDate, v.MOBILENO AS mobileNo, v.EMAILADDRESS AS emailAddress, v.DESIGNATION AS designation, @@ -1647,7 +1643,9 @@ SELECT ISNULL(NULLIF(v.Branch, ''), v.OUTPayBranch) AS branch, ISNULL(NULLIF(v.ACCOUNTNO, ''), v.OutPayAccountNo) AS accountNo, v.NATIONALID AS nationalId, - v.TINNO AS tinNo + 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 @@ -1655,12 +1653,39 @@ 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 +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 index bb54fd8..be6cfe6 100644 --- a/HRM.DA/DA/VirtualPaging/README.md +++ b/HRM.DA/DA/VirtualPaging/README.md @@ -43,7 +43,7 @@ public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, { tc = TransactionContext.Begin(); string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); - result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); // "employeeNo" = a unique field + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId"); // fields that together are unique tc.End(); } catch (Exception e) @@ -120,4 +120,21 @@ preview() { skip and take are SQL parameters; field names must be plain identifiers and are bracketed. - **Access**: authorization in this app is menu-driven, so every page endpoint checks who may call it (self-service logins are refused above). -- The key field passed to `GetPage` must be unique, so pages never overlap or skip rows. +- 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 index decd485..636c0ab 100644 --- a/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs +++ b/HRM.DA/DA/VirtualPaging/VirtualPagingDA.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Data; +using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -17,28 +18,36 @@ namespace HRM.DA /// 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"); + /// 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) reaches - /// SQL only as parameters; field names are checked to be plain identifiers and bracketed. + /// 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). - /// A unique field (e.g. employeeNo): the default sort and the tie-breaker that keeps pages from overlapping. - internal static VirtualPageResult GetPage(TransactionContext tc, string query, VirtualPageRequest request, string keyField) + /// + /// 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."); - if (!IsIdentifier(keyField)) - throw new ArgumentException("Invalid key field."); + 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(); @@ -51,7 +60,20 @@ namespace HRM.DA bool paged = !export && request.Take > 0; bool countTotal = !export && request.CountTotal; - var sql = new StringBuilder(); + 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) @@ -66,11 +88,14 @@ namespace HRM.DA .Append(columns.Count == 0 ? "*" : string.Join(", ", columns.Select(c => "[" + c.Field + "]"))) .Append(source) .Append(searchCondition == null ? "" : " WHERE " + searchCondition) - .Append(" ORDER BY ").Append(OrderBy(columns, request, keyField)); + .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"); - var parameters = new List(); // SqlHelper expects a SqlParameter[] if (searchCondition != null) parameters.Add(SqlHelperExtension.CreateInParam("@vpSearch", SqlDbType.NVarChar, "%" + EscapeLike(search) + "%", 400)); if (paged) @@ -110,6 +135,18 @@ namespace HRM.DA 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) { @@ -156,17 +193,24 @@ namespace HRM.DA return parts.Count == 0 ? "1 = 0" : "(" + string.Join(" OR ", parts) + ")"; } - /// The grid's sort (only by one of its columns), then the key field so the order is always the same. - private static string OrderBy(List columns, VirtualPageRequest request, string keyField) + /// + /// 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)); - if (sort == null || string.Equals(sort.Field, keyField, 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) { - bool keyDesc = sort != null && string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); - return "[" + keyField + "]" + (keyDesc ? " DESC" : " ASC"); + if (sort == null || !string.Equals(key, sort.Field, StringComparison.OrdinalIgnoreCase)) + parts.Add("[" + key + "] ASC"); } - bool desc = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); - return "[" + sort.Field + "]" + (desc ? " DESC" : " ASC") + ", [" + keyField + "] ASC"; + return string.Join(", ", parts); } /// Makes %, _, [ and \ in the search text match themselves. @@ -175,4 +219,19 @@ namespace HRM.DA 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/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index a05ad4a..295b305 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -2730,6 +2730,40 @@ 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 /// @@ -2745,7 +2779,7 @@ namespace HRM.DA { tc = TransactionContext.Begin(); string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); - result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); + result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId"); tc.End(); } catch (Exception e) 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) {