OrderRequestService.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.WebUtilities;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Configuration;
  5. using MTWorkHR.Application.Identity;
  6. using MTWorkHR.Application.Mapper;
  7. using MTWorkHR.Application.Models;
  8. using MTWorkHR.Core.Global;
  9. using MTWorkHR.Core.IRepositories;
  10. using MTWorkHR.Core.UnitOfWork;
  11. using MTWorkHR.Infrastructure.Entities;
  12. using MTWorkHR.Application.Services.Interfaces;
  13. using MTWorkHR.Core.Email;
  14. using MTWorkHR.Core.Entities;
  15. using MTWorkHR.Infrastructure.UnitOfWorks;
  16. using MTWorkHR.Core.Entities.User;
  17. using System.Linq.Dynamic.Core;
  18. using Microsoft.AspNetCore.Http;
  19. namespace MTWorkHR.Application.Services
  20. {
  21. public class OrderRequestService : BaseService<OrderRequest, OrderRequestDto, OrderRequestDto>, IOrderRequestService
  22. {
  23. private readonly IUnitOfWork _unitOfWork;
  24. private readonly IMailSender _emailSender;
  25. private readonly ApplicationUserManager _userManager;
  26. private readonly GlobalInfo _globalInfo;
  27. private readonly IUserService _userService;
  28. public OrderRequestService(IUnitOfWork unitOfWork, IMailSender emailSender, ApplicationUserManager userManager, GlobalInfo globalInfo, IUserService userService) : base(unitOfWork)
  29. {
  30. _unitOfWork = unitOfWork;
  31. _emailSender = emailSender;
  32. _userManager = userManager;
  33. _globalInfo = globalInfo;
  34. _userService = userService;
  35. }
  36. public override async Task<OrderRequestDto> GetById(long id)
  37. {
  38. var entity = await _unitOfWork.OrderRequest.GetByIdWithAllChildren(id);
  39. var response = MapperObject.Mapper.Map<OrderRequestDto>(entity);
  40. response.Employee = await _userService.GetUserWithAttachmentById(entity.RequestingEmployeeId);
  41. return response;
  42. }
  43. public async Task<PagingResultDto<OrderRequestDto>> GetAll(OrderPagingInputDto PagingInputDto)
  44. {
  45. var res = await _unitOfWork.OrderRequest.GetAllWithChildrenAsync();
  46. var query = res.Item1;
  47. if (_globalInfo.UserType != UserTypeEnum.Business)
  48. {
  49. query = query.Where(m => m.RequestingEmployeeId != null && m.RequestingEmployeeId == _globalInfo.UserId);
  50. }
  51. if (PagingInputDto.Filter != null)
  52. {
  53. var filter = PagingInputDto.Filter;
  54. query = query.Where(u => u.RequestComments!.Contains(filter)
  55. || u.OrderType.NameEn!.Contains(filter)
  56. || u.OrderType.NameAr!.Contains(filter)
  57. || u.LeaveType!.NameEn!.Contains(filter)
  58. || u.LeaveType!.NameAr!.Contains(filter));
  59. }
  60. if (PagingInputDto.SearchDate != null)
  61. {
  62. query = query.Where(u => u.StartDate.Date <= PagingInputDto.SearchDate.Value.Date && u.EndDate!.Value.Date >= PagingInputDto.SearchDate.Value.Date) ;
  63. }
  64. if (PagingInputDto.OrderTypeId != null)
  65. {
  66. query = query.Where(u => u.OrderTypeId == PagingInputDto.OrderTypeId);
  67. }
  68. if (PagingInputDto.LeaveTypeId != null)
  69. {
  70. query = query.Where(u => u.LeaveTypeId == PagingInputDto.LeaveTypeId);
  71. }
  72. if (PagingInputDto.StatusId != null)
  73. {
  74. query = query.Where(u => (long?)u.OrderStatus == PagingInputDto.StatusId);
  75. }
  76. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  77. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  78. var total = await query.CountAsync();
  79. var list = MapperObject.Mapper
  80. .Map<IList<OrderRequestDto>>(await page.ToListAsync());
  81. foreach (var item in list)
  82. {
  83. if (item.RequestingEmployeeId != null)
  84. {
  85. var user = await _userService.GetUserWithAttachmentById(item.RequestingEmployeeId);
  86. if (user != null)
  87. {
  88. item.Employee = user;
  89. var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  90. if(attach != null)
  91. using (var stream = new MemoryStream(attach.Content))
  92. {
  93. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName)
  94. {
  95. Headers = new HeaderDictionary(),
  96. ContentType = attach.ContentType,
  97. };
  98. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  99. {
  100. FileName = file.FileName
  101. };
  102. file.ContentDisposition = cd.ToString();
  103. item.Employee.ProfileImage = file;
  104. }
  105. }
  106. }
  107. }
  108. var response = new PagingResultDto<OrderRequestDto>
  109. {
  110. Result = list,
  111. Total = total
  112. };
  113. return response;
  114. }
  115. public override async Task<OrderRequestDto> Create(OrderRequestDto input)
  116. {
  117. var period = DateTime.Now.Year;
  118. if(string.IsNullOrEmpty( input.RequestingEmployeeId))
  119. {
  120. input.RequestingEmployeeId = _globalInfo.UserId;
  121. }
  122. var allocation = await _unitOfWork.OrderAllocation.GetUserAllocations(input.RequestingEmployeeId, input.OrderTypeId, input.LeaveTypeId, period);
  123. if (allocation is null)
  124. {
  125. throw new AppException(ExceptionEnum.NoVacationBalance, "You do not have any allocations for this leave type.");
  126. }
  127. else
  128. {
  129. int daysRequested = (int)(input.EndDate - input.StartDate).TotalDays;
  130. if (daysRequested > allocation.NumberOfDays)
  131. {
  132. throw new AppException(ExceptionEnum.NoVacationBalance, "You do not have enough days for this request");
  133. }
  134. }
  135. var orderRequest = MapperObject.Mapper.Map<OrderRequest>(input);
  136. orderRequest = await _unitOfWork.OrderRequest.AddAsync(orderRequest);
  137. await _unitOfWork.CompleteAsync();
  138. try
  139. {
  140. var requestingEmployee = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == input.RequestingEmployeeId);
  141. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  142. {
  143. To = requestingEmployee.Email,
  144. Body = $"Your leave request for {input.StartDate:D} to {input.EndDate:D} " +
  145. $"has been submitted successfully.",
  146. Subject = "Leave Request Submitted",
  147. userId = input.RequestingEmployeeId
  148. });
  149. if (!sendMailResult)
  150. {
  151. throw new AppException("User created, but could not send the email!");
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. //// Log or handle error, but don't throw...
  157. }
  158. var response = MapperObject.Mapper.Map<OrderRequestDto>(orderRequest);
  159. if (response.RequestingEmployeeId != null)
  160. {
  161. var user = await _userService.GetUserWithAttachmentById(response.RequestingEmployeeId);
  162. if (user != null)
  163. {
  164. response.Employee = user;
  165. var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  166. if (attach != null)
  167. using (var stream = new MemoryStream(attach.Content))
  168. {
  169. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName)
  170. {
  171. Headers = new HeaderDictionary(),
  172. ContentType = attach.ContentType,
  173. };
  174. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  175. {
  176. FileName = file.FileName
  177. };
  178. file.ContentDisposition = cd.ToString();
  179. response.Employee.ProfileImage = file;
  180. }
  181. }
  182. }
  183. return response;
  184. }
  185. public async Task<OrderRequestDto> ChangeStatus(long id, int statusId )
  186. {
  187. var orderRequest = await _unitOfWork.OrderRequest.GetByIdAsync(id);
  188. orderRequest.OrderStatus = (ApprovalStatusEnum)statusId;
  189. if (orderRequest.OrderStatus == ApprovalStatusEnum.Approved)
  190. {
  191. var allocation = await _unitOfWork.OrderAllocation.GetUserAllocations(orderRequest.RequestingEmployeeId, orderRequest.OrderTypeId, orderRequest.LeaveTypeId, DateTime.Now.Year);
  192. int daysRequested = !orderRequest.EndDate.HasValue ? 1 : (int)(orderRequest.EndDate.Value - orderRequest.StartDate).TotalDays;
  193. allocation.NumberOfDays -= daysRequested;
  194. }
  195. await _unitOfWork.CompleteAsync();
  196. var response = MapperObject.Mapper.Map<OrderRequestDto>(orderRequest);
  197. return response;
  198. }
  199. }
  200. }