ContractService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. //___________Get Teams
  152. //var TeamsList = teamUsersList.Item1.Where(t => t.AssignedUserId == item.UserId).Select(t => GlobalInfo.lang == "en" ? t.Team.NameEn : t.Team.NameAr);
  153. //item.Teams = TeamsList == null ? "" : string.Join(",", TeamsList);
  154. var latestTeam = teamUsersList.Item1.OrderByDescending(a=> a.Id).FirstOrDefault(t => t.AssignedUserId == item.UserId);
  155. item.Teams = latestTeam == null ? "" : GlobalInfo.lang == "en" ? latestTeam.Team?.NameEn : latestTeam.Team?.NameAr;
  156. //_____________Get vacation balance
  157. var remainVacations = vacationAllocations.Item1.FirstOrDefault(t => t.EmployeeId == item.UserId && t.ContractId == item.Id);
  158. item.RestVacations = remainVacations == null ? item.VacationDays : remainVacations.NumberOfDays ;
  159. item.SpentVacations = item.VacationDays - item.RestVacations;
  160. }
  161. }
  162. }
  163. // Filter employees by name if provided
  164. if (!string.IsNullOrEmpty(PagingInputDto.UserName))
  165. {
  166. var filter = PagingInputDto.UserName;
  167. list = list.Where(u =>
  168. (u.EmployeeName != null && u.EmployeeName.Contains(filter))
  169. || (u.EmployeeEmail != null && u.EmployeeEmail.Contains(filter))
  170. ).ToList();
  171. }
  172. var response = new PagingResultDto<ContractAllHRDto>
  173. {
  174. Result = list,
  175. Total = list.Count
  176. };
  177. return response;
  178. }
  179. public async Task<ContractHRDto> GetByIdHRDetails(long contractId)
  180. {
  181. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(contractId);
  182. if (entity != null)
  183. {
  184. var response = MapperObject.Mapper.Map<ContractHRDto>(entity);
  185. response.WorkingDays = entity.WorkingDays != null ? entity.WorkingDays.Split(",").ToList() : null;
  186. //--------------------
  187. var user = await _userService.GetUserWithAttachmentById(entity.UserId);
  188. response.EmployeeName = user.FirstName + " " + user.LastName;
  189. response.EmployeeEmail = user.Email;
  190. //___________Get Teams
  191. var teamUsersList = await _unitOfWork.TeamUser.GetUserTeams(entity.UserId);
  192. var teamsList = MapperObject.Mapper.Map<List<TeamDto>>(teamUsersList.Item1);
  193. response.TeamList = teamsList;
  194. //_____________Get vacation balance
  195. var vacationAllocations = await _unitOfWork.OrderAllocation.GetUserAllocations(entity.UserId, 1, 1, entity.Id, DateTime.Now.Year);
  196. var remainVacations = vacationAllocations;
  197. response.RestVacations = remainVacations == null ? entity.VacationDays : remainVacations.NumberOfDays;
  198. response.SpentVacations = entity.VacationDays - response.RestVacations;
  199. //__-----------Order Requests----
  200. var orderRequestsList = await _unitOfWork.OrderRequest.GetAllUserOrdersAsync(entity.UserId, contractId);
  201. var vacationsList = orderRequestsList.Item1.Where(o => o.OrderStatus == ApprovalStatusEnum.Approved && o.OrderTypeId == 1 && (o.LeaveTypeId == 1 || o.LeaveTypeId == 2));
  202. var orderList = MapperObject.Mapper.Map<List<OrderRequestHRDto>>(vacationsList);
  203. response.OrderList = orderList;
  204. /////------------------------
  205. var invoiceList = await _unitOfWork.Invoice.GetAllUserInvoices(contractId);
  206. var Invoices = MapperObject.Mapper.Map<List<InvoiceDto>>(invoiceList.Item1);
  207. response.InvoiceList = Invoices;
  208. //------------------
  209. if(entity.ContractTypeId == (int)ContractTypeEnum.EmployeeContract)
  210. {
  211. var lastInvoice = Invoices.LastOrDefault();
  212. var diffDate = DateTime.Now.Date - entity.StartDate.Value.Date;
  213. if(lastInvoice != null)
  214. {
  215. if (entity.BillingCycle == "Monthly")
  216. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddMonths(1);
  217. else if (entity.BillingCycle == "Fortnightly")
  218. response.NextSalaryDate = lastInvoice.InvoiceDate.Value.AddDays(15);
  219. }
  220. else
  221. {
  222. if (entity.BillingCycle == "Monthly")
  223. response.NextSalaryDate = entity.StartDate.Value.AddMonths(1);
  224. else if(entity.BillingCycle == "Fortnightly")
  225. response.NextSalaryDate = entity.StartDate.Value.AddDays(15);
  226. }
  227. }
  228. return response;
  229. }
  230. return new ContractHRDto();
  231. }
  232. #endregion
  233. public async Task<bool> ChangeStatus(long contractId, int statusId)
  234. {
  235. var entity = await _unitOfWork.Contract.GetByIdAsync(contractId);
  236. if (entity == null)
  237. throw new AppException(ExceptionEnum.RecordNotExist);
  238. entity.ContractStatusId = statusId;
  239. bool result = true;
  240. if (statusId == (int)ContractStatusEnum.Approved)
  241. {
  242. var updatedSuccess = await _userService.Update(entity.UserId, entity.CompanyId);
  243. addVacationAllocation(entity.VacationDays.HasValue ? entity.VacationDays.Value : 0, entity.UserId, contractId);
  244. if (!updatedSuccess) {
  245. result = false;
  246. }
  247. }
  248. return result;
  249. }
  250. private async Task addVacationAllocation(int noVacationDays, string employeeId, long contractId)
  251. {
  252. try
  253. {
  254. await _orderAllocationService.Create(new OrderAllocationDto { ContractId = contractId, EmployeeId = employeeId, OrderTypeId = 1, LeaveTypeId = 1, NumberOfDays = noVacationDays, Period = DateTime.Now.Year });
  255. // var orderTypes = await _unitOfWork.OrderType.GetAllAsync();
  256. // var leaveTypes = await _unitOfWork.LeaveType.GetAllAsync();
  257. //foreach (var orderType in orderTypes.Item1)
  258. //{
  259. // foreach (var leaveType in leaveTypes.Item1)
  260. // {
  261. // if (orderType.Id != 1 && leaveType.Id != 1 && (leaveType.DefaultDays > 0 || orderType.DefaultDays > 0))
  262. // {
  263. // await _orderAllocationService.Create(new OrderAllocationDto
  264. // {
  265. // ContractId = contractId,
  266. // EmployeeId = employeeId,
  267. // OrderTypeId = (int)orderType.Id,
  268. // LeaveTypeId = (int)leaveType.Id,
  269. // NumberOfDays = leaveType.DefaultDays > 0 ? leaveType.DefaultDays : orderType.DefaultDays,
  270. // Period = DateTime.Now.Year
  271. // }
  272. // );
  273. // }
  274. // }
  275. //}
  276. }
  277. catch(Exception ex)
  278. {
  279. throw ;
  280. }
  281. }
  282. public async Task<ContractDetail> GetByIdReport(long id)
  283. {
  284. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(id);
  285. var contract = MapperObject.Mapper.Map<ContractDetail>(entity);
  286. contract.WorkingDays = entity.WorkingDays;//!= null ? entity.WorkingDays.Split(",").ToList() : null;
  287. var user = await _userService.GetUserById(entity.UserId);
  288. if (user != null)
  289. {
  290. contract.EmployeeName = user.FirstName + " " + user.LastName;
  291. contract.EmployeeEmail = user.Email;
  292. contract.EmployeePassport = user.PassportNumber;
  293. contract.EmployeePhone = user.PhoneNumber;
  294. contract.EmployeeUniversity = user.UniversityName;
  295. contract.AcademicQualification = user.QualificationName;
  296. contract.EmployeeJobName = user.JobTitleName;
  297. }
  298. return contract;
  299. }
  300. public async Task<AttachmentResponseDto> GenerateContractPdf(string outputPath, long contractId)
  301. {
  302. try
  303. {
  304. var entity = await _unitOfWork.Contract.GetByIdWithAllChildren(contractId);
  305. var contract = new ContractDetail
  306. {
  307. StartDate = entity.StartDate,
  308. BillingCycle = entity.BillingCycle,
  309. ContractDuration = entity.ContractDurationId != null ? ((ContractDurationEnum)entity.ContractDurationId).ToString() : "",
  310. ContractStatusId = (ContractStatusEnum)entity.ContractStatusId,
  311. FirstPatchAmount = entity.FirstPatchAmount,
  312. FirstPatchDateFrom = entity.FirstPatchDateFrom,
  313. FirstPatchDateTo = entity.FirstPatchDateTo,
  314. LastPatchAmount = entity.LastPatchAmount,
  315. LastPatchDateFrom = entity.LastPatchDateFrom,
  316. LastPatchDateTo = entity.LastPatchDateTo,
  317. JobDescription = entity.JobDescription,
  318. JobNumber = entity.JobNumber,
  319. Salary = entity.Salary,
  320. JobTitleName = entity.JobTitleName,//Specialization = entity.SpecializationId,
  321. TrialPeriod = entity.TrialPeriod,
  322. VacationDays = entity.VacationDays, //WhoCanTerminateContract = entity.WhoCanTerminateContract,TypeOfWork = entity.TypeOfWork
  323. //WhoCanTerminateContractInTrial =
  324. WorkCountry = entity.WorkCountryId + "",
  325. WorkingHours = entity.WorkingHours + "",
  326. ContractTypeId = (ContractTypeEnum)entity.ContractTypeId,
  327. Currency = entity.Currency,
  328. FixedAllowances = entity.FixedAllowances,
  329. ProjectStages = entity.ProjectStages,
  330. ContractTasks = entity.ContractTasks,
  331. WorkState = entity.WorkStateId + "",
  332. WorkingDays = entity.WorkingDays
  333. };
  334. var user = await _userService.GetUserById(entity.UserId);
  335. if (user != null)
  336. {
  337. contract.EmployeeName = user.FirstName + " " + user.LastName;
  338. contract.EmployeeEmail = user.Email;
  339. contract.EmployeePassport = user.PassportNumber;
  340. contract.EmployeePhone = user.PhoneNumber;
  341. contract.EmployeeUniversity = user.UniversityName;
  342. contract.AcademicQualification = user.QualificationName;
  343. contract.EmployeeJobName = user.JobTitleName;
  344. contract.EmployeeDateOfBirth = user.DateOfBirth;
  345. }
  346. var representativeUser = await _userService.GetUserById(entity.CompanyRepresentativeId);
  347. if (representativeUser != null)
  348. {
  349. contract.CompanyRepresentativeName = representativeUser.FirstName + " " + representativeUser.LastName;
  350. contract.CompanyRepresentativeEmail = representativeUser.Email;
  351. contract.CompanyRepresentativePassport = representativeUser.PassportNumber;
  352. contract.CompanyRepresentativePhone = representativeUser.PhoneNumber;
  353. contract.CompanyRepresentativePosition = representativeUser.Position ?? "";
  354. }
  355. var company = await _unitOfWork.Company.GetByIdAsync(entity.CompanyId);
  356. if (company != null)
  357. {
  358. contract.CompanyName = company.CompanyName;
  359. contract.CompanyEmail = company.Email;
  360. contract.CompanyPhone = company.PhoneNumber;
  361. contract.CompanyCR = company.CRNumber;
  362. contract.CompanyAddress = company.Address;
  363. }
  364. var pdfBytes = await new ContractPdfGenerator().GenerateContractPdf(outputPath, contract);
  365. // Upload to Azure Blob Storage and return the Blob URL
  366. string fileName = $"contract_{Guid.NewGuid()}.pdf";
  367. var result = await _fileService.UploadFile(pdfBytes, fileName);
  368. entity.FilePath = result.FilePath;
  369. await _unitOfWork.CompleteAsync();
  370. return result;
  371. }
  372. catch (Exception e)
  373. {
  374. throw e;
  375. // _logger.LogError(e, "Failed to generate contract PDF for contractId {ContractId}", contractId);
  376. var msg = e.Message;
  377. //return new AttachmentResponseDto();
  378. }
  379. }
  380. public byte[] generatePdfTest()
  381. {
  382. var pdfBytes = new ContractPdfGenerator().GeneratePdf();
  383. return pdfBytes;
  384. }
  385. }
  386. }