private async Task <ProcessRequestEntity> ProcessManualAddress( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); if (!currentPage.IsValid) { var cachedAnswers = _distributedCache.GetString(guid); var convertedAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var cachedSearchResults = convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"] as IEnumerable <object>; var model = await _pageFactory.Build(currentPage, viewModel, baseForm, guid, convertedAnswers, cachedSearchResults.ToList()); return(new ProcessRequestEntity { Page = currentPage, ViewModel = model }); } return(new ProcessRequestEntity { Page = currentPage }); }
public void SaveAnswers(Dictionary <string, dynamic> viewModel, string guid, string form, IEnumerable <CustomFormFile> files, bool isPageValid, bool appendMultipleFileUploadParts = false) { var formData = _distributedCache.GetString(guid); var convertedAnswers = new FormAnswers { Pages = new List <PageAnswers>() }; var currentPageAnswers = new PageAnswers(); if (!string.IsNullOrEmpty(formData)) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); } if (convertedAnswers.Pages != null && convertedAnswers.Pages.Any(_ => _.PageSlug == viewModel["Path"].ToLower())) { currentPageAnswers = convertedAnswers.Pages.Where(_ => _.PageSlug == viewModel["Path"].ToLower()).ToList().FirstOrDefault(); convertedAnswers.Pages = convertedAnswers.Pages.Where(_ => _.PageSlug != viewModel["Path"].ToLower()).ToList(); } var answers = new List <Answers>(); foreach (var item in viewModel) { if (!_disallowedKeys.DisallowedAnswerKeys.Any(key => item.Key.Contains(key))) { answers.Add(new Answers { QuestionId = item.Key, Response = item.Value }); } } if ((files == null || !files.Any()) && currentPageAnswers.Answers != null && currentPageAnswers.Answers.Any() && isPageValid && appendMultipleFileUploadParts) { answers = currentPageAnswers.Answers; } if (files != null && files.Any() && isPageValid) { answers = SaveFormFileAnswers(answers, files, appendMultipleFileUploadParts, currentPageAnswers); } convertedAnswers.Pages?.Add(new PageAnswers { PageSlug = viewModel["Path"].ToLower(), Answers = answers }); convertedAnswers.Path = viewModel["Path"]; convertedAnswers.FormName = form; _distributedCache.SetStringAsync(guid, JsonConvert.SerializeObject(convertedAnswers)); }
private async Task <ProcessRequestEntity> ProccessAutomaticStreet( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { var cachedAnswers = _distributedCache.GetString(guid); var streetElement = currentPage.Elements.Where(_ => _.Type.Equals(EElementType.Street)).FirstOrDefault(); var convertedAnswers = cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var street = (string)convertedAnswers .Pages .FirstOrDefault(_ => _.PageSlug.Equals(path)) .Answers .FirstOrDefault(_ => _.QuestionId.Equals($"{streetElement.Properties.QuestionId}")) .Response; if (currentPage.IsValid && streetElement.Properties.Optional && string.IsNullOrEmpty(street)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); } if (!currentPage.IsValid) { var cachedSearchResults = convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"] as IEnumerable <object>; var model = await _pageFactory.Build(currentPage, viewModel, baseForm, guid, convertedAnswers, cachedSearchResults.ToList()); return(new ProcessRequestEntity { Page = currentPage, ViewModel = model }); } _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); }
public object GetFormDataValue(string guid, string key) { var formData = _distributedCache.GetString(guid); var convertedAnswers = new FormAnswers { Pages = new List <PageAnswers>() }; if (!string.IsNullOrEmpty(formData)) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); } return(convertedAnswers.FormData.ContainsKey(key) ? convertedAnswers.FormData.GetValueOrDefault(key) : string.Empty); }
public async Task <FormBuilderViewModel> Build(Page page, Dictionary <string, dynamic> viewModel, FormSchema baseForm, string sessionGuid, FormAnswers formAnswers = null, List <object> results = null) { if (formAnswers == null) { var cachedAnswers = _distributedCache.GetString(sessionGuid); formAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); } _tagParsers.ToList().ForEach(_ => _.Parse(page, formAnswers)); var result = await _pageHelper.GenerateHtml(page, viewModel, baseForm, sessionGuid, formAnswers, results); result.Path = page.PageSlug; result.FormName = baseForm.FormName; result.PageTitle = page.Title; result.FeedbackForm = baseForm.FeedbackForm; result.FeedbackPhase = baseForm.FeedbackPhase; result.HideBackButton = (viewModel.IsAutomatic() || viewModel.IsManual()) ? false : page.HideBackButton; result.BreadCrumbs = baseForm.BreadCrumbs; result.DisplayBreadCrumbs = page.DisplayBreadCrumbs; result.StartPageUrl = baseForm.StartPageUrl; return(result); }
public async Task <T> GetFromCacheOrDirectlyFromSchemaAsync <T>(string cacheKey, int minutes, ESchemaType type) { T result; var prefix = type == ESchemaType.PaymentConfiguration ? "payment-config/" : string.Empty; if (_distributedCacheConfiguration.Value.UseDistributedCache && minutes > 0) { var data = _distributedCache.GetString($"{type.ToESchemaTypePrefix(_configuration["ApplicationVersion"])}{cacheKey}"); if (data == null) { result = await _schemaProvider.Get <T>($"{prefix}{cacheKey}"); if (result != null) { await _distributedCache.SetStringAsync($"{type.ToESchemaTypePrefix(_configuration["ApplicationVersion"])}{cacheKey}", JsonConvert.SerializeObject(result), minutes); } return(result); } return(JsonConvert.DeserializeObject <T>(data)); } return(await _schemaProvider.Get <T>($"{prefix}{cacheKey}")); }
public bool TryGetValue <T>(object key, out T value) { bool output = false; value = default(T); if (_memoryCache == null) { _logger.LogInformation("Cache is missing"); return(false); } var returnData = string.Empty; try { returnData = _memoryCache.GetString(key.ToString()).Result; } catch (Exception ex) { _logger.LogCritical(new EventId(), ex, "An error occurred trying to read from Redis"); return(false); } if (returnData != null) { value = JsonConvert.DeserializeObject <T>(returnData); _logger.LogInformation("Key found in cache:" + key + " of type:" + typeof(T)); output = value != null; } return(output); }
public async Task <FormSchema> Build(string formKey) { if (!_schemaProvider.ValidateSchemaName(formKey).Result) { return(null); } if (_distributedCacheConfiguration.UseDistributedCache && _distributedCacheExpirationConfiguration.FormJson > 0) { var data = _distributedCache.GetString($"{ESchemaType.FormJson.ToESchemaTypePrefix(_configuration["ApplicationVersion"])}{formKey}"); if (data != null) { return(JsonConvert.DeserializeObject <FormSchema>(data)); } } var formSchema = await _schemaProvider.Get <FormSchema>(formKey); formSchema = await _reusableElementSchemaFactory.Transform(formSchema); formSchema = _lookupSchemaFactory.Transform(formSchema); if (_distributedCacheConfiguration.UseDistributedCache && _distributedCacheExpirationConfiguration.FormJson > 0) { await _distributedCache.SetStringAsync($"{ESchemaType.FormJson.ToESchemaTypePrefix(_configuration["ApplicationVersion"])}{formKey}", JsonConvert.SerializeObject(formSchema), _distributedCacheExpirationConfiguration.FormJson); } return(formSchema); }
private async Task <(FormAnswers convertedAnswers, FormSchema baseForm)> GetFormAnswers(string form, string sessionGuid) { var baseForm = await _schemaFactory.Build(form); if (string.IsNullOrEmpty(sessionGuid)) { throw new ApplicationException("MappingService::GetFormAnswers Session has expired"); } var sessionData = _distributedCache.GetString(sessionGuid); if (sessionData is null) { throw new ApplicationException("MappingService::GetFormAnswers, Session data is null"); } var convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(sessionData); convertedAnswers.Pages = convertedAnswers.GetReducedAnswers(baseForm); convertedAnswers.FormName = form; if (convertedAnswers.Pages is null || !convertedAnswers.Pages.Any()) { var deviceInformation = $"Device Type: {_detectionService.Device.Type}, Browser Name/Version: {_detectionService.Browser.Name}/{_detectionService.Browser.Version}, Platform Name: {_detectionService.Platform.Name}, Engine Name: {_detectionService.Engine.Name}, Crawler: {_detectionService.Crawler.IsCrawler}/{_detectionService.Crawler.Name}"; _logger.LogWarning($"MappingService::GetFormAnswers, Reduced Answers returned empty or null list, Creating submit data but no answers collected. Form {form}, Session {sessionGuid}, {deviceInformation}"); } return(convertedAnswers, baseForm); }
public FormAnswers GetFormAnswers() { string sessionGuid = _sessionHelper.GetSessionGuid(); string cachedAnswers = _distributedCache.GetString(sessionGuid); return(cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers)); }
public async Task <string> ProcessSubmission(MappingEntity mappingEntity, string form, string sessionGuid) { var baseForm = await _schemaFactory.Build(form); var reference = string.Empty; if (baseForm.GenerateReferenceNumber) { var answers = JsonConvert.DeserializeObject <FormAnswers>(_distributedCache.GetString(sessionGuid)); reference = answers.CaseReference; } return(_submissionServiceConfiguration.FakeSubmission ? ProcessFakeSubmission(mappingEntity, form, sessionGuid, reference) : await ProcessGenuineSubmission(mappingEntity, form, sessionGuid, baseForm, reference)); }
private async Task <(FormAnswers convertedAnswers, FormSchema baseForm)> GetFormAnswers(string form, string sessionGuid) { var baseForm = await _schemaFactory.Build(form); var convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(_distributedCache.GetString(sessionGuid)); convertedAnswers.Pages = convertedAnswers.GetReducedAnswers(baseForm); convertedAnswers.FormName = form; if (convertedAnswers.Pages == null || !convertedAnswers.Pages.Any()) { _logger.LogWarning($"MappingService::GetFormAnswers, Reduced Answers returned empty or null list, Creating submit data but no answers collected. Form {form}, Session {sessionGuid}"); } return(convertedAnswers, baseForm); }
public async Task Process(List <IAction> actions) { var sessionGuid = _sessionHelper.GetSessionGuid(); if (string.IsNullOrEmpty(sessionGuid)) { throw new Exception("EmailService::Process: Session has expired"); } var formData = _distributedCache.GetString(sessionGuid); var formAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); foreach (var action in actions) { await action.Process(_actionHelper, _emailProvider, formAnswers); } }
public async Task <byte[]> GenerateSummaryDocumentAsync(EDocumentType documentType, Guid id) { var formData = _distributedCache.GetString($"document-{id.ToString()}"); if (formData is null) { throw new DocumentExpiredException($"DocumentWorkflow::GenerateSummaryDocument, Previous answers has expired, unable to generate {documentType.ToString()} document for summary"); } var previousAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); var baseForm = await _schemaFactory.Build(previousAnswers.FormName); return(await _documentSummaryService.GenerateDocument(new DocumentSummaryEntity { DocumentType = documentType, PreviousAnswers = previousAnswers, FormSchema = baseForm })); }
private ProcessRequestEntity RemoveFile( Dictionary <string, dynamic> viewModel, FormSchema baseForm, string path, string sessionGuid) { var cachedAnswers = _distributedCache.GetString(sessionGuid); var convertedAnswers = cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var currentPageAnswers = convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))?.Answers.FirstOrDefault(); List <FileUploadModel> response = JsonConvert.DeserializeObject <List <FileUploadModel> >(currentPageAnswers.Response.ToString()); var fileToRemove = response.FirstOrDefault(_ => _.TrustedOriginalFileName.Equals(viewModel[FileUploadConstants.FILE_TO_DELETE])); response.Remove(fileToRemove); convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path)).Answers.FirstOrDefault().Response = response; _distributedCache.SetStringAsync(sessionGuid, JsonConvert.SerializeObject(convertedAnswers), CancellationToken.None); var fileStorageType = _configuration["FileStorageProvider:Type"]; var fileStorageProvider = _fileStorageProviders.Get(fileStorageType); fileStorageProvider.Remove(fileToRemove.Key); return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path } }); }
public async Task <bool> ValidateSchemaName(string schemaName) { if (!_distributedCacheConfiguration.UseDistributedCache) { return(true); } var cachedIndexSchema = _distributedCacheWrapper.GetString(CacheConstants.INDEX_SCHEMA); var indexSchema = new List <string>(); if (string.IsNullOrEmpty(cachedIndexSchema)) { indexSchema = await IndexSchema(); } else { indexSchema = JsonConvert.DeserializeObject <List <string> >(cachedIndexSchema); } return(indexSchema.Any(_ => _.Contains(schemaName))); }
public Task ProcessTemplatedEmail(List <IAction> actions) { var sessionGuid = _sessionHelper.GetSessionGuid(); if (string.IsNullOrEmpty(sessionGuid)) { throw new Exception("TemplatedEmailService::Process: Session has expired"); } var formData = _distributedCache.GetString(sessionGuid); var formAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); foreach (var action in actions) { var templatedEmailProvider = _templatedEmailProviders.Get(action.Properties.EmailTemplateProvider); var convertedAnswers = formAnswers.AllAnswers.ToDictionary(x => x.QuestionId, x => x.Response); var personalisation = new Dictionary <string, dynamic>(); if (action.Properties.IncludeCaseReference) { personalisation.Add("reference", formAnswers.CaseReference); } if (action.Properties.Personalisation is not null && !convertedAnswers.Count.Equals(0)) { action.Properties.Personalisation.ForEach(field => { personalisation.Add(field, convertedAnswers[field]); }); } action.ProcessTemplatedEmail( _actionHelper, templatedEmailProvider, personalisation, formAnswers); } return(null); }
public async Task <BookingProcessEntity> Get(string baseUrl, Page currentPage, string guid) { var bookingElement = currentPage.Elements .Where(_ => _.Type == EElementType.Booking) .FirstOrDefault(); var appointmentTimes = new List <AvailabilityDayResponse>(); var bookingInformationCacheKey = $"{bookingElement.Properties.QuestionId}{BookingConstants.APPOINTMENT_TYPE_SEARCH_RESULTS}"; var cachedAnswers = _distributedCache.GetString(guid); if (cachedAnswers != null) { var convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); if (convertedAnswers.FormData.ContainsKey(bookingInformationCacheKey)) { var cachedBookingInformation = JsonConvert.DeserializeObject <BookingInformation>(convertedAnswers.FormData[bookingInformationCacheKey].ToString()); var cachedInfo = new List <object> { cachedBookingInformation }; return(new BookingProcessEntity { BookingInfo = cachedInfo }); } } var bookingProvider = _bookingProviders.Get(bookingElement.Properties.BookingProvider); var nextAvailability = await RetrieveNextAvailability(bookingElement, bookingProvider); if (nextAvailability.BookingHasNoAvailableAppointments) { return new BookingProcessEntity { BookingHasNoAvailableAppointments = true } } ; appointmentTimes = await bookingProvider.GetAvailability(new AvailabilityRequest { StartDate = nextAvailability.DayResponse.Date, EndDate = nextAvailability.DayResponse.Date.LastDayOfTheMonth(), AppointmentId = bookingElement.Properties.AppointmentType, OptionalResources = bookingElement.Properties.OptionalResources }); var bookingInformation = new BookingInformation { Appointments = appointmentTimes, CurrentSearchedMonth = new DateTime(nextAvailability.DayResponse.Date.Year, nextAvailability.DayResponse.Date.Month, 1), FirstAvailableMonth = new DateTime(nextAvailability.DayResponse.Date.Year, nextAvailability.DayResponse.Date.Month, 1), IsFullDayAppointment = nextAvailability.DayResponse.IsFullDayAppointment }; if (nextAvailability.DayResponse.IsFullDayAppointment) { bookingInformation.AppointmentStartTime = DateTime.Today.Add(nextAvailability.DayResponse.AppointmentTimes.First().StartTime); bookingInformation.AppointmentEndTime = DateTime.Today.Add(nextAvailability.DayResponse.AppointmentTimes.First().EndTime); } _pageHelper.SaveFormData(bookingInformationCacheKey, bookingInformation, guid, baseUrl); var bookingInfo = new List <object> { bookingInformation }; return(new BookingProcessEntity { BookingInfo = bookingInfo }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.MultipleFileUpload)) { return new ValidationResult { IsValid = true } } ; if (element.Properties.Optional && viewModel.ContainsKey(ButtonConstants.SUBMIT)) { return new ValidationResult { IsValid = true } } ; var key = $"{ element.Properties.QuestionId}{FileUploadConstants.SUFFIX}"; var isValid = false; List <DocumentModel> value = viewModel.ContainsKey(key) ? viewModel[key] : null; isValid = !(value is null); if (value is null) { var sessionGuid = _sessionHelper.GetSessionGuid(); var cachedAnswers = _distributedCache.GetString(sessionGuid); var convertedAnswers = cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var path = viewModel.FirstOrDefault(_ => _.Key.Equals("Path")).Value; var pageAnswersString = convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))?.Answers.FirstOrDefault(_ => _.QuestionId.Equals(key)); var response = new List <FileUploadModel>(); if (pageAnswersString is not null) { response = JsonConvert.DeserializeObject <List <FileUploadModel> >(pageAnswersString.Response.ToString()); if (response.Any()) { isValid = true; } } } return(new ValidationResult { IsValid = isValid, Message = ValidationConstants.FILEUPLOAD_EMPTY }); } } }
public async Task <BookingProcessEntity> Get(string baseUrl, Page currentPage, string sessionGuid) { var bookingElement = currentPage.Elements .First(element => element.Type .Equals(EElementType.Booking)); List <AvailabilityDayResponse> appointmentTimes = new(); var bookingInformationCacheKey = $"{bookingElement.Properties.QuestionId}{BookingConstants.APPOINTMENT_TYPE_SEARCH_RESULTS}"; var appointmentType = bookingElement.Properties.AppointmentTypes .GetAppointmentTypeForEnvironment(_environment.EnvironmentName); var cachedAnswers = _distributedCache.GetString(sessionGuid); FormAnswers convertedAnswers = new(); if (cachedAnswers is not null) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); if (appointmentType.NeedsAppointmentIdMapping) { _mappingService.MapAppointmentId(appointmentType, convertedAnswers); } if (convertedAnswers.FormData.ContainsKey(bookingInformationCacheKey)) { var cachedBookingInformation = JsonConvert .DeserializeObject <BookingInformation>(convertedAnswers.FormData[bookingInformationCacheKey].ToString()); if (appointmentType.AppointmentId.Equals(cachedBookingInformation.AppointmentTypeId)) { return new BookingProcessEntity { BookingInfo = new() { cachedBookingInformation } } } ; } } var bookingProvider = _bookingProviders.Get(bookingElement.Properties.BookingProvider); var nextAvailability = await RetrieveNextAvailability(bookingElement, bookingProvider, appointmentType); if (nextAvailability.BookingHasNoAvailableAppointments) { return new BookingProcessEntity { BookingHasNoAvailableAppointments = true } } ; appointmentTimes = await bookingProvider.GetAvailability(new AvailabilityRequest { StartDate = nextAvailability.DayResponse.Date, EndDate = nextAvailability.DayResponse.Date.LastDayOfTheMonth(), AppointmentId = appointmentType.AppointmentId, OptionalResources = appointmentType.OptionalResources }); BookingInformation bookingInformation = new() { AppointmentTypeId = appointmentType.AppointmentId, Appointments = appointmentTimes, CurrentSearchedMonth = new DateTime(nextAvailability.DayResponse.Date.Year, nextAvailability.DayResponse.Date.Month, 1), FirstAvailableMonth = new DateTime(nextAvailability.DayResponse.Date.Year, nextAvailability.DayResponse.Date.Month, 1), IsFullDayAppointment = nextAvailability.DayResponse.IsFullDayAppointment }; if (nextAvailability.DayResponse.IsFullDayAppointment) { bookingInformation.AppointmentStartTime = DateTime.Today.Add(nextAvailability.DayResponse.AppointmentTimes.First().StartTime); bookingInformation.AppointmentEndTime = DateTime.Today.Add(nextAvailability.DayResponse.AppointmentTimes.First().EndTime); } _pageHelper.SaveFormData(bookingInformationCacheKey, bookingInformation, sessionGuid, baseUrl); return(new BookingProcessEntity { BookingInfo = new() { bookingInformation } }); }
public async Task <ProcessPageEntity> ProcessPage(string form, string path, string subPath, IQueryCollection queryParameters) { if (string.IsNullOrEmpty(path)) { _sessionHelper.RemoveSessionGuid(); } var sessionGuid = _sessionHelper.GetSessionGuid(); if (string.IsNullOrEmpty(sessionGuid)) { sessionGuid = Guid.NewGuid().ToString(); _sessionHelper.SetSessionGuid(sessionGuid); } var baseForm = await _schemaFactory.Build(form); if (baseForm is null) { return(null); } if (!_formAvailabilityService.IsAvailable(baseForm.EnvironmentAvailabilities, _environment.EnvironmentName)) { _logger.LogWarning($"Form: {form} is not available in this Environment: {_environment.EnvironmentName.ToS3EnvPrefix()}"); return(null); } if (string.IsNullOrEmpty(path)) { return new ProcessPageEntity { ShouldRedirect = true, TargetPage = baseForm.FirstPageSlug } } ; var formData = _distributedCache.GetString(sessionGuid); if (string.IsNullOrEmpty(formData) && !path.Equals(baseForm.FirstPageSlug) && (!baseForm.HasDocumentUpload || !path.Equals(FileUploadConstants.DOCUMENT_UPLOAD_URL_PATH))) { return new ProcessPageEntity { ShouldRedirect = true, TargetPage = baseForm.FirstPageSlug } } ; if (!string.IsNullOrEmpty(formData) && path.Equals(baseForm.FirstPageSlug)) { var convertedFormData = JsonConvert.DeserializeObject <FormAnswers>(formData); if (!form.Equals(convertedFormData.FormName, StringComparison.OrdinalIgnoreCase)) { _distributedCache.Remove(sessionGuid); } } var page = baseForm.GetPage(_pageHelper, path); if (page is null) { throw new ApplicationException($"Requested path '{path}' object could not be found for form '{form}'"); } List <object> searchResults = null; var convertedAnswers = new FormAnswers { Pages = new List <PageAnswers>() }; if (!string.IsNullOrEmpty(formData)) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); } if (page.Elements.Any(_ => _.Type.Equals(EElementType.Summary))) { var journeyPages = baseForm.GetReducedPages(convertedAnswers); foreach (var schemaPage in journeyPages) { await _schemaFactory.TransformPage(schemaPage, convertedAnswers); } } else { await _schemaFactory.TransformPage(page, convertedAnswers); } if (subPath.Equals(LookUpConstants.Automatic) || subPath.Equals(LookUpConstants.Manual)) { if (convertedAnswers.FormData.ContainsKey($"{path}{LookUpConstants.SearchResultsKeyPostFix}")) { searchResults = ((IEnumerable <object>)convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"])?.ToList(); } } if (page.HasIncomingGetValues) { var result = _incomingDataHelper.AddIncomingFormDataValues(page, queryParameters, convertedAnswers); _pageHelper.SaveNonQuestionAnswers(result, form, path, sessionGuid); } if (page.HasPageActionsGetValues) { await _actionsWorkflow.Process(page.PageActions, null, form); } if (page.Elements.Any(_ => _.Type.Equals(EElementType.Booking))) { var bookingProcessEntity = await _bookingService.Get(baseForm.BaseURL, page, sessionGuid); if (bookingProcessEntity.BookingHasNoAvailableAppointments) { return(new ProcessPageEntity { ShouldRedirect = true, TargetPage = BookingConstants.NO_APPOINTMENT_AVAILABLE }); } searchResults = bookingProcessEntity.BookingInfo; } var viewModel = await GetViewModel(page, baseForm, path, sessionGuid, subPath, searchResults); return(new ProcessPageEntity { ViewModel = viewModel }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (element.Type != EElementType.MultipleFileUpload) { return new ValidationResult { IsValid = true } } ; var key = $"{element.Properties.QuestionId}{FileUploadConstants.SUFFIX}"; if (!viewModel.ContainsKey(key)) { return new ValidationResult { IsValid = true } } ; List <DocumentModel> documentModel = viewModel[key]; if (documentModel == null) { return new ValidationResult { IsValid = true } } ; var maxCombinedFileSize = element.Properties.MaxCombinedFileSize > 0 ? element.Properties.MaxCombinedFileSize * SystemConstants.OneMBInBinaryBytes : SystemConstants.DefaultMaxCombinedFileSize; var sessionGuid = _sessionHelper.GetSessionGuid(); var cachedAnswers = _distributedCache.GetString(sessionGuid); var convertedAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var path = viewModel.FirstOrDefault(_ => _.Key.Equals("Path")).Value; var pageAnswersString = convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))?.Answers.FirstOrDefault(_ => _.QuestionId == key); var response = new List <FileUploadModel>(); if (pageAnswersString != null) { response = JsonConvert.DeserializeObject <List <FileUploadModel> >(pageAnswersString.Response.ToString()); } if (documentModel.Sum(_ => _.FileSize) + response?.Sum(_ => _.FileSize) < maxCombinedFileSize) { return new ValidationResult { IsValid = true } } ; return(new ValidationResult { IsValid = false, Message = $"The total size of all your added files must not be more than {maxCombinedFileSize.ToReadableMaxFileSize()}MB" }); } } }
public async Task <ProcessPageEntity> ProcessPage(string form, string path, string subPath, IQueryCollection queryParamters) { if (string.IsNullOrEmpty(path)) { _sessionHelper.RemoveSessionGuid(); } var sessionGuid = _sessionHelper.GetSessionGuid(); if (string.IsNullOrEmpty(sessionGuid)) { sessionGuid = Guid.NewGuid().ToString(); _sessionHelper.SetSessionGuid(sessionGuid); } var baseForm = await _schemaFactory.Build(form); if (baseForm == null) { return(null); } if (!baseForm.IsAvailable(_environment.EnvironmentName)) { throw new ApplicationException($"Form: {form} is not available in this Environment: {_environment.EnvironmentName.ToS3EnvPrefix()}"); } var formData = _distributedCache.GetString(sessionGuid); if (formData == null && path != baseForm.FirstPageSlug && (!baseForm.HasDocumentUpload || path != FileUploadConstants.DOCUMENT_UPLOAD_URL_PATH)) { return new ProcessPageEntity { ShouldRedirect = true, TargetPage = baseForm.FirstPageSlug } } ; if (string.IsNullOrEmpty(path)) { return new ProcessPageEntity { ShouldRedirect = true, TargetPage = baseForm.FirstPageSlug } } ; if (formData != null && path == baseForm.FirstPageSlug) { var convertedFormData = JsonConvert.DeserializeObject <FormAnswers>(formData); if (form.ToLower() != convertedFormData.FormName.ToLower()) { _distributedCache.Remove(sessionGuid); } } var page = baseForm.GetPage(_pageHelper, path); if (page == null) { throw new ApplicationException($"Requested path '{path}' object could not be found for form '{form}'"); } await baseForm.ValidateFormSchema(_pageHelper, form, path); List <object> searchResults = null; if (subPath.Equals(LookUpConstants.Automatic) || subPath.Equals(LookUpConstants.Manual)) { var convertedAnswers = new FormAnswers { Pages = new List <PageAnswers>() }; if (!string.IsNullOrEmpty(formData)) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); } if (convertedAnswers.FormData.ContainsKey($"{path}{LookUpConstants.SearchResultsKeyPostFix}")) { searchResults = ((IEnumerable <object>)convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"])?.ToList(); } } if (page.Elements.Any(_ => _.Type == EElementType.PaymentSummary)) { var data = await _mappingService.Map(sessionGuid, form); var paymentAmount = await _payService.GetFormPaymentInformation(data, form, page); page.Elements.First(_ => _.Type == EElementType.PaymentSummary).Properties.Value = paymentAmount.Settings.Amount; } if (page.HasIncomingGetValues) { var convertedAnswers = new FormAnswers { Pages = new List <PageAnswers>() }; if (!string.IsNullOrEmpty(formData)) { convertedAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); } var result = _incomingDataHelper.AddIncomingFormDataValues(page, queryParamters, convertedAnswers); _pageHelper.SaveNonQuestionAnswers(result, form, path, sessionGuid); } if (page.HasPageActionsGetValues) { await _actionsWorkflow.Process(page.PageActions, null, form); } if (page.Elements.Any(_ => _.Type.Equals(EElementType.Booking))) { var bookingProcessEntity = await _bookingService.Get(baseForm.BaseURL, page, sessionGuid); if (bookingProcessEntity.BookingHasNoAvailableAppointments) { return(new ProcessPageEntity { ShouldRedirect = true, TargetPage = BookingConstants.NO_APPOINTMENT_AVAILABLE }); } searchResults = bookingProcessEntity.BookingInfo; } var viewModel = await GetViewModel(page, baseForm, path, sessionGuid, subPath, searchResults); return(new ProcessPageEntity { ViewModel = viewModel }); }