using BMA.EHR.Application.Repositories;
using BMA.EHR.Application.Repositories.MessageQueue;
using BMA.EHR.Application.Repositories.Reports;
using BMA.EHR.Application.Responses;
using BMA.EHR.Application.Responses.Profiles;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Models.Retirement;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Infrastructure.Persistence;
using BMA.EHR.Retirement.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.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
namespace BMA.EHR.Retirement.Service.Controllers
{
[Route("api/v{version:apiVersion}/retirement/deceased")]
[ApiVersion("1.0")]
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("ระบบแจ้งการถึงแก่กรรม")]
public class RetirementDeceasedController : BaseController
{
private readonly RetirementRepository _repository;
private readonly NotificationRepository _repositoryNoti;
private readonly RetireReportRepository _repositoryRetireReport;
private readonly ApplicationDBContext _context;
private readonly MinIOService _documentService;
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly UserProfileRepository _userProfileRepository;
private readonly PermissionRepository _permission;
public RetirementDeceasedController(RetirementRepository repository,
NotificationRepository repositoryNoti,
RetireReportRepository repositoryRetireReport,
ApplicationDBContext context,
MinIOService documentService,
IConfiguration configuration,
IHttpContextAccessor httpContextAccessor,
UserProfileRepository userProfileRepository,
PermissionRepository permission)
{
_repository = repository;
_repositoryNoti = repositoryNoti;
_repositoryRetireReport = repositoryRetireReport;
_context = context;
_documentService = documentService;
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_userProfileRepository = userProfileRepository;
_permission = permission;
}
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
private string? token => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
private string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
#endregion
///
/// list รายการบันทึกเวียนแจ้งการถึงแก่กรรม
///
///
///
/// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
/// ไม่ได้ Login เข้าระบบ
/// เมื่อเกิดข้อผิดพลาดในการทำงาน
[HttpGet()]
public async Task> GetList()
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_PASSAWAY");
var jsonData = JsonConvert.DeserializeObject(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 node = profileAdmin?.Node;
var retirementDeceaseds = await _context.RetirementDeceaseds.AsQueryable()
.OrderByDescending(x => x.CreatedAt)
.Select(p => new
{
p.Id,
p.profileType,
p.citizenId,
p.profileId,
p.prefix,
p.firstName,
p.lastName,
p.root,
p.rootShortName,
p.child1,
p.child1ShortName,
p.child2,
p.child2ShortName,
p.child3,
p.child3ShortName,
p.child4,
p.child4ShortName,
p.posMasterNo,
p.position,
p.PositionExecutiveOld,
p.posLevelName,
p.posTypeName,
p.CreatedAt,
p.IsActive,
p.rootDnaId,
p.child1DnaId,
p.child2DnaId,
p.child3DnaId,
p.child4DnaId,
})
.ToListAsync();
if (role == "OWNER")
{
node = null;
}
if (role == "OWNER" || role == "CHILD")
{
retirementDeceaseds = retirementDeceaseds
.Where(x => node == 4 ? x.child4DnaId == nodeId : (node == 3 ? x.child3DnaId == nodeId : (node == 2 ? x.child2DnaId == nodeId : (node == 1 ? x.child1DnaId == nodeId : (node == 0 ? x.rootDnaId == nodeId : (node == null ? true : true)))))).ToList();
}
else if (role == "BROTHER")
{
retirementDeceaseds = retirementDeceaseds
.Where(x => node == 4 ? x.child3DnaId == nodeId : (node == 3 ? x.child2DnaId == nodeId : (node == 2 ? x.child1DnaId == nodeId : (node == 1 || node == 0 ? x.rootDnaId == nodeId : (node == null ? true : true))))).ToList();
}
else if (role == "ROOT")
{
retirementDeceaseds = retirementDeceaseds
.Where(x => x.rootDnaId == nodeId).ToList();
}
// else if (role == "PARENT")
// {
// retirementDeceaseds = retirementDeceaseds
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementDeceaseds = retirementDeceaseds.Where(x =>
node == 0 ? x.rootDnaId == nodeId && x.child1DnaId == null :
node == 1 ? x.child1DnaId == nodeId && x.child2DnaId == null :
node == 2 ? x.child2DnaId == nodeId && x.child3DnaId == null :
node == 3 ? x.child3DnaId == nodeId && x.child4DnaId == null :
node == 4 ? x.child4DnaId == nodeId :
true
).ToList();
}
return Success(retirementDeceaseds);
}
///
/// get รายละเอียดบันทึกเวียนแจ้งการถึงแก่กรรม
///
/// Id การถึงแก่กรรม
///
///
/// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
/// ไม่ได้ Login เข้าระบบ
/// เมื่อเกิดข้อผิดพลาดในการทำงาน
[HttpGet("{id:length(36)}")]
public async Task> GetDetailByUser(Guid id)
{
var data = await _context.RetirementDeceaseds.AsQueryable()
.Where(x => x.Id == id)
.Select(p => new
{
p.Id,
p.profileId,
p.profileType,
p.prefix,
p.firstName,
p.lastName,
p.root,
p.rootShortName,
p.child1,
p.child1ShortName,
p.child2,
p.child2ShortName,
p.child3,
p.child3ShortName,
p.child4,
p.child4ShortName,
p.posMasterNo,
p.position,
p.PositionExecutiveOld,
p.posLevelName,
p.posTypeName,
p.Number,
p.Date,
p.Location,
p.Reason,
FileName = p.Document == null ? null : p.Document.FileName,
PathName = p.Document == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.Document.Id,
p.IsActive,
p.CreatedAt,
})
.FirstOrDefaultAsync();
if (data == null)
return Error(GlobalMessages.RetirementDeceasedNotFound, 404);
var _data = new
{
data.Id,
data.profileId,
data.prefix,
data.firstName,
data.lastName,
data.profileType,
data.root,
data.rootShortName,
data.child1,
data.child1ShortName,
data.child2,
data.child2ShortName,
data.child3,
data.child3ShortName,
data.child4,
data.child4ShortName,
data.posMasterNo,
data.position,
data.PositionExecutiveOld,
data.posLevelName,
data.posTypeName,
data.Number,
data.Date,
data.Location,
data.Reason,
PathName = data.PathName == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(data.PathName),
data.IsActive,
data.CreatedAt,
};
return Success(_data);
}
///
/// สร้าง รายละเอียดบันทึกเวียนแจ้งการถึงแก่กรรม
///
///
///
/// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
/// ไม่ได้ Login เข้าระบบ
/// เมื่อเกิดข้อผิดพลาดในการทำงาน
[HttpPost()]
public async Task> Post([FromForm] RetirementDeceasedRequest req)
{
// var profile = await _context.Profiles
// .Include(x => x.Prefix)
// .FirstOrDefaultAsync(x => x.Id == req.ProfileId);
// if (profile == null)
// return Error(GlobalMessages.DataNotFound, 404);
// profile.LeaveDate = DateTime.Now;
// profile.IsLeave = true;
// profile.LeaveReason = "DEATH";
var retirementDeceased = new RetirementDeceased
{
// Profile = profile,
Number = req.Number,
profileType = req.profileType.Trim().ToUpper(),
Date = req.Date,
Location = req.Location,
Reason = req.Reason,
IsActive = true,
CreatedFullName = FullName ?? "System Administrator",
CreatedUserId = UserId ?? "",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
};
if (req.profileType.Trim().ToUpper() == "OFFICER")
{
var apiUrl = $"{_configuration["API"]}/org/profile/profileid/position/{req.ProfileId}";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl);
var _res = await client.SendAsync(_req);
var _result = await _res.Content.ReadAsStringAsync();
var org = JsonConvert.DeserializeObject(_result);
if (org == null || org.result == null)
return Error("ไม่พบหน่วยงานของผู้ใช้งานคนนี้", 404);
retirementDeceased.profileId = org.result.profileId;
retirementDeceased.prefix = org.result.prefix;
retirementDeceased.firstName = org.result.firstName;
retirementDeceased.lastName = org.result.lastName;
retirementDeceased.citizenId = org.result.citizenId;
retirementDeceased.root = org.result.root;
retirementDeceased.rootId = org.result.rootId;
retirementDeceased.rootDnaId = org.result.rootDnaId;
retirementDeceased.rootShortName = org.result.rootShortName;
retirementDeceased.child1 = org.result.child1;
retirementDeceased.child1Id = org.result.child1Id;
retirementDeceased.child1DnaId = org.result.child1DnaId;
retirementDeceased.child1ShortName = org.result.child1ShortName;
retirementDeceased.child2 = org.result.child2;
retirementDeceased.child2Id = org.result.child2Id;
retirementDeceased.child2DnaId = org.result.child2DnaId;
retirementDeceased.child2ShortName = org.result.child2ShortName;
retirementDeceased.child3 = org.result.child3;
retirementDeceased.child3Id = org.result.child3Id;
retirementDeceased.child3DnaId = org.result.child3DnaId;
retirementDeceased.child3ShortName = org.result.child3ShortName;
retirementDeceased.child4 = org.result.child4;
retirementDeceased.child4Id = org.result.child4Id;
retirementDeceased.child4DnaId = org.result.child4DnaId;
retirementDeceased.child4ShortName = org.result.child4ShortName;
retirementDeceased.posMasterNo = org.result.posMasterNo;
retirementDeceased.position = org.result.position;
retirementDeceased.PositionExecutiveOld = org.result.posExecutiveName;
retirementDeceased.positionExecutiveFieldOld = org.result.positionExecutiveField;
retirementDeceased.positionAreaOld = org.result.positionArea;
retirementDeceased.posTypeId = org.result.posTypeId;
retirementDeceased.posTypeName = $"{org.result.posTypeShortName} {org.result.posTypeName}";
retirementDeceased.posLevelId = org.result.posLevelId;
retirementDeceased.posLevelName = org.result.posLevelName;
}
await _context.RetirementDeceaseds.AddAsync(retirementDeceased);
var _baseAPI = _configuration["API"];
var _apiUrl = $"{_baseAPI}/org/profile/leave/{req.ProfileId}";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _req = new HttpRequestMessage(HttpMethod.Post, _apiUrl);
var _res = await client.PostAsJsonAsync(_apiUrl, new
{
isLeave = true,
leaveReason = retirementDeceased.Reason,
dateLeave = req.Date,
});
var _result = await _res.Content.ReadAsStringAsync();
}
}
else
{
var apiUrl = $"{_configuration["API"]}/org/profile-employee/profileid/position/{req.ProfileId}";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl);
var _res = await client.SendAsync(_req);
var _result = await _res.Content.ReadAsStringAsync();
var org = JsonConvert.DeserializeObject(_result);
if (org == null || org.result == null)
return Error("ไม่พบหน่วยงานของผู้ใช้งานคนนี้", 404);
retirementDeceased.profileId = org.result.profileId;
retirementDeceased.prefix = org.result.prefix;
retirementDeceased.firstName = org.result.firstName;
retirementDeceased.lastName = org.result.lastName;
retirementDeceased.citizenId = org.result.citizenId;
retirementDeceased.root = org.result.root;
retirementDeceased.rootId = org.result.rootId;
retirementDeceased.rootDnaId = org.result.rootDnaId;
retirementDeceased.rootShortName = org.result.rootShortName;
retirementDeceased.child1 = org.result.child1;
retirementDeceased.child1Id = org.result.child1Id;
retirementDeceased.child1DnaId = org.result.child1DnaId;
retirementDeceased.child1ShortName = org.result.child1ShortName;
retirementDeceased.child2 = org.result.child2;
retirementDeceased.child2Id = org.result.child2Id;
retirementDeceased.child2DnaId = org.result.child2DnaId;
retirementDeceased.child2ShortName = org.result.child2ShortName;
retirementDeceased.child3 = org.result.child3;
retirementDeceased.child3Id = org.result.child3Id;
retirementDeceased.child3DnaId = org.result.child3DnaId;
retirementDeceased.child3ShortName = org.result.child3ShortName;
retirementDeceased.child4 = org.result.child4;
retirementDeceased.child4Id = org.result.child4Id;
retirementDeceased.child4DnaId = org.result.child4DnaId;
retirementDeceased.child4ShortName = org.result.child4ShortName;
retirementDeceased.posMasterNo = org.result.posMasterNo;
retirementDeceased.position = org.result.position;
retirementDeceased.posTypeId = org.result.posTypeId;
retirementDeceased.posTypeName = org.result.posTypeName;
retirementDeceased.posLevelId = org.result.posLevelId;
retirementDeceased.posLevelName = org.result.posLevelName;
}
await _context.RetirementDeceaseds.AddAsync(retirementDeceased);
var _baseAPI = _configuration["API"];
var _apiUrl = $"{_baseAPI}/org/profile-employee/leave/{req.ProfileId}";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _req = new HttpRequestMessage(HttpMethod.Post, _apiUrl);
var _res = await client.PostAsJsonAsync(_apiUrl, new
{
isLeave = true,
leaveReason = retirementDeceased.Reason,
dateLeave = req.Date,
});
var _result = await _res.Content.ReadAsStringAsync();
}
}
var _doc = new Domain.Models.Documents.Document();
if (Request.Form.Files != null && Request.Form.Files.Count != 0)
{
var file = Request.Form.Files[0];
var fileExtension = Path.GetExtension(file.FileName);
var doc = await _documentService.UploadFileAsync(file, file.FileName);
_doc = await _context.Documents.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == doc.Id);
if (_doc != null)
retirementDeceased.Document = _doc;
}
//retirementDeceased.RetirementDeceasedNotis.Add(new RetirementDeceasedNoti
//{
// CitizenId = retirementDeceased.citizenId == null ? "" : retirementDeceased.citizenId,
// Prefix = retirementDeceased.prefix == null ? "" : retirementDeceased.prefix,
// FirstName = retirementDeceased.firstName == null ? "" : retirementDeceased.firstName,
// LastName = retirementDeceased.lastName == null ? "" : retirementDeceased.lastName,
// IsSendMail = true,
// IsSendInbox = true,
// IsSendNotification = true,
// OrganizationName = retirementDeceased.root == null ? "" : retirementDeceased.root,
// PositionName = retirementDeceased.position == null ? "" : retirementDeceased.position,
// profileId = req.ProfileId,
// CreatedFullName = FullName ?? "System Administrator",
// CreatedUserId = UserId ?? "",
// CreatedAt = DateTime.Now,
// LastUpdateFullName = FullName ?? "System Administrator",
// LastUpdateUserId = UserId ?? "",
// LastUpdatedAt = DateTime.Now,
//});
var pathUrl = $"{_configuration["API"]}/org/command/find-higher";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _res = await client.PostAsJsonAsync(pathUrl, new
{
persons = new List