Merged PR 85: user access module changes for populating employee Information

This commit is contained in:
Uppu, Vijay 2023-12-12 23:15:03 +00:00
commit 28de758da0
11 changed files with 127 additions and 23 deletions

View File

@ -1,4 +1,5 @@
using DamageAssesment.Api.Questions.Interfaces;
using DamageAssesment.Api.Questions.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@ -111,6 +112,26 @@ namespace DamageAssesment.Api.Questions.Controllers
return CreatedAtRoute("DefaultApi", questions);
}
/// <summary>
/// PUT request for update a multiple question (multilingual) for survey.
/// </summary>
[HttpPut("questions/multiple/{surveyid}")]
public async Task<IActionResult> CreateQuestions(int surveyid, List<Models.Question> questions)
{
if (questions != null)
{
var result = await this.questionsProvider.PutQuestionsAsync(surveyid,questions);
if (result.IsSuccess)
{
return Ok(result.Question);
}
if (result.ErrorMessage == "Not Found")
return NotFound(result.ErrorMessage);
return BadRequest(result.ErrorMessage);
}
return CreatedAtRoute("DefaultApi", questions);
}
/// <summary>
/// POST request for creating a new question (multilingual).
/// </summary>

View File

@ -9,6 +9,7 @@ namespace DamageAssesment.Api.Questions.Interfaces
Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language);
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question);
Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PostQuestionsAsync(List<Models.Question> Questions);
Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PutQuestionsAsync(int surveyId,List<Models.Question> Questions);
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question);
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id);

View File

@ -376,6 +376,36 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PutQuestionsAsync(int surveyId, List<Models.Question> Questions)
{
try
{
var questions=await questionDbContext.Questions.AsNoTracking().Where(a=>a.SurveyId == surveyId).ToListAsync();
if (questions != null)
{
List<int> questionids=questions.Select(a=>a.Id).ToList();
var questiontrans = await questionDbContext.QuestionsTranslations.AsNoTracking().Where(x => questionids.Contains(x.QuestionId)).ToListAsync();
if (questiontrans != null)
questionDbContext.QuestionsTranslations.RemoveRange(questiontrans);
questionDbContext.Questions.RemoveRange(questions);
questionDbContext.SaveChanges();
}
List<Models.MultiLanguage> results = new List<MultiLanguage>();
logger?.LogInformation("Query Question");
foreach (Models.Question Question in Questions)
{
Question.SurveyId = surveyId;
results.Add(InsertQuestion(Question));
}
return (true, results, null);
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question)
{
try
@ -409,8 +439,11 @@ namespace DamageAssesment.Api.Questions.Providers
if (question != null)
{
var questiontrans=await questionDbContext.QuestionsTranslations.AsNoTracking().Where(x=>x.QuestionId== id).ToListAsync();
var result = mapper.Map<Db.Question, Models.MultiLanguage>(question);
result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
if(questiontrans!=null)
questionDbContext.QuestionsTranslations.RemoveRange(questiontrans);
questionDbContext.Questions.Remove(question);
questionDbContext.SaveChanges();
return (true, result, $"QuestionID {id} deleted Successfuly");

View File

@ -4,7 +4,7 @@ namespace DamageAssesment.Api.UsersAccess.Interfaces
{
public interface IEmployeeServiceProvider
{
Task<List<Employee>> getEmployeesAsync();
Task<Employee> getEmployeeAsync(int employeeId);
Task<List<Employee>> getEmployeesAsync(string token);
Task<Employee> getEmployeeAsync(int employeeId, string token);
}
}

View File

@ -4,8 +4,8 @@ namespace DamageAssesment.Api.UsersAccess.Interfaces
{
public interface IUsersAccessProvider
{
public Task<(bool IsSuccess, IEnumerable< Models.User> Users, string ErrorMessage)> GetUsersAsync();
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id);
public Task<(bool IsSuccess, IEnumerable<object> Users, string ErrorMessage)> GetUsersAsync();
public Task<(bool IsSuccess, object User, string ErrorMessage)> GetUsersAsync(int Id);
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User User);
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id,Models.User User);
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id);

View File

@ -2,6 +2,6 @@
{
public interface IHttpUtil
{
Task<string> SendAsync(HttpMethod method, string url, string JsonInput);
Task<string> SendAsync(HttpMethod method, string url, string JsonInput, string token);
}
}

View File

@ -68,6 +68,7 @@ builder.Services.AddAuthorization(options =>
var _jwtsettings = builder.Configuration.GetSection("JwtSettings");
builder.Services.Configure<JwtSettings>(_jwtsettings);
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

View File

@ -2,9 +2,12 @@
using DamageAssesment.Api.UsersAccess.Db;
using DamageAssesment.Api.UsersAccess.Interfaces;
using DamageAssesment.Api.UsersAccess.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
@ -18,21 +21,23 @@ namespace DamageAssesment.Api.UsersAccess.Providers
private readonly UsersAccessDbContext userAccessDbContext;
private readonly ILogger<UsersAccessProvider> logger;
private readonly IMapper mapper;
//private readonly IEmployeeServiceProvider employeeServiceProvider;
private readonly IEmployeeServiceProvider employeeServiceProvider;
private readonly JwtSettings jwtSettings;
private readonly ITokenServiceProvider tokenServiceProvider;
private readonly IConfiguration configuration;
private readonly IHttpContextAccessor httpContextAccessor;
public UsersAccessProvider(IConfiguration configuration,IOptions<JwtSettings> options, ITokenServiceProvider tokenServiceProvider, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger<UsersAccessProvider> logger, IMapper mapper)
public UsersAccessProvider(IConfiguration configuration,IOptions<JwtSettings> options, ITokenServiceProvider tokenServiceProvider, IHttpContextAccessor httpContextAccessor, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger<UsersAccessProvider> logger, IMapper mapper)
{
this.userAccessDbContext = userAccessDbContext;
//this.employeeServiceProvider = employeeServiceProvider;
this.employeeServiceProvider = employeeServiceProvider;
this.logger = logger;
this.mapper = mapper;
jwtSettings = options.Value;
this.tokenServiceProvider = tokenServiceProvider;
this.httpContextAccessor = httpContextAccessor;
this.configuration = configuration;
// seedData();
seedData();
}
public void seedData()
@ -55,18 +60,47 @@ namespace DamageAssesment.Api.UsersAccess.Providers
userAccessDbContext.SaveChanges();
}
}
public async Task<(bool IsSuccess, IEnumerable<Models.User> Users, string ErrorMessage)> GetUsersAsync()
private string GetToken()
{
string token = httpContextAccessor.HttpContext.Request.Headers.Authorization;
if (token != null)
{
token = token.Replace("Bearer ", string.Empty);
}
else
{
token = "";
}
return token;
}
public async Task<(bool IsSuccess, IEnumerable<object> Users, string ErrorMessage)> GetUsersAsync()
{
try
{
logger?.LogInformation("Gell all Users from DB");
var users = await userAccessDbContext.Users.ToListAsync();
List<object> userslist= new List<object>();
if (users != null)
{
var employees = await employeeServiceProvider.getEmployeesAsync( GetToken());
var roles = await userAccessDbContext.Roles.ToListAsync();
foreach (Db.User user in users)
{
var employee = employees.SingleOrDefault(a=>a.Id==user.EmployeeId);
var role = roles.SingleOrDefault(s => s.Id == user.RoleId);
userslist.Add(new
{
Id = user.Id,
EmployeeId = user.EmployeeId,
EmployeeCode = user.EmployeeCode,
EmployeeName = (employee != null) ? employee.Name : null,
RoleId = user.RoleId,
RoleName = (role != null) ? role.Name : null
});
}
logger?.LogInformation($"{users.Count} Items(s) found");
var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users);
return (true, result, null);
// var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users);
return (true, userslist, null);
}
return (false, null, "Not found");
}
@ -76,18 +110,29 @@ namespace DamageAssesment.Api.UsersAccess.Providers
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id)
public async Task<(bool IsSuccess, object User, string ErrorMessage)> GetUsersAsync(int Id)
{
try
{
logger?.LogInformation("Querying Users table");
var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id);
if (user != null)
{
var employee = await employeeServiceProvider.getEmployeeAsync(user.EmployeeId,GetToken());
var role = await userAccessDbContext.Roles.SingleOrDefaultAsync(s => s.Id == user.RoleId);
var data = new
{
Id = user.Id,
EmployeeId = user.EmployeeId,
EmployeeCode=user.EmployeeCode,
EmployeeName = (employee != null) ? employee.Name : null,
RoleId = user.RoleId,
RoleName = (role!=null)?role.Name:null
};
logger?.LogInformation($"User Id: {Id} found");
var result = mapper.Map<Db.User, Models.User>(user);
return (true, result, null);
return (true, data, null);
}
return (false, null, "Not found");
}

View File

@ -10,11 +10,11 @@ namespace DamageAssesment.Api.UsersAccess.Services
{
}
public async Task<List<Employee>> getEmployeesAsync()
public async Task<List<Employee>> getEmployeesAsync(string token)
{
try
{
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null,token);
var employees = JsonConvert.DeserializeObject<List<Employee>>(responseJsonString);
if (employees == null || !employees.Any())
@ -28,12 +28,12 @@ namespace DamageAssesment.Api.UsersAccess.Services
}
}
public async Task<Employee> getEmployeeAsync(int employeeId)
public async Task<Employee> getEmployeeAsync(int employeeId, string token)
{
try
{
url = urlBase + string.Format(configuration.GetValue<string>("RessourceSettings:EmployeeById"), employeeId);
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null,token);
var employee = JsonConvert.DeserializeObject<Employee>(responseJsonString);
if (employee == null)

View File

@ -14,7 +14,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
this.httpClient = httpClient;
this.logger = logger;
}
public async Task<string> SendAsync(HttpMethod method, string url, string JsonInput)
public async Task<string> SendAsync(HttpMethod method, string url, string JsonInput,string token)
{
try
{
@ -22,7 +22,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (method == HttpMethod.Post)
{
request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json");

View File

@ -8,8 +8,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
//"EndPointSettings": {
// "EmployeeUrlBase": "http://localhost:5135"
//},
"EndPointSettings": {
"EmployeeUrlBase": "http://localhost:5135"
"EmployeeUrlBase": "http://damageassesment.api.employees:80"
},
"RessourceSettings": {
"Employee": "/Employees",