hrms-api-backend/BMA.EHR.Discipline.Service/Controllers/DisciplineSuspendController.cs
2025-12-23 18:02:59 +07:00

454 lines
26 KiB
C#

using BMA.EHR.Application.Repositories;
using BMA.EHR.Application.Repositories.MessageQueue;
using BMA.EHR.Application.Responses.Profiles;
using BMA.EHR.Discipline.Service.Requests;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Models.Discipline;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Infrastructure.Persistence;
using Elasticsearch.Net;
// using BMA.EHR.Placement.Service.Requests;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.Annotations;
using System.Linq;
using System.Security.Claims;
namespace BMA.EHR.DisciplineSuspend.Service.Controllers
{
[Route("api/v{version:apiVersion}/discipline/suspend")]
[ApiVersion("1.0")]
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("ระบบวินัยเรื่องผู้ถูกพักราชการ")]
public class DisciplineSuspendController : BaseController
{
private readonly DisciplineDbContext _context;
private readonly MinIODisciplineService _documentService;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly PermissionRepository _permission;
private readonly UserProfileRepository _userProfileRepository;
public DisciplineSuspendController(DisciplineDbContext context,
MinIODisciplineService documentService,
IHttpContextAccessor httpContextAccessor,
PermissionRepository permission,
UserProfileRepository userProfileRepository)
{
// _repository = repository;
_context = context;
_documentService = documentService;
_httpContextAccessor = httpContextAccessor;
_permission = permission;
_userProfileRepository = userProfileRepository;
}
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
private string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
#endregion
/// <summary>
/// list รายการผู้ถูกพักราชการ
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet()]
public async Task<ActionResult<ResponseObject>> GetDisciplineSuspend(DateTime? startDate, DateTime? endDate, int page = 1, int pageSize = 25, string keyword = "", string profileType = "", string? sortBy = "", bool? descending = false, string? status="")
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_DISCIPLINE_SUSPENDED");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
// กรองสิทธิ์
string role = jsonData["result"]?.ToString() ?? "";
var nodeId = string.Empty;
var profileAdmin = new GetUserOCAllDto();
profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken);
if (role == "NORMAL" || role == "CHILD")
{
nodeId = profileAdmin?.Node == 4
? profileAdmin?.Child4DnaId
: profileAdmin?.Node == 3
? profileAdmin?.Child3DnaId
: profileAdmin?.Node == 2
? profileAdmin?.Child2DnaId
: profileAdmin?.Node == 1
? profileAdmin?.Child1DnaId
: profileAdmin?.Node == 0
? profileAdmin?.RootDnaId
: "";
}
else if (role == "BROTHER")
{
nodeId = profileAdmin?.Node == 4
? profileAdmin?.Child3DnaId
: profileAdmin?.Node == 3
? profileAdmin?.Child2DnaId
: profileAdmin?.Node == 2
? profileAdmin?.Child1DnaId
: profileAdmin?.Node == 1 || profileAdmin?.Node == 0
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
{
nodeId = profileAdmin?.RootDnaId;
}
var data_search = (from x in _context.DisciplineReport_Profiles.Include(x => x.DisciplineDisciplinary)
where
(
endDate != null && startDate != null?
(
(x.StartDateSuspend.Value.Date >= startDate.Value.Date && x.StartDateSuspend.Value.Date <= endDate.Value.Date) ||
(x.EndDateSuspend.Value.Date >= startDate.Value.Date && x.EndDateSuspend.Value.Date <= endDate.Value.Date) ||
(x.StartDateSuspend.Value.Date <= startDate.Value.Date && x.EndDateSuspend.Value.Date >= endDate.Value.Date)
) :
true
)
&&
(
(x.CitizenId != null && x.CitizenId.Contains(keyword)) ||
((x.Prefix ?? "") + (x.FirstName ?? "") + " " + (x.LastName ?? "")).Contains(keyword) ||
(x.Organization != null && x.Organization.Contains(keyword)) ||
(x.Position != null && x.Position.Contains(keyword)) ||
(x.PosNo != null && x.PosNo.Contains(keyword)) ||
((x.posTypeName ?? "") + " (" + (x.posLevelName ?? "") + ")").Contains(keyword) ||
(x.Title != null && x.Title.Contains(keyword))
)
&&
(
string.IsNullOrEmpty(profileType) ||
(profileType.ToUpper() == "OFFICER" && x.profileType == "OFFICER") ||
(profileType.ToUpper() == "EMPLOYEE" && x.profileType == "EMPLOYEE")
)
&&
(
!string.IsNullOrEmpty(status) ? x.Status!.Trim().ToUpper() == status : true
)
&&
(
role == "OWNER"
? true
: role == "ROOT"
? x.rootDnaId == nodeId
: role == "PARENT"
? x.rootDnaId == nodeId && x.child1DnaId != null
: role == "CHILD"
? (
profileAdmin.Node == 4 ? x.child4DnaId == nodeId :
profileAdmin.Node == 3 ? x.child3DnaId == nodeId :
profileAdmin.Node == 2 ? x.child2DnaId == nodeId :
profileAdmin.Node == 1 ? x.child1DnaId == nodeId :
profileAdmin.Node == 0 ? x.rootDnaId == nodeId :
true
)
: role == "BROTHER"
? (
profileAdmin.Node == 4 ? x.child3DnaId == nodeId :
profileAdmin.Node == 3 ? x.child2DnaId == nodeId :
profileAdmin.Node == 2 ? x.child1DnaId == nodeId :
(
profileAdmin.Node == 1 || profileAdmin.Node == 0
)
? x.rootDnaId == nodeId : true
)
: role == "NORMAL"
? (
profileAdmin.Node == 0 ? x.rootDnaId == nodeId && x.child1DnaId == null :
profileAdmin.Node == 1 ? x.child1DnaId == nodeId && x.child2DnaId == null :
profileAdmin.Node == 2 ? x.child2DnaId == nodeId && x.child3DnaId == null :
profileAdmin.Node == 3 ? x.child3DnaId == nodeId && x.child4DnaId == null :
profileAdmin.Node == 4 ? x.child4DnaId == nodeId :
true
)
: true
)
select x).ToList();
var query = data_search
.Select(x => new
{
Id = x.Id,
CitizenId = x.CitizenId,
Prefix = x.Prefix,
FirstName = x.FirstName,
LastName = x.LastName,
ProfileId = x.PersonId,
Organization = x.Organization,
root = x.root,
rootId = x.rootId,
rootDnaId = x.rootDnaId,
rootShortName = x.rootShortName,
child1 = x.child1,
child1Id = x.child1Id,
child1DnaId = x.child1DnaId,
child1ShortName = x.child1ShortName,
child2 = x.child2,
child2Id = x.child2Id,
child2DnaId = x.child2DnaId,
child2ShortName = x.child2ShortName,
child3 = x.child3,
child3Id = x.child3Id,
child3DnaId = x.child3DnaId,
child3ShortName = x.child3ShortName,
child4 = x.child4,
child4Id = x.child4Id,
child4DnaId = x.child4DnaId,
child4ShortName = x.child4ShortName,
posMasterNo = x.posMasterNo,
posTypeId = x.posTypeId,
posTypeName = x.posTypeName,
posLevelId = x.posLevelId,
posLevelName = x.posLevelName,
Position = x.Position,
PosNo = x.PosNo,
PositionLevel = x.PositionLevel == null ? "" : x.PositionLevel,
PositionType = x.PositionType == null ? "" : x.PositionType,
Salary = x.Salary,
Status = x.Status,
DescriptionSuspend = x.DescriptionSuspend,
StartDateSuspend = x.StartDateSuspend,
EndDateSuspend = x.EndDateSuspend,
Title = x.DisciplineDisciplinary.Title,
OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด
DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด
DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด
profileType = x.profileType,
CreatedAt = x.CreatedAt,
});
bool desc = descending ?? false;
if (!string.IsNullOrEmpty(sortBy))
{
if (sortBy == "title")
{
query = desc ? query.OrderByDescending(x => x.Title)
: query.OrderBy(x => x.Title);
}
else if (sortBy == "prefix" || sortBy == "firstName" || sortBy == "lastName")
{
query = desc ?
query
//.OrderByDescending(x => x.Prefix)
.OrderByDescending(x => x.FirstName)
.ThenByDescending(x => x.LastName) :
query
//.OrderBy(x => x.Prefix)
.OrderBy(x => x.FirstName)
.ThenBy(x => x.LastName);
}
else if (sortBy == "position")
{
query = desc ? query.OrderByDescending(x => x.Position)
: query.OrderBy(x => x.Position);
}
else if (sortBy == "positionType" || sortBy == "positionLevel")
{
query = desc ?
query
.OrderByDescending(x => x.PositionType)
.ThenByDescending(x => x.PositionLevel) :
query
.OrderBy(x => x.PositionType)
.ThenBy(x => x.PositionLevel);
}
else if (sortBy == "organization")
{
query = desc ? query.OrderByDescending(x => x.Organization)
: query.OrderBy(x => x.Organization);
}
else if (sortBy == "startDateSuspend")
{
query = desc ? query.OrderByDescending(x => x.StartDateSuspend)
: query.OrderBy(x => x.StartDateSuspend);
}
else if (sortBy == "endDateSuspend")
{
query = desc ? query.OrderByDescending(x => x.EndDateSuspend)
: query.OrderBy(x => x.EndDateSuspend);
}
else if (sortBy == "descriptionSuspend")
{
query = desc ? query.OrderByDescending(x => x.DescriptionSuspend)
: query.OrderBy(x => x.DescriptionSuspend);
}
else
{
query = query.OrderByDescending(x => x.profileType)
.ThenByDescending(x => x.CreatedAt)
.ThenByDescending(x => x.CitizenId);
}
}
var data = query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
return Success(new { data, total = data_search.Count() });
}
/// <summary>
/// get รายการผู้ถูกพักราชการ
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("{id:guid}")]
public async Task<ActionResult<ResponseObject>> GetByDisciplineSuspend(Guid id)
{
var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_DISCIPLINE_SUSPENDED");
if (getWorkflow == false)
{
var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_DISCIPLINE_SUSPENDED");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
}
var _data = await _context.DisciplineReport_Profiles
.Select(x => new
{
Id = x.Id,
ProfileId = x.PersonId,
CitizenId = x.CitizenId,
Prefix = x.Prefix,
FirstName = x.FirstName,
LastName = x.LastName,
Organization = x.Organization,
root = x.root,
rootId = x.rootId,
rootDnaId = x.rootDnaId,
rootShortName = x.rootShortName,
child1 = x.child1,
child1Id = x.child1Id,
child1DnaId = x.child1DnaId,
child1ShortName = x.child1ShortName,
child2 = x.child2,
child2Id = x.child2Id,
child2DnaId = x.child2DnaId,
child2ShortName = x.child2ShortName,
child3 = x.child3,
child3Id = x.child3Id,
child3DnaId = x.child3DnaId,
child3ShortName = x.child3ShortName,
child4 = x.child4,
child4Id = x.child4Id,
child4DnaId = x.child4DnaId,
child4ShortName = x.child4ShortName,
posMasterNo = x.posMasterNo,
posTypeId = x.posTypeId,
posTypeName = x.posTypeName,
posLevelId = x.posLevelId,
posLevelName = x.posLevelName,
Position = x.Position,
PosNo = x.PosNo,
PositionLevel = x.PositionLevel,
PositionType = x.PositionType,
Salary = x.Salary,
Status = x.Status,
DescriptionSuspend = x.DescriptionSuspend,
StartDateSuspend = x.StartDateSuspend,
EndDateSuspend = x.EndDateSuspend,
Title = x.DisciplineDisciplinary.Title,
OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด
DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด
DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด
})
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
if (_data == null)
return Error(new Exception(GlobalMessages.DataNotFound), (int)StatusCodes.Status404NotFound);
return Success(_data);
}
/// <summary>
/// แก้ไขรายการผู้ถูกพักราชการ
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("{id:guid}")]
public async Task<ActionResult<ResponseObject>> UpdateDisciplineSuspend([FromBody] DisciplineSuspendRequest req, Guid id)
{
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_DISCIPLINE_SUSPENDED");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var data = await _context.DisciplineReport_Profiles.Where(x => x.Id == id).FirstOrDefaultAsync();
if (data == null)
return Error(new Exception(GlobalMessages.DataNotFound), (int)StatusCodes.Status404NotFound);
data.Organization = req.Organization;
data.Position = req.Position;
data.PosNo = req.PosNo;
data.PositionLevel = req.PositionLevel;
data.PositionType = req.PositionType;
data.Salary = req.Salary;
data.DescriptionSuspend = req.DescriptionSuspend;
data.StartDateSuspend = req.StartDateSuspend;
data.EndDateSuspend = req.EndDateSuspend;
data.LastUpdateFullName = FullName ?? "System Administrator";
data.LastUpdateUserId = UserId ?? "";
data.LastUpdatedAt = DateTime.Now;
await _context.SaveChangesAsync();
return Success(data.Id);
}
/// <summary>
/// สั่งรายชื่อไปออกคำสั่งพักราชการ
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
// [HttpPost("report")]
[HttpPut("report/{commandTypeId:length(36)}")]
public async Task<ActionResult<ResponseObject>> PostToReport([FromBody] DisciplineProfileRequest req, Guid commandTypeId)
{
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_DISCIPLINE_SUSPENDED");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
foreach (var item in req.id)
{
var uppdated = await _context.DisciplineReport_Profiles
.FirstOrDefaultAsync(x => x.Id == item);
if (uppdated == null)
continue;
uppdated.CommandTypeId = commandTypeId;
uppdated.Status = "REPORT";
uppdated.LastUpdateFullName = FullName ?? "System Administrator";
uppdated.LastUpdateUserId = UserId ?? "";
uppdated.LastUpdatedAt = DateTime.Now;
}
await _context.SaveChangesAsync();
return Success();
}
}
}