private SurveyResponseModel GetLinkedProducts(Guid surveyId, List <SurveyProfileAnswerModel> answers)
        {
            //Get Linked Products
            var surveyResult  = _surveyApi.GetSurvey(surveyId);
            var survey        = surveyResult.Result;
            var searchRequest = new SearchRequestModel
            {
                AllowFacet = false,
                Filters    = new List <SearchFilter>()
            };

            foreach (var ans in answers)
            {
                var ques = survey.Questions.FirstOrDefault(x => x.RecordId == ans.QuestionId);
                if (ques != null)
                {
                    var option = ques.InputOptions.FirstOrDefault(x => x.OptionValue.ToLower() == ans.SelectedAnswer.ToLower());
                    if (option != null)
                    {
                        if (option.LinkedStockCodes != null && option.LinkedStockCodes.Any())
                        {
                            ans.LinkedStockCodes = option.LinkedStockCodes;
                            foreach (var linkedStock in option.LinkedStockCodes)
                            {
                                searchRequest.Filters.Add(new SearchFilter {
                                    Key = "stockCode", Value = linkedStock.Key
                                });
                            }
                        }
                    }
                }
            }
            var responseModel = new SurveyResponseModel {
                Id = survey.RecordId, Name = survey.Name, Products = new List <SurveyProductModel>()
            };

            if (searchRequest.Filters.Any())
            {
                var result = SearchHelper.GetPaginatedProducts(searchRequest);
                foreach (var ans in answers)
                {
                    if (ans.LinkedStockCodes != null)
                    {
                        foreach (var opt in ans.LinkedStockCodes)
                        {
                            var prod = result.Results.FirstOrDefault(x => x.StockCode == opt.Key);
                            if (prod != null)
                            {
                                responseModel.Products.Add(new SurveyProductModel {
                                    qty = opt.Value, Product = prod
                                });
                            }
                        }
                    }
                }
            }
            return(responseModel);
        }
Esempio n. 2
0
        private void SubmitSurveyResponse(SurveyResponseModel Response, String DeviceId)
        {
            var parameters = new Dictionary <string, string>
            {
                { "DeviceId", DeviceId },
            };

            ApiClient.InvokeApiAsync("SurveyResponses", JObject.FromObject(Response), HttpMethod.Post, parameters).Wait();
        }
        /// <summary>
        /// Submits a survey response to the service.
        /// </summary>
        /// <param name="surveyResponse">The survey response</param>
        /// <returns>
        /// A task to await the submission.
        /// </returns>
        public static Task SubmitSurveyResponseAsync(SurveyResponseModel surveyResponse)
        {
            var parameters = new Dictionary <string, string>
            {
                { "deviceId", UserSettings.VolunteerId },
            };

            using (new LatencyMetric("SubmitSurveyResponse"))
            {
                return(ApiClient.InvokeApiAsync("SurveyResponses", JObject.FromObject(surveyResponse), HttpMethod.Post, parameters));
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Searches the survey response for a well-known answer, e.g., initials or date of birth.
        /// </summary>
        /// <param name="response">The survey response.</param>
        /// <param name="survey">The survey.</param>
        /// <param name="question">The well-known question type.</param>
        /// <returns>
        /// The specified valid of the well-known answer, or <code>null</code> if not found.
        /// </returns>
        public static string GetWellKnownAnswer(this SurveyResponseModel response, SurveyModel survey, WellKnownQuestion question)
        {
            var nameQuestion = survey.Questions
                               .FirstOrDefault(q => q.WellKnownQuestion == question);

            if (nameQuestion == null)
            {
                return(null);
            }

            return(response.QuestionResponses
                   .FirstOrDefault(r => r.QuestionID == nameQuestion.QuestionID)?
                   .AnswerChoiceResponses?.FirstOrDefault()?
                   .AdditionalAnswerData);
        }
Esempio n. 5
0
        public virtual ActionResult AddToBag(SurveyResponseModel surveyResponse)
        {
            var bulkAdd    = new List <BasketAddModel>();
            var stockCodes = "";

            foreach (var prod in surveyResponse.Products)
            {
                stockCodes = stockCodes + (string.IsNullOrEmpty(stockCodes)?  prod.Product.StockCode: " " + prod.Product.StockCode);
                bulkAdd.Add(new BasketAddModel {
                    StockCode = prod.Product.StockCode, Qty = prod.qty, ParentProductId = surveyResponse.Id.ToString()
                });
            }
            stockCodes = Constants.SURVEY_BUNDLE_PREFIX + " " + stockCodes;
            bulkAdd.Add(new BasketAddModel {
                StockCode = stockCodes, Qty = 1, ItemType = ItemTypes.DynamicBundle.GetHashCode(), ProductId = surveyResponse.Id.ToString(), ProductName = stockCodes
            });
            var basketApi = DependencyResolver.Current.GetService <IBasketApi>();
            var basket    = basketApi.BulkAddProduct(bulkAdd);

            return(JsonSuccess(basket?.Result, JsonRequestBehavior.AllowGet));
        }
        public Operation <SurveyResponseModel> AddSurveyQuestions(SurveyResponseModel model)
        {
            return(Operation.Create(() =>
            {
                if (model == null)
                {
                    throw new Exception("Answered question model cannot be  empty");
                }

                model.Validate();

                model.SurveyAnswer.ToList().ForEach(m =>
                {
                    m.Validate();

                    var entity = new SurveyQuestion()
                    {
                        AnswerSelected = m.SelectedAnswer,
                        QuestionId = m.QuestionId,
                        UserId = model.UserId,
                        Score = m.Score
                    };
                    _repo.Add <SurveyQuestion>(entity);
                });

                _userPoint.AddUserPointOrUpdate(new UserPointModel()
                {
                    UserId = model.UserId,
                    Channel = PointChannel.IsQuestion,
                    Point = model.Point,
                    //QuestionId = model
                });

                _repo.SaveChanges();
                return model;
            }));
        }
Esempio n. 7
0
 /// <summary>
 /// Gets the filename of the survey response, based on the survey response <see cref="Guid"/>.
 /// </summary>
 /// <param name="response">The survey response.</param>
 /// <returns>The filename.</returns>
 private static string GetFilename(this SurveyResponseModel response)
 {
     return($"{response.ResponseIdentifier}.survey.json");
 }
        public IActionResult SubmitAnswer([FromBody] SurveyResponseModel model)
        {
            var op = _service.AddSurveyQuestions(model);

            return(Ok(op));
        }
Esempio n. 9
0
        public async Task <IHttpActionResult> PostSurveyResponse(SurveyResponseModel surveyResponse, Guid?deviceId)
        {
            Volunteer sv = await GetAuthenticatedVolunteerAsync(deviceId);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!deviceId.HasValue)
            {
                return(BadRequest("The DeviceId was not specified."));
            }
            else if (deviceId.Value == Guid.Empty)
            {
                return(BadRequest("The DeviceId was not valid."));
            }

            if (sv == null)
            {
                return(BadRequest("The specified InterviewerID is not recognized. User not logged in?"));
            }

            SurveyResponse sr = db.SurveyResponses.Where(r => r.ResponseIdentifier == surveyResponse.ResponseIdentifier).SingleOrDefault();

            if (sr != null)
            {
                // Delete current response to replace with new one
                db.SurveyResponses.Remove(sr);
            }

            try
            {
                ModelConverter converter = new ModelConverter(db);

                SurveyResponse response = converter.ConvertToEntity(surveyResponse);

                response.Volunteer = sv;

                response.DeviceId = deviceId.Value;

                response.DateUploaded = DateTimeOffset.Now;

                db.SurveyResponses.Add(response);

                db.SaveChanges();

                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (DbEntityValidationException evex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var eve in evex.EntityValidationErrors)
                {
                    sb.AppendLine($"{eve.Entry.Entity.GetType().Name}");

                    foreach (var ve in eve.ValidationErrors)
                    {
                        sb.AppendLine($"{ve.PropertyName}: {ve.ErrorMessage}");
                    }
                }
                Trace.TraceError("Error processing SurveyResponse: " + evex.ToString());
                telemetry.TrackException(evex);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, sb.ToString()));
            }
            catch (ArgumentException ae)
            {
                Trace.TraceError("Error processing SurveyResponse: " + ae.Message);
                telemetry.TrackException(ae);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ae.Message));
            }
            catch (FormatException fe)
            {
                Trace.TraceError("Error processing SurveyResponse: " + fe.Message);
                telemetry.TrackException(fe);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, fe.Message));
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error processing SurveyResponse: " + ex.ToString());
                telemetry.TrackException(ex);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString()));
            }
        }
Esempio n. 10
0
        public SurveyResponse ConvertToEntity(SurveyResponseModel model)
        {
            // 4326 is most common coordinate system used by GPS/Maps
            const int coordinateSystemID = 4326;

            // TODO: Validate that question and answer IDs are valid for specified survey (use ArgumentException).
            // TODO: Validate that AdditionalAnswerData matches the expected format, where applicable (use FormatException).

            var survey = _db.Surveys.Include("SurveyQuestions").Include("SurveyQuestions.AnswerChoices").Where(s => s.ID == model.SurveyID).SingleOrDefault();

            if (survey == null)
            {
                throw new ArgumentException("Invalid SurveyID.");
            }

            SurveyResponse response = new SurveyResponse()
            {
                Survey_ID          = model.SurveyID,
                Survey_Version     = model.Survey_Version,
                GPSLocation        = (model.GPSLocation?.Lat != null && model.GPSLocation?.Lon != null) ? System.Data.Entity.Spatial.DbGeography.PointFromText($"Point({model.GPSLocation.Lon} {model.GPSLocation.Lat})", coordinateSystemID) : null,
                LocationNotes      = model.LocationNotes,
                NearestAddress     = model.NearestAddress ?? new PITCSurveyLib.Address(),
                ResponseIdentifier = model.ResponseIdentifier,
                InterviewStarted   = model.StartTime,
                InterviewCompleted = model.EndTime
            };

            foreach (SurveyQuestionResponseModel qrm in model.QuestionResponses)
            {
                var question = survey.SurveyQuestions.Where(q => q.Question_ID == qrm.QuestionID).SingleOrDefault();

                if (question == null)
                {
                    throw new ArgumentException("Invalid QuestionID for this survey.");
                }

                foreach (SurveyQuestionAnswerChoiceResponseModel qacrm in qrm.AnswerChoiceResponses)
                {
                    var choice = question.AnswerChoices.Where(c => c.AnswerChoice_ID == qacrm.AnswerChoiceID).SingleOrDefault();

                    if (choice == null)
                    {
                        throw new ArgumentException("Invalid AnswerChoiceID for this survey question.");
                    }

                    switch (choice.AnswerChoice.AdditionalAnswerDataFormat)
                    {
                    case PITCSurveyLib.AnswerFormat.Int:
                        int intResult;
                        if (!int.TryParse(qacrm.AdditionalAnswerData, out intResult))
                        {
                            throw new FormatException("AdditionalAnswerData not parsable as 'int'.");
                        }
                        break;

                    case PITCSurveyLib.AnswerFormat.Date:
                        DateTime dateResult;
                        if (!DateTime.TryParse(qacrm.AdditionalAnswerData, out dateResult))
                        {
                            throw new FormatException("AdditionalAnswerData not parsable as 'DateTime'.");
                        }
                        break;
                    }

                    SurveyResponseAnswer answer = new SurveyResponseAnswer()
                    {
                        Question_ID          = qrm.QuestionID,
                        AnswerChoice_ID      = qacrm.AnswerChoiceID,
                        AdditionalAnswerData = qacrm.AdditionalAnswerData
                    };

                    response.Answers.Add(answer);
                }
            }

            return(response);
        }
Esempio n. 11
0
        public static SurveyResponseModel GenerateRandomResponseForSurvey(Survey Survey)
        {
            var Addr = Generator.GenerateAddress();

            SurveyResponseModel Responses = new SurveyResponseModel()
            {
                StartTime   = DateTime.Now.AddMinutes(-7),
                EndTime     = DateTime.Now,
                GPSLocation = new PITCSurveyLib.GPSLocation()
                {
                    Lat = 47.6419587, Lon = -122.1327818, Accuracy = 0
                },
                NearestAddress = new PITCSurveyLib.Address()
                {
                    Street  = Addr.AddressLine,
                    City    = Addr.City,
                    State   = Addr.StateAbbreviation,
                    ZipCode = Addr.ZipCode
                },
                LocationNotes      = "",
                SurveyID           = 1,
                Survey_Version     = Survey.Version,
                ResponseIdentifier = Guid.NewGuid(),
            };

            foreach (var Question in Survey.SurveyQuestions)
            {
                var Response = new SurveyQuestionResponseModel()
                {
                    QuestionID = Question.ID
                };

                int AnswersToSelect = Question.Question.AllowMultipleAnswers ? Rnd.Next(1, Question.AnswerChoices.Count() / 4) : 1;

                for (int i = 0; i < AnswersToSelect; i++)
                {
                    SurveyAnswerChoice Choice = Question.AnswerChoices[i];

                    SurveyQuestionAnswerChoiceResponseModel Answer = new SurveyQuestionAnswerChoiceResponseModel()
                    {
                        QuestionID     = Question.Question.ID,
                        AnswerChoiceID = Choice.AnswerChoice.ID
                    };

                    switch (Choice.AnswerChoice.AdditionalAnswerDataFormat)
                    {
                    case PITCSurveyLib.AnswerFormat.Int:
                        Answer.AdditionalAnswerData = Ints().ToString();
                        break;

                    case PITCSurveyLib.AnswerFormat.Date:
                        Answer.AdditionalAnswerData = Dates().ToShortDateString();
                        break;

                    case PITCSurveyLib.AnswerFormat.String:
                        if (Question.Question.WellKnownQuestion == PITCSurveyLib.WellKnownQuestion.NameOrInitials)
                        {
                            Answer.AdditionalAnswerData = Names();
                        }
                        else
                        {
                            Answer.AdditionalAnswerData = Words();
                        }
                        break;

                    default:
                        break;
                    }

                    Response.AnswerChoiceResponses.Add(Answer);
                }

                Responses.QuestionResponses.Add(Response);
            }

            return(Responses);
        }