From 4e0b8278591b074e3bc9338a1c9629b684717de1 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Wed, 25 Nov 2026 14:24:56 +0600 Subject: [PATCH 1/9] Employee Wise PF Handling including Uploader --- HRM.BO/Employee/Employee.cs | 1 + HRM.BO/HREmployee/EmpLifeCycle.cs | 9 ++ HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs | 10 +- HRM.DA/DA/HREmployee/HREmployeeDA.cs | 6 + .../Common/BasicDataUploadProcessService.cs | 30 ++++ .../Common/RegularDataUploadService.cs | 20 +++ HRM.DA/Service/Employee/EmployeeService.cs | 7 + .../Service/HREmployee/EmpLifeCycleService.cs | 17 ++ HRM.DA/Service/Salary/SalaryCalculator.cs | 152 +++++++++++++++++- .../src/app/_models/Employee/empLifeCycle.ts | 1 + .../src/app/_models/Employee/employee.ts | 2 + .../employee/empLifeCycle.service.ts | 3 + .../src/app/app.topbar.component.html | 2 +- .../src/app/app.topbar.component.scss | 5 +- .../ClientApp/src/app/app.topbar.component.ts | 5 + .../data-upload/data-upload.component.ts | 9 ++ .../life-cycle-entry.component.html | 26 ++- .../life-cycle-entry.component.ts | 37 +++++ .../Employee/empLifeCycleController.cs | 16 ++ 19 files changed, 348 insertions(+), 10 deletions(-) diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index e93399d..448aa54 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -123,6 +123,7 @@ namespace HRM.BO public bool IsShownInTaxSheet { get; set; } // R public EnumPFMembershipType PFMemberType { get; set; } public DateTime? PFMemberShiptDate { get; set; } + public double PFPercentage { get; set; } public int? BranchID { get; set; } public string AccountNo { get; set; } public int? OutPayBranchID { get; set; } diff --git a/HRM.BO/HREmployee/EmpLifeCycle.cs b/HRM.BO/HREmployee/EmpLifeCycle.cs index 5b01b3a..8fa3e3e 100644 --- a/HRM.BO/HREmployee/EmpLifeCycle.cs +++ b/HRM.BO/HREmployee/EmpLifeCycle.cs @@ -168,6 +168,14 @@ namespace HRM.BO } } #endregion + #region PFPercentage : double + private double? _pFPercentage; + public double? PFPercentage + { + get { return _pFPercentage; } + set { _pFPercentage = value; } + } + #endregion #region EmployeeID : ID private int _employeeID; public int EmployeeID @@ -577,6 +585,7 @@ namespace HRM.BO List GetEmpID(int nEmpID, DateTime effectDate); EmpLifeCycle GetLastPosition(int nEmpID); void UpdateApprovalStatus(List oEmpLifeCycles, int currentPayrollTypeID); + bool IsAutoPFMembership(); int Save(EmpLifeCycle item, DateTime nextPayProcessDate, int payrollTypeID); int Save(List items, DateTime nextPayProcessDate); void Delete(EmpLifeCycle item, DateTime nextPayProcessDate); diff --git a/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs b/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs index c3ea03c..090a1aa 100644 --- a/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs +++ b/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs @@ -26,8 +26,8 @@ namespace HRM.DA public static void Insert(TransactionContext tc, EmpLifeCycle item) { tc.ExecuteNonQuery( - "INSERT INTO EmpLifeCycle(EmpLifeCycleID,EffectDate,NodeID,GrossSalary,BasicSalary,GradeID,CategoryID,CompanyID,FunctionID,DesignationID,LocationID,DepartmentID,IsConfirm,pFMemberType,IsDiscontinue,IsContinue,EmployeeID,StatusDetailID,Remarks,Description,Status,CreatedBy, CreationDate, SequenceNo,SalaryMonth,IsCurrentMonthIncluded,CostCenterID,GradeSalaryAssesmentID,EmployeeCCID,IncrementNo,PayrollTypeID,ComplainID,PunishmentID,ApprovalStatus)" + - " VALUES( %n , %D , %n , %n , %n , %n , %n , %n , %n , %n , %n , %n , %b , %n , %b , %b , %n , %n , %s , %s , %n , %n , %D , %n , %D , %b , %n , %n , %n ,%n, %n,%n,%n,%n )", + "INSERT INTO EmpLifeCycle(EmpLifeCycleID,EffectDate,NodeID,GrossSalary,BasicSalary,GradeID,CategoryID,CompanyID,FunctionID,DesignationID,LocationID,DepartmentID,IsConfirm,pFMemberType,IsDiscontinue,IsContinue,EmployeeID,StatusDetailID,Remarks,Description,Status,CreatedBy, CreationDate, SequenceNo,SalaryMonth,IsCurrentMonthIncluded,CostCenterID,GradeSalaryAssesmentID,EmployeeCCID,IncrementNo,PayrollTypeID,ComplainID,PunishmentID,ApprovalStatus,PFPercentage)" + + " VALUES( %n , %D , %n , %n , %n , %n , %n , %n , %n , %n , %n , %n , %b , %n , %b , %b , %n , %n , %s , %s , %n , %n , %D , %n , %D , %b , %n , %n , %n ,%n, %n,%n,%n,%n,%n )", item.ID, item.EffectDate, item.NodeID, item.GrossSalary, item.BasicSalary, item.GradeID, item.CategoryID, item.CompanyID, item.FunctionID, @@ -37,7 +37,7 @@ namespace HRM.DA item.Description, item.EmployeeStatus, DataReader.GetNullValue(item.CreatedBy, 0), item.CreatedDate, item.Sequence, item.SalaryMonth, item.IsCurrentMonthIncluded, item.CostCenterID, item.GradeSalaryAssesmentID, - item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus); + item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.PFPercentage); //1 //2 //3 //4 //5 //6 //7 //8 //9 //10 //11 //12 //13 //14 //15 //16 //17 //18 //19 //20 //21 //21 //22 //23 //24 //25 } @@ -49,7 +49,7 @@ namespace HRM.DA { tc.ExecuteNonQuery(@"UPDATE EmpLifeCycle set EffectDate=%D,NodeID=%n,GrossSalary=%n,BasicSalary=%n,GradeID=%n,CategoryID=%n,CompanyID=%n,FunctionID=%n,DesignationID=%n, LocationID=%n,DepartmentID=%n,IsConfirm=%b,pFMemberType=%n,IsDiscontinue=%b,IsContinue=%b,EmployeeID=%n,StatusDetailID=%n,Remarks=%s,Description=%s,Status=%n,CreatedBy=%n, CreationDate=%D, -SequenceNo=%n,SalaryMonth=%D,IsCurrentMonthIncluded=%b,CostCenterID=%n,GradeSalaryAssesmentID=%n,EmployeeCCID=%n,IncrementNo=%n,PayrollTypeID=%n,ComplainID=%n,PunishmentID=%n,ApprovalStatus=%n +SequenceNo=%n,SalaryMonth=%D,IsCurrentMonthIncluded=%b,CostCenterID=%n,GradeSalaryAssesmentID=%n,EmployeeCCID=%n,IncrementNo=%n,PayrollTypeID=%n,ComplainID=%n,PunishmentID=%n,ApprovalStatus=%n,PFPercentage=%n WHERE EmpLifeCycleID=%n", item.EffectDate, item.NodeID, item.GrossSalary, item.BasicSalary, item.GradeID, item.CategoryID, item.CompanyID, item.FunctionID, @@ -59,7 +59,7 @@ WHERE EmpLifeCycleID=%n", item.EffectDate, item.NodeID, item.GrossSalary, item.B item.Description, item.EmployeeStatus, DataReader.GetNullValue(item.CreatedBy, 0), item.CreatedDate, item.Sequence, item.SalaryMonth, item.IsCurrentMonthIncluded, item.CostCenterID, item.GradeSalaryAssesmentID, - item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.ID); + item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.PFPercentage, item.ID); } public static void UpdateApprovalStatus(TransactionContext tc, EmpLifeCycle item) diff --git a/HRM.DA/DA/HREmployee/HREmployeeDA.cs b/HRM.DA/DA/HREmployee/HREmployeeDA.cs index f5f1bf3..526b751 100644 --- a/HRM.DA/DA/HREmployee/HREmployeeDA.cs +++ b/HRM.DA/DA/HREmployee/HREmployeeDA.cs @@ -318,6 +318,12 @@ namespace HRM.DA } + public static void UpdatePFPercentage(TransactionContext tc, int EmployeeID, double pfPercentage) + { + tc.ExecuteNonQuery("UPDATE Employee SET PFPercentage=%n WHERE EmployeeID=%n", + pfPercentage, EmployeeID); + } + public static void UpdateEndofContact(TransactionContext tc, int EmployeeID, DateTime dt) { tc.ExecuteNonQuery("UPDATE Employee SET ENDOFCONTRACTDATE= %d WHERE EmployeeID=%n", diff --git a/HRM.DA/Service/Common/BasicDataUploadProcessService.cs b/HRM.DA/Service/Common/BasicDataUploadProcessService.cs index 2b88c94..b4d7651 100644 --- a/HRM.DA/Service/Common/BasicDataUploadProcessService.cs +++ b/HRM.DA/Service/Common/BasicDataUploadProcessService.cs @@ -189,6 +189,25 @@ namespace HRM.DA } } + // PF Percentage column exists only when autopfmembership is on; it is needed when this row makes the employee a Live PF member + if (autopf && odataTable.Columns.Contains("PF Percentage")) + { + string sPFPercentage = dr["PF Percentage"].ToString().Trim(); + double pfPercentage = 0; + if (sPFPercentage != string.Empty + && (!double.TryParse(sPFPercentage, out pfPercentage) || pfPercentage <= 0 || pfPercentage > 100)) + { + _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "PF Percentage must be greater than 0 and up to 100", oemployee.EmployeeNo, oemployee.Name)); + } + else if (oemployee.PFMemberType == EnumPFMembershipType.Live) + { + if (sPFPercentage == string.Empty) + _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "PF Percentage can't be empty when Confirmation Date is given", oemployee.EmployeeNo, oemployee.Name)); + else + oemployee.PFPercentage = pfPercentage; + } + } + //Refresh Employee Grade Salary if (oemployee.GradeID != null) { @@ -841,6 +860,7 @@ namespace HRM.DA bool isbankCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "bank", "codeautogenerate")); bool isbranchCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "branch", "codeautogenerate")); bool isGrossApplicable = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "grossapplicable"); + bool autopf = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership"); item.SheetName = "EmpBasicInformation"; @@ -883,6 +903,9 @@ namespace HRM.DA // item.Add("PayScaleID", "String", "Yes"); //15 item.Add("Confirmation Date", "Date", "Yes"); //17 + // auto PF membership on confirmation: the employee's own PF % (Employee.PFPercentage) + if (autopf == true) + item.Add("PF Percentage", "Double", "Yes"); item.Add("Basic Salary", "Double", "No"); //16 if (isGrossApplicable == true) item.Add("Gross Salary", "Double", "No"); //15 @@ -1077,6 +1100,13 @@ namespace HRM.DA } } + // PF membership needs the employee's own PF % (Employee.PFPercentage): the event makes the employee a + // Live PF member either through its PF_Member component, or through Confirm when autopfmembership is on + bool autopf = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership"); + bool hasPFMember = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.PF_Member); + bool hasConfirm = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.Confirm); + if (hasPFMember || (hasConfirm && autopf)) + item.Add("PF Percentage", "Double", "No"); return item; } diff --git a/HRM.DA/Service/Common/RegularDataUploadService.cs b/HRM.DA/Service/Common/RegularDataUploadService.cs index ba85660..02dbfdb 100644 --- a/HRM.DA/Service/Common/RegularDataUploadService.cs +++ b/HRM.DA/Service/Common/RegularDataUploadService.cs @@ -5221,6 +5221,9 @@ namespace HRM.DA int locationid = new MiscellaneousService().GetNextID("location", "locationid", ""); int designationid = new MiscellaneousService().GetNextID("Designation", "DesignationID", ""); int costcenterid = new MiscellaneousService().GetNextID("crg", "crgid", ""); + bool needPFPercentage = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.PF_Member) + || (ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.Confirm) + && new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership")); string description = ""; try { @@ -5657,6 +5660,23 @@ namespace HRM.DA } } + // PF membership needs the employee's own PF % (Employee.PFPercentage): the event makes the employee a + // Live PF member either through its PF_Member component, or through Confirm when autopfmembership is on + if (needPFPercentage) + { + double pfPercentage = 0; + string sPFPercentage = dr.Table.Columns.Contains("PF Percentage") ? dr["PF Percentage"].ToString().Trim() : ""; + if (sPFPercentage == "") + _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "(" + dr["Employee No"].ToString() + ")" + "PF Percentage can't be Empty")); + else if (!double.TryParse(sPFPercentage, out pfPercentage) || pfPercentage <= 0 || pfPercentage > 100) + _errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "(" + dr["Employee No"].ToString() + ")" + "PF Percentage must be greater than 0 and up to 100")); + else + { + lifeCycle.PFPercentage = pfPercentage; + description = description + " PF Percentage " + pfPercentage.ToString() + "%"; + } + } + if (lifeCycle.EffectDate.Date < DateTime.Today) { lifeCycle.IsProcessed = null; diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index 23513a2..2bd4f12 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -50,6 +50,7 @@ namespace HRM.DA oEmployee.PFMemberShiptDate = oReader.GetDateTime("pfMemberShipDt").HasValue ? oReader.GetDateTime("pfMemberShipDt").Value : DateTime.Now; + oEmployee.PFPercentage = oReader.GetDouble("PFPercentage", true, 0); oEmployee.BranchID = oReader.GetInt32("branchID"); oEmployee.AccountNo = oReader.GetString("accountNo"); oEmployee.OutPayBranchID = oReader.GetInt32("OUTPAYBRANCHID"); @@ -3459,6 +3460,10 @@ namespace HRM.DA oEmployee.Name = oEmployee.Name == "" ? "Employee-" + oEmployee.EmployeeNo : oEmployee.Name; EmployeeDA.Insert(tc, oEmployee); + // employee's own PF % (from the upload's PF Percentage column), used by SalaryCalculator.PFNEW + if (oEmployee.PFMemberType == EnumPFMembershipType.Live && oEmployee.PFPercentage > 0) + HREmployeeDA.UpdatePFPercentage(tc, oEmployee.ID, oEmployee.PFPercentage); + int id = 0; if (uploadtype == EnumRegularDataUpload.EmployeeWithBasic || !IsFinantialAprovalRequired) @@ -3534,6 +3539,8 @@ namespace HRM.DA oEmployee.EmpLifeCycle.LocationID = oEmployee.LocationID; oEmployee.EmpLifeCycle.CategoryID = oEmployee.CategoryID; oEmployee.EmpLifeCycle.IsConfirm = (oEmployee.IsConfirmed == true) ? true : false; + if (oEmployee.PFMemberType == EnumPFMembershipType.Live && oEmployee.PFPercentage > 0) + oEmployee.EmpLifeCycle.PFPercentage = oEmployee.PFPercentage; oEmployee.EmpLifeCycle.CreatedBy = oEmployee.CreatedBy; oEmployee.EmpLifeCycle.CreatedDate = oEmployee.CreatedDate; oEmployee.EmpLifeCycle.GradeSalaryAssesmentID = oEmployee.EmployeeGradeSalary.ID; diff --git a/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs b/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs index af40cb5..674c1b3 100644 --- a/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs +++ b/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs @@ -51,6 +51,8 @@ namespace HRM.DA if (oReader.GetInt32("pFMemberType").HasValue) oEmpLifeCycle.PFMemberType = (EnumPFMembershipType)oReader.GetInt32("pFMemberType").Value; else oEmpLifeCycle.PFMemberType = null; + double pfPercentage = oReader.GetDouble("PFPercentage", true, 0); + oEmpLifeCycle.PFPercentage = pfPercentage > 0 ? pfPercentage : (double?)null; oEmpLifeCycle.IsDiscontinue = oReader.GetBoolean("IsDiscontinue"); oEmpLifeCycle.IsContinue = oReader.GetBoolean("IsContinue"); oEmpLifeCycle.EmployeeID = oReader.GetInt32("EmployeeID").Value; @@ -749,6 +751,12 @@ namespace HRM.DA } } + // Logic XML confirmation/autopfmembership: confirming an employee also makes them a Live PF member + public bool IsAutoPFMembership() + { + return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership"); + } + public void UpdateApprovalStatus(List oEmpLifeCycles, int currentPayrollTypeID) { TransactionContext tc = null; @@ -943,6 +951,9 @@ namespace HRM.DA HREmployeeDA.UpdatePFInfo(tc, oEmpLifeCycle.EmployeeID, EnumPFMembershipType.Live, oEmpLifeCycle.EffectDate); + // PF membership: the employee's own PF % (used by SalaryCalculator.PFNEW) + if (oEmpLifeCycle.PFPercentage != null) + HREmployeeDA.UpdatePFPercentage(tc, oEmpLifeCycle.EmployeeID, (double)oEmpLifeCycle.PFPercentage); } } //else @@ -971,8 +982,14 @@ namespace HRM.DA // if conponent contain pf member, update employee pfMembership property property and pfMembership date. if (oEmpLifeCycle.PFMemberType != null) + { HREmployeeDA.UpdatePFInfo(tc, oEmpLifeCycle.EmployeeID, (EnumPFMembershipType)oEmpLifeCycle.PFMemberType, oEmpLifeCycle.EffectDate); + + // PF membership: the employee's own PF % (used by SalaryCalculator.PFNEW) + if (oEmpLifeCycle.PFMemberType == EnumPFMembershipType.Live && oEmpLifeCycle.PFPercentage != null) + HREmployeeDA.UpdatePFPercentage(tc, oEmpLifeCycle.EmployeeID, (double)oEmpLifeCycle.PFPercentage); + } break; case EnumEmployeeStatus.Discontinued: EmployeeDA.UpdateStatus(tc, oEmpLifeCycle.EmployeeID, oEmpLifeCycle.ID, diff --git a/HRM.DA/Service/Salary/SalaryCalculator.cs b/HRM.DA/Service/Salary/SalaryCalculator.cs index f6e1934..91e5fcd 100644 --- a/HRM.DA/Service/Salary/SalaryCalculator.cs +++ b/HRM.DA/Service/Salary/SalaryCalculator.cs @@ -125,8 +125,9 @@ namespace HRM.DA UpdateprocessStatus("Calculating Salary deduct item(unauthorized leave)...."); this.UnAuthorizeLeave(); UpdateprocessStatus("Calculating PF & CPF...."); - - this.PF(); + + //this.PF(); + this.PFNEW(); // this.OverTimeArrearProcess(); needed later //UpdateprocessStatus("Calculating Employees Income tax...."); UpdateprocessStatus("Calculating Income Tax"); @@ -692,6 +693,153 @@ namespace HRM.DA } + private void PFNEW() + { + UpdateProgressStatus(EnumProcessStatus.Start); + bool bEchoTexException = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "salary", "echotexexception"); + + bool earnedBasic = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "pf", "earnedbasic"); + // PF % comes from each employee (Employee.PFPercentage), not from SystemInformation. + //List oPfExceptions = PFException.Get(); + foreach (SalaryMonthly salary in _salaryMonthlys) + { + + UpdateProgressStatus(EnumProcessStatus.PerformStep); + SalaryMonthlyDetail pfDetail = null; + + if (salary.Employee.PFMemberType != EnumPFMembershipType.Live) continue; + double pfPercent = (salary.Employee.PFPercentage / 100); + // SalaryMonthly prvSalary = _PrvMonthsalary.FirstOrDefault(x => x.EmployeeID == salary.EmployeeID); + + var basicitem = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.Basic_Salary + && x.empid == salary.EmployeeID); + bool RcvLastMonthSalary = false; + if (basicitem != null) RcvLastMonthSalary = true; + double arrearPF = 0; + + if (earnedBasic == true) + { + if (RcvLastMonthSalary == true) + { + //SalaryMonthlyDetail prvPF = prvSalary.Details.Find(delegate (SalaryMonthlyDetail detail) + //{ + // return (detail.ItemCode == EnumSalaryItemCode.PF_Contribution + // && detail.itemGroupCode == EnumSalaryGroup.Deductions); + //}); + + var prvPF = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.PF_Contribution + && x.empid == salary.EmployeeID); + + if (salary.Employee.ConfirDate != null && salary.Employee.ConfirDate < + GlobalFunctions.FirstDateOfMonth(_processMonth) && RcvLastMonthSalary == true && prvPF == null) // if pf continue with previous month salary + { + DateTime? tepConfirm = salary.Employee.ConfirDate; + while (GlobalFunctions.LastDateOfMonth((DateTime)tepConfirm) <= this.payrollType.LastPayProcessDate) + { + EmployeeGradeSalary gradeSal = new EmployeeGradeSalaryService().GetBasicOnDateBAT(salary.EmployeeID, (DateTime)tepConfirm); + if (gradeSal == null) + { + AddProcessStatus(salary.Employee, " Employee previous salary not found during PF arrear calculation"); + break; + } + + double fractionate = 0; + if (tepConfirm == GlobalFunctions.FirstDateOfMonth((DateTime)tepConfirm)) + fractionate = 1; + if (tepConfirm == GlobalFunctions.LastDateOfMonth((DateTime)tepConfirm)) + fractionate = 30 / 29; + else fractionate = GlobalFunctions.GetFractinalOfMonth((DateTime)tepConfirm); + + arrearPF = arrearPF + ((gradeSal.BasicSalary * fractionate) * pfPercent); + + tepConfirm = GlobalFunctions.FirstDateOfMonth(((DateTime)tepConfirm).AddMonths(1)); + } + } + } + SalaryMonthlyDetail basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary + && detail.itemGroupCode == EnumSalaryGroup.Gross); }); + if (basic != null) + { + pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions, + EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution, 0, + "PF", GlobalFunctions.Round(basic.CalculatedAmount * pfPercent)); + } + + basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary + && detail.itemGroupCode == EnumSalaryGroup.Arrear); }); + if (basic != null) + { + pfDetail.CalculatedAmount = pfDetail.CalculatedAmount + GlobalFunctions.Round(basic.CalculatedAmount * pfPercent); + } + + basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary + && detail.itemGroupCode == EnumSalaryGroup.UnauthLeave); }); + if (basic != null) + { + pfDetail.CalculatedAmount = pfDetail.CalculatedAmount - GlobalFunctions.Round(basic.CalculatedAmount * pfPercent); + } + + if (pfDetail != null) + { + + if (salary.Employee.ConfirDate != null && + GlobalFunctions.LastDateOfMonth((DateTime)salary.Employee.ConfirDate) == _processMonth) + { + if ((DateTime)salary.Employee.ConfirDate != salary.Employee.JoiningDate) + { + pfDetail.CalculatedAmount = GlobalFunctions.Round(pfDetail.CalculatedAmount * + ((double)(31 - ((DateTime)salary.Employee.ConfirDate).Day) / (double)30)); + } + } + pfDetail.CalculatedAmount = pfDetail.CalculatedAmount + GlobalFunctions.Round(arrearPF); + pfDetail.ChangedAmount = pfDetail.CalculatedAmount; + + } + } + else + { + double months = 1; + if (bEchoTexException == false) + { + salaryHistory prvPF = null; + if (RcvLastMonthSalary == true) + { + prvPF = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.PF_Contribution + && x.empid == salary.EmployeeID); + } + + if (RcvLastMonthSalary == true) + { + if (prvPF == null) + months = Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.ConfirDate, _processMonth) + 1; + else + { + if (salary.ArrearGradeSalaries.Count > 0) + { + pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions, + EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution, + 0, "PF", GlobalFunctions.Round(salary.GetGrossAmount(EnumSalaryItemCode.Basic_Salary, (int)EnumSalaryItemCode.Basic_Salary) + * pfPercent)); + continue; + } + } + } + else if ((Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.JoiningDate, _processMonth) + 1) <= 2) // joining in last month + { + months = Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.JoiningDate, _processMonth) + 1; + } + } + pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions, + EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution, + 0, "PF", GlobalFunctions.Round(salary.ThisMonthBasic * pfPercent * months)); + + } + + } + UpdateProgressStatus(EnumProcessStatus.End); + + } + private void AllowanceDeduction() { diff --git a/HRM.UI/ClientApp/src/app/_models/Employee/empLifeCycle.ts b/HRM.UI/ClientApp/src/app/_models/Employee/empLifeCycle.ts index 31ebf14..468ac47 100644 --- a/HRM.UI/ClientApp/src/app/_models/Employee/empLifeCycle.ts +++ b/HRM.UI/ClientApp/src/app/_models/Employee/empLifeCycle.ts @@ -20,6 +20,7 @@ export class EmpLifeCycle extends BaseObject { departmentID: number; isConfirm?: boolean; pfMemberType?: EnumPFMembershipType; + pfPercentage?: number; employeeID: number; statusDetailID: number; grossSalary: number; diff --git a/HRM.UI/ClientApp/src/app/_models/Employee/employee.ts b/HRM.UI/ClientApp/src/app/_models/Employee/employee.ts index 18eb0f3..8b4e0eb 100644 --- a/HRM.UI/ClientApp/src/app/_models/Employee/employee.ts +++ b/HRM.UI/ClientApp/src/app/_models/Employee/employee.ts @@ -47,6 +47,7 @@ export class Employee { isShownInTaxSheet: boolean; pfMemberType: EnumPFMembershipType; pfMemberShiptDate: Date; + pfPercentage: number; branchID: number; accountNo: string; outPayBranchID: number; @@ -142,6 +143,7 @@ export class Employee { this.statusName = ''; this.isShownInTaxSheet = false; this.pfMemberType = EnumPFMembershipType.NotYetLive; + this.pfPercentage = 0; this.branchID = null; this.accountNo = ''; this.outPayBranchID = null; diff --git a/HRM.UI/ClientApp/src/app/_services/employee/empLifeCycle.service.ts b/HRM.UI/ClientApp/src/app/_services/employee/empLifeCycle.service.ts index b8f2e78..6159090 100644 --- a/HRM.UI/ClientApp/src/app/_services/employee/empLifeCycle.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/employee/empLifeCycle.service.ts @@ -33,6 +33,9 @@ export class EmpLifeCycleServices { GetByUserID() { return this.apiService.httpGet('/EmpLifeCycle/GetByUserID'); } + IsAutoPFMembership() { + return this.apiService.httpGet('/EmpLifeCycle/IsAutoPFMembership'); + } getEmpLifeCyclesByDate(param: any) { return this.apiService.httpPost('/EmpLifeCycle/getEmpLifeCyclesByDate', param); } diff --git a/HRM.UI/ClientApp/src/app/app.topbar.component.html b/HRM.UI/ClientApp/src/app/app.topbar.component.html index e25b04d..22c845c 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.html +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.html @@ -101,7 +101,7 @@ @if (payrollTypeName) {
  • - {{payrollTypeName}} + {{payrollTypeName}}@if (salaryMonth) { | {{salaryMonth | date:'MMMM-yyyy'}}}
  • } diff --git a/HRM.UI/ClientApp/src/app/app.topbar.component.scss b/HRM.UI/ClientApp/src/app/app.topbar.component.scss index 910c584..75e0522 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.scss +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.scss @@ -442,7 +442,7 @@ } .topbar-payroll-type { display: inline-block; - max-width: 260px; + max-width: 380px; padding: 4px 12px; border: 1px solid color-mix(in srgb, $color-white 35%, transparent); border-radius: 999px; @@ -456,6 +456,9 @@ text-overflow: ellipsis; cursor: default; } +.topbar-salary-month { + font-weight: 500; +} // Admin / super-user profile menu (Babylon li.user-profile > ul) drawn exactly like the ESS user // menu (.ss-dd.ss-user-dd above): white card, 14px corners, soft shadow, header row with a divider, diff --git a/HRM.UI/ClientApp/src/app/app.topbar.component.ts b/HRM.UI/ClientApp/src/app/app.topbar.component.ts index 3b5fe32..7fd0a71 100644 --- a/HRM.UI/ClientApp/src/app/app.topbar.component.ts +++ b/HRM.UI/ClientApp/src/app/app.topbar.component.ts @@ -59,6 +59,8 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { // (EnumUserType.User) logins only. Re-read whenever the stored token changes // (login, user switch, payroll-type switch, logout). payrollTypeName: string = ''; + // current salary month = the payroll type's nextPayProcessDate + salaryMonth: Date = null; private payrollTypeToken: string | null | undefined = undefined; private payrollTypeSub: Subscription | null = null; @@ -196,15 +198,18 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy { } if (!user || user.UserType != EnumUserType.User || !user.PayrollTypeID) { this.payrollTypeName = ''; + this.salaryMonth = null; return; } this.payrollTypeSub = this.authService.GetPayrollTypeByLoginID().subscribe({ next: (payrollType) => { this.payrollTypeName = payrollType?.description ?? ''; + this.salaryMonth = payrollType?.nextPayProcessDate ? new Date(payrollType.nextPayProcessDate) : null; }, error: () => { this.payrollTypeName = ''; + this.salaryMonth = null; }, }); } diff --git a/HRM.UI/ClientApp/src/app/common-interface/data-upload/data-upload.component.ts b/HRM.UI/ClientApp/src/app/common-interface/data-upload/data-upload.component.ts index 6b53f60..d6bd092 100644 --- a/HRM.UI/ClientApp/src/app/common-interface/data-upload/data-upload.component.ts +++ b/HRM.UI/ClientApp/src/app/common-interface/data-upload/data-upload.component.ts @@ -117,6 +117,8 @@ export class DataUploadComponent implements OnInit, OnDestroy { this.dataUploadColumnDefinition = undefined; this.sheetName = undefined; this.scolName = undefined; + this.htmlContent = undefined; + this.test = undefined; this.uploadErrorOrSuccess = []; this.uploadFileList = []; this.dataUploadForm = new FormGroup({}); @@ -174,6 +176,11 @@ export class DataUploadComponent implements OnInit, OnDestroy { this.dataUploadColumnDefinition = undefined; this.sheetName = undefined; this.scolName = undefined; + // the component is reused across upload types: clear the previous page's columns and selection + this.htmlContent = undefined; + this.test = undefined; + this.itemid = undefined; + this.itemidTwo = undefined; this.uploadErrorOrSuccess = []; this.uploadFileList = []; this.dataUploadForm = new FormGroup({}); @@ -236,6 +243,8 @@ export class DataUploadComponent implements OnInit, OnDestroy { name: x.description, }); }); + // events in alphabetical order + this.ItemData.sort((a, b) => (a.name || '').localeCompare(b.name || '')); }, (x) => { this.loadingPanel.ShowLoadingPanel = false; diff --git a/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html b/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html index 230108c..f7d82d2 100644 --- a/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html +++ b/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html @@ -193,11 +193,35 @@ kendoCheckBox /> -
    + +
    } + @if (this.isPFPercentage == true) { +
    + +
    +
    :
    +
    + + +
    + @if (this.isShowConfirmed != true) { +
    + } + } + + + @if (selectedTab === 0) { +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    + + + + +
    +
    Approved LFA requests awaiting payment · 0 selected · Est. LFA amount 0.00
    + + + + + + + + + + + + No records found. + +
    + } +
    + + + + @if (selectedTab === 1) { +
    +
    +
    + + +
    + +
    + + + +
    +
    + +
    +
    + + +
    + + + + +
    + +
    +
    Employees
    {{ rows.length }}
    +
    Total Basic Salary
    {{ totalBasic | number: '1.2-2' }}
    +
    Total LFA Amount (BDT)
    {{ totalAmount | number: '1.2-2' }}
    +
    Batch ID (on process)
    {{ rows.length > 0 && info ? info.nextBatchNumber : '—' }}
    +
    + + + + + Total + + + {{ rows.length }} employees + + + + + +
    {{ totalBasic | number: '1.2-2' }}
    +
    + +
    {{ totalAmount | number: '1.2-2' }}
    +
    + + + + + + No employees yet. Upload the Excel file. + +
    + + @if (issues.length > 0) { +
    + {{ issues.length }} error(s) found in the uploaded file. These rows are not in the list. + +
    + } + +
    Uploaded file columns: Employee ID, Name. Amounts in BDT.
    +
    + } +
    + + + + @if (selectedTab === 2) { +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    + +
    +
    +
    + + +
    + + + +
    + + + + + + + + + + +
    {{ historyTotalBasic | number: '1.2-2' }}
    +
    + +
    {{ historyTotalAmount | number: '1.2-2' }}
    +
    + + + {{ dataItem.statusText }} + + + No records found. + +
    +
    {{ historySummary }}
    +
    + } +
    +
    + +@if (showConfirm) { +
    + +

    You are about to process LFA payment for {{ rows.length }} employee(s). This will create a new payment batch.

    + + + + + + +
    Batch ID{{ info ? info.nextBatchNumber : '' }}
    Payment Date{{ paymentDate | date: 'dd-MMM-yyyy' }}
    Total LFA AmountBDT {{ totalAmount | number: '1.2-2' }}
    + + + + +
    +
    +} + + +@if (showIssues) { +
    + + + + {{ dataItem.rowNo > 0 ? dataItem.rowNo : 'File' }} + + + + + No errors. + + + + + + + +
    +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss index e69de29..b6a1ee1 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss @@ -0,0 +1,146 @@ +/* LFA Payment: layout only; colours are the theme's --gh-* variables */ +.lfa-month { + padding: 0 4px 8px; + color: var(--gh-lk); +} + +.lfa-tab { + display: flex; + flex-direction: column; + gap: 14px; + padding: 8px 2px; +} + +.lfa-toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px; +} + +.lfa-field { + display: flex; + flex-direction: column; + gap: 4px; + width: 180px; + + label { + font-size: 12px; + font-weight: 600; + color: var(--gh-muted); + } +} + +.lfa-field--wide { + width: 280px; +} + +.lfa-field--remarks { + width: 360px; +} + +.lfa-required { + color: var(--gh-dn); +} + +.lfa-spacer { + flex: 1 1 auto; +} + +.lfa-upload { + display: flex; + flex: 1 1 520px; + align-items: center; + gap: 6px; +} + +.lfa-upload__file { + flex: 1 1 auto; + min-width: 0; + max-width: 520px; +} + +.lfa-info, +.lfa-note { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; +} + +.lfa-stat { + padding: 12px 14px; + border: 1px solid var(--gh-bo); + border-radius: 6px; + background: var(--gh-tb); +} + +.lfa-stat__key { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-stat__value { + margin-top: 4px; + font-size: 18px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-issues__head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 6px; + font-weight: 600; + color: var(--gh-dn); +} + +.lfa-right { + text-align: right; +} + +.lfa-badge { + display: inline-block; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + color: var(--gh-warn); + background: color-mix(in srgb, var(--gh-warn) 15%, transparent); +} + +.lfa-badge--paid { + color: var(--gh-ok); + background: color-mix(in srgb, var(--gh-ok) 15%, transparent); +} + +.lfa-badge--failed { + color: var(--gh-dn); + background: color-mix(in srgb, var(--gh-dn) 15%, transparent); +} + +.lfa-confirm { + width: 100%; + + td { + padding: 4px 0; + } + + td:last-child { + text-align: right; + font-weight: 600; + } +} + +@media (max-width: 640px) { + .lfa-field, + .lfa-field--wide, + .lfa-field--remarks { + width: 100%; + } +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts index 013e9fb..42ba40e 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts @@ -1,6 +1,20 @@ -import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { Component, ElementRef, OnInit, ViewChild, ChangeDetectionStrategy } from '@angular/core'; +import * as fileSaver from 'file-saver'; +import { ExcelExportData } from '@progress/kendo-angular-excel-export'; +import { Observable } from 'rxjs'; import { ApiService } from '../../app.api.service'; +import { HRMNotificationService } from '../../app.notification.service'; +import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service'; +import { LFAService } from '../../_services/payroll/lfa.service'; +import { + EnumLFAPaymentStatus, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentInput, LFAPaymentIssue, + LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentRow +} from '../../_models/Payroll/lfaPayment'; +/** + * LFA Payment: LFA Request (design only for now), New LFA Payment (Excel upload → calculated grid → Process + * Payment) and Payment History. Every amount comes from the server, which calculates again on process. + */ @Component({ selector: 'app-lfa-payment', templateUrl: './lfa-payment.component.html', @@ -10,10 +24,419 @@ import { ApiService } from '../../app.api.service'; }) export class LfaPaymentComponent implements OnInit { - constructor(public apiService: ApiService) { + @ViewChild('fileInput', { static: false }) fileInput: ElementRef; + + readonly maxFileSizeMB = 10; + readonly allDepartments = 'All departments'; + readonly allStatuses = 'All statuses'; + + selectedTab = 0; + info: LFAPaymentInfo = null; + + // ── LFA Request (design only; no data yet) ── + requests: any[] = []; + requestSearch = ''; + requestDepartment = this.allDepartments; + requestFrom: Date = null; + requestTo: Date = null; + + // ── New LFA Payment ── + paymentDate: Date = this.today(); + remarks = ''; + selectedFile: File = null; // picked, not uploaded yet + uploadedFile: File = null; // the file the list was read from + rows: LFAPaymentRow[] = []; + issues: LFAPaymentIssue[] = []; + totalBasic = 0; + totalAmount = 0; + isBusy = false; + showConfirm = false; + showIssues = false; + /** Employees taken out of the list; they stay out when the file is calculated again. */ + private removedEmployeeNos: string[] = []; + + // ── Payment History ── + historyFrom: Date = new Date(new Date().getFullYear(), 0, 1); + historyTo: Date = this.today(); + historySearch = ''; + historyStatus = this.allStatuses; + historyDepartment = this.allDepartments; + historyStatuses = [this.allStatuses, 'Pending', 'Paid', 'Failed']; + historyDepartments = [this.allDepartments]; + history: LFAPaymentHistory[] = []; + historyRows: LFAPaymentHistory[] = []; + historyTotalBasic = 0; + historyTotalAmount = 0; + historySummary = ''; + + constructor(public apiService: ApiService, + public notificationService: HRMNotificationService, + public loadingPanel: loadingPanelService, + private lfaService: LFAService) { this.apiService.selectedMenuName = 'LFA Payment'; } ngOnInit() { + this.loadInfo(); + } + + private loadInfo() { + this.start(); + this.lfaService.getPaymentInfo().subscribe({ + next: (resp) => { + this.stop(); + this.info = resp; + }, + error: (err) => this.fail(err, 'Could not read the current salary month.') + }); + } + + onTabSelect(index: number) { + this.selectedTab = index; + this.selectedFile = null; // the file input is created again with its tab + if (index === 2) { + this.loadHistory(); + } + } + + // ── New LFA Payment: upload and calculate ─────────────────────── + + downloadTemplate() { + this.start(); + this.lfaService.downloadTemplate().subscribe({ + next: (file) => { + this.stop(); + fileSaver.saveAs(file, 'LFA-Payment-Template.xlsx'); + }, + error: (err) => this.fail(err, 'Could not download the template.') + }); + } + + /** The same file can be picked again after a correction. */ + clearSelectedFile() { + this.selectedFile = null; + if (this.fileInput) { + this.fileInput.nativeElement.value = ''; + } + } + + selectFile(event: Event) { + const input = event.target as HTMLInputElement; + this.selectedFile = input.files && input.files.length > 0 ? input.files[0] : null; + } + + uploadFile() { + if (!this.paymentDate) { + this.notificationService.showWarning('Please select the Payment Date first.'); + return; + } + if (!this.selectedFile) { + this.notificationService.showWarning('Please choose a file first.'); + return; + } + this.upload(this.selectedFile); + } + + private upload(file: File) { + if (!file.name.toLowerCase().endsWith('.xlsx')) { + this.notificationService.showError('Only .xlsx files are allowed. Please use the downloaded template.'); + return; + } + if (file.size > this.maxFileSizeMB * 1024 * 1024) { + this.notificationService.showError('The file is larger than ' + this.maxFileSizeMB + ' MB.'); + return; + } + this.uploadedFile = file; + this.removedEmployeeNos = []; + this.calculate(true); + } + + /** The Payment Date decides who has completed 6 months. */ + onPaymentInfoChange() { + if (this.paymentDate && (this.uploadedFile || this.rows.length > 0)) { + this.calculate(false); + } + } + + private calculate(isUpload: boolean) { + const date = this.dateText(this.paymentDate); + const call: Observable = this.uploadedFile + ? this.lfaService.readUpload(this.uploadedFile, date) + : this.lfaService.calculatePayment(this.request()); + this.start(); + call.subscribe({ + next: (resp) => { + this.stop(); + this.applyResult(resp); + if (isUpload) { + this.showUploadMessage(); + } + }, + error: (err) => { + this.setRows([]); + this.issues = []; + this.fail(err, 'Could not calculate the LFA. Please upload the file again.'); + } + }); + } + + private showUploadMessage() { + if (this.rows.length === 0) { + this.notificationService.showError('No employee of the file can be paid. Please check the error list.'); + } else if (this.issues.length > 0) { + this.notificationService.showWarning(this.rows.length + ' employee(s) loaded. Some rows have errors; please check the error list.'); + } else { + this.notificationService.showSuccess(this.rows.length + ' employee(s) loaded.'); + } + } + + private applyResult(result: LFAPaymentReadResult) { + this.issues = (result.issues || []).filter(x => !this.isRemoved(x.employeeNo)); + this.showIssues = this.issues.length > 0; // every validation problem is listed in the error dialog + this.setRows((result.rows || []).filter(x => !this.isRemoved(x.employeeNo)).map(x => ({ + ...x, + joiningDate: this.toDate(x.joiningDate), + confirmationDate: this.toDate(x.confirmationDate), + paymentDate: this.toDate(x.paymentDate) + }))); + } + + private setRows(rows: LFAPaymentRow[]) { + this.rows = rows; + this.totalBasic = this.sum(rows, x => x.basicSalary); + this.totalAmount = this.sum(rows, x => x.amount); + } + + removeRow(row: LFAPaymentRow) { + this.removedEmployeeNos.push(row.employeeNo); + this.setRows(this.rows.filter(x => x !== row)); + } + + private isRemoved(employeeNo: string): boolean { + return this.removedEmployeeNos.indexOf(employeeNo) >= 0; + } + + clear() { + if (this.rows.length === 0 && this.issues.length === 0) { + this.resetPayment(); + return; + } + this.notificationService.showActiveConfirm('Confirmation', 'Clear the payment list?').then((isConfirmed) => { + if (isConfirmed) { + this.resetPayment(); + } + }); + } + + private resetPayment() { + this.clearSelectedFile(); + this.uploadedFile = null; + this.removedEmployeeNos = []; + this.issues = []; + this.showIssues = false; + this.remarks = ''; + this.setRows([]); + } + + allPaymentRows = (): ExcelExportData => ({ data: this.rows }); + allIssues = (): ExcelExportData => ({ data: this.issues }); + + // ── New LFA Payment: process ──────────────────────────────────── + + confirmProcess() { + if (!this.paymentDate) { + this.notificationService.showWarning('Payment Date is required.'); + return; + } + if (this.rows.length === 0) { + this.notificationService.showWarning('Add at least one employee.'); + return; + } + this.showConfirm = true; + } + + process() { + if (this.isBusy) { + return; + } + this.start(); + this.lfaService.processPayment(this.request()).subscribe({ + next: (resp: LFAPaymentProcessResult) => { + this.stop(); + this.showConfirm = false; + if (!resp.saved) { + if (resp.validation) { + this.applyResult(resp.validation); + } + this.notificationService.showError(resp.message); + return; + } + this.notificationService.showSuccess(resp.message); + this.resetPayment(); + this.includeInHistory(this.paymentDate); + this.loadInfo(); + this.onTabSelect(2); + }, + error: (err) => { + this.showConfirm = false; + this.fail(err, 'Nothing was saved. Please try again.'); + } + }); + } + + private request(): LFAPaymentRequest { + return { + paymentDate: this.dateText(this.paymentDate), + remarks: this.remarks, + rows: this.rows.map((x): LFAPaymentInput => ({ + rowNo: x.rowNo, + employeeNo: x.employeeNo + })), + expectedTotal: this.totalAmount + }; + } + + // ── Payment History ───────────────────────────────────────────── + + loadHistory() { + if (!this.historyFrom || !this.historyTo) { + this.notificationService.showWarning('Start Date and End Date are required.'); + return; + } + if (this.historyFrom > this.historyTo) { + this.notificationService.showWarning('Start Date cannot be after End Date.'); + return; + } + this.start(); + this.lfaService.getPaymentHistory(this.dateText(this.historyFrom), this.dateText(this.historyTo)).subscribe({ + next: (resp) => { + this.stop(); + this.history = (resp || []).map(x => ({ + ...x, + paymentDate: this.toDate(x.paymentDate), + joiningDate: this.toDate(x.joiningDate), + statusText: EnumLFAPaymentStatus[x.paymentStatus] + })); + this.historyDepartments = [this.allDepartments].concat( + Array.from(new Set(this.history.map(x => x.departmentName).filter(x => !!x))).sort()); + if (this.historyDepartments.indexOf(this.historyDepartment) < 0) { + this.historyDepartment = this.allDepartments; + } + this.filterHistory(); + }, + error: (err) => this.fail(err, 'Could not load the payment history.') + }); + } + + filterHistory() { + const search = (this.historySearch || '').trim().toLowerCase(); + this.historyRows = this.history.filter(x => + (this.historyStatus === this.allStatuses || x.statusText === this.historyStatus) + && (this.historyDepartment === this.allDepartments || x.departmentName === this.historyDepartment) + && (!search || [x.batchNumber, x.employeeNo, x.name, x.designationName, x.departmentName] + .some(v => (v || '').toLowerCase().indexOf(search) >= 0))); + this.historyTotalBasic = this.sum(this.historyRows, x => x.basicSalary); + this.historyTotalAmount = this.sum(this.historyRows, x => x.amount); + const count = (status: EnumLFAPaymentStatus) => this.historyRows.filter(x => x.paymentStatus === status).length; + this.historySummary = 'Total ' + this.historyRows.length + ' records · ' + + new Set(this.historyRows.map(x => x.batchNumber)).size + ' batch(es) · Paid ' + count(EnumLFAPaymentStatus.Paid) + + ' · Pending ' + count(EnumLFAPaymentStatus.Pending) + ' · Failed ' + count(EnumLFAPaymentStatus.Failed); + } + + allHistoryRows = (): ExcelExportData => ({ data: this.historyRows }); + + printHistory() { + if (this.historyRows.length === 0) { + this.notificationService.showWarning('Nothing to print.'); + return; + } + const w = window.open('', '_blank'); + if (!w) { + this.notificationService.showWarning('Please allow pop-ups to print.'); + return; + } + const money = (n: number) => this.money(n); + const cells = (values: any[], tag: string) => values.map(v => '<' + tag + '>' + this.escape(v) + '').join(''); + const body = this.historyRows.map(x => '' + cells([x.batchNumber, this.displayDate(x.paymentDate), x.employeeNo, x.name, + x.designationName, x.departmentName, this.displayDate(x.joiningDate), money(x.basicSalary), money(x.amount), + x.statusText], 'td') + '').join(''); + w.document.write('LFA Payment History' + + '

    LFA Payment History (' + this.displayDate(this.historyFrom) + ' - ' + this.displayDate(this.historyTo) + ')

    ' + + cells(['Batch ID', 'Payment Date', 'Employee ID', 'Name', 'Designation', 'Department', 'Joining Date', 'Basic Salary', + 'LFA Amount', 'Payment Status'], 'th') + + '' + body + '

    ' + this.escape(this.historySummary) + ' · LFA Amount ' + + money(this.historyTotalAmount) + '

    '); + w.document.close(); + w.focus(); + w.print(); + } + + /** A batch just processed must be inside the range the history shows. */ + private includeInHistory(date: Date) { + if (date < this.historyFrom) { + this.historyFrom = date; + } + if (date > this.historyTo) { + this.historyTo = date; + } + } + + // ── LFA Request (design only) ─────────────────────────────────── + + resetRequestFilter() { + this.requestSearch = ''; + this.requestDepartment = this.allDepartments; + this.requestFrom = null; + this.requestTo = null; + } + + // ── Helpers ───────────────────────────────────────────────────── + + private start() { + this.isBusy = true; + this.loadingPanel.ShowLoadingPanel = true; + } + + private stop() { + this.isBusy = false; + this.loadingPanel.ShowLoadingPanel = false; + } + + private fail(err: any, fallback: string) { + this.stop(); + // httpPostBlob gives the server's text itself, the other calls an HttpErrorResponse + const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : ''; + this.notificationService.showError(text || fallback); + } + + private today(): Date { + const now = new Date(); + return new Date(now.getFullYear(), now.getMonth(), now.getDate()); + } + + private toDate(value: any): Date { + return value ? new Date(value) : null; + } + + /** yyyy-MM-dd of the picked day, whatever the browser's time zone. */ + private dateText(date: Date): string { + return date ? this.apiService.datepipe.transform(date, 'yyyy-MM-dd') : null; + } + + private displayDate(date: Date): string { + return date ? this.apiService.datepipe.transform(date, 'dd-MMM-yyyy') : ''; + } + + private money(value: number): string { + return (value || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + } + + private escape(value: any): string { + return String(value ?? '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + } + + private sum(items: T[], value: (item: T) => number): number { + return Math.round(items.reduce((total, x) => total + (value(x) || 0), 0) * 100) / 100; } } diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts index 005e5b2..152ac29 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts @@ -1,9 +1,17 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; import { CardModule } from '@progress/kendo-angular-layout'; +import { ExcelModule, GridModule } from '@progress/kendo-angular-grid'; +import { ButtonsModule } from '@progress/kendo-angular-buttons'; +import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; +import { DatePickerModule } from '@progress/kendo-angular-dateinputs'; +import { TextBoxModule } from '@progress/kendo-angular-inputs'; +import { DialogsModule } from '@progress/kendo-angular-dialog'; import { PayrollLfaRoutingModule } from './payroll-lfa-routing.module'; import { LoadingPanelModule } from '../hrm-loding panel/loading-panel.module'; +import { TabViewCompatModule } from '../custom-components/tab-view-compat/tab-view-compat'; import { LfaPaymentComponent } from './lfa-payment/lfa-payment.component'; import { LfaPaymentUndoComponent } from './lfa-payment-undo/lfa-payment-undo.component'; import { LfaPaymentApprovalComponent } from './lfa-payment-approval/lfa-payment-approval.component'; @@ -19,8 +27,17 @@ import { LfaBankAdviceComponent } from './lfa-bank-advice/lfa-bank-advice.compon imports: [ CommonModule, PayrollLfaRoutingModule, + FormsModule, LoadingPanelModule, - CardModule + CardModule, + TabViewCompatModule, + GridModule, + ExcelModule, + ButtonsModule, + DropDownListModule, + DatePickerModule, + TextBoxModule, + DialogsModule ] }) export class PayrollLfaModule { } diff --git a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs index 7ca7791..f188c22 100644 --- a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs +++ b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs @@ -366,6 +366,9 @@ namespace HRM.UI.Configuration.DI services.AddTransient(); services.AddTransient(); + //LFA + services.AddTransient(); + //Fund services.AddTransient(); services.AddTransient(); diff --git a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs index 926f32e..9a73017 100644 --- a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs +++ b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs @@ -25,13 +25,15 @@ namespace HRM.UI.Controllers.Payroll private readonly IEmployeePhotoBulkUploadService _employeePhotoBulkUploadService; private readonly ICacheManager _cashManager; private readonly IBonusProcessService _bonusProcessService; + private readonly ILFAPaymentService _lfaPaymentService; public DataUploadController(IDataUploadColumnDefinition columnDefination, IEmployeeBulkUploadService employeeBulkUploadService, ISalaryMasterBulkUploadService salaryMasterBulkUploadService, IEmployeePhotoBulkUploadService employeePhotoBulkUploadService, ICacheManager cashManager, - IBonusProcessService bonusProcessService) + IBonusProcessService bonusProcessService, + ILFAPaymentService lfaPaymentService) { this._columnDefination = columnDefination; this._employeeBulkUploadService = employeeBulkUploadService; @@ -39,6 +41,7 @@ namespace HRM.UI.Controllers.Payroll this._employeePhotoBulkUploadService = employeePhotoBulkUploadService; this._cashManager = cashManager; this._bonusProcessService = bonusProcessService; + this._lfaPaymentService = lfaPaymentService; } // loan @@ -586,6 +589,60 @@ namespace HRM.UI.Controllers.Payroll #endregion + #region LFA Payment Upload + + /// The empty LFA payment workbook: Employee ID and Name. + [HttpGet("lfa-payment-upload-template")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult GetLFAPaymentUploadTemplate() + { + try + { + return File(this._lfaPaymentService.GetUploadTemplate(), + LFAPaymentUploadTemplate.ContentType, LFAPaymentUploadTemplate.FileName); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// + /// Reads a filled LFA payment workbook (multipart form: first file, plus "paymentDate") + /// and returns the calculated employees and every problem. Nothing is saved. + /// + [HttpPost("lfa-payment-upload-read")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult ReadLFAPaymentUpload() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment."); + } + IFormFile file = Request.Form.Files.Count > 0 ? Request.Form.Files[0] : null; + DateTime paymentDate; + if (!DateTime.TryParse(Request.Form["paymentDate"].FirstOrDefault(), out paymentDate)) + { + return BadRequest("Payment Date is required."); + } + + try + { + using (Stream stream = file == null ? null : file.OpenReadStream()) + { + return Ok(this._lfaPaymentService.ReadUpload(stream, file == null ? null : file.FileName, + file == null ? 0 : file.Length, paymentDate, this.CurrentPayrollTypeID(0))); + } + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + #endregion + /// The "salaryMonth" form field (the month picked on the page) as the last date of that month. private bool TryGetPostedSalaryMonth(out DateTime salaryMonth) { diff --git a/HRM.UI/Controllers/Payroll/LFAController.cs b/HRM.UI/Controllers/Payroll/LFAController.cs new file mode 100644 index 0000000..947c83a --- /dev/null +++ b/HRM.UI/Controllers/Payroll/LFAController.cs @@ -0,0 +1,104 @@ +using System; +using HRM.BO; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace HRM.UI.Controllers.Payroll +{ + /// + /// Core Payroll > LFA. The Excel template and upload are in DataUploadController, with every other uploader. + /// + [Route("api/lfa")] + [Authorize] + [ApiController] + public class LFAController : ControllerBase + { + private readonly ILFAPaymentService _lfaPaymentService; + + public LFAController(ILFAPaymentService lfaPaymentService) + { + this._lfaPaymentService = lfaPaymentService; + } + + /// The current salary month and the next batch number. + [HttpGet("getPaymentInfo")] + public ActionResult GetPaymentInfo() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetInfo(currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// Calculates the rows again; nothing is saved. + [HttpPost("calculatePayment")] + public ActionResult CalculatePayment(LFAPaymentRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.Calculate(request, currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// Saves the rows as a new batch, all or nothing. The payroll type and user come from the token. + [HttpPost("processPayment")] + public ActionResult ProcessPayment(LFAPaymentRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.Process(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpGet("getPaymentHistory/{fromDate}/{toDate}")] + public ActionResult GetPaymentHistory(DateTime fromDate, DateTime toDate) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetHistory(fromDate, toDate, currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + private ActionResult NotAllowed() + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment."); + } + } +} diff --git a/LFA_DB_Changes.sql b/LFA_DB_Changes.sql new file mode 100644 index 0000000..d4cb0a5 --- /dev/null +++ b/LFA_DB_Changes.sql @@ -0,0 +1,146 @@ +/* ===================================================================== + LFA_DB_Changes.sql + + Leave Fare Assistance (Core Payroll > LFA). Three tables: + + dbo.LFARequest who asked for LFA, for which leave (LFA Request tab) + dbo.LFAPayment one payment batch (like SalaryProcess) + dbo.LFAPaymentDetail one employee of a batch (like SalaryMonthly) + + - Part 0 DROPS the three tables, Parts 1-3 create them again. The drop is + refused, and nothing runs, when any of the tables already holds rows. + - LFAYear is a DATETIME in all three tables: the last date of the calendar + year the LFA is for (2026 = 31-Dec-2026), as SalaryMonth is the last date + of its month. + - IDs are generated by the application (tc.GenerateID), no IDENTITY. + - A detail row is a snapshot: grade, department, bank account and basic are + kept as they were when the batch was processed. + - Columns that point to existing tables (EMPLOYEE, DEPARTMENT, GRADES, CRG, + BRANCHES, LEAVEENTRY ...) have no foreign key, as in Calendar_DB_Changes.sql. + + Run order: once per database, together with the LFA code. + ===================================================================== */ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO + +/* ---------- 0. Drop (child table first) ---------- */ +IF EXISTS (SELECT 1 FROM sys.partitions + WHERE object_id IN (OBJECT_ID(N'dbo.LFAPaymentDetail', N'U'), OBJECT_ID(N'dbo.LFAPayment', N'U'), OBJECT_ID(N'dbo.LFARequest', N'U')) + AND index_id IN (0, 1) AND rows > 0) +BEGIN + RAISERROR('The LFA tables hold data. Nothing was dropped or created. Back up and clear them first.', 16, 1); + SET NOEXEC ON; -- skips the rest of this script +END +GO +DROP TABLE IF EXISTS dbo.LFAPaymentDetail; +DROP TABLE IF EXISTS dbo.LFAPayment; +DROP TABLE IF EXISTS dbo.LFARequest; +GO + +/* ---------- 1. dbo.LFARequest ---------- */ +CREATE TABLE dbo.LFARequest ( + LFARequestID INT NOT NULL, + PayrollTypeID INT NOT NULL, + EmployeeID INT NOT NULL, + LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for + LeaveEntryID INT NULL, -- LEAVEENTRY.TRANID of the LFA leave + RequestDate DATETIME NOT NULL, + LeaveFromDate DATETIME NOT NULL, -- LFA Start Date + LeaveToDate DATETIME NOT NULL, -- LFA End Date + LeaveDays DECIMAL(9, 2) NOT NULL, + Remarks NVARCHAR(500) NULL, + Status TINYINT NOT NULL CONSTRAINT DF_LFARequest_Status DEFAULT (1), -- 1 Pending, 2 Approved, 3 Rejected, 4 Cancelled + WFStatus INT NULL, -- enumwfStatus; NULL = not submitted + CreatedBy INT NOT NULL, + CreationDate DATETIME NOT NULL, + ModifiedBy INT NULL, + ModifiedDate DATETIME NULL, + + CONSTRAINT PK_LFARequest PRIMARY KEY (LFARequestID), + CONSTRAINT CK_LFARequest_Dates CHECK (LeaveToDate >= LeaveFromDate), + CONSTRAINT CK_LFARequest_Status CHECK (Status IN (1, 2, 3, 4)) +); +GO +/* one open or approved request per employee per calendar year */ +CREATE UNIQUE INDEX UX_LFARequest_EmployeeYear ON dbo.LFARequest (EmployeeID, LFAYear) WHERE Status IN (1, 2); +GO +/* LFA Request tab: approved requests of a payroll type */ +CREATE INDEX IX_LFARequest_List ON dbo.LFARequest (PayrollTypeID, Status, LeaveFromDate); +GO + +/* ---------- 2. dbo.LFAPayment ---------- */ +CREATE TABLE dbo.LFAPayment ( + LFAPaymentID INT NOT NULL, + BatchNumber VARCHAR(30) NOT NULL, -- LFA-2026-001 + PayrollTypeID INT NOT NULL, + SalaryMonth DATETIME NOT NULL, -- last date of PAYROLLTYPE.NEXTPAYPROCESSDATE's month + LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for + PaymentDate DATETIME NOT NULL, + Remarks NVARCHAR(500) NULL, + IsTaxUpdated BIT NOT NULL CONSTRAINT DF_LFAPayment_IsTaxUpdated DEFAULT (0), -- 1 = the batch is already in the income tax data + WFStatus INT NULL, -- enumwfStatus; NULL = not submitted + ApprovedBy INT NULL, + ApprovedDate DATETIME NULL, + CreatedBy INT NOT NULL, + CreationDate DATETIME NOT NULL, + ModifiedBy INT NULL, + ModifiedDate DATETIME NULL, + + CONSTRAINT PK_LFAPayment PRIMARY KEY (LFAPaymentID), + CONSTRAINT UQ_LFAPayment_BatchNumber UNIQUE (PayrollTypeID, BatchNumber) +); +GO +/* Payment, Undo and Approval pages: the batches of a payroll type and month */ +CREATE INDEX IX_LFAPayment_Month ON dbo.LFAPayment (PayrollTypeID, SalaryMonth) INCLUDE (WFStatus); +GO +/* Payment History tab: date range */ +CREATE INDEX IX_LFAPayment_PaymentDate ON dbo.LFAPayment (PayrollTypeID, PaymentDate); +GO + +/* ---------- 3. dbo.LFAPaymentDetail ---------- */ +CREATE TABLE dbo.LFAPaymentDetail ( + LFAPaymentDetailID INT NOT NULL, + LFAPaymentID INT NOT NULL, + EmployeeID INT NOT NULL, + LFAYear DATETIME NOT NULL, -- same value as LFAPayment.LFAYear + + /* employee snapshot */ + JoiningDate DATETIME NOT NULL, + ConfirmationDate DATETIME NULL, + GradeID INT NULL, + DesignationID INT NULL, + DepartmentID INT NULL, + CostCenterID INT NULL, -- CRG.CRGID + BranchID INT NULL, -- bank branch, for Bank Advice + AccountNo VARCHAR(50) NULL, + + /* calculation */ + JoiningBasic MONEY NULL, + LastDecBasic MONEY NULL, -- basic as of 31 Dec of the preceding year; NULL = joined in LFAYear + BasicSalary MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_BasicSalary DEFAULT (0), -- basic the LFA was calculated on + CalculatedAmount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_CalculatedAmount DEFAULT (0), -- before rounding + Amount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_Amount DEFAULT (0), -- LFA amount to pay + + Remarks NVARCHAR(500) NULL, + PaymentStatus TINYINT NOT NULL CONSTRAINT DF_LFAPayDtl_PaymentStatus DEFAULT (1), -- 1 Pending, 2 Paid, 3 Failed + CreatedBy INT NOT NULL, + CreationDate DATETIME NOT NULL, + ModifiedBy INT NULL, + ModifiedDate DATETIME NULL, + + CONSTRAINT PK_LFAPaymentDetail PRIMARY KEY (LFAPaymentDetailID), + CONSTRAINT FK_LFAPayDtl_Payment FOREIGN KEY (LFAPaymentID) REFERENCES dbo.LFAPayment (LFAPaymentID), + CONSTRAINT CK_LFAPayDtl_Amount CHECK (Amount >= 0), + CONSTRAINT CK_LFAPayDtl_PaymentStatus CHECK (PaymentStatus IN (1, 2, 3)) +); +GO +/* policy: LFA once in a calendar year (Undo deletes the rows, which frees the employee again) */ +CREATE UNIQUE INDEX UX_LFAPayDtl_EmployeeYear ON dbo.LFAPaymentDetail (EmployeeID, LFAYear); +GO +/* the rows of one batch */ +CREATE INDEX IX_LFAPayDtl_Payment ON dbo.LFAPaymentDetail (LFAPaymentID); +GO + +SET NOEXEC OFF; +GO From 7fc90dd86427d2bee29716f5102099ebe5101083 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Thu, 26 Nov 2026 11:35:51 +0600 Subject: [PATCH 4/9] LFA Calculator --- HRM.DA/DA/LFA/LFAPaymentDA.cs | 24 ++++++++++++++--- HRM.DA/Service/LFA/LFACalculator.cs | 14 +++++++--- HRM.DA/Service/LFA/LFAPaymentService.cs | 35 ++++++++++++++++--------- LFA_DB_Changes.sql | 12 +++++---- 4 files changed, 60 insertions(+), 25 deletions(-) diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs index b79d62d..8a10b8a 100644 --- a/HRM.DA/DA/LFA/LFAPaymentDA.cs +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -75,7 +75,9 @@ namespace HRM.DA /// internal static IDataReader GetEmployees(TransactionContext tc, List employeeNos, DateTime lfaYear) { - DateTime lastDec = new DateTime(lfaYear.Year - 1, 12, 31); + // LFAYear is a month end, so "this year" / "last year" are date ranges of the calendar year + DateTime yearStart = new DateTime(lfaYear.Year, 1, 1); + DateTime lastYearStart = yearStart.AddYears(-1); string sql = SQLParser.MakeSQL(@"SET NOCOUNT ON; IF OBJECT_ID('tempdb..#lfaEmp') IS NOT NULL DROP TABLE #lfaEmp; @@ -109,12 +111,13 @@ namespace HRM.DA ON cc.EMPLOYEEID = e.EMPLOYEEID AND cc.RowNo = 1 LEFT JOIN (SELECT dt.EmployeeID, p.BatchNumber FROM LFAPaymentDetail dt INNER JOIN LFAPayment p ON p.LFAPaymentID = dt.LFAPaymentID - WHERE dt.LFAYear = %d) py ON py.EmployeeID = e.EMPLOYEEID - LEFT JOIN LFAPaymentDetail pv ON pv.EmployeeID = e.EMPLOYEEID AND pv.LFAYear = %d + WHERE dt.LFAYear >= %d AND dt.LFAYear < %d) py ON py.EmployeeID = e.EMPLOYEEID + OUTER APPLY (SELECT TOP 1 x.LFAPaymentDetailID FROM LFAPaymentDetail x + WHERE x.EmployeeID = e.EMPLOYEEID AND x.LFAYear >= %d AND x.LFAYear < %d) pv ORDER BY e.EMPLOYEENO; DROP TABLE #lfaEmp;", - true, lfaYear, lastDec); + true, yearStart, yearStart.AddYears(1), lastYearStart, yearStart); // must be a SqlParameter[]: Ease.Core casts the array to SqlParameter[] SqlParameter[] parameters = @@ -124,6 +127,19 @@ namespace HRM.DA return tc.ExecuteReader(CommandType.Text, sql, parameters); } + /// + /// Every employee's basic on a date: the latest salary record that starts before it. A copy of + /// EmployeeGradeSalaryDA.GetBasicOnDate, kept for LFA so that it runs in the LFA transaction. + /// + internal static IDataReader GetBasicOnDate(TransactionContext tc, DateTime effectdate) + { + return tc.ExecuteReader(@"SELECT g.EMPLOYEEID, g.BASICSALARY FROM GRADESALARYASSIGNMENT g + where g.empGradeSalaryid = (select Max(mx.empGradeSalaryid) from GRADESALARYASSIGNMENT mx + where g.EMPLOYEEID = mx.EMPLOYEEID and mx.EFFECTDATE < %d ) + order by g.EMPLOYEEID ", + effectdate); + } + /// Payment History tab: every paid employee of the payment date range. internal static IDataReader GetHistory(TransactionContext tc, DateTime fromDate, DateTime toDate, int payrollTypeID) { diff --git a/HRM.DA/Service/LFA/LFACalculator.cs b/HRM.DA/Service/LFA/LFACalculator.cs index 7c3490e..b42f1d3 100644 --- a/HRM.DA/Service/LFA/LFACalculator.cs +++ b/HRM.DA/Service/LFA/LFACalculator.cs @@ -12,6 +12,8 @@ namespace HRM.DA /// - Joined in the LFA year: joining basic, pro-rata from the joining date to 31 December. /// - Joined in the preceding year and had not completed 6 months by its 31 December: that year's /// pro-rata on the joining basic, plus the current year's full amount. + /// lfaYear is the last date of the payment date's month; the year it falls in is the LFA year, and every + /// pro-rata runs to 31 December of that year. /// internal static class LFACalculator { @@ -37,8 +39,8 @@ namespace HRM.DA problems.Add("Employee is not confirmed."); DateTime eligibleFrom = employee.JoiningDate.Date.AddMonths(ServiceMonths); - if (employee.JoiningDate.Date > lfaYear) - problems.Add("Employee joined after " + DateText(lfaYear) + "."); + if (employee.JoiningDate.Date > YearEnd(lfaYear)) + problems.Add("Employee joined after " + DateText(YearEnd(lfaYear)) + "."); else if (eligibleFrom > paymentDate.Date) problems.Add("6 months of service will be completed on " + DateText(eligibleFrom) + ", after the payment date."); @@ -58,7 +60,7 @@ namespace HRM.DA { bool joinedInYear = IsJoinedInYear(employee, lfaYear); double currentYear = joinedInYear - ? ProRata(employee.JoiningBasic, employee.JoiningDate, lfaYear) + ? ProRata(employee.JoiningBasic, employee.JoiningDate, YearEnd(lfaYear)) : employee.LastDecBasic; double prevYear = HasPreviousYear(employee, lfaYear) ? ProRata(employee.JoiningBasic, employee.JoiningDate, LastDec(lfaYear)) @@ -102,6 +104,12 @@ namespace HRM.DA && !employee.IsPaidLastYear; } + /// 31 December of the LFA year. + private static DateTime YearEnd(DateTime lfaYear) + { + return new DateTime(lfaYear.Year, 12, 31); + } + private static DateTime LastDec(DateTime lfaYear) { return new DateTime(lfaYear.Year - 1, 12, 31); diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs index 76c17cc..6b83dcd 100644 --- a/HRM.DA/Service/LFA/LFAPaymentService.cs +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -311,7 +311,7 @@ namespace HRM.DA return details; } - DateTime lfaYear = GetLFAYear(result.SalaryMonth); + DateTime lfaYear = GetLFAYear(paymentDate); foreach (LFAPaymentInput input in inputs) { input.EmployeeNo = (input.EmployeeNo ?? "").Trim(); @@ -336,15 +336,7 @@ namespace HRM.DA // Basic as of 31 December of the preceding year: the salary record that starts before 1 January // (the latest entry), as the bonus reads it. - Dictionary lastDecBasics = new Dictionary(); - List gradeSalaries = new EmployeeGradeSalaryService().GetBasicOnDate(new DateTime(lfaYear.Year, 1, 1)); - if (gradeSalaries != null) - { - foreach (EmployeeGradeSalary gradeSalary in gradeSalaries) - { - lastDecBasics[gradeSalary.EmployeeID] = gradeSalary.BasicSalary; - } - } + Dictionary lastDecBasics = GetBasicOnDate(tc, new DateTime(lfaYear.Year, 1, 1)); foreach (LFAEmployee employee in employees.Values) { double basic; @@ -391,6 +383,22 @@ namespace HRM.DA return details; } + /// + /// EmployeeID → basic on the date (LFAPaymentDA.GetBasicOnDate, the LFA copy of + /// EmployeeGradeSalaryService.GetBasicOnDate). Every row is read, the first one included. + /// + private static Dictionary GetBasicOnDate(TransactionContext tc, DateTime effectDate) + { + Dictionary basics = new Dictionary(); + DataReader dr = new DataReader(LFAPaymentDA.GetBasicOnDate(tc, effectDate)); + while (dr.Read()) + { + basics[dr.GetInt32("EMPLOYEEID").Value] = dr.GetDouble("BASICSALARY", 0); + } + dr.Close(); + return basics; + } + private static LFAPaymentRow ToRow(LFAEmployee employee, LFAPaymentInput input, LFAPaymentDetail detail, DateTime paymentDate) { @@ -459,7 +467,7 @@ namespace HRM.DA oPayment.BatchNumber = BatchNumber(prefix, batchNo); oPayment.PayrollTypeID = payrollTypeID; oPayment.SalaryMonth = validation.SalaryMonth; - oPayment.LFAYear = GetLFAYear(validation.SalaryMonth); + oPayment.LFAYear = GetLFAYear(request.PaymentDate.Value); oPayment.PaymentDate = request.PaymentDate.Value.Date; oPayment.Remarks = string.IsNullOrWhiteSpace(request.Remarks) ? null : request.Remarks.Trim(); oPayment.CreatedBy = userID; @@ -524,9 +532,10 @@ namespace HRM.DA return GlobalFunctions.LastDateOfMonth(payrollType.NextPayProcessDate).Date; } - private static DateTime GetLFAYear(DateTime salaryMonth) + /// LFAYear: the last date of the payment date's month (the LFA is for that date's calendar year). + private static DateTime GetLFAYear(DateTime paymentDate) { - return new DateTime(salaryMonth.Year, 12, 31); + return GlobalFunctions.LastDateOfMonth(paymentDate).Date; } private static string BatchPrefix(DateTime salaryMonth) diff --git a/LFA_DB_Changes.sql b/LFA_DB_Changes.sql index d4cb0a5..13a6ded 100644 --- a/LFA_DB_Changes.sql +++ b/LFA_DB_Changes.sql @@ -9,9 +9,10 @@ - Part 0 DROPS the three tables, Parts 1-3 create them again. The drop is refused, and nothing runs, when any of the tables already holds rows. - - LFAYear is a DATETIME in all three tables: the last date of the calendar - year the LFA is for (2026 = 31-Dec-2026), as SalaryMonth is the last date - of its month. + - LFAYear is a DATETIME in all three tables: the last date of the Payment + Date's month (paid 08-Dec-2026 = 31-Dec-2026), as SalaryMonth is the last + date of its month. The LFA is for the calendar year of that date, so + "once in a calendar year" is enforced on YEAR(LFAYear) (LFACalendarYear). - IDs are generated by the application (tc.GenerateID), no IDENTITY. - A detail row is a snapshot: grade, department, bank account and basic are kept as they were when the batch was processed. @@ -75,7 +76,7 @@ CREATE TABLE dbo.LFAPayment ( BatchNumber VARCHAR(30) NOT NULL, -- LFA-2026-001 PayrollTypeID INT NOT NULL, SalaryMonth DATETIME NOT NULL, -- last date of PAYROLLTYPE.NEXTPAYPROCESSDATE's month - LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for + LFAYear DATETIME NOT NULL, -- last date of PaymentDate's month PaymentDate DATETIME NOT NULL, Remarks NVARCHAR(500) NULL, IsTaxUpdated BIT NOT NULL CONSTRAINT DF_LFAPayment_IsTaxUpdated DEFAULT (0), -- 1 = the batch is already in the income tax data @@ -104,6 +105,7 @@ CREATE TABLE dbo.LFAPaymentDetail ( LFAPaymentID INT NOT NULL, EmployeeID INT NOT NULL, LFAYear DATETIME NOT NULL, -- same value as LFAPayment.LFAYear + LFACalendarYear AS (YEAR(LFAYear)) PERSISTED, -- computed, never written: for the once-a-year index /* employee snapshot */ JoiningDate DATETIME NOT NULL, @@ -136,7 +138,7 @@ CREATE TABLE dbo.LFAPaymentDetail ( ); GO /* policy: LFA once in a calendar year (Undo deletes the rows, which frees the employee again) */ -CREATE UNIQUE INDEX UX_LFAPayDtl_EmployeeYear ON dbo.LFAPaymentDetail (EmployeeID, LFAYear); +CREATE UNIQUE INDEX UX_LFAPayDtl_EmployeeYear ON dbo.LFAPaymentDetail (EmployeeID, LFACalendarYear); GO /* the rows of one batch */ CREATE INDEX IX_LFAPayDtl_Payment ON dbo.LFAPaymentDetail (LFAPaymentID); From 0f5b150e9825b05cbc0bc3853b23cb6666c7b444 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Thu, 26 Nov 2026 15:13:21 +0600 Subject: [PATCH 5/9] LFA Undo --- HRM.BO/LFA/LFAPayment.cs | 6 +- HRM.BO/LFA/LFAPaymentUndo.cs | 70 ++++ HRM.BO/LFA/LFAPaymentUploadTemplate.cs | 2 + HRM.DA/DA/LFA/LFAPaymentDA.cs | 47 ++- HRM.DA/DA/LFA/LFAPaymentDetailDA.cs | 33 ++ HRM.DA/Service/LFA/LFACalculator.cs | 36 +- HRM.DA/Service/LFA/LFAPaymentService.cs | 324 ++++++++++++++++-- .../src/app/_models/Payroll/lfaPayment.ts | 52 +++ .../src/app/_services/payroll/lfa.service.ts | 18 +- .../lfa-payment-undo.component.html | 103 +++++- .../lfa-payment-undo.component.scss | 70 ++++ .../lfa-payment-undo.component.ts | 188 +++++++++- .../lfa-payment/lfa-payment.component.html | 3 +- .../lfa-payment/lfa-payment.component.ts | 7 +- HRM.UI/Controllers/Payroll/LFAController.cs | 58 ++++ 15 files changed, 959 insertions(+), 58 deletions(-) create mode 100644 HRM.BO/LFA/LFAPaymentUndo.cs diff --git a/HRM.BO/LFA/LFAPayment.cs b/HRM.BO/LFA/LFAPayment.cs index fd7f1d9..7e60521 100644 --- a/HRM.BO/LFA/LFAPayment.cs +++ b/HRM.BO/LFA/LFAPayment.cs @@ -103,7 +103,6 @@ namespace HRM.BO public string EmployeeNo { get; set; } public string Name { get; set; } public int PayrollTypeID { get; set; } - public string PayrollTypeName { get; set; } public EnumEmployeeStatus Status { get; set; } public bool IsConfirmed { get; set; } public DateTime JoiningDate { get; set; } @@ -147,6 +146,11 @@ namespace HRM.BO LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID); LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID); List GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID); + + // LFA Payment Undo + List GetUndoBatches(int payrollTypeID); + List GetBatchEmployees(int lfaPaymentID, int payrollTypeID); + LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID); } #endregion diff --git a/HRM.BO/LFA/LFAPaymentUndo.cs b/HRM.BO/LFA/LFAPaymentUndo.cs new file mode 100644 index 0000000..4f722f2 --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentUndo.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region LFA Payment Undo (not tables) + + /// One batch of the LFA Payment Undo page. + public class LFAPaymentBatch + { + public int LFAPaymentID { get; set; } + public string BatchNumber { get; set; } + public DateTime SalaryMonth { get; set; } + public DateTime LFAYear { get; set; } + public DateTime PaymentDate { get; set; } + public string Remarks { get; set; } + public enumwfStatus? WFStatus { get; set; } + public bool IsTaxUpdated { get; set; } + public int HeadCount { get; set; } + public int PaidCount { get; set; } + public double TotalAmount { get; set; } + public string CreatedByName { get; set; } + public DateTime CreationDate { get; set; } + + /// Approval state in words (Not Submitted, Pending Approval, Approved, ...). + public string StatusText { get; set; } + public bool CanUndo { get; set; } + /// Why the batch cannot be undone; empty when it can. + public string UndoBlockedReason { get; set; } + } + + /// One employee of a batch, on the LFA Payment Undo page. + public class LFAPaymentBatchEmployee + { + public int LFAPaymentDetailID { get; set; } + public int EmployeeID { get; set; } + public string EmployeeNo { get; set; } + public string Name { get; set; } + public string DesignationName { get; set; } + public string DepartmentName { get; set; } + public DateTime JoiningDate { get; set; } + public double BasicSalary { get; set; } + public double Amount { get; set; } + public EnumLFAPaymentStatus PaymentStatus { get; set; } + } + + /// What to undo: the whole batch (no DetailIDs) or only these employees of it. + public class LFAPaymentUndoRequest + { + public LFAPaymentUndoRequest() + { + DetailIDs = new List(); + } + + public int LFAPaymentID { get; set; } + /// LFAPaymentDetailIDs of the employees to remove; empty = the whole batch. + public List DetailIDs { get; set; } + } + + public class LFAPaymentUndoResult + { + public bool Undone { get; set; } + public string Message { get; set; } + public int RemovedCount { get; set; } + /// True when the batch itself was deleted (whole batch, or its last employee). + public bool BatchRemoved { get; set; } + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentUploadTemplate.cs b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs index 6f8a5e0..08fb565 100644 --- a/HRM.BO/LFA/LFAPaymentUploadTemplate.cs +++ b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs @@ -66,6 +66,8 @@ namespace HRM.BO public string DepartmentName { get; set; } public DateTime JoiningDate { get; set; } public DateTime? ConfirmationDate { get; set; } + /// Joining Date to Payment Date, e.g. "2 Years 9 Months 27 Days". + public string ServiceLength { get; set; } public double JoiningBasic { get; set; } public double? LastDecBasic { get; set; } public double BasicSalary { get; set; } diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs index 8a10b8a..8901057 100644 --- a/HRM.DA/DA/LFA/LFAPaymentDA.cs +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -35,6 +35,23 @@ namespace HRM.DA #endregion + #region Update / Delete function + + /// Stamps who changed the batch (some of its employees were undone). + internal static void UpdateModified(TransactionContext tc, int lfaPaymentID, int modifiedBy, DateTime modifiedDate) + { + tc.ExecuteNonQuery("UPDATE LFAPayment SET ModifiedBy=%n, ModifiedDate=%D WHERE LFAPaymentID=%n", + modifiedBy, modifiedDate, lfaPaymentID); + } + + /// Deletes the batch header; its detail rows must be deleted first. + internal static void Delete(TransactionContext tc, int lfaPaymentID) + { + tc.ExecuteNonQuery("DELETE FROM LFAPayment WHERE LFAPaymentID=%n", lfaPaymentID); + } + + #endregion + #region Get Function internal static IDataReader Get(TransactionContext tc, int nID) @@ -42,6 +59,33 @@ namespace HRM.DA return tc.ExecuteReader("SELECT * FROM LFAPayment WHERE LFAPaymentID=%n", nID); } + /// + /// The batch, locked until the transaction ends: an approval or a second undo of the same batch + /// waits instead of running at the same time. + /// + internal static IDataReader GetForUpdate(TransactionContext tc, int nID) + { + return tc.ExecuteReader("SELECT * FROM LFAPayment WITH (UPDLOCK, ROWLOCK) WHERE LFAPaymentID=%n", nID); + } + + /// LFA Payment Undo: every batch of the payroll type with its head count and total, newest first. + internal static IDataReader GetBatches(TransactionContext tc, int payrollTypeID) + { + return tc.ExecuteReader( + @"SELECT p.LFAPaymentID, p.BatchNumber, p.SalaryMonth, p.LFAYear, p.PaymentDate, p.Remarks, p.WFStatus, + p.IsTaxUpdated, p.CreationDate, ISNULL(u.UserName, u.LoginID) AS CreatedByName, + ISNULL(s.HeadCount, 0) AS HeadCount, ISNULL(s.PaidCount, 0) AS PaidCount, + ISNULL(s.TotalAmount, 0) AS TotalAmount + FROM LFAPayment p + LEFT JOIN (SELECT dt.LFAPaymentID, COUNT(*) AS HeadCount, SUM(dt.Amount) AS TotalAmount, + SUM(CASE WHEN dt.PaymentStatus = %n THEN 1 ELSE 0 END) AS PaidCount + FROM LFAPaymentDetail dt GROUP BY dt.LFAPaymentID) s ON s.LFAPaymentID = p.LFAPaymentID + LEFT JOIN Users u ON u.UserID = p.CreatedBy + WHERE p.PayrollTypeID=%n + ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC", + (int)EnumLFAPaymentStatus.Paid, payrollTypeID); + } + /// The highest running number of the batches that start with this prefix; 0 = none yet. internal static int GetLastBatchNo(TransactionContext tc, int payrollTypeID, string batchPrefix) { @@ -86,7 +130,7 @@ namespace HRM.DA SELECT e.EMPLOYEEID FROM EMPLOYEE e WHERE e.EMPLOYEENO IN (SELECT value FROM STRING_SPLIT(@employeeNos, ',') WHERE value <> ''); - SELECT e.EMPLOYEEID, e.EMPLOYEENO, e.NAME, e.PAYROLLTYPEID, pt.DESCRIPTION AS PayrollTypeName, e.STATUS, e.ISCONFIRMED, e.JOININGDATE, + SELECT e.EMPLOYEEID, e.EMPLOYEENO, e.NAME, e.PAYROLLTYPEID, e.STATUS, e.ISCONFIRMED, e.JOININGDATE, e.DATEOFCONFIRMATION, e.GRADEID, g.DESCRIPTION AS GradeName, e.DESIGNATIONID, ds.NAME AS DesignationName, e.DEPARTMENTID, d.DESCRIPTION AS DepartmentName, pd.DESCRIPTION AS DivisionName, cc.COSTCENTERID, e.BRANCHID, e.ACCOUNTNO, @@ -95,7 +139,6 @@ namespace HRM.DA CASE WHEN pv.LFAPaymentDetailID IS NULL THEN 0 ELSE 1 END AS IsPaidLastYear FROM #lfaEmp t INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = t.EmployeeID - LEFT JOIN PAYROLLTYPE pt ON pt.PAYROLLTYPEID = e.PAYROLLTYPEID LEFT JOIN GRADES g ON g.GRADEID = e.GRADEID LEFT JOIN DESIGNATION ds ON ds.DESIGNATIONID = e.DESIGNATIONID LEFT JOIN DEPARTMENT d ON d.DEPARTMENTID = e.DEPARTMENTID diff --git a/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs index 3cc15d0..e699af4 100644 --- a/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs +++ b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs @@ -94,6 +94,39 @@ namespace HRM.DA return tc.ExecuteReader("SELECT * FROM LFAPaymentDetail WHERE LFAPaymentID=%n ORDER BY LFAPaymentDetailID", paymentID); } + /// LFA Payment Undo: the employees of one batch. + internal static IDataReader GetBatchEmployees(TransactionContext tc, int paymentID) + { + return tc.ExecuteReader( + @"SELECT dt.LFAPaymentDetailID, dt.EmployeeID, e.EMPLOYEENO, e.NAME, ds.NAME AS DesignationName, + d.DESCRIPTION AS DepartmentName, dt.JoiningDate, dt.BasicSalary, dt.Amount, dt.PaymentStatus + FROM LFAPaymentDetail dt + INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = dt.EmployeeID + LEFT JOIN DESIGNATION ds ON ds.DESIGNATIONID = dt.DesignationID + LEFT JOIN DEPARTMENT d ON d.DEPARTMENTID = dt.DepartmentID + WHERE dt.LFAPaymentID=%n + ORDER BY e.EMPLOYEENO", + paymentID); + } + + #endregion + + #region Delete function + + /// Deletes every employee of the batch. + internal static void DeleteByPaymentID(TransactionContext tc, int paymentID) + { + tc.ExecuteNonQuery("DELETE FROM LFAPaymentDetail WHERE LFAPaymentID=%n", paymentID); + } + + /// Deletes these employees of the batch (IDs the service has already checked). + internal static void Delete(TransactionContext tc, int paymentID, List detailIDs) + { + // %q: a list of ints joined by this code, never user text + tc.ExecuteNonQuery("DELETE FROM LFAPaymentDetail WHERE LFAPaymentID=%n AND LFAPaymentDetailID IN (%q)", + paymentID, string.Join(",", detailIDs)); + } + #endregion } diff --git a/HRM.DA/Service/LFA/LFACalculator.cs b/HRM.DA/Service/LFA/LFACalculator.cs index b42f1d3..aa7cf11 100644 --- a/HRM.DA/Service/LFA/LFACalculator.cs +++ b/HRM.DA/Service/LFA/LFACalculator.cs @@ -21,16 +21,13 @@ namespace HRM.DA private const double DaysOfYear = 365; /// Every reason the employee cannot be paid; empty = eligible. - internal static List Validate(LFAEmployee employee, DateTime lfaYear, DateTime paymentDate, - int payrollTypeID) + internal static List Validate(LFAEmployee employee, DateTime lfaYear, DateTime paymentDate, int payrollTypeID) { List problems = new List(); - if (employee.PayrollTypeID != payrollTypeID) { - // an employee's LFA is processed only in the employee's own payroll type - problems.Add("Employee belongs to another payroll type (" + (employee.PayrollTypeName ?? employee.PayrollTypeID.ToString()) - + "); the LFA can be processed only in that payroll type."); + // another payroll type's employee is not shown: it reads as not found + problems.Add("Employee is not found."); return problems; } if (employee.Status != EnumEmployeeStatus.Live) @@ -85,6 +82,33 @@ namespace HRM.DA return detail; } + /// + /// Completed service from the joining date to the date (the payment date), e.g. "2 Years 9 Months 27 Days". + /// + internal static string ServiceLength(DateTime joiningDate, DateTime asOf) + { + DateTime from = joiningDate.Date; + DateTime to = asOf.Date; + if (to <= from) + return "0 Days"; + + int totalMonths = (to.Year - from.Year) * 12 + to.Month - from.Month; + if (from.AddMonths(totalMonths) > to) + totalMonths--; + int days = (to - from.AddMonths(totalMonths)).Days; + int years = totalMonths / 12; + int months = totalMonths % 12; + + List parts = new List(); + if (years > 0) + parts.Add(years + (years == 1 ? " Year" : " Years")); + if (months > 0) + parts.Add(months + (months == 1 ? " Month" : " Months")); + if (days > 0 || parts.Count == 0) + parts.Add(days + (days == 1 ? " Day" : " Days")); + return string.Join(" ", parts); + } + /// Days from the joining date to the year end, the joining date itself not counted, over 365. private static double ProRata(double amount, DateTime joiningDate, DateTime yearEnd) { diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs index 6b83dcd..0dd5c5b 100644 --- a/HRM.DA/Service/LFA/LFAPaymentService.cs +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -80,7 +80,6 @@ namespace HRM.DA employee.EmployeeNo = oReader.GetString("EMPLOYEENO"); employee.Name = oReader.GetString("NAME"); employee.PayrollTypeID = oReader.GetInt32("PAYROLLTYPEID").Value; - employee.PayrollTypeName = oReader.GetString("PayrollTypeName"); employee.Status = (EnumEmployeeStatus)oReader.GetInt32("STATUS").Value; employee.IsConfirmed = oReader.GetBoolean("ISCONFIRMED", false); employee.JoiningDate = oReader.GetDateTime("JOININGDATE").Value; @@ -118,6 +117,45 @@ namespace HRM.DA return history; } + private LFAPaymentBatch MapBatch(DataReader oReader) + { + LFAPaymentBatch batch = new LFAPaymentBatch(); + batch.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value; + batch.BatchNumber = oReader.GetString("BatchNumber"); + batch.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value; + batch.LFAYear = oReader.GetDateTime("LFAYear").Value; + batch.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + batch.Remarks = oReader.GetString("Remarks"); + batch.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus"); + batch.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value; + batch.CreationDate = oReader.GetDateTime("CreationDate").Value; + batch.CreatedByName = oReader.GetString("CreatedByName"); + batch.HeadCount = oReader.GetInt32("HeadCount").Value; + batch.PaidCount = oReader.GetInt32("PaidCount").Value; + batch.TotalAmount = oReader.GetDouble("TotalAmount").Value; + + batch.StatusText = StatusText(batch.WFStatus); + batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount); + batch.CanUndo = batch.UndoBlockedReason == null; + return batch; + } + + private LFAPaymentBatchEmployee MapBatchEmployee(DataReader oReader) + { + LFAPaymentBatchEmployee employee = new LFAPaymentBatchEmployee(); + employee.LFAPaymentDetailID = oReader.GetInt32("LFAPaymentDetailID").Value; + employee.EmployeeID = oReader.GetInt32("EmployeeID").Value; + employee.EmployeeNo = oReader.GetString("EMPLOYEENO"); + employee.Name = oReader.GetString("NAME"); + employee.DesignationName = oReader.GetString("DesignationName"); + employee.DepartmentName = oReader.GetString("DepartmentName"); + employee.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + employee.BasicSalary = oReader.GetDouble("BasicSalary").Value; + employee.Amount = oReader.GetDouble("Amount").Value; + employee.PaymentStatus = (EnumLFAPaymentStatus)oReader.GetInt32("PaymentStatus").Value; + return employee; + } + #endregion #region Get @@ -243,8 +281,7 @@ namespace HRM.DA } /// Reads an uploaded workbook and calculates its employees. Nothing is saved. - public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, - int payrollTypeID) + public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, int payrollTypeID) { LFAPaymentReadResult result = new LFAPaymentReadResult(); TransactionContext tc = null; @@ -254,8 +291,11 @@ namespace HRM.DA List rows = LFAPaymentWorkbook.Read(stream, fileName, fileLength, result); tc = TransactionContext.Begin(); - Calculate(tc, result, rows, paymentDate, payrollTypeID); + List> validRows = Validate(tc, result, rows, paymentDate, payrollTypeID); tc.End(); + + if (result.Issues.Count == 0) + Calculate(result, validRows, paymentDate); // only a fully valid file is calculated } catch (Exception e) { @@ -282,8 +322,12 @@ namespace HRM.DA result.SalaryMonth = GetSalaryMonth(payrollTypeID); tc = TransactionContext.Begin(); - Calculate(tc, result, request.Rows, request.PaymentDate.Value, payrollTypeID); + List> validRows = Validate(tc, result, request.Rows, + request.PaymentDate.Value, payrollTypeID); tc.End(); + + if (result.Issues.Count == 0) + Calculate(result, validRows, request.PaymentDate.Value); } catch (Exception e) { @@ -300,15 +344,17 @@ namespace HRM.DA } /// - /// Puts every row that can be paid into result.Rows and every problem of the others into - /// result.Issues. Returns the detail of each payable row, in the same order. + /// Validation, the first step of every upload, recalculation and process: runs EVERY check on EVERY row + /// and puts every problem into result.Issues (the file's own problems, found while reading it, are + /// already there). Nothing is calculated here. Returns the rows that passed with their employee; they + /// may be calculated only when result.Issues is empty. /// - private List Calculate(TransactionContext tc, LFAPaymentReadResult result, List inputs, DateTime paymentDate, int payrollTypeID) + private List> Validate(TransactionContext tc, LFAPaymentReadResult result, List inputs, DateTime paymentDate, int payrollTypeID) { - List details = new List(); - if (inputs.Count == 0) + List> valid = new List>(); + if (inputs == null || inputs.Count == 0) { - return details; + return valid; } DateTime lfaYear = GetLFAYear(paymentDate); @@ -319,15 +365,13 @@ namespace HRM.DA // An Employee No may exist in another payroll type too; the current payroll type's employee comes first. Dictionary employees = new Dictionary(StringComparer.OrdinalIgnoreCase); - DataReader dr = new DataReader(LFAPaymentDA.GetEmployees(tc, - inputs.Select(x => x.EmployeeNo).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), lfaYear)); + DataReader dr = new DataReader(LFAPaymentDA.GetEmployees(tc, inputs.Select(x => x.EmployeeNo).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), lfaYear)); while (dr.Read()) { LFAEmployee employee = MapEmployee(dr); string key = (employee.EmployeeNo ?? "").Trim(); LFAEmployee found; - if (!employees.TryGetValue(key, out found) - || (found.PayrollTypeID != payrollTypeID && employee.PayrollTypeID == payrollTypeID)) + if (!employees.TryGetValue(key, out found) || (found.PayrollTypeID != payrollTypeID && employee.PayrollTypeID == payrollTypeID)) { employees[key] = employee; } @@ -343,43 +387,47 @@ namespace HRM.DA employee.LastDecBasic = lastDecBasics.TryGetValue(employee.EmployeeID, out basic) ? basic : 0; } - Dictionary> rowNos = inputs.GroupBy(x => x.EmployeeNo, StringComparer.OrdinalIgnoreCase) - .ToDictionary(x => x.Key, x => x.Select(i => i.RowNo).ToList(), StringComparer.OrdinalIgnoreCase); - + Dictionary> rowNos = inputs.GroupBy(x => x.EmployeeNo, StringComparer.OrdinalIgnoreCase).ToDictionary(x => x.Key, x => x.Select(i => i.RowNo).ToList(), StringComparer.OrdinalIgnoreCase); foreach (LFAPaymentInput input in inputs) { LFAEmployee employee; - if (!employees.TryGetValue(input.EmployeeNo, out employee)) + if (!employees.TryGetValue(input.EmployeeNo, out employee) || employee.PayrollTypeID != payrollTypeID) { result.AddIssue(input.RowNo, input.EmployeeNo, null, "Employee is not found."); continue; } - List problems = LFACalculator.Validate(employee, lfaYear, paymentDate, payrollTypeID); if (rowNos[input.EmployeeNo].Count > 1) { problems.Add("Employee is more than once in the file (rows " + string.Join(", ", rowNos[input.EmployeeNo]) + ")."); } - if (problems.Count > 0) + foreach (string problem in problems) { - foreach (string problem in problems) - { - result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem); - } - continue; + result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem); } - - LFAPaymentDetail detail = LFACalculator.Calculate(employee, lfaYear); - if (detail.Amount <= 0) + if (problems.Count == 0) { - result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, "LFA amount is zero."); - continue; + valid.Add(new KeyValuePair(input, employee)); } - details.Add(detail); - result.Rows.Add(ToRow(employee, input, detail, paymentDate)); } - result.Issues = result.Issues.OrderBy(x => x.RowNo).ToList(); + return valid; + } + + /// + /// Calculation (LFACalculator.Calculate) of rows that Validate passed. Call it ONLY when Validate left + /// result.Issues empty. Fills result.Rows and returns each row's detail, in the same order. + /// + private static List Calculate(LFAPaymentReadResult result, List> validRows, DateTime paymentDate) + { + DateTime lfaYear = GetLFAYear(paymentDate); + List details = new List(); + foreach (KeyValuePair item in validRows) + { + LFAPaymentDetail detail = LFACalculator.Calculate(item.Value, lfaYear); + details.Add(detail); + result.Rows.Add(ToRow(item.Value, item.Key, detail, paymentDate)); + } return details; } @@ -414,6 +462,7 @@ namespace HRM.DA DepartmentName = employee.DepartmentName, JoiningDate = employee.JoiningDate, ConfirmationDate = employee.ConfirmationDate, + ServiceLength = LFACalculator.ServiceLength(employee.JoiningDate, paymentDate), JoiningBasic = employee.JoiningBasic, LastDecBasic = detail.LastDecBasic, BasicSalary = detail.BasicSalary, @@ -448,8 +497,11 @@ namespace HRM.DA tc = TransactionContext.Begin(true); int batchNo = LFAPaymentDA.GetLastBatchNoForUpdate(tc, payrollTypeID, prefix) + 1; - List details = Calculate(tc, validation, request.Rows, request.PaymentDate.Value, - payrollTypeID); + List> validRows = Validate(tc, validation, request.Rows, + request.PaymentDate.Value, payrollTypeID); + List details = validation.Issues.Count == 0 + ? Calculate(validation, validRows, request.PaymentDate.Value) // only after a clean validation + : new List(); if (validation.Issues.Count > 0) { @@ -513,6 +565,206 @@ namespace HRM.DA #endregion + #region Undo + + /// LFA Payment Undo: every batch of the payroll type, and whether each one can be undone. + public List GetUndoBatches(int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.GetBatches(tc, payrollTypeID)); + while (dr.Read()) + { + items.Add(MapBatch(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 items; + } + + /// The employees of one batch of the payroll type; empty when the batch is not found. + public List GetBatchEmployees(int lfaPaymentID, int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment != null && oPayment.PayrollTypeID == payrollTypeID) + { + dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, lfaPaymentID)); + while (dr.Read()) + { + items.Add(MapBatchEmployee(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 items; + } + + /// + /// Undoes the whole batch (request.DetailIDs empty) or only those employees of it, in ONE transaction. + /// Everything is checked again here with the batch locked: a batch submitted for approval, approved, + /// already in the tax data or with a paid employee is not undone. When the last employee goes, the + /// batch goes too. The undone employees can then be paid again in another batch. + /// + public LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID) + { + LFAPaymentUndoResult result = new LFAPaymentUndoResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + List detailIDs = (request.DetailIDs ?? new List()).Distinct().ToList(); + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, request.LFAPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + { + result.Message = "The batch is not found. It may have been undone already."; + tc.End(); + return result; + } + + List details = new List(); + dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, oPayment.ID)); + while (dr.Read()) + { + LFAPaymentDetail oDetail = new LFAPaymentDetail(); + MapDetailObject(oDetail, dr); + details.Add(oDetail); + } + dr.Close(); + + bool wholeBatch = detailIDs.Count == 0 || details.All(x => detailIDs.Contains(x.ID)); + List selected = wholeBatch ? details : details.Where(x => detailIDs.Contains(x.ID)).ToList(); + + string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated, + selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid)); + if (blocked != null) + { + result.Message = blocked; + } + else if (!wholeBatch && selected.Count != detailIDs.Count) + { + result.Message = "Some of the selected employees are no longer in batch " + oPayment.BatchNumber + + ". Please load the batch again."; + } + else + { + if (wholeBatch) + { + LFAPaymentDetailDA.DeleteByPaymentID(tc, oPayment.ID); + LFAPaymentDA.Delete(tc, oPayment.ID); + result.BatchRemoved = true; + result.Message = "Batch " + oPayment.BatchNumber + " is undone (" + selected.Count + " employee(s))."; + } + else + { + LFAPaymentDetailDA.Delete(tc, oPayment.ID, selected.Select(x => x.ID).ToList()); + LFAPaymentDA.UpdateModified(tc, oPayment.ID, userID, DateTime.Now); + result.Message = selected.Count + " employee(s) undone from batch " + oPayment.BatchNumber + "."; + } + result.Undone = true; + result.RemovedCount = selected.Count; + } + 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; + } + + /// + /// Why a batch cannot be undone; null when it can. Undo is allowed before the batch is submitted for + /// approval, and after the approver sends it back (Revert) or declines it. + /// + private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount) + { + if (wfStatus == enumwfStatus.Approve) + return "The batch is already approved."; + if (wfStatus != null && wfStatus != enumwfStatus.Not_yet_Submitted && wfStatus != enumwfStatus.Revert + && wfStatus != enumwfStatus.Decline) + return "The batch is submitted and pending for approval."; + if (isTaxUpdated) + return "The batch is already in the income tax data."; + if (paidCount > 0) + return paidCount + " employee(s) of the batch are already paid."; + return null; + } + + private static string StatusText(enumwfStatus? wfStatus) + { + if (wfStatus == null || wfStatus == enumwfStatus.Not_yet_Submitted) + return "Not Submitted"; + switch (wfStatus.Value) + { + case enumwfStatus.Approve: + return "Approved"; + case enumwfStatus.Revert: + return "Reverted"; + case enumwfStatus.Decline: + return "Declined"; + default: + return "Pending Approval"; + } + } + + #endregion + #region Helpers private static void CheckRequest(LFAPaymentRequest request) diff --git a/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts index 5963fcc..e56a4dc 100644 --- a/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts +++ b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts @@ -22,6 +22,7 @@ export class LFAPaymentRow extends LFAPaymentInput { departmentName: string; joiningDate: Date; confirmationDate: Date; + serviceLength: string; // Joining Date to Payment Date joiningBasic: number; lastDecBasic: number; basicSalary: number; @@ -79,3 +80,54 @@ export class LFAPaymentHistory { // filled on the page statusText: string; } + +// ── LFA Payment Undo ── + +/** One batch of the LFA Payment Undo page. */ +export class LFAPaymentBatch { + lfaPaymentID: number; + batchNumber: string; + salaryMonth: Date; + lfaYear: Date; + paymentDate: Date; + remarks: string; + wfStatus: number; + isTaxUpdated: boolean; + headCount: number; + paidCount: number; + totalAmount: number; + createdByName: string; + creationDate: Date; + statusText: string; + canUndo: boolean; + undoBlockedReason: string; +} + +/** One employee of a batch. */ +export class LFAPaymentBatchEmployee { + lfaPaymentDetailID: number; + employeeID: number; + employeeNo: string; + name: string; + designationName: string; + departmentName: string; + joiningDate: Date; + basicSalary: number; + amount: number; + paymentStatus: EnumLFAPaymentStatus; + // filled on the page + statusText: string; +} + +/** detailIDs empty = the whole batch. */ +export class LFAPaymentUndoRequest { + lfaPaymentID: number; + detailIDs: number[]; +} + +export class LFAPaymentUndoResult { + undone: boolean; + message: string; + removedCount: number; + batchRemoved: boolean; +} diff --git a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts index dd0ca68..228a3f8 100644 --- a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts @@ -2,7 +2,8 @@ import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from '../../app.api.service'; import { - LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest + LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult, + LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentUndoRequest, LFAPaymentUndoResult } from '../../_models/Payroll/lfaPayment'; @Injectable({ @@ -43,4 +44,19 @@ export class LFAService { getPaymentHistory(fromDate: string, toDate: string): Observable { return this.apiService.httpGet('/lfa/getPaymentHistory/' + fromDate + '/' + toDate); } + + // ── LFA Payment Undo ── + + getUndoBatches(): Observable { + return this.apiService.httpGet('/lfa/getUndoBatches'); + } + + getBatchEmployees(lfaPaymentID: number): Observable { + return this.apiService.httpGet('/lfa/getBatchEmployees/' + lfaPaymentID); + } + + /** The whole batch (no detailIDs) or the selected employees of it. The server checks everything again. */ + undoPayment(request: LFAPaymentUndoRequest): Observable { + return this.apiService.httpPost('/lfa/undoPayment', request); + } } diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.html b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.html index b3ed55b..6c5f0d3 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.html +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.html @@ -1,8 +1,99 @@ -
    - - LFA Payment Undo - - - + +
    + +
    + LFA Batches + A batch can be undone until it is submitted for approval. Undone employees can be paid again in a new batch. + + +
    + + + + + + {{ dataItem.lfaYear | date: 'yyyy' }} + + + + + + {{ dataItem.statusText }} + + + + + + + + + + + + No LFA batch found. + + + + @if (selectedBatch) { +
    + Batch {{ selectedBatch.batchNumber }} + + Payment Date {{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }} · {{ employees.length }} employee(s) · + {{ selectedDetailIDs.length }} ticked ({{ selectedAmount | number: '1.2-2' }}) + + + + + +
    + + @if (!selectedBatch.canUndo) { +
    This batch cannot be undone: {{ selectedBatch.undoBlockedReason }}
    + } + + + + + + + + + + + + No employee in this batch. + + + }
    + +@if (showConfirm && confirmBatch) { +
    + + @if (confirmWholeBatch) { +

    The whole batch {{ confirmBatch.batchNumber }} will be deleted. This cannot be reversed.

    + } @else { +

    {{ confirmCount }} employee(s) will be removed from batch {{ confirmBatch.batchNumber }}. This cannot be reversed.

    + } + + + + + + + +
    Batch ID{{ confirmBatch.batchNumber }}
    Payment Date{{ confirmBatch.paymentDate | date: 'dd-MMM-yyyy' }}
    Employees{{ confirmCount }}
    LFA AmountBDT {{ confirmAmount | number: '1.2-2' }}
    + + + + +
    +
    +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.scss b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.scss index e69de29..c21b092 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.scss +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.scss @@ -0,0 +1,70 @@ +/* LFA Payment Undo: layout only; colours are the theme's --gh-* variables */ +.lfa-undo { + display: flex; + flex-direction: column; + gap: 12px; + padding: 8px 4px; +} + +.lfa-undo__head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.lfa-undo__title { + font-size: 16px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-undo__hint { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-undo__spacer { + flex: 1 1 auto; +} + +.lfa-undo__blocked { + padding: 8px 12px; + border-radius: 6px; + font-weight: 600; + color: var(--gh-dn); + background: color-mix(in srgb, var(--gh-dn) 10%, transparent); +} + +.lfa-selected { + border-color: var(--gh-lk); + color: var(--gh-lk); +} + +.lfa-badge { + display: inline-block; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + color: var(--gh-dn); + background: color-mix(in srgb, var(--gh-dn) 12%, transparent); +} + +.lfa-badge--ok { + color: var(--gh-warn); + background: color-mix(in srgb, var(--gh-warn) 15%, transparent); +} + +.lfa-confirm { + width: 100%; + + td { + padding: 4px 0; + } + + td:last-child { + text-align: right; + font-weight: 600; + } +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.ts index ea47e07..4c5fbcc 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-undo/lfa-payment-undo.component.ts @@ -1,6 +1,17 @@ import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { ExcelExportData } from '@progress/kendo-angular-excel-export'; import { ApiService } from '../../app.api.service'; +import { HRMNotificationService } from '../../app.notification.service'; +import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service'; +import { LFAService } from '../../_services/payroll/lfa.service'; +import { + EnumLFAPaymentStatus, LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentUndoRequest, LFAPaymentUndoResult +} from '../../_models/Payroll/lfaPayment'; +/** + * LFA Payment Undo: the payroll type's LFA batches. A batch can be undone whole, or only some of its + * employees, until it is submitted for approval (as Salary Undo). The server checks everything again. + */ @Component({ selector: 'app-lfa-payment-undo', templateUrl: './lfa-payment-undo.component.html', @@ -10,10 +21,185 @@ import { ApiService } from '../../app.api.service'; }) export class LfaPaymentUndoComponent implements OnInit { - constructor(public apiService: ApiService) { + batches: LFAPaymentBatch[] = []; + selectedBatch: LFAPaymentBatch = null; + employees: LFAPaymentBatchEmployee[] = []; + selectedDetailIDs: number[] = []; + isBusy = false; + + // confirm dialog: the whole batch, or the selected employees + showConfirm = false; + confirmWholeBatch = true; + confirmBatch: LFAPaymentBatch = null; + + constructor(public apiService: ApiService, + public notificationService: HRMNotificationService, + public loadingPanel: loadingPanelService, + private lfaService: LFAService) { this.apiService.selectedMenuName = 'LFA Payment Undo'; } ngOnInit() { + this.loadBatches(); + } + + // ── Batches ───────────────────────────────────────────────────── + + loadBatches(keepBatchID: number = 0) { + this.start(); + this.lfaService.getUndoBatches().subscribe({ + next: (resp) => { + this.stop(); + this.batches = (resp || []).map(x => ({ + ...x, + paymentDate: this.toDate(x.paymentDate), + lfaYear: this.toDate(x.lfaYear), + creationDate: this.toDate(x.creationDate) + })); + const keep = keepBatchID ? this.batches.find(x => x.lfaPaymentID === keepBatchID) : null; + if (keep) { + this.viewBatch(keep); + } else { + this.clearBatch(); + } + }, + error: (err) => this.fail(err, 'Could not load the LFA batches.') + }); + } + + viewBatch(batch: LFAPaymentBatch) { + this.selectedBatch = batch; + this.selectedDetailIDs = []; + this.employees = []; + this.start(); + this.lfaService.getBatchEmployees(batch.lfaPaymentID).subscribe({ + next: (resp) => { + this.stop(); + this.employees = (resp || []).map(x => ({ + ...x, + joiningDate: this.toDate(x.joiningDate), + statusText: this.paymentStatusText(x.paymentStatus) + })); + }, + error: (err) => this.fail(err, 'Could not load the employees of the batch.') + }); + } + + clearBatch() { + this.selectedBatch = null; + this.employees = []; + this.selectedDetailIDs = []; + } + + // ── Undo ──────────────────────────────────────────────────────── + + /** Undo the whole batch (from the batch grid). */ + confirmUndoBatch(batch: LFAPaymentBatch) { + if (!batch.canUndo) { + this.notificationService.showWarning(batch.undoBlockedReason, 'Cannot undo'); + return; + } + this.confirmBatch = batch; + this.confirmWholeBatch = true; + this.showConfirm = true; + } + + /** Undo only the ticked employees of the selected batch. */ + confirmUndoEmployees() { + if (!this.selectedBatch) { + return; + } + if (!this.selectedBatch.canUndo) { + this.notificationService.showWarning(this.selectedBatch.undoBlockedReason, 'Cannot undo'); + return; + } + if (this.selectedDetailIDs.length === 0) { + this.notificationService.showWarning('Please tick at least one employee.'); + return; + } + this.confirmBatch = this.selectedBatch; + // every employee ticked is the same as the whole batch + this.confirmWholeBatch = this.selectedDetailIDs.length === this.employees.length; + this.showConfirm = true; + } + + get confirmCount(): number { + return this.confirmWholeBatch ? (this.confirmBatch ? this.confirmBatch.headCount : 0) : this.selectedDetailIDs.length; + } + + get confirmAmount(): number { + if (this.confirmWholeBatch) { + return this.confirmBatch ? this.confirmBatch.totalAmount : 0; + } + return this.sum(this.employees.filter(x => this.selectedDetailIDs.indexOf(x.lfaPaymentDetailID) >= 0), x => x.amount); + } + + get selectedAmount(): number { + return this.sum(this.employees.filter(x => this.selectedDetailIDs.indexOf(x.lfaPaymentDetailID) >= 0), x => x.amount); + } + + undo() { + if (this.isBusy || !this.confirmBatch) { + return; + } + const batch = this.confirmBatch; + const request: LFAPaymentUndoRequest = { + lfaPaymentID: batch.lfaPaymentID, + detailIDs: this.confirmWholeBatch ? [] : [...this.selectedDetailIDs] + }; + this.start(); + this.lfaService.undoPayment(request).subscribe({ + next: (resp: LFAPaymentUndoResult) => { + this.stop(); + this.showConfirm = false; + if (!resp.undone) { + this.notificationService.showError(resp.message); + this.loadBatches(batch.lfaPaymentID); // the batch may have changed meanwhile + return; + } + this.notificationService.showSuccess(resp.message); + this.loadBatches(resp.batchRemoved ? 0 : batch.lfaPaymentID); + }, + error: (err) => { + this.showConfirm = false; + this.fail(err, 'Nothing was undone. Please try again.'); + } + }); + } + + allEmployees = (): ExcelExportData => ({ data: this.employees }); + + // ── Helpers ───────────────────────────────────────────────────── + + private paymentStatusText(status: EnumLFAPaymentStatus): string { + switch (status) { + case EnumLFAPaymentStatus.Paid: return 'Paid'; + case EnumLFAPaymentStatus.Failed: return 'Failed'; + default: return 'Pending'; + } + } + + private start() { + this.isBusy = true; + this.loadingPanel.ShowLoadingPanel = true; + } + + private stop() { + this.isBusy = false; + this.loadingPanel.ShowLoadingPanel = false; + } + + private fail(err: any, fallback: string) { + this.stop(); + const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : ''; + this.notificationService.showError(text || fallback); + } + + private toDate(value: any): Date { + return value ? new Date(value) : null; + } + + private sum(items: T[], value: (item: T) => number): number { + return Math.round(items.reduce((total, x) => total + (value(x) || 0), 0) * 100) / 100; } } diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.html b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.html index 1743817..20e2ef9 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.html +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.html @@ -100,6 +100,7 @@ +
    {{ totalBasic | number: '1.2-2' }}
    @@ -117,7 +118,7 @@ @if (issues.length > 0) {
    - {{ issues.length }} error(s) found in the uploaded file. These rows are not in the list. + {{ issues.length }} error(s) found. Nothing was calculated: correct every error in the file and upload it again.
    } diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts index 42ba40e..7b42bf4 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts @@ -181,10 +181,9 @@ export class LfaPaymentComponent implements OnInit { } private showUploadMessage() { - if (this.rows.length === 0) { - this.notificationService.showError('No employee of the file can be paid. Please check the error list.'); - } else if (this.issues.length > 0) { - this.notificationService.showWarning(this.rows.length + ' employee(s) loaded. Some rows have errors; please check the error list.'); + // all or nothing: one error anywhere in the file and nothing is calculated + if (this.issues.length > 0) { + this.notificationService.showError('Nothing was calculated. Please correct every error in the file and upload it again.'); } else { this.notificationService.showSuccess(this.rows.length + ' employee(s) loaded.'); } diff --git a/HRM.UI/Controllers/Payroll/LFAController.cs b/HRM.UI/Controllers/Payroll/LFAController.cs index 947c83a..cf94821 100644 --- a/HRM.UI/Controllers/Payroll/LFAController.cs +++ b/HRM.UI/Controllers/Payroll/LFAController.cs @@ -96,6 +96,64 @@ namespace HRM.UI.Controllers.Payroll } } + // ── LFA Payment Undo ── + + /// Every batch of the current payroll type, and whether each one can be undone. + [HttpGet("getUndoBatches")] + public ActionResult GetUndoBatches() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetUndoBatches(currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpGet("getBatchEmployees/{lfaPaymentID}")] + public ActionResult GetBatchEmployees(int lfaPaymentID) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetBatchEmployees(lfaPaymentID, currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// Undoes the whole batch or the selected employees of it; the server checks everything again. + [HttpPost("undoPayment")] + public ActionResult UndoPayment(LFAPaymentUndoRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.Undo(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + private ActionResult NotAllowed() { return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment."); From c57a15e87dfc4dd792c0e4891e14732902bd4438 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Thu, 26 Nov 2026 18:54:00 +0600 Subject: [PATCH 6/9] LFA Payment Approval --- HRM.BO/LFA/LFAPayment.cs | 32 +- HRM.BO/LFA/LFAPaymentApproval.cs | 78 +++ HRM.BO/LFA/LFAPaymentUndo.cs | 10 + HRM.DA/DA/LFA/LFAPaymentDA.cs | 88 ++- HRM.DA/DA/Workflow/WFMovementTranDA.cs | 1 + HRM.DA/Service/LFA/LFAPaymentService.cs | 523 +++++++++++++++++- .../src/app/_models/Payroll/lfaPayment.ts | 39 ++ .../src/app/_services/payroll/lfa.service.ts | 40 ++ .../lfa-approval/lfa-approval.component.html | 72 +++ .../lfa-approval/lfa-approval.component.scss | 88 +++ .../lfa-approval/lfa-approval.component.ts | 168 ++++++ .../payment-approval-routing.module.ts | 2 + .../payment-approval.module.ts | 4 +- .../lfa-payment-approval.component.html | 153 ++++- .../lfa-payment-approval.component.scss | 145 +++++ .../lfa-payment-approval.component.ts | 226 +++++++- HRM.UI/Controllers/Payroll/LFAController.cs | 141 +++++ 17 files changed, 1790 insertions(+), 20 deletions(-) create mode 100644 HRM.BO/LFA/LFAPaymentApproval.cs create mode 100644 HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.html create mode 100644 HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.scss create mode 100644 HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.ts diff --git a/HRM.BO/LFA/LFAPayment.cs b/HRM.BO/LFA/LFAPayment.cs index 7e60521..36cc42c 100644 --- a/HRM.BO/LFA/LFAPayment.cs +++ b/HRM.BO/LFA/LFAPayment.cs @@ -19,7 +19,7 @@ namespace HRM.BO #region LFAPayment /// One Leave Fare Assistance payment batch (dbo.LFAPayment), as SalaryProcess is for the salary. - public class LFAPayment : AuditTrailBase + public class LFAPayment : AuditTrailBase, IworkflowInterface { public LFAPayment() { @@ -47,6 +47,26 @@ namespace HRM.BO public DateTime? ApprovedDate { get; set; } public List Details { get; set; } + + #region IworkflowInterface Members + + public string ObjectDescription + { + get { return "LFA payment batch " + BatchNumber; } + } + + /// The workflow type (WFTYPE 33), as SalaryProcess returns 30. + public int SetupID + { + get { return LFAPaymentApproval.WFTypeID; } + } + + public int ObjectID + { + get { return this.ID; } + } + + #endregion } #endregion @@ -151,6 +171,16 @@ namespace HRM.BO List GetUndoBatches(int payrollTypeID); List GetBatchEmployees(int lfaPaymentID, int payrollTypeID); LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID); + + // LFA Payment Approval (as Salary Approval) + LFAApprovalInfo GetApprovalInfo(int? employeeID); + List GetApprovalBatches(int payrollTypeID); + List GetFlowHistory(int lfaPaymentID, int payrollTypeID); + LFAApprovalResult ApproveDirect(LFAApprovalRequest request, int payrollTypeID, int userID); + LFAApprovalResult SubmitForApproval(LFAApprovalRequest request, int payrollTypeID, int? employeeID, int userID); + LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID); + LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID); + LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID); } #endregion diff --git a/HRM.BO/LFA/LFAPaymentApproval.cs b/HRM.BO/LFA/LFAPaymentApproval.cs new file mode 100644 index 0000000..113304a --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentApproval.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region LFA Payment Approval (not tables) + + /// + /// LFA Payment Approval works exactly as Salary Approval: the Logic key lfaapproval/workflow decides + /// between Direct Approve ("No") and the approval workflow ("Yes"), whose approvers are set up for + /// WFTYPE 33 in Work Flow Setup and act from the Payment Approval page (/payment-approval/lfa). + /// + public static class LFAPaymentApproval + { + /// WFTYPE.WFTYPEID of LFA Payment (Salary 30, Bonus 31, Leave Encashment 32). + public const int WFTypeID = 33; + + /// Logic configuration: lfaapproval / workflow = Yes | No. + public const string LogicParent = "lfaapproval"; + public const string LogicChild = "workflow"; + } + + /// What the LFA Payment Approval page needs to know before it shows its buttons. + public class LFAApprovalInfo + { + /// lfaapproval/workflow = Yes: batches go through the approval workflow. + public bool IsWorkflowRequired { get; set; } + + /// The login is linked with an employee (the workflow needs an initiator employee). + public bool HasEmployee { get; set; } + + /// At least one approval rule is set up for LFA Payment in Work Flow Setup. + public bool HasWorkflowSetup { get; set; } + } + + /// Approve (Direct) or Submit for approval one batch. + public class LFAApprovalRequest + { + public int LFAPaymentID { get; set; } + public string Remarks { get; set; } + } + + /// An approver approves or reverts the workflow step (WFMovementTran) they received. + public class LFAApproverActionRequest + { + public int WFMovementTranID { get; set; } + public string Remarks { get; set; } + } + + public class LFAApprovalResult + { + public bool Done { get; set; } + public string Message { get; set; } + + /// True when the batch is now fully approved. + public bool Approved { get; set; } + } + + /// The batch an approver opened from the Payment Approval page. + public class LFAApproverBatch + { + public LFAApproverBatch() + { + Employees = new List(); + } + + public LFAPaymentBatch Batch { get; set; } + public List Employees { get; set; } + + /// The login is a pending approver of this step and may Approve or Revert it. + public bool CanAct { get; set; } + + /// Why the login cannot act (already acted, not their step, batch undone ...). + public string Message { get; set; } + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentUndo.cs b/HRM.BO/LFA/LFAPaymentUndo.cs index 4f722f2..fd91904 100644 --- a/HRM.BO/LFA/LFAPaymentUndo.cs +++ b/HRM.BO/LFA/LFAPaymentUndo.cs @@ -21,6 +21,16 @@ namespace HRM.BO public double TotalAmount { get; set; } public string CreatedByName { get; set; } public DateTime CreationDate { get; set; } + public string ApprovedByName { get; set; } + public DateTime? ApprovedDate { get; set; } + + // approval workflow (WFTYPE 33): the latest step of the batch, if it was ever submitted + public int? WFMovementTranID { get; set; } + public int? UniqueNumber { get; set; } + /// The batch is back with the person who submitted it (an approver reverted it to them). + public bool IsAtInitiator { get; set; } + /// Who has to act now, e.g. "Md. Karim [D1004]". + public string PendingWith { get; set; } /// Approval state in words (Not Submitted, Pending Approval, Approved, ...). public string StatusText { get; set; } diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs index 8901057..5ab61c6 100644 --- a/HRM.DA/DA/LFA/LFAPaymentDA.cs +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -44,6 +44,34 @@ namespace HRM.DA modifiedBy, modifiedDate, lfaPaymentID); } + /// Sets the batch's approval status (Not_yet_Initiated while it is in the workflow), as SalaryProcess.WFStatus. + internal static void UpdateWFStatus(TransactionContext tc, int lfaPaymentID, enumwfStatus? wfStatus) + { + tc.ExecuteNonQuery("UPDATE LFAPayment SET WFStatus=%n WHERE LFAPaymentID=%n", (int?)wfStatus, lfaPaymentID); + } + + /// The batch is approved: Direct Approve, or the last approver of the workflow. + internal static void Approve(TransactionContext tc, int lfaPaymentID, int approvedBy, DateTime approvedDate) + { + tc.ExecuteNonQuery("UPDATE LFAPayment SET WFStatus=%n, ApprovedBy=%n, ApprovedDate=%D WHERE LFAPaymentID=%n", + (int)enumwfStatus.Approve, approvedBy, approvedDate, lfaPaymentID); + } + + /// + /// Deletes the approval workflow of an undone batch (WFTYPE 33 steps, their approvers and notifications). + /// Batch IDs are reused (MAX + 1), so an old workflow must never stay behind for a new batch to inherit. + /// + internal static void DeleteWorkflow(TransactionContext tc, int lfaPaymentID) + { + const string trans = "SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE WFTYPEID=%n AND OBJECTID=%n"; + tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTTASK WHERE WFMOVEMENTTRANID IN (" + trans + ")", + LFAPaymentApproval.WFTypeID, lfaPaymentID); + tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTNEXT WHERE WFMOVEMENTTRANID IN (" + trans + ")", + LFAPaymentApproval.WFTypeID, lfaPaymentID); + tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTTRAN WHERE WFTYPEID=%n AND OBJECTID=%n", + LFAPaymentApproval.WFTypeID, lfaPaymentID); + } + /// Deletes the batch header; its detail rows must be deleted first. internal static void Delete(TransactionContext tc, int lfaPaymentID) { @@ -68,22 +96,76 @@ namespace HRM.DA return tc.ExecuteReader("SELECT * FROM LFAPayment WITH (UPDLOCK, ROWLOCK) WHERE LFAPaymentID=%n", nID); } - /// LFA Payment Undo: every batch of the payroll type with its head count and total, newest first. + /// + /// LFA Payment Undo and Approval: every batch of the payroll type with its head count, total and approval + /// workflow state (latest step, who has it now, whether it is back with the initiator), newest first. + /// internal static IDataReader GetBatches(TransactionContext tc, int payrollTypeID) { return tc.ExecuteReader( @"SELECT p.LFAPaymentID, p.BatchNumber, p.SalaryMonth, p.LFAYear, p.PaymentDate, p.Remarks, p.WFStatus, p.IsTaxUpdated, p.CreationDate, ISNULL(u.UserName, u.LoginID) AS CreatedByName, + p.ApprovedDate, ISNULL(ua.UserName, ua.LoginID) AS ApprovedByName, ISNULL(s.HeadCount, 0) AS HeadCount, ISNULL(s.PaidCount, 0) AS PaidCount, - ISNULL(s.TotalAmount, 0) AS TotalAmount + ISNULL(s.TotalAmount, 0) AS TotalAmount, + lt.WFMOVEMENTTRANID AS WFMovementTranID, lt.UNIQUENUMBER AS UniqueNumber, + CASE WHEN EXISTS (SELECT 1 FROM WFMOVEMENTNEXT n + WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n + AND n.EMPLOYEEID = it.InitiatorEmpID) THEN 1 ELSE 0 END AS IsAtInitiator, + STUFF((SELECT ', ' + e.NAME + ' [' + e.EMPLOYEENO + ']' + FROM WFMOVEMENTNEXT n INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = n.EMPLOYEEID + WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n + FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS PendingWith FROM LFAPayment p LEFT JOIN (SELECT dt.LFAPaymentID, COUNT(*) AS HeadCount, SUM(dt.Amount) AS TotalAmount, SUM(CASE WHEN dt.PaymentStatus = %n THEN 1 ELSE 0 END) AS PaidCount FROM LFAPaymentDetail dt GROUP BY dt.LFAPaymentID) s ON s.LFAPaymentID = p.LFAPaymentID LEFT JOIN Users u ON u.UserID = p.CreatedBy + LEFT JOIN Users ua ON ua.UserID = p.ApprovedBy + OUTER APPLY (SELECT TOP 1 t.WFMOVEMENTTRANID, t.UNIQUENUMBER FROM WFMOVEMENTTRAN t + WHERE t.WFTYPEID = %n AND t.OBJECTID = p.LFAPaymentID + ORDER BY t.WFMOVEMENTTRANID DESC) lt + OUTER APPLY (SELECT TOP 1 f.FROMEMPLOYEEID AS InitiatorEmpID FROM WFMOVEMENTTRAN f + WHERE f.UNIQUENUMBER = lt.UNIQUENUMBER ORDER BY f.WFMOVEMENTTRANID) it WHERE p.PayrollTypeID=%n ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC", - (int)EnumLFAPaymentStatus.Paid, payrollTypeID); + (int)EnumwfStatus.Received, (int)EnumwfStatus.Received, (int)EnumLFAPaymentStatus.Paid, + LFAPaymentApproval.WFTypeID, payrollTypeID); + } + + /// + /// The approval workflow state of one batch: its latest step (WFMovementTranID, UniqueNumber), the + /// employee who submitted it (InitiatorEmpID) and whether it is back with them now (IsAtInitiator). + /// No row when the batch was never submitted. + /// + internal static IDataReader GetWorkflowState(TransactionContext tc, int lfaPaymentID) + { + return tc.ExecuteReader( + @"SELECT lt.WFMOVEMENTTRANID AS WFMovementTranID, lt.UNIQUENUMBER AS UniqueNumber, it.InitiatorEmpID, + CASE WHEN EXISTS (SELECT 1 FROM WFMOVEMENTNEXT n + WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n + AND n.EMPLOYEEID = it.InitiatorEmpID) THEN 1 ELSE 0 END AS IsAtInitiator + FROM (SELECT TOP 1 t.WFMOVEMENTTRANID, t.UNIQUENUMBER FROM WFMOVEMENTTRAN t + WHERE t.WFTYPEID = %n AND t.OBJECTID = %n ORDER BY t.WFMOVEMENTTRANID DESC) lt + OUTER APPLY (SELECT TOP 1 f.FROMEMPLOYEEID AS InitiatorEmpID FROM WFMOVEMENTTRAN f + WHERE f.UNIQUENUMBER = lt.UNIQUENUMBER ORDER BY f.WFMOVEMENTTRANID) it", + (int)EnumwfStatus.Received, LFAPaymentApproval.WFTypeID, lfaPaymentID); + } + + /// + /// True when the employee is a pending approver of this step and the step is still the latest one of + /// its workflow (an approver who already acted, or a step that moved on, cannot act again). + /// + internal static bool IsPendingApprover(TransactionContext tc, int wfMovementTranID, int employeeID) + { + object found = tc.ExecuteScalar( + @"SELECT COUNT(*) FROM WFMOVEMENTTRAN t + INNER JOIN WFMOVEMENTNEXT n ON n.WFMOVEMENTTRANID = t.WFMOVEMENTTRANID + WHERE t.WFMOVEMENTTRANID = %n AND t.WFTYPEID = %n AND n.EMPLOYEEID = %n AND n.STATUS = %n + AND t.WFMOVEMENTTRANID = (SELECT MAX(x.WFMOVEMENTTRANID) FROM WFMOVEMENTTRAN x + WHERE x.UNIQUENUMBER = t.UNIQUENUMBER)", + wfMovementTranID, LFAPaymentApproval.WFTypeID, employeeID, (int)EnumwfStatus.Received); + return found != null && found != DBNull.Value && Convert.ToInt32(found) > 0; } /// The highest running number of the batches that start with this prefix; 0 = none yet. diff --git a/HRM.DA/DA/Workflow/WFMovementTranDA.cs b/HRM.DA/DA/Workflow/WFMovementTranDA.cs index bab6fdd..17878be 100644 --- a/HRM.DA/DA/Workflow/WFMovementTranDA.cs +++ b/HRM.DA/DA/Workflow/WFMovementTranDA.cs @@ -548,6 +548,7 @@ Union WHEN WT.wftypeid =30 THEN '/payment-approval/salary' WHEN WT.wftypeid =31 THEN '/payment-approval/bonus' WHEN WT.wftypeid =32 THEN '/payment-approval/leaveencashment' + WHEN WT.wftypeid =33 THEN '/payment-approval/lfa' ELSE 'none' END AS link,0 count FROM WFMovementTran WT, WFMovementNext WN WHERE WN.Status = 1 AND WN.EmployeeId = %n AND WT.wftypeid <> 4 AND WT.WFMovementTranID = WN.WFMovementTranID diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs index 0dd5c5b..ba6d767 100644 --- a/HRM.DA/Service/LFA/LFAPaymentService.cs +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -133,9 +133,15 @@ namespace HRM.DA batch.HeadCount = oReader.GetInt32("HeadCount").Value; batch.PaidCount = oReader.GetInt32("PaidCount").Value; batch.TotalAmount = oReader.GetDouble("TotalAmount").Value; + batch.ApprovedDate = oReader.GetDateTime("ApprovedDate"); + batch.ApprovedByName = oReader.GetString("ApprovedByName"); + batch.WFMovementTranID = oReader.GetInt32("WFMovementTranID"); + batch.UniqueNumber = oReader.GetInt32("UniqueNumber"); + batch.IsAtInitiator = oReader.GetInt32("IsAtInitiator", 0) == 1; + batch.PendingWith = oReader.GetString("PendingWith"); - batch.StatusText = StatusText(batch.WFStatus); - batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount); + batch.StatusText = StatusText(batch.WFStatus, batch.IsAtInitiator); + batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount, batch.IsAtInitiator); batch.CanUndo = batch.UndoBlockedReason == null; return batch; } @@ -569,6 +575,11 @@ namespace HRM.DA /// LFA Payment Undo: every batch of the payroll type, and whether each one can be undone. public List GetUndoBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID); + } + + private List GetBatches(int payrollTypeID) { List items = new List(); TransactionContext tc = null; @@ -683,8 +694,9 @@ namespace HRM.DA bool wholeBatch = detailIDs.Count == 0 || details.All(x => detailIDs.Contains(x.ID)); List selected = wholeBatch ? details : details.Where(x => detailIDs.Contains(x.ID)).ToList(); + bool isAtInitiator = GetIsAtInitiator(tc, oPayment.ID); string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated, - selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid)); + selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid), isAtInitiator); if (blocked != null) { result.Message = blocked; @@ -699,6 +711,7 @@ namespace HRM.DA if (wholeBatch) { LFAPaymentDetailDA.DeleteByPaymentID(tc, oPayment.ID); + LFAPaymentDA.DeleteWorkflow(tc, oPayment.ID); LFAPaymentDA.Delete(tc, oPayment.ID); result.BatchRemoved = true; result.Message = "Batch " + oPayment.BatchNumber + " is undone (" + selected.Count + " employee(s))."; @@ -729,15 +742,15 @@ namespace HRM.DA } /// - /// Why a batch cannot be undone; null when it can. Undo is allowed before the batch is submitted for - /// approval, and after the approver sends it back (Revert) or declines it. + /// Why a batch cannot be undone; null when it can. As Salary Undo: allowed before the batch is + /// submitted for approval, and when an approver has reverted it back to the person who submitted it. /// - private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount) + private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount, bool isAtInitiator) { if (wfStatus == enumwfStatus.Approve) return "The batch is already approved."; if (wfStatus != null && wfStatus != enumwfStatus.Not_yet_Submitted && wfStatus != enumwfStatus.Revert - && wfStatus != enumwfStatus.Decline) + && wfStatus != enumwfStatus.Decline && !isAtInitiator) return "The batch is submitted and pending for approval."; if (isTaxUpdated) return "The batch is already in the income tax data."; @@ -746,10 +759,12 @@ namespace HRM.DA return null; } - private static string StatusText(enumwfStatus? wfStatus) + private static string StatusText(enumwfStatus? wfStatus, bool isAtInitiator) { if (wfStatus == null || wfStatus == enumwfStatus.Not_yet_Submitted) return "Not Submitted"; + if (wfStatus != enumwfStatus.Approve && isAtInitiator) + return "Reverted to Initiator"; switch (wfStatus.Value) { case enumwfStatus.Approve: @@ -765,6 +780,498 @@ namespace HRM.DA #endregion + #region Approval + + /// Logic key, the login's employee and the Work Flow Setup of LFA Payment. + public LFAApprovalInfo GetApprovalInfo(int? employeeID) + { + LFAApprovalInfo info = new LFAApprovalInfo(); + TransactionContext tc = null; + try + { + info.IsWorkflowRequired = IsWorkflowRequired(); + info.HasEmployee = employeeID.GetValueOrDefault() > 0; + + tc = TransactionContext.Begin(); + info.HasWorkflowSetup = new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count > 0; + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return info; + } + + /// LFA Payment Approval: every batch of the payroll type with its approval state. + public List GetApprovalBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID); + } + + /// Every approval step of the batch, as Salary Approve shows its flow history. + public List GetFlowHistory(int lfaPaymentID, int payrollTypeID) + { + LFAPayment oPayment = this.Get(lfaPaymentID); + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + return new List(); + return new WFMovementTranService().GetFlowHistoriesByObjectID(lfaPaymentID, LFAPaymentApproval.WFTypeID, null) + ?? new List(); + } + + /// + /// Direct Approve (lfaapproval/workflow = No), as Salary's ApproveSalary: the batch is approved at once. + /// Refused while the workflow is on, or when the batch was already submitted or approved. + /// + public LFAApprovalResult ApproveDirect(LFAApprovalRequest request, int payrollTypeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + if (IsWorkflowRequired()) + { + result.Message = "LFA approval goes through the approval workflow. Please submit the batch for approval."; + return result; + } + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); + string blocked = oPayment == null ? "The batch is not found. It may have been undone." : DirectApproveBlockedReason(oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); + result.Done = true; + result.Approved = true; + result.Message = "Batch " + oPayment.BatchNumber + " is approved."; + } + 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; + } + + /// + /// Submit for approval (lfaapproval/workflow = Yes), as Salary's ApproveSalaryNew: a new batch starts the + /// workflow (WFTYPE 33) with the login's employee as initiator. A batch an approver reverted back to its + /// initiator is submitted again from where it stopped, as ApproveSalaryForInitiator does. + /// + public LFAApprovalResult SubmitForApproval(LFAApprovalRequest request, int payrollTypeID, int? employeeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + if (!IsWorkflowRequired()) + { + result.Message = "The LFA approval workflow is off. Please approve the batch directly."; + return result; + } + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee. The approval workflow needs an employee to submit the batch."; + return result; + } + int empID = employeeID.Value; + string remarks = (request.Remarks ?? "").Trim(); + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); + if (oPayment == null) + { + result.Message = "The batch is not found. It may have been undone."; + } + else if (oPayment.WFStatus == enumwfStatus.Approve) + { + result.Message = "Batch " + oPayment.BatchNumber + " is already approved."; + } + else if (oPayment.WFStatus == null || oPayment.WFStatus == enumwfStatus.Not_yet_Submitted) + { + // first submit: start the workflow + if (new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count == 0) + { + result.Message = "No approval workflow is set up for LFA Payment. Please set it up in Work Flow Setup first."; + } + else if (!HasEmployees(tc, oPayment.ID)) + { + result.Message = "Batch " + oPayment.BatchNumber + " has no employee."; + } + else + { + LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); + string subject = "LFA payment batch " + oPayment.BatchNumber + " (payment date " + + oPayment.PaymentDate.ToString("dd-MMM-yyyy") + "). Your approval is required."; + try + { + new WFManager(oPayment).InitiateProcess(tc, empID, LFAPaymentApproval.WFTypeID, + oPayment.ID, remarks, subject); + } + catch (Exception wfError) + { + // e.g. no rule of the setup applies to this employee + throw new ServiceException("The approval workflow could not start: " + wfError.Message + + " Please check the LFA Payment rules in Work Flow Setup.", wfError); + } + result.Done = true; + result.Message = "Batch " + oPayment.BatchNumber + " is submitted for approval."; + } + } + else + { + // already in the workflow: only the initiator, after a revert, can submit it again + WorkflowState state = GetWorkflowState(tc, oPayment.ID); + if (state == null || !state.IsAtInitiator) + { + result.Message = "Batch " + oPayment.BatchNumber + " is submitted and pending for approval."; + } + else if (state.InitiatorEmpID != empID) + { + result.Message = "Only the employee who submitted batch " + oPayment.BatchNumber + " can submit it again."; + } + else + { + string subject = "LFA payment batch " + oPayment.BatchNumber + " is submitted again"; + WFMovementTran next = new WFManager().Approve(tc, state.WFMovementTranID, empID, + remarks, subject); + result.Approved = FinishStep(tc, oPayment, next, userID); + result.Done = true; + result.Message = result.Approved + ? "Batch " + oPayment.BatchNumber + " is approved." + : "Batch " + oPayment.BatchNumber + " is submitted for approval again."; + } + } + 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; + } + + /// The batch an approver opened from the Payment Approval page, and whether they may act on it. + public LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID) + { + LFAApproverBatch result = new LFAApproverBatch(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); + if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) + { + result.Message = "The LFA approval request is not found."; + } + else + { + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, oTran.ObjectID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null) + { + result.Message = "The LFA batch is not found. It may have been undone."; + } + else + { + dr = new DataReader(LFAPaymentDA.GetBatches(tc, oPayment.PayrollTypeID)); + while (dr.Read()) + { + if (dr.GetInt32("LFAPaymentID").Value == oPayment.ID) + { + result.Batch = MapBatch(dr); + break; + } + } + dr.Close(); + + dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, oPayment.ID)); + while (dr.Read()) + { + result.Employees.Add(MapBatchEmployee(dr)); + } + dr.Close(); + + result.CanAct = employeeID.GetValueOrDefault() > 0 + && oPayment.WFStatus != enumwfStatus.Approve + && LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID.Value); + if (!result.CanAct) + { + result.Message = oPayment.WFStatus == enumwfStatus.Approve + ? "Batch " + oPayment.BatchNumber + " is already approved." + : "This approval step is not pending with you any more."; + } + } + } + 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; + } + + /// + /// An approver approves their step, as Salary's ApproveSalaryFromApprover: the workflow moves to the next + /// approver, or, after the last one, the batch is approved. + /// + public LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.WFMovementTranID <= 0) + throw new ServiceException("The LFA approval request is not found."); + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee."; + return result; + } + + tc = TransactionContext.Begin(true); + LFAPayment oPayment; + string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + string subject = "LFA payment batch " + oPayment.BatchNumber + " has been approved"; + WFMovementTran next = new WFManager().Approve(tc, request.WFMovementTranID, + employeeID.Value, (request.Remarks ?? "").Trim(), subject); + result.Approved = FinishStep(tc, oPayment, next, userID); + result.Done = true; + result.Message = result.Approved + ? "Batch " + oPayment.BatchNumber + " is approved." + : "Batch " + oPayment.BatchNumber + " is approved by you and sent to the next approver."; + } + 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; + } + + /// An approver reverts their step to the previous one (or to the initiator), as Salary's revert. + public LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.WFMovementTranID <= 0) + throw new ServiceException("The LFA approval request is not found."); + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee."; + return result; + } + string remarks = (request.Remarks ?? "").Trim(); + if (remarks.Length == 0) + { + result.Message = "Please write why the batch is reverted."; + return result; + } + + Employee oFromEmployee = new EmployeeService().Get(employeeID.Value); + tc = TransactionContext.Begin(true); + LFAPayment oPayment; + string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + string subject = "(" + (oFromEmployee != null ? oFromEmployee.EmployeeNo + ")-" + oFromEmployee.Name : employeeID + ")") + + " has reverted LFA payment batch " + oPayment.BatchNumber; + new WFManager().RevertNew(tc, request.WFMovementTranID, employeeID.Value, remarks, subject); + result.Done = true; + result.Message = "Batch " + oPayment.BatchNumber + " is reverted."; + } + 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; + } + + /// lfaapproval/workflow = Yes. + private static bool IsWorkflowRequired() + { + return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, + LFAPaymentApproval.LogicParent, LFAPaymentApproval.LogicChild); + } + + /// The batch of the payroll type, locked until the transaction ends; null when not found. + private LFAPayment GetForUpdate(TransactionContext tc, int lfaPaymentID, int payrollTypeID) + { + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + return oPayment != null && oPayment.PayrollTypeID == payrollTypeID ? oPayment : null; + } + + private static string DirectApproveBlockedReason(LFAPayment oPayment) + { + if (oPayment.WFStatus == enumwfStatus.Approve) + return "Batch " + oPayment.BatchNumber + " is already approved."; + if (oPayment.WFStatus != null && oPayment.WFStatus != enumwfStatus.Not_yet_Submitted) + return "Batch " + oPayment.BatchNumber + " is in the approval workflow. It is approved from the Payment Approval page."; + return null; + } + + private static bool HasEmployees(TransactionContext tc, int lfaPaymentID) + { + DataReader dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, lfaPaymentID)); + bool any = dr.Read(); + dr.Close(); + return any; + } + + /// + /// Why the employee cannot act on this step (null when they can): the step must be an LFA one, still the + /// latest of its workflow, pending with them, and its batch must exist and not be approved yet. + /// The batch is locked until the transaction ends. + /// + private string CheckApproverStep(TransactionContext tc, int wfMovementTranID, int employeeID, out LFAPayment oPayment) + { + oPayment = null; + WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); + if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) + return "The LFA approval request is not found."; + + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, oTran.ObjectID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null) + return "The LFA batch is not found. It may have been undone."; + if (oPayment.WFStatus == enumwfStatus.Approve) + return "Batch " + oPayment.BatchNumber + " is already approved."; + if (!LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID)) + return "This approval step is not pending with you any more."; + return null; + } + + /// + /// After a workflow step: the batch is approved when the workflow ended, otherwise it stays in the + /// workflow (Not_yet_Initiated), as Salary's ApproveSalaryNew. Returns true when approved. + /// + private static bool FinishStep(TransactionContext tc, LFAPayment oPayment, WFMovementTran next, int userID) + { + if (next != null && next.Status == EnumwfStatus.End) + { + LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); + return true; + } + LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); + return false; + } + + private class WorkflowState + { + public int WFMovementTranID; + public int InitiatorEmpID; + public bool IsAtInitiator; + } + + private static WorkflowState GetWorkflowState(TransactionContext tc, int lfaPaymentID) + { + WorkflowState state = null; + DataReader dr = new DataReader(LFAPaymentDA.GetWorkflowState(tc, lfaPaymentID)); + if (dr.Read()) + { + state = new WorkflowState + { + WFMovementTranID = dr.GetInt32("WFMovementTranID").Value, + InitiatorEmpID = dr.GetInt32("InitiatorEmpID", 0), + IsAtInitiator = dr.GetInt32("IsAtInitiator", 0) == 1 + }; + } + dr.Close(); + return state; + } + + private static bool GetIsAtInitiator(TransactionContext tc, int lfaPaymentID) + { + WorkflowState state = GetWorkflowState(tc, lfaPaymentID); + return state != null && state.IsAtInitiator; + } + + #endregion + #region Helpers private static void CheckRequest(LFAPaymentRequest request) diff --git a/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts index e56a4dc..152414d 100644 --- a/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts +++ b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts @@ -98,6 +98,13 @@ export class LFAPaymentBatch { totalAmount: number; createdByName: string; creationDate: Date; + approvedByName: string; + approvedDate: Date; + // approval workflow (WFTYPE 33) + wfMovementTranID: number; + uniqueNumber: number; + isAtInitiator: boolean; + pendingWith: string; statusText: string; canUndo: boolean; undoBlockedReason: string; @@ -131,3 +138,35 @@ export class LFAPaymentUndoResult { removedCount: number; batchRemoved: boolean; } + +// ── LFA Payment Approval (as Salary Approve) ── + +export class LFAApprovalInfo { + /** Logic lfaapproval/workflow = Yes */ + isWorkflowRequired: boolean; + hasEmployee: boolean; + hasWorkflowSetup: boolean; +} + +export class LFAApprovalRequest { + lfaPaymentID: number; + remarks: string; +} + +export class LFAApproverActionRequest { + wfMovementTranID: number; + remarks: string; +} + +export class LFAApprovalResult { + done: boolean; + message: string; + approved: boolean; +} + +export class LFAApproverBatch { + batch: LFAPaymentBatch; + employees: LFAPaymentBatchEmployee[]; + canAct: boolean; + message: string; +} diff --git a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts index 228a3f8..e8179ea 100644 --- a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts @@ -2,9 +2,11 @@ import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ApiService } from '../../app.api.service'; import { + LFAApprovalInfo, LFAApprovalRequest, LFAApprovalResult, LFAApproverActionRequest, LFAApproverBatch, LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentUndoRequest, LFAPaymentUndoResult } from '../../_models/Payroll/lfaPayment'; +import { WFFlowHistory } from '../../_models/Work-Flow/wFMovementNext'; @Injectable({ providedIn: 'root' @@ -59,4 +61,42 @@ export class LFAService { undoPayment(request: LFAPaymentUndoRequest): Observable { return this.apiService.httpPost('/lfa/undoPayment', request); } + + // ── LFA Payment Approval (as Salary Approve) ── + + getApprovalInfo(): Observable { + return this.apiService.httpGet('/lfa/getApprovalInfo'); + } + + getApprovalBatches(): Observable { + return this.apiService.httpGet('/lfa/getApprovalBatches'); + } + + getFlowHistory(lfaPaymentID: number): Observable { + return this.apiService.httpGet('/lfa/getFlowHistory/' + lfaPaymentID); + } + + /** Workflow off: approve at once. */ + approveDirect(request: LFAApprovalRequest): Observable { + return this.apiService.httpPost('/lfa/approveDirect', request); + } + + /** Workflow on: submit (or submit again after a revert). */ + submitForApproval(request: LFAApprovalRequest): Observable { + return this.apiService.httpPost('/lfa/submitForApproval', request); + } + + // the approver's side (/payment-approval/lfa) + + getApproverBatch(wfMovementTranID: number): Observable { + return this.apiService.httpGet('/lfa/getApproverBatch/' + wfMovementTranID); + } + + approveFromApprover(request: LFAApproverActionRequest): Observable { + return this.apiService.httpPost('/lfa/approveFromApprover', request); + } + + revertFromApprover(request: LFAApproverActionRequest): Observable { + return this.apiService.httpPost('/lfa/revertFromApprover', request); + } } diff --git a/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.html b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.html new file mode 100644 index 0000000..99221ac --- /dev/null +++ b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.html @@ -0,0 +1,72 @@ + + +
    +
    LFA Payment Approval
    + + @if (data && data.batch) { +
    +
    Batch ID
    {{ data.batch.batchNumber }}
    +
    Payment Date
    {{ data.batch.paymentDate | date: 'dd-MMM-yyyy' }}
    +
    LFA Year
    {{ data.batch.lfaYear | date: 'yyyy' }}
    +
    Employees
    {{ data.batch.headCount }}
    +
    Total LFA Amount (BDT)
    {{ data.batch.totalAmount | number: '1.2-2' }}
    +
    + @if (data.batch.remarks) { +
    Remarks of the batch: {{ data.batch.remarks }}
    + } + +
    + Employees + + +
    + + + + + + + + + No employee in this batch. + + + } @else if (data && data.message) { +
    {{ data.message }}
    + } + + @if (flowHistory.length > 0) { +
    Approval History
    + + + {{ dataItem.employeeNo }} - {{ dataItem.employeeName }} + + + {{ dataItem.tranDate | date: 'dd-MMM-yyyy' }} + + + {{ flowStatusText(dataItem.status) }} + + + {{ dataItem.statusUpdateDate | date: 'dd-MMM-yyyy hh:mm a' }} + + + + } + + @if (data && data.batch) { + @if (canAct) { +
    +
    + + +
    + + +
    + } @else if (data.message) { +
    {{ data.message }}
    + } + } +
    diff --git a/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.scss b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.scss new file mode 100644 index 0000000..09bb364 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.scss @@ -0,0 +1,88 @@ +/* Payment Approval › LFA: layout only; colours are the theme's --gh-* variables */ +.lfa-apv { + display: flex; + flex-direction: column; + gap: 12px; + padding: 8px 4px; +} + +.lfa-apv__title { + font-size: 18px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-apv__sub { + font-size: 14px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-apv__head { + display: flex; + align-items: center; + gap: 10px; +} + +.lfa-apv__spacer { + flex: 1 1 auto; +} + +.lfa-apv__note { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-apv__blocked { + padding: 8px 12px; + border-radius: 6px; + font-weight: 600; + color: var(--gh-dn); + background: color-mix(in srgb, var(--gh-dn) 10%, transparent); +} + +.lfa-apv__action { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px; +} + +.lfa-apv__remarks { + display: flex; + flex-direction: column; + gap: 4px; + width: 420px; + max-width: 100%; + + label { + font-size: 12px; + font-weight: 600; + color: var(--gh-muted); + } +} + +.lfa-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); + gap: 12px; +} + +.lfa-stat { + padding: 12px 14px; + border: 1px solid var(--gh-bo); + border-radius: 6px; + background: var(--gh-tb); +} + +.lfa-stat__key { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-stat__value { + margin-top: 4px; + font-size: 18px; + font-weight: 700; + color: var(--gh-lk); +} diff --git a/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.ts b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.ts new file mode 100644 index 0000000..ff19259 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/payment-approval/lfa-approval/lfa-approval.component.ts @@ -0,0 +1,168 @@ +import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { ExcelExportData } from '@progress/kendo-angular-excel-export'; +import { ApiService } from 'src/app/app.api.service'; +import { HRMNotificationService } from 'src/app/app.notification.service'; +import { DataTransferService } from 'src/app/data.transfer.service'; +import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service'; +import { LFAService } from 'src/app/_services/payroll/lfa.service'; +import { WorkflowService } from 'src/app/_services/workflow/workflow.service'; +import { WFFlowHistory } from 'src/app/_models/Work-Flow/wFMovementNext'; +import { + EnumLFAPaymentStatus, LFAApprovalResult, LFAApproverBatch, LFAPaymentBatchEmployee +} from 'src/app/_models/Payroll/lfaPayment'; + +/** + * Payment Approval › LFA (/payment-approval/lfa): an approver opens the LFA batch they received from their + * pending list and approves it (to the next approver, or finally) or reverts it, as for the salary. + */ +@Component({ + selector: 'app-lfa-approval', + templateUrl: './lfa-approval.component.html', + styleUrls: ['./lfa-approval.component.scss'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false +}) +export class LfaApprovalComponent implements OnInit { + + wfMovementTranID = 0; + data: LFAApproverBatch = null; + employees: LFAPaymentBatchEmployee[] = []; + flowHistory: WFFlowHistory[] = []; + remarks = ''; + isBusy = false; + acted = false; + + constructor(public apiService: ApiService, + public notificationService: HRMNotificationService, + public loadingPanel: loadingPanelService, + private dataTransferService: DataTransferService, + private workflowService: WorkflowService, + private lfaService: LFAService) { + this.apiService.selectedMenuName = 'LFA Payment Approval'; + } + + ngOnInit() { + // the pending list puts the workflow step (WFMovementTranID) here before it opens the page + this.wfMovementTranID = Number(this.dataTransferService.getData()) || 0; + this.load(); + } + + load() { + if (!this.wfMovementTranID) { + this.notificationService.showWarning('Please open the LFA approval request from your pending list.'); + return; + } + this.start(); + this.lfaService.getApproverBatch(this.wfMovementTranID).subscribe({ + next: (resp) => { + this.data = resp; + this.employees = (resp && resp.employees || []).map(x => ({ + ...x, + joiningDate: this.toDate(x.joiningDate), + statusText: this.paymentStatusText(x.paymentStatus) + })); + if (resp && resp.batch) { + resp.batch.paymentDate = this.toDate(resp.batch.paymentDate); + resp.batch.lfaYear = this.toDate(resp.batch.lfaYear); + } + this.workflowService.getFlowHistorybyTranID(this.wfMovementTranID).subscribe({ + next: (history: any) => { + this.stop(); + this.flowHistory = history || []; + }, + error: () => this.stop() + }); + }, + error: (err) => this.fail(err, 'Could not load the LFA approval request.') + }); + } + + get canAct(): boolean { + return !!this.data && this.data.canAct && !this.acted; + } + + approve() { + if (!this.canAct || this.isBusy) { + return; + } + this.notificationService.showActiveConfirm('Confirmation', 'Are you sure to approve this LFA payment batch?').then((isConfirmed) => { + if (isConfirmed) { + this.send(this.lfaService.approveFromApprover({ wfMovementTranID: this.wfMovementTranID, remarks: this.remarks })); + } + }); + } + + revert() { + if (!this.canAct || this.isBusy) { + return; + } + if (!this.remarks || !this.remarks.trim()) { + this.notificationService.showWarning('Please write in Remarks why the batch is reverted.'); + return; + } + this.notificationService.showActiveConfirm('Confirmation', 'Are you sure to revert this LFA payment batch?').then((isConfirmed) => { + if (isConfirmed) { + this.send(this.lfaService.revertFromApprover({ wfMovementTranID: this.wfMovementTranID, remarks: this.remarks })); + } + }); + } + + private send(call: any) { + this.start(); + call.subscribe({ + next: (resp: LFAApprovalResult) => { + this.stop(); + if (resp.done) { + this.acted = true; + this.notificationService.showSuccess(resp.message); + } else { + this.notificationService.showError(resp.message); + } + this.load(); + }, + error: (err) => this.fail(err, 'Nothing was changed. Please try again.') + }); + } + + allEmployees = (): ExcelExportData => ({ data: this.employees }); + + flowStatusText(status: number): string { + switch (status) { // the workflow's EnumwfStatus + case 0: return 'Submitted'; + case 1: return 'Received & Working'; + case 2: return 'Reverted'; + case 3: return 'Declined'; + case 4: return 'Approved'; + case 7: return 'Completed'; + default: return ''; + } + } + + private paymentStatusText(status: EnumLFAPaymentStatus): string { + switch (status) { + case EnumLFAPaymentStatus.Paid: return 'Paid'; + case EnumLFAPaymentStatus.Failed: return 'Failed'; + default: return 'Pending'; + } + } + + private start() { + this.isBusy = true; + this.loadingPanel.ShowLoadingPanel = true; + } + + private stop() { + this.isBusy = false; + this.loadingPanel.ShowLoadingPanel = false; + } + + private fail(err: any, fallback: string) { + this.stop(); + const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : ''; + this.notificationService.showError(text || fallback); + } + + private toDate(value: any): Date { + return value ? new Date(value) : null; + } +} diff --git a/HRM.UI/ClientApp/src/app/payment-approval/payment-approval-routing.module.ts b/HRM.UI/ClientApp/src/app/payment-approval/payment-approval-routing.module.ts index aa70a6c..b96af42 100644 --- a/HRM.UI/ClientApp/src/app/payment-approval/payment-approval-routing.module.ts +++ b/HRM.UI/ClientApp/src/app/payment-approval/payment-approval-routing.module.ts @@ -3,12 +3,14 @@ import { RouterModule, Routes } from '@angular/router'; import { PaymentApprovalComponent } from './payment-approval/payment-approval.component'; import { AuthGuard } from '../_guards/auth.guard'; import { ApprovalHistoryComponent } from './approval-history/approval-history.component'; +import { LfaApprovalComponent } from './lfa-approval/lfa-approval.component'; export const routes: Routes = [ { path: 'salary', component: PaymentApprovalComponent, canActivate: [AuthGuard] }, { path: 'bonus', component: PaymentApprovalComponent, canActivate: [AuthGuard] }, { path: 'leaveencashment', component: PaymentApprovalComponent, canActivate: [AuthGuard] }, { path: 'opi', component: PaymentApprovalComponent, canActivate: [AuthGuard] }, + { path: 'lfa', component: LfaApprovalComponent, canActivate: [AuthGuard] }, { path: 'approval-history', component: ApprovalHistoryComponent, canActivate: [AuthGuard] }, ]; diff --git a/HRM.UI/ClientApp/src/app/payment-approval/payment-approval.module.ts b/HRM.UI/ClientApp/src/app/payment-approval/payment-approval.module.ts index d39a7cb..12df297 100644 --- a/HRM.UI/ClientApp/src/app/payment-approval/payment-approval.module.ts +++ b/HRM.UI/ClientApp/src/app/payment-approval/payment-approval.module.ts @@ -38,13 +38,15 @@ import { EmpLifeCycleServices } from '../_services/employee/empLifeCycle.service import { PaymentApprovalRoutingModule } from './payment-approval-routing.module'; import { PaymentApprovalComponent } from './payment-approval/payment-approval.component'; import { ApprovalHistoryComponent } from './approval-history/approval-history.component'; +import { LfaApprovalComponent } from './lfa-approval/lfa-approval.component'; import { BackgroundCanvasModule } from '../BackgroundCanvas/BackgroundCanvas.module'; @NgModule({ declarations: [ PaymentApprovalComponent, - ApprovalHistoryComponent + ApprovalHistoryComponent, + LfaApprovalComponent ], imports: [ CommonModule, diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.html b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.html index cd96c1d..58eaa29 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.html +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.html @@ -1,8 +1,149 @@ -
    - - LFA Payment Approval - - - + +
    + + @if (info) { +
    + @if (isWorkflow) { + Approval Workflow is on. Submit a batch for approval; the approvers set up for LFA Payment in Work Flow Setup approve it one after another from the Payment Approval page. + @if (!info.hasWorkflowSetup) { +
    No approval workflow is set up for LFA Payment yet. Please set it up in Work Flow Setup.
    + } + @if (!info.hasEmployee) { +
    Your login is not linked with an employee, so you cannot submit a batch for approval.
    + } + } @else { + Direct Approve. The approval workflow is off; a batch is approved here at once. + } +
    + } + + +
    + LFA Batches + + + +
    + + + + + + {{ dataItem.lfaYear | date: 'yyyy' }} + + + + + + {{ dataItem.statusText }} + + + + {{ dataItem.wfStatus === approvedStatus ? '' : dataItem.pendingWith }} + + + + + + + + + {{ showApproved ? 'No LFA batch found.' : 'No LFA batch is waiting for approval.' }} + + + + @if (selectedBatch) { +
    + Batch {{ selectedBatch.batchNumber }} + {{ selectedBatch.statusText }} + + + +
    + +
    +
    Payment Date
    {{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }}
    +
    Employees
    {{ selectedBatch.headCount }}
    +
    Total LFA Amount (BDT)
    {{ selectedBatch.totalAmount | number: '1.2-2' }}
    +
    +
    {{ selectedBatch.wfStatus === approvedStatus ? 'Approved By' : 'Pending With' }}
    +
    {{ selectedBatch.wfStatus === approvedStatus ? (selectedBatch.approvedByName || '—') : (selectedBatch.pendingWith || '—') }}
    +
    +
    + + + + + + + + + + + No employee in this batch. + + + + @if (flowHistory.length > 0) { +
    Approval History
    + + + {{ dataItem.employeeNo }} - {{ dataItem.employeeName }} + + + {{ dataItem.tranDate | date: 'dd-MMM-yyyy' }} + + + {{ flowStatusText(dataItem.status) }} + + + {{ dataItem.statusUpdateDate | date: 'dd-MMM-yyyy hh:mm a' }} + + + + } + + @if (selectedBatch.wfStatus !== approvedStatus) { +
    +
    + + +
    + +
    + @if (actionBlockedReason) { +
    {{ actionBlockedReason }}
    + } + } + }
    + +@if (showConfirm && selectedBatch) { +
    + + @if (isWorkflow) { +

    Batch {{ selectedBatch.batchNumber }} will be sent to the approvers of LFA Payment.

    + } @else { +

    Batch {{ selectedBatch.batchNumber }} will be approved. This cannot be reversed.

    + } + + + + + + + +
    Batch ID{{ selectedBatch.batchNumber }}
    Payment Date{{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }}
    Employees{{ selectedBatch.headCount }}
    Total LFA AmountBDT {{ selectedBatch.totalAmount | number: '1.2-2' }}
    + + + + +
    +
    +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.scss b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.scss index e69de29..e88e688 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.scss +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.scss @@ -0,0 +1,145 @@ +/* LFA Payment Approval: layout only; colours are the theme's --gh-* variables */ +.lfa-appr { + display: flex; + flex-direction: column; + gap: 12px; + padding: 8px 4px; +} + +.lfa-appr__mode { + padding: 10px 14px; + border-radius: 6px; + border: 1px solid var(--gh-bo); + background: var(--gh-tb); +} + +.lfa-appr__mode--wf { + border-color: color-mix(in srgb, var(--gh-lk) 40%, transparent); +} + +.lfa-appr__warn { + margin-top: 6px; + font-weight: 600; + color: var(--gh-dn); +} + +.lfa-appr__head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.lfa-appr__title { + font-size: 16px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-appr__title--small { + font-size: 14px; +} + +.lfa-appr__spacer { + flex: 1 1 auto; +} + +.lfa-appr__check { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; +} + +.lfa-appr__action { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px; +} + +.lfa-appr__remarks { + display: flex; + flex-direction: column; + gap: 4px; + width: 420px; + max-width: 100%; + + label { + font-size: 12px; + font-weight: 600; + color: var(--gh-muted); + } +} + +.lfa-appr__note { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-selected { + border-color: var(--gh-lk); + color: var(--gh-lk); +} + +.lfa-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; +} + +.lfa-stat { + padding: 12px 14px; + border: 1px solid var(--gh-bo); + border-radius: 6px; + background: var(--gh-tb); +} + +.lfa-stat__key { + font-size: 12px; + color: var(--gh-muted); +} + +.lfa-stat__value { + margin-top: 4px; + font-size: 18px; + font-weight: 700; + color: var(--gh-lk); +} + +.lfa-stat__value--small { + font-size: 14px; +} + +.lfa-badge { + display: inline-block; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + color: var(--gh-warn); + background: color-mix(in srgb, var(--gh-warn) 15%, transparent); +} + +.lfa-badge--ok { + color: var(--gh-ok); + background: color-mix(in srgb, var(--gh-ok) 15%, transparent); +} + +.lfa-badge--back { + color: var(--gh-dn); + background: color-mix(in srgb, var(--gh-dn) 12%, transparent); +} + +.lfa-confirm { + width: 100%; + + td { + padding: 4px 0; + } + + td:last-child { + text-align: right; + font-weight: 600; + } +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.ts index e2626dd..d9dd1d8 100644 --- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment-approval/lfa-payment-approval.component.ts @@ -1,6 +1,20 @@ import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { ExcelExportData } from '@progress/kendo-angular-excel-export'; import { ApiService } from '../../app.api.service'; +import { HRMNotificationService } from '../../app.notification.service'; +import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service'; +import { LFAService } from '../../_services/payroll/lfa.service'; +import { WFFlowHistory } from '../../_models/Work-Flow/wFMovementNext'; +import { + EnumLFAPaymentStatus, LFAApprovalInfo, LFAApprovalResult, LFAPaymentBatch, LFAPaymentBatchEmployee +} from '../../_models/Payroll/lfaPayment'; +/** + * LFA Payment Approval, as Salary Approve: the Logic key lfaapproval/workflow decides between Direct Approve + * ("No") and Submit for Approval ("Yes"). In the workflow the approvers set up for LFA Payment in Work Flow + * Setup act one after another from the Payment Approval page; a reverted batch comes back here to be + * submitted again. The server checks everything again. + */ @Component({ selector: 'app-lfa-payment-approval', templateUrl: './lfa-payment-approval.component.html', @@ -10,10 +24,220 @@ import { ApiService } from '../../app.api.service'; }) export class LfaPaymentApprovalComponent implements OnInit { - constructor(public apiService: ApiService) { + readonly approvedStatus = 5; // enumwfStatus.Approve + + info: LFAApprovalInfo = null; + batches: LFAPaymentBatch[] = []; + showApproved = false; + selectedBatch: LFAPaymentBatch = null; + employees: LFAPaymentBatchEmployee[] = []; + flowHistory: WFFlowHistory[] = []; + remarks = ''; + isBusy = false; + showConfirm = false; + + constructor(public apiService: ApiService, + public notificationService: HRMNotificationService, + public loadingPanel: loadingPanelService, + private lfaService: LFAService) { this.apiService.selectedMenuName = 'LFA Payment Approval'; } ngOnInit() { + this.start(); + this.lfaService.getApprovalInfo().subscribe({ + next: (resp) => { + this.info = resp; + this.loadBatches(); + }, + error: (err) => this.fail(err, 'Could not read the LFA approval settings.') + }); + } + + // ── Batches ───────────────────────────────────────────────────── + + get visibleBatches(): LFAPaymentBatch[] { + return this.showApproved ? this.batches : this.batches.filter(x => x.wfStatus !== this.approvedStatus); + } + + loadBatches(keepBatchID: number = 0) { + this.start(); + this.lfaService.getApprovalBatches().subscribe({ + next: (resp) => { + this.stop(); + this.batches = (resp || []).map(x => ({ + ...x, + paymentDate: this.toDate(x.paymentDate), + lfaYear: this.toDate(x.lfaYear), + creationDate: this.toDate(x.creationDate), + approvedDate: this.toDate(x.approvedDate) + })); + const keep = keepBatchID ? this.batches.find(x => x.lfaPaymentID === keepBatchID) : null; + if (keep) { + this.viewBatch(keep); + } else { + this.clearBatch(); + } + }, + error: (err) => this.fail(err, 'Could not load the LFA batches.') + }); + } + + viewBatch(batch: LFAPaymentBatch) { + this.selectedBatch = batch; + this.employees = []; + this.flowHistory = []; + this.remarks = ''; + this.start(); + this.lfaService.getBatchEmployees(batch.lfaPaymentID).subscribe({ + next: (resp) => { + this.employees = (resp || []).map(x => ({ + ...x, + joiningDate: this.toDate(x.joiningDate), + statusText: this.paymentStatusText(x.paymentStatus) + })); + if (!batch.wfMovementTranID) { + this.stop(); + return; + } + this.lfaService.getFlowHistory(batch.lfaPaymentID).subscribe({ + next: (history) => { + this.stop(); + this.flowHistory = history || []; + }, + error: (err) => this.fail(err, 'Could not load the approval history.') + }); + }, + error: (err) => this.fail(err, 'Could not load the employees of the batch.') + }); + } + + clearBatch() { + this.selectedBatch = null; + this.employees = []; + this.flowHistory = []; + this.remarks = ''; + } + + // ── What the selected batch allows ────────────────────────────── + + get isWorkflow(): boolean { + return !!this.info && this.info.isWorkflowRequired; + } + + /** The batch has not been approved or submitted yet. */ + get isNew(): boolean { + const b = this.selectedBatch; + return !!b && (b.wfStatus === null || b.wfStatus === undefined || b.wfStatus === 8); + } + + get actionLabel(): string { + if (!this.isWorkflow) { + return 'Approve'; + } + return this.selectedBatch && this.selectedBatch.isAtInitiator ? 'Submit Again' : 'Submit for Approval'; + } + + /** Why the button is disabled; empty when it can be used. */ + get actionBlockedReason(): string { + const b = this.selectedBatch; + if (!b || !this.info) { + return 'Please select a batch.'; + } + if (b.wfStatus === this.approvedStatus) { + return 'This batch is already approved.'; + } + if (b.headCount === 0) { + return 'This batch has no employee.'; + } + if (!this.isWorkflow) { + return this.isNew ? '' : 'This batch is in the approval workflow; it is approved from the Payment Approval page.'; + } + if (!this.info.hasEmployee) { + return 'Your login is not linked with an employee. The approval workflow needs an employee to submit the batch.'; + } + if (this.isNew) { + return this.info.hasWorkflowSetup ? '' : 'No approval workflow is set up for LFA Payment. Please set it up in Work Flow Setup first.'; + } + return b.isAtInitiator ? '' : 'This batch is submitted and pending for approval' + (b.pendingWith ? ' with ' + b.pendingWith : '') + '.'; + } + + confirmAction() { + const reason = this.actionBlockedReason; + if (reason) { + this.notificationService.showWarning(reason); + return; + } + this.showConfirm = true; + } + + act() { + if (this.isBusy || !this.selectedBatch) { + return; + } + const batchID = this.selectedBatch.lfaPaymentID; + const request = { lfaPaymentID: batchID, remarks: this.remarks }; + const call = this.isWorkflow ? this.lfaService.submitForApproval(request) : this.lfaService.approveDirect(request); + this.start(); + call.subscribe({ + next: (resp: LFAApprovalResult) => { + this.stop(); + this.showConfirm = false; + if (resp.done) { + this.notificationService.showSuccess(resp.message); + } else { + this.notificationService.showError(resp.message); + } + this.loadBatches(batchID); + }, + error: (err) => { + this.showConfirm = false; + this.fail(err, 'Nothing was changed. Please try again.'); + } + }); + } + + allEmployees = (): ExcelExportData => ({ data: this.employees }); + + flowStatusText(status: number): string { + switch (status) { // the workflow's EnumwfStatus + case 0: return 'Submitted'; + case 1: return 'Received & Working'; + case 2: return 'Reverted'; + case 3: return 'Declined'; + case 4: return 'Approved'; + case 7: return 'Completed'; + default: return ''; + } + } + + // ── Helpers ───────────────────────────────────────────────────── + + private paymentStatusText(status: EnumLFAPaymentStatus): string { + switch (status) { + case EnumLFAPaymentStatus.Paid: return 'Paid'; + case EnumLFAPaymentStatus.Failed: return 'Failed'; + default: return 'Pending'; + } + } + + private start() { + this.isBusy = true; + this.loadingPanel.ShowLoadingPanel = true; + } + + private stop() { + this.isBusy = false; + this.loadingPanel.ShowLoadingPanel = false; + } + + private fail(err: any, fallback: string) { + this.stop(); + const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : ''; + this.notificationService.showError(text || fallback); + } + + private toDate(value: any): Date { + return value ? new Date(value) : null; } } diff --git a/HRM.UI/Controllers/Payroll/LFAController.cs b/HRM.UI/Controllers/Payroll/LFAController.cs index cf94821..468ee53 100644 --- a/HRM.UI/Controllers/Payroll/LFAController.cs +++ b/HRM.UI/Controllers/Payroll/LFAController.cs @@ -154,6 +154,147 @@ namespace HRM.UI.Controllers.Payroll } } + // ── LFA Payment Approval (as Salary Approve: Direct Approve or the approval workflow, Logic lfaapproval/workflow) ── + + /// Logic key, whether the login has an employee, and whether Work Flow Setup has LFA rules. + [HttpGet("getApprovalInfo")] + public ActionResult GetApprovalInfo() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetApprovalInfo(currentUser.EmployeeID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpGet("getApprovalBatches")] + public ActionResult GetApprovalBatches() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetApprovalBatches(currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpGet("getFlowHistory/{lfaPaymentID}")] + public ActionResult GetFlowHistory(int lfaPaymentID) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.GetFlowHistory(lfaPaymentID, currentUser.PayrollTypeID.GetValueOrDefault())); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// Direct Approve, when the workflow is off. + [HttpPost("approveDirect")] + public ActionResult ApproveDirect(LFAApprovalRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.ApproveDirect(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + /// Submit for approval (or submit again after a revert), when the workflow is on. + [HttpPost("submitForApproval")] + public ActionResult SubmitForApproval(LFAApprovalRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return NotAllowed(); + } + try + { + return Ok(this._lfaPaymentService.SubmitForApproval(request, currentUser.PayrollTypeID.GetValueOrDefault(), + currentUser.EmployeeID, currentUser.UserID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + // The approver's side (/payment-approval/lfa). Approvers act as employees, as on Salary's Payment Approval + // page, so these are open to every login; the service checks that the step is pending with the login. + + [HttpGet("getApproverBatch/{wfMovementTranID}")] + public ActionResult GetApproverBatch(int wfMovementTranID) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + try + { + return Ok(this._lfaPaymentService.GetApproverBatch(wfMovementTranID, currentUser.EmployeeID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpPost("approveFromApprover")] + public ActionResult ApproveFromApprover(LFAApproverActionRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + try + { + return Ok(this._lfaPaymentService.ApproveFromApprover(request, currentUser.EmployeeID, currentUser.UserID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + + [HttpPost("revertFromApprover")] + public ActionResult RevertFromApprover(LFAApproverActionRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + try + { + return Ok(this._lfaPaymentService.RevertFromApprover(request, currentUser.EmployeeID)); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } + private ActionResult NotAllowed() { return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment."); From fa8c19b2095237ee492d3be6ffa6b1105542ce55 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Sun, 29 Nov 2026 09:50:10 +0600 Subject: [PATCH 7/9] LFA BANK Advice --- HRM.BO/HRBasic/Enums.cs | 3 +- HRM.BO/LFA/LFAPayment.cs | 4 + HRM.DA/DA/LFA/LFAPaymentDA.cs | 32 +++++ HRM.DA/Service/LFA/LFAPaymentService.cs | 59 +++++++++ HRM.Report/Class/rptLFABankAdvice.cs | 85 +++++++++++++ HRM.Report/HRM.Report.csproj | 2 + HRM.Report/RDLC/LFABankAdvice.rdlc | 19 +++ HRM.UI/ClientApp/src/app/_models/enums.ts | 1 + .../lfa-bank-advice.component.html | 8 -- .../lfa-bank-advice.component.scss | 0 .../lfa-bank-advice.component.ts | 19 --- .../payroll-lfa/payroll-lfa-routing.module.ts | 6 +- .../src/app/payroll-lfa/payroll-lfa.module.ts | 4 +- .../report-viewer/report-viewer.component.ts | 115 ++++++++++++++++++ HRM.UI/Controllers/Payroll/LFAController.cs | 19 +++ HRM.UI/Controllers/Report/ReportController.cs | 4 + 16 files changed, 347 insertions(+), 33 deletions(-) create mode 100644 HRM.Report/Class/rptLFABankAdvice.cs create mode 100644 HRM.Report/RDLC/LFABankAdvice.rdlc delete mode 100644 HRM.UI/ClientApp/src/app/payroll-lfa/lfa-bank-advice/lfa-bank-advice.component.html delete mode 100644 HRM.UI/ClientApp/src/app/payroll-lfa/lfa-bank-advice/lfa-bank-advice.component.scss delete mode 100644 HRM.UI/ClientApp/src/app/payroll-lfa/lfa-bank-advice/lfa-bank-advice.component.ts diff --git a/HRM.BO/HRBasic/Enums.cs b/HRM.BO/HRBasic/Enums.cs index fad6fef..1b4f3ec 100644 --- a/HRM.BO/HRBasic/Enums.cs +++ b/HRM.BO/HRBasic/Enums.cs @@ -2439,7 +2439,8 @@ namespace HRM.BO ITReport177Yearly = 1005, TAXReconciliation = 1006, BasePay = 1008, - ITReport177Quaterly = 1010 + ITReport177Quaterly = 1010, + LFABankAdvice = 1201 } diff --git a/HRM.BO/LFA/LFAPayment.cs b/HRM.BO/LFA/LFAPayment.cs index 36cc42c..2514326 100644 --- a/HRM.BO/LFA/LFAPayment.cs +++ b/HRM.BO/LFA/LFAPayment.cs @@ -181,6 +181,10 @@ namespace HRM.BO LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID); LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID); LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID); + + // LFA Bank Advice (report viewer, EnumReportType.LFABankAdvice) + List GetBankAdviceBatches(int payrollTypeID); + System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID); } #endregion diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs index 5ab61c6..f3fb467 100644 --- a/HRM.DA/DA/LFA/LFAPaymentDA.cs +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -281,6 +281,38 @@ namespace HRM.DA payrollTypeID, fromDate, toDate); } + /// + /// LFA Bank Advice: the employees of one batch with an amount to pay, with the bank account kept on the + /// detail row when the batch was processed. empIDs = joined ints made by the service (empty = whole batch); + /// bankID 0 = every bank. + /// + internal static DataSet GetBankAdvice(TransactionContext tc, int lfaPaymentID, string empIDs, int bankID, int payrollTypeID) + { + string sql = SQLParser.MakeSQL( + @"SELECT e.EMPLOYEENO, e.NAME, e.EMAILADDRESS, ds.NAME AS DesignationName, d.DESCRIPTION AS DepartmentName, + ISNULL(cc.DESCRIPTION, '') AS CostCenter, dt.AccountNo, ISNULL(bk.NAME, '') AS BankName, + ISNULL(br.NAME, '') AS BranchName, ISNULL(br.ROUTINGNO, '') AS RoutingNo, dt.Amount, + p.BatchNumber, p.PaymentDate, p.LFAYear + FROM LFAPayment p + INNER JOIN LFAPaymentDetail dt ON dt.LFAPaymentID = p.LFAPaymentID + INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = dt.EmployeeID + LEFT JOIN DESIGNATION ds ON ds.DESIGNATIONID = dt.DesignationID + LEFT JOIN DEPARTMENT d ON d.DEPARTMENTID = dt.DepartmentID + LEFT JOIN CRG cc ON cc.CRGID = dt.CostCenterID + LEFT JOIN BRANCHES br ON br.BRANCHID = dt.BranchID + LEFT JOIN BANKS bk ON bk.BANKID = br.BANKID + WHERE p.LFAPaymentID=%n AND p.PayrollTypeID=%n AND dt.Amount > 0", + lfaPaymentID, payrollTypeID); + + if (!string.IsNullOrEmpty(empIDs)) + sql += SQLParser.MakeSQL(" AND dt.EmployeeID IN (%q)", empIDs); + if (bankID > 0) + sql += SQLParser.MakeSQL(" AND br.BANKID=%n", bankID); + sql += " ORDER BY bk.NAME, e.EMPLOYEENO"; + + return tc.ExecuteDataSet(sql); + } + #endregion } diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs index ba6d767..66fd04d 100644 --- a/HRM.DA/Service/LFA/LFAPaymentService.cs +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -1160,6 +1160,65 @@ namespace HRM.DA return result; } + #region LFA Bank Advice + + /// LFA Bank Advice: only the approved batches of the payroll type can go to the bank. + public List GetBankAdviceBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID).Where(x => x.WFStatus == enumwfStatus.Approve).ToList(); + } + + /// + /// The bank advice rows of one approved batch of the payroll type: the selected employees (sEmpIDs, + /// comma separated; empty = the whole batch), of one bank (bankID; 0 = every bank). Not approved, + /// or not of this payroll type, is refused. + /// + public System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID) + { + // the IDs go into the SQL as %q, so only digits pass + string empIDs = string.Join(",", (sEmpIDs ?? string.Empty) + .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => int.TryParse(x.Trim(), out int id) ? id : 0) + .Where(id => id > 0) + .Distinct()); + + System.Data.DataSet ds = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + throw new Exception("LFA payment batch not found."); + if (oPayment.WFStatus != enumwfStatus.Approve) + throw new Exception("LFA payment batch " + oPayment.BatchNumber + " is not approved yet."); + + ds = LFAPaymentDA.GetBankAdvice(tc, lfaPaymentID, empIDs, bankID, payrollTypeID); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return ds; + } + + #endregion + /// lfaapproval/workflow = Yes. private static bool IsWorkflowRequired() { diff --git a/HRM.Report/Class/rptLFABankAdvice.cs b/HRM.Report/Class/rptLFABankAdvice.cs new file mode 100644 index 0000000..12db918 --- /dev/null +++ b/HRM.Report/Class/rptLFABankAdvice.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Data; +using HRM.BO; +using HRM.DA; +using Microsoft.Reporting.NETCore; + +namespace HRM.Report +{ + /// + /// LFA Bank Advice (EnumReportType.LFABankAdvice, /payroll-lfa/lfa-bank-advice): the employees of one + /// approved LFA payment batch with their bank account and LFA amount, rendered with LFABankAdvice.rdlc. + /// + public class rptLFABankAdvice + { + private const string RdlcName = "HRM.Report.RDLC.LFABankAdvice.rdlc"; + private const string DataSetName = "dsLFABankAdvice"; + + public byte[] ShowLFABankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeId, string reportType) + { + if (lfaPaymentID <= 0) + throw new Exception("Select an LFA payment batch."); + + DataSet oSource = new LFAPaymentService().GetBankAdvice(lfaPaymentID, sEmpIDs, bankID, payrollTypeId); + if (oSource == null || oSource.Tables.Count == 0 || oSource.Tables[0].Rows.Count == 0) + throw new Exception("No employee of the selected batch has an LFA amount to pay for this selection."); + + DataTable bankAdvice = new DataTable(DataSetName); + bankAdvice.Columns.Add("SLNo", typeof(int)); + bankAdvice.Columns.Add("EmpNo", typeof(string)); + bankAdvice.Columns.Add("EmpName", typeof(string)); + bankAdvice.Columns.Add("Designation", typeof(string)); + bankAdvice.Columns.Add("Department", typeof(string)); + bankAdvice.Columns.Add("CostCenter", typeof(string)); + bankAdvice.Columns.Add("AccountNo", typeof(string)); + bankAdvice.Columns.Add("Bank", typeof(string)); + bankAdvice.Columns.Add("Branch", typeof(string)); + bankAdvice.Columns.Add("RoutingNo", typeof(string)); + bankAdvice.Columns.Add("Email", typeof(string)); + bankAdvice.Columns.Add("Amount", typeof(double)); + + string batchNumber = string.Empty; + DateTime paymentDate = DateTime.Today; + DateTime lfaYear = DateTime.Today; + int count = 1; + foreach (DataRow oDRow in oSource.Tables[0].Rows) + { + DataRow oDR = bankAdvice.NewRow(); + oDR["SLNo"] = count; + oDR["EmpNo"] = Convert.ToString(oDRow["EMPLOYEENO"]); + oDR["EmpName"] = Convert.ToString(oDRow["NAME"]); + oDR["Designation"] = Convert.ToString(oDRow["DesignationName"]); + oDR["Department"] = Convert.ToString(oDRow["DepartmentName"]); + oDR["CostCenter"] = Convert.ToString(oDRow["CostCenter"]); + oDR["AccountNo"] = Convert.ToString(oDRow["AccountNo"]); + oDR["Bank"] = Convert.ToString(oDRow["BankName"]); + oDR["Branch"] = Convert.ToString(oDRow["BranchName"]); + oDR["RoutingNo"] = Convert.ToString(oDRow["RoutingNo"]); + oDR["Email"] = Convert.ToString(oDRow["EMAILADDRESS"]); + oDR["Amount"] = Math.Round(Convert.ToDouble(oDRow["Amount"])); + bankAdvice.Rows.Add(oDR); + + if (count == 1) + { + batchNumber = Convert.ToString(oDRow["BatchNumber"]); + paymentDate = Convert.ToDateTime(oDRow["PaymentDate"]); + lfaYear = Convert.ToDateTime(oDRow["LFAYear"]); + } + count++; + } + + DataSet dSet = new DataSet(); + dSet.Tables.Add(bankAdvice); + + List parameters = new List + { + new ReportParameter("BatchNumber", batchNumber), + new ReportParameter("PaymentDate", paymentDate.ToString("dd MMM yyyy")), + new ReportParameter("LFAYear", lfaYear.Year.ToString()) + }; + + return new ReportProcessor().CommonReportView(null, RdlcName, dSet, null, parameters, true, payrollTypeId, reportType); + } + } +} diff --git a/HRM.Report/HRM.Report.csproj b/HRM.Report/HRM.Report.csproj index 0b3d320..3c8f9d2 100644 --- a/HRM.Report/HRM.Report.csproj +++ b/HRM.Report/HRM.Report.csproj @@ -61,6 +61,7 @@ + @@ -376,6 +377,7 @@ + diff --git a/HRM.Report/RDLC/LFABankAdvice.rdlc b/HRM.Report/RDLC/LFABankAdvice.rdlc new file mode 100644 index 0000000..801c4cb --- /dev/null +++ b/HRM.Report/RDLC/LFABankAdvice.rdlc @@ -0,0 +1,19 @@ + + +0 +SQL0484ed6e-5b42-4ef1-9904-d52d763ef1b2 +DummyDataSourcetrueSLNoSystem.Int32EmpNoSystem.StringEmpNameSystem.StringDesignationSystem.StringDepartmentSystem.StringCostCenterSystem.StringAccountNoSystem.StringBankSystem.StringBranchSystem.StringRoutingNoSystem.StringEmailSystem.StringAmountSystem.Double + +truetrue="LFA Bank Advice - LFA Year " & Parameters!LFAYear.Value0.05in0.1in0.25in7.5intruetrue="Batch No : " & Parameters!BatchNumber.Value & " Payment Date : " & Parameters!PaymentDate.Value0.32in0.1in0.22in7.5in0.35in0.85in1.9in1.3in1.35in0.85in0.9in0.25intruetrueSLSilverMiddle2pt2pt2pt2pttruetrueEmp IDSilverMiddle2pt2pt2pt2pttruetrueEmployee NameSilverMiddle2pt2pt2pt2pttruetrueAccount NoSilverMiddle2pt2pt2pt2pttruetrueBranchSilverMiddle2pt2pt2pt2pttruetrueRouting NoSilverMiddle2pt2pt2pt2pttruetrueAmount BDT.SilverMiddle2pt2pt2pt2pt0.22intruetrue="Bank : " & IIf(Fields!Bank.Value = "", "(No bank)", Fields!Bank.Value)WhiteSmokeMiddle2pt2pt2pt2pt70.22intruetrue=Fields!SLNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!EmpNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!EmpName.ValueMiddle2pt2pt2pt2pttruetrue=Fields!AccountNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!Branch.ValueMiddle2pt2pt2pt2pttruetrue=Fields!RoutingNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!Amount.ValueMiddle2pt2pt2pt2pt0.22intruetrue="Sub Total (" & CountRows() & " employees)"Middle2pt2pt2pt2pt6truetrue=Sum(Fields!Amount.Value)Middle2pt2pt2pt2pt0.25intruetrue="Total Amount (" & CountRows() & " employees)"SilverMiddle2pt2pt2pt2pt6truetrue=Sum(Fields!Amount.Value)SilverMiddle2pt2pt2pt2ptAftertruetrue=Fields!Bank.Value=Fields!Bank.ValueAftertrueBeforetrueBeforetruedsLFABankAdvice0.62in0.1in1.16in7.5in0.3in1.8in0.25in4intruetrue=Parameters!Address.Value0.55in1.8in0.2in4inExternal="file:///" & Parameters!Logo.Valueimage/pngFitProportional0.05in0.1in0.7in1.6in0.05in0.1in0.2in2.2intruetrue="Page " & Globals!PageNumber & " of " & Globals!TotalPages0.05in6.4in0.2in1.2in' + '

    LFA Payment History (' + this.displayDate(this.historyFrom) + ' - ' + this.displayDate(this.historyTo) + ')

    ' + cells(['Batch ID', 'Payment Date', 'Employee ID', 'Name', 'Designation', 'Department', 'Joining Date', 'Basic Salary', - 'LFA Amount', 'Payment Status'], 'th') + 'LFA Amount'], 'th') + '' + body + '

    ' + this.escape(this.historySummary) + ' · LFA Amount ' + money(this.historyTotalAmount) + '

    '); w.document.close(); diff --git a/LFA_DB_Changes.sql b/LFA_DB_Changes.sql index 13a6ded..712fdc2 100644 --- a/LFA_DB_Changes.sql +++ b/LFA_DB_Changes.sql @@ -125,7 +125,6 @@ CREATE TABLE dbo.LFAPaymentDetail ( Amount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_Amount DEFAULT (0), -- LFA amount to pay Remarks NVARCHAR(500) NULL, - PaymentStatus TINYINT NOT NULL CONSTRAINT DF_LFAPayDtl_PaymentStatus DEFAULT (1), -- 1 Pending, 2 Paid, 3 Failed CreatedBy INT NOT NULL, CreationDate DATETIME NOT NULL, ModifiedBy INT NULL, @@ -133,8 +132,7 @@ CREATE TABLE dbo.LFAPaymentDetail ( CONSTRAINT PK_LFAPaymentDetail PRIMARY KEY (LFAPaymentDetailID), CONSTRAINT FK_LFAPayDtl_Payment FOREIGN KEY (LFAPaymentID) REFERENCES dbo.LFAPayment (LFAPaymentID), - CONSTRAINT CK_LFAPayDtl_Amount CHECK (Amount >= 0), - CONSTRAINT CK_LFAPayDtl_PaymentStatus CHECK (PaymentStatus IN (1, 2, 3)) + CONSTRAINT CK_LFAPayDtl_Amount CHECK (Amount >= 0) ); GO /* policy: LFA once in a calendar year (Undo deletes the rows, which frees the employee again) */ @@ -146,3 +144,19 @@ GO SET NOEXEC OFF; GO + +/* ---------- 4. Drop LFAPaymentDetail.PaymentStatus (no longer used) ---------- + Runs even when Part 0 refused (the tables hold data): a database that already + has the column loses it, with its default and check constraints. Re-runnable. */ +IF OBJECT_ID(N'dbo.CK_LFAPayDtl_PaymentStatus', N'C') IS NOT NULL + ALTER TABLE dbo.LFAPaymentDetail DROP CONSTRAINT CK_LFAPayDtl_PaymentStatus; +GO +IF OBJECT_ID(N'dbo.DF_LFAPayDtl_PaymentStatus', N'D') IS NOT NULL + ALTER TABLE dbo.LFAPaymentDetail DROP CONSTRAINT DF_LFAPayDtl_PaymentStatus; +GO +IF COL_LENGTH(N'dbo.LFAPaymentDetail', N'PaymentStatus') IS NOT NULL +BEGIN + ALTER TABLE dbo.LFAPaymentDetail DROP COLUMN PaymentStatus; + PRINT 'LFAPaymentDetail.PaymentStatus dropped.'; +END +GO From 908a6d28ff1076cae544c2e069d5ef4afe5433d6 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Sun, 29 Nov 2026 10:06:33 +0600 Subject: [PATCH 9/9] Done --- .../src/app/_services/payroll/lfa.service.ts | 7 +++++++ .../reports/report-viewer/report-viewer.component.ts | 11 +++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts index e8179ea..085abf5 100644 --- a/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts @@ -62,6 +62,13 @@ export class LFAService { return this.apiService.httpPost('/lfa/undoPayment', request); } + // ── LFA Bank Advice (report viewer, /payroll-lfa/lfa-bank-advice) ── + + /** The approved batches of the payroll type. */ + getBankAdviceBatches(): Observable { + return this.apiService.httpGet('/lfa/getBankAdviceBatches'); + } + // ── LFA Payment Approval (as Salary Approve) ── getApprovalInfo(): Observable { diff --git a/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.ts b/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.ts index 4f8e4fa..00e68b1 100644 --- a/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.ts +++ b/HRM.UI/ClientApp/src/app/reports/report-viewer/report-viewer.component.ts @@ -39,6 +39,7 @@ import { User } from '../../_models/Authentication/user'; import { AuthService } from '../../_services/auth/auth.service'; import { saveAs } from 'file-saver'; import { SalaryService } from '../../_services/payroll/salary.service'; +import { LFAService } from '../../_services/payroll/lfa.service'; import { LoanIssue } from 'src/app/_models/Payroll/Loan/loanIssue'; import { Bank } from 'src/app/_models/Basic/bank'; import { formatDate } from '@progress/kendo-angular-intl'; @@ -73,6 +74,7 @@ export class ReportViewerComponent implements OnInit { public loanService: LoanService, public taxService: TaxService, public salaryService: SalaryService, + public lfaService: LFAService, public leaveYearService: LeaveService, public router: Router, public loadingPanel: loadingPanelService, public notificationService: HRMNotificationService, @@ -1291,15 +1293,12 @@ export class ReportViewerComponent implements OnInit { /** LFA Bank Advice: the approved LFA payment batches of the payroll type. */ loadLFABankAdviceBatches() { this.loadingPanel.ShowLoadingPanel = true; - this.apiService.httpGet('/lfa/getBankAdviceBatches').subscribe( + this.lfaService.getBankAdviceBatches().subscribe( (resp) => { (resp || []).forEach(x => { const paymentDate = x.paymentDate ? formatDate(new Date(x.paymentDate), 'dd MMM yyyy') : ''; - this.items.push(new Item(x.lfaPaymentID, x.batchNumber + ' (' + paymentDate + ', ' + x.headCount + ' emp)')); + this.items.push(new Item(x.lfaPaymentID, x.batchNumber + ' (' + x.headCount + ' emp)')); }); - if (this.items.length === 0) { - this.notificationService.showWarning('No approved LFA payment batch found.'); - } }, (err) => { this.loadingPanel.ShowLoadingPanel = false; @@ -1320,7 +1319,7 @@ export class ReportViewerComponent implements OnInit { this.skip = 0; this.loadData(); this.loadingPanel.ShowLoadingPanel = true; - this.apiService.httpGet('/lfa/getBatchEmployees/' + this.selectedItemid).subscribe( + this.lfaService.getBatchEmployees(this.selectedItemid).subscribe( (resp) => { this.searchEmployees = (resp || []) .filter(x => x.amount > 0)