using BMA.EHR.Application.Repositories; using BMA.EHR.Application.Repositories.MessageQueue; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Extensions; 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 Newtonsoft.Json.Linq; using Swashbuckle.AspNetCore.Annotations; using System.Net.Http.Headers; using System.Security.Claims; using System.Reflection; using BMA.EHR.Application.Responses.Profiles; namespace BMA.EHR.Placement.Service.Controllers { [Route("api/v{version:apiVersion}/placement/Receive")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบรับโอน")] public class PlacementReceiveController : 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; private readonly UserProfileRepository _userProfileRepository; private readonly PermissionRepository _permission; public PlacementReceiveController(PlacementRepository repository, NotificationRepository repositoryNoti, ApplicationDBContext context, MinIOService documentService, IHttpContextAccessor httpContextAccessor, IConfiguration configuration, UserProfileRepository userProfileRepository, PermissionRepository permiss) { _repository = repository; _repositoryNoti = repositoryNoti; _context = context; _documentService = documentService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; _userProfileRepository = userProfileRepository; _permission = permiss; } #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> GetListByAdmin(string? status = "ALL") { var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_TRANSFER_RECEIVE"); 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 placementReceives = await _context.PlacementReceives.AsQueryable() // .Where(x => rootId == null ? true : rootId.Contains(x.rootOldId)) // .Where(x => child1Id == null ? true : child1Id.Contains(x.child1OldId)) // .Where(x => child2Id == null ? true : child2Id.Contains(x.child2OldId)) // .Where(x => child3Id == null ? true : child3Id.Contains(x.child3OldId)) // .Where(x => child4Id == null ? true : child4Id.Contains(x.child4OldId)) .OrderByDescending(x => x.CreatedAt) .Select(p => new { p.Id, p.prefix, p.firstName, p.lastName, p.citizenId, p.DateOfBirth, p.Status, p.ReportingDate, p.root, p.rootId, p.rootShortName, p.child1, p.child1Id, p.child1ShortName, p.child2, p.child2Id, p.child2ShortName, p.child3, p.child3Id, p.child3ShortName, p.child4, p.child4Id, p.child4ShortName, p.orgRevisionId, p.positionId, p.posMasterNo, p.position, p.positionField, p.posTypeId, p.posTypeName, p.posLevelId, p.posLevelName, p.posmasterId, node = p.root == null ? (int?)null : (p.child1 == null ? 0 : (p.child2 == null ? 1 : (p.child3 == null ? 2 : (p.child4 == null ? 3 : 4)))), nodeName = p.root == null ? null : (p.child1 == null ? p.root : (p.child2 == null ? p.child1 : (p.child3 == null ? p.child2 : (p.child4 == null ? p.child3 : p.child4)))), nodeId = p.rootId == null ? null : (p.child1Id == null ? p.rootId : (p.child2Id == null ? p.child1Id : (p.child3Id == null ? p.child2Id : (p.child4Id == null ? p.child3Id : p.child4Id)))), nodeShortName = p.rootShortName == null ? null : (p.child1ShortName == null ? p.rootShortName : (p.child2ShortName == null ? p.child1ShortName : (p.child3ShortName == null ? p.child2ShortName : (p.child4ShortName == null ? p.child3ShortName : p.child4ShortName)))), p.IsActive, p.Reason, p.EducationOld, p.AmountOld, p.PositionTypeOld, p.PositionLevelOld, p.PositionNumberOld, p.OrganizationPositionOld, p.OrganizationOld, p.rootOld, p.rootOldId, p.rootShortNameOld, p.child1Old, p.child1OldId, p.child1ShortNameOld, p.child2Old, p.child2OldId, p.child2ShortNameOld, p.child3Old, p.child3OldId, p.child3ShortNameOld, p.child4Old, p.child4OldId, p.child4ShortNameOld, p.posMasterNoOld, p.PositionOld, p.PositionExecutiveOld, p.positionExecutiveFieldOld, p.positionAreaOld, p.posTypeOldId, p.posTypeNameOld, p.posLevelOldId, p.posLevelNameOld, p.CreatedAt, p.CreatedUserId, p.profileId, p.rootDnaId, p.child1DnaId, p.child2DnaId, p.child3DnaId, p.child4DnaId, }) .ToListAsync(); if (status != null && status.Trim().ToUpper() != "ALL") placementReceives = placementReceives.Where(x => x.Status.Contains(status.Trim().ToUpper())).ToList(); if (role == "OWNER") { node = null; } if (role == "OWNER" || role == "CHILD") { placementReceives = placementReceives .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)))))) || (x.CreatedUserId == UserId)).ToList(); } else if (role == "BROTHER") { placementReceives = placementReceives .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") { placementReceives = placementReceives .Where(x => (x.rootDnaId == nodeId) || (x.CreatedUserId == UserId)).ToList(); } else if (role == "PARENT") { placementReceives = placementReceives .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); } else if (role == "NORMAL") { placementReceives = placementReceives.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(placementReceives); } /// /// get รายละเอียดรับโอน /// /// Id รับโอน /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{id:length(36)}")] public async Task> GetDetailByUser(Guid id) { var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_TRANSFER_RECEIVE"); if (getWorkflow == false) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } } var data = await _context.PlacementReceives.AsQueryable() .Where(x => x.Id == id) .Select(p => new { p.Id, // ProfileId = p.Profile.Id, p.citizenId, p.prefix, p.firstName, p.lastName, p.DateOfBirth, Gender = p.Gender, p.Nationality, p.Race, Religion = p.Religion, BloodGroup = p.BloodGroup, Relationship = p.Relationship, p.TelephoneNumber, p.Status, p.Amount, p.ReportingDate, p.root, p.rootId, p.rootShortName, p.child1, p.child1Id, p.child1ShortName, p.child2, p.child2Id, p.child2ShortName, p.child3, p.child3Id, p.child3ShortName, p.child4, p.child4Id, p.child4ShortName, p.orgRevisionId, p.positionId, p.posMasterNo, p.position, p.positionField, p.posTypeId, p.posTypeName, p.posLevelId, p.posLevelName, p.CreatedAt, p.Reason, p.EducationOld, p.AmountOld, p.PositionOld, p.PositionExecutiveOld, p.positionExecutiveFieldOld, p.positionAreaOld, p.OrganizationOld, p.PositionTypeOld, p.PositionLevelOld, p.PositionNumberOld, p.OrganizationPositionOld, p.IsActive, p.rootOld, p.rootOldId, p.rootShortNameOld, p.child1Old, p.child1OldId, p.child1ShortNameOld, p.child2Old, p.child2OldId, p.child2ShortNameOld, p.child3Old, p.child3OldId, p.child3ShortNameOld, p.child4Old, p.child4OldId, p.child4ShortNameOld, p.posMasterNoOld, p.posTypeOldId, p.posTypeNameOld, p.posLevelOldId, p.posLevelNameOld, Avatar = p.Avatar == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.Avatar.Id, PlacementReceiveDocs = p.PlacementReceiveDocs.Where(d => d.Document != null).Select(d => new { d.Document.Id, d.Document.FileName }), }) .FirstOrDefaultAsync(); if (data == null) return Error(GlobalMessages.DataNotFound, 404); var placementReceiveDocs = new List(); foreach (var doc in data.PlacementReceiveDocs) { var _doc = new { doc.FileName, PathName = await _documentService.ImagesPath(doc.Id) }; placementReceiveDocs.Add(_doc); } var _data = new { data.Id, // data.ProfileId, data.citizenId, data.prefix, data.firstName, data.lastName, data.DateOfBirth, data.Gender, data.Nationality, data.Race, data.Religion, data.BloodGroup, data.Relationship, data.TelephoneNumber, data.Status, data.Amount, data.ReportingDate, data.root, data.rootId, data.rootShortName, data.child1, data.child1Id, data.child1ShortName, data.child2, data.child2Id, data.child2ShortName, data.child3, data.child3Id, data.child3ShortName, data.child4, data.child4Id, data.child4ShortName, node = data.root == null ? (int?)null : (data.child1 == null ? 0 : (data.child2 == null ? 1 : (data.child3 == null ? 2 : (data.child4 == null ? 3 : 4)))), nodeName = data.root == null ? null : (data.child1 == null ? data.root : (data.child2 == null ? data.child1 : (data.child3 == null ? data.child2 : (data.child4 == null ? data.child3 : data.child4)))), nodeId = data.rootId == null ? null : (data.child1Id == null ? data.rootId : (data.child2Id == null ? data.child1Id : (data.child3Id == null ? data.child2Id : (data.child4Id == null ? data.child3Id : data.child4Id)))), nodeShortName = data.rootShortName == null ? null : (data.child1ShortName == null ? data.rootShortName : (data.child2ShortName == null ? data.child1ShortName : (data.child3ShortName == null ? data.child2ShortName : (data.child4ShortName == null ? data.child3ShortName : data.child4ShortName)))), data.orgRevisionId, data.positionId, data.posMasterNo, data.position, data.positionField, data.posTypeId, data.posTypeName, data.posLevelId, data.posLevelName, data.CreatedAt, data.Reason, data.EducationOld, data.AmountOld, data.PositionOld, data.PositionExecutiveOld, data.positionExecutiveFieldOld, data.positionAreaOld, organizationOld = data.OrganizationOld == "/" || data.OrganizationOld == null ? null : data.OrganizationOld, data.PositionTypeOld, data.PositionLevelOld, data.PositionNumberOld, organizationPositionOld = data.OrganizationPositionOld == "/" || data.OrganizationPositionOld == null ? null : data.OrganizationPositionOld, data.IsActive, data.rootOld, data.rootOldId, data.rootShortNameOld, data.child1Old, data.child1OldId, data.child1ShortNameOld, data.child2Old, data.child2OldId, data.child2ShortNameOld, data.child3Old, data.child3OldId, data.child3ShortNameOld, data.child4Old, data.child4OldId, data.child4ShortNameOld, data.posMasterNoOld, data.posTypeOldId, data.posTypeNameOld, data.posLevelOldId, data.posLevelNameOld, Avatar = data.Avatar == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(data.Avatar), Docs = placementReceiveDocs, }; return Success(_data); } /// /// สร้างรับโอน /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost()] public async Task> Post([FromForm] PlacementReceiveRequest req) { var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var placementReceive = new PlacementReceive { // Profile = profile, citizenId = req.citizenId, prefix = req.prefix, firstName = req.firstName, lastName = req.lastName, DateOfBirth = req.BirthDate, Gender = req.Gender, Nationality = req.Nationality, Race = req.Race, Religion = req.Religion, BloodGroup = req.BloodGroup, Relationship = req.Relationship, TelephoneNumber = req.TelephoneNumber, Status = "WAITTING", CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; var apiUrlCheckCitizen = $"{_configuration["API"]}/org/dotnet/check-citizen"; 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(apiUrlCheckCitizen, new { placementReceive.citizenId }); var _result = await _res.Content.ReadAsStringAsync(); var jsonDataCheckCitizen = JsonConvert.DeserializeObject(_result); if (!_res.IsSuccessStatusCode) throw new Exception(jsonDataCheckCitizen?["message"]?.ToString()); } var avatarUrl = string.Empty; var apiUrl = $"{_configuration["API"]}/org/profile/citizenid/position/{req.citizenId}"; 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) { placementReceive.profileId = org.result.profileId; // placementReceive.prefix = org.result.prefix; // placementReceive.firstName = org.result.firstName; // placementReceive.lastName = org.result.lastName; // placementReceive.citizenId = org.result.citizenId; placementReceive.rootOld = org.result.root; placementReceive.rootOldId = org.result.rootId; placementReceive.rootDnaId = org.result.rootDnaId; placementReceive.rootShortNameOld = org.result.rootShortName; placementReceive.child1Old = org.result.child1; placementReceive.child1OldId = org.result.child1Id; placementReceive.child1DnaId = org.result.child1DnaId; placementReceive.child1ShortNameOld = org.result.child1ShortName; placementReceive.child2Old = org.result.child2; placementReceive.child2OldId = org.result.child2Id; placementReceive.child2DnaId = org.result.child2DnaId; placementReceive.child2ShortNameOld = org.result.child2ShortName; placementReceive.child3Old = org.result.child3; placementReceive.child3OldId = org.result.child3Id; placementReceive.child4DnaId = org.result.child4DnaId; placementReceive.child3ShortNameOld = org.result.child3ShortName; placementReceive.child4Old = org.result.child4; placementReceive.child4OldId = org.result.child4Id; placementReceive.child4DnaId = org.result.child4DnaId; placementReceive.child4ShortNameOld = org.result.child4ShortName; placementReceive.posMasterNoOld = org.result.posMasterNo; placementReceive.posTypeOldId = org.result.posTypeId; placementReceive.posTypeNameOld = org.result.posTypeName; placementReceive.posLevelOldId = org.result.posLevelId; placementReceive.posLevelNameOld = org.result.posLevelName; placementReceive.EducationOld = org.result.education; placementReceive.AmountOld = org.result.Amount; placementReceive.PositionOld = org.result.position; placementReceive.PositionExecutiveOld = org.result.posExecutiveName; placementReceive.positionExecutiveFieldOld = org.result.positionExecutiveField; placementReceive.positionAreaOld = org.result.positionArea; placementReceive.PositionLevelOld = org.result.posLevelName; placementReceive.PositionTypeOld = org.result.posTypeName; placementReceive.PositionNumberOld = org.result.nodeShortName + " " + org.result.posMasterNo; placementReceive.OrganizationOld = (org.result.child4 == null ? "" : org.result.child4 + "\n") + (org.result.child3 == null ? "" : org.result.child3 + "\n") + (org.result.child2 == null ? "" : org.result.child2 + "\n") + (org.result.child1 == null ? "" : org.result.child1 + "\n") + (org.result.root == null ? "" : org.result.root); placementReceive.OrganizationPositionOld = org.result.position + "\n" + (placementReceive.PositionExecutiveOld == null ? "" : (placementReceive.positionExecutiveField == null ? placementReceive.PositionExecutiveOld + "\n" : placementReceive.PositionExecutiveOld + "(" + placementReceive.positionExecutiveField + ")" + "\n")) + placementReceive.OrganizationOld; avatarUrl = org.result.avatarUrl ?? null; } } await _context.PlacementReceives.AddAsync(placementReceive); await _context.SaveChangesAsync(); 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); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) { placementReceive.Avatar = _doc; } } else { if (avatarUrl != null && avatarUrl != "") { IFormFile imageFile = await _documentService.GetImageToFormFileAsync(avatarUrl); var doc = await _documentService.UploadFileAsync(imageFile, imageFile.FileName); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) { placementReceive.Avatar = _doc; } } } await _context.SaveChangesAsync(); return Success(); } /// /// อัพไฟล์เอกสาร /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("upload/{id:length(36)}")] public async Task> PostFile([FromForm] PlacementFileRequest req, Guid id) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var uppdated = await _context.PlacementReceives .Include(x => x.PlacementReceiveDocs) .ThenInclude(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (uppdated == null) return Error(GlobalMessages.PlacementReceiveNotFound, 404); var placementReceiveDocs = new List(); foreach (var doc in uppdated.PlacementReceiveDocs) { if (doc.Document != null) placementReceiveDocs.Add(doc.Document.Id); } _context.PlacementReceiveDocs.RemoveRange(uppdated.PlacementReceiveDocs); await _context.SaveChangesAsync(); foreach (var doc in placementReceiveDocs) { if (doc != null) await _documentService.DeleteFileAsync(doc); } if (Request.Form.Files != null && Request.Form.Files.Count != 0) { foreach (var file in Request.Form.Files) { 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) { var placementReceiveDoc = new PlacementReceiveDoc { PlacementReceive = uppdated, Document = _doc, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.PlacementReceiveDocs.AddAsync(placementReceiveDoc); } } } await _context.SaveChangesAsync(); return Success(); } /// /// เลือกหน่วยงาน /// /// Id รับโอน /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("position/{id:length(36)}")] public async Task> UpdatePositionPlacementReceive([FromBody] PersonSelectPositionReceiveRequest req, Guid id) { var uppdated = await _context.PlacementReceives .FirstOrDefaultAsync(x => x.Id == id); if (uppdated == null) return Error(GlobalMessages.PlacementReceiveNotFound, 404); var apiUrl = $"{_configuration["API"]}/org/find/all"; 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 { node = req.node, nodeId = req.nodeId, }); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return Error("ไม่พบหน่วยงานนี้ในระบบ", 404); uppdated.root = org.result.root; uppdated.rootId = org.result.rootId; uppdated.rootDnaId = org.result.rootDnaId; uppdated.rootShortName = org.result.rootShortName; uppdated.child1 = req.node <= 0 ? null : org.result.child1; uppdated.child1Id = req.node <= 0 ? null : org.result.child1Id; uppdated.child1DnaId = req.node <= 0 ? null : org.result.child1DnaId; uppdated.child1ShortName = req.node <= 0 ? null : org.result.child1ShortName; uppdated.child2 = req.node <= 1 ? null : org.result.child2; uppdated.child2Id = req.node <= 1 ? null : org.result.child2Id; uppdated.child2DnaId = req.node <= 1 ? null : org.result.child2DnaId; uppdated.child2ShortName = req.node <= 1 ? null : org.result.child2ShortName; uppdated.child3 = req.node <= 2 ? null : org.result.child3; uppdated.child3Id = req.node <= 2 ? null : org.result.child3Id; uppdated.child3DnaId = req.node <= 2 ? null : org.result.child3DnaId; uppdated.child3ShortName = req.node <= 2 ? null : org.result.child3ShortName; uppdated.child4 = req.node <= 3 ? null : org.result.child4; uppdated.child4Id = req.node <= 3 ? null : org.result.child4Id; uppdated.child4DnaId = req.node <= 3 ? null : org.result.child4DnaId; uppdated.child4ShortName = req.node <= 3 ? null : org.result.child4ShortName; } // var apiUrlUpdate = $"{_configuration["API"]}/org/pos/officer/master-old/book"; // using (var client = new HttpClient()) // { // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); // client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); // var _resUpdate = await client.PostAsJsonAsync(apiUrlUpdate, new // { // posMasterOldId = uppdated.posmasterId, // posMasterId = req.posmasterId, // profileId = uppdated.profileId, // }); // } uppdated.posmasterId = req.posmasterId; uppdated.node = req.node; uppdated.nodeId = req.nodeId; uppdated.orgRevisionId = req.orgRevisionId; uppdated.positionId = req.positionId; uppdated.posMasterNo = req.posMasterNo; uppdated.position = req.positionName; uppdated.PositionExecutive = req.posExecutiveName; uppdated.positionExecutiveField = req.positionExecutiveField; uppdated.positionArea = req.positionArea; uppdated.positionField = req.positionField; uppdated.posTypeId = req.posTypeId; uppdated.posTypeName = req.posTypeName; uppdated.posLevelId = req.posLevelId; uppdated.posLevelName = req.posLevelName; uppdated.Amount = req.Amount; uppdated.ReportingDate = req.reportingDate; uppdated.Status = "PENDING"; uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateUserId = UserId ?? ""; uppdated.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// แก้ไขรับโอน /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("{id:length(36)}")] public async Task> Put([FromBody] PlacementReceiveEditRequest req, Guid id) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var uppdated = await _context.PlacementReceives .FirstOrDefaultAsync(x => x.Id == id); if (uppdated == null) return Error(GlobalMessages.PlacementReceiveNotFound, 404); var apiUrlCheckCitizen = $"{_configuration["API"]}/org/dotnet/check-citizen"; 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(apiUrlCheckCitizen, new { req.citizenId }); var _result = await _res.Content.ReadAsStringAsync(); var jsonDataCheckCitizen = JsonConvert.DeserializeObject(_result); if (!_res.IsSuccessStatusCode) throw new Exception(jsonDataCheckCitizen?["message"]?.ToString()); } uppdated.Relationship = req.Relationship; uppdated.Religion = req.Religion; uppdated.BloodGroup = req.BloodGroup; uppdated.Gender = req.Gender; uppdated.citizenId = req.citizenId; uppdated.prefix = req.prefix; uppdated.firstName = req.firstName; uppdated.lastName = req.lastName; uppdated.DateOfBirth = req.DateOfBirth; uppdated.Nationality = req.Nationality; uppdated.Race = req.Race; uppdated.TelephoneNumber = req.TelephoneNumber; uppdated.EducationOld = req.EducationOld; uppdated.Reason = req.Reason; uppdated.OrganizationPositionOld = req.OrganizationPositionOld; uppdated.PositionTypeOld = req.PositionTypeOld; uppdated.PositionLevelOld = req.PositionLevelOld; uppdated.PositionNumberOld = req.PositionNumberOld; uppdated.Amount = req.Amount; uppdated.AmountOld = req.AmountOld; 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 getPermission = await _permission.GetPermissionAPIAsync("DELETE", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var deleted = await _context.PlacementReceives.AsQueryable() .Include(x => x.PlacementReceiveDocs) .ThenInclude(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (deleted == null) return NotFound(); var placementReceiveDocs = new List(); foreach (var doc in deleted.PlacementReceiveDocs) { if (doc.Document != null) placementReceiveDocs.Add(doc.Document.Id); } _context.PlacementReceiveDocs.RemoveRange(deleted.PlacementReceiveDocs); await _context.SaveChangesAsync(); _context.PlacementReceives.Remove(deleted); foreach (var doc in placementReceiveDocs) { if (doc != null) await _documentService.DeleteFileAsync(doc); } await _context.SaveChangesAsync(); return Success(); } /// /// สั่งรายชื่อไปออกคำสั่ง /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("report")] public async Task> PostToReport([FromBody] PlacementProfileRequest req) { var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_TRANSFER_RECEIVE"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } foreach (var item in req.Id) { var uppdated = await _context.PlacementReceives .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(); } /// /// หน่วยงานที่ถูกเลือกไปแล้ว /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("use")] public async Task> GetPositionUse() { var position = await _context.PlacementReceives .Where(x => x.posmasterId != null) .Where(x => x.Status != "DONE") .Select(x => x.posmasterId) .ToListAsync(); return Success(position); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-14 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command/report")] public async Task> PostReport([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementReceives .Where(x => req.refIds.Contains(x.Id.ToString())) .ToListAsync(); placementProfiles.ForEach(profile => profile.Status = req.status.Trim().ToUpper()); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-14 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command/report/delete")] public async Task> PostReportDelete([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementReceives .Where(x => req.refIds.Contains(x.Id.ToString())) // .Where(x => x.Status.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.Status = "PENDING"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-14 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementReceives .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { No = r.Sequence.ToString().ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", Education = p.EducationOld == null ? "-" : p.EducationOld, OldOrg = p.OrganizationPositionOld ?? "-", OldOc = (p.PositionOld == null ? "" : $"{p.PositionOld}\n") + (p.PositionExecutiveOld == null ? "" : (p.positionExecutiveFieldOld == null ? $"{p.PositionExecutiveOld}\n" : $"{p.PositionExecutiveOld}({p.positionExecutiveFieldOld})\n")) + (p.child4Old == null ? "" : $"{p.child4Old}\n") + (p.child3Old == null ? "" : $"{p.child3Old}\n") + (p.child2Old == null ? "" : $"{p.child2Old}\n") + (p.child1Old == null ? "" : $"{p.child1Old}\n") + (p.rootOld == null ? "" : $"{p.rootOld}"), OldPositionType = p.PositionTypeOld ?? "-", OldPositionLevel = p.PositionLevelOld ?? "-", OldSalary = p.AmountOld == null ? "-" : p.AmountOld.Value.ToNumericNoDecimalText().ToThaiNumber(), NewOc = (p.position == null ? "" : $"{p.position}\n") + (p.PositionExecutive == null ? "" : (p.positionExecutiveField == null ? $"{p.PositionExecutive}\n" : $"{p.PositionExecutive}({p.positionExecutiveField})\n")) + (p.child4 == null ? "" : $"{p.child4}\n") + (p.child3 == null ? "" : $"{p.child3}\n") + (p.child2 == null ? "" : $"{p.child2}\n") + (p.child1 == null ? "" : $"{p.child1}\n") + (p.root == null ? "" : $"{p.root}"), NewPositionType = p.posTypeName == null ? "-" : p.posTypeName, NewPositionLevel = p.posLevelName == null ? "-" : p.posLevelName, NewPositionNumber = p.posMasterNo == null ? "-" : p.node == 4 ? $"{p.child4ShortName} {p.posMasterNo}".ToThaiNumber() : p.node == 3 ? $"{p.child3ShortName} {p.posMasterNo}".ToThaiNumber() : p.node == 2 ? $"{p.child2ShortName} {p.posMasterNo}".ToThaiNumber() : p.node == 1 ? $"{p.child1ShortName} {p.posMasterNo}".ToThaiNumber() : p.node == 0 ? $"{p.rootShortName} {p.posMasterNo}".ToThaiNumber() : "", NewSalary = r.Amount == null ? "-" : r.Amount.Value.ToNumericNoDecimalText().ToThaiNumber(), AppointDate = p.ReportingDate == null ? "-" : p.ReportingDate.Value.ToThaiShortDate2().ToThaiNumber(), CommandExcecuteDate = string.IsNullOrEmpty(r.CommandExcecuteDate.ToString()) ? "-" : r.CommandExcecuteDate.Value.ToThaiShortDate2().ToThaiNumber(), RemarkHorizontal = r.RemarkHorizontal == null ? "-" : r.RemarkHorizontal.ToThaiNumber(), RemarkVertical = r.RemarkVertical == null ? "-" : r.RemarkVertical.ToThaiNumber() }).ToList(); var result = new List(); foreach (var r in report_data) { result.Add(r); string? _null = null; if (r.RemarkHorizontal != null && r.RemarkHorizontal != "") { result.Add(new { No = _null, FullName = r.RemarkHorizontal, Education = _null, OldOrg = _null, OldOc = _null, OldPositionType = _null, OldPositionLevel = _null, OldSalary = _null, NewOc = _null, NewPositionType = _null, NewPositionLevel = _null, NewPositionNumber = _null, NewSalary = _null, AppointDate = _null, CommandExcecuteDate = _null, RemarkHorizontal = _null, RemarkVertical = _null, }); } } return Success(result); } catch { throw; } } /// /// ออกคำสั่ง C-PM-14 คำสั่งรับโอนข้าราชการกรุงเทพมหานครสามัญ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command/report/excecute")] public async Task> PostReportExecute([FromBody] ReportExecuteRequest req) { var data = await _context.PlacementReceives .Include(x => x.Avatar) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .ToListAsync(); var resultData = (from p in data join r in req.refIds on p.Id.ToString() equals r.refId select new { bodyProfile = new { rank = string.Empty, prefix = p.prefix == null ? string.Empty : p.prefix, firstName = p.firstName == null ? string.Empty : p.firstName, lastName = p.lastName == null ? string.Empty : p.lastName, citizenId = p.citizenId == null ? string.Empty : p.citizenId, position = p.position == null ? string.Empty : p.position, posLevelId = p.posLevelId == null ? string.Empty : p.posLevelId, posTypeId = p.posTypeId == null ? string.Empty : p.posTypeId, email = (String?)null, phone = p.TelephoneNumber == null ? string.Empty : p.TelephoneNumber, keycloak = string.Empty, isProbation = false, isLeave = false, dateRetire = (DateTime?)null, dateAppoint = r.commandDateAffect, dateStart = r.commandDateAffect, govAgeAbsent = 0, govAgePlus = 0, birthDate = (p.DateOfBirth == null || p.DateOfBirth == DateTime.MinValue) ? (DateTime?)null : p.DateOfBirth, reasonSameDate = (DateTime?)null, ethnicity = p.Race == null ? string.Empty : p.Race, telephoneNumber = (String?)null, nationality = p.Nationality == null ? string.Empty : p.Nationality, gender = p.Gender == null ? string.Empty : p.Gender, relationship = p.Relationship == null ? string.Empty : p.Relationship, religion = p.Religion == null ? string.Empty : p.Religion, bloodGroup = p.BloodGroup == null ? string.Empty : p.BloodGroup, registrationAddress = (String?)null, registrationProvinceId = (String?)null, registrationDistrictId = (String?)null, registrationSubDistrictId = (String?)null, registrationZipCode = (String?)null, currentAddress = (String?)null, currentProvinceId = (String?)null, currentDistrictId = (String?)null, currentSubDistrictId = (String?)null, currentZipCode = (String?)null, amount = r.amount, amountSpecial = r.amountSpecial, objectRefId = p.Avatar != null && p.Avatar?.ObjectRefId != null ? p.Avatar?.ObjectRefId.ToString("D") : null, }, bodySalarys = new { profileId = p.profileId, amount = r.amount, amountSpecial = r.amountSpecial, positionSalaryAmount = r.positionSalaryAmount, mouthSalaryAmount = r.mouthSalaryAmount, positionExecutive = p.PositionExecutive, positionExecutiveField = p.positionExecutiveField, positionArea = p.positionArea, positionType = p.posTypeName, positionLevel = p.posLevelName, commandId = r.commandId, orgRoot = p.root, orgChild1 = p.child1, orgChild2 = p.child2, orgChild3 = p.child3, orgChild4 = p.child4, commandNo = r.commandNo, commandYear = r.commandYear, posNo = p.posMasterNo?.ToString(), posNoAbb = p.node == 4 ? $"{p.child4ShortName}" : p.node == 3 ? $"{p.child3ShortName}" : p.node == 2 ? $"{p.child2ShortName}" : p.node == 1 ? $"{p.child1ShortName}" : p.node == 0 ? $"{p.rootShortName}" : "", commandDateAffect = r.commandDateAffect, commandDateSign = r.commandDateSign, positionName = p.position, commandCode = r.commandCode, commandName = r.commandName, remark = r.remark, }, bodyPosition = new { posmasterId = p.posmasterId, positionId = p.positionId } }).ToList(); var baseAPIOrg = _configuration["API"]; //var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; var apiUrlOrg = $"{_configuration["API"]}/org/command/excexute/create-officer-profile"; 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(apiUrlOrg, new { data = resultData, }); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { data.ForEach(profile => profile.Status = "DONE"); await _context.SaveChangesAsync(); } } return Success(); } } }