LFA
This commit is contained in:
parent
58ccd13a12
commit
88235461bf
153
HRM.BO/LFA/LFAPayment.cs
Normal file
153
HRM.BO/LFA/LFAPayment.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace HRM.BO
|
||||
{
|
||||
#region Enums
|
||||
|
||||
/// <summary>LFAPaymentDetail.PaymentStatus.</summary>
|
||||
public enum EnumLFAPaymentStatus
|
||||
{
|
||||
Pending = 1,
|
||||
Paid = 2,
|
||||
Failed = 3
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region LFAPayment
|
||||
|
||||
/// <summary>One Leave Fare Assistance payment batch (dbo.LFAPayment), as SalaryProcess is for the salary.</summary>
|
||||
public class LFAPayment : AuditTrailBase
|
||||
{
|
||||
public LFAPayment()
|
||||
{
|
||||
BatchNumber = string.Empty;
|
||||
Details = new List<LFAPaymentDetail>();
|
||||
}
|
||||
|
||||
public string BatchNumber { get; set; }
|
||||
public int PayrollTypeID { get; set; }
|
||||
|
||||
/// <summary>The last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE.</summary>
|
||||
public DateTime SalaryMonth { get; set; }
|
||||
|
||||
/// <summary>The last date of the calendar year the LFA is for.</summary>
|
||||
public DateTime LFAYear { get; set; }
|
||||
|
||||
public DateTime PaymentDate { get; set; }
|
||||
public string Remarks { get; set; }
|
||||
public bool IsTaxUpdated { get; set; }
|
||||
|
||||
/// <summary>Null = not submitted yet, as SalaryProcess.WFStatus.</summary>
|
||||
public enumwfStatus? WFStatus { get; set; }
|
||||
|
||||
public int? ApprovedBy { get; set; }
|
||||
public DateTime? ApprovedDate { get; set; }
|
||||
|
||||
public List<LFAPaymentDetail> Details { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region LFAPaymentDetail
|
||||
|
||||
/// <summary>One employee of a batch (dbo.LFAPaymentDetail): a snapshot of the employee and of the calculation.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Basic as of 31 December of the preceding year; null when the employee joined in the LFA year.</summary>
|
||||
public double? LastDecBasic { get; set; }
|
||||
|
||||
/// <summary>The basic the LFA was calculated on.</summary>
|
||||
public double BasicSalary { get; set; }
|
||||
|
||||
/// <summary>What the policy gives, before rounding to whole taka.</summary>
|
||||
public double CalculatedAmount { get; set; }
|
||||
|
||||
/// <summary>The LFA amount to pay.</summary>
|
||||
public double Amount { get; set; }
|
||||
|
||||
public string Remarks { get; set; }
|
||||
public EnumLFAPaymentStatus PaymentStatus { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region LFAEmployee
|
||||
|
||||
/// <summary>What the LFA calculation needs to know of one employee (not a table).</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>The parent of the employee's department.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>The batch that already has this employee's LFA of the year; empty = none.</summary>
|
||||
public string PaidBatchNumber { get; set; }
|
||||
|
||||
/// <summary>The employee already has an LFA payment for the preceding year.</summary>
|
||||
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<LFAPaymentHistory> GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
148
HRM.BO/LFA/LFAPaymentUploadTemplate.cs
Normal file
148
HRM.BO/LFA/LFAPaymentUploadTemplate.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace HRM.BO
|
||||
{
|
||||
#region Template layout
|
||||
|
||||
/// <summary>
|
||||
/// The LFA payment upload sheet. The downloadable workbook is generated from this and an uploaded
|
||||
/// one is read against it.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>How many rows of the template are formatted as text.</summary>
|
||||
public const int FormattedDataRows = 1000;
|
||||
|
||||
public const int EmployeeNoColumn = 1;
|
||||
public const int NameColumn = 2;
|
||||
|
||||
public const int MaxRemarksLength = 500;
|
||||
|
||||
/// <summary>Employee ID is the Employee No. Name only helps whoever fills the file; it is not checked.</summary>
|
||||
public static readonly string[] Headings = { "Employee ID", "Name" };
|
||||
public static readonly double[] Widths = { 18, 40 };
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Upload and process data
|
||||
|
||||
/// <summary>One uploaded row: what the user gives. Every amount is worked out by the server.</summary>
|
||||
public class LFAPaymentInput
|
||||
{
|
||||
public int RowNo { get; set; }
|
||||
public string EmployeeNo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The page's payment information and rows, to calculate or to process.</summary>
|
||||
public class LFAPaymentRequest
|
||||
{
|
||||
public DateTime? PaymentDate { get; set; }
|
||||
public string Remarks { get; set; }
|
||||
public List<LFAPaymentInput> Rows { get; set; }
|
||||
|
||||
/// <summary>The total the page shows; processing stops when the calculation no longer gives it.</summary>
|
||||
public double ExpectedTotal { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One calculated row, as the New LFA Payment grid shows it.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Why a row (or, with RowNo 0, the file) cannot be paid.</summary>
|
||||
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<LFAPaymentRow>();
|
||||
Issues = new List<LFAPaymentIssue>();
|
||||
}
|
||||
|
||||
public DateTime SalaryMonth { get; set; }
|
||||
|
||||
/// <summary>The rows that can be paid.</summary>
|
||||
public List<LFAPaymentRow> Rows { get; set; }
|
||||
|
||||
/// <summary>Every problem of every other row.</summary>
|
||||
public List<LFAPaymentIssue> 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; }
|
||||
|
||||
/// <summary>Set when nothing was saved because the rows no longer pass.</summary>
|
||||
public LFAPaymentReadResult Validation { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The current salary month of the payroll type and the next batch number.</summary>
|
||||
public class LFAPaymentInfo
|
||||
{
|
||||
public int PayrollTypeID { get; set; }
|
||||
public DateTime SalaryMonth { get; set; }
|
||||
public string NextBatchNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One row of the Payment History tab.</summary>
|
||||
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
|
||||
}
|
||||
147
HRM.DA/DA/LFA/LFAPaymentDA.cs
Normal file
147
HRM.DA/DA/LFA/LFAPaymentDA.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>The highest running number of the batches that start with this prefix; 0 = none yet.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static IDataReader GetEmployees(TransactionContext tc, List<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>Payment History tab: every paid employee of the payment date range.</summary>
|
||||
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
|
||||
}
|
||||
101
HRM.DA/DA/LFA/LFAPaymentDetailDA.cs
Normal file
101
HRM.DA/DA/LFA/LFAPaymentDetailDA.cs
Normal file
|
|
@ -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
|
||||
|
||||
/// <summary>
|
||||
/// Inserts every row of a batch in one SqlBulkCopy, inside the caller's transaction (as
|
||||
/// BonusProcessDA.InsertBulk). IDs must already be set.
|
||||
/// </summary>
|
||||
internal static void InsertBulk(TransactionContext tc, List<LFAPaymentDetail> 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
|
||||
}
|
||||
115
HRM.DA/Service/LFA/LFACalculator.cs
Normal file
115
HRM.DA/Service/LFA/LFACalculator.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using HRM.BO;
|
||||
|
||||
namespace HRM.DA
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class LFACalculator
|
||||
{
|
||||
private const int ServiceMonths = 6;
|
||||
private const double DaysOfYear = 365;
|
||||
|
||||
/// <summary>Every reason the employee cannot be paid; empty = eligible.</summary>
|
||||
internal static List<string> Validate(LFAEmployee employee, DateTime lfaYear, DateTime paymentDate,
|
||||
int payrollTypeID)
|
||||
{
|
||||
List<string> problems = new List<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The detail row of an eligible employee (see Validate).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Days from the joining date to the year end, the joining date itself not counted, over 365.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Joined in the preceding year, not eligible within that year, and not paid for it.</summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
544
HRM.DA/Service/LFA/LFAPaymentService.cs
Normal file
544
HRM.DA/Service/LFA/LFAPaymentService.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>LFA Payment (Core Payroll > LFA): upload, calculate, process into a batch, and the payment history.</summary>
|
||||
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<T>(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<LFAPayment>(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;
|
||||
}
|
||||
|
||||
/// <summary>The current salary month and the batch number the next process will take.</summary>
|
||||
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<LFAPaymentHistory> GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID)
|
||||
{
|
||||
List<LFAPaymentHistory> items = new List<LFAPaymentHistory>();
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads an uploaded workbook and calculates its employees. Nothing is saved.</summary>
|
||||
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<LFAPaymentInput> 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;
|
||||
}
|
||||
|
||||
/// <summary>Calculates the page's rows again (payment date or mode changed, draft opened). Nothing is saved.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private List<LFAPaymentDetail> Calculate(TransactionContext tc, LFAPaymentReadResult result, List<LFAPaymentInput> inputs, DateTime paymentDate, int payrollTypeID)
|
||||
{
|
||||
List<LFAPaymentDetail> details = new List<LFAPaymentDetail>();
|
||||
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<string, LFAEmployee> employees = new Dictionary<string, LFAEmployee>(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<int, double> lastDecBasics = new Dictionary<int, double>();
|
||||
List<EmployeeGradeSalary> 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<string, List<int>> 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<string> 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
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<LFAPaymentDetail> 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.");
|
||||
}
|
||||
|
||||
/// <summary>The current salary month: the last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE.</summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
174
HRM.DA/Service/LFA/LFAPaymentWorkbook.cs
Normal file
174
HRM.DA/Service/LFA/LFAPaymentWorkbook.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// The LFA payment workbook: builds the template from <see cref="LFAPaymentUploadTemplate"/> and reads
|
||||
/// an uploaded one. Only what the file itself can tell is checked here.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
/// <summary>The file's rows. Problems go into <paramref name="result"/>; a row with one is not returned.</summary>
|
||||
internal static List<LFAPaymentInput> Read(Stream stream, string fileName, long fileLength, LFAPaymentReadResult result)
|
||||
{
|
||||
List<LFAPaymentInput> rows = new List<LFAPaymentInput>();
|
||||
|
||||
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<string> wrong = new List<string>();
|
||||
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<LFAPaymentInput> 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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the cell holds, as text; an Employee ID stored as a number comes without separators.</summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
81
HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts
Normal file
81
HRM.UI/ClientApp/src/app/_models/Payroll/lfaPayment.ts
Normal file
|
|
@ -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;
|
||||
}
|
||||
46
HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts
Normal file
46
HRM.UI/ClientApp/src/app/_services/payroll/lfa.service.ts
Normal file
|
|
@ -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<LFAPaymentInfo> {
|
||||
return this.apiService.httpGet<LFAPaymentInfo>('/lfa/getPaymentInfo');
|
||||
}
|
||||
|
||||
downloadTemplate(): Observable<Blob> {
|
||||
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<LFAPaymentReadResult> {
|
||||
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<LFAPaymentReadResult> {
|
||||
return this.apiService.httpPost<LFAPaymentReadResult>('/lfa/calculatePayment', request);
|
||||
}
|
||||
|
||||
/** Saves the rows as a new batch, all or nothing. The server calculates every row again. */
|
||||
processPayment(request: LFAPaymentRequest): Observable<LFAPaymentProcessResult> {
|
||||
return this.apiService.httpPost<LFAPaymentProcessResult>('/lfa/processPayment', request);
|
||||
}
|
||||
|
||||
/** Dates as yyyy-MM-dd. */
|
||||
getPaymentHistory(fromDate: string, toDate: string): Observable<LFAPaymentHistory[]> {
|
||||
return this.apiService.httpGet<LFAPaymentHistory[]>('/lfa/getPaymentHistory/' + fromDate + '/' + toDate);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,233 @@
|
|||
<app-loading-panel></app-loading-panel>
|
||||
<div class="col-12">
|
||||
<kendo-card style="width: 100%;">
|
||||
<kendo-card-header style="font-size:22px; font-weight:400;" align="middle">LFA Payment</kendo-card-header>
|
||||
<kendo-card-body>
|
||||
</kendo-card-body>
|
||||
</kendo-card>
|
||||
|
||||
<div class="lfa-page">
|
||||
<app-tab-view [(activeIndex)]="selectedTab" [scrollable]="true" (onChange)="onTabSelect($event.index)">
|
||||
<!-- ================= LFA Request (design only for now) ================= -->
|
||||
<app-tab-panel header="LFA Request ({{ requests.length }})" leftIcon="pi pi-list">
|
||||
@if (selectedTab === 0) {
|
||||
<div class="lfa-tab">
|
||||
<div class="lfa-toolbar">
|
||||
<div class="lfa-field lfa-field--wide">
|
||||
<label>Search</label>
|
||||
<kendo-textbox [(ngModel)]="requestSearch" placeholder="ID, name, designation…" [clearButton]="true"></kendo-textbox>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>Department</label>
|
||||
<kendo-dropdownlist [data]="[allDepartments]" [(ngModel)]="requestDepartment"></kendo-dropdownlist>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>LFA Start From</label>
|
||||
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="requestFrom"></kendo-datepicker>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>LFA Start To</label>
|
||||
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="requestTo"></kendo-datepicker>
|
||||
</div>
|
||||
<button class="gh-reset" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['undo']" (click)="resetRequestFilter()">Reset</button>
|
||||
<span class="lfa-spacer"></span>
|
||||
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="true">Export</button>
|
||||
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['forward']" [disabled]="true">Payment Proceed</button>
|
||||
</div>
|
||||
<div class="lfa-info">Approved LFA requests awaiting payment · <b>0</b> selected · Est. LFA amount <b>0.00</b></div>
|
||||
<kendo-grid [kendoGridBinding]="requests" [pageable]="true" [pageSize]="10" [sortable]="true" [height]="420">
|
||||
<kendo-grid-checkbox-column [width]="45" [showSelectAll]="requests.length > 0"></kendo-grid-checkbox-column>
|
||||
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120"></kendo-grid-column>
|
||||
<kendo-grid-column field="name" title="Name" [width]="180"></kendo-grid-column>
|
||||
<kendo-grid-column field="designationName" title="Designation" [width]="160"></kendo-grid-column>
|
||||
<kendo-grid-column field="departmentName" title="Department" [width]="160"></kendo-grid-column>
|
||||
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="120"></kendo-grid-column>
|
||||
<kendo-grid-column field="service" title="Service (Yrs)" [width]="110"></kendo-grid-column>
|
||||
<kendo-grid-column field="leaveFromDate" title="LFA Start Date" [width]="130"></kendo-grid-column>
|
||||
<kendo-grid-column field="leaveToDate" title="LFA End Date" [width]="130"></kendo-grid-column>
|
||||
<kendo-grid-column field="leaveDays" title="Days" [width]="80"></kendo-grid-column>
|
||||
<ng-template kendoGridNoRecordsTemplate>No records found.</ng-template>
|
||||
</kendo-grid>
|
||||
</div>
|
||||
}
|
||||
</app-tab-panel>
|
||||
|
||||
<!-- ================= New LFA Payment ================= -->
|
||||
<app-tab-panel header="New LFA Payment ({{ rows.length }})" leftIcon="pi pi-money-bill">
|
||||
@if (selectedTab === 1) {
|
||||
<div class="lfa-tab">
|
||||
<div class="lfa-toolbar">
|
||||
<div class="lfa-field">
|
||||
<label>Payment Date <span class="lfa-required">*</span></label>
|
||||
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="paymentDate" (valueChange)="paymentDate = $event; onPaymentInfoChange()"></kendo-datepicker>
|
||||
</div>
|
||||
<!-- same file input as /common-interface/data-upload, on the right of the Payment Date -->
|
||||
<div class="lfa-upload">
|
||||
<input #fileInput id="fupLFAPayment" kendoTextBox type="file" accept=".xlsx" class="lfa-upload__file"
|
||||
(click)="clearSelectedFile()" (change)="selectFile($event)">
|
||||
<button class="k-button k-primary gh-import" type="button" kendoButton
|
||||
[svgIcon]="apiService.KendoSVGIcon['upload']" [disabled]="isBusy || !selectedFile" (click)="uploadFile()">
|
||||
Upload
|
||||
</button>
|
||||
<button class="k-button k-primary gh-download" type="button" kendoButton
|
||||
[svgIcon]="apiService.KendoSVGIcon['download']" (click)="downloadTemplate()">
|
||||
Sample File Download
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="lfa-toolbar">
|
||||
<div class="lfa-field lfa-field--remarks">
|
||||
<label>Remarks</label>
|
||||
<kendo-textbox [(ngModel)]="remarks" [maxlength]="500" placeholder="e.g. LFA for December 2026"></kendo-textbox>
|
||||
</div>
|
||||
<span class="lfa-spacer"></span>
|
||||
<button class="gh-reset" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['cross']" [disabled]="isBusy" (click)="clear()">Clear</button>
|
||||
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="rows.length === 0" (click)="paymentGrid.saveAsExcel()">Export</button>
|
||||
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['gear']" [disabled]="isBusy || rows.length === 0" (click)="confirmProcess()">Process Payment</button>
|
||||
</div>
|
||||
|
||||
<div class="lfa-summary">
|
||||
<div class="lfa-stat"><div class="lfa-stat__key">Employees</div><div class="lfa-stat__value">{{ rows.length }}</div></div>
|
||||
<div class="lfa-stat"><div class="lfa-stat__key">Total Basic Salary</div><div class="lfa-stat__value">{{ totalBasic | number: '1.2-2' }}</div></div>
|
||||
<div class="lfa-stat"><div class="lfa-stat__key">Total LFA Amount (BDT)</div><div class="lfa-stat__value">{{ totalAmount | number: '1.2-2' }}</div></div>
|
||||
<div class="lfa-stat"><div class="lfa-stat__key">Batch ID (on process)</div><div class="lfa-stat__value">{{ rows.length > 0 && info ? info.nextBatchNumber : '—' }}</div></div>
|
||||
</div>
|
||||
|
||||
<!-- virtual scrolling: only the rows on screen are rendered -->
|
||||
<kendo-grid #paymentGrid="kendoGrid" [kendoGridBinding]="rows" scrollable="virtual" [rowHeight]="40" [pageSize]="50"
|
||||
[sortable]="true" [resizable]="true" [height]="430">
|
||||
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120">
|
||||
<ng-template kendoGridFooterTemplate>Total</ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="name" title="Name" [width]="210" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }">
|
||||
<ng-template kendoGridFooterTemplate>{{ rows.length }} employees</ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="designationName" title="Designation" [width]="190" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
|
||||
<kendo-grid-column field="departmentName" title="Department" [width]="190" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
|
||||
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="130" format="dd-MMM-yyyy"></kendo-grid-column>
|
||||
<kendo-grid-column field="basicSalary" title="Basic Salary" [width]="140" format="n2" [style]="{ 'text-align': 'right' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
|
||||
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ totalBasic | number: '1.2-2' }}</div></ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="amount" title="LFA Amount" [width]="140" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
|
||||
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ totalAmount | number: '1.2-2' }}</div></ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-command-column title="Action" [width]="75">
|
||||
<ng-template kendoGridCellTemplate let-dataItem>
|
||||
<button type="button" kendoButton class="kt-delete" title="Remove" [svgIcon]="apiService.KendoSVGIcon['delete']" (click)="removeRow(dataItem)"></button>
|
||||
</ng-template>
|
||||
</kendo-grid-command-column>
|
||||
<ng-template kendoGridNoRecordsTemplate>No employees yet. Upload the Excel file.</ng-template>
|
||||
<kendo-grid-excel fileName="LFA-Payment.xlsx" [fetchData]="allPaymentRows"></kendo-grid-excel>
|
||||
</kendo-grid>
|
||||
|
||||
@if (issues.length > 0) {
|
||||
<div class="lfa-issues__head">
|
||||
<span>{{ issues.length }} error(s) found in the uploaded file. These rows are not in the list.</span>
|
||||
<button class="gh-view" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['eye']" (click)="showIssues = true">View Errors</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="lfa-note">Uploaded file columns: Employee ID, Name. Amounts in BDT.</div>
|
||||
</div>
|
||||
}
|
||||
</app-tab-panel>
|
||||
|
||||
<!-- ================= Payment History ================= -->
|
||||
<app-tab-panel header="Payment History" leftIcon="pi pi-history">
|
||||
@if (selectedTab === 2) {
|
||||
<div class="lfa-tab">
|
||||
<div class="lfa-toolbar">
|
||||
<div class="lfa-field">
|
||||
<label>Start Date <span class="lfa-required">*</span></label>
|
||||
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="historyFrom"></kendo-datepicker>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>End Date <span class="lfa-required">*</span></label>
|
||||
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="historyTo"></kendo-datepicker>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>Status</label>
|
||||
<kendo-dropdownlist [data]="historyStatuses" [(ngModel)]="historyStatus" (valueChange)="historyStatus = $event; filterHistory()"></kendo-dropdownlist>
|
||||
</div>
|
||||
<div class="lfa-field">
|
||||
<label>Department</label>
|
||||
<kendo-dropdownlist [data]="historyDepartments" [(ngModel)]="historyDepartment" (valueChange)="historyDepartment = $event; filterHistory()"></kendo-dropdownlist>
|
||||
</div>
|
||||
<button class="gh-refresh" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['redo']" [disabled]="isBusy" (click)="loadHistory()">Load</button>
|
||||
</div>
|
||||
<div class="lfa-toolbar">
|
||||
<div class="lfa-field lfa-field--wide">
|
||||
<label>Search in results</label>
|
||||
<kendo-textbox [(ngModel)]="historySearch" (valueChange)="historySearch = $event; filterHistory()" [clearButton]="true" placeholder="Batch, ID, name…"></kendo-textbox>
|
||||
</div>
|
||||
<span class="lfa-spacer"></span>
|
||||
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="historyRows.length === 0" (click)="historyGrid.saveAsExcel()">Export</button>
|
||||
<button class="gh-print" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['print']" [disabled]="historyRows.length === 0" (click)="printHistory()">Print</button>
|
||||
</div>
|
||||
|
||||
<kendo-grid #historyGrid="kendoGrid" [kendoGridBinding]="historyRows" [sortable]="true" [resizable]="true"
|
||||
[pageable]="{ pageSizes: [10, 25, 50, 100] }" [pageSize]="25" [height]="500">
|
||||
<kendo-grid-column field="batchNumber" title="Batch ID" [width]="130" [style]="{ 'font-weight': '600' }"></kendo-grid-column>
|
||||
<kendo-grid-column field="paymentDate" title="Payment Date" [width]="120" format="dd-MMM-yyyy"></kendo-grid-column>
|
||||
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="110"></kendo-grid-column>
|
||||
<kendo-grid-column field="name" title="Name" [width]="190"></kendo-grid-column>
|
||||
<kendo-grid-column field="designationName" title="Designation" [width]="160"></kendo-grid-column>
|
||||
<kendo-grid-column field="departmentName" title="Department" [width]="170"></kendo-grid-column>
|
||||
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="120" format="dd-MMM-yyyy"></kendo-grid-column>
|
||||
<kendo-grid-column field="basicSalary" title="Basic Salary" [width]="130" format="n2" [style]="{ 'text-align': 'right' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
|
||||
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ historyTotalBasic | number: '1.2-2' }}</div></ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="amount" title="LFA Amount" [width]="130" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
|
||||
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ historyTotalAmount | number: '1.2-2' }}</div></ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="statusText" title="Payment Status" [width]="130">
|
||||
<ng-template kendoGridCellTemplate let-dataItem>
|
||||
<span class="lfa-badge" [class.lfa-badge--paid]="dataItem.statusText === 'Paid'"
|
||||
[class.lfa-badge--failed]="dataItem.statusText === 'Failed'">{{ dataItem.statusText }}</span>
|
||||
</ng-template>
|
||||
</kendo-grid-column>
|
||||
<ng-template kendoGridNoRecordsTemplate>No records found.</ng-template>
|
||||
<kendo-grid-excel fileName="LFA-Payment-History.xlsx" [fetchData]="allHistoryRows"></kendo-grid-excel>
|
||||
</kendo-grid>
|
||||
<div class="lfa-info">{{ historySummary }}</div>
|
||||
</div>
|
||||
}
|
||||
</app-tab-panel>
|
||||
</app-tab-view>
|
||||
</div>
|
||||
|
||||
@if (showConfirm) {
|
||||
<div class="blur-background">
|
||||
<kendo-dialog title="Confirm LFA Payment" [width]="460" maxHeight="90vh" (close)="showConfirm = false" (keydown.escape)="$event.stopPropagation()">
|
||||
<p>You are about to process LFA payment for <b>{{ rows.length }}</b> employee(s). This will create a new payment batch.</p>
|
||||
<table class="lfa-confirm">
|
||||
<tbody>
|
||||
<tr><td>Batch ID</td><td>{{ info ? info.nextBatchNumber : '' }}</td></tr>
|
||||
<tr><td>Payment Date</td><td>{{ paymentDate | date: 'dd-MMM-yyyy' }}</td></tr>
|
||||
<tr><td>Total LFA Amount</td><td>BDT {{ totalAmount | number: '1.2-2' }}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<kendo-dialog-actions>
|
||||
<button class="gh-cancel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['cancel']" [disabled]="isBusy" (click)="showConfirm = false">Cancel</button>
|
||||
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['check']" [disabled]="isBusy" (click)="process()">Confirm & Process</button>
|
||||
</kendo-dialog-actions>
|
||||
</kendo-dialog>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- validation errors of the upload / calculation / process -->
|
||||
@if (showIssues) {
|
||||
<div class="blur-background">
|
||||
<kendo-dialog title="Error List ({{ issues.length }})" [width]="900" maxHeight="90vh" (close)="showIssues = false" (keydown.escape)="$event.stopPropagation()">
|
||||
<kendo-grid #issueGrid="kendoGrid" [kendoGridBinding]="issues" [pageable]="true" [pageSize]="20" [sortable]="true" [resizable]="true">
|
||||
<kendo-grid-column field="rowNo" title="Excel Row" [width]="90">
|
||||
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.rowNo > 0 ? dataItem.rowNo : 'File' }}</ng-template>
|
||||
</kendo-grid-column>
|
||||
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120"></kendo-grid-column>
|
||||
<kendo-grid-column field="employeeName" title="Name" [width]="200"></kendo-grid-column>
|
||||
<kendo-grid-column field="message" title="Error"></kendo-grid-column>
|
||||
<ng-template kendoGridNoRecordsTemplate>No errors.</ng-template>
|
||||
<kendo-grid-excel fileName="LFA-Payment-Errors.xlsx" [fetchData]="allIssues"></kendo-grid-excel>
|
||||
</kendo-grid>
|
||||
<kendo-dialog-actions>
|
||||
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" (click)="issueGrid.saveAsExcel()">Export</button>
|
||||
<button class="gh-cancel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['cancel']" (click)="showIssues = false">Close</button>
|
||||
</kendo-dialog-actions>
|
||||
</kendo-dialog>
|
||||
</div>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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%;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<HTMLInputElement>;
|
||||
|
||||
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<LFAPaymentReadResult> = 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) + '</' + tag + '>').join('');
|
||||
const body = this.historyRows.map(x => '<tr>' + 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') + '</tr>').join('');
|
||||
w.document.write('<html><head><title>LFA Payment History</title><style>body{font-family:Arial;font-size:12px}'
|
||||
+ 'table{border-collapse:collapse;width:100%}th,td{border:1px solid #999;padding:4px;text-align:left}</style></head><body>'
|
||||
+ '<h3>LFA Payment History (' + this.displayDate(this.historyFrom) + ' - ' + this.displayDate(this.historyTo) + ')</h3><table><thead><tr>'
|
||||
+ cells(['Batch ID', 'Payment Date', 'Employee ID', 'Name', 'Designation', 'Department', 'Joining Date', 'Basic Salary',
|
||||
'LFA Amount', 'Payment Status'], 'th')
|
||||
+ '</tr></thead><tbody>' + body + '</tbody></table><p>' + this.escape(this.historySummary) + ' · LFA Amount '
|
||||
+ money(this.historyTotalAmount) + '</p></body></html>');
|
||||
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, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
private sum<T>(items: T[], value: (item: T) => number): number {
|
||||
return Math.round(items.reduce((total, x) => total + (value(x) || 0), 0) * 100) / 100;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 { }
|
||||
|
|
|
|||
|
|
@ -366,6 +366,9 @@ namespace HRM.UI.Configuration.DI
|
|||
services.AddTransient<IHistorySalaryMonthlyService, HistorySalaryMonthlyService>();
|
||||
services.AddTransient<ISalaryMasterBulkUploadService, SalaryMasterBulkUploadService>();
|
||||
|
||||
//LFA
|
||||
services.AddTransient<ILFAPaymentService, LFAPaymentService>();
|
||||
|
||||
//Fund
|
||||
services.AddTransient<IFundTypeService, FundTypeService>();
|
||||
services.AddTransient<IFundBankService, FundBankService>();
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
/// <summary>The empty LFA payment workbook: Employee ID and Name.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a filled LFA payment workbook (multipart form: first file, plus "paymentDate")
|
||||
/// and returns the calculated employees and every problem. Nothing is saved.
|
||||
/// </summary>
|
||||
[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
|
||||
|
||||
/// <summary>The "salaryMonth" form field (the month picked on the page) as the last date of that month.</summary>
|
||||
private bool TryGetPostedSalaryMonth(out DateTime salaryMonth)
|
||||
{
|
||||
|
|
|
|||
104
HRM.UI/Controllers/Payroll/LFAController.cs
Normal file
104
HRM.UI/Controllers/Payroll/LFAController.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Core Payroll > LFA. The Excel template and upload are in DataUploadController, with every other uploader.
|
||||
/// </summary>
|
||||
[Route("api/lfa")]
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
public class LFAController : ControllerBase
|
||||
{
|
||||
private readonly ILFAPaymentService _lfaPaymentService;
|
||||
|
||||
public LFAController(ILFAPaymentService lfaPaymentService)
|
||||
{
|
||||
this._lfaPaymentService = lfaPaymentService;
|
||||
}
|
||||
|
||||
/// <summary>The current salary month and the next batch number.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calculates the rows again; nothing is saved.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Saves the rows as a new batch, all or nothing. The payroll type and user come from the token.</summary>
|
||||
[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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
146
LFA_DB_Changes.sql
Normal file
146
LFA_DB_Changes.sql
Normal file
|
|
@ -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
|
||||
Loading…
Reference in New Issue
Block a user