Multi language dynamic object changes

This commit is contained in:
uppuv 2023-09-08 15:40:06 -04:00
parent 24a6e6513e
commit 4cf7d9f891
21 changed files with 370 additions and 283 deletions

View File

@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Questions.Controllers namespace DamageAssesment.Api.Questions.Controllers
{ {
[Route("api")]
[ApiController] [ApiController]
public class QuestionsController : ControllerBase public class QuestionsController : ControllerBase
{ {
@ -21,12 +20,12 @@ namespace DamageAssesment.Api.Questions.Controllers
/// </summary> /// </summary>
// get all questions // get all questions
[Route("{Language}/Questions")]
[Route("Questions")] [Route("Questions")]
[Route("Questions/{language:alpha}")]
[HttpGet] [HttpGet]
public async Task<IActionResult> GetQuestionsAsync(string? Language) public async Task<IActionResult> GetQuestionsAsync(string? language)
{ {
var result = await this.questionsProvider.GetQuestionsAsync(Language); var result = await this.questionsProvider.GetQuestionsAsync(language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Questions); return Ok(result.Questions);
@ -38,12 +37,12 @@ namespace DamageAssesment.Api.Questions.Controllers
/// <summary> /// <summary>
/// GET request for retrieving a question by ID. /// GET request for retrieving a question by ID.
/// </summary> /// </summary>
[Route("{Language}/Questions/{id}")] [Route("Questions/{id}/{language:alpha}")]
[Route("Questions/{id}")] [Route("Questions/{id:int}")]
[HttpGet] [HttpGet]
public async Task<IActionResult> GetQuestionAsync(int id, string? Language) public async Task<IActionResult> GetQuestionByIdAsync(string? language,int id)
{ {
var result = await this.questionsProvider.GetQuestionAsync(id,Language); var result = await this.questionsProvider.GetQuestionAsync(id, language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Question); return Ok(result.Question);
@ -56,12 +55,12 @@ namespace DamageAssesment.Api.Questions.Controllers
/// GET request for retrieving survey questions based on a survey ID. /// GET request for retrieving survey questions based on a survey ID.
/// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages
/// </summary> /// </summary>
[Route("{Language}/GetSurveyQuestions/{surveyId}")] [Route("Questions/BySurvey/{surveyId:int}")]
[Route("GetSurveyQuestions/{surveyId}")] [Route("Questions/BySurvey/{surveyId:int}/{language:alpha}")]
[HttpGet] [HttpGet]
public async Task<IActionResult> GetSurveyQuestions(int surveyId,string? Language) public async Task<IActionResult> GetSurveyQuestions(int surveyId,string? language)
{ {
var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language); var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.SurveyQuestions); return Ok(result.SurveyQuestions);
@ -126,10 +125,11 @@ namespace DamageAssesment.Api.Questions.Controllers
/// GET request for retrieving question categories. /// GET request for retrieving question categories.
/// </summary> /// </summary>
[HttpGet("QuestionCategories")] [HttpGet("Questions/Categories")]
public async Task<IActionResult> GetQuestionCategoriesAsync() [HttpGet("Questions/Categories/{language:alpha}")]
public async Task<IActionResult> GetQuestionCategoriesAsync(string? language)
{ {
var result = await this.questionsProvider.GetQuestionCategoriesAsync(); var result = await this.questionsProvider.GetQuestionCategoriesAsync(language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.QuestionCategories); return Ok(result.QuestionCategories);
@ -140,10 +140,11 @@ namespace DamageAssesment.Api.Questions.Controllers
/// GET request for retrieving a question category by ID. /// GET request for retrieving a question category by ID.
/// </summary> /// </summary>
[HttpGet("QuestionCategories/{id}")] [HttpGet("Questions/Categories/{id:int}")]
public async Task<IActionResult> GetQuestionCategoryAsync(int id) [HttpGet("Questions/Categories/{id:int}/{language:alpha}")]
public async Task<IActionResult> GetQuestionCategoryAsync(int id,string? language)
{ {
var result = await this.questionsProvider.GetQuestionCategoryAsync(id); var result = await this.questionsProvider.GetQuestionCategoryAsync(id, language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.QuestionCategory); return Ok(result.QuestionCategory);
@ -156,7 +157,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// PUT request for updating a question category. /// PUT request for updating a question category.
/// </summary> /// </summary>
[HttpPut("QuestionCategories")] [HttpPut("Questions/Categories")]
public async Task<IActionResult> UpdateQuestionCategory(Models.QuestionCategory questionCategory) public async Task<IActionResult> UpdateQuestionCategory(Models.QuestionCategory questionCategory)
{ {
if (questionCategory != null) if (questionCategory != null)
@ -177,7 +178,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// POST request for creating a new question category. /// POST request for creating a new question category.
/// </summary> /// </summary>
[HttpPost("QuestionCategories")] [HttpPost("Questions/Categories")]
public async Task<IActionResult> CreateQuestionCategory(Models.QuestionCategory questionCategory) public async Task<IActionResult> CreateQuestionCategory(Models.QuestionCategory questionCategory)
{ {
if (questionCategory != null) if (questionCategory != null)
@ -195,7 +196,7 @@ namespace DamageAssesment.Api.Questions.Controllers
/// DELETE request for deleting a question category based on ID. /// DELETE request for deleting a question category based on ID.
/// </summary> /// </summary>
[HttpDelete("QuestionCategories/{id}")] [HttpDelete("Questions/Categories/{id}")]
public async Task<IActionResult> DeleteQuestionCategory(int id) public async Task<IActionResult> DeleteQuestionCategory(int id)
{ {
var result = await this.questionsProvider.DeleteQuestionCategoryAsync(id); var result = await this.questionsProvider.DeleteQuestionCategoryAsync(id);

View File

@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace DamageAssesment.Api.Questions.Db
{
public class CategoryTranslation
{
[Key]
public int Id { get; set; }
[ForeignKey("QuestionCategory")]
public int CategoryId { get; set; }
public string Title { get; set; }
public string Language { get; set; }
}
}

View File

@ -7,8 +7,8 @@ namespace DamageAssesment.Api.Questions.Db
{ {
[Key] [Key]
public int Id { get; set; } public int Id { get; set; }
public string CategoryName { get; set; } public string IconName { get; set; }
public string CategoryImage { get; set; } public string IconLibrary { get; set; }
} }
} }

View File

@ -10,6 +10,7 @@ namespace DamageAssesment.Api.Questions.Db
public DbSet<Db.QuestionType> QuestionTypes { get; set; } public DbSet<Db.QuestionType> QuestionTypes { get; set; }
public DbSet<Db.QuestionsTranslation> QuestionsTranslations { get; set; } public DbSet<Db.QuestionsTranslation> QuestionsTranslations { get; set; }
public DbSet<Db.QuestionCategory> QuestionCategories { get; set; } public DbSet<Db.QuestionCategory> QuestionCategories { get; set; }
public DbSet<Db.CategoryTranslation> CategoryTranslations { get; set; }
public QuestionDbContext(DbContextOptions options) : base(options) public QuestionDbContext(DbContextOptions options) : base(options)
{ {
@ -29,6 +30,9 @@ namespace DamageAssesment.Api.Questions.Db
modelBuilder.Entity<QuestionCategory>() modelBuilder.Entity<QuestionCategory>()
.Property(item => item.Id) .Property(item => item.Id)
.ValueGeneratedOnAdd(); .ValueGeneratedOnAdd();
modelBuilder.Entity<CategoryTranslation>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
} }
} }
} }

View File

@ -4,19 +4,19 @@ namespace DamageAssesment.Api.Questions.Interfaces
{ {
public interface IQuestionsProvider : IQuestionTypesProvider public interface IQuestionsProvider : IQuestionTypesProvider
{ {
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language); Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language);
Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language); Task<(bool IsSuccess, IEnumerable<Models.MultiLanQuestion> Questions, string ErrorMessage)> GetQuestionsAsync(string language);
Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string Language); Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language);
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question);
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question);
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id); Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id);
Task<(bool IsSuccess, IEnumerable<Models.QuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(); Task<(bool IsSuccess, IEnumerable<Models.MultiLanQuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language);
Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int Id); Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int id, string? language);
Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory);
Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory);
Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id); Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int id);
void SeedData(); void SeedData();
} }
} }

View File

@ -0,0 +1,8 @@
namespace DamageAssesment.Api.Questions.Models
{
public class CategoryTranslation
{
public string Title { get; set; }
public string Language { get; set; }
}
}

View File

@ -2,11 +2,17 @@
namespace DamageAssesment.Api.Questions.Models namespace DamageAssesment.Api.Questions.Models
{ {
public class Question public class MultiLanQuestion: BaseQuestion
{
public MultiLanguage Questions { get; set; }
}
public class Question: BaseQuestion
{
public List<QuestionsTranslation> Questions { get; set; }
}
public class BaseQuestion
{ {
public int Id { get; set; } public int Id { get; set; }
public List<QuestionsTranslation> Questions { get; set; }
//public int QuestionTypeID { get; set; } //public int QuestionTypeID { get; set; }
public string TypeText { get; set; } = string.Empty; public string TypeText { get; set; } = string.Empty;

View File

@ -1,9 +1,17 @@
namespace DamageAssesment.Api.Questions.Models namespace DamageAssesment.Api.Questions.Models
{ {
public class QuestionCategory public class MultiLanQuestionCategory : BaseQuestionCategory
{
public object Titles { get; set; }
}
public class QuestionCategory : BaseQuestionCategory
{
public List<CategoryTranslation> Categories { get; set; }
}
public class BaseQuestionCategory
{ {
public int Id { get; set; } public int Id { get; set; }
public string CategoryName { get; set; } public string IconName { get; set; }
public string CategoryImage { get; set; } public string IconLibrary { get; set; }
} }
} }

View File

@ -5,4 +5,8 @@
public string QuestionText { get; set; } public string QuestionText { get; set; }
public string Language { get; set; } = "En"; public string Language { get; set; } = "En";
} }
public class MultiLanguage
{
public object questionText { get; set; }
}
} }

View File

@ -3,8 +3,8 @@
public class SurveyQuestions public class SurveyQuestions
{ {
public int CategoryId { get; set; } public int CategoryId { get; set; }
public string CategoryName { get; set; } public string IconName { get; set; }
public string CategoryImage { get; set; } public string IconLibrary { get; set; }
public List<Question> Questions { get; set; } public List<MultiLanQuestion> Questions { get; set; }
} }
} }

View File

@ -8,11 +8,15 @@ namespace DamageAssesment.Api.Questions.Profiles
{ {
CreateMap<Db.Question, Models.Question>().ForMember(dest => dest.TypeText, CreateMap<Db.Question, Models.Question>().ForMember(dest => dest.TypeText,
opt => opt.MapFrom(src => src.QuestionType.TypeText)); opt => opt.MapFrom(src => src.QuestionType.TypeText));
CreateMap<Db.Question, Models.MultiLanQuestion>().ForMember(dest => dest.TypeText,
opt => opt.MapFrom(src => src.QuestionType.TypeText));
CreateMap<Models.QuestionCategory, Db.QuestionCategory>(); CreateMap<Models.QuestionCategory, Db.QuestionCategory>();
CreateMap<Db.QuestionCategory, Models.QuestionCategory>(); CreateMap<Db.QuestionCategory, Models.MultiLanQuestionCategory>();
CreateMap<Models.Question, Db.Question>(); CreateMap<Models.Question, Db.Question>();
CreateMap<Db.QuestionsTranslation, Models.QuestionsTranslation>(); CreateMap<Db.QuestionsTranslation, Models.QuestionsTranslation>();
CreateMap<Models.QuestionsTranslation, Db.QuestionsTranslation>(); CreateMap<Models.QuestionsTranslation, Db.QuestionsTranslation>();
CreateMap<Db.CategoryTranslation, Models.CategoryTranslation>();
CreateMap<Models.CategoryTranslation, Db.CategoryTranslation>();
} }
} }
} }

View File

@ -5,6 +5,8 @@ using DamageAssesment.Api.Questions.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Collections;
using System.Collections.Generic;
namespace DamageAssesment.Api.Questions.Providers namespace DamageAssesment.Api.Questions.Providers
{ {
@ -57,16 +59,89 @@ namespace DamageAssesment.Api.Questions.Providers
if (!questionDbContext.QuestionCategories.Any()) if (!questionDbContext.QuestionCategories.Any())
{ {
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Flooding", CategoryImage= "https://example.com/images/img1.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, IconName = "Flooding", IconLibrary= "https://example.com/images/img1.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Electrical", CategoryImage = "https://example.com/images/img2.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, IconName = "Electrical", IconLibrary = "https://example.com/images/img2.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Structural", CategoryImage = "https://example.com/images/img3.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, IconName = "Structural", IconLibrary = "https://example.com/images/img3.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Utility", CategoryImage = "https://example.com/images/img4.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, IconName = "Utility", IconLibrary = "https://example.com/images/img4.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Debris", CategoryImage = "https://example.com/images/img5.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, IconName = "Debris", IconLibrary = "https://example.com/images/img5.png" });
questionDbContext.SaveChanges();
}
if (!questionDbContext.CategoryTranslations.Any())
{
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 1, CategoryId = 1, Title = "Flooding", Language = "en" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 2, CategoryId = 2, Title = "Electrical", Language = "en" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 3, CategoryId = 3, Title = "Structural", Language = "en" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 4, CategoryId = 4, Title = "Utility", Language = "en" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 5, CategoryId = 5, Title = "Debris", Language = "en" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 6, CategoryId = 1, Title = "Inondation", Language = "fr" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 7, CategoryId = 2, Title = "Électrique", Language = "fr" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 8, CategoryId = 3, Title = "De construction", Language = "fr" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 9, CategoryId = 4, Title = "Utilitaire", Language = "fr" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 10, CategoryId = 5, Title = "Débris", Language = "fr" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 11, CategoryId = 1, Title = "Inundación", Language = "es" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 12, CategoryId = 2, Title = "Eléctrica", Language = "es" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 13, CategoryId = 3, Title = "Estructural", Language = "es" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 14, CategoryId = 4, Title = "Utilidad", Language = "es" });
questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 15, CategoryId = 5, Title = "Escombros", Language = "es" });
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
} }
} }
public async Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language) public List<Models.CategoryTranslation> GetCategoryTranslations(int id, string? language)
{
List<Models.CategoryTranslation> categoryTranslations = new List<Models.CategoryTranslation>();
if (string.IsNullOrEmpty(language))
{
categoryTranslations = mapper.Map<List<Db.CategoryTranslation>, List<Models.CategoryTranslation>>(
questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id).ToList());
}
else
{
categoryTranslations = mapper.Map<List<Db.CategoryTranslation>, List<Models.CategoryTranslation>>(
questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id && a.Language == language).ToList());
}
return categoryTranslations;
}
public object CreateCategoryMultiLanguageObject(List<Models.CategoryTranslation> categoryTranslations)
{
object MultiLanguage = new object();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (Models.CategoryTranslation item in categoryTranslations)
{
dict.Add(item.Language, item.Title);
}
MultiLanguage = dict;
return MultiLanguage;
}
public List<Models.QuestionsTranslation> GetQuestionsTranslations(int id, string? language)
{
List<Models.QuestionsTranslation> QuestionTranslations;
if (string.IsNullOrEmpty(language))
{
QuestionTranslations = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id).ToList());
}
else
{
QuestionTranslations = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id && a.Language == language).ToList());
}
return QuestionTranslations;
}
public MultiLanguage CreateMultiLanguageObject(List<Models.QuestionsTranslation> questions)
{
MultiLanguage MultiLanguage = new MultiLanguage();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (Models.QuestionsTranslation item in questions)
{
dict.Add(item.Language, item.QuestionText);
}
MultiLanguage.questionText = dict;
return MultiLanguage;
}
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanQuestion> Questions, string ErrorMessage)> GetQuestionsAsync(string language)
{ {
try try
{ {
@ -76,21 +151,10 @@ namespace DamageAssesment.Api.Questions.Providers
{ {
//logger?.LogInformation($"{question} customer(s) found"); //logger?.LogInformation($"{question} customer(s) found");
var result = mapper.Map<IEnumerable<Db.Question>, IEnumerable<Models.Question>>(questions); var result = mapper.Map<IEnumerable<Db.Question>, IEnumerable<Models.MultiLanQuestion>>(questions);
foreach (var question in result) foreach (var question in result)
{ {
if (string.IsNullOrEmpty(Language)) question.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(question.Id, language));
{
question.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id).ToList());
}
else
{
question.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id && a.Language == Language).ToList());
}
} }
return (true, result, null); return (true, result, null);
} }
@ -102,27 +166,17 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language) public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language)
{ {
try try
{ {
logger?.LogInformation("Query Question"); logger?.LogInformation("Query Question");
var question = await questionDbContext.Questions.Include("QuestionType").AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); var question = await questionDbContext.Questions.Include("QuestionType").AsNoTracking().FirstOrDefaultAsync(q => q.Id == id);
if (question != null) if (question != null)
{ {
logger?.LogInformation($"{question} customer(s) found"); logger?.LogInformation($"{question} customer(s) found");
var result = mapper.Map<Db.Question, Models.Question>(question); var result = mapper.Map<Db.Question, Models.MultiLanQuestion>(question);
result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(id, language));
if (string.IsNullOrEmpty(Language))
{
result.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList());
}
else
{
result.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id && a.Language == Language).ToList());
}
return (true, result, null); return (true, result, null);
} }
return (false, null, "Not found"); return (false, null, "Not found");
@ -133,27 +187,15 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public List<Models.Question> GetSurveyQuestion(List<Models.Question> questions, string Language) public List<Models.MultiLanQuestion> GetSurveyQuestion(List<Models.MultiLanQuestion> questions, string language)
{ {
if (string.IsNullOrEmpty(Language)) foreach (var item in questions)
{ {
foreach (var item in questions) item.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language));
{
item.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id).ToList());
}
}
else
{
foreach (var item in questions)
{
item.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language == Language).ToList());
}
} }
return questions; return questions;
} }
public async Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string Language) public async Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string language)
{ {
try try
{ {
@ -170,9 +212,9 @@ namespace DamageAssesment.Api.Questions.Providers
surveyQuestionsList.Add(new SurveyQuestions() surveyQuestionsList.Add(new SurveyQuestions()
{ {
CategoryId = item.Id, CategoryId = item.Id,
CategoryImage = item.CategoryImage, IconLibrary = item.IconLibrary,
CategoryName = item.CategoryName, IconName = item.IconName,
Questions = GetSurveyQuestion(mapper.Map<List<Db.Question>, List<Models.Question>>(questions.Where(a => a.CategoryId == item.Id).ToList()), Language) Questions = GetSurveyQuestion(mapper.Map<List<Db.Question>, List<Models.MultiLanQuestion>>(questions.Where(a => a.CategoryId == item.Id).ToList()), language)
}); });
} }
@ -187,7 +229,7 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question)
{ {
try try
{ {
@ -200,7 +242,9 @@ namespace DamageAssesment.Api.Questions.Providers
questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
Question.Id = dbquestion.Id; Question.Id = dbquestion.Id;
return (true, Question, null); var result = mapper.Map<Db.Question, Models.MultiLanQuestion>(dbquestion);
result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,""));
return (true, result, null);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -208,7 +252,7 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question)
{ {
try try
{ {
@ -222,7 +266,9 @@ namespace DamageAssesment.Api.Questions.Providers
dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id);
questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
return (true, Question, null); var result = mapper.Map<Db.Question, Models.MultiLanQuestion>(dbquestion);
result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
return (true, result, null);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -231,21 +277,23 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id) public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id)
{ {
try try
{ {
var question = await questionDbContext.Questions.Where(x => x.Id == Id).FirstOrDefaultAsync(); var question = await questionDbContext.Questions.Where(x => x.Id == id).FirstOrDefaultAsync();
if (question != null) if (question != null)
{ {
var result = mapper.Map<Db.Question, Models.MultiLanQuestion>(question);
result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
questionDbContext.Questions.Remove(question); questionDbContext.Questions.Remove(question);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
return (true, mapper.Map<Db.Question, Models.Question>(question), $"QuestionID {Id} deleted Successfuly"); return (true, result, $"QuestionID {id} deleted Successfuly");
} }
else else
{ {
logger?.LogInformation($"QuestionID: {Id} Not found"); logger?.LogInformation($"QuestionID: {id} Not found");
return (false, null, "Not Found"); return (false, null, "Not Found");
} }
} }
@ -258,7 +306,7 @@ namespace DamageAssesment.Api.Questions.Providers
//Question Category Logic //Question Category Logic
public async Task<(bool IsSuccess, IEnumerable<Models.QuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync() public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanQuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language)
{ {
try try
{ {
@ -267,7 +315,11 @@ namespace DamageAssesment.Api.Questions.Providers
if (questionCategories != null) if (questionCategories != null)
{ {
//logger?.LogInformation($"{question} customer(s) found"); //logger?.LogInformation($"{question} customer(s) found");
var result = mapper.Map<IEnumerable<Db.QuestionCategory>, IEnumerable<Models.QuestionCategory>>(questionCategories); var result = mapper.Map<IEnumerable<Db.QuestionCategory>, IEnumerable<Models.MultiLanQuestionCategory>>(questionCategories);
foreach (var category in result)
{
category.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(category.Id, language));
}
return (true, result, null); return (true, result, null);
} }
return (false, null, "Not found"); return (false, null, "Not found");
@ -278,16 +330,17 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int Id) public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int id, string? language)
{ {
try try
{ {
logger?.LogInformation("Query Question"); logger?.LogInformation("Query Question");
var questioncategory = await questionDbContext.QuestionCategories.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); var questioncategory = await questionDbContext.QuestionCategories.AsNoTracking().FirstOrDefaultAsync(q => q.Id == id);
if (questioncategory != null) if (questioncategory != null)
{ {
logger?.LogInformation($"{questioncategory} customer(s) found"); logger?.LogInformation($"{questioncategory} customer(s) found");
var result = mapper.Map<Db.QuestionCategory, Models.QuestionCategory>(questioncategory); var result = mapper.Map<Db.QuestionCategory, Models.MultiLanQuestionCategory>(questioncategory);
result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, language));
return (true, result, null); return (true, result, null);
} }
return (false, null, "Not found"); return (false, null, "Not found");
@ -298,17 +351,23 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory)
{ {
try try
{ {
logger?.LogInformation("Query Question"); logger?.LogInformation("Query Question");
var dbQuestionCategory = mapper.Map<Models.QuestionCategory, Db.QuestionCategory>(QuestionCategory); var dbQuestionCategory = mapper.Map<Models.QuestionCategory, Db.QuestionCategory>(QuestionCategory);
var dbCategorytranslations = mapper.Map<List<Models.CategoryTranslation>, List<Db.CategoryTranslation>>(QuestionCategory.Categories);
// Question.QuestionType = GetQuestionType(Question.QuestionTypeId); // Question.QuestionType = GetQuestionType(Question.QuestionTypeId);
questionDbContext.QuestionCategories.Add(dbQuestionCategory); questionDbContext.QuestionCategories.Add(dbQuestionCategory);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
QuestionCategory.Id = dbQuestionCategory.Id; QuestionCategory.Id = dbQuestionCategory.Id;
return (true, QuestionCategory, null); dbCategorytranslations.ForEach(i => i.CategoryId = QuestionCategory.Id);
questionDbContext.CategoryTranslations.AddRange(dbCategorytranslations);
questionDbContext.SaveChanges();
var result = mapper.Map<Db.QuestionCategory, Models.MultiLanQuestionCategory>(dbQuestionCategory);
result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, ""));
return (true, result, null);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -316,15 +375,23 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory)
{ {
try try
{ {
var dbQuestionCategory = mapper.Map<Models.QuestionCategory, Db.QuestionCategory>(QuestionCategory); var dbQuestionCategory = mapper.Map<Models.QuestionCategory, Db.QuestionCategory>(QuestionCategory);
var dbCategorytranslations = mapper.Map<List<Models.CategoryTranslation>, List<Db.CategoryTranslation>>(QuestionCategory.Categories);
questionDbContext.Entry(dbQuestionCategory).State = EntityState.Modified; questionDbContext.Entry(dbQuestionCategory).State = EntityState.Modified;
QuestionCategory.Id = dbQuestionCategory.Id;
var oldcategories = questionDbContext.CategoryTranslations.Where(a => a.CategoryId == dbQuestionCategory.Id).ToList();
if (oldcategories != null)
questionDbContext.CategoryTranslations.RemoveRange(oldcategories);
dbCategorytranslations.ForEach(i => i.CategoryId = QuestionCategory.Id);
questionDbContext.CategoryTranslations.AddRange(dbCategorytranslations);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
return (true, QuestionCategory, null); var result = mapper.Map<Db.QuestionCategory, Models.MultiLanQuestionCategory>(dbQuestionCategory);
result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, ""));
return (true, result, null);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -333,18 +400,20 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id) public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id)
{ {
try try
{ {
var questioncategory = await questionDbContext.QuestionCategories.Where(x => x.Id == Id).FirstOrDefaultAsync(); var questioncategory = await questionDbContext.QuestionCategories.Where(x => x.Id == Id).FirstOrDefaultAsync();
if (questioncategory != null) if (questioncategory != null)
{ {
var result = mapper.Map<Db.QuestionCategory, Models.MultiLanQuestionCategory>(questioncategory);
result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, ""));
var question = await questionDbContext.Questions.Where(x => x.Id == Id).ToListAsync(); var question = await questionDbContext.Questions.Where(x => x.Id == Id).ToListAsync();
questionDbContext.Questions.RemoveRange(question); questionDbContext.Questions.RemoveRange(question);
questionDbContext.QuestionCategories.Remove(questioncategory); questionDbContext.QuestionCategories.Remove(questioncategory);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
return (true, mapper.Map<Db.QuestionCategory, Models.QuestionCategory>(questioncategory), $"QuestionID {Id} deleted Successfuly"); return (true, result, $"QuestionID {Id} deleted Successfuly");
} }
else else
{ {

View File

@ -8,42 +8,42 @@ namespace DamageAssesment.Api.Questions.Test
{ {
public class CategoryMockData public class CategoryMockData
{ {
public static async Task<(bool, IEnumerable<Questions.Models.QuestionCategory>, string)> getOkResponse() public static async Task<(bool, IEnumerable<Questions.Models.MultiLanQuestionCategory>, string)> getOkResponse()
{ {
IEnumerable<Questions.Models.QuestionCategory> list = new List<Questions.Models.QuestionCategory>(); IEnumerable<Questions.Models.MultiLanQuestionCategory> list = new List<Questions.Models.MultiLanQuestionCategory>();
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
list.Append(new Questions.Models.QuestionCategory { Id = i, CategoryImage = "img"+i,CategoryName="Category "+i }); list.Append(new Questions.Models.MultiLanQuestionCategory { Id = i, IconLibrary = "img"+i,IconName="Category "+i });
} }
return (true, list, null); return (true, list, null);
} }
public static async Task<(bool, Questions.Models.QuestionCategory, string)> getOkResponse(int Id) public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getOkResponse(int Id)
{ {
var Questions = await getOkResponse(); var Questions = await getOkResponse();
var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id);
return (true, Question, null); return (true, Question, null);
} }
public static async Task<(bool, Questions.Models.QuestionCategory, string)> getBadRequestResponse() public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getBadRequestResponse()
{ {
return (false, null, "Bad Request"); return (false, null, "Bad Request");
} }
public static async Task<(bool, Questions.Models.QuestionCategory, string)> getNotFoundResponse() public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getNotFoundResponse()
{ {
return (false, null, "Not Found"); return (false, null, "Not Found");
} }
public static async Task<(bool, IEnumerable<Questions.Models.QuestionCategory>, string)> getNoContentResponse() public static async Task<(bool, IEnumerable<Questions.Models.MultiLanQuestionCategory>, string)> getNoContentResponse()
{ {
IEnumerable<Questions.Models.QuestionCategory> list = new List<Questions.Models.QuestionCategory>(); IEnumerable<Questions.Models.MultiLanQuestionCategory> list = new List<Questions.Models.MultiLanQuestionCategory>();
return (false, list, null); return (false, list, null);
} }
public static async Task<Questions.Models.QuestionCategory> getInputQuestionCategoryData() public static async Task<Questions.Models.QuestionCategory> getInputQuestionCategoryData()
{ {
return new Questions.Models.QuestionCategory { Id = 1, CategoryName = "Category 1",CategoryImage="img 1" }; return new Questions.Models.QuestionCategory { Id = 1, IconName = "Category 1",IconLibrary="img 1" };
} }
} }

View File

@ -5,13 +5,13 @@ namespace DamageAssesment.Api.Questions.Test
public class MockData public class MockData
{ {
public static async Task<(bool, IEnumerable<Questions.Models.Question>, string)> getOkResponse() public static async Task<(bool, IEnumerable<Questions.Models.MultiLanQuestion>, string)> getOkResponse()
{ {
IEnumerable<Questions.Models.Question> list = new List<Questions.Models.Question>(); IEnumerable<Questions.Models.MultiLanQuestion> list = new List<Questions.Models.MultiLanQuestion>();
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
list.Append(new Questions.Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); list.Append(new Questions.Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i });
} }
return (true, list, null); return (true, list, null);
} }
@ -23,38 +23,38 @@ namespace DamageAssesment.Api.Questions.Test
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
List<Models.Question> question = new List<Models.Question>(); List<Models.MultiLanQuestion> question = new List<Models.MultiLanQuestion>();
question.Add(new Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); question.Add(new Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i });
list.Append(new Questions.Models.SurveyQuestions list.Append(new Questions.Models.SurveyQuestions
{ {
CategoryId = i, CategoryId = i,
CategoryImage = "img" + i, IconLibrary = "img" + i,
CategoryName = "Category " + i, IconName = "Category " + i,
Questions = question Questions = question
}); });
} }
return (true, list, null); return (true, list, null);
} }
public static async Task<(bool, Questions.Models.Question, string)> getOkResponse(int Id) public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getOkResponse(int Id)
{ {
var Questions = await getOkResponse(); var Questions = await getOkResponse();
var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id);
return (true, Question, null); return (true, Question, null);
} }
public static async Task<(bool, Questions.Models.Question, string)> getBadRequestResponse() public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getBadRequestResponse()
{ {
return (false, null, "Bad Request"); return (false, null, "Bad Request");
} }
public static async Task<(bool, Questions.Models.Question, string)> getNotFoundResponse() public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getNotFoundResponse()
{ {
return (false, null, "Not Found"); return (false, null, "Not Found");
} }
public static async Task<(bool, IEnumerable<Questions.Models.Question>, string)> getNoContentResponse() public static async Task<(bool, IEnumerable<Questions.Models.MultiLanQuestion>, string)> getNoContentResponse()
{ {
IEnumerable<Questions.Models.Question> list = new List<Questions.Models.Question>(); IEnumerable<Questions.Models.MultiLanQuestion> list = new List<Questions.Models.MultiLanQuestion>();
return (false, list, null); return (false, list, null);
} }
public static async Task<(bool, List<Questions.Models.SurveyQuestions>, string)> getNoSurveyContentResponse() public static async Task<(bool, List<Questions.Models.SurveyQuestions>, string)> getNoSurveyContentResponse()

View File

@ -42,7 +42,7 @@ namespace DamageAssesment.Api.Questions.Test
mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1,null); var result = (OkObjectResult)await QuestionProvider.GetQuestionByIdAsync(1,null);
Assert.Equal(200, result.StatusCode); Assert.Equal(200, result.StatusCode);
} }
@ -55,7 +55,7 @@ namespace DamageAssesment.Api.Questions.Test
mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99,null); var result = (NotFoundResult)await QuestionProvider.GetQuestionByIdAsync(99,null);
Assert.Equal(404, result.StatusCode); Assert.Equal(404, result.StatusCode);
} }
@ -188,10 +188,10 @@ namespace DamageAssesment.Api.Questions.Test
{ {
var mockQuestionService = new Mock<IQuestionsProvider>(); var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await CategoryMockData.getOkResponse(); var mockResponse = await CategoryMockData.getOkResponse();
mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync()).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync("en")).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync(); var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync("en");
Assert.Equal(200, result.StatusCode); Assert.Equal(200, result.StatusCode);
} }
@ -201,10 +201,10 @@ namespace DamageAssesment.Api.Questions.Test
{ {
var mockQuestionService = new Mock<IQuestionsProvider>(); var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await CategoryMockData.getNoContentResponse(); var mockResponse = await CategoryMockData.getNoContentResponse();
mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync()).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync("en")).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync(); var result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync("en");
Assert.Equal(204, result.StatusCode); Assert.Equal(204, result.StatusCode);
} }
@ -214,10 +214,10 @@ namespace DamageAssesment.Api.Questions.Test
{ {
var mockQuestionService = new Mock<IQuestionsProvider>(); var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await CategoryMockData.getOkResponse(1); var mockResponse = await CategoryMockData.getOkResponse(1);
mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(1)).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(1, "en")).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1); var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1, "en");
Assert.Equal(200, result.StatusCode); Assert.Equal(200, result.StatusCode);
} }
@ -227,10 +227,10 @@ namespace DamageAssesment.Api.Questions.Test
{ {
var mockQuestionService = new Mock<IQuestionsProvider>(); var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await CategoryMockData.getNotFoundResponse(); var mockResponse = await CategoryMockData.getNotFoundResponse();
mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(99)).ReturnsAsync(mockResponse); mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(99, "en")).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object); var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99); var result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99, "en");
Assert.Equal(404, result.StatusCode); Assert.Equal(404, result.StatusCode);
} }

View File

@ -9,37 +9,37 @@ namespace DamageAssesment.Api.Survey.Test
{ {
public class MockData public class MockData
{ {
public static async Task<(bool, IEnumerable<Surveys.Models.Survey>, string)> getOkResponse() public static async Task<(bool, IEnumerable<Surveys.Models.MultiLanSurvey>, string)> getOkResponse()
{ {
IEnumerable<Surveys.Models.Survey> list = new List<Surveys.Models.Survey>(); IEnumerable<Surveys.Models.MultiLanSurvey> list = new List<Surveys.Models.MultiLanSurvey>();
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
list.Append(new Surveys.Models.Survey { Id = i, /*Title = "Survey Title - " + i */}); list.Append(new Surveys.Models.MultiLanSurvey { Id = i, /*Title = "Survey Title - " + i */});
} }
return (true, list, null); return (true, list, null);
} }
public static async Task<(bool, Surveys.Models.Survey, string)> getOkResponse( int Id) public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getOkResponse( int Id)
{ {
var surveys = await getOkResponse(); var surveys = await getOkResponse();
var survey = surveys.Item2.FirstOrDefault(s => s.Id == Id); var survey = surveys.Item2.FirstOrDefault(s => s.Id == Id);
return (true, survey, null); return (true, survey, null);
} }
public static async Task<(bool, Surveys.Models.Survey, string)> getBadRequestResponse() public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getBadRequestResponse()
{ {
return (false, null,"Bad Request"); return (false, null,"Bad Request");
} }
public static async Task<(bool, Surveys.Models.Survey, string)> getNotFoundResponse() public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getNotFoundResponse()
{ {
return (false, null, "Not Found"); return (false, null, "Not Found");
} }
public static async Task<(bool, IEnumerable<Surveys.Models.Survey>, string)> getNoContentResponse() public static async Task<(bool, IEnumerable<Surveys.Models.MultiLanSurvey>, string)> getNoContentResponse()
{ {
IEnumerable<Surveys.Models.Survey> list = new List<Surveys.Models.Survey>(); IEnumerable<Surveys.Models.MultiLanSurvey> list = new List<Surveys.Models.MultiLanSurvey>();
return (false, list, null); return (false, list, null);
} }

View File

@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Surveys.Controllers namespace DamageAssesment.Api.Surveys.Controllers
{ {
[Route("api")]
[ApiController] [ApiController]
public class SurveysController : ControllerBase public class SurveysController : ControllerBase
{ {
@ -18,11 +17,11 @@ namespace DamageAssesment.Api.Surveys.Controllers
/// </summary> /// </summary>
[Route("Surveys")] [Route("Surveys")]
[Route("{Language}/Surveys")] [Route("Surveys/{language:alpha}")]
[HttpGet] [HttpGet]
public async Task<ActionResult> GetSurveysAsync(string? Language) public async Task<ActionResult> GetSurveysAsync(string? language)
{ {
var result = await this.surveyProvider.GetSurveysAsync(Language); var result = await this.surveyProvider.GetSurveysAsync(language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Surveys); return Ok(result.Surveys);
@ -33,12 +32,12 @@ namespace DamageAssesment.Api.Surveys.Controllers
/// <summary> /// <summary>
/// GET request for retrieving surveys by ID. /// GET request for retrieving surveys by ID.
/// </summary> /// </summary>
[Route("Surveys/{Id}")] [Route("Surveys/{id:int}")]
[Route("{Language}/Surveys/{Id}")] [Route("Surveys/{id:int}/{language:alpha}")]
[HttpGet] [HttpGet]
public async Task<ActionResult> GetSurveysAsync(int Id, string? Language) public async Task<ActionResult> GetSurveysAsync(int id, string? language)
{ {
var result = await this.surveyProvider.GetSurveysAsync(Id, Language); var result = await this.surveyProvider.GetSurveysAsync(id, language);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Surveys); return Ok(result.Surveys);
@ -64,10 +63,10 @@ namespace DamageAssesment.Api.Surveys.Controllers
/// </summary> /// </summary>
[HttpPut("Surveys/{Id}")] [HttpPut("Surveys/{id}")]
public async Task<ActionResult> PutSurveysAsync(int Id, Models.Survey survey) public async Task<ActionResult> PutSurveysAsync(int id, Models.Survey survey)
{ {
var result = await this.surveyProvider.PutSurveyAsync(Id, survey); var result = await this.surveyProvider.PutSurveyAsync(id, survey);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Survey); return Ok(result.Survey);
@ -81,10 +80,10 @@ namespace DamageAssesment.Api.Surveys.Controllers
/// <summary> /// <summary>
/// DELETE request for deleting a survey by ID. /// DELETE request for deleting a survey by ID.
/// </summary> /// </summary>
[HttpDelete("Surveys/{Id}")] [HttpDelete("Surveys/{id}")]
public async Task<ActionResult> DeleteSurveysAsync(int Id) public async Task<ActionResult> DeleteSurveysAsync(int id)
{ {
var result = await this.surveyProvider.DeleteSurveyAsync(Id); var result = await this.surveyProvider.DeleteSurveyAsync(id);
if (result.IsSuccess) if (result.IsSuccess)
{ {
return Ok(result.Survey); return Ok(result.Survey);

View File

@ -2,11 +2,11 @@
{ {
public interface ISurveyProvider public interface ISurveyProvider
{ {
Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language); Task<(bool IsSuccess, IEnumerable< Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language);
Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language); Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language);
Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey); Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey);
Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PutSurveyAsync(int Id,Models.Survey Survey); Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int id, Models.Survey Survey);
Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id); Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> DeleteSurveyAsync(int id);
void seedData(); void seedData();
} }

View File

@ -2,13 +2,21 @@
namespace DamageAssesment.Api.Surveys.Models namespace DamageAssesment.Api.Surveys.Models
{ {
public class Survey public class MultiLanSurvey : BaseSurvey
{
public object Titles { get; set; }
}
public class Survey : BaseSurvey
{
public IEnumerable<SurveyTranslation> Titles { get; set; }
}
public class BaseSurvey
{ {
public int Id { get; set; } public int Id { get; set; }
public bool IsEnabled { get; set; } public bool IsEnabled { get; set; }
public DateTime StartDate { get; set; } public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; } public DateTime EndDate { get; set; }
public DateTime CreatedDate { get; set; } public DateTime CreatedDate { get; set; }
public IEnumerable<SurveyTranslation> Titles { get; set; }
} }
} }

View File

@ -3,8 +3,10 @@
public class SurveysProfile:AutoMapper.Profile public class SurveysProfile:AutoMapper.Profile
{ {
public SurveysProfile() { public SurveysProfile() {
CreateMap<Db.Survey, Models.Survey>(); CreateMap<Db.Survey, Models.MultiLanSurvey>();
CreateMap<Models.Survey, Db.Survey>(); CreateMap<Models.Survey, Db.Survey>();
CreateMap<Db.SurveyTranslation, Models.SurveyTranslation>();
CreateMap<Models.SurveyTranslation, Db.SurveyTranslation>();
} }
} }
} }

View File

@ -49,60 +49,57 @@ namespace DamageAssesment.Api.Surveys.Providers
} }
} }
public async Task<(bool IsSuccess, IEnumerable<Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language) public IEnumerable<Models.SurveyTranslation> GetSurveyTranslations(int id, IEnumerable<Models.SurveyTranslation> SurveyTranslation,string? language)
{ {
IEnumerable<Models.Survey> surveysList = null; if (SurveyTranslation == null)
{
if (string.IsNullOrEmpty(language))
{
SurveyTranslation = mapper.Map<IEnumerable<Db.SurveyTranslation>, IEnumerable<Models.SurveyTranslation>>(
surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id).ToList());
}
else
{
SurveyTranslation = mapper.Map<IEnumerable<Db.SurveyTranslation>, IEnumerable<Models.SurveyTranslation>>(
surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id && a.Language == language).ToList());
}
}
return SurveyTranslation;
}
public object CreateMultiLanguageObject(IEnumerable<Models.SurveyTranslation> surveyTranslations)
{
object MultiLanguage = new object();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (Models.SurveyTranslation item in surveyTranslations)
{
dict.Add(item.Language, item.Title);
}
MultiLanguage = dict;
return MultiLanguage;
}
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language)
{
IEnumerable<Models.MultiLanSurvey> surveysList = null;
try try
{ {
logger?.LogInformation("Gell all Surveys from DB"); logger?.LogInformation("Gell all Surveys from DB");
var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync(); var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync();
var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); //var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync();
if (surveys != null) if (surveys != null)
{ {
if (string.IsNullOrEmpty(Language)) surveysList = from s in surveys
{ select new
surveysList = from s in surveys Models.MultiLanSurvey
select new {
Models.Survey Id = s.Id,
{ StartDate = s.StartDate,
Id = s.Id, EndDate = s.EndDate,
StartDate = s.StartDate, IsEnabled = s.IsEnabled,
EndDate = s.EndDate, CreatedDate = s.CreatedDate,
IsEnabled = s.IsEnabled, Titles = CreateMultiLanguageObject(GetSurveyTranslations(s.Id,null, language))
CreatedDate = s.CreatedDate,
Titles = from t in surveyTranslations
where t.SurveyId == s.Id
select new Models.SurveyTranslation
{
Title = t.Title,
Language = t.Language
}
}; };
}
else
{
surveysList = from s in surveys
select new
Models.Survey
{
Id = s.Id,
StartDate = s.StartDate,
EndDate = s.EndDate,
IsEnabled = s.IsEnabled,
CreatedDate = s.CreatedDate,
Titles = from t in surveyTranslations
where t.SurveyId == s.Id
&& t.Language == Language
select new Models.SurveyTranslation
{
Title = t.Title,
Language = t.Language
}
};
}
logger?.LogInformation($"{surveys.Count} Items(s) found"); logger?.LogInformation($"{surveys.Count} Items(s) found");
return (true, surveysList, null); return (true, surveysList, null);
@ -115,55 +112,27 @@ namespace DamageAssesment.Api.Surveys.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language) public async Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language)
{ {
try try
{ {
logger?.LogInformation("Query Survey"); logger?.LogInformation("Query Survey");
var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id && s.IsEnabled == true); var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == id && s.IsEnabled == true);
if (survey != null) if (survey != null)
{ {
Models.Survey result = null; Models.MultiLanSurvey result = null;
var surveyTranslations = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == survey.Id).ToListAsync(); var surveyTranslations = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == survey.Id).ToListAsync();
result = new Models.MultiLanSurvey
if (string.IsNullOrEmpty(Language))
{ {
result = new Models.Survey Id = survey.Id,
{ StartDate = survey.StartDate,
Id = survey.Id, EndDate = survey.EndDate,
StartDate = survey.StartDate, IsEnabled = survey.IsEnabled,
EndDate = survey.EndDate, CreatedDate = survey.CreatedDate,
IsEnabled = survey.IsEnabled, Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id,null, language))
CreatedDate = survey.CreatedDate,
Titles = from t in surveyTranslations
select new Models.SurveyTranslation
{
Title = t.Title,
Language = t.Language
}
}; };
} logger?.LogInformation($"Survey Id: {id} found");
else
{
result = new Models.Survey
{
Id = survey.Id,
StartDate = survey.StartDate,
EndDate = survey.EndDate,
IsEnabled = survey.IsEnabled,
CreatedDate = survey.CreatedDate,
Titles = from t in surveyTranslations
where t.Language == Language
select new Models.SurveyTranslation
{
Title = t.Title,
Language = t.Language
}
};
}
logger?.LogInformation($"Survey Id: {Id} found");
return (true, result, null); return (true, result, null);
} }
return (false, null, "Not found"); return (false, null, "Not found");
@ -175,7 +144,7 @@ namespace DamageAssesment.Api.Surveys.Providers
} }
} }
public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey survey) public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey survey)
{ {
try try
{ {
@ -192,8 +161,9 @@ namespace DamageAssesment.Api.Surveys.Providers
surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title });
} }
await surveyDbContext.SaveChangesAsync(); await surveyDbContext.SaveChangesAsync();
survey.Id = _survey.Id; var result = mapper.Map<Db.Survey, Models.MultiLanSurvey>(_survey);
return (true,survey, "Successful"); result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, ""));
return (true, result, "Successful");
} }
else else
{ {
@ -208,7 +178,7 @@ namespace DamageAssesment.Api.Surveys.Providers
} }
} }
public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PutSurveyAsync(int Id, Models.Survey survey) public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int Id, Models.Survey survey)
{ {
try try
{ {
@ -236,21 +206,8 @@ namespace DamageAssesment.Api.Surveys.Providers
surveyDbContext.SurveysTranslation.AddRange(listSurveyTranslation); surveyDbContext.SurveysTranslation.AddRange(listSurveyTranslation);
await surveyDbContext.SaveChangesAsync(); await surveyDbContext.SaveChangesAsync();
var result = new Models.Survey var result = mapper.Map<Db.Survey, Models.MultiLanSurvey>(_survey);
{ result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, ""));
Id = Id,
StartDate = survey.StartDate,
EndDate = survey.EndDate,
IsEnabled = survey.IsEnabled,
CreatedDate = survey.CreatedDate,
Titles = from t in listSurveyTranslation
select new Models.SurveyTranslation
{
Title = t.Title,
Language = t.Language
}
};
return (true, result, "Successful"); return (true, result, "Successful");
} }
else else
@ -272,7 +229,7 @@ namespace DamageAssesment.Api.Surveys.Providers
} }
} }
public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id) public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id)
{ {
try try
{ {
@ -280,9 +237,11 @@ namespace DamageAssesment.Api.Surveys.Providers
if (survey != null) if (survey != null)
{ {
var result = mapper.Map<Db.Survey, Models.MultiLanSurvey>(survey);
result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id, null, ""));
surveyDbContext.Surveys.Remove(survey); surveyDbContext.Surveys.Remove(survey);
await surveyDbContext.SaveChangesAsync(); await surveyDbContext.SaveChangesAsync();
return (true, mapper.Map<Db.Survey, Models.Survey>(survey), $"Survey Id: {Id} deleted Successfuly"); return (true, result, $"Survey Id: {Id} deleted Successfuly");
} }
else else
{ {