UserService.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. namespace MTWorkHR.Application.Services
  28. {
  29. public class UserService : IUserService
  30. {
  31. private readonly RoleManager<ApplicationRole> _roleManager;
  32. private readonly ApplicationUserManager _userManager;
  33. private readonly IUnitOfWork _unitOfWork;
  34. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  35. private readonly AppSettingsConfiguration _configuration;
  36. private readonly IMailSender _emailSender;
  37. private readonly GlobalInfo _globalInfo;
  38. private readonly IFileService _fileService;
  39. private readonly IOTPService _oTPService;
  40. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  41. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IMailSender emailSender
  42. , IUserRoleRepository<IdentityUserRole<string>> userRole, IFileService fileService, IOTPService oTPService)
  43. {
  44. _userManager = userManager;
  45. _unitOfWork = unitOfWork;
  46. _roleManager = roleManager;
  47. _userRole = userRole;
  48. _configuration = configuration;
  49. _emailSender = emailSender;
  50. _globalInfo = globalInfo;
  51. _fileService = fileService;
  52. _oTPService = oTPService;
  53. }
  54. public async Task<UserDto> GetById()
  55. {
  56. return await GetById(_globalInfo.UserId);
  57. }
  58. public async Task<UserDto> GetByEmail(string email)
  59. {
  60. var user = _userManager.Users.FirstOrDefault(x => x.Email == email);
  61. if(user == null)
  62. throw new AppException(ExceptionEnum.UserNotExist);
  63. return await GetById(user.Id);
  64. }
  65. public async Task<UserDto> GetById(string id)
  66. {
  67. var entity = await _userManager.Users
  68. .Include(x => x.UserRoles)
  69. .Include(x => x.UserAddress).ThenInclude(x=> x.City)
  70. .Include(x => x.UserAddress).ThenInclude(x=> x.Country)
  71. .Include(x => x.UserAttachments)
  72. .Include(x => x.JobTitle)
  73. .Include(x => x.Industry)
  74. .Include(x => x.University)
  75. .Include(x => x.Country)
  76. .Include(x => x.Qualification)
  77. .FirstOrDefaultAsync(x => x.Id == id);
  78. var response = MapperObject.Mapper.Map<UserDto>(entity);
  79. if (response.UserAttachments != null)
  80. foreach (var attach in response.UserAttachments.Where(a => a.Content != null))
  81. {
  82. //var stream = new MemoryStream(attach.Content);
  83. //IFormFile file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName);
  84. using (var stream = new MemoryStream(attach.Content))
  85. {
  86. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
  87. {
  88. Headers = new HeaderDictionary(),
  89. ContentType = attach.ContentType,
  90. };
  91. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  92. {
  93. FileName = file.FileName
  94. };
  95. file.ContentDisposition = cd.ToString();
  96. switch (attach.AttachmentTypeId)
  97. {
  98. case 1:
  99. response.CVAttach = file;
  100. break;
  101. case 2:
  102. response.PassportAttach = file;
  103. break;
  104. case 3:
  105. response.EduCertificateAttach = file;
  106. break;
  107. case 4:
  108. response.ExperienceCertificateAttach= file;
  109. break;
  110. case 5:
  111. response.ProfCertificateAttach = file;
  112. break;
  113. case 6:
  114. response.CommercialRegAttach = file;
  115. break;
  116. case 7:
  117. response.TaxDeclarationAttach = file;
  118. break;
  119. case 8:
  120. response.IdAttach = file;
  121. break;
  122. case 9:
  123. response.ProfileImage = file;
  124. break;
  125. }
  126. attach.Content = new byte[0];
  127. }
  128. }
  129. var attendance = await _unitOfWork.Attendance.GetAttendanceByUserId(id, DateTime.Now.Date);
  130. response.IsCheckedIn = attendance != null && attendance.CheckInTime.HasValue;
  131. response.IsCheckedOut = attendance != null && attendance.CheckOutTime.HasValue;
  132. return response;
  133. }
  134. public async Task<UserDto> GetUserById(string id)
  135. {
  136. var entity = await _userManager.Users
  137. .FirstOrDefaultAsync(x => x.Id == id);
  138. var response = MapperObject.Mapper.Map<UserDto>(entity);
  139. return response;
  140. }
  141. public async Task<string> GetUserFullName(string userId)
  142. {
  143. var entity = await GetUserById(userId);
  144. var name = entity == null ? "" : entity.FirstName + " " + entity.LastName;
  145. return name;
  146. }
  147. public async Task<UserDto> GetUserWithAttachmentById(string id)
  148. {
  149. var entity = await _userManager.Users.Include(u=> u.UserAttachments)
  150. .FirstOrDefaultAsync(x => x.Id == id);
  151. var response = MapperObject.Mapper.Map<UserDto>(entity);
  152. return response;
  153. }
  154. public async Task<string> GetProfileImage(string userId)
  155. {
  156. string imagePath = null;
  157. var user = await _userManager.Users.Include(u => u.UserAttachments)
  158. .FirstOrDefaultAsync(x => x.Id == userId);
  159. if (user != null)
  160. {
  161. var imageAtt = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  162. imagePath = imageAtt != null ? imageAtt.FilePath : "";
  163. }
  164. return imagePath;
  165. }
  166. //public async Task<List<UserDto>> GetAll(PagingInputDto pagingInput)
  167. //{
  168. // var employees = await _userManager.GetUsersInRoleAsync("Employee");
  169. // return employees.Select(e => new UserDto
  170. // {
  171. // Email = e.Email,
  172. // FirstName = e.FirstName,
  173. // LastName = e.LastName,
  174. // Id = e.Id
  175. // }).ToList();
  176. //}
  177. public virtual async Task<PagingResultDto<UserAllDto>> GetAll(UserPagingInputDto PagingInputDto)
  178. {
  179. var companies = await _unitOfWork.Company.GetAllAsync();
  180. var query = _userManager.Users
  181. .Include(u => u.Qualification)
  182. .Include(u => u.JobTitle)
  183. .Include(u => u.University)
  184. .Include(u => u.Industry)
  185. .Include(u => u.Country)
  186. .Where(u => !u.IsDeleted && !u.IsStopped && ( _globalInfo.CompanyId == null || u.CompanyId != _globalInfo.CompanyId));
  187. var filter = PagingInputDto.Filter?.Trim();
  188. // Filtering by text fields and handling full name search
  189. if (!string.IsNullOrEmpty(filter))
  190. {
  191. var filters = filter.Split(" ");
  192. var firstNameFilter = filters[0];
  193. var lastNameFilter = filters.Length > 1 ? filters[1] : "";
  194. query = query.Where(u =>
  195. u.UserName.Contains(filter) || u.Email.Contains(filter) || u.FavoriteName.Contains(filter) ||
  196. u.Position.Contains(filter) || u.PhoneNumber.Contains(filter) ||
  197. u.FirstName.Contains(firstNameFilter) && (string.IsNullOrEmpty(lastNameFilter) || u.LastName.Contains(lastNameFilter)) ||
  198. u.LastName.Contains(lastNameFilter) && (string.IsNullOrEmpty(firstNameFilter) || u.FirstName.Contains(firstNameFilter))
  199. );
  200. }
  201. // Applying additional filters
  202. if (PagingInputDto.IndustryId?.Count > 0)
  203. query = query.Where(u => u.IndustryId.HasValue && PagingInputDto.IndustryId.Contains(u.IndustryId.Value));
  204. if (PagingInputDto.QualificationId.HasValue)
  205. query = query.Where(u => u.QualificationId == PagingInputDto.QualificationId);
  206. if (PagingInputDto.JobTitleId.HasValue)
  207. query = query.Where(u => u.JobTitleId == PagingInputDto.JobTitleId);
  208. if (PagingInputDto.UniversityId.HasValue)
  209. query = query.Where(u => u.UniversityId == PagingInputDto.UniversityId);
  210. if (PagingInputDto.CountryId?.Count > 0)
  211. query = query.Where(u => u.CountryId.HasValue && PagingInputDto.CountryId.Contains(u.CountryId.Value));
  212. if (PagingInputDto.UserTypeId?.Count > 0)
  213. query = query.Where(u => PagingInputDto.UserTypeId.Contains(u.UserType));
  214. if (PagingInputDto.Employed.HasValue)
  215. query = query.Where(u => PagingInputDto.Employed.Value ? u.CompanyId != null : u.CompanyId == null);
  216. // Ordering by specified field and direction
  217. var orderByField = !string.IsNullOrEmpty(PagingInputDto.OrderByField) ? PagingInputDto.OrderByField : "UserName";
  218. var orderByDirection = PagingInputDto.OrderType?.ToLower() == "desc" ? "desc" : "asc";
  219. query = query.OrderBy($"{orderByField} {orderByDirection}");
  220. // Pagination
  221. var total = await query.CountAsync();
  222. var result = await query
  223. .Skip((PagingInputDto.PageNumber - 1) * PagingInputDto.PageSize)
  224. .Take(PagingInputDto.PageSize)
  225. .ToListAsync();
  226. var list = MapperObject.Mapper.Map<IList<UserAllDto>>(result);
  227. var ss = list
  228. .Join(companies.Item1, // Join the list with companies.Item1
  229. u => u.CompanyId, // Key selector for User (CompanyId)
  230. c => c.Id, // Key selector for Company (Id)
  231. (u, c) => { // Project the join result
  232. u.CompanyName = c.CompanyName; // Assuming 'Name' is the CompanyName in Company entity
  233. return u; // Return the updated UserAllDto with CompanyName filled
  234. })
  235. .ToList();
  236. return new PagingResultDto<UserAllDto> { Result = list, Total = total };
  237. }
  238. public async Task<List<UserDto>> GetAllEmployees()
  239. {
  240. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  241. return employees.Select(e => new UserDto
  242. {
  243. Email = e.Email,
  244. FirstName = e.FirstName,
  245. LastName = e.LastName,
  246. Id = e.Id
  247. }).ToList();
  248. }
  249. public async Task<List<UserAllDto>> GetAllCompanyEmployees()
  250. {
  251. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  252. var res = employees.Where(e => e.CompanyId == _globalInfo.CompanyId).ToList();
  253. var response = MapperObject.Mapper.Map<List<UserAllDto>>(res);
  254. return response;
  255. }
  256. public async Task<bool> UnAssignCompanyEmployees(long companyId)
  257. {
  258. try
  259. {
  260. var AllEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  261. var AllContractors = await _userManager.GetUsersInRoleAsync("Contractor");
  262. var employees = AllEmployees.Where(e => e.CompanyId == companyId).ToList();
  263. var contractors = AllContractors.Where(e => e.CompanyId == companyId).ToList();
  264. foreach (var emp in employees.Union(contractors))
  265. {
  266. emp.CompanyId = null;
  267. await _userManager.UpdateAsync(emp);
  268. }
  269. await _unitOfWork.CompleteAsync();
  270. return true;
  271. }
  272. catch(Exception ex)
  273. { return false; }
  274. }
  275. public async Task Delete(string id)
  276. {
  277. var user = await _userManager.FindByIdAsync(id);
  278. if (user == null)
  279. throw new AppException(ExceptionEnum.RecordNotExist);
  280. if (!user.IsDeleted )
  281. {
  282. user.IsDeleted = true;
  283. await _userManager.UpdateAsync(user);
  284. await _unitOfWork.CompleteAsync();
  285. }
  286. }
  287. public async Task Suspend(string id)
  288. {
  289. var user = await _userManager.FindByIdAsync(id);
  290. if (user == null)
  291. throw new AppException(ExceptionEnum.RecordNotExist);
  292. if (!user.IsStopped)
  293. {
  294. user.IsStopped = true;
  295. await _userManager.UpdateAsync(user);
  296. await _unitOfWork.CompleteAsync();
  297. }
  298. }
  299. public async Task ActiveUser(string userId)
  300. {
  301. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  302. if (entity == null)
  303. throw new AppException(ExceptionEnum.RecordNotExist);
  304. entity.IsStopped = false;
  305. entity.AccessFailedCount = 0;
  306. entity.LockoutEnabled = false;
  307. entity.LockoutEnd = null;
  308. await _userManager.UpdateAsync(entity);
  309. await _unitOfWork.CompleteAsync();
  310. }
  311. public async Task<UserDto> Create(UserDto input)
  312. {
  313. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  314. if (emailExists != null)
  315. throw new AppException(ExceptionEnum.RecordEmailAlreadyExist);
  316. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  317. if (phoneExists != null)
  318. throw new AppException(ExceptionEnum.RecordPhoneAlreadyExist);
  319. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  320. if (userExists != null)
  321. throw new AppException(ExceptionEnum.RecordNameAlreadyExist);
  322. //loop for given list of attachment, and move each file from Temp path to Actual path
  323. // _fileService.UploadFiles(files);
  324. input.CountryId = input.CountryId == null || input.CountryId == 0 ? input.UserAddress?.CountryId : input.CountryId;
  325. if (input.UserAttachments == null )
  326. input.UserAttachments = new List<AttachmentDto>();
  327. if (input.ProfileImage != null)
  328. {
  329. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  330. }
  331. if (input.CVAttach != null)
  332. {
  333. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name,FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  334. }
  335. if (input.PassportAttach != null)
  336. {
  337. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  338. }
  339. if (input.EduCertificateAttach != null)
  340. {
  341. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  342. }
  343. if (input.ExperienceCertificateAttach != null)
  344. {
  345. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  346. }
  347. if (input.ProfCertificateAttach != null)
  348. {
  349. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  350. }
  351. var files = input.UserAttachments.Select(a=> a.FileData).ToList();
  352. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  353. _fileService.CopyFileToCloud(ref attachs);
  354. //if (!res)
  355. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  356. input.UserAttachments = attachs;
  357. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  358. if(user.UserType == 0)
  359. {
  360. user.UserType = (int)UserTypeEnum.Employee;//default if not selected
  361. }
  362. _unitOfWork.BeginTran();
  363. user.CreateDate = DateTime.Now;
  364. //saving user
  365. var result = await _userManager.CreateAsync(user, input.Password);
  366. if (!result.Succeeded)
  367. {
  368. if(result.Errors != null && result.Errors.Count() > 0)
  369. {
  370. var msg = result.Errors.Select(a => a.Description ).Aggregate((a,b) => a + " /r/n " + b);
  371. throw new AppException(msg);
  372. }
  373. throw new AppException(ExceptionEnum.RecordCreationFailed);
  374. }
  375. input.Id = user.Id;
  376. //saving userRoles
  377. if(input.UserRoles == null || input.UserRoles.Count == 0)
  378. {
  379. if(user.UserType == (int)UserTypeEnum.Employee)
  380. {
  381. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  382. if (employeeRole != null)
  383. {
  384. await _userManager.AddToRoleAsync(user, "Employee");
  385. }
  386. }
  387. else if (user.UserType == (int)UserTypeEnum.Contractor)
  388. {
  389. var employeeRole = await _roleManager.FindByNameAsync("Contractor");
  390. if (employeeRole != null)
  391. {
  392. await _userManager.AddToRoleAsync(user, "Contractor");
  393. }
  394. }
  395. }
  396. else
  397. {
  398. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  399. foreach (var role in userRoles)
  400. {
  401. role.UserId = user.Id;
  402. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  403. throw new AppException(ExceptionEnum.RecordNotExist);
  404. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  405. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  406. await _userManager.AddToRoleAsync(user, roleName);
  407. }
  408. }
  409. // await _userRole.AddRangeAsync(userRoles);
  410. await _unitOfWork.CompleteAsync();
  411. _unitOfWork.CommitTran();
  412. try
  413. {
  414. var resultPassReset = await GetConfirmEmailURL(user.Id);
  415. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  416. {
  417. Subject = "Register Confirmation",
  418. To = input.Email,
  419. Body = "Please Set Your Password (this link will expired after 24 hours)"
  420. ,
  421. url = resultPassReset.Item1,
  422. userId = user.Id
  423. });
  424. if (!sendMailResult)
  425. {
  426. throw new AppException("User created, but could not send the email!");
  427. }
  428. }
  429. catch
  430. {
  431. throw new AppException("User created, but could not send the email!");
  432. }
  433. return input;
  434. }
  435. public async Task<BlobObject> Download(string filePath)
  436. {
  437. var file = await _fileService.Download(filePath);
  438. return file;
  439. }
  440. public async Task<bool> ConfirmEmail(ConfirmEmailDto input)
  441. {
  442. var user = await _userManager.FindByIdAsync(input.UserId);
  443. if (user == null)
  444. throw new AppException(ExceptionEnum.UserNotExist);
  445. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  446. return result.Succeeded;
  447. }
  448. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  449. {
  450. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  451. if (user == null)
  452. throw new AppException(ExceptionEnum.UserNotExist);
  453. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  454. var route = "auth/ConfirmEmail";
  455. var origin = _configuration.JwtSettings.Audience;
  456. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  457. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  458. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  459. return new Tuple<string, string>(passwordResetURL, user.Email);
  460. }
  461. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  462. {
  463. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  464. if (user == null)
  465. throw new AppException(ExceptionEnum.UserNotExist);
  466. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  467. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  468. var route = "auth/ConfirmEmail";
  469. var origin = _configuration.JwtSettings.Audience;
  470. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  471. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  472. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  473. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  474. }
  475. public async Task<UserUpdateDto> Update(UserUpdateDto input)
  476. {
  477. try
  478. {
  479. var entity = _userManager.Users.Include(x => x.UserAttachments).FirstOrDefault(x=> x.Id == input.Id);
  480. if (entity == null)
  481. throw new AppException(ExceptionEnum.UserNotExist);
  482. if (input.UserAttachments == null)
  483. input.UserAttachments = new List<AttachmentDto>();
  484. var oldAttachList = entity.UserAttachments;
  485. if (input.ProfileImage != null)
  486. {
  487. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 9 || x.OriginalName == input.ProfileImage?.Name).FirstOrDefault();
  488. if(oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  489. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  490. }
  491. if (input.CVAttach != null)
  492. {
  493. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 1 || x.OriginalName == input.CVAttach?.Name).FirstOrDefault();
  494. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  495. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name, FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  496. }
  497. if (input.PassportAttach != null)
  498. {
  499. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 2 || x.OriginalName == input.PassportAttach?.Name).FirstOrDefault();
  500. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  501. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  502. }
  503. if (input.EduCertificateAttach != null)
  504. {
  505. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 3 || x.OriginalName == input.EduCertificateAttach?.Name).FirstOrDefault();
  506. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  507. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  508. }
  509. if (input.ExperienceCertificateAttach != null)
  510. {
  511. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 4 || x.OriginalName == input.ExperienceCertificateAttach?.Name).FirstOrDefault();
  512. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  513. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  514. }
  515. if (input.ProfCertificateAttach != null)
  516. {
  517. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 5 || x.OriginalName == input.ProfCertificateAttach?.Name).FirstOrDefault();
  518. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  519. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  520. }
  521. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  522. _fileService.CopyFileToCloud(ref attachs);
  523. input.UserAttachments = attachs;
  524. //if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  525. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  526. MapperObject.Mapper.Map(input, entity);
  527. _unitOfWork.BeginTran();
  528. entity.UpdateDate = DateTime.Now;
  529. //saving user
  530. var result = await _userManager.UpdateAsync(entity);
  531. if (!result.Succeeded)
  532. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  533. //**saving userRoles
  534. //add new user roles
  535. //var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  536. //if (input.UserRoles == null)
  537. // input.UserRoles = new List<UserRoleDto>();
  538. //var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  539. //newAddedRoles.ForEach(x => x.UserId = input.Id);
  540. //await _userRole.AddRangeAsync(newAddedRoles);
  541. ////delete removed roles
  542. //var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  543. //var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  544. //await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  545. await _unitOfWork.CompleteAsync();
  546. _unitOfWork.CommitTran();
  547. }
  548. catch (Exception e)
  549. {
  550. throw e;
  551. }
  552. var userResponse = await GetById(input.Id);
  553. var user = MapperObject.Mapper.Map<UserUpdateDto>(userResponse);
  554. return user;
  555. }
  556. public async Task<bool> Update(string userId, long companyId)
  557. {
  558. try
  559. {
  560. var entity = _userManager.Users.FirstOrDefault(x => x.Id == userId);
  561. if (entity == null)
  562. throw new AppException(ExceptionEnum.UserNotExist);
  563. entity.CompanyId = companyId;
  564. entity.UpdateDate = DateTime.Now;
  565. //saving user
  566. var result = await _userManager.UpdateAsync(entity);
  567. if (!result.Succeeded)
  568. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  569. await _unitOfWork.CompleteAsync();
  570. return true;
  571. }
  572. catch (Exception e)
  573. {
  574. throw e;
  575. }
  576. }
  577. public async Task<bool> IsExpiredToken(ConfirmEmailDto input)
  578. {
  579. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  580. if (user == null)
  581. throw new AppException(ExceptionEnum.UserNotExist);
  582. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  583. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  584. return !result;
  585. }
  586. public async Task<bool> ResetPassword(ResetPasswordDto input)
  587. {
  588. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  589. if (user == null)
  590. throw new AppException(ExceptionEnum.UserNotExist);
  591. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  592. throw new AppException(ExceptionEnum.WrongCredentials);
  593. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  594. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  595. if (!result.Succeeded)
  596. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  597. return true;
  598. }
  599. public async Task<ForgetPasswordResponseDto> ForgetPasswordMail(string email) //Begin forget password
  600. {
  601. var foundUser = await _userManager.FindByEmailAsync(email);
  602. if (foundUser != null)
  603. {
  604. string oneTimePassword = await _oTPService.RandomOneTimePassword(foundUser.Id);
  605. await _oTPService.SentOTPByMail(foundUser.Id, foundUser.Email, oneTimePassword);
  606. ForgetPasswordResponseDto res = new ForgetPasswordResponseDto { UserId = foundUser.Id};
  607. return res;
  608. }
  609. else
  610. {
  611. throw new AppException(ExceptionEnum.UserNotExist);
  612. }
  613. }
  614. public async Task<bool> VerifyOTP(VerifyOTPDto input)
  615. {
  616. if (! await _oTPService.VerifyOTP(input.UserId, input.OTP))
  617. throw new AppException(ExceptionEnum.WrongOTP);
  618. return true;
  619. }
  620. public async Task<bool> ForgetPassword(ForgetPasswordDto input)
  621. {
  622. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  623. if (user == null)
  624. throw new AppException(ExceptionEnum.UserNotExist);
  625. string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
  626. var result = await _userManager.ResetPasswordAsync(user, resetToken, input.Password);
  627. if (!result.Succeeded)
  628. {
  629. if (result.Errors != null && result.Errors.Count() > 0)
  630. {
  631. var msg = result.Errors.Select(a => a.Description).Aggregate((a, b) => a + " /r/n " + b);
  632. throw new AppException(msg);
  633. }
  634. throw new AppException(ExceptionEnum.RecordCreationFailed);
  635. }
  636. return result.Succeeded;
  637. }
  638. public async Task StopUser(string userId)
  639. {
  640. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  641. if (entity == null)
  642. throw new AppException(ExceptionEnum.UserNotExist);
  643. if (!entity.IsStopped)
  644. {
  645. entity.IsStopped = true;
  646. await _unitOfWork.CompleteAsync();
  647. }
  648. }
  649. }
  650. }