276 lines
9.6 KiB
C#

using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Dtos.Roles;
using Marco.Pms.Model.Entitlements;
using Marco.Pms.Model.Mapper;
using Marco.Pms.Model.Utilities;
using Marco.Pms.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
namespace MarcoBMS.Services.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class RolesController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
public RolesController(UserManager<IdentityUser> userManager, ApplicationDbContext context)
{
_context = context;
_userManager = userManager;
}
private int GetTenantId()
{
var tenant = User.FindFirst("TenantId")?.Value;
return (tenant != null ? Convert.ToInt32(tenant) : 1);
}
[HttpGet("jobrole")]
public async Task<IActionResult> GetAllJobRoles()
{
int TenantId = GetTenantId();
var roles = await _context.JobRoles.Where(c => c.TenantId == TenantId).Select(x => new JobRoleVM()
{
Id = x.Id,
Name = x.Name,
Description = x.Description
}).ToListAsync();
return Ok(roles);
}
[HttpPost("jobrole")]
public async Task<IActionResult> AddJobRole([FromBody] CreateJobRoleDto createJobRoleDto)
{
int TenantId = GetTenantId();
if (await _context.JobRoles.AnyAsync(c => c.Name.ToLower() == createJobRoleDto.Name.ToLower() && c.TenantId == TenantId))
{
return Ok(ApiResponse<object>.SuccessResponse(null, "Role with same name already Exists.", 200));
}
else
{
JobRole jr = createJobRoleDto.ToJobRoleFromCreateJobRoleDot(TenantId);
_context.JobRoles.Add(jr);
await _context.SaveChangesAsync();
return Ok(ApiResponse<object>.SuccessResponse(jr, "Success.", 200));
}
}
[HttpPut("jobrole/{id}")]
public async Task<IActionResult> UpdateJobRole(string id, [FromBody] UpdateJobRoleDto updateRoleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != updateRoleDto.Id.ToString())
return BadRequest("Role ID mismatch");
try
{
int TenantId = GetTenantId();
JobRole jr = updateRoleDto.ToJobRoleFromUpdateJobRoleDot(TenantId);
_context.JobRoles.Update(jr);
await _context.SaveChangesAsync();
return Ok(ApiResponse<object>.SuccessResponse(jr, "Success.", 200));
}
catch (Exception ex)
{
return Ok(null);
}
}
[HttpGet]
public async Task<IActionResult> GetAllRoles()
{
int TenantId = GetTenantId();
var roles = await _context.ApplicationRoles.Where(c => c.TenantId == TenantId).ToListAsync();
var roleFeaturePermissions = await _context.RolePermissionMappings
.Join(
_context.FeaturePermissions,
rfp => rfp.FeaturePermissionId,
fp => fp.Id,
(rfp, fp) => new { rfp.ApplicationRoleId, FeaturePermission = fp })
.Join(
_context.ApplicationRoles,
result => result.ApplicationRoleId,
role => role.Id,
(result, role) => new { Role = role, result.FeaturePermission })
.Where(x => x.Role.TenantId == TenantId) // Filter by TenantId
.Select(x => new
{
RoleId = x.Role.Id,
RoleName = x.Role.Role,
FeaturePermission = x.FeaturePermission
})
.ToListAsync();
List<ApplicationRolesVM> applicationRoles = new List<ApplicationRolesVM>();
foreach (var item in roles)
{
var rolesVM = new ApplicationRolesVM()
{
Id = item.Id,
Role = item.Role,
Description = item.Description,
FeaturePermission = []
};
ICollection<FeaturePermission> permissions = roleFeaturePermissions.Where(c => c.RoleId == item.Id)
.Select(c => c.FeaturePermission).ToList();
foreach (var permission in permissions)
{
rolesVM.FeaturePermission.Add(
new FeaturePermissionVM()
{
Id = permission.Id,
Description = permission.Description,
FeatureId = permission.FeatureId,
IsEnabled = permission.IsEnabled,
Name = permission.Name
});
}
applicationRoles.Add(rolesVM);
}
return Ok(applicationRoles);
}
[HttpPost]
public async Task<IActionResult> AddRole([FromBody] CreateApplicationRoleDto createRoleDto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
int TenantId = GetTenantId();
if (createRoleDto.FeaturesPermission == null || (createRoleDto.FeaturesPermission != null && createRoleDto.FeaturesPermission.Count == 0))
{
return BadRequest(new { Message = "Feature Permission is required." });
}
ApplicationRole role = createRoleDto.ToApplicationRoleFromCreateDto(TenantId);
_context.ApplicationRoles.Add(role);
foreach (var permission in createRoleDto.FeaturesPermission)
{
var item = new RolePermissionMappings() { ApplicationRoleId = role.Id, FeaturePermissionId = permission.Id };
bool assigned = _context.RolePermissionMappings.Any(c => c.ApplicationRoleId == role.Id && c.FeaturePermissionId == permission.Id);
if (permission.IsEnabled && !assigned)
_context.RolePermissionMappings.Add(item);
else
_context.RolePermissionMappings.Remove(item);
}
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetRoleById), new { id = role.Id }, role.ToRoleVMFromApplicationRole());
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateRole(string id, [FromBody] UpdateApplicationRoleDto updateRoleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != updateRoleDto.Id.ToString())
return BadRequest("Role ID mismatch");
try
{
int TenantId = GetTenantId();
ApplicationRole role = updateRoleDto.ToApplicationRoleFromUpdateDto(TenantId);
if (role.TenantId != TenantId)
return Unauthorized();
var projectModel = _context.ApplicationRoles.Update(role);
if (projectModel == null)
{
return NotFound("Project not found");
}
foreach (var permission in updateRoleDto.FeaturesPermission)
{
var item = new RolePermissionMappings() { ApplicationRoleId = role.Id, FeaturePermissionId = permission.Id };
bool assigned = _context.RolePermissionMappings.Any(c => c.ApplicationRoleId == role.Id && c.FeaturePermissionId == permission.Id);
if (permission.IsEnabled && !assigned)
_context.RolePermissionMappings.Add(item);
else
_context.RolePermissionMappings.Remove(item);
}
return Ok(role.ToRoleVMFromApplicationRole());
}
catch (Exception ex)
{
return Ok(null);
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetRoleById(Guid id)
{
int TenantId = GetTenantId();
var role = await _context.ApplicationRoles.FindAsync(id);
if (role == null)
return NotFound();
if (role.TenantId != TenantId)
return Unauthorized();
var featurePermissions = await _context.RolePermissionMappings
.Where(rfp => rfp.ApplicationRoleId == id)
.Join(
_context.FeaturePermissions,
rfp => rfp.FeaturePermissionId,
fp => fp.Id,
(rfp, fp) => new FeaturePermissionVM()
{
Id = fp.Id,
Name = fp.Name,
Description = fp.Description,
IsEnabled = fp.IsEnabled,
FeatureId = fp.FeatureId
})
.ToListAsync();
ApplicationRolesVM vm = new ApplicationRolesVM()
{
Id = role.Id,
Role = role.Role,
FeaturePermission = featurePermissions
};
return Ok(vm);
}
}
}