hrms-api-backend/BMA.EHR.Insignia/Controllers/InsigniaPeriodController.cs
kittapath 87e8c17309
Some checks failed
release-dev / release-dev (push) Failing after 11s
ให้ออกลูกจ้าง
2025-01-27 10:14:54 +07:00

391 lines
No EOL
19 KiB
C#

using System.Security.Claims;
using BMA.EHR.Application.Repositories;
using BMA.EHR.Application.Repositories.MessageQueue;
using BMA.EHR.Application.Requests;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Models.Insignias;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
namespace BMA.EHR.Insignia.Service.Controllers
{
[Route("api/v{version:apiVersion}/insignia/period")]
[ApiVersion("1.0")]
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("รอบเครื่องราชฯ")]
public class InsigniaPeriodController : BaseController
{
private readonly ApplicationDBContext _context;
private readonly MinIOService _documentService;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly InsigniaPeriodsRepository _repository;
private readonly NotificationRepository _repositoryNoti;
private readonly UserProfileRepository _userProfileRepository;
private readonly PermissionRepository _permission;
public InsigniaPeriodController(ApplicationDBContext context,
MinIOService documentService,
InsigniaPeriodsRepository repository,
NotificationRepository repositoryNoti,
IHttpContextAccessor httpContextAccessor,
UserProfileRepository userProfileRepository,
PermissionRepository permission)
{
_context = context;
_documentService = documentService;
_repository = repository;
_repositoryNoti = repositoryNoti;
_httpContextAccessor = httpContextAccessor;
_userProfileRepository = userProfileRepository;
_permission = permission;
}
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
private string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
#endregion
/// <summary>
/// list รอบเครื่องราช
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet()]
public async Task<ActionResult<ResponseObject>> GetList(string path)
{
path = path.Trim().ToUpper();
string getPermission = string.Empty;
if (path == "ROUND")
{
getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_INSIGNIA_ROUND");
}
else if (path == "MANAGE")
{
getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_INSIGNIA_MANAGE");
}
else if (path == "REPORT")
{
getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_INSIGNIA_REPORT");
}
else
{
getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_INSIGNIA_ROUND");
}
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var insigniaPeriods = await _context.InsigniaPeriods.AsQueryable()
.Include(x => x.InsigniaEmployees)
.OrderByDescending(x => x.Year)
.ThenByDescending(x => x.StartDate)
.Select(p => new
{
period_id = p.Id,
period_amount = p.Amount,
period_name = p.Name,
period_round = p.Round,
period_start = p.StartDate,
period_end = p.EndDate,
period_status = p.IsLock == true ? "DONE" : (p.InsigniaRequests.Count() == 0 ? "WAITTING" : "PENDING"),
period_year = p.Year,
period_isActive = p.IsActive,
empPosId = p.InsigniaEmployees.Select(x => x.RefId),
period_doc = p.ReliefDoc == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.ReliefDoc.Id,
period_revision = p.RevisionId,
})
.ToListAsync();
var data = new List<dynamic>();
foreach (var insigniaPeriod in insigniaPeriods)
{
var _data = new
{
period_id = insigniaPeriod.period_id,
period_amount = insigniaPeriod.period_amount,
period_name = insigniaPeriod.period_name,
period_round = insigniaPeriod.period_round,
period_start = insigniaPeriod.period_start,
period_end = insigniaPeriod.period_end,
period_status = insigniaPeriod.period_status,
period_year = insigniaPeriod.period_year,
period_isActive = insigniaPeriod.period_isActive,
empPosId = insigniaPeriod.empPosId,
period_doc = insigniaPeriod.period_doc == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(insigniaPeriod.period_doc),
period_revision = insigniaPeriod.period_revision,
};
data.Add(_data);
}
return Success(data);
}
/// <summary>
/// get รายละเอียดรอบเครื่องราช
/// </summary>
/// <param name="id">Id เครื่องราช</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("{id:length(36)}")]
public async Task<ActionResult<ResponseObject>> GetById(Guid id)
{
var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_INSIGNIA_ROUND");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var data = await _context.InsigniaPeriods.AsQueryable()
.Include(x => x.InsigniaEmployees)
.Where(x => x.Id == id)
.Select(p => new
{
period_id = p.Id,
period_amount = p.Amount,
period_name = p.Name,
period_round = p.Round,
period_start = p.StartDate,
period_end = p.EndDate,
period_status = p.IsLock == true ? "DONE" : (p.InsigniaRequests.Count() == 0 ? "WAITTING" : "PENDING"),
period_year = p.Year,
period_isActive = p.IsActive,
empPosId = p.InsigniaEmployees.Select(x => x.RefId),
period_doc = p.ReliefDoc == null ? Guid.Parse("00000000-0000-0000-0000-000000000000") : p.ReliefDoc.Id,
})
.FirstOrDefaultAsync();
if (data == null)
return Error(GlobalMessages.DataNotFound, 404);
var _data = new
{
period_id = data.period_id,
period_amount = data.period_amount,
period_name = data.period_name,
period_round = data.period_round,
period_start = data.period_start,
period_end = data.period_end,
period_status = data.period_status,
period_year = data.period_year,
period_isActive = data.period_isActive,
empPosId = data.empPosId,
period_doc = data.period_doc == Guid.Parse("00000000-0000-0000-0000-000000000000") ? null : await _documentService.ImagesPath(data.period_doc),
};
return Success(_data);
}
/// <summary>
/// สร้างรอบเครื่องราช
/// </summary>
/// <param name="req.Round">รอบที่</param>
/// <param name="req.Name">ชื่อรอบ</param>
/// <param name="req.Year">ปีที่เสนอ</param>
/// <param name="req.StartDate">วันที่เริ่มต้น</param>
/// <param name="req.EndDate">วันที่สิ้นสุด</param>
/// <param name="req.Amount">จำนวนวันแจ้งเตือน</param>
/// <param name="req.File">เอกสารประกอบ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost()]
public async Task<ActionResult<ResponseObject>> Post([FromForm] InsigniaPeriodRequest req)
{
var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_INSIGNIA_ROUND");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var revisionId = await _userProfileRepository.GetLastRevision(AccessToken);
var insigniaPeriod = await _context.InsigniaPeriods.AsQueryable()
.Where(x => x.Round == req.Round && x.Year == req.Year)
.FirstOrDefaultAsync();
if (insigniaPeriod != null)
return Error(GlobalMessages.InsigniaDupicate);
var period = new InsigniaPeriod
{
Round = req.Round,
Name = req.Name,
Year = req.Year,
StartDate = req.StartDate,
EndDate = req.EndDate,
Amount = req.Amount,
IsActive = true,
CreatedFullName = FullName ?? "System Administrator",
CreatedUserId = UserId ?? "",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
RevisionId = revisionId ?? Guid.Empty
};
foreach (var item in req.EmpPosId)
{
var insigniaEmployee =
new InsigniaEmployee
{
InsigniaPeriod = period,
RefId = item,
CreatedFullName = FullName ?? "System Administrator",
CreatedUserId = UserId ?? "",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
};
await _context.InsigniaEmployees.AddAsync(insigniaEmployee);
}
await _context.InsigniaPeriods.AddAsync(period);
await _context.SaveChangesAsync();
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);
period.ReliefDoc = doc;
}
await _context.SaveChangesAsync();
return Success();
}
/// <summary>
/// ลบรอบเครื่องราช
/// </summary>
/// <param name="id">Id เครื่องราช</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("{id:length(36)}")]
public async Task<ActionResult<ResponseObject>> Delete(Guid id)
{
var getPermission = await _permission.GetPermissionAPIAsync("DELETE", "SYS_INSIGNIA_ROUND");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var deleted = await _context.InsigniaPeriods.AsQueryable()
.Include(x => x.ReliefDoc)
.FirstOrDefaultAsync(x => x.Id == id);
if (deleted == null)
return NotFound();
_context.InsigniaPeriods.Remove(deleted);
await _context.SaveChangesAsync();
if (deleted.ReliefDoc != null)
await _documentService.DeleteFileAsync(deleted.ReliefDoc.Id);
return Success();
}
/// <summary>
/// แก้ไขรอบเครื่องราช
/// </summary>
/// <param name="id">Id เครื่องราช</param>
/// <param name="req.Round">รอบที่</param>
/// <param name="req.Name">ชื่อรอบ</param>
/// <param name="req.Year">ปีที่เสนอ</param>
/// <param name="req.StartDate">วันที่เริ่มต้น</param>
/// <param name="req.EndDate">วันที่สิ้นสุด</param>
/// <param name="req.Amount">จำนวนวันแจ้งเตือน</param>
/// <param name="req.File">เอกสารประกอบ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("{id:length(36)}")]
public async Task<ActionResult<ResponseObject>> Put([FromForm] InsigniaPeriodRequest req, Guid id)
{
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_INSIGNIA_ROUND");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
if (req == null)
return BadRequest();
var insigniaPeriod = await _context.InsigniaPeriods.AsQueryable()
.Where(x => x.Round == req.Round && x.Year == req.Year && x.Id != id)
.FirstOrDefaultAsync();
if (insigniaPeriod != null)
return Error(GlobalMessages.InsigniaDupicate);
var uppdated = await _context.InsigniaPeriods.AsQueryable()
.Include(x => x.InsigniaEmployees)
.Include(x => x.ReliefDoc)
.FirstOrDefaultAsync(x => x.Id == id);
if (uppdated == null)
return NotFound();
uppdated.Round = req.Round;
uppdated.Name = req.Name;
uppdated.Year = req.Year;
uppdated.StartDate = req.StartDate;
uppdated.EndDate = req.EndDate;
uppdated.Amount = req.Amount;
uppdated.LastUpdateFullName = FullName ?? "System Administrator";
uppdated.LastUpdateUserId = UserId ?? "";
uppdated.LastUpdatedAt = DateTime.Now;
_context.InsigniaEmployees.RemoveRange(uppdated.InsigniaEmployees);
foreach (var item in req.EmpPosId)
{
uppdated.InsigniaEmployees.Add(
new InsigniaEmployee
{
RefId = item,
CreatedFullName = FullName ?? "System Administrator",
CreatedUserId = UserId ?? "",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
});
}
if (Request.Form.Files != null && Request.Form.Files.Count != 0)
{
if (uppdated.ReliefDoc != null)
await _documentService.DeleteFileAsync(uppdated.ReliefDoc.Id);
var file = Request.Form.Files[0];
var fileExtension = Path.GetExtension(file.FileName);
var doc = await _documentService.UploadFileAsync(file, file.FileName);
uppdated.ReliefDoc = doc;
}
await _context.SaveChangesAsync();
return Success();
}
}
}