diff --git a/HRM.BO/Bonus/BonusProcess.cs b/HRM.BO/Bonus/BonusProcess.cs index b93633c..5e0ccd4 100644 --- a/HRM.BO/Bonus/BonusProcess.cs +++ b/HRM.BO/Bonus/BonusProcess.cs @@ -949,6 +949,13 @@ namespace HRM.BO DataSet GetBonusBankAdvice(int BonusID, DateTime dBonusMonth, string sEmpID); DataSet GetBonusPaySlip(int BonusID, DateTime dBonusMonth, string sEmpID); int Save(BonusProcess item); + BonusProcessAndSaveResult ProcessAndSave(BonusProcessAndSaveRequest request, int payrolltypeid, int userID); + BonusProcessAndSaveResult UploadAndSave(List uploadedRows, + BonusProcessAndSaveRequest request, int payrolltypeid, int userID); + BonusProcessRowTaxResult CalculateRowTax(BonusProcessRowTaxRequest request, int payrolltypeid); + BonusProcessGridRow SaveRow(BonusProcessRowSaveRequest request, int payrolltypeid, int userID); + List ClearTaxAndSave(int bonusProcessID, int payrolltypeid, int userID); + BonusProcessRowRemoveResult RemoveRow(int bonusProcessDetailID, int payrolltypeid); void Delete(BonusProcess oBonusProcess); List GetProcess(int bonusID, DateTime bonusMonth); List GetProcess(DateTime bonusMonth); diff --git a/HRM.BO/Bonus/BonusProcessAndSave.cs b/HRM.BO/Bonus/BonusProcessAndSave.cs new file mode 100644 index 0000000..7873df0 --- /dev/null +++ b/HRM.BO/Bonus/BonusProcessAndSave.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; + +namespace HRM.BO +{ + /// + /// Bonus Process screen, "Process" button: calculate the bonus (and tax) of these employees and save it + /// in the same request (api/Bonus/processAndSave). Only the header and the employee IDs travel — the + /// browser no longer sends the whole calculated BonusProcess back for a separate Save. + /// + public class BonusProcessAndSaveRequest + { + public int BonusID { get; set; } + public DateTime BasicMonth { get; set; } + public DateTime PayDate { get; set; } + public DateTime CuttOfDate { get; set; } + public double CurrProcess { get; set; } + public bool IsDisburseWithSalary { get; set; } + public bool IsTaxProcess { get; set; } + public List EmployeeIDs { get; set; } + } + + /// One saved row of the Bonus Process grid, read back from the database. + public class BonusProcessGridRow + { + public int BonusProcessDetailID { get; set; } + public int BonusProcessID { get; set; } + public int BonusID { get; set; } + public int EmployeeID { get; set; } + public string EmployeeNo { get; set; } + public string Name { get; set; } + public DateTime? JoiningDate { get; set; } + public bool IsConfirmed { get; set; } + public double GrossSalary { get; set; } + public double BasicSalary { get; set; } + public double BonusAmount { get; set; } + public double ChangeBonusAmount { get; set; } + public double TaxAmount { get; set; } + public double ChangeTaxAmount { get; set; } + } + + /// What processAndSave returns: the saved process and its rows. + public class BonusProcessAndSaveResult + { + public int BonusProcessID { get; set; } + public List Rows { get; set; } = new List(); + /// Employees left out because this bonus was already processed for them this month. + public List AlreadyProcessedEmployeeIDs { get; set; } = new List(); + } + + /// + /// Modify dialog, "Calculate": the tax of one saved row for this bonus amount + /// (api/Bonus/calculateRowTax). Nothing is saved. + /// + public class BonusProcessRowTaxRequest + { + public int BonusProcessDetailID { get; set; } + public double BonusAmount { get; set; } + } + + public class BonusProcessRowTaxResult + { + public int BonusProcessDetailID { get; set; } + public double BonusAmount { get; set; } + public double TaxAmount { get; set; } + } + + /// + /// Modify dialog, "Save": saves one row (api/Bonus/saveRow). With CalculateTax the server works the tax + /// out again from BonusAmount (TaxAmount is ignored); without it TaxAmount is the amount typed in. + /// + public class BonusProcessRowSaveRequest + { + public int BonusProcessDetailID { get; set; } + public double BonusAmount { get; set; } + public double TaxAmount { get; set; } + public bool CalculateTax { get; set; } + /// + /// "Edited Tax Amount" (with CalculateTax): the tax the user settled on after seeing the calculated one. + /// Saved as CHANGETAXAMOUNT and on the Tax Deducted line; TAXAMOUNT keeps the calculated tax. + /// Null = use the calculated tax. + /// + public double? EditedTaxAmount { get; set; } + } + + /// + /// Remove button on a saved row (api/Bonus/removeRow/{id}): what was deleted. ProcessDeleted is true when + /// that was the process's last employee, so the (now empty) BONUSPROCESS header was deleted too. + /// + public class BonusProcessRowRemoveResult + { + public int BonusProcessDetailID { get; set; } + public int BonusProcessID { get; set; } + public bool ProcessDeleted { get; set; } + } +} diff --git a/HRM.DA/DA/Bonus/BonusProcessDA.cs b/HRM.DA/DA/Bonus/BonusProcessDA.cs index e1424f4..80e542b 100644 --- a/HRM.DA/DA/Bonus/BonusProcessDA.cs +++ b/HRM.DA/DA/Bonus/BonusProcessDA.cs @@ -2,6 +2,7 @@ using Ease.Core.DataAccess; using Ease.Core.Utility; using System; +using System.Collections.Generic; using System.Data; @@ -32,6 +33,176 @@ namespace HRM.DA item.UsedProcess, item.PayrollTypeID, item.IsApprove, item.wfstatus); } + /// + /// Inserts every detail row in one SqlBulkCopy (10k+ rows), instead of one INSERT per row. + /// Same columns and values as Insert(tc, BonusProcessDetail) below; IDs must already be set. + /// Runs inside the caller's transaction. + /// + internal static void InsertBulk(TransactionContext tc, List items) + { + if (items == null || items.Count == 0) + return; + + // money columns: round like SQL Server does when it converts a number literal to money (4 places) + Func money = v => Math.Round((decimal)v, 4, MidpointRounding.AwayFromZero); + + // column names exactly as in the BONUSPROCESSDETAIL table (bulk copy mapping is case-sensitive) + DataTable table = new DataTable("BONUSPROCESSDETAIL"); + table.Columns.Add("BONUSPROCESSDETAILID", typeof(int)); + table.Columns.Add("BONUSPROCESSID", typeof(int)); + table.Columns.Add("BONUSID", typeof(int)); + table.Columns.Add("EMPLOYEEID", typeof(int)); + table.Columns.Add("DISBURSEDATE", typeof(DateTime)); + table.Columns.Add("BONUSAMOUNT", typeof(decimal)); + table.Columns.Add("GROSSSALARY", typeof(decimal)); + table.Columns.Add("BASICSALARY", typeof(decimal)); + table.Columns.Add("CHANGEBONUSAMOUNT", typeof(decimal)); + table.Columns.Add("CHANGETAXAMOUNT", typeof(decimal)); + table.Columns.Add("CHANGEADJUSTAMOUNT", typeof(decimal)); + table.Columns.Add("CHANGESALARYITEMAMOUNT", typeof(decimal)); + table.Columns.Add("CALCULATEDADJUSTAMOUNT", typeof(decimal)); + table.Columns.Add("CALCULATEDSALARYITEMAMOUNT", typeof(decimal)); + table.Columns.Add("TAXAMOUNT", typeof(decimal)); + + foreach (BonusProcess.BonusProcessDetail item in items) + { + table.Rows.Add(item.ID, item.BonusProcessID, item.BonusID, item.EmployeeID, + item.BonusMonth.Date, // Insert writes it with %d (date only) + money(item.BonusAmount), money(item.GrossSalary), money(item.BasicSalary), + money(item.ChangeBonusAmount), money(item.ChangeTaxAmount), money(item.ChangeAdjustAmount), + money(item.ChangeSalaryItemAmount), money(item.CalculatedAdjustAmount), + money(item.CalculatedSalaryItemAmount), money(item.TaxAmount)); + } + + using (Microsoft.Data.SqlClient.SqlBulkCopy bulkCopy = new Microsoft.Data.SqlClient.SqlBulkCopy( + (Microsoft.Data.SqlClient.SqlConnection)tc.Connection, Microsoft.Data.SqlClient.SqlBulkCopyOptions.Default, + (Microsoft.Data.SqlClient.SqlTransaction)tc.Transaction)) + { + bulkCopy.BulkCopyTimeout = 6000; // in seconds, as SaveBonusEmpCostCenter + bulkCopy.DestinationTableName = "BONUSPROCESSDETAIL"; + foreach (DataColumn column in table.Columns) + bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName); + bulkCopy.WriteToServer(table); + } + } + + /// The saved rows of one bonus process, with the employee columns the Bonus Process grid shows. + internal static IDataReader GetGridRows(TransactionContext tc, int bonusProcessID) + { + return tc.ExecuteReader(@"SELECT bd.BONUSPROCESSDETAILID, bd.BONUSPROCESSID, bd.BONUSID, bd.EMPLOYEEID, + e.EMPLOYEENO, e.NAME, e.JOININGDATE, e.ISCONFIRMED, + bd.GROSSSALARY, bd.BASICSALARY, bd.BONUSAMOUNT, bd.CHANGEBONUSAMOUNT, bd.TAXAMOUNT, bd.CHANGETAXAMOUNT + FROM BONUSPROCESSDETAIL bd + INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = bd.EMPLOYEEID + WHERE bd.BONUSPROCESSID = %n + ORDER BY e.EMPLOYEENO", bonusProcessID); + } + + /// One saved row (Modify dialog), with the employee columns the grid shows. + internal static IDataReader GetGridRow(TransactionContext tc, int bonusProcessDetailID) + { + return tc.ExecuteReader(@"SELECT bd.BONUSPROCESSDETAILID, bd.BONUSPROCESSID, bd.BONUSID, bd.EMPLOYEEID, + e.EMPLOYEENO, e.NAME, e.JOININGDATE, e.ISCONFIRMED, + bd.GROSSSALARY, bd.BASICSALARY, bd.BONUSAMOUNT, bd.CHANGEBONUSAMOUNT, bd.TAXAMOUNT, bd.CHANGETAXAMOUNT + FROM BONUSPROCESSDETAIL bd + INNER JOIN EMPLOYEE e ON e.EMPLOYEEID = bd.EMPLOYEEID + WHERE bd.BONUSPROCESSDETAILID = %n", bonusProcessDetailID); + } + + /// One saved row and the header fields the Modify dialog needs (bonus, month, payroll type). + internal static IDataReader GetRowWithHeader(TransactionContext tc, int bonusProcessDetailID) + { + return tc.ExecuteReader(@"SELECT bd.BONUSPROCESSDETAILID, bd.BONUSPROCESSID, bd.BONUSID, bd.EMPLOYEEID, + bd.CHANGEBONUSAMOUNT, bd.CHANGETAXAMOUNT, bd.TAXAMOUNT, + b.BONUSMONTH, b.PAYROLLTYPEID, b.ISTAXPROCESS + FROM BONUSPROCESSDETAIL bd + INNER JOIN BONUSPROCESS b ON b.BONUSPROCESSID = bd.BONUSPROCESSID + WHERE bd.BONUSPROCESSDETAILID = %n", bonusProcessDetailID); + } + + /// Modify dialog, Save: the amounts of one row. + internal static void UpdateRowAmounts(TransactionContext tc, int bonusProcessDetailID, double changeBonusAmount, + double changeTaxAmount, double taxAmount, int modifiedBy, DateTime modifiedDate) + { + tc.ExecuteNonQuery(@"UPDATE BONUSPROCESSDETAIL SET CHANGEBONUSAMOUNT = %n, CHANGETAXAMOUNT = %n, TAXAMOUNT = %n, + MODIFIEDBY = %n, MODIFIEDDATE = %D + WHERE BONUSPROCESSDETAILID = %n", + changeBonusAmount, changeTaxAmount, taxAmount, modifiedBy, modifiedDate, bonusProcessDetailID); + } + + /// Clear Tax: the header fields of one bonus process (bonus, month, payroll type, options). + internal static IDataReader GetProcessHeaderForClearTax(TransactionContext tc, int bonusProcessID) + { + return tc.ExecuteReader(@"SELECT BONUSPROCESSID, BONUSID, BONUSMONTH, PAYROLLTYPEID, ISTAXPROCESS, ISDISBURSEWITHSALARY + FROM BONUSPROCESS + WHERE BONUSPROCESSID = %n", bonusProcessID); + } + + /// + /// Clear Tax: the tax of every row of one bonus process becomes 0 — what the old Clear Tax + Save wrote + /// to BONUSPROCESSDETAIL (only CHANGETAXAMOUNT; TAXAMOUNT, the calculated tax, is kept). + /// + internal static void ClearTaxOfProcess(TransactionContext tc, int bonusProcessID, int modifiedBy, DateTime modifiedDate) + { + tc.ExecuteNonQuery(@"UPDATE BONUSPROCESSDETAIL SET CHANGETAXAMOUNT = 0, MODIFIEDBY = %n, MODIFIEDDATE = %D + WHERE BONUSPROCESSID = %n", + modifiedBy, modifiedDate, bonusProcessID); + } + + /// + /// Clear Tax: the Tax Deducted line (ITEMCODE = Tax_Deducted, -212) of the bonus tax data (BONUSTEMPIT) of + /// every employee of one bonus process gets THISMONTHAMOUNT = 0 — the old save() merge with a cleared tax. + /// The other lines and columns are not touched. + /// + internal static void ClearBonusTempTaxOfProcess(TransactionContext tc, int bonusProcessID, int taxDeductedItemCode) + { + tc.ExecuteNonQuery(@"UPDATE BONUSTEMPIT SET THISMONTHAMOUNT = 0 + WHERE ITEMCODE = %n + AND EMPLOYEEID IN (SELECT EMPLOYEEID FROM BONUSPROCESSDETAIL WHERE BONUSPROCESSID = %n)", + taxDeductedItemCode, bonusProcessID); + } + + /// + /// Remove (saved row): this employee's bonus tax data (BONUSTEMPIT), only when the process was saved + /// with Calculate Tax — a process without tax wrote no BONUSTEMPIT rows for it. + /// + internal static void DeleteRowBonusTempTax(TransactionContext tc, int bonusProcessID, int employeeID) + { + tc.ExecuteNonQuery(@"DELETE FROM BONUSTEMPIT + WHERE EMPLOYEEID = %n + AND EXISTS (SELECT 1 FROM BONUSPROCESS WHERE BONUSPROCESSID = %n AND ISTAXPROCESS = 1)", + employeeID, bonusProcessID); + } + + /// Remove (saved row): this employee's cost-center split in this process. + internal static void DeleteRowCostCenter(TransactionContext tc, int bonusProcessID, int employeeID) + { + tc.ExecuteNonQuery("DELETE FROM BonusEmpCostCenter WHERE BonusProcessID = %n AND EmployeeID = %n", + bonusProcessID, employeeID); + } + + /// Remove (saved row): the row itself. + internal static void DeleteRow(TransactionContext tc, int bonusProcessDetailID) + { + tc.ExecuteNonQuery("DELETE FROM BONUSPROCESSDETAIL WHERE BONUSPROCESSDETAILID = %n", bonusProcessDetailID); + } + + /// Remove (saved row): how many rows the process still has. + internal static int CountRows(TransactionContext tc, int bonusProcessID) + { + object count = tc.ExecuteScalar("SELECT COUNT(*) FROM BONUSPROCESSDETAIL WHERE BONUSPROCESSID = %n", bonusProcessID); + return count == null || count == DBNull.Value ? 0 : Convert.ToInt32(count); + } + + /// Remove (saved row): the header of a process that has no rows left, and anything still hanging on it. + internal static void DeleteEmptyProcess(TransactionContext tc, int bonusProcessID) + { + tc.ExecuteNonQuery("DELETE FROM BonusEmpCostCenter WHERE BonusProcessID = %n", bonusProcessID); + tc.ExecuteNonQuery(@"DELETE FROM BONUSPROCESS WHERE BONUSPROCESSID = %n + AND NOT EXISTS (SELECT 1 FROM BONUSPROCESSDETAIL WHERE BONUSPROCESSID = %n)", + bonusProcessID, bonusProcessID); + } + internal static void Insert(TransactionContext tc, BonusProcess.BonusProcessDetail item) { string sql = SQLParser.MakeSQL( diff --git a/HRM.DA/DA/Employee/EmployeeDA.cs b/HRM.DA/DA/Employee/EmployeeDA.cs index 83be850..e16219e 100644 --- a/HRM.DA/DA/Employee/EmployeeDA.cs +++ b/HRM.DA/DA/Employee/EmployeeDA.cs @@ -785,6 +785,32 @@ namespace HRM.DA tc.ExecuteNonQuery("UPDATE EMPCONTACT SET presentPOInBangla = %s, presentAddressInBangla = %s, parmanentPOInBangla = %s, permanentAddressInBangla =%s WHERE EMPLOYEEID = %s", employeBanglaInfo[1], employeBanglaInfo[2], employeBanglaInfo[3], employeBanglaInfo[4], employeBanglaInfo[0]); } + /// + /// The full Employee rows of the given employees of one payroll type, for any number of employees + /// (10k+). Same result as GetByEmpIDs(tc, empIDs, payrollTypeID), but the IDs go in as ONE + /// varchar(max) parameter and a temp table with a primary key instead of an "IN (1,2,3,...)" list in + /// the SQL text. Needs SQL Server 2016+ (STRING_SPLIT). + /// + internal static IDataReader GetByEmpIDList(TransactionContext tc, List empIDs, int payrollTypeID) + { + string sql = SQLParser.MakeSQL(@"SET NOCOUNT ON; + IF OBJECT_ID('tempdb..#empListIds') IS NOT NULL DROP TABLE #empListIds; + CREATE TABLE #empListIds (ID int NOT NULL PRIMARY KEY); + INSERT INTO #empListIds (ID) SELECT DISTINCT CONVERT(int, value) FROM STRING_SPLIT(@empIds, ',') WHERE value <> ''; + SELECT e.* FROM Employee e + INNER JOIN #empListIds t ON t.ID = e.EMPLOYEEID + WHERE e.PAYROLLTYPEID = %n + ORDER BY e.EmployeeNo; + DROP TABLE #empListIds;", payrollTypeID); + + // must be a SqlParameter[]: Ease.Core casts the array to SqlParameter[] + SqlParameter[] parameters = + { + SqlHelperExtension.CreateInParam("@empIds", SqlDbType.VarChar, string.Join(",", empIDs), -1) // varchar(max) + }; + return tc.ExecuteReader(CommandType.Text, sql, parameters); + } + internal static IDataReader GetByEmpIDs(TransactionContext tc, string empIDs) { string sTableName; diff --git a/HRM.DA/DA/Tax/IncomeTaxDA.cs b/HRM.DA/DA/Tax/IncomeTaxDA.cs index 469ab93..1f3c025 100644 --- a/HRM.DA/DA/Tax/IncomeTaxDA.cs +++ b/HRM.DA/DA/Tax/IncomeTaxDA.cs @@ -160,6 +160,19 @@ namespace HRM.DA else return true; } + /// + /// Like hasTaxDataInSalaryTemp(tc, employeeId), but only SALARYTEMPIT (a salary processed and not yet + /// finalized) — BONUSTEMPIT is not looked at. Used by the Bonus Process Modify dialog: there the + /// employee's BONUSTEMPIT rows are that same bonus's own tax data, saved by Process. + /// + internal static bool hasTaxDataInSalaryTempOnly(TransactionContext tc, int employeeId) + { + object isprocessed = tc.ExecuteScalar(@"select count(*) cnt from SALARYTEMPIT WHERE EmployeeID =%n", employeeId); + if (isprocessed == null || isprocessed == DBNull.Value) + return false; + return Convert.ToInt32(isprocessed) > 0; + } + internal static EnumIncomeTaxDataFrom TaxDataFrom(TransactionContext tc, int employeeId) { object isprocessed = tc.ExecuteScalar(@"if exists(select * from SALARYTEMPIT where EmployeeID =%n ) select 3 diff --git a/HRM.DA/Service/Bonus/BonusCalculator.cs b/HRM.DA/Service/Bonus/BonusCalculator.cs index b91fb76..c7dc373 100644 --- a/HRM.DA/Service/Bonus/BonusCalculator.cs +++ b/HRM.DA/Service/Bonus/BonusCalculator.cs @@ -495,6 +495,60 @@ namespace HRM.DA } } + /// + /// A copy of CalculateTax for the Bonus Process Modify dialog (one employee, after Process has already + /// saved). The only difference: the "salary processed and not yet finalized" check looks at SALARYTEMPIT + /// only, not at BONUSTEMPIT — after Process the employee's BONUSTEMPIT rows are this same bonus's own + /// tax data, so CalculateTax would always refuse. A salary in the middle of its process still stops it. + /// CalculateTax itself is unchanged and still used by Process, Upload and CalculateBonusTax. + /// + public void CalculateTaxForModify(List bprocesdetails, List oEmployees, Bonus oBonus, int payrolltypeid) + { + if (_payrolltype == null) + _payrolltype = new PayrollTypeService().Get(payrolltypeid); + + if (_parameters == null) + _parameters = new BonusParameterService().Get(EnumStatus.Regardless, payrolltypeid); + + if (_payrolltype.TaxParamID == null) throw new ServiceException("Current year Tax paramter setup not found."); + TaxParameter oparamter = new TaxParameterService().Get((int)_payrolltype.TaxParamID); + + List oParams = new ADParameterService().Get(EnumStatus.Regardless, EnumAllowOrDeduct.Allowance, _payrolltype.ID); + List oTaxes = new IncomeTaxService().Get(EnumIncomeTaxDataFrom.ProcessTempData, _payrolltype.ID); + double nTaxAmount = 0; + int nCount = 0; + // salary only (SALARYTEMPIT); the employee's own bonus tax rows (BONUSTEMPIT) do not stop a Modify + IncomeTaxService taxService = new IncomeTaxService(); + bool salaryProcessed = oEmployees.Any(e => e != null && taxService.hasTaxDataInSalaryTempOnly(e.ID)); + if (salaryProcessed == true) + { + throw new ServiceException("Current month salary is processed and not yet finalized. Tax calculation " + + " is not allowed middle of this process. You have to Undo or finalize the salary to calculate tax."); + } + TaxCalculator oCalculator = new TaxCalculator((int)_payrolltype.TaxParamID, _payrolltype.ID); + oCalculator.TaxParameter = oparamter; + oCalculator.payrolltype = _payrolltype; + foreach (BonusProcess.BonusProcessDetail item in bprocesdetails) + { + nCount++; + oCalculator.Employee = oEmployees.FirstOrDefault(x => x.ID == item.EmployeeID); + if (item.BonusParam == null) + { + item.BonusParam = new BonusParameterService().GetApplicableParameter(item.Employee, (int)item.Employee.GradeID, _parameters, oBonus.ID); + } + + if (item.ChangeBonusAmount > 0) + { + List oTaxRowItems = new List(); + oTaxRowItems.Add(TaxRawItem.Create(oBonus.Name, item.ChangeBonusAmount, enumIncomeTaxItemType.Bonus, item.BonusID)); + nTaxAmount = 0; + item.IncomeTaxcoll = oCalculator.CalculateBonus(oTaxRowItems, item.BonusParam, ref nTaxAmount, oParams, oTaxes); + item.TaxAmount = nTaxAmount; + item.ChangeTaxAmount = nTaxAmount; + } + } + } + public void UndoTax(BonusProcess oProcessedItems, List oEmployees, Bonus oBonus) { if (_payrolltype.TaxParamID == null) throw new ServiceException("Current year Tax paramter setup not found."); diff --git a/HRM.DA/Service/Bonus/BonusProcessService.cs b/HRM.DA/Service/Bonus/BonusProcessService.cs index 335e9a8..b26b15e 100644 --- a/HRM.DA/Service/Bonus/BonusProcessService.cs +++ b/HRM.DA/Service/Bonus/BonusProcessService.cs @@ -903,6 +903,692 @@ namespace HRM.DA } } + /// + /// Bonus Process screen, "Process" button: calculate the bonus (and tax) of the given employees and + /// save it in the same call — there is no separate Save step any more. Does on the server what the + /// screen used to do in three requests (BonusProcess, the tax-merge step of save(), saveBonusProcess): + /// 1. checks: bonus not approved, inputs present; employees this bonus was already processed for this + /// month are left out (the screen already leaves them out and lists them); + /// 2. CalculateBonus — the same BonusCalculator.CalCulate the old Process button called; + /// 3. tax merge — the same rule save() applied in the browser, now for every row; + /// 4. save — the same rows Save(BonusProcess) writes, in ONE transaction (all or nothing), with the + /// detail rows inserted by one bulk copy instead of one INSERT each; + /// 5. returns the saved rows, read back from the database. + /// + public BonusProcessAndSaveResult ProcessAndSave(BonusProcessAndSaveRequest request, int payrolltypeid, int userID) + { + if (request == null) + throw new ServiceException("Nothing to process."); + if (request.BonusID <= 0) + throw new ServiceException("Please select a bonus."); + if (request.EmployeeIDs == null || request.EmployeeIDs.Count == 0) + throw new ServiceException("Please select employee for the proces"); + if (request.CurrProcess <= 0) + throw new ServiceException("Currently Process For Basic must be greater than zero."); + + PayrollType payrollType = new PayrollTypeService().Get(payrolltypeid); + if (payrollType == null) + throw new ServiceException("Payroll type not found."); + DateTime bonusMonth = payrollType.NextPayProcessDate; + + // 1. checks + if (this.IsApproved(request.BonusID, bonusMonth, payrolltypeid)) + throw new ServiceException("selected Bonus is already process and Approved"); + + BonusProcessAndSaveResult result = new BonusProcessAndSaveResult(); + HashSet alreadyProcessed = new HashSet( + (this.GetBonusDetails(payrolltypeid, request.BonusID, bonusMonth) ?? new List()) + .Select(x => x.EmployeeID)); + List empIDs = new List(); + foreach (int id in request.EmployeeIDs.Distinct()) + { + if (alreadyProcessed.Contains(id)) result.AlreadyProcessedEmployeeIDs.Add(id); + else empIDs.Add(id); + } + if (empIDs.Count == 0) + throw new ServiceException("The selected bonus is already processed for all the selected employees."); + + List employees = new EmployeeService().GetByEmpIDList(empIDs, payrolltypeid); + if (employees.Count == 0) + throw new ServiceException("Selected employees not found in the current payroll type."); + + // 2. calculate (bonus, and tax when IsTaxProcess and not disbursed with salary) + BonusProcess oProcess = this.CalculateBonus(payrolltypeid, employees, request.BonusID, request.BasicMonth, + request.PayDate, request.CuttOfDate, request.CurrProcess, request.IsDisburseWithSalary, request.IsTaxProcess); + if (oProcess == null || oProcess.BonusProcessDetails == null || oProcess.BonusProcessDetails.Count == 0) + throw new ServiceException("There are no data to save"); + + // 3. tax merge: the bonus head's tax line carries the bonus amount, the Tax Deducted line the tax + if (request.IsTaxProcess) + ApplyTaxMerge(oProcess, employees, payrollType, request.BonusID); + + // 4. save — header as saveBonusProcess set it, then the same rows Save(BonusProcess) writes + oProcess.PayrollTypeID = payrolltypeid; + oProcess.DisburseDate = request.PayDate; + oProcess.IsTaxProcess = request.IsTaxProcess; + oProcess.IsDisburseWithSalary = request.IsDisburseWithSalary; + oProcess.CreatedBy = userID; + oProcess.CreatedDate = DateTime.Today; + SaveNewProcess(oProcess); + + // 5. what was saved + result.BonusProcessID = oProcess.ID; + result.Rows = this.GetGridRows(oProcess.ID); + return result; + } + + /// + /// Bonus Process screen, "Upload Data": the rows read from the bonus Excel file (employee + amount, + /// RegularDataUploadService.GetBonusData) are saved in the same request — what used to be upload → + /// (Tax Re-calculate) → Save, now on the server in one go: + /// 1. checks: bonus selected, pay date, not approved; every employee in the current payroll type and + /// only once in the file; employees this bonus was already processed for this month are left out; + /// 2. with IsTaxProcess, the tax of every row (the same CalculateTax "Tax Re-calculate" ran) and the + /// save() tax merge; without it the amounts are saved as they are in the file; + /// 3. the same save as the Process button (one transaction, all or nothing); + /// 4. returns the saved rows, read back from the database. + /// The header is filled the way the screen filled it after an upload (bonus month and basic month = + /// the next pay process month, disburse date = pay date). + /// + public BonusProcessAndSaveResult UploadAndSave(List uploadedRows, + BonusProcessAndSaveRequest request, int payrolltypeid, int userID) + { + if (request == null || request.BonusID <= 0) + throw new ServiceException("Please select a bonus."); + if (request.PayDate == DateTime.MinValue) + throw new ServiceException("Please select the pay date."); + if (uploadedRows == null || uploadedRows.Count == 0) + throw new ServiceException("No employee found in the uploaded file."); + + PayrollType payrollType = new PayrollTypeService().Get(payrolltypeid); + if (payrollType == null) + throw new ServiceException("Payroll type not found."); + DateTime bonusMonth = payrollType.NextPayProcessDate; + + // 1. checks + if (this.IsApproved(request.BonusID, bonusMonth, payrolltypeid)) + throw new ServiceException("selected Bonus is already process and Approved"); + + List problems = new List(); + var otherPayroll = uploadedRows.Where(x => x.Employee != null && x.Employee.PayrollTypeID != payrolltypeid) + .Select(x => x.Employee.EmployeeNo).Distinct().ToList(); + if (otherPayroll.Count > 0) + problems.Add("Not in the current payroll type: " + string.Join(", ", otherPayroll)); + var duplicates = uploadedRows.GroupBy(x => x.EmployeeID).Where(g => g.Count() > 1) + .Select(g => g.First().Employee?.EmployeeNo ?? g.Key.ToString()).ToList(); + if (duplicates.Count > 0) + problems.Add("More than once in the file: " + string.Join(", ", duplicates)); + var negative = uploadedRows.Where(x => x.BonusAmount < 0).Select(x => x.Employee?.EmployeeNo ?? x.EmployeeID.ToString()).ToList(); + if (negative.Count > 0) + problems.Add("Negative amount: " + string.Join(", ", negative)); + if (problems.Count > 0) + throw new ServiceException("Nothing was saved. " + string.Join(" | ", problems)); + + BonusProcessAndSaveResult result = new BonusProcessAndSaveResult(); + HashSet alreadyProcessed = new HashSet( + (this.GetBonusDetails(payrolltypeid, request.BonusID, bonusMonth) ?? new List()) + .Select(x => x.EmployeeID)); + + BonusProcess oProcess = new BonusProcess(); + oProcess.BonusProcessDetails = new List(); + oProcess.BonusID = request.BonusID; + oProcess.BonusMonth = bonusMonth; + oProcess.BasicOnMonth = bonusMonth; + oProcess.DisburseDate = request.PayDate; + oProcess.IsTaxProcess = request.IsTaxProcess; + oProcess.IsDisburseWithSalary = request.IsDisburseWithSalary; + oProcess.PayrollTypeID = payrolltypeid; + oProcess.CreatedBy = userID; + oProcess.CreatedDate = DateTime.Today; + + List employees = new List(); + foreach (BonusProcess.BonusProcessDetail row in uploadedRows) + { + if (alreadyProcessed.Contains(row.EmployeeID)) + { + result.AlreadyProcessedEmployeeIDs.Add(row.EmployeeID); + continue; + } + row.BonusID = request.BonusID; + row.BonusMonth = bonusMonth; + oProcess.BonusProcessDetails.Add(row); + if (row.Employee != null) employees.Add(row.Employee); + } + if (oProcess.BonusProcessDetails.Count == 0) + throw new ServiceException("The selected bonus is already processed for all the employees in the file."); + + // 2. tax (as "Tax Re-calculate" did) and the save() merge + if (request.IsTaxProcess) + { + Bonus obonus = new BonusService().Get(request.BonusID); + new BonusCalculator().CalculateTax(oProcess.BonusProcessDetails, employees, obonus, payrolltypeid); + ApplyTaxMerge(oProcess, employees, payrollType, request.BonusID); + } + + // 3. save + SaveNewProcess(oProcess); + + // 4. what was saved + result.BonusProcessID = oProcess.ID; + result.Rows = this.GetGridRows(oProcess.ID); + return result; + } + + /// + /// The tax-merge rule the screen's save() applied: on every row the bonus head's tax line + /// (TaxMergeMaster of this bonus) carries the bonus amount and the Tax Deducted line the tax. + /// + private void ApplyTaxMerge(BonusProcess oProcess, List employees, PayrollType payrollType, int bonusID) + { + // a row with no bonus gets no tax lines (CalculateTax skips it), so only rows with a bonus need them + if (oProcess.BonusProcessDetails.Any(x => x.ChangeBonusAmount > 0 && (x.IncomeTaxcoll == null || x.IncomeTaxcoll.Count == 0))) + throw new ServiceException("Tax Calculation not yet done"); + if (payrollType.TaxParamID == null) + throw new ServiceException("Current year Tax paramter setup not found."); + + TaxMergeMaster mitem = new TaxMergeMasterService().Get(payrollType.ID, (int)payrollType.TaxParamID, + EnumTaxMergeType.Bonus, bonusID); + if (mitem == null) + throw new ServiceException("Bonus head not found in the income tax Grouping"); + + Dictionary empByID = employees.GroupBy(x => x.ID).ToDictionary(g => g.Key, g => g.First()); + foreach (BonusProcess.BonusProcessDetail detail in oProcess.BonusProcessDetails) + { + if (detail.IncomeTaxcoll == null || detail.IncomeTaxcoll.Count == 0) + continue; // no bonus, no tax lines + IncomeTax bonusLine = detail.IncomeTaxcoll.Find(y => y.ItemGroup == mitem.ItemGroup && y.ItemID == mitem.ItemID); + if (bonusLine == null) + { + Employee emp; + empByID.TryGetValue(detail.EmployeeID, out emp); + throw new ServiceException("Income tax amount not found in the collection" + + (emp != null ? " (" + emp.EmployeeNo + " " + emp.Name + ")" : "")); + } + bonusLine.ThisMonthAmount = detail.ChangeBonusAmount; + + IncomeTax taxLine = detail.IncomeTaxcoll.Find(y => y.ItemGroup == EnumIncomeTaxItemGroup.Tax_Deducted); + if (taxLine != null) + taxLine.ThisMonthAmount = detail.ChangeTaxAmount; + } + } + + /// + /// Saves a new bonus process in ONE transaction: the header, every detail row (one bulk copy), the + /// bonus tax data (BonusITTempData) and the employee cost-center split — the rows Save(BonusProcess) + /// writes for a new process. Sets the IDs on oProcess and its details. + /// + private void SaveNewProcess(BonusProcess oProcess) + { + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(true); + + int processID = tc.GenerateID("BONUSPROCESS", "BONUSPROCESSID"); + base.SetObjectID(oProcess, processID); + BonusProcessDA.Insert(tc, oProcess); + + int detailID = tc.GenerateID("BONUSPROCESSDETAIL", "BonusProcessDetailID"); + List incometaxes = new List(); + foreach (BonusProcess.BonusProcessDetail detail in oProcess.BonusProcessDetails) + { + base.SetObjectID(detail, detailID++); + detail.BonusProcessID = oProcess.ID; + // IncomeTaxcoll null means tax process not required + if (detail.IncomeTaxcoll != null && detail.IncomeTaxcoll.Count > 0) + incometaxes.AddRange(detail.IncomeTaxcoll); + } + BonusProcessDA.InsertBulk(tc, oProcess.BonusProcessDetails); + + if (incometaxes.Count > 0) + new IncomeTaxService().SaveBulk(tc, incometaxes, EnumIncomeTaxDataFrom.BonusITTempData); + + SaveBonusEmpCostCenter(tc, oProcess); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + } + + /// The saved rows of one bonus process, as the Bonus Process grid shows them. + public List GetGridRows(int bonusProcessID) + { + List rows = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + + DataReader dr = new DataReader(BonusProcessDA.GetGridRows(tc, bonusProcessID)); + while (dr.Read()) + rows.Add(MapGridRow(dr)); + dr.Close(); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return rows; + } + + private static BonusProcessGridRow MapGridRow(DataReader dr) + { + return new BonusProcessGridRow + { + BonusProcessDetailID = dr.GetInt32("BONUSPROCESSDETAILID", 0), + BonusProcessID = dr.GetInt32("BONUSPROCESSID", 0), + BonusID = dr.GetInt32("BONUSID", 0), + EmployeeID = dr.GetInt32("EMPLOYEEID", 0), + EmployeeNo = dr.GetString("EMPLOYEENO", string.Empty), + Name = dr.GetString("NAME", string.Empty), + JoiningDate = dr.GetDateTime("JOININGDATE"), + IsConfirmed = dr.GetBoolean("ISCONFIRMED", false), + GrossSalary = dr.GetDouble("GROSSSALARY", 0), + BasicSalary = dr.GetDouble("BASICSALARY", 0), + BonusAmount = dr.GetDouble("BONUSAMOUNT", 0), + ChangeBonusAmount = dr.GetDouble("CHANGEBONUSAMOUNT", 0), + TaxAmount = dr.GetDouble("TAXAMOUNT", 0), + ChangeTaxAmount = dr.GetDouble("CHANGETAXAMOUNT", 0), + }; + } + + /// One saved row of the Bonus Process grid (after a Modify-dialog save). + public BonusProcessGridRow GetGridRow(int bonusProcessDetailID) + { + BonusProcessGridRow row = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + + DataReader dr = new DataReader(BonusProcessDA.GetGridRow(tc, bonusProcessDetailID)); + if (dr.Read()) + row = MapGridRow(dr); + dr.Close(); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return row; + } + + #region Modify dialog (one row at a time) + + /// A saved bonus row and the header fields the Modify dialog needs. + private class ModifyRow + { + public int BonusProcessDetailID; + public int BonusProcessID; + public int BonusID; + public int EmployeeID; + public double TaxAmount; + public DateTime BonusMonth; + public int PayrollTypeID; + } + + /// + /// Loads a saved row for the Modify dialog and refuses it when it is not the current payroll type's + /// or the bonus is already approved (the same rule as the Process button). + /// + private ModifyRow GetRowForModify(int bonusProcessDetailID, int payrolltypeid) + { + ModifyRow row = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + + DataReader dr = new DataReader(BonusProcessDA.GetRowWithHeader(tc, bonusProcessDetailID)); + if (dr.Read()) + { + row = new ModifyRow + { + BonusProcessDetailID = dr.GetInt32("BONUSPROCESSDETAILID", 0), + BonusProcessID = dr.GetInt32("BONUSPROCESSID", 0), + BonusID = dr.GetInt32("BONUSID", 0), + EmployeeID = dr.GetInt32("EMPLOYEEID", 0), + TaxAmount = dr.GetDouble("TAXAMOUNT", 0), + BonusMonth = dr.GetDateTime("BONUSMONTH", DateTime.MinValue), + PayrollTypeID = dr.GetInt32("PAYROLLTYPEID", 0), + }; + } + dr.Close(); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + if (row == null) + throw new ServiceException("Bonus row not found. Please process the bonus again."); + if (row.PayrollTypeID != payrolltypeid) + throw new ServiceException("This bonus row does not belong to the current payroll type."); + if (this.IsApproved(row.BonusID, row.BonusMonth, payrolltypeid)) + throw new ServiceException("selected Bonus is already process and Approved"); + return row; + } + + /// + /// The tax of one row for this bonus amount — the same BonusCalculator.CalculateTax that + /// "Tax Re-calculate" (CalculateBonusTax) runs, for one employee. Returns the detail with TaxAmount, + /// ChangeTaxAmount and IncomeTaxcoll filled in. + /// + private BonusProcess.BonusProcessDetail CalculateTaxFor(ModifyRow row, double bonusAmount, int payrolltypeid) + { + Employee emp = new EmployeeService().Get(row.EmployeeID); + if (emp == null) + throw new ServiceException("Employee not found."); + + BonusProcess.BonusProcessDetail detail = new BonusProcess.BonusProcessDetail(); + detail.BonusID = row.BonusID; + detail.EmployeeID = row.EmployeeID; + detail.BonusMonth = row.BonusMonth; + detail.ChangeBonusAmount = bonusAmount; + detail.Employee = emp; + + Bonus obonus = new BonusService().Get(row.BonusID); + // CalculateTaxForModify: CalculateTax, except that this employee's own (already saved) bonus tax rows + // do not block it — only an unfinalized salary does + new BonusCalculator().CalculateTaxForModify(new List { detail }, + new List { emp }, obonus, payrolltypeid); + return detail; + } + + /// Modify dialog, "Calculate": the tax for this bonus amount. Nothing is saved. + public BonusProcessRowTaxResult CalculateRowTax(BonusProcessRowTaxRequest request, int payrolltypeid) + { + if (request == null || request.BonusProcessDetailID <= 0) + throw new ServiceException("Please select a bonus row."); + if (request.BonusAmount < 0) + throw new ServiceException("Bonus amount can not be negative."); + + ModifyRow row = GetRowForModify(request.BonusProcessDetailID, payrolltypeid); + BonusProcess.BonusProcessDetail detail = CalculateTaxFor(row, request.BonusAmount, payrolltypeid); + return new BonusProcessRowTaxResult + { + BonusProcessDetailID = row.BonusProcessDetailID, + BonusAmount = request.BonusAmount, + TaxAmount = detail.ChangeTaxAmount, + }; + } + + /// + /// Modify dialog, "Save": saves ONE row — what Save(BonusProcess) did for every row after + /// "Tax Re-calculate", now for one employee, in one transaction: + /// - BONUSPROCESSDETAIL: ChangeBonusAmount, ChangeTaxAmount (and TaxAmount when the tax is calculated); + /// - this employee's BonusITTempData (BONUSTEMPIT) rows: deleted and written again, with the bonus + /// head's line carrying the bonus amount and the Tax Deducted line the tax (the save() merge rule). + /// With CalculateTax the tax is worked out again here (the amount the browser sent is not trusted); + /// without it the typed tax is used and the employee's existing tax rows are updated, as the old + /// screen did when a tax was typed into the grid and saved without recalculating. + /// + public BonusProcessGridRow SaveRow(BonusProcessRowSaveRequest request, int payrolltypeid, int userID) + { + if (request == null || request.BonusProcessDetailID <= 0) + throw new ServiceException("Please select a bonus row."); + if (request.BonusAmount < 0) + throw new ServiceException("Bonus amount can not be negative."); + if (!request.CalculateTax && request.TaxAmount < 0) + throw new ServiceException("Tax amount can not be negative."); + if (request.CalculateTax && request.EditedTaxAmount.HasValue && request.EditedTaxAmount.Value < 0) + throw new ServiceException("Edited tax amount can not be negative."); + + ModifyRow row = GetRowForModify(request.BonusProcessDetailID, payrolltypeid); + + double bonusAmount = request.BonusAmount; + double changeTaxAmount; + double taxAmount = row.TaxAmount; // the calculated tax; kept when a tax is typed in + List taxLines = null; + + if (request.CalculateTax) + { + BonusProcess.BonusProcessDetail detail = CalculateTaxFor(row, bonusAmount, payrolltypeid); + // the user's "Edited Tax Amount" wins over the calculated one; TAXAMOUNT keeps the calculated tax + changeTaxAmount = request.EditedTaxAmount.HasValue ? request.EditedTaxAmount.Value : detail.ChangeTaxAmount; + taxAmount = detail.TaxAmount; + taxLines = detail.IncomeTaxcoll; + } + else + { + changeTaxAmount = request.TaxAmount; + List existing = new IncomeTaxService().Get(row.EmployeeID, EnumIncomeTaxDataFrom.BonusITTempData); + if (existing != null && existing.Count > 0) + taxLines = existing; + } + + if (taxLines != null && taxLines.Count > 0) + { + PayrollType payrollType = new PayrollTypeService().Get(payrolltypeid); + if (payrollType == null || payrollType.TaxParamID == null) + throw new ServiceException("Current year Tax paramter setup not found."); + TaxMergeMaster mitem = new TaxMergeMasterService().Get(payrolltypeid, (int)payrollType.TaxParamID, + EnumTaxMergeType.Bonus, row.BonusID); + if (mitem == null) + throw new ServiceException("Bonus head not found in the income tax Grouping"); + + IncomeTax bonusLine = taxLines.Find(y => y.ItemGroup == mitem.ItemGroup && y.ItemID == mitem.ItemID); + if (bonusLine == null) + throw new ServiceException("Income tax amount not found in the collection"); + bonusLine.ThisMonthAmount = bonusAmount; + + IncomeTax taxLine = taxLines.Find(y => y.ItemGroup == EnumIncomeTaxItemGroup.Tax_Deducted); + if (taxLine != null) + taxLine.ThisMonthAmount = changeTaxAmount; + } + + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(true); + + BonusProcessDA.UpdateRowAmounts(tc, row.BonusProcessDetailID, bonusAmount, changeTaxAmount, taxAmount, + userID, DateTime.Now); + + if (taxLines != null && taxLines.Count > 0) + { + IncomeTaxService taxService = new IncomeTaxService(); + taxService.Delete(tc, row.EmployeeID.ToString(), EnumIncomeTaxDataFrom.BonusITTempData); + taxService.SaveBulk(tc, taxLines, EnumIncomeTaxDataFrom.BonusITTempData); + } + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return this.GetGridRow(row.BonusProcessDetailID); + } + + #endregion + + #region Remove (one saved row, deleted straight away) + + /// + /// Remove button on a saved row: what the old Remove + Save left in the database (the employee simply + /// not saved), now deleted at once since Process already saved it — in one transaction: + /// - BONUSTEMPIT: this employee's rows (only when the process was saved with Calculate Tax); + /// - BonusEmpCostCenter: this employee's rows in this process; + /// - BONUSPROCESSDETAIL: the row; + /// - BONUSPROCESS: the header too, when that was the process's last employee. + /// Refused when the row is not found, not the current payroll type's, or the bonus is already approved + /// (the same checks as the Modify dialog). Rows not saved yet are removed in the browser only, as before. + /// + public BonusProcessRowRemoveResult RemoveRow(int bonusProcessDetailID, int payrolltypeid) + { + if (bonusProcessDetailID <= 0) + throw new ServiceException("Please select a bonus row."); + + ModifyRow row = GetRowForModify(bonusProcessDetailID, payrolltypeid); + BonusProcessRowRemoveResult result = new BonusProcessRowRemoveResult + { + BonusProcessDetailID = row.BonusProcessDetailID, + BonusProcessID = row.BonusProcessID, + }; + + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(true); + + BonusProcessDA.DeleteRowBonusTempTax(tc, row.BonusProcessID, row.EmployeeID); + BonusProcessDA.DeleteRowCostCenter(tc, row.BonusProcessID, row.EmployeeID); + BonusProcessDA.DeleteRow(tc, row.BonusProcessDetailID); + + if (BonusProcessDA.CountRows(tc, row.BonusProcessID) == 0) + { + BonusProcessDA.DeleteEmptyProcess(tc, row.BonusProcessID); + result.ProcessDeleted = true; + } + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return result; + } + + #endregion + + #region Clear Tax (whole process, saved straight away) + + /// + /// Bonus Process screen, "Clear Tax": what the old Clear Tax + Save did, now saved at once (there is no + /// Save button any more), for every employee of the process on the screen, in one transaction: + /// - BONUSPROCESSDETAIL: CHANGETAXAMOUNT = 0 (TAXAMOUNT, the calculated tax, is kept); + /// - BONUSTEMPIT: THISMONTHAMOUNT = 0 on the Tax Deducted line (-212) of those employees. + /// Refused when the process is not the current payroll type's or the bonus is already approved. + /// The old clearTax() (browser only) is kept as it was. + /// + public List ClearTaxAndSave(int bonusProcessID, int payrolltypeid, int userID) + { + if (bonusProcessID <= 0) + throw new ServiceException("Please process the bonus first."); + + int bonusID = 0; + int processPayrollTypeID = 0; + DateTime bonusMonth = DateTime.MinValue; + bool found = false; + + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(BonusProcessDA.GetProcessHeaderForClearTax(tc, bonusProcessID)); + if (dr.Read()) + { + found = true; + bonusID = dr.GetInt32("BONUSID", 0); + bonusMonth = dr.GetDateTime("BONUSMONTH", DateTime.MinValue); + processPayrollTypeID = dr.GetInt32("PAYROLLTYPEID", 0); + } + dr.Close(); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + if (!found) + throw new ServiceException("Bonus process not found. Please process the bonus again."); + if (processPayrollTypeID != payrolltypeid) + throw new ServiceException("This bonus process does not belong to the current payroll type."); + if (this.IsApproved(bonusID, bonusMonth, payrolltypeid)) + throw new ServiceException("selected Bonus is already process and Approved"); + + tc = null; + try + { + tc = TransactionContext.Begin(true); + + BonusProcessDA.ClearTaxOfProcess(tc, bonusProcessID, userID, DateTime.Now); + BonusProcessDA.ClearBonusTempTaxOfProcess(tc, bonusProcessID, (int)EnumIncomeTaxItemGroup.Tax_Deducted); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return this.GetGridRows(bonusProcessID); + } + + #endregion + /// /// Builds the employee cost-center split for every employee in the bonus process and /// bulk-inserts it into BonusEmpCostCenter (mirrors the SalaryEmpCostCenter handling in diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index e5b7abb..ff0e2b2 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -1860,6 +1860,43 @@ namespace HRM.DA return employees; } + /// + /// Same as GetByEmpIDs(string, int), for any number of employees (10k+): the IDs reach SQL Server as + /// one parameter and a temp table, not as an IN list in the SQL text. + /// + public List GetByEmpIDList(List empIDs, int payrollTypeID) + { + List employees = new List(); + if (empIDs == null || empIDs.Count == 0) + return employees; + + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + + DataReader dr = new DataReader(EmployeeDA.GetByEmpIDList(tc, empIDs.Distinct().ToList(), payrollTypeID)); + employees = this.CreateObjects(dr); + dr.Close(); + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + + throw new ServiceException(e.Message, e); + + #endregion + } + + return employees; + } + public List GetByEmpIDs(string empIDs) { List employees = new List(); diff --git a/HRM.DA/Service/Tax/IncomeTaxService.cs b/HRM.DA/Service/Tax/IncomeTaxService.cs index d2186dd..3f8ca8a 100644 --- a/HRM.DA/Service/Tax/IncomeTaxService.cs +++ b/HRM.DA/Service/Tax/IncomeTaxService.cs @@ -316,6 +316,36 @@ namespace HRM.DA return DataExist; } + /// + /// Only SALARYTEMPIT (salary processed, not yet finalized) — unlike hasTaxDataInSalaryTemp, the + /// employee's BONUSTEMPIT rows are not counted. For the Bonus Process Modify dialog. + /// + public bool hasTaxDataInSalaryTempOnly(int employeeID) + { + bool DataExist = false; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataExist = IncomeTaxDA.hasTaxDataInSalaryTempOnly(tc, employeeID); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + + throw new ServiceException(e.Message, e); + + #endregion + } + + return DataExist; + } + public EnumIncomeTaxDataFrom currentYeardataSource(int employeeID) { diff --git a/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcess.ts b/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcess.ts index 3106fb5..ed68dc2 100644 --- a/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcess.ts +++ b/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcess.ts @@ -31,6 +31,8 @@ export class BonusProcess extends BaseObject { } export class BonusProcessDetail { + // the saved row's BONUSPROCESSDETAILID (set on rows that came back from api/Bonus/processAndSave) + bonusProcessDetailID?: number; isProjectedBonus: boolean; bonusProcessID: number; bonusID: number; diff --git a/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcessAndSave.ts b/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcessAndSave.ts new file mode 100644 index 0000000..3631f7a --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/Payroll/bonusProcessAndSave.ts @@ -0,0 +1,66 @@ +// api/Bonus/processAndSave — mirrors HRM.BO BonusProcessAndSave.cs (add a field in both). + +// What the Process button sends: the header and the employee IDs only. +export interface BonusProcessAndSaveRequest { + bonusID: number; + basicMonth: Date; + payDate: Date; + cuttOfDate: Date; + currProcess: number; + isDisburseWithSalary: boolean; + isTaxProcess: boolean; + employeeIDs: number[]; +} + +// One saved row of the Bonus Process grid, read back from the database. +export interface BonusProcessGridRow { + bonusProcessDetailID: number; + bonusProcessID: number; + bonusID: number; + employeeID: number; + employeeNo: string; + name: string; + joiningDate: Date; + isConfirmed: boolean; + grossSalary: number; + basicSalary: number; + bonusAmount: number; + changeBonusAmount: number; + taxAmount: number; + changeTaxAmount: number; +} + +// Modify dialog, Calculate (api/Bonus/calculateRowTax): nothing is saved +export interface BonusProcessRowTaxRequest { + bonusProcessDetailID: number; + bonusAmount: number; +} +export interface BonusProcessRowTaxResult { + bonusProcessDetailID: number; + bonusAmount: number; + taxAmount: number; +} + +// Modify dialog, Save (api/Bonus/saveRow): with calculateTax the server works the tax out again +export interface BonusProcessRowSaveRequest { + bonusProcessDetailID: number; + bonusAmount: number; + taxAmount: number; + calculateTax: boolean; + // "Edited Tax Amount": with calculateTax, the tax the user settled on (saved as changeTaxAmount); undefined = the calculated tax + editedTaxAmount?: number; +} + +export interface BonusProcessAndSaveResult { + bonusProcessID: number; + rows: BonusProcessGridRow[]; + // employees left out because this bonus was already processed for them this month + alreadyProcessedEmployeeIDs: number[]; +} + +// Remove on a saved row (api/Bonus/removeRow/{id}): processDeleted = it was the last employee, the header is gone too +export interface BonusProcessRowRemoveResult { + bonusProcessDetailID: number; + bonusProcessID: number; + processDeleted: boolean; +} diff --git a/HRM.UI/ClientApp/src/app/_services/Basic/dataUpload.service.ts b/HRM.UI/ClientApp/src/app/_services/Basic/dataUpload.service.ts index b04e1e5..6625a01 100644 --- a/HRM.UI/ClientApp/src/app/_services/Basic/dataUpload.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/Basic/dataUpload.service.ts @@ -2,6 +2,7 @@ import {Injectable} from '@angular/core'; import {ApiService} from '../../app.api.service'; import {HttpClient, HttpEvent, HttpRequest} from '@angular/common/http'; import { Observable } from 'rxjs'; +import { BonusProcessAndSaveRequest, BonusProcessAndSaveResult } from '../../_models/Payroll/bonusProcessAndSave'; @Injectable({ providedIn: 'root' @@ -35,6 +36,15 @@ export class DataUploadService { return this.http.request(req); } + // Bonus Process, Upload Data: the file is read AND saved (with the tax when asked) in one request. + // header = the same fields the Process button sends (api/dataUpload/uploadBonusFileAndSave) + public uploadBonusFileAndSave(selectedFile: File, header: BonusProcessAndSaveRequest): Observable { + const formData: FormData = new FormData(); + formData.append('excelfile', selectedFile); + formData.append('header', JSON.stringify(header)); + return this.http.post(`${this.apiService.base_url + '/'}dataUpload/uploadBonusFileAndSave`, formData); + } + public uploadBonusFile(selectedFile: File, payrolltypeid: number): Observable> { const formData: FormData = new FormData(); diff --git a/HRM.UI/ClientApp/src/app/_services/payroll/bonus.service.ts b/HRM.UI/ClientApp/src/app/_services/payroll/bonus.service.ts index b49136c..cb0750c 100644 --- a/HRM.UI/ClientApp/src/app/_services/payroll/bonus.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/payroll/bonus.service.ts @@ -10,6 +10,8 @@ import { ProductionBonusSetup } from '../../_models/Payroll/ProductionBonus/prod import { ProductionBonusSetupComponent } from 'src/app/payroll-ot/production-bonus-setup/production-bonus-setup.component'; import { ProdBonusLine } from 'src/app/_models/Payroll/ProductionBonus/prodBonusLine'; import { Employee } from 'src/app/_models/Employee/employee'; +import { BonusProcessAndSaveRequest, BonusProcessAndSaveResult, BonusProcessGridRow, BonusProcessRowSaveRequest, + BonusProcessRowTaxRequest, BonusProcessRowTaxResult, BonusProcessRowRemoveResult } from 'src/app/_models/Payroll/bonusProcessAndSave'; import { ProdBonusAttn } from 'src/app/_models/Payroll/ProductionBonus/prodBonusAttn'; import { ProdBonusProcess } from 'src/app/_models/Payroll/ProductionBonus/prodBonusProcess'; import { PRBCalculation, PRBCalculationReport, PRBKpi } from '../../_models/Payroll/prbCalculation'; @@ -44,6 +46,23 @@ export class BonusService { saveBonusProcess(param: any) { return this.apiService.httpPost('/Bonus/saveBonusProcess/', param); } + // Process button: calculates and saves in one request; returns the saved rows (see BonusProcessService.ProcessAndSave) + processAndSave(param: BonusProcessAndSaveRequest) { + return this.apiService.httpPost('/Bonus/processAndSave', param); + } + // Modify dialog: tax of one saved row (nothing saved), and saving one row + calculateRowTax(param: BonusProcessRowTaxRequest) { + return this.apiService.httpPost('/Bonus/calculateRowTax', param); + } + saveRow(param: BonusProcessRowSaveRequest) { + return this.apiService.httpPost('/Bonus/saveRow', param); + } + clearTaxAndSave(bonusProcessID: number) { + return this.apiService.httpPost('/Bonus/clearTaxAndSave/' + bonusProcessID, {}); + } + removeRow(bonusProcessDetailID: number) { + return this.apiService.httpPost('/Bonus/removeRow/' + bonusProcessDetailID, {}); + } GetUnApprovedBonusses() { return this.apiService.httpGet('/Bonus/GetUnApprovedBonusses' ); } diff --git a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.css b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.css index e69de29..0e7bc82 100644 --- a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.css +++ b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.css @@ -0,0 +1,70 @@ +/* Bonus Process: the input panels at the top (colors are the app's $brand-* / $gray-* tokens as literals) */ +.bp-panel { + background: #ffffff; + border: 1px solid #E4E4EE; + border-radius: 8px; + padding: 12px 16px 6px 16px; + margin-bottom: 12px; +} + +.bp-panel-title { + font-weight: 600; + font-size: 14px; + color: #414278; + padding-bottom: 8px; + margin-bottom: 6px; + border-bottom: 1px solid #DEDEFF; +} + +.bp-field { + display: flex; + flex-direction: column; + gap: 4px; +} + +.bp-label { + font-size: 12px; + font-weight: 600; + color: #666666; +} + +.bp-required { + color: #d9534f; +} + +.bp-options { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 24px; + min-height: 30px; +} + +.bp-option { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.bp-option label { + cursor: pointer; + margin: 0; +} + +/* Process / Clear Tax / Upload Data: pushed to the far right of the options row */ +.bp-actions { + display: inline-flex; + flex-wrap: wrap; + gap: 6px; + margin-left: auto; +} + +.bp-message { + padding: 6px 2px 8px 2px; + color: #414278; +} + +/* in the grid toolbar: no extra height, kept on the far right */ +span.bp-message { + padding: 0 4px; +} diff --git a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.html b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.html index 62ee824..d260c4f 100644 --- a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.html +++ b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.html @@ -3,133 +3,96 @@
-
-
-
- -
-
- - -
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
- - -
- -
-
-
-
-
- -
-
- - {{returnMessage}} -
-
-
-
-
-
-
- - -
+ +
+
+
Bonus Information
+
+
+ + +
-
-
- - -
+
+ + +
+
+ + + +
+
+ + +
+
+ + +
+
+
+ +
+
Employees & Options
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
- - - -
-
-
- - -
-
- - -
-
- - - - -
-
-
- + +
+
@@ -140,6 +103,10 @@ Export to Excel Count: {{ bonusProcess?.bonusProcessDetails.length}} + @if (returnMessage) { + + {{returnMessage}} + } @@ -167,6 +134,8 @@ {{dataItem.employee.basicSalary | number:'1.2-2'}} + + + + {{dataItem.changeBonusAmount | number:'1.2-2'}} + + + + + {{dataItem.changeTaxAmount | number:'1.2-2'}} + + {{(dataItem.changeBonusAmount - dataItem.changeTaxAmount) | number:'1.2-2'}} - + + + + + @if (dataItem.bonusProcessDetailID) { + + } + + + -
- - -
- - - - - @if (showModal) { @@ -235,8 +220,6 @@
} - - @if (showBonusUpload) { @@ -255,8 +238,9 @@
- + +
@@ -266,3 +250,61 @@
} + + + @if (showModify && modifyRow) { +
+ + +
+
+
{{modifyRow.employee?.employeeNo}} - {{modifyRow.employee?.name}}
+
+
+ + +
+
+
+ + +
+ +
+
+ + + @if (modifyCalculateTax && !modifyTaxCalculated) { + Press Calculate to see the tax. On Save the tax is calculated again for this bonus. + } +
+ + @if (modifyCalculateTax) { +
+
+ + +
+ } +
+
{{ ((modifyBonusAmount || 0) - ((modifyCalculateTax ? modifyEditedTaxAmount : modifyTaxAmount) || 0)) | number:'1.2-2' }}
+
+ + + + +
+
+ } diff --git a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.ts b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.ts index d67ae90..0e66f1c 100644 --- a/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.ts +++ b/HRM.UI/ClientApp/src/app/payroll-ot/bonus-process/bonus-process.component.ts @@ -12,6 +12,7 @@ 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'; @@ -66,6 +67,17 @@ export class BonusProcessComponent implements OnInit { 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, @@ -111,6 +123,13 @@ export class BonusProcessComponent implements OnInit { }); } 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) { @@ -217,6 +236,20 @@ export class BonusProcessComponent implements OnInit { 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( @@ -235,41 +268,281 @@ export class BonusProcessComponent implements OnInit { 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 - }); - }); + // 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.BonusProcess(this.processRequest).subscribe( - (resp: any) => { - this.bonusProcess = resp; + this.bonusService.processAndSave(request).subscribe( + (resp: BonusProcessAndSaveResult) => { + result = resp; }, (err: any) => { this.loadingPanelService.ShowLoadingPanel = false; - this.notificationService.showWarning(err.error); - this.returnMessage = err.error; + 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; - this.notificationService.showSuccess('Bonus processed successfully'); - this.returnMessage = 'Bonus processed successfully'; + 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(); @@ -512,7 +785,6 @@ export class BonusProcessComponent implements OnInit { console.log('[SAVE SIZE] could not measure:', e); } } - saveData() { this.loadingPanelService.ShowLoadingPanel = true; this.bonusProcess.disburseDate = this.payDate; @@ -538,8 +810,52 @@ export class BonusProcessComponent implements OnInit { } ); } - 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; @@ -548,36 +864,72 @@ export class BonusProcessComponent implements OnInit { }); 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() { } diff --git a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs index 8731907..926f32e 100644 --- a/HRM.UI/Controllers/CommonInterface/DataUploadController.cs +++ b/HRM.UI/Controllers/CommonInterface/DataUploadController.cs @@ -24,18 +24,21 @@ namespace HRM.UI.Controllers.Payroll private readonly ISalaryMasterBulkUploadService _salaryMasterBulkUploadService; private readonly IEmployeePhotoBulkUploadService _employeePhotoBulkUploadService; private readonly ICacheManager _cashManager; + private readonly IBonusProcessService _bonusProcessService; public DataUploadController(IDataUploadColumnDefinition columnDefination, IEmployeeBulkUploadService employeeBulkUploadService, ISalaryMasterBulkUploadService salaryMasterBulkUploadService, IEmployeePhotoBulkUploadService employeePhotoBulkUploadService, - ICacheManager cashManager) + ICacheManager cashManager, + IBonusProcessService bonusProcessService) { this._columnDefination = columnDefination; this._employeeBulkUploadService = employeeBulkUploadService; this._salaryMasterBulkUploadService = salaryMasterBulkUploadService; this._employeePhotoBulkUploadService = employeePhotoBulkUploadService; this._cashManager = cashManager; + this._bonusProcessService = bonusProcessService; } // loan @@ -156,6 +159,53 @@ namespace HRM.UI.Controllers.Payroll return Ok(items); } + /// + /// Bonus Process screen, "Upload Data": reads the bonus file (sheet EmpBonus: Employee No, Amount — the + /// same reader as uploadBonusFile) and saves it in the same request, with the tax when the header asks + /// for it (BonusProcessService.UploadAndSave). Form fields: excelfile, and header = the JSON of a + /// BonusProcessAndSaveRequest (bonus, dates, flags). Returns the saved rows. + /// + [HttpPost] + [Route("uploadBonusFileAndSave")] + public ActionResult uploadBonusFileAndSave() + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + BonusProcessAndSaveResult result = null; + try + { + int payrolltypeid = (int)currentUser.PayrollTypeID; + string headerJson = Convert.ToString(Request.Form["header"]); + if (string.IsNullOrWhiteSpace(headerJson)) + return StatusCode(StatusCodes.Status500InternalServerError, "Bonus information not found."); + // same JSON reading as the Process button's request (Newtonsoft defaults), so dates arrive the same way + BonusProcessAndSaveRequest request = JsonConvert.DeserializeObject(headerJson); + + IFormFile formFile = Request.Form.Files.FirstOrDefault(); + if (formFile == null || formFile.Length == 0) + return StatusCode(StatusCodes.Status500InternalServerError, "Please select a file."); + string extension = Path.GetExtension(formFile.FileName ?? string.Empty).ToLowerInvariant(); + if (extension != ".xlsx" && extension != ".xls") + return StatusCode(StatusCodes.Status500InternalServerError, "Please select an Excel file (.xlsx or .xls)."); + + DataUploadColumnDefinition oColumnDefination = this._columnDefination.GetColumnDefinition( + (int)EnumRegularDataUpload.Bonus, null, payrolltypeid); + List items; + using (Stream stream = formFile.OpenReadStream()) + { + items = new RegularDataUploadService().GetBonusData((int)EnumRegularDataUpload.Bonus, oColumnDefination, + stream, payrolltypeid); + } + + result = _bonusProcessService.UploadAndSave(items, request, payrolltypeid, currentUser.UserID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(result); + } + /// /// The Employee Bulk Upload layout — groups, sub-groups and columns — that the page shows /// as section checkboxes and in its template guide. diff --git a/HRM.UI/Controllers/Payroll/BonusController.cs b/HRM.UI/Controllers/Payroll/BonusController.cs index 78c71dd..ad89036 100644 --- a/HRM.UI/Controllers/Payroll/BonusController.cs +++ b/HRM.UI/Controllers/Payroll/BonusController.cs @@ -239,6 +239,105 @@ namespace HRM.UI.Controllers.Payroll return Ok(true); } + /// + /// Bonus Process screen, "Process" button: calculates the bonus (and tax) of the posted employees and + /// saves it in the same request — there is no separate Save step. Body: the header and the employee + /// IDs only. Returns the saved rows read back from the database. See BonusProcessService.ProcessAndSave. + /// + [HttpPost] + [Route("processAndSave")] + public ActionResult ProcessAndSave([FromBody] BonusProcessAndSaveRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + BonusProcessAndSaveResult result = null; + try + { + result = _bonusProcessService.ProcessAndSave(request, (int)currentUser.PayrollTypeID, currentUser.UserID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(result); + } + + /// Modify dialog, "Calculate": the tax of one saved row for a bonus amount. Nothing is saved. + [HttpPost] + [Route("calculateRowTax")] + public ActionResult CalculateRowTax([FromBody] BonusProcessRowTaxRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + BonusProcessRowTaxResult result = null; + try + { + result = _bonusProcessService.CalculateRowTax(request, (int)currentUser.PayrollTypeID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(result); + } + + /// Modify dialog, "Save": saves one row (amounts + that employee's bonus tax data); returns the saved row. + [HttpPost] + [Route("saveRow")] + public ActionResult SaveRow([FromBody] BonusProcessRowSaveRequest request) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + BonusProcessGridRow row = null; + try + { + row = _bonusProcessService.SaveRow(request, (int)currentUser.PayrollTypeID, currentUser.UserID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(row); + } + + /// "Clear Tax": the tax of every row of the process becomes 0 and is saved at once; returns the saved rows. + [HttpPost] + [Route("clearTaxAndSave/{bonusProcessID}")] + public ActionResult ClearTaxAndSave(int bonusProcessID) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + List rows = null; + try + { + rows = _bonusProcessService.ClearTaxAndSave(bonusProcessID, (int)currentUser.PayrollTypeID, currentUser.UserID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(rows); + } + + /// Remove button on a saved row: deletes that employee's saved bonus data (and the header when it was the last). + [HttpPost] + [Route("removeRow/{bonusProcessDetailID}")] + public ActionResult RemoveRow(int bonusProcessDetailID) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + BonusProcessRowRemoveResult result = null; + try + { + result = _bonusProcessService.RemoveRow(bonusProcessDetailID, (int)currentUser.PayrollTypeID); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(result); + } + [HttpPost] [Route("CalculateBonusTax")] public ActionResult CalculateBonusTax(List items)