using BMA.EHR.Application.Repositories; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Placement.Service.Requests; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Swashbuckle.AspNetCore.Annotations; using System.Security.Claims; namespace BMA.EHR.Placement.Service.Controllers { [Route("api/[controller]/placement")] [ApiController] [Produces("application/json")] //[Authorize] [SwaggerTag("ระบบบรรจุ")] public class PlacementController : BaseController { private readonly PlacementRepository _repository; private readonly ApplicationDBContext _context; private readonly MinIOService _documentService; private readonly IHttpContextAccessor _httpContextAccessor; public PlacementController(PlacementRepository repository, ApplicationDBContext context, MinIOService documentService, IHttpContextAccessor httpContextAccessor) { _repository = repository; _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; #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)).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) { 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, 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, Disclaim = x.IsRelief, }).ToListAsync(); return Success(data); } [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, FullName = x.Prefix == null ? null : x.Prefix.Name + $"{x.Firstname} {x.Lastname}", DateOfBirth = x.DateOfBirth, Gender = x.Gender == null ? null : x.Gender.Name, 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 { EducationLevel = p.EducationLevel == null ? null : p.EducationLevel.Name, Major = p.Major, Scores = p.Scores, Name = p.Name, DurationStart = p.DurationStart, DurationEnd = p.DurationEnd, }), 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), }).FirstOrDefaultAsync(x => x.PersonalId == personalId); 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) { 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); } [HttpPost("pass/deferment"), DisableRequestSizeLimit] public async Task> UpdatePersonDeferment() { 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 = "UN-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.FindAsync(req.PersonalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); 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 (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.Amount = req.SalaryAmount; person.MouthSalaryAmount = req.MouthSalaryAmount; person.PositionSalaryAmount = req.PositionSalaryAmount; person.RecruitDate = req.ContainDate; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpGet("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(); } [HttpGet("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.RegistSame = req.RegistrationSame; person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpGet("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(); } [HttpGet("certificate/{personalId:length(36)}")] public async Task> UpdateCertificate([FromBody] PersonCertificateRequest req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } [HttpGet("education/{personalId:length(36)}")] public async Task> UpdateEducation([FromBody] PersonEducationRequest req, Guid personalId) { var person = await _context.PlacementProfiles.FindAsync(personalId); if (person == null) return Error(GlobalMessages.DataNotFound, 404); person.LastUpdateFullName = FullName ?? "System Administrator"; person.LastUpdateUserId = UserId ?? ""; person.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } } }