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.Domain.Common; using BMA.EHR.Domain.Extensions; using BMA.EHR.Domain.Models.HR; using BMA.EHR.Domain.Models.MetaData; using BMA.EHR.Domain.Models.Notifications; 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.Reflection.Metadata; using System.Security.Claims; using System.Security.Cryptography; using static Microsoft.EntityFrameworkCore.DbLoggerCategory; 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 PermissionRepository _permission; public RetirementDeceasedController(RetirementRepository repository, NotificationRepository repositoryNoti, RetireReportRepository repositoryRetireReport, ApplicationDBContext context, MinIOService documentService, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, PermissionRepository permission) { _repository = repository; _repositoryNoti = repositoryNoti; _repositoryRetireReport = repositoryRetireReport; _context = context; _documentService = documentService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; _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"]; #endregion /// /// list รายการบันทึกเวียนแจ้งการถึงแก่กรรม /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet()] public async Task> GetList() { var getPermission = await _permission.GetPermissionOrgAPIAsync("LIST", "SYS_PASSAWAY", UserId); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } string?[] rootId = jsonData?.result?.rootId ?? null; string?[] child1Id = jsonData?.result?.child1Id ?? null; string?[] child2Id = jsonData?.result?.child2Id ?? null; string?[] child3Id = jsonData?.result?.child3Id ?? null; string?[] child4Id = jsonData?.result?.child4Id ?? null; var retirementDeceaseds = await _context.RetirementDeceaseds.AsQueryable() .OrderByDescending(x => x.CreatedAt) .Where(x => rootId == null ? true : rootId.Contains(x.rootId)) .Where(x => child1Id == null ? true : child1Id.Contains(x.child1Id)) .Where(x => child2Id == null ? true : child2Id.Contains(x.child2Id)) .Where(x => child3Id == null ? true : child3Id.Contains(x.child3Id)) .Where(x => child4Id == null ? true : child4Id.Contains(x.child4Id)) .Select(p => new { p.Id, 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.posLevelName, p.posTypeName, p.CreatedAt, p.IsActive, }) .ToListAsync(); 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.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.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, // Avatar = p.Profile.Avatar == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.Profile.Avatar.Id, }) .FirstOrDefaultAsync(); if (data == null) return Error(GlobalMessages.RetirementDeceasedNotFound, 404); var _data = new { data.Id, data.profileId, data.prefix, data.firstName, data.lastName, 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.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, // Avatar = data.Avatar == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(data.Avatar), }; 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, 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, }; 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.rootShortName = org.result.rootShortName; retirementDeceased.child1 = org.result.child1; retirementDeceased.child1Id = org.result.child1Id; retirementDeceased.child1ShortName = org.result.child1ShortName; retirementDeceased.child2 = org.result.child2; retirementDeceased.child2Id = org.result.child2Id; retirementDeceased.child2ShortName = org.result.child2ShortName; retirementDeceased.child3 = org.result.child3; retirementDeceased.child3Id = org.result.child3Id; retirementDeceased.child3ShortName = org.result.child3ShortName; retirementDeceased.child4 = org.result.child4; retirementDeceased.child4Id = org.result.child4Id; 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); //await _context.SaveChangesAsync(); 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 = "ถึงแก่กรรม", 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; } // await _context.ProfileSalaries.AddAsync(new ProfileSalary // { // Date = req.Date, // SalaryRef = req.Number, // CommandNo = "-", // SalaryClass = "-", // PosNoEmployee = "-", // CommandTypeName = "-", // SalaryStatus = "DEATH", // Profile = profile, // CreatedFullName = FullName ?? "System Administrator", // CreatedUserId = UserId ?? "", // CreatedAt = DateTime.Now, // LastUpdateFullName = FullName ?? "System Administrator", // LastUpdateUserId = UserId ?? "", // LastUpdatedAt = DateTime.Now, // }); // if (_doc != null) // { // await _context.ProfilePapers.AddAsync(new ProfilePaper // { // Detail = "ถึงแก่กรรม", // CategoryName = "DEATH", // Document = _doc, // Profile = profile, // CreatedFullName = FullName ?? "System Administrator", // CreatedUserId = UserId ?? "", // CreatedAt = DateTime.Now, // LastUpdateFullName = FullName ?? "System Administrator", // LastUpdateUserId = UserId ?? "", // LastUpdatedAt = DateTime.Now, // }); // } // var orgPos = await _context.ProfilePositions // .Include(x => x.Profile) // .ThenInclude(x => x!.Prefix) // .Include(x => x.OrganizationPosition) // .ThenInclude(x => x!.Organization) // .ThenInclude(x => x!.OrganizationOrganization) // .Include(x => x.OrganizationPosition) // .ThenInclude(x => x!.PositionMaster) // .ThenInclude(x => x!.PositionPath) // .Where(x => x.OrganizationPosition!.IsDirector! == true) // .Where(x => x.OrganizationPosition!.Organization!.Id == profile.OcId) // .FirstOrDefaultAsync(); // if (orgPos != null) // { // if (orgPos.Profile != null) // { 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.OrganizationName, 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, }); // } // } await _context.SaveChangesAsync(); return Success(); } /// /// แก้ไข รายละเอียดบันทึกเวียนแจ้งการถึงแก่กรรม /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("{id:length(36)}")] public async Task> Put([FromForm] RetirementDeceasedRequest req, Guid id) { var updated = await _context.RetirementDeceaseds .Include(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (updated == null) return Error(GlobalMessages.RetirementDeceasedNotFound, 404); if (Request.Form.Files != null && Request.Form.Files.Count != 0) { if (updated.Document != null) await _documentService.DeleteFileAsync(updated.Document.Id); var file = Request.Form.Files[0]; var fileExtension = Path.GetExtension(file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) updated.Document = _doc; } updated.Number = req.Number; updated.Date = req.Date; updated.Location = req.Location; updated.Reason = req.Reason; updated.LastUpdateFullName = FullName ?? "System Administrator"; updated.LastUpdateUserId = UserId ?? ""; updated.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// ลบ รายละเอียดบันทึกเวียนแจ้งการถึงแก่กรรม /// /// Id การถึงแก่กรรม /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("{id:length(36)}")] public async Task> Delete(Guid id) { var deleted = await _context.RetirementDeceaseds.AsQueryable() .Include(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (deleted == null) return Error(GlobalMessages.RetirementDeceasedNotFound, 404); if (deleted.Document != null) await _documentService.DeleteFileAsync(deleted.Document.Id); _context.RetirementDeceaseds.Remove(deleted); await _context.SaveChangesAsync(); return Success(); } /// /// List รายชื่อส่งหนังสือเวียน /// /// Id การถึงแก่กรรม /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("detail/{id:length(36)}")] public async Task> GetDetail(Guid id) { var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_PASSAWAY"); if (getWorkflow == false) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PASSAWAY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } } var data = await _context.RetirementDeceasedNotis.AsQueryable() .Where(x => x.RetirementDeceased.Id == id) .Select(p => new { p.Id, p.CitizenId, p.Prefix, p.FirstName, p.LastName, p.IsSendMail, p.IsSendInbox, p.IsSendNotification, p.OrganizationName, p.PositionName, p.profileId, }) .ToListAsync(); return Success(data); } /// /// เพิ่มรายชื่อส่งหนังสือเวียน /// /// Id การถึงแก่กรรม /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("detail/{id:length(36)}")] public async Task> UpdateDetail([FromBody] RetirementDeceasedAddNotiPersonRequest req, Guid id) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_PASSAWAY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var retirementDeceased = await _context.RetirementDeceaseds.AsQueryable() .Include(x => x.RetirementDeceasedNotis) .FirstOrDefaultAsync(x => x.Id == id); if (retirementDeceased == null) return Error(GlobalMessages.RetirementDeceasedNotFound, 404); foreach (var item in req.Persons) { // var profile = await _context.Profiles.AsQueryable() // .Include(x => x.Prefix) // .Include(x => x.Position) // .FirstOrDefaultAsync(x => x.Id == item.ProfileId); // if (profile == null) // continue; var retirementDeceasedNoti = new RetirementDeceasedNoti { profileId = item.ProfileId, IsSendMail = item.IsSendMail, IsSendInbox = item.IsSendInbox, IsSendNotification = item.IsSendNotification, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; var apiUrl = $"{_configuration["API"]}/org/profile/profileid/position/{item.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) continue; retirementDeceasedNoti.Prefix = org.result.prefix == null ? "" : org.result.prefix; retirementDeceasedNoti.FirstName = org.result.firstName == null ? "" : org.result.firstName; retirementDeceasedNoti.LastName = org.result.lastName == null ? "" : org.result.lastName; retirementDeceasedNoti.CitizenId = org.result.citizenId == null ? "" : org.result.citizenId; retirementDeceasedNoti.PositionName = org.result.position == null ? "" : org.result.position; retirementDeceasedNoti.OrganizationName = (org.result.child4 == null ? "" : org.result.child4 + "/") + (org.result.child3 == null ? "" : org.result.child3 + "/") + (org.result.child2 == null ? "" : org.result.child2 + "/") + (org.result.child1 == null ? "" : org.result.child1 + "/") + (org.result.root == null ? "" : org.result.root); retirementDeceased.RetirementDeceasedNotis.Add(retirementDeceasedNoti); } await _context.SaveChangesAsync(); } return Success(); } /// /// ลบรายชื่อส่งหนังสือเวียน /// /// Id หนังสือเวียน /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("detail/{id:length(36)}")] public async Task> DeleteDetail(Guid id) { var getPermission = await _permission.GetPermissionAPIAsync("DELETE", "SYS_PASSAWAY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var retirementDeceasedNoti = await _context.RetirementDeceasedNotis.AsQueryable() .FirstOrDefaultAsync(x => x.Id == id); if (retirementDeceasedNoti == null) return Error(GlobalMessages.RetirementDeceasedNotiNotFound, 404); _context.RetirementDeceasedNotis.Remove(retirementDeceasedNoti); await _context.SaveChangesAsync(); return Success(); } /// /// Noti ส่งหนังสือเวียน /// /// Id การถึงแก่กรรม /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("noti/{id:length(36)}")] public async Task> NotiDeceased([FromBody] RetirementDeceasedAddNotiPersonRequest req, Guid id) { var items = await _context.RetirementDeceasedNotis.AsQueryable() // .Include(x => x.ReceiveUser) .Include(x => x.RetirementDeceased) // .ThenInclude(x => x.Profile) // .ThenInclude(x => x.Prefix) .Where(x => x.RetirementDeceased.Id == id) .ToListAsync(); var retirementDeceased = await _context.RetirementDeceaseds.AsQueryable() .Include(x => x.DocumentForward) .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (retirementDeceased == null) return Error(GlobalMessages.RetirementDeceasedNotFound, 404); // if (retirementDeceased.DocumentForward == null) // return Error(GlobalMessages.NoFileToUpload, 404); // create command payload var payload_attach = new List(); payload_attach.Add(new PayloadAttachment { name = "หนังสือเวียนถึงแก่กรรม", url = $"{_configuration["APIV2"]}/report/deceased/copy/36/{retirementDeceased.Id}" }); var payload = new CommandPayload() { attachments = payload_attach }; var payload_str = JsonConvert.SerializeObject(payload); foreach (var item in items) { // var profile = item.profileId; // var prefix = item.profileId; var profile = req.Persons.FirstOrDefault(x => x.ProfileId == item.profileId); if (profile != null) { if (item.profileId != null) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(item.profileId), $"หนังสือเวียนถึงแก่กรรมของ {item.RetirementDeceased.prefix}{item.RetirementDeceased.firstName} {item.RetirementDeceased.lastName}", $"แจ้งข่าวการถึงแก่กรรมของ {item.RetirementDeceased.prefix}{item.RetirementDeceased.firstName} {item.RetirementDeceased.lastName}", payload_str, "", profile.IsSendInbox, profile.IsSendMail ); } item.IsSendMail = profile.IsSendMail; item.IsSendInbox = profile.IsSendInbox; item.IsSendNotification = profile.IsSendNotification; } else { if (item.profileId != null) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(item.profileId), $"หนังสือเวียนถึงแก่กรรมของ {item.RetirementDeceased.prefix}{item.RetirementDeceased.firstName} {item.RetirementDeceased.lastName}", $"แจ้งข่าวการถึงแก่กรรมของ {item.RetirementDeceased.prefix}{item.RetirementDeceased.firstName} {item.RetirementDeceased.lastName}", payload_str, "", item.IsSendInbox, item.IsSendMail ); } } } await _context.SaveChangesAsync(); return Success(); } } }