shoc-backend/Api.SeaHavenIndustries/Controllers/SettingsController.cs
Adam Moussa e8c400a20a Add null safety checks across all API controllers
- Add null checks after FirstOrDefault() before property access
- Guard navigation property access (Locations, AssignToUser, ApplicationUser, POC, Contacts)
- Null-coalesce string properties in search/filter LINQ queries
- Protect Sum() on nullable LineItems collections
- Change FirstAsync to FirstOrDefaultAsync with null guard in UserController
- Add null check on model.Attachments iteration in EditWorkorder
2026-04-16 16:33:42 -04:00

241 lines
8.8 KiB
C#

using Api.SeaHavenIndustries.DTOs;
using Api.SeaHavenIndustries.Helper.ViewModel;
using Data.SeaHavenIndustries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Api.SeaHavenIndustries.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class SettingsController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _db;
public SettingsController(UserManager<ApplicationUser> userManager, ApplicationDbContext db)
{
_userManager = userManager;
_db = db;
}
[HttpPost]
[Route("AddCategory")]
public async Task<IActionResult> AddCategory(Category_DTO model)
{
try
{
Category category = new Category();
category.Name = model.Name;
_db.Categories.Add(category);
await _db.SaveChangesAsync();
return Ok(new DataResponse { Message = "Successfully Saved Data", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = ex.Message });
}
}
[HttpPost]
[Route("EditCategory")]
public async Task<IActionResult> EditCategory(EditCategory_DTO model)
{
try
{
var exist = _db.Categories.Where(w => w.Id == model.Id).FirstOrDefault();
if (exist == null)
return BadRequest(new Response { Status = "Error", Message = "Category not found" });
exist.Name = model.Name;
_db.Categories.Update(exist);
await _db.SaveChangesAsync();
return Ok(new DataResponse { Message = "Updated Successfully", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = ex.Message });
}
}
[HttpGet]
[Route("DeleteCategory")]
public async Task<IActionResult> DeleteCategory(int id)
{
try
{
var exist = _db.Categories.Where(w => w.Id == id).FirstOrDefault();
if (exist != null)
{
var chkexist = _db.Templates.Where(w => w.CategoryId == id).ToList();
if (chkexist != null)
{
_db.RemoveRange(chkexist);
}
var chkworkordercategory = _db.workOrderCategories.Where(w => w.CategoryId == id).ToList();
if (chkworkordercategory != null)
{
_db.RemoveRange(chkworkordercategory);
}
_db.Remove(exist);
}
else
{
return BadRequest(new Response { Status = "Error", Message = "ID not matched!" });
}
await _db.SaveChangesAsync();
return Ok(new DataResponse { Message = "Deleted Successfully", Status = "200" });
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = ex.Message });
}
}
[HttpGet]
[Route("GetCategoryList")]
public IActionResult GetCategoryList(int page = 1, int pageSize = 10)
{
var totalCount = _db.Categories.Count();
var data = _db.Categories.Select(s => new
{
s.Id,
s.Name
}).OrderByDescending(d => d.Id).ToList().Skip((page - 1) * pageSize)
.Take(pageSize);
// Calculate the number of pages
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
// Create a view model containing the paged items and pagination metadata
var viewModel = new Pagination_DTO
{
Data = data,
PageNumber = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
};
return Ok(viewModel);
}
[HttpGet]
[Route("GetTemplates")]
public IActionResult GetTemplates(int page = 1, int pageSize = 10)
{
try
{
var totalCount = _db.workOrders.Where(w=> w.istemplate == true).Count();
var data = _db.workOrders.Where(w => w.istemplate == true).OrderByDescending(d => d.Id).ToList().Skip((page - 1) * pageSize)
.Take(pageSize);
// Calculate the number of pages
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
// Create a view model containing the paged items and pagination metadata
var viewModel = new Pagination_DTO
{
Data = data,
PageNumber = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
};
return Ok(viewModel);
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = ex.Message });
}
}
[HttpGet]
[Route("GetUsers")]
public async Task<IActionResult> GetUsers(string? search = "", int page = 1, int pageSize = 10)
{
try
{
var totalCount = _db.Users.Count();
var allUsers = _db.Users.Where(w => (w.FirstName ?? "").ToLower().Contains((search ?? "").ToLower())).OrderByDescending(d => d.Id).ToList().Skip((page - 1) * pageSize)
.Take(pageSize);
// Calculate the number of pages
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var filteredUsers = new List<UserRoleViewModel>();
foreach (var user in allUsers)
{
var roles = await _userManager.GetRolesAsync(user);
if (!roles.Contains("Admin"))
{
filteredUsers.Add(new UserRoleViewModel
{
RoleName = roles.Count() > 0 ? roles.First() : "",
Email = user.Email,
UserName = user.FirstName,
Date = user.CreatedDate?.Date.ToString(),
Status = user.UniqueName,
Id = user.Id
});
}
}
// Create a view model containing the paged items and pagination metadata
var viewModel = new Pagination_DTO
{
Data = filteredUsers,
PageNumber = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
};
return Ok(viewModel);
}
catch (Exception ex)
{
return BadRequest(new { Status = "Error", Message = ex.Message });
}
}
[HttpGet]
[Route("GetRoles")]
public async Task<IActionResult> GetRoles()
{
try
{
var data = _db.Roles.ToList();
List<Roles_DTO> roles = new List<Roles_DTO>();
foreach (var role in data)
{
if (role.Name == "Admin")
{
roles.Add(new Roles_DTO { Name = role.Name, Description = "Full Access" });
}
else if(role.Name == "Supervisor")
{
roles.Add(new Roles_DTO { Name = role.Name, Description = "Access to Team's Work Orders Only" });
}
else if(role.Name == "Manager")
{
roles.Add(new Roles_DTO { Name = role.Name, Description = "Full access accept quotes" });
}
else if(role.Name =="User")
{
roles.Add(new Roles_DTO { Name = role.Name, Description = "Access to Assigned Work Orders Only" });
}
}
return Ok(roles);
}
catch (Exception ex)
{
return BadRequest(new Response { Status = "Error", Message = ex.Message });
}
}
}
}