-
- LFA Payment
-
-
-
+
+
+
+
+
+ @if (selectedTab === 0) {
+
+
+
Approved LFA requests awaiting payment · 0 selected · Est. LFA amount 0.00
+
+ 0">
+
+
+
+
+
+
+
+
+
+ No records found.
+
+
+ }
+
+
+
+
+ @if (selectedTab === 1) {
+
+
+
+
+
+
+
+
+
+
+
+
+
Employees
{{ rows.length }}
+
Total Basic Salary
{{ totalBasic | number: '1.2-2' }}
+
Total LFA Amount (BDT)
{{ totalAmount | number: '1.2-2' }}
+
Batch ID (on process)
{{ rows.length > 0 && info ? info.nextBatchNumber : '—' }}
+
+
+
+
+
+ Total
+
+
+ {{ rows.length }} employees
+
+
+
+
+
+ {{ totalBasic | number: '1.2-2' }}
+
+
+ {{ totalAmount | number: '1.2-2' }}
+
+
+
+
+
+
+ No employees yet. Upload the Excel file.
+
+
+
+ @if (issues.length > 0) {
+
+ {{ issues.length }} error(s) found in the uploaded file. These rows are not in the list.
+
+
+ }
+
+
Uploaded file columns: Employee ID, Name. Amounts in BDT.
+
+ }
+
+
+
+
+ @if (selectedTab === 2) {
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ historyTotalBasic | number: '1.2-2' }}
+
+
+ {{ historyTotalAmount | number: '1.2-2' }}
+
+
+
+ {{ dataItem.statusText }}
+
+
+ No records found.
+
+
+
{{ historySummary }}
+
+ }
+
+
+
+@if (showConfirm) {
+
+
+ You are about to process LFA payment for {{ rows.length }} employee(s). This will create a new payment batch.
+
+
+ | Batch ID | {{ info ? info.nextBatchNumber : '' }} |
+ | Payment Date | {{ paymentDate | date: 'dd-MMM-yyyy' }} |
+ | Total LFA Amount | BDT {{ totalAmount | number: '1.2-2' }} |
+
+
+
+
+
+
+
+
+}
+
+
+@if (showIssues) {
+
+
+
+
+ {{ dataItem.rowNo > 0 ? dataItem.rowNo : 'File' }}
+
+
+
+
+ No errors.
+
+
+
+
+
+
+
+
+}
diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss
index e69de29..b6a1ee1 100644
--- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss
+++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.scss
@@ -0,0 +1,146 @@
+/* LFA Payment: layout only; colours are the theme's --gh-* variables */
+.lfa-month {
+ padding: 0 4px 8px;
+ color: var(--gh-lk);
+}
+
+.lfa-tab {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ padding: 8px 2px;
+}
+
+.lfa-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ gap: 12px;
+}
+
+.lfa-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ width: 180px;
+
+ label {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--gh-muted);
+ }
+}
+
+.lfa-field--wide {
+ width: 280px;
+}
+
+.lfa-field--remarks {
+ width: 360px;
+}
+
+.lfa-required {
+ color: var(--gh-dn);
+}
+
+.lfa-spacer {
+ flex: 1 1 auto;
+}
+
+.lfa-upload {
+ display: flex;
+ flex: 1 1 520px;
+ align-items: center;
+ gap: 6px;
+}
+
+.lfa-upload__file {
+ flex: 1 1 auto;
+ min-width: 0;
+ max-width: 520px;
+}
+
+.lfa-info,
+.lfa-note {
+ font-size: 12px;
+ color: var(--gh-muted);
+}
+
+.lfa-summary {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 12px;
+}
+
+.lfa-stat {
+ padding: 12px 14px;
+ border: 1px solid var(--gh-bo);
+ border-radius: 6px;
+ background: var(--gh-tb);
+}
+
+.lfa-stat__key {
+ font-size: 12px;
+ color: var(--gh-muted);
+}
+
+.lfa-stat__value {
+ margin-top: 4px;
+ font-size: 18px;
+ font-weight: 700;
+ color: var(--gh-lk);
+}
+
+.lfa-issues__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 6px;
+ font-weight: 600;
+ color: var(--gh-dn);
+}
+
+.lfa-right {
+ text-align: right;
+}
+
+.lfa-badge {
+ display: inline-block;
+ padding: 2px 10px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--gh-warn);
+ background: color-mix(in srgb, var(--gh-warn) 15%, transparent);
+}
+
+.lfa-badge--paid {
+ color: var(--gh-ok);
+ background: color-mix(in srgb, var(--gh-ok) 15%, transparent);
+}
+
+.lfa-badge--failed {
+ color: var(--gh-dn);
+ background: color-mix(in srgb, var(--gh-dn) 15%, transparent);
+}
+
+.lfa-confirm {
+ width: 100%;
+
+ td {
+ padding: 4px 0;
+ }
+
+ td:last-child {
+ text-align: right;
+ font-weight: 600;
+ }
+}
+
+@media (max-width: 640px) {
+ .lfa-field,
+ .lfa-field--wide,
+ .lfa-field--remarks {
+ width: 100%;
+ }
+}
diff --git a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts
index 013e9fb..42ba40e 100644
--- a/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts
+++ b/HRM.UI/ClientApp/src/app/payroll-lfa/lfa-payment/lfa-payment.component.ts
@@ -1,6 +1,20 @@
-import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
+import { Component, ElementRef, OnInit, ViewChild, ChangeDetectionStrategy } from '@angular/core';
+import * as fileSaver from 'file-saver';
+import { ExcelExportData } from '@progress/kendo-angular-excel-export';
+import { Observable } from 'rxjs';
import { ApiService } from '../../app.api.service';
+import { HRMNotificationService } from '../../app.notification.service';
+import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service';
+import { LFAService } from '../../_services/payroll/lfa.service';
+import {
+ EnumLFAPaymentStatus, LFAPaymentHistory, LFAPaymentInfo, LFAPaymentInput, LFAPaymentIssue,
+ LFAPaymentProcessResult, LFAPaymentReadResult, LFAPaymentRequest, LFAPaymentRow
+} from '../../_models/Payroll/lfaPayment';
+/**
+ * LFA Payment: LFA Request (design only for now), New LFA Payment (Excel upload → calculated grid → Process
+ * Payment) and Payment History. Every amount comes from the server, which calculates again on process.
+ */
@Component({
selector: 'app-lfa-payment',
templateUrl: './lfa-payment.component.html',
@@ -10,10 +24,419 @@ import { ApiService } from '../../app.api.service';
})
export class LfaPaymentComponent implements OnInit {
- constructor(public apiService: ApiService) {
+ @ViewChild('fileInput', { static: false }) fileInput: ElementRef
;
+
+ readonly maxFileSizeMB = 10;
+ readonly allDepartments = 'All departments';
+ readonly allStatuses = 'All statuses';
+
+ selectedTab = 0;
+ info: LFAPaymentInfo = null;
+
+ // ── LFA Request (design only; no data yet) ──
+ requests: any[] = [];
+ requestSearch = '';
+ requestDepartment = this.allDepartments;
+ requestFrom: Date = null;
+ requestTo: Date = null;
+
+ // ── New LFA Payment ──
+ paymentDate: Date = this.today();
+ remarks = '';
+ selectedFile: File = null; // picked, not uploaded yet
+ uploadedFile: File = null; // the file the list was read from
+ rows: LFAPaymentRow[] = [];
+ issues: LFAPaymentIssue[] = [];
+ totalBasic = 0;
+ totalAmount = 0;
+ isBusy = false;
+ showConfirm = false;
+ showIssues = false;
+ /** Employees taken out of the list; they stay out when the file is calculated again. */
+ private removedEmployeeNos: string[] = [];
+
+ // ── Payment History ──
+ historyFrom: Date = new Date(new Date().getFullYear(), 0, 1);
+ historyTo: Date = this.today();
+ historySearch = '';
+ historyStatus = this.allStatuses;
+ historyDepartment = this.allDepartments;
+ historyStatuses = [this.allStatuses, 'Pending', 'Paid', 'Failed'];
+ historyDepartments = [this.allDepartments];
+ history: LFAPaymentHistory[] = [];
+ historyRows: LFAPaymentHistory[] = [];
+ historyTotalBasic = 0;
+ historyTotalAmount = 0;
+ historySummary = '';
+
+ constructor(public apiService: ApiService,
+ public notificationService: HRMNotificationService,
+ public loadingPanel: loadingPanelService,
+ private lfaService: LFAService) {
this.apiService.selectedMenuName = 'LFA Payment';
}
ngOnInit() {
+ this.loadInfo();
+ }
+
+ private loadInfo() {
+ this.start();
+ this.lfaService.getPaymentInfo().subscribe({
+ next: (resp) => {
+ this.stop();
+ this.info = resp;
+ },
+ error: (err) => this.fail(err, 'Could not read the current salary month.')
+ });
+ }
+
+ onTabSelect(index: number) {
+ this.selectedTab = index;
+ this.selectedFile = null; // the file input is created again with its tab
+ if (index === 2) {
+ this.loadHistory();
+ }
+ }
+
+ // ── New LFA Payment: upload and calculate ───────────────────────
+
+ downloadTemplate() {
+ this.start();
+ this.lfaService.downloadTemplate().subscribe({
+ next: (file) => {
+ this.stop();
+ fileSaver.saveAs(file, 'LFA-Payment-Template.xlsx');
+ },
+ error: (err) => this.fail(err, 'Could not download the template.')
+ });
+ }
+
+ /** The same file can be picked again after a correction. */
+ clearSelectedFile() {
+ this.selectedFile = null;
+ if (this.fileInput) {
+ this.fileInput.nativeElement.value = '';
+ }
+ }
+
+ selectFile(event: Event) {
+ const input = event.target as HTMLInputElement;
+ this.selectedFile = input.files && input.files.length > 0 ? input.files[0] : null;
+ }
+
+ uploadFile() {
+ if (!this.paymentDate) {
+ this.notificationService.showWarning('Please select the Payment Date first.');
+ return;
+ }
+ if (!this.selectedFile) {
+ this.notificationService.showWarning('Please choose a file first.');
+ return;
+ }
+ this.upload(this.selectedFile);
+ }
+
+ private upload(file: File) {
+ if (!file.name.toLowerCase().endsWith('.xlsx')) {
+ this.notificationService.showError('Only .xlsx files are allowed. Please use the downloaded template.');
+ return;
+ }
+ if (file.size > this.maxFileSizeMB * 1024 * 1024) {
+ this.notificationService.showError('The file is larger than ' + this.maxFileSizeMB + ' MB.');
+ return;
+ }
+ this.uploadedFile = file;
+ this.removedEmployeeNos = [];
+ this.calculate(true);
+ }
+
+ /** The Payment Date decides who has completed 6 months. */
+ onPaymentInfoChange() {
+ if (this.paymentDate && (this.uploadedFile || this.rows.length > 0)) {
+ this.calculate(false);
+ }
+ }
+
+ private calculate(isUpload: boolean) {
+ const date = this.dateText(this.paymentDate);
+ const call: Observable = this.uploadedFile
+ ? this.lfaService.readUpload(this.uploadedFile, date)
+ : this.lfaService.calculatePayment(this.request());
+ this.start();
+ call.subscribe({
+ next: (resp) => {
+ this.stop();
+ this.applyResult(resp);
+ if (isUpload) {
+ this.showUploadMessage();
+ }
+ },
+ error: (err) => {
+ this.setRows([]);
+ this.issues = [];
+ this.fail(err, 'Could not calculate the LFA. Please upload the file again.');
+ }
+ });
+ }
+
+ private showUploadMessage() {
+ if (this.rows.length === 0) {
+ this.notificationService.showError('No employee of the file can be paid. Please check the error list.');
+ } else if (this.issues.length > 0) {
+ this.notificationService.showWarning(this.rows.length + ' employee(s) loaded. Some rows have errors; please check the error list.');
+ } else {
+ this.notificationService.showSuccess(this.rows.length + ' employee(s) loaded.');
+ }
+ }
+
+ private applyResult(result: LFAPaymentReadResult) {
+ this.issues = (result.issues || []).filter(x => !this.isRemoved(x.employeeNo));
+ this.showIssues = this.issues.length > 0; // every validation problem is listed in the error dialog
+ this.setRows((result.rows || []).filter(x => !this.isRemoved(x.employeeNo)).map(x => ({
+ ...x,
+ joiningDate: this.toDate(x.joiningDate),
+ confirmationDate: this.toDate(x.confirmationDate),
+ paymentDate: this.toDate(x.paymentDate)
+ })));
+ }
+
+ private setRows(rows: LFAPaymentRow[]) {
+ this.rows = rows;
+ this.totalBasic = this.sum(rows, x => x.basicSalary);
+ this.totalAmount = this.sum(rows, x => x.amount);
+ }
+
+ removeRow(row: LFAPaymentRow) {
+ this.removedEmployeeNos.push(row.employeeNo);
+ this.setRows(this.rows.filter(x => x !== row));
+ }
+
+ private isRemoved(employeeNo: string): boolean {
+ return this.removedEmployeeNos.indexOf(employeeNo) >= 0;
+ }
+
+ clear() {
+ if (this.rows.length === 0 && this.issues.length === 0) {
+ this.resetPayment();
+ return;
+ }
+ this.notificationService.showActiveConfirm('Confirmation', 'Clear the payment list?').then((isConfirmed) => {
+ if (isConfirmed) {
+ this.resetPayment();
+ }
+ });
+ }
+
+ private resetPayment() {
+ this.clearSelectedFile();
+ this.uploadedFile = null;
+ this.removedEmployeeNos = [];
+ this.issues = [];
+ this.showIssues = false;
+ this.remarks = '';
+ this.setRows([]);
+ }
+
+ allPaymentRows = (): ExcelExportData => ({ data: this.rows });
+ allIssues = (): ExcelExportData => ({ data: this.issues });
+
+ // ── New LFA Payment: process ────────────────────────────────────
+
+ confirmProcess() {
+ if (!this.paymentDate) {
+ this.notificationService.showWarning('Payment Date is required.');
+ return;
+ }
+ if (this.rows.length === 0) {
+ this.notificationService.showWarning('Add at least one employee.');
+ return;
+ }
+ this.showConfirm = true;
+ }
+
+ process() {
+ if (this.isBusy) {
+ return;
+ }
+ this.start();
+ this.lfaService.processPayment(this.request()).subscribe({
+ next: (resp: LFAPaymentProcessResult) => {
+ this.stop();
+ this.showConfirm = false;
+ if (!resp.saved) {
+ if (resp.validation) {
+ this.applyResult(resp.validation);
+ }
+ this.notificationService.showError(resp.message);
+ return;
+ }
+ this.notificationService.showSuccess(resp.message);
+ this.resetPayment();
+ this.includeInHistory(this.paymentDate);
+ this.loadInfo();
+ this.onTabSelect(2);
+ },
+ error: (err) => {
+ this.showConfirm = false;
+ this.fail(err, 'Nothing was saved. Please try again.');
+ }
+ });
+ }
+
+ private request(): LFAPaymentRequest {
+ return {
+ paymentDate: this.dateText(this.paymentDate),
+ remarks: this.remarks,
+ rows: this.rows.map((x): LFAPaymentInput => ({
+ rowNo: x.rowNo,
+ employeeNo: x.employeeNo
+ })),
+ expectedTotal: this.totalAmount
+ };
+ }
+
+ // ── Payment History ─────────────────────────────────────────────
+
+ loadHistory() {
+ if (!this.historyFrom || !this.historyTo) {
+ this.notificationService.showWarning('Start Date and End Date are required.');
+ return;
+ }
+ if (this.historyFrom > this.historyTo) {
+ this.notificationService.showWarning('Start Date cannot be after End Date.');
+ return;
+ }
+ this.start();
+ this.lfaService.getPaymentHistory(this.dateText(this.historyFrom), this.dateText(this.historyTo)).subscribe({
+ next: (resp) => {
+ this.stop();
+ this.history = (resp || []).map(x => ({
+ ...x,
+ paymentDate: this.toDate(x.paymentDate),
+ joiningDate: this.toDate(x.joiningDate),
+ statusText: EnumLFAPaymentStatus[x.paymentStatus]
+ }));
+ this.historyDepartments = [this.allDepartments].concat(
+ Array.from(new Set(this.history.map(x => x.departmentName).filter(x => !!x))).sort());
+ if (this.historyDepartments.indexOf(this.historyDepartment) < 0) {
+ this.historyDepartment = this.allDepartments;
+ }
+ this.filterHistory();
+ },
+ error: (err) => this.fail(err, 'Could not load the payment history.')
+ });
+ }
+
+ filterHistory() {
+ const search = (this.historySearch || '').trim().toLowerCase();
+ this.historyRows = this.history.filter(x =>
+ (this.historyStatus === this.allStatuses || x.statusText === this.historyStatus)
+ && (this.historyDepartment === this.allDepartments || x.departmentName === this.historyDepartment)
+ && (!search || [x.batchNumber, x.employeeNo, x.name, x.designationName, x.departmentName]
+ .some(v => (v || '').toLowerCase().indexOf(search) >= 0)));
+ this.historyTotalBasic = this.sum(this.historyRows, x => x.basicSalary);
+ this.historyTotalAmount = this.sum(this.historyRows, x => x.amount);
+ const count = (status: EnumLFAPaymentStatus) => this.historyRows.filter(x => x.paymentStatus === status).length;
+ this.historySummary = 'Total ' + this.historyRows.length + ' records · '
+ + new Set(this.historyRows.map(x => x.batchNumber)).size + ' batch(es) · Paid ' + count(EnumLFAPaymentStatus.Paid)
+ + ' · Pending ' + count(EnumLFAPaymentStatus.Pending) + ' · Failed ' + count(EnumLFAPaymentStatus.Failed);
+ }
+
+ allHistoryRows = (): ExcelExportData => ({ data: this.historyRows });
+
+ printHistory() {
+ if (this.historyRows.length === 0) {
+ this.notificationService.showWarning('Nothing to print.');
+ return;
+ }
+ const w = window.open('', '_blank');
+ if (!w) {
+ this.notificationService.showWarning('Please allow pop-ups to print.');
+ return;
+ }
+ const money = (n: number) => this.money(n);
+ const cells = (values: any[], tag: string) => values.map(v => '<' + tag + '>' + this.escape(v) + '' + tag + '>').join('');
+ const body = this.historyRows.map(x => '' + cells([x.batchNumber, this.displayDate(x.paymentDate), x.employeeNo, x.name,
+ x.designationName, x.departmentName, this.displayDate(x.joiningDate), money(x.basicSalary), money(x.amount),
+ x.statusText], 'td') + '
').join('');
+ w.document.write('LFA Payment History'
+ + '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', 'Payment Status'], '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.module.ts b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts
index 005e5b2..152ac29 100644
--- a/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts
+++ b/HRM.UI/ClientApp/src/app/payroll-lfa/payroll-lfa.module.ts
@@ -1,9 +1,17 @@
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';
@@ -19,8 +27,17 @@ import { LfaBankAdviceComponent } from './lfa-bank-advice/lfa-bank-advice.compon
imports: [
CommonModule,
PayrollLfaRoutingModule,
+ FormsModule,
LoadingPanelModule,
- CardModule
+ CardModule,
+ TabViewCompatModule,
+ GridModule,
+ ExcelModule,
+ ButtonsModule,
+ DropDownListModule,
+ DatePickerModule,
+ TextBoxModule,
+ DialogsModule
]
})
export class PayrollLfaModule { }
diff --git a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs
index 7ca7791..f188c22 100644
--- a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs
+++ b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs
@@ -366,6 +366,9 @@ namespace HRM.UI.Configuration.DI
services.AddTransient();
services.AddTransient();
+ //LFA
+ services.AddTransient();
+
//Fund
services.AddTransient();
services.AddTransient();
diff --git a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs
index 926f32e..9a73017 100644
--- a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs
+++ b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs
@@ -25,13 +25,15 @@ namespace HRM.UI.Controllers.Payroll
private readonly IEmployeePhotoBulkUploadService _employeePhotoBulkUploadService;
private readonly ICacheManager _cashManager;
private readonly IBonusProcessService _bonusProcessService;
+ private readonly ILFAPaymentService _lfaPaymentService;
public DataUploadController(IDataUploadColumnDefinition columnDefination,
IEmployeeBulkUploadService employeeBulkUploadService,
ISalaryMasterBulkUploadService salaryMasterBulkUploadService,
IEmployeePhotoBulkUploadService employeePhotoBulkUploadService,
ICacheManager cashManager,
- IBonusProcessService bonusProcessService)
+ IBonusProcessService bonusProcessService,
+ ILFAPaymentService lfaPaymentService)
{
this._columnDefination = columnDefination;
this._employeeBulkUploadService = employeeBulkUploadService;
@@ -39,6 +41,7 @@ namespace HRM.UI.Controllers.Payroll
this._employeePhotoBulkUploadService = employeePhotoBulkUploadService;
this._cashManager = cashManager;
this._bonusProcessService = bonusProcessService;
+ this._lfaPaymentService = lfaPaymentService;
}
// loan
@@ -586,6 +589,60 @@ namespace HRM.UI.Controllers.Payroll
#endregion
+ #region LFA Payment Upload
+
+ /// The empty LFA payment workbook: Employee ID and Name.
+ [HttpGet("lfa-payment-upload-template")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult GetLFAPaymentUploadTemplate()
+ {
+ try
+ {
+ return File(this._lfaPaymentService.GetUploadTemplate(),
+ LFAPaymentUploadTemplate.ContentType, LFAPaymentUploadTemplate.FileName);
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ ///
+ /// Reads a filled LFA payment workbook (multipart form: first file, plus "paymentDate")
+ /// and returns the calculated employees and every problem. Nothing is saved.
+ ///
+ [HttpPost("lfa-payment-upload-read")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult ReadLFAPaymentUpload()
+ {
+ CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
+ if (currentUser.UserType == EnumUserType.Employee)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment.");
+ }
+ IFormFile file = Request.Form.Files.Count > 0 ? Request.Form.Files[0] : null;
+ DateTime paymentDate;
+ if (!DateTime.TryParse(Request.Form["paymentDate"].FirstOrDefault(), out paymentDate))
+ {
+ return BadRequest("Payment Date is required.");
+ }
+
+ try
+ {
+ using (Stream stream = file == null ? null : file.OpenReadStream())
+ {
+ return Ok(this._lfaPaymentService.ReadUpload(stream, file == null ? null : file.FileName,
+ file == null ? 0 : file.Length, paymentDate, this.CurrentPayrollTypeID(0)));
+ }
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ #endregion
+
/// The "salaryMonth" form field (the month picked on the page) as the last date of that month.
private bool TryGetPostedSalaryMonth(out DateTime salaryMonth)
{
diff --git a/HRM.UI/Controllers/Payroll/LFAController.cs b/HRM.UI/Controllers/Payroll/LFAController.cs
new file mode 100644
index 0000000..947c83a
--- /dev/null
+++ b/HRM.UI/Controllers/Payroll/LFAController.cs
@@ -0,0 +1,104 @@
+using System;
+using HRM.BO;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+
+namespace HRM.UI.Controllers.Payroll
+{
+ ///
+ /// Core Payroll > LFA. The Excel template and upload are in DataUploadController, with every other uploader.
+ ///
+ [Route("api/lfa")]
+ [Authorize]
+ [ApiController]
+ public class LFAController : ControllerBase
+ {
+ private readonly ILFAPaymentService _lfaPaymentService;
+
+ public LFAController(ILFAPaymentService lfaPaymentService)
+ {
+ this._lfaPaymentService = lfaPaymentService;
+ }
+
+ /// The current salary month and the next batch number.
+ [HttpGet("getPaymentInfo")]
+ public ActionResult GetPaymentInfo()
+ {
+ CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
+ if (currentUser.UserType == EnumUserType.Employee)
+ {
+ return NotAllowed();
+ }
+ try
+ {
+ return Ok(this._lfaPaymentService.GetInfo(currentUser.PayrollTypeID.GetValueOrDefault()));
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ /// Calculates the rows again; nothing is saved.
+ [HttpPost("calculatePayment")]
+ public ActionResult CalculatePayment(LFAPaymentRequest request)
+ {
+ CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
+ if (currentUser.UserType == EnumUserType.Employee)
+ {
+ return NotAllowed();
+ }
+ try
+ {
+ return Ok(this._lfaPaymentService.Calculate(request, currentUser.PayrollTypeID.GetValueOrDefault()));
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ /// Saves the rows as a new batch, all or nothing. The payroll type and user come from the token.
+ [HttpPost("processPayment")]
+ public ActionResult ProcessPayment(LFAPaymentRequest request)
+ {
+ CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
+ if (currentUser.UserType == EnumUserType.Employee)
+ {
+ return NotAllowed();
+ }
+ try
+ {
+ return Ok(this._lfaPaymentService.Process(request, currentUser.PayrollTypeID.GetValueOrDefault(), currentUser.UserID));
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ [HttpGet("getPaymentHistory/{fromDate}/{toDate}")]
+ public ActionResult GetPaymentHistory(DateTime fromDate, DateTime toDate)
+ {
+ CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
+ if (currentUser.UserType == EnumUserType.Employee)
+ {
+ return NotAllowed();
+ }
+ try
+ {
+ return Ok(this._lfaPaymentService.GetHistory(fromDate, toDate, currentUser.PayrollTypeID.GetValueOrDefault()));
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
+
+ private ActionResult NotAllowed()
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to process LFA payment.");
+ }
+ }
+}
diff --git a/LFA_DB_Changes.sql b/LFA_DB_Changes.sql
new file mode 100644
index 0000000..d4cb0a5
--- /dev/null
+++ b/LFA_DB_Changes.sql
@@ -0,0 +1,146 @@
+/* =====================================================================
+ LFA_DB_Changes.sql
+
+ Leave Fare Assistance (Core Payroll > LFA). Three tables:
+
+ dbo.LFARequest who asked for LFA, for which leave (LFA Request tab)
+ dbo.LFAPayment one payment batch (like SalaryProcess)
+ dbo.LFAPaymentDetail one employee of a batch (like SalaryMonthly)
+
+ - Part 0 DROPS the three tables, Parts 1-3 create them again. The drop is
+ refused, and nothing runs, when any of the tables already holds rows.
+ - LFAYear is a DATETIME in all three tables: the last date of the calendar
+ year the LFA is for (2026 = 31-Dec-2026), as SalaryMonth is the last date
+ of its month.
+ - IDs are generated by the application (tc.GenerateID), no IDENTITY.
+ - A detail row is a snapshot: grade, department, bank account and basic are
+ kept as they were when the batch was processed.
+ - Columns that point to existing tables (EMPLOYEE, DEPARTMENT, GRADES, CRG,
+ BRANCHES, LEAVEENTRY ...) have no foreign key, as in Calendar_DB_Changes.sql.
+
+ Run order: once per database, together with the LFA code.
+ ===================================================================== */
+SET ANSI_NULLS ON;
+SET QUOTED_IDENTIFIER ON;
+GO
+
+/* ---------- 0. Drop (child table first) ---------- */
+IF EXISTS (SELECT 1 FROM sys.partitions
+ WHERE object_id IN (OBJECT_ID(N'dbo.LFAPaymentDetail', N'U'), OBJECT_ID(N'dbo.LFAPayment', N'U'), OBJECT_ID(N'dbo.LFARequest', N'U'))
+ AND index_id IN (0, 1) AND rows > 0)
+BEGIN
+ RAISERROR('The LFA tables hold data. Nothing was dropped or created. Back up and clear them first.', 16, 1);
+ SET NOEXEC ON; -- skips the rest of this script
+END
+GO
+DROP TABLE IF EXISTS dbo.LFAPaymentDetail;
+DROP TABLE IF EXISTS dbo.LFAPayment;
+DROP TABLE IF EXISTS dbo.LFARequest;
+GO
+
+/* ---------- 1. dbo.LFARequest ---------- */
+CREATE TABLE dbo.LFARequest (
+ LFARequestID INT NOT NULL,
+ PayrollTypeID INT NOT NULL,
+ EmployeeID INT NOT NULL,
+ LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for
+ LeaveEntryID INT NULL, -- LEAVEENTRY.TRANID of the LFA leave
+ RequestDate DATETIME NOT NULL,
+ LeaveFromDate DATETIME NOT NULL, -- LFA Start Date
+ LeaveToDate DATETIME NOT NULL, -- LFA End Date
+ LeaveDays DECIMAL(9, 2) NOT NULL,
+ Remarks NVARCHAR(500) NULL,
+ Status TINYINT NOT NULL CONSTRAINT DF_LFARequest_Status DEFAULT (1), -- 1 Pending, 2 Approved, 3 Rejected, 4 Cancelled
+ WFStatus INT NULL, -- enumwfStatus; NULL = not submitted
+ CreatedBy INT NOT NULL,
+ CreationDate DATETIME NOT NULL,
+ ModifiedBy INT NULL,
+ ModifiedDate DATETIME NULL,
+
+ CONSTRAINT PK_LFARequest PRIMARY KEY (LFARequestID),
+ CONSTRAINT CK_LFARequest_Dates CHECK (LeaveToDate >= LeaveFromDate),
+ CONSTRAINT CK_LFARequest_Status CHECK (Status IN (1, 2, 3, 4))
+);
+GO
+/* one open or approved request per employee per calendar year */
+CREATE UNIQUE INDEX UX_LFARequest_EmployeeYear ON dbo.LFARequest (EmployeeID, LFAYear) WHERE Status IN (1, 2);
+GO
+/* LFA Request tab: approved requests of a payroll type */
+CREATE INDEX IX_LFARequest_List ON dbo.LFARequest (PayrollTypeID, Status, LeaveFromDate);
+GO
+
+/* ---------- 2. dbo.LFAPayment ---------- */
+CREATE TABLE dbo.LFAPayment (
+ LFAPaymentID INT NOT NULL,
+ BatchNumber VARCHAR(30) NOT NULL, -- LFA-2026-001
+ PayrollTypeID INT NOT NULL,
+ SalaryMonth DATETIME NOT NULL, -- last date of PAYROLLTYPE.NEXTPAYPROCESSDATE's month
+ LFAYear DATETIME NOT NULL, -- last date of the calendar year the LFA is for
+ PaymentDate DATETIME NOT NULL,
+ Remarks NVARCHAR(500) NULL,
+ IsTaxUpdated BIT NOT NULL CONSTRAINT DF_LFAPayment_IsTaxUpdated DEFAULT (0), -- 1 = the batch is already in the income tax data
+ WFStatus INT NULL, -- enumwfStatus; NULL = not submitted
+ ApprovedBy INT NULL,
+ ApprovedDate DATETIME NULL,
+ CreatedBy INT NOT NULL,
+ CreationDate DATETIME NOT NULL,
+ ModifiedBy INT NULL,
+ ModifiedDate DATETIME NULL,
+
+ CONSTRAINT PK_LFAPayment PRIMARY KEY (LFAPaymentID),
+ CONSTRAINT UQ_LFAPayment_BatchNumber UNIQUE (PayrollTypeID, BatchNumber)
+);
+GO
+/* Payment, Undo and Approval pages: the batches of a payroll type and month */
+CREATE INDEX IX_LFAPayment_Month ON dbo.LFAPayment (PayrollTypeID, SalaryMonth) INCLUDE (WFStatus);
+GO
+/* Payment History tab: date range */
+CREATE INDEX IX_LFAPayment_PaymentDate ON dbo.LFAPayment (PayrollTypeID, PaymentDate);
+GO
+
+/* ---------- 3. dbo.LFAPaymentDetail ---------- */
+CREATE TABLE dbo.LFAPaymentDetail (
+ LFAPaymentDetailID INT NOT NULL,
+ LFAPaymentID INT NOT NULL,
+ EmployeeID INT NOT NULL,
+ LFAYear DATETIME NOT NULL, -- same value as LFAPayment.LFAYear
+
+ /* employee snapshot */
+ JoiningDate DATETIME NOT NULL,
+ ConfirmationDate DATETIME NULL,
+ GradeID INT NULL,
+ DesignationID INT NULL,
+ DepartmentID INT NULL,
+ CostCenterID INT NULL, -- CRG.CRGID
+ BranchID INT NULL, -- bank branch, for Bank Advice
+ AccountNo VARCHAR(50) NULL,
+
+ /* calculation */
+ JoiningBasic MONEY NULL,
+ LastDecBasic MONEY NULL, -- basic as of 31 Dec of the preceding year; NULL = joined in LFAYear
+ BasicSalary MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_BasicSalary DEFAULT (0), -- basic the LFA was calculated on
+ CalculatedAmount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_CalculatedAmount DEFAULT (0), -- before rounding
+ Amount MONEY NOT NULL CONSTRAINT DF_LFAPayDtl_Amount DEFAULT (0), -- LFA amount to pay
+
+ Remarks NVARCHAR(500) NULL,
+ PaymentStatus TINYINT NOT NULL CONSTRAINT DF_LFAPayDtl_PaymentStatus DEFAULT (1), -- 1 Pending, 2 Paid, 3 Failed
+ CreatedBy INT NOT NULL,
+ CreationDate DATETIME NOT NULL,
+ ModifiedBy INT NULL,
+ ModifiedDate DATETIME NULL,
+
+ CONSTRAINT PK_LFAPaymentDetail PRIMARY KEY (LFAPaymentDetailID),
+ CONSTRAINT FK_LFAPayDtl_Payment FOREIGN KEY (LFAPaymentID) REFERENCES dbo.LFAPayment (LFAPaymentID),
+ CONSTRAINT CK_LFAPayDtl_Amount CHECK (Amount >= 0),
+ CONSTRAINT CK_LFAPayDtl_PaymentStatus CHECK (PaymentStatus IN (1, 2, 3))
+);
+GO
+/* policy: LFA once in a calendar year (Undo deletes the rows, which frees the employee again) */
+CREATE UNIQUE INDEX UX_LFAPayDtl_EmployeeYear ON dbo.LFAPaymentDetail (EmployeeID, LFAYear);
+GO
+/* the rows of one batch */
+CREATE INDEX IX_LFAPayDtl_Payment ON dbo.LFAPaymentDetail (LFAPaymentID);
+GO
+
+SET NOEXEC OFF;
+GO