LFA Payment Approval

This commit is contained in:
Mohaimen Hasan 2026-11-26 18:54:00 +06:00
parent 0f5b150e98
commit c57a15e87d
17 changed files with 1790 additions and 20 deletions

View File

@ -19,7 +19,7 @@ namespace HRM.BO
#region LFAPayment
/// <summary>One Leave Fare Assistance payment batch (dbo.LFAPayment), as SalaryProcess is for the salary.</summary>
public class LFAPayment : AuditTrailBase
public class LFAPayment : AuditTrailBase, IworkflowInterface
{
public LFAPayment()
{
@ -47,6 +47,26 @@ namespace HRM.BO
public DateTime? ApprovedDate { get; set; }
public List<LFAPaymentDetail> Details { get; set; }
#region IworkflowInterface Members
public string ObjectDescription
{
get { return "LFA payment batch " + BatchNumber; }
}
/// <summary>The workflow type (WFTYPE 33), as SalaryProcess returns 30.</summary>
public int SetupID
{
get { return LFAPaymentApproval.WFTypeID; }
}
public int ObjectID
{
get { return this.ID; }
}
#endregion
}
#endregion
@ -151,6 +171,16 @@ namespace HRM.BO
List<LFAPaymentBatch> GetUndoBatches(int payrollTypeID);
List<LFAPaymentBatchEmployee> GetBatchEmployees(int lfaPaymentID, int payrollTypeID);
LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID);
// LFA Payment Approval (as Salary Approval)
LFAApprovalInfo GetApprovalInfo(int? employeeID);
List<LFAPaymentBatch> GetApprovalBatches(int payrollTypeID);
List<WFFlowHistory> GetFlowHistory(int lfaPaymentID, int payrollTypeID);
LFAApprovalResult ApproveDirect(LFAApprovalRequest request, int payrollTypeID, int userID);
LFAApprovalResult SubmitForApproval(LFAApprovalRequest request, int payrollTypeID, int? employeeID, int userID);
LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID);
LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID);
LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID);
}
#endregion

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
namespace HRM.BO
{
#region LFA Payment Approval (not tables)
/// <summary>
/// LFA Payment Approval works exactly as Salary Approval: the Logic key lfaapproval/workflow decides
/// between Direct Approve ("No") and the approval workflow ("Yes"), whose approvers are set up for
/// WFTYPE 33 in Work Flow Setup and act from the Payment Approval page (/payment-approval/lfa).
/// </summary>
public static class LFAPaymentApproval
{
/// <summary>WFTYPE.WFTYPEID of LFA Payment (Salary 30, Bonus 31, Leave Encashment 32).</summary>
public const int WFTypeID = 33;
/// <summary>Logic configuration: lfaapproval / workflow = Yes | No.</summary>
public const string LogicParent = "lfaapproval";
public const string LogicChild = "workflow";
}
/// <summary>What the LFA Payment Approval page needs to know before it shows its buttons.</summary>
public class LFAApprovalInfo
{
/// <summary>lfaapproval/workflow = Yes: batches go through the approval workflow.</summary>
public bool IsWorkflowRequired { get; set; }
/// <summary>The login is linked with an employee (the workflow needs an initiator employee).</summary>
public bool HasEmployee { get; set; }
/// <summary>At least one approval rule is set up for LFA Payment in Work Flow Setup.</summary>
public bool HasWorkflowSetup { get; set; }
}
/// <summary>Approve (Direct) or Submit for approval one batch.</summary>
public class LFAApprovalRequest
{
public int LFAPaymentID { get; set; }
public string Remarks { get; set; }
}
/// <summary>An approver approves or reverts the workflow step (WFMovementTran) they received.</summary>
public class LFAApproverActionRequest
{
public int WFMovementTranID { get; set; }
public string Remarks { get; set; }
}
public class LFAApprovalResult
{
public bool Done { get; set; }
public string Message { get; set; }
/// <summary>True when the batch is now fully approved.</summary>
public bool Approved { get; set; }
}
/// <summary>The batch an approver opened from the Payment Approval page.</summary>
public class LFAApproverBatch
{
public LFAApproverBatch()
{
Employees = new List<LFAPaymentBatchEmployee>();
}
public LFAPaymentBatch Batch { get; set; }
public List<LFAPaymentBatchEmployee> Employees { get; set; }
/// <summary>The login is a pending approver of this step and may Approve or Revert it.</summary>
public bool CanAct { get; set; }
/// <summary>Why the login cannot act (already acted, not their step, batch undone ...).</summary>
public string Message { get; set; }
}
#endregion
}

View File

@ -21,6 +21,16 @@ namespace HRM.BO
public double TotalAmount { get; set; }
public string CreatedByName { get; set; }
public DateTime CreationDate { get; set; }
public string ApprovedByName { get; set; }
public DateTime? ApprovedDate { get; set; }
// approval workflow (WFTYPE 33): the latest step of the batch, if it was ever submitted
public int? WFMovementTranID { get; set; }
public int? UniqueNumber { get; set; }
/// <summary>The batch is back with the person who submitted it (an approver reverted it to them).</summary>
public bool IsAtInitiator { get; set; }
/// <summary>Who has to act now, e.g. "Md. Karim [D1004]".</summary>
public string PendingWith { get; set; }
/// <summary>Approval state in words (Not Submitted, Pending Approval, Approved, ...).</summary>
public string StatusText { get; set; }

View File

@ -44,6 +44,34 @@ namespace HRM.DA
modifiedBy, modifiedDate, lfaPaymentID);
}
/// <summary>Sets the batch's approval status (Not_yet_Initiated while it is in the workflow), as SalaryProcess.WFStatus.</summary>
internal static void UpdateWFStatus(TransactionContext tc, int lfaPaymentID, enumwfStatus? wfStatus)
{
tc.ExecuteNonQuery("UPDATE LFAPayment SET WFStatus=%n WHERE LFAPaymentID=%n", (int?)wfStatus, lfaPaymentID);
}
/// <summary>The batch is approved: Direct Approve, or the last approver of the workflow.</summary>
internal static void Approve(TransactionContext tc, int lfaPaymentID, int approvedBy, DateTime approvedDate)
{
tc.ExecuteNonQuery("UPDATE LFAPayment SET WFStatus=%n, ApprovedBy=%n, ApprovedDate=%D WHERE LFAPaymentID=%n",
(int)enumwfStatus.Approve, approvedBy, approvedDate, lfaPaymentID);
}
/// <summary>
/// Deletes the approval workflow of an undone batch (WFTYPE 33 steps, their approvers and notifications).
/// Batch IDs are reused (MAX + 1), so an old workflow must never stay behind for a new batch to inherit.
/// </summary>
internal static void DeleteWorkflow(TransactionContext tc, int lfaPaymentID)
{
const string trans = "SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE WFTYPEID=%n AND OBJECTID=%n";
tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTTASK WHERE WFMOVEMENTTRANID IN (" + trans + ")",
LFAPaymentApproval.WFTypeID, lfaPaymentID);
tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTNEXT WHERE WFMOVEMENTTRANID IN (" + trans + ")",
LFAPaymentApproval.WFTypeID, lfaPaymentID);
tc.ExecuteNonQuery("DELETE FROM WFMOVEMENTTRAN WHERE WFTYPEID=%n AND OBJECTID=%n",
LFAPaymentApproval.WFTypeID, lfaPaymentID);
}
/// <summary>Deletes the batch header; its detail rows must be deleted first.</summary>
internal static void Delete(TransactionContext tc, int lfaPaymentID)
{
@ -68,22 +96,76 @@ namespace HRM.DA
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>
/// <summary>
/// LFA Payment Undo and Approval: every batch of the payroll type with its head count, total and approval
/// workflow state (latest step, who has it now, whether it is back with the initiator), 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,
p.ApprovedDate, ISNULL(ua.UserName, ua.LoginID) AS ApprovedByName,
ISNULL(s.HeadCount, 0) AS HeadCount, ISNULL(s.PaidCount, 0) AS PaidCount,
ISNULL(s.TotalAmount, 0) AS TotalAmount
ISNULL(s.TotalAmount, 0) AS TotalAmount,
lt.WFMOVEMENTTRANID AS WFMovementTranID, lt.UNIQUENUMBER AS UniqueNumber,
CASE WHEN EXISTS (SELECT 1 FROM WFMOVEMENTNEXT n
WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n
AND n.EMPLOYEEID = it.InitiatorEmpID) THEN 1 ELSE 0 END AS IsAtInitiator,
STUFF((SELECT ', ' + e.NAME + ' [' + e.EMPLOYEENO + ']'
FROM WFMOVEMENTNEXT n INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = n.EMPLOYEEID
WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS PendingWith
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
LEFT JOIN Users ua ON ua.UserID = p.ApprovedBy
OUTER APPLY (SELECT TOP 1 t.WFMOVEMENTTRANID, t.UNIQUENUMBER FROM WFMOVEMENTTRAN t
WHERE t.WFTYPEID = %n AND t.OBJECTID = p.LFAPaymentID
ORDER BY t.WFMOVEMENTTRANID DESC) lt
OUTER APPLY (SELECT TOP 1 f.FROMEMPLOYEEID AS InitiatorEmpID FROM WFMOVEMENTTRAN f
WHERE f.UNIQUENUMBER = lt.UNIQUENUMBER ORDER BY f.WFMOVEMENTTRANID) it
WHERE p.PayrollTypeID=%n
ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC",
(int)EnumLFAPaymentStatus.Paid, payrollTypeID);
(int)EnumwfStatus.Received, (int)EnumwfStatus.Received, (int)EnumLFAPaymentStatus.Paid,
LFAPaymentApproval.WFTypeID, payrollTypeID);
}
/// <summary>
/// The approval workflow state of one batch: its latest step (WFMovementTranID, UniqueNumber), the
/// employee who submitted it (InitiatorEmpID) and whether it is back with them now (IsAtInitiator).
/// No row when the batch was never submitted.
/// </summary>
internal static IDataReader GetWorkflowState(TransactionContext tc, int lfaPaymentID)
{
return tc.ExecuteReader(
@"SELECT lt.WFMOVEMENTTRANID AS WFMovementTranID, lt.UNIQUENUMBER AS UniqueNumber, it.InitiatorEmpID,
CASE WHEN EXISTS (SELECT 1 FROM WFMOVEMENTNEXT n
WHERE n.WFMOVEMENTTRANID = lt.WFMOVEMENTTRANID AND n.STATUS = %n
AND n.EMPLOYEEID = it.InitiatorEmpID) THEN 1 ELSE 0 END AS IsAtInitiator
FROM (SELECT TOP 1 t.WFMOVEMENTTRANID, t.UNIQUENUMBER FROM WFMOVEMENTTRAN t
WHERE t.WFTYPEID = %n AND t.OBJECTID = %n ORDER BY t.WFMOVEMENTTRANID DESC) lt
OUTER APPLY (SELECT TOP 1 f.FROMEMPLOYEEID AS InitiatorEmpID FROM WFMOVEMENTTRAN f
WHERE f.UNIQUENUMBER = lt.UNIQUENUMBER ORDER BY f.WFMOVEMENTTRANID) it",
(int)EnumwfStatus.Received, LFAPaymentApproval.WFTypeID, lfaPaymentID);
}
/// <summary>
/// True when the employee is a pending approver of this step and the step is still the latest one of
/// its workflow (an approver who already acted, or a step that moved on, cannot act again).
/// </summary>
internal static bool IsPendingApprover(TransactionContext tc, int wfMovementTranID, int employeeID)
{
object found = tc.ExecuteScalar(
@"SELECT COUNT(*) FROM WFMOVEMENTTRAN t
INNER JOIN WFMOVEMENTNEXT n ON n.WFMOVEMENTTRANID = t.WFMOVEMENTTRANID
WHERE t.WFMOVEMENTTRANID = %n AND t.WFTYPEID = %n AND n.EMPLOYEEID = %n AND n.STATUS = %n
AND t.WFMOVEMENTTRANID = (SELECT MAX(x.WFMOVEMENTTRANID) FROM WFMOVEMENTTRAN x
WHERE x.UNIQUENUMBER = t.UNIQUENUMBER)",
wfMovementTranID, LFAPaymentApproval.WFTypeID, employeeID, (int)EnumwfStatus.Received);
return found != null && found != DBNull.Value && Convert.ToInt32(found) > 0;
}
/// <summary>The highest running number of the batches that start with this prefix; 0 = none yet.</summary>

View File

@ -548,6 +548,7 @@ Union
WHEN WT.wftypeid =30 THEN '/payment-approval/salary'
WHEN WT.wftypeid =31 THEN '/payment-approval/bonus'
WHEN WT.wftypeid =32 THEN '/payment-approval/leaveencashment'
WHEN WT.wftypeid =33 THEN '/payment-approval/lfa'
ELSE 'none' END AS link,0 count FROM WFMovementTran WT, WFMovementNext WN
WHERE WN.Status = 1 AND WN.EmployeeId = %n AND WT.wftypeid <> 4
AND WT.WFMovementTranID = WN.WFMovementTranID

View File

@ -133,9 +133,15 @@ namespace HRM.DA
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.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.PaidCount);
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;
}
@ -569,6 +575,11 @@ namespace HRM.DA
/// <summary>LFA Payment Undo: every batch of the payroll type, and whether each one can be undone.</summary>
public List<LFAPaymentBatch> GetUndoBatches(int payrollTypeID)
{
return GetBatches(payrollTypeID);
}
private List<LFAPaymentBatch> GetBatches(int payrollTypeID)
{
List<LFAPaymentBatch> items = new List<LFAPaymentBatch>();
TransactionContext tc = null;
@ -683,8 +694,9 @@ namespace HRM.DA
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();
bool isAtInitiator = GetIsAtInitiator(tc, oPayment.ID);
string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated,
selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid));
selected.Count(x => x.PaymentStatus == EnumLFAPaymentStatus.Paid), isAtInitiator);
if (blocked != null)
{
result.Message = blocked;
@ -699,6 +711,7 @@ namespace HRM.DA
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)).";
@ -729,15 +742,15 @@ namespace HRM.DA
}
/// <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.
/// 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.
/// </summary>
private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, int paidCount)
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)
&& 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.";
@ -746,10 +759,12 @@ namespace HRM.DA
return null;
}
private static string StatusText(enumwfStatus? wfStatus)
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:
@ -765,6 +780,498 @@ namespace HRM.DA
#endregion
#region Approval
/// <summary>Logic key, the login's employee and the Work Flow Setup of LFA Payment.</summary>
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;
}
/// <summary>LFA Payment Approval: every batch of the payroll type with its approval state.</summary>
public List<LFAPaymentBatch> GetApprovalBatches(int payrollTypeID)
{
return GetBatches(payrollTypeID);
}
/// <summary>Every approval step of the batch, as Salary Approve shows its flow history.</summary>
public List<WFFlowHistory> GetFlowHistory(int lfaPaymentID, int payrollTypeID)
{
LFAPayment oPayment = this.Get(lfaPaymentID);
if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID)
return new List<WFFlowHistory>();
return new WFMovementTranService().GetFlowHistoriesByObjectID(lfaPaymentID, LFAPaymentApproval.WFTypeID, null)
?? new List<WFFlowHistory>();
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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<IworkflowInterface>(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<IworkflowInterface>().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;
}
/// <summary>The batch an approver opened from the Payment Approval page, and whether they may act on it.</summary>
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<LFAPayment>(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;
}
/// <summary>
/// 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.
/// </summary>
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<IworkflowInterface>().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;
}
/// <summary>An approver reverts their step to the previous one (or to the initiator), as Salary's revert.</summary>
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<IworkflowInterface>().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;
}
/// <summary>lfaapproval/workflow = Yes.</summary>
private static bool IsWorkflowRequired()
{
return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic,
LFAPaymentApproval.LogicParent, LFAPaymentApproval.LogicChild);
}
/// <summary>The batch of the payroll type, locked until the transaction ends; null when not found.</summary>
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<LFAPayment>(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;
}
/// <summary>
/// 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.
/// </summary>
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<LFAPayment>(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;
}
/// <summary>
/// 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.
/// </summary>
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)

View File

@ -98,6 +98,13 @@ export class LFAPaymentBatch {
totalAmount: number;
createdByName: string;
creationDate: Date;
approvedByName: string;
approvedDate: Date;
// approval workflow (WFTYPE 33)
wfMovementTranID: number;
uniqueNumber: number;
isAtInitiator: boolean;
pendingWith: string;
statusText: string;
canUndo: boolean;
undoBlockedReason: string;
@ -131,3 +138,35 @@ export class LFAPaymentUndoResult {
removedCount: number;
batchRemoved: boolean;
}
// ── LFA Payment Approval (as Salary Approve) ──
export class LFAApprovalInfo {
/** Logic lfaapproval/workflow = Yes */
isWorkflowRequired: boolean;
hasEmployee: boolean;
hasWorkflowSetup: boolean;
}
export class LFAApprovalRequest {
lfaPaymentID: number;
remarks: string;
}
export class LFAApproverActionRequest {
wfMovementTranID: number;
remarks: string;
}
export class LFAApprovalResult {
done: boolean;
message: string;
approved: boolean;
}
export class LFAApproverBatch {
batch: LFAPaymentBatch;
employees: LFAPaymentBatchEmployee[];
canAct: boolean;
message: string;
}

View File

@ -2,9 +2,11 @@ import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '../../app.api.service';
import {
LFAApprovalInfo, LFAApprovalRequest, LFAApprovalResult, LFAApproverActionRequest, LFAApproverBatch,
LFAPaymentBatch, LFAPaymentBatchEmployee, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentProcessResult,
LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentUndoRequest, LFAPaymentUndoResult
} from '../../_models/Payroll/lfaPayment';
import { WFFlowHistory } from '../../_models/Work-Flow/wFMovementNext';
@Injectable({
providedIn: 'root'
@ -59,4 +61,42 @@ export class LFAService {
undoPayment(request: LFAPaymentUndoRequest): Observable<LFAPaymentUndoResult> {
return this.apiService.httpPost<LFAPaymentUndoResult>('/lfa/undoPayment', request);
}
// ── LFA Payment Approval (as Salary Approve) ──
getApprovalInfo(): Observable<LFAApprovalInfo> {
return this.apiService.httpGet<LFAApprovalInfo>('/lfa/getApprovalInfo');
}
getApprovalBatches(): Observable<LFAPaymentBatch[]> {
return this.apiService.httpGet<LFAPaymentBatch[]>('/lfa/getApprovalBatches');
}
getFlowHistory(lfaPaymentID: number): Observable<WFFlowHistory[]> {
return this.apiService.httpGet<WFFlowHistory[]>('/lfa/getFlowHistory/' + lfaPaymentID);
}
/** Workflow off: approve at once. */
approveDirect(request: LFAApprovalRequest): Observable<LFAApprovalResult> {
return this.apiService.httpPost<LFAApprovalResult>('/lfa/approveDirect', request);
}
/** Workflow on: submit (or submit again after a revert). */
submitForApproval(request: LFAApprovalRequest): Observable<LFAApprovalResult> {
return this.apiService.httpPost<LFAApprovalResult>('/lfa/submitForApproval', request);
}
// the approver's side (/payment-approval/lfa)
getApproverBatch(wfMovementTranID: number): Observable<LFAApproverBatch> {
return this.apiService.httpGet<LFAApproverBatch>('/lfa/getApproverBatch/' + wfMovementTranID);
}
approveFromApprover(request: LFAApproverActionRequest): Observable<LFAApprovalResult> {
return this.apiService.httpPost<LFAApprovalResult>('/lfa/approveFromApprover', request);
}
revertFromApprover(request: LFAApproverActionRequest): Observable<LFAApprovalResult> {
return this.apiService.httpPost<LFAApprovalResult>('/lfa/revertFromApprover', request);
}
}

View File

@ -0,0 +1,72 @@
<app-loading-panel></app-loading-panel>
<div class="lfa-apv">
<div class="lfa-apv__title">LFA Payment Approval</div>
@if (data && data.batch) {
<div class="lfa-summary">
<div class="lfa-stat"><div class="lfa-stat__key">Batch ID</div><div class="lfa-stat__value">{{ data.batch.batchNumber }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Payment Date</div><div class="lfa-stat__value">{{ data.batch.paymentDate | date: 'dd-MMM-yyyy' }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">LFA Year</div><div class="lfa-stat__value">{{ data.batch.lfaYear | date: 'yyyy' }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Employees</div><div class="lfa-stat__value">{{ data.batch.headCount }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Total LFA Amount (BDT)</div><div class="lfa-stat__value">{{ data.batch.totalAmount | number: '1.2-2' }}</div></div>
</div>
@if (data.batch.remarks) {
<div class="lfa-apv__note">Remarks of the batch: {{ data.batch.remarks }}</div>
}
<div class="lfa-apv__head">
<span class="lfa-apv__sub">Employees</span>
<span class="lfa-apv__spacer"></span>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="employees.length === 0" (click)="employeeGrid.saveAsExcel()">Export</button>
</div>
<kendo-grid #employeeGrid="kendoGrid" [kendoGridBinding]="employees" [sortable]="true" [resizable]="true"
scrollable="virtual" [rowHeight]="40" [pageSize]="50" [height]="360">
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120"></kendo-grid-column>
<kendo-grid-column field="name" title="Name" [width]="210"></kendo-grid-column>
<kendo-grid-column field="designationName" title="Designation" [width]="180"></kendo-grid-column>
<kendo-grid-column field="departmentName" title="Department" [width]="180"></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>
<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>
} @else if (data && data.message) {
<div class="lfa-apv__blocked">{{ data.message }}</div>
}
@if (flowHistory.length > 0) {
<div class="lfa-apv__sub">Approval History</div>
<kendo-grid [data]="flowHistory">
<kendo-grid-column title="Employee" [width]="240">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.employeeNo }} - {{ dataItem.employeeName }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="tranDate" title="Received On" [width]="130">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.tranDate | date: 'dd-MMM-yyyy' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="status" title="Status" [width]="150">
<ng-template kendoGridCellTemplate let-dataItem>{{ flowStatusText(dataItem.status) }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="statusUpdateDate" title="Action On" [width]="170">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.statusUpdateDate | date: 'dd-MMM-yyyy hh:mm a' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="remarks" title="Remarks"></kendo-grid-column>
</kendo-grid>
}
@if (data && data.batch) {
@if (canAct) {
<div class="lfa-apv__action">
<div class="lfa-apv__remarks">
<label>Remarks</label>
<kendo-textbox [(ngModel)]="remarks" [maxlength]="500" placeholder="Required to revert"></kendo-textbox>
</div>
<button class="gh-cancel" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['undo']" [disabled]="isBusy" (click)="revert()">Revert</button>
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['check']" [disabled]="isBusy" (click)="approve()">Approve</button>
</div>
} @else if (data.message) {
<div class="lfa-apv__blocked">{{ data.message }}</div>
}
}
</div>

View File

@ -0,0 +1,88 @@
/* Payment Approval › LFA: layout only; colours are the theme's --gh-* variables */
.lfa-apv {
display: flex;
flex-direction: column;
gap: 12px;
padding: 8px 4px;
}
.lfa-apv__title {
font-size: 18px;
font-weight: 700;
color: var(--gh-lk);
}
.lfa-apv__sub {
font-size: 14px;
font-weight: 700;
color: var(--gh-lk);
}
.lfa-apv__head {
display: flex;
align-items: center;
gap: 10px;
}
.lfa-apv__spacer {
flex: 1 1 auto;
}
.lfa-apv__note {
font-size: 12px;
color: var(--gh-muted);
}
.lfa-apv__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-apv__action {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
}
.lfa-apv__remarks {
display: flex;
flex-direction: column;
gap: 4px;
width: 420px;
max-width: 100%;
label {
font-size: 12px;
font-weight: 600;
color: var(--gh-muted);
}
}
.lfa-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 12px;
}
.lfa-stat {
padding: 12px 14px;
border: 1px solid var(--gh-bo);
border-radius: 6px;
background: var(--gh-tb);
}
.lfa-stat__key {
font-size: 12px;
color: var(--gh-muted);
}
.lfa-stat__value {
margin-top: 4px;
font-size: 18px;
font-weight: 700;
color: var(--gh-lk);
}

View File

@ -0,0 +1,168 @@
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ExcelExportData } from '@progress/kendo-angular-excel-export';
import { ApiService } from 'src/app/app.api.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { DataTransferService } from 'src/app/data.transfer.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { LFAService } from 'src/app/_services/payroll/lfa.service';
import { WorkflowService } from 'src/app/_services/workflow/workflow.service';
import { WFFlowHistory } from 'src/app/_models/Work-Flow/wFMovementNext';
import {
EnumLFAPaymentStatus, LFAApprovalResult, LFAApproverBatch, LFAPaymentBatchEmployee
} from 'src/app/_models/Payroll/lfaPayment';
/**
* Payment Approval › LFA (/payment-approval/lfa): an approver opens the LFA batch they received from their
* pending list and approves it (to the next approver, or finally) or reverts it, as for the salary.
*/
@Component({
selector: 'app-lfa-approval',
templateUrl: './lfa-approval.component.html',
styleUrls: ['./lfa-approval.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false
})
export class LfaApprovalComponent implements OnInit {
wfMovementTranID = 0;
data: LFAApproverBatch = null;
employees: LFAPaymentBatchEmployee[] = [];
flowHistory: WFFlowHistory[] = [];
remarks = '';
isBusy = false;
acted = false;
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
public loadingPanel: loadingPanelService,
private dataTransferService: DataTransferService,
private workflowService: WorkflowService,
private lfaService: LFAService) {
this.apiService.selectedMenuName = 'LFA Payment Approval';
}
ngOnInit() {
// the pending list puts the workflow step (WFMovementTranID) here before it opens the page
this.wfMovementTranID = Number(this.dataTransferService.getData()) || 0;
this.load();
}
load() {
if (!this.wfMovementTranID) {
this.notificationService.showWarning('Please open the LFA approval request from your pending list.');
return;
}
this.start();
this.lfaService.getApproverBatch(this.wfMovementTranID).subscribe({
next: (resp) => {
this.data = resp;
this.employees = (resp && resp.employees || []).map(x => ({
...x,
joiningDate: this.toDate(x.joiningDate),
statusText: this.paymentStatusText(x.paymentStatus)
}));
if (resp && resp.batch) {
resp.batch.paymentDate = this.toDate(resp.batch.paymentDate);
resp.batch.lfaYear = this.toDate(resp.batch.lfaYear);
}
this.workflowService.getFlowHistorybyTranID(this.wfMovementTranID).subscribe({
next: (history: any) => {
this.stop();
this.flowHistory = history || [];
},
error: () => this.stop()
});
},
error: (err) => this.fail(err, 'Could not load the LFA approval request.')
});
}
get canAct(): boolean {
return !!this.data && this.data.canAct && !this.acted;
}
approve() {
if (!this.canAct || this.isBusy) {
return;
}
this.notificationService.showActiveConfirm('Confirmation', 'Are you sure to approve this LFA payment batch?').then((isConfirmed) => {
if (isConfirmed) {
this.send(this.lfaService.approveFromApprover({ wfMovementTranID: this.wfMovementTranID, remarks: this.remarks }));
}
});
}
revert() {
if (!this.canAct || this.isBusy) {
return;
}
if (!this.remarks || !this.remarks.trim()) {
this.notificationService.showWarning('Please write in Remarks why the batch is reverted.');
return;
}
this.notificationService.showActiveConfirm('Confirmation', 'Are you sure to revert this LFA payment batch?').then((isConfirmed) => {
if (isConfirmed) {
this.send(this.lfaService.revertFromApprover({ wfMovementTranID: this.wfMovementTranID, remarks: this.remarks }));
}
});
}
private send(call: any) {
this.start();
call.subscribe({
next: (resp: LFAApprovalResult) => {
this.stop();
if (resp.done) {
this.acted = true;
this.notificationService.showSuccess(resp.message);
} else {
this.notificationService.showError(resp.message);
}
this.load();
},
error: (err) => this.fail(err, 'Nothing was changed. Please try again.')
});
}
allEmployees = (): ExcelExportData => ({ data: this.employees });
flowStatusText(status: number): string {
switch (status) { // the workflow's EnumwfStatus
case 0: return 'Submitted';
case 1: return 'Received & Working';
case 2: return 'Reverted';
case 3: return 'Declined';
case 4: return 'Approved';
case 7: return 'Completed';
default: return '';
}
}
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;
}
}

View File

@ -3,12 +3,14 @@ import { RouterModule, Routes } from '@angular/router';
import { PaymentApprovalComponent } from './payment-approval/payment-approval.component';
import { AuthGuard } from '../_guards/auth.guard';
import { ApprovalHistoryComponent } from './approval-history/approval-history.component';
import { LfaApprovalComponent } from './lfa-approval/lfa-approval.component';
export const routes: Routes = [
{ path: 'salary', component: PaymentApprovalComponent, canActivate: [AuthGuard] },
{ path: 'bonus', component: PaymentApprovalComponent, canActivate: [AuthGuard] },
{ path: 'leaveencashment', component: PaymentApprovalComponent, canActivate: [AuthGuard] },
{ path: 'opi', component: PaymentApprovalComponent, canActivate: [AuthGuard] },
{ path: 'lfa', component: LfaApprovalComponent, canActivate: [AuthGuard] },
{ path: 'approval-history', component: ApprovalHistoryComponent, canActivate: [AuthGuard] },
];

View File

@ -38,13 +38,15 @@ import { EmpLifeCycleServices } from '../_services/employee/empLifeCycle.service
import { PaymentApprovalRoutingModule } from './payment-approval-routing.module';
import { PaymentApprovalComponent } from './payment-approval/payment-approval.component';
import { ApprovalHistoryComponent } from './approval-history/approval-history.component';
import { LfaApprovalComponent } from './lfa-approval/lfa-approval.component';
import { BackgroundCanvasModule } from '../BackgroundCanvas/BackgroundCanvas.module';
@NgModule({
declarations: [
PaymentApprovalComponent,
ApprovalHistoryComponent
ApprovalHistoryComponent,
LfaApprovalComponent
],
imports: [
CommonModule,

View File

@ -1,8 +1,149 @@
<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 Approval</kendo-card-header>
<kendo-card-body>
</kendo-card-body>
</kendo-card>
<div class="lfa-appr">
<!-- approval mode, from the Logic key lfaapproval/workflow -->
@if (info) {
<div class="lfa-appr__mode" [class.lfa-appr__mode--wf]="isWorkflow">
@if (isWorkflow) {
<b>Approval Workflow is on.</b> Submit a batch for approval; the approvers set up for LFA Payment in Work Flow Setup approve it one after another from the Payment Approval page.
@if (!info.hasWorkflowSetup) {
<div class="lfa-appr__warn">No approval workflow is set up for LFA Payment yet. Please set it up in Work Flow Setup.</div>
}
@if (!info.hasEmployee) {
<div class="lfa-appr__warn">Your login is not linked with an employee, so you cannot submit a batch for approval.</div>
}
} @else {
<b>Direct Approve.</b> The approval workflow is off; a batch is approved here at once.
}
</div>
}
<!-- ================= Batches ================= -->
<div class="lfa-appr__head">
<span class="lfa-appr__title">LFA Batches</span>
<span class="lfa-appr__spacer"></span>
<label class="lfa-appr__check"><input type="checkbox" [(ngModel)]="showApproved"> Show approved batches</label>
<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]="visibleBatches" [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]="170">
<ng-template kendoGridCellTemplate let-dataItem>
<span class="lfa-badge" [class.lfa-badge--ok]="dataItem.wfStatus === approvedStatus"
[class.lfa-badge--back]="dataItem.isAtInitiator && dataItem.wfStatus !== approvedStatus">{{ dataItem.statusText }}</span>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="pendingWith" title="Pending With" [width]="200" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.wfStatus === approvedStatus ? '' : dataItem.pendingWith }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="createdByName" title="Processed By" [width]="140"></kendo-grid-column>
<kendo-grid-column field="approvedDate" title="Approved On" [width]="160" format="dd-MMM-yyyy hh:mm a"></kendo-grid-column>
<kendo-grid-command-column title="Action" [width]="100">
<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>
</ng-template>
</kendo-grid-command-column>
<ng-template kendoGridNoRecordsTemplate>{{ showApproved ? 'No LFA batch found.' : 'No LFA batch is waiting for approval.' }}</ng-template>
</kendo-grid>
<!-- ================= The selected batch ================= -->
@if (selectedBatch) {
<div class="lfa-appr__head">
<span class="lfa-appr__title">Batch {{ selectedBatch.batchNumber }}</span>
<span class="lfa-badge" [class.lfa-badge--ok]="selectedBatch.wfStatus === approvedStatus"
[class.lfa-badge--back]="selectedBatch.isAtInitiator && selectedBatch.wfStatus !== approvedStatus">{{ selectedBatch.statusText }}</span>
<span class="lfa-appr__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>
</div>
<div class="lfa-summary">
<div class="lfa-stat"><div class="lfa-stat__key">Payment Date</div><div class="lfa-stat__value">{{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Employees</div><div class="lfa-stat__value">{{ selectedBatch.headCount }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Total LFA Amount (BDT)</div><div class="lfa-stat__value">{{ selectedBatch.totalAmount | number: '1.2-2' }}</div></div>
<div class="lfa-stat">
<div class="lfa-stat__key">{{ selectedBatch.wfStatus === approvedStatus ? 'Approved By' : 'Pending With' }}</div>
<div class="lfa-stat__value lfa-stat__value--small">{{ selectedBatch.wfStatus === approvedStatus ? (selectedBatch.approvedByName || '—') : (selectedBatch.pendingWith || '—') }}</div>
</div>
</div>
<kendo-grid #employeeGrid="kendoGrid" [kendoGridBinding]="employees" [sortable]="true" [resizable]="true"
scrollable="virtual" [rowHeight]="40" [pageSize]="50" [height]="360">
<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>
@if (flowHistory.length > 0) {
<div class="lfa-appr__title lfa-appr__title--small">Approval History</div>
<kendo-grid [data]="flowHistory">
<kendo-grid-column title="Employee" [width]="240">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.employeeNo }} - {{ dataItem.employeeName }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="tranDate" title="Received On" [width]="130">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.tranDate | date: 'dd-MMM-yyyy' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="status" title="Status" [width]="150">
<ng-template kendoGridCellTemplate let-dataItem>{{ flowStatusText(dataItem.status) }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="statusUpdateDate" title="Action On" [width]="170">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.statusUpdateDate | date: 'dd-MMM-yyyy hh:mm a' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="remarks" title="Remarks"></kendo-grid-column>
</kendo-grid>
}
@if (selectedBatch.wfStatus !== approvedStatus) {
<div class="lfa-appr__action">
<div class="lfa-appr__remarks">
<label>Remarks</label>
<kendo-textbox [(ngModel)]="remarks" [maxlength]="500" placeholder="Optional"></kendo-textbox>
</div>
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['check']"
[disabled]="isBusy || !!actionBlockedReason" [title]="actionBlockedReason" (click)="confirmAction()">{{ actionLabel }}</button>
</div>
@if (actionBlockedReason) {
<div class="lfa-appr__note">{{ actionBlockedReason }}</div>
}
}
}
</div>
@if (showConfirm && selectedBatch) {
<div class="blur-background">
<kendo-dialog [title]="isWorkflow ? 'Confirm ' + actionLabel : 'Confirm LFA Payment Approval'" [width]="480" maxHeight="90vh" (close)="showConfirm = false" (keydown.escape)="$event.stopPropagation()">
@if (isWorkflow) {
<p>Batch <b>{{ selectedBatch.batchNumber }}</b> will be sent to the approvers of LFA Payment.</p>
} @else {
<p>Batch <b>{{ selectedBatch.batchNumber }}</b> will be approved. This cannot be reversed.</p>
}
<table class="lfa-confirm">
<tbody>
<tr><td>Batch ID</td><td>{{ selectedBatch.batchNumber }}</td></tr>
<tr><td>Payment Date</td><td>{{ selectedBatch.paymentDate | date: 'dd-MMM-yyyy' }}</td></tr>
<tr><td>Employees</td><td>{{ selectedBatch.headCount }}</td></tr>
<tr><td>Total LFA Amount</td><td>BDT {{ selectedBatch.totalAmount | number: '1.2-2' }}</td></tr>
</tbody>
</table>
<kendo-dialog-actions>
<button class="gh-cancel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['cancel']" [disabled]="isBusy" (click)="showConfirm = false">Cancel</button>
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['check']" [disabled]="isBusy" (click)="act()">Confirm</button>
</kendo-dialog-actions>
</kendo-dialog>
</div>
}

View File

@ -0,0 +1,145 @@
/* LFA Payment Approval: layout only; colours are the theme's --gh-* variables */
.lfa-appr {
display: flex;
flex-direction: column;
gap: 12px;
padding: 8px 4px;
}
.lfa-appr__mode {
padding: 10px 14px;
border-radius: 6px;
border: 1px solid var(--gh-bo);
background: var(--gh-tb);
}
.lfa-appr__mode--wf {
border-color: color-mix(in srgb, var(--gh-lk) 40%, transparent);
}
.lfa-appr__warn {
margin-top: 6px;
font-weight: 600;
color: var(--gh-dn);
}
.lfa-appr__head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.lfa-appr__title {
font-size: 16px;
font-weight: 700;
color: var(--gh-lk);
}
.lfa-appr__title--small {
font-size: 14px;
}
.lfa-appr__spacer {
flex: 1 1 auto;
}
.lfa-appr__check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
}
.lfa-appr__action {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
}
.lfa-appr__remarks {
display: flex;
flex-direction: column;
gap: 4px;
width: 420px;
max-width: 100%;
label {
font-size: 12px;
font-weight: 600;
color: var(--gh-muted);
}
}
.lfa-appr__note {
font-size: 12px;
color: var(--gh-muted);
}
.lfa-selected {
border-color: var(--gh-lk);
color: var(--gh-lk);
}
.lfa-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 12px;
}
.lfa-stat {
padding: 12px 14px;
border: 1px solid var(--gh-bo);
border-radius: 6px;
background: var(--gh-tb);
}
.lfa-stat__key {
font-size: 12px;
color: var(--gh-muted);
}
.lfa-stat__value {
margin-top: 4px;
font-size: 18px;
font-weight: 700;
color: var(--gh-lk);
}
.lfa-stat__value--small {
font-size: 14px;
}
.lfa-badge {
display: inline-block;
padding: 2px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
color: var(--gh-warn);
background: color-mix(in srgb, var(--gh-warn) 15%, transparent);
}
.lfa-badge--ok {
color: var(--gh-ok);
background: color-mix(in srgb, var(--gh-ok) 15%, transparent);
}
.lfa-badge--back {
color: var(--gh-dn);
background: color-mix(in srgb, var(--gh-dn) 12%, transparent);
}
.lfa-confirm {
width: 100%;
td {
padding: 4px 0;
}
td:last-child {
text-align: right;
font-weight: 600;
}
}

View File

@ -1,6 +1,20 @@
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 { WFFlowHistory } from '../../_models/Work-Flow/wFMovementNext';
import {
EnumLFAPaymentStatus, LFAApprovalInfo, LFAApprovalResult, LFAPaymentBatch, LFAPaymentBatchEmployee
} from '../../_models/Payroll/lfaPayment';
/**
* LFA Payment Approval, as Salary Approve: the Logic key lfaapproval/workflow decides between Direct Approve
* ("No") and Submit for Approval ("Yes"). In the workflow the approvers set up for LFA Payment in Work Flow
* Setup act one after another from the Payment Approval page; a reverted batch comes back here to be
* submitted again. The server checks everything again.
*/
@Component({
selector: 'app-lfa-payment-approval',
templateUrl: './lfa-payment-approval.component.html',
@ -10,10 +24,220 @@ import { ApiService } from '../../app.api.service';
})
export class LfaPaymentApprovalComponent implements OnInit {
constructor(public apiService: ApiService) {
readonly approvedStatus = 5; // enumwfStatus.Approve
info: LFAApprovalInfo = null;
batches: LFAPaymentBatch[] = [];
showApproved = false;
selectedBatch: LFAPaymentBatch = null;
employees: LFAPaymentBatchEmployee[] = [];
flowHistory: WFFlowHistory[] = [];
remarks = '';
isBusy = false;
showConfirm = false;
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
public loadingPanel: loadingPanelService,
private lfaService: LFAService) {
this.apiService.selectedMenuName = 'LFA Payment Approval';
}
ngOnInit() {
this.start();
this.lfaService.getApprovalInfo().subscribe({
next: (resp) => {
this.info = resp;
this.loadBatches();
},
error: (err) => this.fail(err, 'Could not read the LFA approval settings.')
});
}
// ── Batches ─────────────────────────────────────────────────────
get visibleBatches(): LFAPaymentBatch[] {
return this.showApproved ? this.batches : this.batches.filter(x => x.wfStatus !== this.approvedStatus);
}
loadBatches(keepBatchID: number = 0) {
this.start();
this.lfaService.getApprovalBatches().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),
approvedDate: this.toDate(x.approvedDate)
}));
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.employees = [];
this.flowHistory = [];
this.remarks = '';
this.start();
this.lfaService.getBatchEmployees(batch.lfaPaymentID).subscribe({
next: (resp) => {
this.employees = (resp || []).map(x => ({
...x,
joiningDate: this.toDate(x.joiningDate),
statusText: this.paymentStatusText(x.paymentStatus)
}));
if (!batch.wfMovementTranID) {
this.stop();
return;
}
this.lfaService.getFlowHistory(batch.lfaPaymentID).subscribe({
next: (history) => {
this.stop();
this.flowHistory = history || [];
},
error: (err) => this.fail(err, 'Could not load the approval history.')
});
},
error: (err) => this.fail(err, 'Could not load the employees of the batch.')
});
}
clearBatch() {
this.selectedBatch = null;
this.employees = [];
this.flowHistory = [];
this.remarks = '';
}
// ── What the selected batch allows ──────────────────────────────
get isWorkflow(): boolean {
return !!this.info && this.info.isWorkflowRequired;
}
/** The batch has not been approved or submitted yet. */
get isNew(): boolean {
const b = this.selectedBatch;
return !!b && (b.wfStatus === null || b.wfStatus === undefined || b.wfStatus === 8);
}
get actionLabel(): string {
if (!this.isWorkflow) {
return 'Approve';
}
return this.selectedBatch && this.selectedBatch.isAtInitiator ? 'Submit Again' : 'Submit for Approval';
}
/** Why the button is disabled; empty when it can be used. */
get actionBlockedReason(): string {
const b = this.selectedBatch;
if (!b || !this.info) {
return 'Please select a batch.';
}
if (b.wfStatus === this.approvedStatus) {
return 'This batch is already approved.';
}
if (b.headCount === 0) {
return 'This batch has no employee.';
}
if (!this.isWorkflow) {
return this.isNew ? '' : 'This batch is in the approval workflow; it is approved from the Payment Approval page.';
}
if (!this.info.hasEmployee) {
return 'Your login is not linked with an employee. The approval workflow needs an employee to submit the batch.';
}
if (this.isNew) {
return this.info.hasWorkflowSetup ? '' : 'No approval workflow is set up for LFA Payment. Please set it up in Work Flow Setup first.';
}
return b.isAtInitiator ? '' : 'This batch is submitted and pending for approval' + (b.pendingWith ? ' with ' + b.pendingWith : '') + '.';
}
confirmAction() {
const reason = this.actionBlockedReason;
if (reason) {
this.notificationService.showWarning(reason);
return;
}
this.showConfirm = true;
}
act() {
if (this.isBusy || !this.selectedBatch) {
return;
}
const batchID = this.selectedBatch.lfaPaymentID;
const request = { lfaPaymentID: batchID, remarks: this.remarks };
const call = this.isWorkflow ? this.lfaService.submitForApproval(request) : this.lfaService.approveDirect(request);
this.start();
call.subscribe({
next: (resp: LFAApprovalResult) => {
this.stop();
this.showConfirm = false;
if (resp.done) {
this.notificationService.showSuccess(resp.message);
} else {
this.notificationService.showError(resp.message);
}
this.loadBatches(batchID);
},
error: (err) => {
this.showConfirm = false;
this.fail(err, 'Nothing was changed. Please try again.');
}
});
}
allEmployees = (): ExcelExportData => ({ data: this.employees });
flowStatusText(status: number): string {
switch (status) { // the workflow's EnumwfStatus
case 0: return 'Submitted';
case 1: return 'Received & Working';
case 2: return 'Reverted';
case 3: return 'Declined';
case 4: return 'Approved';
case 7: return 'Completed';
default: return '';
}
}
// ── 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;
}
}

View File

@ -154,6 +154,147 @@ namespace HRM.UI.Controllers.Payroll
}
}
// ── LFA Payment Approval (as Salary Approve: Direct Approve or the approval workflow, Logic lfaapproval/workflow) ──
/// <summary>Logic key, whether the login has an employee, and whether Work Flow Setup has LFA rules.</summary>
[HttpGet("getApprovalInfo")]
public ActionResult GetApprovalInfo()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetApprovalInfo(currentUser.EmployeeID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet("getApprovalBatches")]
public ActionResult GetApprovalBatches()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetApprovalBatches(currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet("getFlowHistory/{lfaPaymentID}")]
public ActionResult GetFlowHistory(int lfaPaymentID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetFlowHistory(lfaPaymentID, currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>Direct Approve, when the workflow is off.</summary>
[HttpPost("approveDirect")]
public ActionResult ApproveDirect(LFAApprovalRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.ApproveDirect(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>Submit for approval (or submit again after a revert), when the workflow is on.</summary>
[HttpPost("submitForApproval")]
public ActionResult SubmitForApproval(LFAApprovalRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.SubmitForApproval(request, currentUser.PayrollTypeID.GetValueOrDefault(),
currentUser.EmployeeID, currentUser.UserID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// The approver's side (/payment-approval/lfa). Approvers act as employees, as on Salary's Payment Approval
// page, so these are open to every login; the service checks that the step is pending with the login.
[HttpGet("getApproverBatch/{wfMovementTranID}")]
public ActionResult GetApproverBatch(int wfMovementTranID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(this._lfaPaymentService.GetApproverBatch(wfMovementTranID, currentUser.EmployeeID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpPost("approveFromApprover")]
public ActionResult ApproveFromApprover(LFAApproverActionRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(this._lfaPaymentService.ApproveFromApprover(request, currentUser.EmployeeID, currentUser.UserID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpPost("revertFromApprover")]
public ActionResult RevertFromApprover(LFAApproverActionRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(this._lfaPaymentService.RevertFromApprover(request, currentUser.EmployeeID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
private ActionResult NotAllowed()
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment.");