using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ease.Core.DataAccess; using Ease.Core.Model; using Ease.Core.Utility; using HRM.BO; namespace HRM.DA { /// LFA Payment (Core Payroll > LFA): upload, calculate, process into a batch, and the payment history. public class LFAPaymentService : ServiceTemplate, ILFAPaymentService { public LFAPaymentService() { } #region Mapping private void MapObject(LFAPayment oPayment, DataReader oReader) { base.SetObjectID(oPayment, oReader.GetInt32("LFAPaymentID").Value); oPayment.BatchNumber = oReader.GetString("BatchNumber"); oPayment.PayrollTypeID = oReader.GetInt32("PayrollTypeID").Value; oPayment.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value; oPayment.LFAYear = oReader.GetDateTime("LFAYear").Value; oPayment.PaymentDate = oReader.GetDateTime("PaymentDate").Value; oPayment.Remarks = oReader.GetString("Remarks"); oPayment.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value; oPayment.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus"); oPayment.ApprovedBy = oReader.GetInt32("ApprovedBy"); oPayment.ApprovedDate = oReader.GetDateTime("ApprovedDate"); oPayment.CreatedBy = oReader.GetInt32("CreatedBy").Value; oPayment.CreatedDate = oReader.GetDateTime("CreationDate").Value; oPayment.ModifiedBy = oReader.GetInt32("ModifiedBy"); oPayment.ModifiedDate = oReader.GetDateTime("ModifiedDate"); this.SetObjectState(oPayment, Ease.Core.ObjectState.Saved); } protected override T CreateObject(DataReader oReader) { LFAPayment oPayment = new LFAPayment(); MapObject(oPayment, oReader); return oPayment as T; } private void MapDetailObject(LFAPaymentDetail oDetail, DataReader oReader) { base.SetObjectID(oDetail, oReader.GetInt32("LFAPaymentDetailID").Value); oDetail.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value; oDetail.EmployeeID = oReader.GetInt32("EmployeeID").Value; oDetail.LFAYear = oReader.GetDateTime("LFAYear").Value; oDetail.JoiningDate = oReader.GetDateTime("JoiningDate").Value; oDetail.ConfirmationDate = oReader.GetDateTime("ConfirmationDate"); oDetail.GradeID = oReader.GetInt32("GradeID"); oDetail.DesignationID = oReader.GetInt32("DesignationID"); oDetail.DepartmentID = oReader.GetInt32("DepartmentID"); oDetail.CostCenterID = oReader.GetInt32("CostCenterID"); oDetail.BranchID = oReader.GetInt32("BranchID"); oDetail.AccountNo = oReader.GetString("AccountNo"); oDetail.JoiningBasic = oReader.GetDouble("JoiningBasic"); oDetail.LastDecBasic = oReader.GetDouble("LastDecBasic"); oDetail.BasicSalary = oReader.GetDouble("BasicSalary").Value; oDetail.CalculatedAmount = oReader.GetDouble("CalculatedAmount").Value; oDetail.Amount = oReader.GetDouble("Amount").Value; oDetail.Remarks = oReader.GetString("Remarks"); oDetail.PaymentStatus = (EnumLFAPaymentStatus)oReader.GetInt32("PaymentStatus").Value; oDetail.CreatedBy = oReader.GetInt32("CreatedBy").Value; oDetail.CreatedDate = oReader.GetDateTime("CreationDate").Value; oDetail.ModifiedBy = oReader.GetInt32("ModifiedBy"); oDetail.ModifiedDate = oReader.GetDateTime("ModifiedDate"); this.SetObjectState(oDetail, Ease.Core.ObjectState.Saved); } private LFAEmployee MapEmployee(DataReader oReader) { LFAEmployee employee = new LFAEmployee(); employee.EmployeeID = oReader.GetInt32("EMPLOYEEID").Value; employee.EmployeeNo = oReader.GetString("EMPLOYEENO"); employee.Name = oReader.GetString("NAME"); employee.PayrollTypeID = oReader.GetInt32("PAYROLLTYPEID").Value; employee.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.ApprovedDate = oReader.GetDateTime("ApprovedDate"); batch.ApprovedByName = oReader.GetString("ApprovedByName"); batch.WFMovementTranID = oReader.GetInt32("WFMovementTranID"); batch.UniqueNumber = oReader.GetInt32("UniqueNumber"); batch.IsAtInitiator = oReader.GetInt32("IsAtInitiator", 0) == 1; batch.PendingWith = oReader.GetString("PendingWith"); batch.StatusText = StatusText(batch.WFStatus, batch.IsAtInitiator); batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount, batch.IsAtInitiator); 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(dr); } dr.Close(); if (oPayment != null) { dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, id)); while (dr.Read()) { LFAPaymentDetail oDetail = new LFAPaymentDetail(); MapDetailObject(oDetail, dr); oPayment.Details.Add(oDetail); } dr.Close(); } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return oPayment; } /// The current salary month and the batch number the next process will take. public LFAPaymentInfo GetInfo(int payrollTypeID) { LFAPaymentInfo info = new LFAPaymentInfo(); TransactionContext tc = null; try { info.PayrollTypeID = payrollTypeID; info.SalaryMonth = GetSalaryMonth(payrollTypeID); string prefix = BatchPrefix(info.SalaryMonth); tc = TransactionContext.Begin(); info.NextBatchNumber = BatchNumber(prefix, LFAPaymentDA.GetLastBatchNo(tc, payrollTypeID, prefix) + 1); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return info; } public List GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID) { List items = new List(); TransactionContext tc = null; try { tc = TransactionContext.Begin(); DataReader dr = new DataReader(LFAPaymentDA.GetHistory(tc, fromDate.Date, toDate.Date, payrollTypeID)); while (dr.Read()) { items.Add(MapHistory(dr)); } dr.Close(); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return items; } #endregion #region Upload and calculate public byte[] GetUploadTemplate() { try { return LFAPaymentWorkbook.BuildTemplate(); } catch (Exception e) { #region Handle Exception ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } } /// Reads an uploaded workbook and calculates its employees. Nothing is saved. public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, int payrollTypeID) { LFAPaymentReadResult result = new LFAPaymentReadResult(); TransactionContext tc = null; try { result.SalaryMonth = GetSalaryMonth(payrollTypeID); List rows = LFAPaymentWorkbook.Read(stream, fileName, fileLength, result); tc = TransactionContext.Begin(); List> validRows = Validate(tc, result, rows, paymentDate, payrollTypeID); tc.End(); if (result.Issues.Count == 0) Calculate(result, validRows, paymentDate); // only a fully valid file is calculated } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// Calculates the page's rows again (payment date or mode changed, draft opened). Nothing is saved. public LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID) { LFAPaymentReadResult result = new LFAPaymentReadResult(); TransactionContext tc = null; try { CheckRequest(request); result.SalaryMonth = GetSalaryMonth(payrollTypeID); tc = TransactionContext.Begin(); List> validRows = Validate(tc, result, request.Rows, request.PaymentDate.Value, payrollTypeID); tc.End(); if (result.Issues.Count == 0) Calculate(result, validRows, request.PaymentDate.Value); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// /// Validation, the first step of every upload, recalculation and process: runs EVERY check on EVERY row /// and puts every problem into result.Issues (the file's own problems, found while reading it, are /// already there). Nothing is calculated here. Returns the rows that passed with their employee; they /// may be calculated only when result.Issues is empty. /// private List> Validate(TransactionContext tc, LFAPaymentReadResult result, List inputs, DateTime paymentDate, int payrollTypeID) { List> valid = new List>(); 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 employees = new Dictionary(StringComparer.OrdinalIgnoreCase); DataReader dr = new DataReader(LFAPaymentDA.GetEmployees(tc, inputs.Select(x => x.EmployeeNo).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), lfaYear)); while (dr.Read()) { LFAEmployee employee = MapEmployee(dr); string key = (employee.EmployeeNo ?? "").Trim(); LFAEmployee found; if (!employees.TryGetValue(key, out found) || (found.PayrollTypeID != payrollTypeID && employee.PayrollTypeID == payrollTypeID)) { employees[key] = employee; } } dr.Close(); // Basic as of 31 December of the preceding year: the salary record that starts before 1 January // (the latest entry), as the bonus reads it. Dictionary lastDecBasics = 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> 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 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(input, employee)); } } result.Issues = result.Issues.OrderBy(x => x.RowNo).ToList(); return valid; } /// /// Calculation (LFACalculator.Calculate) of rows that Validate passed. Call it ONLY when Validate left /// result.Issues empty. Fills result.Rows and returns each row's detail, in the same order. /// private static List Calculate(LFAPaymentReadResult result, List> validRows, DateTime paymentDate) { DateTime lfaYear = GetLFAYear(paymentDate); List details = new List(); foreach (KeyValuePair item in validRows) { LFAPaymentDetail detail = LFACalculator.Calculate(item.Value, lfaYear); details.Add(detail); result.Rows.Add(ToRow(item.Value, item.Key, detail, paymentDate)); } return details; } /// /// EmployeeID → basic on the date (LFAPaymentDA.GetBasicOnDate, the LFA copy of /// EmployeeGradeSalaryService.GetBasicOnDate). Every row is read, the first one included. /// private static Dictionary GetBasicOnDate(TransactionContext tc, DateTime effectDate) { Dictionary basics = new Dictionary(); DataReader dr = new DataReader(LFAPaymentDA.GetBasicOnDate(tc, effectDate)); while (dr.Read()) { basics[dr.GetInt32("EMPLOYEEID").Value] = dr.GetDouble("BASICSALARY", 0); } dr.Close(); return basics; } private static LFAPaymentRow ToRow(LFAEmployee employee, LFAPaymentInput input, LFAPaymentDetail detail, DateTime paymentDate) { 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 /// /// Saves the page's rows as one new batch, in ONE transaction. Every row is validated and calculated /// again here; when a row no longer passes, or the total is not the one the page shows, nothing is saved. /// public LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID) { LFAPaymentProcessResult result = new LFAPaymentProcessResult(); TransactionContext tc = null; try { CheckRequest(request); if (request.Rows.Count == 0) throw new ServiceException("Add at least one employee."); if ((request.Remarks ?? "").Length > LFAPaymentUploadTemplate.MaxRemarksLength) throw new ServiceException("Remarks is longer than " + LFAPaymentUploadTemplate.MaxRemarksLength + " characters."); LFAPaymentReadResult validation = new LFAPaymentReadResult(); validation.SalaryMonth = GetSalaryMonth(payrollTypeID); string prefix = BatchPrefix(validation.SalaryMonth); tc = TransactionContext.Begin(true); int batchNo = LFAPaymentDA.GetLastBatchNoForUpdate(tc, payrollTypeID, prefix) + 1; List> validRows = Validate(tc, validation, request.Rows, request.PaymentDate.Value, payrollTypeID); List details = validation.Issues.Count == 0 ? Calculate(validation, validRows, request.PaymentDate.Value) // only after a clean validation : new List(); if (validation.Issues.Count > 0) { 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 /// LFA Payment Undo: every batch of the payroll type, and whether each one can be undone. public List GetUndoBatches(int payrollTypeID) { return GetBatches(payrollTypeID); } private List GetBatches(int payrollTypeID) { List items = new List(); TransactionContext tc = null; try { tc = TransactionContext.Begin(); DataReader dr = new DataReader(LFAPaymentDA.GetBatches(tc, payrollTypeID)); while (dr.Read()) { items.Add(MapBatch(dr)); } dr.Close(); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return items; } /// The employees of one batch of the payroll type; empty when the batch is not found. public List GetBatchEmployees(int lfaPaymentID, int payrollTypeID) { List items = new List(); TransactionContext tc = null; try { tc = TransactionContext.Begin(); LFAPayment oPayment = null; DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); if (oPayment != null && oPayment.PayrollTypeID == payrollTypeID) { dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, lfaPaymentID)); while (dr.Read()) { items.Add(MapBatchEmployee(dr)); } dr.Close(); } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return items; } /// /// Undoes the whole batch (request.DetailIDs empty) or only those employees of it, in ONE transaction. /// Everything is checked again here with the batch locked: a batch submitted for approval, approved, /// already in the tax data or with a paid employee is not undone. When the last employee goes, the /// batch goes too. The undone employees can then be paid again in another batch. /// public LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID) { LFAPaymentUndoResult result = new LFAPaymentUndoResult(); TransactionContext tc = null; try { if (request == null || request.LFAPaymentID <= 0) throw new ServiceException("Please select a batch."); List detailIDs = (request.DetailIDs ?? new List()).Distinct().ToList(); tc = TransactionContext.Begin(true); LFAPayment oPayment = null; DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, request.LFAPaymentID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) { result.Message = "The batch is not found. It may have been undone already."; tc.End(); return result; } List details = new List(); dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, oPayment.ID)); while (dr.Read()) { LFAPaymentDetail oDetail = new LFAPaymentDetail(); MapDetailObject(oDetail, dr); details.Add(oDetail); } dr.Close(); bool wholeBatch = detailIDs.Count == 0 || details.All(x => detailIDs.Contains(x.ID)); List selected = wholeBatch ? details : details.Where(x => detailIDs.Contains(x.ID)).ToList(); bool isAtInitiator = GetIsAtInitiator(tc, oPayment.ID); string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated, selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid), isAtInitiator); 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.DeleteWorkflow(tc, oPayment.ID); LFAPaymentDA.Delete(tc, oPayment.ID); result.BatchRemoved = true; result.Message = "Batch " + oPayment.BatchNumber + " is undone (" + selected.Count + " employee(s))."; } else { LFAPaymentDetailDA.Delete(tc, oPayment.ID, selected.Select(x => x.ID).ToList()); LFAPaymentDA.UpdateModified(tc, oPayment.ID, userID, DateTime.Now); result.Message = selected.Count + " employee(s) undone from batch " + oPayment.BatchNumber + "."; } result.Undone = true; result.RemovedCount = selected.Count; } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// /// Why a batch cannot be undone; null when it can. As Salary Undo: allowed before the batch is /// submitted for approval, and when an approver has reverted it back to the person who submitted it. /// private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount, bool isAtInitiator) { if (wfStatus == enumwfStatus.Approve) return "The batch is already approved."; if (wfStatus != null && wfStatus != enumwfStatus.Not_yet_Submitted && wfStatus != enumwfStatus.Revert && wfStatus != enumwfStatus.Decline && !isAtInitiator) 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, bool isAtInitiator) { if (wfStatus == null || wfStatus == enumwfStatus.Not_yet_Submitted) return "Not Submitted"; if (wfStatus != enumwfStatus.Approve && isAtInitiator) return "Reverted to Initiator"; switch (wfStatus.Value) { case enumwfStatus.Approve: return "Approved"; case enumwfStatus.Revert: return "Reverted"; case enumwfStatus.Decline: return "Declined"; default: return "Pending Approval"; } } #endregion #region Approval /// Logic key, the login's employee and the Work Flow Setup of LFA Payment. public LFAApprovalInfo GetApprovalInfo(int? employeeID) { LFAApprovalInfo info = new LFAApprovalInfo(); TransactionContext tc = null; try { info.IsWorkflowRequired = IsWorkflowRequired(); info.HasEmployee = employeeID.GetValueOrDefault() > 0; tc = TransactionContext.Begin(); info.HasWorkflowSetup = new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count > 0; tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return info; } /// LFA Payment Approval: every batch of the payroll type with its approval state. public List GetApprovalBatches(int payrollTypeID) { return GetBatches(payrollTypeID); } /// Every approval step of the batch, as Salary Approve shows its flow history. public List GetFlowHistory(int lfaPaymentID, int payrollTypeID) { LFAPayment oPayment = this.Get(lfaPaymentID); if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) return new List(); return new WFMovementTranService().GetFlowHistoriesByObjectID(lfaPaymentID, LFAPaymentApproval.WFTypeID, null) ?? new List(); } /// /// Direct Approve (lfaapproval/workflow = No), as Salary's ApproveSalary: the batch is approved at once. /// Refused while the workflow is on, or when the batch was already submitted or approved. /// public LFAApprovalResult ApproveDirect(LFAApprovalRequest request, int payrollTypeID, int userID) { LFAApprovalResult result = new LFAApprovalResult(); TransactionContext tc = null; try { if (request == null || request.LFAPaymentID <= 0) throw new ServiceException("Please select a batch."); if (IsWorkflowRequired()) { result.Message = "LFA approval goes through the approval workflow. Please submit the batch for approval."; return result; } tc = TransactionContext.Begin(true); LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); string blocked = oPayment == null ? "The batch is not found. It may have been undone." : DirectApproveBlockedReason(oPayment); if (blocked != null) { result.Message = blocked; } else { LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); result.Done = true; result.Approved = true; result.Message = "Batch " + oPayment.BatchNumber + " is approved."; } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// /// Submit for approval (lfaapproval/workflow = Yes), as Salary's ApproveSalaryNew: a new batch starts the /// workflow (WFTYPE 33) with the login's employee as initiator. A batch an approver reverted back to its /// initiator is submitted again from where it stopped, as ApproveSalaryForInitiator does. /// public LFAApprovalResult SubmitForApproval(LFAApprovalRequest request, int payrollTypeID, int? employeeID, int userID) { LFAApprovalResult result = new LFAApprovalResult(); TransactionContext tc = null; try { if (request == null || request.LFAPaymentID <= 0) throw new ServiceException("Please select a batch."); if (!IsWorkflowRequired()) { result.Message = "The LFA approval workflow is off. Please approve the batch directly."; return result; } if (employeeID.GetValueOrDefault() <= 0) { result.Message = "Your login is not linked with an employee. The approval workflow needs an employee to submit the batch."; return result; } int empID = employeeID.Value; string remarks = (request.Remarks ?? "").Trim(); tc = TransactionContext.Begin(true); LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); if (oPayment == null) { result.Message = "The batch is not found. It may have been undone."; } else if (oPayment.WFStatus == enumwfStatus.Approve) { result.Message = "Batch " + oPayment.BatchNumber + " is already approved."; } else if (oPayment.WFStatus == null || oPayment.WFStatus == enumwfStatus.Not_yet_Submitted) { // first submit: start the workflow if (new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count == 0) { result.Message = "No approval workflow is set up for LFA Payment. Please set it up in Work Flow Setup first."; } else if (!HasEmployees(tc, oPayment.ID)) { result.Message = "Batch " + oPayment.BatchNumber + " has no employee."; } else { LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); string subject = "LFA payment batch " + oPayment.BatchNumber + " (payment date " + oPayment.PaymentDate.ToString("dd-MMM-yyyy") + "). Your approval is required."; try { new WFManager(oPayment).InitiateProcess(tc, empID, LFAPaymentApproval.WFTypeID, oPayment.ID, remarks, subject); } catch (Exception wfError) { // e.g. no rule of the setup applies to this employee throw new ServiceException("The approval workflow could not start: " + wfError.Message + " Please check the LFA Payment rules in Work Flow Setup.", wfError); } result.Done = true; result.Message = "Batch " + oPayment.BatchNumber + " is submitted for approval."; } } else { // already in the workflow: only the initiator, after a revert, can submit it again WorkflowState state = GetWorkflowState(tc, oPayment.ID); if (state == null || !state.IsAtInitiator) { result.Message = "Batch " + oPayment.BatchNumber + " is submitted and pending for approval."; } else if (state.InitiatorEmpID != empID) { result.Message = "Only the employee who submitted batch " + oPayment.BatchNumber + " can submit it again."; } else { string subject = "LFA payment batch " + oPayment.BatchNumber + " is submitted again"; WFMovementTran next = new WFManager().Approve(tc, state.WFMovementTranID, empID, remarks, subject); result.Approved = FinishStep(tc, oPayment, next, userID); result.Done = true; result.Message = result.Approved ? "Batch " + oPayment.BatchNumber + " is approved." : "Batch " + oPayment.BatchNumber + " is submitted for approval again."; } } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// The batch an approver opened from the Payment Approval page, and whether they may act on it. public LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID) { LFAApproverBatch result = new LFAApproverBatch(); TransactionContext tc = null; try { tc = TransactionContext.Begin(); WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) { result.Message = "The LFA approval request is not found."; } else { LFAPayment oPayment = null; DataReader dr = new DataReader(LFAPaymentDA.Get(tc, oTran.ObjectID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); if (oPayment == null) { result.Message = "The LFA batch is not found. It may have been undone."; } else { dr = new DataReader(LFAPaymentDA.GetBatches(tc, oPayment.PayrollTypeID)); while (dr.Read()) { if (dr.GetInt32("LFAPaymentID").Value == oPayment.ID) { result.Batch = MapBatch(dr); break; } } dr.Close(); dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, oPayment.ID)); while (dr.Read()) { result.Employees.Add(MapBatchEmployee(dr)); } dr.Close(); result.CanAct = employeeID.GetValueOrDefault() > 0 && oPayment.WFStatus != enumwfStatus.Approve && LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID.Value); if (!result.CanAct) { result.Message = oPayment.WFStatus == enumwfStatus.Approve ? "Batch " + oPayment.BatchNumber + " is already approved." : "This approval step is not pending with you any more."; } } } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// /// An approver approves their step, as Salary's ApproveSalaryFromApprover: the workflow moves to the next /// approver, or, after the last one, the batch is approved. /// public LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID) { LFAApprovalResult result = new LFAApprovalResult(); TransactionContext tc = null; try { if (request == null || request.WFMovementTranID <= 0) throw new ServiceException("The LFA approval request is not found."); if (employeeID.GetValueOrDefault() <= 0) { result.Message = "Your login is not linked with an employee."; return result; } tc = TransactionContext.Begin(true); LFAPayment oPayment; string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); if (blocked != null) { result.Message = blocked; } else { string subject = "LFA payment batch " + oPayment.BatchNumber + " has been approved"; WFMovementTran next = new WFManager().Approve(tc, request.WFMovementTranID, employeeID.Value, (request.Remarks ?? "").Trim(), subject); result.Approved = FinishStep(tc, oPayment, next, userID); result.Done = true; result.Message = result.Approved ? "Batch " + oPayment.BatchNumber + " is approved." : "Batch " + oPayment.BatchNumber + " is approved by you and sent to the next approver."; } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } /// An approver reverts their step to the previous one (or to the initiator), as Salary's revert. public LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID) { LFAApprovalResult result = new LFAApprovalResult(); TransactionContext tc = null; try { if (request == null || request.WFMovementTranID <= 0) throw new ServiceException("The LFA approval request is not found."); if (employeeID.GetValueOrDefault() <= 0) { result.Message = "Your login is not linked with an employee."; return result; } string remarks = (request.Remarks ?? "").Trim(); if (remarks.Length == 0) { result.Message = "Please write why the batch is reverted."; return result; } Employee oFromEmployee = new EmployeeService().Get(employeeID.Value); tc = TransactionContext.Begin(true); LFAPayment oPayment; string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); if (blocked != null) { result.Message = blocked; } else { string subject = "(" + (oFromEmployee != null ? oFromEmployee.EmployeeNo + ")-" + oFromEmployee.Name : employeeID + ")") + " has reverted LFA payment batch " + oPayment.BatchNumber; new WFManager().RevertNew(tc, request.WFMovementTranID, employeeID.Value, remarks, subject); result.Done = true; result.Message = "Batch " + oPayment.BatchNumber + " is reverted."; } tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return result; } #region LFA Bank Advice /// LFA Bank Advice: only the approved batches of the payroll type can go to the bank. public List GetBankAdviceBatches(int payrollTypeID) { return GetBatches(payrollTypeID).Where(x => x.WFStatus == enumwfStatus.Approve).ToList(); } /// /// The bank advice rows of one approved batch of the payroll type: the selected employees (sEmpIDs, /// comma separated; empty = the whole batch), of one bank (bankID; 0 = every bank). Not approved, /// or not of this payroll type, is refused. /// public System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID) { // the IDs go into the SQL as %q, so only digits pass string empIDs = string.Join(",", (sEmpIDs ?? string.Empty) .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.TryParse(x.Trim(), out int id) ? id : 0) .Where(id => id > 0) .Distinct()); System.Data.DataSet ds = null; TransactionContext tc = null; try { tc = TransactionContext.Begin(); LFAPayment oPayment = null; DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) throw new Exception("LFA payment batch not found."); if (oPayment.WFStatus != enumwfStatus.Approve) throw new Exception("LFA payment batch " + oPayment.BatchNumber + " is not approved yet."); ds = LFAPaymentDA.GetBankAdvice(tc, lfaPaymentID, empIDs, bankID, payrollTypeID); tc.End(); } catch (Exception e) { #region Handle Exception if (tc != null) tc.HandleError(); ExceptionLog.Write(e); throw new ServiceException(e.Message, e); #endregion } return ds; } #endregion /// lfaapproval/workflow = Yes. private static bool IsWorkflowRequired() { return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, LFAPaymentApproval.LogicParent, LFAPaymentApproval.LogicChild); } /// The batch of the payroll type, locked until the transaction ends; null when not found. private LFAPayment GetForUpdate(TransactionContext tc, int lfaPaymentID, int payrollTypeID) { LFAPayment oPayment = null; DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, lfaPaymentID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); return oPayment != null && oPayment.PayrollTypeID == payrollTypeID ? oPayment : null; } private static string DirectApproveBlockedReason(LFAPayment oPayment) { if (oPayment.WFStatus == enumwfStatus.Approve) return "Batch " + oPayment.BatchNumber + " is already approved."; if (oPayment.WFStatus != null && oPayment.WFStatus != enumwfStatus.Not_yet_Submitted) return "Batch " + oPayment.BatchNumber + " is in the approval workflow. It is approved from the Payment Approval page."; return null; } private static bool HasEmployees(TransactionContext tc, int lfaPaymentID) { DataReader dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, lfaPaymentID)); bool any = dr.Read(); dr.Close(); return any; } /// /// Why the employee cannot act on this step (null when they can): the step must be an LFA one, still the /// latest of its workflow, pending with them, and its batch must exist and not be approved yet. /// The batch is locked until the transaction ends. /// private string CheckApproverStep(TransactionContext tc, int wfMovementTranID, int employeeID, out LFAPayment oPayment) { oPayment = null; WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) return "The LFA approval request is not found."; DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, oTran.ObjectID)); if (dr.Read()) { oPayment = this.CreateObject(dr); } dr.Close(); if (oPayment == null) return "The LFA batch is not found. It may have been undone."; if (oPayment.WFStatus == enumwfStatus.Approve) return "Batch " + oPayment.BatchNumber + " is already approved."; if (!LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID)) return "This approval step is not pending with you any more."; return null; } /// /// After a workflow step: the batch is approved when the workflow ended, otherwise it stays in the /// workflow (Not_yet_Initiated), as Salary's ApproveSalaryNew. Returns true when approved. /// private static bool FinishStep(TransactionContext tc, LFAPayment oPayment, WFMovementTran next, int userID) { if (next != null && next.Status == EnumwfStatus.End) { LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); return true; } LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); return false; } private class WorkflowState { public int WFMovementTranID; public int InitiatorEmpID; public bool IsAtInitiator; } private static WorkflowState GetWorkflowState(TransactionContext tc, int lfaPaymentID) { WorkflowState state = null; DataReader dr = new DataReader(LFAPaymentDA.GetWorkflowState(tc, lfaPaymentID)); if (dr.Read()) { state = new WorkflowState { WFMovementTranID = dr.GetInt32("WFMovementTranID").Value, InitiatorEmpID = dr.GetInt32("InitiatorEmpID", 0), IsAtInitiator = dr.GetInt32("IsAtInitiator", 0) == 1 }; } dr.Close(); return state; } private static bool GetIsAtInitiator(TransactionContext tc, int lfaPaymentID) { WorkflowState state = GetWorkflowState(tc, lfaPaymentID); return state != null && state.IsAtInitiator; } #endregion #region Helpers private static void CheckRequest(LFAPaymentRequest request) { if (request == null || request.Rows == null) throw new ServiceException("Nothing to process."); if (request.PaymentDate == null) throw new ServiceException("Payment Date is required."); } /// The current salary month: the last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE. private static DateTime GetSalaryMonth(int payrollTypeID) { PayrollType payrollType = new PayrollTypeService().Get(payrollTypeID); if (payrollType == null || payrollType.ID <= 0) throw new ServiceException("Payroll type not found."); return GlobalFunctions.LastDateOfMonth(payrollType.NextPayProcessDate).Date; } /// LFAYear: the last date of the payment date's month (the LFA is for that date's calendar year). private static DateTime GetLFAYear(DateTime paymentDate) { return 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 } }