Employee Detail Information

This commit is contained in:
Mohaimen Hasan 2026-11-09 17:22:45 +06:00
parent 186a5b60a8
commit 1e8b51b706
9 changed files with 278 additions and 76 deletions

View File

@ -608,6 +608,7 @@ namespace HRM.BO
DataSet GetEmpDetailsView(); DataSet GetEmpDetailsView();
// Discontinue Employee Details report: employees discontinued (Status = Discontinued) whose // Discontinue Employee Details report: employees discontinued (Status = Discontinued) whose
// discontinue date (ENDOFCONTRACTDATE) falls inside the range, in one payroll type. // discontinue date (ENDOFCONTRACTDATE) falls inside the range, in one payroll type.
VirtualPageResult GetEmpDetailInfoPage(VirtualPageRequest request, List<int> employeeIds, int payrollTypeID);
VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID); VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID);
int GetCurrentHeadCount(int departmentId, int designationId, int gradeId); int GetCurrentHeadCount(int departmentId, int designationId, int gradeId);
List<Employee> GetbyDepartment(int deptId); List<Employee> GetbyDepartment(int deptId);

View File

@ -58,6 +58,27 @@ namespace HRM.BO
return value; return value;
} }
/// <summary>
/// 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.
/// </summary>
public List<int> GetIntList(string name, string label = null)
{
var values = new List<int>();
var seen = new HashSet<int>();
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;
}
/// <summary>A whole-number filter. Throws a message fit for the user when it is missing or invalid.</summary> /// <summary>A whole-number filter. Throws a message fit for the user when it is missing or invalid.</summary>
public int GetInt(string name, string label = null) public int GetInt(string name, string label = null)
{ {

View File

@ -1597,26 +1597,22 @@ namespace HRM.DA
return oEmpDetails; return oEmpDetails;
} }
/// <summary> #region Employee Details grids (virtual paging)
/// 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 columns of the Employee Details report, for the virtual-paging grids (Employee Detail
/// the Employee Details report. Column aliases are the grid's field names; VirtualPagingDA adds the // Information, Discontinue Employee Details). Each alias is a grid field name. Values the old
/// search, sort and paging, so there is no ORDER BY here. // 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
/// Department tiers: the employee's department sits at its own tier (TIRE) and its parents fill the // the tiers above it (no tiers for a department without a parent), as GetEmpDetailInfo did;
/// tiers above it, as EmployeeController.GetEmpDetailInfo works them out (no tiers for a department // - blood group name; bank / branch / account no falling back to the out-pay values.
/// without a parent). The end date is exclusive (toDate + 1 day) so a time part never drops the last day. // Used with EmployeeDetailFromSql, which defines the aliases v, e, d0..d4 and t.
/// </summary> private const string EmployeeDetailColumnsSql = @"
internal static string GetDiscontinuedEmployeeQuery(DateTime fromDate, DateTime toDate, int payrollTypeID) e.EMPLOYEEID AS employeeId,
{
return SQLParser.MakeSQL(@"
SELECT
v.EMPLOYEENO AS employeeNo, v.EMPLOYEENO AS employeeNo,
v.NAME AS name, v.NAME AS name,
v.Gender AS gender, v.Gender AS gender,
v.BIRTHDATE AS birthDate, v.BIRTHDATE AS birthDate,
v.JOININGDATE AS joiningDate, v.JOININGDATE AS joiningDate,
e.ENDOFCONTRACTDATE AS discontinueDate,
v.MOBILENO AS mobileNo, v.MOBILENO AS mobileNo,
v.EMAILADDRESS AS emailAddress, v.EMAILADDRESS AS emailAddress,
v.DESIGNATION AS designation, v.DESIGNATION AS designation,
@ -1647,7 +1643,9 @@ SELECT
ISNULL(NULLIF(v.Branch, ''), v.OUTPayBranch) AS branch, ISNULL(NULLIF(v.Branch, ''), v.OUTPayBranch) AS branch,
ISNULL(NULLIF(v.ACCOUNTNO, ''), v.OutPayAccountNo) AS accountNo, ISNULL(NULLIF(v.ACCOUNTNO, ''), v.OutPayAccountNo) AS accountNo,
v.NATIONALID AS nationalId, v.NATIONALID AS nationalId,
v.TINNO AS tinNo v.TINNO AS tinNo";
private const string EmployeeDetailFromSql = @"
FROM VW_EMPLOYEEBASIC v FROM VW_EMPLOYEEBASIC v
INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = v.EmployeeId
LEFT JOIN DEPARTMENT d0 ON d0.DEPARTMENTID = e.DEPARTMENTID 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 d2 ON d2.DEPARTMENTID = d1.PARENTID
LEFT JOIN DEPARTMENT d3 ON d3.DEPARTMENTID = d2.PARENTID LEFT JOIN DEPARTMENT d3 ON d3.DEPARTMENTID = d2.PARENTID
LEFT JOIN DEPARTMENT d4 ON d4.DEPARTMENTID = d3.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";
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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 WHERE e.STATUS = %n AND e.PAYROLLTYPEID = %n
AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d", AND e.ENDOFCONTRACTDATE >= %d AND e.ENDOFCONTRACTDATE < %d",
(int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1)); (int)EnumEmployeeStatus.Discontinued, payrollTypeID, fromDate.Date, toDate.Date.AddDays(1));
} }
#endregion
internal static DataSet GetEmpDetailsView(TransactionContext tc) internal static DataSet GetEmpDetailsView(TransactionContext tc)
{ {
DataSet oEmpDetails = new DataSet(); DataSet oEmpDetails = new DataSet();

View File

@ -43,7 +43,7 @@ public VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request,
{ {
tc = TransactionContext.Begin(); tc = TransactionContext.Begin();
string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); 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(); tc.End();
} }
catch (Exception e) catch (Exception e)
@ -120,4 +120,21 @@ preview() {
skip and take are SQL parameters; field names must be plain identifiers and are bracketed. 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 - **Access**: authorization in this app is menu-driven, so every page endpoint checks who may call it
(self-service logins are refused above). (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`).

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@ -17,28 +18,36 @@ namespace HRM.DA
/// they can change. A page's service calls it with its own query: /// they can change. A page's service calls it with its own query:
/// ///
/// string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); /// 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 /// 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. /// 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 /// Safety: the page query is built by code with MakeSQL; user input (search text, skip, take, ID lists)
/// SQL only as parameters; field names are checked to be plain identifiers and bracketed. /// reaches SQL only as parameters; field names are checked to be plain identifiers and bracketed.
/// </summary> /// </summary>
internal static class VirtualPagingDA internal static class VirtualPagingDA
{ {
private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); 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 MaxRowsPerPage = 1000;
private const int MaxSearchLength = 200; private const int MaxSearchLength = 200;
/// <param name="query">The page's SELECT (column aliases = grid fields, no ORDER BY).</param> /// <param name="query">The page's SELECT (column aliases = grid fields, no ORDER BY).</param>
/// <param name="keyField">A unique field (e.g. employeeNo): the default sort and the tie-breaker that keeps pages from overlapping.</param> /// <param name="keyFields">
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.
/// </param>
/// <param name="idLists">ID lists the query reads as temp tables, e.g. IdList("#empIds", ids). Optional.</param>
internal static VirtualPageResult GetPage(TransactionContext tc, string query, VirtualPageRequest request, string keyFields,
params VirtualPagingIdList[] idLists)
{ {
if (request == null) if (request == null)
throw new ArgumentException("Invalid request."); throw new ArgumentException("Invalid request.");
if (!IsIdentifier(keyField)) List<string> keys = (keyFields ?? "").Split(',').Select(k => k.Trim()).ToList();
throw new ArgumentException("Invalid key field."); if (keys.Count == 0 || !keys.All(IsIdentifier))
throw new ArgumentException("Invalid key fields.");
idLists = idLists ?? new VirtualPagingIdList[0];
List<VirtualPageColumn> columns = GetColumns(request.Columns); List<VirtualPageColumn> columns = GetColumns(request.Columns);
string search = (request.Search ?? "").Trim(); string search = (request.Search ?? "").Trim();
@ -51,7 +60,20 @@ namespace HRM.DA
bool paged = !export && request.Take > 0; bool paged = !export && request.Take > 0;
bool countTotal = !export && request.CountTotal; bool countTotal = !export && request.CountTotal;
var sql = new StringBuilder(); var sql = new StringBuilder("SET NOCOUNT ON;\n");
var parameters = new List<SqlParameter>(); // 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. // 1. Totals, only on Preview / new search (scroll and sort do not change them). One scan for both.
if (countTotal) if (countTotal)
@ -66,11 +88,14 @@ namespace HRM.DA
.Append(columns.Count == 0 ? "*" : string.Join(", ", columns.Select(c => "[" + c.Field + "]"))) .Append(columns.Count == 0 ? "*" : string.Join(", ", columns.Select(c => "[" + c.Field + "]")))
.Append(source) .Append(source)
.Append(searchCondition == null ? "" : " WHERE " + searchCondition) .Append(searchCondition == null ? "" : " WHERE " + searchCondition)
.Append(" ORDER BY ").Append(OrderBy(columns, request, keyField)); .Append(" ORDER BY ").Append(OrderBy(columns, request, keys));
if (paged) if (paged)
sql.Append(" OFFSET @vpSkip ROWS FETCH NEXT @vpTake ROWS ONLY"); 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<SqlParameter>(); // SqlHelper expects a SqlParameter[]
if (searchCondition != null) if (searchCondition != null)
parameters.Add(SqlHelperExtension.CreateInParam("@vpSearch", SqlDbType.NVarChar, "%" + EscapeLike(search) + "%", 400)); parameters.Add(SqlHelperExtension.CreateInParam("@vpSearch", SqlDbType.NVarChar, "%" + EscapeLike(search) + "%", 400));
if (paged) if (paged)
@ -110,6 +135,18 @@ namespace HRM.DA
return result; return result;
} }
/// <summary>
/// A list of IDs (e.g. the employees selected on the screen), however many there are. GetPage loads it
/// into the temp table <paramref name="tableName"/> (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).
/// </summary>
internal static VirtualPagingIdList IdList(string tableName, IEnumerable<int> ids)
{
if (tableName == null || !TempTableName.IsMatch(tableName))
throw new ArgumentException("Invalid temp table name.");
return new VirtualPagingIdList(tableName, (ids ?? Enumerable.Empty<int>()).ToList());
}
/// <summary>The requested columns; every field must be a plain identifier (it is put in the SQL in brackets).</summary> /// <summary>The requested columns; every field must be a plain identifier (it is put in the SQL in brackets).</summary>
private static List<VirtualPageColumn> GetColumns(List<VirtualPageColumn> requested) private static List<VirtualPageColumn> GetColumns(List<VirtualPageColumn> requested)
{ {
@ -156,17 +193,24 @@ namespace HRM.DA
return parts.Count == 0 ? "1 = 0" : "(" + string.Join(" OR ", parts) + ")"; return parts.Count == 0 ? "1 = 0" : "(" + string.Join(" OR ", parts) + ")";
} }
/// <summary>The grid's sort (only by one of its columns), then the key field so the order is always the same.</summary> /// <summary>
private static string OrderBy(List<VirtualPageColumn> 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).
/// </summary>
private static string OrderBy(List<VirtualPageColumn> columns, VirtualPageRequest request, List<string> keys)
{ {
VirtualPageColumn sort = columns.FirstOrDefault(c => string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase)); 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<string>();
if (sort != null)
parts.Add("[" + sort.Field + "]" + dir);
foreach (string key in keys)
{ {
bool keyDesc = sort != null && string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); if (sort == null || !string.Equals(key, sort.Field, StringComparison.OrdinalIgnoreCase))
return "[" + keyField + "]" + (keyDesc ? " DESC" : " ASC"); parts.Add("[" + key + "] ASC");
} }
bool desc = string.Equals(request.SortDir, "desc", StringComparison.OrdinalIgnoreCase); return string.Join(", ", parts);
return "[" + sort.Field + "]" + (desc ? " DESC" : " ASC") + ", [" + keyField + "] ASC";
} }
/// <summary>Makes %, _, [ and \ in the search text match themselves.</summary> /// <summary>Makes %, _, [ and \ in the search text match themselves.</summary>
@ -175,4 +219,19 @@ namespace HRM.DA
private static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); private static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name);
} }
/// <summary>An ID list for a virtual-paging query (made by VirtualPagingDA.IdList).</summary>
internal sealed class VirtualPagingIdList
{
internal VirtualPagingIdList(string tableName, List<int> ids)
{
TableName = tableName;
Ids = ids;
}
internal string TableName { get; }
internal List<int> Ids { get; }
internal string ToText() => string.Join(",", Ids.Select(id => id.ToString(CultureInfo.InvariantCulture)));
}
} }

View File

@ -2730,6 +2730,40 @@ namespace HRM.DA
return oEmpDetails; return oEmpDetails;
} }
#region Employee Detail Information
/// <summary>
/// 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).
/// </summary>
public VirtualPageResult GetEmpDetailInfoPage(VirtualPageRequest request, List<int> 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 #region Discontinue Employee Details
/// <summary> /// <summary>
@ -2745,7 +2779,7 @@ namespace HRM.DA
{ {
tc = TransactionContext.Begin(); tc = TransactionContext.Begin();
string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID); string query = EmployeeDA.GetDiscontinuedEmployeeQuery(fromDate, toDate, payrollTypeID);
result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo"); result = VirtualPagingDA.GetPage(tc, query, request, "employeeNo,employeeId");
tc.End(); tc.End();
} }
catch (Exception e) catch (Exception e)

View File

@ -357,6 +357,16 @@
<kendo-grid-excel fileName="EmployeesDetail.xlsx"></kendo-grid-excel> <kendo-grid-excel fileName="EmployeesDetail.xlsx"></kendo-grid-excel>
</kendo-grid> </kendo-grid>
</div>--> </div>-->
@if (reportType === 'empDetailInfo') {
<!-- Employee Detail Information only: virtual-scrolling grid, 100 rows at a time from the server
(EmployeeController.getEmpDetailInfoPage). Every other report keeps the grid below. -->
<div class="col-12">
<app-virtual-grid #empDetailGrid url="/Employee/getEmpDetailInfoPage" [columns]="empDetailColumns" [height]="500"
exportFileName="EmployeesDetail.xlsx" noRecordsText="No data found."
(loaded)="onEmpDetailLoaded($event)">
</app-virtual-grid>
</div>
}
@if (showAny) { @if (showAny) {
<div class="col-12"> <div class="col-12">
<!-- <kendo-grid #grid="kendoGrid" [data]="gridView" [pageSize]="state.take" [resizable]="true" [pageable]="true" <!-- <kendo-grid #grid="kendoGrid" [data]="gridView" [pageSize]="state.take" [resizable]="true" [pageable]="true"

View File

@ -1,4 +1,4 @@
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { Component, OnInit, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { DynamicPicker, EnumDynamicpickerType } from '../../picker/dynamic-picker/Dynamic-Picker'; import { DynamicPicker, EnumDynamicpickerType } from '../../picker/dynamic-picker/Dynamic-Picker';
import { import {
EnumBloodGroup, EnumBloodGroup,
@ -48,6 +48,8 @@ import { DatePipe } from '@angular/common';
import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service'; import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service';
import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration'; import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration';
import { GlobalfunctionExtension } from 'src/app/_models/globalFunctions'; import { GlobalfunctionExtension } from 'src/app/_models/globalFunctions';
import { VirtualGridComponent } from 'src/app/custom-components/virtual-grid/virtual-grid.component';
import { VirtualGridColumn, VirtualGridLoadedEvent } from 'src/app/_models/common/virtual-grid';
import { SVGIcon, saveIcon, gearIcon, fileExcelIcon, filePdfIcon, searchIcon, cancelIcon, plusIcon, pencilIcon } from '@progress/kendo-svg-icons'; import { SVGIcon, saveIcon, gearIcon, fileExcelIcon, filePdfIcon, searchIcon, cancelIcon, plusIcon, pencilIcon } from '@progress/kendo-svg-icons';
const EXCEL_TYPE = const EXCEL_TYPE =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"; "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
@ -125,6 +127,9 @@ export class ReportViewerComponent implements OnInit {
tempReportList: Columns[]; tempReportList: Columns[];
ReportColumnDefinitions: ColumnDefinition[] = []; ReportColumnDefinitions: ColumnDefinition[] = [];
dynamicColumnNames: ColumnDefinition[] = []; dynamicColumnNames: ColumnDefinition[] = [];
/** Employee Detail Information (empDetailInfo) only: the virtual-scrolling grid and its columns. */
@ViewChild('empDetailGrid') empDetailGrid: VirtualGridComponent;
empDetailColumns: VirtualGridColumn[] = [];
reportType: any; reportType: any;
isPdfExport: boolean = false; isPdfExport: boolean = false;
fromDate: Date = new Date(); fromDate: Date = new Date();
@ -332,6 +337,7 @@ export class ReportViewerComponent implements OnInit {
]; ];
this.dynamicColumnNames.push(...newColumns); this.dynamicColumnNames.push(...newColumns);
this.reportViewerColumn = new ReportViewerListColumn(this.reportType, this.dynamicColumnNames, employeeBasicInfo, 'EmployeesDetail'); this.reportViewerColumn = new ReportViewerListColumn(this.reportType, this.dynamicColumnNames, employeeBasicInfo, 'EmployeesDetail');
this.empDetailColumns = this.toEmpDetailColumns(this.dynamicColumnNames);
//console.log(this.dynamicColumnNames); //console.log(this.dynamicColumnNames);
}); });
@ -1422,7 +1428,9 @@ export class ReportViewerComponent implements OnInit {
if (this.empIds !== '') { if (this.empIds !== '') {
this.empIds += ','; this.empIds += ',';
} }
selectedemps.push(this.searchEmployees.find(e => e.employeeID === x)); if (this.reportType !== 'empDetailInfo') { // empDetailInfo sends only the IDs (see below)
selectedemps.push(this.searchEmployees.find(e => e.employeeID === x));
}
this.empIds += x; this.empIds += x;
}); });
@ -1454,44 +1462,21 @@ export class ReportViewerComponent implements OnInit {
); );
} }
else if (this.reportType === 'empDetailInfo') { else if (this.reportType === 'empDetailInfo') {
if (this.selectedEmp !== undefined) { // Virtual scrolling: the grid asks the server for 100 rows at a time
selectedemps.push(this.selectedEmp); // (EmployeeController.getEmpDetailInfoPage), so thousands of employees load at once.
// Same employees as before: the tagged ones plus the one picked in the employee picker.
if (!this.empDetailGrid) {
return;
} }
this.loadingPanel.ShowLoadingPanel = true; const employeeIds = new Set<number>(this.taggedSelection);
if (this.selectedEmp !== undefined) {
this.employeeService.getEmpDetailInfo(selectedemps).subscribe( employeeIds.add(this.selectedEmp.employeeID);
(resp) => { }
// this.employeeDetailInfos = resp; if (this.empDetailColumns.length === 0) {
this.loadingPanel.ShowLoadingPanel = false; this.empDetailColumns = this.toEmpDetailColumns(this.dynamicColumnNames);
this.data = resp; }
//debugger; this.empDetailGrid.columns = this.empDetailColumns;
}, this.empDetailGrid.load({ employeeIds: Array.from(employeeIds).join(',') });
(err) => {
console.log(err);
this.notificationService.showError(err.error);
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
// console.log(this.data);
for (let i = 0; i < this.data.length; i++) {
this.data[i]['birthDate'] = this.data[i]['birthDate'] != null ?
this.datePipe.transform(this.data[i]['birthDate'], 'dd MMM yyyy').toString() : "";
this.data[i]['joiningDate'] = this.data[i]['joiningDate'] != null ?
this.datePipe.transform(this.data[i]['joiningDate'], 'dd MMM yyyy').toString() : "";
this.data[i]['dateOfConfirmation'] = this.data[i]['dateOfConfirmation'] != null ?
this.datePipe.transform(this.data[i]['dateOfConfirmation'], 'dd MMM yyyy').toString() : "";
// Format basicSalary and grossSalary with commas and 2 decimals
this.data[i]['basicSalary'] = this.data[i]['basicSalary'] != null ?
new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(this.data[i]['basicSalary']) : "0.00";
this.data[i]['grossSalary'] = this.data[i]['grossSalary'] != null ?
new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(this.data[i]['grossSalary']) : "0.00";
}
// debugger;
this.showAny = true;
this.loadGrid();
}
);
} }
else if (this.reportType === 'dailyPresentReport' && reportType != 'new-PDF') { else if (this.reportType === 'dailyPresentReport' && reportType != 'new-PDF') {
if (this.fromDate === undefined) { if (this.fromDate === undefined) {
@ -2186,6 +2171,25 @@ export class ReportViewerComponent implements OnInit {
loadAttenGrid() { loadAttenGrid() {
this.gridViewAtten = process(this.data, { group: this.groups }); this.gridViewAtten = process(this.data, { group: this.groups });
} }
/** Employee Detail Information: the report columns as virtual-grid columns (dates and money formatted). */
toEmpDetailColumns(columns: ColumnDefinition[]): VirtualGridColumn[] {
const dateFields = ['birthDate', 'joiningDate', 'dateOfConfirmation'];
const moneyFields = ['basicSalary', 'grossSalary'];
return (columns || []).map(c => ({
field: c.columnName,
title: c.columnHeader,
width: Math.max(Number(c.width) || 0, 120),
type: dateFields.includes(c.columnName) ? 'date' : moneyFields.includes(c.columnName) ? 'money' : 'text',
} as VirtualGridColumn));
}
/** Employee Detail Information: same message as before when the selected employees give no rows. */
onEmpDetailLoaded(event: VirtualGridLoadedEvent): void {
if (event.firstLoad && event.total === 0) {
this.notificationService.showError('No data found');
}
}
loadGrid() { loadGrid() {
//debugger //debugger
// this.loadGridView(); // this.loadGridView();

View File

@ -3442,5 +3442,36 @@ namespace HRM.UI.Controllers
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
} }
} }
/// <summary>
/// Employee Detail Information (/reports/report-viewer/empDetailInfo): one window of rows for
/// &lt;app-virtual-grid&gt;. Filter: employeeIds (the selected employees, "12,15,40").
/// SQL Server does the paging, search and sort (VirtualPagingDA). The old getEmpDetailInfo is unchanged.
/// </summary>
[HttpPost("getEmpDetailInfoPage")]
public ActionResult GetEmpDetailInfoPage(VirtualPageRequest request)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee) // self-service logins never see this report
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see this report.");
List<int> employeeIds = request.GetIntList("employeeIds", "employee");
VirtualPageResult result = _EmployeeService.GetEmpDetailInfoPage(request, employeeIds, currentUser.PayrollTypeID ?? 0);
if (result.ExcelFile != null) // Export to Excel
return File(result.ExcelFile, VirtualPageResult.ExcelContentType, "EmployeesDetail.xlsx");
return Ok(result);
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
} }
} }