HRM-10/HRM.DA/Service/LFA/LFAPaymentService.cs
Mohaimen Hasan 0f5b150e98 LFA Undo
2026-11-26 15:13:21 +06:00

806 lines
35 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.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;
}
private LFAPaymentBatch MapBatch(DataReader oReader)
{
LFAPaymentBatch batch = new LFAPaymentBatch();
batch.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value;
batch.BatchNumber = oReader.GetString("BatchNumber");
batch.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value;
batch.LFAYear = oReader.GetDateTime("LFAYear").Value;
batch.PaymentDate = oReader.GetDateTime("PaymentDate").Value;
batch.Remarks = oReader.GetString("Remarks");
batch.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus");
batch.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value;
batch.CreationDate = oReader.GetDateTime("CreationDate").Value;
batch.CreatedByName = oReader.GetString("CreatedByName");
batch.HeadCount = oReader.GetInt32("HeadCount").Value;
batch.PaidCount = oReader.GetInt32("PaidCount").Value;
batch.TotalAmount = oReader.GetDouble("TotalAmount").Value;
batch.StatusText = StatusText(batch.WFStatus);
batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount);
batch.CanUndo = batch.UndoBlockedReason == null;
return batch;
}
private LFAPaymentBatchEmployee MapBatchEmployee(DataReader oReader)
{
LFAPaymentBatchEmployee employee = new LFAPaymentBatchEmployee();
employee.LFAPaymentDetailID = oReader.GetInt32("LFAPaymentDetailID").Value;
employee.EmployeeID = oReader.GetInt32("EmployeeID").Value;
employee.EmployeeNo = oReader.GetString("EMPLOYEENO");
employee.Name = oReader.GetString("NAME");
employee.DesignationName = oReader.GetString("DesignationName");
employee.DepartmentName = oReader.GetString("DepartmentName");
employee.JoiningDate = oReader.GetDateTime("JoiningDate").Value;
employee.BasicSalary = oReader.GetDouble("BasicSalary").Value;
employee.Amount = oReader.GetDouble("Amount").Value;
employee.PaymentStatus = (EnumLFAPaymentStatus)oReader.GetInt32("PaymentStatus").Value;
return employee;
}
#endregion
#region Get
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();
List<KeyValuePair<LFAPaymentInput, LFAEmployee>> validRows = Validate(tc, result, rows, paymentDate, payrollTypeID);
tc.End();
if (result.Issues.Count == 0)
Calculate(result, validRows, paymentDate); // only a fully valid file is calculated
}
catch (Exception e)
{
#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();
List<KeyValuePair<LFAPaymentInput, LFAEmployee>> validRows = Validate(tc, result, request.Rows,
request.PaymentDate.Value, payrollTypeID);
tc.End();
if (result.Issues.Count == 0)
Calculate(result, validRows, request.PaymentDate.Value);
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return result;
}
/// <summary>
/// Validation, the first step of every upload, recalculation and process: runs EVERY check on EVERY row
/// and puts every problem into result.Issues (the file's own problems, found while reading it, are
/// already there). Nothing is calculated here. Returns the rows that passed with their employee; they
/// may be calculated only when result.Issues is empty.
/// </summary>
private List<KeyValuePair<LFAPaymentInput, LFAEmployee>> Validate(TransactionContext tc, LFAPaymentReadResult result, List<LFAPaymentInput> inputs, DateTime paymentDate, int payrollTypeID)
{
List<KeyValuePair<LFAPaymentInput, LFAEmployee>> valid = new List<KeyValuePair<LFAPaymentInput, LFAEmployee>>();
if (inputs == null || inputs.Count == 0)
{
return valid;
}
DateTime lfaYear = GetLFAYear(paymentDate);
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 = GetBasicOnDate(tc, new DateTime(lfaYear.Year, 1, 1));
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) || employee.PayrollTypeID != payrollTypeID)
{
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]) + ").");
}
foreach (string problem in problems)
{
result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem);
}
if (problems.Count == 0)
{
valid.Add(new KeyValuePair<LFAPaymentInput, LFAEmployee>(input, employee));
}
}
result.Issues = result.Issues.OrderBy(x => x.RowNo).ToList();
return valid;
}
/// <summary>
/// Calculation (LFACalculator.Calculate) of rows that Validate passed. Call it ONLY when Validate left
/// result.Issues empty. Fills result.Rows and returns each row's detail, in the same order.
/// </summary>
private static List<LFAPaymentDetail> Calculate(LFAPaymentReadResult result, List<KeyValuePair<LFAPaymentInput, LFAEmployee>> validRows, DateTime paymentDate)
{
DateTime lfaYear = GetLFAYear(paymentDate);
List<LFAPaymentDetail> details = new List<LFAPaymentDetail>();
foreach (KeyValuePair<LFAPaymentInput, LFAEmployee> item in validRows)
{
LFAPaymentDetail detail = LFACalculator.Calculate(item.Value, lfaYear);
details.Add(detail);
result.Rows.Add(ToRow(item.Value, item.Key, detail, paymentDate));
}
return details;
}
/// <summary>
/// EmployeeID → basic on the date (LFAPaymentDA.GetBasicOnDate, the LFA copy of
/// EmployeeGradeSalaryService.GetBasicOnDate). Every row is read, the first one included.
/// </summary>
private static Dictionary<int, double> GetBasicOnDate(TransactionContext tc, DateTime effectDate)
{
Dictionary<int, double> basics = new Dictionary<int, double>();
DataReader dr = new DataReader(LFAPaymentDA.GetBasicOnDate(tc, effectDate));
while (dr.Read())
{
basics[dr.GetInt32("EMPLOYEEID").Value] = dr.GetDouble("BASICSALARY", 0);
}
dr.Close();
return basics;
}
private static LFAPaymentRow ToRow(LFAEmployee employee, LFAPaymentInput input, LFAPaymentDetail detail,
DateTime paymentDate)
{
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,
ServiceLength = LFACalculator.ServiceLength(employee.JoiningDate, paymentDate),
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<KeyValuePair<LFAPaymentInput, LFAEmployee>> validRows = Validate(tc, validation, request.Rows,
request.PaymentDate.Value, payrollTypeID);
List<LFAPaymentDetail> details = validation.Issues.Count == 0
? Calculate(validation, validRows, request.PaymentDate.Value) // only after a clean validation
: new List<LFAPaymentDetail>();
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(request.PaymentDate.Value);
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 Undo
/// <summary>LFA Payment Undo: every batch of the payroll type, and whether each one can be undone.</summary>
public List<LFAPaymentBatch> GetUndoBatches(int payrollTypeID)
{
List<LFAPaymentBatch> items = new List<LFAPaymentBatch>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(LFAPaymentDA.GetBatches(tc, payrollTypeID));
while (dr.Read())
{
items.Add(MapBatch(dr));
}
dr.Close();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return items;
}
/// <summary>The employees of one batch of the payroll type; empty when the batch is not found.</summary>
public List<LFAPaymentBatchEmployee> GetBatchEmployees(int lfaPaymentID, int payrollTypeID)
{
List<LFAPaymentBatchEmployee> items = new List<LFAPaymentBatchEmployee>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
LFAPayment oPayment = null;
DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID));
if (dr.Read())
{
oPayment = this.CreateObject<LFAPayment>(dr);
}
dr.Close();
if (oPayment != null && oPayment.PayrollTypeID == payrollTypeID)
{
dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, lfaPaymentID));
while (dr.Read())
{
items.Add(MapBatchEmployee(dr));
}
dr.Close();
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return items;
}
/// <summary>
/// Undoes the whole batch (request.DetailIDs empty) or only those employees of it, in ONE transaction.
/// Everything is checked again here with the batch locked: a batch submitted for approval, approved,
/// already in the tax data or with a paid employee is not undone. When the last employee goes, the
/// batch goes too. The undone employees can then be paid again in another batch.
/// </summary>
public LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID)
{
LFAPaymentUndoResult result = new LFAPaymentUndoResult();
TransactionContext tc = null;
try
{
if (request == null || request.LFAPaymentID <= 0)
throw new ServiceException("Please select a batch.");
List<int> detailIDs = (request.DetailIDs ?? new List<int>()).Distinct().ToList();
tc = TransactionContext.Begin(true);
LFAPayment oPayment = null;
DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, request.LFAPaymentID));
if (dr.Read())
{
oPayment = this.CreateObject<LFAPayment>(dr);
}
dr.Close();
if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID)
{
result.Message = "The batch is not found. It may have been undone already.";
tc.End();
return result;
}
List<LFAPaymentDetail> details = new List<LFAPaymentDetail>();
dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, oPayment.ID));
while (dr.Read())
{
LFAPaymentDetail oDetail = new LFAPaymentDetail();
MapDetailObject(oDetail, dr);
details.Add(oDetail);
}
dr.Close();
bool wholeBatch = detailIDs.Count == 0 || details.All(x => detailIDs.Contains(x.ID));
List<LFAPaymentDetail> selected = wholeBatch ? details : details.Where(x => detailIDs.Contains(x.ID)).ToList();
string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated,
selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid));
if (blocked != null)
{
result.Message = blocked;
}
else if (!wholeBatch && selected.Count != detailIDs.Count)
{
result.Message = "Some of the selected employees are no longer in batch " + oPayment.BatchNumber
+ ". Please load the batch again.";
}
else
{
if (wholeBatch)
{
LFAPaymentDetailDA.DeleteByPaymentID(tc, oPayment.ID);
LFAPaymentDA.Delete(tc, oPayment.ID);
result.BatchRemoved = true;
result.Message = "Batch " + oPayment.BatchNumber + " is undone (" + selected.Count + " employee(s)).";
}
else
{
LFAPaymentDetailDA.Delete(tc, oPayment.ID, selected.Select(x => x.ID).ToList());
LFAPaymentDA.UpdateModified(tc, oPayment.ID, userID, DateTime.Now);
result.Message = selected.Count + " employee(s) undone from batch " + oPayment.BatchNumber + ".";
}
result.Undone = true;
result.RemovedCount = selected.Count;
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return result;
}
/// <summary>
/// Why a batch cannot be undone; null when it can. Undo is allowed before the batch is submitted for
/// approval, and after the approver sends it back (Revert) or declines it.
/// </summary>
private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount)
{
if (wfStatus == enumwfStatus.Approve)
return "The batch is already approved.";
if (wfStatus != null && wfStatus != enumwfStatus.Not_yet_Submitted && wfStatus != enumwfStatus.Revert
&& wfStatus != enumwfStatus.Decline)
return "The batch is submitted and pending for approval.";
if (isTaxUpdated)
return "The batch is already in the income tax data.";
if (paidCount > 0)
return paidCount + " employee(s) of the batch are already paid.";
return null;
}
private static string StatusText(enumwfStatus? wfStatus)
{
if (wfStatus == null || wfStatus == enumwfStatus.Not_yet_Submitted)
return "Not Submitted";
switch (wfStatus.Value)
{
case enumwfStatus.Approve:
return "Approved";
case enumwfStatus.Revert:
return "Reverted";
case enumwfStatus.Decline:
return "Declined";
default:
return "Pending Approval";
}
}
#endregion
#region Helpers
private static void CheckRequest(LFAPaymentRequest request)
{
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;
}
/// <summary>LFAYear: the last date of the payment date's month (the LFA is for that date's calendar year).</summary>
private static DateTime GetLFAYear(DateTime paymentDate)
{
return GlobalFunctions.LastDateOfMonth(paymentDate).Date;
}
private static string BatchPrefix(DateTime salaryMonth)
{
return "LFA-" + salaryMonth.Year + "-";
}
private static string BatchNumber(string prefix, int no)
{
return prefix + no.ToString("000");
}
#endregion
}
}