Skip to content

Instantly share code, notes, and snippets.

@buraxta
Created January 20, 2025 15:20
Show Gist options
  • Save buraxta/b4229fcc4b0bd423519f8169f00799b0 to your computer and use it in GitHub Desktop.
Save buraxta/b4229fcc4b0bd423519f8169f00799b0 to your computer and use it in GitHub Desktop.
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Serilog;
using VAP_API.Configuration;
using VAP_API.Data;
using VAP_API.DTOs;
using VAP_API.Enums;
using VAP_API.Models;
using VAP_API.Services;
namespace VAP_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = ApiJwtTokens.ApiAuthScheme)]
public class OrganizationsController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly OrganizationService _organizationService;
public OrganizationsController(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
OrganizationService organizationService
)
{
_context = context;
_userManager = userManager;
_organizationService = organizationService;
}
#region GET
[HttpGet()]
public async Task<IActionResult> GetAllOrganizations([FromQuery] string? userId)
{
if (userId != null)
{
Log.Information(
"GetOrganizationByUserId request received. UserId: {UserId}",
userId
);
if (userId == "0" || userId == string.Empty)
{
Log.Information("UserId not provided. Retrieving UserId from user's claim.");
userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
Log.Warning("User identity not found.");
return Unauthorized("User identity not found");
}
}
Log.Information("Retrieving user with UserId: {UserId}", userId);
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
Log.Warning("User not found. UserId: {UserId}", userId);
return NotFound("User not found");
}
Log.Information("Retrieving organization for UserId: {UserId}", userId);
var organization = await _context
.Organizations.Where(o => o.Id == user.OrganizationId && !o.IsDeleted)
.FirstOrDefaultAsync();
if (organization == null)
{
Log.Warning("Organization not found for UserId: {UserId}", userId);
return NotFound("Organization not found");
}
var OrganizationDTO = new OrganizationDTO
{
Id = organization.Id,
MainOrganizationId = organization.MainOrganizationId,
Name = organization.Name,
CreatedAt = organization.CreatedAt,
UpdatedAt = organization.UpdatedAt,
};
Log.Information(
"GetOrganizationByUserId request completed successfully for UserId: {UserId}",
userId
);
return Ok(OrganizationDTO);
}
Log.Information("GetAllOrganizations request received.");
var organizations = await _context.Organizations.Where(o => !o.IsDeleted).ToListAsync();
if (organizations == null || organizations.Count == 0)
{
Log.Warning("No organizations found.");
return NotFound("There is no organization to be found");
}
var organizationsDTO = organizations
.Select(o => new OrganizationDTO
{
Id = o.Id,
Name = o.Name,
MainOrganizationId = o.MainOrganizationId,
CreatedAt = o.CreatedAt,
UpdatedAt = o.UpdatedAt,
})
.ToList();
Log.Information("GetAllOrganizations request completed successfully.");
return Ok(organizationsDTO);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetOrganization(int id = 0)
{
Log.Information(
"GetOrganization request received. OrganizationId: {OrganizationId}",
id
);
Organization? organization = null;
if (id == 0)
{
Log.Information(
"No organizationId provided. Retrieving organizationId from user's claim."
);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
Log.Warning("User identity not found.");
return Unauthorized("User identity not found");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
Log.Warning("User not found. UserId: {UserId}", userId);
return NotFound("User not found");
}
Log.Information("Retrieving organization for UserId: {UserId}", userId);
organization = await _context
.Organizations.Where(o => o.Id == user.OrganizationId && !o.IsDeleted)
.FirstOrDefaultAsync();
}
else
{
Log.Information(
"Retrieving organization for provided OrganizationId: {OrganizationId}",
id
);
organization = await _context
.Organizations.Where(o => o.Id == id && !o.IsDeleted)
.FirstOrDefaultAsync();
}
if (organization == null)
{
Log.Warning("Organization not found. OrganizationId: {OrganizationId}", id);
return NotFound("Organization not found");
}
var OrganizationDTO = new OrganizationDTO
{
Id = organization.Id,
MainOrganizationId = organization.MainOrganizationId,
Name = organization.Name,
CreatedAt = organization.CreatedAt,
UpdatedAt = organization.UpdatedAt,
};
Log.Information(
"GetOrganization request completed successfully for OrganizationId: {OrganizationId}",
id
);
return Ok(OrganizationDTO);
}
// [HttpGet("getOrganizationByUserId/{userId}")]
// public async Task<IActionResult> GetOrganizationByUserId(string userId = "0")
// {
// Log.Information("GetOrganizationByUserId request received. UserId: {UserId}", userId);
// if (userId == "0" || userId == string.Empty)
// {
// Log.Information("UserId not provided. Retrieving UserId from user's claim.");
// userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
// if (userId == null)
// {
// Log.Warning("User identity not found.");
// return Unauthorized("User identity not found");
// }
// }
// Log.Information("Retrieving user with UserId: {UserId}", userId);
// var user = await _userManager.FindByIdAsync(userId);
// if (user == null)
// {
// Log.Warning("User not found. UserId: {UserId}", userId);
// return NotFound("User not found");
// }
// Log.Information("Retrieving organization for UserId: {UserId}", userId);
// var organization = await _context
// .Organizations.Where(o => o.Id == user.OrganizationId && !o.IsDeleted)
// .FirstOrDefaultAsync();
// if (organization == null)
// {
// Log.Warning("Organization not found for UserId: {UserId}", userId);
// return NotFound("Organization not found");
// }
// var OrganizationDTO = new OrganizationDTO
// {
// Id = organization.Id,
// MainOrganizationId = organization.MainOrganizationId,
// Name = organization.Name,
// CreatedAt = organization.CreatedAt,
// UpdatedAt = organization.UpdatedAt,
// };
// Log.Information(
// "GetOrganizationByUserId request completed successfully for UserId: {UserId}",
// userId
// );
// return Ok(OrganizationDTO);
// }
[HttpGet("{organizationId}/children")]
public async Task<IActionResult> GetAllSubOrganizations(
int organizationId = 0,
[FromQuery] bool? Flatten = false
)
{
if (Flatten == true)
{
Log.Information(
"GetFlatAllSubOrganizations request received. OrganizationId: {OrganizationId}",
organizationId
);
List<OrganizationHierarchyDTO> FlatOrganizations;
if (organizationId == 0)
{
Log.Information(
"OrganizationId not provided. Retrieving OrganizationId from user's claim."
);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
Log.Warning("User identity not found.");
return Unauthorized("User identity not found");
}
Log.Information("Retrieving user with UserId: {UserId}", userId);
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
Log.Warning("User not found. UserId: {UserId}", userId);
return NotFound("User not found");
}
Log.Information(
"Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
user.OrganizationId
);
FlatOrganizations = await _organizationService.GetFlatOrganizationHierarchy(
user.OrganizationId
);
}
else
{
Log.Information(
"Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
organizationId
);
FlatOrganizations = await _organizationService.GetFlatOrganizationHierarchy(
organizationId
);
}
if (FlatOrganizations == null)
{
Log.Warning(
"Organization hierarchy not found for OrganizationId: {OrganizationId}",
organizationId
);
return NotFound("Organization not found.");
}
Log.Information(
"GetAllSubOrganizations request completed successfully for OrganizationId: {OrganizationId}",
organizationId
);
return Ok(FlatOrganizations);
}
Log.Information(
"GetAllSubOrganizations request received. OrganizationId: {OrganizationId}",
organizationId
);
OrganizationHierarchyDTO organizations;
if (organizationId == 0)
{
Log.Information(
"OrganizationId not provided. Retrieving OrganizationId from user's claim."
);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
Log.Warning("User identity not found.");
return Unauthorized("User identity not found");
}
Log.Information("Retrieving user with UserId: {UserId}", userId);
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
Log.Warning("User not found. UserId: {UserId}", userId);
return NotFound("User not found");
}
Log.Information(
"Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
user.OrganizationId
);
organizations = await _organizationService.GetOrganizationHierarchy(
user.OrganizationId
);
}
else
{
Log.Information(
"Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
organizationId
);
organizations = await _organizationService.GetOrganizationHierarchy(organizationId);
}
if (organizations == null)
{
Log.Warning(
"Organization hierarchy not found for OrganizationId: {OrganizationId}",
organizationId
);
return NotFound("Organization not found.");
}
Log.Information(
"GetAllSubOrganizations request completed successfully for OrganizationId: {OrganizationId}",
organizationId
);
return Ok(organizations);
}
// [HttpGet("getFlatAllSubOrganizations/{organizationId}")]
// public async Task<IActionResult> GetFlatAllSubOrganizations(int organizationId = 0)
// {
// Log.Information(
// "GetFlatAllSubOrganizations request received. OrganizationId: {OrganizationId}",
// organizationId
// );
// List<OrganizationHierarchyDTO> organizations;
// if (organizationId == 0)
// {
// Log.Information(
// "OrganizationId not provided. Retrieving OrganizationId from user's claim."
// );
// var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
// if (userId == null)
// {
// Log.Warning("User identity not found.");
// return Unauthorized("User identity not found");
// }
// Log.Information("Retrieving user with UserId: {UserId}", userId);
// var user = await _userManager.FindByIdAsync(userId);
// if (user == null)
// {
// Log.Warning("User not found. UserId: {UserId}", userId);
// return NotFound("User not found");
// }
// Log.Information(
// "Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
// user.OrganizationId
// );
// organizations = await _organizationService.GetFlatOrganizationHierarchy(
// user.OrganizationId
// );
// }
// else
// {
// Log.Information(
// "Retrieving organization hierarchy for OrganizationId: {OrganizationId}",
// organizationId
// );
// organizations = await _organizationService.GetFlatOrganizationHierarchy(
// organizationId
// );
// }
// if (organizations == null)
// {
// Log.Warning(
// "Organization hierarchy not found for OrganizationId: {OrganizationId}",
// organizationId
// );
// return NotFound("Organization not found.");
// }
// Log.Information(
// "GetAllSubOrganizations request completed successfully for OrganizationId: {OrganizationId}",
// organizationId
// );
// return Ok(organizations);
// }
#endregion
#region POST
[HttpPost()]
public async Task<IActionResult> CreateOrganization([FromBody] CreateOrganizationDTO model)
{
Log.Information("CreateOrganization request received with Model: {@Model}", model);
if (!ModelState.IsValid)
{
Log.Warning("Invalid model state for CreateOrganization request.");
return BadRequest(ModelState);
}
if (model.MainOrganizationId <= -1)
{
Log.Information(
"MainOrganizationId is invalid. Attempting to retrieve the creator's organization."
);
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
Log.Warning("User identity not found.");
return Unauthorized("User identity not found in /api/CreateUser");
}
Log.Information("Retrieving user with UserId: {UserId}", userId);
var creator = await _userManager.FindByIdAsync(userId);
if (creator != null)
{
model.MainOrganizationId = creator.OrganizationId;
Log.Information(
"MainOrganizationId set to creator's OrganizationId: {MainOrganizationId}",
creator.OrganizationId
);
}
else
{
Log.Warning("Unable to find creator's organization. UserId: {UserId}", userId);
return Unauthorized("Unable to find creator's organization.");
}
}
var organization = new Organization
{
Name = model.Name,
MainOrganizationId = model.MainOrganizationId,
};
Log.Information(
"Creating new organization with Name: {OrganizationName} and MainOrganizationId: {MainOrganizationId}",
model.Name,
model.MainOrganizationId
);
await _context.Organizations.AddAsync(organization);
var result = await _context.SaveChangesAsync();
await _organizationService.AssignDefaultModulesToOrganization(
_context,
organization.Id
);
if (result <= 0)
{
Log.Warning("Failed to create organization. No changes were saved.");
return BadRequest("Failed to create organization.");
}
Log.Information(
"Organization created successfully with Id: {OrganizationId}",
organization.Id
);
return Ok(new { message = "Organization created successfully", organization.Id });
}
#endregion
#region PUT
[HttpPut()]
public async Task<IActionResult> UpdateOrganization([FromBody] UpdateOrganizationDTO model)
{
Log.Information("UpdateOrganization request received with Model: {@Model}", model);
if (!ModelState.IsValid)
{
Log.Warning("Invalid model state for UpdateOrganization request.");
return BadRequest(ModelState);
}
var organization = await _context
.Organizations.Where(o => o.Id == model.Id && !o.IsDeleted)
.FirstOrDefaultAsync();
if (organization == null)
{
Log.Warning("Organization with Id: {OrganizationId} not found", model.Id);
return NotFound("Organization not found");
}
Log.Information("Updating organization with Id: {OrganizationId}", model.Id);
organization.Name = model.Name ?? organization.Name;
organization.MainOrganizationId =
model.MainOrganizationId ?? organization.MainOrganizationId;
organization.IsDeleted = model.IsDeleted ?? organization.IsDeleted;
_context.Organizations.Update(organization);
var result = await _context.SaveChangesAsync();
if (result <= 0)
{
Log.Warning(
"Failed to update organization with Id: {OrganizationId}. No changes saved.",
model.Id
);
return BadRequest("Failed to update organization");
}
Log.Information(
"Organization with Id: {OrganizationId} updated successfully",
model.Id
);
return Ok("Organization updated successfully");
}
#endregion
#region DELETE
// [HttpDelete("{id}")]
// public async Task<IActionResult> DeleteOrganization(int id)
// {
// Log.Information("DeleteOrganization request received for Id: {OrganizationId}", id);
// var organization = await _context
// .Organizations.Where(o => o.Id == id && !o.IsDeleted)
// .FirstOrDefaultAsync();
// if (organization == null)
// {
// Log.Warning("Organization with Id: {OrganizationId} not found", id);
// return NotFound("Organization not found");
// }
// organization.IsDeleted = true;
// _context.Organizations.Update(organization);
// var result = await _context.SaveChangesAsync();
// if (result <= 0)
// {
// Log.Warning(
// "Failed to delete organization with Id: {OrganizationId}. No changes saved.",
// id
// );
// return BadRequest("Failed to delete organization");
// }
// Log.Information("Organization with Id: {OrganizationId} marked as deleted", id);
// return Ok("Organization marked as deleted");
// }
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteOrganizationAndRelevantData(int id)
{
Log.Information(
"DeleteOrganizationAndRelevantData request received for Id: {OrganizationId}",
id
);
if (id <= 0)
{
Log.Warning("Invalid organization ID: {OrganizationId}", id);
return BadRequest("Invalid organization ID");
}
// Organizasyonu bul
var organization = await _context.Organizations.FirstOrDefaultAsync(o =>
o.Id == id && !o.IsDeleted
);
if (organization == null)
{
Log.Warning("Organization with Id: {OrganizationId} not found", id);
return NotFound("Organization not found");
}
// Organizasyonu silindi olarak işaretle
organization.IsDeleted = true;
// OrganizationId'si aynı olan OrganizationDetails'ları al
var organizationDetails = await _context
.OrganizationDetails.Where(od => od.OrganizationId == id && !od.IsDeleted)
.ToListAsync();
// OrganizationDetails'ları silindi olarak işaretle
organizationDetails.ForEach(detail => detail.IsDeleted = true);
Log.Information(
"Marked {DetailsCount} OrganizationDetails as deleted for OrganizationId: {OrganizationId}",
organizationDetails.Count,
id
);
// OrganizationId'si aynı olan Users'ları al
var users = await _userManager
.Users.Where(u => u.OrganizationId == id && !u.IsDeleted)
.ToListAsync();
// Users'ları silindi olarak işaretle
users.ForEach(user => user.IsDeleted = true);
Log.Information(
"Marked {UsersCount} Users as deleted for OrganizationId: {OrganizationId}",
users.Count,
id
);
// OrganizationId'si aynı olan OrganizationModules'leri al
var organizationModules = await _context
.OrganizationModules.Where(om => om.OrganizationId == id && !om.IsDeleted)
.ToListAsync();
// OrganizationModules'leri silindi olarak işaretle
organizationModules.ForEach(module => module.IsDeleted = true);
Log.Information(
"Marked {ModulesCount} OrganizationModules as deleted for OrganizationId: {OrganizationId}",
organizationModules.Count,
id
);
// OrganizationId'si aynı olan Role'leri al
var roles = await _context
.Role.Where(r => r.OrganizationId == id && !r.IsDeleted)
.ToListAsync();
// Role'leri silindi olarak işaretle
roles.ForEach(role => role.IsDeleted = true);
Log.Information(
"Marked {RolesCount} Roles as deleted for OrganizationId: {OrganizationId}",
roles.Count,
id
);
// Silinen rollerin RoleId'sine sahip Permission'ları al
var roleIds = roles.Select(r => r.Id).ToList();
var permissions = await _context
.Permissions.Where(p => roleIds.Contains(p.RoleId) && !p.IsDeleted)
.ToListAsync();
// Permission'ları silindi olarak işaretle
permissions.ForEach(permission => permission.IsDeleted = true);
Log.Information(
"Marked {PermissionsCount} Permissions as deleted for OrganizationId: {OrganizationId}",
permissions.Count,
id
);
// Güncellenmiş verileri kaydet
_context.Organizations.Update(organization);
_context.Role.UpdateRange(roles);
_context.OrganizationDetails.UpdateRange(organizationDetails);
_context.Users.UpdateRange(users);
_context.OrganizationModules.UpdateRange(organizationModules);
_context.Permissions.UpdateRange(permissions);
// Değişiklikleri veritabanına kaydet
var result = await _context.SaveChangesAsync();
// Kaydetme işlemi başarısızsa hata döndür
if (result <= 0)
{
Log.Warning(
"Failed to delete organization and relevant data for OrganizationId: {OrganizationId}",
id
);
return BadRequest("Failed to delete organization and related data");
}
Log.Information(
"Organization and relevant data for OrganizationId: {OrganizationId} marked as deleted successfully",
id
);
return Ok("Organization and relevant data marked as deleted successfully");
}
// [HttpDelete("deleteOrganizationAndMoveRelevantData/{id}")]
// public async Task<IActionResult> DeleteOrganizationAndMoveRelevantData(int id)
// {
// Log.Information(
// "DeleteOrganizationAndMoveRelevantData request received for OrganizationId: {OrganizationId}",
// id
// );
// // İsteği atan kullanıcının kimliğini al
// var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
// if (userId == null)
// {
// Log.Warning("User identity not found for the request");
// return Unauthorized("User identity not found");
// }
// // Kullanıcıyı bul
// var user = await _userManager.FindByIdAsync(userId);
// if (user == null)
// {
// Log.Warning("User not found or is deleted: {UserId}", userId);
// return Unauthorized("User not found or is deleted");
// }
// // Taşınacak hedef organizasyon ID'si
// var targetOrganizationId = user.OrganizationId;
// // Silinecek organizasyonu bul
// var organization = await _context.Organizations.FirstOrDefaultAsync(o =>
// o.Id == id && !o.IsDeleted
// );
// if (organization == null)
// {
// Log.Warning("Organization with Id: {OrganizationId} not found", id);
// return NotFound("Organization not found");
// }
// // Silinecek organizasyon, kullanıcı ile aynı organizasyon ise işlem iptal edilir
// if (organization.Id == targetOrganizationId)
// {
// Log.Warning(
// "User {UserId} cannot delete their own organization with Id: {OrganizationId}",
// userId,
// id
// );
// return BadRequest("You cannot use this process for your own organization.");
// }
// var organizationDetails = await _context
// .OrganizationDetails.Where(od => od.OrganizationId == id && !od.IsDeleted)
// .ToListAsync();
// // Organizasyon detaylarını güncelle
// organizationDetails.ForEach(detail => detail.OrganizationId = targetOrganizationId);
// Log.Information(
// "Moved {DetailsCount} OrganizationDetails to OrganizationId: {TargetOrganizationId}",
// organizationDetails.Count,
// targetOrganizationId
// );
// var users = await _userManager
// .Users.Where(u => u.OrganizationId == id && !u.IsDeleted)
// .ToListAsync();
// // Kullanıcıları güncelle
// users.ForEach(user => user.OrganizationId = targetOrganizationId);
// Log.Information(
// "Moved {UsersCount} Users to OrganizationId: {TargetOrganizationId}",
// users.Count,
// targetOrganizationId
// );
// // İlgili verileri bul ve organizationId'lerini değiştir
// var roles = await _context
// .Role.Where(r => r.OrganizationId == id && !r.IsDeleted)
// .ToListAsync();
// // Rolleri güncelle ve taşınacak rolleri bul
// roles.ForEach(role => role.OrganizationId = targetOrganizationId);
// Log.Information(
// "Moved {RolesCount} Roles to OrganizationId: {TargetOrganizationId}",
// roles.Count,
// targetOrganizationId
// );
// // Organizasyonu silindi olarak işaretle
// organization.IsDeleted = true;
// // Değişiklikleri kaydet
// var result = await _context.SaveChangesAsync();
// if (result <= 0)
// {
// Log.Warning(
// "Failed to delete organization and move data for OrganizationId: {OrganizationId}",
// id
// );
// return BadRequest("Failed to delete organization and move relevant data");
// }
// Log.Information(
// "Organization with Id: {OrganizationId} deleted and data moved successfully",
// id
// );
// return Ok("Organization deleted and data moved successfully");
// }
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment