using BMA.EHR.Application.Repositories; 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.Models.Retirement; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Retirement.Service.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Swashbuckle.AspNetCore.Annotations; using System.Drawing; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; namespace BMA.EHR.Retirement.Service.Controllers { [Route("api/v{version:apiVersion}/retirement")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบพ้นราชการ")] public class RetirementController : BaseController { private readonly RetirementRepository _repository; private readonly ApplicationDBContext _context; private readonly MinIOService _documentService; private readonly IHttpContextAccessor _httpContextAccessor; public RetirementController(RetirementRepository 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 #region " จัดลำดับเกษียณ " private async Task GenOrderByYear(string type, int year) { if (type.Trim().ToUpper().Contains("OFFICER")) { var profiles = await _context.RetirementProfiles .Where(x => x.CreatedAt.Year == year) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .OrderBy(x => x.Profile.OrganizationOrganization) .ThenBy(x => x.Profile.PositionType == null ? null : x.Profile.PositionType.Name) .ThenBy(x => x.Profile.PositionLevel == null ? null : x.Profile.PositionLevel.Name) .ToListAsync(); var order = 1; foreach (var profile in profiles) { profile.Order = order; profile.LastUpdateFullName = FullName ?? "System Administrator"; profile.LastUpdateUserId = UserId ?? ""; profile.LastUpdatedAt = DateTime.Now; order++; } } if (type.Trim().ToUpper().Contains("EMPLOYEE")) { var profiles = await _context.RetirementProfiles .Where(x => x.CreatedAt.Year == year) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .OrderBy(x => x.Profile.OrganizationOrganization) .ThenBy(x => x.Profile.EmployeeType) .ThenBy(x => x.Profile.PositionEmployeeLevel) .ToListAsync(); var order = 1; foreach (var profile in profiles) { profile.Order = order; profile.LastUpdateFullName = FullName ?? "System Administrator"; profile.LastUpdateUserId = UserId ?? ""; profile.LastUpdatedAt = DateTime.Now; order++; } } _context.SaveChanges(); } #endregion /// /// list ประกาศเกษียณอายุราชการ /// /// ประเภทUser(officer,employee)(ตัวใหญ่หรือเล็กก็ได้) /// ปีงบประมาณ(ค.ศ.) /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{type}/{year}")] public async Task> GetRetirement(string type, int year) { if (type.Trim().ToUpper().Contains("OFFICER") || type.Trim().ToUpper().Contains("EMPLOYEE")) { var retire_old = await _context.RetirementPeriods .Include(x => x.RetirementProfiles) .Where(x => x.CreatedAt.Year == year) .Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .OrderByDescending(x => x.Round) .FirstOrDefaultAsync(); if (retire_old != null) { var data = await _context.RetirementPeriods .Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .Where(x => year > 0 ? (x.CreatedAt.Year == year) : (x.CreatedAt.Year > 0)) .Select(x => new { Id = x.Id, CreatedAt = x.CreatedAt, Round = x.Round, Total = retire_old.Id == x.Id ? retire_old.RetirementProfiles.Count() : retire_old.RetirementProfiles.Count() - x.RetirementProfiles.Where(x => x.Remove == true).Count(), }).OrderByDescending(x => x.CreatedAt) .ToListAsync(); return Success(data); } } return Success(); } /// /// สร้างประกาศเกษียณใหม่ /// /// ประเภทUser(officer,employee)(ตัวใหญ่หรือเล็กก็ได้) /// ปีงบประมาณ(ค.ศ.) /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("profile/{type}/{year}")] public async Task> CreateProfileRetirement(string type, int year) { var round = 1; var retire_old = await _context.RetirementPeriods .Include(x => x.RetirementProfiles) .Where(x => x.CreatedAt.Year == year) .Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .OrderByDescending(x => x.Round) .FirstOrDefaultAsync(); if (retire_old != null) round = retire_old.Round + 1; var retire = new RetirementPeriod { Round = round, Type = type.Trim().ToUpper(), CreatedUserId = FullName ?? "", CreatedFullName = UserId ?? "System Administrator", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.RetirementPeriods.AddAsync(retire); if (retire_old != null) { var profiles = await _context.RetirementProfiles .Where(x => x.RetirementPeriod == retire_old) .Where(x => x.Remove == false) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .ToListAsync(); foreach (var profile in profiles) { profile.RetirementPeriod = retire; profile.LastUpdateFullName = FullName ?? "System Administrator"; profile.LastUpdateUserId = UserId ?? ""; profile.LastUpdatedAt = DateTime.Now; } } else { var profiles = await _context.Profiles.AsQueryable() // .Where(x => x.BirthDate.CalculateRetireDate().Year == year) .Where(x => x.ProfileType.Trim().ToUpper().Contains(type.Trim().ToUpper())) // .Where(x => x.CitizenId == "0000000000001") .ToListAsync(); // var profiles = await (from p in _context.Profiles // where p.BirthDate.CalculateRetireDate().Year == year // select p) // .ToListAsync(); profiles = profiles.Where(x=>x.BirthDate.CalculateRetireDate().Year == year).ToList(); var order = 1; foreach (var profile in profiles) { var data = new RetirementProfile { Order = order, Remove = false, RetirementPeriod = retire, Profile = profile, CreatedUserId = FullName ?? "", CreatedFullName = UserId ?? "System Administrator", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.RetirementProfiles.AddAsync(data); order++; } } _context.SaveChanges(); var retire_all_year = await _context.RetirementPeriods .Where(x => x.CreatedAt.Year == year) .Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper())) .CountAsync(); if (retire_all_year <= 1) { await GenOrderByYear(type.Trim().ToUpper(), year); } _context.SaveChanges(); var profile_new = await _context.RetirementProfiles .Where(x => x.RetirementPeriod == retire) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(retire.Type.Trim().ToUpper())) .Select(x => new { Order = x.Order, Id = x.Id, Reason = x.Reason, Remove = x.Remove, ProfileId = x.Profile.Id, CitizenId = x.Profile.CitizenId, Prefix = x.Profile.Prefix == null ? null : x.Profile.Prefix.Name, FullName = $"{x.Profile.FirstName} {x.Profile.LastName}", OrganizationOrganization = x.Profile.OrganizationOrganization, Oc = x.Profile.Oc, Position = x.Profile.Position == null ? null : x.Profile.Position.Name, PositionType = x.Profile.PositionType == null ? null : x.Profile.PositionType.Name, PositionExecutive = x.Profile.PositionExecutive, PosNo = x.Profile.PosNo == null ? null : x.Profile.PosNo.Name, PositionEmployeePosition = x.Profile.PositionEmployeePosition, PositionEmployeeLevel = x.Profile.PositionEmployeeLevel, PositionEmployeeGroup = x.Profile.PositionEmployeeGroup, PosNoEmployee = x.Profile.PosNoEmployee, }) .ToListAsync(); return Success(new { retire.Id, retire.CreatedAt, retire.Round, retire.Type, profile = profile_new }); } /// /// View รายชื่อผู้เกษียณอายุราชการในประกาศ /// /// Id ประกาศ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{retireId:length(36)}")] public async Task> GetProfileRetirement(Guid retireId) { var retire = await _context.RetirementPeriods .FirstOrDefaultAsync(x => x.Id == retireId); if (retire == null) return Error(GlobalMessages.InvalidRetirementRequest, 404); var retire_old = await _context.RetirementPeriods .Where(x => x.CreatedAt < retire.CreatedAt) .Where(x => x.Type.Trim().ToUpper().Contains(retire.Type.Trim().ToUpper())) .ToListAsync(); var profile = await _context.RetirementProfiles .Where(x => !retire_old.Contains(x.RetirementPeriod)) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(retire.Type.Trim().ToUpper())) .Select(x => new { Order = x.Order, Id = x.Id, Reason = x.Reason, Remove = x.Remove, ProfileId = x.Profile.Id, CitizenId = x.Profile.CitizenId, Prefix = x.Profile.Prefix == null ? null : x.Profile.Prefix.Name, FullName = $"{x.Profile.FirstName} {x.Profile.LastName}", OrganizationOrganization = x.Profile.OrganizationOrganization, Oc = x.Profile.Oc, Position = x.Profile.Position == null ? null : x.Profile.Position.Name, PositionType = x.Profile.PositionType == null ? null : x.Profile.PositionType.Name, PositionExecutive = x.Profile.PositionExecutive, PosNo = x.Profile.PosNo == null ? null : x.Profile.PosNo.Name, PositionEmployeePosition = x.Profile.PositionEmployeePosition, PositionEmployeeLevel = x.Profile.PositionEmployeeLevel, PositionEmployeeGroup = x.Profile.PositionEmployeeGroup, PosNoEmployee = x.Profile.PosNoEmployee, }) .ToListAsync(); return Success(profile); } /// /// Delete รายชื่อผู้เกษียณอายุราชการในประกาศ /// /// Id ผู้ใช้งานในประกาศ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("profile/{retireProfileId:length(36)}")] public async Task> DeleteProfileRetirement(Guid retireProfileId) { var profile = await _context.RetirementProfiles .FirstOrDefaultAsync(x => x.Id == retireProfileId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); _context.RetirementProfiles.Remove(profile); _context.SaveChanges(); return Success(); } /// /// Add รายชื่อผู้เกษียณอายุราชการในประกาศ /// /// Id ประกาศ /// Id ผู้ใช้งาน /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("profile/{retireId:length(36)}")] public async Task> AddProfileRetirement([FromBody] ProfileRequest req, Guid retireId) { var profile = await _context.Profiles .FirstOrDefaultAsync(x => x.Id == req.ProfileId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); var retire = await _context.RetirementPeriods .FirstOrDefaultAsync(x => x.Id == retireId); if (retire == null) return Error(GlobalMessages.InvalidRetirementRequest, 404); var order = 1; var retire_old = await _context.RetirementPeriods .Where(x => x.CreatedAt.Year == retire.CreatedAt.Year) .Where(x => x.Type.Trim().ToUpper().Contains(retire.Type.Trim().ToUpper())) .ToListAsync(); var last_order = await _context.RetirementProfiles .Where(x => retire_old.Contains(x.RetirementPeriod)) .Where(x => x.RetirementPeriod.Type.Trim().ToUpper().Contains(retire.Type.Trim().ToUpper())) .OrderByDescending(x => x.Order) .FirstOrDefaultAsync(); if (last_order != null) order = last_order.Order + 1; var data = new RetirementProfile { Order = order, Remove = false, RetirementPeriod = retire, Profile = profile, CreatedUserId = FullName ?? "", CreatedFullName = UserId ?? "System Administrator", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; if (retire_old.Count() <= 1) { await GenOrderByYear(retire.Type.Trim().ToUpper(), retire.CreatedAt.Year); } _context.RetirementProfiles.Add(data); _context.SaveChanges(); return Success(); } /// /// ใส่เหตุผลไม่เกษียณ /// /// Id ผู้ใช้งานในประกาศ /// เหตุผล /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("reason")] public async Task> EditReasonProfileRetirement([FromBody] ProfileRetireRequest req) { var profile = await _context.RetirementProfiles .FirstOrDefaultAsync(x => x.Id == req.RetireProfileId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); profile.Remove = true; profile.Reason = req.Reason; profile.LastUpdateFullName = FullName ?? "System Administrator"; profile.LastUpdateUserId = UserId ?? ""; profile.LastUpdatedAt = DateTime.Now; _context.SaveChanges(); return Success(); } /// /// View เหตุผลไม่เกษียณ /// /// Id ผู้ใช้งานในประกาศ /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("reason/{retireProfileId:length(36)}")] public async Task> ViewReasonProfileRetirement(Guid retireProfileId) { var profile = await _context.RetirementProfiles .Select(x => new { Id = x.Id, Reason = x.Reason, }) .FirstOrDefaultAsync(x => x.Id == retireProfileId); if (profile == null) return Error(GlobalMessages.DataNotFound, 404); return Success(profile); } } }