UserService.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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.Application.Services.Interfaces;
  12. using MTWorkHR.Core.Email;
  13. using MTWorkHR.Core.Entities;
  14. using MTWorkHR.Infrastructure.UnitOfWorks;
  15. using MTWorkHR.Infrastructure.Entities;
  16. using static Org.BouncyCastle.Crypto.Engines.SM2Engine;
  17. using System.Web;
  18. using System.Data;
  19. using MTWorkHR.Core.IDto;
  20. using System.Linq.Dynamic.Core;
  21. using MTWorkHR.Core.Entities.Base;
  22. using MTWorkHR.Infrastructure.EmailService;
  23. using Countries.NET.Database;
  24. using Microsoft.AspNetCore.Http;
  25. using System.Collections;
  26. using System.Linq;
  27. using System.ComponentModel.Design;
  28. using static iText.StyledXmlParser.Jsoup.Select.Evaluator;
  29. using static iText.IO.Util.IntHashtable;
  30. using Microsoft.Extensions.Logging;
  31. namespace MTWorkHR.Application.Services
  32. {
  33. public class UserService : IUserService
  34. {
  35. private readonly RoleManager<ApplicationRole> _roleManager;
  36. private readonly ApplicationUserManager _userManager;
  37. private readonly IUnitOfWork _unitOfWork;
  38. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  39. private readonly AppSettingsConfiguration _configuration;
  40. private readonly IMailSender _emailSender;
  41. private readonly GlobalInfo _globalInfo;
  42. private readonly IFileService _fileService;
  43. private readonly IOTPService _oTPService;
  44. private readonly ILogger<UserService> _logger;
  45. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  46. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IMailSender emailSender
  47. , IUserRoleRepository<IdentityUserRole<string>> userRole, IFileService fileService, IOTPService oTPService, ILogger<UserService> logger)
  48. {
  49. _userManager = userManager;
  50. _unitOfWork = unitOfWork;
  51. _roleManager = roleManager;
  52. _userRole = userRole;
  53. _configuration = configuration;
  54. _emailSender = emailSender;
  55. _globalInfo = globalInfo;
  56. _fileService = fileService;
  57. _oTPService = oTPService;
  58. _logger = logger;
  59. }
  60. public async Task<UserDto> GetById()
  61. {
  62. return await GetById(_globalInfo.UserId);
  63. }
  64. public async Task<UserDto> GetByEmail(string email)
  65. {
  66. var user = _userManager.Users.FirstOrDefault(x => x.Email == email);
  67. if(user == null)
  68. throw new AppException(ExceptionEnum.UserNotExist);
  69. return await GetById(user.Id);
  70. }
  71. public async Task<UserDto> GetById(string id)
  72. {
  73. var entity = await _userManager.Users
  74. .Include(x => x.UserRoles)
  75. .Include(x => x.UserAddress).ThenInclude(x=> x.City)
  76. .Include(x => x.UserAddress).ThenInclude(x=> x.Country)
  77. .Include(x => x.UserAttachments)
  78. .Include(x => x.JobTitle)
  79. .Include(x => x.Industry)
  80. .Include(x => x.University)
  81. .Include(x => x.Country)
  82. .Include(x => x.Qualification)
  83. .FirstOrDefaultAsync(x => x.Id == id);
  84. var response = MapperObject.Mapper.Map<UserDto>(entity);
  85. if (response.UserAttachments != null)
  86. foreach (var attach in response.UserAttachments.Where(a => a.Content != null))
  87. {
  88. //var stream = new MemoryStream(attach.Content);
  89. //IFormFile file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName);
  90. using (var stream = new MemoryStream(attach.Content))
  91. {
  92. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
  93. {
  94. Headers = new HeaderDictionary(),
  95. ContentType = attach.ContentType,
  96. };
  97. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  98. {
  99. FileName = file.FileName
  100. };
  101. file.ContentDisposition = cd.ToString();
  102. switch (attach.AttachmentTypeId)
  103. {
  104. case 1:
  105. response.CVAttach = file;
  106. break;
  107. case 2:
  108. response.PassportAttach = file;
  109. break;
  110. case 3:
  111. response.EduCertificateAttach = file;
  112. break;
  113. case 4:
  114. response.ExperienceCertificateAttach = file;
  115. break;
  116. case 5:
  117. response.ProfCertificateAttach = file;
  118. break;
  119. case 6:
  120. response.CommercialRegAttach = file;
  121. break;
  122. case 7:
  123. response.TaxDeclarationAttach = file;
  124. break;
  125. case 8:
  126. response.IdAttach = file;
  127. break;
  128. case 9:
  129. response.ProfileImage = file;
  130. response.ProfileImagePath = attach.FilePath;
  131. break;
  132. }
  133. attach.Content = new byte[0];
  134. }
  135. }
  136. var attendance = await _unitOfWork.Attendance.GetAttendanceByUserId(id, DateTime.UtcNow.Date);
  137. response.IsCheckedIn = attendance != null && attendance.CheckInTime.HasValue;
  138. response.IsCheckedOut = attendance != null && attendance.CheckOutTime.HasValue;
  139. return response;
  140. }
  141. public async Task<UserUpdateDto> GetByIdForUpdate(string id)
  142. {
  143. var entity = await _userManager.Users
  144. .Include(x => x.UserRoles)
  145. .Include(x => x.UserAddress).ThenInclude(x => x.City)
  146. .Include(x => x.UserAddress).ThenInclude(x => x.Country)
  147. .Include(x => x.UserAttachments)
  148. .Include(x => x.JobTitle)
  149. .Include(x => x.Industry)
  150. .Include(x => x.University)
  151. .Include(x => x.Country)
  152. .Include(x => x.Qualification)
  153. .FirstOrDefaultAsync(x => x.Id == id);
  154. var response = MapperObject.Mapper.Map<UserUpdateDto>(entity);
  155. if (response.UserAttachments != null)
  156. foreach (var attach in response.UserAttachments)
  157. {
  158. switch (attach.AttachmentTypeId)
  159. {
  160. case 1:
  161. response.CVAttach = attach;
  162. break;
  163. case 2:
  164. response.PassportAttach = attach;
  165. break;
  166. case 3:
  167. response.EduCertificateAttach = attach;
  168. break;
  169. case 4:
  170. response.ExperienceCertificateAttach = attach;
  171. break;
  172. case 5:
  173. response.ProfCertificateAttach = attach;
  174. break;
  175. case 6:
  176. response.CommercialRegAttach = attach;
  177. break;
  178. case 7:
  179. response.TaxDeclarationAttach = attach;
  180. break;
  181. case 8:
  182. response.IdAttach = attach;
  183. break;
  184. case 9:
  185. response.ProfileImage = attach;
  186. response.ProfileImagePath = attach.FilePath;
  187. break;
  188. }
  189. attach.Content = new byte[0];
  190. }
  191. var attendance = await _unitOfWork.Attendance.GetAttendanceByUserId(id, DateTime.UtcNow.Date);
  192. response.IsCheckedIn = attendance != null && attendance.CheckInTime.HasValue;
  193. response.IsCheckedOut = attendance != null && attendance.CheckOutTime.HasValue;
  194. return response;
  195. }
  196. public async Task<EmployeeInfoDto> GetEmployeeInfo(string id)
  197. {
  198. var entity = await _userManager.Users
  199. .Include(x => x.UserRoles)
  200. .Include(x => x.UserAddress).ThenInclude(x => x.City)
  201. .Include(x => x.UserAddress).ThenInclude(x => x.Country)
  202. .Include(x => x.UserAttachments)
  203. .Include(x => x.JobTitle)
  204. .Include(x => x.Industry)
  205. .Include(x => x.University)
  206. .Include(x => x.Country)
  207. .Include(x => x.Qualification)
  208. .FirstOrDefaultAsync(x => x.Id == id);
  209. if(entity == null)
  210. {
  211. throw new AppException(ExceptionEnum.RecordNotExist);
  212. }
  213. var response = MapperObject.Mapper.Map<EmployeeInfoDto>(entity);
  214. if (entity.UserAttachments != null)
  215. foreach (var attach in entity.UserAttachments.Where(a => a.Content != null))
  216. {
  217. //var stream = new MemoryStream(attach.Content);
  218. //IFormFile file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName);
  219. using (var stream = new MemoryStream(attach.Content))
  220. {
  221. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
  222. {
  223. Headers = new HeaderDictionary(),
  224. ContentType = attach.ContentType,
  225. };
  226. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  227. {
  228. FileName = file.FileName
  229. };
  230. file.ContentDisposition = cd.ToString();
  231. switch (attach.AttachmentTypeId)
  232. {
  233. case 1:
  234. response.CVAttach = file;
  235. break;
  236. case 4:
  237. response.ExperienceCertificateAttach = file;
  238. break;
  239. case 5:
  240. response.ProfCertificateAttach = file;
  241. break;
  242. case 9:
  243. response.ProfileImage = file;
  244. response.ProfileImagePath = attach.FilePath;
  245. break;
  246. }
  247. attach.Content = new byte[0];
  248. }
  249. }
  250. return response;
  251. }
  252. public async Task<UserDto> GetUserById(string id)
  253. {
  254. var entity = await _userManager.Users
  255. .FirstOrDefaultAsync(x => x.Id == id);
  256. var response = MapperObject.Mapper.Map<UserDto>(entity);
  257. return response;
  258. }
  259. public async Task<string> GetUserFullName(string userId)
  260. {
  261. var entity = await GetUserById(userId);
  262. var name = $"{entity.FirstName} {entity.LastName}".Trim();
  263. return name;
  264. }
  265. public async Task<(string FullName, string Email)> GetUserNameEmail(string userId)
  266. {
  267. var entity = await GetUserById(userId);
  268. if (entity == null)
  269. return (string.Empty, string.Empty);
  270. var name = $"{entity.FirstName} {entity.LastName}".Trim();
  271. var email = entity.Email ?? string.Empty;
  272. return (name, email);
  273. }
  274. public async Task<UserDto> GetUserWithAttachmentById(string id)
  275. {
  276. var entity = await _userManager.Users.Include(u=> u.UserAttachments).Include(u=> u.JobTitle)
  277. .FirstOrDefaultAsync(x => x.Id == id);
  278. var response = MapperObject.Mapper.Map<UserDto>(entity);
  279. return response;
  280. }
  281. public async Task<List<UserDto>> GetUsersWithAttachmentsByIds(List<string> ids)
  282. {
  283. // Validate input
  284. if (ids == null || !ids.Any())
  285. {
  286. return new List<UserDto>();
  287. }
  288. // Query users with related data
  289. var users = await _userManager.Users
  290. .AsNoTracking() // Optional: Use if read-only data is sufficient
  291. .Include(u => u.UserAttachments)
  292. .Include(u => u.JobTitle)
  293. .Where(u => ids.Contains(u.Id))
  294. .ToListAsync();
  295. var response = MapperObject.Mapper.Map<List<UserDto>>(users);
  296. return response;
  297. }
  298. public async Task<string> GetProfileImage(string userId)
  299. {
  300. string imagePath = "";
  301. var user = await _userManager.Users.Include(u => u.UserAttachments)
  302. .FirstOrDefaultAsync(x => x.Id == userId);
  303. if (user != null)
  304. {
  305. var imageAtt = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  306. imagePath = imageAtt != null ? imageAtt.FilePath : "";
  307. }
  308. return imagePath;
  309. }
  310. //public async Task<List<UserDto>> GetAll(PagingInputDto pagingInput)
  311. //{
  312. // var employees = await _userManager.GetUsersInRoleAsync("Employee");
  313. // return employees.Select(e => new UserDto
  314. // {
  315. // Email = e.Email,
  316. // FirstName = e.FirstName,
  317. // LastName = e.LastName,
  318. // Id = e.Id
  319. // }).ToList();
  320. //}
  321. public virtual async Task<PagingResultDto<UserAllDto>> GetAll(UserPagingInputDto PagingInputDto)
  322. {
  323. var companies = await _unitOfWork.Company.GetAllAsync();
  324. var query = _userManager.Users
  325. .Include(u => u.Qualification)
  326. .Include(u => u.JobTitle)
  327. .Include(u => u.University)
  328. .Include(u => u.Industry)
  329. .Include(u => u.Country)
  330. .Where(u => !u.IsDeleted && !u.IsStopped && ( _globalInfo.CompanyId == null || u.CompanyId != _globalInfo.CompanyId));
  331. var filter = PagingInputDto.Filter?.Trim();
  332. // Filtering by text fields and handling full name search
  333. if (!string.IsNullOrEmpty(filter))
  334. {
  335. var filters = filter.Split(" ");
  336. var firstNameFilter = filters[0];
  337. var lastNameFilter = filters.Length > 1 ? filters[1] : "";
  338. query = query.Where(u =>
  339. u.UserName.Contains(filter) || u.Email.Contains(filter) || u.FavoriteName.Contains(filter) ||
  340. u.Position.Contains(filter) || u.PhoneNumber.Contains(filter) ||
  341. u.FirstName.Contains(firstNameFilter) && (string.IsNullOrEmpty(lastNameFilter) || u.LastName.Contains(lastNameFilter)) ||
  342. u.LastName.Contains(lastNameFilter) && (string.IsNullOrEmpty(firstNameFilter) || u.FirstName.Contains(firstNameFilter))
  343. );
  344. }
  345. // Applying additional filters
  346. if (PagingInputDto.IndustryId?.Count > 0)
  347. query = query.Where(u => u.IndustryId.HasValue && PagingInputDto.IndustryId.Contains(u.IndustryId.Value));
  348. if (PagingInputDto.QualificationId.HasValue)
  349. query = query.Where(u => u.QualificationId == PagingInputDto.QualificationId);
  350. if (PagingInputDto.JobTitleId.HasValue)
  351. query = query.Where(u => u.JobTitleId == PagingInputDto.JobTitleId);
  352. if (PagingInputDto.UniversityId.HasValue)
  353. query = query.Where(u => u.UniversityId == PagingInputDto.UniversityId);
  354. if (PagingInputDto.CountryId?.Count > 0)
  355. query = query.Where(u => u.CountryId.HasValue && PagingInputDto.CountryId.Contains(u.CountryId.Value));
  356. if (PagingInputDto.UserTypeId?.Count > 0)
  357. query = query.Where(u => PagingInputDto.UserTypeId.Contains(u.UserType));
  358. if (PagingInputDto.Employed.HasValue)
  359. query = query.Where(u => PagingInputDto.Employed.Value ? u.CompanyId != null : u.CompanyId == null);
  360. // Ordering by specified field and direction
  361. var orderByField = !string.IsNullOrEmpty(PagingInputDto.OrderByField) ? PagingInputDto.OrderByField : "UserName";
  362. var orderByDirection = PagingInputDto.OrderType?.ToLower() == "desc" ? "desc" : "asc";
  363. query = query.OrderBy($"{orderByField} {orderByDirection}");
  364. // Pagination
  365. var total = await query.CountAsync();
  366. var result = await query
  367. .Skip((PagingInputDto.PageNumber - 1) * PagingInputDto.PageSize)
  368. .Take(PagingInputDto.PageSize)
  369. .ToListAsync();
  370. var list = MapperObject.Mapper.Map<IList<UserAllDto>>(result);
  371. var ss = list
  372. .Join(companies.Item1, // Join the list with companies.Item1
  373. u => u.CompanyId, // Key selector for User (CompanyId)
  374. c => c.Id, // Key selector for Company (Id)
  375. (u, c) => { // Project the join result
  376. u.CompanyName = c.CompanyName; // Assuming 'Name' is the CompanyName in Company entity
  377. return u; // Return the updated UserAllDto with CompanyName filled
  378. })
  379. .ToList();
  380. return new PagingResultDto<UserAllDto> { Result = list, Total = total };
  381. }
  382. public async Task<List<UserDto>> GetAllEmployees()
  383. {
  384. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  385. return employees.Select(e => new UserDto
  386. {
  387. Email = e.Email,
  388. FirstName = e.FirstName,
  389. LastName = e.LastName,
  390. Id = e.Id
  391. }).ToList();
  392. }
  393. public async Task<List<UserAllDto>> GetAllCompanyEmployees()
  394. {
  395. var AllEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  396. var AllContractors = await _userManager.GetUsersInRoleAsync("Contractor");
  397. var employees = AllEmployees.Where(e => e.CompanyId == _globalInfo.CompanyId).ToList();
  398. var contractors = AllContractors.Where(e => e.CompanyId == _globalInfo.CompanyId).ToList();
  399. var allUsers = employees.Union(contractors);
  400. var response = MapperObject.Mapper.Map<List<UserAllDto>>(allUsers);
  401. return response;
  402. }
  403. public async Task<bool> UnAssignCompanyEmployees(long companyId)
  404. {
  405. try
  406. {
  407. var AllEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  408. var AllContractors = await _userManager.GetUsersInRoleAsync("Contractor");
  409. var employees = AllEmployees.Where(e => e.CompanyId == companyId).ToList();
  410. var contractors = AllContractors.Where(e => e.CompanyId == companyId).ToList();
  411. foreach (var emp in employees.Union(contractors))
  412. {
  413. emp.CompanyId = null;
  414. await _userManager.UpdateAsync(emp);
  415. }
  416. await _unitOfWork.CompleteAsync();
  417. return true;
  418. }
  419. catch(Exception ex)
  420. { return false; }
  421. }
  422. public async Task Delete(string id)
  423. {
  424. var user = await _userManager.FindByIdAsync(id);
  425. if (user == null)
  426. throw new AppException(ExceptionEnum.RecordNotExist);
  427. if (!user.IsDeleted )
  428. {
  429. user.IsDeleted = true;
  430. await _userManager.UpdateAsync(user);
  431. await _unitOfWork.CompleteAsync();
  432. }
  433. }
  434. public async Task Suspend(string id)
  435. {
  436. var user = await _userManager.FindByIdAsync(id);
  437. if (user == null)
  438. throw new AppException(ExceptionEnum.RecordNotExist);
  439. if (!user.IsStopped)
  440. {
  441. user.IsStopped = true;
  442. await _userManager.UpdateAsync(user);
  443. await _unitOfWork.CompleteAsync();
  444. }
  445. }
  446. public async Task ActiveUser(string userId)
  447. {
  448. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  449. if (entity == null)
  450. throw new AppException(ExceptionEnum.RecordNotExist);
  451. entity.IsStopped = false;
  452. entity.AccessFailedCount = 0;
  453. entity.LockoutEnabled = false;
  454. entity.LockoutEnd = null;
  455. await _userManager.UpdateAsync(entity);
  456. await _unitOfWork.CompleteAsync();
  457. }
  458. public async Task<UserDto> Create(UserDto input)
  459. {
  460. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  461. if (emailExists != null)
  462. throw new AppException(ExceptionEnum.RecordEmailAlreadyExist);
  463. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  464. if (phoneExists != null)
  465. throw new AppException(ExceptionEnum.RecordPhoneAlreadyExist);
  466. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  467. if (userExists != null)
  468. throw new AppException(ExceptionEnum.RecordNameAlreadyExist);
  469. //loop for given list of attachment, and move each file from Temp path to Actual path
  470. // _fileService.UploadFiles(files);
  471. input.CountryId = input.CountryId == null || input.CountryId == 0 ? input.UserAddress?.CountryId : input.CountryId;
  472. if (input.UserAttachments == null)
  473. input.UserAttachments = new List<AttachmentDto>();
  474. if (input.ProfileImage != null)
  475. {
  476. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  477. }
  478. if (input.CVAttach != null)
  479. {
  480. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name, FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  481. }
  482. if (input.PassportAttach != null)
  483. {
  484. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  485. }
  486. if (input.EduCertificateAttach != null)
  487. {
  488. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  489. }
  490. if (input.ExperienceCertificateAttach != null)
  491. {
  492. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  493. }
  494. if (input.ProfCertificateAttach != null)
  495. {
  496. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  497. }
  498. var files = input.UserAttachments.Select(a=> a.FileData).ToList();
  499. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  500. if(attachs != null && attachs.Count > 0)
  501. _fileService.CopyFileToCloud(ref attachs);
  502. //if (!res)
  503. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  504. input.UserAttachments = attachs;
  505. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  506. if(user.UserType == 0)
  507. {
  508. user.UserType = (int)UserTypeEnum.Employee;//default if not selected
  509. }
  510. _unitOfWork.BeginTran();
  511. user.CreateDate = DateTime.UtcNow;
  512. //saving user
  513. var result = await _userManager.CreateAsync(user, input.Password);
  514. if (!result.Succeeded)
  515. {
  516. if(result.Errors != null && result.Errors.Count() > 0)
  517. {
  518. var msg = result.Errors.Select(a => a.Description ).Aggregate((a,b) => a + " /r/n " + b);
  519. throw new AppException(msg);
  520. }
  521. throw new AppException(ExceptionEnum.RecordCreationFailed);
  522. }
  523. input.Id = user.Id;
  524. //saving userRoles
  525. if(input.UserRoles == null || input.UserRoles.Count == 0)
  526. {
  527. if(user.UserType == (int)UserTypeEnum.Employee)
  528. {
  529. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  530. if (employeeRole != null)
  531. {
  532. await _userManager.AddToRoleAsync(user, "Employee");
  533. }
  534. }
  535. else if (user.UserType == (int)UserTypeEnum.Contractor)
  536. {
  537. var employeeRole = await _roleManager.FindByNameAsync("Contractor");
  538. if (employeeRole != null)
  539. {
  540. await _userManager.AddToRoleAsync(user, "Contractor");
  541. }
  542. }
  543. }
  544. else
  545. {
  546. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  547. foreach (var role in userRoles)
  548. {
  549. role.UserId = user.Id;
  550. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  551. throw new AppException(ExceptionEnum.RecordNotExist);
  552. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  553. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  554. await _userManager.AddToRoleAsync(user, roleName);
  555. }
  556. }
  557. // await _userRole.AddRangeAsync(userRoles);
  558. await _unitOfWork.CompleteAsync();
  559. _unitOfWork.CommitTran();
  560. try
  561. {
  562. var resultPassReset = await GetConfirmEmailURL(user.Id);
  563. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  564. {
  565. Subject = "Register Confirmation",
  566. To = input.Email,
  567. Body = "Please Set Your Password (this link will expired after 24 hours)"
  568. ,
  569. url = resultPassReset.Item1,
  570. userId = user.Id
  571. });
  572. if (!sendMailResult)
  573. {
  574. _logger.LogError("User created, but could not send the email!");
  575. throw new AppException("User created, but could not send the email!");
  576. }
  577. }
  578. catch(Exception ex)
  579. {
  580. _logger.LogError(ex.Message);
  581. throw new AppException("User created, but could not send the email!");
  582. }
  583. return input;
  584. }
  585. public async Task<BlobObject> Download(string filePath)
  586. {
  587. var file = await _fileService.Download(filePath);
  588. return file;
  589. }
  590. public async Task<bool> ConfirmEmail(ConfirmEmailDto input)
  591. {
  592. var user = await _userManager.FindByIdAsync(input.UserId);
  593. if (user == null)
  594. throw new AppException(ExceptionEnum.UserNotExist);
  595. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  596. return result.Succeeded;
  597. }
  598. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  599. {
  600. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  601. if (user == null)
  602. throw new AppException(ExceptionEnum.UserNotExist);
  603. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  604. var route = "auth/ConfirmEmail";
  605. var origin = _configuration.JwtSettings.Audience;
  606. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  607. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  608. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  609. return new Tuple<string, string>(passwordResetURL, user.Email);
  610. }
  611. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  612. {
  613. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  614. if (user == null)
  615. throw new AppException(ExceptionEnum.UserNotExist);
  616. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  617. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  618. var route = "auth/ConfirmEmail";
  619. var origin = _configuration.JwtSettings.Audience;
  620. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  621. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  622. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  623. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  624. }
  625. public async Task<UserUpdateDto> Update(UserUpdateDto input)
  626. {
  627. try
  628. {
  629. var entity = await _userManager.Users
  630. .Include(x => x.UserAttachments)
  631. .FirstOrDefaultAsync(x => x.Id == input.Id);
  632. if (entity == null)
  633. throw new AppException(ExceptionEnum.UserNotExist);
  634. input.UserAttachments = new List<AttachmentDto>();
  635. var oldAttachList = entity.UserAttachments;
  636. // Process each attachment type
  637. ProcessAttachment(oldAttachList, input.UserAttachments, input.ProfileImage, 9);
  638. ProcessAttachment(oldAttachList, input.UserAttachments, input.CVAttach, 1);
  639. ProcessAttachment(oldAttachList, input.UserAttachments, input.PassportAttach, 2);
  640. ProcessAttachment(oldAttachList, input.UserAttachments, input.EduCertificateAttach, 3);
  641. ProcessAttachment(oldAttachList, input.UserAttachments, input.ExperienceCertificateAttach, 4);
  642. ProcessAttachment(oldAttachList, input.UserAttachments, input.ProfCertificateAttach, 5);
  643. // Cloud copy
  644. List<AttachmentDto> attachments = input.UserAttachments.ToList();
  645. _fileService.CopyFileToCloud(ref attachments);
  646. input.UserAttachments = attachments;
  647. // Map updated input to entity
  648. MapperObject.Mapper.Map(input, entity);
  649. entity.UpdateDate = DateTime.UtcNow;
  650. _unitOfWork.BeginTran();
  651. var result = await _userManager.UpdateAsync(entity);
  652. if (!result.Succeeded)
  653. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  654. await _unitOfWork.CompleteAsync();
  655. _unitOfWork.CommitTran();
  656. }
  657. catch (Exception e)
  658. {
  659. throw e;
  660. }
  661. // Return updated user
  662. var userResponse = await GetByIdForUpdate(input.Id);
  663. return userResponse;
  664. }
  665. private void ProcessAttachment(ICollection<UserAttachment> oldAttachments, IList<AttachmentDto> newAttachments, AttachmentDto attachment,int attachmentTypeId)
  666. {
  667. if (attachment == null)
  668. return;
  669. var oldAttach = oldAttachments
  670. .FirstOrDefault(x => x.AttachmentTypeId == attachmentTypeId || x.FileName == attachment.FileName);
  671. if (oldAttach != null)
  672. oldAttachments.Remove(oldAttach);
  673. newAttachments.Add(new AttachmentDto
  674. {
  675. FilePath = attachment.FilePath,
  676. OriginalName = string.IsNullOrEmpty( attachment.OriginalName) ? attachment.FileName : attachment.OriginalName,
  677. FileName = attachment.FileName,
  678. AttachmentTypeId = attachmentTypeId
  679. });
  680. }
  681. //public async Task<UserUpdateDto> Update2(UserUpdateDto input)
  682. //{
  683. // try
  684. // {
  685. // var entity = _userManager.Users.Include(x => x.UserAttachments).FirstOrDefault(x=> x.Id == input.Id);
  686. // if (entity == null)
  687. // throw new AppException(ExceptionEnum.UserNotExist);
  688. // if (input.UserAttachments == null)
  689. // input.UserAttachments = new List<AttachmentDto>();
  690. // var oldAttachList = entity.UserAttachments;
  691. // if (input.ProfileImage != null)
  692. // {
  693. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 9 || x.OriginalName == input.ProfileImage?.Name).FirstOrDefault();
  694. // if(oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  695. // input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  696. // }
  697. // if (input.CVAttach != null)
  698. // {
  699. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 1 || x.OriginalName == input.CVAttach?.Name).FirstOrDefault();
  700. // if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  701. // input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name, FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  702. // }
  703. // if (input.PassportAttach != null)
  704. // {
  705. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 2 || x.OriginalName == input.PassportAttach?.Name).FirstOrDefault();
  706. // if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  707. // input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  708. // }
  709. // if (input.EduCertificateAttach != null)
  710. // {
  711. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 3 || x.OriginalName == input.EduCertificateAttach?.Name).FirstOrDefault();
  712. // if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  713. // input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  714. // }
  715. // if (input.ExperienceCertificateAttach != null)
  716. // {
  717. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 4 || x.OriginalName == input.ExperienceCertificateAttach?.Name).FirstOrDefault();
  718. // if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  719. // input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  720. // }
  721. // if (input.ProfCertificateAttach != null)
  722. // {
  723. // var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 5 || x.OriginalName == input.ProfCertificateAttach?.Name).FirstOrDefault();
  724. // if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  725. // input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  726. // }
  727. // List<AttachmentDto> attachs = input.UserAttachments.ToList();
  728. // _fileService.CopyFileToCloud(ref attachs);
  729. // input.UserAttachments = attachs;
  730. // //if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  731. // // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  732. // MapperObject.Mapper.Map(input, entity);
  733. // _unitOfWork.BeginTran();
  734. // entity.UpdateDate = DateTime.UtcNow;
  735. // //saving user
  736. // var result = await _userManager.UpdateAsync(entity);
  737. // if (!result.Succeeded)
  738. // throw new AppException(ExceptionEnum.RecordUpdateFailed);
  739. // await _unitOfWork.CompleteAsync();
  740. // _unitOfWork.CommitTran();
  741. // }
  742. // catch (Exception e)
  743. // {
  744. // throw e;
  745. // }
  746. // var userResponse = await GetById(input.Id);
  747. // var user = MapperObject.Mapper.Map<UserUpdateDto>(userResponse);
  748. // return user;
  749. //}
  750. public async Task<bool> Update(string userId, long companyId)
  751. {
  752. try
  753. {
  754. var entity = _userManager.Users.FirstOrDefault(x => x.Id == userId);
  755. if (entity == null)
  756. throw new AppException(ExceptionEnum.UserNotExist);
  757. entity.CompanyId = companyId;
  758. entity.UpdateDate = DateTime.UtcNow;
  759. //saving user
  760. var result = await _userManager.UpdateAsync(entity);
  761. if (!result.Succeeded)
  762. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  763. await _unitOfWork.CompleteAsync();
  764. return true;
  765. }
  766. catch (Exception e)
  767. {
  768. throw e;
  769. }
  770. }
  771. public async Task<bool> IsExpiredToken(ConfirmEmailDto input)
  772. {
  773. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  774. if (user == null)
  775. throw new AppException(ExceptionEnum.UserNotExist);
  776. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  777. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  778. return !result;
  779. }
  780. public async Task<bool> ResetPassword(ResetPasswordDto input)
  781. {
  782. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  783. if (user == null)
  784. throw new AppException(ExceptionEnum.UserNotExist);
  785. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  786. throw new AppException(ExceptionEnum.WrongCredentials);
  787. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  788. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  789. if (!result.Succeeded)
  790. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  791. return true;
  792. }
  793. public async Task<ForgetPasswordResponseDto> ForgetPasswordMail(string email) //Begin forget password
  794. {
  795. var foundUser = await _userManager.FindByEmailAsync(email);
  796. if (foundUser != null)
  797. {
  798. string oneTimePassword = await _oTPService.RandomOneTimePassword(foundUser.Id);
  799. await _oTPService.SentOTPByMail(foundUser.Id, foundUser.Email, oneTimePassword);
  800. ForgetPasswordResponseDto res = new ForgetPasswordResponseDto { UserId = foundUser.Id};
  801. return res;
  802. }
  803. else
  804. {
  805. throw new AppException(ExceptionEnum.UserNotExist);
  806. }
  807. }
  808. public async Task<bool> VerifyOTP(VerifyOTPDto input)
  809. {
  810. if (! await _oTPService.VerifyOTP(input.UserId, input.OTP))
  811. throw new AppException(ExceptionEnum.WrongOTP);
  812. return true;
  813. }
  814. public async Task<bool> ForgetPassword(ForgetPasswordDto input)
  815. {
  816. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  817. if (user == null)
  818. throw new AppException(ExceptionEnum.UserNotExist);
  819. string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
  820. var result = await _userManager.ResetPasswordAsync(user, resetToken, input.Password);
  821. if (!result.Succeeded)
  822. {
  823. if (result.Errors != null && result.Errors.Count() > 0)
  824. {
  825. var msg = result.Errors.Select(a => a.Description).Aggregate((a, b) => a + " /r/n " + b);
  826. throw new AppException(msg);
  827. }
  828. throw new AppException(ExceptionEnum.RecordCreationFailed);
  829. }
  830. return result.Succeeded;
  831. }
  832. public async Task StopUser(string userId)
  833. {
  834. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  835. if (entity == null)
  836. throw new AppException(ExceptionEnum.UserNotExist);
  837. if (!entity.IsStopped)
  838. {
  839. entity.IsStopped = true;
  840. await _unitOfWork.CompleteAsync();
  841. }
  842. }
  843. public async Task<JobInterviewDto> SetUpInterview(JobInterviewDto input)
  844. {
  845. var foundUser = await _userManager.FindByEmailAsync(input.Email);
  846. if (foundUser != null)
  847. {
  848. if (input.SendByMail.HasValue && input.SendByMail.Value)
  849. {
  850. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  851. {
  852. Subject = "Interview meeting link",
  853. To = input.Email,
  854. Body = "Please attend the job interview by using the following link"
  855. ,
  856. url = input.InterviewLink,
  857. userId = foundUser.Id
  858. });
  859. if (!sendMailResult)
  860. {
  861. throw new AppException("could not send the email!");
  862. }
  863. }
  864. input.UserId = foundUser.Id;
  865. var jobInterview = MapperObject.Mapper.Map<JobInterview>(input);
  866. var result = await _unitOfWork.JobInterview.AddAsync(jobInterview);
  867. await _unitOfWork.CompleteAsync();
  868. var res = MapperObject.Mapper.Map<JobInterviewDto>(result);
  869. return res;
  870. }
  871. else
  872. {
  873. throw new AppException(ExceptionEnum.UserNotExist);
  874. }
  875. }
  876. }
  877. }