ContractService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using Microsoft.EntityFrameworkCore;
  2. using MTWorkHR.Application.Identity;
  3. using MTWorkHR.Application.Mapper;
  4. using MTWorkHR.Application.Models;
  5. using MTWorkHR.Core.Global;
  6. using MTWorkHR.Core.UnitOfWork;
  7. using MTWorkHR.Application.Services.Interfaces;
  8. using MTWorkHR.Core.Entities;
  9. using System.Linq.Dynamic.Core;
  10. using Microsoft.AspNetCore.Identity;
  11. using MTWorkHR.Infrastructure.Entities;
  12. using System.Linq;
  13. using MTWorkHR.Core.IDto;
  14. using MTWorkHR.Core.Entities.User;
  15. namespace MTWorkHR.Application.Services
  16. {
  17. public class ContractService : BaseService<Contract, ContractDto, ContractDto>, IContractService
  18. {
  19. private readonly IUnitOfWork _unitOfWork;
  20. private readonly IUserService _userService;
  21. private readonly GlobalInfo _globalInfo;
  22. private readonly IOrderAllocationService _orderAllocationService;
  23. public ContractService(IUnitOfWork unitOfWork, IUserService userService, GlobalInfo globalInfo, IOrderAllocationService orderAllocationService) : base(unitOfWork)
  24. {
  25. _unitOfWork = unitOfWork;
  26. _userService = userService;
  27. _globalInfo = globalInfo;
  28. _orderAllocationService = orderAllocationService;
  29. }
  30. public override async Task<ContractDto> GetById(long id)
  31. {
  32. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(id);
  33. var response = MapperObject.Mapper.Map<ContractDto>(entity);
  34. response.WorkingDays = entity.WorkingDays != null ? entity.WorkingDays.Split(",").ToList() : null;
  35. return response;
  36. }
  37. public override async Task<ContractDto> Create(ContractDto input)
  38. {
  39. var entity = MapperObject.Mapper.Map<Contract>(input);
  40. if (entity is null)
  41. {
  42. throw new AppException(ExceptionEnum.MapperIssue);
  43. }
  44. entity.WorkingDays = input.WorkingDays!=null? string.Join(",", input.WorkingDays): null;
  45. var team = await _unitOfWork.Contract.AddAsync(entity);
  46. await _unitOfWork.CompleteAsync();
  47. var response = MapperObject.Mapper.Map<ContractDto>(team);
  48. return response;
  49. }
  50. //public override async Task<ContractDto> Update(ContractDto input)
  51. //{
  52. // var entity = MapperObject.Mapper.Map<Contract>(input);
  53. // if (entity is null)
  54. // {
  55. // throw new AppException(ExceptionEnum.MapperIssue);
  56. // }
  57. // var contract = await _unitOfWork.Contract.upd(entity);
  58. // await _unitOfWork.CompleteAsync();
  59. // var response = Mapper.MapperObject.Mapper.Map<ContractDto>(entity);
  60. // return response;
  61. //}
  62. public async Task<PagingResultDto<ContractDto>> GetAll(ContractPagingInputDto PagingInputDto)
  63. {
  64. var res = await _unitOfWork.Contract.GetAllWithChildrenAsync();
  65. var query = res.Item1;
  66. if (_globalInfo.UserType != UserTypeEnum.Business)
  67. {
  68. // query = query.Where(m => m.ContractUsers != null && m.ContractUsers.Count > 0 && m.ContractUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);
  69. }
  70. if (PagingInputDto.Filter != null)
  71. {
  72. var filter = PagingInputDto.Filter;
  73. query = query.Where(u => u.JobDescription != null && u.JobDescription.Contains(filter));
  74. }
  75. if (PagingInputDto.ContractStatusId != null)
  76. {
  77. query = query.Where(u => (int)u.ContractStatusId == PagingInputDto.ContractStatusId);
  78. }
  79. if (PagingInputDto.ContractTypeId != null)
  80. {
  81. query = query.Where(u => (int)u.ContractTypeId == PagingInputDto.ContractTypeId);
  82. }
  83. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  84. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  85. var total = await query.CountAsync();
  86. var list = MapperObject.Mapper
  87. .Map<IList<ContractDto>>(await page.ToListAsync());
  88. foreach (var item in list)
  89. {
  90. if (item.UserId != null)
  91. {
  92. var user = await _userService.GetUserWithAttachmentById(item.UserId);
  93. if (user != null)
  94. {
  95. item.EmployeeName = user.FirstName + " " + user.LastName;
  96. item.EmployeeEmail = user.Email;
  97. }
  98. }
  99. }
  100. var response = new PagingResultDto<ContractDto>
  101. {
  102. Result = list,
  103. Total = total
  104. };
  105. return response;
  106. }
  107. #region HR data____________________________
  108. public async Task<PagingResultDto<ContractAllHRDto>> GetAllForHr(ContractPagingInputDto PagingInputDto)
  109. {
  110. var res = await _unitOfWork.Contract.GetAllWithChildrenAsync();
  111. var query = res.Item1;
  112. if (_globalInfo.UserType != UserTypeEnum.Business)
  113. {
  114. // query = query.Where(m => m.ContractUsers != null && m.ContractUsers.Count > 0 && m.ContractUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);
  115. }
  116. if (PagingInputDto.Filter != null)
  117. {
  118. var filter = PagingInputDto.Filter;
  119. query = query.Where(u => u.JobDescription.Contains(filter));
  120. }
  121. if (PagingInputDto.ContractStatusId != null)
  122. {
  123. query = query.Where(u => (int)u.ContractStatusId == PagingInputDto.ContractStatusId);
  124. }
  125. if (PagingInputDto.ContractTypeId != null)
  126. {
  127. query = query.Where(u => (int)u.ContractTypeId == PagingInputDto.ContractTypeId);
  128. }
  129. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  130. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  131. var total = await query.CountAsync();
  132. var list = MapperObject.Mapper
  133. .Map<IList<ContractAllHRDto>>(await page.ToListAsync());
  134. var teamUsersList = await _unitOfWork.TeamUser.GetAllWithChildrenAsync();
  135. var vacationAllocations = await _unitOfWork.OrderAllocation.GetAllAsync();
  136. foreach (var item in list)
  137. {
  138. if (item.UserId != null)
  139. {
  140. var user = await _userService.GetUserWithAttachmentById(item.UserId);
  141. if (user != null)
  142. {
  143. item.EmployeeName = user.FirstName + " " + user.LastName;
  144. item.EmployeeEmail = user.Email;
  145. //___________Get Teams
  146. //var TeamsList = teamUsersList.Item1.Where(t => t.AssignedUserId == item.UserId).Select(t => GlobalInfo.lang == "en" ? t.Team.NameEn : t.Team.NameAr);
  147. //item.Teams = TeamsList == null ? "" : string.Join(",", TeamsList);
  148. var latestTeam = teamUsersList.Item1.OrderByDescending(a=> a.Id).FirstOrDefault(t => t.AssignedUserId == item.UserId);
  149. item.Teams = latestTeam == null ? "" : GlobalInfo.lang == "en" ? latestTeam.Team?.NameEn : latestTeam.Team?.NameAr;
  150. //_____________Get vacation balance
  151. var remainVacations = vacationAllocations.Item1.FirstOrDefault(t => t.EmployeeId == item.UserId && t.ContractId == item.Id);
  152. item.RestVacations = remainVacations == null ? item.VacationDays : remainVacations.NumberOfDays ;
  153. item.SpentVacations = item.VacationDays - item.RestVacations;
  154. }
  155. }
  156. }
  157. // Filter employees by name if provided
  158. if (!string.IsNullOrEmpty(PagingInputDto.UserName))
  159. {
  160. var filter = PagingInputDto.UserName;
  161. list = list.Where(u =>
  162. (u.EmployeeName != null && u.EmployeeName.Contains(filter))
  163. || (u.EmployeeEmail != null && u.EmployeeEmail.Contains(filter))
  164. ).ToList();
  165. }
  166. var response = new PagingResultDto<ContractAllHRDto>
  167. {
  168. Result = list,
  169. Total = list.Count
  170. };
  171. return response;
  172. }
  173. public async Task<ContractHRDto> GetByIdHRDetails(long contractId)
  174. {
  175. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(contractId);
  176. if (entity != null)
  177. {
  178. var response = MapperObject.Mapper.Map<ContractHRDto>(entity);
  179. response.WorkingDays = entity.WorkingDays != null ? entity.WorkingDays.Split(",").ToList() : null;
  180. //--------------------
  181. var user = await _userService.GetUserWithAttachmentById(entity.UserId);
  182. response.EmployeeName = user.FirstName + " " + user.LastName;
  183. response.EmployeeEmail = user.Email;
  184. //___________Get Teams
  185. var teamUsersList = await _unitOfWork.TeamUser.GetUserTeams(entity.UserId);
  186. var teamsList = MapperObject.Mapper.Map<List<TeamDto>>(teamUsersList.Item1);
  187. response.TeamList = teamsList;
  188. //_____________Get vacation balance
  189. var vacationAllocations = await _unitOfWork.OrderAllocation.GetUserAllocations(entity.UserId, 1, 1, entity.Id, DateTime.Now.Year);
  190. var remainVacations = vacationAllocations;
  191. response.RestVacations = remainVacations == null ? entity.VacationDays : remainVacations.NumberOfDays;
  192. response.SpentVacations = entity.VacationDays - response.RestVacations;
  193. //__-----------Order Requests----
  194. var orderRequestsList = await _unitOfWork.OrderRequest.GetAllUserOrdersAsync(entity.UserId, contractId);
  195. var vacationsList = orderRequestsList.Item1.Where(o => o.OrderStatus == ApprovalStatusEnum.Approved && o.OrderTypeId == 1 && (o.LeaveTypeId == 1 || o.LeaveTypeId == 2));
  196. var orderList = MapperObject.Mapper.Map<List<OrderRequestHRDto>>(vacationsList);
  197. response.OrderList = orderList;
  198. /////------------------------
  199. var invoiceList = await _unitOfWork.Invoice.GetAllUserInvoices(contractId);
  200. var Invoices = MapperObject.Mapper.Map<List<InvoiceDto>>(invoiceList.Item1);
  201. response.InvoiceList = Invoices;
  202. //------------------
  203. if(entity.ContractTypeId == (int)ContractTypeEnum.EmployeeContract)
  204. {
  205. var lastInvoice = Invoices.LastOrDefault();
  206. var diffDate = DateTime.Now.Date - entity.StartDate.Value.Date;
  207. if(lastInvoice != null)
  208. {
  209. if (entity.BillingCycle == "Monthly")
  210. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddMonths(1);
  211. else if (entity.BillingCycle == "Fortnightly")
  212. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddDays(15);
  213. }
  214. else
  215. {
  216. if (entity.BillingCycle == "Monthly")
  217. response.NextSalaryDate = entity.StartDate.Value.AddMonths(1);
  218. else if(entity.BillingCycle == "Fortnightly")
  219. response.NextSalaryDate = entity.StartDate.Value.AddDays(15);
  220. }
  221. }
  222. return response;
  223. }
  224. return new ContractHRDto();
  225. }
  226. #endregion
  227. public async Task<bool> ChangeStatus(long contractId, int statusId)
  228. {
  229. var entity = await _unitOfWork.Contract.GetByIdAsync(contractId);
  230. if (entity == null)
  231. throw new AppException(ExceptionEnum.RecordNotExist);
  232. entity.ContractStatusId = statusId;
  233. bool result = true;
  234. if (statusId == (int)ContractStatusEnum.Approved)
  235. {
  236. var updatedSuccess = await _userService.Update(entity.UserId, entity.CompanyId);
  237. addVacationAllocation(entity.VacationDays.HasValue ? entity.VacationDays.Value : 0, entity.UserId, contractId);
  238. if (!updatedSuccess) {
  239. result = false;
  240. }
  241. }
  242. return result;
  243. }
  244. private async Task addVacationAllocation(int noVacationDays, string employeeId, long contractId)
  245. {
  246. try
  247. {
  248. await _orderAllocationService.Create(new OrderAllocationDto { ContractId = contractId, EmployeeId = employeeId, OrderTypeId = 1, LeaveTypeId = 1, NumberOfDays = noVacationDays, Period = DateTime.Now.Year });
  249. // var orderTypes = await _unitOfWork.OrderType.GetAllAsync();
  250. // var leaveTypes = await _unitOfWork.LeaveType.GetAllAsync();
  251. //foreach (var orderType in orderTypes.Item1)
  252. //{
  253. // foreach (var leaveType in leaveTypes.Item1)
  254. // {
  255. // if (orderType.Id != 1 && leaveType.Id != 1 && (leaveType.DefaultDays > 0 || orderType.DefaultDays > 0))
  256. // {
  257. // await _orderAllocationService.Create(new OrderAllocationDto
  258. // {
  259. // ContractId = contractId,
  260. // EmployeeId = employeeId,
  261. // OrderTypeId = (int)orderType.Id,
  262. // LeaveTypeId = (int)leaveType.Id,
  263. // NumberOfDays = leaveType.DefaultDays > 0 ? leaveType.DefaultDays : orderType.DefaultDays,
  264. // Period = DateTime.Now.Year
  265. // }
  266. // );
  267. // }
  268. // }
  269. //}
  270. }
  271. catch(Exception ex)
  272. {
  273. throw ;
  274. }
  275. }
  276. }
  277. }