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; 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_LIST"); 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(); 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_LIST"); 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_LIST"); 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); } } // /// แก้ไขรายการ /// /// /// /// เมื่อทำรายการสำเร็จ /// ไม่ได้ 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_LIST"); 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; 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_LIST"); 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.CreatedUserId = userId.ToString("D"); leaveBeginning.CreatedFullName = FullName ?? ""; leaveBeginning.CreatedAt = DateTime.Now; await _leaveBeginningRepository.AddAsync(leaveBeginning); return Success(); } catch (Exception ex) { return Error(ex); } } #endregion } }