Merge pull request 'dev_mohaimen' (#1) from dev_mohaimen into main

Reviewed-on: http://103.197.204.162:3025/CelHRTeam/HRM-10/pulls/1
This commit is contained in:
Abdullah_Al_Mohaimen_Hasan 2026-11-09 17:36:29 +06:00
commit 88ce01d574
24 changed files with 1706 additions and 41 deletions

View File

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

View File

@ -606,6 +606,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<int> employeeIds, int payrollTypeID);
VirtualPageResult GetDiscontinuedEmployeePage(VirtualPageRequest request, DateTime fromDate, DateTime toDate, int payrollTypeID);
int GetCurrentHeadCount(int departmentId, int designationId, int gradeId);
List<Employee> GetbyDepartment(int deptId);
List<Employee> NotYetAssigned(int payrollTypeID);

View File

@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace HRM.BO
{
/// <summary>
/// What &lt;app-virtual-grid&gt; 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.
/// </summary>
public class VirtualPageRequest
{
/// <summary>The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString.</summary>
public Dictionary<string, string> Filters { get; set; } = new Dictionary<string, string>();
/// <summary>The grid's columns. Only these are selected, searched and sortable.</summary>
public List<VirtualPageColumn> Columns { get; set; } = new List<VirtualPageColumn>();
public int Skip { get; set; }
/// <summary>Rows wanted. 0 = all rows (used by Export to Excel).</summary>
public int Take { get; set; } = 100;
public string Search { get; set; }
public string SortField { get; set; }
/// <summary>"asc" or "desc".</summary>
public string SortDir { get; set; }
/// <summary>
/// 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.
/// </summary>
public bool CountTotal { get; set; }
/// <summary>
/// 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.
/// </summary>
public bool ExportExcel { get; set; }
/// <summary>A filter as text, or null when it was not sent.</summary>
public string GetString(string name)
{
string value;
if (Filters != null && Filters.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value))
return value.Trim();
return null;
}
/// <summary>A "yyyy-MM-dd" filter. Throws a message fit for the user when it is missing or invalid.</summary>
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;
}
/// <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>
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;
}
}
/// <summary>One grid column: Field = a column alias of the page's query; Type = how it is shown.</summary>
public class VirtualPageColumn
{
public string Field { get; set; }
/// <summary>"text" (default), "number", "money", "date" or "datetime".</summary>
public string Type { get; set; }
/// <summary>Header text in the Excel file.</summary>
public string Title { get; set; }
/// <summary>Column width in the grid (px); the Excel column gets a matching width.</summary>
public int Width { get; set; }
}
/// <summary>One window of rows for the grid.</summary>
public class VirtualPageResult
{
/// <summary>Rows matching the search (all rows when there is no search). Null when not counted (CountTotal = false).</summary>
public int? Total { get; set; }
/// <summary>All rows, ignoring the search. Null when not counted.</summary>
public int? TotalWithoutSearch { get; set; }
/// <summary>The rows of this window, holding only the requested columns.</summary>
public List<Dictionary<string, object>> Data { get; set; } = new List<Dictionary<string, object>>();
/// <summary>The .xlsx file, set only for ExportExcel requests. The controller returns it as a file.</summary>
public byte[] ExcelFile { get; set; }
public const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
}

View File

@ -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";
/// <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
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();

View File

@ -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`) | `<app-virtual-grid>`: 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
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"
exportFileName="DiscontinueEmployeeDetails.xlsx"></app-virtual-grid>
```
```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`).

View File

@ -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
{
/// <summary>
/// Server side of &lt;app-virtual-grid&gt;: 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.
/// </summary>
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;
/// <param name="query">The page's SELECT (column aliases = grid fields, no ORDER BY).</param>
/// <param name="keyFields">
/// 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)
throw new ArgumentException("Invalid request.");
List<string> 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<VirtualPageColumn> 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<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.
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<string, object>(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;
}
/// <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>
private static List<VirtualPageColumn> GetColumns(List<VirtualPageColumn> requested)
{
var columns = new List<VirtualPageColumn>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (VirtualPageColumn c in requested ?? new List<VirtualPageColumn>())
{
if (c == null || !IsIdentifier(c.Field))
throw new ArgumentException("Invalid column: " + c?.Field);
if (seen.Add(c.Field))
columns.Add(c);
}
return columns;
}
/// <summary>
/// "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").
/// </summary>
private static string SearchCondition(List<VirtualPageColumn> columns)
{
const string like = " LIKE @vpSearch ESCAPE '\\'";
var parts = new List<string>();
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) + ")";
}
/// <summary>
/// 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));
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)
{
if (sort == null || !string.Equals(key, sort.Field, StringComparison.OrdinalIgnoreCase))
parts.Add("[" + key + "] ASC");
}
return string.Join(", ", parts);
}
/// <summary>Makes %, _, [ and \ in the search text match themselves.</summary>
private static string EscapeLike(string text) =>
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_").Replace("[", "\\[");
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

@ -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
{
/// <summary>
/// Export to Excel for &lt;app-virtual-grid&gt;: 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.
/// </summary>
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<VirtualPageColumn> columns)
{
// Columns to write: the grid's, or every field of the query when none were sent.
var fields = new List<ExcelColumn>();
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<WorkbookStylesPart>();
stylesPart.Stylesheet = CreateStylesheet();
stylesPart.Stylesheet.Save();
WorksheetPart sheetPart = workbookPart.AddNewPart<WorksheetPart>();
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();
}
}
/// <summary>Header + every row, streamed. Returns the last row number.</summary>
private static int WriteSheet(WorksheetPart sheetPart, IDataReader reader, List<ExcelColumn> 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);
}
/// <summary>An inline text cell (never a formula). Characters XML cannot hold are dropped.</summary>
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();
}
/// <summary>1 → A, 27 → AA.</summary>
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;
}
}
}

View File

@ -2730,6 +2730,73 @@ namespace HRM.DA
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
/// <summary>
/// Discontinue Employee Details: one window of rows for the grid. SQL Server pages, searches and
/// sorts (VirtualPagingDA); the query is EmployeeDA.GetDiscontinuedEmployeeQuery.
/// </summary>
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();

View File

@ -0,0 +1,44 @@
/**
* <app-virtual-grid> (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 <app-virtual-grid> after every window it loads. */
export interface VirtualGridLoadedEvent {
total: number;
totalWithoutSearch: number;
/** True for the first window after load(filters). */
firstLoad: boolean;
}

View File

@ -98,6 +98,12 @@
}
</ul>
</li>
<!-- li items float right, so this one (last in DOM) sits LEFT of the Pending Jobs icon -->
@if (payrollTypeName) {
<li class="topbar-payroll-type-item">
<span class="topbar-payroll-type" kendoTooltip title="Current payroll type">{{payrollTypeName}}</span>
</li>
}
</ul>
<a class="layout-menus">
@if (apiService.menuItems !== null) {

View File

@ -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;
}

View File

@ -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() {

View File

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

View File

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

View File

@ -0,0 +1,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:
*
* <app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"></app-virtual-grid>
* 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<VirtualGridLoadedEvent>();
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<VirtualPageRequest>();
private readonly search$ = new Subject<string>();
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<VirtualPageResult>(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);
}
}
}

View File

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

View File

@ -0,0 +1,27 @@
<app-loading-panel></app-loading-panel>
<fieldset class="filter-box">
<legend>Search Criteria</legend>
<div class="filter-bar">
<div class="filter-field">
<label>From Date</label>
<kendo-datepicker [(ngModel)]="fromDate" [format]="dateFormat"></kendo-datepicker>
</div>
<div class="filter-field">
<label>To Date</label>
<kendo-datepicker [(ngModel)]="toDate" [format]="dateFormat"></kendo-datepicker>
</div>
<div class="filter-action">
<button kendoButton themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="preview()">Preview</button>
</div>
</div>
</fieldset>
<!-- Common virtual-scrolling grid: data from the endpoint, columns from this page. -->
<div class="col-12">
<app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns" [height]="660"
exportFileName="DiscontinueEmployeeDetails.xlsx"
noRecordsText="No employee was discontinued in the selected date range."
(loaded)="onLoaded($event)">
</app-virtual-grid>
</div>

View File

@ -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;
}
}

View File

@ -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 <app-virtual-grid> 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 },
];
}
}

View File

@ -357,6 +357,16 @@
<kendo-grid-excel fileName="EmployeesDetail.xlsx"></kendo-grid-excel>
</kendo-grid>
</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) {
<div class="col-12">
<!-- <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 {
EnumBloodGroup,
@ -48,6 +48,8 @@ import { DatePipe } from '@angular/common';
import { SystemConfigurationService } from 'src/app/_services/common/systemconfiguration.service';
import { SystemConfigaration } from 'src/app/_models/common/SystemConfigaration';
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';
const EXCEL_TYPE =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
@ -125,6 +127,9 @@ export class ReportViewerComponent implements OnInit {
tempReportList: Columns[];
ReportColumnDefinitions: ColumnDefinition[] = [];
dynamicColumnNames: ColumnDefinition[] = [];
/** Employee Detail Information (empDetailInfo) only: the virtual-scrolling grid and its columns. */
@ViewChild('empDetailGrid') empDetailGrid: VirtualGridComponent;
empDetailColumns: VirtualGridColumn[] = [];
reportType: any;
isPdfExport: boolean = false;
fromDate: Date = new Date();
@ -332,6 +337,7 @@ export class ReportViewerComponent implements OnInit {
];
this.dynamicColumnNames.push(...newColumns);
this.reportViewerColumn = new ReportViewerListColumn(this.reportType, this.dynamicColumnNames, employeeBasicInfo, 'EmployeesDetail');
this.empDetailColumns = this.toEmpDetailColumns(this.dynamicColumnNames);
//console.log(this.dynamicColumnNames);
});
@ -1422,7 +1428,9 @@ export class ReportViewerComponent implements OnInit {
if (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;
});
@ -1454,44 +1462,21 @@ export class ReportViewerComponent implements OnInit {
);
}
else if (this.reportType === 'empDetailInfo') {
if (this.selectedEmp !== undefined) {
selectedemps.push(this.selectedEmp);
// Virtual scrolling: the grid asks the server for 100 rows at a time
// (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;
this.employeeService.getEmpDetailInfo(selectedemps).subscribe(
(resp) => {
// this.employeeDetailInfos = resp;
this.loadingPanel.ShowLoadingPanel = false;
this.data = resp;
//debugger;
},
(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();
}
);
const employeeIds = new Set<number>(this.taggedSelection);
if (this.selectedEmp !== undefined) {
employeeIds.add(this.selectedEmp.employeeID);
}
if (this.empDetailColumns.length === 0) {
this.empDetailColumns = this.toEmpDetailColumns(this.dynamicColumnNames);
}
this.empDetailGrid.columns = this.empDetailColumns;
this.empDetailGrid.load({ employeeIds: Array.from(employeeIds).join(',') });
}
else if (this.reportType === 'dailyPresentReport' && reportType != 'new-PDF') {
if (this.fromDate === undefined) {
@ -2186,6 +2171,25 @@ export class ReportViewerComponent implements OnInit {
loadAttenGrid() {
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() {
//debugger
// this.loadGridView();

View File

@ -33,6 +33,7 @@ import { CcwiseNewPfMemberWithAmountComponent } from './ccwise-new-pf-member-wit
import { TrainingReportsComponent } from './training-reports/training-reports.component';
import { EssTaxCertificateComponent } from './ess-tax-certificate/ess-tax-certificate.component';
import { JvReportComponent } from './jv-report/jv-report.component';
import { DiscontinueEmployeeDetailsComponent } from './discontinue-employee-details/discontinue-employee-details.component';
export const routes: Routes = [
{ path: 'report-viewer/36', component: ReportViewerComponent, canActivate: [AuthGuard] },
@ -82,6 +83,7 @@ export const routes: Routes = [
{ path: 'date-wise-job-card-new', component: DateWiseJobCardNewComponent, canActivate: [AuthGuard] },
{ path: 'date-wise-attn-records', component: DateWiseAttnRecordsComponent, canActivate: [AuthGuard] },
{ path: 'monthly-exception-report', component: MonthlyExceptionReportComponent, canActivate: [AuthGuard] },
{ path: 'discontinue-employee-details', component: DiscontinueEmployeeDetailsComponent, canActivate: [AuthGuard] },
{ path: 'report-viewer/34', component: ReportViewerComponent, canActivate: [AuthGuard] },
{ path: 'report-viewer/170', component: ReportViewerComponent, canActivate: [AuthGuard] },
{ path: 'report-viewer/169', component: ReportViewerComponent, canActivate: [AuthGuard] },

View File

@ -56,6 +56,8 @@ import { TabViewCompatModule } from 'src/app/custom-components/tab-view-compat/t
import { EssTaxCertificateComponent } from './ess-tax-certificate/ess-tax-certificate.component';
import { EmpCommonInformationModule } from '../ess/emp-common-information/EmpCommonInformationModule';
import { JvReportComponent } from './jv-report/jv-report.component';
import { DiscontinueEmployeeDetailsComponent } from './discontinue-employee-details/discontinue-employee-details.component';
import { VirtualGridModule } from '../custom-components/virtual-grid/virtual-grid.module';
@NgModule({
declarations: [
@ -86,7 +88,8 @@ import { JvReportComponent } from './jv-report/jv-report.component';
TrainingReportsComponent,
CareerHistoryReportComponent,
EssTaxCertificateComponent,
JvReportComponent
JvReportComponent,
DiscontinueEmployeeDetailsComponent
],
imports: [
TextBoxModule,
@ -112,7 +115,8 @@ import { JvReportComponent } from './jv-report/jv-report.component';
CardModule,
BackgroundCanvasModule,
TabViewCompatModule,
EmpCommonInformationModule
EmpCommonInformationModule,
VirtualGridModule
],
providers: [
EmployeeServices,

View File

@ -3410,5 +3410,68 @@ namespace HRM.UI.Controllers
/// <summary>
/// Discontinue Employee Details (Manage Employee › Report): one window of rows for &lt;app-virtual-grid&gt;.
/// Filters: fromDate, toDate ("yyyy-MM-dd"). SQL Server does the paging, search and sort (VirtualPagingDA).
/// </summary>
[HttpPost("getDiscontinueEmployeePage")]
public ActionResult GetDiscontinueEmployeePage(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.");
DateTime fromDate = request.GetDate("fromDate", "From Date");
DateTime toDate = request.GetDate("toDate", "To Date");
if (fromDate > toDate)
return BadRequest("From Date cannot be after 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);
}
}
/// <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);
}
}
}
}