This commit is contained in:
Mohaimen Hasan 2026-11-26 15:13:21 +06:00
parent 7fc90dd864
commit 0f5b150e98
15 changed files with 959 additions and 58 deletions

View File

@ -103,7 +103,6 @@ namespace HRM.BO
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; }
@ -147,6 +146,11 @@ namespace HRM.BO
LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID);
LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID);
List<LFAPaymentHistory> GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID);
// LFA Payment Undo
List<LFAPaymentBatch> GetUndoBatches(int payrollTypeID);
List<LFAPaymentBatchEmployee> GetBatchEmployees(int lfaPaymentID, int payrollTypeID);
LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID);
}
#endregion

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
namespace HRM.BO
{
#region LFA Payment Undo (not tables)
/// <summary>One batch of the LFA Payment Undo page.</summary>
public class LFAPaymentBatch
{
public int LFAPaymentID { get; set; }
public string BatchNumber { get; set; }
public DateTime SalaryMonth { get; set; }
public DateTime LFAYear { get; set; }
public DateTime PaymentDate { get; set; }
public string Remarks { get; set; }
public enumwfStatus? WFStatus { get; set; }
public bool IsTaxUpdated { get; set; }
public int HeadCount { get; set; }
public int PaidCount { get; set; }
public double TotalAmount { get; set; }
public string CreatedByName { get; set; }
public DateTime CreationDate { get; set; }
/// <summary>Approval state in words (Not Submitted, Pending Approval, Approved, ...).</summary>
public string StatusText { get; set; }
public bool CanUndo { get; set; }
/// <summary>Why the batch cannot be undone; empty when it can.</summary>
public string UndoBlockedReason { get; set; }
}
/// <summary>One employee of a batch, on the LFA Payment Undo page.</summary>
public class LFAPaymentBatchEmployee
{
public int LFAPaymentDetailID { get; set; }
public int EmployeeID { 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; }
}
/// <summary>What to undo: the whole batch (no DetailIDs) or only these employees of it.</summary>
public class LFAPaymentUndoRequest
{
public LFAPaymentUndoRequest()
{
DetailIDs = new List<int>();
}
public int LFAPaymentID { get; set; }
/// <summary>LFAPaymentDetailIDs of the employees to remove; empty = the whole batch.</summary>
public List<int> DetailIDs { get; set; }
}
public class LFAPaymentUndoResult
{
public bool Undone { get; set; }
public string Message { get; set; }
public int RemovedCount { get; set; }
/// <summary>True when the batch itself was deleted (whole batch, or its last employee).</summary>
public bool BatchRemoved { get; set; }
}
#endregion
}

View File

@ -66,6 +66,8 @@ namespace HRM.BO
public string DepartmentName { get; set; }
public DateTime JoiningDate { get; set; }
public DateTime? ConfirmationDate { get; set; }
/// <summary>Joining Date to Payment Date, e.g. "2 Years 9 Months 27 Days".</summary>
public string ServiceLength { get; set; }
public double JoiningBasic { get; set; }
public double? LastDecBasic { get; set; }
public double BasicSalary { get; set; }

View File

@ -35,6 +35,23 @@ namespace HRM.DA
#endregion
#region Update / Delete function
/// <summary>Stamps who changed the batch (some of its employees were undone).</summary>
internal static void UpdateModified(TransactionContext tc, int lfaPaymentID, int modifiedBy, DateTime modifiedDate)
{
tc.ExecuteNonQuery("UPDATE LFAPayment SET ModifiedBy=%n, ModifiedDate=%D WHERE LFAPaymentID=%n",
modifiedBy, modifiedDate, lfaPaymentID);
}
/// <summary>Deletes the batch header; its detail rows must be deleted first.</summary>
internal static void Delete(TransactionContext tc, int lfaPaymentID)
{
tc.ExecuteNonQuery("DELETE FROM LFAPayment WHERE LFAPaymentID=%n", lfaPaymentID);
}
#endregion
#region Get Function
internal static IDataReader Get(TransactionContext tc, int nID)
@ -42,6 +59,33 @@ namespace HRM.DA
return tc.ExecuteReader("SELECT * FROM LFAPayment WHERE LFAPaymentID=%n", nID);
}
/// <summary>
/// The batch, locked until the transaction ends: an approval or a second undo of the same batch
/// waits instead of running at the same time.
/// </summary>
internal static IDataReader GetForUpdate(TransactionContext tc, int nID)
{
return tc.ExecuteReader("SELECT * FROM LFAPayment WITH (UPDLOCK, ROWLOCK) WHERE LFAPaymentID=%n", nID);
}
/// <summary>LFA Payment Undo: every batch of the payroll type with its head count and total, newest first.</summary>
internal static IDataReader GetBatches(TransactionContext tc, int payrollTypeID)
{
return tc.ExecuteReader(
@"SELECT p.LFAPaymentID, p.BatchNumber, p.SalaryMonth, p.LFAYear, p.PaymentDate, p.Remarks, p.WFStatus,
p.IsTaxUpdated, p.CreationDate, ISNULL(u.UserName, u.LoginID) AS CreatedByName,
ISNULL(s.HeadCount, 0) AS HeadCount, ISNULL(s.PaidCount, 0) AS PaidCount,
ISNULL(s.TotalAmount, 0) AS TotalAmount
FROM LFAPayment p
LEFT JOIN (SELECT dt.LFAPaymentID, COUNT(*) AS HeadCount, SUM(dt.Amount) AS TotalAmount,
SUM(CASE WHEN dt.PaymentStatus = %n THEN 1 ELSE 0 END) AS PaidCount
FROM LFAPaymentDetail dt GROUP BY dt.LFAPaymentID) s ON s.LFAPaymentID = p.LFAPaymentID
LEFT JOIN Users u ON u.UserID = p.CreatedBy
WHERE p.PayrollTypeID=%n
ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC",
(int)EnumLFAPaymentStatus.Paid, payrollTypeID);
}
/// <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)
{
@ -86,7 +130,7 @@ namespace HRM.DA
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,
SELECT e.EMPLOYEEID, e.EMPLOYEENO, e.NAME, e.PAYROLLTYPEID, 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,
@ -95,7 +139,6 @@ namespace HRM.DA
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

View File

@ -94,6 +94,39 @@ namespace HRM.DA
return tc.ExecuteReader("SELECT * FROM LFAPaymentDetail WHERE LFAPaymentID=%n ORDER BY LFAPaymentDetailID", paymentID);
}
/// <summary>LFA Payment Undo: the employees of one batch.</summary>
internal static IDataReader GetBatchEmployees(TransactionContext tc, int paymentID)
{
return tc.ExecuteReader(
@"SELECT dt.LFAPaymentDetailID, dt.EmployeeID, e.EMPLOYEENO, e.NAME, ds.NAME AS DesignationName,
d.DESCRIPTION AS DepartmentName, dt.JoiningDate, dt.BasicSalary, dt.Amount, dt.PaymentStatus
FROM LFAPaymentDetail dt
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 dt.LFAPaymentID=%n
ORDER BY e.EMPLOYEENO",
paymentID);
}
#endregion
#region Delete function
/// <summary>Deletes every employee of the batch.</summary>
internal static void DeleteByPaymentID(TransactionContext tc, int paymentID)
{
tc.ExecuteNonQuery("DELETE FROM LFAPaymentDetail WHERE LFAPaymentID=%n", paymentID);
}
/// <summary>Deletes these employees of the batch (IDs the service has already checked).</summary>
internal static void Delete(TransactionContext tc, int paymentID, List<int> detailIDs)
{
// %q: a list of ints joined by this code, never user text
tc.ExecuteNonQuery("DELETE FROM LFAPaymentDetail WHERE LFAPaymentID=%n AND LFAPaymentDetailID IN (%q)",
paymentID, string.Join(",", detailIDs));
}
#endregion
}

View File

@ -21,16 +21,13 @@ namespace HRM.DA
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)
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.");
// another payroll type's employee is not shown: it reads as not found
problems.Add("Employee is not found.");
return problems;
}
if (employee.Status != EnumEmployeeStatus.Live)
@ -85,6 +82,33 @@ namespace HRM.DA
return detail;
}
/// <summary>
/// Completed service from the joining date to the date (the payment date), e.g. "2 Years 9 Months 27 Days".
/// </summary>
internal static string ServiceLength(DateTime joiningDate, DateTime asOf)
{
DateTime from = joiningDate.Date;
DateTime to = asOf.Date;
if (to <= from)
return "0 Days";
int totalMonths = (to.Year - from.Year) * 12 + to.Month - from.Month;
if (from.AddMonths(totalMonths) > to)
totalMonths--;
int days = (to - from.AddMonths(totalMonths)).Days;
int years = totalMonths / 12;
int months = totalMonths % 12;
List<string> parts = new List<string>();
if (years > 0)
parts.Add(years + (years == 1 ? " Year" : " Years"));
if (months > 0)
parts.Add(months + (months == 1 ? " Month" : " Months"));
if (days > 0 || parts.Count == 0)
parts.Add(days + (days == 1 ? " Day" : " Days"));
return string.Join(" ", parts);
}
/// <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)
{

View File

@ -80,7 +80,6 @@ namespace HRM.DA
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;
@ -118,6 +117,45 @@ namespace HRM.DA
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
@ -243,8 +281,7 @@ namespace HRM.DA
}
/// <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)
public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, int payrollTypeID)
{
LFAPaymentReadResult result = new LFAPaymentReadResult();
TransactionContext tc = null;
@ -254,8 +291,11 @@ namespace HRM.DA
List<LFAPaymentInput> rows = LFAPaymentWorkbook.Read(stream, fileName, fileLength, result);
tc = TransactionContext.Begin();
Calculate(tc, result, rows, paymentDate, payrollTypeID);
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)
{
@ -282,8 +322,12 @@ namespace HRM.DA
result.SalaryMonth = GetSalaryMonth(payrollTypeID);
tc = TransactionContext.Begin();
Calculate(tc, result, request.Rows, request.PaymentDate.Value, payrollTypeID);
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)
{
@ -300,15 +344,17 @@ namespace HRM.DA
}
/// <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.
/// 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<LFAPaymentDetail> Calculate(TransactionContext tc, LFAPaymentReadResult result, List<LFAPaymentInput> inputs, DateTime paymentDate, int payrollTypeID)
private List<KeyValuePair<LFAPaymentInput, LFAEmployee>> Validate(TransactionContext tc, LFAPaymentReadResult result, List<LFAPaymentInput> inputs, DateTime paymentDate, int payrollTypeID)
{
List<LFAPaymentDetail> details = new List<LFAPaymentDetail>();
if (inputs.Count == 0)
List<KeyValuePair<LFAPaymentInput, LFAEmployee>> valid = new List<KeyValuePair<LFAPaymentInput, LFAEmployee>>();
if (inputs == null || inputs.Count == 0)
{
return details;
return valid;
}
DateTime lfaYear = GetLFAYear(paymentDate);
@ -319,15 +365,13 @@ namespace HRM.DA
// 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));
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))
if (!employees.TryGetValue(key, out found) || (found.PayrollTypeID != payrollTypeID && employee.PayrollTypeID == payrollTypeID))
{
employees[key] = employee;
}
@ -343,43 +387,47 @@ namespace HRM.DA
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);
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))
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]) + ").");
}
if (problems.Count > 0)
foreach (string problem in problems)
{
foreach (string problem in problems)
{
result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem);
}
continue;
result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem);
}
LFAPaymentDetail detail = LFACalculator.Calculate(employee, lfaYear);
if (detail.Amount <= 0)
if (problems.Count == 0)
{
result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, "LFA amount is zero.");
continue;
valid.Add(new KeyValuePair<LFAPaymentInput, LFAEmployee>(input, employee));
}
details.Add(detail);
result.Rows.Add(ToRow(employee, input, detail, paymentDate));
}
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;
}
@ -414,6 +462,7 @@ namespace HRM.DA
DepartmentName = employee.DepartmentName,
JoiningDate = employee.JoiningDate,
ConfirmationDate = employee.ConfirmationDate,
ServiceLength = LFACalculator.ServiceLength(employee.JoiningDate, paymentDate),
JoiningBasic = employee.JoiningBasic,
LastDecBasic = detail.LastDecBasic,
BasicSalary = detail.BasicSalary,
@ -448,8 +497,11 @@ namespace HRM.DA
tc = TransactionContext.Begin(true);
int batchNo = LFAPaymentDA.GetLastBatchNoForUpdate(tc, payrollTypeID, prefix) + 1;
List<LFAPaymentDetail> details = Calculate(tc, validation, request.Rows, request.PaymentDate.Value,
payrollTypeID);
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)
{
@ -513,6 +565,206 @@ namespace HRM.DA
#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)

View File

@ -22,6 +22,7 @@ export class LFAPaymentRow extends LFAPaymentInput {
departmentName: string;
joiningDate: Date;
confirmationDate: Date;
serviceLength: string; // Joining Date to Payment Date
joiningBasic: number;
lastDecBasic: number;
basicSalary: number;
@ -79,3 +80,54 @@ export class LFAPaymentHistory {
// filled on the page
statusText: string;
}
// ── LFA Payment Undo ──
/** One batch of the LFA Payment Undo page. */
export class LFAPaymentBatch {
lfaPaymentID: number;
batchNumber: string;
salaryMonth: Date;
lfaYear: Date;
paymentDate: Date;
remarks: string;
wfStatus: number;
isTaxUpdated: boolean;
headCount: number;
paidCount: number;
totalAmount: number;
createdByName: string;
creationDate: Date;
statusText: string;
canUndo: boolean;
undoBlockedReason: string;
}
/** One employee of a batch. */
export class LFAPaymentBatchEmployee {
lfaPaymentDetailID: number;
employeeID: number;
employeeNo: string;
name: string;
designationName: string;
departmentName: string;
joiningDate: Date;
basicSalary: number;
amount: number;
paymentStatus: EnumLFAPaymentStatus;
// filled on the page
statusText: string;
}
/** detailIDs empty = the whole batch. */
export class LFAPaymentUndoRequest {
lfaPaymentID: number;
detailIDs: number[];
}
export class LFAPaymentUndoResult {
undone: boolean;
message: string;
removedCount: number;
batchRemoved: boolean;
}

View File

@ -2,7 +2,8 @@ import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '../../app.api.service';
import {
LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest
LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult,
LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentUndoRequest, LFAPaymentUndoResult
} from '../../_models/Payroll/lfaPayment';
@Injectable({
@ -43,4 +44,19 @@ export class LFAService {
getPaymentHistory(fromDate: string, toDate: string): Observable<LFAPaymentHistory[]> {
return this.apiService.httpGet<LFAPaymentHistory[]>('/lfa/getPaymentHistory/' + fromDate + '/' + toDate);
}
// ── LFA Payment Undo ──
getUndoBatches(): Observable<LFAPaymentBatch[]> {
return this.apiService.httpGet<LFAPaymentBatch[]>('/lfa/getUndoBatches');
}
getBatchEmployees(lfaPaymentID: number): Observable<LFAPaymentBatchEmployee[]> {
return this.apiService.httpGet<LFAPaymentBatchEmployee[]>('/lfa/getBatchEmployees/' + lfaPaymentID);
}
/** The whole batch (no detailIDs) or the selected employees of it. The server checks everything again. */
undoPayment(request: LFAPaymentUndoRequest): Observable<LFAPaymentUndoResult> {
return this.apiService.httpPost<LFAPaymentUndoResult>('/lfa/undoPayment', request);
}
}

View File

@ -1,8 +1,99 @@
<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 Undo</kendo-card-header>
<kendo-card-body>
</kendo-card-body>
</kendo-card>
<div class="lfa-undo">
<!-- ================= Batches ================= -->
<div class="lfa-undo__head">
<span class="lfa-undo__title">LFA Batches</span>
<span class="lfa-undo__hint">A batch can be undone until it is submitted for approval. Undone employees can be paid again in a new batch.</span>
<span class="lfa-undo__spacer"></span>
<button class="gh-refresh" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['redo']" [disabled]="isBusy" (click)="loadBatches(selectedBatch ? selectedBatch.lfaPaymentID : 0)">Refresh</button>
</div>
<kendo-grid [kendoGridBinding]="batches" [sortable]="true" [resizable]="true" [pageable]="true" [pageSize]="10">
<kendo-grid-column field="batchNumber" title="Batch ID" [width]="140" [style]="{ 'font-weight': '600' }"></kendo-grid-column>
<kendo-grid-column field="paymentDate" title="Payment Date" [width]="125" format="dd-MMM-yyyy"></kendo-grid-column>
<kendo-grid-column field="lfaYear" title="LFA Year" [width]="95">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.lfaYear | date: 'yyyy' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="headCount" title="Employees" [width]="105" [style]="{ 'text-align': 'right' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }"></kendo-grid-column>
<kendo-grid-column field="totalAmount" title="Total LFA Amount" [width]="150" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }"></kendo-grid-column>
<kendo-grid-column field="statusText" title="Status" [width]="140">
<ng-template kendoGridCellTemplate let-dataItem>
<span class="lfa-badge" [class.lfa-badge--ok]="dataItem.canUndo" [title]="dataItem.undoBlockedReason || ''">{{ dataItem.statusText }}</span>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="remarks" title="Remarks" [width]="200" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
<kendo-grid-column field="createdByName" title="Processed By" [width]="140"></kendo-grid-column>
<kendo-grid-column field="creationDate" title="Processed On" [width]="160" format="dd-MMM-yyyy hh:mm a"></kendo-grid-column>
<kendo-grid-command-column title="Action" [width]="200">
<ng-template kendoGridCellTemplate let-dataItem>
<button kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['eye']" [disabled]="isBusy"
[class.lfa-selected]="selectedBatch && selectedBatch.lfaPaymentID === dataItem.lfaPaymentID" (click)="viewBatch(dataItem)">View</button>
<button kendoButton type="button" class="kt-delete" [svgIcon]="apiService.KendoSVGIcon['undo']" [disabled]="isBusy || !dataItem.canUndo"
[title]="dataItem.canUndo ? 'Undo the whole batch' : dataItem.undoBlockedReason" (click)="confirmUndoBatch(dataItem)">Undo</button>
</ng-template>
</kendo-grid-command-column>
<ng-template kendoGridNoRecordsTemplate>No LFA batch found.</ng-template>
</kendo-grid>
<!-- ================= Employees of the selected batch ================= -->
@if (selectedBatch) {
<div class="lfa-undo__head">
<span class="lfa-undo__title">Batch {{ selectedBatch.batchNumber }}</span>
<span class="lfa-undo__hint">
Payment Date {{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }} · {{ employees.length }} employee(s) ·
<b>{{ selectedDetailIDs.length }}</b> ticked ({{ selectedAmount | number: '1.2-2' }})
</span>
<span class="lfa-undo__spacer"></span>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="employees.length === 0" (click)="employeeGrid.saveAsExcel()">Export</button>
<button class="gh-cancel" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['cancel']" (click)="clearBatch()">Close</button>
<button class="kt-delete" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['undo']"
[disabled]="isBusy || !selectedBatch.canUndo || selectedDetailIDs.length === 0" (click)="confirmUndoEmployees()">Undo Selected Employees</button>
</div>
@if (!selectedBatch.canUndo) {
<div class="lfa-undo__blocked">This batch cannot be undone: {{ selectedBatch.undoBlockedReason }}</div>
}
<kendo-grid #employeeGrid="kendoGrid" [kendoGridBinding]="employees" [sortable]="true" [resizable]="true"
scrollable="virtual" [rowHeight]="40" [pageSize]="50" [height]="420"
[selectable]="{ checkboxOnly: true, mode: 'multiple', enabled: selectedBatch.canUndo }"
kendoGridSelectBy="lfaPaymentDetailID" [(selectedKeys)]="selectedDetailIDs">
<kendo-grid-checkbox-column [width]="45" [showSelectAll]="selectedBatch.canUndo && employees.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]="210" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
<kendo-grid-column field="designationName" title="Designation" [width]="180" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
<kendo-grid-column field="departmentName" title="Department" [width]="180" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }"></kendo-grid-column>
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="125" format="dd-MMM-yyyy"></kendo-grid-column>
<kendo-grid-column field="basicSalary" title="Basic Salary" [width]="135" format="n2" [style]="{ 'text-align': 'right' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }"></kendo-grid-column>
<kendo-grid-column field="amount" title="LFA Amount" [width]="135" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }"></kendo-grid-column>
<kendo-grid-column field="statusText" title="Payment Status" [width]="130"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>No employee in this batch.</ng-template>
<kendo-grid-excel fileName="LFA-Batch-Employees.xlsx" [fetchData]="allEmployees"></kendo-grid-excel>
</kendo-grid>
}
</div>
@if (showConfirm && confirmBatch) {
<div class="blur-background">
<kendo-dialog title="Confirm LFA Payment Undo" [width]="480" maxHeight="90vh" (close)="showConfirm = false" (keydown.escape)="$event.stopPropagation()">
@if (confirmWholeBatch) {
<p>The whole batch <b>{{ confirmBatch.batchNumber }}</b> will be deleted. This cannot be reversed.</p>
} @else {
<p><b>{{ confirmCount }}</b> employee(s) will be removed from batch <b>{{ confirmBatch.batchNumber }}</b>. This cannot be reversed.</p>
}
<table class="lfa-confirm">
<tbody>
<tr><td>Batch ID</td><td>{{ confirmBatch.batchNumber }}</td></tr>
<tr><td>Payment Date</td><td>{{ confirmBatch.paymentDate | date: 'dd-MMM-yyyy' }}</td></tr>
<tr><td>Employees</td><td>{{ confirmCount }}</td></tr>
<tr><td>LFA Amount</td><td>BDT {{ confirmAmount | 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="kt-delete" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['check']" [disabled]="isBusy" (click)="undo()">Confirm &amp; Undo</button>
</kendo-dialog-actions>
</kendo-dialog>
</div>
}

View File

@ -0,0 +1,70 @@
/* LFA Payment Undo: layout only; colours are the theme's --gh-* variables */
.lfa-undo {
display: flex;
flex-direction: column;
gap: 12px;
padding: 8px 4px;
}
.lfa-undo__head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.lfa-undo__title {
font-size: 16px;
font-weight: 700;
color: var(--gh-lk);
}
.lfa-undo__hint {
font-size: 12px;
color: var(--gh-muted);
}
.lfa-undo__spacer {
flex: 1 1 auto;
}
.lfa-undo__blocked {
padding: 8px 12px;
border-radius: 6px;
font-weight: 600;
color: var(--gh-dn);
background: color-mix(in srgb, var(--gh-dn) 10%, transparent);
}
.lfa-selected {
border-color: var(--gh-lk);
color: var(--gh-lk);
}
.lfa-badge {
display: inline-block;
padding: 2px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
color: var(--gh-dn);
background: color-mix(in srgb, var(--gh-dn) 12%, transparent);
}
.lfa-badge--ok {
color: var(--gh-warn);
background: color-mix(in srgb, var(--gh-warn) 15%, transparent);
}
.lfa-confirm {
width: 100%;
td {
padding: 4px 0;
}
td:last-child {
text-align: right;
font-weight: 600;
}
}

View File

@ -1,6 +1,17 @@
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ExcelExportData } from '@progress/kendo-angular-excel-export';
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, LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentUndoRequest, LFAPaymentUndoResult
} from '../../_models/Payroll/lfaPayment';
/**
* LFA Payment Undo: the payroll type's LFA batches. A batch can be undone whole, or only some of its
* employees, until it is submitted for approval (as Salary Undo). The server checks everything again.
*/
@Component({
selector: 'app-lfa-payment-undo',
templateUrl: './lfa-payment-undo.component.html',
@ -10,10 +21,185 @@ import { ApiService } from '../../app.api.service';
})
export class LfaPaymentUndoComponent implements OnInit {
constructor(public apiService: ApiService) {
batches: LFAPaymentBatch[] = [];
selectedBatch: LFAPaymentBatch = null;
employees: LFAPaymentBatchEmployee[] = [];
selectedDetailIDs: number[] = [];
isBusy = false;
// confirm dialog: the whole batch, or the selected employees
showConfirm = false;
confirmWholeBatch = true;
confirmBatch: LFAPaymentBatch = null;
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
public loadingPanel: loadingPanelService,
private lfaService: LFAService) {
this.apiService.selectedMenuName = 'LFA Payment Undo';
}
ngOnInit() {
this.loadBatches();
}
// ── Batches ─────────────────────────────────────────────────────
loadBatches(keepBatchID: number = 0) {
this.start();
this.lfaService.getUndoBatches().subscribe({
next: (resp) => {
this.stop();
this.batches = (resp || []).map(x => ({
...x,
paymentDate: this.toDate(x.paymentDate),
lfaYear: this.toDate(x.lfaYear),
creationDate: this.toDate(x.creationDate)
}));
const keep = keepBatchID ? this.batches.find(x => x.lfaPaymentID === keepBatchID) : null;
if (keep) {
this.viewBatch(keep);
} else {
this.clearBatch();
}
},
error: (err) => this.fail(err, 'Could not load the LFA batches.')
});
}
viewBatch(batch: LFAPaymentBatch) {
this.selectedBatch = batch;
this.selectedDetailIDs = [];
this.employees = [];
this.start();
this.lfaService.getBatchEmployees(batch.lfaPaymentID).subscribe({
next: (resp) => {
this.stop();
this.employees = (resp || []).map(x => ({
...x,
joiningDate: this.toDate(x.joiningDate),
statusText: this.paymentStatusText(x.paymentStatus)
}));
},
error: (err) => this.fail(err, 'Could not load the employees of the batch.')
});
}
clearBatch() {
this.selectedBatch = null;
this.employees = [];
this.selectedDetailIDs = [];
}
// ── Undo ────────────────────────────────────────────────────────
/** Undo the whole batch (from the batch grid). */
confirmUndoBatch(batch: LFAPaymentBatch) {
if (!batch.canUndo) {
this.notificationService.showWarning(batch.undoBlockedReason, 'Cannot undo');
return;
}
this.confirmBatch = batch;
this.confirmWholeBatch = true;
this.showConfirm = true;
}
/** Undo only the ticked employees of the selected batch. */
confirmUndoEmployees() {
if (!this.selectedBatch) {
return;
}
if (!this.selectedBatch.canUndo) {
this.notificationService.showWarning(this.selectedBatch.undoBlockedReason, 'Cannot undo');
return;
}
if (this.selectedDetailIDs.length === 0) {
this.notificationService.showWarning('Please tick at least one employee.');
return;
}
this.confirmBatch = this.selectedBatch;
// every employee ticked is the same as the whole batch
this.confirmWholeBatch = this.selectedDetailIDs.length === this.employees.length;
this.showConfirm = true;
}
get confirmCount(): number {
return this.confirmWholeBatch ? (this.confirmBatch ? this.confirmBatch.headCount : 0) : this.selectedDetailIDs.length;
}
get confirmAmount(): number {
if (this.confirmWholeBatch) {
return this.confirmBatch ? this.confirmBatch.totalAmount : 0;
}
return this.sum(this.employees.filter(x => this.selectedDetailIDs.indexOf(x.lfaPaymentDetailID) >= 0), x => x.amount);
}
get selectedAmount(): number {
return this.sum(this.employees.filter(x => this.selectedDetailIDs.indexOf(x.lfaPaymentDetailID) >= 0), x => x.amount);
}
undo() {
if (this.isBusy || !this.confirmBatch) {
return;
}
const batch = this.confirmBatch;
const request: LFAPaymentUndoRequest = {
lfaPaymentID: batch.lfaPaymentID,
detailIDs: this.confirmWholeBatch ? [] : [...this.selectedDetailIDs]
};
this.start();
this.lfaService.undoPayment(request).subscribe({
next: (resp: LFAPaymentUndoResult) => {
this.stop();
this.showConfirm = false;
if (!resp.undone) {
this.notificationService.showError(resp.message);
this.loadBatches(batch.lfaPaymentID); // the batch may have changed meanwhile
return;
}
this.notificationService.showSuccess(resp.message);
this.loadBatches(resp.batchRemoved ? 0 : batch.lfaPaymentID);
},
error: (err) => {
this.showConfirm = false;
this.fail(err, 'Nothing was undone. Please try again.');
}
});
}
allEmployees = (): ExcelExportData => ({ data: this.employees });
// ── Helpers ─────────────────────────────────────────────────────
private paymentStatusText(status: EnumLFAPaymentStatus): string {
switch (status) {
case EnumLFAPaymentStatus.Paid: return 'Paid';
case EnumLFAPaymentStatus.Failed: return 'Failed';
default: return 'Pending';
}
}
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();
const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : '';
this.notificationService.showError(text || fallback);
}
private toDate(value: any): Date {
return value ? new Date(value) : null;
}
private sum<T>(items: T[], value: (item: T) => number): number {
return Math.round(items.reduce((total, x) => total + (value(x) || 0), 0) * 100) / 100;
}
}

View File

@ -100,6 +100,7 @@
<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="serviceLength" title="Service Length" [width]="190" [sortable]="false"></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>
@ -117,7 +118,7 @@
@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>
<span>{{ issues.length }} error(s) found. Nothing was calculated: correct every error in the file and upload it again.</span>
<button class="gh-view" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['eye']" (click)="showIssues = true">View Errors</button>
</div>
}

View File

@ -181,10 +181,9 @@ export class LfaPaymentComponent implements OnInit {
}
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.');
// all or nothing: one error anywhere in the file and nothing is calculated
if (this.issues.length > 0) {
this.notificationService.showError('Nothing was calculated. Please correct every error in the file and upload it again.');
} else {
this.notificationService.showSuccess(this.rows.length + ' employee(s) loaded.');
}

View File

@ -96,6 +96,64 @@ namespace HRM.UI.Controllers.Payroll
}
}
// ── LFA Payment Undo ──
/// <summary>Every batch of the current payroll type, and whether each one can be undone.</summary>
[HttpGet("getUndoBatches")]
public ActionResult GetUndoBatches()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetUndoBatches(currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet("getBatchEmployees/{lfaPaymentID}")]
public ActionResult GetBatchEmployees(int lfaPaymentID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetBatchEmployees(lfaPaymentID, currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>Undoes the whole batch or the selected employees of it; the server checks everything again.</summary>
[HttpPost("undoPayment")]
public ActionResult UndoPayment(LFAPaymentUndoRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.Undo(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
private ActionResult NotAllowed()
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment.");