Merge pull request 'Brac_Master_Mohaimen' (#2) from Brac_Master_Mohaimen into Brac_Master

Reviewed-on: http://100.100.100.162:3025/CelHRTeam/HRM-10/pulls/2
This commit is contained in:
Abdullah_Al_Mohaimen_Hasan 2026-11-29 11:32:11 +06:00
commit 79db92de68
60 changed files with 6128 additions and 24 deletions

View File

@ -61,7 +61,9 @@ but several specifics are stale — prefer *this* file wherever the two disagree
at `e:\HRMGIT\` alongside a sibling `IntegrationSuite` project (this checkout is a single
self-contained repo and no `IntegrationSuite` exists), lists `npm run lint` as a working command (it
is broken — see below), describes `Ease.Core` as "referenced as the `Ease.NetCore` NuGet package"
(the live one is the project in this repo), and counts "~250+" services (there are ~450 service classes, ~310 of them DI-registered).
(the live one is the project in this repo), and counts "~250+" services (there are ~450 service classes, ~310 of them DI-registered), describes the UI
kit as a PrimeNG/Kendo/Bootstrap mix (PrimeNG and Bootstrap are gone), and gives an absolute
`https://localhost:44374/api` dev base URL (it is the relative `/api`, see *Frontend*).
## Build & run
@ -106,7 +108,7 @@ npm test # ng test (Karma, entry src/test.ts)
Both SPAs `ng serve` on 4200, so only one of the two can run at a time.
- `npm run lint` is **broken**: `angular.json` still points at the `@angular-devkit/build-angular:tslint`
builder (with a `tslint.json`), which no longer exists in Angular 19. The `@angular-eslint/*` and `eslint` 9 devDependencies are
builder (with a `tslint.json`), which is not installed. `@angular-eslint/builder` and `eslint` 9 are
installed, but there is no ESLint config file and no `@angular-eslint/builder:lint` target yet, so
wiring ESLint up means adding both.
- `npm test` works, but coverage is nominal — 18 `.spec.ts` files across the whole app. Single spec:
@ -117,8 +119,9 @@ Both SPAs `ng serve` on 4200, so only one of the two can run at a time.
[`deploy.ps1`](deploy.ps1) does the whole thing: bumps `HRM.UI/ClientApp/src/version.json`
(`YYYYMMDD-NN`, counter auto-increments per day), runs `ng build --configuration production
--base-href <baseHref>`, `dotnet publish` for `win-x64`, copies `dist/babylon` into the publish
folder's `wwwroot`, and writes an Angular `web.config` (SPA rewrites + no-cache for
--base-href <baseHref>`, `dotnet publish` for `win-x64` into `<outputFolder>_<version>`, copies
`dist/babylon` into its `wwwroot` and the whole `HRM.UI/RDLC` folder into its `RDLC` (publish alone copies
only the RDLC files the csproj lists), and writes an Angular `web.config` (SPA rewrites + no-cache for
`index.html`/`version.json`). Edit `$baseHref`/`$outputFolder` at the top per client/environment
before running. `VersionCheckService` (`ClientApp/src/app/version-check.service.ts`) polls
`version.json` every 5 minutes and prompts a reload when the server version changes — keep the
@ -243,6 +246,29 @@ Every Excel interface in the app is served by the one
[DataUploadController](HRM.UI/Controllers/CommonInterface/DataUploadController.cs) (`api/dataUpload`)
— do not add a separate controller for a new uploader.
The older regular uploads (employee basic, life cycle, allowance, fund data, …; screen
`/common-interface/data-upload/:id`) all post to `regularExcelInterface`, and
`RegularDataUploadService.UploadData` switches on `EnumRegularDataUpload`. Their expected columns are declared
in `DataUploadColumnDefinationService` (file `BasicDataUploadProcessService.cs`), so a new column needs both:
declare it there and read it in the matching `Import…` method.
### Large lists: virtual paging
A list or report that can return many rows uses `<app-virtual-grid>` + `VirtualPagingDA.GetPage`: SQL Server
pages, searches, sorts and counts, and Export to Excel is streamed from the server. Follow the 4 steps in
[HRM.DA/DA/VirtualPaging/README.md](HRM.DA/DA/VirtualPaging/README.md) (worked examples: Discontinue Employee
Details, Employee Detail Information). Needs SQL Server 2016+.
### PF percentage is per employee
`SalaryCalculator.Process` calls `PFNEW()`, which takes the PF % from `Employee.PFPercentage`, not from
`SystemInformation` as the old `PF()` does (`PF()` is now used only by `ProcessLTA`). A Live PF member with no
percentage gets a PF of 0. The value is set through a life-cycle event (`EmpLifeCycle.PFPercentage`, copied to
`Employee` by `HREmployeeDA.UpdatePFPercentage`) or the employee / life-cycle uploads; the Logic key
`confirmation` / `autopfmembership` decides whether a confirmation also makes the employee a PF member.
**No `_DB_Changes.sql` adds these two columns**: without `EmpLifeCycle.PFPercentage` every life-cycle
insert/update fails, and without `Employee.PFPercentage` setting the percentage fails.
### Employee Bulk Upload
The whole information of many employees in one spreadsheet — one row per employee, carrying that
@ -438,16 +464,16 @@ calendar's Users dropdown once came back silently empty for exactly this reason.
column: use the pattern in `CalendarItemDA.UserEmailExpression`, which checks `COL_LENGTH` once per process
and builds `COALESCE(EmailAddress, Email)` from whichever columns exist. Server-side SQL errors that the UI
swallows land in `HRM.UI/Log/Error.log` (`ExceptionLog`), the first place to look.
Two places don't follow that pattern yet. `UserDA.Insert` writes only `Email`, so creating a user fails on a
Two places don't follow that pattern yet. `UserDA.Insert` and `Update` write only `Email`, so saving a user fails on a
database that lacks it (the pending `UsersEmailColumn_DB_Changes.sql` adds it; its header wrongly says Insert
writes both columns). `UserService.MapObject`
reads only `Email` (the `EmailAddress` line is commented out), so the user list's `email` is blank wherever
addresses live in `EmailAddress`.
Gotcha in user approval: `UserDA.Approve` always sets `Status = Approved` (5), whatever the request was. So
"approving" an `Inactive_Not_Yet_Approve` (9) or `Inactive` (8) user **re-activates** them, and a deactivation
can never actually be approved. The user list labels that action "Re-activate" for this reason; the fix
belongs in the server.
Gotcha in user approval: `UserDA.Approve` writes whatever `UserStatus` the client posts; the server works
nothing out. `users-list.component.ts` sends `Inactive` when approving a pending deactivation (status 9) and
`Approved` otherwise, and the "maker cannot approve their own change" check for users is only in that
component too. (Its comment saying the server always sets Approved is out of date.)
### Authentication pages: maker-checker and audit log
@ -458,6 +484,24 @@ change is saved with an `EnumAuthStatus` (`HRM.BO/HRBasic/Enums.cs`) pending sta
`Approve` / `Reject`, `RoleService` for roles and permissions). Follow that state set for any new
Authentication page rather than inventing a status column.
**Super User IDs can be negative.** Test "has a user" / "was edited" as `!= 0`, never `> 0` (a role's maker is
`ModifiedBy` when it is not 0, else `CreatedBy`), in C# and in Angular alike. `AuthController.ValidateResetToken`
still checks `data.UserID <= 0`, so a reset link for a negative-ID Super User always reads as invalid.
### Login, OTP and forgot password
- **MFA** is on when `LDAPSettings.isMFA` is true (`MFATimer` = minutes); the code length and mail/SMS channel
are Logic keys under `mfa`. `login` then returns an `mfaSessionId`, and `verify-mfa` issues the token. The
challenge is held in **in-process memory**, so it does not survive a restart or a second server.
- `login`, `verify-mfa` and `resend-otp` are rate-limited per IP (`LoginPolicy` / `MfaPolicy` /
`ResendOtpPolicy` in `Startup`). The forgot-password endpoints are not.
- The OTP flow writes a trace to `C:\Log\OTP log <date>.txt`; `C:\Log` must exist on the server.
- **Forgot password** mails a link to `#/reset-password?token=…`. Nothing is stored: the token
(`HRM.UI/Helpers/PasswordResetTokenHelper.cs`) is AES-GCM encrypted with a key derived from
`AppSettings.Secret`, expires after `ForgotPasswordSettings.LinkExpiryMinutes`, and carries a fingerprint of
the current password, which makes it single-use. The link's base address is `EmailSettings.WebAddress`
(`http://localhost:4200/` in Development), so set that per deployment.
The **System Audit Log** page (`SystemAuditHistoryService`, `HRM.DA/DA/Users/SystemAuditHistoryDA.cs`) writes
nothing itself: it reads `Z_ROLE`, `Z_ROLEPERMISSION`, `Z_USERS`, `Z_USERROLE`, `Z_USERACCESSTYPE`, which
**database triggers** (`trRole`, `trRolePermission`, `trUsers`, `truserrole`, `trUserAccessType`) fill. Only
@ -500,7 +544,9 @@ When behavior differs between clients, look for or add a Logic key rather than b
**This checkout is not that repo.** It is `HRM-10` (`origin` = `103.197.204.162:3025/CelHRTeam/HRM-10`),
a fresh import whose history starts at one squashed commit (`838b8d4` "first commit"). Since then it
uses ordinary short-lived branches: `main` is the integration branch (PR target), with per-developer
branches (`dev_<name>`, `dev_<name>_<feature>`, `shamim`) merged back into it.
branches (`dev_<name>`, `dev_<name>_<feature>`, `shamim`) merged back into it. Client branches have started here too:
`Brac_Master` (with `Brac_Master_<name>` developer branches) is ahead of `main`, so check which line a change
belongs to before choosing a PR target.
None of the older history exists here: every commit hash quoted elsewhere in this file (`c8588ce67`,
`91369150c`, `ac179c03e`, `73f466cd0`, `bfd085e0e`) is from the original `CelHRTeam/cel.hrm` repo, and
`git show`/`git log` recovery commands only work in a clone of that repo, not here.
@ -538,7 +584,7 @@ What actually drives the DB connection:
Other live sections: `AppSettings` (`Secret`, `DefaultDB`, `RDLCLocation`, `downloadFolder`,
attendance import settings), `EmailSettings`, `EmployeeApiInfo`, `AdminPendingJob`,
`MobileAppSettings`, `FundInfo`, `OpenAI`, `LDAPSettings`, `Calendar` (bound to
`MobileAppSettings`, `FundInfo`, `OpenAI`, `LDAPSettings`, `ForgotPasswordSettings`, `Calendar` (bound to
`HRM.BO/Configuration/CalendarSettings.cs`), plus many payroll/fund GL-head keys.
`Startup.cs` has large commented-out blocks — verify against live code before assuming a feature is
@ -713,6 +759,7 @@ Four pieces decide where a page load actually lands, and they are easy to break
`/ess/landing-page`, `SuperUser` stays. So anything that lands on `''` ends up on a dashboard.
- `AppMainComponent`'s constructor calls `authService.logout()` when the load is **not** a reload
(`performance.navigation.type`), which is why opening a deep link in a fresh tab signs the user out.
The exception is `#/reset-password`: it logs out but stays on the page.
- `<app-login [hidden]="!isLoginForm()">` sits in
[app.main.component.html](HRM.UI/ClientApp/src/app/app.main.component.html) — `[hidden]`, **not
`*ngIf`**. So `LoginComponent`'s constructor runs once at bootstrap on *every* route, not just on

View File

@ -123,6 +123,7 @@ namespace HRM.BO
public bool IsShownInTaxSheet { get; set; } // R
public EnumPFMembershipType PFMemberType { get; set; }
public DateTime? PFMemberShiptDate { get; set; }
public double PFPercentage { get; set; }
public int? BranchID { get; set; }
public string AccountNo { get; set; }
public int? OutPayBranchID { get; set; }

View File

@ -2439,7 +2439,8 @@ namespace HRM.BO
ITReport177Yearly = 1005,
TAXReconciliation = 1006,
BasePay = 1008,
ITReport177Quaterly = 1010
ITReport177Quaterly = 1010,
LFABankAdvice = 1201
}

View File

@ -168,6 +168,14 @@ namespace HRM.BO
}
}
#endregion
#region PFPercentage : double
private double? _pFPercentage;
public double? PFPercentage
{
get { return _pFPercentage; }
set { _pFPercentage = value; }
}
#endregion
#region EmployeeID : ID
private int _employeeID;
public int EmployeeID
@ -577,6 +585,7 @@ namespace HRM.BO
List<EmpLifeCycle> GetEmpID(int nEmpID, DateTime effectDate);
EmpLifeCycle GetLastPosition(int nEmpID);
void UpdateApprovalStatus(List<EmpLifeCycle> oEmpLifeCycles, int currentPayrollTypeID);
bool IsAutoPFMembership();
int Save(EmpLifeCycle item, DateTime nextPayProcessDate, int payrollTypeID);
int Save(List<EmpLifeCycle> items, DateTime nextPayProcessDate);
void Delete(EmpLifeCycle item, DateTime nextPayProcessDate);

173
HRM.BO/LFA/LFAPayment.cs Normal file
View File

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.IO;
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, IworkflowInterface
{
public LFAPayment()
{
BatchNumber = string.Empty;
Details = new List<LFAPaymentDetail>();
}
public string BatchNumber { get; set; }
public int PayrollTypeID { get; set; }
/// <summary>The last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE.</summary>
public DateTime SalaryMonth { get; set; }
/// <summary>The last date of the calendar year the LFA is for.</summary>
public DateTime LFAYear { get; set; }
public DateTime PaymentDate { get; set; }
public string Remarks { get; set; }
public bool IsTaxUpdated { get; set; }
/// <summary>Null = not submitted yet, as SalaryProcess.WFStatus.</summary>
public enumwfStatus? WFStatus { get; set; }
public int? ApprovedBy { get; set; }
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
#region LFAPaymentDetail
/// <summary>One employee of a batch (dbo.LFAPaymentDetail): a snapshot of the employee and of the calculation.</summary>
public class LFAPaymentDetail : AuditTrailBase
{
public int LFAPaymentID { get; set; }
public int EmployeeID { get; set; }
public DateTime LFAYear { get; set; }
public DateTime JoiningDate { get; set; }
public DateTime? ConfirmationDate { get; set; }
public int? GradeID { get; set; }
public int? DesignationID { get; set; }
public int? DepartmentID { get; set; }
public int? CostCenterID { get; set; }
public int? BranchID { get; set; }
public string AccountNo { get; set; }
public double? JoiningBasic { get; set; }
/// <summary>Basic as of 31 December of the preceding year; null when the employee joined in the LFA year.</summary>
public double? LastDecBasic { get; set; }
/// <summary>The basic the LFA was calculated on.</summary>
public double BasicSalary { get; set; }
/// <summary>What the policy gives, before rounding to whole taka.</summary>
public double CalculatedAmount { get; set; }
/// <summary>The LFA amount to pay.</summary>
public double Amount { get; set; }
public string Remarks { get; set; }
}
#endregion
#region LFAEmployee
/// <summary>What the LFA calculation needs to know of one employee (not a table).</summary>
public class LFAEmployee
{
public int EmployeeID { get; set; }
public string EmployeeNo { get; set; }
public string Name { get; set; }
public int PayrollTypeID { get; set; }
public EnumEmployeeStatus Status { get; set; }
public bool IsConfirmed { get; set; }
public DateTime JoiningDate { get; set; }
public DateTime? ConfirmationDate { get; set; }
public int? GradeID { get; set; }
public string GradeName { get; set; }
public int? DesignationID { get; set; }
public string DesignationName { get; set; }
public int? DepartmentID { get; set; }
public string DepartmentName { get; set; }
/// <summary>The parent of the employee's department.</summary>
public string DivisionName { get; set; }
public int? CostCenterID { get; set; }
public int? BranchID { get; set; }
public string AccountNo { get; set; }
public double JoiningBasic { get; set; }
public double LastDecBasic { get; set; }
/// <summary>The batch that already has this employee's LFA of the year; empty = none.</summary>
public string PaidBatchNumber { get; set; }
/// <summary>The employee already has an LFA payment for the preceding year.</summary>
public bool IsPaidLastYear { get; set; }
}
#endregion
#region ILFAPaymentService
public interface ILFAPaymentService
{
LFAPayment Get(int id);
LFAPaymentInfo GetInfo(int payrollTypeID);
byte[] GetUploadTemplate();
LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate,
int payrollTypeID);
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);
// 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);
// LFA Bank Advice (report viewer, EnumReportType.LFABankAdvice)
List<LFAPaymentBatch> GetBankAdviceBatches(int payrollTypeID);
System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID);
}
#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

@ -0,0 +1,78 @@
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 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; }
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; }
}
/// <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

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
namespace HRM.BO
{
#region Template layout
/// <summary>
/// The LFA payment upload sheet. The downloadable workbook is generated from this and an uploaded
/// one is read against it.
/// </summary>
public static class LFAPaymentUploadTemplate
{
public const string SheetName = "LFA Payment";
public const string FileName = "LFA-Payment-Template.xlsx";
public const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public const int MaxUploadMegabytes = 10;
public const int MaxRows = 20000;
public const int HeadingRow = 1;
public const int FirstDataRow = 2;
/// <summary>How many rows of the template are formatted as text.</summary>
public const int FormattedDataRows = 1000;
public const int EmployeeNoColumn = 1;
public const int NameColumn = 2;
public const int MaxRemarksLength = 500;
/// <summary>Employee ID is the Employee No. Name only helps whoever fills the file; it is not checked.</summary>
public static readonly string[] Headings = { "Employee ID", "Name" };
public static readonly double[] Widths = { 18, 40 };
}
#endregion
#region Upload and process data
/// <summary>One uploaded row: what the user gives. Every amount is worked out by the server.</summary>
public class LFAPaymentInput
{
public int RowNo { get; set; }
public string EmployeeNo { get; set; }
}
/// <summary>The page's payment information and rows, to calculate or to process.</summary>
public class LFAPaymentRequest
{
public DateTime? PaymentDate { get; set; }
public string Remarks { get; set; }
public List<LFAPaymentInput> Rows { get; set; }
/// <summary>The total the page shows; processing stops when the calculation no longer gives it.</summary>
public double ExpectedTotal { get; set; }
}
/// <summary>One calculated row, as the New LFA Payment grid shows it.</summary>
public class LFAPaymentRow : LFAPaymentInput
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string GradeName { get; set; }
public string DesignationName { get; set; }
public string DivisionName { get; set; }
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; }
public double Amount { get; set; }
public DateTime PaymentDate { get; set; }
}
/// <summary>Why a row (or, with RowNo 0, the file) cannot be paid.</summary>
public class LFAPaymentIssue
{
public int RowNo { get; set; }
public string EmployeeNo { get; set; }
public string EmployeeName { get; set; }
public string Message { get; set; }
}
public class LFAPaymentReadResult
{
public LFAPaymentReadResult()
{
Rows = new List<LFAPaymentRow>();
Issues = new List<LFAPaymentIssue>();
}
public DateTime SalaryMonth { get; set; }
/// <summary>The rows that can be paid.</summary>
public List<LFAPaymentRow> Rows { get; set; }
/// <summary>Every problem of every other row.</summary>
public List<LFAPaymentIssue> Issues { get; set; }
public void AddIssue(int rowNo, string employeeNo, string employeeName, string message)
{
Issues.Add(new LFAPaymentIssue
{
RowNo = rowNo,
EmployeeNo = employeeNo,
EmployeeName = employeeName,
Message = message
});
}
}
public class LFAPaymentProcessResult
{
public bool Saved { get; set; }
public string Message { get; set; }
public string BatchNumber { get; set; }
/// <summary>Set when nothing was saved because the rows no longer pass.</summary>
public LFAPaymentReadResult Validation { get; set; }
}
/// <summary>The current salary month of the payroll type and the next batch number.</summary>
public class LFAPaymentInfo
{
public int PayrollTypeID { get; set; }
public DateTime SalaryMonth { get; set; }
public string NextBatchNumber { get; set; }
}
/// <summary>One row of the Payment History tab.</summary>
public class LFAPaymentHistory
{
public int LFAPaymentDetailID { get; set; }
public string BatchNumber { get; set; }
public DateTime PaymentDate { 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; }
}
#endregion
}

View File

@ -26,8 +26,8 @@ namespace HRM.DA
public static void Insert(TransactionContext tc, EmpLifeCycle item)
{
tc.ExecuteNonQuery(
"INSERT INTO EmpLifeCycle(EmpLifeCycleID,EffectDate,NodeID,GrossSalary,BasicSalary,GradeID,CategoryID,CompanyID,FunctionID,DesignationID,LocationID,DepartmentID,IsConfirm,pFMemberType,IsDiscontinue,IsContinue,EmployeeID,StatusDetailID,Remarks,Description,Status,CreatedBy, CreationDate, SequenceNo,SalaryMonth,IsCurrentMonthIncluded,CostCenterID,GradeSalaryAssesmentID,EmployeeCCID,IncrementNo,PayrollTypeID,ComplainID,PunishmentID,ApprovalStatus)" +
" VALUES( %n , %D , %n , %n , %n , %n , %n , %n , %n , %n , %n , %n , %b , %n , %b , %b , %n , %n , %s , %s , %n , %n , %D , %n , %D , %b , %n , %n , %n ,%n, %n,%n,%n,%n )",
"INSERT INTO EmpLifeCycle(EmpLifeCycleID,EffectDate,NodeID,GrossSalary,BasicSalary,GradeID,CategoryID,CompanyID,FunctionID,DesignationID,LocationID,DepartmentID,IsConfirm,pFMemberType,IsDiscontinue,IsContinue,EmployeeID,StatusDetailID,Remarks,Description,Status,CreatedBy, CreationDate, SequenceNo,SalaryMonth,IsCurrentMonthIncluded,CostCenterID,GradeSalaryAssesmentID,EmployeeCCID,IncrementNo,PayrollTypeID,ComplainID,PunishmentID,ApprovalStatus,PFPercentage)" +
" VALUES( %n , %D , %n , %n , %n , %n , %n , %n , %n , %n , %n , %n , %b , %n , %b , %b , %n , %n , %s , %s , %n , %n , %D , %n , %D , %b , %n , %n , %n ,%n, %n,%n,%n,%n,%n )",
item.ID, item.EffectDate, item.NodeID, item.GrossSalary, item.BasicSalary,
item.GradeID, item.CategoryID,
item.CompanyID, item.FunctionID,
@ -37,7 +37,7 @@ namespace HRM.DA
item.Description, item.EmployeeStatus, DataReader.GetNullValue(item.CreatedBy, 0),
item.CreatedDate, item.Sequence, item.SalaryMonth, item.IsCurrentMonthIncluded,
item.CostCenterID, item.GradeSalaryAssesmentID,
item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus);
item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.PFPercentage);
//1 //2 //3 //4 //5 //6 //7 //8 //9 //10 //11 //12 //13 //14 //15 //16 //17 //18 //19 //20 //21 //21 //22 //23 //24 //25
}
@ -49,7 +49,7 @@ namespace HRM.DA
{
tc.ExecuteNonQuery(@"UPDATE EmpLifeCycle set EffectDate=%D,NodeID=%n,GrossSalary=%n,BasicSalary=%n,GradeID=%n,CategoryID=%n,CompanyID=%n,FunctionID=%n,DesignationID=%n,
LocationID=%n,DepartmentID=%n,IsConfirm=%b,pFMemberType=%n,IsDiscontinue=%b,IsContinue=%b,EmployeeID=%n,StatusDetailID=%n,Remarks=%s,Description=%s,Status=%n,CreatedBy=%n, CreationDate=%D,
SequenceNo=%n,SalaryMonth=%D,IsCurrentMonthIncluded=%b,CostCenterID=%n,GradeSalaryAssesmentID=%n,EmployeeCCID=%n,IncrementNo=%n,PayrollTypeID=%n,ComplainID=%n,PunishmentID=%n,ApprovalStatus=%n
SequenceNo=%n,SalaryMonth=%D,IsCurrentMonthIncluded=%b,CostCenterID=%n,GradeSalaryAssesmentID=%n,EmployeeCCID=%n,IncrementNo=%n,PayrollTypeID=%n,ComplainID=%n,PunishmentID=%n,ApprovalStatus=%n,PFPercentage=%n
WHERE EmpLifeCycleID=%n", item.EffectDate, item.NodeID, item.GrossSalary, item.BasicSalary,
item.GradeID, item.CategoryID,
item.CompanyID, item.FunctionID,
@ -59,7 +59,7 @@ WHERE EmpLifeCycleID=%n", item.EffectDate, item.NodeID, item.GrossSalary, item.B
item.Description, item.EmployeeStatus, DataReader.GetNullValue(item.CreatedBy, 0),
item.CreatedDate, item.Sequence, item.SalaryMonth, item.IsCurrentMonthIncluded,
item.CostCenterID, item.GradeSalaryAssesmentID,
item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.ID);
item.EmployeeCCID, item.IncrementNo, DataReader.GetNullValue(item.PayrollTypeID, 0), DataReader.GetNullValue(item.ComplainID, 0), DataReader.GetNullValue(item.PunishmentID, 0), item.ApprovalStatus, item.PFPercentage, item.ID);
}
public static void UpdateApprovalStatus(TransactionContext tc, EmpLifeCycle item)

View File

@ -318,6 +318,12 @@ namespace HRM.DA
}
public static void UpdatePFPercentage(TransactionContext tc, int EmployeeID, double pfPercentage)
{
tc.ExecuteNonQuery("UPDATE Employee SET PFPercentage=%n WHERE EmployeeID=%n",
pfPercentage, EmployeeID);
}
public static void UpdateEndofContact(TransactionContext tc, int EmployeeID, DateTime dt)
{
tc.ExecuteNonQuery("UPDATE Employee SET ENDOFCONTRACTDATE= %d WHERE EmployeeID=%n",

View File

@ -0,0 +1,319 @@
using System;
using System.Collections.Generic;
using System.Data;
using Ease.Core.DataAccess;
using Ease.Core.DataAccess.SQL;
using HRM.BO;
using Microsoft.Data.SqlClient;
namespace HRM.DA
{
#region LFAPaymentDA
internal class LFAPaymentDA
{
#region Constructor
private LFAPaymentDA()
{
}
#endregion
#region Insert function
internal static void Insert(TransactionContext tc, LFAPayment item)
{
tc.ExecuteNonQuery(
"INSERT INTO LFAPayment(LFAPaymentID, BatchNumber, PayrollTypeID, SalaryMonth, LFAYear, PaymentDate," +
" Remarks, IsTaxUpdated, WFStatus, ApprovedBy, ApprovedDate, CreatedBy, CreationDate)" +
" VALUES(%n, %s, %n, %d, %d, %d, %u, %b, %n, %n, %D, %n, %D)",
item.ID, item.BatchNumber, item.PayrollTypeID, item.SalaryMonth, item.LFAYear, item.PaymentDate,
item.Remarks, item.IsTaxUpdated, (int?)item.WFStatus, item.ApprovedBy,
DataReader.GetNullValue(item.ApprovedDate), item.CreatedBy, item.CreatedDate);
}
#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>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)
{
tc.ExecuteNonQuery("DELETE FROM LFAPayment WHERE LFAPaymentID=%n", lfaPaymentID);
}
#endregion
#region Get Function
internal static IDataReader Get(TransactionContext tc, int nID)
{
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 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.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
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)EnumwfStatus.Received, (int)EnumwfStatus.Received,
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>
internal static int GetLastBatchNo(TransactionContext tc, int payrollTypeID, string batchPrefix)
{
object last = tc.ExecuteScalar(
"SELECT MAX(CAST(SUBSTRING(BatchNumber, %n, 20) AS INT)) FROM LFAPayment" +
" WHERE PayrollTypeID=%n AND LEFT(BatchNumber, %n)=%s",
batchPrefix.Length + 1, payrollTypeID, batchPrefix.Length, batchPrefix);
return last == null || last == DBNull.Value ? 0 : Convert.ToInt32(last);
}
/// <summary>
/// The same, holding the payroll type's batches until the transaction ends: two users processing at
/// the same time then wait for each other instead of taking the same number or the same employee.
/// </summary>
internal static int GetLastBatchNoForUpdate(TransactionContext tc, int payrollTypeID, string batchPrefix)
{
object last = tc.ExecuteScalar(
"SELECT MAX(CAST(SUBSTRING(BatchNumber, %n, 20) AS INT)) FROM LFAPayment WITH (UPDLOCK, HOLDLOCK)" +
" WHERE PayrollTypeID=%n AND LEFT(BatchNumber, %n)=%s",
batchPrefix.Length + 1, payrollTypeID, batchPrefix.Length, batchPrefix);
return last == null || last == DBNull.Value ? 0 : Convert.ToInt32(last);
}
/// <summary>
/// Everything the LFA calculation needs of the given Employee Nos, whatever their payroll type and
/// status (the caller says why one cannot be paid). The numbers go in as one parameter, as in
/// EmployeeDA.GetByEmpIDList (STRING_SPLIT, SQL Server 2016+).
/// - joining salary: the employee's first salary record;
/// (the 31 December basic comes from EmployeeGradeSalaryService.GetBasicOnDate, as the bonus uses it);
/// - cost center: the current one with the highest percentage.
/// </summary>
internal static IDataReader GetEmployees(TransactionContext tc, List<string> employeeNos, DateTime lfaYear)
{
// LFAYear is a month end, so "this year" / "last year" are date ranges of the calendar year
DateTime yearStart = new DateTime(lfaYear.Year, 1, 1);
DateTime lastYearStart = yearStart.AddYears(-1);
string sql = SQLParser.MakeSQL(@"SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#lfaEmp') IS NOT NULL DROP TABLE #lfaEmp;
CREATE TABLE #lfaEmp (EmployeeID int NOT NULL PRIMARY KEY);
INSERT INTO #lfaEmp (EmployeeID)
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, 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,
ISNULL(jn.BASICSALARY, 0) AS JoiningBasic,
py.BatchNumber AS PaidBatchNumber,
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 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
LEFT JOIN DEPARTMENT pd ON pd.DEPARTMENTID = d.PARENTID
LEFT JOIN (SELECT s.EMPLOYEEID, s.BASICSALARY,
ROW_NUMBER() OVER (PARTITION BY s.EMPLOYEEID ORDER BY s.EFFECTDATE, s.GRADESALARYID) AS RowNo
FROM GRADESALARYASSIGNMENT s INNER JOIN #lfaEmp x ON x.EmployeeID = s.EMPLOYEEID) jn
ON jn.EMPLOYEEID = e.EMPLOYEEID AND jn.RowNo = 1
LEFT JOIN (SELECT c.EMPLOYEEID, c.COSTCENTERID,
ROW_NUMBER() OVER (PARTITION BY c.EMPLOYEEID ORDER BY c.PERCENTAGE DESC, c.ID DESC) AS RowNo
FROM EMPCOSTCENTER c INNER JOIN #lfaEmp x ON x.EmployeeID = c.EMPLOYEEID
WHERE c.CurrentCC = %b) cc
ON cc.EMPLOYEEID = e.EMPLOYEEID AND cc.RowNo = 1
LEFT JOIN (SELECT dt.EmployeeID, p.BatchNumber
FROM LFAPaymentDetail dt INNER JOIN LFAPayment p ON p.LFAPaymentID = dt.LFAPaymentID
WHERE dt.LFAYear >= %d AND dt.LFAYear < %d) py ON py.EmployeeID = e.EMPLOYEEID
OUTER APPLY (SELECT TOP 1 x.LFAPaymentDetailID FROM LFAPaymentDetail x
WHERE x.EmployeeID = e.EMPLOYEEID AND x.LFAYear >= %d AND x.LFAYear < %d) pv
ORDER BY e.EMPLOYEENO;
DROP TABLE #lfaEmp;",
true, yearStart, yearStart.AddYears(1), lastYearStart, yearStart);
// must be a SqlParameter[]: Ease.Core casts the array to SqlParameter[]
SqlParameter[] parameters =
{
SqlHelperExtension.CreateInParam("@employeeNos", SqlDbType.VarChar, string.Join(",", employeeNos), -1) // varchar(max)
};
return tc.ExecuteReader(CommandType.Text, sql, parameters);
}
/// <summary>
/// Every employee's basic on a date: the latest salary record that starts before it. A copy of
/// EmployeeGradeSalaryDA.GetBasicOnDate, kept for LFA so that it runs in the LFA transaction.
/// </summary>
internal static IDataReader GetBasicOnDate(TransactionContext tc, DateTime effectdate)
{
return tc.ExecuteReader(@"SELECT g.EMPLOYEEID, g.BASICSALARY FROM GRADESALARYASSIGNMENT g
where g.empGradeSalaryid = (select Max(mx.empGradeSalaryid) from GRADESALARYASSIGNMENT mx
where g.EMPLOYEEID = mx.EMPLOYEEID and mx.EFFECTDATE < %d )
order by g.EMPLOYEEID ",
effectdate);
}
/// <summary>Payment History tab: every employee of the batches of the payment date range.</summary>
internal static IDataReader GetHistory(TransactionContext tc, DateTime fromDate, DateTime toDate, int payrollTypeID)
{
return tc.ExecuteReader(
@"SELECT dt.LFAPaymentDetailID, p.BatchNumber, p.PaymentDate, e.EMPLOYEENO, e.NAME, ds.NAME AS DesignationName,
d.DESCRIPTION AS DepartmentName, dt.JoiningDate, dt.BasicSalary, dt.Amount
FROM LFAPayment p
INNER JOIN LFAPaymentDetail dt ON dt.LFAPaymentID = p.LFAPaymentID
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 p.PayrollTypeID=%n AND p.PaymentDate BETWEEN %d AND %d
ORDER BY p.PaymentDate DESC, p.LFAPaymentID DESC, e.EMPLOYEENO",
payrollTypeID, fromDate, toDate);
}
/// <summary>
/// LFA Bank Advice: the employees of one batch with an amount to pay, with the bank account kept on the
/// detail row when the batch was processed. empIDs = joined ints made by the service (empty = whole batch);
/// bankID 0 = every bank.
/// </summary>
internal static DataSet GetBankAdvice(TransactionContext tc, int lfaPaymentID, string empIDs, int bankID, int payrollTypeID)
{
string sql = SQLParser.MakeSQL(
@"SELECT e.EMPLOYEENO, e.NAME, e.EMAILADDRESS, ds.NAME AS DesignationName, d.DESCRIPTION AS DepartmentName,
ISNULL(cc.DESCRIPTION, '') AS CostCenter, dt.AccountNo, ISNULL(bk.NAME, '') AS BankName,
ISNULL(br.NAME, '') AS BranchName, ISNULL(br.ROUTINGNO, '') AS RoutingNo, dt.Amount,
p.BatchNumber, p.PaymentDate, p.LFAYear
FROM LFAPayment p
INNER JOIN LFAPaymentDetail dt ON dt.LFAPaymentID = p.LFAPaymentID
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
LEFT JOIN CRG cc ON cc.CRGID = dt.CostCenterID
LEFT JOIN BRANCHES br ON br.BRANCHID = dt.BranchID
LEFT JOIN BANKS bk ON bk.BANKID = br.BANKID
WHERE p.LFAPaymentID=%n AND p.PayrollTypeID=%n AND dt.Amount > 0",
lfaPaymentID, payrollTypeID);
if (!string.IsNullOrEmpty(empIDs))
sql += SQLParser.MakeSQL(" AND dt.EmployeeID IN (%q)", empIDs);
if (bankID > 0)
sql += SQLParser.MakeSQL(" AND br.BANKID=%n", bankID);
sql += " ORDER BY bk.NAME, e.EMPLOYEENO";
return tc.ExecuteDataSet(sql);
}
#endregion
}
#endregion
}

View File

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Data;
using Ease.Core.DataAccess;
using HRM.BO;
using Microsoft.Data.SqlClient;
namespace HRM.DA
{
#region LFAPaymentDetailDA
internal class LFAPaymentDetailDA
{
#region Constructor
private LFAPaymentDetailDA()
{
}
#endregion
#region Insert function
/// <summary>
/// Inserts every row of a batch in one SqlBulkCopy, inside the caller's transaction (as
/// BonusProcessDA.InsertBulk). IDs must already be set.
/// </summary>
internal static void InsertBulk(TransactionContext tc, List<LFAPaymentDetail> items)
{
if (items == null || items.Count == 0)
return;
// column names exactly as in the table (bulk copy mapping is case-sensitive)
DataTable table = new DataTable("LFAPaymentDetail");
table.Columns.Add("LFAPaymentDetailID", typeof(int));
table.Columns.Add("LFAPaymentID", typeof(int));
table.Columns.Add("EmployeeID", typeof(int));
table.Columns.Add("LFAYear", typeof(DateTime));
table.Columns.Add("JoiningDate", typeof(DateTime));
table.Columns.Add("ConfirmationDate", typeof(DateTime));
table.Columns.Add("GradeID", typeof(int));
table.Columns.Add("DesignationID", typeof(int));
table.Columns.Add("DepartmentID", typeof(int));
table.Columns.Add("CostCenterID", typeof(int));
table.Columns.Add("BranchID", typeof(int));
table.Columns.Add("AccountNo", typeof(string));
table.Columns.Add("JoiningBasic", typeof(decimal));
table.Columns.Add("LastDecBasic", typeof(decimal));
table.Columns.Add("BasicSalary", typeof(decimal));
table.Columns.Add("CalculatedAmount", typeof(decimal));
table.Columns.Add("Amount", typeof(decimal));
table.Columns.Add("Remarks", typeof(string));
table.Columns.Add("CreatedBy", typeof(int));
table.Columns.Add("CreationDate", typeof(DateTime));
foreach (LFAPaymentDetail item in items)
{
table.Rows.Add(item.ID, item.LFAPaymentID, item.EmployeeID, item.LFAYear, item.JoiningDate,
Null(item.ConfirmationDate), Null(item.GradeID), Null(item.DesignationID), Null(item.DepartmentID),
Null(item.CostCenterID), Null(item.BranchID), Null(item.AccountNo), Null(Money(item.JoiningBasic)),
Null(Money(item.LastDecBasic)), Money(item.BasicSalary), Money(item.CalculatedAmount),
Money(item.Amount), Null(item.Remarks), item.CreatedBy, item.CreatedDate);
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)tc.Connection, SqlBulkCopyOptions.CheckConstraints,
(SqlTransaction)tc.Transaction))
{
bulkCopy.BulkCopyTimeout = 6000; // in seconds
bulkCopy.DestinationTableName = "LFAPaymentDetail";
foreach (DataColumn column in table.Columns)
bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
bulkCopy.WriteToServer(table);
}
}
private static object Null(object value)
{
return value ?? DBNull.Value;
}
// money columns: 4 places, as SQL Server rounds a number literal to money
private static decimal? Money(double? value)
{
return value == null ? (decimal?)null : Math.Round((decimal)value.Value, 4, MidpointRounding.AwayFromZero);
}
#endregion
#region Get Function
internal static IDataReader GetByPaymentID(TransactionContext tc, int paymentID)
{
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
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
}
#endregion
}

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

@ -189,6 +189,25 @@ namespace HRM.DA
}
}
// PF Percentage column exists only when autopfmembership is on; it is needed when this row makes the employee a Live PF member
if (autopf && odataTable.Columns.Contains("PF Percentage"))
{
string sPFPercentage = dr["PF Percentage"].ToString().Trim();
double pfPercentage = 0;
if (sPFPercentage != string.Empty
&& (!double.TryParse(sPFPercentage, out pfPercentage) || pfPercentage <= 0 || pfPercentage > 100))
{
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "PF Percentage must be greater than 0 and up to 100", oemployee.EmployeeNo, oemployee.Name));
}
else if (oemployee.PFMemberType == EnumPFMembershipType.Live)
{
if (sPFPercentage == string.Empty)
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "PF Percentage can't be empty when Confirmation Date is given", oemployee.EmployeeNo, oemployee.Name));
else
oemployee.PFPercentage = pfPercentage;
}
}
//Refresh Employee Grade Salary
if (oemployee.GradeID != null)
{
@ -841,6 +860,7 @@ namespace HRM.DA
bool isbankCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "bank", "codeautogenerate"));
bool isbranchCodeAutoGen = Convert.ToBoolean(ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "branch", "codeautogenerate"));
bool isGrossApplicable = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "grade", "grossapplicable");
bool autopf = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership");
item.SheetName = "EmpBasicInformation";
@ -883,6 +903,9 @@ namespace HRM.DA
// item.Add("PayScaleID", "String", "Yes"); //15
item.Add("Confirmation Date", "Date", "Yes"); //17
// auto PF membership on confirmation: the employee's own PF % (Employee.PFPercentage)
if (autopf == true)
item.Add("PF Percentage", "Double", "Yes");
item.Add("Basic Salary", "Double", "No"); //16
if (isGrossApplicable == true)
item.Add("Gross Salary", "Double", "No"); //15
@ -1077,6 +1100,13 @@ namespace HRM.DA
}
}
// PF membership needs the employee's own PF % (Employee.PFPercentage): the event makes the employee a
// Live PF member either through its PF_Member component, or through Confirm when autopfmembership is on
bool autopf = ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership");
bool hasPFMember = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.PF_Member);
bool hasConfirm = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.Confirm);
if (hasPFMember || (hasConfirm && autopf))
item.Add("PF Percentage", "Double", "No");
return item;
}

View File

@ -5221,6 +5221,9 @@ namespace HRM.DA
int locationid = new MiscellaneousService().GetNextID("location", "locationid", "");
int designationid = new MiscellaneousService().GetNextID("Designation", "DesignationID", "");
int costcenterid = new MiscellaneousService().GetNextID("crg", "crgid", "");
bool needPFPercentage = ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.PF_Member)
|| (ostatus.EmployeeStatusComponents.Exists(x => x.ComponentType == EnumLifeCycleComponent.Confirm)
&& new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership"));
string description = "";
try
{
@ -5657,6 +5660,23 @@ namespace HRM.DA
}
}
// PF membership needs the employee's own PF % (Employee.PFPercentage): the event makes the employee a
// Live PF member either through its PF_Member component, or through Confirm when autopfmembership is on
if (needPFPercentage)
{
double pfPercentage = 0;
string sPFPercentage = dr.Table.Columns.Contains("PF Percentage") ? dr["PF Percentage"].ToString().Trim() : "";
if (sPFPercentage == "")
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "(" + dr["Employee No"].ToString() + ")" + "PF Percentage can't be Empty"));
else if (!double.TryParse(sPFPercentage, out pfPercentage) || pfPercentage <= 0 || pfPercentage > 100)
_errorOrSuccessList.Add(UploadErrorOrSuccess.Create("PF Percentage", nRow, "(" + dr["Employee No"].ToString() + ")" + "PF Percentage must be greater than 0 and up to 100"));
else
{
lifeCycle.PFPercentage = pfPercentage;
description = description + " PF Percentage " + pfPercentage.ToString() + "%";
}
}
if (lifeCycle.EffectDate.Date < DateTime.Today)
{
lifeCycle.IsProcessed = null;

View File

@ -50,6 +50,7 @@ namespace HRM.DA
oEmployee.PFMemberShiptDate = oReader.GetDateTime("pfMemberShipDt").HasValue
? oReader.GetDateTime("pfMemberShipDt").Value
: DateTime.Now;
oEmployee.PFPercentage = oReader.GetDouble("PFPercentage", true, 0);
oEmployee.BranchID = oReader.GetInt32("branchID");
oEmployee.AccountNo = oReader.GetString("accountNo");
oEmployee.OutPayBranchID = oReader.GetInt32("OUTPAYBRANCHID");
@ -3459,6 +3460,10 @@ namespace HRM.DA
oEmployee.Name = oEmployee.Name == "" ? "Employee-" + oEmployee.EmployeeNo : oEmployee.Name;
EmployeeDA.Insert(tc, oEmployee);
// employee's own PF % (from the upload's PF Percentage column), used by SalaryCalculator.PFNEW
if (oEmployee.PFMemberType == EnumPFMembershipType.Live && oEmployee.PFPercentage > 0)
HREmployeeDA.UpdatePFPercentage(tc, oEmployee.ID, oEmployee.PFPercentage);
int id = 0;
if (uploadtype == EnumRegularDataUpload.EmployeeWithBasic || !IsFinantialAprovalRequired)
@ -3534,6 +3539,8 @@ namespace HRM.DA
oEmployee.EmpLifeCycle.LocationID = oEmployee.LocationID;
oEmployee.EmpLifeCycle.CategoryID = oEmployee.CategoryID;
oEmployee.EmpLifeCycle.IsConfirm = (oEmployee.IsConfirmed == true) ? true : false;
if (oEmployee.PFMemberType == EnumPFMembershipType.Live && oEmployee.PFPercentage > 0)
oEmployee.EmpLifeCycle.PFPercentage = oEmployee.PFPercentage;
oEmployee.EmpLifeCycle.CreatedBy = oEmployee.CreatedBy;
oEmployee.EmpLifeCycle.CreatedDate = oEmployee.CreatedDate;
oEmployee.EmpLifeCycle.GradeSalaryAssesmentID = oEmployee.EmployeeGradeSalary.ID;

View File

@ -51,6 +51,8 @@ namespace HRM.DA
if (oReader.GetInt32("pFMemberType").HasValue)
oEmpLifeCycle.PFMemberType = (EnumPFMembershipType)oReader.GetInt32("pFMemberType").Value;
else oEmpLifeCycle.PFMemberType = null;
double pfPercentage = oReader.GetDouble("PFPercentage", true, 0);
oEmpLifeCycle.PFPercentage = pfPercentage > 0 ? pfPercentage : (double?)null;
oEmpLifeCycle.IsDiscontinue = oReader.GetBoolean("IsDiscontinue");
oEmpLifeCycle.IsContinue = oReader.GetBoolean("IsContinue");
oEmpLifeCycle.EmployeeID = oReader.GetInt32("EmployeeID").Value;
@ -749,6 +751,12 @@ namespace HRM.DA
}
}
// Logic XML confirmation/autopfmembership: confirming an employee also makes them a Live PF member
public bool IsAutoPFMembership()
{
return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "confirmation", "autopfmembership");
}
public void UpdateApprovalStatus(List<EmpLifeCycle> oEmpLifeCycles, int currentPayrollTypeID)
{
TransactionContext tc = null;
@ -943,6 +951,9 @@ namespace HRM.DA
HREmployeeDA.UpdatePFInfo(tc, oEmpLifeCycle.EmployeeID,
EnumPFMembershipType.Live, oEmpLifeCycle.EffectDate);
// PF membership: the employee's own PF % (used by SalaryCalculator.PFNEW)
if (oEmpLifeCycle.PFPercentage != null)
HREmployeeDA.UpdatePFPercentage(tc, oEmpLifeCycle.EmployeeID, (double)oEmpLifeCycle.PFPercentage);
}
}
//else
@ -971,8 +982,14 @@ namespace HRM.DA
// if conponent contain pf member, update employee pfMembership property property and pfMembership date.
if (oEmpLifeCycle.PFMemberType != null)
{
HREmployeeDA.UpdatePFInfo(tc, oEmpLifeCycle.EmployeeID,
(EnumPFMembershipType)oEmpLifeCycle.PFMemberType, oEmpLifeCycle.EffectDate);
// PF membership: the employee's own PF % (used by SalaryCalculator.PFNEW)
if (oEmpLifeCycle.PFMemberType == EnumPFMembershipType.Live && oEmpLifeCycle.PFPercentage != null)
HREmployeeDA.UpdatePFPercentage(tc, oEmpLifeCycle.EmployeeID, (double)oEmpLifeCycle.PFPercentage);
}
break;
case EnumEmployeeStatus.Discontinued:
EmployeeDA.UpdateStatus(tc, oEmpLifeCycle.EmployeeID, oEmpLifeCycle.ID,

View File

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using HRM.BO;
namespace HRM.DA
{
/// <summary>
/// The LFA policy: who is eligible and for how much. No database access.
/// - An employee must be live, confirmed and have completed 6 months of service on the payment date,
/// and gets LFA once in a calendar year.
/// - The full amount is one month's basic as of 31 December of the preceding year (365 days).
/// - Joined in the LFA year: joining basic, pro-rata from the joining date to 31 December.
/// - Joined in the preceding year and had not completed 6 months by its 31 December: that year's
/// pro-rata on the joining basic, plus the current year's full amount.
/// lfaYear is the last date of the payment date's month; the year it falls in is the LFA year, and every
/// pro-rata runs to 31 December of that year.
/// </summary>
internal static class LFACalculator
{
private const int ServiceMonths = 6;
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)
{
List<string> problems = new List<string>();
if (employee.PayrollTypeID != payrollTypeID)
{
// 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)
problems.Add("Employee is not active.");
if (!employee.IsConfirmed)
problems.Add("Employee is not confirmed.");
DateTime eligibleFrom = employee.JoiningDate.Date.AddMonths(ServiceMonths);
if (employee.JoiningDate.Date > YearEnd(lfaYear))
problems.Add("Employee joined after " + DateText(YearEnd(lfaYear)) + ".");
else if (eligibleFrom > paymentDate.Date)
problems.Add("6 months of service will be completed on " + DateText(eligibleFrom) + ", after the payment date.");
if (!string.IsNullOrEmpty(employee.PaidBatchNumber))
problems.Add("LFA of " + lfaYear.Year + " is already processed in batch " + employee.PaidBatchNumber + ".");
if (!IsJoinedInYear(employee, lfaYear) && employee.LastDecBasic <= 0)
problems.Add("Basic salary as of " + DateText(LastDec(lfaYear)) + " is not found.");
if ((IsJoinedInYear(employee, lfaYear) || HasPreviousYear(employee, lfaYear)) && employee.JoiningBasic <= 0)
problems.Add("Joining basic salary is not found.");
return problems;
}
/// <summary>The detail row of an eligible employee (see Validate).</summary>
internal static LFAPaymentDetail Calculate(LFAEmployee employee, DateTime lfaYear)
{
bool joinedInYear = IsJoinedInYear(employee, lfaYear);
double currentYear = joinedInYear
? ProRata(employee.JoiningBasic, employee.JoiningDate, YearEnd(lfaYear))
: employee.LastDecBasic;
double prevYear = HasPreviousYear(employee, lfaYear)
? ProRata(employee.JoiningBasic, employee.JoiningDate, LastDec(lfaYear))
: 0;
LFAPaymentDetail detail = new LFAPaymentDetail();
detail.EmployeeID = employee.EmployeeID;
detail.LFAYear = lfaYear;
detail.JoiningDate = employee.JoiningDate;
detail.ConfirmationDate = employee.ConfirmationDate;
detail.GradeID = employee.GradeID;
detail.DesignationID = employee.DesignationID;
detail.DepartmentID = employee.DepartmentID;
detail.CostCenterID = employee.CostCenterID;
detail.BranchID = employee.BranchID;
detail.AccountNo = employee.AccountNo;
detail.JoiningBasic = employee.JoiningBasic;
detail.LastDecBasic = joinedInYear ? (double?)null : employee.LastDecBasic;
detail.BasicSalary = joinedInYear ? employee.JoiningBasic : employee.LastDecBasic;
detail.CalculatedAmount = Math.Round(prevYear + currentYear, 2, MidpointRounding.AwayFromZero);
detail.Amount = Math.Round(detail.CalculatedAmount, 0, MidpointRounding.AwayFromZero); // paid in whole taka
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)
{
return amount / DaysOfYear * (yearEnd.Date - joiningDate.Date).Days;
}
private static bool IsJoinedInYear(LFAEmployee employee, DateTime lfaYear)
{
return employee.JoiningDate.Year == lfaYear.Year;
}
/// <summary>Joined in the preceding year, not eligible within that year, and not paid for it.</summary>
private static bool HasPreviousYear(LFAEmployee employee, DateTime lfaYear)
{
return employee.JoiningDate.Year == lfaYear.Year - 1
&& employee.JoiningDate.Date.AddMonths(ServiceMonths) > LastDec(lfaYear)
&& !employee.IsPaidLastYear;
}
/// <summary>31 December of the LFA year.</summary>
private static DateTime YearEnd(DateTime lfaYear)
{
return new DateTime(lfaYear.Year, 12, 31);
}
private static DateTime LastDec(DateTime lfaYear)
{
return new DateTime(lfaYear.Year - 1, 12, 31);
}
private static string DateText(DateTime date)
{
return date.ToString("dd-MMM-yyyy");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using HRM.BO;
namespace HRM.DA
{
/// <summary>
/// The LFA payment workbook: builds the template from <see cref="LFAPaymentUploadTemplate"/> and reads
/// an uploaded one. Only what the file itself can tell is checked here.
/// </summary>
internal static class LFAPaymentWorkbook
{
#region Template
internal static byte[] BuildTemplate()
{
using (XLWorkbook workbook = new XLWorkbook())
{
IXLWorksheet sheet = workbook.Worksheets.Add(LFAPaymentUploadTemplate.SheetName);
for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++)
{
IXLCell cell = sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1);
cell.Value = LFAPaymentUploadTemplate.Headings[i];
cell.Style.Font.Bold = true;
cell.Style.Fill.BackgroundColor = XLColor.FromHtml("#D9E1F2");
cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
sheet.Column(i + 1).Width = LFAPaymentUploadTemplate.Widths[i];
}
int first = LFAPaymentUploadTemplate.FirstDataRow;
int last = first + LFAPaymentUploadTemplate.FormattedDataRows - 1;
// Text, so an Employee ID such as 00123 keeps its zeros.
sheet.Range(first, LFAPaymentUploadTemplate.EmployeeNoColumn, last, LFAPaymentUploadTemplate.NameColumn)
.Style.NumberFormat.Format = "@";
sheet.SheetView.FreezeRows(LFAPaymentUploadTemplate.HeadingRow);
using (MemoryStream stream = new MemoryStream())
{
workbook.SaveAs(stream);
return stream.ToArray();
}
}
}
#endregion
#region Read
/// <summary>The file's rows. Problems go into <paramref name="result"/>; a row with one is not returned.</summary>
internal static List<LFAPaymentInput> Read(Stream stream, string fileName, long fileLength, LFAPaymentReadResult result)
{
List<LFAPaymentInput> rows = new List<LFAPaymentInput>();
if (stream == null || string.IsNullOrWhiteSpace(fileName) || fileLength <= 0)
{
result.AddIssue(0, null, null, "No file was received, or the file is empty.");
return rows;
}
if (!fileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
{
result.AddIssue(0, null, null, "Only Excel workbooks (.xlsx) are allowed. Please use the downloaded template.");
return rows;
}
if (fileLength > LFAPaymentUploadTemplate.MaxUploadMegabytes * 1024L * 1024L)
{
result.AddIssue(0, null, null, "The file is larger than " + LFAPaymentUploadTemplate.MaxUploadMegabytes + " MB.");
return rows;
}
// ClosedXML needs a seekable stream; an upload stream may not be one.
using (MemoryStream buffer = new MemoryStream())
{
stream.CopyTo(buffer);
buffer.Position = 0;
XLWorkbook workbook;
try
{
workbook = new XLWorkbook(buffer);
}
catch (Exception)
{
result.AddIssue(0, null, null, "The file could not be opened as an Excel workbook. It may be damaged or password-protected.");
return rows;
}
using (workbook)
{
IXLWorksheet sheet;
if (!workbook.TryGetWorksheet(LFAPaymentUploadTemplate.SheetName, out sheet))
sheet = workbook.Worksheets.First();
if (!CheckHeadings(sheet, result))
return rows;
ReadRows(sheet, rows, result);
}
}
if (rows.Count == 0 && result.Issues.Count == 0)
result.AddIssue(0, null, null, "No employee found in the file.");
return rows;
}
private static bool CheckHeadings(IXLWorksheet sheet, LFAPaymentReadResult result)
{
List<string> wrong = new List<string>();
for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++)
{
string found = Text(sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1));
if (Normalize(found) != Normalize(LFAPaymentUploadTemplate.Headings[i]))
wrong.Add("column " + (char)('A' + i) + " must be \"" + LFAPaymentUploadTemplate.Headings[i] + "\""
+ (found == "" ? " (it is empty)" : " (found \"" + found + "\")"));
}
if (wrong.Count == 0)
return true;
result.AddIssue(0, null, null, "The headings in row " + LFAPaymentUploadTemplate.HeadingRow
+ " do not match the template: " + string.Join(", ", wrong) + ".");
return false;
}
private static void ReadRows(IXLWorksheet sheet, List<LFAPaymentInput> rows, LFAPaymentReadResult result)
{
// cells with a value only: the template's formatted but empty rows are not "used"
int lastRow = sheet.LastRowUsed(XLCellsUsedOptions.Contents)?.RowNumber() ?? 0;
int count = 0;
for (int rowNo = LFAPaymentUploadTemplate.FirstDataRow; rowNo <= lastRow; rowNo++)
{
string employeeNo = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.EmployeeNoColumn));
string name = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.NameColumn));
if (employeeNo == "" && name == "")
continue;
if (++count > LFAPaymentUploadTemplate.MaxRows)
{
rows.Clear();
result.AddIssue(0, null, null, "The file has more than " + LFAPaymentUploadTemplate.MaxRows + " employees. Please split it.");
return;
}
if (employeeNo == "")
{
result.AddIssue(rowNo, null, name, "Employee ID is required.");
continue;
}
rows.Add(new LFAPaymentInput { RowNo = rowNo, EmployeeNo = employeeNo });
}
}
/// <summary>What the cell holds, as text; an Employee ID stored as a number comes without separators.</summary>
private static string Text(IXLCell cell)
{
if (cell.DataType == XLDataType.Number)
{
string shown = cell.GetFormattedString().Trim();
return shown.Length > 0 && shown.All(char.IsDigit)
? shown
: cell.GetDouble().ToString("0.##########", CultureInfo.InvariantCulture);
}
return cell.GetFormattedString().Trim();
}
private static string Normalize(string heading)
{
return new string((heading ?? "").Where(x => !char.IsWhiteSpace(x)).ToArray()).ToUpperInvariant();
}
#endregion
}
}

View File

@ -125,8 +125,9 @@ namespace HRM.DA
UpdateprocessStatus("Calculating Salary deduct item(unauthorized leave)....");
this.UnAuthorizeLeave();
UpdateprocessStatus("Calculating PF & CPF....");
this.PF();
//this.PF();
this.PFNEW();
// this.OverTimeArrearProcess(); needed later
//UpdateprocessStatus("Calculating Employees Income tax....");
UpdateprocessStatus("Calculating Income Tax");
@ -692,6 +693,153 @@ namespace HRM.DA
}
private void PFNEW()
{
UpdateProgressStatus(EnumProcessStatus.Start);
bool bEchoTexException = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "salary", "echotexexception");
bool earnedBasic = new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, "pf", "earnedbasic");
// PF % comes from each employee (Employee.PFPercentage), not from SystemInformation.
//List<PFException> oPfExceptions = PFException.Get();
foreach (SalaryMonthly salary in _salaryMonthlys)
{
UpdateProgressStatus(EnumProcessStatus.PerformStep);
SalaryMonthlyDetail pfDetail = null;
if (salary.Employee.PFMemberType != EnumPFMembershipType.Live) continue;
double pfPercent = (salary.Employee.PFPercentage / 100);
// SalaryMonthly prvSalary = _PrvMonthsalary.FirstOrDefault(x => x.EmployeeID == salary.EmployeeID);
var basicitem = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.Basic_Salary
&& x.empid == salary.EmployeeID);
bool RcvLastMonthSalary = false;
if (basicitem != null) RcvLastMonthSalary = true;
double arrearPF = 0;
if (earnedBasic == true)
{
if (RcvLastMonthSalary == true)
{
//SalaryMonthlyDetail prvPF = prvSalary.Details.Find(delegate (SalaryMonthlyDetail detail)
//{
// return (detail.ItemCode == EnumSalaryItemCode.PF_Contribution
// && detail.itemGroupCode == EnumSalaryGroup.Deductions);
//});
var prvPF = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.PF_Contribution
&& x.empid == salary.EmployeeID);
if (salary.Employee.ConfirDate != null && salary.Employee.ConfirDate <
GlobalFunctions.FirstDateOfMonth(_processMonth) && RcvLastMonthSalary == true && prvPF == null) // if pf continue with previous month salary
{
DateTime? tepConfirm = salary.Employee.ConfirDate;
while (GlobalFunctions.LastDateOfMonth((DateTime)tepConfirm) <= this.payrollType.LastPayProcessDate)
{
EmployeeGradeSalary gradeSal = new EmployeeGradeSalaryService().GetBasicOnDateBAT(salary.EmployeeID, (DateTime)tepConfirm);
if (gradeSal == null)
{
AddProcessStatus(salary.Employee, " Employee previous salary not found during PF arrear calculation");
break;
}
double fractionate = 0;
if (tepConfirm == GlobalFunctions.FirstDateOfMonth((DateTime)tepConfirm))
fractionate = 1;
if (tepConfirm == GlobalFunctions.LastDateOfMonth((DateTime)tepConfirm))
fractionate = 30 / 29;
else fractionate = GlobalFunctions.GetFractinalOfMonth((DateTime)tepConfirm);
arrearPF = arrearPF + ((gradeSal.BasicSalary * fractionate) * pfPercent);
tepConfirm = GlobalFunctions.FirstDateOfMonth(((DateTime)tepConfirm).AddMonths(1));
}
}
}
SalaryMonthlyDetail basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary
&& detail.itemGroupCode == EnumSalaryGroup.Gross); });
if (basic != null)
{
pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions,
EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution, 0,
"PF", GlobalFunctions.Round(basic.CalculatedAmount * pfPercent));
}
basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary
&& detail.itemGroupCode == EnumSalaryGroup.Arrear); });
if (basic != null)
{
pfDetail.CalculatedAmount = pfDetail.CalculatedAmount + GlobalFunctions.Round(basic.CalculatedAmount * pfPercent);
}
basic = salary.Details.Find(delegate (SalaryMonthlyDetail detail) { return (detail.ItemCode == EnumSalaryItemCode.Basic_Salary
&& detail.itemGroupCode == EnumSalaryGroup.UnauthLeave); });
if (basic != null)
{
pfDetail.CalculatedAmount = pfDetail.CalculatedAmount - GlobalFunctions.Round(basic.CalculatedAmount * pfPercent);
}
if (pfDetail != null)
{
if (salary.Employee.ConfirDate != null &&
GlobalFunctions.LastDateOfMonth((DateTime)salary.Employee.ConfirDate) == _processMonth)
{
if ((DateTime)salary.Employee.ConfirDate != salary.Employee.JoiningDate)
{
pfDetail.CalculatedAmount = GlobalFunctions.Round(pfDetail.CalculatedAmount *
((double)(31 - ((DateTime)salary.Employee.ConfirDate).Day) / (double)30));
}
}
pfDetail.CalculatedAmount = pfDetail.CalculatedAmount + GlobalFunctions.Round(arrearPF);
pfDetail.ChangedAmount = pfDetail.CalculatedAmount;
}
}
else
{
double months = 1;
if (bEchoTexException == false)
{
salaryHistory prvPF = null;
if (RcvLastMonthSalary == true)
{
prvPF = _PrvMonthsalaryItems.FirstOrDefault(x => x.itemCode == EnumSalaryItemCode.PF_Contribution
&& x.empid == salary.EmployeeID);
}
if (RcvLastMonthSalary == true)
{
if (prvPF == null)
months = Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.ConfirDate, _processMonth) + 1;
else
{
if (salary.ArrearGradeSalaries.Count > 0)
{
pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions,
EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution,
0, "PF", GlobalFunctions.Round(salary.GetGrossAmount(EnumSalaryItemCode.Basic_Salary, (int)EnumSalaryItemCode.Basic_Salary)
* pfPercent));
continue;
}
}
}
else if ((Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.JoiningDate, _processMonth) + 1) <= 2) // joining in last month
{
months = Global.DateFunctions.DateDiff("m", (DateTime)salary.Employee.JoiningDate, _processMonth) + 1;
}
}
pfDetail = this.AddDetail(salary, EnumSalaryGroup.Deductions,
EnumSalaryItemCode.PF_Contribution, (int)EnumSalaryItemCode.PF_Contribution,
0, "PF", GlobalFunctions.Round(salary.ThisMonthBasic * pfPercent * months));
}
}
UpdateProgressStatus(EnumProcessStatus.End);
}
private void AllowanceDeduction()
{

View File

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Data;
using HRM.BO;
using HRM.DA;
using Microsoft.Reporting.NETCore;
namespace HRM.Report
{
/// <summary>
/// LFA Bank Advice (EnumReportType.LFABankAdvice, /payroll-lfa/lfa-bank-advice): the employees of one
/// approved LFA payment batch with their bank account and LFA amount, rendered with LFABankAdvice.rdlc.
/// </summary>
public class rptLFABankAdvice
{
private const string RdlcName = "HRM.Report.RDLC.LFABankAdvice.rdlc";
private const string DataSetName = "dsLFABankAdvice";
public byte[] ShowLFABankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeId, string reportType)
{
if (lfaPaymentID <= 0)
throw new Exception("Select an LFA payment batch.");
DataSet oSource = new LFAPaymentService().GetBankAdvice(lfaPaymentID, sEmpIDs, bankID, payrollTypeId);
if (oSource == null || oSource.Tables.Count == 0 || oSource.Tables[0].Rows.Count == 0)
throw new Exception("No employee of the selected batch has an LFA amount to pay for this selection.");
DataTable bankAdvice = new DataTable(DataSetName);
bankAdvice.Columns.Add("SLNo", typeof(int));
bankAdvice.Columns.Add("EmpNo", typeof(string));
bankAdvice.Columns.Add("EmpName", typeof(string));
bankAdvice.Columns.Add("Designation", typeof(string));
bankAdvice.Columns.Add("Department", typeof(string));
bankAdvice.Columns.Add("CostCenter", typeof(string));
bankAdvice.Columns.Add("AccountNo", typeof(string));
bankAdvice.Columns.Add("Bank", typeof(string));
bankAdvice.Columns.Add("Branch", typeof(string));
bankAdvice.Columns.Add("RoutingNo", typeof(string));
bankAdvice.Columns.Add("Email", typeof(string));
bankAdvice.Columns.Add("Amount", typeof(double));
string batchNumber = string.Empty;
DateTime paymentDate = DateTime.Today;
DateTime lfaYear = DateTime.Today;
int count = 1;
foreach (DataRow oDRow in oSource.Tables[0].Rows)
{
DataRow oDR = bankAdvice.NewRow();
oDR["SLNo"] = count;
oDR["EmpNo"] = Convert.ToString(oDRow["EMPLOYEENO"]);
oDR["EmpName"] = Convert.ToString(oDRow["NAME"]);
oDR["Designation"] = Convert.ToString(oDRow["DesignationName"]);
oDR["Department"] = Convert.ToString(oDRow["DepartmentName"]);
oDR["CostCenter"] = Convert.ToString(oDRow["CostCenter"]);
oDR["AccountNo"] = Convert.ToString(oDRow["AccountNo"]);
oDR["Bank"] = Convert.ToString(oDRow["BankName"]);
oDR["Branch"] = Convert.ToString(oDRow["BranchName"]);
oDR["RoutingNo"] = Convert.ToString(oDRow["RoutingNo"]);
oDR["Email"] = Convert.ToString(oDRow["EMAILADDRESS"]);
oDR["Amount"] = Math.Round(Convert.ToDouble(oDRow["Amount"]));
bankAdvice.Rows.Add(oDR);
if (count == 1)
{
batchNumber = Convert.ToString(oDRow["BatchNumber"]);
paymentDate = Convert.ToDateTime(oDRow["PaymentDate"]);
lfaYear = Convert.ToDateTime(oDRow["LFAYear"]);
}
count++;
}
DataSet dSet = new DataSet();
dSet.Tables.Add(bankAdvice);
List<ReportParameter> parameters = new List<ReportParameter>
{
new ReportParameter("BatchNumber", batchNumber),
new ReportParameter("PaymentDate", paymentDate.ToString("dd MMM yyyy")),
new ReportParameter("LFAYear", lfaYear.Year.ToString())
};
return new ReportProcessor().CommonReportView(null, RdlcName, dSet, null, parameters, true, payrollTypeId, reportType);
}
}
}

View File

@ -61,6 +61,7 @@
<None Remove="RDLC\BanglaPSlipBonus.rdlc" />
<None Remove="RDLC\BanglaPSlipSub.rdlc" />
<None Remove="RDLC\BankAdvice.rdlc" />
<None Remove="RDLC\LFABankAdvice.rdlc" />
<None Remove="RDLC\BankAdviceNmgt.rdlc" />
<None Remove="RDLC\BankAdviceSalary.rdlc" />
<None Remove="RDLC\BankAdviceSalaryHnm.rdlc" />
@ -376,6 +377,7 @@
<EmbeddedResource Include="RDLC\BanglaPSlipSub.rdlc" />
<EmbeddedResource Include="RDLC\BankAdviceWithRoutingNo.rdlc" />
<EmbeddedResource Include="RDLC\BankAdvice.rdlc" />
<EmbeddedResource Include="RDLC\LFABankAdvice.rdlc" />
<EmbeddedResource Include="RDLC\BankAdviceNmgt.rdlc" />
<EmbeddedResource Include="RDLC\BankAdviceSalary.rdlc" />
<EmbeddedResource Include="RDLC\BankAdviceSalaryHnm.rdlc" />

File diff suppressed because one or more lines are too long

View File

@ -20,6 +20,7 @@ export class EmpLifeCycle extends BaseObject {
departmentID: number;
isConfirm?: boolean;
pfMemberType?: EnumPFMembershipType;
pfPercentage?: number;
employeeID: number;
statusDetailID: number;
grossSalary: number;

View File

@ -47,6 +47,7 @@ export class Employee {
isShownInTaxSheet: boolean;
pfMemberType: EnumPFMembershipType;
pfMemberShiptDate: Date;
pfPercentage: number;
branchID: number;
accountNo: string;
outPayBranchID: number;
@ -142,6 +143,7 @@ export class Employee {
this.statusName = '';
this.isShownInTaxSheet = false;
this.pfMemberType = EnumPFMembershipType.NotYetLive;
this.pfPercentage = 0;
this.branchID = null;
this.accountNo = '';
this.outPayBranchID = null;

View File

@ -0,0 +1,159 @@
// LFA Payment (HRM.BO/LFA)
/** One uploaded row: what the user gives. Every amount is worked out by the server. */
export class LFAPaymentInput {
rowNo: number;
employeeNo: string;
}
/** One calculated row of the New LFA Payment grid. */
export class LFAPaymentRow extends LFAPaymentInput {
employeeID: number;
name: string;
gradeName: string;
designationName: string;
divisionName: string;
departmentName: string;
joiningDate: Date;
confirmationDate: Date;
serviceLength: string; // Joining Date to Payment Date
joiningBasic: number;
lastDecBasic: number;
basicSalary: number;
amount: number;
paymentDate: Date;
}
/** Why a row (or, with rowNo 0, the file) cannot be paid. */
export class LFAPaymentIssue {
rowNo: number;
employeeNo: string;
employeeName: string;
message: string;
}
export class LFAPaymentReadResult {
salaryMonth: Date;
rows: LFAPaymentRow[];
issues: LFAPaymentIssue[];
}
export class LFAPaymentRequest {
paymentDate: string; // yyyy-MM-dd
remarks: string;
rows: LFAPaymentInput[];
expectedTotal: number;
}
export class LFAPaymentProcessResult {
saved: boolean;
message: string;
batchNumber: string;
validation: LFAPaymentReadResult; // set when nothing was saved because the rows no longer pass
}
export class LFAPaymentInfo {
payrollTypeID: number;
salaryMonth: Date;
nextBatchNumber: string;
}
/** One row of the Payment History grid. */
export class LFAPaymentHistory {
lfaPaymentDetailID: number;
batchNumber: string;
paymentDate: Date;
employeeNo: string;
name: string;
designationName: string;
departmentName: string;
joiningDate: Date;
basicSalary: number;
amount: number;
}
// ── 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;
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;
}
/** 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;
}
/** detailIDs empty = the whole batch. */
export class LFAPaymentUndoRequest {
lfaPaymentID: number;
detailIDs: number[];
}
export class LFAPaymentUndoResult {
undone: boolean;
message: string;
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

@ -1799,6 +1799,7 @@ export enum EnumReportType {
DailyAbsentLiFung = 609,
DailyOddLiFung = 610,
DailyAttnLiFung = 611,
LFABankAdvice = 1201,
}

View File

@ -33,6 +33,9 @@ export class EmpLifeCycleServices {
GetByUserID() {
return this.apiService.httpGet<EmployeeStatus[]>('/EmpLifeCycle/GetByUserID');
}
IsAutoPFMembership() {
return this.apiService.httpGet<boolean>('/EmpLifeCycle/IsAutoPFMembership');
}
getEmpLifeCyclesByDate(param: any) {
return this.apiService.httpPost<EmpLifeCycle[]>('/EmpLifeCycle/getEmpLifeCyclesByDate', param);
}

View File

@ -0,0 +1,109 @@
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'
})
export class LFAService {
constructor(public apiService: ApiService) {
}
/** The current salary month and the next batch number. */
getPaymentInfo(): Observable<LFAPaymentInfo> {
return this.apiService.httpGet<LFAPaymentInfo>('/lfa/getPaymentInfo');
}
downloadTemplate(): Observable<Blob> {
return this.apiService.httpGetBlob('/dataUpload/lfa-payment-upload-template');
}
/** Reads a filled template on the server and returns the calculated employees. Nothing is saved. */
readUpload(file: File, paymentDate: string): Observable<LFAPaymentReadResult> {
const formData = new FormData();
formData.append('excelfile', file, file.name);
formData.append('paymentDate', paymentDate);
return this.apiService.httpPostBlob('/dataUpload/lfa-payment-upload-read', formData);
}
calculatePayment(request: LFAPaymentRequest): Observable<LFAPaymentReadResult> {
return this.apiService.httpPost<LFAPaymentReadResult>('/lfa/calculatePayment', request);
}
/** Saves the rows as a new batch, all or nothing. The server calculates every row again. */
processPayment(request: LFAPaymentRequest): Observable<LFAPaymentProcessResult> {
return this.apiService.httpPost<LFAPaymentProcessResult>('/lfa/processPayment', request);
}
/** Dates as yyyy-MM-dd. */
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);
}
// ── LFA Bank Advice (report viewer, /payroll-lfa/lfa-bank-advice) ──
/** The approved batches of the payroll type. */
getBankAdviceBatches(): Observable<LFAPaymentBatch[]> {
return this.apiService.httpGet<LFAPaymentBatch[]>('/lfa/getBankAdviceBatches');
}
// ── 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

@ -145,6 +145,11 @@ export const routes: Routes = [
loadChildren: () => import('./payroll-ot/payroll-ot.module').then(m => m.PayrollOtModule)
},
{
path: 'payroll-lfa',
canActivate: [AuthGuard],
loadChildren: () => import('./payroll-lfa/payroll-lfa.module').then(m => m.PayrollLfaModule)
},
{
path: 'payroll-tax',
canActivate: [AuthGuard],

View File

@ -101,7 +101,7 @@
<!-- li items float right, so this one (last in DOM) sits LEFT of the Pending Jobs icon -->
@if (payrollTypeName) {
<li class="topbar-payroll-type-item">
<span class="topbar-payroll-type" kendoTooltip title="Current payroll type">{{payrollTypeName}}</span>
<span class="topbar-payroll-type" kendoTooltip title="Current payroll type and salary month">{{payrollTypeName}}@if (salaryMonth) {<span class="topbar-salary-month"> | {{salaryMonth | date:'MMMM-yyyy'}}</span>}</span>
</li>
}
</ul>

View File

@ -442,7 +442,7 @@
}
.topbar-payroll-type {
display: inline-block;
max-width: 260px;
max-width: 380px;
padding: 4px 12px;
border: 1px solid color-mix(in srgb, $color-white 35%, transparent);
border-radius: 999px;
@ -456,6 +456,9 @@
text-overflow: ellipsis;
cursor: default;
}
.topbar-salary-month {
font-weight: 500;
}
// Admin / super-user profile menu (Babylon li.user-profile > ul) drawn exactly like the ESS user
// menu (.ss-dd.ss-user-dd above): white card, 14px corners, soft shadow, header row with a divider,

View File

@ -59,6 +59,8 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy {
// (EnumUserType.User) logins only. Re-read whenever the stored token changes
// (login, user switch, payroll-type switch, logout).
payrollTypeName: string = '';
// current salary month = the payroll type's nextPayProcessDate
salaryMonth: Date = null;
private payrollTypeToken: string | null | undefined = undefined;
private payrollTypeSub: Subscription | null = null;
@ -196,15 +198,18 @@ export class AppTopBarComponent implements OnInit, DoCheck, OnDestroy {
}
if (!user || user.UserType != EnumUserType.User || !user.PayrollTypeID) {
this.payrollTypeName = '';
this.salaryMonth = null;
return;
}
this.payrollTypeSub = this.authService.GetPayrollTypeByLoginID().subscribe({
next: (payrollType) => {
this.payrollTypeName = payrollType?.description ?? '';
this.salaryMonth = payrollType?.nextPayProcessDate ? new Date(payrollType.nextPayProcessDate) : null;
},
error: () => {
this.payrollTypeName = '';
this.salaryMonth = null;
},
});
}

View File

@ -117,6 +117,8 @@ export class DataUploadComponent implements OnInit, OnDestroy {
this.dataUploadColumnDefinition = undefined;
this.sheetName = undefined;
this.scolName = undefined;
this.htmlContent = undefined;
this.test = undefined;
this.uploadErrorOrSuccess = [];
this.uploadFileList = [];
this.dataUploadForm = new FormGroup({});
@ -174,6 +176,11 @@ export class DataUploadComponent implements OnInit, OnDestroy {
this.dataUploadColumnDefinition = undefined;
this.sheetName = undefined;
this.scolName = undefined;
// the component is reused across upload types: clear the previous page's columns and selection
this.htmlContent = undefined;
this.test = undefined;
this.itemid = undefined;
this.itemidTwo = undefined;
this.uploadErrorOrSuccess = [];
this.uploadFileList = [];
this.dataUploadForm = new FormGroup({});
@ -236,6 +243,8 @@ export class DataUploadComponent implements OnInit, OnDestroy {
name: x.description,
});
});
// events in alphabetical order
this.ItemData.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
},
(x) => {
this.loadingPanel.ShowLoadingPanel = false;

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,159 @@
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 {
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)
}));
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 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

@ -0,0 +1,148 @@
<app-loading-panel></app-loading-panel>
<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>
<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

@ -0,0 +1,234 @@
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 {
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',
styleUrls: ['./lfa-payment-approval.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class LfaPaymentApprovalComponent implements OnInit {
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)
}));
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 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

@ -0,0 +1,98 @@
<app-loading-panel></app-loading-panel>
<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>
<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

@ -0,0 +1,196 @@
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 {
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',
styleUrls: ['./lfa-payment-undo.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class LfaPaymentUndoComponent implements OnInit {
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)
}));
},
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 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

@ -0,0 +1,224 @@
<app-loading-panel></app-loading-panel>
<div class="lfa-page">
<app-tab-view [(activeIndex)]="selectedTab" [scrollable]="true" (onChange)="onTabSelect($event.index)">
<!-- ================= LFA Request (design only for now) ================= -->
<app-tab-panel header="LFA Request ({{ requests.length }})" leftIcon="pi pi-list">
@if (selectedTab === 0) {
<div class="lfa-tab">
<div class="lfa-toolbar">
<div class="lfa-field lfa-field--wide">
<label>Search</label>
<kendo-textbox [(ngModel)]="requestSearch" placeholder="ID, name, designation…" [clearButton]="true"></kendo-textbox>
</div>
<div class="lfa-field">
<label>Department</label>
<kendo-dropdownlist [data]="[allDepartments]" [(ngModel)]="requestDepartment"></kendo-dropdownlist>
</div>
<div class="lfa-field">
<label>LFA Start From</label>
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="requestFrom"></kendo-datepicker>
</div>
<div class="lfa-field">
<label>LFA Start To</label>
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="requestTo"></kendo-datepicker>
</div>
<button class="gh-reset" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['undo']" (click)="resetRequestFilter()">Reset</button>
<span class="lfa-spacer"></span>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="true">Export</button>
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['forward']" [disabled]="true">Payment Proceed</button>
</div>
<div class="lfa-info">Approved LFA requests awaiting payment · <b>0</b> selected · Est. LFA amount <b>0.00</b></div>
<kendo-grid [kendoGridBinding]="requests" [pageable]="true" [pageSize]="10" [sortable]="true" [height]="420">
<kendo-grid-checkbox-column [width]="45" [showSelectAll]="requests.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]="180"></kendo-grid-column>
<kendo-grid-column field="designationName" title="Designation" [width]="160"></kendo-grid-column>
<kendo-grid-column field="departmentName" title="Department" [width]="160"></kendo-grid-column>
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="120"></kendo-grid-column>
<kendo-grid-column field="service" title="Service (Yrs)" [width]="110"></kendo-grid-column>
<kendo-grid-column field="leaveFromDate" title="LFA Start Date" [width]="130"></kendo-grid-column>
<kendo-grid-column field="leaveToDate" title="LFA End Date" [width]="130"></kendo-grid-column>
<kendo-grid-column field="leaveDays" title="Days" [width]="80"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>No records found.</ng-template>
</kendo-grid>
</div>
}
</app-tab-panel>
<!-- ================= New LFA Payment ================= -->
<app-tab-panel header="New LFA Payment ({{ rows.length }})" leftIcon="pi pi-money-bill">
@if (selectedTab === 1) {
<div class="lfa-tab">
<div class="lfa-toolbar">
<div class="lfa-field">
<label>Payment Date <span class="lfa-required">*</span></label>
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="paymentDate" (valueChange)="paymentDate = $event; onPaymentInfoChange()"></kendo-datepicker>
</div>
<!-- same file input as /common-interface/data-upload, on the right of the Payment Date -->
<div class="lfa-upload">
<input #fileInput id="fupLFAPayment" kendoTextBox type="file" accept=".xlsx" class="lfa-upload__file"
(click)="clearSelectedFile()" (change)="selectFile($event)">
<button class="k-button k-primary gh-import" type="button" kendoButton
[svgIcon]="apiService.KendoSVGIcon['upload']" [disabled]="isBusy || !selectedFile" (click)="uploadFile()">
Upload
</button>
<button class="k-button k-primary gh-download" type="button" kendoButton
[svgIcon]="apiService.KendoSVGIcon['download']" (click)="downloadTemplate()">
Sample File Download
</button>
</div>
</div>
<div class="lfa-toolbar">
<div class="lfa-field lfa-field--remarks">
<label>Remarks</label>
<kendo-textbox [(ngModel)]="remarks" [maxlength]="500" placeholder="e.g. LFA for December 2026"></kendo-textbox>
</div>
<span class="lfa-spacer"></span>
<button class="gh-reset" kendoButton type="button" fillMode="outline" [svgIcon]="apiService.KendoSVGIcon['cross']" [disabled]="isBusy" (click)="clear()">Clear</button>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="rows.length === 0" (click)="paymentGrid.saveAsExcel()">Export</button>
<button class="gh-process" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['gear']" [disabled]="isBusy || rows.length === 0" (click)="confirmProcess()">Process Payment</button>
</div>
<div class="lfa-summary">
<div class="lfa-stat"><div class="lfa-stat__key">Employees</div><div class="lfa-stat__value">{{ rows.length }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Total Basic Salary</div><div class="lfa-stat__value">{{ totalBasic | number: '1.2-2' }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Total LFA Amount (BDT)</div><div class="lfa-stat__value">{{ totalAmount | number: '1.2-2' }}</div></div>
<div class="lfa-stat"><div class="lfa-stat__key">Batch ID (on process)</div><div class="lfa-stat__value">{{ rows.length > 0 && info ? info.nextBatchNumber : '—' }}</div></div>
</div>
<!-- virtual scrolling: only the rows on screen are rendered -->
<kendo-grid #paymentGrid="kendoGrid" [kendoGridBinding]="rows" scrollable="virtual" [rowHeight]="40" [pageSize]="50"
[sortable]="true" [resizable]="true" [height]="430">
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120">
<ng-template kendoGridFooterTemplate>Total</ng-template>
</kendo-grid-column>
<kendo-grid-column field="name" title="Name" [width]="210" [style]="{ 'white-space': 'nowrap', 'overflow': 'hidden', 'text-overflow': 'ellipsis' }">
<ng-template kendoGridFooterTemplate>{{ rows.length }} employees</ng-template>
</kendo-grid-column>
<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>
<kendo-grid-column field="amount" title="LFA Amount" [width]="140" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ totalAmount | number: '1.2-2' }}</div></ng-template>
</kendo-grid-column>
<kendo-grid-command-column title="Action" [width]="75">
<ng-template kendoGridCellTemplate let-dataItem>
<button type="button" kendoButton class="kt-delete" title="Remove" [svgIcon]="apiService.KendoSVGIcon['delete']" (click)="removeRow(dataItem)"></button>
</ng-template>
</kendo-grid-command-column>
<ng-template kendoGridNoRecordsTemplate>No employees yet. Upload the Excel file.</ng-template>
<kendo-grid-excel fileName="LFA-Payment.xlsx" [fetchData]="allPaymentRows"></kendo-grid-excel>
</kendo-grid>
@if (issues.length > 0) {
<div class="lfa-issues__head">
<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>
}
<div class="lfa-note">Uploaded file columns: Employee ID, Name. Amounts in BDT.</div>
</div>
}
</app-tab-panel>
<!-- ================= Payment History ================= -->
<app-tab-panel header="Payment History" leftIcon="pi pi-history">
@if (selectedTab === 2) {
<div class="lfa-tab">
<div class="lfa-toolbar">
<div class="lfa-field">
<label>Start Date <span class="lfa-required">*</span></label>
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="historyFrom"></kendo-datepicker>
</div>
<div class="lfa-field">
<label>End Date <span class="lfa-required">*</span></label>
<kendo-datepicker [format]="'dd-MMM-yyyy'" [(ngModel)]="historyTo"></kendo-datepicker>
</div>
<div class="lfa-field">
<label>Department</label>
<kendo-dropdownlist [data]="historyDepartments" [(ngModel)]="historyDepartment" (valueChange)="historyDepartment = $event; filterHistory()"></kendo-dropdownlist>
</div>
<button class="gh-refresh" kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['redo']" [disabled]="isBusy" (click)="loadHistory()">Load</button>
</div>
<div class="lfa-toolbar">
<div class="lfa-field lfa-field--wide">
<label>Search in results</label>
<kendo-textbox [(ngModel)]="historySearch" (valueChange)="historySearch = $event; filterHistory()" [clearButton]="true" placeholder="Batch, ID, name…"></kendo-textbox>
</div>
<span class="lfa-spacer"></span>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" [disabled]="historyRows.length === 0" (click)="historyGrid.saveAsExcel()">Export</button>
<button class="gh-print" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['print']" [disabled]="historyRows.length === 0" (click)="printHistory()">Print</button>
</div>
<kendo-grid #historyGrid="kendoGrid" [kendoGridBinding]="historyRows" [sortable]="true" [resizable]="true"
[pageable]="{ pageSizes: [10, 25, 50, 100] }" [pageSize]="25" [height]="500">
<kendo-grid-column field="batchNumber" title="Batch ID" [width]="130" [style]="{ 'font-weight': '600' }"></kendo-grid-column>
<kendo-grid-column field="paymentDate" title="Payment Date" [width]="120" format="dd-MMM-yyyy"></kendo-grid-column>
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="110"></kendo-grid-column>
<kendo-grid-column field="name" title="Name" [width]="190"></kendo-grid-column>
<kendo-grid-column field="designationName" title="Designation" [width]="160"></kendo-grid-column>
<kendo-grid-column field="departmentName" title="Department" [width]="170"></kendo-grid-column>
<kendo-grid-column field="joiningDate" title="Joining Date" [width]="120" format="dd-MMM-yyyy"></kendo-grid-column>
<kendo-grid-column field="basicSalary" title="Basic Salary" [width]="130" format="n2" [style]="{ 'text-align': 'right' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ historyTotalBasic | number: '1.2-2' }}</div></ng-template>
</kendo-grid-column>
<kendo-grid-column field="amount" title="LFA Amount" [width]="130" format="n2" [style]="{ 'text-align': 'right', 'font-weight': '600' }" [headerStyle]="{ 'text-align': 'right', 'justify-content': 'flex-end' }">
<ng-template kendoGridFooterTemplate><div class="lfa-right">{{ historyTotalAmount | number: '1.2-2' }}</div></ng-template>
</kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>No records found.</ng-template>
<kendo-grid-excel fileName="LFA-Payment-History.xlsx" [fetchData]="allHistoryRows"></kendo-grid-excel>
</kendo-grid>
<div class="lfa-info">{{ historySummary }}</div>
</div>
}
</app-tab-panel>
</app-tab-view>
</div>
@if (showConfirm) {
<div class="blur-background">
<kendo-dialog title="Confirm LFA Payment" [width]="460" maxHeight="90vh" (close)="showConfirm = false" (keydown.escape)="$event.stopPropagation()">
<p>You are about to process LFA payment for <b>{{ rows.length }}</b> employee(s). This will create a new payment batch.</p>
<table class="lfa-confirm">
<tbody>
<tr><td>Batch ID</td><td>{{ info ? info.nextBatchNumber : '' }}</td></tr>
<tr><td>Payment Date</td><td>{{ paymentDate | date: 'dd-MMM-yyyy' }}</td></tr>
<tr><td>Total LFA Amount</td><td>BDT {{ 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)="process()">Confirm &amp; Process</button>
</kendo-dialog-actions>
</kendo-dialog>
</div>
}
<!-- validation errors of the upload / calculation / process -->
@if (showIssues) {
<div class="blur-background">
<kendo-dialog title="Error List ({{ issues.length }})" [width]="900" maxHeight="90vh" (close)="showIssues = false" (keydown.escape)="$event.stopPropagation()">
<kendo-grid #issueGrid="kendoGrid" [kendoGridBinding]="issues" [pageable]="true" [pageSize]="20" [sortable]="true" [resizable]="true">
<kendo-grid-column field="rowNo" title="Excel Row" [width]="90">
<ng-template kendoGridCellTemplate let-dataItem>{{ dataItem.rowNo > 0 ? dataItem.rowNo : 'File' }}</ng-template>
</kendo-grid-column>
<kendo-grid-column field="employeeNo" title="Employee ID" [width]="120"></kendo-grid-column>
<kendo-grid-column field="employeeName" title="Name" [width]="200"></kendo-grid-column>
<kendo-grid-column field="message" title="Error"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>No errors.</ng-template>
<kendo-grid-excel fileName="LFA-Payment-Errors.xlsx" [fetchData]="allIssues"></kendo-grid-excel>
</kendo-grid>
<kendo-dialog-actions>
<button class="gh-excel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']" (click)="issueGrid.saveAsExcel()">Export</button>
<button class="gh-cancel" kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['cancel']" (click)="showIssues = false">Close</button>
</kendo-dialog-actions>
</kendo-dialog>
</div>
}

View File

@ -0,0 +1,126 @@
/* LFA Payment: layout only; colours are the theme's --gh-* variables */
.lfa-month {
padding: 0 4px 8px;
color: var(--gh-lk);
}
.lfa-tab {
display: flex;
flex-direction: column;
gap: 14px;
padding: 8px 2px;
}
.lfa-toolbar {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
}
.lfa-field {
display: flex;
flex-direction: column;
gap: 4px;
width: 180px;
label {
font-size: 12px;
font-weight: 600;
color: var(--gh-muted);
}
}
.lfa-field--wide {
width: 280px;
}
.lfa-field--remarks {
width: 360px;
}
.lfa-required {
color: var(--gh-dn);
}
.lfa-spacer {
flex: 1 1 auto;
}
.lfa-upload {
display: flex;
flex: 1 1 520px;
align-items: center;
gap: 6px;
}
.lfa-upload__file {
flex: 1 1 auto;
min-width: 0;
max-width: 520px;
}
.lfa-info,
.lfa-note {
font-size: 12px;
color: var(--gh-muted);
}
.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-issues__head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
font-weight: 600;
color: var(--gh-dn);
}
.lfa-right {
text-align: right;
}
.lfa-confirm {
width: 100%;
td {
padding: 4px 0;
}
td:last-child {
text-align: right;
font-weight: 600;
}
}
@media (max-width: 640px) {
.lfa-field,
.lfa-field--wide,
.lfa-field--remarks {
width: 100%;
}
}

View File

@ -0,0 +1,433 @@
import { Component, ElementRef, OnInit, ViewChild, ChangeDetectionStrategy } from '@angular/core';
import * as fileSaver from 'file-saver';
import { ExcelExportData } from '@progress/kendo-angular-excel-export';
import { Observable } from 'rxjs';
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 {
LFAPaymentHistory, LFAPaymentInfo, LFAPaymentInput, LFAPaymentIssue,
LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentRow
} from '../../_models/Payroll/lfaPayment';
/**
* LFA Payment: LFA Request (design only for now), New LFA Payment (Excel upload → calculated grid → Process
* Payment) and Payment History. Every amount comes from the server, which calculates again on process.
*/
@Component({
selector: 'app-lfa-payment',
templateUrl: './lfa-payment.component.html',
styleUrls: ['./lfa-payment.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class LfaPaymentComponent implements OnInit {
@ViewChild('fileInput', { static: false }) fileInput: ElementRef<HTMLInputElement>;
readonly maxFileSizeMB = 10;
readonly allDepartments = 'All departments';
selectedTab = 0;
info: LFAPaymentInfo = null;
// ── LFA Request (design only; no data yet) ──
requests: any[] = [];
requestSearch = '';
requestDepartment = this.allDepartments;
requestFrom: Date = null;
requestTo: Date = null;
// ── New LFA Payment ──
paymentDate: Date = this.today();
remarks = '';
selectedFile: File = null; // picked, not uploaded yet
uploadedFile: File = null; // the file the list was read from
rows: LFAPaymentRow[] = [];
issues: LFAPaymentIssue[] = [];
totalBasic = 0;
totalAmount = 0;
isBusy = false;
showConfirm = false;
showIssues = false;
/** Employees taken out of the list; they stay out when the file is calculated again. */
private removedEmployeeNos: string[] = [];
// ── Payment History ──
historyFrom: Date = new Date(new Date().getFullYear(), 0, 1);
historyTo: Date = this.today();
historySearch = '';
historyDepartment = this.allDepartments;
historyDepartments = [this.allDepartments];
history: LFAPaymentHistory[] = [];
historyRows: LFAPaymentHistory[] = [];
historyTotalBasic = 0;
historyTotalAmount = 0;
historySummary = '';
constructor(public apiService: ApiService,
public notificationService: HRMNotificationService,
public loadingPanel: loadingPanelService,
private lfaService: LFAService) {
this.apiService.selectedMenuName = 'LFA Payment';
}
ngOnInit() {
this.loadInfo();
}
private loadInfo() {
this.start();
this.lfaService.getPaymentInfo().subscribe({
next: (resp) => {
this.stop();
this.info = resp;
},
error: (err) => this.fail(err, 'Could not read the current salary month.')
});
}
onTabSelect(index: number) {
this.selectedTab = index;
this.selectedFile = null; // the file input is created again with its tab
if (index === 2) {
this.loadHistory();
}
}
// ── New LFA Payment: upload and calculate ───────────────────────
downloadTemplate() {
this.start();
this.lfaService.downloadTemplate().subscribe({
next: (file) => {
this.stop();
fileSaver.saveAs(file, 'LFA-Payment-Template.xlsx');
},
error: (err) => this.fail(err, 'Could not download the template.')
});
}
/** The same file can be picked again after a correction. */
clearSelectedFile() {
this.selectedFile = null;
if (this.fileInput) {
this.fileInput.nativeElement.value = '';
}
}
selectFile(event: Event) {
const input = event.target as HTMLInputElement;
this.selectedFile = input.files && input.files.length > 0 ? input.files[0] : null;
}
uploadFile() {
if (!this.paymentDate) {
this.notificationService.showWarning('Please select the Payment Date first.');
return;
}
if (!this.selectedFile) {
this.notificationService.showWarning('Please choose a file first.');
return;
}
this.upload(this.selectedFile);
}
private upload(file: File) {
if (!file.name.toLowerCase().endsWith('.xlsx')) {
this.notificationService.showError('Only .xlsx files are allowed. Please use the downloaded template.');
return;
}
if (file.size > this.maxFileSizeMB * 1024 * 1024) {
this.notificationService.showError('The file is larger than ' + this.maxFileSizeMB + ' MB.');
return;
}
this.uploadedFile = file;
this.removedEmployeeNos = [];
this.calculate(true);
}
/** The Payment Date decides who has completed 6 months. */
onPaymentInfoChange() {
if (this.paymentDate && (this.uploadedFile || this.rows.length > 0)) {
this.calculate(false);
}
}
private calculate(isUpload: boolean) {
const date = this.dateText(this.paymentDate);
const call: Observable<LFAPaymentReadResult> = this.uploadedFile
? this.lfaService.readUpload(this.uploadedFile, date)
: this.lfaService.calculatePayment(this.request());
this.start();
call.subscribe({
next: (resp) => {
this.stop();
this.applyResult(resp);
if (isUpload) {
this.showUploadMessage();
}
},
error: (err) => {
this.setRows([]);
this.issues = [];
this.fail(err, 'Could not calculate the LFA. Please upload the file again.');
}
});
}
private showUploadMessage() {
// 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.');
}
}
private applyResult(result: LFAPaymentReadResult) {
this.issues = (result.issues || []).filter(x => !this.isRemoved(x.employeeNo));
this.showIssues = this.issues.length > 0; // every validation problem is listed in the error dialog
this.setRows((result.rows || []).filter(x => !this.isRemoved(x.employeeNo)).map(x => ({
...x,
joiningDate: this.toDate(x.joiningDate),
confirmationDate: this.toDate(x.confirmationDate),
paymentDate: this.toDate(x.paymentDate)
})));
}
private setRows(rows: LFAPaymentRow[]) {
this.rows = rows;
this.totalBasic = this.sum(rows, x => x.basicSalary);
this.totalAmount = this.sum(rows, x => x.amount);
}
removeRow(row: LFAPaymentRow) {
this.removedEmployeeNos.push(row.employeeNo);
this.setRows(this.rows.filter(x => x !== row));
}
private isRemoved(employeeNo: string): boolean {
return this.removedEmployeeNos.indexOf(employeeNo) >= 0;
}
clear() {
if (this.rows.length === 0 && this.issues.length === 0) {
this.resetPayment();
return;
}
this.notificationService.showActiveConfirm('Confirmation', 'Clear the payment list?').then((isConfirmed) => {
if (isConfirmed) {
this.resetPayment();
}
});
}
private resetPayment() {
this.clearSelectedFile();
this.uploadedFile = null;
this.removedEmployeeNos = [];
this.issues = [];
this.showIssues = false;
this.remarks = '';
this.setRows([]);
}
allPaymentRows = (): ExcelExportData => ({ data: this.rows });
allIssues = (): ExcelExportData => ({ data: this.issues });
// ── New LFA Payment: process ────────────────────────────────────
confirmProcess() {
if (!this.paymentDate) {
this.notificationService.showWarning('Payment Date is required.');
return;
}
if (this.rows.length === 0) {
this.notificationService.showWarning('Add at least one employee.');
return;
}
this.showConfirm = true;
}
process() {
if (this.isBusy) {
return;
}
this.start();
this.lfaService.processPayment(this.request()).subscribe({
next: (resp: LFAPaymentProcessResult) => {
this.stop();
this.showConfirm = false;
if (!resp.saved) {
if (resp.validation) {
this.applyResult(resp.validation);
}
this.notificationService.showError(resp.message);
return;
}
this.notificationService.showSuccess(resp.message);
this.resetPayment();
this.includeInHistory(this.paymentDate);
this.loadInfo();
this.onTabSelect(2);
},
error: (err) => {
this.showConfirm = false;
this.fail(err, 'Nothing was saved. Please try again.');
}
});
}
private request(): LFAPaymentRequest {
return {
paymentDate: this.dateText(this.paymentDate),
remarks: this.remarks,
rows: this.rows.map((x): LFAPaymentInput => ({
rowNo: x.rowNo,
employeeNo: x.employeeNo
})),
expectedTotal: this.totalAmount
};
}
// ── Payment History ─────────────────────────────────────────────
loadHistory() {
if (!this.historyFrom || !this.historyTo) {
this.notificationService.showWarning('Start Date and End Date are required.');
return;
}
if (this.historyFrom > this.historyTo) {
this.notificationService.showWarning('Start Date cannot be after End Date.');
return;
}
this.start();
this.lfaService.getPaymentHistory(this.dateText(this.historyFrom), this.dateText(this.historyTo)).subscribe({
next: (resp) => {
this.stop();
this.history = (resp || []).map(x => ({
...x,
paymentDate: this.toDate(x.paymentDate),
joiningDate: this.toDate(x.joiningDate)
}));
this.historyDepartments = [this.allDepartments].concat(
Array.from(new Set(this.history.map(x => x.departmentName).filter(x => !!x))).sort());
if (this.historyDepartments.indexOf(this.historyDepartment) < 0) {
this.historyDepartment = this.allDepartments;
}
this.filterHistory();
},
error: (err) => this.fail(err, 'Could not load the payment history.')
});
}
filterHistory() {
const search = (this.historySearch || '').trim().toLowerCase();
this.historyRows = this.history.filter(x =>
(this.historyDepartment === this.allDepartments || x.departmentName === this.historyDepartment)
&& (!search || [x.batchNumber, x.employeeNo, x.name, x.designationName, x.departmentName]
.some(v => (v || '').toLowerCase().indexOf(search) >= 0)));
this.historyTotalBasic = this.sum(this.historyRows, x => x.basicSalary);
this.historyTotalAmount = this.sum(this.historyRows, x => x.amount);
this.historySummary = 'Total ' + this.historyRows.length + ' records · '
+ new Set(this.historyRows.map(x => x.batchNumber)).size + ' batch(es)';
}
allHistoryRows = (): ExcelExportData => ({ data: this.historyRows });
printHistory() {
if (this.historyRows.length === 0) {
this.notificationService.showWarning('Nothing to print.');
return;
}
const w = window.open('', '_blank');
if (!w) {
this.notificationService.showWarning('Please allow pop-ups to print.');
return;
}
const money = (n: number) => this.money(n);
const cells = (values: any[], tag: string) => values.map(v => '<' + tag + '>' + this.escape(v) + '</' + tag + '>').join('');
const body = this.historyRows.map(x => '<tr>' + cells([x.batchNumber, this.displayDate(x.paymentDate), x.employeeNo, x.name,
x.designationName, x.departmentName, this.displayDate(x.joiningDate), money(x.basicSalary), money(x.amount)], 'td') + '</tr>').join('');
w.document.write('<html><head><title>LFA Payment History</title><style>body{font-family:Arial;font-size:12px}'
+ 'table{border-collapse:collapse;width:100%}th,td{border:1px solid #999;padding:4px;text-align:left}</style></head><body>'
+ '<h3>LFA Payment History (' + this.displayDate(this.historyFrom) + ' - ' + this.displayDate(this.historyTo) + ')</h3><table><thead><tr>'
+ cells(['Batch ID', 'Payment Date', 'Employee ID', 'Name', 'Designation', 'Department', 'Joining Date', 'Basic Salary',
'LFA Amount'], 'th')
+ '</tr></thead><tbody>' + body + '</tbody></table><p>' + this.escape(this.historySummary) + ' · LFA Amount '
+ money(this.historyTotalAmount) + '</p></body></html>');
w.document.close();
w.focus();
w.print();
}
/** A batch just processed must be inside the range the history shows. */
private includeInHistory(date: Date) {
if (date < this.historyFrom) {
this.historyFrom = date;
}
if (date > this.historyTo) {
this.historyTo = date;
}
}
// ── LFA Request (design only) ───────────────────────────────────
resetRequestFilter() {
this.requestSearch = '';
this.requestDepartment = this.allDepartments;
this.requestFrom = null;
this.requestTo = null;
}
// ── Helpers ─────────────────────────────────────────────────────
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();
// httpPostBlob gives the server's text itself, the other calls an HttpErrorResponse
const text = typeof err === 'string' ? err : err && typeof err.error === 'string' ? err.error : '';
this.notificationService.showError(text || fallback);
}
private today(): Date {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
}
private toDate(value: any): Date {
return value ? new Date(value) : null;
}
/** yyyy-MM-dd of the picked day, whatever the browser's time zone. */
private dateText(date: Date): string {
return date ? this.apiService.datepipe.transform(date, 'yyyy-MM-dd') : null;
}
private displayDate(date: Date): string {
return date ? this.apiService.datepipe.transform(date, 'dd-MMM-yyyy') : '';
}
private money(value: number): string {
return (value || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
private escape(value: any): string {
return String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
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

@ -0,0 +1,22 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from '../_guards/auth.guard';
import { LfaPaymentComponent } from './lfa-payment/lfa-payment.component';
import { LfaPaymentUndoComponent } from './lfa-payment-undo/lfa-payment-undo.component';
import { LfaPaymentApprovalComponent } from './lfa-payment-approval/lfa-payment-approval.component';
import { ReportViewerComponent } from '../reports/report-viewer/report-viewer.component';
export const routes: Routes = [
{ path: 'lfa-payment', component: LfaPaymentComponent, canActivate: [AuthGuard] },
{ path: 'lfa-payment-undo', component: LfaPaymentUndoComponent, canActivate: [AuthGuard] },
{ path: 'lfa-payment-approval', component: LfaPaymentApprovalComponent, canActivate: [AuthGuard] },
// LFA Bank Advice runs on the common report viewer, as Salary Bank Advice (report-viewer/36) does;
// the viewer recognises it by the last URL segment ('lfa-bank-advice').
{ path: 'lfa-bank-advice', component: ReportViewerComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PayrollLfaRoutingModule { }

View File

@ -0,0 +1,41 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CardModule } from '@progress/kendo-angular-layout';
import { ExcelModule, GridModule } from '@progress/kendo-angular-grid';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DropDownListModule } from '@progress/kendo-angular-dropdowns';
import { DatePickerModule } from '@progress/kendo-angular-dateinputs';
import { TextBoxModule } from '@progress/kendo-angular-inputs';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { PayrollLfaRoutingModule } from './payroll-lfa-routing.module';
import { LoadingPanelModule } from '../hrm-loding panel/loading-panel.module';
import { TabViewCompatModule } from '../custom-components/tab-view-compat/tab-view-compat';
import { LfaPaymentComponent } from './lfa-payment/lfa-payment.component';
import { LfaPaymentUndoComponent } from './lfa-payment-undo/lfa-payment-undo.component';
import { LfaPaymentApprovalComponent } from './lfa-payment-approval/lfa-payment-approval.component';
@NgModule({
declarations: [
LfaPaymentComponent,
LfaPaymentUndoComponent,
LfaPaymentApprovalComponent
],
imports: [
CommonModule,
PayrollLfaRoutingModule,
FormsModule,
LoadingPanelModule,
CardModule,
TabViewCompatModule,
GridModule,
ExcelModule,
ButtonsModule,
DropDownListModule,
DatePickerModule,
TextBoxModule,
DialogsModule
]
})
export class PayrollLfaModule { }

View File

@ -193,11 +193,35 @@
kendoCheckBox
/>
</div>
<div class="col-12 lg:col-10" style="margin: auto">
<!-- with PF Percentage the label takes the left half, so PF Percentage sits beside it (under Effect Date) -->
<div class="col-12" [ngClass]="isPFPercentage == true ? 'lg:col-4' : 'lg:col-10'" style="margin: auto">
<label for="chkConfirmed">Is Confirmed</label>
</div>
}
@if (this.isPFPercentage == true) {
<div class="col-12 lg:col-1" style="margin: auto">
<label for="txtPFPercentage">PF Percentage</label>
</div>
<div class="col-12 lg:col-1" style="margin: auto" align="center">:</div>
<div class="col-12 lg:col-4">
<kendo-numerictextbox
id="txtPFPercentage"
[min]="0"
[max]="100"
[decimals]="2"
[format]="'n2'"
[(ngModel)]="_pfPercentage"
(valueChange)="SetFromDescription()"
style="width: 100%"
>
</kendo-numerictextbox>
</div>
@if (this.isShowConfirmed != true) {
<div class="col-12 lg:col-6"></div>
}
}
<!-- <ng-container *ngIf="this.isGrade == true && this.showCompanyProvidedCar == true">
<div class="col-12 lg:col-1" ></div>
<div class="col-12 lg:col-1" > <input type="checkbox" kendoCheckBox /></div>

View File

@ -99,6 +99,10 @@ export class LifeCycleEntryComponent implements OnInit {
public isShowConfirmed: boolean = false;
public isPFMember: boolean = false;
public isPFMemberDiscontinue: boolean = false;
public isPFPercentage: boolean = false;
public _pfPercentage: number = null;
// Logic XML confirmation/autopfmembership: confirming also makes the employee a Live PF member
public isAutoPFMembership: boolean = false;
public isCostCenter: boolean = false;
public isshoDistinueDate: boolean = false;
public isOrganogram: boolean = false;
@ -142,6 +146,10 @@ export class LifeCycleEntryComponent implements OnInit {
this.lifecycleService.GetByUserID().subscribe(
(resp: any) => {
this._employeeStatus = resp;
// events in alphabetical order
if (this._employeeStatus) {
this._employeeStatus.sort((a, b) => (a.description || '').localeCompare(b.description || ''));
}
},
(err: any) => {
console.log(err);
@ -150,6 +158,14 @@ export class LifeCycleEntryComponent implements OnInit {
}
);
this.lifecycleService.IsAutoPFMembership().subscribe(
(resp: any) => {
this.isAutoPFMembership = resp == true;
},
(err: any) => {
console.log(err);
}
);
}
@ -199,6 +215,8 @@ export class LifeCycleEntryComponent implements OnInit {
this.isShowConfirmed = false;
this.isPFMember = false;
this.isPFMemberDiscontinue = false;
this.isPFPercentage = false;
this._pfPercentage = null;
this.isCostCenter = false;
this.isPayrollType = false;
this.isComplain = false;
@ -329,6 +347,16 @@ export class LifeCycleEntryComponent implements OnInit {
}
});
// PF membership needs the employee's own PF %: the event makes the employee a Live PF member
// either through its PF_Member component, or through Confirm when autopfmembership is on
const hasPFMember = item.employeeStatusComponents.some(c => c.componentType == EnumLifeCycleComponent.PF_Member);
const hasConfirm = item.employeeStatusComponents.some(c => c.componentType == EnumLifeCycleComponent.Confirm);
if (hasPFMember || (hasConfirm && this.isAutoPFMembership == true)) {
this.isPFPercentage = true;
if (this.isEditLifeCycle) {
this._pfPercentage = this._empLifeCycle.pfPercentage;
}
}
if (!this.isEditLifeCycle) {
this._sDescription = item.description;
}
@ -662,6 +690,10 @@ export class LifeCycleEntryComponent implements OnInit {
this._sDescription += ' To ' + this._empLifeCycle.basicSalary;
}
if (this.isPFPercentage == true && this._pfPercentage != undefined && this._pfPercentage > 0) {
this._sDescription += '; PF Percentage ' + this._pfPercentage + '%';
}
this._empLifeCycle.HREmployee = new HrEmployee();
this._empLifeCycle.HREmployee.gender = this._employee.gender;
this._empLifeCycle.HREmployee.maritalStatus = this._employee.maritalStatus;
@ -857,6 +889,10 @@ export class LifeCycleEntryComponent implements OnInit {
this.notificationService.showWarning('Please check cofirmation');
bValid = false;
}
if (this.isPFPercentage == true && (this._pfPercentage == undefined || this._pfPercentage <= 0 || this._pfPercentage > 100)) {
this.notificationService.showWarning('Please enter PF Percentage (greater than 0 and up to 100).');
bValid = false;
}
return bValid;
}
@ -929,6 +965,7 @@ export class LifeCycleEntryComponent implements OnInit {
if (this.isPFMemberDiscontinue == true) {
this._empLifeCycle.pfMemberType = EnumPFMembershipType.DiscontinuedfromPayroll;
}
this._empLifeCycle.pfPercentage = this.isPFPercentage == true ? this._pfPercentage : null;
this._empLifeCycle.statusDetailID = this._selectedEventID;
const evt: EmployeeStatus = this._employeeStatus.find(x => x.id === this._selectedEventID);

View File

@ -39,6 +39,7 @@ import { User } from '../../_models/Authentication/user';
import { AuthService } from '../../_services/auth/auth.service';
import { saveAs } from 'file-saver';
import { SalaryService } from '../../_services/payroll/salary.service';
import { LFAService } from '../../_services/payroll/lfa.service';
import { LoanIssue } from 'src/app/_models/Payroll/Loan/loanIssue';
import { Bank } from 'src/app/_models/Basic/bank';
import { formatDate } from '@progress/kendo-angular-intl';
@ -73,6 +74,7 @@ export class ReportViewerComponent implements OnInit {
public loanService: LoanService,
public taxService: TaxService,
public salaryService: SalaryService,
public lfaService: LFAService,
public leaveYearService: LeaveService,
public router: Router, public loadingPanel: loadingPanelService,
public notificationService: HRMNotificationService,
@ -1252,6 +1254,17 @@ export class ReportViewerComponent implements OnInit {
this.hiddenFromMonth = true;
this.hiddenToMonth = true;
}
if (this.reportType === 'lfa-bank-advice') {
// LFA Bank Advice (/payroll-lfa/lfa-bank-advice): Item = an approved LFA payment batch,
// Search lists that batch's employees, Preview/Export renders LFABankAdvice.rdlc.
this.hiddenItemDDL = true;
this.hiddenExport = true;
this.itemName = 'LFA Batch';
this.reportDropdownDefaultName = 'Select LFA Batch...';
this.PDFTitle = 'LFA Bank Advice';
this.apiService.selectedMenuName = 'LFA Bank Advice';
this.loadLFABankAdviceBatches();
}
if (!this.multiselect) {
this.selectableSettings = {
checkboxOnly: true,
@ -1277,6 +1290,51 @@ export class ReportViewerComponent implements OnInit {
}
);
}
/** LFA Bank Advice: the approved LFA payment batches of the payroll type. */
loadLFABankAdviceBatches() {
this.loadingPanel.ShowLoadingPanel = true;
this.lfaService.getBankAdviceBatches().subscribe(
(resp) => {
(resp || []).forEach(x => {
const paymentDate = x.paymentDate ? formatDate(new Date(x.paymentDate), 'dd MMM yyyy') : '';
this.items.push(new Item(x.lfaPaymentID, x.batchNumber + ' (' + x.headCount + ' emp)'));
});
},
(err) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showError(err.error);
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
});
}
/** LFA Bank Advice: Search lists the employees of the selected batch. */
searchLFABatchEmployees() {
if (this.selectedItemid == undefined || this.selectedItemid == 0) {
this.notificationService.showWarning('Please select an LFA Batch.');
return;
}
this.taggedSelection = [];
this.searchEmployees = [];
this.skip = 0;
this.loadData();
this.loadingPanel.ShowLoadingPanel = true;
this.lfaService.getBatchEmployees(this.selectedItemid).subscribe(
(resp) => {
this.searchEmployees = (resp || [])
.filter(x => x.amount > 0)
.map(x => <SearchEmployee><any>{ employeeID: x.employeeID, employeeNo: x.employeeNo, name: x.name });
},
(err) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showError(err.error);
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.loadData();
this.selectAllState = 'unchecked';
});
}
loadEncashmentReportType() {
this.reportItems.push(new Item(1, 'EmployeeWise Encashment'));
this.reportItems.push(new Item(2, 'Bank Advice'));
@ -1963,6 +2021,50 @@ export class ReportViewerComponent implements OnInit {
// );
// }
else if (this.reportType === 'lfa-bank-advice') {
// the route is not numeric, so the report id is sent explicitly; itemid = LFAPaymentID
if (this.selectedItemid == undefined || this.selectedItemid == 0) {
this.notificationService.showWarning('Please select an LFA Batch.');
return;
}
const data = {
reportid: EnumReportType.LFABankAdvice,
itemid: this.selectedItemid,
bankId: (this.selectedBank !== undefined && this.selectedBank.id !== undefined) ? this.selectedBank.id : 0,
selectedReport: '',
empIds: this.empIds,
reportType: reportType,
fromDate: undefined,
toDate: undefined,
locationIds: ''
};
this.loadingPanel.ShowLoadingPanel = true;
if (reportType === 'PDF')
this.showPopUp = true;
this.reportService.getCommonReportData(data).subscribe(
(resp: any) => {
if (resp == null || resp == undefined || resp == "") {
this.closeForm();
this.notificationService.showWarning("No data found");
} else if (reportType === 'PDF') {
this.src = URL.createObjectURL(this.b64toBlob(resp, 'application/pdf', 1024));
var element = <HTMLIFrameElement>(document.getElementById("pdf-viewer-report"));
element.src = this.src;
} else if (reportType === 'EXCELOPENXML') {
this.downloadFile(resp);
}
},
(err) => {
this.closeForm();
this.notificationService.showError(err.error);
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
}
);
}
else {
// ;
let bankId = 0;
@ -2286,6 +2388,10 @@ export class ReportViewerComponent implements OnInit {
search() {
// ;
if (this.reportType === 'lfa-bank-advice') {
this.searchLFABatchEmployees();
return;
}
const srcManager: SearchManager = new SearchManager(EnumSearchFrom.Employee);
srcManager.SearchFrom = this.SearchFrom;
srcManager.IsNegletWithheld = this.IsNegletWithheld;
@ -2547,6 +2653,14 @@ export class ReportViewerComponent implements OnInit {
public onItemChange(data: any) {
data;
this.selectedItemid;
if (this.reportType === 'lfa-bank-advice') {
// another LFA batch: the listed employees belong to the old one
this.taggedSelection = [];
this.searchEmployees = [];
this.skip = 0;
this.selectAllState = 'unchecked';
this.loadData();
}
//;
}
}

View File

@ -366,6 +366,9 @@ namespace HRM.UI.Configuration.DI
services.AddTransient<IHistorySalaryMonthlyService, HistorySalaryMonthlyService>();
services.AddTransient<ISalaryMasterBulkUploadService, SalaryMasterBulkUploadService>();
//LFA
services.AddTransient<ILFAPaymentService, LFAPaymentService>();
//Fund
services.AddTransient<IFundTypeService, FundTypeService>();
services.AddTransient<IFundBankService, FundBankService>();

View File

@ -25,13 +25,15 @@ namespace HRM.UI.Controllers.Payroll
private readonly IEmployeePhotoBulkUploadService _employeePhotoBulkUploadService;
private readonly ICacheManager _cashManager;
private readonly IBonusProcessService _bonusProcessService;
private readonly ILFAPaymentService _lfaPaymentService;
public DataUploadController(IDataUploadColumnDefinition columnDefination,
IEmployeeBulkUploadService employeeBulkUploadService,
ISalaryMasterBulkUploadService salaryMasterBulkUploadService,
IEmployeePhotoBulkUploadService employeePhotoBulkUploadService,
ICacheManager cashManager,
IBonusProcessService bonusProcessService)
IBonusProcessService bonusProcessService,
ILFAPaymentService lfaPaymentService)
{
this._columnDefination = columnDefination;
this._employeeBulkUploadService = employeeBulkUploadService;
@ -39,6 +41,7 @@ namespace HRM.UI.Controllers.Payroll
this._employeePhotoBulkUploadService = employeePhotoBulkUploadService;
this._cashManager = cashManager;
this._bonusProcessService = bonusProcessService;
this._lfaPaymentService = lfaPaymentService;
}
// loan
@ -586,6 +589,60 @@ namespace HRM.UI.Controllers.Payroll
#endregion
#region LFA Payment Upload
/// <summary>The empty LFA payment workbook: Employee ID and Name.</summary>
[HttpGet("lfa-payment-upload-template")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult GetLFAPaymentUploadTemplate()
{
try
{
return File(this._lfaPaymentService.GetUploadTemplate(),
LFAPaymentUploadTemplate.ContentType, LFAPaymentUploadTemplate.FileName);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>
/// Reads a filled LFA payment workbook (multipart form: first file, plus "paymentDate")
/// and returns the calculated employees and every problem. Nothing is saved.
/// </summary>
[HttpPost("lfa-payment-upload-read")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult ReadLFAPaymentUpload()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment.");
}
IFormFile file = Request.Form.Files.Count > 0 ? Request.Form.Files[0] : null;
DateTime paymentDate;
if (!DateTime.TryParse(Request.Form["paymentDate"].FirstOrDefault(), out paymentDate))
{
return BadRequest("Payment Date is required.");
}
try
{
using (Stream stream = file == null ? null : file.OpenReadStream())
{
return Ok(this._lfaPaymentService.ReadUpload(stream, file == null ? null : file.FileName,
file == null ? 0 : file.Length, paymentDate, this.CurrentPayrollTypeID(0)));
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
#endregion
/// <summary>The "salaryMonth" form field (the month picked on the page) as the last date of that month.</summary>
private bool TryGetPostedSalaryMonth(out DateTime salaryMonth)
{

View File

@ -542,6 +542,22 @@ namespace HRM.UI.Controllers
return Ok();
}
// Logic XML confirmation/autopfmembership -- the Life-Cycle entry screen shows
// PF Percentage for a confirmation event when it is on.
[HttpGet]
[Route("IsAutoPFMembership")]
public ActionResult IsAutoPFMembership()
{
try
{
return Ok(_lifeCycleService.IsAutoPFMembership());
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// Users allowed on one payroll type (UserAccessType) -- the Life-Cycle Event
// entry screen picks its approvers from this list.
[HttpGet]

View File

@ -0,0 +1,322 @@
using System;
using HRM.BO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HRM.UI.Controllers.Payroll
{
/// <summary>
/// Core Payroll > LFA. The Excel template and upload are in DataUploadController, with every other uploader.
/// </summary>
[Route("api/lfa")]
[Authorize]
[ApiController]
public class LFAController : ControllerBase
{
private readonly ILFAPaymentService _lfaPaymentService;
public LFAController(ILFAPaymentService lfaPaymentService)
{
this._lfaPaymentService = lfaPaymentService;
}
/// <summary>The current salary month and the next batch number.</summary>
[HttpGet("getPaymentInfo")]
public ActionResult GetPaymentInfo()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetInfo(currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>Calculates the rows again; nothing is saved.</summary>
[HttpPost("calculatePayment")]
public ActionResult CalculatePayment(LFAPaymentRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.Calculate(request, currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>Saves the rows as a new batch, all or nothing. The payroll type and user come from the token.</summary>
[HttpPost("processPayment")]
public ActionResult ProcessPayment(LFAPaymentRequest request)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.Process(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet("getPaymentHistory/{fromDate}/{toDate}")]
public ActionResult GetPaymentHistory(DateTime fromDate, DateTime toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetHistory(fromDate, toDate, currentUser.PayrollTypeID.GetValueOrDefault()));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// ── 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);
}
}
/// <summary>LFA Bank Advice: the approved batches of the payroll type.</summary>
[HttpGet("getBankAdviceBatches")]
public ActionResult GetBankAdviceBatches()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return NotAllowed();
}
try
{
return Ok(this._lfaPaymentService.GetBankAdviceBatches(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);
}
}
// ── 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.");
}
}
}

View File

@ -750,6 +750,10 @@ namespace HRM.UI.Controllers.Report
rptLeave = new rptLeave();
bytes = rptLeave.ShowLeaveEncashmentReports(sEmpIDs, itemid, selectedReport, payrollTypeId, reportType);
break;
case EnumReportType.LFABankAdvice:
// itemid = LFAPaymentID of the selected (approved) LFA batch
bytes = new rptLFABankAdvice().ShowLFABankAdvice(itemid, sEmpIDs, bankId, payrollTypeId, reportType);
break;
case EnumReportType.CCWiseLeaveEncashmentReturn:
rptLeave = new rptLeave();
bytes = rptLeave.ShowCCWiseLeaveEncashmentReturn(itemid, payrollTypeId, reportType);

162
LFA_DB_Changes.sql Normal file
View File

@ -0,0 +1,162 @@
/* =====================================================================
LFA_DB_Changes.sql
Leave Fare Assistance (Core Payroll > LFA). Three tables:
dbo.LFARequest who asked for LFA, for which leave (LFA Request tab)
dbo.LFAPayment one payment batch (like SalaryProcess)
dbo.LFAPaymentDetail one employee of a batch (like SalaryMonthly)
- Part 0 DROPS the three tables, Parts 1-3 create them again. The drop is
refused, and nothing runs, when any of the tables already holds rows.
- LFAYear is a DATETIME in all three tables: the last date of the Payment
Date's month (paid 08-Dec-2026 = 31-Dec-2026), as SalaryMonth is the last
date of its month. The LFA is for the calendar year of that date, so
"once in a calendar year" is enforced on YEAR(LFAYear) (LFACalendarYear).
- IDs are generated by the application (tc.GenerateID), no IDENTITY.
- A detail row is a snapshot: grade, department, bank account and basic are
kept as they were when the batch was processed.
- Columns that point to existing tables (EMPLOYEE, DEPARTMENT, GRADES, CRG,
BRANCHES, LEAVEENTRY ...) have no foreign key, as in Calendar_DB_Changes.sql.
Run order: once per database, together with the LFA code.
===================================================================== */
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
/* ---------- 0. Drop (child table first) ---------- */
IF EXISTS (SELECT 1 FROM sys.partitions
WHERE object_id IN (OBJECT_ID(N'dbo.LFAPaymentDetail', N'U'), OBJECT_ID(N'dbo.LFAPayment', N'U'), OBJECT_ID(N'dbo.LFARequest', N'U'))
AND index_id IN (0, 1) AND rows > 0)
BEGIN
RAISERROR('The LFA tables hold data. Nothing was dropped or created. Back up and clear them first.', 16, 1);
SET NOEXEC ON; -- skips the rest of this script
END
GO
DROP TABLE IF EXISTS dbo.LFAPaymentDetail;
DROP TABLE IF EXISTS dbo.LFAPayment;
DROP TABLE IF EXISTS dbo.LFARequest;
GO
/* ---------- 1. dbo.LFARequest ---------- */
CREATE TABLE dbo.LFARequest (
LFARequestID INT NOT NULL,
PayrollTypeID INT NOT NULL,
EmployeeID INT NOT NULL,
LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for
LeaveEntryID INT NULL, -- LEAVEENTRY.TRANID of the LFA leave
RequestDate DATETIME NOT NULL,
LeaveFromDate DATETIME NOT NULL, -- LFA Start Date
LeaveToDate DATETIME NOT NULL, -- LFA End Date
LeaveDays DECIMAL(9, 2) NOT NULL,
Remarks NVARCHAR(500) NULL,
Status TINYINT NOT NULL CONSTRAINT DF_LFARequest_Status DEFAULT (1), -- 1 Pending, 2 Approved, 3 Rejected, 4 Cancelled
WFStatus INT NULL, -- enumwfStatus; NULL = not submitted
CreatedBy INT NOT NULL,
CreationDate DATETIME NOT NULL,
ModifiedBy INT NULL,
ModifiedDate DATETIME NULL,
CONSTRAINT PK_LFARequest PRIMARY KEY (LFARequestID),
CONSTRAINT CK_LFARequest_Dates CHECK (LeaveToDate >= LeaveFromDate),
CONSTRAINT CK_LFARequest_Status CHECK (Status IN (1, 2, 3, 4))
);
GO
/* one open or approved request per employee per calendar year */
CREATE UNIQUE INDEX UX_LFARequest_EmployeeYear ON dbo.LFARequest (EmployeeID, LFAYear) WHERE Status IN (1, 2);
GO
/* LFA Request tab: approved requests of a payroll type */
CREATE INDEX IX_LFARequest_List ON dbo.LFARequest (PayrollTypeID, Status, LeaveFromDate);
GO
/* ---------- 2. dbo.LFAPayment ---------- */
CREATE TABLE dbo.LFAPayment (
LFAPaymentID INT NOT NULL,
BatchNumber VARCHAR(30) NOT NULL, -- LFA-2026-001
PayrollTypeID INT NOT NULL,
SalaryMonth DATETIME NOT NULL, -- last date of PAYROLLTYPE.NEXTPAYPROCESSDATE's month
LFAYear DATETIME NOT NULL, -- last date of PaymentDate's month
PaymentDate DATETIME NOT NULL,
Remarks NVARCHAR(500) NULL,
IsTaxUpdated BIT NOT NULL CONSTRAINT DF_LFAPayment_IsTaxUpdated DEFAULT (0), -- 1 = the batch is already in the income tax data
WFStatus INT NULL, -- enumwfStatus; NULL = not submitted
ApprovedBy INT NULL,
ApprovedDate DATETIME NULL,
CreatedBy INT NOT NULL,
CreationDate DATETIME NOT NULL,
ModifiedBy INT NULL,
ModifiedDate DATETIME NULL,
CONSTRAINT PK_LFAPayment PRIMARY KEY (LFAPaymentID),
CONSTRAINT UQ_LFAPayment_BatchNumber UNIQUE (PayrollTypeID, BatchNumber)
);
GO
/* Payment, Undo and Approval pages: the batches of a payroll type and month */
CREATE INDEX IX_LFAPayment_Month ON dbo.LFAPayment (PayrollTypeID, SalaryMonth) INCLUDE (WFStatus);
GO
/* Payment History tab: date range */
CREATE INDEX IX_LFAPayment_PaymentDate ON dbo.LFAPayment (PayrollTypeID, PaymentDate);
GO
/* ---------- 3. dbo.LFAPaymentDetail ---------- */
CREATE TABLE dbo.LFAPaymentDetail (
LFAPaymentDetailID INT NOT NULL,
LFAPaymentID INT NOT NULL,
EmployeeID INT NOT NULL,
LFAYear DATETIME NOT NULL, -- same value as LFAPayment.LFAYear
LFACalendarYear AS (YEAR(LFAYear)) PERSISTED, -- computed, never written: for the once-a-year index
/* employee snapshot */
JoiningDate DATETIME NOT NULL,
ConfirmationDate DATETIME NULL,
GradeID INT NULL,
DesignationID INT NULL,
DepartmentID INT NULL,
CostCenterID INT NULL, -- CRG.CRGID
BranchID INT NULL, -- bank branch, for Bank Advice
AccountNo VARCHAR(50) NULL,
/* calculation */
JoiningBasic MONEY NULL,
LastDecBasic MONEY NULL, -- basic as of 31 Dec of the preceding year; NULL = joined in LFAYear
BasicSalary MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_BasicSalary DEFAULT (0), -- basic the LFA was calculated on
CalculatedAmount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_CalculatedAmount DEFAULT (0), -- before rounding
Amount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_Amount DEFAULT (0), -- LFA amount to pay
Remarks NVARCHAR(500) NULL,
CreatedBy INT NOT NULL,
CreationDate DATETIME NOT NULL,
ModifiedBy INT NULL,
ModifiedDate DATETIME NULL,
CONSTRAINT PK_LFAPaymentDetail PRIMARY KEY (LFAPaymentDetailID),
CONSTRAINT FK_LFAPayDtl_Payment FOREIGN KEY (LFAPaymentID) REFERENCES dbo.LFAPayment (LFAPaymentID),
CONSTRAINT CK_LFAPayDtl_Amount CHECK (Amount >= 0)
);
GO
/* policy: LFA once in a calendar year (Undo deletes the rows, which frees the employee again) */
CREATE UNIQUE INDEX UX_LFAPayDtl_EmployeeYear ON dbo.LFAPaymentDetail (EmployeeID, LFACalendarYear);
GO
/* the rows of one batch */
CREATE INDEX IX_LFAPayDtl_Payment ON dbo.LFAPaymentDetail (LFAPaymentID);
GO
SET NOEXEC OFF;
GO
/* ---------- 4. Drop LFAPaymentDetail.PaymentStatus (no longer used) ----------
Runs even when Part 0 refused (the tables hold data): a database that already
has the column loses it, with its default and check constraints. Re-runnable. */
IF OBJECT_ID(N'dbo.CK_LFAPayDtl_PaymentStatus', N'C') IS NOT NULL
ALTER TABLE dbo.LFAPaymentDetail DROP CONSTRAINT CK_LFAPayDtl_PaymentStatus;
GO
IF OBJECT_ID(N'dbo.DF_LFAPayDtl_PaymentStatus', N'D') IS NOT NULL
ALTER TABLE dbo.LFAPaymentDetail DROP CONSTRAINT DF_LFAPayDtl_PaymentStatus;
GO
IF COL_LENGTH(N'dbo.LFAPaymentDetail', N'PaymentStatus') IS NOT NULL
BEGIN
ALTER TABLE dbo.LFAPaymentDetail DROP COLUMN PaymentStatus;
PRINT 'LFAPaymentDetail.PaymentStatus dropped.';
END
GO