import {Component, OnInit, ChangeDetectionStrategy} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; import {Router} from '@angular/router'; import {ApiService} from '../../app.api.service'; import {HRMNotificationService} from '../../app.notification.service'; import {DataTransferService} from '../../data.transfer.service'; import {loadingPanelService} from '../../hrm-loding panel/loding.panel.service'; import {PayrollType} from '../../_models/Authentication/payrollType'; import {Bonus} from '../../_models/Basic/bonus'; import {Employee} from '../../_models/Employee/employee'; import {EmployeeLite} from '../../_models/Employee/employeeLite'; import {SearchEmployee} from '../../_models/Employee/searchEmployee'; import {EnumIncomeTaxItemGroup, EnumStatus, EnumTaxMergeType} from '../../_models/enums'; import {BonusProcess, BonusProcessDetail} from '../../_models/Payroll/bonusProcess'; import {TaxMergeMaster} from '../../_models/Payroll/Tax/taxMergeMaster'; import {AuthService} from '../../_services/auth/auth.service'; import {BasicService} from '../../_services/Basic/basic.service'; import {DataUploadService} from '../../_services/Basic/dataUpload.service'; import {BonusService} from '../../_services/payroll/bonus.service'; import {TaxService} from '../../_services/payroll/tax.service'; import { EmployeeServices } from '../../_services/employee/employee.service'; import { CommonModule } from '@angular/common'; import { LoadingPanelComponent } from 'src/app/hrm-loding panel/loading-panel.component'; import { ButtonModule } from '@progress/kendo-angular-buttons'; import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; import { KENDO_GRID } from '@progress/kendo-angular-grid'; import { DatePickerModule } from '@progress/kendo-angular-dateinputs'; import { EmployeePickerComponent } from 'src/app/picker/employee-picker.component'; @Component({ selector: 'app-bonus-process', templateUrl: './bonus-process.component.html', styleUrls: ['./bonus-process.component.css'] , changeDetection: ChangeDetectionStrategy.Eager, standalone: false, }) export class BonusProcessComponent implements OnInit { selectedFiles?: FileList; bonusProcessForm: FormGroup; dropdown: string; processFor: number = 1; remaining: number = 0; payrollType: PayrollType; selectedEmps: SearchEmployee[]; bonuses: Bonus[]; selectedbonusID: number; basicDate: Date; payDate: Date = new Date(); cuttofDate: Date; disburseWithSalary: boolean = false; isTaxProcess: boolean = true; processRequest: { bonusid: number, basicMonth: Date, payDate: Date, cuttOfDate: Date, currProcess: number, isDisburseWithSalary: boolean, isTaxProcess: boolean, empid: number }[]; errorOrSucessList: any[]; returnMessage: any; pbuttonEnalble: boolean; bonusProcess: BonusProcess; bonusProcessDetails: BonusProcessDetail[]; alreadyProcessesList: SearchEmployee[]; showModal: boolean = false; processCompleted: boolean = false; showBonusUpload: boolean = false; constructor(public basicService: BasicService, public notificationService: HRMNotificationService, public loadingPanelService: loadingPanelService, public empService: EmployeeServices, public datatransferservice: DataTransferService, public bonusService: BonusService, public router: Router, public apiService: ApiService, public dataUploadService: DataUploadService, public authSerivce: AuthService, public taxService: TaxService) { this.apiService.selectedMenuName = 'Bonus Process'; } ngOnInit() { this.bonusProcessForm = new FormGroup({ bonusType: new FormControl(), basicDate: new FormControl(), payDate: new FormControl(), cutOffDate: new FormControl(), calculateTax: new FormControl(), disburseWithSalary: new FormControl(), processFor: new FormControl(), }); this.loadingPanelService.ShowLoadingPanel = false; this.basicService.getAllBonus(EnumStatus.Active).subscribe( (x) => { this.bonuses = x; }, (x) => { this.notificationService.showError(x); }, () => { this.loadingPanelService.ShowLoadingPanel = false; }); this.authSerivce.GetPayrollTypeByLoginID().subscribe( (x) => { this.payrollType = x; }, (x) => { this.notificationService.showError(x); }, () => { this.loadingPanelService.ShowLoadingPanel = false; this.basicDate = new Date(new PayrollType().getFirstDateofMonth(this.payrollType.nextPayProcessDate)); this.cuttofDate = new Date(this.payrollType.nextPayProcessDate); }); } public GetSelectedEmployee(searchEmp: SearchEmployee[]) { this.processCompleted = false; this.selectedEmps = searchEmp; if (this.bonusProcessDetails == undefined) { this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.GetBonusProcessDetail(this.selectedbonusID, new Date(this.payrollType.nextPayProcessDate)).subscribe( (resp: any) => { this.bonusProcessDetails = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { this.loadingPanelService.ShowLoadingPanel = false; this.RefreshDefaultGrid(); } ); } else { this.RefreshDefaultGrid(); } } RefreshDefaultGrid() { if (this.selectedEmps != undefined && this.bonusProcessDetails != undefined) { if (this.bonusProcess == undefined) { this.bonusProcess = new BonusProcess(); this.bonusProcess.bonusProcessDetails = []; } this.alreadyProcessesList = []; this.selectedEmps.forEach(e => { let eindex = this.bonusProcess.bonusProcessDetails.findIndex(b => b.employeeID == e.employeeID); if (eindex == -1) { let bindex = this.bonusProcessDetails.findIndex(b => b.employeeID == e.employeeID); if (bindex == -1) { var item: BonusProcessDetail = new BonusProcessDetail(); item.employeeID = e.employeeID; item.employee = new Employee(); item.employee.employeeID = e.employeeID; item.employee.employeeNo = e.employeeNo; item.employee.name = e.name; this.bonusProcess.bonusProcessDetails.push(item); } else { this.alreadyProcessesList.push(e); } } }); this.bonusProcess.bonusProcessDetails = [...this.bonusProcess.bonusProcessDetails]; this.RefreshEmployees(); if (this.alreadyProcessesList.length > 0) { this.showModal = true; } } } RefreshEmployees() { if (this.selectedEmps == undefined) return; const empIds: number[] = this.selectedEmps.map(e => e.employeeID); var emps: EmployeeLite[]; this.loadingPanelService.ShowLoadingPanel = true; this.empService.getEmployeeLiteByEmpIDs(empIds).subscribe( (resp: any) => { emps = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); }, () => { this.loadingPanelService.ShowLoadingPanel = false; emps.forEach(x => { let bindex = this.bonusProcess.bonusProcessDetails.findIndex(b => b.employeeID == x.employeeID); if (bindex != -1) { this.bonusProcess.bonusProcessDetails[bindex].employee.isConfirmed = x.isConfirmed; this.bonusProcess.bonusProcessDetails[bindex].employee.joiningDate = x.joiningDate; } }); }); } checkWithOrTax(from: number, value: boolean) { if (from == 1) { if (value == true) { this.isTaxProcess = false; } } else { if (value == true) { this.disburseWithSalary = false; } } } onPopUpClose() { this.showModal = false; this.showBonusUpload = false; } showBonusUploadPopUp() { this.showBonusUpload = true; } currentlyProcess($event) { } remainingBasic($event) { } search() { } process() { if (this.bonusProcess == undefined || this.bonusProcess.bonusProcessDetails.length == 0) { this.notificationService.showWarning('Please select employee for the proces'); return; } var isApproved = false; this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.IsBonusApproved(this.selectedbonusID, this.payrollType.nextPayProcessDate).subscribe( (resp: any) => { isApproved = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { if (isApproved == true) { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning('selected Bonus is already process and Approved'); this.returnMessage = 'selected Bonus is already process and Approved'; return; } var returnID: number; this.processRequest = []; var index: number = 0; this.bonusProcess.bonusProcessDetails.forEach(x => { this.processRequest.push({ 'bonusid': this.selectedbonusID, 'basicMonth': this.basicDate, 'payDate': this.payDate, 'cuttOfDate': this.cuttofDate, 'currProcess': this.processFor, 'isDisburseWithSalary': this.disburseWithSalary, 'isTaxProcess': this.isTaxProcess, 'empid': x.employeeID }); }); this.errorOrSucessList = []; this.bonusService.BonusProcess(this.processRequest).subscribe( (resp: any) => { this.bonusProcess = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { this.processCompleted = true; this.loadingPanelService.ShowLoadingPanel = false; this.pbuttonEnalble = false; this.notificationService.showSuccess('Bonus processed successfully'); this.returnMessage = 'Bonus processed successfully'; }); } ); } public BonusvalueChange(value: any): void { this.alreadyProcessesList = []; this.bonusProcess = new BonusProcess(); this.bonusProcess.bonusProcessDetails = []; this.selectedEmps = []; this.processCompleted = false; this.pbuttonEnalble = false; } TaxRecalculate() { this.loadingPanelService.ShowLoadingPanel = true; this.bonusProcess.bonusProcessDetails.forEach(x => { x.bonusID = this.selectedbonusID; }); this.bonusService.CalculateBonusTax(this.bonusProcess.bonusProcessDetails).subscribe( (resp: any) => { this.bonusProcess.bonusProcessDetails = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { this.processCompleted = true; this.loadingPanelService.ShowLoadingPanel = false; this.pbuttonEnalble = false; this.notificationService.showSuccess('Tax Recalculated processed successfully'); this.returnMessage = 'Tax Recalculated processed successfully'; }); } uploadBonusFile(event: any): void { let tempResponse: any; this.selectedFiles = event.target.files; if (this.selectedFiles.length > 0) { const file: File | null = this.selectedFiles.item(0); this.loadingPanelService.ShowLoadingPanel = true; this.dataUploadService.uploadBonusFile(file, this.payrollType.id).subscribe( (resp: any) => { this.loadingPanelService.ShowLoadingPanel = false; if (this.bonusProcess == undefined) { this.bonusProcess = new BonusProcess(); } this.bonusProcess.bonusProcessDetails = []; tempResponse = resp; //console.log(tempResponse); }, error => { this.notificationService.showError(error.error); this.loadingPanelService.ShowLoadingPanel = false; }, () => { this.loadingPanelService.ShowLoadingPanel = false; if (tempResponse.body !== undefined) { this.bonusProcess.bonusID = this.selectedbonusID; this.bonusProcess.paymentDate = this.payDate; this.bonusProcess.payrollTypeID = this.payrollType.id; this.bonusProcess.processDate = new Date(); this.bonusProcess.salaryMonth = this.payrollType.nextPayProcessDate; this.bonusProcess.basicOnMonth = this.payrollType.nextPayProcessDate; this.bonusProcess.bonusMonth = this.payrollType.nextPayProcessDate; this.bonusProcess.disburseDate = this.payDate; this.bonusProcess.bonusProcessDetails = tempResponse.body; this.bonusProcess.bonusProcessDetails.forEach(x => { x.bonusMonth = this.payrollType.nextPayProcessDate; x.bonusID = this.selectedbonusID; }); } this.showBonusUpload = false; this.processCompleted = true; }); } else { this.notificationService.showWarning('please select a file'); } } refresh() { } edit() { } clearAll() { } remove() { } save() { if (this.processCompleted == false) { this.notificationService.showWarning('Please process the Bonus first'); return; } if (this.bonusProcess == undefined || this.bonusProcess?.bonusProcessDetails.length == 0) { this.notificationService.showWarning('There are no data to save'); return; } if (this.isTaxProcess == true && (this.bonusProcess.bonusProcessDetails[0].incomeTaxcoll == undefined || this.bonusProcess.bonusProcessDetails[0].incomeTaxcoll.length == 0)) { this.notificationService.showWarning('Tax Calculation not yet done'); return; } if (this.isTaxProcess == true) { var mitem: TaxMergeMaster = undefined; this.taxService.getTaxMergeMaster(EnumTaxMergeType.Bonus, this.selectedbonusID).subscribe( (resp: any) => { mitem = resp; }, (err: any) => { this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { if (mitem != undefined) { console.log(mitem); this.bonusProcess.bonusProcessDetails.every(x => { var item = x.incomeTaxcoll.find(y => y.itemGroup == mitem.itemGroup && y.itemID == mitem.itemID); if (item != undefined) { item.thisMonthAmount = x.changeBonusAmount; } else { this.notificationService.showWarning('Income tax amount not found in the collection'); return; } item = x.incomeTaxcoll.find(y => y.itemGroup == EnumIncomeTaxItemGroup.Tax_Deducted); if (item != undefined) { item.thisMonthAmount = x.changeTaxAmount; } }); this.saveData(); } else { this.notificationService.showWarning('Bonus head not found in the income tax Grouping'); return; } } ); } else { this.saveData(); } } private logSavePayloadSize() { try { const enc = new TextEncoder(); const bytes = (v: any): number => { const s = JSON.stringify(v); return s === undefined ? 0 : enc.encode(s).length; }; const MB = (b: number) => (b / 1024 / 1024).toFixed(2) + ' MB'; const KB = (b: number) => (b / 1024).toFixed(2) + ' KB'; const LIMIT = 30000000; // IIS / ASP.NET Core default request body limit (bytes) // size of every field over a list of objects (bytes of "key":value, per field), biggest first const fieldTable = (objs: any[], total: number, top = 999) => { const sum: { [k: string]: { b: number, nulls: number, objs: number } } = {}; objs.forEach(o => { if (o == null || typeof o !== 'object') return; Object.keys(o).forEach(k => { const v = o[k]; const e = sum[k] || (sum[k] = { b: 0, nulls: 0, objs: 0 }); if (v === undefined) return; e.b += enc.encode(JSON.stringify(k)).length + 2 + bytes(v); if (v === null) e.nulls++; else if (typeof v === 'object') e.objs++; }); }); return Object.keys(sum) .map(k => ({ field: k, size: MB(sum[k].b), percent: (total ? (sum[k].b * 100 / total) : 0).toFixed(1) + '%', nullRows: sum[k].nulls, objectRows: sum[k].objs, _b: sum[k].b })) .sort((a, b) => b._b - a._b) .slice(0, top) .map(({ _b, ...r }) => r); }; const stats = (counts: number[]) => { if (counts.length == 0) return { total: 0, min: 0, max: 0, avg: '0' }; let total = 0, min = counts[0], max = counts[0]; counts.forEach(c => { total += c; if (c < min) min = c; if (c > max) max = c; }); return { total, min, max, avg: (total / counts.length).toFixed(1) }; }; const d: any[] = this.bonusProcess?.bonusProcessDetails ?? []; // 1. Overview const t0 = performance.now(); const totalBytes = bytes(this.bonusProcess); const stringifyMs = Math.round(performance.now() - t0); const header = { ...this.bonusProcess, bonusProcessDetails: undefined }; console.log('%c[SAVE SIZE] 1. Overview', 'font-weight:bold'); console.table({ rows: d.length, totalRequest: MB(totalBytes), serverLimit: MB(LIMIT), overLimitBy: totalBytes > LIMIT ? MB(totalBytes - LIMIT) + ' (' + (totalBytes / LIMIT).toFixed(1) + 'x the limit)' : 'within the limit', header_withoutDetails: KB(bytes(header)), averagePerRow: d.length ? KB(totalBytes / d.length) : '0', jsonStringifyTime: stringifyMs + ' ms', }); // 2. Every field of a BonusProcessDetail (employee / bonus / incomeTaxcoll are fields too) console.log('%c[SAVE SIZE] 2. Fields of each detail row (all rows together)', 'font-weight:bold'); console.table(fieldTable(d, totalBytes)); // 3. employee const emps = d.map(x => x.employee).filter(x => x != null); const empBytes = bytes(emps); console.log('%c[SAVE SIZE] 3. employee — ' + MB(empBytes) + ', ' + emps.length + ' objects, ' + new Set(emps).size + ' distinct; top 25 fields', 'font-weight:bold'); console.table(fieldTable(emps, empBytes, 25)); // 4. bonus const bonuses = d.map(x => x.bonus).filter(x => x != null); const bonusBytes = bytes(bonuses); console.log('%c[SAVE SIZE] 4. bonus — ' + MB(bonusBytes) + ', ' + bonuses.length + ' objects, ' + new Set(bonuses).size + ' distinct (' + new Set(bonuses.map(b => b?.id)).size + ' distinct ids); one copy = ' + KB(bytes(bonuses[0])), 'font-weight:bold'); if (bonuses.length) console.table(fieldTable(bonuses, bonusBytes, 25)); // 5. incomeTaxcoll const taxCounts = d.map(x => (x.incomeTaxcoll ?? []).length); const taxItems = ([] as any[]).concat(...d.map(x => x.incomeTaxcoll ?? [])); const taxBytes = bytes(taxItems); console.log('%c[SAVE SIZE] 5. incomeTaxcoll — ' + MB(taxBytes) + '; items per row:', 'font-weight:bold', stats(taxCounts), '; rows with no items:', taxCounts.filter(c => c == 0).length, '; one item ≈', taxItems.length ? (taxBytes / taxItems.length).toFixed(0) + ' bytes' : '-'); if (taxItems.length) console.table(fieldTable(taxItems, taxBytes)); // 6. bonusEmpCostCenters const ccCounts = d.map(x => (x.bonusEmpCostCenters ?? []).length); const ccItems = ([] as any[]).concat(...d.map(x => x.bonusEmpCostCenters ?? [])); console.log('%c[SAVE SIZE] 6. bonusEmpCostCenters — ' + MB(bytes(ccItems)) + '; items per row:', 'font-weight:bold', stats(ccCounts)); // 7. What the server actually saves: BonusProcessDA.Insert (detail) + IncomeTaxService.SaveBulk (tax) const pick = (o: any, keys: string[]) => { const r: any = {}; keys.forEach(k => { if (o?.[k] !== undefined) r[k] = o[k]; }); return r; }; const detailKeys = ['employeeID', 'bonusID', 'bonusMonth', 'bonusAmount', 'grossSalary', 'basicSalary', 'changeBonusAmount', 'changeTaxAmount', 'changeAdjustAmount', 'changeSalaryItemAmount', 'calculatedAdjustAmount', 'calculatedSalaryItemAmount', 'taxAmount']; const taxKeys = ['employeeID', 'itemGroup', 'itemID', 'description', 'totalAmount', 'previousAmount', 'thisMonthAmount', 'projectedAmount', 'side', 'position', 'isChanged', 'taxParameterID']; const minimal = { ...header, bonusProcessDetails: d.map(x => ({ ...pick(x, detailKeys), incomeTaxcoll: (x.incomeTaxcoll ?? []).map((t: any) => pick(t, taxKeys)) })), }; const minimalBytes = bytes(minimal); console.log('%c[SAVE SIZE] 7. Only the fields the server saves', 'font-weight:bold'); console.table({ minimalRequest: MB(minimalBytes), ofWhichTax: MB(bytes(minimal.bonusProcessDetails.map(x => x.incomeTaxcoll))), smallerBy: minimalBytes ? (totalBytes / minimalBytes).toFixed(1) + 'x' : '-', fitsInLimit: minimalBytes <= LIMIT ? 'yes' : 'NO', }); } catch (e) { console.log('[SAVE SIZE] could not measure:', e); } } saveData() { this.loadingPanelService.ShowLoadingPanel = true; this.bonusProcess.disburseDate = this.payDate; this.bonusProcess.isTaxProcess = this.isTaxProcess; this.bonusProcess.isDisburseWithSalary = this.disburseWithSalary; this.bonusService.saveBonusProcess(this.bonusProcess).subscribe( (resp: any) => { }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(err.error); this.returnMessage = err.error; }, () => { this.loadingPanelService.ShowLoadingPanel = false; this.pbuttonEnalble = false; this.notificationService.showSuccess('Data saved successfully'); this.bonusProcessDetails = undefined; this.alreadyProcessesList = []; this.bonusProcess = new BonusProcess(); this.bonusProcess.bonusProcessDetails = []; } ); } clearTax() { this.loadingPanelService.ShowLoadingPanel = true; this.bonusProcess.bonusProcessDetails.forEach(x => { x.changeTaxAmount = 0; }); this.loadingPanelService.ShowLoadingPanel = false; } undo() { } uploadData() { } removefromList(rowIndex: number) { this.bonusProcess.bonusProcessDetails.splice(rowIndex, 1); // new array reference so the (virtual) grid re-reads it this.bonusProcess.bonusProcessDetails = [...this.bonusProcess.bonusProcessDetails]; } // Excel export: every row, not only the rows the virtual grid has on screen public allBonusRows = (): any => { const rows = this.bonusProcess?.bonusProcessDetails ?? []; return { data: rows, total: rows.length }; }; removeHandler({dataItem}) { console.log(dataItem); } editHandler({dataItem}) { } addHandler() { } }