ContractService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. using System.Diagnostics.Contracts;
  16. using Contract = MTWorkHR.Core.Entities.Contract;
  17. using MTWorkHR.Infrastructure.Reports;
  18. using DevExpress.DataProcessing;
  19. namespace MTWorkHR.Application.Services
  20. {
  21. public class ContractService : BaseService<Contract, ContractDto, ContractDto>, IContractService
  22. {
  23. private readonly IUnitOfWork _unitOfWork;
  24. private readonly IUserService _userService;
  25. private readonly GlobalInfo _globalInfo;
  26. private readonly IFileService _fileService;
  27. private readonly IOrderAllocationService _orderAllocationService;
  28. public ContractService(IUnitOfWork unitOfWork, IUserService userService, GlobalInfo globalInfo, IOrderAllocationService orderAllocationService, IFileService fileService) : base(unitOfWork)
  29. {
  30. _unitOfWork = unitOfWork;
  31. _userService = userService;
  32. _globalInfo = globalInfo;
  33. _orderAllocationService = orderAllocationService;
  34. _fileService = fileService;
  35. }
  36. public override async Task<ContractDto> GetById(long id)
  37. {
  38. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(id);
  39. var response = MapperObject.Mapper.Map<ContractDto>(entity);
  40. response.WorkingDays = entity.WorkingDays != null ? entity.WorkingDays.Split(",").ToList() : null;
  41. return response;
  42. }
  43. public override async Task<ContractDto> Create(ContractDto input)
  44. {
  45. var entity = MapperObject.Mapper.Map<Contract>(input);
  46. if (entity is null)
  47. {
  48. throw new AppException(ExceptionEnum.MapperIssue);
  49. }
  50. entity.WorkingDays = input.WorkingDays!=null? string.Join(",", input.WorkingDays): null;
  51. var team = await _unitOfWork.Contract.AddAsync(entity);
  52. await _unitOfWork.CompleteAsync();
  53. var response = MapperObject.Mapper.Map<ContractDto>(team);
  54. return response;
  55. }
  56. //public override async Task<ContractDto> Update(ContractDto input)
  57. //{
  58. // var entity = MapperObject.Mapper.Map<Contract>(input);
  59. // if (entity is null)
  60. // {
  61. // throw new AppException(ExceptionEnum.MapperIssue);
  62. // }
  63. // var contract = await _unitOfWork.Contract.upd(entity);
  64. // await _unitOfWork.CompleteAsync();
  65. // var response = Mapper.MapperObject.Mapper.Map<ContractDto>(entity);
  66. // return response;
  67. //}
  68. public async Task<PagingResultDto<ContractDto>> GetAll(ContractPagingInputDto PagingInputDto)
  69. {
  70. var res = await _unitOfWork.Contract.GetAllWithChildrenAsync();
  71. var query = res.Item1;
  72. if (_globalInfo.UserType != UserTypeEnum.Business)
  73. {
  74. // query = query.Where(m => m.ContractUsers != null && m.ContractUsers.Count > 0 && m.ContractUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);
  75. }
  76. if (PagingInputDto.Filter != null)
  77. {
  78. var filter = PagingInputDto.Filter;
  79. query = query.Where(u => u.JobDescription != null && u.JobDescription.Contains(filter));
  80. }
  81. if (PagingInputDto.ContractStatusId != null)
  82. {
  83. query = query.Where(u => (int)u.ContractStatusId == PagingInputDto.ContractStatusId);
  84. }
  85. if (PagingInputDto.ContractTypeId != null)
  86. {
  87. query = query.Where(u => (int)u.ContractTypeId == PagingInputDto.ContractTypeId);
  88. }
  89. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  90. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  91. var total = await query.CountAsync();
  92. var list = MapperObject.Mapper
  93. .Map<IList<ContractDto>>(await page.ToListAsync());
  94. foreach (var item in list)
  95. {
  96. if (item.UserId != null)
  97. {
  98. var user = await _userService.GetUserWithAttachmentById(item.UserId);
  99. if (user != null)
  100. {
  101. item.EmployeeName = user.FirstName + " " + user.LastName;
  102. item.EmployeeEmail = user.Email;
  103. }
  104. }
  105. }
  106. var response = new PagingResultDto<ContractDto>
  107. {
  108. Result = list,
  109. Total = total
  110. };
  111. return response;
  112. }
  113. #region HR data____________________________
  114. public async Task<PagingResultDto<ContractAllHRDto>> GetAllForHr(ContractPagingInputDto PagingInputDto)
  115. {
  116. var res = await _unitOfWork.Contract.GetAllWithChildrenAsync();
  117. var query = res.Item1;
  118. if (_globalInfo.UserType != UserTypeEnum.Business)
  119. {
  120. // query = query.Where(m => m.ContractUsers != null && m.ContractUsers.Count > 0 && m.ContractUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);
  121. }
  122. if (PagingInputDto.Filter != null)
  123. {
  124. var filter = PagingInputDto.Filter;
  125. query = query.Where(u => u.JobDescription.Contains(filter));
  126. }
  127. if (PagingInputDto.ContractStatusId != null)
  128. {
  129. query = query.Where(u => (int)u.ContractStatusId == PagingInputDto.ContractStatusId);
  130. }
  131. if (PagingInputDto.ContractTypeId != null)
  132. {
  133. query = query.Where(u => (int)u.ContractTypeId == PagingInputDto.ContractTypeId);
  134. }
  135. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  136. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  137. var total = await query.CountAsync();
  138. var list = MapperObject.Mapper
  139. .Map<IList<ContractAllHRDto>>(await page.ToListAsync());
  140. var teamUsersList = await _unitOfWork.TeamUser.GetAllWithChildrenAsync();
  141. var vacationAllocations = await _unitOfWork.OrderAllocation.GetAllAsync();
  142. foreach (var item in list)
  143. {
  144. if (item.UserId != null)
  145. {
  146. var user = await _userService.GetUserWithAttachmentById(item.UserId);
  147. if (user != null)
  148. {
  149. item.EmployeeName = user.FirstName + " " + user.LastName;
  150. item.EmployeeEmail = user.Email;
  151. var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  152. item.ProfileImagePath = attach?.FilePath;
  153. //___________Get Teams
  154. //var TeamsList = teamUsersList.Item1.Where(t => t.AssignedUserId == item.UserId).Select(t => GlobalInfo.lang == "en" ? t.Team.NameEn : t.Team.NameAr);
  155. //item.Teams = TeamsList == null ? "" : string.Join(",", TeamsList);
  156. var latestTeam = teamUsersList.Item1.OrderByDescending(a=> a.Id).FirstOrDefault(t => t.AssignedUserId == item.UserId);
  157. item.Teams = latestTeam == null ? "" : GlobalInfo.lang == "en" ? latestTeam.Team?.NameEn : latestTeam.Team?.NameAr;
  158. //_____________Get vacation balance
  159. var remainVacations = vacationAllocations.Item1.FirstOrDefault(t => t.EmployeeId == item.UserId && t.ContractId == item.Id);
  160. item.RestVacations = remainVacations == null ? item.VacationDays : remainVacations.NumberOfDays ;
  161. item.SpentVacations = item.VacationDays - item.RestVacations;
  162. }
  163. }
  164. }
  165. // Filter employees by name if provided
  166. if (!string.IsNullOrEmpty(PagingInputDto.UserName))
  167. {
  168. var filter = PagingInputDto.UserName;
  169. list = list.Where(u =>
  170. (u.EmployeeName != null && u.EmployeeName.ToLower().Contains(filter))
  171. || (u.EmployeeEmail != null && u.EmployeeEmail.ToLower().Contains(filter))
  172. ).ToList();
  173. }
  174. var response = new PagingResultDto<ContractAllHRDto>
  175. {
  176. Result = list,
  177. Total = list.Count
  178. };
  179. return response;
  180. }
  181. public async Task<ContractHRDto> GetByIdHRDetails(long contractId)
  182. {
  183. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(contractId);
  184. if (entity != null)
  185. {
  186. var response = MapperObject.Mapper.Map<ContractHRDto>(entity);
  187. response.WorkingDays = entity.WorkingDays != null ? entity.WorkingDays.Split(",").ToList() : null;
  188. //--------------------
  189. var user = await _userService.GetUserWithAttachmentById(entity.UserId);
  190. response.EmployeeName = user.FirstName + " " + user.LastName;
  191. response.EmployeeEmail = user.Email;
  192. var attach = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  193. response.ProfileImagePath = attach?.FilePath;
  194. //___________Get Teams
  195. var teamUsersList = await _unitOfWork.TeamUser.GetUserTeams(entity.UserId);
  196. var teamsList = MapperObject.Mapper.Map<List<TeamDto>>(teamUsersList.Item1);
  197. response.TeamList = teamsList;
  198. //_____________Get vacation balance
  199. var vacationAllocations = await _unitOfWork.OrderAllocation.GetUserAllocations(entity.UserId, 1, 1, entity.Id, DateTime.Now.Year);
  200. var remainVacations = vacationAllocations;
  201. response.RestVacations = remainVacations == null ? entity.VacationDays : remainVacations.NumberOfDays;
  202. response.SpentVacations = entity.VacationDays - response.RestVacations;
  203. //__-----------Order Requests----
  204. var orderRequestsList = await _unitOfWork.OrderRequest.GetAllUserOrdersAsync(entity.UserId, contractId);
  205. var vacationsList = orderRequestsList.Item1.Where(o => o.OrderStatus == ApprovalStatusEnum.Approved && o.OrderTypeId == 1 && (o.LeaveTypeId == 1 || o.LeaveTypeId == 2));
  206. var orderList = MapperObject.Mapper.Map<List<OrderRequestHRDto>>(vacationsList);
  207. response.OrderList = orderList;
  208. /////------------------------
  209. var invoiceList = await _unitOfWork.Invoice.GetAllUserInvoices(contractId);
  210. var Invoices = MapperObject.Mapper.Map<List<InvoiceDto>>(invoiceList.Item1);
  211. response.InvoiceList = Invoices;
  212. //------------------
  213. if(entity.ContractTypeId == (int)ContractTypeEnum.EmployeeContract)
  214. {
  215. var lastInvoice = Invoices.LastOrDefault();
  216. var diffDate = DateTime.Now.Date - entity.StartDate.Value.Date;
  217. if(lastInvoice != null)
  218. {
  219. if (entity.BillingCycle == "Monthly")
  220. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddMonths(1);
  221. else if (entity.BillingCycle == "Fortnightly")
  222. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddDays(15);
  223. }
  224. else
  225. {
  226. if (entity.BillingCycle == "Monthly")
  227. response.NextSalaryDate = entity.StartDate.Value.AddMonths(1);
  228. else if(entity.BillingCycle == "Fortnightly")
  229. response.NextSalaryDate = entity.StartDate.Value.AddDays(15);
  230. }
  231. }
  232. return response;
  233. }
  234. return new ContractHRDto();
  235. }
  236. #endregion
  237. public async Task<bool> ChangeStatus(long contractId, int statusId)
  238. {
  239. var entity = await _unitOfWork.Contract.GetByIdAsync(contractId);
  240. if (entity == null)
  241. throw new AppException(ExceptionEnum.RecordNotExist);
  242. entity.ContractStatusId = statusId;
  243. bool result = true;
  244. if (statusId == (int)ContractStatusEnum.Approved)
  245. {
  246. var updatedSuccess = await _userService.Update(entity.UserId, entity.CompanyId);
  247. addVacationAllocation(entity.VacationDays.HasValue ? entity.VacationDays.Value : 0, entity.UserId, contractId);
  248. if (!updatedSuccess) {
  249. result = false;
  250. }
  251. }
  252. return result;
  253. }
  254. private async Task addVacationAllocation(int noVacationDays, string employeeId, long contractId)
  255. {
  256. try
  257. {
  258. await _orderAllocationService.Create(new OrderAllocationDto { ContractId = contractId, EmployeeId = employeeId, OrderTypeId = 1, LeaveTypeId = 1, NumberOfDays = noVacationDays, Period = DateTime.Now.Year });
  259. // var orderTypes = await _unitOfWork.OrderType.GetAllAsync();
  260. // var leaveTypes = await _unitOfWork.LeaveType.GetAllAsync();
  261. //foreach (var orderType in orderTypes.Item1)
  262. //{
  263. // foreach (var leaveType in leaveTypes.Item1)
  264. // {
  265. // if (orderType.Id != 1 && leaveType.Id != 1 && (leaveType.DefaultDays > 0 || orderType.DefaultDays > 0))
  266. // {
  267. // await _orderAllocationService.Create(new OrderAllocationDto
  268. // {
  269. // ContractId = contractId,
  270. // EmployeeId = employeeId,
  271. // OrderTypeId = (int)orderType.Id,
  272. // LeaveTypeId = (int)leaveType.Id,
  273. // NumberOfDays = leaveType.DefaultDays > 0 ? leaveType.DefaultDays : orderType.DefaultDays,
  274. // Period = DateTime.Now.Year
  275. // }
  276. // );
  277. // }
  278. // }
  279. //}
  280. }
  281. catch(Exception ex)
  282. {
  283. throw ;
  284. }
  285. }
  286. public async Task<ContractDetail> GetByIdReport(long id)
  287. {
  288. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(id);
  289. var contract = MapperObject.Mapper.Map<ContractDetail>(entity);
  290. contract.WorkingDays = entity.WorkingDays;//!= null ? entity.WorkingDays.Split(",").ToList() : null;
  291. var user = await _userService.GetUserById(entity.UserId);
  292. if (user != null)
  293. {
  294. contract.EmployeeName = user.FirstName + " " + user.LastName;
  295. contract.EmployeeEmail = user.Email;
  296. contract.EmployeePassport = user.PassportNumber;
  297. contract.EmployeePhone = user.PhoneNumber;
  298. contract.EmployeeUniversity = user.UniversityName;
  299. contract.AcademicQualification = user.QualificationName;
  300. contract.EmployeeJobName = user.JobTitleName;
  301. }
  302. return contract;
  303. }
  304. public async Task<AttachmentResponseDto> GenerateContractPdf(string outputPath, long contractId)
  305. {
  306. try
  307. {
  308. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(contractId);
  309. var contract = new ContractDetail
  310. {
  311. StartDate = entity.StartDate,
  312. BillingCycle = entity.BillingCycle,
  313. ContractDuration = entity.ContractDurationId != null ? ((ContractDurationEnum)entity.ContractDurationId).ToString() : "",
  314. ContractStatusId = (ContractStatusEnum)entity.ContractStatusId,
  315. FirstPatchAmount = entity.FirstPatchAmount,
  316. FirstPatchDateFrom = entity.FirstPatchDateFrom,
  317. FirstPatchDateTo = entity.FirstPatchDateTo,
  318. LastPatchAmount = entity.LastPatchAmount,
  319. LastPatchDateFrom = entity.LastPatchDateFrom,
  320. LastPatchDateTo = entity.LastPatchDateTo,
  321. JobDescription = entity.JobDescription,
  322. JobNumber = entity.JobNumber,
  323. Salary = entity.Salary,
  324. JobTitleName = entity.JobTitleName,//Specialization = entity.SpecializationId,
  325. TrialPeriod = entity.TrialPeriod,
  326. VacationDays = entity.VacationDays, //WhoCanTerminateContract = entity.WhoCanTerminateContract,TypeOfWork = entity.TypeOfWork
  327. //WhoCanTerminateContractInTrial =
  328. WorkCountry = entity.WorkCountryId + "",
  329. WorkingHours = entity.WorkingHours + "",
  330. ContractTypeId = (ContractTypeEnum)entity.ContractTypeId,
  331. Currency = entity.Currency,
  332. FixedAllowances = entity.FixedAllowances,
  333. ProjectStages = entity.ProjectStages,
  334. ContractTasks = entity.ContractTasks,
  335. WorkState = entity.WorkStateId + "",
  336. WorkingDays = entity.WorkingDays
  337. };
  338. var user = await _userService.GetUserById(entity.UserId);
  339. if (user != null)
  340. {
  341. contract.EmployeeName = user.FirstName + " " + user.LastName;
  342. contract.EmployeeEmail = user.Email;
  343. contract.EmployeePassport = user.PassportNumber;
  344. contract.EmployeePhone = user.PhoneNumber;
  345. contract.EmployeeUniversity = user.UniversityName;
  346. contract.AcademicQualification = user.QualificationName;
  347. contract.EmployeeJobName = user.JobTitleName;
  348. contract.EmployeeDateOfBirth = user.DateOfBirth;
  349. }
  350. var representativeUser = await _userService.GetUserById(entity.CompanyRepresentativeId);
  351. if (representativeUser != null)
  352. {
  353. contract.CompanyRepresentativeName = representativeUser.FirstName + " " + representativeUser.LastName;
  354. contract.CompanyRepresentativeEmail = representativeUser.Email;
  355. contract.CompanyRepresentativePassport = representativeUser.PassportNumber;
  356. contract.CompanyRepresentativePhone = representativeUser.PhoneNumber;
  357. contract.CompanyRepresentativePosition = representativeUser.Position ?? "";
  358. }
  359. var company = await _unitOfWork.Company.GetByIdAsync(entity.CompanyId);
  360. if (company != null)
  361. {
  362. contract.CompanyName = company.CompanyName;
  363. contract.CompanyEmail = company.Email;
  364. contract.CompanyPhone = company.PhoneNumber;
  365. contract.CompanyCR = company.CRNumber;
  366. contract.CompanyAddress = company.Address;
  367. }
  368. var pdfBytes = await new ContractPdfGenerator().GenerateContractPdf(outputPath, contract);
  369. // Upload to Azure Blob Storage and return the Blob URL
  370. string fileName = $"contract_{Guid.NewGuid()}.pdf";
  371. var result = await _fileService.UploadFile(pdfBytes, fileName);
  372. entity.FilePath = result.FilePath;
  373. await _unitOfWork.CompleteAsync();
  374. return result;
  375. }
  376. catch (Exception e)
  377. {
  378. throw e;
  379. // _logger.LogError(e, "Failed to generate contract PDF for contractId {ContractId}", contractId);
  380. var msg = e.Message;
  381. //return new AttachmentResponseDto();
  382. }
  383. }
  384. public byte[] generatePdfTest()
  385. {
  386. var pdfBytes = new ContractPdfGenerator().GeneratePdf();
  387. return pdfBytes;
  388. }
  389. }
  390. }