HRM-10/HRM.UI/Controllers/Training/TrainingController.cs
2026-11-04 19:03:36 +06:00

1189 lines
53 KiB
C#

using HRM.BO;
using HRM.DA;
using HRM.UI.DTOs.Training;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using static iTextSharp.text.pdf.AcroFields;
namespace HRM.UI.Controllers
{
[ApiController]
[Route("api/Training")]
[Authorize]
public class TrainingController : ControllerBase
{
private readonly ITrainingTypeService _trainingTypeService;
private readonly ITrainingService _trainingService;
private readonly IInstitutionService _institueService;
private readonly INatureOfTrainingService _natureOfTrainingService;
private readonly ITrainingScheduleService _trainingScheduleService;
private readonly ITrainerService _trainerService;
private readonly ITrainingScheduleAttnService _trainingScheduleAttnService;
private readonly IDevelopmentPlanService _developmentPlanService;
private readonly ITrainingNeedAnalysisService _trainingNeedAnalysisService;
public TrainingController(ITrainingTypeService trainingType, ITrainingService training,
IInstitutionService institutionService, INatureOfTrainingService natureOfTrainingService, ITrainingScheduleService trainingScheduleService, ITrainerService trainerService, ITrainingScheduleAttnService trainingScheduleAttnService,
IDevelopmentPlanService developmentPlanService, ITrainingNeedAnalysisService trainingNeedAnalysisService)
{
_trainingNeedAnalysisService = trainingNeedAnalysisService;
_trainingTypeService = trainingType;
this._trainingService = training;
this._institueService = institutionService;
this._natureOfTrainingService = natureOfTrainingService;
_trainingScheduleService = trainingScheduleService;
_trainerService = trainerService;
_trainingScheduleAttnService = trainingScheduleAttnService;
_developmentPlanService = developmentPlanService;
}
[HttpGet("GetAllTrainingType/{status}/{code}/{name}")]
public ActionResult GetAllTrainingType(EnumStatus status, string code, string name)
{
code = GlobalFunctions.GetApiDefaultData(code);
name = GlobalFunctions.GetApiDefaultData(name);
List<TrainingType> items = new List<TrainingType>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = this._trainingTypeService.Get(status);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("GetTrainingybyTypeID/{traininTypeID}")]
public ActionResult GetTrainingybyTypeID(int traininTypeID)
{
List<Training> items = new List<Training>();
try
{
items = this._trainingService.GetbyTypeID(traininTypeID);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("GetAllTraining/{status}/{code}/{name}")]
public ActionResult GetAllTraining(EnumStatus status, string code, string name)
{
code = GlobalFunctions.GetApiDefaultData(code);
name = GlobalFunctions.GetApiDefaultData(name);
List<Training> items = new List<Training>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = this._trainingService.Get();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("GetAllInstitues/{status}/{code}/{name}")]
public ActionResult GetAllInstitues(EnumStatus status, string code, string name)
{
code = GlobalFunctions.GetApiDefaultData(code);
name = GlobalFunctions.GetApiDefaultData(name);
List<Institution> items = new List<Institution>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = this._institueService.Get();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("GetAllTrainingNew/{status}/{code}/{name}")]
public ActionResult GetAllTrainingNew(EnumStatus status, string code, string name)
{
code = GlobalFunctions.GetApiDefaultData(code);
name = GlobalFunctions.GetApiDefaultData(name);
List<Institution> items = new List<Institution>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = this._institueService.GetTraining(status,payrollTypeId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("GetAllNatureOfTraining/{status}/{code}/{name}")]
public ActionResult GetAllNatureOfTraining(EnumStatus status, string code, string name)
{
code = GlobalFunctions.GetApiDefaultData(code);
name = GlobalFunctions.GetApiDefaultData(name);
List<NatureOfTraining> items = new List<NatureOfTraining>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
items = this._natureOfTrainingService.Get();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
#region Training Schedule
[HttpPost]
[Route("savetrainingschedule")]
public ActionResult savetrainingschedule(TrainingSchedule ob)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
ob.CreatedBy = currentUser.UserID;
ob.CreatedDate = DateTime.Today;
ob.PayrollTypeID = currentUser.PayrollTypeID.GetValueOrDefault();
if(ob.EnrolledStartDate== DateTime.MinValue)
{
ob.EnrolledStartDate = null;
}
if (ob.EnrolledEndDate == DateTime.MinValue)
{
ob.EnrolledEndDate = null;
}
ob.ID = _trainingScheduleService.Save(ob);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ob.ID);
}
[HttpPost("getTrainingSchedule")]
public ActionResult GetTrainingSchedule(dynamic data)
{
List<TrainingSchedule> list = new List<TrainingSchedule>();
var items = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
DateTime? fromDate =null;
DateTime? toDate = null;
if (items["fromDate"] != null)
fromDate = (DateTime)items["fromDate"].ToObject<DateTime>();
if (items["toDate"] != null)
toDate = (DateTime)items["toDate"].ToObject<DateTime>();
int trainingId = items["trainingId"].ToObject<int>();
int trainingTypeId = items["trainingTypeId"].ToObject<int>();
try
{
list = _trainingScheduleService.GetTrainingSchedule(trainingId, trainingTypeId, fromDate, toDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(list);
}
[HttpGet("getTrainingScheduleByTrainingID/{pmpYearID}/{trainingID}")]
public ActionResult getTrainingScheduleByTrainingID(int pmpYearID, int? trainingID)
{
PMPProcess pMPProcess = new PMPProcessService().GetPmpProcessByPmpProcesId(pmpYearID);
DateTime fromDate = PayrollGlobalFunctions.FirstDateOfYear(pMPProcess.PmpYear);
DateTime toDate = PayrollGlobalFunctions.LastDateOfYear(pMPProcess.PmpYear);
List<TrainingSchedule> list = new List<TrainingSchedule>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if(trainingID == null || trainingID == 0)
list = _trainingScheduleService.GetByDateRange(fromDate, toDate, currentUser.PayrollTypeID.GetValueOrDefault());
else
list = _trainingScheduleService.GetByTrainingID(trainingID.GetValueOrDefault(), fromDate, toDate, currentUser.PayrollTypeID.GetValueOrDefault());
List<Training> oTrainings = _trainingService.Get();
List<TrainingType> oTrainingTypes = _trainingTypeService.Get();
foreach (var item in list)
{
var training = oTrainings.Find(t => t.ID == item.TrainingID);
var trainingType = oTrainingTypes.Find(t => t.ID == training.TrainingTypeID);
item.TrainingName = training.Name;
item.TrainingTypeName = trainingType.Name;
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(list);
}
[HttpGet("getTrainingScheduleById/{id}")]
public ActionResult getTrainingScheduleById(int id)
{
TrainingSchedule item = null;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
List<Department> departments = new DepartmentService().Get(EnumStatus.Regardless, (int)payrollTypeId);
item = this._trainingScheduleService.Get(id);
if(item != null && item.EnrolledTrainingEmployees != null && item.EnrolledTrainingEmployees.Count > 0)
{
foreach(var x in item.EnrolledTrainingEmployees)
{
x.Employee = new Employee();
x.Employee = new EmployeeService().Get(x.EmployeeID);
var department = departments.FirstOrDefault(d => d.ID == x.Employee.DepartmentID);
if (department != null)
x.Employee.DepartmentName = department.Name;
}
}
if(item != null && item.TrainingScheduleDates != null && item.TrainingScheduleDates.Count > 0)
{
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(item);
}
[HttpGet]
[Route("deleteTrainingByID/{id}")]
public ActionResult deleteTrainingByID(int id)
{
try
{
this._trainingScheduleService.Delete(id);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
#endregion
#region Trainer
[HttpGet]
[Route("getAllTrainers")]
public ActionResult getAllTrainers()
{
List<Trainer> oTrainers = new List<Trainer>();
try
{
oTrainers = this._trainerService.GetAll();
List<Employee> oEmps = new EmployeeService().Get();
foreach(Trainer item in oTrainers)
{
if (item.EmployeeID != null)
item.Employee = oEmps.Find(e => e.ID == item.EmployeeID);
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainers);
}
[HttpGet]
[Route("getTrainerById/{trainerId}")]
public ActionResult getTrainerById(int trainerId)
{
Trainer oTrainer = new Trainer();
try
{
oTrainer = this._trainerService.Get(trainerId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainer);
}
[HttpGet]
[Route("deleteById/{trainerId}")]
public ActionResult deleteById(int trainerId)
{
try
{
this._trainerService.Delete(trainerId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
[HttpPost]
[Route("saveTrainer")]
public ActionResult saveTrainer(Trainer item)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (item.IsNew == true)
{
item.CreatedBy = currentUser.UserID;
item.CreatedDate = DateTime.Today;
}
else
{
item.ModifiedBy = currentUser.UserID;
item.ModifiedDate = DateTime.Today;
}
item.ID = _trainerService.Save(item);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(item.ID);
}
#endregion
#region Training Attendance
[HttpGet("getAllTrainingSchedule")]
public ActionResult getAllTrainingSchedule()
{
List<TrainingSchedule> oTrainingSchedules = new List<TrainingSchedule>();
List<TrainingScheduleEmployee> oTrainingScheduleEmployees = new List<TrainingScheduleEmployee>();
List<TrainingScheduleDate> oTrainingScheduleDates = new List<TrainingScheduleDate>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
oTrainingSchedules = _trainingScheduleService.GetWithPayrollType(payrollTypeId);
oTrainingScheduleEmployees = _trainingScheduleService.GetAllTrainingScheduleEmployees();
oTrainingScheduleDates = _trainingScheduleService.GetAllTrainingScheduleDates();
List<Employee> oEmployees = new EmployeeService().GetAllEmps();
foreach (TrainingSchedule item in oTrainingSchedules)
{
item.TrainingScheduleDates = oTrainingScheduleDates.FindAll(tdate => tdate.TrainingScheduleID == item.ID);
item.EnrolledTrainingEmployees = oTrainingScheduleEmployees.FindAll(temp => temp.TrainingScheduleID == item.ID);
if (item != null && item.EnrolledTrainingEmployees != null && item.EnrolledTrainingEmployees.Count > 0)
{
foreach (var x in item.EnrolledTrainingEmployees)
{
x.Employee = oEmployees.Find(e => e.ID == x.EmployeeID);
}
}
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingSchedules);
}
[HttpGet("getEnrolledTrainingEmployeesbyScheduleDate/{trainingScheduleID}/{trainingScheduleDateID}")]
public ActionResult getEnrolledTrainingEmployeesbyScheduleDate(int trainingScheduleID, int trainingScheduleDateID)
{
List<TrainingScheduleEmployee> oTrainingScheduleEmployees = new List<TrainingScheduleEmployee>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
oTrainingScheduleEmployees = _trainingScheduleService.GetTrainingScheduleEmployees(trainingScheduleID);
string inEmp = TrainingScheduleEmployee.getEmpID(oTrainingScheduleEmployees);
List<Employee> oEmployees = new EmployeeService().Get(inEmp);
List< TrainingScheduleDate> dtates =
_trainingScheduleService.GetTrainingScheduleDates(trainingScheduleID);
var trainigSession = dtates.FirstOrDefault(x => x.ID == trainingScheduleDateID);
List <TrainingScheduleAttn> oTsAttn = _trainingScheduleAttnService.GetByTrainingScheduleDateID(trainingScheduleDateID);
if (oTrainingScheduleEmployees != null && oTrainingScheduleEmployees.Count > 0)
{
foreach (var x in oTrainingScheduleEmployees)
{
x.Employee = oEmployees.Find(e => e.ID == x.EmployeeID);
x.ProposedDate = trainigSession.ScheduleDate;
var attn = oTsAttn.Find(attn => attn.EmployeeID == x.EmployeeID);
if (attn != null)
{
x.Present = true;
}
}
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingScheduleEmployees);
}
[HttpPost]
[Route("saveTrainingAttendance/{trainingScheduleID}/{trainingScheduleDateID}")]
public ActionResult saveTrainingAttendance(int trainingScheduleID, int trainingScheduleDateID, List<TrainingScheduleEmployee> oTrainingScheduleEmployees)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
_trainingScheduleAttnService.saveTrainingAttendance(trainingScheduleID
, trainingScheduleDateID, currentUser.UserID, oTrainingScheduleEmployees);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
#endregion
[HttpPost("uploadTrainingMaterialfiles")]
[AllowAnonymous]
public ActionResult uploadTrainingMaterialfiles(List<IFormFile> files)
{
//empFileupload item = new empFileupload();
string base64String = "";
try
{
int tsID = Convert.ToInt32(Request.Form["trainingScheduleID"]);
//TrainingSchedule trainingSchedule = _trainingScheduleService.Get(tsID);
List<TrainingSchedule> allTrainingSchedules = _trainingScheduleService.GetAll();
TrainingSchedule trainingSchedule = allTrainingSchedules.Find(ts=> ts.ID == tsID);
Training training = _trainingService.Get(trainingSchedule.TrainingID);
PhotoPath photoPath = new PhotoPathService().Get().FirstOrDefault();
_trainingScheduleService.DeleteTrainingMaterial(tsID);
foreach (var file in files)
{
//var fdata = Request.Form.Files["files"];
var fdata = file;
TrainingMaterial item = new TrainingMaterial();
//Upload Image
item.TrainingScheduleID = tsID;
item.FileName = fdata.FileName;
byte[] textAsBytes = null;
using (var ms = new MemoryStream())
{
fdata.CopyTo(ms);
item.FileData = ms.ToArray();
//item.FileName = item.filetype.ToString() + $" {item.referenceID}{Path.GetExtension(fdata.FileName)}";
textAsBytes = ms.ToArray();
base64String = Convert.ToBase64String(textAsBytes);
}
string TargetFolder = training.Name + "-" + "" + tsID.ToString() + "";
if (fdata != null)
{
byte[] bytes = textAsBytes;
try
{
string folderPath = string.Empty;
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
bool inProduction = Configuration.GetSection("TrainingSettings")["InProduction"].ToLower() == "yes" ? true : false;
string projectPath = Configuration.GetSection("TrainingSettings")["ProjectPath"];
string serverAddress = Configuration.GetSection("TrainingSettings")["ServerIP"];
string userID = Configuration.GetSection("TrainingSettings")["UserID"];
string password = Configuration.GetSection("TrainingSettings")["Password"];
if (!inProduction)
{
folderPath = System.IO.Path.Combine(System.Environment.CurrentDirectory + @"\Documents\Training Materials\");
TargetFolder = Path.Combine(folderPath) + TargetFolder;
if (!Directory.Exists(TargetFolder))
{
Directory.CreateDirectory(TargetFolder);
}
//string[] Files = Directory.GetFiles(TargetFolder);
string fullTargetPath = TargetFolder + "\\" + item.FileName;
System.IO.File.WriteAllBytes(fullTargetPath, bytes);
_trainingScheduleService.SaveTrainingMaterial(item);
}
else
{
folderPath = Path.Combine(projectPath + @"\Documents\Training Materials\");
//string folderPath = $@"\\210.4.65.222\c$\inetpub\wwwroot\SGSTest\";
//string folderPath = $@"\\100.100.100.164\c$\inetpub\wwwroot\SGSRevamp\Documents\Training Materials\";
TargetFolder = Path.Combine(folderPath) + TargetFolder;
using (FileAccessWithImpersonation impersonator = new())
{
impersonator.ImpersonateUser(serverAddress, userID, password);
// Run an action as the impersonated user
impersonator.RunAsImpersonated(() =>
{
if (!Directory.Exists(TargetFolder))
{
Directory.CreateDirectory(TargetFolder);
}
//string[] Files = Directory.GetFiles(TargetFolder);
string fullTargetPath = TargetFolder + "\\" + item.FileName;
System.IO.File.WriteAllBytes(fullTargetPath, bytes);
_trainingScheduleService.SaveTrainingMaterial(item);
});
}
}
//For development test only
//TargetFolder = "C:\\Users\\mashfiq.EASE\\Desktop\\Training\\" + TargetFolder;
//string folderPath = System.IO.Path.Combine(System.Environment.CurrentDirectory + @"\Documents\Training Materials\");
//TargetFolder = Path.Combine(folderPath) + TargetFolder;
//if (new FileAccessWithImpersonation().ImpersonateUser("", "", ""))
//{
// if (!Directory.Exists(TargetFolder))
// {
// Directory.CreateDirectory(TargetFolder);
// }
// //string[] Files = Directory.GetFiles(TargetFolder);
// string fullTargetPath = TargetFolder + "\\" + item.FileName;
// System.IO.File.WriteAllBytes(fullTargetPath, bytes);
// _trainingScheduleService.SaveTrainingMaterial(item);
//}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(base64String);
}
[HttpGet("getTrainingMaterials/{trainingScheduleID}")]
public ActionResult getTrainingMaterials(int trainingScheduleID)
{
List<TrainingMaterial> oTrainingMaterials = new List<TrainingMaterial>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
try
{
oTrainingMaterials = _trainingScheduleService.GetTrainingMaterials(trainingScheduleID);
List<TrainingSchedule> allTrainingSchedules = _trainingScheduleService.GetAll();
TrainingSchedule trainingSchedule = allTrainingSchedules.Find(ts => ts.ID == trainingScheduleID);
Training training = _trainingService.Get(trainingSchedule.TrainingID);
string TargetFolder = training.Name + "-" + "" + trainingScheduleID.ToString() + "";
string folderPath = string.Empty;
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
bool inProduction = Configuration.GetSection("TrainingSettings")["InProduction"].ToLower() == "yes" ? true : false;
string projectPath = Configuration.GetSection("TrainingSettings")["ProjectPath"];
if (!inProduction)
{
folderPath = System.IO.Path.Combine(System.Environment.CurrentDirectory + @"\Documents\Training Materials\");
//string folderPath = System.IO.Path.Combine(System.Environment.CurrentDirectory + @"\Documents\Training Materials\");
}
else
{
folderPath = Path.Combine(projectPath + @"\Documents\Training Materials\");
//string folderPath = $@"\\100.100.100.164\c$\inetpub\wwwroot\SGSRevamp\";
}
if (folderPath == string.Empty)
{
throw new Exception("Folder for Training Materials not found");
}
TargetFolder = Path.Combine(folderPath) + TargetFolder;
string fullTargetFolderPath = Path.Combine(folderPath, TargetFolder);
if(oTrainingMaterials != null && oTrainingMaterials.Count > 0)
{
if (!Directory.Exists(fullTargetFolderPath))
{
return NotFound("Target folder " + fullTargetFolderPath + " not found.");
}
var files = Directory.GetFiles(fullTargetFolderPath);
if (files.Length == 0)
{
return NotFound("No files found in the target folder.");
}
foreach (var item in oTrainingMaterials)
{
var targetFile = files.FirstOrDefault(f => f.Equals(fullTargetFolderPath + "\\" + item.FileName));
if (targetFile == null)
{
return NotFound("No matching file found.");
}
item.FileBytes = System.IO.File.ReadAllBytes(targetFile);
}
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingMaterials);
}
[HttpGet("getTrainingScheduleByEmployee")]
public ActionResult getTrainingScheduleByEmployee() //This is for current Employee Enrolled TrainingSchedule
{
List<TrainingSchedule> oTrainingSchedules = new List<TrainingSchedule>();
List<TrainingScheduleEmployee> oTrainingScheduleEmployees = null;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
int employeeId = currentUser.EmployeeID.GetValueOrDefault();
DateTime fromDate = PayrollGlobalFunctions.FirstDateOfYear(DateTime.Now);
DateTime toDate = PayrollGlobalFunctions.LastDateOfYear(DateTime.Now);
try
{
//List<Department> departments = new DepartmentService().Get(EnumStatus.Regardless, (int)payrollTypeId);
List<int> uniqueTrainerIds = new List<int>();
List<int> existedTrainingSchedules = new List<int>();
List<Training> oTrainings = _trainingService.Get();
List<TrainingSchedule> allTrainingSchedules = this._trainingScheduleService.GetWithPayrollType(payrollTypeId).FindAll(ts => ts.StartDate >= fromDate && ts.StartDate <= toDate);
allTrainingSchedules.ForEach(x => { existedTrainingSchedules.Add(x.ID); });
List<TrainingScheduleDate> allTrainingScheduleDates = _trainingScheduleService.GetAllTrainingScheduleDates();
List<Trainer> allTrainers = _trainerService.GetAll();
oTrainingScheduleEmployees = this._trainingScheduleService.GetTrainingScheduleEmployeesByEmployeeId(employeeId);
foreach(var item in oTrainingScheduleEmployees)
{
if (existedTrainingSchedules.Contains(item.TrainingScheduleID))
{
var trainingSchedules = allTrainingSchedules.Find(ts=> ts.ID == item.TrainingScheduleID);
if(trainingSchedules != null)
oTrainingSchedules.Add(trainingSchedules);
}
else
{
continue;
}
}
foreach(var item in oTrainingSchedules)
{
item.TrainingScheduleDates = allTrainingScheduleDates.FindAll(tsd => tsd.TrainingScheduleID == item.ID);
item.TrainingName = oTrainings.Find(t => t.ID == item.TrainingID) != null ? oTrainings.Find(t => t.ID == item.TrainingID).Name : "";
//item.TrainingScheduleDates.ForEach(x => { uniqueTrainerIds.Add(x.TrainerID); });
//uniqueTrainerIds = uniqueTrainerIds.Distinct().ToList();
//item.Trainers = new List<Trainer>();
//foreach (var itemDate in item.TrainingScheduleDates)
//{
// if (uniqueTrainerIds.Contains(itemDate.TrainerID))
// {
// var trainer = allTrainers.Find(tr => tr.ID == itemDate.TrainerID);
// if (trainer != null)
// item.Trainers.Add(trainer);
// }
// else
// {
// continue;
// }
//}
item.Trainers = new List<Trainer>();
item.TrainingScheduleDates.ForEach(x => {
var trainer = allTrainers.Find(tr => tr.ID == x.TrainerID);
if (trainer != null)
item.Trainers.Add(trainer); });
if(item.Trainers.Count != 0)
item.Trainers = item.Trainers.Distinct().ToList();
}
//oTrainingSchedules.ForEach(ts => {
// ts.TrainingScheduleDates = allTrainingScheduleDates.FindAll(tsd => tsd.TrainingScheduleID == ts.ID);
// ts.TrainingName = oTrainings.Find(t => t.ID == ts.TrainingID) != null ? oTrainings.Find(t => t.ID == ts.TrainingID).Name : "";
// ts.TrainingScheduleDates.ForEach(x => { uniqueTrainerIds.Add(x.TrainerID); });
// uniqueTrainerIds = uniqueTrainerIds.Distinct().ToList();
//} );
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingSchedules);
}
[HttpGet("getTrainingScheduleCurrYear")]
public ActionResult getTrainingScheduleCurrYear()
{
List<TrainingSchedule> oTrainingSchedules = new List<TrainingSchedule>();
//List<TrainingScheduleEmployee> oTrainingScheduleEmployees = null;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int payrollTypeId = currentUser.PayrollTypeID.GetValueOrDefault();
int employeeId = currentUser.EmployeeID.GetValueOrDefault();
DateTime fromDate = PayrollGlobalFunctions.FirstDateOfYear(DateTime.Now);
DateTime toDate = PayrollGlobalFunctions.LastDateOfYear(DateTime.Now);
try
{
List<Training> oTrainings = _trainingService.Get();
List<TrainingSchedule> allTrainingSchedules = _trainingScheduleService.GetWithPayrollType(payrollTypeId).FindAll(ts => ts.StartDate >= fromDate && ts.StartDate <= toDate);
List<TrainingScheduleDate> allTrainingScheduleDates = _trainingScheduleService.GetAllTrainingScheduleDates();
List<TrainingScheduleEmployee> allTrainingScheduleEmployees = _trainingScheduleService.GetAllTrainingScheduleEmployees();
List<Trainer> allTrainers = _trainerService.GetAll();
List<Institution> allInstitute = _institueService.Get();
foreach (var item in allTrainingSchedules)
{
item.TrainingScheduleDates = allTrainingScheduleDates.FindAll(tsd => tsd.TrainingScheduleID == item.ID);
item.EnrolledTrainingEmployees = allTrainingScheduleEmployees.FindAll(tse => tse.TrainingScheduleID == item.ID);
item.Training = oTrainings.Find(t => t.ID == item.TrainingID);
item.TrainingName = item.Training != null ? item.Training.Name : "";
item.Institute = allInstitute.Find(i => i.ID == item.InstituteID);
item.Trainers = new List<Trainer>();
item.TrainingScheduleDates.ForEach(x => {
var trainer = allTrainers.Find(tr => tr.ID == x.TrainerID);
if (trainer != null)
item.Trainers.Add(trainer); });
if(item.Trainers.Count != 0)
item.Trainers = item.Trainers.Distinct().ToList();
}
oTrainingSchedules = allTrainingSchedules;
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingSchedules);
}
[HttpGet("getTeamScheduleCurrYear")]
public ActionResult getTeamScheduleCurrYear()
{
DataTable datam = null;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
datam = _trainingScheduleService.getTeamScheduleCurrYear((int)currentUser.EmployeeID);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(datam);
}
[HttpGet("getTrainingScheduleAttnCurrEmployee/{trainingScheduleID}")]
public ActionResult getTrainingScheduleAttnCurrEmployee(int trainingScheduleID)
{
List<TrainingScheduleAttn> oTrainingScheduleAttn = new List<TrainingScheduleAttn>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int employeeID = (int)currentUser.EmployeeID;
try
{
oTrainingScheduleAttn = _trainingScheduleAttnService.GetByTrainingScheduleIDAndEmployeeID(trainingScheduleID, employeeID);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(oTrainingScheduleAttn);
}
[HttpPost]
[Route("trainingAttendanceStatusChange/{attnStatus}")]
public ActionResult trainingAttendanceStatusChange(bool attnStatus, TrainingScheduleAttn oTrainingScheduleAttn)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int employeeID = (int)currentUser.EmployeeID;
oTrainingScheduleAttn.EmployeeID = employeeID;
try
{
//List<TrainingScheduleAttn> oTrainingScheduleAttns = _trainingScheduleAttnService.GetByTrainingScheduleIDAndEmployeeID(oTrainingScheduleAttn.TrainingScheduleID, employeeID);
//var exists = oTrainingScheduleAttns.Find(tsa => tsa.TSDateID == oTrainingScheduleAttn.TSDateID);
if(oTrainingScheduleAttn.ID == 0)
{
oTrainingScheduleAttn.CreatedBy = currentUser.UserID;
oTrainingScheduleAttn.CreatedDate = DateTime.Today;
}
if(attnStatus)
{
_trainingScheduleAttnService.Save(oTrainingScheduleAttn);
}
else
{
_trainingScheduleAttnService.DeletebyEmployeeIdAndTrainingScheduleID(oTrainingScheduleAttn.EmployeeID, oTrainingScheduleAttn.TSDateID);
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpGet("getSubordiateTrainingSchedule/{year}")]
public ActionResult getSubordiateTrainingSchedule(DateTime year)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int employeeID = (int)currentUser.EmployeeID;
int payrollTypeId = (int)currentUser.PayrollTypeID;
DataTable subordinateTrainingScheduledt = new DataTable();
subordinateTrainingScheduledt.Columns.Add("EmployeeID", typeof(int));
subordinateTrainingScheduledt.Columns.Add("EmployeeNo", typeof(string));
subordinateTrainingScheduledt.Columns.Add("Name", typeof(string));
subordinateTrainingScheduledt.Columns.Add("Designation", typeof(string));
subordinateTrainingScheduledt.Columns.Add("TrainingName", typeof(string));
subordinateTrainingScheduledt.Columns.Add("StartDate", typeof(DateTime));
subordinateTrainingScheduledt.Columns.Add("EndDate", typeof(DateTime));
subordinateTrainingScheduledt.Columns.Add("DevelopmentPlanID", typeof(int));
subordinateTrainingScheduledt.Columns.Add("Enrolled", typeof(bool));
try
{
DateTime firstDateOfYear = PayrollGlobalFunctions.FirstDateOfYear(year);
DateTime lastDateOfYear = PayrollGlobalFunctions.LastDateOfYear(year);
List<Training> oTrainings = _trainingService.Get();
List<Designation> oDesignations = new DesignationService().GetAll();
List<Employee> subordinates = new EmployeeService().GetFirstLMTeamMembers(employeeID);
List<int> subordinateIDs = new List<int>();
subordinates.ForEach(s => { subordinateIDs.Add(s.ID); });
//List<TrainingSchedule> oTrainingSchedules = _trainingScheduleService.GetWithPayrollType(payrollTypeId);
//List<int> oTrainingScheduleIDs = new List<int>();
//oTrainingSchedules.ForEach(ts => { oTrainingScheduleIDs.Add(ts.ID); });
//List<TrainingScheduleEmployee> allTrainingScheduleEmployees = _trainingScheduleService.GetAllTrainingScheduleEmployees();
//List<TrainingScheduleEmployee> oTrainingScheduleEmployees = allTrainingScheduleEmployees
// .Where(oTSE => subordinateIDs.Contains(oTSE.EmployeeID) && oTrainingScheduleIDs.Contains(oTSE.TrainingScheduleID)).ToList();
//List<int> subordinateTrainingIDs = new List<int>();
//oTrainingScheduleEmployees.ForEach(oTSE => { subordinateTrainingIDs.Add(oTSE.TrainingScheduleID); });
//List<TrainingSchedule> subordinateTrainingSchedules = oTrainingSchedules.
// Where(ts => subordinateTrainingIDs.Contains(ts.ID) && firstDateOfYear <= ts.StartDate && ts.EndDate <= lastDateOfYear).ToList();
//foreach(TrainingSchedule item in subordinateTrainingSchedules)
//{
// item.EnrolledTrainingEmployees = oTrainingScheduleEmployees.FindAll(e => e.TrainingScheduleID == item.ID);
// if(item.EnrolledTrainingEmployees != null && item.EnrolledTrainingEmployees.Count > 0)
// {
// foreach(var enrollEmp in item.EnrolledTrainingEmployees)
// {
// DataRow oDr = subordinateTrainingScheduledt.NewRow();
// var subordiEmp = subordinates.Find(s => s.ID == enrollEmp.EmployeeID);
// oDr["EmployeeID"] = subordiEmp.ID;
// oDr["EmployeeNo"] = subordiEmp.EmployeeNo;
// oDr["Name"] = subordiEmp.Name;
// oDr["Designation"] = oDesignations.Find(d => d.ID == subordiEmp.DesignationID).Name;
// oDr["TrainingName"] = oTrainings.Find(t => t.ID == item.TrainingID).Name;
// oDr["StartDate"] = item.StartDate;
// oDr["EndDate"] = item.EndDate;
// subordinateTrainingScheduledt.Rows.Add(oDr);
// }
// }
//}
List<DevelopmentPlan> oDevelopmentplans = _developmentPlanService.Get().Where(dvp => subordinateIDs.Contains(dvp.EmployeeID) && firstDateOfYear <= dvp.FromDate && dvp.ToDate <= lastDateOfYear).ToList();
foreach (var item in oDevelopmentplans)
{
DataRow oDr = subordinateTrainingScheduledt.NewRow();
var subordiEmp = subordinates.Find(s => s.ID == item.EmployeeID);
oDr["EmployeeID"] = subordiEmp.ID;
oDr["EmployeeNo"] = subordiEmp.EmployeeNo;
oDr["Name"] = subordiEmp.Name;
oDr["Designation"] = oDesignations.Find(d => d.ID == subordiEmp.DesignationID).Name;
//oDr["TrainingName"] = oTrainings.Find(t => t.ID == item.TrainingID).Name;
oDr["TrainingName"] = item.TrainingName;
oDr["StartDate"] = item.FromDate;
oDr["EndDate"] = item.ToDate;
oDr["DevelopmentPlanID"] = item.ID;
oDr["Enrolled"] = item.Enrolled;
subordinateTrainingScheduledt.Rows.Add(oDr);
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(subordinateTrainingScheduledt);
}
[HttpPost]
[Route("saveDevelopmentPlan")]
public ActionResult SaveDevelopmentPlan(DevelopmentPlan item)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int ans;
try
{
ans = _developmentPlanService.Save(item);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ans);
}
[HttpPost]
[Route("enrollTrainingscheduleEmployeefromDevelopmentPlan/{developmentPlanID}")]
public ActionResult enrollTrainingscheduleEmployeefromDevelopmentPlan(int developmentPlanID,TrainingScheduleEmployee item)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int ans;
try
{
TrainingScheduleEmployee trainingScheduleEmployees = _trainingScheduleService.GetTrainingScheduleEmployees(item.TrainingScheduleID).Find(tse => tse.EmployeeID == item.EmployeeID);
DevelopmentPlan developmentPlan = _developmentPlanService.Get(developmentPlanID);
if (trainingScheduleEmployees == null)
{
item.ScheduleEmpStatus = EnumTSStatus.Requested;
item.ProposedByID = currentUser.UserID;
item.ProposedDate = DateTime.Now;
ans = _trainingScheduleService.SaveTrainingEmp(item);
developmentPlan.Enrolled = true;
_developmentPlanService.Save(developmentPlan);
}
else
{
throw new Exception("Employee Is already Enrolled in the schedule");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ans);
}
#region Training Need Analysis screen (sourced from TrainingNeedAnalysis / IDP)
[HttpGet("getTrainingNeedAnalysisByPmpYear/{pmpYearId}")]
public ActionResult getTrainingNeedAnalysisByPmpYear(int pmpYearId)
{
List<TrainingNeedAnalysis> items = new List<TrainingNeedAnalysis>();
try
{
items = _trainingNeedAnalysisService.GetByPmpYear(pmpYearId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet("getTrainingNeedAnalysisCountByPmpYear/{pmpYearId}")]
public ActionResult getTrainingNeedAnalysisCountByPmpYear(int pmpYearId)
{
DataSet ds = new DataSet();
try
{
ds = _trainingNeedAnalysisService.GetCountByPmpYear(pmpYearId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ds.Tables[0]);
}
// TrainingNeedAnalysis.TrainingID holds a TRAININGTYPE id, so the enrollment popup has to
// resolve the trainings of that type first before looking up their schedules in the PMS year.
[HttpGet("getTrainingScheduleByTrainingTypeID/{pmpYearID}/{trainingTypeID}")]
public ActionResult getTrainingScheduleByTrainingTypeID(int pmpYearID, int? trainingTypeID)
{
List<TrainingSchedule> list = new List<TrainingSchedule>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
PMPProcess pMPProcess = new PMPProcessService().GetPmpProcessByPmpProcesId(pmpYearID);
if (pMPProcess == null)
throw new Exception("PMS year of this training need could not be found.");
DateTime fromDate = PayrollGlobalFunctions.FirstDateOfYear(pMPProcess.PmpYear);
DateTime toDate = PayrollGlobalFunctions.LastDateOfYear(pMPProcess.PmpYear);
list = _trainingScheduleService.GetByDateRange(fromDate, toDate,
currentUser.PayrollTypeID.GetValueOrDefault());
List<Training> oTrainings = _trainingService.Get();
List<TrainingType> oTrainingTypes = _trainingTypeService.Get();
if (trainingTypeID != null && trainingTypeID != 0)
{
List<int> trainingIDsOfType = oTrainings
.FindAll(t => t.TrainingTypeID == trainingTypeID.GetValueOrDefault())
.ConvertAll(t => t.ID);
list = list.FindAll(s => trainingIDsOfType.Contains(s.TrainingID));
}
foreach (var item in list)
{
var training = oTrainings.Find(t => t.ID == item.TrainingID);
if (training == null)
continue;
var trainingType = oTrainingTypes.Find(t => t.ID == training.TrainingTypeID);
item.TrainingName = training.Name;
item.TrainingTypeName = trainingType == null ? string.Empty : trainingType.Name;
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(list);
}
[HttpPost]
[Route("enrollTrainingscheduleEmployeefromTrainingNeedAnalysis/{trainingNeedAnalysisID}")]
public ActionResult enrollTrainingscheduleEmployeefromTrainingNeedAnalysis(int trainingNeedAnalysisID,
TrainingScheduleEmployee item)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int ans;
try
{
TrainingScheduleEmployee alreadyEnrolled = _trainingScheduleService
.GetTrainingScheduleEmployees(item.TrainingScheduleID)
.Find(tse => tse.EmployeeID == item.EmployeeID);
if (alreadyEnrolled == null)
{
item.ScheduleEmpStatus = EnumTSStatus.Requested;
item.ProposedByID = currentUser.UserID;
item.ProposedDate = DateTime.Now;
ans = _trainingScheduleService.SaveTrainingEmp(item);
_trainingNeedAnalysisService.UpdateEnrolledStatus(trainingNeedAnalysisID, true);
}
else
{
throw new Exception("Employee Is already Enrolled in the schedule");
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ans);
}
#endregion
}
}