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