HRM-10/HRM.UI/ClientApp/src/app/ess/component-approval/component-approval.component.ts

296 lines
11 KiB
TypeScript
Raw Normal View History

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { BasicService } from 'src/app/_services/Basic/basic.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { EnumComponentType } from 'src/app/_models/enums';
import { ApiService } from 'src/app/app.api.service';
interface OverviewCard {
title: string;
total: number;
approved: number;
pending: number;
iconType: string;
}
interface PendingRequest {
id: number;
type: string;
iconType: string;
employee: string;
employeeId: string;
initials: string;
requestedDate: string;
requestedTime: string;
salaryMonth: string;
description: string;
status: string;
// raw keys used for approval
_uploadedComponentId: number;
_empId: number;
_componentID: number;
_componentType: number;
_componentName: string;
_amount: number;
_empCount: number;
}
interface BreakdownRow {
employeeNo: string;
name: string;
amount: number;
}
@Component({
selector: 'app-ess-component-approval',
templateUrl: './component-approval.component.html',
styleUrls: ['./component-approval.component.css'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
/** ESS Component Approval (/ess/component-approval), as GP's /hress-approval-state/approval. */
export class EssComponentApprovalComponent implements OnInit {
alertCount = 0;
lastUpdated = '';
// current salary month + approval deadline (admin-set date, re-anchored to the salary month)
salaryMonth: Date | null = null;
deadlinePassed = false;
approvalDeadline: Date | null = null;
overviewCards: OverviewCard[] = [];
pendingRequests: PendingRequest[] = [];
// review dialog
showReviewModal = false;
modalRequest: PendingRequest | null = null;
modalRows: BreakdownRow[] = [];
private modalRowsAll: BreakdownRow[] = [];
modalSearch = '';
modalTotal = 0;
constructor(
private basicService: BasicService,
private loadingPanel: loadingPanelService,
private notify: HRMNotificationService,
private apiService: ApiService,
) {
this.apiService.selectedMenuName = 'Component Approval';
}
ngOnInit(): void {
this.loadDeadline();
this.loadApproverData();
}
private loadDeadline(): void {
this.basicService.getComponentUploadDeadline().subscribe(
(resp: any) => {
this.deadlinePassed = !!resp && resp.allowed === false;
this.approvalDeadline = (resp && resp.deadline) ? new Date(resp.deadline) : null;
if (resp && resp.salaryMonth) { this.salaryMonth = new Date(resp.salaryMonth); }
},
() => {},
);
}
// ───────────────────────── data ─────────────────────────
private loadApproverData(): void {
this.loadingPanel.ShowLoadingPanel = true;
this.basicService.getApproverComponentUploadDT().subscribe(
(resp: any) => {
const rows: any[] = Array.isArray(resp) ? resp : [];
this.pendingRequests = rows.map((r, i) => this.toRequest(r, i));
this.overviewCards = this.buildOverview(rows);
this.alertCount = this.pendingRequests.filter(r => r.status === 'Pending').length;
this.lastUpdated = new Date().toLocaleString('en-US', {
month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit',
});
},
() => { this.loadingPanel.ShowLoadingPanel = false; },
() => { this.loadingPanel.ShowLoadingPanel = false; },
);
}
private toRequest(r: any, index: number): PendingRequest {
const parts = String(r.employeeNoName || '').split('-');
const empNo = parts.length > 1 ? parts[0].trim() : '';
const name = parts.length > 1 ? parts.slice(1).join('-').trim() : String(r.employeeNoName || '').trim();
const empCount = Number(r.empCount) || 0;
return {
id: index,
type: r.componentName || 'Component',
iconType: 'component',
employee: name,
employeeId: empNo ? ('ID: ' + empNo) : '',
initials: this.initials(name),
requestedDate: r.uploadedDate || '',
requestedTime: '',
salaryMonth: r.salaryMonth || '—',
description: (empCount ? (empCount + ' employee' + (empCount > 1 ? 's' : '')) : '—')
+ (r.amount ? (' · total ' + (Number(r.amount) || 0).toLocaleString('en-US')) : ''),
status: r.status || 'Pending',
_uploadedComponentId: Number(r.uploadedComponentId) || 0,
_empId: Number(r.empId) || 0,
_componentID: Number(r.componentID) || 0,
_componentType: this.toComponentTypeNum(r.componentType),
_componentName: r.componentName || '',
_amount: Number(r.amount) || 0,
_empCount: empCount,
};
}
private buildOverview(rows: any[]): OverviewCard[] {
const groups = new Map<string, { total: number; approved: number; pending: number }>();
for (const r of rows) {
const key = r.componentName || 'Component';
const g = groups.get(key) || { total: 0, approved: 0, pending: 0 };
g.total++;
if (r.status === 'Approved') { g.approved++; } else { g.pending++; }
groups.set(key, g);
}
return Array.from(groups.entries()).map(([title, g]) => ({
title, total: g.total, approved: g.approved, pending: g.pending, iconType: 'component',
}));
}
// ───────────────────────── actions ─────────────────────────
// Review → open the dialog showing the uploaded per-employee breakdown.
reviewRequest(req: PendingRequest): void {
if (req.status !== 'Pending') { return; }
if (this.deadlinePassed) {
this.notify.showWarning('The approval date for this salary month has passed. Approval is no longer allowed.');
return;
}
this.loadingPanel.ShowLoadingPanel = true;
this.basicService.viewUploadedComponentForApprover(req._uploadedComponentId).subscribe(
(resp: any) => {
const rows: any[] = Array.isArray(resp) ? resp : [];
this.modalRowsAll = rows.map(x => ({
employeeNo: this.pick(x, 'employeeNo', 'EmployeeNo', 'EMPLOYEENO'),
name: this.pick(x, 'name', 'Name', 'NAME'),
amount: Number(this.pick(x, 'amount', 'Amount', 'AMOUNT')) || 0,
}));
this.modalTotal = this.modalRowsAll.reduce((s, r) => s + (r.amount || 0), 0);
},
() => { this.loadingPanel.ShowLoadingPanel = false; },
() => {
this.modalRows = [...this.modalRowsAll];
this.modalSearch = '';
this.modalRequest = req;
this.showReviewModal = true;
this.loadingPanel.ShowLoadingPanel = false;
},
);
}
filterModalRows(text: string): void {
const q = (text || '').toLowerCase();
this.modalRows = this.modalRowsAll.filter(r =>
Object.values(r).some(v => v != null && v.toString().toLowerCase().includes(q)),
);
}
closeReviewModal(): void {
this.showReviewModal = false;
this.modalRequest = null;
this.modalRows = [];
this.modalRowsAll = [];
}
approveFromModal(): void { if (this.modalRequest) { this.approveRequest(this.modalRequest); } }
rejectFromModal(): void { if (this.modalRequest) { this.rejectRequest(this.modalRequest); } }
approveRequest(req: PendingRequest): void {
if (!req || req.status !== 'Pending') { return; }
if (this.deadlinePassed) {
this.notify.showWarning('The approval date for this salary month has passed. Approval is no longer allowed.');
return;
}
this.notify.showActiveConfirm('Approve Component',
`Approve "${req.type}" uploaded by ${req.employee || 'employee'}? A confirmation mail will be sent.`).then((ok: boolean) => {
if (!ok) { return; }
this.loadingPanel.ShowLoadingPanel = true;
this.basicService.approveComponentUploadByKey(req._empId, req._componentID, req._componentType).subscribe(
() => {},
(err: any) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notify.showError(typeof err?.error === 'string' ? err.error : 'Failed to approve the component.');
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.notify.showSuccess('Component approved successfully.');
this.closeReviewModal();
this.loadApproverData();
},
);
});
}
rejectRequest(req: PendingRequest): void {
if (!req || req.status !== 'Pending') { return; }
if (this.deadlinePassed) {
this.notify.showWarning('The approval date for this salary month has passed. Reject is no longer allowed.');
return;
}
this.notify.showActiveConfirm('Reject Component',
`Reject "${req.type}" uploaded by ${req.employee || 'employee'}? The upload will be removed and the employee can submit it again.`).then((ok: boolean) => {
if (!ok) { return; }
this.loadingPanel.ShowLoadingPanel = true;
this.basicService.rejectComponentUploadByKey(req._empId, req._componentID, req._componentType).subscribe(
() => {},
(err: any) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notify.showError(typeof err?.error === 'string' ? err.error : 'Failed to reject the component.');
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.notify.showSuccess('Component upload rejected.');
this.closeReviewModal();
this.loadApproverData();
},
);
});
}
private pick(o: any, ...keys: string[]): any {
for (const k of keys) { if (o != null && o[k] != null) { return o[k]; } }
return undefined;
}
refresh(): void { this.loadApproverData(); }
viewPending(): void { this.scrollToTable(); }
viewAll(_card: OverviewCard): void { this.scrollToTable(); }
// ───────────────────────── ui helpers ─────────────────────────
padTotal(n: number): string {
return n < 10 ? '0' + n : '' + n;
}
private scrollToTable(): void {
try {
document.querySelector('.ap-card-table')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
} catch { /* ignore */ }
}
private initials(name: string): string {
const parts = String(name || '').trim().split(/\s+/).filter(Boolean);
if (!parts.length) { return '—'; }
if (parts.length === 1) { return parts[0].substring(0, 2).toUpperCase(); }
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
private toComponentTypeNum(v: any): number {
if (v == null) { return 0; }
const n = Number(v);
if (!isNaN(n) && n > 0) { return n; }
const mapped = (EnumComponentType as any)[v];
return typeof mapped === 'number' ? mapped : 0;
}
}