using BMA.EHR.Application.Repositories; using BMA.EHR.Application.Repositories.MessageQueue; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Models.Placement; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Placement.Service.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Swashbuckle.AspNetCore.Annotations; using System.Net.Http.Headers; using System.Security.Claims; namespace BMA.EHR.Placement.Service.Controllers { [Route("api/v{version:apiVersion}/placement/officer")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบช่วยราชการ")] public class PlacementOfficerController : BaseController { private readonly PlacementRepository _repository; private readonly NotificationRepository _repositoryNoti; private readonly ApplicationDBContext _context; private readonly MinIOService _documentService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IConfiguration _configuration; public PlacementOfficerController(PlacementRepository repository, NotificationRepository repositoryNoti, ApplicationDBContext context, MinIOService documentService, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) { _repository = repository; _repositoryNoti = repositoryNoti; _context = context; _documentService = documentService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; } #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 bool? PlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1"); #endregion /// /// list รายการช่วยราชการของ Admin /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet()] public async Task> GetListByAdmin() { var rootId = ""; var child1Id = ""; var child2Id = ""; var child3Id = ""; var child4Id = ""; var apiUrl = $"{_configuration["API"]}org/profile/keycloak/position"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); 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); rootId = org.result.rootId == null ? "" : org.result.rootId; child1Id = org.result.child1Id == null ? "" : org.result.child1Id; child2Id = org.result.child2Id == null ? "" : org.result.child2Id; child3Id = org.result.child3Id == null ? "" : org.result.child3Id; child4Id = org.result.child4Id == null ? "" : org.result.child4Id; var placementOfficers = await _context.PlacementOfficers.AsQueryable() .OrderByDescending(x => x.CreatedAt) .Where(x => PlacementAdmin == true ? true : (rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id)))))) .Select(p => new { p.Id, 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.Reason, p.Status, p.DateStart, p.DateEnd, p.Organization, p.OrganizationPositionOld, p.IsActive, }) .ToListAsync(); return Success(placementOfficers); } } /// /// get รายละเอียดช่วยราชการเจ้าหน้าที่ /// /// Id ช่วยราชการ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{id:length(36)}")] public async Task> GetDetailAdmin(Guid id) { var data = await _context.PlacementOfficers.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.CreatedAt, p.Reason, p.Status, p.DateStart, p.DateEnd, p.Organization, p.OrganizationPositionOld, p.PositionOld, p.OrganizationOld, p.IsActive, }) .FirstOrDefaultAsync(); if (data == null) return Error(GlobalMessages.DataNotFound, 404); return Success(data); } /// /// สร้างช่วยราชการ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost()] public async Task> Post([FromForm] PlacementAddProfileRequest req) { var placementOfficer = new PlacementOfficer { Organization = Request.Form.ContainsKey("Organization") ? Request.Form["Organization"] : "", Reason = Request.Form.ContainsKey("Reason") ? Request.Form["Reason"] : "", Status = "WAITTING", 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.Id}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); 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); placementOfficer.profileId = org.result.profileId; placementOfficer.prefix = org.result.prefix; placementOfficer.firstName = org.result.firstName; placementOfficer.lastName = org.result.lastName; placementOfficer.citizenId = org.result.citizenId; placementOfficer.root = org.result.root; placementOfficer.rootId = org.result.rootId; placementOfficer.rootShortName = org.result.rootShortName; placementOfficer.child1 = org.result.child1; placementOfficer.child1Id = org.result.child1Id; placementOfficer.child1ShortName = org.result.child1ShortName; placementOfficer.child2 = org.result.child2; placementOfficer.child2Id = org.result.child2Id; placementOfficer.child2ShortName = org.result.child2ShortName; placementOfficer.child3 = org.result.child3; placementOfficer.child3Id = org.result.child3Id; placementOfficer.child3ShortName = org.result.child3ShortName; placementOfficer.child4 = org.result.child4; placementOfficer.child4Id = org.result.child4Id; placementOfficer.child4ShortName = org.result.child4ShortName; placementOfficer.posMasterNo = org.result.posMasterNo; placementOfficer.position = org.result.position; placementOfficer.posTypeId = org.result.posTypeId; placementOfficer.posTypeName = org.result.posTypeName; placementOfficer.posLevelId = org.result.posLevelId; placementOfficer.posLevelName = org.result.posLevelName; placementOfficer.PositionOld = org.result.position; placementOfficer.PositionLevelOld = org.result.posLevelName; placementOfficer.PositionTypeOld = org.result.posTypeName; placementOfficer.PositionNumberOld = org.result.nodeShortName + org.result.posMasterNo; placementOfficer.OrganizationOld = (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 + "/"); placementOfficer.OrganizationPositionOld = org.result.position + "-" + placementOfficer.OrganizationOld; } await _context.PlacementOfficers.AddAsync(placementOfficer); await _context.SaveChangesAsync(); return Success(); } /// /// แก้ไขช่วยราชการ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("{id:length(36)}")] public async Task> Put([FromBody] PlacementOfficerEditRequest req, Guid id) { var uppdated = await _context.PlacementOfficers .FirstOrDefaultAsync(x => x.Id == id); if (uppdated == null) return Error(GlobalMessages.PlacementOfficerNotFound, 404); uppdated.PositionNumberOld = req.PositionNumberOld; uppdated.PositionOld = req.PositionOld; uppdated.OrganizationPositionOld = req.OrganizationPositionOld; uppdated.PositionLevelOld = req.PositionLevelOld; uppdated.PositionTypeOld = req.PositionTypeOld; uppdated.AmountOld = req.AmountOld; uppdated.Organization = req.Organization; uppdated.Reason = req.Reason; uppdated.DateStart = req.DateStart; uppdated.DateEnd = req.DateEnd; uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateUserId = UserId ?? ""; uppdated.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// อนุมัติช่วยราชการ /// /// Id ช่วยราชการ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("confirm/{id:length(36)}")] public async Task> AdminConfirm(Guid id) { var uppdated = await _context.PlacementOfficers .FirstOrDefaultAsync(x => x.Id == id); if (uppdated == null) return Error(GlobalMessages.PlacementOfficerNotFound, 404); uppdated.Status = "APPROVE"; uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateUserId = UserId ?? ""; uppdated.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// ลบช่วยราชการ /// /// Id ช่วยราชการ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("{id:length(36)}")] public async Task> Delete(Guid id) { var deleted = await _context.PlacementOfficers.AsQueryable() .FirstOrDefaultAsync(x => x.Id == id); if (deleted == null) return NotFound(); _context.PlacementOfficers.Remove(deleted); await _context.SaveChangesAsync(); return Success(); } /// /// สั่งรายชื่อไปออกคำสั่ง /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("report")] public async Task> PostToReport([FromBody] PlacementProfileRequest req) { foreach (var item in req.Id) { var uppdated = await _context.PlacementOfficers .FirstOrDefaultAsync(x => x.Id == item); if (uppdated == null) continue; uppdated.Status = "REPORT"; uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateUserId = UserId ?? ""; uppdated.LastUpdatedAt = DateTime.Now; } await _context.SaveChangesAsync(); return Success(); } } }