UserService.cs 45 KB

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