diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs index 3b114f7..0969153 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs @@ -98,7 +98,7 @@ namespace DamageAssesment.Api.Answers.Test mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (OkObjectResult) await AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -112,7 +112,7 @@ namespace DamageAssesment.Api.Answers.Test mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) await AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } @@ -126,7 +126,7 @@ namespace DamageAssesment.Api.Answers.Test mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (OkObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -140,7 +140,7 @@ namespace DamageAssesment.Api.Answers.Test mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (NotFoundObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (NotFoundObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(404, result.StatusCode); } @@ -154,7 +154,7 @@ namespace DamageAssesment.Api.Answers.Test mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs index e65d4f4..02466b6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs @@ -43,9 +43,9 @@ namespace DamageAssesment.Api.Answers.Test return (false, list, null); } - public static async Task getInputAnswerData() + public static async Task getInputAnswerData() { - return new Answers.Db.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 }; + return new Answers.Models.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index 27f5c3c..a86cbf1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -5,7 +5,6 @@ using Microsoft.OpenApi.Any; namespace DamageAssesment.Api.Answers.Controllers { - [Route("api")] [ApiController] public class AnswersController: ControllerBase { @@ -14,7 +13,10 @@ namespace DamageAssesment.Api.Answers.Controllers public AnswersController(IAnswersProvider answersProvider) { this.answerProvider=answersProvider; } - //get all answers + /// + /// Get all answers + /// + [HttpGet("Answers")] public async Task GetAnswersAsync() { @@ -26,7 +28,11 @@ namespace DamageAssesment.Api.Answers.Controllers return NoContent(); } - //get answer based on answerid + /// + /// Get an answer based on answerId. + /// + + [HttpGet("Answers/{Id}")] public async Task GetAnswerByIdAsync(int Id) { @@ -39,32 +45,39 @@ namespace DamageAssesment.Api.Answers.Controllers return NotFound(); } - // get all answers based on response id - [HttpGet("AnswersByResponse/{ResponseId}")] - public async Task GetAnswersByResponseId(int ResponseId) + /// + /// Get all answers based on responseId. + /// + [HttpGet("Answers/ByResponse/{responseid}")] + public async Task GetAnswersByResponseId(int responseid) { - var result = await this.answerProvider.GetAnswersAsync(ResponseId); + var result = await this.answerProvider.GetAnswersAsync(responseid); if(result.IsSuccess) { return Ok(result.Answers); } return NoContent(); } - // get all answers based on question id - [HttpGet("AnswersByQuestion/{QuestionId}")] - public async Task AnswersByQuestionId(int QuestionId) + /// + /// Get all answers based on questionId. + /// + + [HttpGet("Answers/ByQuestion/{questionid}")] + public async Task AnswersByQuestionId(int questionid) { - var result = await this.answerProvider.GetAnswersByQuestionAsync(QuestionId); + var result = await this.answerProvider.GetAnswersByQuestionAsync(questionid); if (result.IsSuccess) { return Ok(result.Answers); } return NotFound(); } - //update existing answer + /// + /// Update an existing answer. + /// [HttpPut("Answers")] - public async Task UpdateAnswer(Db.Answer answer) + public async Task UpdateAnswer(Models.Answer answer) { if (answer != null) { @@ -80,13 +93,16 @@ namespace DamageAssesment.Api.Answers.Controllers } return NotFound(); } - //save new answer + /// + /// Save a new answer. + /// + [HttpPost("Answers")] - public async Task CreateAnswer(Db.Answer answer) + public async Task CreateAnswer(Models.Answer answer) { if (answer != null) { - var result = await this.answerProvider.PostAnswerAsync(answer); + var result = await this.answerProvider.PostAnswerAsync(answer); if (result.IsSuccess) { return Ok(result.Answer); @@ -95,7 +111,10 @@ namespace DamageAssesment.Api.Answers.Controllers } return CreatedAtRoute("DefaultApi", new { id = answer.Id }, answer); } - //delete existing answer + /// + /// Delete an existing answer. + /// + [HttpDelete("Answers/{id}")] public async Task DeleteAnswer(int id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj index 8d98ce2..4e9f037 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj @@ -4,10 +4,12 @@ net6.0 enable enable + True + all diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs index e148ac7..2460385 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs @@ -16,7 +16,13 @@ namespace DamageAssesment.Api.Answers.Db options.UseSqlServer(_Configuration.GetConnectionString("AnswerConnection")); } public DbSet Answers { get; set; } - + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs index 4a202f1..d6c2cac 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs @@ -6,8 +6,9 @@ Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersByQuestionAsync(int questionId); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> GetAnswerByIdAsync(int Id); Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync(int responseId); - Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer); - Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer); + Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Models.Answer Answer); + Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Models.Answer Answer); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> DeleteAnswerAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs index 0a5e6ae..ce01163 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs @@ -7,6 +7,7 @@ namespace DamageAssesment.Api.Answers.Profiles public AnswersProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs index e6f66a0..0a38399 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Answers.Db; using DamageAssesment.Api.Answers.Interfaces; using DamageAssesment.Api.Answers.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,15 +11,24 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => { option.UseSqlServer("AnswerConnection"); }); + var app = builder.Build(); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index ebbab54..812f66e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -18,12 +18,11 @@ namespace DamageAssesment.Api.Answers.Providers this.answerDbContext = answerDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } public async Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync() { - try { logger?.LogInformation("Query Question"); @@ -108,16 +107,17 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer) + public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Models.Answer Answer) { try { logger?.LogInformation("Query Answer"); if (!AnswerExists(Answer.Id)) { - answerDbContext.Answers.Add(Answer); - answerDbContext.SaveChanges(); - var result = mapper.Map(Answer); + Db.Answer answer = mapper.Map(Answer); + answerDbContext.Answers.Add(answer); + await answerDbContext.SaveChangesAsync(); + var result = mapper.Map(answer); return (true, result, null); } return (false, null, "Answer is already exits"); @@ -128,7 +128,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer) + public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Models.Answer Answer) { try { @@ -137,9 +137,10 @@ namespace DamageAssesment.Api.Answers.Providers var existing = answerDbContext.Answers.AsNoTracking().FirstOrDefault(x => x.Id == Answer.Id); if (existing != null) { - answerDbContext.Answers.Update(Answer); - answerDbContext.SaveChanges(); - return (true, mapper.Map(Answer), "Successful"); + Db.Answer answer = mapper.Map(Answer); + answerDbContext.Answers.Update(answer); + await answerDbContext.SaveChangesAsync(); + return (true, mapper.Map(answer), "Successful"); } else { @@ -152,7 +153,6 @@ namespace DamageAssesment.Api.Answers.Providers logger?.LogInformation($"{Answer} Bad Request"); return (false, null, "Bad request"); } - } catch (Exception ex) { @@ -187,7 +187,7 @@ namespace DamageAssesment.Api.Answers.Providers return answerDbContext.Answers.AsNoTracking().Count(e => e.Id == id) > 0; } - private void SeedData() + public void SeedData() { if (!answerDbContext.Answers.Any()) { @@ -199,10 +199,6 @@ namespace DamageAssesment.Api.Answers.Providers answerDbContext.Answers.Add(new Db.Answer() { AnswerText = "No", Comment = "No Comment", QuestionId = 3, SurveyResponseId = 2 }); answerDbContext.SaveChanges(); } - } - - - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json index 1dc9826..1cd2bcb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs index 5bf695c..1b3ff31 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs @@ -80,7 +80,7 @@ namespace DamageAssesment.Api.Attachments.Test mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult)await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -96,7 +96,7 @@ namespace DamageAssesment.Api.Attachments.Test var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo=new AttachmentInfo(); - var result = (BadRequestObjectResult)await AttachmentProvider.UploadAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) await AttachmentProvider.UploadAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } @@ -112,7 +112,7 @@ namespace DamageAssesment.Api.Attachments.Test mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult)await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -128,7 +128,7 @@ namespace DamageAssesment.Api.Attachments.Test var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo = new AttachmentInfo(); - var result = (BadRequestObjectResult)await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs index 284830d..c097902 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.Attachments.Test for (int i = 0; i < 10; i++) { - list.Add(new Attachments.Models.Attachment(i, Guid.NewGuid().ToString() + "@gmail.com") + list.Add(new Attachments.Models.Attachment() { Id = i, AnswerId = i, @@ -73,10 +73,10 @@ namespace DamageAssesment.Api.Attachments.Test return (false, list, null); } - public static async Task> getInputAttachmentData() + public static async Task> getInputAttachmentData() { - List Attachments=new List(); - Attachments.Add(new Db.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ; + List Attachments=new List(); + Attachments.Add(new Models.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ; return Attachments; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index a86a151..0fcec65 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -7,7 +7,6 @@ using System.Net.Http.Headers; namespace DamageAssesment.Api.Attachments.Controllers { - [Route("api")] [ApiController] public class AttachmentsController : ControllerBase { @@ -19,7 +18,10 @@ namespace DamageAssesment.Api.Attachments.Controllers this.AttachmentProvider = AttachmentsProvider; this.UploadService = uploadService; } - //get all Attachments + /// + /// Get all attachments. + /// + [HttpGet("Attachments")] public async Task GetAttachmentsAsync() { @@ -32,7 +34,9 @@ namespace DamageAssesment.Api.Attachments.Controllers return NoContent(); } - //get all Attachment by Id + /// + /// Get all attachments by attachmentId. + /// [HttpGet("Attachments/{id}")] public async Task GetAttachmentbyIdAsync(int id) { @@ -73,7 +77,10 @@ namespace DamageAssesment.Api.Attachments.Controllers // } //} - //Save new Attachment + /// + /// Save new Attachment(s) + /// + [HttpPost("Attachments"), DisableRequestSizeLimit] public async Task UploadAttachmentAsync(AttachmentInfo attachmentInfo) { @@ -81,9 +88,9 @@ namespace DamageAssesment.Api.Attachments.Controllers { if (attachmentInfo.Answers.Count > 0) { - var Attachments = await this.AttachmentProvider.GetAttachmentCounter(); - List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); - var result = await this.AttachmentProvider.PostAttachmentAsync(attachments); + var Attachments = await this.AttachmentProvider.GetAttachmentCounter(); + List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); + var result = await this.AttachmentProvider.PostAttachmentAsync(attachments); if (result.IsSuccess) { return Ok(result.Attachments); @@ -97,8 +104,10 @@ namespace DamageAssesment.Api.Attachments.Controllers return BadRequest($"Internal server error: {ex}"); } } + /// + /// Modify an new attachment. + /// - //Save new Attachment [HttpPut("Attachments"), DisableRequestSizeLimit] public async Task UpdateAttachmentAsync(AttachmentInfo attachmentInfo) { @@ -106,10 +115,10 @@ namespace DamageAssesment.Api.Attachments.Controllers { if (attachmentInfo.Answers.Count > 0) { - var res = await this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); + var res = await this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); if (res.IsSuccess) { - List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); + List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); var result = await this.AttachmentProvider.PutAttachmentAsync(attachments); if (result.IsSuccess) { @@ -126,12 +135,14 @@ namespace DamageAssesment.Api.Attachments.Controllers return BadRequest($"Internal server error: {ex}"); } } - //delete existing Attachment - [HttpDelete("Delete")] - public async Task DeleteAttachment(int Id) + /// + /// Delete an existing attachment. + /// + [HttpDelete("Attachments/{id}")] + public async Task DeleteAttachment(int id) { // database soft delete - var result = await this.AttachmentProvider.DeleteAttachmentAsync(Id); + var result = await this.AttachmentProvider.DeleteAttachmentAsync(id); if (result.IsSuccess) { // deleting file from folder diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt deleted file mode 100644 index eed7e79..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt +++ /dev/null @@ -1 +0,0 @@ -sample \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj index 7ce43f2..3d793de 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj @@ -4,13 +4,17 @@ net6.0 enable enable + True - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs index 61af67f..7d92f3a 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs @@ -16,5 +16,12 @@ namespace DamageAssesment.Api.Attachments.Db options.UseSqlServer(_Configuration.GetConnectionString("AttachmentConnection")); } public DbSet Attachments { get; set; } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs index f193e11..5e56dbb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs @@ -6,8 +6,8 @@ namespace DamageAssesment.Api.Attachments.Interfaces { Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync(); Task<(bool IsSuccess, Models.Attachment Attachment, string ErrorMessage)> GetAttachmentByIdAsync(int Id); - Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments); - Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments); + Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments); + Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments); Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id); Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId); Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List answerIds); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs index 121d411..f645593 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs @@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Attachments.Interfaces { public interface IUploadService { - List UploadAttachment(int responseId,int answerId, int counter, List postedFile); - List UploadAttachment(int responseId, int counter, List answers); - public List UpdateAttachments(int responseId, List answers, IEnumerable attachments); + List UploadAttachment(int responseId,int answerId, int counter, List postedFile); + List UploadAttachment(int responseId, int counter, List answers); + public List UpdateAttachments(int responseId, List answers, IEnumerable attachments); void Deletefile(string path); void Movefile(string path); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs index 8f2ba66..b364727 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs @@ -13,10 +13,10 @@ namespace DamageAssesment.Api.Attachments.Models public bool IsDeleted { get; set; } public string FileName { get; set; } - public Attachment(int answerId, string uri) - { - this.AnswerId = answerId; - this.URI = uri; - } + //public Attachment(int answerId, string uri) + //{ + // this.AnswerId = answerId; + // this.URI = uri; + //} } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs index 44ee69f..2dca91e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs @@ -5,6 +5,7 @@ public AttachmentsProfiles() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs index d1aff95..4fd2e59 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs @@ -4,6 +4,7 @@ using DamageAssesment.Api.Attachments.Providers; using Microsoft.AspNetCore.Http.Features; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.FileProviders; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -12,7 +13,14 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs index 6a3cc63..92c20e5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs @@ -21,7 +21,7 @@ namespace DamageAssesment.Api.Attachments.Providers this.logger = logger; this.mapper = mapper; this.uploadservice = uploadservice; - SeedData(); + //SeedData(); } public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync() { @@ -65,14 +65,15 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); - AttachmentDbContext.Attachments.AddRange(Attachments); - AttachmentDbContext.SaveChanges(); - var result = mapper.Map, IEnumerable>(Attachments); + List attachments = mapper.Map, List>(Attachments); + AttachmentDbContext.Attachments.AddRange(attachments); + await AttachmentDbContext.SaveChangesAsync(); + var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } catch (Exception ex) @@ -82,14 +83,15 @@ namespace DamageAssesment.Api.Attachments.Providers } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); - AttachmentDbContext.Attachments.UpdateRange(Attachments); - AttachmentDbContext.SaveChanges(); - var result = mapper.Map, IEnumerable>(Attachments); + List attachments = mapper.Map, List>(Attachments); + AttachmentDbContext.Attachments.UpdateRange(attachments); + await AttachmentDbContext.SaveChangesAsync(); + var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } catch (Exception ex) @@ -108,7 +110,7 @@ namespace DamageAssesment.Api.Attachments.Providers if (Attachments.Count > 0) { AttachmentDbContext.Attachments.RemoveRange(Attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); } return (true, AttachmentId, ""); } @@ -141,7 +143,7 @@ namespace DamageAssesment.Api.Attachments.Providers if (Attachments.Count > 0) { AttachmentDbContext.Attachments.RemoveRange(Attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); } return (true, AttachmentId, ""); } @@ -152,7 +154,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, AttachmentId, ""); } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)>GetAttachmentInfo(List answers) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentInfo(List answers) { try { @@ -181,7 +183,7 @@ namespace DamageAssesment.Api.Attachments.Providers } Attachment.IsDeleted = true; AttachmentDbContext.Attachments.Update(Attachment); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); return (true, mapper.Map(Attachment), $"Attachment {Id} is deleted"); } catch (Exception ex) @@ -204,10 +206,11 @@ namespace DamageAssesment.Api.Attachments.Providers FileModel fileModel= new FileModel(){AttachmentId=0,FileName="Sample",FileContent= "c2FtcGxl",FileExtension=".txt"}; List answerInfos=new List(); answerInfos.Add(new AnswerInfo(){ AnswerId = 1,postedFiles=new List { fileModel }}); - List attachments = uploadservice.UploadAttachment(1, 0, answerInfos); + List attachments = uploadservice.UploadAttachment(1, 0, answerInfos); if (attachments.Count > 0) { - AttachmentDbContext.Attachments.AddRange(attachments); + List Attachments = mapper.Map, List>(attachments); + AttachmentDbContext.Attachments.AddRange(Attachments); AttachmentDbContext.SaveChanges(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs index 3c0f21f..8c9045c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs @@ -24,7 +24,7 @@ namespace DamageAssesment.Api.Attachments.Providers uploadpath = configuration.GetValue("Fileupload:folderpath"); Deletepath = configuration.GetValue("Fileupload:Deletepath"); } - public List UploadAttachment(int responseId,int answerId,int counter, List postedFile) + public List UploadAttachment(int responseId,int answerId,int counter, List postedFile) { var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), uploadpath); String responseDirectory = "Response-" + responseId; @@ -42,7 +42,7 @@ namespace DamageAssesment.Api.Attachments.Providers Deletefile(searchFile); } } - List attachments = new List(); + List attachments = new List(); foreach (IFormFile item in postedFile) { @@ -55,15 +55,15 @@ namespace DamageAssesment.Api.Attachments.Providers { item.CopyTo(stream); } - attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + attachments.Add(new Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } return attachments; } - public List UploadAttachment(int responseId, int counter,List answers) + public List UploadAttachment(int responseId, int counter,List answers) { - List attachments = new List(); + List attachments = new List(); try { foreach (var item in answers) @@ -94,20 +94,20 @@ namespace DamageAssesment.Api.Attachments.Providers var dbPath = Path.Combine(fullDirectoryPath, fileName); File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent)); - attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + attachments.Add(new Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } } return attachments; } catch (Exception ex) { - return new List(); + return new List(); } } - public List UpdateAttachments(int responseId,List answers,IEnumerable attachments) + public List UpdateAttachments(int responseId,List answers,IEnumerable attachments) { - List Dbattachments = new List(); + List Dbattachments = new List(); foreach (Models.Attachment searchFile in attachments) { Deletefile(searchFile.URI); @@ -131,7 +131,7 @@ namespace DamageAssesment.Api.Attachments.Providers var dbPath = Path.Combine(fullDirectoryPath, fileName); File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent)); - Dbattachments.Add(new Db.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + Dbattachments.Add(new Models.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } } return Dbattachments; diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json index 81c309e..1b48365 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs index 4df2f77..28b1c92 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs @@ -7,8 +7,15 @@ namespace DamageAssesment.Api.Documents.Db { public class DocumentDbContext : DbContext { - public DocumentDbContext(DbContextOptions options) : base(options) + private IConfiguration _Configuration { get; set; } + public DocumentDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { + _Configuration = configuration; + } + protected override void OnConfiguring(DbContextOptionsBuilder options) + { + // connect to sql server with connection string from app settings + options.UseSqlServer(_Configuration.GetConnectionString("DocumentConnection")); } public DbSet Documents { get; set; } public DbSet LinkTypes { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs index af38287..a1e9361 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs @@ -17,7 +17,7 @@ builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => { - option.UseInMemoryDatabase("DocumentConnection"); + option.UseSqlServer("DocumentConnection"); }); var app = builder.Build(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json index e38d9fb..843404d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json @@ -6,6 +6,9 @@ } }, "AllowedHosts": "*", + "ConnectionStrings": { + "DocumentConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;" + }, "Fileupload": { "folderpath": "DASA_Documents/Active", "Deletepath": "DASA_Documents/Deleted" diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs index 7c45f0d..4fcecad 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs @@ -43,11 +43,11 @@ namespace DamageAssesment.Api.Employees.Test public async Task GetEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); - mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync("Emp1")).ReturnsAsync(mockResponse); + var mockResponse = await MockData.getOkResponse(1); + mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.GetEmployeeByIdAsync("Emp1"); + var result = (OkObjectResult)await EmployeeProvider.GetEmployeeByIdAsync(1); Assert.Equal(200, result.StatusCode); } @@ -57,10 +57,10 @@ namespace DamageAssesment.Api.Employees.Test { var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync("Emp99")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync(99999)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundResult)await EmployeeProvider.GetEmployeeByIdAsync("Emp99"); + var result = (NotFoundResult)await EmployeeProvider.GetEmployeeByIdAsync(99999); Assert.Equal(404, result.StatusCode); } @@ -68,7 +68,7 @@ namespace DamageAssesment.Api.Employees.Test public async Task PostEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputEmployee = await MockData.getInputEmployeeData(); mockEmployeeService.Setup(service => service.PostEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); @@ -96,12 +96,12 @@ namespace DamageAssesment.Api.Employees.Test public async Task PutEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1,mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee(1,mockInputEmployee); Assert.Equal(200, result.StatusCode); } @@ -112,10 +112,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1, mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee(1, mockInputEmployee); Assert.Equal(404, result.StatusCode); } @@ -126,10 +126,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1, mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee(1, mockInputEmployee); Assert.Equal(400, result.StatusCode); } @@ -138,12 +138,12 @@ namespace DamageAssesment.Api.Employees.Test public async Task DeleteEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); - mockEmployeeService.Setup(service => service.DeleteEmployeeAsync("Emp1")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.DeleteEmployeeAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.DeleteEmployee("Emp1"); + var result = (OkObjectResult)await EmployeeProvider.DeleteEmployee(1); Assert.Equal(200, result.StatusCode); } @@ -153,10 +153,10 @@ namespace DamageAssesment.Api.Employees.Test { var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockEmployeeService.Setup(service => service.DeleteEmployeeAsync("Emp1")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.DeleteEmployeeAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundResult)await EmployeeProvider.DeleteEmployee("Emp1"); + var result = (NotFoundResult)await EmployeeProvider.DeleteEmployee(1); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs index cd5206e..19768fc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text; namespace DamageAssesment.Api.Employees.Test { @@ -15,13 +11,13 @@ namespace DamageAssesment.Api.Employees.Test for (int i = 0; i < 10; i++) { - list.Append(new Employees.Models.Employee { Id = "Emp"+i, Name = "Emoployee"+i, Email = "abc"+i+"@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18-i), IsActive = true, PreferredLanguage = "en" }); + list.Append(new Employees.Models.Employee { Id = i, Name = "Emoployee"+i, Email = "abc"+i+"@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18-i), IsActive = true, PreferredLanguage = "en" }); } return (true, list, null); } - public static async Task<(bool, Employees.Models.Employee, string)> getOkResponse(string Id) + public static async Task<(bool, Employees.Models.Employee, string)> getOkResponse(int Id) { var Employees = await getOkResponse(); var Employee = Employees.Item2.FirstOrDefault(s => s.Id == Id); @@ -33,19 +29,19 @@ namespace DamageAssesment.Api.Employees.Test return (false, null, "Bad Request"); } - public static async Task<(bool, Employees.Models.Employee, string)> getNotFoundResponse() + public static async Task<(bool, Models.Employee, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { IEnumerable list = new List(); return (false, list, null); } - public static async Task getInputEmployeeData() + public static async Task getInputEmployeeData() { - return new Employees.Db.Employee { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; + return new Models.Employee { Id = 1, Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs index 192a9d0..f5e0d88 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Employees.Controllers { - [Route("api")] [ApiController] public class EmployeesController : ControllerBase { @@ -15,7 +14,11 @@ namespace DamageAssesment.Api.Employees.Controllers { this.EmployeeProvider = EmployeesProvider; } - //get all Employees + + /// + /// GET request for retrieving employees. + /// + [HttpGet("Employees")] public async Task GetEmployeesAsync() { @@ -28,12 +31,16 @@ namespace DamageAssesment.Api.Employees.Controllers return NoContent(); } - //get Employee based on Employeeid - [HttpGet("Employees/{Id}")] - public async Task GetEmployeeByIdAsync(string Id) + + /// + /// GET request for retrieving an employee by ID. + /// + + [HttpGet("Employees/{id}")] + public async Task GetEmployeeByIdAsync(int id) { - var result = await EmployeeProvider.GetEmployeeByIdAsync(Id); + var result = await EmployeeProvider.GetEmployeeByIdAsync(id); if (result.IsSuccess) { return Ok(result.Employee); @@ -41,14 +48,17 @@ namespace DamageAssesment.Api.Employees.Controllers return NotFound(); } - //update existing Employee - - [HttpPut("Employees")] - public async Task UpdateEmployee(Db.Employee Employee) + + /// + /// PUT request for updating an existing employee. + /// + /// The updated employee object. + [HttpPut("Employees/{id}")] + public async Task UpdateEmployee(int id, Models.Employee Employee) { if (Employee != null) { - var result = await this.EmployeeProvider.UpdateEmployeeAsync(Employee); + var result = await this.EmployeeProvider.UpdateEmployeeAsync(id,Employee); if (result.IsSuccess) { return Ok(result.Employee); @@ -60,9 +70,13 @@ namespace DamageAssesment.Api.Employees.Controllers } return NotFound(); } - //save new Employee + + /// + /// POST request for creating a new employee. + /// + /// The employee information for creating a new employee. [HttpPost("Employees")] - public async Task CreateEmployee(Db.Employee Employee) + public async Task CreateEmployee(Models.Employee Employee) { if (Employee != null) { @@ -73,11 +87,14 @@ namespace DamageAssesment.Api.Employees.Controllers } return BadRequest(result.ErrorMessage); } - return CreatedAtRoute("DefaultApi", new { id = Employee.Id }, Employee); + return CreatedAtRoute("DefaultApi", new { Id = Employee.Id }, Employee); } - //delete existing Employee + /// + /// DELETE request for deleting an existing employee. + /// + /// The ID of the employee to be deleted. [HttpDelete("Employees/{id}")] - public async Task DeleteEmployee(string id) + public async Task DeleteEmployee(int id) { var result = await this.EmployeeProvider.DeleteEmployeeAsync(id); if (result.IsSuccess) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj index f6a61e2..44ec6d7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj @@ -1,14 +1,17 @@ - + net6.0 enable enable + True + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs index 2b3202a..45ab57e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs @@ -5,7 +5,9 @@ namespace DamageAssesment.Api.Employees.Db public class Employee { [Key] - public string Id { get; set; } + public int Id { get; set; } + [StringLength(50)] + public string EmployeeCode { get; set; } [StringLength(50)] public string Name { get; set; } @@ -17,7 +19,7 @@ namespace DamageAssesment.Api.Employees.Db [StringLength(50)] public string Email { get; set; } - public bool IsActive {get;set;} + public bool IsActive { get; set; } public string? PreferredLanguage { get; set; } = "en"; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs index 20c774e..b04cfd2 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs @@ -14,6 +14,13 @@ namespace DamageAssesment.Api.Employees.Db // connect to sql server with connection string from app settings options.UseSqlServer(_Configuration.GetConnectionString("EmployeeConnection")); } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } public DbSet Employees { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs index 059483d..91da039 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs @@ -3,9 +3,10 @@ public interface IEmployeesProvider { Task<(bool IsSuccess, IEnumerable Employees, string ErrorMessage)> GetEmployeesAsync(); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(string Id); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Db.Employee Employee); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(Db.Employee Employee); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(string Id); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(int Id); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Models.Employee Employee); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(int Id, Models.Employee Employee); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.Designer.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.Designer.cs new file mode 100644 index 0000000..b4aebb2 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.Designer.cs @@ -0,0 +1,72 @@ +// +using System; +using DamageAssesment.Api.Employees.Db; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DamageAssesment.Api.Employees.Migrations +{ + [DbContext(typeof(EmployeeDbContext))] + [Migration("20230913164315_employeeupdate")] + partial class employeeupdate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("DamageAssesment.Api.Employees.Db.Employee", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BirthDate") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("EmployeeCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsActive") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("OfficePhoneNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("PreferredLanguage") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Employees"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.cs new file mode 100644 index 0000000..8b5ff7f --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913164315_employeeupdate.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DamageAssesment.Api.Employees.Migrations +{ + /// + public partial class employeeupdate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Id", + table: "Employees", + type: "int", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(450)") + .Annotation("SqlServer:Identity", "1, 1"); + + migrationBuilder.AddColumn( + name: "EmployeeCode", + table: "Employees", + type: "nvarchar(50)", + maxLength: 50, + nullable: false, + defaultValue: ""); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "EmployeeCode", + table: "Employees"); + + migrationBuilder.AlterColumn( + name: "Id", + table: "Employees", + type: "nvarchar(450)", + nullable: false, + oldClrType: typeof(int), + oldType: "int") + .OldAnnotation("SqlServer:Identity", "1, 1"); + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.Designer.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.Designer.cs new file mode 100644 index 0000000..35e45ac --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.Designer.cs @@ -0,0 +1,72 @@ +// +using System; +using DamageAssesment.Api.Employees.Db; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DamageAssesment.Api.Employees.Migrations +{ + [DbContext(typeof(EmployeeDbContext))] + [Migration("20230913170055_updatedemployee_id")] + partial class updatedemployee_id + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("DamageAssesment.Api.Employees.Db.Employee", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BirthDate") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("EmployeeCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsActive") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("OfficePhoneNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("PreferredLanguage") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Employees"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.cs new file mode 100644 index 0000000..8b004ed --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/20230913170055_updatedemployee_id.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DamageAssesment.Api.Employees.Migrations +{ + /// + public partial class updatedemployee_id : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/EmployeeDbContextModelSnapshot.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/EmployeeDbContextModelSnapshot.cs index 7b928d2..3bfb33c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/EmployeeDbContextModelSnapshot.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Migrations/EmployeeDbContextModelSnapshot.cs @@ -24,8 +24,11 @@ namespace DamageAssesment.Api.Employees.Migrations modelBuilder.Entity("DamageAssesment.Api.Employees.Db.Employee", b => { - b.Property("Id") - .HasColumnType("nvarchar(450)"); + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); b.Property("BirthDate") .HasColumnType("datetime2"); @@ -35,6 +38,11 @@ namespace DamageAssesment.Api.Employees.Migrations .HasMaxLength(50) .HasColumnType("nvarchar(50)"); + b.Property("EmployeeCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + b.Property("IsActive") .HasColumnType("bit"); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs index 37afe32..0d5638c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs @@ -4,18 +4,11 @@ namespace DamageAssesment.Api.Employees.Models { public class Employee { - [Key] - public string Id { get; set; } - - [StringLength(50)] + public int Id { get; set; } + public string EmployeeCode { get; set; } public string Name { get; set; } - public DateTime BirthDate { get; set; } - - [StringLength(50)] public string OfficePhoneNumber { get; set; } - - [StringLength(50)] public string Email { get; set; } public bool IsActive { get; set; } public string? PreferredLanguage { get; set; } = "en"; diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs index 444752b..e46d15f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs @@ -7,6 +7,7 @@ namespace DamageAssesment.Api.Employees.Profiles public EmployeesProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs index 6a19ea0..7d61871 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Employees.Db; using DamageAssesment.Api.Employees.Interfaces; using DamageAssesment.Api.Employees.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,7 +11,15 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); + builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => @@ -25,6 +34,13 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var employeesProvider = services.GetRequiredService(); + employeesProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs index b2ec99b..c6501ac 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs @@ -19,7 +19,7 @@ namespace DamageAssesment.Api.Employees.Providers this.EmployeeDbContext = EmployeeDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + // SeedData(); } public async Task<(bool IsSuccess, IEnumerable Employees, string ErrorMessage)> GetEmployeesAsync() @@ -45,12 +45,12 @@ namespace DamageAssesment.Api.Employees.Providers } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(string Id) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(int Id) { try { logger?.LogInformation("Query Employee"); - var Employee = await EmployeeDbContext.Employees.AsNoTracking().FirstOrDefaultAsync(q => q.Id.ToLower() == Id.ToLower()); + var Employee = await EmployeeDbContext.Employees.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); if (Employee != null) { logger?.LogInformation($"{Employee} customer(s) found"); @@ -65,19 +65,21 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Db.Employee Employee) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Models.Employee Employee) { try { + Db.Employee _employee = mapper.Map(Employee); + logger?.LogInformation("Query Employee"); - if (!EmployeeExists(Employee.Id)) + if (!EmployeeCodeExists(Employee.EmployeeCode)) { - EmployeeDbContext.Employees.Add(Employee); + EmployeeDbContext.Employees.Add(_employee); + Employee.Id = _employee.Id; EmployeeDbContext.SaveChanges(); - var result = mapper.Map(Employee); - return (true, result, null); + return (true, Employee, null); } - return (false, null, "Employee is already exits"); + return (false, null, "Employee code is already exits"); } catch (Exception ex) { @@ -85,19 +87,21 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(Db.Employee Employee) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(int Id, Models.Employee Employee) { try { if (Employee != null) { - var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id.ToLower() == Employee.Id.ToLower()).FirstOrDefaultAsync(); + var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_employee != null) { - EmployeeDbContext.Employees.Update(Employee); + Db.Employee vEmployee = mapper.Map(Employee); + EmployeeDbContext.Employees.Update(vEmployee); EmployeeDbContext.SaveChanges(); - return (true, mapper.Map(Employee), "Successful"); + Employee.Id = Id; + return (true, Employee, "Successful"); } else { @@ -118,11 +122,11 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(string Id) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(int Id) { try { - Db.Employee Employee = EmployeeDbContext.Employees.AsNoTracking().Where(a => a.Id.ToLower() == Id.ToLower()).FirstOrDefault(); + Db.Employee Employee = EmployeeDbContext.Employees.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); if (Employee == null) { return (false, null, "Not Found"); @@ -135,24 +139,29 @@ namespace DamageAssesment.Api.Employees.Providers { logger?.LogError(ex.ToString()); - return (false,null, ex.Message); + return (false, null, ex.Message); } } - private bool EmployeeExists(string id) + private bool EmployeeExists(int id) { - return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.Id.ToLower() == id.ToLower()) > 0; + return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.Id == id) > 0; } - private void SeedData() + private bool EmployeeCodeExists(string employeeCode) + { + return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.EmployeeCode.ToLower() == employeeCode.ToLower()) > 0; + } + + public void SeedData() { if (!EmployeeDbContext.Employees.Any()) { - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678",BirthDate=DateTime.Now.AddYears(-18), IsActive = true,PreferredLanguage="en" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp2", Name = "ABC2", Email = "abc2@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-22), IsActive = true, PreferredLanguage = "fr" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp3", Name = "ABC3", Email = "abc3@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-30) ,IsActive = true, PreferredLanguage = "fr" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp4", Name = "ABC4", Email = "abc4@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-20) ,IsActive = true, PreferredLanguage = "en" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23) ,IsActive = true, PreferredLanguage = "sp" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32) ,IsActive = true, PreferredLanguage = "sp" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp2", Name = "ABC2", Email = "abc2@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-22), IsActive = true, PreferredLanguage = "fr" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp3", Name = "ABC3", Email = "abc3@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-30), IsActive = true, PreferredLanguage = "fr" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp4", Name = "ABC4", Email = "abc4@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-20), IsActive = true, PreferredLanguage = "en" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23), IsActive = true, PreferredLanguage = "es" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { EmployeeCode = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32), IsActive = true, PreferredLanguage = "es" }); EmployeeDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json index a0732a2..e4445e8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs index 4b5dc3c..cc0ad45 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs @@ -1,11 +1,6 @@ -using AutoMapper; using DamageAssesment.Api.Locations.Controllers; -using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; -using DamageAssesment.Api.Locations.Profiles; -using DamageAssesment.Api.Locations.Providers; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; using Moq; using Xunit; @@ -13,7 +8,145 @@ namespace DamageAssesment.Api.Locations.Test { public class LocationsServiceTest { + //Test for locations + [Fact(DisplayName = "Get Locations - Ok case")] + public async Task GetLocationsAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation(); + mockLocationService.Setup(service => service.GetLocationsAsync()).ReturnsAsync(mockResponse); + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.GetLocationsAsync(); + + Assert.Equal(200, result.StatusCode); + } + + + [Fact(DisplayName = "Get Locations - NoContent Case")] + public async Task GetLocationsAsync_ShouldReturnStatusCode204() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getNotFoundResponseLocation(); + mockLocationService.Setup(service => service.GetLocationsAsync()).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NoContentResult)await locationProvider.GetLocationsAsync(); + + Assert.Equal(204, result.StatusCode); + } + + [Fact(DisplayName = "Get Locations by Id- Ok case")] + public async Task GetLocationsByIdAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation(1); + mockLocationService.Setup(service => service.GetLocationByIdAsync(1)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.GetLocationByIdAsync(1); + + Assert.Equal(200, result.StatusCode); + } + + + [Fact(DisplayName = "Get Locations By Id - NoFound Case")] + public async Task GetLocationsByIdAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocationNotFoundResponse(); + mockLocationService.Setup(service => service.GetLocationByIdAsync(1)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.GetLocationByIdAsync(1); + + Assert.Equal(404, result.StatusCode); + } + + + [Fact(DisplayName = "Post Location - Ok case")] + public async Task PostLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation(1); + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.CreateLocation(mockInputLocation); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Post Location - BadRequest case")] + public async Task PostLocationAsync_ShouldReturnStatusCode400() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocationNotFoundResponse(); + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (BadRequestObjectResult)await locationProvider.CreateLocation(mockInputLocation); + + Assert.Equal(400, result.StatusCode); + } + + + [Fact(DisplayName = "Put Location - Ok case")] + public async Task PutLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(true, "update success"); + var mockInputLocation = new Models.Location { Id = 1, LocationCode ="Loc1", RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(1,mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.UpdateLocation(1,mockInputLocation); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Put Location - NotFound case")] + public async Task PutLocationAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(false, null); + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(1,mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.UpdateLocation(1,mockInputLocation); + + Assert.Equal(404, result.StatusCode); + } + + + [Fact(DisplayName = "Delete Location - Ok case")] + public async Task DeleteLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(true, "delete success"); + mockLocationService.Setup(service => service.DeleteLocationAsync(1)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.DeleteLocation(1); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Delete Location - NotFound case")] + public async Task DeleteLocationAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(false, null); + mockLocationService.Setup(service => service.DeleteLocationAsync(1)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.DeleteLocation(1); + + Assert.Equal(404, result.StatusCode); + } //Tests for regions @@ -47,11 +180,11 @@ namespace DamageAssesment.Api.Locations.Test public async Task GetRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); - mockRegionService.Setup(service => service.GetRegionByIdAsync("1")).ReturnsAsync(mockResponse); + var mockResponse = await MockData.getOkResponse(1); + mockRegionService.Setup(service => service.GetRegionByIdAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.GetRegionAsync("1"); + var result = (OkObjectResult)await regionProvider.GetRegionAsync(1); Assert.Equal(200, result.StatusCode); } @@ -61,18 +194,18 @@ namespace DamageAssesment.Api.Locations.Test { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockRegionService.Setup(service => service.GetRegionByIdAsync("99")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.GetRegionByIdAsync(99999)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundResult)await regionProvider.GetRegionAsync("99"); + var result = (NotFoundResult)await regionProvider.GetRegionAsync(99); Assert.Equal(404, result.StatusCode); } [Fact(DisplayName = "Post Region - Ok case")] - public async Task PostSurveyAsync_ShouldReturnStatusCode200() + public async Task PostRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputRegion = await MockData.getInputRegionData(); mockRegionService.Setup(service => service.PostRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); @@ -83,7 +216,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Post Region - BadRequest case")] - public async Task PostSurveyAsync_ShouldReturnStatusCode400() + public async Task PostRegionAsync_ShouldReturnStatusCode400() { var mockRegionService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); @@ -100,68 +233,68 @@ namespace DamageAssesment.Api.Locations.Test public async Task PutRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1,mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (OkObjectResult)await regionProvider.PutRegionAsync(1,mockInputRegion); Assert.Equal(200, result.StatusCode); } [Fact(DisplayName = "Put Region - NotFound case")] - public async Task PutSurveyAsync_ShouldReturnStatusCode404() + public async Task PutRegionAsync_ShouldReturnStatusCode404() { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1, mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (NotFoundObjectResult)await regionProvider.PutRegionAsync(1,mockInputRegion); Assert.Equal(404, result.StatusCode); } [Fact(DisplayName = "Put Region - BadRequest case")] - public async Task PutSurveyAsync_ShouldReturnStatusCode400() + public async Task PutRegionyAsync_ShouldReturnStatusCode400() { var mockRegionService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1, mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (BadRequestObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (BadRequestObjectResult)await regionProvider.PutRegionAsync(1, mockInputRegion); Assert.Equal(400, result.StatusCode); } [Fact(DisplayName = "Delete Region - Ok case")] - public async Task DeleteSurveyAsync_ShouldReturnStatusCode200() + public async Task DeleteRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); - mockRegionService.Setup(service => service.DeleteRegionAsync("1")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.DeleteRegionAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.DeleteRegionAsync("1"); + var result = (OkObjectResult)await regionProvider.DeleteRegionAsync(1); Assert.Equal(200, result.StatusCode); } [Fact(DisplayName = "Delete Region - NotFound case")] - public async Task DeleteSurveyAsync_ShouldReturnStatusCode404() + public async Task DeleteRegionAsync_ShouldReturnStatusCode404() { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockRegionService.Setup(service => service.DeleteRegionAsync("1")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.DeleteRegionAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundResult)await regionProvider.DeleteRegionAsync("1"); + var result = (NotFoundResult)await regionProvider.DeleteRegionAsync(1); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs index cd6b85e..50d1c8c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs @@ -9,17 +9,52 @@ namespace DamageAssesment.Api.Locations.Test for (int i = 0; i < 10; i++) { - list.Append(new Locations.Models.Region { Id = "R" + i, Abbreviation = "AB" + i, Name = "Region " + i }); + list.Append(new Locations.Models.Region { Id = i, Abbreviation = "AB" + i, Name = "Region " + i }); } return (true, list, null); } - public static async Task<(bool, Locations.Models.Region, string)> getOkResponse(string Id) + public static async Task<(bool, Locations.Models.Region, string)> getOkResponse(int Id) { - var surveys = await getOkResponse(); - var survey = surveys.Item2.FirstOrDefault(s => s.Id == Id); - return (true, survey, null); + var regions = await getOkResponse(); + var region = regions.Item2.FirstOrDefault(s => s.Id == Id); + return (true, region, null); + } + + + public static async Task<(bool, IEnumerable, string)> getOkResponseLocation() + { + IEnumerable list = new List(); + + for (int i = 0; i < 10; i++) + { + list.Append(new Locations.Models.Location { Id = i, RegionId = i, Name = "Location" }); + } + return (true, list, null); + } + + public static async Task<(bool, IEnumerable, string)> getNotFoundResponseLocation() + { + return (false, null, null); + } + + public static async Task<(bool, Models.Location, string)> getOkResponseLocation(int Id) + { + var locations = await getOkResponseLocation(); + var location = locations.Item2.FirstOrDefault(s => s.Id == Id); + return (true, location, null); + } + + public static async Task<(bool, Models.Location, string)> getLocation(bool value, string message) + { + var location = new Models.Location { Id = 1, LocationCode = "Loc1", RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + return (value, location, message); + } + + public static async Task<(bool, Locations.Models.Location, string)> getLocationNotFoundResponse() + { + return (false, null, "Not Found"); } public static async Task<(bool, Locations.Models.Region, string)> getBadRequestResponse() @@ -39,8 +74,7 @@ namespace DamageAssesment.Api.Locations.Test public static async Task getInputRegionData() { - return new Locations.Models.Region { Id = "R99", Name = "Region 99", Abbreviation = "A99" }; + return new Locations.Models.Region { Id = 99999, Name = "Region 99", Abbreviation = "A99" }; } - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs index c1df10f..d9bbea3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs @@ -4,17 +4,18 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Locations.Controllers { - [Route("api")] [ApiController] public class LocationsController : ControllerBase { private ILocationsProvider LocationProvider; - public LocationsController(ILocationsProvider LocationsProvider) { this.LocationProvider = LocationsProvider; } - // Get all Locations + /// + /// Get all locations. + /// + [HttpGet("Locations")] public async Task GetLocationsAsync() { @@ -22,14 +23,17 @@ namespace DamageAssesment.Api.Locations.Controllers var result = await LocationProvider.GetLocationsAsync(); if (result.IsSuccess) { - return Ok(result.locations); + return Ok(result.Locations); } - return NotFound(); + return NoContent(); } - // Get all Location based on Id + /// + /// Get all locations based on locationdId. + /// + [HttpGet("Locations/{id}")] - public async Task GetLocationByIdAsync(string id) + public async Task GetLocationByIdAsync(int id) { var result = await LocationProvider.GetLocationByIdAsync(id); @@ -40,44 +44,53 @@ namespace DamageAssesment.Api.Locations.Controllers return NotFound(); } - // Update Location entity - [HttpPut("Locations")] - public async Task UpdateLocation(Db.Location Location) + /// + /// Update a Location. + /// + + [HttpPut("Locations/{id}")] + public async Task UpdateLocation(int id, Models.Location Location) { if (Location != null) { - var result = await this.LocationProvider.UpdateLocationAsync(Location); + var result = await this.LocationProvider.UpdateLocationAsync(id, Location); if (result.IsSuccess) { - return Ok(result.ErrorMessage); + return Ok(result.Location); } return NotFound(); } return NotFound(); } - //save new location + /// + /// Save a new location. + /// + [HttpPost("Locations")] - public async Task CreateLocation(Db.Location Location) + public async Task CreateLocation(Models.Location Location) { if (Location != null) { var result = await this.LocationProvider.PostLocationAsync(Location); if (result.IsSuccess) { - return Ok(result.Question); + return Ok(result.Location); } - return NotFound(); + return BadRequest(result.ErrorMessage); } - return CreatedAtRoute("DefaultApi", new { id = Location.Id }, Location); + return BadRequest(); } - //delete existing location + /// + /// Delete an existing location. + /// + [HttpDelete("Locations/{id}")] - public async Task DeleteLocation(string id) + public async Task DeleteLocation(int id) { var result = await this.LocationProvider.DeleteLocationAsync(id); if (result.IsSuccess) { - return Ok(result.ErrorMessage); + return Ok(result.Location); } return NotFound(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs index 64a9bc7..172043c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Locations.Controllers { - [Route("api/[controller]")] [ApiController] public class RegionsController : ControllerBase { @@ -13,31 +12,39 @@ namespace DamageAssesment.Api.Locations.Controllers { this.regionProvider = regionProvider; } + /// + /// Get all regions.2 + /// - // Get all Regions - [HttpGet] + [HttpGet("regions")] public async Task GetRegionsAsync() { var result = await regionProvider.GetRegionsAsync(); if (result.IsSuccess) { - return Ok(result.regions); + return Ok(result.Regions); } return NoContent(); } + /// + /// GET request for retrieving a region by its ID. + /// - [HttpGet("{Id}")] - public async Task GetRegionAsync(string Id) + [HttpGet("regions/{id}")] + public async Task GetRegionAsync(int id) { - var result = await this.regionProvider.GetRegionByIdAsync(Id); + var result = await this.regionProvider.GetRegionByIdAsync(id); if (result.IsSuccess) { return Ok(result.Region); } return NotFound(); } + /// + /// POST request for creating a new region. + /// - [HttpPost] + [HttpPost("regions")] public async Task PostRegionAsync(Models.Region region) { var result = await this.regionProvider.PostRegionAsync(region); @@ -47,11 +54,14 @@ namespace DamageAssesment.Api.Locations.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing region. + /// - [HttpPut] - public async Task PutRegionAsync(Models.Region region) + [HttpPut("regions/{id}")] + public async Task PutRegionAsync(int id, Models.Region region) { - var result = await this.regionProvider.PutRegionAsync(region); + var result = await this.regionProvider.PutRegionAsync(id,region); if (result.IsSuccess) { return Ok(result.Region); @@ -61,11 +71,15 @@ namespace DamageAssesment.Api.Locations.Controllers return BadRequest(result.ErrorMessage); } + /// + /// DELETE request for deleting a region based on ID. + /// - [HttpDelete("{Id}")] - public async Task DeleteRegionAsync(string Id) + + [HttpDelete("regions/{id}")] + public async Task DeleteRegionAsync(int id) { - var result = await this.regionProvider.DeleteRegionAsync(Id); + var result = await this.regionProvider.DeleteRegionAsync(id); if (result.IsSuccess) { return Ok(result.Region); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj index e7a0c57..812ccd1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True @@ -19,6 +20,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs index 98afcf2..1774c9f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs @@ -6,18 +6,20 @@ namespace DamageAssesment.Api.Locations.Db public class Location { [Key] + public int Id { get; set; } + [ForeignKey("Region")] + public int RegionId { get; set; } [StringLength(4)] - public string Id { get; set; } + public string LocationCode { get; set; } [StringLength(50)] public string Name { get; set; } - [StringLength(1)] + [StringLength(4)] public string MaintenanceCenter { get; set; } [StringLength(2)] public string SchoolType { get; set; } - [ForeignKey("Region")] - public string RegionId { get; set; } + } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs index f5e4914..2e85262 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs @@ -2,7 +2,7 @@ namespace DamageAssesment.Api.Locations.Db { - public class LocationDbContext:DbContext + public class LocationDbContext : DbContext { private IConfiguration _Configuration { get; set; } public LocationDbContext(DbContextOptions options, IConfiguration configuration) : base(options) @@ -16,5 +16,21 @@ namespace DamageAssesment.Api.Locations.Db } public DbSet Locations { get; set; } public DbSet Regions { get; set; } + public LocationDbContext(DbContextOptions options) : base(options) + { + + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs index 7c03858..c0b64bb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs @@ -5,15 +5,12 @@ namespace DamageAssesment.Api.Locations.Db public class Region { [Key] - [StringLength(2)] - public string Id { get; set; } - + public int Id { get; set; } + [StringLength(50)] public string Name { get; set; } [StringLength(5)] public string Abbreviation { get; set; } - - // public ICollection Locations { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs index 8e85496..cd1de0c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs @@ -4,10 +4,11 @@ namespace DamageAssesment.Api.Locations.Interfaces { public interface ILocationsProvider { - Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync(); - Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(string Id); - Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Db.Location Location); - Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Db.Location Location); - Task<(bool IsSuccess, string ErrorMessage)> DeleteLocationAsync(string Id); + Task<(bool IsSuccess, IEnumerable Locations, string ErrorMessage)> GetLocationsAsync(); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(int Id); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> PostLocationAsync(Models.Location Location); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> UpdateLocationAsync(int Id, Models.Location Location); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> DeleteLocationAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs index 1df0776..22ef8b8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs @@ -2,10 +2,11 @@ { public interface IRegionsProvider { - Task<(bool IsSuccess, IEnumerable regions, string ErrorMessage)> GetRegionsAsync(); - Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id); + Task<(bool IsSuccess, IEnumerable Regions, string ErrorMessage)> GetRegionsAsync(); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(int Id); Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PostRegionAsync(Models.Region region); - Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(Models.Region region); - Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(string Id); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(int Id, Models.Region region); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs index 1fdad6a..eafbea6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs @@ -4,19 +4,12 @@ namespace DamageAssesment.Api.Locations.Models { public class Location { - [StringLength(4)] - public string Id { get; set; } - - [StringLength(1)] - public string RegionId { get; set; } - - [StringLength(50)] + [Key] + public int Id { get; set; } + public int RegionId { get; set; } + public string LocationCode { get; set; } public string Name { get; set; } - - [StringLength(1)] public string MaintenanceCenter { get; set; } - - [StringLength(2)] public string SchoolType { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs index ebcabeb..e2481a9 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs @@ -4,14 +4,8 @@ namespace DamageAssesment.Api.Locations.Models { public class Region { - - [StringLength(1)] - public string Id { get; set; } - - [StringLength(50)] + public int Id { get; set; } public string Name { get; set; } - - [StringLength(5)] public string Abbreviation { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs index ca91e6a..dce65b3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs @@ -5,6 +5,7 @@ public LocationProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs index bf25860..f8136bd 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; using DamageAssesment.Api.Locations.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,8 +11,14 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 @@ -26,6 +33,15 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var locationProvider = services.GetRequiredService(); + var regionProvider = services.GetRequiredService(); + locationProvider.SeedData(); + regionProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs index fcba375..02b8566 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs @@ -17,42 +17,19 @@ namespace DamageAssesment.Api.Locations.Providers this.locationDbContext = locationDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } - public async Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync() - { - - try - { - logger?.LogInformation("Query Question"); - var Location = await locationDbContext.Locations.AsNoTracking().ToListAsync(); - if (Location != null) - { - logger?.LogInformation($"{Location.Count} Locations(s) found"); - var result = mapper.Map, IEnumerable>(Location); - return (true, result, null); - } - return (false, null, "Not found"); - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - - } - - public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(string Id) + public async Task<(bool IsSuccess, IEnumerable Locations, string ErrorMessage)> GetLocationsAsync() { try { logger?.LogInformation("Query Location"); - var Location = await locationDbContext.Locations.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); - if (Location != null) + var locations = await locationDbContext.Locations.AsNoTracking().ToListAsync(); + if (locations != null) { - logger?.LogInformation($"{Location} customer(s) found"); - var result = mapper.Map(Location); + logger?.LogInformation($"{locations.Count} Locations(s) found"); + var result = mapper.Map, IEnumerable>(locations); return (true, result, null); } return (false, null, "Not found"); @@ -63,21 +40,42 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Db.Location Location) + + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(int Id) { try { logger?.LogInformation("Query Location"); - if (!LocationExists(Location.Id)) + var location = await locationDbContext.Locations.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); + if (location != null) { - locationDbContext.Locations.Add(Location); - locationDbContext.SaveChanges(); - var result = mapper.Map(Location); + logger?.LogInformation($"{location} found"); + var result = mapper.Map(location); return (true, result, null); } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> PostLocationAsync(Models.Location location) + { + try + { + if (!LocationCodeExists(location.LocationCode)) + { + Db.Location _location = mapper.Map(location); + locationDbContext.Locations.Add(_location); + await locationDbContext.SaveChangesAsync(); + location.Id = _location.Id; + return (true, location, null); + } else { - return (false, null, "Location is Already exists"); + return (false, null, "Location code is already exists"); } } catch (Exception ex) @@ -86,56 +84,67 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Db.Location Location) + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> UpdateLocationAsync(int Id, Models.Location location) { try { - locationDbContext.Entry(Location).State = EntityState.Modified; - locationDbContext.SaveChanges(); - return (true, "Record updated successfully"); - } - catch (Exception ex) - { - - logger?.LogError(ex.ToString()); - return (false, ex.Message); - } - } - public async Task<(bool IsSuccess, string ErrorMessage)> DeleteLocationAsync(string Id) - { - try - { - Db.Location Location = locationDbContext.Locations.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); - if (Location == null) + if (LocationExists(Id)) { - return (false, "record not found"); + Db.Location _location = mapper.Map(location); + locationDbContext.Entry(_location).State = EntityState.Modified; + await locationDbContext.SaveChangesAsync(); + return (true, location, "Record updated successfully"); + } + else + { + return (false, null, "Location is not exists"); } - locationDbContext.Locations.Remove(Location); - locationDbContext.SaveChanges(); - return (true, "Record deleted successfully"); } catch (Exception ex) { - logger?.LogError(ex.ToString()); - return (false, ex.Message); + return (false, null, ex.Message); + } + } + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> DeleteLocationAsync(int Id) + { + try + { + Db.Location location = locationDbContext.Locations.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); + if (location == null) + { + return (false, null, "record not found"); + } + locationDbContext.Locations.Remove(location); + await locationDbContext.SaveChangesAsync(); + return (true, mapper.Map(location), "Record deleted successfully"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); } } - private bool LocationExists(string id) + private bool LocationExists(int id) { return locationDbContext.Locations.AsNoTracking().Count(e => e.Id == id) > 0; } - private void SeedData() + + private bool LocationCodeExists(string locationCode) + { + return locationDbContext.Locations.AsNoTracking().Count(e => e.LocationCode.ToLower() == locationCode.ToLower()) > 0; + } + public void SeedData() { if (!locationDbContext.Locations.Any()) { - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc1", RegionId = "1", Name = "BOB GRAHAM EDUCATION CENTER 1", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc2", RegionId = "2", Name = "BOB GRAHAM EDUCATION CENTER 2", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc3", RegionId = "3", Name = "BOB GRAHAM EDUCATION CENTER 3", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc4", RegionId = "1", Name = "BOB GRAHAM EDUCATION CENTER 4", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc5", RegionId = "2", Name = "BOB GRAHAM EDUCATION CENTER 5", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc6", RegionId = "3", Name = "BOB GRAHAM EDUCATION CENTER 6", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc1", RegionId = 1, Name = "BOB GRAHAM EDUCATION CENTER 1", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc2", RegionId = 2, Name = "BOB GRAHAM EDUCATION CENTER 2", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc3", RegionId = 3, Name = "BOB GRAHAM EDUCATION CENTER 3", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc4", RegionId = 1, Name = "BOB GRAHAM EDUCATION CENTER 4", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc5", RegionId = 2, Name = "BOB GRAHAM EDUCATION CENTER 5", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { LocationCode = "Loc6", RegionId = 3, Name = "BOB GRAHAM EDUCATION CENTER 6", MaintenanceCenter = "1", SchoolType = "US" }); locationDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs index 9d78ce7..f855c7e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs @@ -1,7 +1,6 @@ using AutoMapper; using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; -using DamageAssesment.Api.Locations.Models; using Microsoft.EntityFrameworkCore; namespace DamageAssesment.Api.Locations.Providers @@ -17,10 +16,10 @@ namespace DamageAssesment.Api.Locations.Providers this.locationDbContext = regionDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(int Id) { try { @@ -42,7 +41,7 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, IEnumerable regions, string ErrorMessage)> GetRegionsAsync() + public async Task<(bool IsSuccess, IEnumerable Regions, string ErrorMessage)> GetRegionsAsync() { try { @@ -70,11 +69,10 @@ namespace DamageAssesment.Api.Locations.Providers { if (region != null) { - var regions = await locationDbContext.Regions.AsNoTracking().ToListAsync(); - - region.Id = Convert.ToString(regions.Count + 1); - locationDbContext.Regions.Add(mapper.Map(region)); - locationDbContext.SaveChanges(); + var _region = mapper.Map(region); + locationDbContext.Regions.Add(_region); + await locationDbContext.SaveChangesAsync(); + region.Id = _region.Id; logger?.LogInformation($"{region} added successfuly"); return (true, region, "Successful"); } @@ -91,30 +89,38 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(Models.Region region) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(int Id, Models.Region region) { try { if (region != null) { - var _region = await locationDbContext.Regions.AsNoTracking().Where(s => s.Id == region.Id).FirstOrDefaultAsync(); + var _region = await locationDbContext.Regions.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_region != null) { - locationDbContext.Regions.Update(mapper.Map(region)); - locationDbContext.SaveChanges(); - return (true, region, "Region updated Successfuly"); + if (RegionExists(region.Id)) + { + locationDbContext.Regions.Update(mapper.Map(region)); + locationDbContext.SaveChanges(); + return (true, region, "Region updated Successfuly"); + } + else + { + logger?.LogInformation($"RegionID: {Id} Not exists"); + return (false, null, "Region not exists"); + } } else { - logger?.LogInformation($"RegionID: {region.Id} Not found"); + logger?.LogInformation($"RegionID: {Id} Not found"); return (false, null, "Not Found"); } } else { - logger?.LogInformation($"RegionID: {region.Id} Bad Request"); + logger?.LogInformation($"RegionID: {Id} Bad Request"); return (false, null, "Bad request"); } } @@ -125,7 +131,7 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(string Id) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(int Id) { try { @@ -150,13 +156,18 @@ namespace DamageAssesment.Api.Locations.Providers } } - private void SeedData() + private bool RegionExists(int id) + { + return locationDbContext.Regions.AsNoTracking().Count(e => e.Id == id) > 0; + } + + public void SeedData() { if (!locationDbContext.Regions.Any()) { - locationDbContext.Regions.Add(new Db.Region() { Id = "1", Name = "North", Abbreviation = "N" }); - locationDbContext.Regions.Add(new Db.Region() { Id = "2", Name = "South", Abbreviation = "S" }); - locationDbContext.Regions.Add(new Db.Region() { Id = "3", Name = "Central", Abbreviation = "C" }); + locationDbContext.Regions.Add(new Db.Region() { Name = "North", Abbreviation = "N" }); + locationDbContext.Regions.Add(new Db.Region() { Name = "South", Abbreviation = "S" }); + locationDbContext.Regions.Add(new Db.Region() { Name = "Central", Abbreviation = "C" }); locationDbContext.SaveChanges(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json index 44e3bda..37d1aef 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index 0184d72..17024eb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -1,13 +1,8 @@ -using DamageAssesment.Api.Questions.Db; -using DamageAssesment.Api.Questions.Interfaces; -using DamageAssesment.Api.Questions.Models; -using DamageAssesment.Api.Questions.Providers; -using Microsoft.AspNetCore.Http; +using DamageAssesment.Api.Questions.Interfaces; using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Questions.Controllers { - [Route("api")] [ApiController] public class QuestionsController : ControllerBase { @@ -19,41 +14,63 @@ namespace DamageAssesment.Api.Questions.Controllers this.questionsProvider = questionsProvider; } + + /// + /// GET request for retrieving questions. + /// + // get all questions - [HttpGet("Questions")] - public async Task GetQuestionsAsync() + [Route("Questions")] + [Route("Questions/{language:alpha}")] + [HttpGet] + public async Task GetQuestionsAsync(string? language) { - var result = await this.questionsProvider.GetQuestionsAsync(); + var result = await this.questionsProvider.GetQuestionsAsync(language); if (result.IsSuccess) { return Ok(result.Questions); } return NoContent(); } + //Get questions based on question id - [HttpGet("Questions/{id}")] - public async Task GetQuestionAsync(int id) + /// + /// GET request for retrieving a question by ID. + /// + [Route("Questions/{id}/{language:alpha}")] + [Route("Questions/{id:int}")] + [HttpGet] + public async Task GetQuestionByIdAsync(int id, string? language) { - var result = await this.questionsProvider.GetQuestionAsync(id); + var result = await this.questionsProvider.GetQuestionAsync(id, language); if (result.IsSuccess) { return Ok(result.Question); } return NotFound(); } + //get all questions based on survey id - [HttpGet("GetSurveyQuestions/{surveyId}")] - public async Task GetSurveyQuestions(int surveyId,string? Language) + /// + /// GET request for retrieving survey questions based on a survey ID. + /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages + /// + [Route("Questions/BySurvey/{surveyId:int}")] + [Route("Questions/BySurvey/{surveyId:int}/{language:alpha}")] + [HttpGet] + public async Task GetSurveyQuestions(int surveyId,string? language) { - if (string.IsNullOrEmpty(Language)) Language = "en"; - var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language); + var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, language); if (result.IsSuccess) { return Ok(result.SurveyQuestions); } return NotFound(); } - //update existing question + /// + /// PUT request for updating a question (multilingual). + /// + [HttpPut("Questions")] public async Task UpdateQuestion(Models.Question question) { @@ -71,7 +88,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = question.Id }, question); } - //save new question + /// + /// POST request for creating a new question (multilingual). + /// + [HttpPost("Questions")] public async Task CreateQuestion(Models.Question question) { @@ -86,7 +106,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = question.Id }, question); } - // delete existing question + /// + /// DELETE request for deleting a question based on ID. + /// + [HttpDelete("Questions/{id}")] public async Task DeleteQuestion(int id) { @@ -98,23 +121,30 @@ namespace DamageAssesment.Api.Questions.Controllers return NotFound(); } + /// + /// GET request for retrieving question categories. + /// - // get all questions - [HttpGet("QuestionCategories")] - public async Task GetQuestionCategoriesAsync() + [HttpGet("Questions/Categories")] + [HttpGet("Questions/Categories/{language:alpha}")] + public async Task GetQuestionCategoriesAsync(string? language) { - var result = await this.questionsProvider.GetQuestionCategoriesAsync(); + var result = await this.questionsProvider.GetQuestionCategoriesAsync(language); if (result.IsSuccess) { return Ok(result.QuestionCategories); } return NoContent(); } - //Get questions based on question id - [HttpGet("QuestionCategories/{id}")] - public async Task GetQuestionCategoryAsync(int id) + /// + /// GET request for retrieving a question category by ID. + /// + + [HttpGet("Questions/Categories/{id:int}")] + [HttpGet("Questions/Categories/{id:int}/{language:alpha}")] + public async Task GetQuestionCategoryAsync(int id,string? language) { - var result = await this.questionsProvider.GetQuestionCategoryAsync(id); + var result = await this.questionsProvider.GetQuestionCategoryAsync(id, language); if (result.IsSuccess) { return Ok(result.QuestionCategory); @@ -123,8 +153,11 @@ namespace DamageAssesment.Api.Questions.Controllers } - //update existing question - [HttpPut("QuestionCategories")] + /// + /// PUT request for updating a question category. + /// + + [HttpPut("Questions/Categories")] public async Task UpdateQuestionCategory(Models.QuestionCategory questionCategory) { if (questionCategory != null) @@ -141,8 +174,11 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory); } - //save new question - [HttpPost("QuestionCategories")] + /// + /// POST request for creating a new question category. + /// + + [HttpPost("Questions/Categories")] public async Task CreateQuestionCategory(Models.QuestionCategory questionCategory) { if (questionCategory != null) @@ -156,8 +192,11 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory); } - // delete existing question - [HttpDelete("QuestionCategories/{id}")] + /// + /// DELETE request for deleting a question category based on ID. + /// + + [HttpDelete("Questions/Categories/{id}")] public async Task DeleteQuestionCategory(int id) { var result = await this.questionsProvider.DeleteQuestionCategoryAsync(id); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj index f6a61e2..812ccd1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj @@ -1,9 +1,10 @@ - + net6.0 enable enable + True @@ -19,6 +20,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs new file mode 100644 index 0000000..b6e21fa --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs @@ -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; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs index 846df86..29d0c64 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs @@ -20,7 +20,6 @@ namespace DamageAssesment.Api.Questions.Db public bool Key { get; set; } [ForeignKey("Survey")] public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } [ForeignKey("QuestionCategory")] public int CategoryId { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs index 06fc296..117f770 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs @@ -7,8 +7,8 @@ namespace DamageAssesment.Api.Questions.Db { [Key] public int Id { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs index d3ed79d..51df110 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs @@ -20,12 +20,29 @@ namespace DamageAssesment.Api.Questions.Db public DbSet QuestionTypes { get; set; } public DbSet QuestionsTranslations { get; set; } public DbSet QuestionCategories { get; set; } - //protected override void OnModelCreating(ModelBuilder modelBuilder) - //{ - // modelBuilder.Entity() - // .HasOne(a => a.QuestionType) - // .WithOne(b => b.Question) - // .HasForeignKey(b => b.QuestionTypeID); - //} + public DbSet CategoryTranslations { get; set; } + public QuestionDbContext(DbContextOptions options) : base(options) + { + + } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs index 0f62339..f8e13c8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs @@ -4,18 +4,19 @@ namespace DamageAssesment.Api.Questions.Interfaces { public interface IQuestionsProvider : IQuestionTypesProvider { - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id); - Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(); - Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string Language); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> GetQuestionAsync(int id, string language); + Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language); + Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id); - Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(); - Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int Id); - Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); - Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); - Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id); + Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int id, string? language); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs new file mode 100644 index 0000000..0c60d6b --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs @@ -0,0 +1,8 @@ +namespace DamageAssesment.Api.Questions.Models +{ + public class CategoryTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs index e181f1f..b6c1668 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs @@ -1,24 +1,18 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.Questions.Models +namespace DamageAssesment.Api.Questions.Models { - public class Question + public class Question: BaseQuestion + { + public List Questions { get; set; } + } + public class BaseQuestion { public int Id { get; set; } - public List Questions { get; set; } - - //public int QuestionTypeID { get; set; } - public string TypeText { get; set; } = string.Empty; - public int QuestionNumber { get; set; } public bool IsRequired { get; set; } public bool Comment { get; set; } - public bool Key { get; set; } public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } public int CategoryId { get; set; } - // public int? Survey_SurveyID { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs index 78a6b52..7c8ccc7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs @@ -1,9 +1,17 @@ namespace DamageAssesment.Api.Questions.Models { - public class QuestionCategory + public class MultiLanQuestionCategory : BaseQuestionCategory + { + public object Titles { get; set; } + } + public class QuestionCategory : BaseQuestionCategory + { + public List Categories { get; set; } + } + public class BaseQuestionCategory { public int Id { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs index 6df8219..28548f1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs @@ -3,6 +3,10 @@ public class QuestionsTranslation { public string QuestionText { get; set; } - public string Language { get; set; } = "En"; + public string Language { get; set; } = "en"; + } + public class MultiLanguage : BaseQuestion + { + public Dictionary Text { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs index 9736510..8f4fd7b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs @@ -3,8 +3,8 @@ public class SurveyQuestions { public int CategoryId { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } - public List Questions { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } + public List QuestionsText { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs index 015fe0c..59b402a 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs @@ -8,11 +8,15 @@ namespace DamageAssesment.Api.Questions.Profiles { CreateMap().ForMember(dest => dest.TypeText, opt => opt.MapFrom(src => src.QuestionType.TypeText)); + CreateMap().ForMember(dest => dest.TypeText, + opt => opt.MapFrom(src => src.QuestionType.TypeText)); CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs index a9d2d26..c47a38d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs @@ -2,7 +2,7 @@ using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; using DamageAssesment.Api.Questions.Providers; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -15,9 +15,15 @@ builder.Services.AddControllers(); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); - builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseSqlServer("QuestionConnection"); @@ -29,6 +35,13 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var questionProvider = services.GetRequiredService(); + questionProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index f95591b..13b12c5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -2,9 +2,7 @@ using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; using DamageAssesment.Api.Questions.Models; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace DamageAssesment.Api.Questions.Providers { @@ -24,18 +22,16 @@ namespace DamageAssesment.Api.Questions.Providers SeedData(); } - - - private void SeedData() + public void SeedData() { if (!questionDbContext.QuestionCategories.Any()) { - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { CategoryName = "Electrical", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { CategoryName = "Flooding", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { CategoryName = "Structural", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { CategoryName = "Utility", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { CategoryName = "Debris", CategoryImage = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Electrical", IconLibrary = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Flooding", IconLibrary = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Structural", IconLibrary = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Utility", IconLibrary = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { IconName = "Debris", IconLibrary = "img1" }); questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionTypes.Any()) @@ -47,9 +43,9 @@ namespace DamageAssesment.Api.Questions.Providers } if (!questionDbContext.Questions.Any()) { - questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1",CategoryId=1 }); - questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 3, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 }); - questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 }); + questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=1 }); + questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 3, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 1 }); + questionDbContext.Questions.Add(new Db.Question() { QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, CategoryId = 2 }); questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionsTranslations.Any()) @@ -66,9 +62,81 @@ namespace DamageAssesment.Api.Questions.Providers questionDbContext.SaveChanges(); } + if (!questionDbContext.CategoryTranslations.Any()) + { + + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 1, Title = "Flooding", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 2, Title = "Electrical", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 3, Title = "Structural", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 4, Title = "Utility", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 5, Title = "Debris", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 1, Title = "Inondation", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 2, Title = "Électrique", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 3, Title = "De construction", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 4, Title = "Utilitaire", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 5, Title = "Débris", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 1, Title = "Inundación", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 2, Title = "Eléctrica", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 3, Title = "Estructural", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 4, Title = "Utilidad", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { CategoryId = 5, Title = "Escombros", Language = "es" }); + questionDbContext.SaveChanges(); + } } - public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync() + public List GetCategoryTranslations(int id, string? language) + { + List categoryTranslations = new List(); + if (string.IsNullOrEmpty(language)) + { + categoryTranslations = mapper.Map, List>( + questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id).ToList()); + } + else + { + categoryTranslations = mapper.Map, List>( + questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id && a.Language == language).ToList()); + } + return categoryTranslations; + } + public object CreateCategoryMultiLanguageObject(List categoryTranslations) + { + object MultiLanguage = new object(); + Dictionary dict = new Dictionary(); + foreach (Models.CategoryTranslation item in categoryTranslations) + { + dict.Add(item.Language, item.Title); + } + MultiLanguage = dict; + return MultiLanguage; + } + public List GetQuestionsTranslations(int id, string? language) + { + List QuestionTranslations; + if (string.IsNullOrEmpty(language)) + { + QuestionTranslations = mapper.Map, List>( + questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id).ToList()); + } + else + { + QuestionTranslations = mapper.Map, List>( + questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id && a.Language == language).ToList()); + } + return QuestionTranslations; + } + public Dictionary CreateMultiLanguageObject(List questions) + { + MultiLanguage MultiLanguage = new MultiLanguage(); + Dictionary dict = new Dictionary(); + foreach (Models.QuestionsTranslation item in questions) + { + dict.Add(item.Language, item.QuestionText); + } + //MultiLanguage.questionText = dict; + return dict; + } + public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language) { try { @@ -78,11 +146,10 @@ namespace DamageAssesment.Api.Questions.Providers { //logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map, IEnumerable>(questions); - foreach (var question in result) + var result = mapper.Map, IEnumerable>(questions); + foreach (var item in result) { - question.Questions=mapper.Map,List>( - questionDbContext.QuestionsTranslations.Where(a=>a.QuestionId==question.Id).ToList()); + item.Text = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); } return (true, result, null); } @@ -94,18 +161,17 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> GetQuestionAsync(int id, string language) { try { 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) { logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map(question); - result.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList()); + var result = mapper.Map(question); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(id, language)); return (true, result, null); } return (false, null, "Not found"); @@ -116,35 +182,34 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public List GetSurveyQuestion(List questions,string Language) + public List GetSurveyQuestion(List questions, string language) { foreach (var item in questions) { - item.Questions= mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language== Language).ToList()); + item.Text = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); } return questions; } - public async Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string Language) + public async Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string language) { try { logger?.LogInformation("Query Question"); - var questions = await questionDbContext.Questions.Include("QuestionType").Where(a=>a.SurveyId==SurveyId).AsNoTracking().ToListAsync(); + var questions = await questionDbContext.Questions.Include("QuestionType").Where(a => a.SurveyId == SurveyId).AsNoTracking().ToListAsync(); if (questions != null) { List surveyQuestionsList = new List(); - List CategoryIds=questions.Select(a=>a.CategoryId).Distinct().ToList(); - var questioncategories = await questionDbContext.QuestionCategories.Where(a =>CategoryIds.Contains(a.Id)).ToListAsync(); + List CategoryIds = questions.Select(a => a.CategoryId).Distinct().ToList(); + var questioncategories = await questionDbContext.QuestionCategories.Where(a => CategoryIds.Contains(a.Id)).ToListAsync(); //logger?.LogInformation($"{question} customer(s) found"); foreach (var item in questioncategories) { surveyQuestionsList.Add(new SurveyQuestions() { CategoryId = item.Id, - CategoryImage = item.CategoryImage, - CategoryName = item.CategoryName, - Questions = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), Language) + IconLibrary = item.IconLibrary, + IconName = item.IconName, + QuestionsText = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), language) }); } @@ -159,20 +224,22 @@ namespace DamageAssesment.Api.Questions.Providers 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.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) { try { logger?.LogInformation("Query Question"); var dbquestion = mapper.Map(Question); var dbquestiontranslation = mapper.Map, List>(Question.Questions); - dbquestion.QuestionTypeId=questionDbContext.QuestionTypes.Where(a=>a.TypeText==Question.TypeText).Select(a=>a.Id).FirstOrDefault(); + dbquestion.QuestionTypeId = questionDbContext.QuestionTypes.Where(a => a.TypeText == Question.TypeText).Select(a => a.Id).FirstOrDefault(); questionDbContext.Questions.Add(dbquestion); dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); - questionDbContext.SaveChanges(); + questionDbContext.SaveChanges(); Question.Id = dbquestion.Id; - return (true, Question, null); + var result = mapper.Map(dbquestion); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,"")); + return (true, result, null); } catch (Exception ex) { @@ -180,7 +247,7 @@ namespace DamageAssesment.Api.Questions.Providers 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.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) { try { @@ -189,12 +256,14 @@ namespace DamageAssesment.Api.Questions.Providers dbquestion.QuestionTypeId = questionDbContext.QuestionTypes.Where(a => a.TypeText == Question.TypeText).Select(a => a.Id).FirstOrDefault(); questionDbContext.Entry(dbquestion).State = EntityState.Modified; var oldquestions = questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == dbquestion.Id).ToList(); - if(oldquestions!=null) + if (oldquestions != null) questionDbContext.QuestionsTranslations.RemoveRange(oldquestions); dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.SaveChanges(); - return (true, Question, null); + var result = mapper.Map(dbquestion); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -203,21 +272,23 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id) { 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) { + var result = mapper.Map(question); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); questionDbContext.Questions.Remove(question); questionDbContext.SaveChanges(); - return (true, mapper.Map(question), $"QuestionID {Id} deleted Successfuly"); + return (true, result, $"QuestionID {id} deleted Successfuly"); } else { - logger?.LogInformation($"QuestionID: {Id} Not found"); + logger?.LogInformation($"QuestionID: {id} Not found"); return (false, null, "Not Found"); } } @@ -228,11 +299,9 @@ namespace DamageAssesment.Api.Questions.Providers } } - - //Question Category Logic - public async Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync() + public async Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language) { try { @@ -241,7 +310,11 @@ namespace DamageAssesment.Api.Questions.Providers if (questionCategories != null) { //logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map, IEnumerable>(questionCategories); + var result = mapper.Map, IEnumerable>(questionCategories); + foreach (var category in result) + { + category.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(category.Id, language)); + } return (true, result, null); } return (false, null, "Not found"); @@ -252,16 +325,17 @@ namespace DamageAssesment.Api.Questions.Providers 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 { 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) { logger?.LogInformation($"{questioncategory} customer(s) found"); - var result = mapper.Map(questioncategory); + var result = mapper.Map(questioncategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, language)); return (true, result, null); } return (false, null, "Not found"); @@ -272,17 +346,23 @@ namespace DamageAssesment.Api.Questions.Providers 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 { logger?.LogInformation("Query Question"); var dbQuestionCategory = mapper.Map(QuestionCategory); + var dbCategorytranslations = mapper.Map, List>(QuestionCategory.Categories); // Question.QuestionType = GetQuestionType(Question.QuestionTypeId); questionDbContext.QuestionCategories.Add(dbQuestionCategory); questionDbContext.SaveChanges(); - QuestionCategory.Id=dbQuestionCategory.Id; - return (true, QuestionCategory, null); + QuestionCategory.Id = dbQuestionCategory.Id; + dbCategorytranslations.ForEach(i => i.CategoryId = QuestionCategory.Id); + questionDbContext.CategoryTranslations.AddRange(dbCategorytranslations); + questionDbContext.SaveChanges(); + var result = mapper.Map(dbQuestionCategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -290,15 +370,23 @@ namespace DamageAssesment.Api.Questions.Providers 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 { var dbQuestionCategory = mapper.Map(QuestionCategory); + var dbCategorytranslations = mapper.Map, List>(QuestionCategory.Categories); 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(); - return (true, QuestionCategory, null); + var result = mapper.Map(dbQuestionCategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -307,18 +395,20 @@ namespace DamageAssesment.Api.Questions.Providers 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 { var questioncategory = await questionDbContext.QuestionCategories.Where(x => x.Id == Id).FirstOrDefaultAsync(); if (questioncategory != null) { + var result = mapper.Map(questioncategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); var question = await questionDbContext.Questions.Where(x => x.Id == Id).ToListAsync(); questionDbContext.Questions.RemoveRange(question); questionDbContext.QuestionCategories.Remove(questioncategory); questionDbContext.SaveChanges(); - return (true, mapper.Map(questioncategory), $"QuestionID {Id} deleted Successfuly"); + return (true, result, $"QuestionID {Id} deleted Successfuly"); } else { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json index 2139fc2..8c0132f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs index cf0bb04..e09a7c0 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs @@ -8,42 +8,42 @@ namespace DamageAssesment.Api.Questions.Test { public class CategoryMockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); 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); } - 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 Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); 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"); } - 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"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task 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" }; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs index f9c0c87..8b13b70 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs @@ -1,24 +1,17 @@ -using DamageAssesment.Api.Questions.Db; -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text; namespace DamageAssesment.Api.Questions.Test { public class MockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); 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, QuestionGroup = "group1",CategoryId=i }); + list.Append(new Questions.Models.MultiLanguage { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); } return (true, list, null); } @@ -30,38 +23,38 @@ namespace DamageAssesment.Api.Questions.Test for (int i = 0; i < 10; i++) { - List question = new List(); - question.Add(new Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = i }); + List question = new List(); + question.Add(new Models.MultiLanguage { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); list.Append(new Questions.Models.SurveyQuestions { CategoryId = i, - CategoryImage = "img" + i, - CategoryName = "Category " + i, - Questions = question + IconLibrary = "img" + i, + IconName = "Category " + i, + QuestionsText = question }); } return (true, list, null); } - public static async Task<(bool, Questions.Models.Question, string)> getOkResponse(int Id) + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getOkResponse(int Id) { var Questions = await getOkResponse(); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); return (true, Question, null); } - public static async Task<(bool, Questions.Models.Question, string)> getBadRequestResponse() + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getBadRequestResponse() { return (false, null, "Bad Request"); } - public static async Task<(bool, Questions.Models.Question, string)> getNotFoundResponse() + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task<(bool, List, string)> getNoSurveyContentResponse() @@ -79,7 +72,7 @@ namespace DamageAssesment.Api.Questions.Test }; List QuestionsTranslations = new List(); QuestionsTranslations.Add(QuestionsTranslation); - return new Questions.Models.Question { Id = 1, Questions=QuestionsTranslations, TypeText = "Text 1", SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1" ,CategoryId=1}; + return new Questions.Models.Question { Id = 1, Questions=QuestionsTranslations, TypeText = "Text 1", SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=1}; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs index b21fa9c..bda9db2 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs @@ -1,16 +1,7 @@ - -using AutoMapper; using DamageAssesment.Api.Questions.Controllers; -using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; -using DamageAssesment.Api.Questions.Models; -using DamageAssesment.Api.Questions.Profiles; -using DamageAssesment.Api.Questions.Providers; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Moq; -using Newtonsoft.Json; using Xunit; namespace DamageAssesment.Api.Questions.Test @@ -22,10 +13,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getOkResponse(); - mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync(); + var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync(null); Assert.Equal(200, result.StatusCode); } @@ -35,10 +26,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync(); + var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync(null); Assert.Equal(204, result.StatusCode); } @@ -48,10 +39,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getOkResponse(1); - mockQuestionService.Setup(service => service.GetQuestionAsync(1)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1); + var result = (OkObjectResult)await QuestionProvider.GetQuestionByIdAsync(1,null); Assert.Equal(200, result.StatusCode); } @@ -61,10 +52,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockQuestionService.Setup(service => service.GetQuestionAsync(99)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99); + var result = (NotFoundResult)await QuestionProvider.GetQuestionByIdAsync(99,null); Assert.Equal(404, result.StatusCode); } @@ -197,10 +188,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); 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 result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync(); + var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync("en"); Assert.Equal(200, result.StatusCode); } @@ -210,10 +201,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); 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 result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync(); + var result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync("en"); Assert.Equal(204, result.StatusCode); } @@ -223,10 +214,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); 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 result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1); + var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1, "en"); Assert.Equal(200, result.StatusCode); } @@ -236,10 +227,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); 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 result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99); + var result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99, "en"); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs index 42b29dc..e5f3917 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Configuration; namespace DamageAssesment.Api.SurveyResponses.Controllers { - [Route("api")] [ApiController] public class SurveyResponsesController : ControllerBase { @@ -16,8 +15,11 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers { this.surveyResponseProvider = surveyResponseProvider; } + /// + /// GET request for retrieving survey responses. + /// - [HttpGet("SurveyResponses")] + [HttpGet("Responses")] public async Task GetSurveyResponsesAsync() { var result = await this.surveyResponseProvider.GetSurveyResponsesAsync(); @@ -31,22 +33,30 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return BadRequest(result.ErrorMessage); } - - [HttpGet("SurveyResponses/{surveyId}")] - public async Task GetSurveyResponsesAsync(int surveyId) + /// + /// GET request for retrieving survey responses by survey ID. + /// + + [HttpGet("Responses/BySurvey/{surveyid}")] + public async Task GetSurveyResponsesAsync(int surveyid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAsync(surveyId); + var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAsync(surveyid); if (result.IsSuccess) { return Ok(result.SurveyResponses); } return NoContent(); } + /// + /// GET request for retrieving survey responses by survey and location IDs. + /// + /// The ID of the survey for which responses are to be retrieved. + /// The ID of the location for which responses are to be retrieved. - [HttpGet("Responses/{surveyId}/{locationId}")] - public async Task GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId) + [HttpGet("Responses/{surveyid}/{locationid}")] + public async Task GetSurveyResponsesBySurveyAndLocationAsync(int surveyid, int locationid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(surveyId, locationId); + var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(surveyid, locationid); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -54,11 +64,17 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// GET request for retrieving survey responses by survey, question, and answer. + /// + /// The ID of the survey for which responses are to be retrieved. + /// The ID of the question for which responses are to be retrieved. + /// The answer for which responses are to be retrieved. - [HttpGet("ResponsesByAnswer/{surveyId}/{questionId}/{answer}")] - public async Task GetSurveyResponsesByAnswerAsyncAsync(int surveyId, int questionId, string answer) + [HttpGet("Responses/ByAnswer/{surveyid}/{questionid}/{answer}")] + public async Task GetSurveyResponsesByAnswerAsyncAsync(int surveyid, int questionid, string answer) { - var result = await surveyResponseProvider.GetResponsesByAnswerAsync(surveyId, questionId, answer); + var result = await surveyResponseProvider.GetResponsesByAnswerAsync(surveyid, questionid, answer); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -66,33 +82,45 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// GET request for retrieving answers from survey responses by survey ID and region. + /// + /// The ID of the survey for which answers are to be retrieved. - [HttpGet("AnswersByRegion/{surveyId}")] - public async Task GetAnswersByRegionAsync(int surveyId) + [HttpGet("Responses/ByRegion/{surveyid}")] + public async Task GetAnswersByRegionAsync(int surveyid) { - var result = await this.surveyResponseProvider.GetAnswersByRegionAsync(surveyId); + var result = await this.surveyResponseProvider.GetAnswersByRegionAsync(surveyid); if (result.IsSuccess) { return Ok(result.Answers); } return NoContent(); } + /// + /// GET request for retrieving survey responses by survey ID and maintenance center. + /// + /// The ID of the survey for which responses are to be retrieved. - [HttpGet("AnswersByMaintenanceCenter/{surveyId}")] - public async Task GetAnswersByMaintenaceCentersync(int surveyId) + [HttpGet("Responses/ByMaintenanceCenter/{surveyid}")] + public async Task GetAnswersByMaintenaceCentersync(int surveyid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesByMaintenanceCenterAsync(surveyId); + var result = await this.surveyResponseProvider.GetSurveyResponsesByMaintenanceCenterAsync(surveyid); if (result.IsSuccess) { return Ok(result.SurveyResponses); } return NoContent(); } + /// + /// GET request for retrieving a survey response by response ID. + /// + /// The ID of the survey response to be retrieved. - [HttpGet("SurveyResponse/{responseId}")] - public async Task GetSurveyResponseByIdAsync(int responseId) + [HttpGet("Responses/{id}")] + public async Task GetSurveyResponseByIdAsync(int id) { - var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(responseId); + var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(id); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -100,8 +128,12 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// POST request for creating a new survey response. + /// + /// The survey response object to be created. - [HttpPost("SurveyResponses")] + [HttpPost("Responses")] public async Task PostSurveysAsync(Models.SurveyResponse surveyResponse) { var result = await this.surveyResponseProvider.PostSurveyResponseAsync(surveyResponse); @@ -111,11 +143,16 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing survey response. + /// + /// The ID of the survey response to be updated. + /// The updated survey response object. - [HttpPut("SurveyResponses/{Id}")] - public async Task PutSurveyResponseAsync(int Id, Models.SurveyResponse surveyResponse) + [HttpPut("Responses/{id}")] + public async Task PutSurveyResponseAsync(int id, Models.SurveyResponse surveyResponse) { - var result = await this.surveyResponseProvider.PutSurveyResponseAsync(Id, surveyResponse); + var result = await this.surveyResponseProvider.PutSurveyResponseAsync(id, surveyResponse); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -125,28 +162,29 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return BadRequest(result.ErrorMessage); } - - [HttpDelete("SurveyResponses/{Id}")] - public async Task DeleteSurveyResponseAsync(int Id) + /// + /// DELETE request for deleting an existing survey response. + /// + + [HttpDelete("Responses/{id}")] + public async Task DeleteSurveyResponseAsync(int id) { - var result = await this.surveyResponseProvider.DeleteSurveyResponseAsync(Id); + var result = await this.surveyResponseProvider.DeleteSurveyResponseAsync(id); if (result.IsSuccess) { return Ok(result.SurveyResponse); } return NotFound(); } + /// + /// POST request for submitting survey with multiple answers. + /// + /// The answers to be submitted for the survey. - [HttpPost("SurveyResponses/Answers")] - public async Task PostSurveyAnswersAsync(AnswerRequest answers) + [HttpPost("Responses/Answers")] + public async Task PostSurveyAnswersAsync(Request request) { - /* var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(surveyAnswers); - if (result.IsSuccess) - { - return Ok(result.SurveyResponse); - } - return BadRequest(result.ErrorMessage);*/ - var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(answers); + var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(request); if (result.IsSuccess) return Ok(result.SurveyResponse); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj index 303332f..d588d40 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True @@ -21,6 +22,10 @@ + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs index c1e5db1..2169097 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs @@ -10,21 +10,22 @@ namespace DamageAssesment.Api.SurveyResponses.Db [ForeignKey("Survey")] public int SurveyId { get; set; } - - [StringLength(4)] [ForeignKey("Location")] - public string LocationId { get; set; } + public int LocationId { get; set; } [StringLength(6)] [ForeignKey("Employee")] - public string EmployeeId { get; set; } + public int EmployeeId { get; set; } - //public DateTime? CreatedDate { get; set; } + public DateTime? CreatedDate { get; set; } = DateTime.Now; - //[StringLength(50)] - // public string ClientDevice { get; set; } + [StringLength(50)] + public string? ClientDevice { get; set; } + + [StringLength(250)] + public string? KeyAnswerResult { get; set; } + public double? Longitute { get; set; } + public double? Latitude { get; set; } - // [StringLength(250)] - //public string KeyAnswerResult { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs index 1ac41f6..8520066 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs @@ -15,5 +15,13 @@ namespace DamageAssesment.Api.SurveyResponses.Db options.UseSqlServer(_Configuration.GetConnectionString("SurveyResponseConnection")); } public DbSet SurveyResponses { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs index a402c30..62031d5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs @@ -5,6 +5,6 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces public interface IEmployeeServiceProvider { Task> getEmployeesAsync(); - Task getEmployeeAsync(string employeeID); + Task getEmployeeAsync(int employeeId); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs new file mode 100644 index 0000000..e3f1e66 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs @@ -0,0 +1,9 @@ +using DamageAssesment.Api.SurveyResponses.Models; + +namespace DamageAssesment.Api.SurveyResponses.Interfaces +{ + public interface IHttpUtil + { + Task SendAsync(HttpMethod method, string url, string JsonInput); + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs index 79ca1ad..536353c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs @@ -13,11 +13,11 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> DeleteSurveyResponseAsync(int Id); Task<(bool IsSuccess, dynamic SurveyResponse, string ErrorMessage)> GetSurveyResponseByIdAsync(int responseId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAsync(int surveyId); - Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string location); + Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, int locationId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesByMaintenanceCenterAsync(int surveyId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetResponsesByAnswerAsync(int surveyId, int questionId, string answer); - Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers); + Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Request request); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs deleted file mode 100644 index d728e1d..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AggregateAnswer - { - public string? Answer { get; set; } - public int Counter { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs deleted file mode 100644 index ef8d174..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AggregateResult - { - public string RegionId { get; set; } - public AggregateAnswer Answers { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs index cab6f5b..d607a2f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs @@ -6,11 +6,11 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public int Id { get; set; } public int QuestionId { get; set; } - public string? LocationId { get; set; } + public int LocationId { get; set; } public string AnswerText { get; set; } - public string? Comment { get; set; } + public string Comment { get; set; } public int SurveyResponseId { get; set; } - public string? RegionId { get; set; } + public int RegionId { get; set; } // public string? Name { get; set; } // public string? Abbreviation { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs deleted file mode 100644 index cee0699..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AnswerData - { - public string RegionId { get; set; } - public string Name { get; set; } - public string Abbreviation { get; set; } - public List Answers { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs index 68a217a..3d86488 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs @@ -2,9 +2,9 @@ { public class AnswerRequest { - public int SurveyId { get; set; } - public string LocationId { get; set; } - public string EmployeeId { get; set; } - public List Answers { get; set; } + public int QuestionId { get; set; } + public string AnswerText { get; set; } + public string Comment { get; set; } + public List PostedFiles { get; set; } = new List(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs index c1fb576..9a06020 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs @@ -4,18 +4,13 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Employee { - public string Id { get; set; } - - [StringLength(50)] + public int Id { get; set; } + public string EmployeeCode { get; set; } public string Name { get; set; } - public DateTime BirthDate { get; set; } - - [StringLength(50)] public string OfficePhoneNumber { get; set; } - - [StringLength(50)] public string Email { get; set; } public bool IsActive { get; set; } + public string? PreferredLanguage { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs index 4c7f846..078a5ef 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs @@ -2,8 +2,8 @@ { public class Location { - public string Id { get; set; } - public string RegionId { get; set; } + public int Id { get; set; } + public int RegionId { get; set; } public string Name { get; set; } public string MaintenanceCenter { get; set; } public string SchoolType { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs index 5dba504..37abb4b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs @@ -1,24 +1,17 @@ -using System.ComponentModel.DataAnnotations; +using System.Collections.Generic; namespace DamageAssesment.Api.SurveyResponses.Models { - public class Question + public class Question { public int Id { get; set; } - public List Questions { get; set; } - - //public int QuestionTypeID { get; set; } - - public string TypeText { get; set; } = string.Empty; - + public string TypeText { get; set; } public int QuestionNumber { get; set; } public bool IsRequired { get; set; } public bool Comment { get; set; } - public bool Key { get; set; } - public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } + public int SurveyId { get; set; } public int CategoryId { get; set; } - // public int? Survey_SurveyID { get; set; } + public Dictionary Text { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs deleted file mode 100644 index d0930ab..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class QuestionRequest - { - public int QuestionId { get; set; } - public string AnswerText { get; set; } - public string Comment { get; set; } - public List PostedFiles { get; set; } = new List(); - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs deleted file mode 100644 index e347a5c..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class QuestionsTranslation - { - public string QuestionText { get; set; } - public string Language { get; set; } = "En"; - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs index b1941d2..3fc5ad7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs @@ -4,7 +4,7 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Region { - public string Id { get; set; } + public int Id { get; set; } public string Name { get; set; } public string Abbreviation { get; set; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs new file mode 100644 index 0000000..5060914 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs @@ -0,0 +1,15 @@ +namespace DamageAssesment.Api.SurveyResponses.Models +{ + public class Request + { + public int SurveyId { get; set; } + public int LocationId { get; set; } + public int EmployeeId { get; set; } + public string? ClientDevice { get; set; } + public string? KeyAnswerResult { get; set; } + public double? Longitute { get; set; } + public double? Latitude { get; set; } + public DateTime? CreatedDate { get; set; } = DateTime.Now; + public List Answers { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs deleted file mode 100644 index 4df1631..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class ResultData - { - public List Regions { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs index 04b60e5..b47193e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs @@ -4,25 +4,11 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Survey { - [Key] public int Id { get; set; } - - [StringLength(100)] - public string Title { get; set; } - - //[StringLength(1000)] - //public string Description { get; set; } - public bool IsEnabled { get; set; } - - public DateTime? StartDate { get; set; } - - public DateTime? EndDate { get; set; } - - //public DateTime CreatedDate { get; set; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } - + public DateTime StartDate { get; set; } + public DateTime EndDate { get; set; } + public DateTime CreatedDate { get; set; } + public Dictionary Titles { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs index 12ed615..37862ca 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs @@ -5,24 +5,14 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class SurveyResponse { - [Key] public int Id { get; set; } - - [ForeignKey("Survey")] public int SurveyId { get; set; } - - [ForeignKey("Location")] - public string LocationId { get; set; } - - [ForeignKey("Employee")] - public string EmployeeId { get; set; } - - //public DateTime? CreatedDate { get; set; } - - //[StringLength(50)] - //public string ClientDevice { get; set; } - - //[StringLength(250)] - //public string KeyAnswerResult { get; set; } + public int LocationId { get; set; } + public int EmployeeId { get; set; } + public DateTime CreatedDate { get; set; } + public string ClientDevice { get; set; } + public string KeyAnswerResult { get; set; } + public double Longitute { get; set; } + public double Latitude { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs new file mode 100644 index 0000000..29a1b7c --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs @@ -0,0 +1,13 @@ +namespace DamageAssesment.Api.SurveyResponses.Models +{ + public class SurveyTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs index aa06647..985f3ac 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs @@ -1,9 +1,10 @@ using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Services; using DamageAssesment.Api.SurveyResponses.Providers; -using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.EntityFrameworkCore; using Polly; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); const int maxApiCallRetries = 3; @@ -18,39 +19,29 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddScoped(); -//builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker) )); - -builder.Services.AddHttpClient(). +builder.Services.AddHttpClient(). AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseSqlServer("SurveyResponseConnection"); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs deleted file mode 100644 index 5796eff..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs +++ /dev/null @@ -1,87 +0,0 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Db; -using DamageAssesment.Api.SurveyResponses.Interfaces; -using DamageAssesment.Api.SurveyResponses.Models; -using Newtonsoft.Json; -using System.Data.Common; -using System.Security.Cryptography; -using System.Text.Json.Nodes; -using System.Text; - -namespace DamageAssesment.Api.SurveyResponses.Providers -{ - public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider - { - - public AnswerServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider) : base(configuration, httpClient, logger, "/api/Answers", configuration.GetValue("EndPointSettings:AnswerUrlBase")) - { - } - public async Task> getAnswersAsync() - { - try - { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject>(responseString); - - if (answers == null || !answers.Any()) - return null; - else return answers; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()"); - return null; - } - } - - public async Task> GetAnswersByResponseIdAsync(int responseId) - { - try - { - httpClient.BaseAddress = new Uri(urlBase); - - var response = await httpClient.GetAsync("/api/AnswersByResponse/"+ responseId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject>(responseString); - - if (answers == null || !answers.Any()) - return null; - else return answers; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()"); - return null; - } - } - - public async Task PostAnswersAsync(Answer answer) - { - try - { - httpClient.BaseAddress = new Uri(urlBase); - var jsonObject = JsonConvert.SerializeObject(answer); - var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.PostAsync(ressource,content); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject(responseString); - - if (answers == null) { - logger?.LogError($"Answer cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()"); - return null; - } - else return answers; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.PostAnswersAsync()"); - return null; - } - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs deleted file mode 100644 index faf31ff..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs +++ /dev/null @@ -1,58 +0,0 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; -using DamageAssesment.Api.SurveyResponses.Models; -using Newtonsoft.Json; -using System.Reflection; - -namespace DamageAssesment.Api.SurveyResponses.Providers -{ - public class EmployeeServiceProvider :ServiceProviderBase, IEmployeeServiceProvider - { - public EmployeeServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Employees", configuration.GetValue("EndPointSettings:EmployeeUrlBase")) - { - } - - public async Task> getEmployeesAsync() - { - try - { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var employees = JsonConvert.DeserializeObject>(responseString); - - if (employees == null || !employees.Any()) - return null; - else return employees; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeesAsync()"); - return null; - } - } - - public async Task getEmployeeAsync(string employeeID) - { - try - { - httpClient.BaseAddress = new Uri(urlBase); - //ressource = ressource + "/" + employeeID; - var response = await httpClient.GetAsync("/api/Employees/"+ employeeID); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var employee = JsonConvert.DeserializeObject(responseString); - - if (employee == null ) - return null; - else return employee; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeeAsync()"); - return null; - } - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs index bcc7338..a824a96 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs @@ -3,9 +3,6 @@ using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Internal; -using System.Diagnostics; -using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace DamageAssesment.Api.SurveyResponses.Providers { @@ -34,21 +31,20 @@ namespace DamageAssesment.Api.SurveyResponses.Providers this.questionServiceProvider = questionServiceProvider; this.surveyServiceProvider = surveyServiceProvider; this.mapper = mapper; - - seedData(); + // seedData(); } private void seedData() { if (!surveyResponseDbContext.SurveyResponses.Any()) { - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = "Emp1", LocationId = "Loc1" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = "Emp2", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 3, EmployeeId = "Emp4", LocationId = "Loc1" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 4, EmployeeId = "Emp1", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = "Emp3", LocationId = "Loc3" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc3" }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = 1, LocationId = 1 }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = 2, LocationId = 1 }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 3, EmployeeId = 3, LocationId = 2 }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 4, EmployeeId = 4, LocationId = 2 }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = 5, LocationId = 3}); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = 4, LocationId = 2 }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { SurveyId = 1, EmployeeId = 3, LocationId = 1 }); surveyResponseDbContext.SaveChanges(); } } @@ -141,7 +137,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } } - public async Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId) + public async Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, int locationId) { try { @@ -212,7 +208,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers var question = await questionServiceProvider.getQuestionsAsync(questionId); bool IsCorrectAnswer = answer.ToLower().Equals("yes") || answer.ToLower().Equals("no") ? true : false; - + if (survey != null && question != null && IsCorrectAnswer) { var answers = await getSurveyResponsesByAnswerAsync(survey, question, answer); @@ -228,7 +224,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers else { return (false, null, "Not found"); - } + } } catch (Exception ex) { @@ -251,7 +247,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers answers = new List(); return (true, answers, "Empty object returned"); } - } catch (Exception ex) { @@ -266,16 +261,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (surveyResponse != null) { - var surveyResponses = await surveyResponseDbContext.SurveyResponses.ToListAsync(); - surveyResponse.Id = surveyResponses.Count + 1; - surveyResponseDbContext.SurveyResponses.Add(mapper.Map(surveyResponse)); - surveyResponseDbContext.SaveChanges(); + var _surveyResponse = mapper.Map(surveyResponse); + surveyResponseDbContext.SurveyResponses.Add(_surveyResponse); + await surveyResponseDbContext.SaveChangesAsync(); + surveyResponse.Id = _surveyResponse.Id; return (true, surveyResponse, "Request Successful"); } else { - logger?.LogInformation($"SurveyResponseID={surveyResponse.Id} cannot be added"); - return (false, null, "Survey cannot be added"); + logger?.LogInformation($"SurveyResponse cannot be added"); + return (false, null, "SurveyResponse cannot be added"); } } catch (Exception ex) @@ -292,15 +287,14 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (SurveyResponse != null) { - var _SurveyResponse = await surveyResponseDbContext.SurveyResponses.Where(s => s.Id == Id).FirstOrDefaultAsync(); + var _SurveyResponse = await surveyResponseDbContext.SurveyResponses.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_SurveyResponse != null) { - _SurveyResponse.SurveyId = SurveyResponse.SurveyId; - _SurveyResponse.EmployeeId = SurveyResponse.EmployeeId; - _SurveyResponse.LocationId = SurveyResponse.LocationId; - surveyResponseDbContext.SaveChanges(); - return (true, mapper.Map(_SurveyResponse), "Successful"); + var response = mapper.Map(SurveyResponse); + surveyResponseDbContext.Update(response); + await surveyResponseDbContext.SaveChangesAsync(); + return (true, SurveyResponse, "Successful"); } else { @@ -331,7 +325,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers if (_SurveyResponse != null) { surveyResponseDbContext.Remove(_SurveyResponse); - surveyResponseDbContext.SaveChanges(); + await surveyResponseDbContext.SaveChangesAsync(); return (true, mapper.Map(_SurveyResponse), "Successful"); } else @@ -339,7 +333,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers logger?.LogInformation($"SurveyReponseId = {Id} Not found"); return (false, null, "Not Found"); } - } catch (Exception ex) { @@ -363,13 +356,13 @@ namespace DamageAssesment.Api.SurveyResponses.Providers answer => answer.SurveyResponseId, surveyResponse => surveyResponse.Id, (answer, surveyResponse) => new - Answer + { - Id = answer.Id, - QuestionId = answer.QuestionId, - AnswerText = answer.AnswerText, - Comment = answer.Comment, - LocationId = surveyResponse.LocationId, + answer.Id, + answer.QuestionId, + answer.AnswerText, + answer.Comment, + surveyResponse.LocationId, SurveyResponseId = surveyResponse.Id }); @@ -386,41 +379,46 @@ namespace DamageAssesment.Api.SurveyResponses.Providers //get all the answers based on the locations var result = from answer in surveyAnswers from location in locations - where answer.LocationId == location.Id - select new Answer + where answer.LocationId.Equals(location.Id) + select new { - Id = answer.Id, - QuestionId = answer.QuestionId, - AnswerText = answer.AnswerText, - Comment = answer.Comment, - RegionId = location.RegionId, - LocationId = location.Id, - SurveyResponseId = answer.SurveyResponseId + answer.Id, + answer.QuestionId, + answer.AnswerText, + answer.Comment, + location.RegionId, + LocationId = location.Id, + answer.SurveyResponseId }; + + //group records by answer and region var q = from e in result group e by (e.RegionId, e.AnswerText) into g - select new AggregateResult + select new { - RegionId = g.Key.RegionId, - Answers = new AggregateAnswer + g.Key.RegionId, + Answers = new { - Answer = g.Key.AnswerText, + g.Key.AnswerText, Counter = g.Count() } }; - + //build the result - List resultList = new List(); + + List resultList = new List(); foreach (Region region in regions) { - var answers = q.Where(x => x.RegionId.Equals(region.Id)).Select(x => x.Answers).ToList(); - resultList.Add(new AnswerData { RegionId = region.Id, Name = region.Name, Abbreviation = region.Abbreviation, Answers = answers }); + var answers = from u in q.ToList() + where u.RegionId.Equals(region.Id) + select u.Answers; + + resultList.Add(new { RegionId = region.Id, region.Name, region.Abbreviation, Answers = answers}); } - //return the object result - return new ResultData { Regions = resultList }; + return new { Regions = resultList }; } catch (Exception ex) { @@ -434,35 +432,35 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - var surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.Id == surveyResponse.Id).ToListAsync(); - //var surveyResponse = surveyResonses.SingleOrDefault(); var employee = await employeeServiceProvider.getEmployeeAsync(surveyResponse.EmployeeId); var answers = await answerServiceProvider.GetAnswersByResponseIdAsync(surveyResponse.Id); var allQuestions = await questionServiceProvider.getQuestionsAsync(); - var questions = allQuestions.Where(s=> s.SurveyId == surveyResponse.Id); + var questions = allQuestions.Where(s => s.SurveyId == surveyResponse.SurveyId); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); - - var result = from r in surveyResonses - select new - { - r.Id, - r.SurveyId, - r.LocationId, - r.EmployeeId, - Employee = employee, - answers = from ans in answers - select new - { - ans.QuestionId, - ans.Id, - ans.AnswerText, - ans.Comment, - Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), - Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } - } - }; - return result.SingleOrDefault(); + var result = new + { + surveyResponse.Id, + surveyResponse.SurveyId, + surveyResponse.LocationId, + surveyResponse.EmployeeId, + surveyResponse.ClientDevice, + surveyResponse.KeyAnswerResult, + surveyResponse.Longitute, + surveyResponse.Latitude, + Employee = employee, + answers = from ans in answers + select new + { + ans.QuestionId, + ans.Id, + ans.AnswerText, + ans.Comment, + Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), + Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } + } + }; + return result; } catch (Exception ex) { @@ -494,6 +492,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -503,7 +505,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } @@ -537,6 +539,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -546,7 +552,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, ans.AnswerText, ans.Comment, - Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } }; @@ -587,7 +593,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers //get all the answers with location var surveyAnswersLocations = from surveyAns in surveyAnswers from location in locations - where surveyAns.LocationId == location.Id + where surveyAns.LocationId.Equals(location.Id) select new { surveyAns, location.MaintenanceCenter }; //aggreting the answers @@ -596,9 +602,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers select new { g.Key.MaintenanceCenter, - Answers = new AggregateAnswer + Answers = new { - Answer = g.Key.AnswerText, + g.Key.AnswerText, Counter = g.Count() } }; @@ -621,7 +627,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } //Method to get Survey Responses by surveyId and LocationId - private async Task getSurveyResponsesBySurveyIdLocationIdAsync(int surveyId, string locationId) + private async Task getSurveyResponsesBySurveyIdLocationIdAsync(int surveyId, int locationId) { try { @@ -640,6 +646,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -650,7 +660,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.Id, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } }; @@ -670,8 +680,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers try { var surveyResponses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == survey.Id).ToListAsync(); - //var questions = await questionServiceProvider.getQuestionsAsync(); - var answers = await answerServiceProvider.getAnswersAsync(); var employees = await employeeServiceProvider.getEmployeesAsync(); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); @@ -683,6 +691,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -709,66 +721,49 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } - async Task ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId) + async Task ProcessAnswers(AnswerRequest answerRequest, int surveyResponseId) { - if (questionRequest != null) + if (answerRequest != null) { - var answer = await answerServiceProvider.PostAnswersAsync(new Answer { Id = 0, QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId }); + var answer = await answerServiceProvider.PostAnswersAsync(new Models.Answer { QuestionId = answerRequest.QuestionId, AnswerText = answerRequest.AnswerText, Comment = answerRequest.Comment, SurveyResponseId = surveyResponseId }); if (answer != null) { List listAnswerInfo = new List(); - listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = questionRequest.PostedFiles }); - var attachments = await attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); + listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = answerRequest.PostedFiles }); + var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); - string message = $"Answer for question {questionRequest.QuestionId} saved to the database"; + string message = $"Answer for question {answerRequest.QuestionId} saved to the database"; logger?.LogInformation(message); return (true); } else { - string message = $"Answer for question {questionRequest.QuestionId} cannot be saved to the database"; + string message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database"; logger?.LogInformation(message); return (false); } } else { - var message = $"Answer for question {questionRequest.QuestionId} cannot be saved to the database - questionRequest object is null"; + var message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database - answerRequest object is null"; logger?.LogInformation(message); return (false); } } - public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers) + public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.Request request) { try { - if (answers != null) + if (request != null) { - var response = await PostSurveyResponseAsync(new Models.SurveyResponse { Id = 0, SurveyId = answers.SurveyId, EmployeeId = answers.EmployeeId, LocationId = answers.LocationId }); - + var response = await PostSurveyResponseAsync(new Models.SurveyResponse { SurveyId = request.SurveyId, EmployeeId = request.EmployeeId, LocationId = request.LocationId, ClientDevice = request.ClientDevice, KeyAnswerResult = request.KeyAnswerResult, Latitude = Convert.ToDouble(request.Latitude), Longitute = Convert.ToDouble(request.Longitute), CreatedDate=DateTime.Now }); if (response.IsSuccess) { var surveyResponse = response.SurveyResponse; - - var answerTasks = new List(); //new List(); - - //var tasks = answers.Answers.Select(x => ProcessAnswers(x,surveyResponse.SurveyResponseID)); - foreach (QuestionRequest ans in answers.Answers) - { - //var stopwatch = new Stopwatch(); - //stopwatch.Start(); - var task = Task.Run(() => ProcessAnswers(ans, surveyResponse.Id)); - - //var task = await ProcessAnswers(ans, surveyResponse.Id); - answerTasks.Add(task); - - - //stopwatch.Stop(); - //answerTasks.Add(ProcessAnswers(ans, surveyResponse.Id)); - } - await Task.WhenAll(answerTasks); + var tasks = request.Answers.Select(x => ProcessAnswers(x, surveyResponse.Id)); + await Task.WhenAll(tasks); return (true, surveyResponse, null); } else diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs new file mode 100644 index 0000000..695ad3e --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs @@ -0,0 +1,72 @@ +using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Models; +using Newtonsoft.Json; + + +namespace DamageAssesment.Api.SurveyResponses.Services +{ + public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider + { + public AnswerServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Answer"), configuration.GetValue("EndPointSettings:AnswerUrlBase")) + { + } + public async Task> getAnswersAsync() + { + try + { + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var answers = JsonConvert.DeserializeObject>(responseJsonString); + + if (answers == null || !answers.Any()) + return new List(); + else return answers; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()"); + return new List(); + } + } + + public async Task> GetAnswersByResponseIdAsync(int responseId) + { + try + { + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:AnswerByResponse"), responseId); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var answers = JsonConvert.DeserializeObject>(responseJsonString); + + if (answers == null || !answers.Any()) + return new List(); + else return answers; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()"); + return new List(); + } + } + + public async Task PostAnswersAsync(Answer answer) + { + try + { + var requestJsonString = JsonConvert.SerializeObject(answer); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); + var answers = JsonConvert.DeserializeObject(responseJsonString); + + if (answers == null) + { + logger?.LogError($"Answers cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()"); + return null; + } + else return answers; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.PostAnswersAsync()"); + return null; + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs similarity index 52% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs index 3e46c84..120e60f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs @@ -1,17 +1,12 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; -using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using System.Net.Http; -using System.Runtime.Intrinsics.Arm; -using System.Text; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class AttachmentServiceProvider : ServiceProviderBase, IAttachmentServiceProvider { - public AttachmentServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Attachments", configuration.GetValue("EndPointSettings:AttachmentUrlBase")) + public AttachmentServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Attachment"), configuration.GetValue("EndPointSettings:AttachmentUrlBase")) { } @@ -19,20 +14,17 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var attachments = JsonConvert.DeserializeObject>(responseString); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var attachments = JsonConvert.DeserializeObject>(responseJsonString); if (attachments == null || !attachments.Any()) - return null; + return new List(); else return attachments; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AttachmentServiceProvider.getAttachmentsAsync()"); - return null; + return new List(); } } @@ -40,13 +32,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var jsonObject = JsonConvert.SerializeObject(attachmentInfo); - var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.PostAsync(ressource, content); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var attachments = JsonConvert.DeserializeObject>(responseString); + var requestJsonString = JsonConvert.SerializeObject(attachmentInfo); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); + var attachments = JsonConvert.DeserializeObject>(responseJsonString); if (attachments == null) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs new file mode 100644 index 0000000..8dd1352 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs @@ -0,0 +1,51 @@ +using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Models; +using Microsoft.AspNetCore.Mvc.Routing; +using Newtonsoft.Json; + +namespace DamageAssesment.Api.SurveyResponses.Services +{ + public class EmployeeServiceProvider : ServiceProviderBase, IEmployeeServiceProvider + { + public EmployeeServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Employee"), configuration.GetValue("EndPointSettings:EmployeeUrlBase")) + { + } + + public async Task> getEmployeesAsync() + { + try + { + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var employees = JsonConvert.DeserializeObject>(responseJsonString); + + if (employees == null || !employees.Any()) + return new List(); + else return employees; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeesAsync()"); + return new List(); + } + } + + public async Task getEmployeeAsync(int employeeId) + { + try + { + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:EmployeeById"), employeeId); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var employee = JsonConvert.DeserializeObject(responseJsonString); + + if (employee == null) + return null; + else return employee; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeeAsync()"); + return null; + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs new file mode 100644 index 0000000..8b4755d --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs @@ -0,0 +1,43 @@ +using DamageAssesment.Api.SurveyResponses.Interfaces; +using System.Net.Http.Headers; +using System.Text; + +namespace DamageAssesment.Api.SurveyResponses.Services +{ + public class HttpUtil : IHttpUtil + { + private readonly HttpClient httpClient; + private readonly ILogger logger; + + public HttpUtil(HttpClient httpClient, ILogger logger) + { + this.httpClient = httpClient; + this.logger = logger; + } + public async Task SendAsync(HttpMethod method, string url, string JsonInput) + { + try + { + var request = new HttpRequestMessage(method, url); + request.Headers.Accept.Clear(); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + if (method == HttpMethod.Post) + { + request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json"); + } + + var response = await httpClient.SendAsync(request, CancellationToken.None); + response.EnsureSuccessStatusCode(); + var responseString = await response.Content.ReadAsStringAsync(); + return responseString; + } + catch (Exception ex) + { + logger?.LogError($"Exception Message : {ex.Message} - Ref: HttpUtil.SendAsync()"); + return null; + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs similarity index 50% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs index d5c9161..2e3fa32 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs @@ -1,13 +1,12 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class LocationServiceProvider :ServiceProviderBase, ILocationServiceProvider { - public LocationServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Locations", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public LocationServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Location"), configuration.GetValue("EndPointSettings:LocationUrlBase")) { } @@ -15,20 +14,17 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var locations = JsonConvert.DeserializeObject>(responseString); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var locations = JsonConvert.DeserializeObject>(responseJsonString); if (locations == null || !locations.Any()) - return null; + return new List(); else return locations; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: LocationServiceProvider.getLocationsAsync()"); - return null; + return new List(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs similarity index 55% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs index 2d9e915..138011f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs @@ -1,15 +1,12 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; - - -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class QuestionServiceProvider : ServiceProviderBase, IQuestionServiceProvider { - public QuestionServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Questions", configuration.GetValue("EndPointSettings:QuestionUrlBase")) + public QuestionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Question"), configuration.GetValue("EndPointSettings:QuestionUrlBase")) { } @@ -17,20 +14,17 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var questions = JsonConvert.DeserializeObject>(responseString); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var questions = JsonConvert.DeserializeObject>(responseJsonString); if (questions == null || !questions.Any()) - return null; + return new List(); else return questions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: QuestionServiceProvider.getQuestionsAsync()"); - return null; + return new List(); } } @@ -38,20 +32,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync("/api/GetSurveyQuestions/" + surveyId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var questions = JsonConvert.DeserializeObject>(responseString); + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:SurveyQuestion"), surveyId); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var questions = JsonConvert.DeserializeObject>(responseJsonString); if (questions == null || !questions.Any()) - return null; + return new List() ; else return questions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: QuestionServiceProvider.getSurveyQuestionsAsync()"); - return null; + return new List(); } } @@ -60,11 +52,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync("/api/Questions/" + questionId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var question = JsonConvert.DeserializeObject(responseString); + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:QuestionById"), questionId); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var question = JsonConvert.DeserializeObject(responseJsonString); if (question == null) return null; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs similarity index 50% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs index a435081..091512e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs @@ -1,33 +1,29 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class RegionServiceProvider : ServiceProviderBase, IRegionServiceProvider { - public RegionServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Regions", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public RegionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Region"), configuration.GetValue("EndPointSettings:LocationUrlBase")) { } public async Task> getRegionsAsync() { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var regions = JsonConvert.DeserializeObject>(responseString); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var regions = JsonConvert.DeserializeObject>(responseJsonString); if (regions == null || !regions.Any()) - return null; + return new List(); else return regions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: RegionServiceProvider.getRegionsAsync()"); - return null; + return new List(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs similarity index 50% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs index 71a37b6..af1aa65 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs @@ -1,21 +1,25 @@ -namespace DamageAssesment.Api.SurveyResponses.Bases +using DamageAssesment.Api.SurveyResponses.Interfaces; + +namespace DamageAssesment.Api.SurveyResponses.Services { public class ServiceProviderBase { protected readonly IConfiguration configuration; - protected readonly HttpClient httpClient; - protected private readonly ILogger logger; + protected readonly IHttpUtil httpUtil; + protected readonly ILogger logger; protected string ressource; protected string urlBase; + protected string url; - public ServiceProviderBase(IConfiguration configuration, HttpClient httpClient, ILogger logger, string ressource, string urlBase) + public ServiceProviderBase(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger, string ressource, string urlBase) { this.configuration = configuration; - this.httpClient = httpClient; + this.httpUtil = httpUtil; this.logger = logger; this.ressource = ressource; this.urlBase = urlBase; + url = urlBase + ressource; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs similarity index 54% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs index 06b1eed..c9df4db 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs @@ -1,14 +1,12 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -using System.Reflection; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class SurveyServiceProvider :ServiceProviderBase, ISurveyServiceProvider { - public SurveyServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Surveys", configuration.GetValue("EndPointSettings:SurveyUrlBase")) + public SurveyServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Survey"), configuration.GetValue("EndPointSettings:SurveyUrlBase")) { } @@ -16,20 +14,17 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var surveys = JsonConvert.DeserializeObject>(responseString); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var surveys = JsonConvert.DeserializeObject>(responseJsonString); if (surveys == null || !surveys.Any()) - return null; + return new List(); else return surveys; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: SurveyServiceProvider.getSurveysAsync()"); - return null; + return new List(); } } @@ -37,11 +32,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource+"/"+ surveyId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var survey = JsonConvert.DeserializeObject(responseString); + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:SurveyById"), surveyId); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var survey = JsonConvert.DeserializeObject(responseJsonString); if (survey == null ) return null; @@ -53,7 +46,5 @@ namespace DamageAssesment.Api.SurveyResponses.Providers return null; } } - - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json index 0c208ae..06d7caa 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json @@ -3,6 +3,30 @@ "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" + }, + "EndPointSettings": { + "AnswerUrlBase": "http://localhost:5200", + "LocationUrlBase": "http://localhost:5213", + "RegionUrlBase": "http://localhost:5211", + "QuestionUrlBase": "http://localhost:5133", + "EmployeeUrlBase": "http://localhost:5135", + "AttachmentUrlBase": "http://localhost:5243", + "SurveyUrlBase": "http://localhost:5009" + }, + + "RessourceSettings": { + "Employee": "/Employees", + "EmployeeById": "/Employees/{0}", + "Question": "/Questions", + "QuestionById": "/Questions/{0}", + "SurveyQuestion": "/Questions/BySurvey/{0}", + "Survey": "/Surveys", + "SurveyById": "/Surveys/{0}", + "Attachment": "/Attachments", + "Answer": "/Answers", + "AnswerByResponse": "/Answers/ByResponse/{0}", + "Location": "/Locations", + "Region": "/Regions" } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json new file mode 100644 index 0000000..ba719e5 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true" + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json new file mode 100644 index 0000000..ba719e5 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true" + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json index 569c0e0..0042404 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json @@ -17,6 +17,20 @@ "EmployeeUrlBase": "http://localhost:5135", "AttachmentUrlBase": "http://localhost:5243", "SurveyUrlBase": "http://localhost:5009" + }, + "RessourceSettings": { + "Employee": "/Employees", + "EmployeeById": "/Employees/{0}", + "Question": "/Questions", + "QuestionById": "/Questions/{0}", + "SurveyQuestion": "/Questions/BySurvey/{0}", + "Survey": "/Surveys", + "SurveyById": "/Surveys/{0}", + "Attachment": "/Attachments", + "Answer": "/Answers", + "AnswerByResponse": "/Answers/ByResponse/{0}", + "Location": "/Locations", + "Region": "/Regions" } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs index 6936c04..fa4928d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs @@ -9,43 +9,43 @@ namespace DamageAssesment.Api.Survey.Test { public class MockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); 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); } - 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 survey = surveys.Item2.FirstOrDefault(s => s.Id == Id); 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"); } - 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"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task getInputSurveyData() { - return new Surveys.Models.Survey { Id = 100, Title = "Mock survey", IsEnabled= true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }; + return new Surveys.Models.Survey { Id = 100, /*Title = "Mock survey",*/ IsEnabled= true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs index 1aaf4a6..44f1f6e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs @@ -14,10 +14,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getOkResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (OkObjectResult) await surveyProvider.GetSurveysAsync(); + var result = (OkObjectResult) await surveyProvider.GetSurveysAsync(null); Assert.Equal(200, result.StatusCode); } @@ -27,10 +27,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (NoContentResult)await surveyProvider.GetSurveysAsync(); + var result = (NoContentResult)await surveyProvider.GetSurveysAsync(null); Assert.Equal(204, result.StatusCode); } @@ -40,10 +40,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getOkResponse(1); - mockSurveyService.Setup(service => service.GetSurveysAsync(1)).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(1,null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1); + var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1,null); Assert.Equal(200, result.StatusCode); } @@ -53,10 +53,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync(99)).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(99,null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99); + var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99,null); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index 56f2e29..7853716 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -1,10 +1,8 @@ using DamageAssesment.Api.Surveys.Interfaces; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Surveys.Controllers { - [Route("api/[controller]")] [ApiController] public class SurveysController : ControllerBase { @@ -14,29 +12,43 @@ namespace DamageAssesment.Api.Surveys.Controllers { this.surveyProvider = surveyProvider; } + /// + /// GET request for retrieving surveys. + /// + [Route("Surveys")] + [Route("Surveys/{language:alpha}")] [HttpGet] - public async Task GetSurveysAsync() + public async Task GetSurveysAsync(string? language) { - var result = await this.surveyProvider.GetSurveysAsync(); + var result = await this.surveyProvider.GetSurveysAsync(language); if (result.IsSuccess) { return Ok(result.Surveys); } return NoContent(); } - [HttpGet("{Id}")] - public async Task GetSurveysAsync(int Id) + + /// + /// GET request for retrieving surveys by ID. + /// + [Route("Surveys/{id:int}")] + [Route("Surveys/{id:int}/{language:alpha}")] + [HttpGet] + public async Task GetSurveysAsync(int id, string? language) { - var result = await this.surveyProvider.GetSurveysAsync(Id); + var result = await this.surveyProvider.GetSurveysAsync(id, language); if (result.IsSuccess) { return Ok(result.Surveys); } return NotFound(); } + /// + /// POST request for creating a new survey. + /// - [HttpPost] + [HttpPost("Surveys")] public async Task PostSurveysAsync(Models.Survey survey) { var result = await this.surveyProvider.PostSurveyAsync(survey); @@ -46,25 +58,32 @@ namespace DamageAssesment.Api.Surveys.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing survey (surveyId,Updated Survey data). + /// - [HttpPut("{Id}")] - public async Task PutSurveysAsync(int Id, Models.Survey survey) + + [HttpPut("Surveys/{id}")] + public async Task 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) { return Ok(result.Survey); } if (result.ErrorMessage == "Not Found") return NotFound(result.ErrorMessage); - + return BadRequest(result.ErrorMessage); } - [HttpDelete("{Id}")] - public async Task DeleteSurveysAsync(int Id) + /// + /// DELETE request for deleting a survey by ID. + /// + [HttpDelete("Surveys/{id}")] + public async Task DeleteSurveysAsync(int id) { - var result = await this.surveyProvider.DeleteSurveyAsync(Id); + var result = await this.surveyProvider.DeleteSurveyAsync(id); if (result.IsSuccess) { return Ok(result.Survey); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj index f6a61e2..812ccd1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj @@ -1,9 +1,10 @@ - + net6.0 enable enable + True @@ -19,6 +20,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs index bff0339..c031f57 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace DamageAssesment.Api.Surveys.Db { @@ -6,23 +7,20 @@ namespace DamageAssesment.Api.Surveys.Db { [Key] public int Id { get; set; } - - [StringLength(100)] - [Required] - public string Title { get; set; } - //[StringLength(1000)] //public string Description { 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; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } + public DateTime CreatedDate { get; set; } = DateTime.Now; + /* + [StringLength(10)] + [ForeignKey("Employee")] + public string EmployeeId { get; set; } + */ } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs new file mode 100644 index 0000000..340bf12 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace DamageAssesment.Api.Surveys.Db +{ + public class SurveyTranslation + { + [Key] + public int Id { get; set; } + [ForeignKey("Survey")] + public int SurveyId { get; set; } + + [StringLength(200)] + [Required] + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs index 6677612..7b63771 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs @@ -2,19 +2,32 @@ namespace DamageAssesment.Api.Surveys.Db { - public class SurveysDbContext:DbContext + public class SurveysDbContext : DbContext { private IConfiguration _Configuration { get; set; } public SurveysDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { _Configuration = configuration; } + + public DbSet Surveys { get; set; } + public DbSet SurveysTranslation { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) { // connect to sql server with connection string from app settings options.UseSqlServer(_Configuration.GetConnectionString("SurveyConnection")); } - public DbSet Surveys { get; set; } - + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs index 42c488e..22b2910 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs @@ -2,11 +2,12 @@ { public interface ISurveyProvider { - Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(); - Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id); - Task<(bool IsSuccess, Models.Survey 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.Survey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id); + Task<(bool IsSuccess, IEnumerable< Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language); + Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int id, Models.Survey Survey); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> DeleteSurveyAsync(int id); + void seedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs index cd5691b..25f5405 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs @@ -2,27 +2,20 @@ namespace DamageAssesment.Api.Surveys.Models { - public class Survey + public class MultiLanSurvey : BaseSurvey + { + public object Titles { get; set; } + } + public class Survey : BaseSurvey + { + public IEnumerable Titles { get; set; } + } + public class BaseSurvey { - [Key] public int Id { get; set; } - - [StringLength(100)] - public string Title { get; set; } - - //[StringLength(1000)] - // public string? Description { get; set; } - public bool IsEnabled { get; set; } - - public DateTime? StartDate { get; set; } - - public DateTime? EndDate { get; set; } - - //public DateTime CreatedDate { get; set; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } - + public DateTime StartDate { get; set; } + public DateTime EndDate { get; set; } + public DateTime CreatedDate { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs new file mode 100644 index 0000000..64671ee --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs @@ -0,0 +1,13 @@ +namespace DamageAssesment.Api.Surveys.Models +{ + public class SurveyTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs index 2cb043c..7b65d99 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs @@ -3,8 +3,10 @@ public class SurveysProfile:AutoMapper.Profile { public SurveysProfile() { - CreateMap(); + CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs index 6ef18b6..178b5fd 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs @@ -1,18 +1,47 @@ using DamageAssesment.Api.Surveys.Db; using DamageAssesment.Api.Surveys.Interfaces; using DamageAssesment.Api.Surveys.Providers; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using System.Text; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. +var authkey = builder.Configuration.GetValue("JwtSettings:securitykey"); +builder.Services.AddAuthentication(item => +{ + item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; +}).AddJwtBearer(item => +{ + item.RequireHttpsMetadata = true; + item.SaveToken = true; + item.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero + }; +}); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseSqlServer("SurveyConnection"); @@ -24,8 +53,16 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var surveyProvider = services.GetRequiredService(); + surveyProvider.seedData(); + } } +app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index bde3ee8..ed24d6d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -1,7 +1,9 @@ using AutoMapper; using DamageAssesment.Api.Surveys.Db; using DamageAssesment.Api.Surveys.Interfaces; +using DamageAssesment.Api.Surveys.Models; using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; namespace DamageAssesment.Api.Surveys.Providers { @@ -16,31 +18,91 @@ namespace DamageAssesment.Api.Surveys.Providers this.surveyDbContext = surveysDbContext; this.logger = logger; this.mapper = mapper; - seedData(); + //seedData(); } - private void seedData() + public void seedData() { if (!surveyDbContext.Surveys.Any()) { - surveyDbContext.Surveys.Add(new Db.Survey { Title = "Sample Survey Title:Damage Assesment 2014", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); - surveyDbContext.Surveys.Add(new Db.Survey { Title = "Sample Survey Title: Damage Assesment 2016", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); - surveyDbContext.Surveys.Add(new Db.Survey { Title = "Sample Survey Title: Damage Assesment 2018", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); + surveyDbContext.Surveys.Add(new Db.Survey { IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); + surveyDbContext.Surveys.Add(new Db.Survey { IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); + surveyDbContext.Surveys.Add(new Db.Survey { IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); surveyDbContext.SaveChanges(); } + + if (!surveyDbContext.SurveysTranslation.Any()) + { + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 1, Language = "en", Title = "Impact of Tropical Storm Emily on Florida's Economy" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 1, Language = "es", Title = "Impacto de la tormenta tropical Emily en la economía de Florida" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 1, Language = "fr", Title = "Impact de la tempête tropicale Emily sur l'économie de la Floride" }); + + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 2, Language = "en", Title = "Hurricane Andrew Aftermath Survey" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 2, Language = "es", Title = "Encuesta sobre las secuelas del huracán Andrew" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 2, Language = "fr", Title = "Enquête sur les conséquences de l'ouragan Andrew" }); + + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 3, Language = "en", Title = "Public Perception of Hurricane Michael's Response" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 3, Language = "es", Title = "Percepción pública de la respuesta del huracán Michael" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { SurveyId = 3, Language = "fr", Title = "Perception du public de la réponse de l'ouragan Michael" }); + + surveyDbContext.SaveChangesAsync(); + } } - public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync() + public IEnumerable GetSurveyTranslations(int id, IEnumerable SurveyTranslation,string? language) { + if (SurveyTranslation == null) + { + if (string.IsNullOrEmpty(language)) + { + SurveyTranslation = mapper.Map, IEnumerable>( + surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id).ToList()); + } + else + { + SurveyTranslation = mapper.Map, IEnumerable>( + surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id && a.Language == language).ToList()); + } + } + return SurveyTranslation; + } + public object CreateMultiLanguageObject(IEnumerable surveyTranslations) + { + object MultiLanguage = new object(); + Dictionary dict = new Dictionary(); + foreach (Models.SurveyTranslation item in surveyTranslations) + { + dict.Add(item.Language, item.Title); + } + MultiLanguage = dict; + return MultiLanguage; + } + public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync(string language) + { + IEnumerable surveysList = null; try { logger?.LogInformation("Gell all Surveys from DB"); - var surveys = await surveyDbContext.Surveys.ToListAsync(); + var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync(); + //var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); + if (surveys != null) { + surveysList = from s in surveys + select new + Models.MultiLanSurvey + { + Id = s.Id, + StartDate = s.StartDate, + EndDate = s.EndDate, + IsEnabled = s.IsEnabled, + CreatedDate = s.CreatedDate, + Titles = CreateMultiLanguageObject(GetSurveyTranslations(s.Id,null, language)) + + }; + logger?.LogInformation($"{surveys.Count} Items(s) found"); - var result = mapper.Map, IEnumerable>(surveys); - return (true, result, null); + return (true, surveysList, null); } return (false, null, "Not found"); } @@ -50,16 +112,27 @@ namespace DamageAssesment.Api.Surveys.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language) { try { logger?.LogInformation("Query Survey"); - var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id); + var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == id && s.IsEnabled == true); if (survey != null) { - logger?.LogInformation($"Survey Id: {Id} found"); - var result = mapper.Map(survey); + Models.MultiLanSurvey result = null; + var surveyTranslations = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == survey.Id).ToListAsync(); + result = new Models.MultiLanSurvey + { + Id = survey.Id, + StartDate = survey.StartDate, + EndDate = survey.EndDate, + IsEnabled = survey.IsEnabled, + CreatedDate = survey.CreatedDate, + Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id,null, language)) + + }; + logger?.LogInformation($"Survey Id: {id} found"); return (true, result, null); } return (false, null, "Not found"); @@ -71,17 +144,26 @@ 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 { if (survey != null) { - var surveys = await surveyDbContext.Surveys.ToListAsync(); - survey.Id = surveys.Count + 1; - surveyDbContext.Surveys.Add(mapper.Map(survey)); - surveyDbContext.SaveChanges(); - return (true, survey, "Successful"); + survey.CreatedDate = DateTime.Now; + Db.Survey _survey = mapper.Map(survey); + + surveyDbContext.Surveys.Add(_survey); + await surveyDbContext.SaveChangesAsync(); + + foreach (var title in survey.Titles) + { + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); + } + await surveyDbContext.SaveChangesAsync(); + var result = mapper.Map(_survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, "")); + return (true, result, "Successful"); } else { @@ -96,22 +178,35 @@ 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 { if (survey != null) { - var _survey = await surveyDbContext.Surveys.Where(s => s.Id == Id).SingleOrDefaultAsync(); + var _survey = await surveyDbContext.Surveys.AsNoTracking().Where(s => s.Id == Id).SingleOrDefaultAsync(); if (_survey != null) { - _survey.Title = survey.Title; - _survey.IsEnabled = survey.IsEnabled; - _survey.StartDate = survey.StartDate; - _survey.EndDate = survey.EndDate; - surveyDbContext.SaveChanges(); - return (true, mapper.Map(_survey), "Successful"); + var surveysTranslation = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == Id).ToListAsync(); + surveyDbContext.SurveysTranslation.RemoveRange(surveysTranslation); + await surveyDbContext.SaveChangesAsync(); + _survey = mapper.Map(survey); + surveyDbContext.Surveys.Update(_survey); + await surveyDbContext.SaveChangesAsync(); + + List listSurveyTranslation = new List(); + Random random = new Random(); + foreach (var title in survey.Titles) + { + listSurveyTranslation.Add(new Db.SurveyTranslation { Id = random.Next(), SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); + } + surveyDbContext.SurveysTranslation.AddRange(listSurveyTranslation); + await surveyDbContext.SaveChangesAsync(); + + var result = mapper.Map(_survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, "")); + return (true, result, "Successful"); } else { @@ -132,7 +227,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 { @@ -140,9 +235,11 @@ namespace DamageAssesment.Api.Surveys.Providers if (survey != null) { + var result = mapper.Map(survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id, null, "")); surveyDbContext.Surveys.Remove(survey); - surveyDbContext.SaveChanges(); - return (true, mapper.Map(survey), $"Survey Id: {Id} deleted Successfuly"); + await surveyDbContext.SaveChangesAsync(); + return (true, result, $"Survey Id: {Id} deleted Successfuly"); } else { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json index 713c5f6..0057832 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs index d70772d..5be421f 100644 --- a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs @@ -24,7 +24,7 @@ namespace DamageAssesment.Api.SurveyResponses.Test public static async Task getSurveyResponseObject() { - return new Models.SurveyResponse { EmployeeId = "Emp1", LocationId = "Loc1", SurveyId = 1, Id = 1 }; + return new Models.SurveyResponse { EmployeeId = 1, LocationId = 1, SurveyId = 1, Id = 1 }; } } } diff --git a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs index 182ec5c..47685a5 100644 --- a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs @@ -68,9 +68,9 @@ namespace DamageAssesment.SurveyResponses.Test { SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject(); var mockResponse = await MockData.getOkResponse(); - mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1")).ReturnsAsync(mockResponse); + mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse); var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object); - var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1"); + var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1); Assert.Equal(200, result.StatusCode); } @@ -78,9 +78,9 @@ namespace DamageAssesment.SurveyResponses.Test public async Task GetSurveyResponsesBySurveyLocationAsync_ShouldReturnStatusCode204() { var mockResponse = await MockData.getResponse(); - mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1")).ReturnsAsync(mockResponse); + mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse); var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object); - var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, "Lo1"); + var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1); Assert.Equal(204, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.sln b/DamageAssesmentApi/DamageAssesment.sln index 20b7b6d..808ff69 100644 --- a/DamageAssesmentApi/DamageAssesment.sln +++ b/DamageAssesmentApi/DamageAssesment.sln @@ -68,6 +68,7 @@ Global {D11808FE-AD1C-4BA6-87FD-9D18B2DC81F2}.Release|Any CPU.ActiveCfg = Release|Any CPU {D11808FE-AD1C-4BA6-87FD-9D18B2DC81F2}.Release|Any CPU.Build.0 = Release|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35CD9231-034D-4999-BCFC-1786DD007ED2}.Debug|Any CPU.Build.0 = Debug|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Release|Any CPU.ActiveCfg = Release|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Release|Any CPU.Build.0 = Release|Any CPU {ADFB79E3-83C9-454F-A070-49D167BD28CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU