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 placementOfficers = await _context.PlacementOfficers.AsQueryable() .OrderByDescending(x => x.CreatedAt) .Select(p => new { p.Id, Prefix = p.Profile.Prefix == null ? null : p.Profile.Prefix.Name, p.Profile.FirstName, p.Profile.LastName, position = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.Position == null ? null : p.Profile.Position.Name) : (p.Profile.PositionEmployeePosition == null ? null : p.Profile.PositionEmployeePosition.Name), posNo = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.PosNo == null ? null : p.Profile.PosNo.Name) : p.Profile.PosNoEmployee, positionLevel = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.PositionLevel == null ? null : p.Profile.PositionLevel.Name) : (p.Profile.PositionEmployeeLevel == null ? null : p.Profile.PositionEmployeeLevel.Name), p.CreatedAt, p.Organization, p.Reason, p.Status, p.DateStart, p.DateEnd, salary = p.AmountOld, p.PositionTypeOld, p.PositionLevelOld, p.PositionNumberOld, p.OrganizationPositionOld, p.IsActive, }) .ToListAsync(); if (PlacementAdmin == true) placementOfficers.Where(x => x.Status.Trim().ToUpper().Contains("APPROVE")); 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) .Where(x => x.Profile != null) .Select(p => new { p.Id, PrefixId = p.Profile.Prefix == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.Profile.Prefix.Id, Prefix = p.Profile.Prefix == null ? null : p.Profile.Prefix.Name, p.Profile.FirstName, p.Profile.LastName, ProfileId = p.Profile.Id, position = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.Position == null ? null : p.Profile.Position.Name) : (p.Profile.PositionEmployeePosition == null ? null : p.Profile.PositionEmployeePosition.Name), posNo = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.PosNo == null ? null : p.Profile.PosNo.Name) : p.Profile.PosNoEmployee, positionLevel = p.Profile.ProfileType.Trim().ToUpper().Contains("OFFICER") ? (p.Profile.PositionLevel == null ? null : p.Profile.PositionLevel.Name) : (p.Profile.PositionEmployeeLevel == null ? null : p.Profile.PositionEmployeeLevel.Name), organizationOrganization = p.Profile.OrganizationOrganization, p.Reason, p.Status, p.Organization, p.DateStart, p.DateEnd, salary = p.AmountOld, p.CreatedAt, p.PositionTypeOld, p.PositionLevelOld, p.PositionNumberOld, p.OrganizationPositionOld, Avatar = p.Profile.Avatar == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.Profile.Avatar.Id, }) .FirstOrDefaultAsync(); if (data == null) return Error(GlobalMessages.DataNotFound, 404); var _data = new { data.Id, data.PrefixId, data.Prefix, data.FirstName, data.LastName, data.ProfileId, data.position, data.posNo, data.positionLevel, data.organizationOrganization, data.Reason, data.Status, data.Organization, data.DateStart, data.DateEnd, data.salary, data.CreatedAt, data.PositionTypeOld, data.PositionLevelOld, data.PositionNumberOld, data.OrganizationPositionOld, 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] PlacementAddProfileRequest req) { var placementOfficer = new PlacementOfficer { // Profile = profile, Organization = Request.Form.ContainsKey("Organization") ? Request.Form["Organization"] : "", Reason = Request.Form.ContainsKey("Reason") ? Request.Form["Reason"] : "", // Date = req.Date, // AmountOld = profile.Salaries.Count() == 0 ? null : profile.Salaries.OrderByDescending(x => x.Order).FirstOrDefault().Amount, // PositionLevelOld = profile.PositionLevel == null ? null : profile.PositionLevel.Name, // PositionTypeOld = profile.PositionType == null ? null : profile.PositionType.Name, // PositionNumberOld = profile.PosNo == null ? null : profile.PosNo.Name, // OrganizationPositionOld = profile.Position == null ? profile.Oc : $"{profile.Position.Name}-{profile.Oc}", Status = "WAITTING", CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; 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); 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; } 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.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(); } } }