hrms-api-backend/BMA.EHR.Retirement.Service/Controllers/RetirementController.cs

485 lines
25 KiB
C#

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 class ObjectOrderRetire
{
public int Order { get; set; }
public int? Order1 { get; set; }
public int? Order2 { get; set; }
public int? Order3 { get; set; }
public string LastUpdateFullName { get; set; }
public string LastUpdateUserId { get; set; }
public DateTime? LastUpdatedAt { get; set; }
public Guid? Id { get; set; }
}
private async Task GenOrderByYear(Guid id)
{
var Org = await _context.Organizations.FirstOrDefaultAsync(x => x.OrganizationOrder == null);
var ocIdList = await _context.Organizations.Select(x => x.Id).ToListAsync();
if (Org != null)
ocIdList = _documentService.GetAllIdByRoot(Org.Id);
var retire = await _context.RetirementPeriods
.FirstOrDefaultAsync(x => x.Id == id);
if (retire == null)
return;
var _retireProfile = await _context.RetirementProfiles
.Where(x => x.RetirementPeriod == retire)
.ToListAsync();
var profiles = new List<ObjectOrderRetire>();
if (retire.Type.Trim().ToUpper().Contains("OFFICER"))
{
profiles = await (from x in _context.RetirementProfiles
where x.RetirementPeriod == retire
select new ObjectOrderRetire
{
Id = x.Id,
Order = x.Order,
Order1 = x.Profile == null ? 999999999 : ocIdList.IndexOf((Guid)(x.Profile.OcId)),
Order2 = x.Profile == null || x.Profile.PositionType == null ? 999999999 : x.Profile.PositionType.Order,
Order3 = x.Profile == null || x.Profile.PositionLevel == null ? 999999999 : x.Profile.PositionLevel.Level,
LastUpdateFullName = x.LastUpdateFullName,
LastUpdateUserId = x.LastUpdateUserId,
LastUpdatedAt = x.LastUpdatedAt,
}).ToListAsync();
}
if (retire.Type.Trim().ToUpper().Contains("EMPLOYEE"))
{
profiles = await (from x in _context.RetirementProfiles
where x.RetirementPeriod == retire
// x.Profile.PositionEmployeeLevelId == null ? null : x.Profile.PositionEmployeeLevelId.Order
select new ObjectOrderRetire
{
Id = x.Id,
Order = x.Order,
Order1 = x.Profile == null ? null : ocIdList.IndexOf((Guid)(x.Profile.OcId)),
LastUpdateFullName = x.LastUpdateFullName,
LastUpdateUserId = x.LastUpdateUserId,
LastUpdatedAt = x.LastUpdatedAt,
}).ToListAsync();
}
var _profiles = profiles.AsQueryable().OrderBy(x => x.Order1).ThenBy(x => x.Order2).ThenBy(x => x.Order3).ToList();
var order = 1;
foreach (var profile in _profiles)
{
var retireProfile = _retireProfile.Find(x => x.Id == profile.Id);
retireProfile.Order = order;
retireProfile.LastUpdateFullName = FullName ?? "System Administrator";
retireProfile.LastUpdateUserId = UserId ?? "";
retireProfile.LastUpdatedAt = DateTime.Now;
order++;
}
await _context.SaveChangesAsync();
}
private int SortOrg(Guid? ocId)
{
if (ocId == null)
return 999999999;
var Org = _context.Organizations.Include(x => x.OrganizationOrganization).FirstOrDefault(x => x.OrganizationOrder == null);
if (Org != null && Org.OrganizationOrganization != null && Org.OrganizationOrganization.Name.Contains("ปลัด"))
return -1;
var ocIdList = _context.Organizations.Select(x => x.Id).ToList();
if (Org != null)
ocIdList = _documentService.GetAllIdByRoot(Org.Id);
int index = ocIdList.IndexOf((Guid)ocId);
if (index == -1)
return 999999999;
return index;
}
#endregion
/// <summary>
/// list ประกาศเกษียณอายุราชการ
/// </summary>
/// <param name="type">ประเภทUser(officer,employee)(ตัวใหญ่หรือเล็กก็ได้)</param>
/// <param name="year">ปีงบประมาณ(ค.ศ.)</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("{type}/{year}")]
public async Task<ActionResult<ResponseObject>> GetRetirement(string type, int year)
{
if (type.Trim().ToUpper().Contains("OFFICER") || type.Trim().ToUpper().Contains("EMPLOYEE"))
{
var retire_old = await _context.RetirementPeriodHistorys
.Where(x => x.Year == year)
.Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper()))
.OrderByDescending(x => x.Round)
.Select(x => new
{
Id = x.Id,
CreatedAt = x.CreatedAt,
Year = x.Year,
Round = x.Round,
Total = x.Total,
})
.ToListAsync();
return Success(retire_old);
}
return Success();
}
/// <summary>
/// สร้างประกาศเกษียณใหม่
/// </summary>
/// <param name="type">ประเภทUser(officer,employee)(ตัวใหญ่หรือเล็กก็ได้)</param>
/// <param name="year">ปีงบประมาณ(ค.ศ.)</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("profile/{retire_history_id}/{option}/{type}/{year}")]
public async Task<ActionResult<ResponseObject>> CreateProfileRetirement(Guid retire_history_id, string option, string type, int year)
{
if (!type.Trim().ToUpper().Contains("EMPLOYEE") && !type.Trim().ToUpper().Contains("OFFICER"))
return Error("ประเภทพ้นราชการไม่ถูกต้อง");
var round = 1;
var retire = await _context.RetirementPeriods
.Include(x => x.RetirementPeriodHistorys)
.Include(x => x.RetirementProfiles)
.ThenInclude(x => x.Profile)
.Where(x => x.Year == year)
.Where(x => x.Type.Trim().ToUpper().Contains(type.Trim().ToUpper()))
.FirstOrDefaultAsync();
if (retire == null)
{
retire = new RetirementPeriod
{
Round = round,
TypeReport = null,
Type = type.Trim().ToUpper(),
Year = year,
CreatedUserId = FullName ?? "",
CreatedFullName = UserId ?? "System Administrator",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
};
await _context.RetirementPeriods.AddAsync(retire);
var profiles = await _context.Profiles.AsQueryable()
.Where(x => x.ProfileType.Trim().ToUpper().Contains(type.Trim().ToUpper()))
.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 = "pending",
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++;
}
await _context.SaveChangesAsync();
await GenOrderByYear(retire.Id);
}
else
{
var file_name = DateTime.Now.ToString();
await _documentService.GenerateJsonFile("xxx", "/retire", file_name);
var history = new RetirementPeriodHistory
{
RetirementPeriod = retire,
Round = retire.Round,
TypeReport = retire.TypeReport,
Year = retire.Year,
Type = retire.Type,
Total = retire.RetirementProfiles.Count(),
ProfileFile = file_name,
CreatedUserId = FullName ?? "",
CreatedFullName = UserId ?? "System Administrator",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
};
await _context.RetirementPeriodHistorys.AddAsync(history);
await _context.SaveChangesAsync();
retire.Round = retire.Round + 1;
retire.TypeReport = option.Trim().ToUpper();
retire.LastUpdateFullName = FullName ?? "System Administrator";
retire.LastUpdateUserId = UserId ?? "";
retire.LastUpdatedAt = DateTime.Now;
// retire_history_id
////ดึงไฟล์json
// foreach (var retire_profile in retire.RetirementProfiles)
// {
// retire_profile.Remove = retire_profile.Remove.Trim().ToUpper().Contains("CHANGE") ? "PENDING" : retire_profile.Remove;
// retire_profile.LastUpdateFullName = FullName ?? "System Administrator";
// retire_profile.LastUpdateUserId = UserId ?? "";
// retire_profile.LastUpdatedAt = DateTime.Now;
// }
await _context.SaveChangesAsync();
}
await _context.SaveChangesAsync();
var profile_new = await _context.RetirementProfiles
.Where(x => x.RetirementPeriod == retire)
.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.Year, retire.Round, retire.Type, profile = profile_new });
}
/// <summary>
/// View รายชื่อผู้เกษียณอายุราชการในประกาศ
/// </summary>
/// <param name="retireId">Id ประกาศ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("{retireId:length(36)}")]
public async Task<ActionResult<ResponseObject>> GetProfileRetirement(Guid retireId)
{
var retire = await _context.RetirementPeriodHistorys
.FirstOrDefaultAsync(x => x.Id == retireId);
if (retire == null)
return Error(GlobalMessages.InvalidRetirementRequest, 404);
return Success(retire);
}
/// <summary>
/// Delete รายชื่อผู้เกษียณอายุราชการในประกาศ
/// </summary>
/// <param name="retireProfileId">Id ผู้ใช้งานในประกาศ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("profile/{retireProfileId:length(36)}")]
public async Task<ActionResult<ResponseObject>> 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();
}
/// <summary>
/// Add รายชื่อผู้เกษียณอายุราชการในประกาศ
/// </summary>
/// <param name="retireId">Id ประกาศ</param>
/// <param name="profileId">Id ผู้ใช้งาน</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("profile/{retireId:length(36)}")]
public async Task<ActionResult<ResponseObject>> 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
.Include(x => x.RetirementPeriodHistorys)
.Include(x => x.RetirementProfiles)
.ThenInclude(x => x.Profile)
.FirstOrDefaultAsync(x => x.Id == retireId);
if (retire == null)
return Error(GlobalMessages.InvalidRetirementRequest, 404);
if (retire.RetirementProfiles.Where(x => x.Profile == profile).Count() > 0)
return Error("บุคคลนี้ได้ทำการเลือกไว้อยู่แล้ว");
foreach (var retire_profile in retire.RetirementProfiles)
{
retire_profile.Order++;
retire_profile.LastUpdateFullName = FullName ?? "System Administrator";
retire_profile.LastUpdateUserId = UserId ?? "";
retire_profile.LastUpdatedAt = DateTime.Now;
}
var data = new RetirementProfile
{
Order = 1,
Remove = "PENDING",
RetirementPeriod = retire,
Profile = profile,
CreatedUserId = FullName ?? "",
CreatedFullName = UserId ?? "System Administrator",
CreatedAt = DateTime.Now,
LastUpdateFullName = FullName ?? "System Administrator",
LastUpdateUserId = UserId ?? "",
LastUpdatedAt = DateTime.Now,
};
_context.RetirementProfiles.Add(data);
await _context.SaveChangesAsync();
// if (retire.RetirementPeriodHistorys.Count() <= 1)
// {
// await GenOrderByYear(retire.Id);
// }
return Success();
}
/// <summary>
/// แก้ไขข้อมูลบุคคล
/// </summary>
/// <param name="retireProfileId">Id ผู้ใช้งานในประกาศ</param>
/// <param name="reason">เหตุผล</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("reason")]
public async Task<ActionResult<ResponseObject>> 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 = "EDIT";
profile.Reason = req.Reason;
profile.LastUpdateFullName = FullName ?? "System Administrator";
profile.LastUpdateUserId = UserId ?? "";
profile.LastUpdatedAt = DateTime.Now;
_context.SaveChanges();
return Success();
}
/// <summary>
/// View เหตุผลแก้ไขข้อมูลบุคคล
/// </summary>
/// <param name="retireProfileId">Id ผู้ใช้งานในประกาศ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("reason/{retireProfileId:length(36)}")]
public async Task<ActionResult<ResponseObject>> 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);
}
/// <summary>
/// จัดอันดับเกษียณ
/// </summary>
/// <param name="retireId">Id ประกาศ</param>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("{retireId:length(36)}")]
public async Task<ActionResult<ResponseObject>> UpdateProfileRetirement(Guid retireId)
{
var retire = await _context.RetirementPeriods
.FirstOrDefaultAsync(x => x.Id == retireId);
if (retire == null)
return Error(GlobalMessages.InvalidRetirementRequest, 404);
await GenOrderByYear(retire.Id);
return Success();
}
}
}