using BMA.EHR.Application.Repositories; using BMA.EHR.Application.Repositories.Leaves.LeaveRequests; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Models.Leave.Requests; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Leave.Service.DTOs.LeaveBeginnings; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OfficeOpenXml.ConditionalFormatting; using Swashbuckle.AspNetCore.Annotations; using System.Security.Claims; using Microsoft.EntityFrameworkCore; using BMA.EHR.Application.Responses.Profiles; namespace BMA.EHR.Leave.Service.Controllers { [Route("api/v{version:apiVersion}/leave-beginning")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("API ระบบลงเวลาและการลา (ข้อมูลวันลายกมาและใช้ไป)")] public class LeaveBeginningController : BaseController { #region " Fields " private readonly LeaveBeginningRepository _leaveBeginningRepository; private readonly LeaveDbContext _context; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IWebHostEnvironment _hostingEnvironment; private readonly IConfiguration _configuration; private readonly UserProfileRepository _userProfileRepository; private readonly PermissionRepository _permission; #endregion #region " Constuctor and Destructor " public LeaveBeginningController(LeaveBeginningRepository leaveBeginningRepository, LeaveDbContext context, IHttpContextAccessor httpContextAccessor, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, UserProfileRepository userProfileRepository, PermissionRepository permission) { _leaveBeginningRepository = leaveBeginningRepository; _context = context; _httpContextAccessor = httpContextAccessor; _hostingEnvironment = hostingEnvironment; _configuration = configuration; _userProfileRepository = userProfileRepository; _permission = permission; } #endregion #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"); private string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; private Guid OcId { get { if (UserId != null || UserId != "") return _userProfileRepository.GetUserOCId(Guid.Parse(UserId!), AccessToken); else return Guid.Empty; } } #endregion #region " Methods " /// /// แสดงรายการ /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("list")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> GetListAsync([FromBody] GetLeaveBeginningDto req) { try { var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_HISTORY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var resData = await _leaveBeginningRepository.GetAllByYearAsync(req.Year); if (req.Type != Guid.Empty) resData = resData.Where(x => x.LeaveTypeId == req.Type).ToList(); //กรองสิทธิ์ string role = jsonData["result"]?.ToString(); var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); if (role == "NORMAL" || role == "CHILD") { nodeId = profileAdmin?.Node == 4 ? profileAdmin?.Child4DnaId : profileAdmin?.Node == 3 ? profileAdmin?.Child3DnaId : profileAdmin?.Node == 2 ? profileAdmin?.Child2DnaId : profileAdmin?.Node == 1 ? profileAdmin?.Child1DnaId : profileAdmin?.Node == 0 ? profileAdmin?.RootDnaId : ""; } else if (role == "BROTHER") { nodeId = profileAdmin?.Node == 4 ? profileAdmin?.Child3DnaId : profileAdmin?.Node == 3 ? profileAdmin?.Child2DnaId : profileAdmin?.Node == 2 ? profileAdmin?.Child1DnaId : profileAdmin?.Node == 1 || profileAdmin?.Node == 0 ? profileAdmin?.RootDnaId : ""; } else if (role == "ROOT" || role == "PARENT") { nodeId = profileAdmin?.RootDnaId; } int? node = profileAdmin?.Node; if (role == "OWNER") { node = null; } if (role == "OWNER" || role == "CHILD") { resData = resData .Where(x => node == 4 ? x.Child4DnaId == Guid.Parse(nodeId!) : (node == 3 ? x.Child3DnaId == Guid.Parse(nodeId!) : (node == 2 ? x.Child2DnaId == Guid.Parse(nodeId!) : (node == 1 ? x.Child1DnaId == Guid.Parse(nodeId!) : (node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) : (node == null ? true : true)))))).ToList(); } else if (role == "BROTHER") { resData = resData .Where(x => node == 4 ? x.Child3DnaId == Guid.Parse(nodeId!) : (node == 3 ? x.Child2DnaId == Guid.Parse(nodeId!) : (node == 2 ? x.Child1DnaId == Guid.Parse(nodeId!) : (node == 1 || node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) : (node == null ? true : true))))).ToList(); } else if (role == "ROOT") { resData = resData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); } else if (role == "PARENT") { resData = resData .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); } else if (role == "NORMAL") { resData = resData .Where(x => node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId == null : node == 1 ? x.Child1DnaId == Guid.Parse(nodeId!) && x.Child2DnaId == null : node == 2 ? x.Child2DnaId == Guid.Parse(nodeId!) && x.Child3DnaId == null : node == 3 ? x.Child3DnaId == Guid.Parse(nodeId!) && x.Child4DnaId == null : node == 4 ? x.Child4DnaId == Guid.Parse(nodeId!) : true).ToList(); } //END var result = new List(); foreach (var item in resData) { result.Add(new { item.Id, item.ProfileId, FullName = $"{item.Prefix}{item.FirstName} {item.LastName}", item.Prefix, item.FirstName, item.LastName, item.LeaveTypeId, LeaveTypeCode = item.LeaveType?.Code, LeaveType = item.LeaveType?.Name, item.LeaveYear, item.LeaveDays, item.LeaveDaysUsed, item.CreatedAt, item.CreatedFullName, item.LastUpdatedAt, item.LastUpdateFullName }); } if (req.Keyword != "") result = result.Where(x => x.FullName!.Contains(req.Keyword)).ToList(); if (!string.IsNullOrWhiteSpace(req.sortBy)) { switch (req.sortBy.ToUpper()) { case "FULLNAME": if (req.descending == true) result = result.OrderByDescending(x => x.Prefix) .ThenByDescending(x => x.FirstName) .ThenByDescending(x => x.LastName) .ToList(); else result = result.OrderBy(x => x.Prefix) .ThenBy(x => x.FirstName) .ThenBy(x => x.LastName) .ToList(); break; case "LEAVETYPE": if (req.descending == true) result = result.OrderByDescending(x => x.LeaveType).ToList(); else result = result.OrderBy(x => x.LeaveType).ToList(); break; case "LEAVEYEAR": if (req.descending == true) result = result.OrderByDescending(x => x.LeaveYear).ToList(); else result = result.OrderBy(x => x.LeaveYear).ToList(); break; case "LEAVEDAYS": if (req.descending == true) result = result.OrderByDescending(x => x.LeaveDays).ToList(); else result = result.OrderBy(x => x.LeaveDays).ToList(); break; case "LEAVEDAYSUSED": if (req.descending == true) result = result.OrderByDescending(x => x.LeaveDaysUsed).ToList(); else result = result.OrderBy(x => x.LeaveDaysUsed).ToList(); break; default: break; } } var pageResult = result.Skip((req.Page - 1) * req.PageSize).Take(req.PageSize).ToList(); return Success(new { data = pageResult, total = result.Count }); } catch (Exception ex) { return Error(ex); } } /// /// ลบรายการ /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("{id:guid}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> DeleteAsync(Guid id) { try { var getPermission = await _permission.GetPermissionAPIAsync("DELETE", "SYS_LEAVE_HISTORY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var leaveBeginning = await _leaveBeginningRepository.GetByIdAsync(id); if (leaveBeginning == null) return Error("ไม่พบข้อมูลที่ต้องการลบ", StatusCodes.Status404NotFound); await _leaveBeginningRepository.DeleteAsync(leaveBeginning); return Success("ลบข้อมูลสำเร็จ"); } catch (Exception ex) { return Error(ex); } } /// /// แสดงรายการจาก Id /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{id:guid}")] public async Task> GetByIdAsync(Guid id) { try { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_LEAVE_HISTORY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var leaveBeginning = _leaveBeginningRepository.GetByIdAsync(id); if (leaveBeginning == null) return Error("ไม่พบข้อมูลที่ต้องการลบ", StatusCodes.Status404NotFound); return Success(leaveBeginning); } catch (Exception ex) { return Error(ex); } } [HttpGet("update-dna")] public async Task> UpdateDnaAsync() { try { var leaveBeginnings = await _context.LeaveBeginnings.ToListAsync(); foreach (var item in leaveBeginnings) { var profile = await _userProfileRepository.GetProfileByProfileIdAsync(item.ProfileId, AccessToken); if (profile != null) { item.RootDnaId = profile.RootDnaId; item.Child1DnaId = profile.Child1DnaId; item.Child2DnaId = profile.Child2DnaId; item.Child3DnaId = profile.Child3DnaId; item.Child4DnaId = profile.Child4DnaId; _context.LeaveBeginnings.Update(item); } } await _context.SaveChangesAsync(); return Success("อัพเดทข้อมูลสำเร็จ"); } catch (Exception ex) { return Error(ex); } } // /// แก้ไขรายการ /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("{id:guid}")] public async Task> PutAsync(Guid id, [FromBody] EditLeaveBeginningDto req) { try { var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_LEAVE_HISTORY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var leaveBeginning = await _leaveBeginningRepository.GetByIdAsync(id); if (leaveBeginning == null) return Error("ไม่พบข้อมูลที่ต้องการแก้ไข", StatusCodes.Status404NotFound); var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken); if (profile == null) { return Error("ไม่พบข้อมูลข้าราชการหรือลูกจ้าง", StatusCodes.Status404NotFound); } leaveBeginning.LeaveTypeId = req.LeaveTypeId; leaveBeginning.LeaveYear = req.LeaveYear; leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed; leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.Prefix = profile.Prefix; leaveBeginning.FirstName = profile.FirstName; leaveBeginning.LastName = profile.LastName; leaveBeginning.LastUpdateUserId = userId.ToString("D"); leaveBeginning.LastUpdateFullName = FullName ?? ""; leaveBeginning.LastUpdatedAt = DateTime.Now; leaveBeginning.RootDnaId = profile.RootDnaId; leaveBeginning.Child1DnaId = profile.Child1DnaId; leaveBeginning.Child2DnaId = profile.Child2DnaId; leaveBeginning.Child3DnaId = profile.Child3DnaId; leaveBeginning.Child4DnaId = profile.Child4DnaId; await _leaveBeginningRepository.UpdateAsync(leaveBeginning); return Success("แก้ไขข้อมูลสำเร็จ"); } catch (Exception ex) { return Error(ex); } } /// /// สร้างรายการ /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost()] public async Task> PostAsync([FromBody] EditLeaveBeginningDto req) { try { var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_LEAVE_HISTORY"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken); if (profile == null) { return Error("ไม่พบข้อมูลข้าราชการหรือลูกจ้าง", StatusCodes.Status404NotFound); } // check duplicate var oldData = await _context.LeaveBeginnings.FirstOrDefaultAsync(x => x.ProfileId == req.ProfileId && x.LeaveTypeId == req.LeaveTypeId && x.LeaveYear == req.LeaveYear); if (oldData is not null) { return Error("ไม่สามารถบันทึกข้อมูล เนื่องจากมีข้อมูลในระบบแล้ว"); } var leaveBeginning = new LeaveBeginning(); leaveBeginning.LeaveTypeId = req.LeaveTypeId; leaveBeginning.LeaveYear = req.LeaveYear; leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed; leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.Prefix = profile.Prefix; leaveBeginning.FirstName = profile.FirstName; leaveBeginning.LastName = profile.LastName; leaveBeginning.RootDnaId = profile.RootDnaId; leaveBeginning.Child1DnaId = profile.Child1DnaId; leaveBeginning.Child2DnaId = profile.Child2DnaId; leaveBeginning.Child3DnaId = profile.Child3DnaId; leaveBeginning.Child4DnaId = profile.Child4DnaId; leaveBeginning.CreatedUserId = userId.ToString("D"); leaveBeginning.CreatedFullName = FullName ?? ""; leaveBeginning.CreatedAt = DateTime.Now; await _leaveBeginningRepository.AddAsync(leaveBeginning); return Success(); } catch (Exception ex) { return Error(ex); } } #endregion } }