using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using BMA.EHR.Recruit.Service.Data; using BMA.EHR.Recruit.Service.Models.Recruits; using BMA.EHR.Recruit.Service.Core; using BMA.EHR.MetaData.Service.Models; using BMA.EHR.Domain.Models.Placement; using BMA.EHR.Recurit.Service.Data; using System.Security.Claims; using System.Net.Http.Headers; using Newtonsoft.Json; namespace BMA.EHR.Recruit.Service.Services { public class RecruitService { private readonly ApplicationDbContext _context; private readonly MetadataDbContext _contextMetadata; private readonly MinIOService _minIOService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IConfiguration _configuration; public RecruitService(ApplicationDbContext context, MetadataDbContext contextMetadata, IHttpContextAccessor httpContextAccessor, MinIOService minIOService, IConfiguration configuration) { _context = context; _contextMetadata = contextMetadata; _minIOService = minIOService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; } #region " Properties " private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value; private string? token => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; #endregion public int GetExamCount(string citizenId) { try { var count = _context.Recruits.AsQueryable() .Where(x => x.CitizenId == citizenId) .Count(); return count; } catch { throw; } } public async Task GetExamAttributeAsync(Guid period, Guid exam) { try { var payment = await _context.RecruitPayments.AsQueryable() .Include(x => x.Recruit) .ThenInclude(x => x.RecruitImport) .Where(x => x.Recruit.Id == exam) .Where(x => x.Recruit.RecruitImport.Id == period) .FirstOrDefaultAsync(); return payment != null ? "มีคุณสมบัติ" : "ไม่มีคุณสมบัติ"; } catch { throw; } } public bool CheckValidCertificate(DateTime certDate, int nextYear = 5) { var valid = true; if (DateTime.Now.Date > certDate.Date.AddYears(nextYear)) valid = false; return valid; } public async Task UpdateDocAsync(Guid ImportId, IFormFileCollection files) { var periodExam = await _context.RecruitImports.AsQueryable() .FirstOrDefaultAsync(x => x.Id == ImportId); if (periodExam == null) throw new Exception(GlobalMessages.DataNotFound); foreach (var file in files) { var doc = await _minIOService.UploadFileAsync(file); var periodExamDocument = new RecruitImportDocument { RecruitImportId = ImportId, DocumentId = doc.Id, }; await _context.RecruitImportDocuments.AddAsync(periodExamDocument); } await _context.SaveChangesAsync(); } public async Task UpdateImageAsync(Guid ImportId, IFormFileCollection files) { var periodExam = await _context.RecruitImports.AsQueryable() .FirstOrDefaultAsync(x => x.Id == ImportId); if (periodExam == null) throw new Exception(GlobalMessages.DataNotFound); foreach (var file in files) { var doc = await _minIOService.UploadFileAsync(file); var periodExamImage = new RecruitImportImage { RecruitImportId = ImportId, DocumentId = doc.Id, }; await _context.RecruitImportImages.AddAsync(periodExamImage); } await _context.SaveChangesAsync(); } public async Task DeleteImageAsync(Guid id) { var image = await _context.RecruitImportImages.AsQueryable() .Include(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (image == null) throw new Exception(GlobalMessages.DataNotFound); var doc_id = image.Document.Id; _context.RecruitImportImages.Remove(image); await _context.SaveChangesAsync(); await _minIOService.DeleteFileAsync(doc_id); } public async Task DeleteDocAsync(Guid id) { var doc = await _context.RecruitImportDocuments.AsQueryable() .Include(x => x.Document) .FirstOrDefaultAsync(x => x.Id == id); if (doc == null) throw new Exception(GlobalMessages.DataNotFound); var doc_id = doc.Document.Id; _context.RecruitImportDocuments.Remove(doc); await _context.SaveChangesAsync(); await _minIOService.DeleteFileAsync(doc_id); } public async Task UpdateAsyncRecruitToPlacement(Guid examId) { var recruitImport = await _context.RecruitImports.AsQueryable() .FirstOrDefaultAsync(x => x.Id == examId); if (recruitImport == null) throw new Exception(GlobalMessages.DataNotFound); var _placement = await _contextMetadata.Placements.AsQueryable() .FirstOrDefaultAsync(x => x.Name == recruitImport.Name && x.Year == ((int)(recruitImport.Year == null ? 0 : recruitImport.Year))); if (_placement != null) throw new Exception("รอบการสอบนี้ได้ทำการบรรจุไปแล้ว"); var placement = new Placement { Name = recruitImport.Name, Round = recruitImport.Order == null ? "" : recruitImport.Order.ToString(), Year = (int)(recruitImport.Year == null ? 0 : recruitImport.Year), Number = await _context.Recruits.AsQueryable().Where(x => x.RecruitImport == recruitImport).CountAsync(), PlacementType = await _contextMetadata.PlacementTypes.FirstOrDefaultAsync(x => x.Name.Trim().ToUpper().Contains("สอบแข่งขัน")) == null ? await _contextMetadata.PlacementTypes.FirstOrDefaultAsync() : await _contextMetadata.PlacementTypes.FirstOrDefaultAsync(x => x.Name.Trim().ToUpper().Contains("สอบแข่งขัน")), StartDate = DateTime.Now, EndDate = DateTime.Now.AddYears(2).AddDays(-1), CreatedAt = DateTime.Now, CreatedUserId = UserId ?? "", CreatedFullName = FullName ?? "", LastUpdatedAt = DateTime.Now, LastUpdateUserId = UserId ?? "", LastUpdateFullName = FullName ?? "", }; await _contextMetadata.Placements.AddAsync(placement); var candidates = await _context.Recruits.AsQueryable() .Include(x => x.Addresses) .Include(x => x.Certificates) .Include(x => x.Educations) .Include(x => x.Occupations) .Where(x => x.RecruitImport == recruitImport) .ToListAsync(); foreach (var candidate in candidates) { var IsOfficer = false; dynamic org = null; var apiUrl = $"{_configuration["API"]}/org/profile/citizenid/position/{candidate.CitizenId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) { IsOfficer = false; } else { IsOfficer = true; } } var Address = candidate.Addresses.FirstOrDefault() == null ? null : $"{candidate.Addresses.FirstOrDefault().Address}"; var Moo = candidate.Addresses.FirstOrDefault() == null ? null : $" หมู่ {candidate.Addresses.FirstOrDefault().Moo}"; var Soi = candidate.Addresses.FirstOrDefault() == null ? null : $" ซอย {candidate.Addresses.FirstOrDefault().Soi}"; var Road = candidate.Addresses.FirstOrDefault() == null ? null : $" ถนน {candidate.Addresses.FirstOrDefault().Road}"; var Address1 = candidate.Addresses.FirstOrDefault() == null ? null : $"{candidate.Addresses.FirstOrDefault().Address1}"; var Moo1 = candidate.Addresses.FirstOrDefault() == null ? null : $" หมู่ {candidate.Addresses.FirstOrDefault().Moo1}"; var Soi1 = candidate.Addresses.FirstOrDefault() == null ? null : $" ซอย {candidate.Addresses.FirstOrDefault().Soi1}"; var Road1 = candidate.Addresses.FirstOrDefault() == null ? null : $" ถนน {candidate.Addresses.FirstOrDefault().Road1}"; var scoreImport = await _context.ScoreImports.AsQueryable() .FirstOrDefaultAsync(x => x.RecruitImport == recruitImport); var recruitScore = await _context.RecruitScores.AsQueryable() .Where(x => x.ScoreImport == scoreImport) .Where(x => x.ExamId == candidate.ExamId) .Where(x => x.ExamStatus == "ผ่าน") .FirstOrDefaultAsync(x => x.ExamId == candidate.ExamId && x.ScoreImport == scoreImport); if (recruitScore == null) continue; var profile = await _contextMetadata.Profiles .Include(x => x.Salaries) .FirstOrDefaultAsync(p => p.CitizenId == candidate.CitizenId); var CitizenProvince = await _contextMetadata.Provinces.Where(x => x.Name == candidate.CitizenCardIssuer).FirstOrDefaultAsync(); var RegistProvince = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.Provinces.Where(x => x.Name == candidate.Addresses.FirstOrDefault().Province).FirstOrDefaultAsync(); var RegistDistrict = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.Districts.Where(x => x.Name == candidate.Addresses.FirstOrDefault().District && x.Province.Name == candidate.Addresses.FirstOrDefault().Province).FirstOrDefaultAsync(); var RegistSubDistrict = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.SubDistricts.Where(x => x.Name == candidate.Addresses.FirstOrDefault().Amphur && x.District.Name == candidate.Addresses.FirstOrDefault().District && x.District.Province.Name == candidate.Addresses.FirstOrDefault().Province).FirstOrDefaultAsync(); var CurrentProvince = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.Provinces.Where(x => x.Name == candidate.Addresses.FirstOrDefault().Moo1).FirstOrDefaultAsync(); var CurrentDistrict = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.Districts.Where(x => x.Name == candidate.Addresses.FirstOrDefault().District1 && x.Province.Name == candidate.Addresses.FirstOrDefault().Moo1).FirstOrDefaultAsync(); var CurrentSubDistrict = candidate.Addresses.FirstOrDefault() == null ? null : await _contextMetadata.SubDistricts.Where(x => x.Name == candidate.Addresses.FirstOrDefault().Amphur1 && x.District.Name == candidate.Addresses.FirstOrDefault().District1 && x.District.Province.Name == candidate.Addresses.FirstOrDefault().Moo1).FirstOrDefaultAsync(); var placementProfile = new PlacementProfile { Placement = placement, PositionCandidate = await _contextMetadata.PositionPaths.FirstOrDefaultAsync(x => x.Name == candidate.PositionName), positionName = candidate.PositionName, Prefix = candidate.Prefix, Firstname = candidate.FirstName, Lastname = candidate.LastName, Gender = candidate.Gendor, Nationality = candidate.National, Race = candidate.Race, Religion = candidate.Religion, DateOfBirth = candidate.DateOfBirth, Relationship = candidate.Marry, // Email = candidate.Email, CitizenId = candidate.CitizenId, // CitizenDistrict = await _contextMetadata.Districts.FirstOrDefaultAsync(x => x.Id == candidate.CitizenDistrictId), CitizenProvinceId = CitizenProvince == null ? null : CitizenProvince.Id.ToString(), CitizenDate = candidate.CitizenCardExpireDate, Telephone = candidate.Addresses.FirstOrDefault() == null ? null : candidate.Addresses.FirstOrDefault().Telephone, MobilePhone = candidate.Addresses.FirstOrDefault() == null ? null : candidate.Addresses.FirstOrDefault().Mobile, // Knowledge = candidate.Knowledge, RegistAddress = $"{Address}{Moo}{Soi}{Road}", RegistProvinceId = RegistProvince == null ? null : RegistProvince.Id.ToString(), RegistDistrictId = RegistDistrict == null ? null : RegistDistrict.Id.ToString(), RegistSubDistrictId = RegistSubDistrict == null ? null : RegistSubDistrict.Id.ToString(), RegistZipCode = candidate.Addresses.FirstOrDefault() == null ? null : candidate.Addresses.FirstOrDefault().ZipCode, RegistSame = false, CurrentAddress = $"{Address1}{Moo1}{Soi1}{Road1}", CurrentProvinceId = CurrentProvince == null ? null : CurrentProvince.Id.ToString(), CurrentDistrictId = CurrentDistrict == null ? null : CurrentDistrict.Id.ToString(), CurrentSubDistrictId = CurrentSubDistrict == null ? null : CurrentSubDistrict.Id.ToString(), CurrentZipCode = candidate.Addresses.FirstOrDefault() == null ? null : candidate.Addresses.FirstOrDefault().ZipCode1, Marry = candidate.Marry.Contains("สมรส"), // MarryPrefix = await _contextMetadata.Prefixes.FirstOrDefaultAsync(x => x.Id == candidate.MarryPrefixId), // MarryFirstName = candidate.MarryFirstName, // MarryLastName = candidate.MarryLastName, // MarryOccupation = candidate.MarryOccupation, // MarryNationality = candidate.MarryNationality, // FatherPrefix = await _contextMetadata.Prefixes.FirstOrDefaultAsync(x => x.Id == candidate.FatherPrefixId), // FatherFirstName = candidate.FatherFirstName, // FatherLastName = candidate.FatherLastName, // FatherOccupation = candidate.FatherOccupation, // FatherNationality = candidate.FatherNationality, // MotherPrefix = await _contextMetadata.Prefixes.FirstOrDefaultAsync(x => x.Id == candidate.MotherPrefixId), // MotherFirstName = candidate.MotherFirstName, // MotherLastName = candidate.MotherLastName, // MotherOccupation = candidate.MotherOccupation, // MotherNationality = candidate.MotherNationality, OccupationPositionType = "other", // OccupationCompany = candidate.OccupationCompany, // OccupationDepartment = candidate.Occupations.FirstOrDefault() == null ? null : candidate.Occupations.FirstOrDefault().Workplace, // OccupationEmail = candidate.OccupationEmail, OccupationTelephone = candidate.Occupations.FirstOrDefault() == null ? null : candidate.Occupations.FirstOrDefault().Telephone, OccupationPosition = candidate.Occupations.FirstOrDefault() == null ? null : candidate.Occupations.FirstOrDefault().Position, PointTotalA = recruitScore == null ? null : Convert.ToDouble(recruitScore.FullA), PointA = recruitScore == null ? null : Convert.ToDouble(recruitScore.SumA), PointTotalB = recruitScore == null ? null : Convert.ToDouble(recruitScore.FullB), PointB = recruitScore == null ? null : Convert.ToDouble(recruitScore.SumB), PointTotalC = recruitScore == null ? null : Convert.ToDouble(recruitScore.FullC), PointC = recruitScore == null ? null : Convert.ToDouble(recruitScore.SumC), ExamNumber = recruitScore == null || int.TryParse(recruitScore.Number, out int n) == false ? null : Convert.ToInt32(recruitScore.Number), ExamRound = null, IsRelief = false, PlacementStatus = "UN-CONTAIN", Pass = recruitScore == null ? null : recruitScore.ExamStatus, // ReportingDate = DateTime.Now, RemarkHorizontal = "โดยมีเงื่อนไขว่าต้องปฏิบัติงานให้กรุงเทพมหานครเป็นระยะเวลาไม่น้อยกว่า ๕ ปี นับแต่วันที่ได้รับการบรรจุและแต่งตั้ง โดยห้ามโอนไปหน่วยงานหรือส่วนราชการอื่น เว้นเเต่ลาออกจากราชการ", Amount = org == null || org.result == null ? null : org.result.amount, PositionSalaryAmount = org == null || org.result == null ? null : org.result.positionSalaryAmount, MouthSalaryAmount = org == null || org.result == null ? null : org.result.mouthSalaryAmount, CreatedAt = DateTime.Now, CreatedUserId = UserId ?? "", CreatedFullName = FullName ?? "", LastUpdatedAt = DateTime.Now, LastUpdateUserId = UserId ?? "", LastUpdateFullName = FullName ?? "", IsOfficer = IsOfficer, profileId = org == null || org.result == null ? null : org.result.profileId, IsOld = org == null || org.result == null ? false : true, AmountOld = org == null || org.result == null ? null : org.result.amount, nodeOld = org == null || org.result == null ? null : org.result.node, nodeIdOld = org == null || org.result == null ? null : org.result.nodeId, posmasterIdOld = org == null || org.result == null ? null : org.result.posmasterId, rootOld = org == null || org.result == null ? null : org.result.root, rootIdOld = org == null || org.result == null ? null : org.result.rootId, rootShortNameOld = org == null || org.result == null ? null : org.result.rootShortName, child1Old = org == null || org.result == null ? null : org.result.child1, child1IdOld = org == null || org.result == null ? null : org.result.child1Id, child1ShortNameOld = org == null || org.result == null ? null : org.result.child1ShortName, child2Old = org == null || org.result == null ? null : org.result.child2, child2IdOld = org == null || org.result == null ? null : org.result.child2Id, child2ShortNameOld = org == null || org.result == null ? null : org.result.child2ShortName, child3Old = org == null || org.result == null ? null : org.result.child3, child3IdOld = org == null || org.result == null ? null : org.result.child3Id, child3ShortNameOld = org == null || org.result == null ? null : org.result.child3ShortName, child4Old = org == null || org.result == null ? null : org.result.child4, child4IdOld = org == null || org.result == null ? null : org.result.child4Id, child4ShortNameOld = org == null || org.result == null ? null : org.result.child4ShortName, orgRevisionIdOld = org == null || org.result == null ? null : org.result.orgRevisionId, // positionIdOld = org == null || org.result == null ? null : org.result.positionIdOld, posMasterNoOld = org == null || org.result == null ? null : org.result.posMasterNo, positionNameOld = org == null || org.result == null ? null : org.result.position, // positionFieldOld = org == null || org.result == null ? null : org.result.positionFieldOld, posTypeIdOld = org == null || org.result == null ? null : org.result.posTypeId, posTypeNameOld = org == null || org.result == null ? null : org.result.posTypeName, posLevelIdOld = org == null || org.result == null ? null : org.result.posLevelId, posLevelNameOld = org == null || org.result == null ? null : org.result.posLevelName, }; await _contextMetadata.PlacementProfiles.AddAsync(placementProfile); var placementEducation = new PlacementEducation { PlacementProfile = placementProfile, EducationLevel = await _contextMetadata.EducationLevels.FirstOrDefaultAsync(x => x.Name == (candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().HighDegree)), Field = candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().Major, Gpa = candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().GPA.ToString(), Institute = candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().University, Degree = candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().Degree, // Country = education.Name, // Duration = education.Name, // Other = education.Name, // FundName = education.Name, // DurationYear = education.Name, FinishDate = candidate.Educations.FirstOrDefault() == null ? null : candidate.Educations.FirstOrDefault().BachelorDate, IsDate = true, // StartDate = education.DurationStart, // EndDate = education.DurationEnd, CreatedAt = DateTime.Now, CreatedUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, LastUpdateUserId = UserId ?? "", CreatedFullName = FullName ?? "", LastUpdateFullName = FullName ?? "", }; await _contextMetadata.PlacementEducations.AddAsync(placementEducation); var placementCertificate = new PlacementCertificate { PlacementProfile = placementProfile, CertificateNo = candidate.Certificates.FirstOrDefault() == null ? null : candidate.Certificates.FirstOrDefault().CertificateNo, // Issuer = candidate.Certificates.FirstOrDefault() == null ? null : candidate.Certificates.FirstOrDefault().Issuer, IssueDate = candidate.Certificates.FirstOrDefault() == null ? null : candidate.Certificates.FirstOrDefault().IssueDate, ExpireDate = candidate.Certificates.FirstOrDefault() == null ? null : candidate.Certificates.FirstOrDefault().ExpiredDate, CertificateType = candidate.Certificates.FirstOrDefault() == null ? null : candidate.Certificates.FirstOrDefault().Description, CreatedAt = DateTime.Now, CreatedUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, LastUpdateUserId = UserId ?? "", CreatedFullName = FullName ?? "", LastUpdateFullName = FullName ?? "", }; await _contextMetadata.PlacementCertificates.AddAsync(placementCertificate); } await _contextMetadata.SaveChangesAsync(); } } }