UserService.cs 44 KB

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