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 Swashbuckle.AspNetCore.Annotations; using System.Security.Claims; using System.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace BMA.EHR.Placement.Service.Controllers { [Route("api/v{version:apiVersion}/placement")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบบรรจุ")] public class PlacementController : 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 PermissionRepository _permission; public PlacementController(PlacementRepository repository, NotificationRepository repositoryNoti, ApplicationDBContext context, MinIOService documentService, IHttpContextAccessor httpContextAccessor, IConfiguration configuration, PermissionRepository permission) { _repository = repository; _repositoryNoti = repositoryNoti; _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"]; private bool? PlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1"); #endregion [HttpGet] public async Task> Get() { var data = await _repository.GetAllAsync(); return Success(data); } [HttpGet("fiscal")] public async Task> GetFiscal() { var data = await _repository.GetAllAsync(); if (data != null) { var _data = data.GroupBy(x => x.Year).Select(x => new { Id = x.FirstOrDefault().Year, Name = x.FirstOrDefault().Year + 543, }).ToList(); return Success(_data); } return Success(data); } [HttpGet("exam/{year}")] public async Task> GetExam(int year) // public async Task> GetExam(int year, int page = 1, int pageSize = 10, string keyword = "") { var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var data = await _context.Placements.Where(x => year > 0 ? (x.Year == year) : (x.Year > 0)) .OrderByDescending(x => x.CreatedAt) .Select(x => new { Id = x.Id, ExamRound = x.Name, ExamOrder = x.Round, FiscalYear = x.Year + 543, NumberOfCandidates = x.PlacementProfiles.Count(), ExamTypeValue = x.PlacementType.Id, ExamTypeName = x.PlacementType.Name, AccountStartDate = x.StartDate, AccountEndDate = x.EndDate, AccountExpirationDate = x.EndDate, IsExpired = x.EndDate.Date < DateTime.Now.Date, CreatedAt = x.CreatedAt, }).ToListAsync(); // if (keyword != "") // { // var data_ = data.Where(x => // (x.ExamRound != null && x.ExamRound.Contains(keyword)) || // (x.ExamOrder != null && x.ExamOrder.Contains(keyword)) || // (x.NumberOfCandidates != null && x.NumberOfCandidates.ToString().Contains(keyword))) // .OrderByDescending(x => x.CreatedAt) // .Skip((page - 1) * pageSize) // .Take(pageSize) // .ToList(); // data = data_; // } return Success(data); } [HttpGet("pass/{examId:length(36)}")] public async Task> GetExamByPlacement(Guid examId) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } if (PlacementAdmin == true) { var data = await _context.PlacementProfiles.Where(x => x.Placement.Id == examId).Select(x => new { Id = x.Id, PersonalId = x.Id, Avatar = x.ProfileImg == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.ProfileImg.Id, FullName = $"{x.Prefix}{x.Firstname} {x.Lastname}", Prefix = x.Prefix, Firstname = x.Firstname, Lastname = x.Lastname, IdCard = x.CitizenId, CitizenId = x.CitizenId, ExamNumber = x.ExamNumber, posmasterId = x.posmasterId, root = x.root, rootId = x.rootId, rootShortName = x.rootShortName, child1 = x.child1, child1Id = x.child1Id, child1ShortName = x.child1ShortName, child2 = x.child2, child2Id = x.child2Id, child2ShortName = x.child2ShortName, child3 = x.child3, child3Id = x.child3Id, child3ShortName = x.child3ShortName, child4 = x.child4, child4Id = x.child4Id, child4ShortName = x.child4ShortName, orgRevisionId = x.orgRevisionId, positionId = x.positionId, posMasterNo = x.posMasterNo, positionName = x.positionName, positionField = x.positionField, posTypeId = x.posTypeId, posTypeName = x.posTypeName, posLevelId = x.posLevelId, posLevelName = x.posLevelName, PositionCandidate = x.PositionCandidate == null ? null : x.PositionCandidate.Name, PositionCandidateId = x.PositionCandidate == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionCandidate.Id, ReportingDate = x.ReportingDate, StatusId = x.PlacementStatus, Draft = x.Draft, typeCommand = x.typeCommand, IsOfficer = x.IsOfficer, IsRelief = x.IsRelief, posLevelCandidateId = x.posLevelIdOld != null ? Guid.Parse(x.posLevelIdOld) : (x.PositionLevel == null ? (Guid?)null : x.PositionLevel.Id), posTypeCandidateId = x.posTypeIdOld != null ? Guid.Parse(x.posTypeIdOld) : (x.PositionType == null ? (Guid?)null : x.PositionType.Id), }).OrderBy(x => x.ExamNumber).ToListAsync(); var result = new List(); foreach (var p in data) { var _data = new { p.Id, p.PersonalId, Avatar = p.Avatar == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(p.Avatar), p.FullName, p.Prefix, p.Firstname, p.Lastname, p.IdCard, p.CitizenId, p.ExamNumber, p.posmasterId, 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, 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.orgRevisionId, p.positionId, p.posMasterNo, p.positionName, p.positionField, p.posTypeId, p.posTypeName, p.posLevelId, p.posLevelName, p.PositionCandidate, p.PositionCandidateId, p.ReportingDate, BmaOfficer = p.IsOfficer == true ? "OFFICER" : null, p.StatusId, p.Draft, p.typeCommand, p.IsRelief, p.posLevelCandidateId, p.posTypeCandidateId, }; result.Add(_data); } return Success(result); } else { 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 ", "")); 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); 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; // return Success(new {rootId=rootId,child1Id=child1Id,child2Id=child2Id,child3Id=child3Id,child4Id=child4Id }); var data = await _context.PlacementProfiles .Where(x => x.Placement.Id == examId) .Where(x => x.Draft == true) .Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))) .Select(x => new { Id = x.Id, PersonalId = x.Id, Avatar = x.ProfileImg == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.ProfileImg.Id, FullName = $"{x.Prefix}{x.Firstname} {x.Lastname}", Prefix = x.Prefix, Firstname = x.Firstname, Lastname = x.Lastname, IdCard = x.CitizenId, CitizenId = x.CitizenId, ExamNumber = x.ExamNumber, posmasterId = x.posmasterId, root = x.root, rootId = x.rootId, rootShortName = x.rootShortName, child1 = x.child1, child1Id = x.child1Id, child1ShortName = x.child1ShortName, child2 = x.child2, child2Id = x.child2Id, child2ShortName = x.child2ShortName, child3 = x.child3, child3Id = x.child3Id, child3ShortName = x.child3ShortName, child4 = x.child4, child4Id = x.child4Id, child4ShortName = x.child4ShortName, orgRevisionId = x.orgRevisionId, positionId = x.positionId, posMasterNo = x.posMasterNo, positionName = x.positionName, positionField = x.positionField, posTypeId = x.posTypeId, posTypeName = x.posTypeName, posLevelId = x.posLevelId, posLevelName = x.posLevelName, PositionCandidate = x.PositionCandidate == null ? null : x.PositionCandidate.Name, PositionCandidateId = x.PositionCandidate == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionCandidate.Id, ReportingDate = x.ReportingDate, StatusId = x.PlacementStatus, Draft = x.Draft, typeCommand = x.typeCommand, IsOfficer = x.IsOfficer, IsRelief = x.IsRelief, posLevelCandidateId = x.PositionLevel == null ? (Guid?)null : x.PositionLevel.Id, posTypeCandidateId = x.PositionType == null ? (Guid?)null : x.PositionType.Id, }).OrderBy(x => x.ExamNumber).ToListAsync(); var result = new List(); foreach (var p in data) { var _data = new { p.Id, p.PersonalId, Avatar = p.Avatar == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(p.Avatar), p.FullName, p.Prefix, p.Firstname, p.Lastname, p.IdCard, p.CitizenId, p.ExamNumber, p.posmasterId, 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, 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.orgRevisionId, p.positionId, p.posMasterNo, p.positionName, p.positionField, p.posTypeId, p.posTypeName, p.posLevelId, p.posLevelName, p.PositionCandidate, p.PositionCandidateId, p.ReportingDate, BmaOfficer = p.IsOfficer == true ? "OFFICER" : null, p.StatusId, p.Draft, p.typeCommand, p.IsRelief, p.posLevelCandidateId, p.posTypeCandidateId, }; result.Add(_data); } return Success(result); } } } [HttpGet("personal/{personalId:length(36)}")] public async Task> GetProfileByUser(Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); if (person.IsProperty == null || Newtonsoft.Json.JsonConvert.DeserializeObject>(person.IsProperty).Count() == 0) { var isProperty = await _context.PlacementIsProperties.Select(x => new PersonPropertyRequest { Name = x.Name, Value = false, }).ToListAsync(); person.IsProperty = Newtonsoft.Json.JsonConvert.SerializeObject(isProperty); person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); } var data = await _context.PlacementProfiles.Select(x => new { PersonalId = x.Id, IdCard = x.CitizenId, Prefix = x.Prefix, FullName = $"{x.Prefix}{x.Firstname} {x.Lastname}", Firstname = x.Firstname, Lastname = x.Lastname, Nationality = x.Nationality, Draft = x.Draft, Race = x.Race, DateOfBirth = x.DateOfBirth, Age = x.DateOfBirth == null ? null : x.DateOfBirth.Value.CalculateAgeStrV2(0, 0), Telephone = x.Telephone, PositionCandidate = x.PositionCandidate == null ? null : x.PositionCandidate.Name, PositionCandidateId = x.PositionCandidate == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionCandidate.Id, Gender = x.Gender, Relationship = x.Relationship, BloodGroup = x.BloodGroup, Religion = x.Religion, // Address = $"{x.RegistAddress}" + // (x.RegistSubDistrict == null ? null : " แขวง") + (x.RegistSubDistrict == null ? null : x.RegistSubDistrict.Name) + // (x.RegistDistrict == null ? null : " เขต") + (x.RegistDistrict == null ? null : x.RegistDistrict.Name) + // (x.RegistProvince == null ? null : " จังหวัด") + (x.RegistProvince == null ? null : x.RegistProvince.Name) + // (x.RegistSubDistrict == null ? null : " ") + (x.RegistSubDistrict == null ? null : x.RegistSubDistrict.ZipCode), Education = x.PlacementEducations.Select(p => new { Id = p.Id, EducationLevel = p.EducationLevel == null ? null : p.EducationLevel.Name, EducationLevelId = p.EducationLevel == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.EducationLevel.Id, Institute = p.Institute, Degree = p.Degree, Field = p.Field, Gpa = p.Gpa, Country = p.Country, Duration = p.Duration, Other = p.Other, FundName = p.FundName, DurationYear = p.DurationYear, FinishDate = p.FinishDate, IsDate = p.IsDate, StartDate = p.StartDate, EndDate = p.EndDate, PositionPath = p.PositionPath == null ? null : p.PositionPath.Name, PositionPathId = p.PositionPath == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.PositionPath.Id, IsEducation = p.IsEducation, }), RegistAddress = x.RegistAddress, RegistSubDistrictId = x.RegistSubDistrictId, RegistZipCode = x.RegistZipCode, RegistDistrictId = x.RegistDistrictId, RegistProvinceId = x.RegistProvinceId, CurrentAddress = x.CurrentAddress, CurrentSubDistrictId = x.CurrentSubDistrictId, CurrentZipCode = x.CurrentZipCode, CurrentDistrictId = x.CurrentDistrictId, CurrentProvinceId = x.CurrentProvinceId, RegistSame = x.RegistSame, MarryPrefix = x.MarryPrefix, Couple = x.Marry, MarryFirstName = x.MarryFirstName, MarryLastName = x.MarryLastName, MarryOccupation = x.MarryOccupation, FatherPrefix = x.FatherPrefix, FatherFirstName = x.FatherFirstName, FatherLastName = x.FatherLastName, FatherOccupation = x.FatherOccupation, MotherPrefix = x.MotherPrefix, MotherFirstName = x.MotherFirstName, MotherLastName = x.MotherLastName, MotherOccupation = x.MotherOccupation, Certificates = x.PlacementCertificates.Select(p => new { Id = p.Id, CertificateNo = p.CertificateNo, Issuer = p.Issuer, IssueDate = p.IssueDate, ExpireDate = p.ExpireDate, CertificateType = p.CertificateType, }), PointA = x.PointA, PointB = x.PointB, PointC = x.PointC, PointTotalA = x.PointTotalA, PointTotalB = x.PointTotalB, PointTotalC = x.PointTotalC, Point = x.PointA + x.PointB + x.PointC, PointTotal = x.PointTotalA + x.PointTotalB + x.PointTotalC, ExamNumber = x.ExamNumber, ExamRound = x.ExamRound, Pass = x.Pass, IsRelief = x.IsRelief, IsProperty = x.IsProperty == null ? null : Newtonsoft.Json.JsonConvert.DeserializeObject>(x.IsProperty), BmaOfficer = x.IsOfficer == true ? "OFFICER" : null, PlacementProfileDocs = x.PlacementProfileDocs.Where(d => d.Document != null).Select(d => new { d.Document.Id, d.Document.FileName }), }).FirstOrDefaultAsync(x => x.PersonalId == personalId); if (data == null) return Error(GlobalMessages.DataNotFound, 404); var placementProfileDocs = new List(); foreach (var doc in data.PlacementProfileDocs) { var _doc = new { doc.FileName, PathName = await _documentService.ImagesPath(doc.Id), docId = doc.Id, }; placementProfileDocs.Add(_doc); } var _data = new { data.PersonalId, data.IdCard, data.Prefix, data.FullName, data.Firstname, data.Lastname, data.Draft, data.Nationality, data.Race, data.DateOfBirth, data.Age, data.Telephone, data.PositionCandidate, data.PositionCandidateId, data.Gender, data.Relationship, data.BloodGroup, data.Religion, // data.Address, data.Education, data.RegistAddress, data.RegistSubDistrictId, data.RegistZipCode, data.RegistDistrictId, data.RegistProvinceId, data.CurrentAddress, data.CurrentSubDistrictId, data.CurrentZipCode, data.CurrentDistrictId, data.CurrentProvinceId, data.RegistSame, data.MarryPrefix, data.Couple, data.MarryFirstName, data.MarryLastName, data.MarryOccupation, data.FatherPrefix, data.FatherFirstName, data.FatherLastName, data.FatherOccupation, data.MotherPrefix, data.MotherFirstName, data.MotherLastName, data.MotherOccupation, data.Certificates, data.PointA, data.PointB, data.PointC, data.PointTotalA, data.PointTotalB, data.PointTotalC, data.Point, data.PointTotal, data.ExamNumber, data.ExamRound, data.Pass, data.IsProperty, data.IsRelief, BmaOfficer = data.BmaOfficer, Docs = placementProfileDocs, }; return Success(_data); } [HttpPut("property/{personalId:length(36)}")] public async Task> UpdatePropertyByUser([FromBody] List req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.IsProperty = Newtonsoft.Json.JsonConvert.SerializeObject(req); person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } [HttpGet("pass/stat/{examId:length(36)}")] public async Task> GetDashboardByPlacement(Guid examId) { if (PlacementAdmin == true) { var placement = await _context.Placements .Where(x => x.Id == examId) .Select(x => new { Total = x.PlacementProfiles.Count(), UnContain = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "UN-CONTAIN").Count(), PrepareContain = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "PREPARE-CONTAIN").Count(), Report = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "REPORT").Count(), Done = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "DONE").Count(), Disclaim = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "DISCLAIM").Count(), }).FirstOrDefaultAsync(); if (placement == null) return Error(GlobalMessages.DataNotFound, 404); return Success(placement); } else { 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 ", "")); 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); 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 profileOrg = await _context.Profiles.FirstOrDefaultAsync(x => x.KeycloakId == Guid.Parse(UserId ?? "00000000-0000-0000-0000-000000000000")); // if (profileOrg == null) // return Error(GlobalMessages.DataNotFound, 404); // var ocIdList = _documentService.GetAllIdByRoot(profileOrg.OcId); var placement = await _context.Placements .Where(x => x.Id == examId) .Select(x => new { Total = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Count(), UnContain = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Where(p => p.PlacementStatus.Trim().ToUpper() == "UN-CONTAIN").Count(), PrepareContain = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Where(p => p.PlacementStatus.Trim().ToUpper() == "PREPARE-CONTAIN").Count(), Report = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Where(p => p.PlacementStatus.Trim().ToUpper() == "REPORT").Count(), Done = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Where(p => p.PlacementStatus.Trim().ToUpper() == "DONE").Count(), Disclaim = x.PlacementProfiles.Where(x => x.Draft == true).Where(x => rootId == "" ? true : (child1Id == "" ? x.rootId == rootId : (child2Id == "" ? x.child1Id == child1Id : (child3Id == "" ? x.child2Id == child2Id : (child4Id == "" ? x.child3Id == child3Id : x.child4Id == child4Id))))).Where(p => p.PlacementStatus.Trim().ToUpper() == "DISCLAIM").Count(), }).FirstOrDefaultAsync(); if (placement == null) return Error(GlobalMessages.DataNotFound, 404); return Success(placement); } } } [HttpPost("pass/deferment"), DisableRequestSizeLimit] public async Task> UpdatePersonDeferment([FromForm] PersonDefermentRequest req) { var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var person = await _context.PlacementProfiles.FindAsync(Request.Form.ContainsKey("personalId") ? Guid.Parse(Request.Form["personalId"]) : Guid.Parse("00000000-0000-0000-0000-000000000000")); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.IsRelief = true; person.ReliefReason = Request.Form.ContainsKey("note") ? Request.Form["note"] : ""; person.PlacementStatus = "PREPARE-CONTAIN"; 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); person.ReliefDoc = doc; } person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } [HttpPost("pass/disclaim")] public async Task> UpdatePersonDisclaim([FromBody] PersonDisclaimRequest req) { var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var person = await _context.PlacementProfiles .Include(x => x.OrganizationPosition) .Include(x => x.PositionNumber) .Include(x => x.PositionPath) .Include(x => x.PositionLevel) .Include(x => x.PositionLine) .Include(x => x.PositionPathSide) .Include(x => x.PositionType) .FirstOrDefaultAsync(x => x.Id == req.PersonalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.OrganizationPosition = null; person.PositionNumber = null; person.PositionPath = null; person.PositionLevel = null; person.PositionLine = null; person.PositionPathSide = null; person.PositionType = null; person.Amount = null; person.MouthSalaryAmount = null; person.PositionSalaryAmount = null; person.RecruitDate = null; person.ReportingDate = null; person.RejectReason = req.Note; person.PlacementStatus = "DISCLAIM"; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; person.root = null; person.rootId = null; person.rootShortName = null; person.child1 = null; person.child1Id = null; person.child1ShortName = null; person.child2 = null; person.child2Id = null; person.child2ShortName = null; person.child3 = null; person.child3Id = null; person.child3ShortName = null; person.child4 = null; person.child4Id = null; person.child4ShortName = null; person.orgRevisionId = null; person.posMasterNo = null; person.positionName = null; person.positionField = null; person.posTypeId = null; person.posTypeName = null; person.posLevelId = null; person.posLevelName = null; person.node = null; person.nodeId = null; person.posmasterId = null; person.positionId = null; person.Draft = false; person.typeCommand = null; await _context.SaveChangesAsync(); return Success(); } [HttpGet("pass/deferment/{personalId:length(36)}")] public async Task> GetPersonDeferment(Guid personalId) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var person = await _context.PlacementProfiles.Include(x => x.ReliefDoc).FirstOrDefaultAsync(x => x.Id == personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var data = new { ReliefReason = person.ReliefReason, ReliefDoc = person.ReliefDoc == null ? null : await _documentService.ImagesPath(person.ReliefDoc.Id), }; return Success(data); } [HttpGet("pass/disclaim/{personalId:length(36)}")] public async Task> GetPersonDisclaim(Guid personalId) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var data = new { RejectReason = person.RejectReason, }; return Success(data); } [HttpPost("pass")] public async Task> UpdatePositionByPerson([FromBody] PersonSelectPositionRequest req) { var person = await _context.PlacementProfiles.FindAsync(req.personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); if (person.Draft == true) return Error("ไม่สามารถแก้ไขข้อมูลนี้ได้เนื่องจากเผยแพร่ไปแล้ว"); // person.organizationName = req.organizationName; // person.orgTreeShortName = req.orgTreeShortName; // person.PosPath = req.posPath; // person.PosNumber = req.posNumber; // person.node = req.node; // person.nodeId = req.nodeId; // person.posmasterId = req.posmasterId; // person.positionId = req.positionId; // person.Amount = req.SalaryAmount; // person.MouthSalaryAmount = req.MouthSalaryAmount; // person.PositionSalaryAmount = req.PositionSalaryAmount; // person.RecruitDate = req.ReportingDate; 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); person.root = org.result.root; person.rootId = org.result.rootId; person.rootShortName = org.result.rootShortName; person.child1 = req.node <= 0 ? null : org.result.child1; person.child1Id = req.node <= 0 ? null : org.result.child1Id; person.child1ShortName = req.node <= 0 ? null : org.result.child1ShortName; person.child2 = req.node <= 1 ? null : org.result.child2; person.child2Id = req.node <= 1 ? null : org.result.child2Id; person.child2ShortName = req.node <= 1 ? null : org.result.child2ShortName; person.child3 = req.node <= 2 ? null : org.result.child3; person.child3Id = req.node <= 2 ? null : org.result.child3Id; person.child3ShortName = req.node <= 2 ? null : org.result.child3ShortName; person.child4 = req.node <= 3 ? null : org.result.child4; person.child4Id = req.node <= 3 ? null : org.result.child4Id; person.child4ShortName = req.node <= 3 ? null : org.result.child4ShortName; } person.Draft = false; person.typeCommand = req.typeCommand == null ? null : req.typeCommand.Trim().ToUpper(); person.ReportingDate = req.reportingDate; person.posmasterId = req.posmasterId; person.node = req.node; person.nodeId = req.nodeId; person.orgRevisionId = req.orgRevisionId; person.positionId = req.positionId; person.posMasterNo = req.posMasterNo; person.positionName = req.positionName; person.positionField = req.positionField; person.posTypeId = req.posTypeId; person.posTypeName = req.posTypeName; person.posLevelId = req.posLevelId; person.posLevelName = req.posLevelName; if (person.profileId != null) { apiUrl = $"{_configuration["API"]}/org/profile/profileid/position/{person.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) { person.IsOld = false; } else { person.nodeOld = org.result.node; person.nodeIdOld = org.result.nodeId; person.rootOld = org.result.root; person.rootIdOld = org.result.rootId; person.rootShortNameOld = org.result.rootShortName; person.child1Old = org.result.child1; person.child1IdOld = org.result.child1Id; person.child1ShortNameOld = org.result.child1ShortName; person.child2Old = org.result.child2; person.child2IdOld = org.result.child2Id; person.child2ShortNameOld = org.result.child2ShortName; person.child3Old = org.result.child3; person.child3IdOld = org.result.child3Id; person.child3ShortNameOld = org.result.child3ShortName; person.child4Old = org.result.child4; person.child4IdOld = org.result.child4Id; person.child4ShortNameOld = org.result.child4ShortName; person.posMasterNoOld = org.result.posMasterNo; person.positionNameOld = org.result.position; person.posTypeIdOld = org.result.posTypeId; person.posTypeNameOld = org.result.posTypeName; person.posLevelIdOld = org.result.posLevelId; person.posLevelNameOld = org.result.posLevelName; } } } person.PlacementStatus = "PREPARE-CONTAIN"; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpPut("information/{personalId:length(36)}")] public async Task> UpdateInformation([FromBody] PersonInformationRequest req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.Prefix = req.Prefix; person.Gender = req.Gender; person.Relationship = req.Relationship; person.BloodGroup = req.BloodGroup; person.Religion = req.Religion; person.CitizenId = req.CitizenId; person.Firstname = req.FirstName; person.Lastname = req.LastName; person.Nationality = req.Nationality; person.Race = req.Race; person.DateOfBirth = req.BirthDate; person.Telephone = req.TelephoneNumber; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpPut("address/{personalId:length(36)}")] public async Task> UpdateAddress([FromBody] PersonAddressRequest req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.RegistSubDistrictId = req.RegistrationSubDistrictId; person.RegistZipCode = req.RegistrationZipCode; person.RegistDistrictId = req.RegistrationDistrictId; person.RegistProvinceId = req.RegistrationProvinceId; person.CurrentSubDistrictId = req.CurrentSubDistrictId; person.CurrentZipCode = req.CurrentZipCode; person.CurrentDistrictId = req.CurrentDistrictId; person.CurrentProvinceId = req.CurrentProvinceId; person.CurrentAddress = req.CurrentAddress; person.RegistAddress = req.RegistrationAddress; person.RegistSame = req.RegistrationSame; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpPut("family/{personalId:length(36)}")] public async Task> UpdateFamily([FromBody] PersonFamilyRequest req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.MotherPrefix = req.MotherPrefix; person.FatherPrefix = req.FatherPrefix; person.MarryPrefix = req.CouplePrefix; person.Marry = req.Couple; person.MarryFirstName = req.CoupleFirstName; person.MarryLastName = req.CoupleLastName; // person.MarryLastNameOld = req.CoupleLastNameOld; person.MarryOccupation = req.CoupleCareer; // person.MarryCitizenId = req.CoupleCitizenId; // person.MarryLive = req.CoupleLive; person.FatherFirstName = req.FatherFirstName; person.FatherLastName = req.FatherLastName; person.FatherOccupation = req.FatherCareer; // person.FatherCitizenId = req.FatherCitizenId; // person.FatherLive = req.FatherLive; person.MotherFirstName = req.MotherFirstName; person.MotherLastName = req.MotherLastName; person.MotherOccupation = req.MotherCareer; // person.MotherCitizenId = req.MotherCitizenId; // person.MotherLive = req.MotherLive; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpPost("certificate/{personalId:length(36)}")] public async Task> CreateCertificate([FromBody] PersonCertificateRequest req, Guid personalId) { var person = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .FirstOrDefaultAsync(x => x.Id == personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var data = new PlacementCertificate { PlacementProfile = person, CertificateNo = req.CertificateNo, Issuer = req.Issuer, IssueDate = req.IssueDate, ExpireDate = req.ExpireDate, CertificateType = req.CertificateType, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.PlacementCertificates.AddAsync(data); _context.SaveChanges(); return Success(); } [HttpPut("certificate/{personalId:length(36)}")] public async Task> UpdateCertificate([FromBody] PersonCertificateRequest req, Guid personalId) { var person = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .FirstOrDefaultAsync(x => x.Id == personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var certificate = person.PlacementCertificates.FirstOrDefault(x => x.Id == req.Id); if (certificate == null) return Error(GlobalMessages.CertificateNotFound, 404); certificate.CertificateNo = req.CertificateNo; certificate.Issuer = req.Issuer; certificate.IssueDate = req.IssueDate; certificate.ExpireDate = req.ExpireDate; certificate.CertificateType = req.CertificateType; certificate.LastUpdateFullName = FullName ?? "System Administrator"; certificate.LastUpdateUserId = UserId ?? ""; certificate.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpDelete("certificate/{personalId:length(36)}/{certificateId:length(36)}")] public async Task> DeleteCertificate(Guid personalId, Guid certificateId) { var person = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .FirstOrDefaultAsync(x => x.Id == personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var certificate = person.PlacementCertificates.FirstOrDefault(x => x.Id == certificateId); if (certificate == null) return Error(GlobalMessages.CertificateNotFound, 404); _context.PlacementCertificates.Remove(certificate); _context.SaveChanges(); return Success(); } [HttpPost("education/{personalId:length(36)}")] public async Task> CreateEducation([FromBody] PersonEducationRequest req, Guid personalId) { var profile = await _context.PlacementProfiles.FirstOrDefaultAsync(x => x.Id == personalId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); var educationLevel = await _context.EducationLevels.FirstOrDefaultAsync(x => x.Id == req.EducationLevelId); if (educationLevel == null && req.EducationLevelId != null) return Error(GlobalMessages.DataNotFound, 404); var positionPath = await _context.PositionPaths.FirstOrDefaultAsync(x => x.Id == req.PositionPathId); if (positionPath == null && req.PositionPathId != null) return Error(GlobalMessages.DataNotFound, 404); var data = new PlacementEducation { PlacementProfile = profile, EducationLevel = educationLevel, PositionPath = positionPath, Institute = req.Institute, Degree = req.Degree, Field = req.Field, Gpa = req.Gpa, Country = req.Country, Duration = req.Duration, DurationYear = req.DurationYear, Other = req.Other, FundName = req.FundName, IsDate = req.IsDate, FinishDate = req.FinishDate, StartDate = req.StartDate, EndDate = req.EndDate, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.PlacementEducations.AddAsync(data); await _context.SaveChangesAsync(); return Success(); } [HttpPut("education/{personalId:length(36)}")] public async Task> UpdateEducation([FromBody] PersonEducationRequest req, Guid personalId) { var profile = await _context.PlacementProfiles.FirstOrDefaultAsync(x => x.Id == personalId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); var educationLevel = await _context.EducationLevels.FirstOrDefaultAsync(x => x.Id == req.EducationLevelId); if (educationLevel == null && req.EducationLevelId != null) return Error(GlobalMessages.DataNotFound, 404); var positionPath = await _context.PositionPaths.FirstOrDefaultAsync(x => x.Id == req.PositionPathId); if (positionPath == null && req.PositionPathId != null) return Error(GlobalMessages.DataNotFound, 404); var education = await _context.PlacementEducations.FirstOrDefaultAsync(x => x.Id == req.Id); if (education == null) return Error(GlobalMessages.EducationNotFound, 404); education.EducationLevel = educationLevel; education.PositionPath = positionPath; education.Institute = req.Institute; education.Degree = req.Degree; education.Field = req.Field; education.Gpa = req.Gpa; education.Country = req.Country; education.Duration = req.Duration; education.DurationYear = req.DurationYear; education.Other = req.Other; education.FundName = req.FundName; education.IsDate = req.IsDate; education.FinishDate = req.FinishDate; education.StartDate = req.StartDate; education.EndDate = req.EndDate; education.LastUpdateFullName = FullName ?? "System Administrator"; education.LastUpdateUserId = UserId ?? ""; education.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } [HttpDelete("education/{educationId:length(36)}")] public async Task> DeleteEducation(Guid educationId) { var education = await _context.PlacementEducations.FirstOrDefaultAsync(x => x.Id == educationId); if (education == null) return Error(GlobalMessages.EducationNotFound, 404); _context.PlacementEducations.Remove(education); _context.SaveChanges(); return Success(); } [HttpPut("position/{personalId:length(36)}")] public async Task> UpdatePositionDraft([FromBody] List items, Guid personalId) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var placement = await _context.Placements .FirstOrDefaultAsync(x => x.Id == personalId); if (placement == null) return Error(GlobalMessages.DataNotFound, 404); foreach (var item in items) { var profile = await _context.PlacementProfiles .FirstOrDefaultAsync(x => x.Id == item); if (profile != null) profile.Draft = true; } _context.SaveChanges(); return Success(); } [HttpPost("position/clear/{personalId:length(36)}")] public async Task> UpdatePositionDraft(Guid personalId) { var profile = await _context.PlacementProfiles .Include(x => x.OrganizationPosition) .Include(x => x.PositionNumber) .Include(x => x.PositionPath) .Include(x => x.PositionLevel) .Include(x => x.PositionLine) .Include(x => x.PositionPathSide) .Include(x => x.PositionType) .FirstOrDefaultAsync(x => x.Id == personalId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); profile.root = null; profile.rootId = null; profile.rootShortName = null; profile.child1 = null; profile.child1Id = null; profile.child1ShortName = null; profile.child2 = null; profile.child2Id = null; profile.child2ShortName = null; profile.child3 = null; profile.child3Id = null; profile.child3ShortName = null; profile.child4 = null; profile.child4Id = null; profile.child4ShortName = null; profile.orgRevisionId = null; profile.posMasterNo = null; profile.positionName = null; profile.positionField = null; profile.posTypeId = null; profile.posTypeName = null; profile.posLevelId = null; profile.posLevelName = null; profile.OrganizationPosition = null; profile.PositionNumber = null; profile.PositionPath = null; profile.PositionLevel = null; profile.PositionLine = null; profile.PositionPathSide = null; profile.PositionType = null; profile.Amount = null; profile.MouthSalaryAmount = null; profile.PositionSalaryAmount = null; profile.RecruitDate = null; profile.ReportingDate = null; profile.node = null; profile.nodeId = null; profile.posmasterId = null; profile.positionId = null; profile.Draft = false; profile.typeCommand = null; profile.PlacementStatus = "UN-CONTAIN"; _context.SaveChanges(); return Success(); } [HttpPut("date/update/{personalId:length(36)}")] public async Task> UpdateDateDraft([FromBody] PersonDateRequest req, Guid personalId) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_PLACEMENT_PASS"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var profile = await _context.PlacementProfiles .FirstOrDefaultAsync(x => x.Id == personalId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); profile.ReportingDate = req.Date; _context.SaveChanges(); return Success(); } [HttpGet("user/{personalId:length(36)}")] public async Task> GetUserByOrganization(Guid personalId) { var profile = await _context.Profiles .FirstOrDefaultAsync(x => x.Id == personalId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); var organization = await _context.Organizations .Include(x => x.Parent) .FirstOrDefaultAsync(x => x.Id == profile.OcId); if (organization == null) return Error(GlobalMessages.OrganizationNotFound, 404); var profilePosition = await _context.ProfilePositions .Where(x => x.Profile != null) .Where(x => x.OrganizationPosition != null) .Where(x => x.OrganizationPosition.PositionMaster != null) .Where(x => x.Profile != profile) .Where(x => x.OrganizationPosition.Organization == organization) .Select(x => new { Id = x.Profile.Id, Prefix = x.Profile.Prefix == null ? null : x.Profile.Prefix.Name, FirstName = x.Profile.FirstName, LastName = x.Profile.LastName, CitizenId = x.Profile.CitizenId, Position = x.OrganizationPosition.PositionMaster.PositionPath == null ? "-" : x.OrganizationPosition.PositionMaster.PositionPath.Name, PositionLevel = x.Profile.PositionLevel == null ? "-" : x.Profile.PositionLevel.Name, IsDirector = x.OrganizationPosition.PositionMaster.IsDirector, }) .ToListAsync(); var caregiver = profilePosition.Where(x => x.IsDirector == false).ToList(); var commander = profilePosition.Where(x => x.IsDirector == true).ToList(); if (organization.Parent != null) { var profilePositionHigh = await _context.ProfilePositions .Where(x => x.Profile != null) .Where(x => x.OrganizationPosition != null) .Where(x => x.OrganizationPosition.PositionMaster != null) .Where(x => x.Profile != profile) .Where(x => x.OrganizationPosition.Organization == organization.Parent) .Select(x => new { Id = x.Profile.Id, Prefix = x.Profile.Prefix == null ? null : x.Profile.Prefix.Name, FirstName = x.Profile.FirstName, LastName = x.Profile.LastName, CitizenId = x.Profile.CitizenId, Position = x.Profile.Position == null ? "-" : x.Profile.Position.Name, PositionLevel = x.Profile.PositionLevel == null ? "-" : x.Profile.PositionLevel.Name, IsDirector = x.OrganizationPosition.PositionMaster.IsDirector, }) .ToListAsync(); var chairman = profilePositionHigh.Where(x => x.IsDirector == true).ToList(); return Success(new { caregiver, commander, chairman }); } return Success(new { caregiver, commander, chairman = new List() }); } [HttpGet("file/{docId:length(36)}")] public async Task> GetPathFile(Guid docId) { if (docId == Guid.Parse("00000000-0000-0000-0000-000000000000")) return Error(GlobalMessages.DataNotFound, 404); var path = await _documentService.ImagesPath(docId); return Success(path); } [HttpPut("doc/{personalId:length(36)}")] public async Task> UpdateDoc([FromForm] PlacementFileRequest req, Guid personalId) { var placementProfile = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .FirstOrDefaultAsync(x => x.Id == personalId); if (placementProfile == null) return Error(GlobalMessages.DataNotFound, 404); 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 placementProfileDoc = new PlacementProfileDoc { PlacementProfile = placementProfile, Document = _doc, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.PlacementProfileDocs.AddAsync(placementProfileDoc); } } } _context.SaveChanges(); return Success(); } [HttpDelete("doc/{personalId:length(36)}/{docId:length(36)}")] public async Task> DeleteDoc(Guid personalId, Guid docId) { var person = await _context.PlacementProfiles .Include(x => x.PlacementProfileDocs) .ThenInclude(x => x.Document) .FirstOrDefaultAsync(x => x.Id == personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); var profileDoc = person.PlacementProfileDocs.FirstOrDefault(x => x.Document.Id == docId); if (profileDoc == null) return Error(GlobalMessages.FileNotFoundOnServer, 404); _context.PlacementProfileDocs.RemoveRange(profileDoc); var _docId = profileDoc.Document.Id; await _context.SaveChangesAsync(); await _documentService.DeleteFileAsync(_docId); await _context.SaveChangesAsync(); return Success(); } /// /// หน่วยงานที่ถูกเลือกไปแล้ว /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("use")] public async Task> GetPositionUse() { var position = await _context.PlacementProfiles .Where(x => x.posmasterId != null) .Where(x => x.PlacementStatus != "DONE" && x.PlacementStatus != "REPORT") .Select(x => x.posmasterId) .ToListAsync(); return Success(position); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-01 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("recruit/report")] public async Task> PostReportRecruit([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name != "สอบแข่งขัน") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOINTED") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "REPORT"); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-01 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("recruit/report/delete")] public async Task> PostReportDeleteRecruit([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-01 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("recruit/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportRecruitAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name != "สอบแข่งขัน") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOINTED") .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { Education = p.PlacementEducations == null || p.PlacementEducations.Count == 0 ? "" : p.PlacementEducations.FirstOrDefault().Degree, Seq = r.Sequence.ToString().ToThaiNumber(), CitizenId = r.CitizenId == null ? "-" : r.CitizenId.ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", Oc = p.root == null ? "" : p.root, PositionName = p.positionName == null ? "" : p.positionName, PositionLevel = p.posLevelName == null ? "" : p.posLevelName, PositionType = p.posTypeName == null ? "" : p.posTypeName, PositionNumber = 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() : "", Salary = r.Amount == null ? "0" : r.Amount.Value.ToNumericNoDecimalText().ToThaiNumber().ToThaiNumber(), AppointDate = p.ReportingDate == null ? "" : p.ReportingDate.Value.ToThaiShortDate2().ToThaiNumber(), ExamNumber = p.ExamNumber == null ? "0" : p.ExamNumber.Value.ToString().ToThaiNumber(), PlacementName = $"{p.Placement.Name.ToThaiNumber()} ครั้งที่ {p.Placement.Round.ToThaiNumber()}/{p.Placement.Year.ToThaiYear().ToString().ToThaiNumber()}", RemarkHorizontal = r.RemarkHorizontal, RemarkVertical = r.RemarkVertical, }).ToList(); return Success(report_data); } catch { throw; } } /// /// ออกคำสั่ง C-PM-01 บรรจุและแต่งตั้งผู้สอบแข่งขันได้ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("recruit/report/excecute")] public async Task> PostReportExecuteRecruit([FromBody] ReportExecuteRequest req) { // create new profile foreach (var recv in req.refIds) { // query placement Profile var placementProfile = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .Include(x => x.PlacementEducations) .ThenInclude(x => x.EducationLevel) .FirstOrDefaultAsync(x => x.Id == Guid.Parse(recv.refId)); if (placementProfile == null) continue; /*ข้อมูล Profile ใหม่*/ var apiUrl = $"{_configuration["API"]}/org/profile/all"; var profileId = string.Empty; 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 { rank = string.Empty, prefix = placementProfile.Prefix == null ? string.Empty : placementProfile.Prefix, firstName = placementProfile.Firstname == null ? string.Empty : placementProfile.Firstname, lastName = placementProfile.Lastname == null ? string.Empty : placementProfile.Lastname, citizenId = placementProfile.CitizenId == null ? string.Empty : placementProfile.CitizenId, position = placementProfile.positionName == null ? string.Empty : placementProfile.positionName, posLevelId = placementProfile.posLevelId == null ? string.Empty : placementProfile.posLevelId, posTypeId = placementProfile.posTypeId == null ? string.Empty : placementProfile.posTypeId, email = placementProfile.Email == null ? string.Empty : placementProfile.Email, phone = placementProfile.MobilePhone == null ? string.Empty : placementProfile.MobilePhone, keycloak = string.Empty, isProbation = true, isLeave = false, dateRetire = (DateTime?)null, dateAppoint = recv.commandAffectDate, dateStart = recv.commandAffectDate, govAgeAbsent = 0, govAgePlus = 0, birthDate = placementProfile.DateOfBirth == null ? (DateTime?)null : placementProfile.DateOfBirth, reasonSameDate = (DateTime?)null, ethnicity = placementProfile.Race == null ? string.Empty : placementProfile.Race, telephoneNumber = placementProfile.Telephone == null ? string.Empty : placementProfile.Telephone, nationality = placementProfile.Nationality == null ? string.Empty : placementProfile.Nationality, gender = placementProfile.Gender == null ? string.Empty : placementProfile.Gender, relationship = placementProfile.Relationship == null ? string.Empty : placementProfile.Relationship, religion = placementProfile.Religion == null ? string.Empty : placementProfile.Religion, bloodGroup = string.Empty, registrationAddress = placementProfile.RegistAddress == null ? string.Empty : placementProfile.RegistAddress, registrationProvinceId = (String?)null, registrationDistrictId = (String?)null, registrationSubDistrictId = (String?)null, registrationZipCode = placementProfile.RegistZipCode == null ? string.Empty : placementProfile.RegistZipCode, currentAddress = placementProfile.CurrentAddress == null ? string.Empty : placementProfile.CurrentAddress, currentProvinceId = (String?)null, currentDistrictId = (String?)null, currentSubDistrictId = (String?)null, currentZipCode = placementProfile.CurrentZipCode == null ? string.Empty : placementProfile.CurrentZipCode, }); var _result = await _res.Content.ReadAsStringAsync(); profileId = JsonConvert.DeserializeObject(_result).result; } if (placementProfile.PlacementEducations != null) { var apiUrlEdu = $"{_configuration["API"]}/org/profile/educations"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); foreach (var edu in placementProfile.PlacementEducations) { var _res = await client.PostAsJsonAsync(apiUrlEdu, new { profileId = profileId, country = edu.Country == null ? string.Empty : edu.Country, degree = edu.Degree == null ? string.Empty : edu.Degree, duration = edu.Duration == null ? string.Empty : edu.Duration, durationYear = edu.DurationYear == null ? 0 : edu.DurationYear, field = edu.Field == null ? string.Empty : edu.Field, finishDate = edu.FinishDate == null ? (DateTime?)null : edu.FinishDate, fundName = edu.FundName == null ? string.Empty : edu.FundName, gpa = edu.Gpa == null ? string.Empty : edu.Gpa, institute = edu.Institute == null ? string.Empty : edu.Institute, other = edu.Other == null ? string.Empty : edu.Other, startDate = edu.StartDate == null ? (DateTime?)null : edu.StartDate, endDate = edu.EndDate == null ? (DateTime?)null : edu.EndDate, educationLevel = edu.EducationLevel == null ? string.Empty : edu.EducationLevel.Name, educationLevelId = string.Empty, positionPath = edu.PositionPath == null ? null : edu.PositionPath, positionPathId = string.Empty, isDate = edu.IsDate, isEducation = edu.IsEducation, note = string.Empty, }); var _result = await _res.Content.ReadAsStringAsync(); } } } if (placementProfile.PlacementCertificates != null) { var apiUrlCer = $"{_configuration["API"]}/org/profile/certificate"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); foreach (var cer in placementProfile.PlacementCertificates) { var _res = await client.PostAsJsonAsync(apiUrlCer, new { profileId = profileId, expireDate = cer.ExpireDate == null ? (DateTime?)null : cer.ExpireDate, issueDate = cer.IssueDate == null ? (DateTime?)null : cer.IssueDate, certificateNo = cer.CertificateNo == null ? string.Empty : cer.CertificateNo, certificateType = cer.CertificateType == null ? string.Empty : cer.CertificateType, issuer = cer.Issuer == null ? string.Empty : cer.Issuer, }); var _result = await _res.Content.ReadAsStringAsync(); } } } var apiUrlSalary = $"{_configuration["API"]}/org/profile/salary"; 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(apiUrlSalary, new { profileId = profileId, date = recv.commandAffectDate, amount = placementProfile.Amount, positionSalaryAmount = placementProfile.PositionSalaryAmount, mouthSalaryAmount = placementProfile.MouthSalaryAmount, posNo = placementProfile.posMasterNo == null ? "" : placementProfile.node == 4 ? $"{placementProfile.child4ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 3 ? $"{placementProfile.child3ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 2 ? $"{placementProfile.child2ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 1 ? $"{placementProfile.child1ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 0 ? $"{placementProfile.rootShortName}{placementProfile.posMasterNo}" : "", position = placementProfile.positionName == null ? string.Empty : placementProfile.positionName, positionLine = string.Empty, positionPathSide = string.Empty, positionExecutive = string.Empty, positionType = placementProfile.posTypeName == null ? string.Empty : placementProfile.posTypeName, positionLevel = placementProfile.posLevelName == null ? string.Empty : placementProfile.posLevelName, refCommandNo = $"{recv.commandNo}/{recv.commandYear.ToThaiYear()}", templateDoc = recv.templateDoc, }); var _result = await _res.Content.ReadAsStringAsync(); } var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/pos/report/current"; 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, apiUrlOrg); var _res = await client.PostAsJsonAsync(apiUrlOrg, new { posmasterId = placementProfile.posmasterId, positionId = placementProfile.positionId, profileId = profileId, }); var _result = await _res.Content.ReadAsStringAsync(); } // update placementstatus placementProfile.PlacementStatus = "DONE";//DONE await _context.SaveChangesAsync(); } return Success(); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-02 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("candidate/report")] public async Task> PostReportCandidate([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name != "สอบแข่งขัน") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOINTED") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "REPORT"); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-02 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("candidate/report/delete")] public async Task> PostReportDeleteCandidate([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAI"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-02 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("candidate/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportCandidateAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name != "สอบแข่งขัน") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOINTED") .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { Education = p.PlacementEducations == null || p.PlacementEducations.Count == 0 ? "" : p.PlacementEducations.FirstOrDefault().Degree, Seq = r.Sequence.ToString().ToThaiNumber(), CitizenId = r.CitizenId == null ? "-" : r.CitizenId.ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", Oc = p.root == null ? "" : p.root, PositionName = p.positionName == null ? "" : p.positionName, PositionLevel = p.posLevelName == null ? "" : p.posLevelName, PositionType = p.posTypeName == null ? "" : p.posTypeName, PositionNumber = 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() : "", Salary = r.Amount == null ? "0" : r.Amount.Value.ToNumericNoDecimalText().ToThaiNumber().ToThaiNumber(), AppointDate = p.ReportingDate == null ? "" : p.ReportingDate.Value.ToThaiShortDate2().ToThaiNumber(), ExamNumber = p.ExamNumber == null ? "0" : p.ExamNumber.Value.ToString().ToThaiNumber(), PlacementName = $"{p.Placement.Name.ToThaiNumber()} ครั้งที่ {p.Placement.Round.ToThaiNumber()}/{p.Placement.Year.ToThaiYear().ToString().ToThaiNumber()}", RemarkHorizontal = r.RemarkHorizontal, RemarkVertical = r.RemarkVertical, }).ToList(); return Success(report_data); } catch { throw; } } /// /// ออกคำสั่ง C-PM-02 บรรจุและแต่งตั้งผู้ได้รับคัดเลือก /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("candidate/report/excecute")] public async Task> PostReportExecuteCandidate([FromBody] ReportExecuteRequest req) { // create new profile foreach (var recv in req.refIds) { // query placement Profile var placementProfile = await _context.PlacementProfiles .Include(x => x.PlacementCertificates) .Include(x => x.PlacementEducations) .ThenInclude(x => x.EducationLevel) .FirstOrDefaultAsync(x => x.Id == Guid.Parse(recv.refId)); if (placementProfile == null) continue; /*ข้อมูล Profile ใหม่*/ var apiUrl = $"{_configuration["API"]}/org/profile/all"; var profileId = string.Empty; 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 { rank = string.Empty, prefix = placementProfile.Prefix == null ? string.Empty : placementProfile.Prefix, firstName = placementProfile.Firstname == null ? string.Empty : placementProfile.Firstname, lastName = placementProfile.Lastname == null ? string.Empty : placementProfile.Lastname, citizenId = placementProfile.CitizenId == null ? string.Empty : placementProfile.CitizenId, position = placementProfile.positionName == null ? string.Empty : placementProfile.positionName, posLevelId = placementProfile.posLevelId == null ? string.Empty : placementProfile.posLevelId, posTypeId = placementProfile.posTypeId == null ? string.Empty : placementProfile.posTypeId, email = placementProfile.Email == null ? string.Empty : placementProfile.Email, phone = placementProfile.MobilePhone == null ? string.Empty : placementProfile.MobilePhone, keycloak = string.Empty, isProbation = true, isLeave = false, dateRetire = (DateTime?)null, dateAppoint = recv.commandAffectDate, dateStart = recv.commandAffectDate, govAgeAbsent = 0, govAgePlus = 0, birthDate = placementProfile.DateOfBirth == null ? (DateTime?)null : placementProfile.DateOfBirth, reasonSameDate = (DateTime?)null, ethnicity = placementProfile.Race == null ? string.Empty : placementProfile.Race, telephoneNumber = placementProfile.Telephone == null ? string.Empty : placementProfile.Telephone, nationality = placementProfile.Nationality == null ? string.Empty : placementProfile.Nationality, gender = placementProfile.Gender == null ? string.Empty : placementProfile.Gender, relationship = placementProfile.Relationship == null ? string.Empty : placementProfile.Relationship, religion = placementProfile.Religion == null ? string.Empty : placementProfile.Religion, bloodGroup = string.Empty, registrationAddress = placementProfile.RegistAddress == null ? string.Empty : placementProfile.RegistAddress, registrationProvinceId = (String?)null, registrationDistrictId = (String?)null, registrationSubDistrictId = (String?)null, registrationZipCode = placementProfile.RegistZipCode == null ? string.Empty : placementProfile.RegistZipCode, currentAddress = placementProfile.CurrentAddress == null ? string.Empty : placementProfile.CurrentAddress, currentProvinceId = (String?)null, currentDistrictId = (String?)null, currentSubDistrictId = (String?)null, currentZipCode = placementProfile.CurrentZipCode == null ? string.Empty : placementProfile.CurrentZipCode, }); var _result = await _res.Content.ReadAsStringAsync(); profileId = JsonConvert.DeserializeObject(_result).result; } if (placementProfile.PlacementEducations != null) { var apiUrlEdu = $"{_configuration["API"]}/org/profile/educations"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); foreach (var edu in placementProfile.PlacementEducations) { var _res = await client.PostAsJsonAsync(apiUrlEdu, new { profileId = profileId, country = edu.Country == null ? string.Empty : edu.Country, degree = edu.Degree == null ? string.Empty : edu.Degree, duration = edu.Duration == null ? string.Empty : edu.Duration, durationYear = edu.DurationYear == null ? 0 : edu.DurationYear, field = edu.Field == null ? string.Empty : edu.Field, finishDate = edu.FinishDate == null ? (DateTime?)null : edu.FinishDate, fundName = edu.FundName == null ? string.Empty : edu.FundName, gpa = edu.Gpa == null ? string.Empty : edu.Gpa, institute = edu.Institute == null ? string.Empty : edu.Institute, other = edu.Other == null ? string.Empty : edu.Other, startDate = edu.StartDate == null ? (DateTime?)null : edu.StartDate, endDate = edu.EndDate == null ? (DateTime?)null : edu.EndDate, educationLevel = edu.EducationLevel == null ? string.Empty : edu.EducationLevel.Name, educationLevelId = string.Empty, positionPath = edu.PositionPath == null ? null : edu.PositionPath, positionPathId = string.Empty, isDate = edu.IsDate, isEducation = edu.IsEducation, note = string.Empty, }); var _result = await _res.Content.ReadAsStringAsync(); } } } if (placementProfile.PlacementCertificates != null) { var apiUrlCer = $"{_configuration["API"]}/org/profile/certificate"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); foreach (var cer in placementProfile.PlacementCertificates) { var _res = await client.PostAsJsonAsync(apiUrlCer, new { profileId = profileId, expireDate = cer.ExpireDate == null ? (DateTime?)null : cer.ExpireDate, issueDate = cer.IssueDate == null ? (DateTime?)null : cer.IssueDate, certificateNo = cer.CertificateNo == null ? string.Empty : cer.CertificateNo, certificateType = cer.CertificateType == null ? string.Empty : cer.CertificateType, issuer = cer.Issuer == null ? string.Empty : cer.Issuer, }); var _result = await _res.Content.ReadAsStringAsync(); } } } var apiUrlSalary = $"{_configuration["API"]}/org/profile/salary"; 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(apiUrlSalary, new { profileId = profileId, date = recv.commandAffectDate, amount = placementProfile.Amount, positionSalaryAmount = placementProfile.PositionSalaryAmount, mouthSalaryAmount = placementProfile.MouthSalaryAmount, posNo = placementProfile.posMasterNo == null ? "" : placementProfile.node == 4 ? $"{placementProfile.child4ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 3 ? $"{placementProfile.child3ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 2 ? $"{placementProfile.child2ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 1 ? $"{placementProfile.child1ShortName}{placementProfile.posMasterNo}" : placementProfile.node == 0 ? $"{placementProfile.rootShortName}{placementProfile.posMasterNo}" : "", position = placementProfile.positionName == null ? string.Empty : placementProfile.positionName, positionLine = string.Empty, positionPathSide = string.Empty, positionExecutive = string.Empty, positionType = placementProfile.posTypeName == null ? string.Empty : placementProfile.posTypeName, positionLevel = placementProfile.posLevelName == null ? string.Empty : placementProfile.posLevelName, refCommandNo = $"{recv.commandNo}/{recv.commandYear.ToThaiYear()}", templateDoc = recv.templateDoc, }); var _result = await _res.Content.ReadAsStringAsync(); } var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/pos/report/current"; 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, apiUrlOrg); var _res = await client.PostAsJsonAsync(apiUrlOrg, new { posmasterId = placementProfile.posmasterId, positionId = placementProfile.positionId, profileId = profileId, }); var _result = await _res.Content.ReadAsStringAsync(); } // update placementstatus placementProfile.PlacementStatus = "DONE";//DONE await _context.SaveChangesAsync(); } return Success(); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-03 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("appoint/report")] public async Task> PostReportAppoint([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "แต่งตั้งข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOIN") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "REPORT"); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-03 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("appoint/report/delete")] public async Task> PostReportDeleteAppoint([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-03 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("appoint/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportAppointAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "แต่งตั้งข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOIN") .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { Education = p.PlacementEducations == null || p.PlacementEducations.Count == 0 ? "" : p.PlacementEducations.FirstOrDefault().Degree, Seq = r.Sequence.ToString().ToThaiNumber(), CitizenId = r.CitizenId == null ? "-" : r.CitizenId.ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", OldOc = p.rootOld == null ? "" : p.rootOld, Probation = "", OldPositionName = p.positionNameOld == null ? "" : p.positionNameOld, OldPositionLevel = p.posLevelNameOld == null ? "" : p.posLevelNameOld, OldPositionType = p.posTypeNameOld == null ? "" : p.posTypeNameOld, OldPositionNumber = p.posMasterNoOld == null ? "" : p.nodeOld == "4" ? $"{p.child4ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "3" ? $"{p.child3ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "2" ? $"{p.child2ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "1" ? $"{p.child1ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "0" ? $"{p.rootShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : "", OldSalary = p.AmountOld == null ? "" : p.AmountOld.Value.ToNumericNoDecimalText().ToThaiNumber(), NewOc = p.root == null ? "" : p.root, NewPositionName = p.positionName == null ? "" : p.positionName, NewPositionLevel = p.posLevelName == null ? "" : p.posLevelName, NewPositionType = p.posTypeName == null ? "" : p.posTypeName, 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 = p.Amount == null ? "" : p.Amount.Value.ToNumericNoDecimalText().ToThaiNumber(), AppointDate = p.ReportingDate == null ? "" : p.ReportingDate.Value.ToThaiShortDate2().ToThaiNumber(), RemarkHorizontal = r.RemarkHorizontal, RemarkVertical = r.RemarkVertical }).ToList(); return Success(report_data); } catch { throw; } } /// /// ออกคำสั่ง C-PM-03 แต่งตั้งข้าราชการ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("appoint/report/excecute")] public async Task> PostReportExecuteAppoint([FromBody] ReportExecuteRequest req) { var data = await _context.PlacementProfiles .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 { profileId = p.profileId, date = r.commandAffectDate, amount = r.amount, positionSalaryAmount = r.positionSalaryAmount, mouthSalaryAmount = r.mouthSalaryAmount, posNo = p.posMasterNo == null ? "" : p.node == 4 ? $"{p.child4ShortName}{p.posMasterNo}" : p.node == 3 ? $"{p.child3ShortName}{p.posMasterNo}" : p.node == 2 ? $"{p.child2ShortName}{p.posMasterNo}" : p.node == 1 ? $"{p.child1ShortName}{p.posMasterNo}" : p.node == 0 ? $"{p.rootShortName}{p.posMasterNo}" : "", position = p.positionName, positionLine = "", positionPathSide = "", positionExecutive = "", positionType = p.posTypeName, positionLevel = p.posLevelName, refCommandNo = $"{r.commandNo}/{r.commandYear.ToThaiYear()}", templateDoc = r.templateDoc, posmasterId = p.posmasterId, positionId = p.positionId, }).ToList(); var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; 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.PlacementStatus = "DONE"); await _context.SaveChangesAsync(); } } return Success(); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-04 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("move/report")] public async Task> PostReportMove([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "ย้ายข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "MOVE") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "REPORT"); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-04 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("move/report/delete")] public async Task> PostReportDeleteMove([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-04 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("move/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportMoveAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "แต่งตั้งข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "APPOIN") .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { Education = p.PlacementEducations == null || p.PlacementEducations.Count == 0 ? "" : p.PlacementEducations.FirstOrDefault().Degree, Seq = r.Sequence.ToString().ToThaiNumber(), CitizenId = r.CitizenId == null ? "-" : r.CitizenId.ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", OldOc = p.rootOld == null ? "" : p.rootOld, OldPositionName = p.positionNameOld == null ? "" : p.positionNameOld, OldPositionLevel = p.posLevelNameOld == null ? "" : p.posLevelNameOld, OldPositionType = p.posTypeNameOld == null ? "" : p.posTypeNameOld, OldPositionNumber = p.posMasterNoOld == null ? "" : p.nodeOld == "4" ? $"{p.child4ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "3" ? $"{p.child3ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "2" ? $"{p.child2ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "1" ? $"{p.child1ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "0" ? $"{p.rootShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : "", OldSalary = p.AmountOld == null ? "" : p.AmountOld.Value.ToNumericNoDecimalText().ToThaiNumber(), NewOc = p.root == null ? "" : p.root, NewPositionName = p.positionName == null ? "" : p.positionName, NewPositionLevel = p.posLevelName == null ? "" : p.posLevelName, NewPositionType = p.posTypeName == null ? "" : p.posTypeName, 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(), RemarkHorizontal = r.RemarkHorizontal, RemarkVertical = r.RemarkVertical, }).ToList(); return Success(report_data); } catch { throw; } } /// /// ออกคำสั่ง C-PM-04 ย้ายข้าราชการ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("move/report/excecute")] public async Task> PostReportExecuteMove([FromBody] ReportExecuteRequest req) { var data = await _context.PlacementProfiles .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 { profileId = p.profileId, date = r.commandAffectDate, amount = r.amount, positionSalaryAmount = r.positionSalaryAmount, mouthSalaryAmount = r.mouthSalaryAmount, posNo = p.posMasterNo == null ? "" : p.node == 4 ? $"{p.child4ShortName}{p.posMasterNo}" : p.node == 3 ? $"{p.child3ShortName}{p.posMasterNo}" : p.node == 2 ? $"{p.child2ShortName}{p.posMasterNo}" : p.node == 1 ? $"{p.child1ShortName}{p.posMasterNo}" : p.node == 0 ? $"{p.rootShortName}{p.posMasterNo}" : "", position = p.positionName, positionLine = "", positionPathSide = "", positionExecutive = "", positionType = p.posTypeName, positionLevel = p.posLevelName, refCommandNo = $"{r.commandNo}/{r.commandYear.ToThaiYear()}", templateDoc = r.templateDoc, posmasterId = p.posmasterId, positionId = p.positionId, }).ToList(); var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; 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.PlacementStatus = "DONE"); await _context.SaveChangesAsync(); } } return Success(); } /// /// ส่งรายชื่อออกคำสั่ง C-PM-39 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("slip/report")] public async Task> PostReportSlip([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "เลื่อนข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "SLIP") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "REPORT"); await _context.SaveChangesAsync(); return Success(); } /// /// ลบรายชื่อออกคำสั่ง C-PM-39 /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("slip/report/delete")] public async Task> PostReportDeleteSlip([FromBody] ReportPersonRequest req) { var placementProfiles = await _context.PlacementProfiles .Where(x => req.refIds.Contains(x.Id.ToString())) .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN"); await _context.SaveChangesAsync(); return Success(); } /// /// เอกสารแนบท้าย C-PM-39 /// /// Record Id ของคำสั่ง /// pdf, docx หรือ xlsx /// /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("slip/report/attachment")] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> PostReportSlipAttachment([FromBody] ReportAttachmentRequest req) { try { var report_data = (from p in _context.PlacementProfiles .Include(x => x.Placement) .ThenInclude(x => x.PlacementType) .Where(x => req.refIds.Select(x => x.refId).Contains(x.Id.ToString())) .Where(x => x.Placement!.PlacementType!.Name == "เลื่อนข้าราชการ") .Where(x => x.typeCommand.Trim().ToUpper() == "SLIP") .ToList() join r in req.refIds on p.Id.ToString() equals r.refId orderby r.Sequence select new { Education = p.PlacementEducations == null || p.PlacementEducations.Count == 0 ? "" : p.PlacementEducations.FirstOrDefault().Degree, Seq = r.Sequence.ToString().ToThaiNumber(), CitizenId = r.CitizenId == null ? "-" : r.CitizenId.ToThaiNumber(), FullName = $"{r.Prefix}{r.FirstName} {r.LastName}", OldOc = p.rootOld == null ? "" : p.rootOld, OldPositionName = p.positionNameOld == null ? "" : p.positionNameOld, OldPositionLevel = p.posLevelNameOld == null ? "" : p.posLevelNameOld, OldPositionType = p.posTypeNameOld == null ? "" : p.posTypeNameOld, OldPositionNumber = p.posMasterNoOld == null ? "" : p.nodeOld == "4" ? $"{p.child4ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "3" ? $"{p.child3ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "2" ? $"{p.child2ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "1" ? $"{p.child1ShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : p.nodeOld == "0" ? $"{p.rootShortNameOld}{p.posMasterNoOld}".ToThaiNumber() : "", OldSalary = p.AmountOld == null ? "" : p.AmountOld.Value.ToNumericNoDecimalText().ToThaiNumber(), NewOc = p.root == null ? "" : p.root, NewPositionName = p.positionName == null ? "" : p.positionName, NewPositionLevel = p.posLevelName == null ? "" : p.posLevelName, NewPositionType = p.posTypeName == null ? "" : p.posTypeName, 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(), RemarkHorizontal = r.RemarkHorizontal, RemarkVertical = r.RemarkVertical, }).ToList(); return Success(report_data); } catch { throw; } } /// /// ออกคำสั่ง C-PM-39 เลื่อนข้าราชการ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("slip/report/excecute")] public async Task> PostReportExecuteSlip([FromBody] ReportExecuteRequest req) { var data = await _context.PlacementProfiles .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 { profileId = p.profileId, date = r.commandAffectDate, amount = r.amount, positionSalaryAmount = r.positionSalaryAmount, mouthSalaryAmount = r.mouthSalaryAmount, posNo = p.posMasterNo == null ? "" : p.node == 4 ? $"{p.child4ShortName}{p.posMasterNo}" : p.node == 3 ? $"{p.child3ShortName}{p.posMasterNo}" : p.node == 2 ? $"{p.child2ShortName}{p.posMasterNo}" : p.node == 1 ? $"{p.child1ShortName}{p.posMasterNo}" : p.node == 0 ? $"{p.rootShortName}{p.posMasterNo}" : "", position = p.positionName, positionLine = "", positionPathSide = "", positionExecutive = "", positionType = p.posTypeName, positionLevel = p.posLevelName, refCommandNo = $"{r.commandNo}/{r.commandYear.ToThaiYear()}", templateDoc = r.templateDoc, posmasterId = p.posmasterId, positionId = p.positionId, }).ToList(); var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; 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.PlacementStatus = "DONE"); await _context.SaveChangesAsync(); } } return Success(); } } }