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.Interfaces;
using DamageAssesment.Api.Questions.Models;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -111,6 +112,26 @@ namespace DamageAssesment.Api.Questions.Controllers
return CreatedAtRoute("DefaultApi", questions); return CreatedAtRoute("DefaultApi", questions);
} }
/// <summary> /// <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). /// POST request for creating a new question (multilingual).
/// </summary> /// </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, 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, 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)> 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)> UpdateQuestionAsync(Models.Question Question);
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id); 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); 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) public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question)
{ {
try try
@ -409,8 +439,11 @@ namespace DamageAssesment.Api.Questions.Providers
if (question != null) if (question != null)
{ {
var questiontrans=await questionDbContext.QuestionsTranslations.AsNoTracking().Where(x=>x.QuestionId== id).ToListAsync();
var result = mapper.Map<Db.Question, Models.MultiLanguage>(question); var result = mapper.Map<Db.Question, Models.MultiLanguage>(question);
result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
if(questiontrans!=null)
questionDbContext.QuestionsTranslations.RemoveRange(questiontrans);
questionDbContext.Questions.Remove(question); questionDbContext.Questions.Remove(question);
questionDbContext.SaveChanges(); questionDbContext.SaveChanges();
return (true, result, $"QuestionID {id} deleted Successfuly"); return (true, result, $"QuestionID {id} deleted Successfuly");

View File

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

View File

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

View File

@ -2,6 +2,6 @@
{ {
public interface IHttpUtil 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"); var _jwtsettings = builder.Configuration.GetSection("JwtSettings");
builder.Services.Configure<JwtSettings>(_jwtsettings); builder.Services.Configure<JwtSettings>(_jwtsettings);
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // 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.Db;
using DamageAssesment.Api.UsersAccess.Interfaces; using DamageAssesment.Api.UsersAccess.Interfaces;
using DamageAssesment.Api.UsersAccess.Models; using DamageAssesment.Api.UsersAccess.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
@ -18,21 +21,23 @@ namespace DamageAssesment.Api.UsersAccess.Providers
private readonly UsersAccessDbContext userAccessDbContext; private readonly UsersAccessDbContext userAccessDbContext;
private readonly ILogger<UsersAccessProvider> logger; private readonly ILogger<UsersAccessProvider> logger;
private readonly IMapper mapper; private readonly IMapper mapper;
//private readonly IEmployeeServiceProvider employeeServiceProvider; private readonly IEmployeeServiceProvider employeeServiceProvider;
private readonly JwtSettings jwtSettings; private readonly JwtSettings jwtSettings;
private readonly ITokenServiceProvider tokenServiceProvider; private readonly ITokenServiceProvider tokenServiceProvider;
private readonly IConfiguration configuration; 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.userAccessDbContext = userAccessDbContext;
//this.employeeServiceProvider = employeeServiceProvider; this.employeeServiceProvider = employeeServiceProvider;
this.logger = logger; this.logger = logger;
this.mapper = mapper; this.mapper = mapper;
jwtSettings = options.Value; jwtSettings = options.Value;
this.tokenServiceProvider = tokenServiceProvider; this.tokenServiceProvider = tokenServiceProvider;
this.httpContextAccessor = httpContextAccessor;
this.configuration = configuration; this.configuration = configuration;
// seedData(); seedData();
} }
public void seedData() public void seedData()
@ -55,18 +60,47 @@ namespace DamageAssesment.Api.UsersAccess.Providers
userAccessDbContext.SaveChanges(); userAccessDbContext.SaveChanges();
} }
} }
private string GetToken()
public async Task<(bool IsSuccess, IEnumerable<Models.User> Users, string ErrorMessage)> GetUsersAsync() {
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 try
{ {
logger?.LogInformation("Gell all Users from DB"); logger?.LogInformation("Gell all Users from DB");
var users = await userAccessDbContext.Users.ToListAsync(); var users = await userAccessDbContext.Users.ToListAsync();
List<object> userslist= new List<object>();
if (users != null) 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"); logger?.LogInformation($"{users.Count} Items(s) found");
var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users); // var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users);
return (true, result, null); return (true, userslist, null);
} }
return (false, null, "Not found"); return (false, null, "Not found");
} }
@ -76,18 +110,29 @@ namespace DamageAssesment.Api.UsersAccess.Providers
return (false, null, ex.Message); return (false, null, ex.Message);
} }
} }
public async Task<(bool IsSuccess, object User, string ErrorMessage)> GetUsersAsync(int Id)
public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id)
{ {
try try
{ {
logger?.LogInformation("Querying Users table"); logger?.LogInformation("Querying Users table");
var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id); var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id);
if (user != null) 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"); logger?.LogInformation($"User Id: {Id} found");
var result = mapper.Map<Db.User, Models.User>(user); var result = mapper.Map<Db.User, Models.User>(user);
return (true, result, null); return (true, data, null);
} }
return (false, null, "Not found"); 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 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); var employees = JsonConvert.DeserializeObject<List<Employee>>(responseJsonString);
if (employees == null || !employees.Any()) 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 try
{ {
url = urlBase + string.Format(configuration.GetValue<string>("RessourceSettings:EmployeeById"), employeeId); 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); var employee = JsonConvert.DeserializeObject<Employee>(responseJsonString);
if (employee == null) if (employee == null)

View File

@ -14,7 +14,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
this.httpClient = httpClient; this.httpClient = httpClient;
this.logger = logger; 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 try
{ {
@ -22,7 +22,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
request.Headers.Accept.Clear(); request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 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) if (method == HttpMethod.Post)
{ {
request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json"); request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json");

View File

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