UserService.cs 34 KB

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