HRM-10/HRM.DA/Service/LFA/LFAPaymentService.cs
Mohaimen Hasan 88235461bf LFA
2026-11-26 10:48:45 +06:00

545 lines
23 KiB
C#

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