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 {BonusProcessAndSaveRequest, BonusProcessAndSaveResult, BonusProcessGridRow, BonusProcessRowTaxResult, BonusProcessRowRemoveResult} from '../../_models/Payroll/bonusProcessAndSave'; 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; // Modify dialog (one saved row at a time) showModify: boolean = false; modifyRow: BonusProcessDetail; modifyBonusAmount: number = 0; modifyTaxAmount: number = 0; // "Edited Tax Amount" (with Calculated tax): starts as the calculated tax, the user may change it; saved as changeTaxAmount modifyEditedTaxAmount: number = 0; modifyCalculateTax: boolean = false; modifyTaxCalculated: boolean = false; // the tax shown was calculated for the bonus shown modifyBusy: 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[]) { // the already-processed check needs the bonus: stop here (nothing added to the grid) until one is chosen if (this.selectedbonusID == undefined || this.selectedbonusID <= 0) { const message = 'Please select a Bonus Type first, then select the employees.'; this.notificationService.showWarning(message); this.returnMessage = message; return; } 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; } // Process saves straight to the database, so ask first // tell the user which option the process runs with (the two checkboxes can't both be ticked) const option = this.disburseWithSalary ? 'with Disburse With Salary' : this.isTaxProcess ? 'with Calculate Tax' : 'without Disburse With Salary and Calculate Tax'; this.notificationService.showActiveConfirm('Confirmation', 'Are you sure you want to process the bonus ' + option + '?').then((isConfirmed) => { if (isConfirmed) { this.processConfirmed(); } }); } // the rest of Process, run only after the user confirmed private processConfirmed() { 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; } // Process = calculate + save on the server in one request (no separate Save step). // Only the header and the employee IDs are sent; the saved rows come back from the database. const request: BonusProcessAndSaveRequest = { bonusID: this.selectedbonusID, basicMonth: this.basicDate, payDate: this.payDate, cuttOfDate: this.cuttofDate, currProcess: this.processFor, isDisburseWithSalary: this.disburseWithSalary, isTaxProcess: this.isTaxProcess, employeeIDs: this.bonusProcess.bonusProcessDetails.map(x => x.employeeID), }; var result: BonusProcessAndSaveResult; this.errorOrSucessList = []; this.bonusService.processAndSave(request).subscribe( (resp: BonusProcessAndSaveResult) => { result = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; const message = (typeof err?.error === 'string' && err.error) ? err.error : 'Bonus process failed. Please check the connection and try again.'; this.notificationService.showWarning(message); this.returnMessage = message; }, () => { this.bonusProcess = new BonusProcess(); this.bonusProcess.id = result?.bonusProcessID; // kept so the grid knows how this process was saved (Modify is hidden for Disburse With Salary) this.bonusProcess.isDisburseWithSalary = request.isDisburseWithSalary; this.bonusProcess.bonusProcessDetails = (result?.rows ?? []).map(r => this.toGridDetail(r)); // the already-processed list changed: read it again on the next employee selection this.bonusProcessDetails = undefined; this.alreadyProcessesList = []; this.processCompleted = true; this.loadingPanelService.ShowLoadingPanel = false; this.pbuttonEnalble = false; const skipped = result?.alreadyProcessedEmployeeIDs?.length ?? 0; const message = 'Bonus processed and saved successfully' + (skipped > 0 ? ' (' + skipped + ' already processed employee(s) left out)' : ''); this.notificationService.showSuccess(message); this.returnMessage = message; }); } ); } // ---- Upload Data: check every input, then the server reads the file, calculates the tax (when asked) // and saves, in one request (api/dataUpload/uploadBonusFileAndSave). The old uploadBonusFile is kept. ---- uploadBonusFileAndSave(event: any): void { const input: HTMLInputElement = event?.target; const file: File | null = input?.files && input.files.length > 0 ? input.files.item(0) : null; const clearInput = () => { if (input) input.value = ''; }; // so the same file can be chosen again const problems: string[] = []; if (this.selectedbonusID == undefined || this.selectedbonusID <= 0) problems.push('Bonus Type'); if (this.basicDate == undefined) problems.push('Consider Basic Of'); if (this.payDate == undefined) problems.push('Pay Date'); if (this.cuttofDate == undefined) problems.push('Bonus Cut Off Date'); if (this.processFor == undefined || this.processFor <= 0) problems.push('Currently Process For Basic (must be greater than 0)'); if (this.payrollType == undefined) problems.push('Payroll type (please reload the page)'); if (problems.length > 0) { this.notificationService.showWarning('Please give: ' + problems.join(', ')); clearInput(); return; } if (file == null) { this.notificationService.showWarning('please select a file'); return; } const name = (file.name || '').toLowerCase(); if (!name.endsWith('.xlsx') && !name.endsWith('.xls')) { this.notificationService.showWarning('Please select an Excel file (.xlsx or .xls)'); clearInput(); return; } const header: BonusProcessAndSaveRequest = { bonusID: this.selectedbonusID, basicMonth: this.basicDate, payDate: this.payDate, cuttOfDate: this.cuttofDate, currProcess: this.processFor, isDisburseWithSalary: this.disburseWithSalary, isTaxProcess: this.isTaxProcess, employeeIDs: [], }; 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(this.errorText(err, 'Could not check the bonus. Please try again.')); clearInput(); }, () => { 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'; clearInput(); return; } var result: BonusProcessAndSaveResult; this.dataUploadService.uploadBonusFileAndSave(file, header).subscribe( (resp: BonusProcessAndSaveResult) => { result = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; const message = this.errorText(err, 'Upload failed. Please check the connection and try again.'); this.notificationService.showWarning(message); this.returnMessage = message; clearInput(); }, () => { this.bonusProcess = new BonusProcess(); this.bonusProcess.id = result?.bonusProcessID; // kept so the grid knows how this process was saved (Modify is hidden for Disburse With Salary) this.bonusProcess.isDisburseWithSalary = header.isDisburseWithSalary; this.bonusProcess.bonusProcessDetails = (result?.rows ?? []).map(r => this.toGridDetail(r)); // the already-processed list changed: read it again on the next employee selection this.bonusProcessDetails = undefined; this.alreadyProcessesList = []; this.processCompleted = true; this.showBonusUpload = false; this.loadingPanelService.ShowLoadingPanel = false; const skipped = result?.alreadyProcessedEmployeeIDs?.length ?? 0; const message = 'Bonus uploaded and saved successfully (' + (result?.rows?.length ?? 0) + ' employee(s))' + (skipped > 0 ? '; ' + skipped + ' already processed employee(s) left out' : ''); this.notificationService.showSuccess(message); this.returnMessage = message; clearInput(); }); }); } // ---- Modify dialog: one saved row at a time (api/Bonus/calculateRowTax, api/Bonus/saveRow) ---- openModify(row: BonusProcessDetail) { if (row == undefined || !row.bonusProcessDetailID) { this.notificationService.showWarning('Please process the Bonus first'); return; } this.modifyRow = row; this.modifyBonusAmount = row.changeBonusAmount ?? 0; this.modifyCalculateTax = this.isTaxProcess == true; // with Calculated tax: Tax Amount = the system's tax (taxAmount), Edited Tax Amount = the saved one (changeTaxAmount); // without it the Tax Amount field is typed in as before and starts at the saved tax this.modifyTaxAmount = this.modifyCalculateTax ? (row.taxAmount ?? 0) : (row.changeTaxAmount ?? 0); this.modifyEditedTaxAmount = row.changeTaxAmount ?? 0; this.modifyTaxCalculated = true; // the saved tax belongs to the saved bonus this.modifyBusy = false; this.showModify = true; } closeModify() { this.showModify = false; this.modifyRow = undefined; this.modifyBusy = false; } onModifyBonusChange() { // the tax shown no longer matches the bonus until Calculate is pressed again if (this.modifyCalculateTax) this.modifyTaxCalculated = false; } onModifyCalculateTaxChange() { if (this.modifyCalculateTax) this.modifyTaxCalculated = false; } private errorText(err: any, fallback: string): string { return (typeof err?.error === 'string' && err.error) ? err.error : fallback; } calculateModifyTax() { if (this.modifyRow == undefined) return; if (this.modifyBonusAmount == undefined || this.modifyBonusAmount < 0) { this.notificationService.showWarning('Please enter a valid bonus amount'); return; } this.modifyBusy = true; this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.calculateRowTax({ bonusProcessDetailID: this.modifyRow.bonusProcessDetailID, bonusAmount: this.modifyBonusAmount, }).subscribe( (resp: BonusProcessRowTaxResult) => { this.modifyTaxAmount = resp?.taxAmount ?? 0; // the user sees the new tax in Edited Tax Amount and may change it before Save this.modifyEditedTaxAmount = this.modifyTaxAmount; this.modifyTaxCalculated = true; }, (err: any) => { this.modifyBusy = false; this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(this.errorText(err, 'Tax calculation failed. Please try again.')); }, () => { this.modifyBusy = false; this.loadingPanelService.ShowLoadingPanel = false; }); } saveModify() { if (this.modifyRow == undefined) return; if (this.modifyBonusAmount == undefined || this.modifyBonusAmount < 0) { this.notificationService.showWarning('Please enter a valid bonus amount'); return; } if (!this.modifyCalculateTax && (this.modifyTaxAmount == undefined || this.modifyTaxAmount < 0)) { this.notificationService.showWarning('Please enter a valid tax amount'); return; } if (this.modifyCalculateTax && !this.modifyTaxCalculated) { // the Edited Tax Amount must be chosen against the tax of THIS bonus amount this.notificationService.showWarning('Please press Calculate first, then check the Edited Tax Amount'); return; } if (this.modifyCalculateTax && (this.modifyEditedTaxAmount == undefined || this.modifyEditedTaxAmount < 0)) { this.notificationService.showWarning('Please enter a valid edited tax amount'); return; } const row = this.modifyRow; var saved: BonusProcessGridRow; this.modifyBusy = true; this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.saveRow({ bonusProcessDetailID: row.bonusProcessDetailID, bonusAmount: this.modifyBonusAmount, taxAmount: this.modifyTaxAmount ?? 0, calculateTax: this.modifyCalculateTax == true, editedTaxAmount: this.modifyCalculateTax == true ? (this.modifyEditedTaxAmount ?? 0) : undefined, }).subscribe( (resp: BonusProcessGridRow) => { saved = resp; }, (err: any) => { this.modifyBusy = false; this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showWarning(this.errorText(err, 'Save failed. Please try again.')); }, () => { this.modifyBusy = false; this.loadingPanelService.ShowLoadingPanel = false; if (saved != undefined) { // only this row changes in the grid, with what the database now holds const updated = this.toGridDetail(saved); row.changeBonusAmount = updated.changeBonusAmount; row.changeTaxAmount = updated.changeTaxAmount; row.taxAmount = updated.taxAmount; row.bonusAmount = updated.bonusAmount; row.basicSalary = updated.basicSalary; row.employee = updated.employee; } this.notificationService.showSuccess('Bonus saved for ' + (row.employee?.employeeNo ?? 'the employee')); this.closeModify(); }); } // a saved row from processAndSave, in the shape the grid binds to (dataItem.employee.*, changeBonusAmount, ...) private toGridDetail(r: BonusProcessGridRow): BonusProcessDetail { const item: BonusProcessDetail = new BonusProcessDetail(); item.bonusProcessDetailID = r.bonusProcessDetailID; item.bonusProcessID = r.bonusProcessID; item.bonusID = r.bonusID; item.employeeID = r.employeeID; item.basicSalary = r.basicSalary; item.bonusAmount = r.bonusAmount; item.changeBonusAmount = r.changeBonusAmount; item.taxAmount = r.taxAmount; item.changeTaxAmount = r.changeTaxAmount; item.employee = new Employee(); item.employee.id = r.employeeID; item.employee.employeeID = r.employeeID; item.employee.employeeNo = r.employeeNo; item.employee.name = r.name; item.employee.joiningDate = r.joiningDate; item.employee.isConfirmed = r.isConfirmed; item.employee.grossSalary = r.grossSalary; item.employee.basicSalary = r.basicSalary; return item; } 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.notificationService.showActiveConfirm('Confirmation', "Are you sure you want to clear the tax?").then((isConfirmed) => { if (isConfirmed) { this.clearTaxConfirmed(); } }); } clearTaxAndSave() { const bonusProcessID = this.bonusProcess?.id; if (bonusProcessID == undefined || bonusProcessID <= 0 || !(this.bonusProcess.bonusProcessDetails ?? []).some(x => x.bonusProcessDetailID)) { this.notificationService.showWarning('Please process the bonus first, then clear the tax.'); return; } this.notificationService.showActiveConfirm('Confirmation', "Are you sure you want to clear the tax?").then((isConfirmed) => { if (isConfirmed) { this.clearTaxAndSaveConfirmed(bonusProcessID); } }); } private clearTaxAndSaveConfirmed(bonusProcessID: number) { var rows: BonusProcessGridRow[]; this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.clearTaxAndSave(bonusProcessID).subscribe( (resp: BonusProcessGridRow[]) => { rows = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; const message = this.errorText(err, 'Clear tax failed. Please check the connection and try again.'); this.notificationService.showWarning(message); this.returnMessage = message; }, () => { // the saved rows, read back from the database (new array, so the virtual grid re-reads it) this.bonusProcess.bonusProcessDetails = (rows ?? []).map(r => this.toGridDetail(r)); this.loadingPanelService.ShowLoadingPanel = false; const message = 'Tax cleared and saved successfully'; this.notificationService.showSuccess(message); this.returnMessage = message; }); } // the old Clear Tax body, run only after the user confirmed private clearTaxConfirmed() { 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]; } // ---- Remove button: a row not saved yet is only taken off the grid (removefromList, as before); a saved // row (after Process / Upload) is deleted from the database at once (api/Bonus/removeRow). ---- removeRow(dataItem: BonusProcessDetail, rowIndex: number) { if (!dataItem?.bonusProcessDetailID) { this.removefromList(rowIndex); return; } const who = (dataItem.employee?.employeeNo ? dataItem.employee.employeeNo + ' - ' : '') + (dataItem.employee?.name ?? ''); this.notificationService.showActiveConfirm('Confirmation', 'Are you sure you want to remove ' + who + '? The saved bonus of this employee will be deleted.').then((isConfirmed) => { if (isConfirmed) { this.removeRowConfirmed(dataItem); } }); } private removeRowConfirmed(dataItem: BonusProcessDetail) { var result: BonusProcessRowRemoveResult; this.loadingPanelService.ShowLoadingPanel = true; this.bonusService.removeRow(dataItem.bonusProcessDetailID).subscribe( (resp: BonusProcessRowRemoveResult) => { result = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; const message = this.errorText(err, 'Remove failed. Please check the connection and try again.'); this.notificationService.showWarning(message); this.returnMessage = message; }, () => { // take that row off the grid (new array, so the virtual grid re-reads it) this.bonusProcess.bonusProcessDetails = this.bonusProcess.bonusProcessDetails .filter(x => x.bonusProcessDetailID !== dataItem.bonusProcessDetailID); // the already-processed list changed: read it again on the next employee selection this.bonusProcessDetails = undefined; let message = 'Employee removed successfully'; if (result?.processDeleted) { // that was the last employee: the bonus process itself is gone this.bonusProcess.id = undefined; message = 'Last employee removed, so the bonus process was deleted too'; } this.loadingPanelService.ShowLoadingPanel = false; this.notificationService.showSuccess(message); this.returnMessage = message; }); } // 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() { } }