Beispiel #1
0
        public async Task <Guid> SaveOutcomePostRequestToCache(OutcomePostRequest request)
        {
            var key = Guid.NewGuid();
            await _cacheStorageService.SaveToCache(key.ToString(), request, 1);

            return(key);
        }
        public async Task <GetRoutesListResponse> GetRoutes()
        {
            var response = await _cacheStorageService.RetrieveFromCache <GetRoutesListResponse>(nameof(GetRoutesListResponse));

            if (response == null)
            {
                response = await _coursesApiClient.Get <GetRoutesListResponse>(new GetRoutesListRequest());

                await _cacheStorageService.SaveToCache(nameof(GetRoutesListResponse), response, 23);
            }

            return(response);
        }
Beispiel #3
0
        private async Task UpdateCachedItems(Task <GetSectorsListResponse> sectorsTask, Task <GetLevelsListResponse> levelsTask)
        {
            if (_saveSectorsToCache)
            {
                await _cacheStorageService
                .SaveToCache(nameof(GetSectorsListResponse), sectorsTask.Result, ExpirationInHours);
            }

            if (_saveLevelsToCache)
            {
                await _cacheStorageService.SaveToCache(nameof(GetLevelsListResponse), levelsTask.Result,
                                                       ExpirationInHours);
            }
        }
        public async Task <FrameworkDetailsViewModel> GetFramework(string id)
        {
            var cacheKey = $"FatComponentsCache-Apprenticeship_details-{id}";

            var cacheEntry = await _cacheService.RetrieveFromCache <FrameworkDetailsViewModel>(cacheKey);

            if (cacheEntry == null)
            {
                var response = await _mediator.Send(new GetFrameworkQuery { Id = id });

                string message;

                switch (response.StatusCode)
                {
                case GetFrameworkResponse.ResponseCodes.InvalidFrameworkId:
                    _logger.Info("404 - Framework id has wrong format");
                    throw new ArgumentException($"Framework id: {id} has wrong format");

                case GetFrameworkResponse.ResponseCodes.FrameworkNotFound:
                    message = $"Cannot find framework: {id}";
                    _logger.Warn($"404 - {message}");

                    throw new ArgumentException(message);

                case GetFrameworkResponse.ResponseCodes.Gone:
                    message = $"Expired framework request: {id}";

                    _logger.Warn($"410 - {message}");

                    throw new ArgumentException(message);

                case GetFrameworkResponse.ResponseCodes.Success:
                    _logger.Info($"mapping framework {id}");
                    cacheEntry = _frameworkDetailsViewModelMapper.Map(response.Framework);

                    _logger.Info($"Saving to cache");
                    await _cacheService.SaveToCache(cacheKey, cacheEntry, new TimeSpan(_cacheSettings.CacheAbsoluteExpirationDays, 0, 0, 0), new TimeSpan(_cacheSettings.CacheSlidingExpirationDays, 0, 0, 0));

                    break;

                default:
                    _logger.Info($"Cannot handle GetFrameworkQuery response: {response.StatusCode.ToString()}");
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(cacheEntry);
        }
Beispiel #5
0
        public async Task <TrainingProviderDetailsViewModel> GetDetails(TrainingProviderDetailQueryViewModel detailsQueryModel)
        {
            var cacheKey = $"FatComponentsCache-providerdetails-{detailsQueryModel.Ukprn}-{detailsQueryModel.LocationId}-{detailsQueryModel.ApprenticeshipId}";

            var cacheEntry = await _cacheService.RetrieveFromCache <TrainingProviderDetailsViewModel>(cacheKey);

            if (cacheEntry == null)
            {
                var response = await _mediator.Send(new ApprenticeshipProviderDetailQuery()
                {
                    UkPrn = Convert.ToInt32(detailsQueryModel.Ukprn), ApprenticeshipId = detailsQueryModel.ApprenticeshipId, ApprenticeshipType = detailsQueryModel.ApprenticeshipType, LocationId = detailsQueryModel.LocationId
                });

                if (response.StatusCode == ApprenticeshipProviderDetailResponse.ResponseCodes.ApprenticeshipProviderNotFound)
                {
                    var message = $"Cannot find provider: {detailsQueryModel.Ukprn}";
                    _logger.Warn($"404 - {message}");
                    throw new HttpRequestException(message);
                }

                if (response.StatusCode == ApprenticeshipProviderDetailResponse.ResponseCodes.InvalidInput)
                {
                    var message = $"Not able to call the apprenticeship service.";
                    _logger.Warn($"{response.StatusCode} - {message}");

                    throw new HttpRequestException(message);
                }

                cacheEntry = _trainingProviderDetailsViewModelMapper.Map(response, detailsQueryModel.ApprenticeshipId);

                await _cacheService.SaveToCache(cacheKey, cacheEntry, new TimeSpan(_cacheSettings.CacheAbsoluteExpirationDays, 0, 0, 0), new TimeSpan(_cacheSettings.CacheSlidingExpirationDays, 0, 0, 0));
            }

            return(cacheEntry);
        }
Beispiel #6
0
        public async Task <Unit> Handle(CacheReservationStartDateCommand command, CancellationToken cancellationToken)
        {
            var queryValidationResult = await _validator.ValidateAsync(command);

            if (!queryValidationResult.IsValid())
            {
                throw new ValidationException(queryValidationResult.ConvertToDataAnnotationsValidationResult(), null, null);
            }

            CachedReservation cachedReservation;

            if (!command.UkPrn.HasValue)
            {
                cachedReservation = await _cachedReservationRepository.GetEmployerReservation(command.Id);
            }
            else
            {
                cachedReservation = await _cachedReservationRepository.GetProviderReservation(command.Id, command.UkPrn.Value);
            }

            if (cachedReservation == null)
            {
                throw new CachedReservationNotFoundException(command.Id);
            }

            cachedReservation.TrainingDate = command.TrainingDate;

            await _cacheStorageService.SaveToCache(command.Id.ToString(), cachedReservation, 1);

            return(Unit.Value);
        }
Beispiel #7
0
        private async Task <IDictionary <string, Course> > CacheCoursesFromApi()
        {
            var apiRequest = new GetCoursesApiRequest(_options.Url);

            var result = await _apiClient.Get <GetCoursesApiResponse>(apiRequest);

            var coursesLookUp = result.Courses.ToDictionary(course => course.Id);

            await _cacheService.SaveToCache(nameof(CourseService), coursesLookUp, 24);

            return(coursesLookUp);
        }
Beispiel #8
0
        private async Task <int?> GetSectorId(string sector)
        {
            var response = await _cacheStorageService.RetrieveFromCache <GetRoutesListResponse>(nameof(GetRoutesListResponse));

            if (response == null)
            {
                response = await _coursesApiClient.Get <GetRoutesListResponse>(new GetRoutesListRequest());

                await _cacheStorageService.SaveToCache(nameof(GetRoutesListResponse), response, 23);
            }

            return(response.Routes.FirstOrDefault(c => c.Name.Equals(sector, StringComparison.CurrentCultureIgnoreCase))?.Id);
        }
        private async Task <List <ReferenceDataItem> > GetFromApiWithCache(IGetAllApiRequest request)
        {
            var result = await _cacheStorageService.RetrieveFromCache <List <ReferenceDataItem> >($"{CacheKeyPrefix}{request.GetAllUrl}");

            if (result != null)
            {
                return(result);
            }

            var response = (await _levyTransferMatchingApiClient.GetAll <ReferenceDataItem>(request)).ToList();
            await _cacheStorageService.SaveToCache($"{CacheKeyPrefix}{request.GetAllUrl}", response, CacheExpiryInHours);

            return(response);
        }
Beispiel #10
0
        public async Task <List <Course> > GetAllCourses()
        {
            var cacheResult = await _cacheStorageService.RetrieveFromCache <List <Course> >($"{CacheKey}");

            if (cacheResult != null)
            {
                return(cacheResult);
            }

            var result = await GetAllCoursesFromApi();

            await _cacheStorageService.SaveToCache($"{CacheKey}", result, CacheExpiryInHours);

            return(result);
        }
        public async Task <IReadOnlyList <GetDeliveryAreaListItem> > GetDeliveryAreas()
        {
            var deliveryAreas = await _cacheStorageService
                                .RetrieveFromCache <IReadOnlyList <GetDeliveryAreaListItem> >(nameof(GetDeliveryAreasRequest));

            if (deliveryAreas != null)
            {
                return(deliveryAreas);
            }

            deliveryAreas = (await _assessorsApiClient.GetAll <GetDeliveryAreaListItem>(new GetDeliveryAreasRequest())).ToList();
            await _cacheStorageService.SaveToCache(nameof(GetDeliveryAreasRequest), deliveryAreas, DeliveryAreaCacheDurationInHours);

            return(deliveryAreas);
        }
        public async Task <DeliveryAreaList> GetDeliveryAreas()
        {
            var cachedDeliveryAreas = await _cacheStorageService.RetrieveFromCache <DeliveryAreaList>(nameof(DeliveryAreaList));

            if (cachedDeliveryAreas != default)
            {
                return(cachedDeliveryAreas);
            }

            var apiRequest    = new GetDeliveryAreasApiRequest();
            var deliveryAreas = await _apiClient.Get <DeliveryAreaList>(apiRequest);

            await _cacheStorageService.SaveToCache(nameof(DeliveryAreaList), deliveryAreas, CacheDurationInHours);

            return(deliveryAreas);
        }
Beispiel #13
0
        public async Task <GetRoutesQueryResult> Handle(GetRoutesQuery request, CancellationToken cancellationToken)
        {
            var response = await _cacheStorageService.RetrieveFromCache <GetRoutesListResponse>(nameof(GetRoutesListResponse));

            if (response == null)
            {
                response = await _coursesApiClient.Get <GetRoutesListResponse>(new GetRoutesListRequest());

                await _cacheStorageService.SaveToCache(nameof(GetRoutesListResponse), response, 23);
            }

            return(new GetRoutesQueryResult
            {
                Routes = response.Routes
            });
        }
        public async Task <GetStandardsListResponse> GetCourses()
        {
            var courses = await _cacheStorageService
                          .RetrieveFromCache <GetStandardsListResponse>(nameof(GetStandardsListResponse));

            if (courses != null)
            {
                return(courses);
            }

            courses = await _coursesApiClient.Get <GetStandardsListResponse>(new GetActiveStandardsListRequest());

            await _cacheStorageService.SaveToCache(nameof(GetStandardsListResponse), courses, DeliveryAreaCacheDurationInHours);

            return(courses);
        }
Beispiel #15
0
        public async Task <CourseList> GetCourses()
        {
            var cachedCourseList = await _cacheStorageService.RetrieveFromCache <CourseList>(nameof(CourseList));

            if (cachedCourseList != default)
            {
                return(cachedCourseList);
            }

            var apiRequest = new GetCoursesApiRequest();
            var courseList = await _apiClient.Get <CourseList>(apiRequest);

            await _cacheStorageService.SaveToCache(nameof(CourseList), courseList, CacheDurationInHours);

            return(courseList);
        }
Beispiel #16
0
        public async Task <Unit> Handle(CacheReservationEmployerCommand command, CancellationToken cancellationToken)
        {
            var validationResult = await _validator.ValidateAsync(command);

            if (!validationResult.IsValid())
            {
                throw new ValidationException(validationResult.ConvertToDataAnnotationsValidationResult(), null, null);
            }

            if (validationResult.FailedRuleValidation)
            {
                throw new ReservationLimitReachedException(command.AccountId);
            }

            if (validationResult.FailedAuthorisationValidation)
            {
                throw new ProviderNotAuthorisedException(command.AccountId, command.UkPrn.Value);
            }

            if (validationResult.FailedGlobalRuleValidation)
            {
                throw new GlobalReservationRuleException(command.AccountId);
            }

            if (validationResult.FailedEoiCheck)
            {
                throw new NonEoiUserAccessDeniedException(command.AccountId);
            }

            var reservation = new CachedReservation
            {
                Id                               = command.Id,
                AccountId                        = command.AccountId,
                AccountLegalEntityId             = command.AccountLegalEntityId,
                AccountLegalEntityPublicHashedId = command.AccountLegalEntityPublicHashedId,
                AccountLegalEntityName           = command.AccountLegalEntityName,
                AccountName                      = command.AccountName,
                CohortRef                        = command.CohortRef,
                UkPrn                            = command.UkPrn,
                EmployerHasSingleLegalEntity     = command.EmployerHasSingleLegalEntity,
                IsEmptyCohortFromSelect          = command.IsEmptyCohortFromSelect
            };

            await _cacheStorageService.SaveToCache(reservation.Id.ToString(), reservation, 1);

            return(Unit.Value);
        }
        public async Task <AddOrRemoveFavouriteInBasketResponse> UpdateBasket(string apprenticeshipId, int?ukprn = null, int?locationId = null)
        {
            var cookieBasketId = GetBasketCookieId();

            var basketResponse = await _mediator.Send(new AddOrRemoveFavouriteInBasketCommand
            {
                ApprenticeshipId = apprenticeshipId,
                Ukprn            = ukprn,
                BasketId         = cookieBasketId,
                LocationId       = locationId
            });

            _cookieManager.Set(CookieNames.BasketCookie, basketResponse.BasketId.ToString(), DateTime.Now.AddDays(30));

            await _cacheService.SaveToCache($"FatComponentsCache-Basket-{basketResponse.BasketId.ToString()}", await GetBasket(basketResponse.BasketId, false), new TimeSpan(_cacheSettings.CacheAbsoluteExpirationDays, 0, 0, 0), new TimeSpan(_cacheSettings.CacheSlidingExpirationDays, 0, 0, 0));

            return(basketResponse);
        }
Beispiel #18
0
        public async Task <GetAvailableApiProductsResponse> GetAvailableProducts(string accountType)
        {
            var cachedProducts = await _cacheStorageService.RetrieveFromCache <GetAvailableApiProductsResponse>($"{accountType}-{nameof(GetAvailableApiProductsResponse)}");

            if (cachedProducts != null)
            {
                return(cachedProducts);
            }

            var products =
                await _apimDeveloperApiClient.Get <GetAvailableApiProductsResponse>(
                    new GetAvailableApiProductsRequest(accountType));

            await _cacheStorageService.SaveToCache($"{accountType}-{nameof(GetAvailableApiProductsResponse)}", products,
                                                   CachedProductExpiryTimeInHours);

            return(products);
        }
        public async Task <Unit> Handle(CacheReservationCourseCommand command, CancellationToken cancellationToken)
        {
            var validationResult = await _validator.ValidateAsync(command);

            if (!validationResult.IsValid())
            {
                throw new ValidationException(validationResult.ConvertToDataAnnotationsValidationResult(), null, null);
            }

            CachedReservation cachedReservation;

            if (!command.UkPrn.HasValue)
            {
                cachedReservation = await _cachedReservationRepository.GetEmployerReservation(command.Id);
            }
            else
            {
                cachedReservation = await _cachedReservationRepository.GetProviderReservation(command.Id, command.UkPrn.Value);
            }

            if (cachedReservation == null)
            {
                throw new CachedReservationNotFoundException(command.Id);
            }

            if (string.IsNullOrEmpty(command.SelectedCourseId))
            {
                var course = new Course(null, null, 0);
                cachedReservation.CourseId          = course.Id;
                cachedReservation.CourseDescription = course.CourseDescription;
            }
            else
            {
                var course = await _courseService.GetCourse(command.SelectedCourseId);

                cachedReservation.CourseId          = course.Id;
                cachedReservation.CourseDescription = course.CourseDescription;
            }

            await _cacheStorageService.SaveToCache(cachedReservation.Id.ToString(), cachedReservation, 1);

            return(Unit.Value);
        }
Beispiel #20
0
        public async Task <GetCandidateSkillsQueryResponse> Handle(GetCandidateSkillsQuery request, CancellationToken cancellationToken)
        {
            var cachedSkills = await _cacheStorageService.RetrieveFromCache <List <string> >(CacheKey);

            if (cachedSkills != null)
            {
                return(new GetCandidateSkillsQueryResponse
                {
                    CandidateSkills = cachedSkills
                });
            }

            var response =
                await _apiClient.Get <List <string> >(new GetCandidateSkillsRequest());

            await _cacheStorageService.SaveToCache(CacheKey, response, CacheDurationInHours);

            return(new GetCandidateSkillsQueryResponse()
            {
                CandidateSkills = response
            });
        }
Beispiel #21
0
        public async Task <GetTrainingCoursesQueryResult> Handle(GetTrainingCoursesQuery request, CancellationToken cancellationToken)
        {
            var courses =
                await _cacheStorageService.RetrieveFromCache <GetStandardsListResponse>(
                    nameof(GetStandardsListResponse));

            if (courses != null)
            {
                return(new GetTrainingCoursesQueryResult
                {
                    TrainingCourses = courses.Standards
                });
            }

            courses = await _coursesApiClient.Get <GetStandardsListResponse>(new GetActiveStandardsListRequest());

            await _cacheStorageService.SaveToCache(nameof(GetStandardsListResponse), courses, CourseCacheDurationInHours);

            return(new GetTrainingCoursesQueryResult
            {
                TrainingCourses = courses.Standards
            });
        }
        public async Task <FatSearchResultsViewModel> GetSearchResults(SearchQueryViewModel searchQueryModel)
        {
            var cacheKey = $"FatComponentsCache-searchresults-{searchQueryModel.Keywords}-{searchQueryModel.Page}-{searchQueryModel.ResultsToTake}-{searchQueryModel.SortOrder}";

            foreach (var level in searchQueryModel.SelectedLevels)
            {
                cacheKey += $"-{level}";
            }

            var model = await _cacheService.RetrieveFromCache <FatSearchResultsViewModel>(cacheKey);

            if (model == null)
            {
                var results = _apprenticeshipSearchService.SearchByKeyword(searchQueryModel.Keywords, searchQueryModel.Page, searchQueryModel.ResultsToTake, searchQueryModel.SortOrder, searchQueryModel.SelectedLevels);

                model = _fatSearchResultsViewModelMapper.Map(await results);

                await _cacheService.SaveToCache(cacheKey, model, new TimeSpan(_cacheSettings.CacheAbsoluteExpirationDays, 0, 0, 0), new TimeSpan(_cacheSettings.CacheSlidingExpirationDays, 0, 0, 0));
            }

            model.SearchQuery.AddRemoveBasketResponse = searchQueryModel.AddRemoveBasketResponse;

            return(model);
        }
Beispiel #23
0
 public async Task CreateCacheCourseDemand(ICourseDemand item)
 {
     await _cacheStorageService.SaveToCache(item.Id.ToString(), item, TimeSpan.FromMinutes(30));
 }
        public async Task <GetApprenticeshipsFilterValuesQueryResult> Handle(GetApprenticeshipsFilterValuesQuery query, CancellationToken cancellationToken)
        {
            var cacheKey = "";

            if (query.ProviderId.HasValue)
            {
                cacheKey = $"{nameof(GetApprenticeshipsFilterValuesQueryResult)}-{query.ProviderId}";
            }

            if (query.EmployerAccountId.HasValue)
            {
                cacheKey = $"{nameof(GetApprenticeshipsFilterValuesQueryResult)}-{query.EmployerAccountId}";
            }

            if (!string.IsNullOrWhiteSpace(cacheKey))
            {
                var result =
                    await _cacheStorageService.RetrieveFromCache <GetApprenticeshipsFilterValuesQueryResult>(cacheKey);

                if (result != null)
                {
                    return(result);
                }
            }

            var stringDbTasks = new List <Task <List <string> > >();

            if (query.ProviderId.HasValue)
            {
                stringDbTasks.Add(GetDistinctEmployerNames(query, cancellationToken));
            }

            if (query.EmployerAccountId.HasValue)
            {
                stringDbTasks.Add(GetDistinctProviderNames(query, cancellationToken));
            }

            stringDbTasks.Add(GetDistinctCourseNames(query, cancellationToken));

            var dateDbTasks = new[] {
                GetDistinctStartDates(query, cancellationToken),
                GetDistinctEndDates(query, cancellationToken)
            };

            var dbTasks = new List <Task>();

            dbTasks.AddRange(stringDbTasks);
            dbTasks.AddRange(dateDbTasks);

            Task.WaitAll(dbTasks.ToArray <Task>());

            var queryResult = await Task.FromResult(new GetApprenticeshipsFilterValuesQueryResult
            {
                StartDates = dateDbTasks[0].Result,
                EndDates   = dateDbTasks[1].Result
            });

            if (query.ProviderId.HasValue)
            {
                queryResult.EmployerNames = stringDbTasks[0].Result;
                queryResult.CourseNames   = stringDbTasks[1].Result;
            }
            else if (query.EmployerAccountId.HasValue)
            {
                queryResult.ProviderNames = stringDbTasks[0].Result;
                queryResult.CourseNames   = stringDbTasks[1].Result;
            }
            else
            {
                queryResult.CourseNames = stringDbTasks[1].Result;
            }

            await _cacheStorageService.SaveToCache(cacheKey, queryResult, 1);

            return(queryResult);
        }