| using Diligent.WebAPI.Business.Extensions; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class AdService : IAdService | public class AdService : IAdService | ||||
| { | { | ||||
| private readonly ILogger<AdService> _logger; | |||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly ITechnologyService _technologyService; | private readonly ITechnologyService _technologyService; | ||||
| public AdService(DatabaseContext context, IMapper mapper, ITechnologyService technologyService) | |||||
| public AdService(DatabaseContext context, IMapper mapper, ITechnologyService technologyService, ILogger<AdService> logger) | |||||
| { | { | ||||
| _logger = logger; | |||||
| _context = context; | _context = context; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _technologyService = technologyService; | _technologyService = technologyService; | ||||
| public async Task<List<AdResponseDto>> GetAllAsync() | public async Task<List<AdResponseDto>> GetAllAsync() | ||||
| { | { | ||||
| _logger.LogInformation("Start getting all Ads"); | |||||
| var today = DateTime.Now; | var today = DateTime.Now; | ||||
| return _mapper.Map<List<AdResponseDto>>(await _context.Ads.Include(x => x.Technologies).Where(x => x.ExpiredAt > today).ToListAsync()); | |||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var fromDb = await _context.Ads.Include(x => x.Technologies).Where(x => x.ExpiredAt > today).ToListAsync(); | |||||
| _logger.LogInformation($"Received {fromDb.Count} ads from db."); | |||||
| _logger.LogInformation($"Mapping received ads to AdResponseDto"); | |||||
| var result = _mapper.Map<List<AdResponseDto>>(fromDb); | |||||
| _logger.LogInformation($"Ads has been mapped and received to client: {result.Count} mapped ads"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<AdResponseDto> GetByIdAsync(int id) | public async Task<AdResponseDto> GetByIdAsync(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var ad = await _context.Ads.FindAsync(id); | var ad = await _context.Ads.FindAsync(id); | ||||
| if(ad is null) | |||||
| if (ad is null) | |||||
| { | |||||
| _logger.LogError($"Ad with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Ad not found"); | throw new EntityNotFoundException("Ad not found"); | ||||
| } | |||||
| return _mapper.Map<AdResponseDto>(ad); | |||||
| _logger.LogInformation($"Mapping Ad with id = {id}"); | |||||
| AdResponseDto result = _mapper.Map<AdResponseDto>(ad); | |||||
| _logger.LogInformation($"Ad with id = {id} mapped successfully"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<AdDetailsResponseDto> GetAdDetailsByIdAsync(int id) | public async Task<AdDetailsResponseDto> GetAdDetailsByIdAsync(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start finding Ad with id = {id} with applicants"); | |||||
| var ad = await _context.Ads.Include(x => x.Applicants).Where(x => x.Id == id).FirstOrDefaultAsync(); | var ad = await _context.Ads.Include(x => x.Applicants).Where(x => x.Id == id).FirstOrDefaultAsync(); | ||||
| if (ad is null) | if (ad is null) | ||||
| { | |||||
| _logger.LogError($"Ad with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Ad not found"); | throw new EntityNotFoundException("Ad not found"); | ||||
| } | |||||
| return _mapper.Map<AdDetailsResponseDto>(ad); | |||||
| _logger.LogInformation($"Mapping Ad with id = {id}"); | |||||
| AdDetailsResponseDto result = _mapper.Map<AdDetailsResponseDto>(ad); | |||||
| _logger.LogInformation($"Ad with id = {id} mapped successfully"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<List<AdResponseDto>> GetArchiveAds() | public async Task<List<AdResponseDto>> GetArchiveAds() | ||||
| { | { | ||||
| _logger.LogInformation("Start getting all Archived Ads"); | |||||
| var today = DateTime.Now; | var today = DateTime.Now; | ||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var archiveAds = await _context.Ads.Where(x => x.ExpiredAt < today).ToListAsync(); | var archiveAds = await _context.Ads.Where(x => x.ExpiredAt < today).ToListAsync(); | ||||
| _logger.LogInformation($"Received {archiveAds.Count} ads from db."); | |||||
| return _mapper.Map<List<AdResponseDto>>(archiveAds); | |||||
| _logger.LogInformation($"Mapping received ads to AdResponseDto"); | |||||
| List<AdResponseDto> result = _mapper.Map<List<AdResponseDto>>(archiveAds); | |||||
| _logger.LogInformation($"Ads has been mapped and received to client: {result.Count} mapped ads"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<List<AdResponseDto>> GetFilteredAdsAsync(AdFilterDto filters) | public async Task<List<AdResponseDto>> GetFilteredAdsAsync(AdFilterDto filters) | ||||
| { | { | ||||
| _logger.LogInformation($"Start getting all filtered Ads"); | |||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var filteredAds = await _context.Ads.Include(x => x.Technologies).ToListAsync(); | var filteredAds = await _context.Ads.Include(x => x.Technologies).ToListAsync(); | ||||
| _logger.LogInformation($"Received {filteredAds.Count} ads from db."); | |||||
| return _mapper.Map<List<AdResponseDto>>(filteredAds.Filter(filters)); | |||||
| _logger.LogInformation($"Mapping received ads to AdResponseDto"); | |||||
| List<AdResponseDto> result = _mapper.Map<List<AdResponseDto>>(filteredAds.Filter(filters)); | |||||
| _logger.LogInformation($"Ads has been mapped and received to client: {result.Count} mapped ads"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task CreateAsync(AdCreateDto adCreateDto) | public async Task CreateAsync(AdCreateDto adCreateDto) | ||||
| { | { | ||||
| _logger.LogInformation($"Start creating Ad"); | |||||
| var ad = _mapper.Map<Ad>(adCreateDto); | var ad = _mapper.Map<Ad>(adCreateDto); | ||||
| _logger.LogInformation($"Ad created successfully"); | |||||
| _logger.LogInformation($"Start adding technologies to Ad"); | |||||
| for (int i = 0; i < adCreateDto.TechnologiesIds.Count; i++) | for (int i = 0; i < adCreateDto.TechnologiesIds.Count; i++) | ||||
| { | { | ||||
| var technology = await _technologyService.GetEntityByIdAsync(adCreateDto.TechnologiesIds[i]); | var technology = await _technologyService.GetEntityByIdAsync(adCreateDto.TechnologiesIds[i]); | ||||
| ad.Technologies.Add(technology); | ad.Technologies.Add(technology); | ||||
| _logger.LogInformation($"Technology with id {technology.TechnologyId} added to Ad"); | |||||
| } | } | ||||
| _logger.LogInformation($"Finished adding techonologies"); | |||||
| await _context.Ads.AddAsync(ad); | await _context.Ads.AddAsync(ad); | ||||
| await _context.SaveChangesAsync(); | |||||
| _logger.LogInformation($"Saving Ad to db..."); | |||||
| var result = _context.SaveChangesAsync(); | |||||
| _logger.LogInformation($"Ad saved to DB"); | |||||
| await result; | |||||
| } | } | ||||
| public async Task UpdateAsync(int id, AdUpdateDto adUpdateDto) | public async Task UpdateAsync(int id, AdUpdateDto adUpdateDto) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var ad = await _context.Ads.FindAsync(id); | var ad = await _context.Ads.FindAsync(id); | ||||
| if (ad is null) | if (ad is null) | ||||
| { | |||||
| _logger.LogError($"Ad with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Ad not found"); | throw new EntityNotFoundException("Ad not found"); | ||||
| } | |||||
| _logger.LogInformation($"Mapping Ad with id = {id}"); | |||||
| _mapper.Map(adUpdateDto, ad); | _mapper.Map(adUpdateDto, ad); | ||||
| _logger.LogInformation($"Ad with id = {id} mapped successfully"); | |||||
| _context.Entry(ad).State = EntityState.Modified; | _context.Entry(ad).State = EntityState.Modified; | ||||
| await _context.SaveChangesAsync(); | |||||
| var result = _context.SaveChangesAsync(); | |||||
| _logger.LogInformation($"Ad saved to DB"); | |||||
| await result; | |||||
| } | } | ||||
| public async Task DeleteAsync(int id) | public async Task DeleteAsync(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var ad = await _context.Ads.FindAsync(id); | var ad = await _context.Ads.FindAsync(id); | ||||
| if (ad is null) | if (ad is null) | ||||
| { | |||||
| _logger.LogError($"Ad with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Ad not found"); | throw new EntityNotFoundException("Ad not found"); | ||||
| } | |||||
| _context.Ads.Remove(ad); | _context.Ads.Remove(ad); | ||||
| await _context.SaveChangesAsync(); | |||||
| var result = _context.SaveChangesAsync(); | |||||
| _logger.LogInformation($"Ad saved to DB"); | |||||
| await result; | |||||
| } | } | ||||
| } | } | ||||
| } | } |
| using Diligent.WebAPI.Business.Extensions; | |||||
| using Microsoft.AspNetCore.Http; | |||||
| using static Diligent.WebAPI.Data.Entities.Applicant; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class ApplicantService : IApplicantService | public class ApplicantService : IApplicantService | ||||
| { | { | ||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly ILogger<ApplicantService> _logger; | |||||
| public ApplicantService(DatabaseContext context, IMapper mapper) | |||||
| public ApplicantService(DatabaseContext context, IMapper mapper, ILogger<ApplicantService> logger) | |||||
| { | { | ||||
| _context = context; | _context = context; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<QueryResultDto<ApplicantViewDto>> GetFilteredApplicants(ApplicantFilterDto applicantFilterDto) | public async Task<QueryResultDto<ApplicantViewDto>> GetFilteredApplicants(ApplicantFilterDto applicantFilterDto) | ||||
| { | { | ||||
| _logger.LogInformation("Start getting filtered applicants"); | |||||
| _logger.LogInformation("Getting data from DB and filter"); | |||||
| var filteredApplicants = (await _context.Applicants | var filteredApplicants = (await _context.Applicants | ||||
| .Include(c => c.Ads) | .Include(c => c.Ads) | ||||
| .Include(x => x.TechnologyApplicants) | .Include(x => x.TechnologyApplicants) | ||||
| .FilterApplicants(applicantFilterDto); | .FilterApplicants(applicantFilterDto); | ||||
| int totalNumberOfItems = filteredApplicants.Count; | int totalNumberOfItems = filteredApplicants.Count; | ||||
| _logger.LogInformation($"Got {totalNumberOfItems} applicants"); | |||||
| filteredApplicants = PaginationExtension.ApplyPagging(filteredApplicants, new Pagination | filteredApplicants = PaginationExtension.ApplyPagging(filteredApplicants, new Pagination | ||||
| { | { | ||||
| PageSize = applicantFilterDto.PageSize | PageSize = applicantFilterDto.PageSize | ||||
| }); | }); | ||||
| _logger.LogInformation($"Return list of applicants"); | |||||
| return new QueryResultDto<ApplicantViewDto> | return new QueryResultDto<ApplicantViewDto> | ||||
| { | { | ||||
| Items = _mapper.Map<List<ApplicantViewDto>>(filteredApplicants), | Items = _mapper.Map<List<ApplicantViewDto>>(filteredApplicants), | ||||
| public async Task<ApplicantViewDto> GetById(int id) | public async Task<ApplicantViewDto> GetById(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Applicant with id = {id}"); | |||||
| var applicant = await _context.Applicants | var applicant = await _context.Applicants | ||||
| .Include(x => x.Ads) | .Include(x => x.Ads) | ||||
| .ThenInclude(x => x.Technologies) | .ThenInclude(x => x.Technologies) | ||||
| .FirstOrDefaultAsync(x => x.ApplicantId == id); | .FirstOrDefaultAsync(x => x.ApplicantId == id); | ||||
| if (applicant is null) | if (applicant is null) | ||||
| { | |||||
| _logger.LogError($"Applicant with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Applicant not found"); | throw new EntityNotFoundException("Applicant not found"); | ||||
| return _mapper.Map<ApplicantViewDto>(applicant); | |||||
| } | |||||
| _logger.LogInformation($"Mapping Applicant with id = {id}"); | |||||
| var result = _mapper.Map<ApplicantViewDto>(applicant); | |||||
| _logger.LogInformation($"Applicant with id = {id} mapped successfully"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task CreateApplicant(ApplicantCreateDto applicantCreateDto) | |||||
| { | |||||
| var applicant = _mapper.Map<Applicant>(applicantCreateDto); | |||||
| await _context.Applicants.AddAsync(applicant); | |||||
| await _context.SaveChangesAsync(); | |||||
| } | |||||
| public async Task DeleteApplicant(int id) | |||||
| public async Task<ApplicantViewDto> GetApplicantWithSelectionProcessesById(int id) | |||||
| { | { | ||||
| var applicant = await _context.Applicants.FindAsync(id); | |||||
| var applicant = await _context.Applicants | |||||
| .Include(a => a.SelectionProcesses).ThenInclude(sp => sp.SelectionLevel) | |||||
| .Include(a => a.SelectionProcesses).ThenInclude(sp => sp.Scheduler) | |||||
| .FirstOrDefaultAsync(a => a.ApplicantId == id); | |||||
| if (applicant is null) | if (applicant is null) | ||||
| throw new EntityNotFoundException("Applicant not found"); | throw new EntityNotFoundException("Applicant not found"); | ||||
| _context.Applicants.Remove(applicant); | |||||
| await _context.SaveChangesAsync(); | |||||
| return _mapper.Map<ApplicantViewDto>(applicant); | |||||
| } | } | ||||
| public async Task UpdateApplicant(int id, ApplicantUpdateDto applicantUpdateDto) | |||||
| public async Task DeleteApplicant(int id) | |||||
| { | { | ||||
| _logger.LogInformation($"Start searching Applicant with id = {id}"); | |||||
| var applicant = await _context.Applicants.FindAsync(id); | var applicant = await _context.Applicants.FindAsync(id); | ||||
| if (applicant is null) | if (applicant is null) | ||||
| { | |||||
| _logger.LogError($"Applicant with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Applicant not found"); | throw new EntityNotFoundException("Applicant not found"); | ||||
| } | |||||
| _mapper.Map(applicantUpdateDto, applicant); | |||||
| _context.Entry(applicant).State = EntityState.Modified; | |||||
| await _context.SaveChangesAsync(); | |||||
| _logger.LogError($"Removing Applicant with id = {id}"); | |||||
| _context.Applicants.Remove(applicant); | |||||
| var result = _context.SaveChangesAsync(); | |||||
| _logger.LogError($"Applicant with id = {id} is removed successfully"); | |||||
| await result; | |||||
| } | } | ||||
| public async Task<List<AdApplicantsViewDto>> GetAllAdsApplicants(ApplicantFilterDto applicantFilterDto) | public async Task<List<AdApplicantsViewDto>> GetAllAdsApplicants(ApplicantFilterDto applicantFilterDto) | ||||
| { | { | ||||
| _logger.LogInformation("Start getting filtered applicants"); | |||||
| _logger.LogInformation("Getting data from DB and filter"); | |||||
| var adsApplicants = (await _context.Ads | var adsApplicants = (await _context.Ads | ||||
| .Include(a => a.Applicants) | .Include(a => a.Applicants) | ||||
| .ThenInclude(a => a.TechnologyApplicants) | .ThenInclude(a => a.TechnologyApplicants) | ||||
| .ToListAsync()) | .ToListAsync()) | ||||
| .FilterAdApplicants(applicantFilterDto); | .FilterAdApplicants(applicantFilterDto); | ||||
| return _mapper.Map<List<AdApplicantsViewDto>>(adsApplicants); | |||||
| _logger.LogInformation($"Got {adsApplicants.Count} ads"); | |||||
| var result = _mapper.Map<List<AdApplicantsViewDto>>(adsApplicants); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<ApplicantViewDto> GetApplicantWithSelectionProcessesById(int id) | |||||
| { | |||||
| var applicant = await _context.Applicants | |||||
| .Include(a => a.SelectionProcesses).ThenInclude(sp => sp.SelectionLevel) | |||||
| .Include(a => a.SelectionProcesses).ThenInclude(sp => sp.Scheduler) | |||||
| .FirstOrDefaultAsync(a => a.ApplicantId == id); | |||||
| //public async Task CreateApplicant(ApplicantCreateDto applicantCreateDto) | |||||
| //{ | |||||
| // var applicant = _mapper.Map<Applicant>(applicantCreateDto); | |||||
| // await _context.Applicants.AddAsync(applicant); | |||||
| if (applicant is null) | |||||
| throw new EntityNotFoundException("Applicant not found"); | |||||
| // await _context.SaveChangesAsync(); | |||||
| //} | |||||
| //public async Task UpdateApplicant(int id, ApplicantUpdateDto applicantUpdateDto) | |||||
| //{ | |||||
| // var applicant = await _context.Applicants.FindAsync(id); | |||||
| // if (applicant is null) | |||||
| // throw new EntityNotFoundException("Applicant not found"); | |||||
| // _mapper.Map(applicantUpdateDto, applicant); | |||||
| // _context.Entry(applicant).State = EntityState.Modified; | |||||
| // await _context.SaveChangesAsync(); | |||||
| //} | |||||
| return _mapper.Map<ApplicantViewDto>(applicant); | |||||
| } | |||||
| } | } | ||||
| } | } |
| using Microsoft.AspNetCore.WebUtilities; | using Microsoft.AspNetCore.WebUtilities; | ||||
| using Microsoft.Extensions.Logging; | |||||
| using System.Net; | |||||
| using System.Web; | |||||
| namespace Diligent.WebAPI.Business.Services | namespace Diligent.WebAPI.Business.Services | ||||
| { | { | ||||
| public async Task<ServiceResponseDTO<AuthenticateResponseDto>> Authenticate(AuthenticateRequestDto model) | public async Task<ServiceResponseDTO<AuthenticateResponseDto>> Authenticate(AuthenticateRequestDto model) | ||||
| { | { | ||||
| _logger.LogError($"Checking credentials for user: {model.Username}"); | |||||
| var user = await _userManager.FindByNameAsync(model.Username); | var user = await _userManager.FindByNameAsync(model.Username); | ||||
| // return null if user not found | // return null if user not found | ||||
| if (user == null) | if (user == null) | ||||
| { | { | ||||
| _logger.LogError($"User with username = {model.Username} not found"); | |||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| { | { | ||||
| IsError = true, | IsError = true, | ||||
| // return null if user is disabled | // return null if user is disabled | ||||
| if (user.IsEnabled == false) | if (user.IsEnabled == false) | ||||
| { | { | ||||
| _logger.LogError($"User: {model.Username} is not enabled"); | |||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| { | { | ||||
| IsError = true, | IsError = true, | ||||
| // password is not correct | // password is not correct | ||||
| if (!result) | if (!result) | ||||
| { | { | ||||
| _logger.LogError($"Password for user: {model.Username} is not correct"); | |||||
| await _userManager.AccessFailedAsync(user); | await _userManager.AccessFailedAsync(user); | ||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| ErrorMessage = "Password is not correct" | ErrorMessage = "Password is not correct" | ||||
| }; | }; | ||||
| } | } | ||||
| return await GenerateToken(user); | |||||
| var token = await GenerateToken(user); | |||||
| _logger.LogError($"Successfull login token: {token}"); | |||||
| return token; | |||||
| } | } | ||||
| public async Task<ServiceResponseDTO<AuthenticateResponseDto>> Authenticate(GoogleApiModel model) | public async Task<ServiceResponseDTO<AuthenticateResponseDto>> Authenticate(GoogleApiModel model) | ||||
| { | { | ||||
| _logger.LogError($"Checking token for google login {model.Token}"); | |||||
| if (!(await _httpClient.IsTokenValid(model.Token))) | if (!(await _httpClient.IsTokenValid(model.Token))) | ||||
| { | { | ||||
| _logger.LogError($"Token is not valid"); | |||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| { | { | ||||
| IsError = true, | IsError = true, | ||||
| ErrorMessage = "Invalid Google Api Token" | ErrorMessage = "Invalid Google Api Token" | ||||
| }; | }; | ||||
| } | } | ||||
| _logger.LogError($"Checking if user exists in Db with email : {model.User.email}"); | |||||
| var user = await _userManager.FindByEmailAsync(model.User.email); | var user = await _userManager.FindByEmailAsync(model.User.email); | ||||
| // return null if user not found | // return null if user not found | ||||
| if (user == null) | if (user == null) | ||||
| { | { | ||||
| _logger.LogError($"User does not exist in Db"); | |||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| { | { | ||||
| IsError = true, | IsError = true, | ||||
| if (user.IsEnabled == false) | if (user.IsEnabled == false) | ||||
| { | { | ||||
| _logger.LogError($"User is not enabled"); | |||||
| return new ServiceResponseDTO<AuthenticateResponseDto> | return new ServiceResponseDTO<AuthenticateResponseDto> | ||||
| { | { | ||||
| IsError = true, | IsError = true, | ||||
| ErrorMessage = $"User with email {model.User.email} has no permission to log in." | ErrorMessage = $"User with email {model.User.email} has no permission to log in." | ||||
| }; | }; | ||||
| } | } | ||||
| return await GenerateToken(user); | |||||
| var token = await GenerateToken(user); | |||||
| _logger.LogInformation($"Successfull login. Token :{token}"); | |||||
| return token; | |||||
| } | } | ||||
| private async Task<ServiceResponseDTO<AuthenticateResponseDto>> GenerateToken(User user) | private async Task<ServiceResponseDTO<AuthenticateResponseDto>> GenerateToken(User user) | ||||
| ErrorMessage = "The account is locked out" | ErrorMessage = "The account is locked out" | ||||
| }; | }; | ||||
| // authentication successful so generate jwt token | // authentication successful so generate jwt token | ||||
| var token = await GenerateJwtToken(user, true); | var token = await GenerateJwtToken(user, true); | ||||
| } | } | ||||
| await _databaseContext.SaveChangesAsync(); | await _databaseContext.SaveChangesAsync(); | ||||
| _logger.LogInformation($"JWTToken : {writedToken}"); | |||||
| return writedToken; | return writedToken; | ||||
| } | } | ||||
| var user = await _userManager.FindByIdAsync(validatedToken.Claims.Single(x => x.Type == "id").Value); | var user = await _userManager.FindByIdAsync(validatedToken.Claims.Single(x => x.Type == "id").Value); | ||||
| var token = await GenerateJwtToken(user); | var token = await GenerateJwtToken(user); | ||||
| _logger.LogInformation($"Refresh token : {model.Token}"); | |||||
| return new RefreshTokenResultDto | return new RefreshTokenResultDto | ||||
| { | { | ||||
| ErrorMessage = "Problem with saving changes into database" | ErrorMessage = "Problem with saving changes into database" | ||||
| }; | }; | ||||
| _logger.LogInformation($"Delted refresh token : {refreshToken}"); | |||||
| return new ServiceResponseDTO<string> | return new ServiceResponseDTO<string> | ||||
| { | { | ||||
| Data = null | Data = null | ||||
| public async Task<ServiceResponseDTO<object>> GetForgotPasswordUrlAsync(string email) | public async Task<ServiceResponseDTO<object>> GetForgotPasswordUrlAsync(string email) | ||||
| { | { | ||||
| _logger.LogInformation($"Sending forgot password email for : {email}"); | |||||
| var user = await _userManager.FindByEmailAsync(email); | var user = await _userManager.FindByEmailAsync(email); | ||||
| if (user == null) | if (user == null) | ||||
| { | { | ||||
| await _emailer.SendEmailAndWriteToDbAsync(email, "Reset password", HTMLHelper.RenderForgotPasswordPage($"{_frontEndSettings.BaseUrl}/reset-password?token={token}&email={email}"), isHtml: true); | await _emailer.SendEmailAndWriteToDbAsync(email, "Reset password", HTMLHelper.RenderForgotPasswordPage($"{_frontEndSettings.BaseUrl}/reset-password?token={token}&email={email}"), isHtml: true); | ||||
| _logger.LogInformation($"Reset password email is sent"); | |||||
| return new ServiceResponseDTO<object> | return new ServiceResponseDTO<object> | ||||
| { | { | ||||
| Data = new { code = token, email = email } | Data = new { code = token, email = email } | ||||
| public async Task<ServiceResponseDTO<object>> PasswordResetAsync(string email, string code, string password) | public async Task<ServiceResponseDTO<object>> PasswordResetAsync(string email, string code, string password) | ||||
| { | { | ||||
| _logger.LogInformation($"User with email : {email} changes password"); | |||||
| var user = await _userManager.FindByEmailAsync(email); | var user = await _userManager.FindByEmailAsync(email); | ||||
| if (user == null) | if (user == null) | ||||
| { | { | ||||
| IdentityResult resetResult = await _userManager.ResetPasswordAsync(user, passwordResetToken, password); | IdentityResult resetResult = await _userManager.ResetPasswordAsync(user, passwordResetToken, password); | ||||
| if (resetResult.Succeeded) | if (resetResult.Succeeded) | ||||
| { | { | ||||
| _logger.LogInformation($"Password for user : {email} changed successfully"); | |||||
| return new ServiceResponseDTO<object> { Data = true }; | return new ServiceResponseDTO<object> { Data = true }; | ||||
| } | } | ||||
| using Diligent.WebAPI.Contracts.DTOs.Comment; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class CommentService : ICommentService | public class CommentService : ICommentService | ||||
| { | { | ||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly ILogger<CommentService> _logger; | |||||
| public CommentService(DatabaseContext context, IMapper mapper) | |||||
| public CommentService(DatabaseContext context, IMapper mapper, ILogger<CommentService> logger) | |||||
| { | { | ||||
| _context = context; | _context = context; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task CreateComment(CommentCreateDto commentCreateDto) | public async Task CreateComment(CommentCreateDto commentCreateDto) | ||||
| { | { | ||||
| _logger.LogInformation("Start creating comment"); | |||||
| var comment = _mapper.Map<Comment>(commentCreateDto); | var comment = _mapper.Map<Comment>(commentCreateDto); | ||||
| comment.DateOfSending = DateTime.Now; | comment.DateOfSending = DateTime.Now; | ||||
| _logger.LogInformation($"Comment created successfully in {comment.DateOfSending}"); | |||||
| _logger.LogInformation($"Saving comment in Db"); | |||||
| await _context.Comments.AddAsync(comment); | await _context.Comments.AddAsync(comment); | ||||
| await _context.SaveChangesAsync(); | |||||
| var result = _context.SaveChangesAsync(); | |||||
| _logger.LogInformation($"Comment saved in Db"); | |||||
| await result; | |||||
| } | } | ||||
| } | } | ||||
| } | } |
| using System.Net.Mail; | using System.Net.Mail; | ||||
| using System.Net; | using System.Net; | ||||
| using Diligent.WebAPI.Contracts.Models; | |||||
| namespace Diligent.WebAPI.Business.Services | namespace Diligent.WebAPI.Business.Services | ||||
| { | { | ||||
| public class Emailer : IEmailer | public class Emailer : IEmailer | ||||
| { | { | ||||
| private readonly MailSettings _settings; | private readonly MailSettings _settings; | ||||
| private readonly ILogger<Emailer> _logger; | |||||
| public Emailer(IOptions<MailSettings> mailSettings) | |||||
| public Emailer(IOptions<MailSettings> mailSettings, ILogger<Emailer> logger) | |||||
| { | { | ||||
| _settings = mailSettings.Value; | _settings = mailSettings.Value; | ||||
| //_settings = new AuthorizationSettings | |||||
| //{ | |||||
| // SmtpServer = "smtp.mailtrap.io", | |||||
| // SmtpPort = 2525, | |||||
| // SmtpUseSSL = true, | |||||
| // SmtpUsername = "460e3c49f02e37", | |||||
| // SmtpPassword = "66443869eaad55", | |||||
| // SmtpFrom = "noreply@hrcenter.net", | |||||
| // SmtpFromName = "HRCenter Team" | |||||
| //}; | |||||
| _logger = logger; | |||||
| } | } | ||||
| /// <summary> | /// <summary> | ||||
| /// <returns></returns> | /// <returns></returns> | ||||
| public async Task<bool> SendEmailAndWriteToDbAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null) | public async Task<bool> SendEmailAndWriteToDbAsync(List<string> to, string subject, string body, bool isHtml = false, List<string> cc = null) | ||||
| { | { | ||||
| _logger.LogInformation($"Start sending email to {to}"); | |||||
| var emailResult = await SendEmailAsync(to, subject, body, isHtml, cc); | var emailResult = await SendEmailAsync(to, subject, body, isHtml, cc); | ||||
| //_logger.LogInformation("Create email entity for save in db"); | |||||
| var email = CreateEmail(to, subject, body, isHtml); | var email = CreateEmail(to, subject, body, isHtml); | ||||
| if (emailResult) | if (emailResult) | ||||
| email.SentTime = DateTime.UtcNow; | email.SentTime = DateTime.UtcNow; | ||||
| } | } | ||||
| //_logger.LogInformation("Save email in db"); | |||||
| //var dbResult = await WriteEmailToDbAsync(email); | //var dbResult = await WriteEmailToDbAsync(email); | ||||
| //_logger.LogInformation("Email is saved in db."); | |||||
| return emailResult; // && dbResult > 0; | return emailResult; // && dbResult > 0; | ||||
| } | } | ||||
| { | { | ||||
| try | try | ||||
| { | { | ||||
| _logger.LogInformation("Getting SMTP client settings from appsettings file"); | |||||
| using (var smtp = GetSmtpClient()) | using (var smtp = GetSmtpClient()) | ||||
| { | { | ||||
| _logger.LogInformation("Create mail message"); | |||||
| var message = GetMailMessage(to, subject, body, isHtml, cc); | var message = GetMailMessage(to, subject, body, isHtml, cc); | ||||
| _logger.LogInformation("Message created."); | |||||
| _logger.LogInformation("Sending message to client"); | |||||
| await smtp.SendMailAsync(message); | await smtp.SendMailAsync(message); | ||||
| _logger.LogInformation("Email message sent."); | |||||
| return true; | return true; | ||||
| } | } | ||||
| } | } | ||||
| catch (ArgumentException) | |||||
| catch (ArgumentException ex) | |||||
| { | { | ||||
| _logger.LogInformation($"Error in arguments {ex}"); | |||||
| throw; | throw; | ||||
| } | } | ||||
| catch (Exception e) | catch (Exception e) | ||||
| { | { | ||||
| _logger.LogInformation($"Error {e}"); | |||||
| throw new Exception("Failed to send email message.", e); | throw new Exception("Failed to send email message.", e); | ||||
| } | } | ||||
| } | } |
| private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"; | private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"; | ||||
| private string[] SupportedClientsIds = { "" }; | private string[] SupportedClientsIds = { "" }; | ||||
| private readonly AuthorizationSettings _authSettings; | private readonly AuthorizationSettings _authSettings; | ||||
| private readonly ILogger<HttpClientService> _logger; | |||||
| public HttpClientService(IOptions<AuthorizationSettings> authSettings) | |||||
| public HttpClientService(IOptions<AuthorizationSettings> authSettings, ILogger<HttpClientService> logger) | |||||
| { | { | ||||
| _authSettings = authSettings.Value; | _authSettings = authSettings.Value; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<bool> IsTokenValid(string providerToken) | public async Task<bool> IsTokenValid(string providerToken) | ||||
| { | { | ||||
| _logger.LogInformation($"Start checking is token valid: {providerToken}"); | |||||
| var httpClient = new HttpClient(); | var httpClient = new HttpClient(); | ||||
| var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken)); | var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken)); | ||||
| _logger.LogInformation("Initilazing http call to googleapi"); | |||||
| HttpResponseMessage httpResponseMessage; | HttpResponseMessage httpResponseMessage; | ||||
| try | try | ||||
| { | { | ||||
| _logger.LogInformation("Calling googleapi HTTPGet method"); | |||||
| httpResponseMessage = httpClient.GetAsync(requestUri).Result; | httpResponseMessage = httpClient.GetAsync(requestUri).Result; | ||||
| } | } | ||||
| catch | |||||
| catch(Exception ex) | |||||
| { | { | ||||
| _logger.LogInformation($"Error in call: {ex.Message}"); | |||||
| return false; | return false; | ||||
| } | } | ||||
| var response = httpResponseMessage.Content.ReadAsStringAsync().Result; | var response = httpResponseMessage.Content.ReadAsStringAsync().Result; | ||||
| var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response); | var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response); | ||||
| _logger.LogInformation($"Call pass and it received: {googleApiTokenInfo}"); | |||||
| //if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud)) | //if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud)) | ||||
| if (googleApiTokenInfo.aud != _authSettings.GoogleClientId) | if (googleApiTokenInfo.aud != _authSettings.GoogleClientId) |
| Task<List<AdApplicantsViewDto>> GetAllAdsApplicants(ApplicantFilterDto applicantFilterDto); | Task<List<AdApplicantsViewDto>> GetAllAdsApplicants(ApplicantFilterDto applicantFilterDto); | ||||
| Task<ApplicantViewDto> GetById(int id); | Task<ApplicantViewDto> GetById(int id); | ||||
| Task<ApplicantViewDto> GetApplicantWithSelectionProcessesById(int id); | Task<ApplicantViewDto> GetApplicantWithSelectionProcessesById(int id); | ||||
| Task CreateApplicant(ApplicantCreateDto applicantCreateDto); | |||||
| //Task CreateApplicant(ApplicantCreateDto applicantCreateDto); | |||||
| Task DeleteApplicant(int id); | Task DeleteApplicant(int id); | ||||
| Task UpdateApplicant(int id, ApplicantUpdateDto applicantUpdateDto); | |||||
| //Task UpdateApplicant(int id, ApplicantUpdateDto applicantUpdateDto); | |||||
| } | } | ||||
| } | } |
| { | { | ||||
| public interface ISelectionProcessService | public interface ISelectionProcessService | ||||
| { | { | ||||
| Task CreateAsync(SelectionProcessCreateDto model); | |||||
| Task DeleteAsync(int id); | |||||
| Task<List<SelectionProcessResposneDto>> GetAllAsync(); | Task<List<SelectionProcessResposneDto>> GetAllAsync(); | ||||
| Task<SelectionProcessResposneDto> GetByIdAsync(int id); | |||||
| Task<bool> FinishSelectionProcess(SelectionProcessCreateDto model); | Task<bool> FinishSelectionProcess(SelectionProcessCreateDto model); | ||||
| Task UpdateAsync(int id, SelectionProcessCreateDto model); | |||||
| } | } | ||||
| } | } |
| public interface ITechnologyService | public interface ITechnologyService | ||||
| { | { | ||||
| Task<List<TechnologyResponseDto>> GetAllAsync(); | Task<List<TechnologyResponseDto>> GetAllAsync(); | ||||
| Task<List<TechnologyApplicantViewDto>> GetAllAsync2(); | |||||
| Task<TechnologyResponseDto> GetByIdAsync(int id); | Task<TechnologyResponseDto> GetByIdAsync(int id); | ||||
| Task<TechnologyApplicantViewDto> GetByIdAsync2(int id); | |||||
| Task<Technology> GetEntityByIdAsync(int id); | Task<Technology> GetEntityByIdAsync(int id); | ||||
| } | } | ||||
| } | } |
| using Diligent.WebAPI.Business.Extensions; | |||||
| using Diligent.WebAPI.Contracts.DTOs.SelectionLevel; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class SelectionLevelService : ISelectionLevelService | public class SelectionLevelService : ISelectionLevelService | ||||
| { | { | ||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly ILogger<SelectionLevelService> _logger; | |||||
| public SelectionLevelService(DatabaseContext context, IMapper mapper) | |||||
| public SelectionLevelService(DatabaseContext context, IMapper mapper, ILogger<SelectionLevelService> logger) | |||||
| { | { | ||||
| _context = context; | _context = context; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<List<SelectionLevelResponseWithDataDto>> GetAllAsync() => | |||||
| _mapper.Map<List<SelectionLevelResponseWithDataDto>>(await _context.SelectionLevels.Include(sl => sl.SelectionProcesses).ThenInclude(sp => sp.Applicant).ToListAsync()); | |||||
| public async Task<List<SelectionLevelResponseWithDataDto>> GetAllAsync() | |||||
| { | |||||
| _logger.LogInformation("Start getting all selection levels"); | |||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var fromDb = await _context.SelectionLevels | |||||
| .Include(sl => sl.SelectionProcesses) | |||||
| .ThenInclude(sp => sp.Applicant) | |||||
| .ToListAsync(); | |||||
| _logger.LogInformation($"Received {fromDb.Count} levels from db."); | |||||
| _logger.LogInformation($"Mapping received ads to SelectionLevelResponseWithDataDto"); | |||||
| var result = _mapper.Map<List<SelectionLevelResponseWithDataDto>>(fromDb); | |||||
| _logger.LogInformation($"Levels has been mapped and received to client: {result.Count} mapped levels"); | |||||
| return result; | |||||
| } | |||||
| public async Task<SelectionLevelResposneDto> GetByIdAsync(int id) | public async Task<SelectionLevelResposneDto> GetByIdAsync(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Level with id = {id}"); | |||||
| var sl = await _context.SelectionLevels.FindAsync(id); | var sl = await _context.SelectionLevels.FindAsync(id); | ||||
| if (sl is null) | if (sl is null) | ||||
| { | |||||
| _logger.LogError($"Level with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Selection level not found"); | throw new EntityNotFoundException("Selection level not found"); | ||||
| } | |||||
| return _mapper.Map<SelectionLevelResposneDto>(sl); | |||||
| _logger.LogInformation($"Mapping Level with id = {id} to SelectionLevelResposneDto"); | |||||
| var result = _mapper.Map<SelectionLevelResposneDto>(sl); | |||||
| _logger.LogInformation($"Level with id = {id} mapped successfully"); | |||||
| return result; | |||||
| } | } | ||||
| public List<SelectionLevelResponseWithDataDto> GetFilteredLevelsAsync(SelectionProcessFilterDto filters) | public List<SelectionLevelResponseWithDataDto> GetFilteredLevelsAsync(SelectionProcessFilterDto filters) | ||||
| { | { | ||||
| var filteredLevels = _context.SelectionLevels.Include(x => x.SelectionProcesses).ThenInclude(sp => sp.Applicant).ToList().FilterLevels(filters); | |||||
| _logger.LogInformation("Start getting filtered selection levels"); | |||||
| _logger.LogInformation("Getting data from DB and filter it"); | |||||
| var filteredLevels = _context.SelectionLevels | |||||
| .Include(x => x.SelectionProcesses) | |||||
| .ThenInclude(sp => sp.Applicant).ToList() | |||||
| .FilterLevels(filters); | |||||
| _logger.LogInformation($"Received {filteredLevels.Count} levels from db."); | |||||
| _logger.LogInformation($"Mapping received ads to SelectionLevelResponseWithDataDto"); | |||||
| var result = _mapper.Map<List<SelectionLevelResponseWithDataDto>>(filteredLevels); | |||||
| _logger.LogInformation($"Levels has been mapped and received to client: {result.Count} mapped levels"); | |||||
| return _mapper.Map<List<SelectionLevelResponseWithDataDto>>(filteredLevels); | |||||
| return result; | |||||
| } | } | ||||
| } | } | ||||
| } | } |
| using Diligent.WebAPI.Contracts.DTOs.SelectionProcess; | |||||
| using static System.Net.Mime.MediaTypeNames; | |||||
| using System.Collections.Generic; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class SelectionProcessService : ISelectionProcessService | public class SelectionProcessService : ISelectionProcessService | ||||
| { | { | ||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly ILogger<SelectionProcessService> _logger; | |||||
| public SelectionProcessService(DatabaseContext context, IMapper mapper) | |||||
| public SelectionProcessService(DatabaseContext context, IMapper mapper, ILogger<SelectionProcessService> logger) | |||||
| { | { | ||||
| _context = context; | _context = context; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<List<SelectionProcessResposneDto>> GetAllAsync() => | |||||
| _mapper.Map<List<SelectionProcessResposneDto>>(await _context.SelectionProcesses.ToListAsync()); | |||||
| public async Task<SelectionProcessResposneDto> GetByIdAsync(int id) | |||||
| { | |||||
| var sp = await _context.SelectionProcesses.FindAsync(id); | |||||
| if (sp is null) | |||||
| throw new EntityNotFoundException("Selection process not found"); | |||||
| return _mapper.Map<SelectionProcessResposneDto>(sp); | |||||
| } | |||||
| public async Task CreateAsync(SelectionProcessCreateDto model) | |||||
| { | |||||
| await _context.SelectionProcesses.AddAsync(_mapper.Map<SelectionProcess>(model)); | |||||
| await _context.SaveChangesAsync(); | |||||
| } | |||||
| public async Task UpdateAsync(int id, SelectionProcessCreateDto model) | |||||
| { | |||||
| var sp = await _context.SelectionProcesses.FindAsync(id); | |||||
| if (sp is null) | |||||
| throw new EntityNotFoundException("Selection process not found"); | |||||
| _mapper.Map(model, sp); | |||||
| _context.Entry(sp).State = EntityState.Modified; | |||||
| await _context.SaveChangesAsync(); | |||||
| } | |||||
| public async Task DeleteAsync(int id) | |||||
| public async Task<List<SelectionProcessResposneDto>> GetAllAsync() | |||||
| { | { | ||||
| var sp = await _context.SelectionProcesses.FindAsync(id); | |||||
| if (sp is null) | |||||
| throw new EntityNotFoundException("Selection process not found"); | |||||
| _context.SelectionProcesses.Remove(sp); | |||||
| await _context.SaveChangesAsync(); | |||||
| _logger.LogInformation("Start getting all Selection Processes"); | |||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var fromDB = await _context.SelectionProcesses.ToListAsync(); | |||||
| _logger.LogInformation($"Received {fromDB.Count} processes from db."); | |||||
| _logger.LogInformation($"Mapping received ads to SelectionProcessResposneDto"); | |||||
| var result = _mapper.Map<List<SelectionProcessResposneDto>>(fromDB); | |||||
| _logger.LogInformation($"Processes has been mapped and received to client: {result.Count} mapped processes"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<bool> FinishSelectionProcess(SelectionProcessCreateDto model) | public async Task<bool> FinishSelectionProcess(SelectionProcessCreateDto model) | ||||
| { | { | ||||
| _logger.LogInformation($"Start finishing selection process with {model.Id}"); | |||||
| var sp = await _context.SelectionProcesses.FindAsync(model.Id); | var sp = await _context.SelectionProcesses.FindAsync(model.Id); | ||||
| if (sp is null) | if (sp is null) | ||||
| { | |||||
| _logger.LogError($"Process with id = {model.Id} not found"); | |||||
| throw new EntityNotFoundException("Selection process not found"); | throw new EntityNotFoundException("Selection process not found"); | ||||
| } | |||||
| _logger.LogError($"Changing status for {model.Id}"); | |||||
| sp.Status = "Odrađen"; | sp.Status = "Odrađen"; | ||||
| var nextLevel = _context.SelectionLevels.AsEnumerable().SkipWhile(obj => obj.Id != sp.SelectionLevelId).Skip(1).First(); | |||||
| _logger.LogError($"Skipping throught levels to come to next level"); | |||||
| var nextLevel = _context.SelectionLevels.AsEnumerable() | |||||
| .SkipWhile(obj => obj.Id != sp.SelectionLevelId) | |||||
| .Skip(1).First(); | |||||
| if (nextLevel is null) | if (nextLevel is null) | ||||
| throw new EntityNotFoundException("Candidate came to last selection level"); | |||||
| { | |||||
| _logger.LogError($"Applicant is in the last selection level"); | |||||
| throw new EntityNotFoundException("Candidate came to the last selection level"); | |||||
| } | |||||
| SelectionProcess newProcess = new SelectionProcess | SelectionProcess newProcess = new SelectionProcess | ||||
| { | { | ||||
| SchedulerId = model.SchedulerId | SchedulerId = model.SchedulerId | ||||
| }; | }; | ||||
| _context.SelectionProcesses.Add(newProcess); | _context.SelectionProcesses.Add(newProcess); | ||||
| return await _context.SaveChangesAsync() > 0; | |||||
| _logger.LogError($"Create and add new selection process"); | |||||
| var result = await _context.SaveChangesAsync() > 0; | |||||
| _logger.LogError($"Saved changes to db"); | |||||
| return result; | |||||
| } | } | ||||
| } | } | ||||
| } | } |
| using System; | |||||
| using System.Collections.Generic; | |||||
| using System.Linq; | |||||
| using System.Text; | |||||
| using System.Threading.Tasks; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class TechnologyService : ITechnologyService | public class TechnologyService : ITechnologyService | ||||
| { | { | ||||
| private readonly DatabaseContext _context; | private readonly DatabaseContext _context; | ||||
| private readonly ILogger<TechnologyService> _logger; | |||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| public TechnologyService(IMapper mapper, DatabaseContext context) | |||||
| public TechnologyService(IMapper mapper, DatabaseContext context, ILogger<TechnologyService> logger) | |||||
| { | { | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _context = context; | _context = context; | ||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<List<TechnologyResponseDto>> GetAllAsync() => | |||||
| _mapper.Map<List<TechnologyResponseDto>>(await _context.Technologies.ToListAsync()); | |||||
| public async Task<List<TechnologyApplicantViewDto>> GetAllAsync2() => | |||||
| _mapper.Map<List<TechnologyApplicantViewDto>>(await _context.Technologies.ToListAsync()); | |||||
| public async Task<TechnologyResponseDto> GetByIdAsync(int id) | |||||
| public async Task<List<TechnologyResponseDto>> GetAllAsync() | |||||
| { | { | ||||
| var technology = await _context.Technologies.FindAsync(id); | |||||
| if (technology is null) | |||||
| throw new EntityNotFoundException("Technology not found"); | |||||
| return _mapper.Map<TechnologyResponseDto>(technology); | |||||
| return _mapper.Map<List<TechnologyResponseDto>>(await _context.Technologies.ToListAsync()); | |||||
| } | } | ||||
| public async Task<TechnologyApplicantViewDto> GetByIdAsync2(int id) | |||||
| public async Task<TechnologyResponseDto> GetByIdAsync(int id) | |||||
| { | { | ||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var technology = await _context.Technologies.FindAsync(id); | var technology = await _context.Technologies.FindAsync(id); | ||||
| if (technology is null) | if (technology is null) | ||||
| { | |||||
| _logger.LogError($"Technology with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Technology not found"); | throw new EntityNotFoundException("Technology not found"); | ||||
| return _mapper.Map<TechnologyApplicantViewDto>(technology); | |||||
| } | |||||
| _logger.LogInformation($"Mapping Technology with id = {id}"); | |||||
| var result = _mapper.Map<TechnologyResponseDto>(technology); | |||||
| _logger.LogInformation($"Technology with id = {id} mapped successfully"); | |||||
| return result; | |||||
| } | } | ||||
| public async Task<Technology> GetEntityByIdAsync(int id) | public async Task<Technology> GetEntityByIdAsync(int id) | ||||
| { | { | ||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var technology = await _context.Technologies.FindAsync(id); | var technology = await _context.Technologies.FindAsync(id); | ||||
| if (technology is null) | if (technology is null) | ||||
| { | |||||
| _logger.LogError($"Technology with id = {id} not found"); | |||||
| throw new EntityNotFoundException("Technology not found"); | throw new EntityNotFoundException("Technology not found"); | ||||
| } | |||||
| _logger.LogInformation($"Technology with id = {id} found successfully"); | |||||
| return technology; | return technology; | ||||
| } | } | ||||
| } | } |
| using Diligent.WebAPI.Business.Services.Interfaces; | |||||
| using Diligent.WebAPI.Business.Settings; | |||||
| using Diligent.WebAPI.Contracts.DTOs.User; | |||||
| using Diligent.WebAPI.Data; | |||||
| using Microsoft.AspNetCore.Identity; | |||||
| using Microsoft.AspNetCore.WebUtilities; | |||||
| using Microsoft.Extensions.Logging; | |||||
| using System.Web; | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| namespace Diligent.WebAPI.Business.Services | |||||
| { | { | ||||
| public class UserService : IUserService | public class UserService : IUserService | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly DatabaseContext _databaseContext; | private readonly DatabaseContext _databaseContext; | ||||
| private readonly IEmailer _emailer; | private readonly IEmailer _emailer; | ||||
| //private readonly AuthorizationSettings _authSettings; | |||||
| //private readonly ILogger<UserService> _logger; | |||||
| //private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"; | |||||
| //private string[] SupportedClientsIds = { "" }; | |||||
| private readonly ILogger<UserService> _logger; | |||||
| public UserService(IOptions<FrontEndSettings> frontEndSettings, UserManager<User> userManager, IMapper mapper, DatabaseContext databaseContext, IEmailer emailer) | |||||
| public UserService(IOptions<FrontEndSettings> frontEndSettings, UserManager<User> userManager, IMapper mapper, DatabaseContext databaseContext, IEmailer emailer, ILogger<UserService> logger) | |||||
| { | { | ||||
| _frontEndSettings = frontEndSettings.Value; | _frontEndSettings = frontEndSettings.Value; | ||||
| _userManager = userManager; | _userManager = userManager; | ||||
| _mapper = mapper; | _mapper = mapper; | ||||
| _databaseContext = databaseContext; | _databaseContext = databaseContext; | ||||
| _emailer = emailer; | _emailer = emailer; | ||||
| //_authSettings = authSettings.Value; | |||||
| //_logger = logger; | |||||
| _logger = logger; | |||||
| } | } | ||||
| public async Task<IEnumerable<User?>> GetAll() => | |||||
| await _userManager.Users.ToListAsync(); | |||||
| public async Task<User?> GetById(int id) => | |||||
| await _userManager.FindByIdAsync(id.ToString()); | |||||
| public async Task<IEnumerable<User?>> GetAll() | |||||
| { | |||||
| _logger.LogInformation("Start getting all users"); | |||||
| _logger.LogInformation("Getting data from DB"); | |||||
| var fromDb = await _userManager.Users.ToListAsync(); | |||||
| _logger.LogInformation($"Received {fromDb.Count} ads from db."); | |||||
| return fromDb; | |||||
| } | |||||
| #region REFACTORING CODE HERE TO CHECK IF USER IS NULL | |||||
| public async Task<User?> GetById(int id) | |||||
| { | |||||
| _logger.LogInformation($"Start searching Ad with id = {id}"); | |||||
| var result = await _userManager.FindByIdAsync(id.ToString()); | |||||
| return result; | |||||
| } | |||||
| public async Task<User?> GetByEmail(string email) => | public async Task<User?> GetByEmail(string email) => | ||||
| await _userManager.FindByEmailAsync(email); | await _userManager.FindByEmailAsync(email); | ||||
| #endregion | |||||
| public async Task CreateUser(CreateUserRequestDto model) | public async Task CreateUser(CreateUserRequestDto model) | ||||
| { | { | ||||
| _logger.LogInformation($"Start creating user"); | |||||
| var user = _mapper.Map<User>(model); | var user = _mapper.Map<User>(model); | ||||
| _logger.LogInformation($"User created successfully"); | |||||
| _logger.LogInformation($"Saving user to db..."); | |||||
| await _userManager.CreateAsync(user, model.Password); | await _userManager.CreateAsync(user, model.Password); | ||||
| _logger.LogInformation($"User saved to DB"); | |||||
| } | } | ||||
| public async Task RemoveUser(User user) | public async Task RemoveUser(User user) | ||||
| { | { |
| global using Diligent.WebAPI.Contracts.DTOs.Insurer; | global using Diligent.WebAPI.Contracts.DTOs.Insurer; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.WebhookDefinition; | global using Diligent.WebAPI.Contracts.DTOs.WebhookDefinition; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.WebhookSubscription; | global using Diligent.WebAPI.Contracts.DTOs.WebhookSubscription; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.SelectionProcess; | |||||
| global using Diligent.WebAPI.Contracts.DTOs.Ad; | global using Diligent.WebAPI.Contracts.DTOs.Ad; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.Auth; | global using Diligent.WebAPI.Contracts.DTOs.Auth; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.User; | |||||
| global using Diligent.WebAPI.Contracts.DTOs; | global using Diligent.WebAPI.Contracts.DTOs; | ||||
| global using Diligent.WebAPI.Contracts.Exceptions; | global using Diligent.WebAPI.Contracts.Exceptions; | ||||
| global using Diligent.WebAPI.Contracts.Models; | global using Diligent.WebAPI.Contracts.Models; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.Applicant; | global using Diligent.WebAPI.Contracts.DTOs.Applicant; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.Technology; | global using Diligent.WebAPI.Contracts.DTOs.Technology; | ||||
| global using Diligent.WebAPI.Contracts.DTOs.SelectionLevel; | |||||
| global using Diligent.WebAPI.Contracts.DTOs.Comment; | |||||
| global using Diligent.WebAPI.Business.Extensions; | |||||
| global using Microsoft.EntityFrameworkCore; | global using Microsoft.EntityFrameworkCore; | ||||
| global using Microsoft.Extensions.Options; | global using Microsoft.Extensions.Options; | ||||
| global using Microsoft.IdentityModel.Tokens; | global using Microsoft.IdentityModel.Tokens; | ||||
| global using Newtonsoft.Json; | global using Newtonsoft.Json; | ||||
| global using RestSharp; | global using RestSharp; | ||||
| global using AutoMapper; | global using AutoMapper; | ||||
| global using System.Web; | |||||
| global using Microsoft.AspNetCore.Identity; | global using Microsoft.AspNetCore.Identity; | ||||
| global using Microsoft.Extensions.Logging; |
| <PropertyGroup> | <PropertyGroup> | ||||
| <Controller_SelectedScaffolderID>ApiControllerWithActionsScaffolder</Controller_SelectedScaffolderID> | <Controller_SelectedScaffolderID>ApiControllerWithActionsScaffolder</Controller_SelectedScaffolderID> | ||||
| <Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath> | <Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath> | ||||
| <ActiveDebugProfile>IIS Express</ActiveDebugProfile> | |||||
| <ActiveDebugProfile>Diligent.WebAPI.Host</ActiveDebugProfile> | |||||
| <NameOfLastUsedPublishProfile>IISProfile</NameOfLastUsedPublishProfile> | <NameOfLastUsedPublishProfile>IISProfile</NameOfLastUsedPublishProfile> | ||||
| </PropertyGroup> | </PropertyGroup> | ||||
| <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> |
| var builder = WebApplication.CreateBuilder(args); | |||||
| using Serilog; | |||||
| Log.Logger = new LoggerConfiguration() | |||||
| .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information) | |||||
| .Enrich.FromLogContext() | |||||
| .WriteTo.Console() | |||||
| .CreateBootstrapLogger(); | |||||
| try | |||||
| { | |||||
| Log.Information("Starting web host"); | |||||
| builder.ConfigureHost(); | |||||
| builder.ConfigureData(); | |||||
| builder.ConfigureBusiness(); | |||||
| var builder = WebApplication.CreateBuilder(args); | |||||
| var app = builder.Build(); | |||||
| app.ConfigureHost(); | |||||
| app.ConfigureData(); | |||||
| app.ConfigureBusiness(); | |||||
| builder.Host.UseSerilog((context, services, configuration) => configuration.ReadFrom.Configuration(context.Configuration).ReadFrom.Services(services).Enrich.FromLogContext()); | |||||
| app.Run(); | |||||
| builder.ConfigureHost(); | |||||
| builder.ConfigureData(); | |||||
| builder.ConfigureBusiness(); | |||||
| var app = builder.Build(); | |||||
| app.ConfigureHost(); | |||||
| app.ConfigureData(); | |||||
| app.ConfigureBusiness(); | |||||
| app.Run(); | |||||
| } | |||||
| catch (Exception ex) | |||||
| { | |||||
| Log.Fatal(ex, "Host terminated unexpectedly"); | |||||
| return 1; | |||||
| } | |||||
| finally | |||||
| { | |||||
| Log.CloseAndFlush(); | |||||
| } | |||||
| return 0; |
| { | { | ||||
| "Serilog": { | |||||
| "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ], | |||||
| "MinimumLevel": { | |||||
| "Default": "Debug", | |||||
| "Override": { | |||||
| "Microsoft": "Information", | |||||
| "Microsoft.AspNetCore": "Warning" | |||||
| } | |||||
| }, | |||||
| "WriteTo": [ | |||||
| { | |||||
| "Name": "Console" | |||||
| }, | |||||
| { | |||||
| "Name": "File", | |||||
| "Args": { "path": "Logs/log.txt" } | |||||
| }, | |||||
| { | |||||
| "Name": "Seq", | |||||
| "Args": { "ServerUrl": "http://localhost:5341" } | |||||
| } | |||||
| ], | |||||
| "Enrich": [ "FromLogContext", "WithMachineName", "WtihThreadId", "WithExceptionDetails" ] | |||||
| }, | |||||
| "ConnectionStrings": { | "ConnectionStrings": { | ||||
| "WebApi": "Server=192.168.88.105;Database=HRCenter;User Id=hrcentar;Password=" | "WebApi": "Server=192.168.88.105;Database=HRCenter;User Id=hrcentar;Password=" | ||||
| }, | }, |
| { | { | ||||
| "Serilog": { | |||||
| "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ], | |||||
| "MinimumLevel": { | |||||
| "Default": "Debug", | |||||
| "Override": { | |||||
| "Microsoft": "Information", | |||||
| "Microsoft.AspNetCore": "Warning" | |||||
| } | |||||
| }, | |||||
| "WriteTo": [ | |||||
| { | |||||
| "Name": "Console" | |||||
| }, | |||||
| { | |||||
| "Name": "File", | |||||
| "Args": { "path": "Logs/log.txt" } | |||||
| }, | |||||
| { | |||||
| "Name": "Seq", | |||||
| "Args": { "ServerUrl": "http://localhost:5341" } | |||||
| } | |||||
| ], | |||||
| "Enrich": [ "FromLogContext", "WithMachineName", "WtihThreadId", "WithExceptionDetails" ] | |||||
| }, | |||||
| "ConnectionStrings": { | "ConnectionStrings": { | ||||
| "WebApi": "Server=192.168.88.105;Database=HRCenter;User Id=hrcentar;Password=" | "WebApi": "Server=192.168.88.105;Database=HRCenter;User Id=hrcentar;Password=" | ||||
| }, | }, |
| using Diligent.WebAPI.Contracts.DTOs.Ad; | using Diligent.WebAPI.Contracts.DTOs.Ad; | ||||
| using Diligent.WebAPI.Contracts.Exceptions; | using Diligent.WebAPI.Contracts.Exceptions; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.Extensions.Logging; | |||||
| using System; | using System; | ||||
| using System.Collections.Generic; | using System.Collections.Generic; | ||||
| using System.Linq; | using System.Linq; | ||||
| private readonly List<Ad> _ads = new List<Ad>(); | private readonly List<Ad> _ads = new List<Ad>(); | ||||
| private readonly Ad _ad; | private readonly Ad _ad; | ||||
| private ITechnologyService _technologyService = Substitute.For<ITechnologyService>(); | private ITechnologyService _technologyService = Substitute.For<ITechnologyService>(); | ||||
| private ILogger<AdService> _logger = Substitute.For<ILogger<AdService>>(); | |||||
| private readonly List<Technology> _technologies = new List<Technology>(); | private readonly List<Technology> _technologies = new List<Technology>(); | ||||
| public AdServiceTests() | public AdServiceTests() | ||||
| public async Task GetAll_ShouldReturnListOfAds_WhenCalled() | public async Task GetAll_ShouldReturnListOfAds_WhenCalled() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var result = await adService.GetAllAsync(); | var result = await adService.GetAllAsync(); | ||||
| public async Task GetById_ShouldReturnAd_WhenAdExists() | public async Task GetById_ShouldReturnAd_WhenAdExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var result = await adService.GetByIdAsync(1); | var result = await adService.GetByIdAsync(1); | ||||
| public async Task GetById_ShouldThrowEntityNotFoundException_WhenAdDontExists() | public async Task GetById_ShouldThrowEntityNotFoundException_WhenAdDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.GetByIdAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.GetByIdAsync(1000)); | ||||
| } | } | ||||
| public async Task GetAdDetailsById_ShouldReturnAd_WhenAdExists() | public async Task GetAdDetailsById_ShouldReturnAd_WhenAdExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var result = await adService.GetAdDetailsByIdAsync(1); | var result = await adService.GetAdDetailsByIdAsync(1); | ||||
| public async Task GetAdDetailsById_ShouldThrowEntityNotFoundException_WhenAdDontExists() | public async Task GetAdDetailsById_ShouldThrowEntityNotFoundException_WhenAdDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.GetAdDetailsByIdAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.GetAdDetailsByIdAsync(1000)); | ||||
| } | } | ||||
| public async Task GetArchiveAds_ShouldReturnListOfAds_WhenCalled() | public async Task GetArchiveAds_ShouldReturnListOfAds_WhenCalled() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var result = await adService.GetArchiveAds(); | var result = await adService.GetArchiveAds(); | ||||
| public async Task GetFilteredAds_ShouldReturnListOfAds_WhenCalled() | public async Task GetFilteredAds_ShouldReturnListOfAds_WhenCalled() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var result = await adService.GetFilteredAdsAsync(new AdFilterDto | var result = await adService.GetFilteredAdsAsync(new AdFilterDto | ||||
| { | { | ||||
| public async Task CreateAd_ShouldAddAdIntoDatabase_WhenCalled() | public async Task CreateAd_ShouldAddAdIntoDatabase_WhenCalled() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| _technologyService.GetEntityByIdAsync(Arg.Any<int>()).Returns(new Technology | _technologyService.GetEntityByIdAsync(Arg.Any<int>()).Returns(new Technology | ||||
| { | { | ||||
| TechnologyId = 3, | TechnologyId = 3, | ||||
| public async Task UpdateAd_ShouldUpdateAd_WhenAdExists() | public async Task UpdateAd_ShouldUpdateAd_WhenAdExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| var updateForAd = new AdUpdateDto | var updateForAd = new AdUpdateDto | ||||
| { | { | ||||
| public async Task UpdateAd_ShouldThrowEntityNotFoundException_WhenAdDontExists() | public async Task UpdateAd_ShouldThrowEntityNotFoundException_WhenAdDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.UpdateAsync(1000, new AdUpdateDto | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.UpdateAsync(1000, new AdUpdateDto | ||||
| { | { | ||||
| public async Task DeleteAd_ShouldDeleteAdFromDatabase_WhenAdExists() | public async Task DeleteAd_ShouldDeleteAdFromDatabase_WhenAdExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| await adService.DeleteAsync(1); | await adService.DeleteAsync(1); | ||||
| public async Task DeleteAd_ShouldThrowEntityNotFoundException_WhenAdDontExists() | public async Task DeleteAd_ShouldThrowEntityNotFoundException_WhenAdDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| AdService adService = new(databaseContext, _mapper, _technologyService); | |||||
| AdService adService = new(databaseContext, _mapper, _technologyService, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.DeleteAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await adService.DeleteAsync(1000)); | ||||
| } | } |
| using AutoMapper; | using AutoMapper; | ||||
| using Castle.Core.Logging; | |||||
| using Diligent.WebAPI.Business.Extensions; | using Diligent.WebAPI.Business.Extensions; | ||||
| using Diligent.WebAPI.Business.MappingProfiles; | using Diligent.WebAPI.Business.MappingProfiles; | ||||
| using Diligent.WebAPI.Business.Services; | using Diligent.WebAPI.Business.Services; | ||||
| using Diligent.WebAPI.Contracts.Exceptions; | using Diligent.WebAPI.Contracts.Exceptions; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.AspNetCore.Http; | using Microsoft.AspNetCore.Http; | ||||
| using Microsoft.Extensions.Logging; | |||||
| using static Diligent.WebAPI.Data.Entities.Applicant; | using static Diligent.WebAPI.Data.Entities.Applicant; | ||||
| namespace Diligent.WebAPI.Tests.Services | namespace Diligent.WebAPI.Tests.Services | ||||
| public class ApplicantServiceTests | public class ApplicantServiceTests | ||||
| { | { | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private ILogger<ApplicantService> _logger = Substitute.For<ILogger<ApplicantService>>(); | |||||
| private readonly HttpContext _httpContext; | private readonly HttpContext _httpContext; | ||||
| private readonly List<Applicant> _applicants; | private readonly List<Applicant> _applicants; | ||||
| private readonly List<Ad> _ads; | private readonly List<Ad> _ads; | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| var filterDto = new ApplicantFilterDto(); | var filterDto = new ApplicantFilterDto(); | ||||
| public async Task GetById_ShouldReturnApplicant_WhenApplicantExist() | public async Task GetById_ShouldReturnApplicant_WhenApplicantExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| var result = await applicantService.GetById(1); | var result = await applicantService.GetById(1); | ||||
| public async Task GetById_ShouldThrowEntityNotFooundException_WhenApplicantDontExist() | public async Task GetById_ShouldThrowEntityNotFooundException_WhenApplicantDontExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await applicantService.GetById(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await applicantService.GetById(1000)); | ||||
| } | } | ||||
| [Fact] | |||||
| public async Task CreateApplicant_ShouldAddEntityIntoDatabase_Always() | |||||
| { | |||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantCreateDto applicantCreateDto = new() | |||||
| { | |||||
| ApplicationChannel = "Facebook", | |||||
| BitBucketLink = null, | |||||
| CV = "link", | |||||
| Email = "some@mail.com", | |||||
| Experience = 1, | |||||
| FirstName = "Meris", | |||||
| LastName = "Ahmatovic", | |||||
| GithubLink = null, | |||||
| LinkedlnLink = null, | |||||
| PhoneNumber = "432424", | |||||
| Position = ".NET Developer", | |||||
| TypeOfEmployment = TypesOfEmployment.Intership.ToString() | |||||
| }; | |||||
| await applicantService.CreateApplicant(applicantCreateDto); | |||||
| var filterDto = new ApplicantFilterDto | |||||
| { | |||||
| CurrentPage = 1, | |||||
| PageSize = 4 | |||||
| }; | |||||
| var result = await applicantService.GetFilteredApplicants(filterDto); | |||||
| Assert.Equal(2, result.Total); | |||||
| } | |||||
| //[Fact] | |||||
| //public async Task CreateApplicant_ShouldAddEntityIntoDatabase_Always() | |||||
| //{ | |||||
| // var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | |||||
| // ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| // ApplicantCreateDto applicantCreateDto = new() | |||||
| // { | |||||
| // ApplicationChannel = "Facebook", | |||||
| // BitBucketLink = null, | |||||
| // CV = "link", | |||||
| // Email = "some@mail.com", | |||||
| // Experience = 1, | |||||
| // FirstName = "Meris", | |||||
| // LastName = "Ahmatovic", | |||||
| // GithubLink = null, | |||||
| // LinkedlnLink = null, | |||||
| // PhoneNumber = "432424", | |||||
| // Position = ".NET Developer", | |||||
| // TypeOfEmployment = TypesOfEmployment.Intership.ToString() | |||||
| // }; | |||||
| // await applicantService.CreateApplicant(applicantCreateDto); | |||||
| // var filterDto = new ApplicantFilterDto | |||||
| // { | |||||
| // CurrentPage = 1, | |||||
| // PageSize = 4 | |||||
| // }; | |||||
| // var result = await applicantService.GetFilteredApplicants(filterDto); | |||||
| // Assert.Equal(2, result.Total); | |||||
| //} | |||||
| [Fact] | [Fact] | ||||
| public async Task DeleteApplicant_ShouldDeleteApplicant_WhenApplicantExist() | public async Task DeleteApplicant_ShouldDeleteApplicant_WhenApplicantExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| await applicantService.DeleteApplicant(1); | await applicantService.DeleteApplicant(1); | ||||
| public async Task DeleteApplicant_ShouldThrowEntityNotFooundException_WhenApplicantDontExist() | public async Task DeleteApplicant_ShouldThrowEntityNotFooundException_WhenApplicantDontExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await applicantService.DeleteApplicant(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await applicantService.DeleteApplicant(1000)); | ||||
| } | } | ||||
| [Fact] | |||||
| public async Task UpdateApplicant_ShouldUpdateApplicant_WhenApplicantExist() | |||||
| { | |||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantUpdateDto applicantUpdateDto = new() | |||||
| { | |||||
| ApplicationChannel = "Instagram", | |||||
| BitBucketLink = null, | |||||
| CV = "link", | |||||
| Email = "some@mail.com", | |||||
| Experience = 1, | |||||
| FirstName = "Dzenis", | |||||
| LastName = "Hadzifejzovic", | |||||
| GithubLink = null, | |||||
| LinkedlnLink = null, | |||||
| PhoneNumber = "432424", | |||||
| Position = "React Developer" | |||||
| }; | |||||
| await applicantService.UpdateApplicant(1, applicantUpdateDto); | |||||
| var applicant = await applicantService.GetById(1); | |||||
| Assert.Equal(applicant.Position, applicantUpdateDto.Position); | |||||
| } | |||||
| //[Fact] | |||||
| //public async Task UpdateApplicant_ShouldUpdateApplicant_WhenApplicantExist() | |||||
| //{ | |||||
| // var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | |||||
| // ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| // ApplicantUpdateDto applicantUpdateDto = new() | |||||
| // { | |||||
| // ApplicationChannel = "Instagram", | |||||
| // BitBucketLink = null, | |||||
| // CV = "link", | |||||
| // Email = "some@mail.com", | |||||
| // Experience = 1, | |||||
| // FirstName = "Dzenis", | |||||
| // LastName = "Hadzifejzovic", | |||||
| // GithubLink = null, | |||||
| // LinkedlnLink = null, | |||||
| // PhoneNumber = "432424", | |||||
| // Position = "React Developer" | |||||
| // }; | |||||
| // await applicantService.UpdateApplicant(1, applicantUpdateDto); | |||||
| // var applicant = await applicantService.GetById(1); | |||||
| // Assert.Equal(applicant.Position, applicantUpdateDto.Position); | |||||
| //} | |||||
| [Fact] | [Fact] | ||||
| public async Task GetAllAdsApplicants_ShouldReturnListOfAdApplicants_Always() | public async Task GetAllAdsApplicants_ShouldReturnListOfAdApplicants_Always() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | var databaseContext = await Helpers<Ad>.GetDatabaseContext(_ads); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| var filterDto = MockData.GetApplicantFilters(); | var filterDto = MockData.GetApplicantFilters(); | ||||
| public async Task GetApplicantWithSelectionProcessesById_ShouldReturnApplicant_WhenApplicantExists() | public async Task GetApplicantWithSelectionProcessesById_ShouldReturnApplicant_WhenApplicantExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | var databaseContext = await Helpers<Applicant>.GetDatabaseContext(_applicants); | ||||
| ApplicantService applicantService = new(databaseContext, _mapper); | |||||
| ApplicantService applicantService = new(databaseContext, _mapper, _logger); | |||||
| var result = await applicantService.GetApplicantWithSelectionProcessesById(1); | var result = await applicantService.GetApplicantWithSelectionProcessesById(1); | ||||
| var processes = result.SelectionProcesses; | var processes = result.SelectionProcesses; |
| using Diligent.WebAPI.Contracts.DTOs.Comment; | using Diligent.WebAPI.Contracts.DTOs.Comment; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.EntityFrameworkCore; | using Microsoft.EntityFrameworkCore; | ||||
| using Microsoft.Extensions.Logging; | |||||
| namespace Diligent.WebAPI.Tests.Services | namespace Diligent.WebAPI.Tests.Services | ||||
| { | { | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly List<Comment> _comments; | private readonly List<Comment> _comments; | ||||
| private readonly List<Applicant> _applicants; | private readonly List<Applicant> _applicants; | ||||
| private ILogger<CommentService> _logger = Substitute.For<ILogger<CommentService>>(); | |||||
| private readonly List<User> _users; | private readonly List<User> _users; | ||||
| public CommentServiceTests() | public CommentServiceTests() | ||||
| { | { | ||||
| public async Task CreateComment_ShouldUpdatedListOfComments_Always() | public async Task CreateComment_ShouldUpdatedListOfComments_Always() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Comment>.GetDatabaseContext(_comments); | var databaseContext = await Helpers<Comment>.GetDatabaseContext(_comments); | ||||
| CommentService applicantService = new(databaseContext, _mapper); | |||||
| CommentService applicantService = new(databaseContext, _mapper, _logger); | |||||
| var commentCreateDto = new CommentCreateDto | var commentCreateDto = new CommentCreateDto | ||||
| { | { |
| using Diligent.WebAPI.Contracts.DTOs.SelectionLevel; | using Diligent.WebAPI.Contracts.DTOs.SelectionLevel; | ||||
| using Diligent.WebAPI.Contracts.Exceptions; | using Diligent.WebAPI.Contracts.Exceptions; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.Extensions.Logging; | |||||
| namespace Diligent.WebAPI.Tests.Services | namespace Diligent.WebAPI.Tests.Services | ||||
| { | { | ||||
| { | { | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly List<SelectionLevel> _levels; | private readonly List<SelectionLevel> _levels; | ||||
| private ILogger<SelectionLevelService> _logger = Substitute.For<ILogger<SelectionLevelService>>(); | |||||
| private readonly SelectionLevel _selectionLevel; | private readonly SelectionLevel _selectionLevel; | ||||
| public SelectionLevelsServiceTests() | public SelectionLevelsServiceTests() | ||||
| { | { | ||||
| public async Task GetAll_ShouldReturnListOfLevels_Always() | public async Task GetAll_ShouldReturnListOfLevels_Always() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | ||||
| SelectionLevelService service = new(databaseContext, _mapper); | |||||
| SelectionLevelService service = new(databaseContext, _mapper, _logger); | |||||
| var result = await service.GetAllAsync(); | var result = await service.GetAllAsync(); | ||||
| new SelectionProcess{ Id = 4, Status = "Čeka na zakazivanje", Date = DateTime.Now.AddMonths(-1)}, | new SelectionProcess{ Id = 4, Status = "Čeka na zakazivanje", Date = DateTime.Now.AddMonths(-1)}, | ||||
| }; | }; | ||||
| SelectionLevelService service = new(databaseContext, _mapper); | |||||
| SelectionLevelService service = new(databaseContext, _mapper, _logger); | |||||
| var filter = new SelectionProcessFilterDto | var filter = new SelectionProcessFilterDto | ||||
| { | { | ||||
| DateStart = DateTime.Now.AddDays(-1), | DateStart = DateTime.Now.AddDays(-1), | ||||
| public async Task GetById_ShouldReturnLevel_WhenLevelExist() | public async Task GetById_ShouldReturnLevel_WhenLevelExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | ||||
| SelectionLevelService service = new(databaseContext, _mapper); | |||||
| SelectionLevelService service = new(databaseContext, _mapper, _logger); | |||||
| var result = await service.GetByIdAsync(1); | var result = await service.GetByIdAsync(1); | ||||
| public async Task GetById_ShouldThrowEntityNotFooundException_WhenLevelDoesnotExist() | public async Task GetById_ShouldThrowEntityNotFooundException_WhenLevelDoesnotExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | var databaseContext = await Helpers<SelectionLevel>.GetDatabaseContext(_levels); | ||||
| SelectionLevelService service = new(databaseContext, _mapper); | |||||
| SelectionLevelService service = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.GetByIdAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.GetByIdAsync(1000)); | ||||
| } | } |
| using Diligent.WebAPI.Contracts.DTOs.SelectionProcess; | using Diligent.WebAPI.Contracts.DTOs.SelectionProcess; | ||||
| using Diligent.WebAPI.Contracts.Exceptions; | using Diligent.WebAPI.Contracts.Exceptions; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.Extensions.Logging; | |||||
| namespace Diligent.WebAPI.Tests.Services | namespace Diligent.WebAPI.Tests.Services | ||||
| { | { | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly List<SelectionProcess> _processes; | private readonly List<SelectionProcess> _processes; | ||||
| private readonly SelectionProcess _selectionProcess; | private readonly SelectionProcess _selectionProcess; | ||||
| private ILogger<SelectionProcessService> _logger = Substitute.For<ILogger<SelectionProcessService>>(); | |||||
| private readonly SelectionProcessCreateDto _selectionProcessCreateDto; | private readonly SelectionProcessCreateDto _selectionProcessCreateDto; | ||||
| public SelectionProcessServiceTests() | public SelectionProcessServiceTests() | ||||
| { | { | ||||
| public async Task GetAll_ShouldReturnListOfProcesses_Always() | public async Task GetAll_ShouldReturnListOfProcesses_Always() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | ||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| var result = await service.GetAllAsync(); | var result = await service.GetAllAsync(); | ||||
| result.Should().HaveCount(1); | result.Should().HaveCount(1); | ||||
| } | } | ||||
| [Fact] | |||||
| public async Task GetById_ShouldReturnProcess_WhenProcessExist() | |||||
| { | |||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | |||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| //[Fact] | |||||
| //public async Task GetById_ShouldReturnProcess_WhenProcessExist() | |||||
| //{ | |||||
| // var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | |||||
| // SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| var result = await service.GetByIdAsync(1); | |||||
| // var result = await service.GetByIdAsync(1); | |||||
| result.Should().BeEquivalentTo(_mapper.Map<SelectionProcessResposneDto>(_selectionProcess)); | |||||
| } | |||||
| // result.Should().BeEquivalentTo(_mapper.Map<SelectionProcessResposneDto>(_selectionProcess)); | |||||
| //} | |||||
| [Fact] | |||||
| public async Task GetById_ShouldThrowEntityNotFooundException_WhenProcessDoesnotExist() | |||||
| { | |||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | |||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| //[Fact] | |||||
| //public async Task GetById_ShouldThrowEntityNotFooundException_WhenProcessDoesnotExist() | |||||
| //{ | |||||
| // var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | |||||
| // SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.GetByIdAsync(1000)); | |||||
| } | |||||
| // await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.GetByIdAsync(1000)); | |||||
| //} | |||||
| [Fact] | [Fact] | ||||
| public async Task FinishSelectionProcess_ShouldReturnTrueAndAddNewSelectionProcess_WhenProcessExists() | public async Task FinishSelectionProcess_ShouldReturnTrueAndAddNewSelectionProcess_WhenProcessExists() | ||||
| }; | }; | ||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(processes); | var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(processes); | ||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| var result = await service.FinishSelectionProcess(_selectionProcessCreateDto); | var result = await service.FinishSelectionProcess(_selectionProcessCreateDto); | ||||
| var newProcesses = await service.GetAllAsync(); | var newProcesses = await service.GetAllAsync(); | ||||
| public async Task FinishSelectionProcess_ShouldThrowEntityNotFooundException_WhenProcessDoesnotExist() | public async Task FinishSelectionProcess_ShouldThrowEntityNotFooundException_WhenProcessDoesnotExist() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | ||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.FinishSelectionProcess(new SelectionProcessCreateDto { Id = 1000 })); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await service.FinishSelectionProcess(new SelectionProcessCreateDto { Id = 1000 })); | ||||
| } | } | ||||
| public async Task FinishSelectionProcess_ShouldThrowEntityNotFooundException_WhenProcessIsInLastLevel() | public async Task FinishSelectionProcess_ShouldThrowEntityNotFooundException_WhenProcessIsInLastLevel() | ||||
| { | { | ||||
| var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | var databaseContext = await Helpers<SelectionProcess>.GetDatabaseContext(_processes); | ||||
| SelectionProcessService service = new(databaseContext, _mapper); | |||||
| SelectionProcessService service = new(databaseContext, _mapper, _logger); | |||||
| await Assert.ThrowsAsync<InvalidOperationException>(async () => await service.FinishSelectionProcess(new SelectionProcessCreateDto { Id = 1, SelectionLevelId = 4 })); | await Assert.ThrowsAsync<InvalidOperationException>(async () => await service.FinishSelectionProcess(new SelectionProcessCreateDto { Id = 1, SelectionLevelId = 4 })); | ||||
| } | } |
| using AutoMapper; | using AutoMapper; | ||||
| using Castle.Core.Logging; | |||||
| using Diligent.WebAPI.Business.MappingProfiles; | using Diligent.WebAPI.Business.MappingProfiles; | ||||
| using Diligent.WebAPI.Business.Services; | using Diligent.WebAPI.Business.Services; | ||||
| using Diligent.WebAPI.Contracts.DTOs.Technology; | using Diligent.WebAPI.Contracts.DTOs.Technology; | ||||
| using Diligent.WebAPI.Contracts.Exceptions; | using Diligent.WebAPI.Contracts.Exceptions; | ||||
| using Diligent.WebAPI.Data.Entities; | using Diligent.WebAPI.Data.Entities; | ||||
| using Microsoft.Extensions.Logging; | |||||
| using System; | using System; | ||||
| using System.Collections.Generic; | using System.Collections.Generic; | ||||
| using System.Linq; | using System.Linq; | ||||
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly List<Technology> _technologies = new(); | private readonly List<Technology> _technologies = new(); | ||||
| private readonly Technology _technology; | private readonly Technology _technology; | ||||
| private readonly ILogger<TechnologyService> _logger = Substitute.For<ILogger<TechnologyService>>(); | |||||
| public TechnologyServiceTests() | public TechnologyServiceTests() | ||||
| { | { | ||||
| public async Task GetAll_ShouldReturnListOfTechnologies_WhenCalled() | public async Task GetAll_ShouldReturnListOfTechnologies_WhenCalled() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | ||||
| TechnologyService tehnologyService = new(_mapper, databaseContext); | |||||
| TechnologyService tehnologyService = new(_mapper, databaseContext, _logger); | |||||
| var result = await tehnologyService.GetAllAsync(); | var result = await tehnologyService.GetAllAsync(); | ||||
| public async Task GetById_ShouldReturnTechnology_WhenTechnologyExists() | public async Task GetById_ShouldReturnTechnology_WhenTechnologyExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | ||||
| TechnologyService tehnologyService = new(_mapper, databaseContext); | |||||
| TechnologyService tehnologyService = new(_mapper, databaseContext, _logger); | |||||
| var result = await tehnologyService.GetByIdAsync(1); | var result = await tehnologyService.GetByIdAsync(1); | ||||
| public async Task GetById_ShouldThrowEntityNotFoundException_WhenTechnologyDontExists() | public async Task GetById_ShouldThrowEntityNotFoundException_WhenTechnologyDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | ||||
| TechnologyService tehnologyService = new(_mapper, databaseContext); | |||||
| TechnologyService tehnologyService = new(_mapper, databaseContext, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await tehnologyService.GetByIdAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await tehnologyService.GetByIdAsync(1000)); | ||||
| } | } | ||||
| public async Task GetEntityById_ShouldReturnTechnology_WhenTechnologyExists() | public async Task GetEntityById_ShouldReturnTechnology_WhenTechnologyExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | ||||
| TechnologyService tehnologyService = new(_mapper, databaseContext); | |||||
| TechnologyService tehnologyService = new(_mapper, databaseContext, _logger); | |||||
| var result = await tehnologyService.GetEntityByIdAsync(1); | var result = await tehnologyService.GetEntityByIdAsync(1); | ||||
| public async Task GetEntityById_ShouldThrowEntityNotFoundException_WhenTechnologyDontExists() | public async Task GetEntityById_ShouldThrowEntityNotFoundException_WhenTechnologyDontExists() | ||||
| { | { | ||||
| var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | var databaseContext = await Helpers<Technology>.GetDatabaseContext(_technologies); | ||||
| TechnologyService tehnologyService = new(_mapper, databaseContext); | |||||
| TechnologyService tehnologyService = new(_mapper, databaseContext, _logger); | |||||
| await Assert.ThrowsAsync<EntityNotFoundException>(async () => await tehnologyService.GetEntityByIdAsync(1000)); | await Assert.ThrowsAsync<EntityNotFoundException>(async () => await tehnologyService.GetEntityByIdAsync(1000)); | ||||
| } | } |
| private readonly IMapper _mapper; | private readonly IMapper _mapper; | ||||
| private readonly IUserStore<User> _mockStore; | private readonly IUserStore<User> _mockStore; | ||||
| private readonly UserManager<User> _mockUserManager; | private readonly UserManager<User> _mockUserManager; | ||||
| private readonly ILogger<UserService> _logger; | |||||
| public UserServiceTests() | public UserServiceTests() | ||||
| { | { | ||||
| _mockStore = Substitute.For<IUserStore<User>>(); | _mockStore = Substitute.For<IUserStore<User>>(); | ||||
| _mockUserManager = Substitute.For<UserManager<User>>(_mockStore, null, null, null, null, null, null, null, null); | _mockUserManager = Substitute.For<UserManager<User>>(_mockStore, null, null, null, null, null, null, null, null); | ||||
| _logger = Substitute.For<ILogger<UserService>>(); | |||||
| _user = new User | _user = new User | ||||
| { | { | ||||
| var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | ||||
| var mailer = Substitute.For<IEmailer>(); | var mailer = Substitute.For<IEmailer>(); | ||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer); | |||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer, _logger); | |||||
| var result = await service.GetById(1); | var result = await service.GetById(1); | ||||
| result.Should().Be(_user); | result.Should().Be(_user); | ||||
| } | } | ||||
| var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | ||||
| var mailer = Substitute.For<IEmailer>(); | var mailer = Substitute.For<IEmailer>(); | ||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer); | |||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer, _logger); | |||||
| var result = await service.GetByEmail("mail"); | var result = await service.GetByEmail("mail"); | ||||
| result.Should().Be(_user); | result.Should().Be(_user); | ||||
| } | } | ||||
| var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | ||||
| var mailer = Substitute.For<IEmailer>(); | var mailer = Substitute.For<IEmailer>(); | ||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer); | |||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer, _logger); | |||||
| await service.RemoveUser(_user); | await service.RemoveUser(_user); | ||||
| var result = await service.GetById(2); | var result = await service.GetById(2); | ||||
| var databaseContext = await Helpers<User>.GetDatabaseContext(_users); | var databaseContext = await Helpers<User>.GetDatabaseContext(_users); | ||||
| var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | ||||
| var mailer = Substitute.For<IEmailer>(); | var mailer = Substitute.For<IEmailer>(); | ||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer); | |||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer, _logger); | |||||
| var result = await service.ToggleEnable(_user); | var result = await service.ToggleEnable(_user); | ||||
| Assert.Equal(false, result); | Assert.Equal(false, result); | ||||
| var databaseContext = await Helpers<User>.GetDatabaseContext(_users); | var databaseContext = await Helpers<User>.GetDatabaseContext(_users); | ||||
| var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | var frontSettings = Substitute.For<IOptions<FrontEndSettings>>(); | ||||
| var mailer = Substitute.For<IEmailer>(); | var mailer = Substitute.For<IEmailer>(); | ||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer); | |||||
| var service = new UserService(frontSettings, _mockUserManager, _mapper, databaseContext, mailer, _logger); | |||||
| var result = await service.SendRegistrationLink(new Contracts.DTOs.User.InviteDTO | var result = await service.SendRegistrationLink(new Contracts.DTOs.User.InviteDTO | ||||
| { | { |