Compare commits

..

No commits in common. "devqc" and "dev_sabbir" have entirely different histories.

13 changed files with 35 additions and 314 deletions

View File

@ -1,54 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Overview
EchoTex HR & Payroll: an ASP.NET Core (.NET 8) Web API that hosts an Angular 13 SPA, backed by SQL Server through a hand-written ADO.NET data layer (no EF). Solution file: `EchoTex.sln`. Main branch for PRs is `devqc`; developers work on `dev_<name>` branches.
## Commands
Backend (from repo root):
- Build everything: `dotnet build EchoTex.sln`. `DatabaseComparison` is a legacy .NET Framework 4.6.1 WinForms project, so it may need Visual Studio/MSBuild. Build `HRM.UI/HRM.UI.csproj` directly to skip it.
- Run API + SPA: `dotnet run --project HRM.UI`. In Development, `Startup` calls `spa.UseAngularCliServer(npmScript: "start")`, which runs `ng serve` from `HRM.UI/ClientApp` automatically.
Frontend (from `HRM.UI/ClientApp`):
- `npm install` (Kendo UI license file: `kendo-ui-license.txt`)
- `npm start` (ng serve), `npm run build`, `npm run lint` (tslint), `npm test` (Karma)
The solution has no .NET test projects.
## Architecture
Layered projects, with dependencies flowing downward:
- **Ease.Core**: framework code. `DataAccess/` (`TransactionContext`, `DataReader`, `SQLParser.MakeSQL`, `DbConfig`/`ConnectionFactory` for SQL/Oracle) and `Model/` (`ServiceTemplate`, `ObjectTemplate`).
- **HRM.BO**: business objects grouped by domain folder (Leave, Salary, Tax, PF, Attendance…). Each domain file holds the entity classes (usually derived from `AuditTrailBase` / `BasicBaseObject`) **and** its service interface, e.g. `ILeaveEntryService` is defined at the bottom of `HRM.BO/Leave/LeaveEntry.cs`.
- **HRM.DA**: two halves.
- `DA/<Domain>/*DA.cs`: static internal classes that build raw SQL strings with `SQLParser.MakeSQL(...)` and run them against a `TransactionContext`.
- `Service/<Domain>/*Service.cs`: implement the BO interfaces and inherit `ServiceTemplate`. Each public method follows the same pattern: `tc = TransactionContext.Begin(...)`, call the DA, map rows with `DataReader` in a private `MapObject`, `tc.End()`, and `tc.HandleError()` in the catch block. Overloads that take an existing `TransactionContext tc` let one transaction span several services.
- **HRM.Report**: RDLC report generation (`RDLC/`, typed DataSets, `ReportProcessor.cs`).
- **HRM.UI**: the API host.
- `Controllers/<Area>/`: `[ApiController]` with `[Route("api/<Area>")]`. Each action wraps its body in try/catch and returns `StatusCode(500, e.Message)` on failure. Get the logged-in user from the JWT with `CurrentUser.GetCurrentUser(HttpContext.User)`.
- `Configurations/DI/ServiceCollectionExtensions.cs`: every service interface→implementation pair must be registered here (`AddTransient`). A new service will not resolve until it is added.
- `Configurations/AutoMapper`: mappings, registered by `services.ConfigureMappings()`.
- `appsettings.json` → `AppSettings`: `DefaultDB` names the connection entry in `DbConfig`, whose key is encrypted. The same file also holds JWT, email, and OpenAI settings.
- **HRM.AttendanceAutoProcess** (console) and **HRM.MailNotificationProcess** (WinForms, net8.0-windows): standalone background jobs that reuse BO/DA.
- **Erecruitment.UI**: a separate web app for e-recruitment.
### Adding a feature end-to-end
1. Add the entity and interface in `HRM.BO/<Domain>`.
2. Add the SQL in `HRM.DA/DA/<Domain>/XxxDA.cs`.
3. Add the service in `HRM.DA/Service/<Domain>`.
4. Register it in `ServiceCollectionExtensions`.
5. Add the controller action.
6. Add the Angular service method and component.
### Angular client (`HRM.UI/ClientApp/src/app`)
- Feature modules are lazy-loaded from `app.routes.ts` (e.g. `leave/leave.module`).
- HTTP calls go through per-domain services in `_services/<domain>/`. These wrap `ApiService` (`app.api.service.ts`) and call relative paths such as `this.apiService.httpGet('/Leave/getWeeklyHoliday')`.
- `ApiService` holds `base_url`, `versionNumber`, and the current payroll type/user type. The commented-out `base_url` values are per-client deployment paths.
- UI components come from Kendo UI for Angular and PrimeNG-style layout components (`app.main`, `app.menu`, `app.topbar`). Models live in `_models/`.
- Auth uses JWT (`@auth0/angular-jwt`), with optional Azure AD via MSAL. Route guards are in `_guards/`.

View File

@ -112,14 +112,6 @@ namespace HRM.DA
return rawData; return rawData;
} }
/// <summary>Card tagged with each employee: EmployeeID, CardID, CardNumber.</summary>
internal static IDataReader GetEmployeeCards(TransactionContext tc, string empIDs)
{
return tc.ExecuteReader("SELECT e.EmployeeID, e.CardID, ac.CardNumber FROM Employee e" +
" LEFT JOIN AccessCard ac ON ac.AccessCardID = e.CardID" +
" WHERE e.EmployeeID IN (%q)", empIDs);
}
internal static void Delete(TransactionContext tc, DateTime fromTime, string empIDs) internal static void Delete(TransactionContext tc, DateTime fromTime, string empIDs)
{ {
tc.ExecuteNonQuery("DELETE FROM AttnRawData WHERE PunchTime>=%D and EmployeeID in (%q)", fromTime, empIDs); tc.ExecuteNonQuery("DELETE FROM AttnRawData WHERE PunchTime>=%D and EmployeeID in (%q)", fromTime, empIDs);

View File

@ -2236,12 +2236,6 @@ namespace HRM.DA
return tc.ExecuteReader("Select * From Employee"); return tc.ExecuteReader("Select * From Employee");
} }
/// <param name="quotedEmployeeNos">Comma separated, already quoted/escaped list, e.g. 'E001','E002'</param>
internal static IDataReader GetByEmployeeNos(TransactionContext tc, string quotedEmployeeNos)
{
return tc.ExecuteReader("SELECT * FROM Employee WHERE EmployeeNo IN (%q)", quotedEmployeeNos);
}
internal static IDataReader GetAllEmps(TransactionContext tc, int payrollTypeid) internal static IDataReader GetAllEmps(TransactionContext tc, int payrollTypeid)
{ {
return tc.ExecuteReader("Select * From Employee where payrolltypeid=%n", payrollTypeid); return tc.ExecuteReader("Select * From Employee where payrolltypeid=%n", payrollTypeid);

View File

@ -484,22 +484,6 @@ namespace HRM.DA
return tc.ExecuteReader("SELECT * from LeaveEntry where LeaveYear=%n", nLeaveYear); return tc.ExecuteReader("SELECT * from LeaveEntry where LeaveYear=%n", nLeaveYear);
} }
/// <summary>
/// Leave entries of the given employees whose applied-from date falls in [fromDate, toDate],
/// excluding the given statuses. Used for overlap checks during bulk upload, so the
/// LeaveEntry table is filtered in SQL instead of loading the whole leave year.
/// </summary>
public static IDataReader GetForOverlapCheck(TransactionContext tc, int nLeaveYear, string empIDs,
DateTime fromDate, DateTime toDate, string excludedStatuses)
{
// AppFromDate < (toDate + 1 day) so entries on the last day are included regardless of time part
return tc.ExecuteReader(@"SELECT * FROM LeaveEntry
WHERE LeaveYear=%n AND EmpId IN (%q)
AND AppFromDate >= %d AND AppFromDate < %d
AND LeaveStatus NOT IN (%q)",
nLeaveYear, empIDs, fromDate.Date, toDate.Date.AddDays(1), excludedStatuses);
}
public static IDataReader Get(TransactionContext tc, string empIds, DateTime fromDate, DateTime toDate, public static IDataReader Get(TransactionContext tc, string empIds, DateTime fromDate, DateTime toDate,
string LeaveStatus) string LeaveStatus)
{ {

View File

@ -1,6 +1,5 @@
using DocumentFormat.OpenXml.Drawing.Diagrams; using HRM.BO;
using Ease.Core.DataAccess; using Ease.Core.DataAccess;
using HRM.BO;
using System; using System;
using System.Data; using System.Data;
@ -222,19 +221,9 @@ namespace HRM.DA
tc.ExecuteNonQuery( tc.ExecuteNonQuery(
"DELETE FROM SalaryMonthlyDetail WHERE SalaryMonthlyID in( Select SalaryMonthlyID from SalaryMonthly Where SalaryProcessID=%n)", "DELETE FROM SalaryMonthlyDetail WHERE SalaryMonthlyID in( Select SalaryMonthlyID from SalaryMonthly Where SalaryProcessID=%n)",
id); id);
tc.ExecuteNonQuery(@"ALTER TABLE OPIPayment NOCHECK CONSTRAINT FK_OPIPayment_SALARYMONTHLY;
ALTER TABLE SALARYMONTHLYDETAIL NOCHECK CONSTRAINT FK_SLRMTHDTL_SLRMTH;
ALTER TABLE SALARYTEMPDETAIL NOCHECK CONSTRAINT FK_SLRTMPDTL_SLRMTH; ");
tc.ExecuteNonQuery("DELETE FROM SalaryMonthly WHERE SalaryProcessID=%n", id); tc.ExecuteNonQuery("DELETE FROM SalaryMonthly WHERE SalaryProcessID=%n", id);
//}
tc.ExecuteNonQuery(@" ALTER TABLE OPIPayment WITH CHECK CHECK CONSTRAINT FK_OPIPayment_SALARYMONTHLY; //tc.ExecuteNonQuery("DELETE FROM SalaryProcess WHERE SalaryProcessID=%n", id);
ALTER TABLE SALARYMONTHLYDETAIL WITH CHECK CHECK CONSTRAINT FK_SLRMTHDTL_SLRMTH;
ALTER TABLE SALARYTEMPDETAIL WITH CHECK CHECK CONSTRAINT FK_SLRTMPDTL_SLRMTH;");
tc.ExecuteNonQuery("DELETE FROM SalaryProcess WHERE SalaryProcessID=%n", id);
} }
internal static void UndoMonthlySalaryByIDs(TransactionContext tc, string ids) internal static void UndoMonthlySalaryByIDs(TransactionContext tc, string ids)

View File

@ -2656,6 +2656,7 @@ namespace HRM.DA
{ {
continue; continue;
} }
// 2. If End of Contract date is less than or equal Attendendence date then no attendence // 2. If End of Contract date is less than or equal Attendendence date then no attendence
if (emp.EndOfContractDate != null && emp.EndOfContractDate.Value <= Attdate) if (emp.EndOfContractDate != null && emp.EndOfContractDate.Value <= Attdate)
{ {

View File

@ -392,35 +392,6 @@ namespace HRM.DA
string empIDs = attnRawDatas.Aggregate(new StringBuilder(), string empIDs = attnRawDatas.Aggregate(new StringBuilder(),
(sb, rData) => sb.AppendFormat("{0},", rData.EmployeeID), sb => sb.ToString().Trim(',')); (sb, rData) => sb.AppendFormat("{0},", rData.EmployeeID), sb => sb.ToString().Trim(','));
AttnRawDataDA.Delete(tc, dMinValue, empIDs); AttnRawDataDA.Delete(tc, dMinValue, empIDs);
// Fill CardID (and CardNo when not supplied) from the card tagged with the employee
var empCards = new Dictionary<int, Tuple<int?, string>>();
string distinctEmpIDs = string.Join(",", attnRawDatas.Where(x => x.EmployeeID > 0)
.Select(x => x.EmployeeID).Distinct());
if (distinctEmpIDs.Length > 0)
{
DataReader dr = new DataReader(AttnRawDataDA.GetEmployeeCards(tc, distinctEmpIDs));
while (dr.Read())
{
empCards[dr.GetInt32("EmployeeID", 0)] =
Tuple.Create(dr.GetInt32("CardID"), dr.GetString("CardNumber"));
}
dr.Close();
}
foreach (AttnRawData item in attnRawDatas)
{
Tuple<int?, string> card;
if (empCards.TryGetValue(item.EmployeeID, out card))
{
if (item.CardID <= 0 && card.Item1.HasValue && card.Item1.Value > 0)
item.CardID = card.Item1.Value;
if (string.IsNullOrWhiteSpace(item.CardNo) && !string.IsNullOrWhiteSpace(card.Item2))
item.CardNo = card.Item2.Trim();
}
if (string.IsNullOrWhiteSpace(item.CardNo))
item.CardNo = item.EmployeeNo ?? string.Empty; // employee has no card tagged
}
DataTable _dtRawData = null; DataTable _dtRawData = null;
_dtRawData = new DataTable("AttnRawData"); _dtRawData = new DataTable("AttnRawData");
// _dtRawData.Columns.Add("ATTNRAWDATAID", typeof(int)); // _dtRawData.Columns.Add("ATTNRAWDATAID", typeof(int));
@ -447,7 +418,7 @@ namespace HRM.DA
// item.DeviceNo, // item.DeviceNo,
// item.PunchTime); // item.PunchTime);
_dtRawData.Rows.Add( _dtRawData.Rows.Add(
item.CardID > 0 ? (object)item.CardID : DBNull.Value, null,
item.EmployeeID, item.EmployeeID,
item.CardNo.Trim(), item.CardNo.Trim(),
item.PunchTime, item.PunchTime,

View File

@ -3563,44 +3563,11 @@ namespace HRM.DA
try try
{ {
// Pre-scan the uploaded rows so we only load the employees / leave entries List<LeaveEntry> leaveentries = new LeaveEntryService().GetByLeaveYear(currLeaveYear.ID);
// that are actually referenced, instead of the full Employee and LeaveEntry tables.
List<string> uploadedEmpNos = new List<string>();
DateTime? minFromDate = null;
DateTime? maxToDate = null;
foreach (DataRow row in _uplodedData.Rows)
{
uploadedEmpNos.Add(row[0].ToString().Trim());
DateTime f, t;
if (DateTime.TryParse(row[2].ToString().Trim(), out f)
&& DateTime.TryParse(row[3].ToString().Trim(), out t))
{
if (minFromDate == null || f < minFromDate) minFromDate = f;
if (maxToDate == null || t > maxToDate) maxToDate = t;
}
}
// EmployeeNo -> Employee (ordinal, same exact-match semantics as the previous List.Find)
Dictionary<string, Employee> employeesByNo = new EmployeeService()
.GetByEmployeeNos(uploadedEmpNos)
.Where(e => e.EmployeeNo != null)
.GroupBy(e => e.EmployeeNo, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
// EmpID -> existing (non declined / cancelled) leave entries within the uploaded date window
Dictionary<int, List<LeaveEntry>> leaveEntriesByEmp = new Dictionary<int, List<LeaveEntry>>();
if (minFromDate != null && employeesByNo.Count > 0)
{
leaveEntriesByEmp = new LeaveEntryService()
.GetForOverlapCheck(currLeaveYear.ID, employeesByNo.Values.Select(e => e.ID),
minFromDate.Value, maxToDate.Value, EnumLeaveStatus.Declined, EnumLeaveStatus.Cancel)
.GroupBy(x => x.EmpID)
.ToDictionary(g => g.Key, g => g.ToList());
}
int nRowCount = 1; int nRowCount = 1;
LeaveEntry leaveEntry = new LeaveEntry(); LeaveEntry leaveEntry = new LeaveEntry();
List<LeaveEntry> leaveEntrys = new List<LeaveEntry>(); List<LeaveEntry> leaveEntrys = new List<LeaveEntry>();
List<Employee> employees = new EmployeeService().GetAllEmps();
List<Leave> oLeaves = new LeaveService().GetAll(); List<Leave> oLeaves = new LeaveService().GetAll();
List<LeaveParameter> oLeaveParameters = new List<LeaveParameter>(); List<LeaveParameter> oLeaveParameters = new List<LeaveParameter>();
List<LeaveParameter> leaveParamss = new LeaveParameterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID, null, true); List<LeaveParameter> leaveParamss = new LeaveParameterService().Get(EnumStatus.Regardless, _columnDefinition.PayrollTypeID, null, true);
@ -3625,8 +3592,8 @@ namespace HRM.DA
string remarks = dr[5].ToString().Trim(); string remarks = dr[5].ToString().Trim();
//Leave leave = leaves.Find(delegate(Payroll.BO.Leave le) { return le.Code == leaveCode; }); //Leave leave = leaves.Find(delegate(Payroll.BO.Leave le) { return le.Code == leaveCode; });
Employee employee; Employee employee = employees.Find(delegate (Employee em) { return em.EmployeeNo == Empcode; });
if (!employeesByNo.TryGetValue(Empcode, out employee)) if (employee == null)
{ {
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee Not found")); _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + "Employee Not found"));
continue; continue;
@ -3643,13 +3610,12 @@ namespace HRM.DA
continue; continue;
} }
List<LeaveEntry> empLeaveEntries; List<LeaveEntry> tempLS = leaveentries.Where(x => x.AppliedFromDate >= fromDate
bool hasOverlap = leaveEntriesByEmp.TryGetValue(employee.ID, out empLeaveEntries)
&& empLeaveEntries.Any(x => x.AppliedFromDate >= fromDate
&& x.AppliedFromDate <= toDate && x.AppliedFromDate <= toDate
&& x.EmpID == employee.ID
&& x.LeaveStatus != EnumLeaveStatus.Declined && x.LeaveStatus != EnumLeaveStatus.Declined
&& x.LeaveStatus != EnumLeaveStatus.Cancel); && x.LeaveStatus != EnumLeaveStatus.Cancel).ToList();
if (hasOverlap) if (tempLS.Count > 0)
{ {
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + " Overlap with previously applied leaves.")); _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("Employee No", nRow, "(" + dr["Employee No"].ToString() + ")" + " Overlap with previously applied leaves."));
continue; continue;

View File

@ -1194,51 +1194,6 @@ namespace HRM.DA
return employees; return employees;
} }
/// <summary>
/// Loads only the employees whose EmployeeNo is in the given list (queried in batches),
/// instead of reading the whole Employee table.
/// </summary>
public List<Employee> GetByEmployeeNos(IEnumerable<string> employeeNos)
{
List<Employee> employees = new List<Employee>();
List<string> distinctNos = employeeNos
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
if (distinctNos.Count == 0) return employees;
const int batchSize = 500;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
for (int i = 0; i < distinctNos.Count; i += batchSize)
{
string inList = string.Join(",", distinctNos.Skip(i).Take(batchSize)
.Select(x => "'" + x.Replace("'", "''") + "'"));
DataReader dr = new DataReader(EmployeeDA.GetByEmployeeNos(tc, inList));
employees.AddRange(this.CreateObjects<Employee>(dr));
dr.Close();
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return employees;
}
public List<Employee> GetAllEmps(int payrollTypeid) public List<Employee> GetAllEmps(int payrollTypeid)
{ {
List<Employee> employees = new List<Employee>(); List<Employee> employees = new List<Employee>();

View File

@ -713,52 +713,6 @@ namespace HRM.DA
return oLeaveEntrys; return oLeaveEntrys;
} }
/// <summary>
/// Loads leave entries only for the given employees and applied-from date window
/// (queried in batches), excluding the given statuses. Replacement for
/// GetByLeaveYear when only a few employees need an overlap check.
/// </summary>
public List<LeaveEntry> GetForOverlapCheck(int nLeaveYear, IEnumerable<int> empIDs, DateTime fromDate,
DateTime toDate, params EnumLeaveStatus[] excludedStatuses)
{
List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
List<int> ids = empIDs.Distinct().ToList();
if (ids.Count == 0) return oLeaveEntrys;
string statuses = excludedStatuses != null && excludedStatuses.Length > 0
? string.Join(",", excludedStatuses.Select(x => ((int)x).ToString()))
: "-1";
const int batchSize = 500;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
for (int i = 0; i < ids.Count; i += batchSize)
{
string inList = string.Join(",", ids.Skip(i).Take(batchSize));
DataReader dr = new DataReader(LeaveEntryDA.GetForOverlapCheck(tc, nLeaveYear, inList,
fromDate, toDate, statuses));
oLeaveEntrys.AddRange(this.CreateObjects<LeaveEntry>(dr));
dr.Close();
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
#endregion
}
return oLeaveEntrys;
}
public List<LeaveEntry> Get(string empIds, DateTime fromDate, DateTime toDate, string leaveStatuss) public List<LeaveEntry> Get(string empIds, DateTime fromDate, DateTime toDate, string leaveStatuss)
{ {
List<LeaveEntry> oLeaveEntrys = null; List<LeaveEntry> oLeaveEntrys = null;

View File

@ -37,7 +37,7 @@ export class ReadAttendanceRawdataComponent {
public employees: Employee[] = []; public employees: Employee[] = [];
selectedCard: any; selectedCard: any;
entryModes: any = EnumExtension.getNamesAndValues(EnumEntryMode); entryModes: any = EnumExtension.getNamesAndValues(EnumEntryMode);
format: string = ".csv (Column Names: EmpNo,PunchTime[,CardNo]) PunchTime: M/d/yyyy H:mm"; // CardNo is optional format: string = ".csv (Column Names: EmpNo,PunchTime,CardNo)"; // (Date Time Format: MM/dd/yyyy h:mm)
public gridView: GridDataResult; public gridView: GridDataResult;
public gridView2: GridDataResult; public gridView2: GridDataResult;
public mandatoryItems: mandatoryData[] = []; public mandatoryItems: mandatoryData[] = [];
@ -149,23 +149,22 @@ export class ReadAttendanceRawdataComponent {
}); });
//console.log(text); //console.log(text);
var lines = text.split(/\r?\n/); // handle both Windows (\r\n) and Unix (\n) line endings var lines = text.split("\n");
//console.log(lines); //console.log(lines);
this.uploadedLines = []; this.uploadedLines = [];
const cell = (v: string) => (v === undefined || v === null) ? '' : v.trim().replace(/^"(.*)"$/, '$1').trim();
try { try {
for (var i = 1; i < lines.length; i++) { for (var i = 1; i < lines.length; i++) {
this.uploadeddata = new csvFileData(); this.uploadeddata = new csvFileData();
if (lines[i].trim() !== "") { if (lines[i] !== "") {
//console.log(lines[i]); //console.log(lines[i]);
var temp = lines[i].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); //spliting comma separated values but ignoring commas in double quoted string var temp = lines[i].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); //spliting comma separated values but ignoring commas in double quoted string
this.uploadeddata.rowNo = i.toString(); this.uploadeddata.rowNo = i.toString();
this.uploadeddata.employeeNo = cell(temp[0]); this.uploadeddata.employeeNo = temp[0].replace(/^"(.*)"$/, '$1');
this.uploadeddata.punchTime = cell(temp[1]); this.uploadeddata.punchTime = temp[1].replace(/^"(.*)"$/, '$1');
this.uploadeddata.cardNo = cell(temp[2]); // CardNo column is optional this.uploadeddata.cardNo = temp[2].replace(/^"(.*)"$/, '$1');
//this.uploadeddata.deviceNo = temp[3].replace(/^"(.*)"$/, '$1'); //this.uploadeddata.deviceNo = temp[3].replace(/^"(.*)"$/, '$1');
//this.uploadeddata.deviceIPAddress = temp[4].replace(/^"(.*)"$/, '$1'); //this.uploadeddata.deviceIPAddress = temp[4].replace(/^"(.*)"$/, '$1');
//this.uploadeddata.entryMode = temp[5].replace(/^"(.*)"$/, '$1'); //this.uploadeddata.entryMode = temp[5].replace(/^"(.*)"$/, '$1');
@ -186,8 +185,7 @@ export class ReadAttendanceRawdataComponent {
//console.log(this.uploadeddatas); //console.log(this.uploadeddatas);
} }
catch (e) { catch (e) {
this.uploadeddatas = []; //this.no.showError(e);
this._notificationService.showError("Failed to read CSV file: " + (e && e.message ? e.message : e));
} }
// //console.log(this.iJobs); // //console.log(this.iJobs);
@ -209,27 +207,16 @@ export class ReadAttendanceRawdataComponent {
} }
public upload() { public upload() {
if (this.uploadeddatas == undefined || this.uploadeddatas.length <= 0) { if (this.uploadeddata == undefined || this.uploadeddatas.length <= 0) {
this._notificationService.showError("Data not defined"); this._notificationService.showError("Data not defined");
return; return;
} }
if (this.employees == undefined || this.employees.length <= 0) { if (this.mandatoryItems !== undefined && this.mandatoryItems.length > 0) {
this._notificationService.showError("Employee list is not loaded yet. Please wait a moment and try again.");
return;
}
// re-validate here: the employee list may still have been loading when the file was selected
this.mandatoryDataChecker(this.uploadeddatas);
this.errorChecker(this.uploadeddatas);
this.skip2 = 0;
this.loadGrid2();
if (this.mandatoryItems.some(x => x.Error !== "Employee Not Found")) {
this._notificationService.showError("Employee No and PunchTime cannot be empty"); this._notificationService.showError("Employee No and PunchTime cannot be empty");
return; return;
} }
if (this.faultyItems !== undefined && this.faultyItems.length > 0) { if (this.faultyItems !== undefined && this.faultyItems.length > 0) {
const notFound = Array.from(new Set(this.faultyItems.map(x => x.employeeNo))).join(', '); this._notificationService.showError("Employee No not Found");
this._notificationService.showError("Employee No not found: " + notFound);
return; return;
} }
debugger; debugger;
@ -259,13 +246,10 @@ export class ReadAttendanceRawdataComponent {
item.punchTime = new Date; // otherwise error item.punchTime = new Date; // otherwise error
item.punchTimeDateString = x.punchTime; item.punchTimeDateString = x.punchTime;
//console.log(item.punchTime); //console.log(item.punchTime);
const matchedEmp = this.findEmployee(x.employeeNo); item.employeeID = this.employees.find(e => e.employeeNo.trim().toLowerCase() == x.employeeNo.trim().toLowerCase()) == undefined ? 0 : this.employees.find(e => e.employeeNo.trim().toLowerCase() == x.employeeNo.trim().toLowerCase()).id;
item.employeeID = matchedEmp == undefined ? 0 : matchedEmp.id; item.employeeNo = x.employeeNo,
item.employeeNo = matchedEmp == undefined ? x.employeeNo : matchedEmp.employeeNo.trim(),
item.entryMode = (x.entryMode == undefined || x.entryMode.length <= 0) ? 0 : this.entryModes.find(e => e.name.trim().toLowerCase() == x.entryMode.trim().toLowerCase()).value, item.entryMode = (x.entryMode == undefined || x.entryMode.length <= 0) ? 0 : this.entryModes.find(e => e.name.trim().toLowerCase() == x.entryMode.trim().toLowerCase()).value,
item.cardID = (matchedEmp != undefined && matchedEmp.cardID != undefined && matchedEmp.cardID != null) ? matchedEmp.cardID : 0; item.cardNo = (x.cardNo == undefined || x.cardNo == "" || x.cardNo == null) ? item.employeeNo : x.cardNo,
// empty CardNo -> server fills it from the employee's tagged AccessCard (falls back to EmpNo)
item.cardNo = (x.cardNo == undefined || x.cardNo == null) ? "" : x.cardNo.trim(),
item.deviceNo = (x.deviceNo !== undefined || x.deviceNo !== "" || x.deviceNo !== null) ? "" : item.deviceNo, item.deviceNo = (x.deviceNo !== undefined || x.deviceNo !== "" || x.deviceNo !== null) ? "" : item.deviceNo,
item.deviceIPAddress = (x.deviceIPAddress !== undefined || x.deviceIPAddress !== "" || x.deviceIPAddress !== null) ? "" : item.deviceIPAddress item.deviceIPAddress = (x.deviceIPAddress !== undefined || x.deviceIPAddress !== "" || x.deviceIPAddress !== null) ? "" : item.deviceIPAddress
item.isManualEntry = true; item.isManualEntry = true;
@ -439,8 +423,8 @@ export class ReadAttendanceRawdataComponent {
// this.faultyItems.push(item); // this.faultyItems.push(item);
//} //}
var employeeId = 0; var employeeId = 0;
if (this.employees != undefined && this.employees.length > 0) { if (this.employees != undefined) {
var employee = this.findEmployee(item.employeeNo); var employee = this.employees.find(x => x.employeeNo.trim() === item.employeeNo.trim());
if (employee == undefined) { if (employee == undefined) {
var mandatoryItem = new mandatoryData(); var mandatoryItem = new mandatoryData();
mandatoryItem.ColumnName = "EmployeeNo"; mandatoryItem.ColumnName = "EmployeeNo";
@ -456,18 +440,6 @@ export class ReadAttendanceRawdataComponent {
} }
// Matches an uploaded EmpNo to an employee: trimmed, case-insensitive, and
// tolerant of leading zeros (e.g. "859" matches "00859").
private findEmployee(empNo: string): Employee {
if (empNo == undefined || this.employees == undefined) return undefined;
const norm = (v: string) => (v == undefined || v == null) ? '' : String(v).trim().toLowerCase();
const stripZeros = (v: string) => v.replace(/^0+(?=.)/, '');
const target = norm(empNo);
if (target === '') return undefined;
return this.employees.find(e => norm(e.employeeNo) === target)
|| this.employees.find(e => norm(e.employeeNo) !== '' && stripZeros(norm(e.employeeNo)) === stripZeros(target));
}
public pageChange(event: PageChangeEvent): void { public pageChange(event: PageChangeEvent): void {
this.skip = event.skip; this.skip = event.skip;
this.gridView = { this.gridView = {

View File

@ -47,15 +47,15 @@
</ng-template> </ng-template>
</kendo-grid-column> </kendo-grid-column>
<kendo-grid-column field="approvedFromDate" title="From Date" width="120"> <kendo-grid-column field="appliedFromDate" title="From Date" width="120">
<ng-template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex"> <ng-template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">
{{dataItem.approvedFromDate | date: 'dd-MMM-yyyy'}} {{dataItem.appliedFromDate | date: 'dd-MMM-yyyy'}}
</ng-template> </ng-template>
</kendo-grid-column> </kendo-grid-column>
<kendo-grid-column field="approvedToDate" title="To Date" width="120"> <kendo-grid-column field="appliedToDate" title="To Date" width="120">
<ng-template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex"> <ng-template kendoGridCellTemplate let-dataItem let-rowIndex="rowIndex">
{{dataItem.approvedToDate | date: 'dd-MMM-yyyy'}} {{dataItem.appliedToDate | date: 'dd-MMM-yyyy'}}
</ng-template> </ng-template>
</kendo-grid-column> </kendo-grid-column>
<kendo-grid-column field="isLFA" title="LFA" width="80"> <kendo-grid-column field="isLFA" title="LFA" width="80">

View File

@ -151,9 +151,6 @@ export class LeaveListByAdminComponent implements OnInit {
this._leaveEntry.appliedFromDate = new Date(this._leaveEntry.appliedFromDate); this._leaveEntry.appliedFromDate = new Date(this._leaveEntry.appliedFromDate);
this._leaveEntry.appliedToDate = new Date(this._leaveEntry.appliedToDate); this._leaveEntry.appliedToDate = new Date(this._leaveEntry.appliedToDate);
this._leaveEntry.appliedLeaveDate = new Date(this._leaveEntry.appliedLeaveDate); this._leaveEntry.appliedLeaveDate = new Date(this._leaveEntry.appliedLeaveDate);
this._leaveEntry.approvedFromDate = new Date(this._leaveEntry.approvedFromDate);
this._leaveEntry.approvedToDate = new Date(this._leaveEntry.approvedToDate);
this._leaveEntry.appliedLeaveDate = new Date(this._leaveEntry.appliedLeaveDate);
this.showModal = true; this.showModal = true;
this.isNew = false; this.isNew = false;