From 88235461bf35856b1761cb4c3e79700e218bcdec Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Thu, 26 Nov 2026 10:48:45 +0600 Subject: [PATCH] LFA --- HRM.BO/LFA/LFAPayment.cs | 153 +++++ HRM.BO/LFA/LFAPaymentUploadTemplate.cs | 148 +++++ HRM.DA/DA/LFA/LFAPaymentDA.cs | 147 +++++ HRM.DA/DA/LFA/LFAPaymentDetailDA.cs | 101 ++++ HRM.DA/Service/LFA/LFACalculator.cs | 115 ++++ HRM.DA/Service/LFA/LFAPaymentService.cs | 544 ++++++++++++++++++ HRM.DA/Service/LFA/LFAPaymentWorkbook.cs | 174 ++++++ .../src/app/_models/Payroll/lfaPayment.ts | 81 +++ .../src/app/_services/payroll/lfa.service.ts | 46 ++ .../lfa-payment/lfa-payment.component.html | 237 +++++++- .../lfa-payment/lfa-payment.component.scss | 146 +++++ .../lfa-payment/lfa-payment.component.ts | 427 +++++++++++++- .../src/app/payroll-lfa/payroll-lfa.module.ts | 19 +- .../DI/ServiceCollectionExtensions.cs | 3 + .../CommonInterface/DataUploadController.cs | 59 +- HRM.UI/Controllers/Payroll/LFAController.cs | 104 ++++ LFA_DB_Changes.sql | 146 +++++ 17 files changed, 2640 insertions(+), 10 deletions(-) create mode 100644 HRM.BO/LFA/LFAPayment.cs create mode 100644 HRM.BO/LFA/LFAPaymentUploadTemplate.cs create mode 100644 HRM.DA/DA/LFA/LFAPaymentDA.cs create mode 100644 HRM.DA/DA/LFA/LFAPaymentDetailDA.cs create mode 100644 HRM.DA/Service/LFA/LFACalculator.cs create mode 100644 HRM.DA/Service/LFA/LFAPaymentService.cs create mode 100644 HRM.DA/Service/LFA/LFAPaymentWorkbook.cs create mode 100644 HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts create mode 100644 HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts create mode 100644 HRM.UI/Controllers/Payroll/LFAController.cs create mode 100644 LFA_DB_Changes.sql diff --git a/HRM.BO/LFA/LFAPayment.cs b/HRM.BO/LFA/LFAPayment.cs new file mode 100644 index 0000000..fd7f1d9 --- /dev/null +++ b/HRM.BO/LFA/LFAPayment.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace HRM.BO +{ + #region Enums + + /// LFAPaymentDetail.PaymentStatus. + public enum EnumLFAPaymentStatus + { + Pending = 1, + Paid = 2, + Failed = 3 + } + + #endregion + + #region LFAPayment + + /// One Leave Fare Assistance payment batch (dbo.LFAPayment), as SalaryProcess is for the salary. + public class LFAPayment : AuditTrailBase + { + public LFAPayment() + { + BatchNumber = string.Empty; + Details = new List(); + } + + public string BatchNumber { get; set; } + public int PayrollTypeID { get; set; } + + /// The last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE. + public DateTime SalaryMonth { get; set; } + + /// The last date of the calendar year the LFA is for. + public DateTime LFAYear { get; set; } + + public DateTime PaymentDate { get; set; } + public string Remarks { get; set; } + public bool IsTaxUpdated { get; set; } + + /// Null = not submitted yet, as SalaryProcess.WFStatus. + public enumwfStatus? WFStatus { get; set; } + + public int? ApprovedBy { get; set; } + public DateTime? ApprovedDate { get; set; } + + public List Details { get; set; } + } + + #endregion + + #region LFAPaymentDetail + + /// One employee of a batch (dbo.LFAPaymentDetail): a snapshot of the employee and of the calculation. + public class LFAPaymentDetail : AuditTrailBase + { + public LFAPaymentDetail() + { + PaymentStatus = EnumLFAPaymentStatus.Pending; + } + + public int LFAPaymentID { get; set; } + public int EmployeeID { get; set; } + public DateTime LFAYear { get; set; } + + public DateTime JoiningDate { get; set; } + public DateTime? ConfirmationDate { get; set; } + public int? GradeID { get; set; } + public int? DesignationID { get; set; } + public int? DepartmentID { get; set; } + public int? CostCenterID { get; set; } + public int? BranchID { get; set; } + public string AccountNo { get; set; } + + public double? JoiningBasic { get; set; } + + /// Basic as of 31 December of the preceding year; null when the employee joined in the LFA year. + public double? LastDecBasic { get; set; } + + /// The basic the LFA was calculated on. + public double BasicSalary { get; set; } + + /// What the policy gives, before rounding to whole taka. + public double CalculatedAmount { get; set; } + + /// The LFA amount to pay. + public double Amount { get; set; } + + public string Remarks { get; set; } + public EnumLFAPaymentStatus PaymentStatus { get; set; } + } + + #endregion + + #region LFAEmployee + + /// What the LFA calculation needs to know of one employee (not a table). + public class LFAEmployee + { + public int EmployeeID { get; set; } + 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; } + public DateTime? ConfirmationDate { get; set; } + + public int? GradeID { get; set; } + public string GradeName { get; set; } + public int? DesignationID { get; set; } + public string DesignationName { get; set; } + public int? DepartmentID { get; set; } + public string DepartmentName { get; set; } + + /// The parent of the employee's department. + public string DivisionName { get; set; } + + public int? CostCenterID { get; set; } + public int? BranchID { get; set; } + public string AccountNo { get; set; } + + public double JoiningBasic { get; set; } + public double LastDecBasic { get; set; } + + /// The batch that already has this employee's LFA of the year; empty = none. + public string PaidBatchNumber { get; set; } + + /// The employee already has an LFA payment for the preceding year. + public bool IsPaidLastYear { get; set; } + } + + #endregion + + #region ILFAPaymentService + + public interface ILFAPaymentService + { + LFAPayment Get(int id); + LFAPaymentInfo GetInfo(int payrollTypeID); + byte[] GetUploadTemplate(); + LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, + int payrollTypeID); + LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID); + LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID); + List GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID); + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentUploadTemplate.cs b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs new file mode 100644 index 0000000..6f8a5e0 --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region Template layout + + /// + /// The LFA payment upload sheet. The downloadable workbook is generated from this and an uploaded + /// one is read against it. + /// + public static class LFAPaymentUploadTemplate + { + public const string SheetName = "LFA Payment"; + public const string FileName = "LFA-Payment-Template.xlsx"; + public const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + public const int MaxUploadMegabytes = 10; + public const int MaxRows = 20000; + + public const int HeadingRow = 1; + public const int FirstDataRow = 2; + + /// How many rows of the template are formatted as text. + public const int FormattedDataRows = 1000; + + public const int EmployeeNoColumn = 1; + public const int NameColumn = 2; + + public const int MaxRemarksLength = 500; + + /// Employee ID is the Employee No. Name only helps whoever fills the file; it is not checked. + public static readonly string[] Headings = { "Employee ID", "Name" }; + public static readonly double[] Widths = { 18, 40 }; + } + + #endregion + + #region Upload and process data + + /// One uploaded row: what the user gives. Every amount is worked out by the server. + public class LFAPaymentInput + { + public int RowNo { get; set; } + public string EmployeeNo { get; set; } + } + + /// The page's payment information and rows, to calculate or to process. + public class LFAPaymentRequest + { + public DateTime? PaymentDate { get; set; } + public string Remarks { get; set; } + public List Rows { get; set; } + + /// The total the page shows; processing stops when the calculation no longer gives it. + public double ExpectedTotal { get; set; } + } + + /// One calculated row, as the New LFA Payment grid shows it. + public class LFAPaymentRow : LFAPaymentInput + { + public int EmployeeID { get; set; } + public string Name { get; set; } + public string GradeName { get; set; } + public string DesignationName { get; set; } + public string DivisionName { get; set; } + public string DepartmentName { get; set; } + public DateTime JoiningDate { get; set; } + public DateTime? ConfirmationDate { get; set; } + public double JoiningBasic { get; set; } + public double? LastDecBasic { get; set; } + public double BasicSalary { get; set; } + public double Amount { get; set; } + public DateTime PaymentDate { get; set; } + } + + /// Why a row (or, with RowNo 0, the file) cannot be paid. + public class LFAPaymentIssue + { + public int RowNo { get; set; } + public string EmployeeNo { get; set; } + public string EmployeeName { get; set; } + public string Message { get; set; } + } + + public class LFAPaymentReadResult + { + public LFAPaymentReadResult() + { + Rows = new List(); + Issues = new List(); + } + + public DateTime SalaryMonth { get; set; } + + /// The rows that can be paid. + public List Rows { get; set; } + + /// Every problem of every other row. + public List Issues { get; set; } + + public void AddIssue(int rowNo, string employeeNo, string employeeName, string message) + { + Issues.Add(new LFAPaymentIssue + { + RowNo = rowNo, + EmployeeNo = employeeNo, + EmployeeName = employeeName, + Message = message + }); + } + } + + public class LFAPaymentProcessResult + { + public bool Saved { get; set; } + public string Message { get; set; } + public string BatchNumber { get; set; } + + /// Set when nothing was saved because the rows no longer pass. + public LFAPaymentReadResult Validation { get; set; } + } + + /// The current salary month of the payroll type and the next batch number. + public class LFAPaymentInfo + { + public int PayrollTypeID { get; set; } + public DateTime SalaryMonth { get; set; } + public string NextBatchNumber { get; set; } + } + + /// One row of the Payment History tab. + public class LFAPaymentHistory + { + public int LFAPaymentDetailID { get; set; } + public string BatchNumber { get; set; } + public DateTime PaymentDate { 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; } + } + + #endregion +} diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs new file mode 100644 index 0000000..b79d62d --- /dev/null +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Data; +using Ease.Core.DataAccess; +using Ease.Core.DataAccess.SQL; +using HRM.BO; +using Microsoft.Data.SqlClient; + +namespace HRM.DA +{ + #region LFAPaymentDA + + internal class LFAPaymentDA + { + #region Constructor + + private LFAPaymentDA() + { + } + + #endregion + + #region Insert function + + internal static void Insert(TransactionContext tc, LFAPayment item) + { + tc.ExecuteNonQuery( + "INSERT INTO LFAPayment(LFAPaymentID, BatchNumber, PayrollTypeID, SalaryMonth, LFAYear, PaymentDate," + + " Remarks, IsTaxUpdated, WFStatus, ApprovedBy, ApprovedDate, CreatedBy, CreationDate)" + + " VALUES(%n, %s, %n, %d, %d, %d, %u, %b, %n, %n, %D, %n, %D)", + item.ID, item.BatchNumber, item.PayrollTypeID, item.SalaryMonth, item.LFAYear, item.PaymentDate, + item.Remarks, item.IsTaxUpdated, (int?)item.WFStatus, item.ApprovedBy, + DataReader.GetNullValue(item.ApprovedDate), item.CreatedBy, item.CreatedDate); + } + + #endregion + + #region Get Function + + internal static IDataReader Get(TransactionContext tc, int nID) + { + return tc.ExecuteReader("SELECT * FROM LFAPayment WHERE LFAPaymentID=%n", nID); + } + + /// 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) + { + object last = tc.ExecuteScalar( + "SELECT MAX(CAST(SUBSTRING(BatchNumber, %n, 20) AS INT)) FROM LFAPayment" + + " WHERE PayrollTypeID=%n AND LEFT(BatchNumber, %n)=%s", + batchPrefix.Length + 1, payrollTypeID, batchPrefix.Length, batchPrefix); + return last == null || last == DBNull.Value ? 0 : Convert.ToInt32(last); + } + + /// + /// The same, holding the payroll type's batches until the transaction ends: two users processing at + /// the same time then wait for each other instead of taking the same number or the same employee. + /// + internal static int GetLastBatchNoForUpdate(TransactionContext tc, int payrollTypeID, string batchPrefix) + { + object last = tc.ExecuteScalar( + "SELECT MAX(CAST(SUBSTRING(BatchNumber, %n, 20) AS INT)) FROM LFAPayment WITH (UPDLOCK, HOLDLOCK)" + + " WHERE PayrollTypeID=%n AND LEFT(BatchNumber, %n)=%s", + batchPrefix.Length + 1, payrollTypeID, batchPrefix.Length, batchPrefix); + return last == null || last == DBNull.Value ? 0 : Convert.ToInt32(last); + } + + /// + /// Everything the LFA calculation needs of the given Employee Nos, whatever their payroll type and + /// status (the caller says why one cannot be paid). The numbers go in as one parameter, as in + /// EmployeeDA.GetByEmpIDList (STRING_SPLIT, SQL Server 2016+). + /// - joining salary: the employee's first salary record; + /// (the 31 December basic comes from EmployeeGradeSalaryService.GetBasicOnDate, as the bonus uses it); + /// - cost center: the current one with the highest percentage. + /// + internal static IDataReader GetEmployees(TransactionContext tc, List employeeNos, DateTime lfaYear) + { + DateTime lastDec = new DateTime(lfaYear.Year - 1, 12, 31); + + string sql = SQLParser.MakeSQL(@"SET NOCOUNT ON; + IF OBJECT_ID('tempdb..#lfaEmp') IS NOT NULL DROP TABLE #lfaEmp; + CREATE TABLE #lfaEmp (EmployeeID int NOT NULL PRIMARY KEY); + INSERT INTO #lfaEmp (EmployeeID) + 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, + 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, + ISNULL(jn.BASICSALARY, 0) AS JoiningBasic, + py.BatchNumber AS PaidBatchNumber, + 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 + LEFT JOIN DEPARTMENT pd ON pd.DEPARTMENTID = d.PARENTID + LEFT JOIN (SELECT s.EMPLOYEEID, s.BASICSALARY, + ROW_NUMBER() OVER (PARTITION BY s.EMPLOYEEID ORDER BY s.EFFECTDATE, s.GRADESALARYID) AS RowNo + FROM GRADESALARYASSIGNMENT s INNER JOIN #lfaEmp x ON x.EmployeeID = s.EMPLOYEEID) jn + ON jn.EMPLOYEEID = e.EMPLOYEEID AND jn.RowNo = 1 + LEFT JOIN (SELECT c.EMPLOYEEID, c.COSTCENTERID, + ROW_NUMBER() OVER (PARTITION BY c.EMPLOYEEID ORDER BY c.PERCENTAGE DESC, c.ID DESC) AS RowNo + FROM EMPCOSTCENTER c INNER JOIN #lfaEmp x ON x.EmployeeID = c.EMPLOYEEID + WHERE c.CurrentCC = %b) cc + 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 + ORDER BY e.EMPLOYEENO; + + DROP TABLE #lfaEmp;", + true, lfaYear, lastDec); + + // must be a SqlParameter[]: Ease.Core casts the array to SqlParameter[] + SqlParameter[] parameters = + { + SqlHelperExtension.CreateInParam("@employeeNos", SqlDbType.VarChar, string.Join(",", employeeNos), -1) // varchar(max) + }; + return tc.ExecuteReader(CommandType.Text, sql, parameters); + } + + /// Payment History tab: every paid employee of the payment date range. + internal static IDataReader GetHistory(TransactionContext tc, DateTime fromDate, DateTime toDate, int payrollTypeID) + { + return tc.ExecuteReader( + @"SELECT dt.LFAPaymentDetailID, p.BatchNumber, p.PaymentDate, e.EMPLOYEENO, e.NAME, ds.NAME AS DesignationName, + d.DESCRIPTION AS DepartmentName, dt.JoiningDate, dt.BasicSalary, dt.Amount, dt.PaymentStatus + 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 + WHERE p.PayrollTypeID=%n AND p.PaymentDate BETWEEN %d AND %d + ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC, e.EMPLOYEENO", + payrollTypeID, fromDate, toDate); + } + + #endregion + } + + #endregion +} diff --git a/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs new file mode 100644 index 0000000..3cc15d0 --- /dev/null +++ b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Data; +using Ease.Core.DataAccess; +using HRM.BO; +using Microsoft.Data.SqlClient; + +namespace HRM.DA +{ + #region LFAPaymentDetailDA + + internal class LFAPaymentDetailDA + { + #region Constructor + + private LFAPaymentDetailDA() + { + } + + #endregion + + #region Insert function + + /// + /// Inserts every row of a batch in one SqlBulkCopy, inside the caller's transaction (as + /// BonusProcessDA.InsertBulk). IDs must already be set. + /// + internal static void InsertBulk(TransactionContext tc, List items) + { + if (items == null || items.Count == 0) + return; + + // column names exactly as in the table (bulk copy mapping is case-sensitive) + DataTable table = new DataTable("LFAPaymentDetail"); + table.Columns.Add("LFAPaymentDetailID", typeof(int)); + table.Columns.Add("LFAPaymentID", typeof(int)); + table.Columns.Add("EmployeeID", typeof(int)); + table.Columns.Add("LFAYear", typeof(DateTime)); + table.Columns.Add("JoiningDate", typeof(DateTime)); + table.Columns.Add("ConfirmationDate", typeof(DateTime)); + table.Columns.Add("GradeID", typeof(int)); + table.Columns.Add("DesignationID", typeof(int)); + table.Columns.Add("DepartmentID", typeof(int)); + table.Columns.Add("CostCenterID", typeof(int)); + table.Columns.Add("BranchID", typeof(int)); + table.Columns.Add("AccountNo", typeof(string)); + table.Columns.Add("JoiningBasic", typeof(decimal)); + table.Columns.Add("LastDecBasic", typeof(decimal)); + table.Columns.Add("BasicSalary", typeof(decimal)); + table.Columns.Add("CalculatedAmount", typeof(decimal)); + table.Columns.Add("Amount", typeof(decimal)); + table.Columns.Add("Remarks", typeof(string)); + table.Columns.Add("PaymentStatus", typeof(byte)); + table.Columns.Add("CreatedBy", typeof(int)); + table.Columns.Add("CreationDate", typeof(DateTime)); + + foreach (LFAPaymentDetail item in items) + { + table.Rows.Add(item.ID, item.LFAPaymentID, item.EmployeeID, item.LFAYear, item.JoiningDate, + Null(item.ConfirmationDate), Null(item.GradeID), Null(item.DesignationID), Null(item.DepartmentID), + Null(item.CostCenterID), Null(item.BranchID), Null(item.AccountNo), Null(Money(item.JoiningBasic)), + Null(Money(item.LastDecBasic)), Money(item.BasicSalary), Money(item.CalculatedAmount), + Money(item.Amount), Null(item.Remarks), (byte)item.PaymentStatus, item.CreatedBy, item.CreatedDate); + } + + using (SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.CheckConstraints, + (SqlTransaction)tc.Transaction)) + { + bulkCopy.BulkCopyTimeout = 6000; // in seconds + bulkCopy.DestinationTableName = "LFAPaymentDetail"; + foreach (DataColumn column in table.Columns) + bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName); + bulkCopy.WriteToServer(table); + } + } + + private static object Null(object value) + { + return value ?? DBNull.Value; + } + + // money columns: 4 places, as SQL Server rounds a number literal to money + private static decimal? Money(double? value) + { + return value == null ? (decimal?)null : Math.Round((decimal)value.Value, 4, MidpointRounding.AwayFromZero); + } + + #endregion + + #region Get Function + + internal static IDataReader GetByPaymentID(TransactionContext tc, int paymentID) + { + return tc.ExecuteReader("SELECT * FROM LFAPaymentDetail WHERE LFAPaymentID=%n ORDER BY LFAPaymentDetailID", paymentID); + } + + #endregion + } + + #endregion +} diff --git a/HRM.DA/Service/LFA/LFACalculator.cs b/HRM.DA/Service/LFA/LFACalculator.cs new file mode 100644 index 0000000..7c3490e --- /dev/null +++ b/HRM.DA/Service/LFA/LFACalculator.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using HRM.BO; + +namespace HRM.DA +{ + /// + /// The LFA policy: who is eligible and for how much. No database access. + /// - An employee must be live, confirmed and have completed 6 months of service on the payment date, + /// and gets LFA once in a calendar year. + /// - The full amount is one month's basic as of 31 December of the preceding year (365 days). + /// - 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. + /// + internal static class LFACalculator + { + private const int ServiceMonths = 6; + 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) + { + 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."); + return problems; + } + if (employee.Status != EnumEmployeeStatus.Live) + problems.Add("Employee is not active."); + if (!employee.IsConfirmed) + 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) + "."); + else if (eligibleFrom > paymentDate.Date) + problems.Add("6 months of service will be completed on " + DateText(eligibleFrom) + ", after the payment date."); + + if (!string.IsNullOrEmpty(employee.PaidBatchNumber)) + problems.Add("LFA of " + lfaYear.Year + " is already processed in batch " + employee.PaidBatchNumber + "."); + + if (!IsJoinedInYear(employee, lfaYear) && employee.LastDecBasic <= 0) + problems.Add("Basic salary as of " + DateText(LastDec(lfaYear)) + " is not found."); + if ((IsJoinedInYear(employee, lfaYear) || HasPreviousYear(employee, lfaYear)) && employee.JoiningBasic <= 0) + problems.Add("Joining basic salary is not found."); + + return problems; + } + + /// The detail row of an eligible employee (see Validate). + internal static LFAPaymentDetail Calculate(LFAEmployee employee, DateTime lfaYear) + { + bool joinedInYear = IsJoinedInYear(employee, lfaYear); + double currentYear = joinedInYear + ? ProRata(employee.JoiningBasic, employee.JoiningDate, lfaYear) + : employee.LastDecBasic; + double prevYear = HasPreviousYear(employee, lfaYear) + ? ProRata(employee.JoiningBasic, employee.JoiningDate, LastDec(lfaYear)) + : 0; + + LFAPaymentDetail detail = new LFAPaymentDetail(); + detail.EmployeeID = employee.EmployeeID; + detail.LFAYear = lfaYear; + detail.JoiningDate = employee.JoiningDate; + detail.ConfirmationDate = employee.ConfirmationDate; + detail.GradeID = employee.GradeID; + detail.DesignationID = employee.DesignationID; + detail.DepartmentID = employee.DepartmentID; + detail.CostCenterID = employee.CostCenterID; + detail.BranchID = employee.BranchID; + detail.AccountNo = employee.AccountNo; + detail.JoiningBasic = employee.JoiningBasic; + detail.LastDecBasic = joinedInYear ? (double?)null : employee.LastDecBasic; + detail.BasicSalary = joinedInYear ? employee.JoiningBasic : employee.LastDecBasic; + detail.CalculatedAmount = Math.Round(prevYear + currentYear, 2, MidpointRounding.AwayFromZero); + detail.Amount = Math.Round(detail.CalculatedAmount, 0, MidpointRounding.AwayFromZero); // paid in whole taka + return detail; + } + + /// 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) + { + return amount / DaysOfYear * (yearEnd.Date - joiningDate.Date).Days; + } + + private static bool IsJoinedInYear(LFAEmployee employee, DateTime lfaYear) + { + return employee.JoiningDate.Year == lfaYear.Year; + } + + /// Joined in the preceding year, not eligible within that year, and not paid for it. + private static bool HasPreviousYear(LFAEmployee employee, DateTime lfaYear) + { + return employee.JoiningDate.Year == lfaYear.Year - 1 + && employee.JoiningDate.Date.AddMonths(ServiceMonths) > LastDec(lfaYear) + && !employee.IsPaidLastYear; + } + + private static DateTime LastDec(DateTime lfaYear) + { + return new DateTime(lfaYear.Year - 1, 12, 31); + } + + private static string DateText(DateTime date) + { + return date.ToString("dd-MMM-yyyy"); + } + } +} diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs new file mode 100644 index 0000000..76c17cc --- /dev/null +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -0,0 +1,544 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Ease.Core.DataAccess; +using Ease.Core.Model; +using Ease.Core.Utility; +using HRM.BO; + +namespace HRM.DA +{ + /// LFA Payment (Core Payroll > LFA): upload, calculate, process into a batch, and the payment history. + public class LFAPaymentService : ServiceTemplate, ILFAPaymentService + { + public LFAPaymentService() + { + } + + #region Mapping + + private void MapObject(LFAPayment oPayment, DataReader oReader) + { + base.SetObjectID(oPayment, oReader.GetInt32("LFAPaymentID").Value); + oPayment.BatchNumber = oReader.GetString("BatchNumber"); + oPayment.PayrollTypeID = oReader.GetInt32("PayrollTypeID").Value; + oPayment.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value; + oPayment.LFAYear = oReader.GetDateTime("LFAYear").Value; + oPayment.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + oPayment.Remarks = oReader.GetString("Remarks"); + oPayment.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value; + oPayment.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus"); + oPayment.ApprovedBy = oReader.GetInt32("ApprovedBy"); + oPayment.ApprovedDate = oReader.GetDateTime("ApprovedDate"); + oPayment.CreatedBy = oReader.GetInt32("CreatedBy").Value; + oPayment.CreatedDate = oReader.GetDateTime("CreationDate").Value; + oPayment.ModifiedBy = oReader.GetInt32("ModifiedBy"); + oPayment.ModifiedDate = oReader.GetDateTime("ModifiedDate"); + this.SetObjectState(oPayment, Ease.Core.ObjectState.Saved); + } + + protected override T CreateObject(DataReader oReader) + { + LFAPayment oPayment = new LFAPayment(); + MapObject(oPayment, oReader); + return oPayment as T; + } + + private void MapDetailObject(LFAPaymentDetail oDetail, DataReader oReader) + { + base.SetObjectID(oDetail, oReader.GetInt32("LFAPaymentDetailID").Value); + oDetail.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value; + oDetail.EmployeeID = oReader.GetInt32("EmployeeID").Value; + oDetail.LFAYear = oReader.GetDateTime("LFAYear").Value; + oDetail.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + oDetail.ConfirmationDate = oReader.GetDateTime("ConfirmationDate"); + oDetail.GradeID = oReader.GetInt32("GradeID"); + oDetail.DesignationID = oReader.GetInt32("DesignationID"); + oDetail.DepartmentID = oReader.GetInt32("DepartmentID"); + oDetail.CostCenterID = oReader.GetInt32("CostCenterID"); + oDetail.BranchID = oReader.GetInt32("BranchID"); + oDetail.AccountNo = oReader.GetString("AccountNo"); + oDetail.JoiningBasic = oReader.GetDouble("JoiningBasic"); + oDetail.LastDecBasic = oReader.GetDouble("LastDecBasic"); + oDetail.BasicSalary = oReader.GetDouble("BasicSalary").Value; + oDetail.CalculatedAmount = oReader.GetDouble("CalculatedAmount").Value; + oDetail.Amount = oReader.GetDouble("Amount").Value; + oDetail.Remarks = oReader.GetString("Remarks"); + oDetail.PaymentStatus = (EnumLFAPaymentStatus)oReader.GetInt32("PaymentStatus").Value; + oDetail.CreatedBy = oReader.GetInt32("CreatedBy").Value; + oDetail.CreatedDate = oReader.GetDateTime("CreationDate").Value; + oDetail.ModifiedBy = oReader.GetInt32("ModifiedBy"); + oDetail.ModifiedDate = oReader.GetDateTime("ModifiedDate"); + this.SetObjectState(oDetail, Ease.Core.ObjectState.Saved); + } + + private LFAEmployee MapEmployee(DataReader oReader) + { + LFAEmployee employee = new LFAEmployee(); + employee.EmployeeID = oReader.GetInt32("EMPLOYEEID").Value; + 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; + employee.ConfirmationDate = oReader.GetDateTime("DATEOFCONFIRMATION"); + employee.GradeID = oReader.GetInt32("GRADEID"); + employee.GradeName = oReader.GetString("GradeName"); + employee.DesignationID = oReader.GetInt32("DESIGNATIONID"); + employee.DesignationName = oReader.GetString("DesignationName"); + employee.DepartmentID = oReader.GetInt32("DEPARTMENTID"); + employee.DepartmentName = oReader.GetString("DepartmentName"); + employee.DivisionName = oReader.GetString("DivisionName"); + employee.CostCenterID = oReader.GetInt32("COSTCENTERID"); + employee.BranchID = oReader.GetInt32("BRANCHID"); + employee.AccountNo = oReader.GetString("ACCOUNTNO"); + employee.JoiningBasic = oReader.GetDouble("JoiningBasic").Value; + employee.PaidBatchNumber = oReader.GetString("PaidBatchNumber"); + employee.IsPaidLastYear = oReader.GetInt32("IsPaidLastYear").Value == 1; + return employee; + } + + private LFAPaymentHistory MapHistory(DataReader oReader) + { + LFAPaymentHistory history = new LFAPaymentHistory(); + history.LFAPaymentDetailID = oReader.GetInt32("LFAPaymentDetailID").Value; + history.BatchNumber = oReader.GetString("BatchNumber"); + history.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + history.EmployeeNo = oReader.GetString("EMPLOYEENO"); + history.Name = oReader.GetString("NAME"); + history.DesignationName = oReader.GetString("DesignationName"); + history.DepartmentName = oReader.GetString("DepartmentName"); + history.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + history.BasicSalary = oReader.GetDouble("BasicSalary").Value; + history.Amount = oReader.GetDouble("Amount").Value; + history.PaymentStatus = (EnumLFAPaymentStatus)oReader.GetInt32("PaymentStatus").Value; + return history; + } + + #endregion + + #region Get + + public LFAPayment Get(int id) + { + LFAPayment oPayment = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, id)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment != null) + { + dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, id)); + while (dr.Read()) + { + LFAPaymentDetail oDetail = new LFAPaymentDetail(); + MapDetailObject(oDetail, dr); + oPayment.Details.Add(oDetail); + } + 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 oPayment; + } + + /// The current salary month and the batch number the next process will take. + public LFAPaymentInfo GetInfo(int payrollTypeID) + { + LFAPaymentInfo info = new LFAPaymentInfo(); + TransactionContext tc = null; + try + { + info.PayrollTypeID = payrollTypeID; + info.SalaryMonth = GetSalaryMonth(payrollTypeID); + string prefix = BatchPrefix(info.SalaryMonth); + + tc = TransactionContext.Begin(); + info.NextBatchNumber = BatchNumber(prefix, LFAPaymentDA.GetLastBatchNo(tc, payrollTypeID, prefix) + 1); + 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; + } + + public List GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.GetHistory(tc, fromDate.Date, toDate.Date, payrollTypeID)); + while (dr.Read()) + { + items.Add(MapHistory(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; + } + + #endregion + + #region Upload and calculate + + public byte[] GetUploadTemplate() + { + try + { + return LFAPaymentWorkbook.BuildTemplate(); + } + catch (Exception e) + { + #region Handle Exception + + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + } + + /// Reads an uploaded workbook and calculates its employees. Nothing is saved. + public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, + int payrollTypeID) + { + LFAPaymentReadResult result = new LFAPaymentReadResult(); + TransactionContext tc = null; + try + { + result.SalaryMonth = GetSalaryMonth(payrollTypeID); + List rows = LFAPaymentWorkbook.Read(stream, fileName, fileLength, result); + + tc = TransactionContext.Begin(); + Calculate(tc, result, rows, paymentDate, 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 result; + } + + /// Calculates the page's rows again (payment date or mode changed, draft opened). Nothing is saved. + public LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID) + { + LFAPaymentReadResult result = new LFAPaymentReadResult(); + TransactionContext tc = null; + try + { + CheckRequest(request); + result.SalaryMonth = GetSalaryMonth(payrollTypeID); + + tc = TransactionContext.Begin(); + Calculate(tc, result, request.Rows, request.PaymentDate.Value, 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 result; + } + + /// + /// 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. + /// + private List Calculate(TransactionContext tc, LFAPaymentReadResult result, List inputs, DateTime paymentDate, int payrollTypeID) + { + List details = new List(); + if (inputs.Count == 0) + { + return details; + } + + DateTime lfaYear = GetLFAYear(result.SalaryMonth); + foreach (LFAPaymentInput input in inputs) + { + input.EmployeeNo = (input.EmployeeNo ?? "").Trim(); + } + + // 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)); + 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)) + { + employees[key] = employee; + } + } + dr.Close(); + + // 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; + } + } + foreach (LFAEmployee employee in employees.Values) + { + double basic; + 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); + + foreach (LFAPaymentInput input in inputs) + { + LFAEmployee employee; + if (!employees.TryGetValue(input.EmployeeNo, out employee)) + { + 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) + { + result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem); + } + continue; + } + + LFAPaymentDetail detail = LFACalculator.Calculate(employee, lfaYear); + if (detail.Amount <= 0) + { + result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, "LFA amount is zero."); + continue; + } + details.Add(detail); + result.Rows.Add(ToRow(employee, input, detail, paymentDate)); + } + + result.Issues = result.Issues.OrderBy(x => x.RowNo).ToList(); + return details; + } + + private static LFAPaymentRow ToRow(LFAEmployee employee, LFAPaymentInput input, LFAPaymentDetail detail, + DateTime paymentDate) + { + return new LFAPaymentRow + { + RowNo = input.RowNo, + EmployeeNo = employee.EmployeeNo, + EmployeeID = employee.EmployeeID, + Name = employee.Name, + GradeName = employee.GradeName, + DesignationName = employee.DesignationName, + DivisionName = employee.DivisionName, + DepartmentName = employee.DepartmentName, + JoiningDate = employee.JoiningDate, + ConfirmationDate = employee.ConfirmationDate, + JoiningBasic = employee.JoiningBasic, + LastDecBasic = detail.LastDecBasic, + BasicSalary = detail.BasicSalary, + Amount = detail.Amount, + PaymentDate = paymentDate.Date + }; + } + + #endregion + + #region Process + + /// + /// Saves the page's rows as one new batch, in ONE transaction. Every row is validated and calculated + /// again here; when a row no longer passes, or the total is not the one the page shows, nothing is saved. + /// + public LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID) + { + LFAPaymentProcessResult result = new LFAPaymentProcessResult(); + TransactionContext tc = null; + try + { + CheckRequest(request); + if (request.Rows.Count == 0) + throw new ServiceException("Add at least one employee."); + if ((request.Remarks ?? "").Length > LFAPaymentUploadTemplate.MaxRemarksLength) + throw new ServiceException("Remarks is longer than " + LFAPaymentUploadTemplate.MaxRemarksLength + " characters."); + + LFAPaymentReadResult validation = new LFAPaymentReadResult(); + validation.SalaryMonth = GetSalaryMonth(payrollTypeID); + string prefix = BatchPrefix(validation.SalaryMonth); + + tc = TransactionContext.Begin(true); + int batchNo = LFAPaymentDA.GetLastBatchNoForUpdate(tc, payrollTypeID, prefix) + 1; + List details = Calculate(tc, validation, request.Rows, request.PaymentDate.Value, + payrollTypeID); + + if (validation.Issues.Count > 0) + { + result.Validation = validation; + result.Message = "Nothing was saved. Some employees can no longer be paid; please check the list."; + } + else if (Math.Abs(details.Sum(x => x.Amount) - request.ExpectedTotal) > 0.001) + { + result.Validation = validation; + result.Message = "Nothing was saved. The LFA amounts have changed; please check them and process again."; + } + else + { + LFAPayment oPayment = new LFAPayment(); + oPayment.BatchNumber = BatchNumber(prefix, batchNo); + oPayment.PayrollTypeID = payrollTypeID; + oPayment.SalaryMonth = validation.SalaryMonth; + oPayment.LFAYear = GetLFAYear(validation.SalaryMonth); + oPayment.PaymentDate = request.PaymentDate.Value.Date; + oPayment.Remarks = string.IsNullOrWhiteSpace(request.Remarks) ? null : request.Remarks.Trim(); + oPayment.CreatedBy = userID; + oPayment.CreatedDate = DateTime.Now; + oPayment.Details = details; + Insert(tc, oPayment); + + result.Saved = true; + result.BatchNumber = oPayment.BatchNumber; + result.Message = "Batch " + oPayment.BatchNumber + " created for " + details.Count + " employee(s)."; + } + 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; + } + + private void Insert(TransactionContext tc, LFAPayment oPayment) + { + base.SetObjectID(oPayment, tc.GenerateID("LFAPayment", "LFAPaymentID")); + LFAPaymentDA.Insert(tc, oPayment); + + int detailID = tc.GenerateID("LFAPaymentDetail", "LFAPaymentDetailID"); + foreach (LFAPaymentDetail oDetail in oPayment.Details) + { + base.SetObjectID(oDetail, detailID++); + oDetail.LFAPaymentID = oPayment.ID; + oDetail.CreatedBy = oPayment.CreatedBy; + oDetail.CreatedDate = oPayment.CreatedDate; + } + LFAPaymentDetailDA.InsertBulk(tc, oPayment.Details); + } + + #endregion + + #region Helpers + + private static void CheckRequest(LFAPaymentRequest request) + { + if (request == null || request.Rows == null) + throw new ServiceException("Nothing to process."); + if (request.PaymentDate == null) + throw new ServiceException("Payment Date is required."); + } + + /// The current salary month: the last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE. + private static DateTime GetSalaryMonth(int payrollTypeID) + { + PayrollType payrollType = new PayrollTypeService().Get(payrollTypeID); + if (payrollType == null || payrollType.ID <= 0) + throw new ServiceException("Payroll type not found."); + return GlobalFunctions.LastDateOfMonth(payrollType.NextPayProcessDate).Date; + } + + private static DateTime GetLFAYear(DateTime salaryMonth) + { + return new DateTime(salaryMonth.Year, 12, 31); + } + + private static string BatchPrefix(DateTime salaryMonth) + { + return "LFA-" + salaryMonth.Year + "-"; + } + + private static string BatchNumber(string prefix, int no) + { + return prefix + no.ToString("000"); + } + + #endregion + } +} diff --git a/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs b/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs new file mode 100644 index 0000000..8c22596 --- /dev/null +++ b/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using ClosedXML.Excel; +using HRM.BO; + +namespace HRM.DA +{ + /// + /// The LFA payment workbook: builds the template from and reads + /// an uploaded one. Only what the file itself can tell is checked here. + /// + internal static class LFAPaymentWorkbook + { + #region Template + + internal static byte[] BuildTemplate() + { + using (XLWorkbook workbook = new XLWorkbook()) + { + IXLWorksheet sheet = workbook.Worksheets.Add(LFAPaymentUploadTemplate.SheetName); + for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++) + { + IXLCell cell = sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1); + cell.Value = LFAPaymentUploadTemplate.Headings[i]; + cell.Style.Font.Bold = true; + cell.Style.Fill.BackgroundColor = XLColor.FromHtml("#D9E1F2"); + cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; + cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; + sheet.Column(i + 1).Width = LFAPaymentUploadTemplate.Widths[i]; + } + + int first = LFAPaymentUploadTemplate.FirstDataRow; + int last = first + LFAPaymentUploadTemplate.FormattedDataRows - 1; + // Text, so an Employee ID such as 00123 keeps its zeros. + sheet.Range(first, LFAPaymentUploadTemplate.EmployeeNoColumn, last, LFAPaymentUploadTemplate.NameColumn) + .Style.NumberFormat.Format = "@"; + sheet.SheetView.FreezeRows(LFAPaymentUploadTemplate.HeadingRow); + + using (MemoryStream stream = new MemoryStream()) + { + workbook.SaveAs(stream); + return stream.ToArray(); + } + } + } + + #endregion + + #region Read + + /// The file's rows. Problems go into ; a row with one is not returned. + internal static List Read(Stream stream, string fileName, long fileLength, LFAPaymentReadResult result) + { + List rows = new List(); + + if (stream == null || string.IsNullOrWhiteSpace(fileName) || fileLength <= 0) + { + result.AddIssue(0, null, null, "No file was received, or the file is empty."); + return rows; + } + if (!fileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase)) + { + result.AddIssue(0, null, null, "Only Excel workbooks (.xlsx) are allowed. Please use the downloaded template."); + return rows; + } + if (fileLength > LFAPaymentUploadTemplate.MaxUploadMegabytes * 1024L * 1024L) + { + result.AddIssue(0, null, null, "The file is larger than " + LFAPaymentUploadTemplate.MaxUploadMegabytes + " MB."); + return rows; + } + + // ClosedXML needs a seekable stream; an upload stream may not be one. + using (MemoryStream buffer = new MemoryStream()) + { + stream.CopyTo(buffer); + buffer.Position = 0; + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(buffer); + } + catch (Exception) + { + result.AddIssue(0, null, null, "The file could not be opened as an Excel workbook. It may be damaged or password-protected."); + return rows; + } + + using (workbook) + { + IXLWorksheet sheet; + if (!workbook.TryGetWorksheet(LFAPaymentUploadTemplate.SheetName, out sheet)) + sheet = workbook.Worksheets.First(); + + if (!CheckHeadings(sheet, result)) + return rows; + ReadRows(sheet, rows, result); + } + } + + if (rows.Count == 0 && result.Issues.Count == 0) + result.AddIssue(0, null, null, "No employee found in the file."); + return rows; + } + + private static bool CheckHeadings(IXLWorksheet sheet, LFAPaymentReadResult result) + { + List wrong = new List(); + for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++) + { + string found = Text(sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1)); + if (Normalize(found) != Normalize(LFAPaymentUploadTemplate.Headings[i])) + wrong.Add("column " + (char)('A' + i) + " must be \"" + LFAPaymentUploadTemplate.Headings[i] + "\"" + + (found == "" ? " (it is empty)" : " (found \"" + found + "\")")); + } + if (wrong.Count == 0) + return true; + result.AddIssue(0, null, null, "The headings in row " + LFAPaymentUploadTemplate.HeadingRow + + " do not match the template: " + string.Join(", ", wrong) + "."); + return false; + } + + private static void ReadRows(IXLWorksheet sheet, List rows, LFAPaymentReadResult result) + { + // cells with a value only: the template's formatted but empty rows are not "used" + int lastRow = sheet.LastRowUsed(XLCellsUsedOptions.Contents)?.RowNumber() ?? 0; + int count = 0; + for (int rowNo = LFAPaymentUploadTemplate.FirstDataRow; rowNo <= lastRow; rowNo++) + { + string employeeNo = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.EmployeeNoColumn)); + string name = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.NameColumn)); + if (employeeNo == "" && name == "") + continue; + + if (++count > LFAPaymentUploadTemplate.MaxRows) + { + rows.Clear(); + result.AddIssue(0, null, null, "The file has more than " + LFAPaymentUploadTemplate.MaxRows + " employees. Please split it."); + return; + } + + if (employeeNo == "") + { + result.AddIssue(rowNo, null, name, "Employee ID is required."); + continue; + } + rows.Add(new LFAPaymentInput { RowNo = rowNo, EmployeeNo = employeeNo }); + } + } + + /// What the cell holds, as text; an Employee ID stored as a number comes without separators. + private static string Text(IXLCell cell) + { + if (cell.DataType == XLDataType.Number) + { + string shown = cell.GetFormattedString().Trim(); + return shown.Length > 0 && shown.All(char.IsDigit) + ? shown + : cell.GetDouble().ToString("0.##########", CultureInfo.InvariantCulture); + } + return cell.GetFormattedString().Trim(); + } + + private static string Normalize(string heading) + { + return new string((heading ?? "").Where(x => !char.IsWhiteSpace(x)).ToArray()).ToUpperInvariant(); + } + + #endregion + } +} diff --git a/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts new file mode 100644 index 0000000..5963fcc --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts @@ -0,0 +1,81 @@ +// LFA Payment (HRM.BO/LFA) + +export enum EnumLFAPaymentStatus { + Pending = 1, + Paid = 2, + Failed = 3 +} + +/** One uploaded row: what the user gives. Every amount is worked out by the server. */ +export class LFAPaymentInput { + rowNo: number; + employeeNo: string; +} + +/** One calculated row of the New LFA Payment grid. */ +export class LFAPaymentRow extends LFAPaymentInput { + employeeID: number; + name: string; + gradeName: string; + designationName: string; + divisionName: string; + departmentName: string; + joiningDate: Date; + confirmationDate: Date; + joiningBasic: number; + lastDecBasic: number; + basicSalary: number; + amount: number; + paymentDate: Date; +} + +/** Why a row (or, with rowNo 0, the file) cannot be paid. */ +export class LFAPaymentIssue { + rowNo: number; + employeeNo: string; + employeeName: string; + message: string; +} + +export class LFAPaymentReadResult { + salaryMonth: Date; + rows: LFAPaymentRow[]; + issues: LFAPaymentIssue[]; +} + +export class LFAPaymentRequest { + paymentDate: string; // yyyy-MM-dd + remarks: string; + rows: LFAPaymentInput[]; + expectedTotal: number; +} + +export class LFAPaymentProcessResult { + saved: boolean; + message: string; + batchNumber: string; + validation: LFAPaymentReadResult; // set when nothing was saved because the rows no longer pass +} + +export class LFAPaymentInfo { + payrollTypeID: number; + salaryMonth: Date; + nextBatchNumber: string; +} + +/** One row of the Payment History grid. */ +export class LFAPaymentHistory { + lfaPaymentDetailID: number; + batchNumber: string; + paymentDate: Date; + employeeNo: string; + name: string; + designationName: string; + departmentName: string; + joiningDate: Date; + basicSalary: number; + amount: number; + paymentStatus: EnumLFAPaymentStatus; + // filled on the page + statusText: 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 new file mode 100644 index 0000000..dd0ca68 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts @@ -0,0 +1,46 @@ +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { ApiService } from '../../app.api.service'; +import { + LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest +} from '../../_models/Payroll/lfaPayment'; + +@Injectable({ + providedIn: 'root' +}) +export class LFAService { + + constructor(public apiService: ApiService) { + } + + /** The current salary month and the next batch number. */ + getPaymentInfo(): Observable { + return this.apiService.httpGet('/lfa/getPaymentInfo'); + } + + downloadTemplate(): Observable { + return this.apiService.httpGetBlob('/dataUpload/lfa-payment-upload-template'); + } + + /** Reads a filled template on the server and returns the calculated employees. Nothing is saved. */ + readUpload(file: File, paymentDate: string): Observable { + const formData = new FormData(); + formData.append('excelfile', file, file.name); + formData.append('paymentDate', paymentDate); + return this.apiService.httpPostBlob('/dataUpload/lfa-payment-upload-read', formData); + } + + calculatePayment(request: LFAPaymentRequest): Observable { + return this.apiService.httpPost('/lfa/calculatePayment', request); + } + + /** Saves the rows as a new batch, all or nothing. The server calculates every row again. */ + processPayment(request: LFAPaymentRequest): Observable { + return this.apiService.httpPost('/lfa/processPayment', request); + } + + /** Dates as yyyy-MM-dd. */ + getPaymentHistory(fromDate: string, toDate: string): Observable { + return this.apiService.httpGet('/lfa/getPaymentHistory/' + fromDate + '/' + toDate); + } +} 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 dd849b6..1743817 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 @@ -1,8 +1,233 @@ -
- - LFA Payment - - - + +
+ + + + @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