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.MetaData; 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.Security.Cryptography; 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; public PlacementController(PlacementRepository repository, NotificationRepository repositoryNoti, ApplicationDBContext context, MinIOService documentService, IHttpContextAccessor httpContextAccessor) { _repository = repository; _repositoryNoti = repositoryNoti; _context = context; _documentService = documentService; _httpContextAccessor = httpContextAccessor; } #region " Properties " private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value; 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) { 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, }).ToListAsync(); return Success(data); } [HttpGet("pass/{examId:length(36)}")] public async Task> GetExamByPlacement(Guid examId) { if (PlacementAdmin == true) { var data = await _context.PlacementProfiles.Where(x => x.Placement.Id == examId).Select(x => new { PersonalId = x.Id, FullName = x.Prefix == null ? null : x.Prefix.Name + $"{x.Firstname} {x.Lastname}", IdCard = x.CitizenId, ProfilePhoto = x.Id, PositionCandidate = x.PositionCandidate == null ? null : x.PositionCandidate.Name, PositionCandidateId = x.PositionCandidate == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionCandidate.Id, OrganizationName = x.OrganizationPosition == null ? null : (x.OrganizationPosition.Organization == null ? null : (x.OrganizationPosition.Organization.OrganizationOrganization == null ? null : x.OrganizationPosition.Organization.OrganizationOrganization.Name)),//// OrganizationShortName = x.OrganizationPosition == null ? null : (x.OrganizationPosition.Organization == null ? null : (x.OrganizationPosition.Organization.OrganizationShortName == null ? null : x.OrganizationPosition.Organization.OrganizationShortName.Name)),//// PositionNumber = x.PositionNumber == null ? null : x.PositionNumber.Name, PositionPath = x.PositionPath == null ? null : x.PositionPath.Name, ReportingDate = x.ReportingDate, BmaOfficer = x.IsOfficer, StatusId = x.PlacementStatus, Draft = x.Draft, ExamNumber = x.ExamNumber, Deferment = x.IsRelief, ContainDate = x.RecruitDate, OrganizationPositionId = x.OrganizationPosition == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.OrganizationPosition.Id, PosNoId = x.PositionNumber == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionNumber.Id, PositionId = x.PositionPath == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionPath.Id, PositionLevelId = x.PositionLevel == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionLevel.Id, PositionLineId = x.PositionLine == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionLine.Id, PositionPathSideId = x.PositionPathSide == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionPathSide.Id, PositionTypeId = x.PositionType == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionType.Id, SalaryAmount = x.Amount, MouthSalaryAmount = x.MouthSalaryAmount, PositionSalaryAmount = x.PositionSalaryAmount, Avatar = x.ProfileImg == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.ProfileImg.Id, }).OrderBy(x => x.ExamNumber).ToListAsync(); var result = new List(); foreach (var p in data) { var _data = new { p.PersonalId, p.FullName, p.IdCard, p.ProfilePhoto, p.PositionCandidate, p.PositionCandidateId, p.OrganizationName, p.OrganizationShortName, p.PositionNumber, p.PositionPath, p.ReportingDate, BmaOfficer = await _documentService.CheckBmaOfficer(p.IdCard), p.StatusId, p.Draft, p.ExamNumber, p.Deferment, p.ContainDate, p.OrganizationPositionId, p.PosNoId, p.PositionId, p.PositionLevelId, p.PositionLineId, p.PositionPathSideId, p.PositionTypeId, p.SalaryAmount, p.MouthSalaryAmount, p.PositionSalaryAmount, Avatar = p.Avatar == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(p.Avatar), }; result.Add(_data); } return Success(result); } else { 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 == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : profileOrg.OcId); var ocIdList = _documentService.GetAllIdByRoot(profileOrg.OcId); var data = await _context.PlacementProfiles .Where(x => x.Placement.Id == examId) .Where(x => x.OrganizationPosition != null) .Where(x => x.OrganizationPosition.Organization != null) .Where(x => x.Draft == true) .Where(x => ocIdList.Contains(x.OrganizationPosition.Organization.Id)) .Select(x => new { PersonalId = x.Id, FullName = x.Prefix == null ? null : x.Prefix.Name + $"{x.Firstname} {x.Lastname}", IdCard = x.CitizenId, ProfilePhoto = x.Id, PositionCandidate = x.PositionCandidate == null ? null : x.PositionCandidate.Name, PositionCandidateId = x.PositionCandidate == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionCandidate.Id, OrganizationName = x.OrganizationPosition == null ? null : (x.OrganizationPosition.Organization == null ? null : (x.OrganizationPosition.Organization.OrganizationOrganization == null ? null : x.OrganizationPosition.Organization.OrganizationOrganization.Name)),//// OrganizationShortName = x.OrganizationPosition == null ? null : (x.OrganizationPosition.Organization == null ? null : (x.OrganizationPosition.Organization.OrganizationShortName == null ? null : x.OrganizationPosition.Organization.OrganizationShortName.Name)),//// PositionNumber = x.PositionNumber == null ? null : x.PositionNumber.Name, PositionPath = x.PositionPath == null ? null : x.PositionPath.Name, ReportingDate = x.ReportingDate, BmaOfficer = x.IsOfficer, StatusId = x.PlacementStatus, Draft = x.Draft, ExamNumber = x.ExamNumber, Deferment = x.IsRelief, ContainDate = x.RecruitDate, OrganizationPositionId = x.OrganizationPosition == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.OrganizationPosition.Id, PosNoId = x.PositionNumber == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionNumber.Id, PositionId = x.PositionPath == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionPath.Id, PositionLevelId = x.PositionLevel == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionLevel.Id, PositionLineId = x.PositionLine == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionLine.Id, PositionPathSideId = x.PositionPathSide == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionPathSide.Id, PositionTypeId = x.PositionType == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.PositionType.Id, SalaryAmount = x.Amount, MouthSalaryAmount = x.MouthSalaryAmount, PositionSalaryAmount = x.PositionSalaryAmount, }).OrderBy(x => x.ExamNumber).ToListAsync(); var result = new List(); foreach (var p in data) { var _data = new { p.PersonalId, p.FullName, p.IdCard, p.ProfilePhoto, p.PositionCandidate, p.PositionCandidateId, p.OrganizationName, p.OrganizationShortName, p.PositionNumber, p.PositionPath, p.ReportingDate, BmaOfficer = await _documentService.CheckBmaOfficer(p.IdCard), p.StatusId, p.Draft, p.ExamNumber, p.Deferment, p.ContainDate, p.OrganizationPositionId, p.PosNoId, p.PositionId, p.PositionLevelId, p.PositionLineId, p.PositionPathSideId, p.PositionTypeId, p.SalaryAmount, p.MouthSalaryAmount, p.PositionSalaryAmount, }; 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 == null ? null : x.Prefix.Name, PrefixId = x.Prefix == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.Prefix.Id, FullName = x.Prefix == null ? null : x.Prefix.Name + $"{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 == null ? null : x.Gender.Name, GenderId = x.Gender == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.Gender.Id, Relationship = x.Relationship == null ? null : x.Relationship.Name, RelationshipId = x.Relationship == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.Relationship.Id, BloodGroup = x.BloodGroup == null ? null : x.BloodGroup.Name, BloodGroupId = x.BloodGroup == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.BloodGroup.Id, Religion = x.Religion == null ? null : x.Religion.Name, ReligionId = x.Religion == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.Religion.Id, 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, RegistSubDistrict = x.RegistSubDistrict == null ? null : x.RegistSubDistrict.Name, RegistSubDistrictId = x.RegistSubDistrict == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.RegistSubDistrict.Id, RegistZipCode = x.RegistSubDistrict == null ? null : x.RegistSubDistrict.ZipCode, RegistDistrict = x.RegistDistrict == null ? null : x.RegistDistrict.Name, RegistDistrictId = x.RegistDistrict == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.RegistDistrict.Id, RegistProvince = x.RegistProvince == null ? null : x.RegistProvince.Name, RegistProvinceId = x.RegistProvince == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.RegistProvince.Id, CurrentAddress = x.CurrentAddress, CurrentSubDistrict = x.CurrentSubDistrict == null ? null : x.CurrentSubDistrict.Name, CurrentSubDistrictId = x.CurrentSubDistrict == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.CurrentSubDistrict.Id, CurrentZipCode = x.CurrentSubDistrict == null ? null : x.CurrentSubDistrict.ZipCode, CurrentDistrict = x.CurrentDistrict == null ? null : x.CurrentDistrict.Name, CurrentDistrictId = x.CurrentDistrict == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.CurrentDistrict.Id, CurrentProvince = x.CurrentProvince == null ? null : x.CurrentProvince.Name, CurrentProvinceId = x.CurrentProvince == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.CurrentProvince.Id, RegistSame = x.RegistSame, MarryPrefix = x.MarryPrefix == null ? null : x.MarryPrefix.Name, MarryPrefixId = x.MarryPrefix == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.MarryPrefix.Id, Couple = x.Marry, MarryFirstName = x.MarryFirstName, MarryLastName = x.MarryLastName, MarryOccupation = x.MarryOccupation, FatherPrefix = x.FatherPrefix == null ? null : x.FatherPrefix.Name, FatherPrefixId = x.FatherPrefix == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.FatherPrefix.Id, FatherFirstName = x.FatherFirstName, FatherLastName = x.FatherLastName, FatherOccupation = x.FatherOccupation, MotherPrefix = x.MotherPrefix == null ? null : x.MotherPrefix.Name, MotherPrefixId = x.MotherPrefix == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : x.MotherPrefix.Id, 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, IsProperty = x.IsProperty == null ? null : Newtonsoft.Json.JsonConvert.DeserializeObject>(x.IsProperty), BmaOfficer = "", 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.PrefixId, 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.GenderId, data.Relationship, data.RelationshipId, data.BloodGroup, data.BloodGroupId, data.Religion, data.ReligionId, data.Address, data.Education, data.RegistAddress, data.RegistSubDistrict, data.RegistSubDistrictId, data.RegistZipCode, data.RegistDistrict, data.RegistDistrictId, data.RegistProvince, data.RegistProvinceId, data.CurrentAddress, data.CurrentSubDistrict, data.CurrentSubDistrictId, data.CurrentZipCode, data.CurrentDistrict, data.CurrentDistrictId, data.CurrentProvince, data.CurrentProvinceId, data.RegistSame, data.MarryPrefix, data.MarryPrefixId, data.Couple, data.MarryFirstName, data.MarryLastName, data.MarryOccupation, data.FatherPrefix, data.FatherPrefixId, data.FatherFirstName, data.FatherLastName, data.FatherOccupation, data.MotherPrefix, data.MotherPrefixId, 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, BmaOfficer = data.IdCard == null ? null : await _documentService.CheckBmaOfficer(data.IdCard), 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(), Contain = x.PlacementProfiles.Where(p => p.PlacementStatus.Trim().ToUpper() == "CONTAIN").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 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(p => ocIdList.Contains(p.OrganizationPosition.Organization.Id)).Count(), UnContain = x.PlacementProfiles.Where(p => ocIdList.Contains(p.OrganizationPosition.Organization.Id)).Where(p => p.PlacementStatus.Trim().ToUpper() == "UN-CONTAIN").Count(), PrepareContain = x.PlacementProfiles.Where(p => ocIdList.Contains(p.OrganizationPosition.Organization.Id)).Where(p => p.PlacementStatus.Trim().ToUpper() == "PREPARE-CONTAIN").Count(), Contain = x.PlacementProfiles.Where(p => ocIdList.Contains(p.OrganizationPosition.Organization.Id)).Where(p => p.PlacementStatus.Trim().ToUpper() == "CONTAIN").Count(), Disclaim = x.PlacementProfiles.Where(p => ocIdList.Contains(p.OrganizationPosition.Organization.Id)).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 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 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; await _context.SaveChangesAsync(); return Success(); } [HttpGet("pass/deferment/{personalId:length(36)}")] public async Task> GetPersonDeferment(Guid personalId) { 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 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("ไม่สามารถแก้ไขข้อมูลนี้ได้เนื่องจากเผยแพร่ไปแล้ว"); if (req.PosNoId != null) { var save_posNo = await _context.PositionNumbers.FindAsync(req.PosNoId); if (save_posNo == null) return Error(GlobalMessages.PositionPosNoNotFound, 404); person.PositionNumber = save_posNo; var save_orgPosition = await _context.OrganizationPositions.FirstOrDefaultAsync(x => x.PositionNumber == save_posNo); if (save_orgPosition == null) return Error(GlobalMessages.PositionPosNoNotFound, 404); person.OrganizationPosition = save_orgPosition; } if (req.PositionId != null) { var save = await _context.PositionPaths.FindAsync(req.PositionId); if (save == null) return Error(GlobalMessages.PositionPathNotFound, 404); person.PositionPath = save; } if (req.PositionLevelId != null) { var save = await _context.PositionLevels.FindAsync(req.PositionLevelId); if (save == null) return Error(GlobalMessages.PositionLevelNotFound, 404); person.PositionLevel = save; } if (req.PositionLineId != null) { var save = await _context.PositionLines.FindAsync(req.PositionLineId); if (save == null) return Error(GlobalMessages.PositionLineNotFound, 404); person.PositionLine = save; } if (req.PositionPathSideId != null) { var save = await _context.PositionPathSides.FindAsync(req.PositionPathSideId); if (save == null) return Error(GlobalMessages.PositionPathSideNotFound, 404); person.PositionPathSide = save; } if (req.PositionTypeId != null) { var save = await _context.PositionTypes.FindAsync(req.PositionTypeId); if (save == null) return Error(GlobalMessages.PositionTypeNotFound, 404); person.PositionType = save; } person.Draft = false; person.Amount = req.SalaryAmount; person.MouthSalaryAmount = req.MouthSalaryAmount; person.PositionSalaryAmount = req.PositionSalaryAmount; person.RecruitDate = req.ContainDate; person.ReportingDate = req.ContainDate; 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); if (req.PrefixId != null) { var save = await _context.Prefixes .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.PrefixId); if (save == null) return Error(GlobalMessages.PrefixNotFound, 404); person.Prefix = save; } if (req.GenderId != null) { var save = await _context.Genders .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.GenderId); if (save == null) return Error(GlobalMessages.GenderNotFound, 404); person.Gender = save; } if (req.RelationshipId != null) { var save = await _context.Relationships .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.RelationshipId); if (save == null) return Error(GlobalMessages.RelationshipNotFound, 404); person.Relationship = save; } if (req.BloodGroupId != null) { var save = await _context.BloodGroups .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.BloodGroupId); if (save == null) return Error(GlobalMessages.BloodGroupNotFound, 404); person.BloodGroup = save; } if (req.ReligionId != null) { var save = await _context.Religions .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.ReligionId); if (save == null) return Error(GlobalMessages.ReligionNotFound, 404); person.Religion = save; } 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); if (req.RegistrationSubDistrictId != null) { var save = await _context.SubDistricts.FindAsync(req.RegistrationSubDistrictId); if (save == null) return Error(GlobalMessages.SubDistrictNotFound, 404); person.RegistSubDistrict = save; person.RegistZipCode = save.ZipCode; } if (req.RegistrationDistrictId != null) { var save = await _context.Districts.FindAsync(req.RegistrationDistrictId); if (save == null) return Error(GlobalMessages.DistrictNotFound, 404); person.RegistDistrict = save; } if (req.RegistrationProvinceId != null) { var save = await _context.Provinces.FindAsync(req.RegistrationProvinceId); if (save == null) return Error(GlobalMessages.ProvinceNotFound, 404); person.RegistProvince = save; } if (req.CurrentSubDistrictId != null) { var save = await _context.SubDistricts.FindAsync(req.CurrentSubDistrictId); if (save == null) return Error(GlobalMessages.SubDistrictNotFound, 404); person.CurrentSubDistrict = save; person.CurrentZipCode = save.ZipCode; } if (req.CurrentDistrictId != null) { var save = await _context.Districts.FindAsync(req.CurrentDistrictId); if (save == null) return Error(GlobalMessages.DistrictNotFound, 404); person.CurrentDistrict = save; } if (req.CurrentProvinceId != null) { var save = await _context.Provinces.FindAsync(req.CurrentProvinceId); if (save == null) return Error(GlobalMessages.ProvinceNotFound, 404); person.CurrentProvince = save; } 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); if (req.Couple == true && req.CouplePrefixId != null) { var save_prefix = await _context.Prefixes .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.CouplePrefixId); if (save_prefix == null) return Error(GlobalMessages.PrefixNotFound, 404); person.MarryPrefix = save_prefix; } if (req.FatherPrefixId != null) { var save_prefix = await _context.Prefixes .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.FatherPrefixId); if (save_prefix == null) return Error(GlobalMessages.PrefixNotFound, 404); person.FatherPrefix = save_prefix; } if (req.MotherPrefixId != null) { var save_prefix = await _context.Prefixes .AsQueryable() .FirstOrDefaultAsync(x => x.Id == req.MotherPrefixId); if (save_prefix == null) return Error(GlobalMessages.PrefixNotFound, 404); person.MotherPrefix = save_prefix; } 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, CreatedUserId = UserId ?? "System Administrator", CreatedFullName = FullName ?? "", 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, CreatedUserId = UserId ?? "System Administrator", CreatedFullName = FullName ?? "", 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(); } [HttpGet("position/use")] public async Task> GetPositionUse() { var position = await _context.PlacementProfiles .Where(x => x.PositionNumber != null) .Select(x => x.PositionNumber.Id) .ToListAsync(); return Success(position); } [HttpPut("position/{personalId:length(36)}")] public async Task> UpdatePositionDraft([FromBody] List items, Guid personalId) { 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.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; _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, CreatedUserId = UserId ?? "System Administrator", CreatedFullName = FullName ?? "", 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(); } } }