diff --git a/CLAUDE.md b/CLAUDE.md index 0527700..77e9600 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 `, `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 `, `dotnet publish` for `win-x64` into `_`, 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 `` + `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 .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_`, `dev__`, `shamim`) merged back into it. +branches (`dev_`, `dev__`, `shamim`) merged back into it. Client branches have started here too: +`Brac_Master` (with `Brac_Master_` 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. - `` 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 diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index e93399d..448aa54 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -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; } diff --git a/HRM.BO/HRBasic/Enums.cs b/HRM.BO/HRBasic/Enums.cs index fad6fef..1b4f3ec 100644 --- a/HRM.BO/HRBasic/Enums.cs +++ b/HRM.BO/HRBasic/Enums.cs @@ -2439,7 +2439,8 @@ namespace HRM.BO ITReport177Yearly = 1005, TAXReconciliation = 1006, BasePay = 1008, - ITReport177Quaterly = 1010 + ITReport177Quaterly = 1010, + LFABankAdvice = 1201 } diff --git a/HRM.BO/HREmployee/EmpLifeCycle.cs b/HRM.BO/HREmployee/EmpLifeCycle.cs index 5b01b3a..8fa3e3e 100644 --- a/HRM.BO/HREmployee/EmpLifeCycle.cs +++ b/HRM.BO/HREmployee/EmpLifeCycle.cs @@ -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 GetEmpID(int nEmpID, DateTime effectDate); EmpLifeCycle GetLastPosition(int nEmpID); void UpdateApprovalStatus(List oEmpLifeCycles, int currentPayrollTypeID); + bool IsAutoPFMembership(); int Save(EmpLifeCycle item, DateTime nextPayProcessDate, int payrollTypeID); int Save(List items, DateTime nextPayProcessDate); void Delete(EmpLifeCycle item, DateTime nextPayProcessDate); diff --git a/HRM.BO/LFA/LFAPayment.cs b/HRM.BO/LFA/LFAPayment.cs new file mode 100644 index 0000000..0e2f352 --- /dev/null +++ b/HRM.BO/LFA/LFAPayment.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace HRM.BO +{ + #region LFAPayment + + /// One Leave Fare Assistance payment batch (dbo.LFAPayment), as SalaryProcess is for the salary. + public class LFAPayment : AuditTrailBase, IworkflowInterface + { + public LFAPayment() + { + BatchNumber = string.Empty; + Details = new List(); + } + + public string BatchNumber { get; set; } + public int PayrollTypeID { get; set; } + + /// The last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE. + public DateTime SalaryMonth { get; set; } + + /// The last date of the calendar year the LFA is for. + public DateTime LFAYear { get; set; } + + public DateTime PaymentDate { get; set; } + public string Remarks { get; set; } + public bool IsTaxUpdated { get; set; } + + /// Null = not submitted yet, as SalaryProcess.WFStatus. + public enumwfStatus? WFStatus { get; set; } + + public int? ApprovedBy { get; set; } + public DateTime? ApprovedDate { get; set; } + + public List Details { get; set; } + + #region IworkflowInterface Members + + public string ObjectDescription + { + get { return "LFA payment batch " + BatchNumber; } + } + + /// The workflow type (WFTYPE 33), as SalaryProcess returns 30. + public int SetupID + { + get { return LFAPaymentApproval.WFTypeID; } + } + + public int ObjectID + { + get { return this.ID; } + } + + #endregion + } + + #endregion + + #region LFAPaymentDetail + + /// One employee of a batch (dbo.LFAPaymentDetail): a snapshot of the employee and of the calculation. + 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; } + + /// Basic as of 31 December of the preceding year; null when the employee joined in the LFA year. + public double? LastDecBasic { get; set; } + + /// The basic the LFA was calculated on. + public double BasicSalary { get; set; } + + /// What the policy gives, before rounding to whole taka. + public double CalculatedAmount { get; set; } + + /// The LFA amount to pay. + public double Amount { get; set; } + + public string Remarks { get; set; } + } + + #endregion + + #region LFAEmployee + + /// What the LFA calculation needs to know of one employee (not a table). + 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; } + + /// The parent of the employee's department. + 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; } + + /// The batch that already has this employee's LFA of the year; empty = none. + public string PaidBatchNumber { get; set; } + + /// The employee already has an LFA payment for the preceding year. + 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 GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID); + + // LFA Payment Undo + List GetUndoBatches(int payrollTypeID); + List GetBatchEmployees(int lfaPaymentID, int payrollTypeID); + LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID); + + // LFA Payment Approval (as Salary Approval) + LFAApprovalInfo GetApprovalInfo(int? employeeID); + List GetApprovalBatches(int payrollTypeID); + List 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 GetBankAdviceBatches(int payrollTypeID); + System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID); + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentApproval.cs b/HRM.BO/LFA/LFAPaymentApproval.cs new file mode 100644 index 0000000..113304a --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentApproval.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region LFA Payment Approval (not tables) + + /// + /// 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). + /// + public static class LFAPaymentApproval + { + /// WFTYPE.WFTYPEID of LFA Payment (Salary 30, Bonus 31, Leave Encashment 32). + public const int WFTypeID = 33; + + /// Logic configuration: lfaapproval / workflow = Yes | No. + public const string LogicParent = "lfaapproval"; + public const string LogicChild = "workflow"; + } + + /// What the LFA Payment Approval page needs to know before it shows its buttons. + public class LFAApprovalInfo + { + /// lfaapproval/workflow = Yes: batches go through the approval workflow. + public bool IsWorkflowRequired { get; set; } + + /// The login is linked with an employee (the workflow needs an initiator employee). + public bool HasEmployee { get; set; } + + /// At least one approval rule is set up for LFA Payment in Work Flow Setup. + public bool HasWorkflowSetup { get; set; } + } + + /// Approve (Direct) or Submit for approval one batch. + public class LFAApprovalRequest + { + public int LFAPaymentID { get; set; } + public string Remarks { get; set; } + } + + /// An approver approves or reverts the workflow step (WFMovementTran) they received. + 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; } + + /// True when the batch is now fully approved. + public bool Approved { get; set; } + } + + /// The batch an approver opened from the Payment Approval page. + public class LFAApproverBatch + { + public LFAApproverBatch() + { + Employees = new List(); + } + + public LFAPaymentBatch Batch { get; set; } + public List Employees { get; set; } + + /// The login is a pending approver of this step and may Approve or Revert it. + public bool CanAct { get; set; } + + /// Why the login cannot act (already acted, not their step, batch undone ...). + public string Message { get; set; } + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentUndo.cs b/HRM.BO/LFA/LFAPaymentUndo.cs new file mode 100644 index 0000000..247a405 --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentUndo.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region LFA Payment Undo (not tables) + + /// One batch of the LFA Payment Undo page. + 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; } + /// The batch is back with the person who submitted it (an approver reverted it to them). + public bool IsAtInitiator { get; set; } + /// Who has to act now, e.g. "Md. Karim [D1004]". + public string PendingWith { get; set; } + + /// Approval state in words (Not Submitted, Pending Approval, Approved, ...). + public string StatusText { get; set; } + public bool CanUndo { get; set; } + /// Why the batch cannot be undone; empty when it can. + public string UndoBlockedReason { get; set; } + } + + /// One employee of a batch, on the LFA Payment Undo page. + 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; } + } + + /// What to undo: the whole batch (no DetailIDs) or only these employees of it. + public class LFAPaymentUndoRequest + { + public LFAPaymentUndoRequest() + { + DetailIDs = new List(); + } + + public int LFAPaymentID { get; set; } + /// LFAPaymentDetailIDs of the employees to remove; empty = the whole batch. + public List DetailIDs { get; set; } + } + + public class LFAPaymentUndoResult + { + public bool Undone { get; set; } + public string Message { get; set; } + public int RemovedCount { get; set; } + /// True when the batch itself was deleted (whole batch, or its last employee). + public bool BatchRemoved { get; set; } + } + + #endregion +} diff --git a/HRM.BO/LFA/LFAPaymentUploadTemplate.cs b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs new file mode 100644 index 0000000..75e6164 --- /dev/null +++ b/HRM.BO/LFA/LFAPaymentUploadTemplate.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + #region Template layout + + /// + /// The LFA payment upload sheet. The downloadable workbook is generated from this and an uploaded + /// one is read against it. + /// + 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; + + /// How many rows of the template are formatted as text. + public const int FormattedDataRows = 1000; + + public const int EmployeeNoColumn = 1; + public const int NameColumn = 2; + + public const int MaxRemarksLength = 500; + + /// Employee ID is the Employee No. Name only helps whoever fills the file; it is not checked. + public static readonly string[] Headings = { "Employee ID", "Name" }; + public static readonly double[] Widths = { 18, 40 }; + } + + #endregion + + #region Upload and process data + + /// One uploaded row: what the user gives. Every amount is worked out by the server. + public class LFAPaymentInput + { + public int RowNo { get; set; } + public string EmployeeNo { get; set; } + } + + /// The page's payment information and rows, to calculate or to process. + public class LFAPaymentRequest + { + public DateTime? PaymentDate { get; set; } + public string Remarks { get; set; } + public List Rows { get; set; } + + /// The total the page shows; processing stops when the calculation no longer gives it. + public double ExpectedTotal { get; set; } + } + + /// One calculated row, as the New LFA Payment grid shows it. + 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; } + /// Joining Date to Payment Date, e.g. "2 Years 9 Months 27 Days". + 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; } + } + + /// Why a row (or, with RowNo 0, the file) cannot be paid. + 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(); + Issues = new List(); + } + + public DateTime SalaryMonth { get; set; } + + /// The rows that can be paid. + public List Rows { get; set; } + + /// Every problem of every other row. + public List 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; } + + /// Set when nothing was saved because the rows no longer pass. + public LFAPaymentReadResult Validation { get; set; } + } + + /// The current salary month of the payroll type and the next batch number. + public class LFAPaymentInfo + { + public int PayrollTypeID { get; set; } + public DateTime SalaryMonth { get; set; } + public string NextBatchNumber { get; set; } + } + + /// One row of the Payment History tab. + 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 +} diff --git a/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs b/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs index c3ea03c..090a1aa 100644 --- a/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs +++ b/HRM.DA/DA/HREmployee/EmpLifeCycleDA.cs @@ -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) diff --git a/HRM.DA/DA/HREmployee/HREmployeeDA.cs b/HRM.DA/DA/HREmployee/HREmployeeDA.cs index f5f1bf3..526b751 100644 --- a/HRM.DA/DA/HREmployee/HREmployeeDA.cs +++ b/HRM.DA/DA/HREmployee/HREmployeeDA.cs @@ -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", diff --git a/HRM.DA/DA/LFA/LFAPaymentDA.cs b/HRM.DA/DA/LFA/LFAPaymentDA.cs new file mode 100644 index 0000000..a65a0e0 --- /dev/null +++ b/HRM.DA/DA/LFA/LFAPaymentDA.cs @@ -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 + + /// Stamps who changed the batch (some of its employees were undone). + 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); + } + + /// Sets the batch's approval status (Not_yet_Initiated while it is in the workflow), as SalaryProcess.WFStatus. + internal static void UpdateWFStatus(TransactionContext tc, int lfaPaymentID, enumwfStatus? wfStatus) + { + tc.ExecuteNonQuery("UPDATE LFAPayment SET WFStatus=%n WHERE LFAPaymentID=%n", (int?)wfStatus, lfaPaymentID); + } + + /// The batch is approved: Direct Approve, or the last approver of the workflow. + 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); + } + + /// + /// 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. + /// + 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); + } + + /// Deletes the batch header; its detail rows must be deleted first. + 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); + } + + /// + /// 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. + /// + internal static IDataReader GetForUpdate(TransactionContext tc, int nID) + { + return tc.ExecuteReader("SELECT * FROM LFAPayment WITH (UPDLOCK, ROWLOCK) WHERE LFAPaymentID=%n", nID); + } + + /// + /// 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. + /// + 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); + } + + /// + /// 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. + /// + 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); + } + + /// + /// 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). + /// + 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; + } + + /// The highest running number of the batches that start with this prefix; 0 = none yet. + 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); + } + + /// + /// 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. + /// + 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); + } + + /// + /// 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. + /// + internal static IDataReader GetEmployees(TransactionContext tc, List 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); + } + + /// + /// 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. + /// + 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); + } + + /// Payment History tab: every employee of the batches of the payment date range. + 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); + } + + /// + /// 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. + /// + 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 +} diff --git a/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs new file mode 100644 index 0000000..fa59abc --- /dev/null +++ b/HRM.DA/DA/LFA/LFAPaymentDetailDA.cs @@ -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 + + /// + /// Inserts every row of a batch in one SqlBulkCopy, inside the caller's transaction (as + /// BonusProcessDA.InsertBulk). IDs must already be set. + /// + internal static void InsertBulk(TransactionContext tc, List 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); + } + + /// LFA Payment Undo: the employees of one batch. + 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 + + /// Deletes every employee of the batch. + internal static void DeleteByPaymentID(TransactionContext tc, int paymentID) + { + tc.ExecuteNonQuery("DELETE FROM LFAPaymentDetail WHERE LFAPaymentID=%n", paymentID); + } + + /// Deletes these employees of the batch (IDs the service has already checked). + internal static void Delete(TransactionContext tc, int paymentID, List 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 +} diff --git a/HRM.DA/DA/Workflow/WFMovementTranDA.cs b/HRM.DA/DA/Workflow/WFMovementTranDA.cs index bab6fdd..17878be 100644 --- a/HRM.DA/DA/Workflow/WFMovementTranDA.cs +++ b/HRM.DA/DA/Workflow/WFMovementTranDA.cs @@ -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 diff --git a/HRM.DA/Service/Common/BasicDataUploadProcessService.cs b/HRM.DA/Service/Common/BasicDataUploadProcessService.cs index 2b88c94..b4d7651 100644 --- a/HRM.DA/Service/Common/BasicDataUploadProcessService.cs +++ b/HRM.DA/Service/Common/BasicDataUploadProcessService.cs @@ -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; } diff --git a/HRM.DA/Service/Common/RegularDataUploadService.cs b/HRM.DA/Service/Common/RegularDataUploadService.cs index ba85660..02dbfdb 100644 --- a/HRM.DA/Service/Common/RegularDataUploadService.cs +++ b/HRM.DA/Service/Common/RegularDataUploadService.cs @@ -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; diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index 23513a2..2bd4f12 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -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; diff --git a/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs b/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs index af40cb5..674c1b3 100644 --- a/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs +++ b/HRM.DA/Service/HREmployee/EmpLifeCycleService.cs @@ -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 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, diff --git a/HRM.DA/Service/LFA/LFACalculator.cs b/HRM.DA/Service/LFA/LFACalculator.cs new file mode 100644 index 0000000..aa7cf11 --- /dev/null +++ b/HRM.DA/Service/LFA/LFACalculator.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using HRM.BO; + +namespace HRM.DA +{ + /// + /// 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. + /// + internal static class LFACalculator + { + private const int ServiceMonths = 6; + private const double DaysOfYear = 365; + + /// Every reason the employee cannot be paid; empty = eligible. + internal static List Validate(LFAEmployee employee, DateTime lfaYear, DateTime paymentDate, int payrollTypeID) + { + List problems = new List(); + 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; + } + + /// The detail row of an eligible employee (see Validate). + 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; + } + + /// + /// Completed service from the joining date to the date (the payment date), e.g. "2 Years 9 Months 27 Days". + /// + 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 parts = new List(); + 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); + } + + /// Days from the joining date to the year end, the joining date itself not counted, over 365. + 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; + } + + /// Joined in the preceding year, not eligible within that year, and not paid for it. + private static bool HasPreviousYear(LFAEmployee employee, DateTime lfaYear) + { + return employee.JoiningDate.Year == lfaYear.Year - 1 + && employee.JoiningDate.Date.AddMonths(ServiceMonths) > LastDec(lfaYear) + && !employee.IsPaidLastYear; + } + + /// 31 December of the LFA year. + 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"); + } + } +} diff --git a/HRM.DA/Service/LFA/LFAPaymentService.cs b/HRM.DA/Service/LFA/LFAPaymentService.cs new file mode 100644 index 0000000..843dcd5 --- /dev/null +++ b/HRM.DA/Service/LFA/LFAPaymentService.cs @@ -0,0 +1,1364 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Ease.Core.DataAccess; +using Ease.Core.Model; +using Ease.Core.Utility; +using HRM.BO; + +namespace HRM.DA +{ + /// LFA Payment (Core Payroll > LFA): upload, calculate, process into a batch, and the payment history. + public class LFAPaymentService : ServiceTemplate, ILFAPaymentService + { + public LFAPaymentService() + { + } + + #region Mapping + + private void MapObject(LFAPayment oPayment, DataReader oReader) + { + base.SetObjectID(oPayment, oReader.GetInt32("LFAPaymentID").Value); + oPayment.BatchNumber = oReader.GetString("BatchNumber"); + oPayment.PayrollTypeID = oReader.GetInt32("PayrollTypeID").Value; + oPayment.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value; + oPayment.LFAYear = oReader.GetDateTime("LFAYear").Value; + oPayment.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + oPayment.Remarks = oReader.GetString("Remarks"); + oPayment.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value; + oPayment.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus"); + oPayment.ApprovedBy = oReader.GetInt32("ApprovedBy"); + oPayment.ApprovedDate = oReader.GetDateTime("ApprovedDate"); + oPayment.CreatedBy = oReader.GetInt32("CreatedBy").Value; + oPayment.CreatedDate = oReader.GetDateTime("CreationDate").Value; + oPayment.ModifiedBy = oReader.GetInt32("ModifiedBy"); + oPayment.ModifiedDate = oReader.GetDateTime("ModifiedDate"); + this.SetObjectState(oPayment, Ease.Core.ObjectState.Saved); + } + + protected override T CreateObject(DataReader oReader) + { + LFAPayment oPayment = new LFAPayment(); + MapObject(oPayment, oReader); + return oPayment as T; + } + + private void MapDetailObject(LFAPaymentDetail oDetail, DataReader oReader) + { + base.SetObjectID(oDetail, oReader.GetInt32("LFAPaymentDetailID").Value); + oDetail.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value; + oDetail.EmployeeID = oReader.GetInt32("EmployeeID").Value; + oDetail.LFAYear = oReader.GetDateTime("LFAYear").Value; + oDetail.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + oDetail.ConfirmationDate = oReader.GetDateTime("ConfirmationDate"); + oDetail.GradeID = oReader.GetInt32("GradeID"); + oDetail.DesignationID = oReader.GetInt32("DesignationID"); + oDetail.DepartmentID = oReader.GetInt32("DepartmentID"); + oDetail.CostCenterID = oReader.GetInt32("CostCenterID"); + oDetail.BranchID = oReader.GetInt32("BranchID"); + oDetail.AccountNo = oReader.GetString("AccountNo"); + oDetail.JoiningBasic = oReader.GetDouble("JoiningBasic"); + oDetail.LastDecBasic = oReader.GetDouble("LastDecBasic"); + oDetail.BasicSalary = oReader.GetDouble("BasicSalary").Value; + oDetail.CalculatedAmount = oReader.GetDouble("CalculatedAmount").Value; + oDetail.Amount = oReader.GetDouble("Amount").Value; + oDetail.Remarks = oReader.GetString("Remarks"); + oDetail.CreatedBy = oReader.GetInt32("CreatedBy").Value; + oDetail.CreatedDate = oReader.GetDateTime("CreationDate").Value; + oDetail.ModifiedBy = oReader.GetInt32("ModifiedBy"); + oDetail.ModifiedDate = oReader.GetDateTime("ModifiedDate"); + this.SetObjectState(oDetail, Ease.Core.ObjectState.Saved); + } + + private LFAEmployee MapEmployee(DataReader oReader) + { + LFAEmployee employee = new LFAEmployee(); + employee.EmployeeID = oReader.GetInt32("EMPLOYEEID").Value; + employee.EmployeeNo = oReader.GetString("EMPLOYEENO"); + employee.Name = oReader.GetString("NAME"); + employee.PayrollTypeID = oReader.GetInt32("PAYROLLTYPEID").Value; + employee.Status = (EnumEmployeeStatus)oReader.GetInt32("STATUS").Value; + employee.IsConfirmed = oReader.GetBoolean("ISCONFIRMED", false); + employee.JoiningDate = oReader.GetDateTime("JOININGDATE").Value; + employee.ConfirmationDate = oReader.GetDateTime("DATEOFCONFIRMATION"); + employee.GradeID = oReader.GetInt32("GRADEID"); + employee.GradeName = oReader.GetString("GradeName"); + employee.DesignationID = oReader.GetInt32("DESIGNATIONID"); + employee.DesignationName = oReader.GetString("DesignationName"); + employee.DepartmentID = oReader.GetInt32("DEPARTMENTID"); + employee.DepartmentName = oReader.GetString("DepartmentName"); + employee.DivisionName = oReader.GetString("DivisionName"); + employee.CostCenterID = oReader.GetInt32("COSTCENTERID"); + employee.BranchID = oReader.GetInt32("BRANCHID"); + employee.AccountNo = oReader.GetString("ACCOUNTNO"); + employee.JoiningBasic = oReader.GetDouble("JoiningBasic").Value; + employee.PaidBatchNumber = oReader.GetString("PaidBatchNumber"); + employee.IsPaidLastYear = oReader.GetInt32("IsPaidLastYear").Value == 1; + return employee; + } + + private LFAPaymentHistory MapHistory(DataReader oReader) + { + LFAPaymentHistory history = new LFAPaymentHistory(); + history.LFAPaymentDetailID = oReader.GetInt32("LFAPaymentDetailID").Value; + history.BatchNumber = oReader.GetString("BatchNumber"); + history.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + history.EmployeeNo = oReader.GetString("EMPLOYEENO"); + history.Name = oReader.GetString("NAME"); + history.DesignationName = oReader.GetString("DesignationName"); + history.DepartmentName = oReader.GetString("DepartmentName"); + history.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + history.BasicSalary = oReader.GetDouble("BasicSalary").Value; + history.Amount = oReader.GetDouble("Amount").Value; + return history; + } + + private LFAPaymentBatch MapBatch(DataReader oReader) + { + LFAPaymentBatch batch = new LFAPaymentBatch(); + batch.LFAPaymentID = oReader.GetInt32("LFAPaymentID").Value; + batch.BatchNumber = oReader.GetString("BatchNumber"); + batch.SalaryMonth = oReader.GetDateTime("SalaryMonth").Value; + batch.LFAYear = oReader.GetDateTime("LFAYear").Value; + batch.PaymentDate = oReader.GetDateTime("PaymentDate").Value; + batch.Remarks = oReader.GetString("Remarks"); + batch.WFStatus = (enumwfStatus?)oReader.GetInt32("WFStatus"); + batch.IsTaxUpdated = oReader.GetBoolean("IsTaxUpdated").Value; + batch.CreationDate = oReader.GetDateTime("CreationDate").Value; + batch.CreatedByName = oReader.GetString("CreatedByName"); + batch.HeadCount = oReader.GetInt32("HeadCount").Value; + batch.TotalAmount = oReader.GetDouble("TotalAmount").Value; + batch.ApprovedDate = oReader.GetDateTime("ApprovedDate"); + batch.ApprovedByName = oReader.GetString("ApprovedByName"); + batch.WFMovementTranID = oReader.GetInt32("WFMovementTranID"); + batch.UniqueNumber = oReader.GetInt32("UniqueNumber"); + batch.IsAtInitiator = oReader.GetInt32("IsAtInitiator", 0) == 1; + batch.PendingWith = oReader.GetString("PendingWith"); + + batch.StatusText = StatusText(batch.WFStatus, batch.IsAtInitiator); + batch.UndoBlockedReason = UndoBlockedReason(batch.WFStatus, batch.IsTaxUpdated, batch.IsAtInitiator); + batch.CanUndo = batch.UndoBlockedReason == null; + return batch; + } + + private LFAPaymentBatchEmployee MapBatchEmployee(DataReader oReader) + { + LFAPaymentBatchEmployee employee = new LFAPaymentBatchEmployee(); + employee.LFAPaymentDetailID = oReader.GetInt32("LFAPaymentDetailID").Value; + employee.EmployeeID = oReader.GetInt32("EmployeeID").Value; + employee.EmployeeNo = oReader.GetString("EMPLOYEENO"); + employee.Name = oReader.GetString("NAME"); + employee.DesignationName = oReader.GetString("DesignationName"); + employee.DepartmentName = oReader.GetString("DepartmentName"); + employee.JoiningDate = oReader.GetDateTime("JoiningDate").Value; + employee.BasicSalary = oReader.GetDouble("BasicSalary").Value; + employee.Amount = oReader.GetDouble("Amount").Value; + return employee; + } + + #endregion + + #region Get + + public LFAPayment Get(int id) + { + LFAPayment oPayment = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, id)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment != null) + { + dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, id)); + while (dr.Read()) + { + LFAPaymentDetail oDetail = new LFAPaymentDetail(); + MapDetailObject(oDetail, dr); + oPayment.Details.Add(oDetail); + } + dr.Close(); + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return oPayment; + } + + /// The current salary month and the batch number the next process will take. + public LFAPaymentInfo GetInfo(int payrollTypeID) + { + LFAPaymentInfo info = new LFAPaymentInfo(); + TransactionContext tc = null; + try + { + info.PayrollTypeID = payrollTypeID; + info.SalaryMonth = GetSalaryMonth(payrollTypeID); + string prefix = BatchPrefix(info.SalaryMonth); + + tc = TransactionContext.Begin(); + info.NextBatchNumber = BatchNumber(prefix, LFAPaymentDA.GetLastBatchNo(tc, payrollTypeID, prefix) + 1); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return info; + } + + public List GetHistory(DateTime fromDate, DateTime toDate, int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.GetHistory(tc, fromDate.Date, toDate.Date, payrollTypeID)); + while (dr.Read()) + { + items.Add(MapHistory(dr)); + } + dr.Close(); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return items; + } + + #endregion + + #region Upload and calculate + + public byte[] GetUploadTemplate() + { + try + { + return LFAPaymentWorkbook.BuildTemplate(); + } + catch (Exception e) + { + #region Handle Exception + + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + } + + /// Reads an uploaded workbook and calculates its employees. Nothing is saved. + public LFAPaymentReadResult ReadUpload(Stream stream, string fileName, long fileLength, DateTime paymentDate, int payrollTypeID) + { + LFAPaymentReadResult result = new LFAPaymentReadResult(); + TransactionContext tc = null; + try + { + result.SalaryMonth = GetSalaryMonth(payrollTypeID); + List rows = LFAPaymentWorkbook.Read(stream, fileName, fileLength, result); + + tc = TransactionContext.Begin(); + List> validRows = Validate(tc, result, rows, paymentDate, payrollTypeID); + tc.End(); + + if (result.Issues.Count == 0) + Calculate(result, validRows, paymentDate); // only a fully valid file is calculated + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// Calculates the page's rows again (payment date or mode changed, draft opened). Nothing is saved. + public LFAPaymentReadResult Calculate(LFAPaymentRequest request, int payrollTypeID) + { + LFAPaymentReadResult result = new LFAPaymentReadResult(); + TransactionContext tc = null; + try + { + CheckRequest(request); + result.SalaryMonth = GetSalaryMonth(payrollTypeID); + + tc = TransactionContext.Begin(); + List> validRows = Validate(tc, result, request.Rows, + request.PaymentDate.Value, payrollTypeID); + tc.End(); + + if (result.Issues.Count == 0) + Calculate(result, validRows, request.PaymentDate.Value); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// + /// Validation, the first step of every upload, recalculation and process: runs EVERY check on EVERY row + /// and puts every problem into result.Issues (the file's own problems, found while reading it, are + /// already there). Nothing is calculated here. Returns the rows that passed with their employee; they + /// may be calculated only when result.Issues is empty. + /// + private List> Validate(TransactionContext tc, LFAPaymentReadResult result, List inputs, DateTime paymentDate, int payrollTypeID) + { + List> valid = new List>(); + if (inputs == null || inputs.Count == 0) + { + return valid; + } + + DateTime lfaYear = GetLFAYear(paymentDate); + foreach (LFAPaymentInput input in inputs) + { + input.EmployeeNo = (input.EmployeeNo ?? "").Trim(); + } + + // An Employee No may exist in another payroll type too; the current payroll type's employee comes first. + Dictionary employees = new Dictionary(StringComparer.OrdinalIgnoreCase); + DataReader dr = new DataReader(LFAPaymentDA.GetEmployees(tc, inputs.Select(x => x.EmployeeNo).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), lfaYear)); + while (dr.Read()) + { + LFAEmployee employee = MapEmployee(dr); + string key = (employee.EmployeeNo ?? "").Trim(); + LFAEmployee found; + if (!employees.TryGetValue(key, out found) || (found.PayrollTypeID != payrollTypeID && employee.PayrollTypeID == payrollTypeID)) + { + employees[key] = employee; + } + } + dr.Close(); + + // Basic as of 31 December of the preceding year: the salary record that starts before 1 January + // (the latest entry), as the bonus reads it. + Dictionary lastDecBasics = GetBasicOnDate(tc, new DateTime(lfaYear.Year, 1, 1)); + foreach (LFAEmployee employee in employees.Values) + { + double basic; + employee.LastDecBasic = lastDecBasics.TryGetValue(employee.EmployeeID, out basic) ? basic : 0; + } + + Dictionary> rowNos = inputs.GroupBy(x => x.EmployeeNo, StringComparer.OrdinalIgnoreCase).ToDictionary(x => x.Key, x => x.Select(i => i.RowNo).ToList(), StringComparer.OrdinalIgnoreCase); + foreach (LFAPaymentInput input in inputs) + { + LFAEmployee employee; + if (!employees.TryGetValue(input.EmployeeNo, out employee) || employee.PayrollTypeID != payrollTypeID) + { + result.AddIssue(input.RowNo, input.EmployeeNo, null, "Employee is not found."); + continue; + } + List problems = LFACalculator.Validate(employee, lfaYear, paymentDate, payrollTypeID); + if (rowNos[input.EmployeeNo].Count > 1) + { + problems.Add("Employee is more than once in the file (rows " + string.Join(", ", rowNos[input.EmployeeNo]) + ")."); + } + foreach (string problem in problems) + { + result.AddIssue(input.RowNo, employee.EmployeeNo, employee.Name, problem); + } + if (problems.Count == 0) + { + valid.Add(new KeyValuePair(input, employee)); + } + } + result.Issues = result.Issues.OrderBy(x => x.RowNo).ToList(); + return valid; + } + + /// + /// Calculation (LFACalculator.Calculate) of rows that Validate passed. Call it ONLY when Validate left + /// result.Issues empty. Fills result.Rows and returns each row's detail, in the same order. + /// + private static List Calculate(LFAPaymentReadResult result, List> validRows, DateTime paymentDate) + { + DateTime lfaYear = GetLFAYear(paymentDate); + List details = new List(); + foreach (KeyValuePair item in validRows) + { + LFAPaymentDetail detail = LFACalculator.Calculate(item.Value, lfaYear); + details.Add(detail); + result.Rows.Add(ToRow(item.Value, item.Key, detail, paymentDate)); + } + return details; + } + + /// + /// EmployeeID → basic on the date (LFAPaymentDA.GetBasicOnDate, the LFA copy of + /// EmployeeGradeSalaryService.GetBasicOnDate). Every row is read, the first one included. + /// + private static Dictionary GetBasicOnDate(TransactionContext tc, DateTime effectDate) + { + Dictionary basics = new Dictionary(); + DataReader dr = new DataReader(LFAPaymentDA.GetBasicOnDate(tc, effectDate)); + while (dr.Read()) + { + basics[dr.GetInt32("EMPLOYEEID").Value] = dr.GetDouble("BASICSALARY", 0); + } + dr.Close(); + return basics; + } + + private static LFAPaymentRow ToRow(LFAEmployee employee, LFAPaymentInput input, LFAPaymentDetail detail, + DateTime paymentDate) + { + return new LFAPaymentRow + { + RowNo = input.RowNo, + EmployeeNo = employee.EmployeeNo, + EmployeeID = employee.EmployeeID, + Name = employee.Name, + GradeName = employee.GradeName, + DesignationName = employee.DesignationName, + DivisionName = employee.DivisionName, + DepartmentName = employee.DepartmentName, + JoiningDate = employee.JoiningDate, + ConfirmationDate = employee.ConfirmationDate, + ServiceLength = LFACalculator.ServiceLength(employee.JoiningDate, paymentDate), + JoiningBasic = employee.JoiningBasic, + LastDecBasic = detail.LastDecBasic, + BasicSalary = detail.BasicSalary, + Amount = detail.Amount, + PaymentDate = paymentDate.Date + }; + } + + #endregion + + #region Process + + /// + /// Saves the page's rows as one new batch, in ONE transaction. Every row is validated and calculated + /// again here; when a row no longer passes, or the total is not the one the page shows, nothing is saved. + /// + public LFAPaymentProcessResult Process(LFAPaymentRequest request, int payrollTypeID, int userID) + { + LFAPaymentProcessResult result = new LFAPaymentProcessResult(); + TransactionContext tc = null; + try + { + CheckRequest(request); + if (request.Rows.Count == 0) + throw new ServiceException("Add at least one employee."); + if ((request.Remarks ?? "").Length > LFAPaymentUploadTemplate.MaxRemarksLength) + throw new ServiceException("Remarks is longer than " + LFAPaymentUploadTemplate.MaxRemarksLength + " characters."); + + LFAPaymentReadResult validation = new LFAPaymentReadResult(); + validation.SalaryMonth = GetSalaryMonth(payrollTypeID); + string prefix = BatchPrefix(validation.SalaryMonth); + + tc = TransactionContext.Begin(true); + int batchNo = LFAPaymentDA.GetLastBatchNoForUpdate(tc, payrollTypeID, prefix) + 1; + List> validRows = Validate(tc, validation, request.Rows, + request.PaymentDate.Value, payrollTypeID); + List details = validation.Issues.Count == 0 + ? Calculate(validation, validRows, request.PaymentDate.Value) // only after a clean validation + : new List(); + + if (validation.Issues.Count > 0) + { + result.Validation = validation; + result.Message = "Nothing was saved. Some employees can no longer be paid; please check the list."; + } + else if (Math.Abs(details.Sum(x => x.Amount) - request.ExpectedTotal) > 0.001) + { + result.Validation = validation; + result.Message = "Nothing was saved. The LFA amounts have changed; please check them and process again."; + } + else + { + LFAPayment oPayment = new LFAPayment(); + oPayment.BatchNumber = BatchNumber(prefix, batchNo); + oPayment.PayrollTypeID = payrollTypeID; + oPayment.SalaryMonth = validation.SalaryMonth; + oPayment.LFAYear = GetLFAYear(request.PaymentDate.Value); + oPayment.PaymentDate = request.PaymentDate.Value.Date; + oPayment.Remarks = string.IsNullOrWhiteSpace(request.Remarks) ? null : request.Remarks.Trim(); + oPayment.CreatedBy = userID; + oPayment.CreatedDate = DateTime.Now; + oPayment.Details = details; + Insert(tc, oPayment); + + result.Saved = true; + result.BatchNumber = oPayment.BatchNumber; + result.Message = "Batch " + oPayment.BatchNumber + " created for " + details.Count + " employee(s)."; + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + private void Insert(TransactionContext tc, LFAPayment oPayment) + { + base.SetObjectID(oPayment, tc.GenerateID("LFAPayment", "LFAPaymentID")); + LFAPaymentDA.Insert(tc, oPayment); + + int detailID = tc.GenerateID("LFAPaymentDetail", "LFAPaymentDetailID"); + foreach (LFAPaymentDetail oDetail in oPayment.Details) + { + base.SetObjectID(oDetail, detailID++); + oDetail.LFAPaymentID = oPayment.ID; + oDetail.CreatedBy = oPayment.CreatedBy; + oDetail.CreatedDate = oPayment.CreatedDate; + } + LFAPaymentDetailDA.InsertBulk(tc, oPayment.Details); + } + + #endregion + + #region Undo + + /// LFA Payment Undo: every batch of the payroll type, and whether each one can be undone. + public List GetUndoBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID); + } + + private List GetBatches(int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(LFAPaymentDA.GetBatches(tc, payrollTypeID)); + while (dr.Read()) + { + items.Add(MapBatch(dr)); + } + dr.Close(); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return items; + } + + /// The employees of one batch of the payroll type; empty when the batch is not found. + public List GetBatchEmployees(int lfaPaymentID, int payrollTypeID) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment != null && oPayment.PayrollTypeID == payrollTypeID) + { + dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, lfaPaymentID)); + while (dr.Read()) + { + items.Add(MapBatchEmployee(dr)); + } + dr.Close(); + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return items; + } + + /// + /// Undoes the whole batch (request.DetailIDs empty) or only those employees of it, in ONE transaction. + /// Everything is checked again here with the batch locked: a batch submitted for approval, approved + /// or already in the tax data is not undone. When the last employee goes, the + /// batch goes too. The undone employees can then be paid again in another batch. + /// + public LFAPaymentUndoResult Undo(LFAPaymentUndoRequest request, int payrollTypeID, int userID) + { + LFAPaymentUndoResult result = new LFAPaymentUndoResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + List detailIDs = (request.DetailIDs ?? new List()).Distinct().ToList(); + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, request.LFAPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + { + result.Message = "The batch is not found. It may have been undone already."; + tc.End(); + return result; + } + + List details = new List(); + dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, oPayment.ID)); + while (dr.Read()) + { + LFAPaymentDetail oDetail = new LFAPaymentDetail(); + MapDetailObject(oDetail, dr); + details.Add(oDetail); + } + dr.Close(); + + bool wholeBatch = detailIDs.Count == 0 || details.All(x => detailIDs.Contains(x.ID)); + List selected = wholeBatch ? details : details.Where(x => detailIDs.Contains(x.ID)).ToList(); + + bool isAtInitiator = GetIsAtInitiator(tc, oPayment.ID); + string blocked = UndoBlockedReason(oPayment.WFStatus, oPayment.IsTaxUpdated, isAtInitiator); + if (blocked != null) + { + result.Message = blocked; + } + else if (!wholeBatch && selected.Count != detailIDs.Count) + { + result.Message = "Some of the selected employees are no longer in batch " + oPayment.BatchNumber + + ". Please load the batch again."; + } + else + { + if (wholeBatch) + { + LFAPaymentDetailDA.DeleteByPaymentID(tc, oPayment.ID); + LFAPaymentDA.DeleteWorkflow(tc, oPayment.ID); + LFAPaymentDA.Delete(tc, oPayment.ID); + result.BatchRemoved = true; + result.Message = "Batch " + oPayment.BatchNumber + " is undone (" + selected.Count + " employee(s))."; + } + else + { + LFAPaymentDetailDA.Delete(tc, oPayment.ID, selected.Select(x => x.ID).ToList()); + LFAPaymentDA.UpdateModified(tc, oPayment.ID, userID, DateTime.Now); + result.Message = selected.Count + " employee(s) undone from batch " + oPayment.BatchNumber + "."; + } + result.Undone = true; + result.RemovedCount = selected.Count; + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// + /// Why a batch cannot be undone; null when it can. As Salary Undo: allowed before the batch is + /// submitted for approval, and when an approver has reverted it back to the person who submitted it. + /// + private static string UndoBlockedReason(enumwfStatus? wfStatus, bool isTaxUpdated, bool isAtInitiator) + { + if (wfStatus == enumwfStatus.Approve) + return "The batch is already approved."; + if (wfStatus != null && wfStatus != enumwfStatus.Not_yet_Submitted && wfStatus != enumwfStatus.Revert + && wfStatus != enumwfStatus.Decline && !isAtInitiator) + return "The batch is submitted and pending for approval."; + if (isTaxUpdated) + return "The batch is already in the income tax data."; + return null; + } + + private static string StatusText(enumwfStatus? wfStatus, bool isAtInitiator) + { + if (wfStatus == null || wfStatus == enumwfStatus.Not_yet_Submitted) + return "Not Submitted"; + if (wfStatus != enumwfStatus.Approve && isAtInitiator) + return "Reverted to Initiator"; + switch (wfStatus.Value) + { + case enumwfStatus.Approve: + return "Approved"; + case enumwfStatus.Revert: + return "Reverted"; + case enumwfStatus.Decline: + return "Declined"; + default: + return "Pending Approval"; + } + } + + #endregion + + #region Approval + + /// Logic key, the login's employee and the Work Flow Setup of LFA Payment. + public LFAApprovalInfo GetApprovalInfo(int? employeeID) + { + LFAApprovalInfo info = new LFAApprovalInfo(); + TransactionContext tc = null; + try + { + info.IsWorkflowRequired = IsWorkflowRequired(); + info.HasEmployee = employeeID.GetValueOrDefault() > 0; + + tc = TransactionContext.Begin(); + info.HasWorkflowSetup = new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count > 0; + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return info; + } + + /// LFA Payment Approval: every batch of the payroll type with its approval state. + public List GetApprovalBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID); + } + + /// Every approval step of the batch, as Salary Approve shows its flow history. + public List GetFlowHistory(int lfaPaymentID, int payrollTypeID) + { + LFAPayment oPayment = this.Get(lfaPaymentID); + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + return new List(); + return new WFMovementTranService().GetFlowHistoriesByObjectID(lfaPaymentID, LFAPaymentApproval.WFTypeID, null) + ?? new List(); + } + + /// + /// Direct Approve (lfaapproval/workflow = No), as Salary's ApproveSalary: the batch is approved at once. + /// Refused while the workflow is on, or when the batch was already submitted or approved. + /// + public LFAApprovalResult ApproveDirect(LFAApprovalRequest request, int payrollTypeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + if (IsWorkflowRequired()) + { + result.Message = "LFA approval goes through the approval workflow. Please submit the batch for approval."; + return result; + } + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); + string blocked = oPayment == null ? "The batch is not found. It may have been undone." : DirectApproveBlockedReason(oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); + result.Done = true; + result.Approved = true; + result.Message = "Batch " + oPayment.BatchNumber + " is approved."; + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// + /// Submit for approval (lfaapproval/workflow = Yes), as Salary's ApproveSalaryNew: a new batch starts the + /// workflow (WFTYPE 33) with the login's employee as initiator. A batch an approver reverted back to its + /// initiator is submitted again from where it stopped, as ApproveSalaryForInitiator does. + /// + public LFAApprovalResult SubmitForApproval(LFAApprovalRequest request, int payrollTypeID, int? employeeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.LFAPaymentID <= 0) + throw new ServiceException("Please select a batch."); + if (!IsWorkflowRequired()) + { + result.Message = "The LFA approval workflow is off. Please approve the batch directly."; + return result; + } + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee. The approval workflow needs an employee to submit the batch."; + return result; + } + int empID = employeeID.Value; + string remarks = (request.Remarks ?? "").Trim(); + + tc = TransactionContext.Begin(true); + LFAPayment oPayment = GetForUpdate(tc, request.LFAPaymentID, payrollTypeID); + if (oPayment == null) + { + result.Message = "The batch is not found. It may have been undone."; + } + else if (oPayment.WFStatus == enumwfStatus.Approve) + { + result.Message = "Batch " + oPayment.BatchNumber + " is already approved."; + } + else if (oPayment.WFStatus == null || oPayment.WFStatus == enumwfStatus.Not_yet_Submitted) + { + // first submit: start the workflow + if (new WFRuleService().GetRules(tc, LFAPaymentApproval.WFTypeID).Count == 0) + { + result.Message = "No approval workflow is set up for LFA Payment. Please set it up in Work Flow Setup first."; + } + else if (!HasEmployees(tc, oPayment.ID)) + { + result.Message = "Batch " + oPayment.BatchNumber + " has no employee."; + } + else + { + LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); + string subject = "LFA payment batch " + oPayment.BatchNumber + " (payment date " + + oPayment.PaymentDate.ToString("dd-MMM-yyyy") + "). Your approval is required."; + try + { + new WFManager(oPayment).InitiateProcess(tc, empID, LFAPaymentApproval.WFTypeID, + oPayment.ID, remarks, subject); + } + catch (Exception wfError) + { + // e.g. no rule of the setup applies to this employee + throw new ServiceException("The approval workflow could not start: " + wfError.Message + + " Please check the LFA Payment rules in Work Flow Setup.", wfError); + } + result.Done = true; + result.Message = "Batch " + oPayment.BatchNumber + " is submitted for approval."; + } + } + else + { + // already in the workflow: only the initiator, after a revert, can submit it again + WorkflowState state = GetWorkflowState(tc, oPayment.ID); + if (state == null || !state.IsAtInitiator) + { + result.Message = "Batch " + oPayment.BatchNumber + " is submitted and pending for approval."; + } + else if (state.InitiatorEmpID != empID) + { + result.Message = "Only the employee who submitted batch " + oPayment.BatchNumber + " can submit it again."; + } + else + { + string subject = "LFA payment batch " + oPayment.BatchNumber + " is submitted again"; + WFMovementTran next = new WFManager().Approve(tc, state.WFMovementTranID, empID, + remarks, subject); + result.Approved = FinishStep(tc, oPayment, next, userID); + result.Done = true; + result.Message = result.Approved + ? "Batch " + oPayment.BatchNumber + " is approved." + : "Batch " + oPayment.BatchNumber + " is submitted for approval again."; + } + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// The batch an approver opened from the Payment Approval page, and whether they may act on it. + public LFAApproverBatch GetApproverBatch(int wfMovementTranID, int? employeeID) + { + LFAApproverBatch result = new LFAApproverBatch(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); + if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) + { + result.Message = "The LFA approval request is not found."; + } + else + { + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, oTran.ObjectID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null) + { + result.Message = "The LFA batch is not found. It may have been undone."; + } + else + { + dr = new DataReader(LFAPaymentDA.GetBatches(tc, oPayment.PayrollTypeID)); + while (dr.Read()) + { + if (dr.GetInt32("LFAPaymentID").Value == oPayment.ID) + { + result.Batch = MapBatch(dr); + break; + } + } + dr.Close(); + + dr = new DataReader(LFAPaymentDetailDA.GetBatchEmployees(tc, oPayment.ID)); + while (dr.Read()) + { + result.Employees.Add(MapBatchEmployee(dr)); + } + dr.Close(); + + result.CanAct = employeeID.GetValueOrDefault() > 0 + && oPayment.WFStatus != enumwfStatus.Approve + && LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID.Value); + if (!result.CanAct) + { + result.Message = oPayment.WFStatus == enumwfStatus.Approve + ? "Batch " + oPayment.BatchNumber + " is already approved." + : "This approval step is not pending with you any more."; + } + } + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// + /// An approver approves their step, as Salary's ApproveSalaryFromApprover: the workflow moves to the next + /// approver, or, after the last one, the batch is approved. + /// + public LFAApprovalResult ApproveFromApprover(LFAApproverActionRequest request, int? employeeID, int userID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.WFMovementTranID <= 0) + throw new ServiceException("The LFA approval request is not found."); + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee."; + return result; + } + + tc = TransactionContext.Begin(true); + LFAPayment oPayment; + string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + string subject = "LFA payment batch " + oPayment.BatchNumber + " has been approved"; + WFMovementTran next = new WFManager().Approve(tc, request.WFMovementTranID, + employeeID.Value, (request.Remarks ?? "").Trim(), subject); + result.Approved = FinishStep(tc, oPayment, next, userID); + result.Done = true; + result.Message = result.Approved + ? "Batch " + oPayment.BatchNumber + " is approved." + : "Batch " + oPayment.BatchNumber + " is approved by you and sent to the next approver."; + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + /// An approver reverts their step to the previous one (or to the initiator), as Salary's revert. + public LFAApprovalResult RevertFromApprover(LFAApproverActionRequest request, int? employeeID) + { + LFAApprovalResult result = new LFAApprovalResult(); + TransactionContext tc = null; + try + { + if (request == null || request.WFMovementTranID <= 0) + throw new ServiceException("The LFA approval request is not found."); + if (employeeID.GetValueOrDefault() <= 0) + { + result.Message = "Your login is not linked with an employee."; + return result; + } + string remarks = (request.Remarks ?? "").Trim(); + if (remarks.Length == 0) + { + result.Message = "Please write why the batch is reverted."; + return result; + } + + Employee oFromEmployee = new EmployeeService().Get(employeeID.Value); + tc = TransactionContext.Begin(true); + LFAPayment oPayment; + string blocked = CheckApproverStep(tc, request.WFMovementTranID, employeeID.Value, out oPayment); + if (blocked != null) + { + result.Message = blocked; + } + else + { + string subject = "(" + (oFromEmployee != null ? oFromEmployee.EmployeeNo + ")-" + oFromEmployee.Name : employeeID + ")") + + " has reverted LFA payment batch " + oPayment.BatchNumber; + new WFManager().RevertNew(tc, request.WFMovementTranID, employeeID.Value, remarks, subject); + result.Done = true; + result.Message = "Batch " + oPayment.BatchNumber + " is reverted."; + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return result; + } + + #region LFA Bank Advice + + /// LFA Bank Advice: only the approved batches of the payroll type can go to the bank. + public List GetBankAdviceBatches(int payrollTypeID) + { + return GetBatches(payrollTypeID).Where(x => x.WFStatus == enumwfStatus.Approve).ToList(); + } + + /// + /// The bank advice rows of one approved batch of the payroll type: the selected employees (sEmpIDs, + /// comma separated; empty = the whole batch), of one bank (bankID; 0 = every bank). Not approved, + /// or not of this payroll type, is refused. + /// + public System.Data.DataSet GetBankAdvice(int lfaPaymentID, string sEmpIDs, int bankID, int payrollTypeID) + { + // the IDs go into the SQL as %q, so only digits pass + string empIDs = string.Join(",", (sEmpIDs ?? string.Empty) + .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => int.TryParse(x.Trim(), out int id) ? id : 0) + .Where(id => id > 0) + .Distinct()); + + System.Data.DataSet ds = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.Get(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null || oPayment.PayrollTypeID != payrollTypeID) + throw new Exception("LFA payment batch not found."); + if (oPayment.WFStatus != enumwfStatus.Approve) + throw new Exception("LFA payment batch " + oPayment.BatchNumber + " is not approved yet."); + + ds = LFAPaymentDA.GetBankAdvice(tc, lfaPaymentID, empIDs, bankID, payrollTypeID); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + return ds; + } + + #endregion + + /// lfaapproval/workflow = Yes. + private static bool IsWorkflowRequired() + { + return new SystemConfigarationService().GetconfigBooleanValue(EnumConfigurationType.Logic, + LFAPaymentApproval.LogicParent, LFAPaymentApproval.LogicChild); + } + + /// The batch of the payroll type, locked until the transaction ends; null when not found. + private LFAPayment GetForUpdate(TransactionContext tc, int lfaPaymentID, int payrollTypeID) + { + LFAPayment oPayment = null; + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, lfaPaymentID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + return oPayment != null && oPayment.PayrollTypeID == payrollTypeID ? oPayment : null; + } + + private static string DirectApproveBlockedReason(LFAPayment oPayment) + { + if (oPayment.WFStatus == enumwfStatus.Approve) + return "Batch " + oPayment.BatchNumber + " is already approved."; + if (oPayment.WFStatus != null && oPayment.WFStatus != enumwfStatus.Not_yet_Submitted) + return "Batch " + oPayment.BatchNumber + " is in the approval workflow. It is approved from the Payment Approval page."; + return null; + } + + private static bool HasEmployees(TransactionContext tc, int lfaPaymentID) + { + DataReader dr = new DataReader(LFAPaymentDetailDA.GetByPaymentID(tc, lfaPaymentID)); + bool any = dr.Read(); + dr.Close(); + return any; + } + + /// + /// Why the employee cannot act on this step (null when they can): the step must be an LFA one, still the + /// latest of its workflow, pending with them, and its batch must exist and not be approved yet. + /// The batch is locked until the transaction ends. + /// + private string CheckApproverStep(TransactionContext tc, int wfMovementTranID, int employeeID, out LFAPayment oPayment) + { + oPayment = null; + WFMovementTran oTran = new WFMovementTranService().Get(tc, wfMovementTranID); + if (oTran == null || oTran.WFTypeID != LFAPaymentApproval.WFTypeID) + return "The LFA approval request is not found."; + + DataReader dr = new DataReader(LFAPaymentDA.GetForUpdate(tc, oTran.ObjectID)); + if (dr.Read()) + { + oPayment = this.CreateObject(dr); + } + dr.Close(); + + if (oPayment == null) + return "The LFA batch is not found. It may have been undone."; + if (oPayment.WFStatus == enumwfStatus.Approve) + return "Batch " + oPayment.BatchNumber + " is already approved."; + if (!LFAPaymentDA.IsPendingApprover(tc, wfMovementTranID, employeeID)) + return "This approval step is not pending with you any more."; + return null; + } + + /// + /// After a workflow step: the batch is approved when the workflow ended, otherwise it stays in the + /// workflow (Not_yet_Initiated), as Salary's ApproveSalaryNew. Returns true when approved. + /// + private static bool FinishStep(TransactionContext tc, LFAPayment oPayment, WFMovementTran next, int userID) + { + if (next != null && next.Status == EnumwfStatus.End) + { + LFAPaymentDA.Approve(tc, oPayment.ID, userID, DateTime.Now); + return true; + } + LFAPaymentDA.UpdateWFStatus(tc, oPayment.ID, enumwfStatus.Not_yet_Initiated); + return false; + } + + private class WorkflowState + { + public int WFMovementTranID; + public int InitiatorEmpID; + public bool IsAtInitiator; + } + + private static WorkflowState GetWorkflowState(TransactionContext tc, int lfaPaymentID) + { + WorkflowState state = null; + DataReader dr = new DataReader(LFAPaymentDA.GetWorkflowState(tc, lfaPaymentID)); + if (dr.Read()) + { + state = new WorkflowState + { + WFMovementTranID = dr.GetInt32("WFMovementTranID").Value, + InitiatorEmpID = dr.GetInt32("InitiatorEmpID", 0), + IsAtInitiator = dr.GetInt32("IsAtInitiator", 0) == 1 + }; + } + dr.Close(); + return state; + } + + private static bool GetIsAtInitiator(TransactionContext tc, int lfaPaymentID) + { + WorkflowState state = GetWorkflowState(tc, lfaPaymentID); + return state != null && state.IsAtInitiator; + } + + #endregion + + #region Helpers + + private static void CheckRequest(LFAPaymentRequest request) + { + if (request == null || request.Rows == null) + throw new ServiceException("Nothing to process."); + if (request.PaymentDate == null) + throw new ServiceException("Payment Date is required."); + } + + /// The current salary month: the last date of the month of PAYROLLTYPE.NEXTPAYPROCESSDATE. + private static DateTime GetSalaryMonth(int payrollTypeID) + { + PayrollType payrollType = new PayrollTypeService().Get(payrollTypeID); + if (payrollType == null || payrollType.ID <= 0) + throw new ServiceException("Payroll type not found."); + return GlobalFunctions.LastDateOfMonth(payrollType.NextPayProcessDate).Date; + } + + /// LFAYear: the last date of the payment date's month (the LFA is for that date's calendar year). + private static DateTime GetLFAYear(DateTime paymentDate) + { + return GlobalFunctions.LastDateOfMonth(paymentDate).Date; + } + + private static string BatchPrefix(DateTime salaryMonth) + { + return "LFA-" + salaryMonth.Year + "-"; + } + + private static string BatchNumber(string prefix, int no) + { + return prefix + no.ToString("000"); + } + + #endregion + } +} diff --git a/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs b/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs new file mode 100644 index 0000000..8c22596 --- /dev/null +++ b/HRM.DA/Service/LFA/LFAPaymentWorkbook.cs @@ -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 +{ + /// + /// The LFA payment workbook: builds the template from and reads + /// an uploaded one. Only what the file itself can tell is checked here. + /// + 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 + + /// The file's rows. Problems go into ; a row with one is not returned. + internal static List Read(Stream stream, string fileName, long fileLength, LFAPaymentReadResult result) + { + List rows = new List(); + + 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 wrong = new List(); + 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 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 }); + } + } + + /// What the cell holds, as text; an Employee ID stored as a number comes without separators. + 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 + } +} diff --git a/HRM.DA/Service/Salary/SalaryCalculator.cs b/HRM.DA/Service/Salary/SalaryCalculator.cs index f6e1934..91e5fcd 100644 --- a/HRM.DA/Service/Salary/SalaryCalculator.cs +++ b/HRM.DA/Service/Salary/SalaryCalculator.cs @@ -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 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() { diff --git a/HRM.Report/Class/rptLFABankAdvice.cs b/HRM.Report/Class/rptLFABankAdvice.cs new file mode 100644 index 0000000..12db918 --- /dev/null +++ b/HRM.Report/Class/rptLFABankAdvice.cs @@ -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 +{ + /// + /// 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. + /// + 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 parameters = new List + { + 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); + } + } +} diff --git a/HRM.Report/HRM.Report.csproj b/HRM.Report/HRM.Report.csproj index 0b3d320..3c8f9d2 100644 --- a/HRM.Report/HRM.Report.csproj +++ b/HRM.Report/HRM.Report.csproj @@ -61,6 +61,7 @@ + @@ -376,6 +377,7 @@ + diff --git a/HRM.Report/RDLC/LFABankAdvice.rdlc b/HRM.Report/RDLC/LFABankAdvice.rdlc new file mode 100644 index 0000000..801c4cb --- /dev/null +++ b/HRM.Report/RDLC/LFABankAdvice.rdlc @@ -0,0 +1,19 @@ + + +0 +SQL0484ed6e-5b42-4ef1-9904-d52d763ef1b2 +DummyDataSourcetrueSLNoSystem.Int32EmpNoSystem.StringEmpNameSystem.StringDesignationSystem.StringDepartmentSystem.StringCostCenterSystem.StringAccountNoSystem.StringBankSystem.StringBranchSystem.StringRoutingNoSystem.StringEmailSystem.StringAmountSystem.Double + +truetrue="LFA Bank Advice - LFA Year " & Parameters!LFAYear.Value0.05in0.1in0.25in7.5intruetrue="Batch No : " & Parameters!BatchNumber.Value & " Payment Date : " & Parameters!PaymentDate.Value0.32in0.1in0.22in7.5in0.35in0.85in1.9in1.3in1.35in0.85in0.9in0.25intruetrueSLSilverMiddle2pt2pt2pt2pttruetrueEmp IDSilverMiddle2pt2pt2pt2pttruetrueEmployee NameSilverMiddle2pt2pt2pt2pttruetrueAccount NoSilverMiddle2pt2pt2pt2pttruetrueBranchSilverMiddle2pt2pt2pt2pttruetrueRouting NoSilverMiddle2pt2pt2pt2pttruetrueAmount BDT.SilverMiddle2pt2pt2pt2pt0.22intruetrue="Bank : " & IIf(Fields!Bank.Value = "", "(No bank)", Fields!Bank.Value)WhiteSmokeMiddle2pt2pt2pt2pt70.22intruetrue=Fields!SLNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!EmpNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!EmpName.ValueMiddle2pt2pt2pt2pttruetrue=Fields!AccountNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!Branch.ValueMiddle2pt2pt2pt2pttruetrue=Fields!RoutingNo.ValueMiddle2pt2pt2pt2pttruetrue=Fields!Amount.ValueMiddle2pt2pt2pt2pt0.22intruetrue="Sub Total (" & CountRows() & " employees)"Middle2pt2pt2pt2pt6truetrue=Sum(Fields!Amount.Value)Middle2pt2pt2pt2pt0.25intruetrue="Total Amount (" & CountRows() & " employees)"SilverMiddle2pt2pt2pt2pt6truetrue=Sum(Fields!Amount.Value)SilverMiddle2pt2pt2pt2ptAftertruetrue=Fields!Bank.Value=Fields!Bank.ValueAftertrueBeforetrueBeforetruedsLFABankAdvice0.62in0.1in1.16in7.5in0.3in1.8in0.25in4intruetrue=Parameters!Address.Value0.55in1.8in0.2in4inExternal="file:///" & Parameters!Logo.Valueimage/pngFitProportional0.05in0.1in0.7in1.6in0.05in0.1in0.2in2.2intruetrue="Page " & Globals!PageNumber & " of " & Globals!TotalPages0.05in6.4in0.2in1.2in' + + '

LFA Payment History (' + this.displayDate(this.historyFrom) + ' - ' + this.displayDate(this.historyTo) + ')

' + + cells(['Batch ID', 'Payment Date', 'Employee ID', 'Name', 'Designation', 'Department', 'Joining Date', 'Basic Salary', + 'LFA Amount'], 'th') + + '' + body + '

' + this.escape(this.historySummary) + ' · LFA Amount ' + + money(this.historyTotalAmount) + '

'); + 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, '&').replace(//g, '>').replace(/"/g, '"'); + } + + private sum(items: T[], value: (item: T) => number): number { + return Math.round(items.reduce((total, x) => total + (value(x) || 0), 0) * 100) / 100; + } +} diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa-routing.module.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa-routing.module.ts new file mode 100644 index 0000000..7aceb7b --- /dev/null +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa-routing.module.ts @@ -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 { } diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts new file mode 100644 index 0000000..721d49f --- /dev/null +++ b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts @@ -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 { } diff --git a/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html b/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html index 230108c..f7d82d2 100644 --- a/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html +++ b/HRM.UI/ClientApp/src/app/payroll/career-and-profile/life-cycle-entry/life-cycle-entry.component.html @@ -193,11 +193,35 @@ kendoCheckBox /> -
+ +
} + @if (this.isPFPercentage == true) { +
+ +
+
:
+
+ + +
+ @if (this.isShowConfirmed != true) { +
+ } + } +