HRM-10/HRM.UI/Controllers/Payroll/SalaryController.cs
Mohaimen Hasan 838b8d4480 first commit
2026-11-03 13:06:00 +06:00

1980 lines
75 KiB
C#

using Aspose.Words;
using HRM.BO;
using HRM.BO.Configuration;
using HRM.DA;
using HRM.Report;
using HRM.UI.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Mail;
using System.Security.Claims;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;
namespace HRM.UI.Controllers.Payroll
{
[Route("api/salary")]
[ApiController]
[Authorize]
public class SalaryController : ControllerBase
{
private readonly ISalaryMonthlyService _salaryMonthlyService;
private readonly ISalaryProcessService _salaryProcessService;
private readonly IEmployeeService _employeeService;
private readonly IEmployeeGradeSalaryService _empGradeSalaries;
private readonly IOptions<EmailSettings> _emailSettings;
private readonly IPayrollComponentListService _payrollComponentListService;
private readonly IConfiguration _config;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IEmailDispatchService _emailDispatchService;
private readonly IHistorySalaryMonthlyService _historySalaryMonthlyService;
private readonly string Secret;
public SalaryController(ISalaryMonthlyService salaryMonthlyService,
ISalaryProcessService salaryProcessService, IPayrollComponentListService payrollComponentListService,
IEmployeeService empService, IEmployeeGradeSalaryService empGradeSalaries, IOptions<EmailSettings> emailSettings,IConfiguration config,
IWebHostEnvironment webHostEnvironment, IOptions<AppSettings> appSettings,
IEmailDispatchService emailDispatchService, IHistorySalaryMonthlyService historySalaryMonthlyService)
{
_config = config;
this._emailDispatchService = emailDispatchService;
this._historySalaryMonthlyService = historySalaryMonthlyService;
this._salaryMonthlyService = salaryMonthlyService;
this._salaryProcessService = salaryProcessService;
this._employeeService = empService;
this._empGradeSalaries = empGradeSalaries;
this._emailSettings = emailSettings;
this._payrollComponentListService = payrollComponentListService;
this._webHostEnvironment = webHostEnvironment;
this.Secret = appSettings.Value.Secret;
}
// Salary Monthly
[HttpGet("getSalaryMonthlyById/{id}")]
public ActionResult GetSalaryMonthlyById(int id)
{
SalaryMonthly salaryMonthly = new SalaryMonthly();
try
{
salaryMonthly = _salaryMonthlyService.Get(id);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthly);
}
/// <summary>
/// Salary Master Data View: what Salary Master Data Bulk Upload saved for one salary month
/// (any day of it) — every employee of the login's payroll type, by Employee ID.
/// </summary>
[HttpGet("getSalaryMasterData/{salaryMonth}")]
public ActionResult GetSalaryMasterData(DateTime salaryMonth)
{
List<HistorySalaryMonthly> items = new List<HistorySalaryMonthly>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = _historySalaryMonthlyService.Get(salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet("ConstantItemsForSalary")]
public ActionResult ConstantItemsForSalary()
{
List<PayrollComponentList> componenentList = new List<PayrollComponentList>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
componenentList = _payrollComponentListService.ConstantItemsForSalary(payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(componenentList);
}
[HttpGet("getLastPaidSalaryMonth/{empId}")]
public ActionResult GetLastPaidSalaryMonth(int empId)
{
DateTime dt = new DateTime();
try
{
dt = _salaryMonthlyService.GetLastPaidSalaryMonth(empId).GetValueOrDefault();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(dt);
}
[HttpPost]
[Route("updateSalaryMonthly")]
public ActionResult UpdateSalaryMonthly(SalaryMonthly salaryMonthly)
{
try
{
_salaryMonthlyService.Update(salaryMonthly);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("UpdateDetail")]
public ActionResult UpdateDetail(List<SalaryMonthlyDetail> salaryMonthlyDetails)
{
List<IncomeTax> incomeTaxes = new List<IncomeTax>();
try
{
_salaryMonthlyService.UpdateDetail(salaryMonthlyDetails, incomeTaxes);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
//[HttpPost]
//[Route("saveSalaryMonthly")]
//public ActionResult SaveSalaryMonthly(SalaryProcess process)
//{
// List<SalaryMonthly> items = new List<SalaryMonthly>();
// try
// {
// _salaryMonthlyService.Save(process, items);
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok();
//}
[HttpPost]
[Route("deleteSalaryMonthly")]
public ActionResult DeleteSalaryMonthly(int id)
{
try
{
_salaryMonthlyService.Delete(id);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("getSumOnRange/{employeeId}/{fromDate}/{toDate}/{groupCode}/{itemCode}/{itemId}")]
public ActionResult GetSumOnRange(int employeeId, DateTime fromDate, DateTime toDate, EnumSalaryGroup groupCode,
EnumSalaryItemCode itemCode, int itemId)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetSumOnRange(employeeId, fromDate, toDate, groupCode, itemCode, itemId,
payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getSumOnRangeOnRound/{employeeId}/{fromDate}/{toDate}/{groupCode}/{itemCode}/{itemId}")]
public ActionResult GetSumOnRangeOnRound(int employeeId, DateTime fromDate, DateTime toDate,
EnumSalaryGroup groupCode, EnumSalaryItemCode itemCode, int itemId)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetSumOnRangeOnRound(employeeId, fromDate, toDate, groupCode, itemCode,
itemId, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getSalaryMonthlyByEmpId/{empId}/{dateTime}")]
public ActionResult GetSalaryMonthlyByEmpId(int empId, DateTime dateTime)
{
SalaryMonthly salaryMonthly = new SalaryMonthly();
try
{
salaryMonthly = _salaryMonthlyService.Get(empId, dateTime);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthly);
}
[HttpGet("getSalaryMonthlyList/{empId}/{salaryMonth}")]
public ActionResult GetSalaryMonthlyList(DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlyList = new List<SalaryMonthly>();
try
{
salaryMonthlyList = _salaryMonthlyService.Get(salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyList);
}
[HttpGet("getForJV/{salaryMonth}")]
public ActionResult GetForJV(DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlyList = new List<SalaryMonthly>();
try
{
salaryMonthlyList = _salaryMonthlyService.GetForJV(salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyList);
}
[HttpGet("getSalaryMonthlyListByEmpId/{empId}/{salaryMonth}")]
public ActionResult GetSalaryMonthlyListByEmpId(string empId, DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlyList = new List<SalaryMonthly>();
try
{
salaryMonthlyList = _salaryMonthlyService.Get(empId, salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyList);
}
[HttpGet("getForWTP/{empId}/{salaryMonth}")]
public ActionResult GetForWTP(string empId, DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlyList = new List<SalaryMonthly>();
try
{
salaryMonthlyList = _salaryMonthlyService.GetForWTP(empId, salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyList);
}
[HttpGet("getForCC/{salaryMonthId}")]
public ActionResult GetForCC(int salaryMonthId)
{
List<SalaryEmpCostCenter> salaryEmpCostCenters = new List<SalaryEmpCostCenter>();
try
{
salaryEmpCostCenters = _salaryMonthlyService.GetForCC(salaryMonthId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryEmpCostCenters);
}
[HttpGet("getCostCenterList/{salaryMonth}")]
public ActionResult GetCostCenterList(DateTime salaryMonth)
{
List<SalaryEmpCostCenter> salaryEmpCostCenters = new List<SalaryEmpCostCenter>();
try
{
salaryEmpCostCenters = _salaryMonthlyService.GetCostCenter(salaryMonth);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryEmpCostCenters);
}
[HttpGet("getUnAuthorizeAmountOnDateRange/{employeeId}/{fromDate}/{toDate}/{groupCode}")]
public ActionResult GetUnAuthorizeAmountOnDateRange(int employeeId, DateTime fromDate, DateTime toDate,
EnumSalaryGroup groupCode)
{
Double result;
try
{
result = _salaryMonthlyService.GetUnAuthorizeAmountOnDateRange(employeeId, fromDate, toDate, groupCode);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("isSalaryProcessed/{employeeId}/{salaryMonth}")]
public ActionResult IsSalaryProcessed(int employeeId, DateTime salaryMonth)
{
bool ans;
try
{
ans = _salaryMonthlyService.IsSalaryProcessed(employeeId, salaryMonth);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("isSalaryProcessedWeb/{salaryMonth}")]
public ActionResult IsSalaryProcessedWeb(DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
bool ans;
try
{
ans = _salaryMonthlyService.IsSalaryProcessedWeb(salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("isPermanentEmp/{employeeId}/{salaryMonth}")]
public ActionResult IsPermanentEmp(int employeeId, DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
bool ans;
try
{
ans = _salaryMonthlyService.IsPermanentEmp(employeeId, salaryMonth, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("isSalaryProcessedAndFinalized/{employeeId}/{salaryMonth}/{isProcessed}/{isFinalized}")]
public ActionResult IsSalaryProcessedAndFinalized(int employeeId, DateTime salaryMonth, bool isProcessed,
bool isFinalized)
{
try
{
_salaryMonthlyService.IsSalaryProcessedAndFinalized(employeeId, salaryMonth, ref isProcessed,
ref isFinalized);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("getUnAuthorizeDays/{employeeId}/{salaryMonth}")]
public ActionResult GetUnAuthorizeDays(int employeeId, DateTime salaryMonth)
{
int ans;
try
{
ans = _salaryMonthlyService.GetUnAuthorizeDays(employeeId, salaryMonth);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("getSalaryDetailList/{salaryMonthlyId}")]
public ActionResult GetSalaryDetailList(int salaryMonthlyId)
{
List<SalaryMonthlyDetail> salaryMonthlyDetails = new List<SalaryMonthlyDetail>();
try
{
salaryMonthlyDetails = _salaryMonthlyService.GetSalaryDetail(salaryMonthlyId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyDetails);
}
[HttpGet("getSalaryDetailListBySalaryMonthlyIds/{salaryMonthlyIds}")]
public ActionResult GetSalaryDetailListBySalaryMonthlyIds(string salaryMonthlyIds)
{
List<SalaryMonthlyDetail> salaryMonthlyDetails = new List<SalaryMonthlyDetail>();
try
{
salaryMonthlyDetails = _salaryMonthlyService.GetSalaryDetail(salaryMonthlyIds);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyDetails);
}
[HttpGet("getTotalEmp/{salaryProcessId}")]
public ActionResult GetTotalEmp(int salaryProcessId)
{
int ans;
try
{
ans = _salaryMonthlyService.GetTotalEmp(salaryProcessId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("getAmountOnDateDiff/{employeeId}/{fromDate}/{toDate}/{groupCode}/{itemCode}/{itemId}")]
public ActionResult GetAmountOnDateDiff(int employeeId, DateTime fromDate, DateTime toDate,
EnumSalaryGroup groupCode, EnumSalaryItemCode itemCode, int itemId)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetAmountOnDateDiff(employeeId, fromDate, toDate, groupCode, itemCode,
itemId, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getThisMonthBasicOnDateDiff/{employeeId}/{fromDate}/{toDate}/{groupCode}/{itemCode}/{itemId}")]
public ActionResult GetThisMonthBasicOnDateDiff(int employeeId, DateTime fromDate, DateTime toDate,
EnumSalaryGroup groupCode, EnumSalaryItemCode itemCode, int itemId)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetThisMonthBasicOnDateDiff(employeeId, fromDate, toDate, groupCode,
itemCode, itemId, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getAmountOnDateDiffForOverTime/{employeeId}/{fromDate}/{toDate}/{groupCode}/{itemCode}/{itemId}")]
public ActionResult GetAmountOnDateDiffForOverTime(int employeeId, DateTime fromDate, DateTime toDate,
EnumSalaryGroup groupCode, EnumSalaryItemCode itemCode, int itemId)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetAmountOnDateDiffForOverTime(employeeId, fromDate, toDate, groupCode,
itemCode, itemId, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getAmountOnDateDiffForAll/{employeeId}/{fromDate}/{toDate}")]
public ActionResult GetAmountOnDateDiffForAll(int employeeId, DateTime fromDate, DateTime toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
Double result;
try
{
result = _salaryMonthlyService.GetAmountOnDateDiffForAll(employeeId, fromDate, toDate, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getPrvTaxAmount/{dataForm}/{employeeId}/{fromDate}/{toDate}")]
public ActionResult GetPrvTaxAmount(EnumIncomeTaxDataFrom dataFrom, int employeeId, DateTime fromDate,
DateTime toDate)
{
Double result;
try
{
result = _salaryMonthlyService.GetPrvTaxAmount(dataFrom, employeeId, fromDate, toDate);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(result);
}
[HttpGet("getByDateRange/{startDate}/{endDate}")]
public ActionResult GetByDateRange(DateTime startDate, DateTime endDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlies = new List<SalaryMonthly>();
try
{
salaryMonthlies = _salaryMonthlyService.GetByDateRange(startDate, endDate, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlies);
}
[HttpGet("getByDateRangeByEmpId/{empId}/{startDate}/{endDate}")]
public ActionResult GetByDateRangeByEmpId(int empId, DateTime startDate, DateTime endDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlies = new List<SalaryMonthly>();
try
{
salaryMonthlies = _salaryMonthlyService.GetByDateRange(empId, startDate, endDate, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlies);
}
[HttpGet("getHead/{index}/{salaryMonth}")]
public ActionResult GetHead(int index, DateTime salaryMonth)
{
List<SalaryMonthlyDetail> salaryMonthlyDetails = new List<SalaryMonthlyDetail>();
try
{
salaryMonthlyDetails = _salaryMonthlyService.GetHead(index, salaryMonth);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlyDetails);
}
[HttpGet("getSalaryMonthlyByDateRange/{empId}/{fromDate}/{toDate}")]
public ActionResult GetSalaryMonthlyByDateRange(string empId, DateTime fromDate, DateTime toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryMonthly> salaryMonthlies = new List<SalaryMonthly>();
try
{
salaryMonthlies = _salaryMonthlyService.Get(empId, fromDate, toDate, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlies);
}
[HttpGet("getByProcessID/{processId}")]
public ActionResult GetByProcessID(int processId)
{
List<SalaryMonthly> salaryMonthlies = new List<SalaryMonthly>();
try
{
salaryMonthlies = _salaryMonthlyService.GetByProcessID(processId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryMonthlies);
}
[HttpGet("isSalaryProcessedAndFinalizedByDateRange/{dateTime}/{isProcessed}/{isFinalized}")]
public ActionResult IsSalaryProcessedAndFinalizedByDateRange(DateTime dateTime, bool isProcessed,
bool isFinalized)
{
try
{
_salaryMonthlyService.IsSalaryProcessedAndFinalized(dateTime, ref isProcessed, ref isFinalized);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("GetUnApprovedSalaries")]
public ActionResult GetUnApprovedSalaries()
{
List<SalaryProcess> salaryProcess = new List<SalaryProcess>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
salaryProcess = _salaryProcessService.GetUnApprovedSalaries((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryProcess);
}
[HttpPost("Updatepayment")]
public ActionResult Updatepayment(dynamic data)//Hello World Chapal Bhai
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
DateTime paymentDate = DateTime.Today;
if (items["paymentDate"] != null)
paymentDate = (DateTime)items["paymentDate"].ToObject<DateTime>();
int salarymonthlyid = items["salarymonthlyid"].ToObject<int>();
string chequeNo = items["chequeno"].ToObject<string>();
string remarks = items["remarks"].ToObject<string>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
//DataTable olist = null;
try
{
_salaryMonthlyService.Updatepayment(paymentDate, salarymonthlyid, chequeNo, remarks, currentUser.UserID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost("GetWithheldData")]
public ActionResult GetWithheldData(dynamic data)
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
DateTime salarymonth = DateTime.Today;
if (items["salaryMonth"] != null)
salarymonth = (DateTime)items["salaryMonth"].ToObject<DateTime>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DataTable olist = null;
try
{
olist = _salaryMonthlyService.GetWithheldData(GlobalFunctions.LastDateOfMonth(salarymonth), (int)currentUser.PayrollTypeID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(olist);
}
// SalaryProcess
//[HttpGet("getSalaryProcessById/{id}")]
//public ActionResult GetSalaryProcessById(int id)
//{
// SalaryProcess salaryProcess = new SalaryProcess();
// try
// {
// salaryProcess = _salaryProcessService.Get(id);
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok(salaryProcess);
//}
//[HttpGet("getSalaryProcessWithPayrollType")]
//public ActionResult GetSalaryProcessWithPayrollType()
//{
// CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
// int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
// List<SalaryProcess> salaryProcesses = new List<SalaryProcess>();
// try
// {
// salaryProcesses = _salaryProcessService.GetWithPayrollType(payrollTypeId);
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok(salaryProcesses);
//}
//[HttpGet("getAllSalaryProcess")]
//public ActionResult GetAllSalaryProcess()
//{
// List<SalaryProcess> salaryProcesses = new List<SalaryProcess>();
// try
// {
// salaryProcesses = _salaryProcessService.GetSP();
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok(salaryProcesses);
//}
[HttpGet("getSalaryProcessBySMonth/{month}")]
public ActionResult GetSalaryProcessBySMonth(DateTime month)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
bool ans;
try
{
ans = _salaryProcessService.GetBySMonth(month, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ans);
}
[HttpGet("getSalaryProcessSummary")]
public ActionResult GetSalaryProcessSummary()
{
// Payroll type, tax parameter and salary month all come off the token, never the client -
// the same salary month SalaryProcess itself processes.
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
int taxParamId = currentUser.TaxParamID.GetValueOrDefault();
DateTime salaryMonth = GlobalFunctions.LastDateOfMonth(
currentUser.NextPayProcessDate.GetValueOrDefault());
DataSet summary = new DataSet();
try
{
summary = _salaryProcessService.GetProcessSummary(salaryMonth, payrollTypeId, taxParamId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(summary.Tables[0]);
}
[HttpPost]
[Route("saveSalaryProcess")]
public ActionResult SaveSalaryProcess(SalaryProcess process)
{
try
{
_salaryProcessService.Save(process);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("ApproveSalary")]
public ActionResult ApproveSalary(dynamic processItems)
{
// string remarks = (string)processItems["remarks"].ToObject<string>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
_salaryProcessService.ApproveSalary((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
[HttpGet]
[Route("ApproveSalaryNew/{remarks}")]
public ActionResult ApproveSalaryNew(string remarks)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
//if (currentUser.EmployeeID == null && currentUser.UserName == "Mohammad Abdul Quader")
// currentUser.EmployeeID = 1;
SalaryProcess oSalaryProcess = new SalaryProcess();
try
{
oSalaryProcess = _salaryProcessService.GetSalaryProcess((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
if (oSalaryProcess != null)
{
if (remarks == "Remarks")
remarks = string.Empty;
oSalaryProcess.Remarks = remarks;
_salaryProcessService.ApproveSalaryNew(oSalaryProcess, (int)currentUser.EmployeeID);
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
[HttpGet]
[Route("GetCurrentSalaryProcessStatus")]
public ActionResult GetCurrentSalaryProcessStatus()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
SalaryProcess oSalaryProcess = new SalaryProcess();
int? status = null;
try
{
oSalaryProcess = _salaryProcessService.GetSalaryProcess((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
if (oSalaryProcess != null)
{
status = oSalaryProcess.WFStatus == null ? null : (int)oSalaryProcess.WFStatus;
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(status);
}
[HttpGet]
[Route("SalaryInBankTransfer/{isBankTransfer}")]
public ActionResult SalaryInBankTransfer(bool isBankTransfer)
{
EmailSettings emailSettings = _emailSettings.Value;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
SalaryProcess oSalaryProcess = new SalaryProcess();
int? status = null;
try
{
oSalaryProcess = _salaryProcessService.GetSalaryProcess((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
if (oSalaryProcess != null && isBankTransfer == true)
{
oSalaryProcess.IsBankTransfer = isBankTransfer;
_salaryProcessService.SalryBankTransfer(oSalaryProcess);
if (!string.IsNullOrEmpty(oSalaryProcess.NotifyEmail))
{
string[] allEmails = oSalaryProcess.NotifyEmail.Split(',');
if (allEmails.Length > 0)
{
for (int email = 0; email < allEmails.Length; email++)
{
allEmails[email] = allEmails[email].Trim();
}
foreach (string email in allEmails)
{
if (email != "")
{
MailSender mailSender = new MailSender();
mailSender.AddTo(email);
mailSender.Subject = $"Bank Advice has been submitted to Bank Portal Salary Month {oSalaryProcess.SalaryMonth.ToString("MMMM yyyy")}";
mailSender.Body = @"Dear Sir,
<p>Bank Advice has been submitted to Bank Portal Salary Month <b>" + oSalaryProcess.SalaryMonth.ToString("MMMM yyyy") + "</b></p>";
mailSender.ThreadSendMail(emailSettings);
}
}
}
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(status);
}
[HttpPost]
[Route("deleteSalaryProcessById")]
public ActionResult DeleteSalaryProcessById(int id)
{
try
{
_salaryProcessService.Delete(id);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet]
[Route("deleteSalarySalaryApprovalAttachment/{ID}")]
public ActionResult DeleteSalaryApprovalAttachment(int ID)
{
try
{
_salaryProcessService.DeleteSalaryApprovalAttachment(ID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("SaveSalaryApprovalAttachment")]
public ActionResult SaveSalaryApprovalAttachment(dynamic data)
{
string connectionString = _config.GetSection("dbSettings").GetSection("SqlCommandConnection").Value;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
List<SalaryApprovalAttachment> allSalaryApprovalAttachment = (List<SalaryApprovalAttachment>)items["salaryApprovalAttachment"].ToObject<List<SalaryApprovalAttachment>>();
try
{
if (allSalaryApprovalAttachment != null && allSalaryApprovalAttachment.Count > 0)
{
foreach (SalaryApprovalAttachment attachment in allSalaryApprovalAttachment)
{
attachment.ConnectionString = connectionString;
if (attachment.FileName.ToLower().EndsWith(".doc"))
{
ConvertDocToDocX(attachment);
}
}
new SalaryProcessService().SalaryApprovalAttachment(allSalaryApprovalAttachment);
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet]
[Route("GetSalaryApprovalAttachment")]
public ActionResult GetSalaryApprovalAttachment()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
List<SalaryApprovalAttachment> allAttachment = new List<SalaryApprovalAttachment>();
try
{
allAttachment = new SalaryProcessService().GetSalaryApprovalAttachment((DateTime)currentUser.NextPayProcessDate,(int)currentUser.PayrollTypeID, EnumFileType.Salary);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(allAttachment);
}
[HttpGet]
[Route("GetSalaryApprovalAttachmentForAll/{month}")]
public ActionResult GetSalaryApprovalAttachmentForAll(string month)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
List<SalaryApprovalAttachment> allAttachment = new List<SalaryApprovalAttachment>();
DateTime salaryMonth = Convert.ToDateTime(month);
try
{
allAttachment = new SalaryProcessService().GetSalaryApprovalAttachment(salaryMonth, (int)currentUser.PayrollTypeID, EnumFileType.Salary);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(allAttachment);
}
[HttpGet]
[Route("GetBonusApprovalAttachment/{bMonth}/{bonusID}")]
public ActionResult GetBonusApprovalAttachment(string bMonth, int bonusID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
List<SalaryApprovalAttachment> allAttachment = new List<SalaryApprovalAttachment>();
DateTime bonusMonth = Convert.ToDateTime(bMonth);
try
{
allAttachment = new SalaryProcessService().GetSalaryApprovalAttachment(bonusMonth, (int)currentUser.PayrollTypeID, EnumFileType.Bonus, bonusID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(allAttachment);
}
private SalaryApprovalAttachment ConvertDocToDocX(SalaryApprovalAttachment externalItem)
{
string[] items = externalItem.FileData.Split(new char[] { ',', ' ' }, StringSplitOptions.None);
byte[] newBytes = Convert.FromBase64String(items[1]);
externalItem.FileAsByteArray = newBytes;
if (externalItem.FileAsByteArray is byte[] docData)
{
using (MemoryStream docStream = new MemoryStream(docData))
{
Document doc = new Document(docStream);
using (MemoryStream docxStream = new MemoryStream())
{
doc.Save(docxStream, SaveFormat.Docx);
externalItem.FileName = Path.ChangeExtension(externalItem.FileName, "docx");
externalItem.FileAsByteArray = docxStream.ToArray();
externalItem.PrevFileName = externalItem.FileName;
}
}
}
return externalItem;
}
[HttpPost]
[Route("SalaryProcess")]
public ActionResult SalaryProcess(dynamic processItems)
{
SalaryProcess oporcess = new SalaryProcess();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(processItems));
int index = 0;
//List<Employee> employees = this._employeeService.GetByEmpIDs
List<SearchEmployee> searhemp = new List<SearchEmployee>();
string empid = "";
foreach (var item in items)
{
if (index == 0)
{
oporcess.PayrollTypeID = (int)currentUser.PayrollTypeID;
oporcess.CreatedBy = currentUser.UserID;
oporcess.CreatedDate = DateTime.Today;
oporcess.SalaryMonth =GlobalFunctions.LastDateOfMonth((DateTime)currentUser.NextPayProcessDate);
if (item["euroRate"] != null)
{
oporcess.EuroRate = (double)item["euroRate"].ToObject<double>();
}
if (item["remarks"] != null)
oporcess.Remarks = (string)item["remarks"].ToObject<string>();
oporcess.PaymentDate = (DateTime)item["paymentDate"].ToObject<DateTime>();
oporcess.ProcessCode = oporcess.SalaryMonth.ToString("ddmmyy") + DateTime.Today.ToString("hh:mm");
oporcess.ProcessDate = DateTime.Today;
}
empid = empid + (string)item["empid"].ToObject<string>() + ",";
}
if (empid.Length > 0)
{
empid = empid.Substring(0, empid.Length - 1);
}
List<SalaryProcessStatus> errorOrSucess = new List<SalaryProcessStatus>();
try
{
List<Employee> employees = this._employeeService.GetByEmpIDs(empid, (int)currentUser.PayrollTypeID);
errorOrSucess = _salaryProcessService.SalaryProcess(oporcess, employees);
if (errorOrSucess.Count == 0) errorOrSucess = null;
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(errorOrSucess);
}
[HttpPost]
[Route("undoSalaryProcessById")]
public ActionResult UndoSalaryProcessById(SalaryProcess item)
{
bool isNowInInitiator = false;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if (item.WFStatus == null)
{
_salaryProcessService.UndoSalary(item.ID);
}
else
{
isNowInInitiator = new WFMovementTranService().IsNowInInitiator((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID, 0);
if (isNowInInitiator)
{
_salaryProcessService.UndoSalaryForInitiator(item.ID);
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("undoMonthlySalaryProcessByEmpId")]
public ActionResult UndoMonthlySalaryProcessByEmpId(List<SearchEmployee> emps)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
_salaryProcessService.UndoMonthlySalaryByEmpIDs(SearchEmployee.getEmpID(emps), (DateTime)currentUser.NextPayProcessDate);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("updateSalaryProcess")]
public ActionResult UpdateSalaryProcess(SalaryProcess process)
{
try
{
_salaryProcessService.Update(process);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("distinct-details/{startDate}/{endDate}")]
public ActionResult GetDistinctSalaryMonthlyDetails(DateTime startDate,
DateTime endDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DataTable dt = null;
try {
dt = _salaryMonthlyService.GetDistinctSalaryMonthlyDetails(startDate, endDate,
(int)currentUser.PayrollTypeID, (int) currentUser.TaxParamID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(dt); // You may want to convert DataTable to a list of objects for JSON serialization
}
[HttpPost]
[Route("salaryProcessApprove")]
public ActionResult SalaryProcessApprove(SalaryProcess process)
{
try
{
_salaryProcessService.SPApprove(process);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost("salaryValidation")]
public ActionResult salaryValidation(List<SearchEmployee> emps)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryProcess> salaryProcesses = new List<SalaryProcess>();
List<SalaryProcessStatus> errorList = new List<SalaryProcessStatus>();
try
{
DataSet GradeSalary = this._empGradeSalaries.GetmultipleTilldatedemp(payrollTypeId);
if (GradeSalary.Tables[0].Rows.Count > 0)
{
string smsg = string.Empty;
int nCount = 0;
foreach (DataRow oRow in GradeSalary.Tables[0].Rows)
{
nCount = nCount + 1;
var emp = emps.FirstOrDefault(x => x.EmployeeID == Convert.ToInt32(oRow["EmployeeId"]));
if (emp != null)
{
errorList.Add(new SalaryProcessStatus(emp.EmployeeNo, emp.Name,
"Salary Entry Error, please see the Life-cycle-salary information"));
}
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
if (errorList.Count == 0) errorList = null;
return Ok(errorList);
}
[HttpGet("getSalaryProcessByMonthAndPayrollTypeId/{month}")]
public ActionResult GetSalaryProcessByMonthAndPayrollTypeId(DateTime month)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryProcess> salaryProcesses = new List<SalaryProcess>();
try
{
salaryProcesses = _salaryProcessService.Get(month, payrollTypeId);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryProcesses);
}
[HttpPost]
[Route("salaryProcessMonthEnd")]
public ActionResult SalaryProcessMonthEnd(dynamic MonthEnddata)
{
//var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
//int userid = (int)item["userid"].ToObject<int>();
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(MonthEnddata));
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DateTime paymentDate = DateTime.Today; //(DateTime)items[0].ToObject<DateTime>();
try
{
_salaryProcessService.MonthEnd(currentUser.UserID, (DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID, paymentDate);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
string newToken = GenerateTokenAfterMonthEnd(currentUser);
return Ok(newToken);
}
private string GenerateTokenAfterMonthEnd(CurrentUser currentUser)
{
var user = new UserService().Get(currentUser.UserID);
var payrollType = currentUser.PayrollTypeID.HasValue
? new PayrollTypeService().Get(currentUser.PayrollTypeID.Value)
: null;
bool hasDataPermission = false;
if (payrollType != null) {
hasDataPermission = new DataPermissionService().hasDataPermission(user.ID, payrollType.ID);
}
var claims = new[]
{
new Claim("UserID", user.ID.ToString()),
new Claim("LoginID", user.LoginID),
new Claim("UserName", user.UserName),
new Claim("UserType", ((int)user.UserType).ToString()),
new Claim("ChangePasswordAtNextLogon", user.ChangePasswordAtNextLogon.ToString()),
new Claim("EmployeeID", user.EmployeeID?.ToString() ?? "0"),
new Claim("PayrollTypeID", currentUser.PayrollTypeID?.ToString() ?? "0"),
new Claim("taxParamId", payrollType?.TaxParamID.ToString() ?? "0"),
new Claim("hasDataPermission", hasDataPermission.ToString()),
new Claim("nextPayProcessDate", payrollType == null ? "null" : payrollType.NextPayProcessDate.ToString()),
};
var key = Ease.Core.Utility.JwtSigningKey.FromSecret(this.Secret);
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
string tokenString = tokenHandler.WriteToken(token);
HttpContext.Session.SetString("JWToken", tokenString);
return tokenString;
}
[HttpGet("getAllSalaryProcessByNextPayProcessDate/{nextPayProcessDate}")]
public ActionResult GetAllSalaryProcessByNextPayProcessDate(DateTime nextPayProcessDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
List<SalaryProcess> salaryProcesses = new List<SalaryProcess>();
try
{
salaryProcesses = _salaryProcessService.GetAllProcess(payrollTypeId, nextPayProcessDate);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(salaryProcesses);
}
[HttpGet("GetNetAmountofCurrentMonth")]
public ActionResult GetNetAmountofCurrentMonth()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DataTable ot = new DataTable();
SalaryProcess oSalaryProcess = new SalaryProcess();
try
{
oSalaryProcess = _salaryProcessService.GetSalaryProcess((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
ot = this._salaryMonthlyService.GetNetAmount((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
if (oSalaryProcess != null)
{
ot.Columns.Add("IsBankTransfer", typeof(bool));
foreach (DataRow row in ot.Rows)
{
row["IsBankTransfer"] = oSalaryProcess.IsBankTransfer;
}
}
foreach (DataRow row in ot.Rows)
{
if (row["CurrentMonth"] != DBNull.Value)
{
ot.Columns.Add("CurrentMonthTaka", typeof(string));
double value = Convert.ToDouble(row["CurrentMonth"]);
row["CurrentMonthTaka"] = GlobalFunctions.TakaFormat(value);
}
if (row["PrviousMonth"] != DBNull.Value)
{
ot.Columns.Add("PrviousMonthTaka", typeof(string));
double value = Convert.ToDouble(row["PrviousMonth"]);
row["PrviousMonthTaka"] = GlobalFunctions.TakaFormat(value);
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ot);
}
[HttpGet("GetNetAmountofCurrentMonthFromApprover/{wfmovementTranID}")]
public ActionResult GetNetAmountofCurrentMonthFromApprover(int wfmovementTranID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
WFMovementTran oWFMovementTran = new WFMovementTran();
SalaryProcess oSalaryProcess = new SalaryProcess();
DataTable ot = new DataTable();
try
{
oWFMovementTran = new WFMovementTranService().Get(wfmovementTranID);
if (oWFMovementTran != null)
{
oSalaryProcess = new SalaryProcessService().GetSalaryProcess(oWFMovementTran.ObjectID);
ot = this._salaryMonthlyService.GetNetAmount(oSalaryProcess.SalaryMonth, oSalaryProcess.PayrollTypeID);
ot.Columns.Add("SalaryProcessID", typeof(int));
foreach (DataRow row in ot.Rows)
{
row["SalaryProcessID"] = oSalaryProcess.ID;
if (row["CurrentMonth"] != DBNull.Value)
{
ot.Columns.Add("CurrentMonthTaka", typeof(string));
double value = Convert.ToDouble(row["CurrentMonth"]);
row["CurrentMonthTaka"] = GlobalFunctions.TakaFormat(value);
}
if (row["PrviousMonth"] != DBNull.Value)
{
ot.Columns.Add("PrviousMonthTaka", typeof(string));
double value = Convert.ToDouble(row["PrviousMonth"]);
row["PrviousMonthTaka"] = GlobalFunctions.TakaFormat(value);
}
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ot);
}
[HttpGet("ApproveSalaryFromApprover/{wfmovementTranID}/{remarks}")]
public ActionResult ApproveSalaryFromApprover(int wfmovementTranID, string remarks)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
WFMovementTran oWFMovementTran = new WFMovementTran();
SalaryProcess oSalaryProcess = new SalaryProcess();
enumwfStatus status;
EmailSettings emailSettings = _emailSettings.Value;
try
{
oWFMovementTran = new WFMovementTranService().Get(wfmovementTranID);
if (oWFMovementTran != null)
{
oWFMovementTran.FromEmployeeID = (int)currentUser.EmployeeID;
oWFMovementTran.Remarks = remarks == "Salary Process Approval" ? "" : remarks;
status = _salaryProcessService.ApproveSalaryNew(oWFMovementTran);
if (status != null && status == enumwfStatus.Approve)
{
DataTable initiatorEmployee = new WFMovementTranService().GetInitiatorEmployee(oWFMovementTran.UniqueNumber);
var row = initiatorEmployee?.Rows.Count > 0 ? initiatorEmployee.Rows[0] : null;
string empNo = row?.Field<string>("EMPLOYEENO");
string name = row?.Field<string>("NAME");
string email = row?.Field<string>("EMAILADDRESS");
oSalaryProcess = new SalaryProcessService().GetSalaryProcess(oWFMovementTran.ObjectID);
if (oSalaryProcess != null &&!string.IsNullOrEmpty(empNo) && !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email))
{
MailSender mailSender = new MailSender();
mailSender.AddTo(email);
mailSender.Subject = $"Salary process approved for the month {oSalaryProcess.SalaryMonth.ToString("MMMM yyyy")}";
mailSender.Body = $@"<p>Dear {name},</p>
<p>Salary has been approved for the month <b>{oSalaryProcess.SalaryMonth:MMMM yyyy}</b>.</p>
<p>Please proceed with the next step.</p>";
mailSender.ThreadSendMail(emailSettings);
}
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("RevertSalaryFromApprover/{wfmovementTranID}/{remarks}")]
public ActionResult RevertSalaryFromApprover(int wfmovementTranID, string remarks)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
WFMovementTran oWFMovementTran = new WFMovementTran();
SalaryProcess oSalaryProcess = new SalaryProcess();
try
{
oWFMovementTran = new WFMovementTranService().Get(wfmovementTranID);
if (oWFMovementTran != null)
{
oWFMovementTran.FromEmployeeID = (int)currentUser.EmployeeID;
_salaryProcessService.SalaryProcessRevertRevert(oWFMovementTran, remarks);
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("getBasicSalaryOfEmployee/{id}")]
public ActionResult getBasicSalaryOfEmployee(int id)
{
string currentBasic;
try
{
currentBasic = new EmployeeService().GetBasicSalary(id);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(currentBasic);
}
[HttpPost]
[Route("sendEmailForMultiple")]
public ActionResult SendEmailForMultiple(dynamic data)
{
EmailSettings emailSettings = _emailSettings.Value;
var employees = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data.list));
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
string subject = (string)item["emailSubject"].ToObject<string>();
string body = (string)item["emailBody"].ToObject<string>();
try
{
foreach (var employee in employees)
{
MailSender mailSender = new MailSender();
mailSender.AddTo(employee.employeeEmail.ToString());
mailSender.Subject = subject;
mailSender.Body = "<p>" + body + "</p>";
mailSender.SendMail(emailSettings);
System.Threading.Thread.Sleep(500);
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
/// <summary>
/// Mails the payslip of one salary month to many employees.
///
/// The work is handed to the central dispatcher, so every recipient -
/// including the ones with no email address on file - gets a row in
/// MasterEmailLogDetails with its own outcome. A bad address, a month
/// with no processed salary for one employee, or an SMTP refusal is
/// recorded against that employee alone; the rest of the batch still
/// goes out.
///
/// Returns as soon as the batch is written. The caller polls
/// api/emailLog/getLog/{id} to follow it and can replay the failures
/// later from api/emailLog/retryFailed/{id}.
/// </summary>
[HttpPost]
[Route("sendPayslipForMultiple")]
public ActionResult sendPayslipForMultiple(dynamic data)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
// This controller carries no [Authorize], so an anonymous caller
// reaches here with no claims at all. Say so plainly instead of
// failing later on a null reference.
if (currentUser == null || currentUser.PayrollTypeID == null)
{
return Unauthorized(new { message = "A signed-in payroll user is required to send payslips." });
}
try
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
var employees = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data.list));
DateTime salaryMonth = ((DateTime)item["salaryMonth"].ToObject<DateTime>()).Date;
string subject = (string)item["emailSubject"].ToObject<string>();
string body = (string)item["emailBody"].ToObject<string>();
int payrollTypeID = (int)currentUser.PayrollTypeID;
List<EmailRecipient> recipients = new List<EmailRecipient>();
foreach (var employee in employees)
{
EmailRecipient recipient = new EmailRecipient();
recipient.EmployeeID = Convert.ToInt32(employee.employeeID);
recipient.EmployeeNo = Convert.ToString(employee.employeeNo);
recipient.EmployeeName = Convert.ToString(employee.name);
recipient.MailTo = employee.employeeEmail == null ? string.Empty : Convert.ToString(employee.employeeEmail);
recipient.Subject = subject;
recipient.Body = BuildPayslipBody(recipient.EmployeeName, body, salaryMonth);
recipient.SalaryMonth = salaryMonth;
recipients.Add(recipient);
}
if (recipients.Count == 0)
{
return BadRequest(new { message = "No employee was selected." });
}
EmailDispatchRequest request = new EmailDispatchRequest();
request.EmailType = EnumEmailType.Payslip;
request.Description = "Payslip - " + salaryMonth.ToString("MMMM yyyy");
request.PayrollTypeID = payrollTypeID;
request.ParameterJson = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
salaryMonth = salaryMonth,
payrollTypeId = payrollTypeID
});
request.UserID = currentUser.UserID;
request.Recipients = recipients;
// HRM.DA cannot reference HRM.Report, so the document is built
// here and handed to the dispatcher. Every mail type plugs in
// the same way.
request.AttachmentResolver = (EmailRecipient recipient) =>
{
byte[] bytes = new PaySlip().DownloadPayslip(payrollTypeID, salaryMonth, recipient.EmployeeID.ToString(), false);
if (bytes == null || bytes.Length == 0)
{
throw new Exception("No processed payslip found for " + salaryMonth.ToString("MMMM yyyy") + ".");
}
string fileName = "PaySlip_" + recipient.EmployeeNo + "_" + salaryMonth.ToString("yyyy_MM") + ".pdf";
return new EmailAttachmentInfo(fileName, bytes);
};
// Written in full before a single mail goes out, so nothing is
// lost even if the run is interrupted.
int masterEmailLogID = _emailDispatchService.CreateBatch(request);
EmailSettings emailSettings = _emailSettings.Value;
IEmailDispatchService dispatchService = _emailDispatchService;
EmailLogBackgroundRunner.Run(() => dispatchService.ProcessBatch(masterEmailLogID, request, emailSettings));
return Ok(new
{
masterEmailLogID = masterEmailLogID,
totalCount = recipients.Count,
message = "Sending started for " + recipients.Count + " employee(s)."
});
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/// <summary>
/// The mail text for one employee. The operator's own message is kept
/// as its own paragraph rather than being folded into a sentence.
/// </summary>
private static string BuildPayslipBody(string employeeName, string operatorBody, DateTime salaryMonth)
{
string message = string.IsNullOrWhiteSpace(operatorBody)
? string.Empty
: "<p>" + operatorBody.Trim() + "</p>";
return $@"<p>Dear {employeeName},</p>
{message}
<p>Please find attached your payslip for {salaryMonth.ToString("MMM yyyy")}.</p>
<p>If you have any questions or notice any discrepancies, feel free to reach out to the HR department.</p>
<p>Best regards,<br/>Payroll Department</p>";
}
[HttpPost]
[Route("DownloadPayslipForMultiple")]
public ActionResult DownloadPayslipForMultiple(dynamic data)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
byte[] bytes = null;
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
var employees = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data.list));
DateTime SalaryMonth2 = DateTime.Today.AddMonths(-1);
DateTime SalaryMonth = ((DateTime)item["salaryMonth"].ToObject<DateTime>()).Date.AddMonths(0);
var folderName = "Payslip_" + DateTime.Today.Year + "_" + SalaryMonth.Month.ToString() + "_" + (int)currentUser.PayrollTypeID;
try
{
bool isForESS = false;
foreach (var employee in employees)
{
//create bytes for pdf
bytes = new PaySlip().DownloadPayslip((int)currentUser.PayrollTypeID, SalaryMonth, employee.employeeID.ToString(), isForESS);
if (bytes == null)
{
//return BadRequest("Invalid salary month");
//return BadRequest(new { message = "Invalid salary month" });
continue;
}
string fileName = "PaySlip_" + employee.employeeNo.ToString() + "_" + DateTime.Today.Year + "_" + SalaryMonth.Month.ToString().PadLeft(2, '0') + ".pdf";
//save pdf in folder
SavePdf(bytes, folderName, fileName);
}
return (ActionResult)DownloadPayslipZip(folderName);
}
catch (Exception ex)
{
// Save log
//SaveLog(ex);
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpPost("upload-pdf")]
public IActionResult SavePdf(byte[] pdfBytes, string folderName, string employeeNo)
{
//var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//var desktopFolderPath = Path.Combine(desktopPath, folderName);
var resourcesPath = Path.Combine(_webHostEnvironment.ContentRootPath, "Resources", folderName);
//Directory.CreateDirectory(desktopFolderPath);
Directory.CreateDirectory(resourcesPath);
var fileName = $"Payslip_{employeeNo}_{DateTime.Today:yyyy_MMM}.pdf";
//var desktopFilePath = Path.Combine(desktopFolderPath, fileName);
var resourcesFilePath = Path.Combine(resourcesPath, fileName);
try
{
// Save to desktop
//System.IO.File.WriteAllBytes(desktopFilePath, pdfBytes);
// Also save to resources folder for zipping
System.IO.File.WriteAllBytes(resourcesFilePath, pdfBytes);
return Ok(new { message = "PDF saved to Desktop and server folder!" });
}
catch (Exception ex)
{
return BadRequest(new { message = "Error saving PDF", error = ex.Message });
}
}
[HttpGet]
public IActionResult DownloadPayslipZip(string folderName)
{
var resourcesPath = Path.Combine(_webHostEnvironment.ContentRootPath, "Resources", folderName);
if (!Directory.Exists(resourcesPath))
{
return BadRequest(new { message = "Folder does not exist." });
}
var files = Directory.GetFiles(resourcesPath, "*.pdf");
if (files.Length == 0)
{
return BadRequest(new { message = "No files available to zip." });
}
try
{
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
var fileName = Path.GetFileName(file);
var zipEntry = archive.CreateEntry(fileName);
using (var entryStream = zipEntry.Open())
using (var fileStream = System.IO.File.OpenRead(file))
{
fileStream.CopyTo(entryStream);
}
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
var zipFileName = folderName + ".zip";
var result = File(memoryStream.ToArray(), "application/zip", zipFileName);
Directory.Delete(resourcesPath, true);
return result;
}
}
catch (Exception ex)
{
return BadRequest(new { message = "Error creating zip file", error = ex.Message });
}
}
[HttpGet]
[Route("IsNowInInitiator/{uniqueID}")]
public ActionResult IsNowInInitiator(int uniqueID)
{
bool isNowInInitiator = false;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
isNowInInitiator = new WFMovementTranService().IsNowInInitiator((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID, uniqueID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(isNowInInitiator);
}
[HttpGet]
[Route("ApproveSalaryForInitiator/{remarks}/{uniqueID}")]
public ActionResult ApproveSalaryForInitiator(string remarks, int uniqueID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.EmployeeID == null && currentUser.UserName == "Mohammad Abdul Quader")
currentUser.EmployeeID = 1;
SalaryProcess oSalaryProcess = new SalaryProcess();
WFMovementTran oWFMovementTran = new WFMovementTran();
DataTable ot = new DataTable();
enumwfStatus status;
EmailSettings emailSettings = _emailSettings.Value;
try
{
oWFMovementTran = new WFMovementTranService().GetLastByUniqueID(uniqueID);
if (oWFMovementTran != null)
{
oWFMovementTran.FromEmployeeID = (int)currentUser.EmployeeID;
oWFMovementTran.Remarks = remarks == "Salary Process Approval" ? "" : remarks;
status = _salaryProcessService.ApproveSalaryNew(oWFMovementTran);
if (status != null && status == enumwfStatus.Approve)
{
Employee oEmployee = new EmployeeService().GetByEmployeeNo("D1263");
oSalaryProcess = new SalaryProcessService().GetSalaryProcess(oWFMovementTran.ObjectID);
if (oSalaryProcess != null && oEmployee != null && oEmployee.EmailAddress != "")
{
MailSender mailSender = new MailSender();
mailSender.AddTo(oEmployee.EmailAddress);
mailSender.Subject = $"Salary process approved for the month {oSalaryProcess.SalaryMonth.ToString("MMMM yyyy")}";
mailSender.Body = @"Dear Hridoy,
<p>Salary has been approved for the month <b>" + oSalaryProcess.SalaryMonth.ToString("MMMM yyyy") + "</b>. Please proceed with the next step.</p>";
mailSender.ThreadSendMail(emailSettings);
}
}
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
[HttpGet]
[Route("GetCurrentSalaryProcessStatusByUniqueID/{uniqueID}")]
public ActionResult GetCurrentSalaryProcessStatusByUniqueID(int uniqueID)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
SalaryProcess oSalaryProcess = new SalaryProcess();
int? status = null;
try
{
if (uniqueID == 0)
{
oSalaryProcess = _salaryProcessService.GetSalaryProcess((DateTime)currentUser.NextPayProcessDate, (int)currentUser.PayrollTypeID);
}
else
{
oSalaryProcess = _salaryProcessService.GetSalaryProcessByUniqueID(uniqueID);
}
if (oSalaryProcess != null)
{
status = oSalaryProcess.WFStatus == null ? null : (int)oSalaryProcess.WFStatus;
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(status);
}
[HttpGet]
[Route("GetCurrentandPreviousMonthNetAmount/{salaryMonth}")]
public ActionResult GetCurrentandPreviousMonthNetAmount(DateTime salaryMonth)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DataTable oSalaryProcess = null;
int? status = null;
try
{
oSalaryProcess = _salaryMonthlyService.GetCurrentandPreviousMonthNetAmount(currentUser.EmployeeID ?? 0, salaryMonth);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(oSalaryProcess);
}
}
}