diff --git a/.vscode/launch.json b/.vscode/launch.json index 205e817c..6be3e592 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -26,6 +26,31 @@ "/Views": "${workspaceFolder}/Views" } }, + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md. + "name": ".NET Core Launch (web) - Insignia", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/BMA.EHR.Insignia/bin/Debug/net7.0/BMA.EHR.Insignia.dll", + "args": [], + "cwd": "${workspaceFolder}/BMA.EHR.Insignia", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, { "name": ".NET Core Attach", "type": "coreclr", diff --git a/BMA.EHR.Application/ApplicationServicesRegistration.cs b/BMA.EHR.Application/ApplicationServicesRegistration.cs index bf6dc6df..0b99a7b6 100644 --- a/BMA.EHR.Application/ApplicationServicesRegistration.cs +++ b/BMA.EHR.Application/ApplicationServicesRegistration.cs @@ -61,6 +61,8 @@ namespace BMA.EHR.Application services.AddTransient(); + services.AddTransient(); + return services; } diff --git a/BMA.EHR.Application/Repositories/GenericRepository.cs b/BMA.EHR.Application/Repositories/GenericRepository.cs index 805b88ba..d825ccaf 100644 --- a/BMA.EHR.Application/Repositories/GenericRepository.cs +++ b/BMA.EHR.Application/Repositories/GenericRepository.cs @@ -115,7 +115,7 @@ namespace BMA.EHR.Application.Repositories } - protected async Task PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) + public async Task PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) { try { diff --git a/BMA.EHR.Application/Repositories/Leaves/GenericLeaveRepository.cs b/BMA.EHR.Application/Repositories/Leaves/GenericLeaveRepository.cs index 5fbbb8a1..2e550d71 100644 --- a/BMA.EHR.Application/Repositories/Leaves/GenericLeaveRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/GenericLeaveRepository.cs @@ -2,8 +2,11 @@ using BMA.EHR.Domain.Models.Base; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; +using Newtonsoft.Json; using System.IO.Pipes; +using System.Net.Http.Headers; using System.Security.Claims; +using System.Text; namespace BMA.EHR.Application.Repositories.Leaves { @@ -43,6 +46,38 @@ namespace BMA.EHR.Application.Repositories.Leaves #region " Methods " + public async Task PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) + { + try + { + // กำหนด timeout เป็น 30 นาที + using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30)); + using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token); + var json = JsonConvert.SerializeObject(body); + var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); + //stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + using (var client = new HttpClient()) + { + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", "")); + client.DefaultRequestHeaders.Add("api-key", apiKey); + var _res = await client.PostAsync(apiPath, stringContent, combinedCts.Token); + if (_res.IsSuccessStatusCode) + { + var _result = await _res.Content.ReadAsStringAsync(); + + return _result; + } + return string.Empty; + } + } + catch + { + throw; + } + } + + public virtual async Task> GetAllAsync() { return await _dbSet.ToListAsync(); @@ -68,6 +103,24 @@ namespace BMA.EHR.Application.Repositories.Leaves return entity; } + public virtual async Task> AddRangeAsync(List entities) + { + foreach (var entity in entities) + { + if (entity is EntityBase) + { + (entity as EntityBase).CreatedUserId = UserId ?? ""; + (entity as EntityBase).CreatedFullName = FullName ?? "System Administrator"; + (entity as EntityBase).CreatedAt = DateTime.Now; + } + } + + await _dbSet.AddRangeAsync(entities); + await _dbContext.SaveChangesAsync(); + + return entities; + } + public virtual async Task UpdateAsync(T entity) { if (entity is EntityBase) diff --git a/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveBeginingRepository.cs b/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveBeginingRepository.cs index 2d14db9c..a62aa291 100644 --- a/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveBeginingRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveBeginingRepository.cs @@ -80,7 +80,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task UpdateLeaveUsageAsync(int year, Guid typeId, Guid userId, double day) { // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (pf == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -102,7 +102,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task UpdateLeaveCountAsync(int year, Guid typeId, Guid userId, int count) { // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (pf == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -124,7 +124,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task GetByYearAndTypeIdForUserAsync(int year, Guid typeId, Guid userId) { // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (pf == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -263,7 +263,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task GetByYearAndTypeIdForUser2Async(int year, Guid typeId, Guid userId) { // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (pf == null) { return null; diff --git a/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveRequestRepository.cs b/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveRequestRepository.cs index 972a228d..54f1488d 100644 --- a/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveRequestRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/LeaveRequests/LeaveRequestRepository.cs @@ -254,7 +254,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task> GetLeaveRequestByYearAsync(int year, Guid userId) { // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { @@ -307,11 +307,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests rawData = rawData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)); } - else if (role == "PARENT") - { - rawData = rawData - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); - } + // else if (role == "PARENT") + // { + // rawData = rawData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); + // } else if (role == "NORMAL") { rawData = rawData @@ -354,7 +354,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests var rawData = _dbContext.Set().AsNoTracking() .Include(x => x.Type) .Where(x => x.LeaveStatus != "DRAFT") - .OrderByDescending(x => x.CreatedAt) + .OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt)) .AsQueryable(); if (year != 0) @@ -380,7 +380,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests var rawData = _dbContext.Set().AsNoTracking() .Include(x => x.Type) .Where(x => x.LeaveStatus != "DRAFT") - .OrderByDescending(x => x.CreatedAt) + .OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt)) .AsQueryable(); // fix issue : 1830 if (year != 0) @@ -421,11 +421,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests rawData = rawData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)); } - else if (role == "PARENT") - { - rawData = rawData - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); - } + // else if (role == "PARENT") + // { + // rawData = rawData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); + // } else if (role == "NORMAL") { rawData = rawData @@ -447,7 +447,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests .Include(x => x.Type) .Where(x => keycloakIdList.Contains(x.KeycloakUserId)) .Where(x => x.LeaveStatus != "DRAFT") - .OrderByDescending(x => x.CreatedAt) + .OrderByDescending(x =>(x.DateSendLeave ?? x.CreatedAt)) .AsQueryable(); if (year != 0) @@ -497,7 +497,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests public async Task GetSumLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year) { // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(keycloakUserId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(keycloakUserId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(keycloakUserId, AccessToken); if (pf == null) throw new Exception(GlobalMessages.DataNotFound); @@ -558,6 +558,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests var data = await _dbContext.Set().AsQueryable().AsNoTracking() .Include(x => x.Type) .Where(x => x.LeaveStartDate.Date < beforeDate.Date) + //.Where(x => x.CreatedAt < beforeDate) .Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.Type.Id == leaveTypeId) .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") @@ -568,6 +569,22 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests return data; } + public async Task GetLastLeaveRequestByTypeForUserAsync2(Guid keycloakUserId, Guid leaveTypeId, DateTime beforeDate) + { + var data = await _dbContext.Set().AsQueryable().AsNoTracking() + .Include(x => x.Type) + //.Where(x => x.LeaveStartDate.Date < beforeDate.Date) + .Where(x => (x.DateSendLeave ?? x.CreatedAt) < beforeDate) + .Where(x => x.KeycloakUserId == keycloakUserId) + .Where(x => x.Type.Id == leaveTypeId) + .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") + //.Where(x => x.LeaveStatus != "REJECT" && x.LeaveStatus != "DELETE") + .OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt)) + .FirstOrDefaultAsync(); + + return data; + } + public async Task> GetCancelLeaveRequestForAdminAsync(int year, Guid type, string status, string role, string? nodeId, int? node) { var rawData = _dbContext.Set().AsNoTracking() @@ -610,11 +627,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests rawData = rawData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)); } - else if (role == "PARENT") - { - rawData = rawData - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); - } + // else if (role == "PARENT") + // { + // rawData = rawData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); + // } else if (role == "NORMAL") { rawData = rawData @@ -634,7 +651,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests try { // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(data.KeycloakUserId, AccessToken ?? ""); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken ?? ""); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken ?? ""); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -659,6 +676,9 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests thisYear = thisYear + 1; } await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, data.Type.Id, data.KeycloakUserId, -1 * data.LeaveTotal); + // update leave count ลดลง 1 ครั้ง + await _leaveBeginningRepository.UpdateLeaveCountAsync(thisYear, data.Type.Id, data.KeycloakUserId, -1); + var _baseAPI = _configuration["API"]; var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{data.Id}"; @@ -708,7 +728,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests } // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? ""); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken ?? ""); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? ""); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -797,7 +817,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests } // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? ""); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken ?? ""); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? ""); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -884,6 +904,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests rawData.LeaveStatus = "NEW"; + rawData.DateSendLeave = DateTime.Now; // Update วันที่ยื่นลาเป็นวันที่ปัจจุบัน //rawData.ApproveStep = "st2"; await UpdateAsync(rawData); @@ -1222,7 +1243,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests else { // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -1268,6 +1289,8 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests status = "approve", reason = rawData.LeaveDetail, leaveId = rawData.Id, + leaveSubTypeName = rawData.LeaveSubTypeName, + coupleDayLevelCountry = rawData.CoupleDayLevelCountry, }); // var _result = await _res.Content.ReadAsStringAsync(); } @@ -1291,6 +1314,8 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests status = "approve", reason = rawData.LeaveDetail, leaveId = rawData.Id, + leaveSubTypeName = rawData.LeaveSubTypeName, + coupleDayLevelCountry = rawData.CoupleDayLevelCountry, }); } } @@ -1388,7 +1413,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests else { // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -1675,10 +1700,10 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests { data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList(); } - else if (role == "PARENT") - { - data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => @@ -1694,7 +1719,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT") { data = data - .Where(x => nodeByReq == 4 ? x.Child4Id == Guid.Parse(nodeIdByReq) : nodeByReq == 3 ? x.Child3Id == Guid.Parse(nodeIdByReq) : nodeByReq == 2 ? x.Child2Id == Guid.Parse(nodeIdByReq) : nodeByReq == 1 ? x.Child1Id == Guid.Parse(nodeIdByReq) : nodeByReq == 0 ? x.RootId == Guid.Parse(nodeIdByReq) : true) + .Where(x => nodeByReq == 4 ? x.Child4DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 3 ? x.Child3DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 2 ? x.Child2DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 1 ? x.Child1DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 0 ? x.RootDnaId == Guid.Parse(nodeIdByReq) : true) .ToList(); } // รายงานการลางานจำแนกตามเพศฯ Template ให้หน่วยงานแสดงก่อนส่วนราชการ @@ -1835,6 +1860,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests .Include(x => x.Type) .Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.Type.Id == leaveTypeId) + //.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate) .Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") .ToListAsync(); @@ -1845,6 +1871,74 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests return 0; } + public async Task GetSumApproveLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate) + { + var data = await _dbContext.Set().AsQueryable().AsNoTracking() + .Include(x => x.Type) + .Where(x => x.KeycloakUserId == keycloakUserId) + .Where(x => x.Type.Id == leaveTypeId) + .Where(x => (x.DateSendLeave ?? x.CreatedAt).Date >= startDate && (x.DateSendLeave ??x.CreatedAt).Date < endDate) + //.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) + .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") + .ToListAsync(); + + if (data.Count > 0) + return data.Sum(x => x.LeaveTotal); + else + return 0; + } + + /// + /// วันลาที่สร้างแบบร่างยังไม่ได้ยื่น + /// + /// + /// + /// + /// + /// + public async Task GetSumDraftLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate) + { + var data = await _dbContext.Set().AsQueryable().AsNoTracking() + .Include(x => x.Type) + .Where(x => x.KeycloakUserId == keycloakUserId) + .Where(x => x.Type.Id == leaveTypeId) + .Where(x => (x.DateSendLeave ?? x.CreatedAt).Date >= startDate + && (x.DateSendLeave ?? x.CreatedAt).Date < endDate) + //.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) + .Where(x => x.LeaveStatus == "DRAFT") + .ToListAsync(); + + if (data.Count > 0) + return data.Sum(x => x.LeaveTotal); + else + return 0; + } + + /// + /// วันลาที่ยื่นแล้วรอพิจารณา + /// + /// + /// + /// + /// + /// + public async Task GetSumNewLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate) + { + var data = await _dbContext.Set().AsQueryable().AsNoTracking() + .Include(x => x.Type) + .Where(x => x.KeycloakUserId == keycloakUserId) + .Where(x => x.Type.Id == leaveTypeId) + .Where(x => (x.DateSendLeave ?? x.CreatedAt).Date >= startDate && (x.DateSendLeave ??x.CreatedAt).Date < endDate) + //.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) + .Where(x => x.LeaveStatus == "NEW") + .ToListAsync(); + + if (data.Count > 0) + return data.Sum(x => x.LeaveTotal); + else + return 0; + } + public async Task GetCountApproveLeaveByTypeAndRangeForUser(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate) { var data = await _dbContext.Set().AsQueryable().AsNoTracking() @@ -1852,6 +1946,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests .Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.Type.Id == leaveTypeId) .Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) + //.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate) .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") .ToListAsync(); diff --git a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/AdditionalCheckRequestRepository.cs b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/AdditionalCheckRequestRepository.cs index 3dca61e1..0544e261 100644 --- a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/AdditionalCheckRequestRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/AdditionalCheckRequestRepository.cs @@ -185,11 +185,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants data = data .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); } - else if (role == "PARENT") - { - data = data - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList(); - } + // else if (role == "PARENT") + // { + // data = data + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => diff --git a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/LeaveProcessJobStatusRepository.cs b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/LeaveProcessJobStatusRepository.cs new file mode 100644 index 00000000..5e9944ad --- /dev/null +++ b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/LeaveProcessJobStatusRepository.cs @@ -0,0 +1,795 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Text.Json; +using System.IO; +using BMA.EHR.Application.Common.Interfaces; +using BMA.EHR.Application.Repositories.Leaves.LeaveRequests; +using BMA.EHR.Application.Repositories.MetaData; +using BMA.EHR.Application.Responses.Profiles; +using BMA.EHR.Domain.Extensions; +using BMA.EHR.Domain.Models.Leave.TimeAttendants; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; + +namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants +{ + public class LeaveProcessJobStatusRepository: GenericLeaveRepository + { + #region " Fields " + + private readonly ILeaveDbContext _dbContext; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly UserProfileRepository _userProfileRepository; + private readonly HolidayRepository _holidayRepository; + private readonly DutyTimeRepository _dutyTimeRepository; + private readonly UserDutyTimeRepository _userDutyTimeRepository; + private readonly ProcessUserTimeStampRepository _processUserTimeStampRepository; + private readonly LeaveRequestRepository _leaveRequestRepository; + private readonly IConfiguration _configuration; + private readonly IWebHostEnvironment _env; + + #endregion + + #region " Constructor and Destructor " + + public LeaveProcessJobStatusRepository(ILeaveDbContext dbContext, + IHttpContextAccessor httpContextAccessor, + UserProfileRepository userProfileRepository, + HolidayRepository holidayRepository, + DutyTimeRepository dutyTimeRepository, + UserDutyTimeRepository userDutyTimeRepository, + ProcessUserTimeStampRepository processUserTimeStampRepository, + LeaveRequestRepository leaveRequestRepository, + IConfiguration configuration, + IWebHostEnvironment env) : base(dbContext, httpContextAccessor) + { + _dbContext = dbContext; + _httpContextAccessor = httpContextAccessor; + _userProfileRepository = userProfileRepository; + _holidayRepository = holidayRepository; + _configuration = configuration; + _leaveRequestRepository = leaveRequestRepository; + _dutyTimeRepository = dutyTimeRepository; + _userDutyTimeRepository = userDutyTimeRepository; + _processUserTimeStampRepository = processUserTimeStampRepository; + _env = env; + } + + #endregion + + #region " Methods " + + /// + /// ดึงข้อมูล Job Status จาก TaskId + /// + public async Task GetByTaskIdAsync(Guid id) + { + var data = await _dbContext.Set() + .Where(x => x.Id == id) + .FirstOrDefaultAsync(); + + return data; + } + + /// + /// ดึงข้อมูล Job Status จาก UserId และสถานะ + /// + public async Task> GetByUserIdAndStatusAsync(Guid userId, string status) + { + var data = await _dbContext.Set() + .Where(x => x.CreatedUserId == userId.ToString("D") && x.Status == status) + .OrderByDescending(x => x.CreatedDate) + .ToListAsync(); + + return data; + } + + /// + /// ดึงข้อมูล Job Status จาก UserId + /// + public async Task> GetByUserIdAsync(Guid userId) + { + var data = await _dbContext.Set() + .Where(x => x.CreatedUserId == userId.ToString("D")) + .OrderByDescending(x => x.CreatedDate) + .ToListAsync(); + + return data; + } + + /// + /// ดึงข้อมูล Job Status ที่ยัง pending หรือ processing + /// + public async Task> GetPendingOrProcessingJobsAsync(Guid userId) + { + var data = await _dbContext.Set() + .Where(x => x.CreatedUserId == userId.ToString("D") && + (x.Status == "PENDING" || x.Status == "PROCESSING")) + //.OrderByDescending(x => x.CreatedDate) + .ToListAsync(); + + return data; + } + + public async Task> GetPendingJobsAsync() + { + var data = await _dbContext.Set() + .Where(x => x.Status == "PENDING") + .ToListAsync(); + + return data; + } + + /// + /// อัปเดตสถานะเป็น Processing + /// + public async Task UpdateToProcessingAsync(Guid id) + { + var job = await GetByTaskIdAsync(id); + if (job != null) + { + job.Status = "PROCESSING"; + job.ProcessingDate = DateTime.Now; + await UpdateAsync(job); + } + return job!; + } + + /// + /// อัปเดตสถานะเป็น Completed + /// + public async Task UpdateToCompletedAsync(Guid id, string? additionalData = null) + { + var job = await GetByTaskIdAsync(id); + if (job != null) + { + job.Status = "COMPLETED"; + job.CompletedDate = DateTime.Now; + await UpdateAsync(job); + } + return job!; + } + + /// + /// อัปเดตสถานะเป็น Failed + /// + public async Task UpdateToFailedAsync(Guid id, string errorMessage) + { + var job = await GetByTaskIdAsync(id); + if (job != null) + { + job.Status = "FAILED"; + job.CompletedDate = DateTime.Now; + job.ErrorMessage = errorMessage; + await UpdateAsync(job); + } + return job!; + } + + public async Task ProcessTaskAsync(Guid rootDnaId, DateTime? startDate, DateTime? endDate) + { + + var profiles = new List(); + var dateStart = startDate?.Date ?? DateTime.Now.Date; + var dateEnd = endDate?.Date ?? DateTime.Now.Date; + + var holidays = await _holidayRepository.GetHolidayAsync(dateStart, dateEnd); + var weekend = _holidayRepository.GetWeekEnd(dateStart, dateEnd); + var excludeDates = holidays.Union(weekend).ToList(); + + var dateList = new List(); + for (DateTime i = dateStart; i <= dateEnd; i = i.AddDays(1)) + { + if (holidays.Contains(i)) + { + var d = await _holidayRepository.GetHolidayAsync(i); + dateList.Add(new LoopDate + { + date = i, + isHoliday = true, + isWeekEnd = false, + dateRemark = d + }); + } + else if (weekend.Contains(i)) + { + dateList.Add(new LoopDate + { + date = i, + isHoliday = true, + isWeekEnd = false, + dateRemark = "วันหยุด" + }); + } + else + { + dateList.Add(new LoopDate + { + date = i, + isHoliday = false, + isWeekEnd = false, + dateRemark = "" + }); + } + } + + var defaultRound = await _dutyTimeRepository.GetDefaultAsync(); + if (defaultRound == null) + { + throw new Exception("ไม่พบรอบการลงเวลา Default"); + } + + var employees = new List(); + + foreach (var dd in dateList.Where(x => !x.isHoliday && !x.isWeekEnd)) + { + profiles = await _userProfileRepository.GetAllOfficerByRootDnaId(rootDnaId.ToString(),dd.date); + foreach (var p in profiles) + { + var count = 1; + var keycloakUserId = p.Keycloak ?? Guid.Empty; + + var timeStamps = await _processUserTimeStampRepository.GetTimestampByDateAsync(keycloakUserId, dd.date); + + var fullName = $"{p.Prefix}{p.FirstName} {p.LastName}"; + + var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id, dd.date); + var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty; + var userRound = await _dutyTimeRepository.GetByIdAsync(roundId); + + var duty = userRound ?? defaultRound; + + // check วันลาของแต่ละคน + var leaveReq = await _leaveRequestRepository.GetLeavePeriodAsync(keycloakUserId, dd.date); + var remarkStr = string.Empty; + var status = string.Empty; + var stampType = string.Empty; + var stampAmount = 0.0; + + if (leaveReq != null) + { + switch (leaveReq.Type.Code.ToUpper()) + { + case "LV-001": + case "LV-002": + case "LV-005": + remarkStr += leaveReq.Type.Name; + var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper(); + + if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + + + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRangeEnd == "MORNING") + // remarkStr += "ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += "ครึ่งวันบ่าย"; + + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRange != leaveRangeEnd) + { + if (leaveRangeEnd == "MORNING") + remarkStr += " - ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += " - ครึ่งวันบ่าย"; + } + } + else + { + if(dd.date == leaveReq.LeaveStartDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else if(dd.date == leaveReq.LeaveEndDate.Date) + { + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRangeEnd == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + else + remarkStr += "เต็มวัน"; + } + else + { + remarkStr += "เต็มวัน"; + } + } + + + break; + default: + remarkStr += leaveReq.Type.Name; + break; + } + status = "LEAVE"; + if(leaveReq.LeaveStartDate.Date == dd.date) + { + stampType = leaveReq.LeaveRange ?? ""; + stampAmount = leaveReq.LeaveRange != "ALL" ? 0.5 : 1; + } + else if(leaveReq.LeaveEndDate.Date == dd.date) + { + stampAmount = leaveReq.LeaveRangeEnd != "ALL" ? 0.5 : 1; + stampType = leaveReq.LeaveRangeEnd ?? ""; + } + else + stampAmount = leaveReq.LeaveRange != "ALL" || leaveReq.LeaveRangeEnd != "ALL" ? 0.5 : 1; + if(stampType == "ALL") stampType = "FULL_DAY"; + } + else + { + if (timeStamps == null) + { + if (dd.date <= DateTime.Now.Date) + { + remarkStr = "ขาดราชการ"; + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + if (dd.isHoliday == true) + { + remarkStr = $"วันหยุด ({dd.dateRemark})"; + status = "HOLIDAY"; + } + else if (dd.isWeekEnd) + { + remarkStr = dd.dateRemark; + status = "WEEKEND"; + } + } + else remarkStr = ""; + } + else + { + // check status ของการลงเวลา + if (timeStamps.CheckOut != null) + { + if (timeStamps.CheckOutStatus == "ABSENT") + { + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckOut ? $" (นอกสถานที่:{timeStamps.CheckOutLocationName})".Trim() : ""); + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + } + else if (timeStamps.CheckInStatus == "ABSENT") + { + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + } + else if (timeStamps.CheckInStatus == "LATE") + { + remarkStr = "สาย" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + status = "LATE"; + stampType = "FULL_DAY"; + stampAmount = 1; + //lateTotal += 1; + } + else + remarkStr = !timeStamps.IsLocationCheckIn ? $" นอกสถานที่:{timeStamps.CheckInLocationName}".Trim() : ""; + } + else + { + if (timeStamps.CheckInStatus == "ABSENT") + { + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + } + else if (timeStamps.CheckInStatus == "LATE") + { + status = "LATE"; + stampType = "FULL_DAY"; + stampAmount = 1; + remarkStr = "สาย" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + //lateTotal += 1; + } + else + remarkStr = !timeStamps.IsLocationCheckIn ? $" นอกสถานที่:{timeStamps.CheckInLocationName}".Trim() : ""; + } + } + } + + var emp = new DateResultReport + { + profileId = p.Id.ToString(), + stampDate = dd.date, + stampType = stampType, + stampAmount = stampAmount, + remark = remarkStr, + status = status + }; + + employees.Add(emp); + count++; + } + + // Write employees to JSON file + // var fileName = $"employees_{DateTime.Now:yyyyMMdd_HHmmss}.txt"; + // var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Exports", fileName); + + // // Ensure directory exists + // var directory = Path.GetDirectoryName(filePath); + // if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + // { + // Directory.CreateDirectory(directory); + // } + + // var jsonOptions = new JsonSerializerOptions + // { + // WriteIndented = true, + // Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping + // }; + + // var jsonContent = JsonSerializer.Serialize(employees, jsonOptions); + // await File.WriteAllTextAsync(filePath, jsonContent); + } + + //call api + var apiPath = $"{_configuration["API"]}/org/unauthorize/profile/absent-late/batch"; + var apiKey = _configuration["API_KEY"]; + var body = new + { + records = employees.Where(x => x.status == "ABSENT" || x.status == "LATE").ToList() + }; + + var apiResult = await PostExternalAPIAsync(apiPath, AccessToken ?? "", body, apiKey); + if(apiResult == "") + { + throw new Exception($"เรียก API {apiPath} ไม่สำเร็จ"); + } + } + + public async Task ProcessEmpTaskAsync(Guid rootDnaId, DateTime? startDate, DateTime? endDate) + { + + var profiles = new List(); + var dateStart = startDate?.Date ?? DateTime.Now.Date; + var dateEnd = endDate?.Date ?? DateTime.Now.Date; + + var holidays = await _holidayRepository.GetHolidayAsync(dateStart, dateEnd); + var weekend = _holidayRepository.GetWeekEnd(dateStart, dateEnd); + var excludeDates = holidays.Union(weekend).ToList(); + + var dateList = new List(); + for (DateTime i = dateStart; i <= dateEnd; i = i.AddDays(1)) + { + if (holidays.Contains(i)) + { + var d = await _holidayRepository.GetHolidayAsync(i); + dateList.Add(new LoopDate + { + date = i, + isHoliday = true, + isWeekEnd = false, + dateRemark = d + }); + } + else if (weekend.Contains(i)) + { + dateList.Add(new LoopDate + { + date = i, + isHoliday = true, + isWeekEnd = false, + dateRemark = "วันหยุด" + }); + } + else + { + dateList.Add(new LoopDate + { + date = i, + isHoliday = false, + isWeekEnd = false, + dateRemark = "" + }); + } + } + + var defaultRound = await _dutyTimeRepository.GetDefaultAsync(); + if (defaultRound == null) + { + throw new Exception("ไม่พบรอบการลงเวลา Default"); + } + + var employees = new List(); + + foreach (var dd in dateList.Where(x => !x.isHoliday && !x.isWeekEnd)) + { + profiles = await _userProfileRepository.GetAllEmployeeByRootDnaId(rootDnaId.ToString(),dd.date); + foreach (var p in profiles) + { + var count = 1; + var keycloakUserId = p.Keycloak ?? Guid.Empty; + + var timeStamps = await _processUserTimeStampRepository.GetTimestampByDateAsync(keycloakUserId, dd.date); + + var fullName = $"{p.Prefix}{p.FirstName} {p.LastName}"; + + var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id, dd.date); + var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty; + var userRound = await _dutyTimeRepository.GetByIdAsync(roundId); + + var duty = userRound ?? defaultRound; + + // check วันลาของแต่ละคน + var leaveReq = await _leaveRequestRepository.GetLeavePeriodAsync(keycloakUserId, dd.date); + var remarkStr = string.Empty; + var status = string.Empty; + var stampType = string.Empty; + var stampAmount = 0.0; + + if (leaveReq != null) + { + switch (leaveReq.Type.Code.ToUpper()) + { + case "LV-001": + case "LV-002": + case "LV-005": + remarkStr += leaveReq.Type.Name; + var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper(); + + if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + + + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRangeEnd == "MORNING") + // remarkStr += "ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += "ครึ่งวันบ่าย"; + + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRange != leaveRangeEnd) + { + if (leaveRangeEnd == "MORNING") + remarkStr += " - ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += " - ครึ่งวันบ่าย"; + } + } + else + { + if(dd.date == leaveReq.LeaveStartDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else if(dd.date == leaveReq.LeaveEndDate.Date) + { + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRangeEnd == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else + { + remarkStr += "เต็มวัน"; + } + } + break; + default: + remarkStr += leaveReq.Type.Name; + break; + } + status = "LEAVE"; + if(leaveReq.LeaveStartDate.Date == dd.date) + { + stampType = leaveReq.LeaveRange ?? ""; + stampAmount = leaveReq.LeaveRange != "ALL" ? 0.5 : 1; + } + else if(leaveReq.LeaveEndDate.Date == dd.date) + { + stampAmount = leaveReq.LeaveRangeEnd != "ALL" ? 0.5 : 1; + stampType = leaveReq.LeaveRangeEnd ?? ""; + } + else + stampAmount = leaveReq.LeaveRange != "ALL" || leaveReq.LeaveRangeEnd != "ALL" ? 0.5 : 1; + if(stampType == "ALL") stampType = "FULL_DAY"; + //stampAmount = leaveReq.LeaveRange != "ALL" || leaveReq.LeaveRangeEnd != "ALL" ? 0.5 : 1; + } + else + { + if (timeStamps == null) + { + if (dd.date <= DateTime.Now.Date) + { + remarkStr = "ขาดราชการ"; + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + if (dd.isHoliday == true) + { + remarkStr = $"วันหยุด ({dd.dateRemark})"; + status = "HOLIDAY"; + } + else if (dd.isWeekEnd) + { + remarkStr = dd.dateRemark; + status = "WEEKEND"; + } + } + else remarkStr = ""; + } + else + { + // check status ของการลงเวลา + if (timeStamps.CheckOut != null) + { + if (timeStamps.CheckOutStatus == "ABSENT") + { + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckOut ? $" (นอกสถานที่:{timeStamps.CheckOutLocationName})".Trim() : ""); + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + } + else if (timeStamps.CheckInStatus == "ABSENT") + { + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + } + else if (timeStamps.CheckInStatus == "LATE") + { + remarkStr = "สาย" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + status = "LATE"; + stampType = "FULL_DAY"; + stampAmount = 1; + //lateTotal += 1; + } + else + remarkStr = !timeStamps.IsLocationCheckIn ? $" นอกสถานที่:{timeStamps.CheckInLocationName}".Trim() : ""; + } + else + { + if (timeStamps.CheckInStatus == "ABSENT") + { + status = "ABSENT"; + stampType = "FULL_DAY"; + stampAmount = 1; + remarkStr = "ขาดราชการ" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + } + else if (timeStamps.CheckInStatus == "LATE") + { + status = "LATE"; + stampType = "FULL_DAY"; + stampAmount = 1; + remarkStr = "สาย" + (!timeStamps.IsLocationCheckIn ? $" (นอกสถานที่:{timeStamps.CheckInLocationName})".Trim() : ""); + //lateTotal += 1; + } + else + remarkStr = !timeStamps.IsLocationCheckIn ? $" นอกสถานที่:{timeStamps.CheckInLocationName}".Trim() : ""; + } + } + } + + var emp = new DateResultReport + { + profileId = p.Id.ToString(), + stampDate = dd.date, + stampType = stampType, + stampAmount = stampAmount, + remark = remarkStr, + status = status + }; + + employees.Add(emp); + count++; + } + + // Write employees to JSON file + // var fileName = $"employees_{DateTime.Now:yyyyMMdd_HHmmss}.txt"; + // var filePath = Path.Combine(_env.ContentRootPath, "Exports", fileName); + + // // Ensure directory exists + // var directory = Path.GetDirectoryName(filePath); + // if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + // { + // Directory.CreateDirectory(directory); + // } + + // var jsonOptions = new JsonSerializerOptions + // { + // WriteIndented = true, + // Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping + // }; + + // var jsonContent = JsonSerializer.Serialize(employees, jsonOptions); + // Console.WriteLine($"Writing file to: {filePath}"); + // await File.WriteAllTextAsync(filePath, jsonContent); + // Console.WriteLine($"File written successfully: {fileName}"); + } + + // call api + var apiPath = $"{_configuration["API"]}/org/unauthorize/profile-employee/absent-late/batch"; + var apiKey = _configuration["API_KEY"]; + var body = new + { + records = employees.Where(x => x.status == "ABSENT" || x.status == "LATE").ToList() + }; + + var apiResult = await PostExternalAPIAsync(apiPath, AccessToken ?? "", body, apiKey); + if(apiResult == "") + { + throw new Exception($"เรียก API {apiPath} ไม่สำเร็จ"); + } + } + + + public async Task ProcessPendingJobsAsync() + { + var pendingJobs = await GetPendingJobsAsync(); + Console.WriteLine($"พบงานที่ค้างอยู่ในสถานะ PENDING จำนวน {pendingJobs.Count} งาน"); + + foreach (var job in pendingJobs) + { + try + { + // อัปเดตสถานะเป็น Processing + await UpdateToProcessingAsync(job.Id); + + // ทำงานที่ต้องการที่นี่ (เช่น เรียก API, ประมวลผลข้อมูล ฯลฯ) + await ProcessTaskAsync(job.RootDnaId,job.StartDate, job.EndDate); + await ProcessEmpTaskAsync(job.RootDnaId,job.StartDate, job.EndDate); + + // อัปเดตสถานะเป็น Completed + await UpdateToCompletedAsync(job.Id); + } + catch (Exception ex) + { + // หากเกิดข้อผิดพลาด อัปเดตสถานะเป็น Failed พร้อมข้อความแสดงข้อผิดพลาด + await UpdateToFailedAsync(job.Id, ex.Message); + } + } + } + + #endregion + } + + class LoopDate + { + public DateTime date { get; set; } + + public bool isHoliday { get; set; } + + public bool isWeekEnd { get; set; } + + public string dateRemark { get; set; } + + } + + class DateResultReport + { + public string? profileId { get; set; } + public DateTime stampDate { get; set; } + public string stampType { get; set; } + public double stampAmount { get; set; } + public string remark { get; set; } + public string status { get; set; } + } + +} \ No newline at end of file diff --git a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/ProcessUserTimeStampRepository.cs b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/ProcessUserTimeStampRepository.cs index 64d32a19..77aba421 100644 --- a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/ProcessUserTimeStampRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/ProcessUserTimeStampRepository.cs @@ -172,10 +172,10 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants { data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList(); } - else if (role == "PARENT") - { - data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => @@ -191,11 +191,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT") { data = data.Where(x => - nodeByReq == 4 ? x.Child4Id == Guid.Parse(nodeIdByReq) : - nodeByReq == 3 ? x.Child3Id == Guid.Parse(nodeIdByReq) : - nodeByReq == 2 ? x.Child2Id == Guid.Parse(nodeIdByReq) : - nodeByReq == 1 ? x.Child1Id == Guid.Parse(nodeIdByReq) : - nodeByReq == 0 ? x.RootId == Guid.Parse(nodeIdByReq) : true + nodeByReq == 4 ? x.Child4DnaId == Guid.Parse(nodeIdByReq) : + nodeByReq == 3 ? x.Child3DnaId == Guid.Parse(nodeIdByReq) : + nodeByReq == 2 ? x.Child2DnaId == Guid.Parse(nodeIdByReq) : + nodeByReq == 1 ? x.Child1DnaId == Guid.Parse(nodeIdByReq) : + nodeByReq == 0 ? x.RootDnaId == Guid.Parse(nodeIdByReq) : true ).ToList(); } return data; @@ -227,6 +227,19 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants return data; } + public async Task> GetTimeStampHistoryAsync2(Guid keycloakId, int year) + { + var fiscalDateStart = new DateTime(year - 1, 10, 1); + var fiscalDateEnd = new DateTime(year, 9, 30); + + var data = await _dbContext.Set() + .Where(u => u.KeycloakUserId == keycloakId) + .Where(u => u.CheckIn.Date >= fiscalDateStart && u.CheckIn.Date <= fiscalDateEnd) + .OrderByDescending(u => u.CheckIn.Date) + .ToListAsync(); + return data; + } + public async Task GetTimeStampHistoryForAdminCountAsync(DateTime startDate, DateTime endDate) { var data = await _dbContext.Set() @@ -288,12 +301,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants .Where(x => x.RootDnaId == Guid.Parse(nodeId!)) .ToList(); } - else if (role == "PARENT") - { - data = data - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) - .ToList(); - } + // else if (role == "PARENT") + // { + // data = data + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) + // .ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => diff --git a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/UserTimeStampRepository.cs b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/UserTimeStampRepository.cs index 2598dace..6dffcb6c 100644 --- a/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/UserTimeStampRepository.cs +++ b/BMA.EHR.Application/Repositories/Leaves/TimeAttendants/UserTimeStampRepository.cs @@ -140,12 +140,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants .Where(x => x.RootDnaId == Guid.Parse(nodeId!)) .ToList(); } - else if (role == "PARENT") - { - data = data - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) - .ToList(); - } + // else if (role == "PARENT") + // { + // data = data + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) + // .ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => diff --git a/BMA.EHR.Application/Repositories/PermissionRepository.cs b/BMA.EHR.Application/Repositories/PermissionRepository.cs index 84191f91..a63207ec 100644 --- a/BMA.EHR.Application/Repositories/PermissionRepository.cs +++ b/BMA.EHR.Application/Repositories/PermissionRepository.cs @@ -10,6 +10,7 @@ using System.Net.Http.Headers; using Microsoft.Extensions.Configuration; using System.Security.Claims; using System.Net.Http.Json; +using BMA.EHR.Application.Responses.Leaves; namespace BMA.EHR.Application.Repositories { @@ -76,6 +77,39 @@ namespace BMA.EHR.Application.Repositories } } + public async Task GetPermissionWithActingAPIAsync(string action, string system) + { + try + { + var apiPath = $"{_configuration["API"]}/org/permission/dotnet-acting/{action}/{system}"; + + using (var client = new HttpClient()) + { + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); + client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); + var req = await client.GetAsync(apiPath); + if (!req.IsSuccessStatusCode) + { + throw new Exception("Error calling permission API"); + } + var apiResult = await req.Content.ReadAsStringAsync(); + //return res; + + if (apiResult != null) + { + var raw = JsonConvert.DeserializeObject(apiResult); + return raw; + } + return null; + } + } + catch + { + throw; + } + } + public async Task GetPermissionOrgAPIAsync(string action, string system, string profileId) { try diff --git a/BMA.EHR.Application/Repositories/Reports/InsigniaReportRepository.cs b/BMA.EHR.Application/Repositories/Reports/InsigniaReportRepository.cs index c094738e..a1dd7936 100644 --- a/BMA.EHR.Application/Repositories/Reports/InsigniaReportRepository.cs +++ b/BMA.EHR.Application/Repositories/Reports/InsigniaReportRepository.cs @@ -893,7 +893,7 @@ namespace BMA.EHR.Application.Repositories.Reports select new { RowNo = 1, - DepartmentName = _userProfileRepository.GetOc(g.Key.OcId, 0, AccessToken).Root, //_organizationCommonRepository.GetOrganizationNameFullPath(g.Key.OcId, false, false), + DepartmentName = _userProfileRepository.GetOc(g.Key.OcId, 0, AccessToken)?.Root ?? "-", //_organizationCommonRepository.GetOrganizationNameFullPath(g.Key.OcId, false, false), G1Male = g.Sum(x => x.Gendor == "ชาย" && x.RequestInsigniaName == "เหรียญจักรพรรดิมาลา" ? 1 : 0), G1Female = g.Sum(x => x.Gendor == "หญิง" && x.RequestInsigniaName == "เหรียญจักรพรรดิมาลา" ? 1 : 0), G2Male = g.Sum(x => x.Gendor == "ชาย" ? 1 : 0), diff --git a/BMA.EHR.Application/Repositories/Reports/RetireReportRepository.cs b/BMA.EHR.Application/Repositories/Reports/RetireReportRepository.cs index ecb65e2f..6ad5a61a 100644 --- a/BMA.EHR.Application/Repositories/Reports/RetireReportRepository.cs +++ b/BMA.EHR.Application/Repositories/Reports/RetireReportRepository.cs @@ -192,7 +192,7 @@ namespace BMA.EHR.Application.Repositories.Reports }).ToList(); } string SignDate = retireHistorys.SignDate != null ? DateTime.Parse(retireHistorys.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-"; - return new { SignDate, retireHistorys.Detail, retireHistorys.Id, retireHistorys.CreatedAt, Year = retireHistorys.Year.ToThaiYear().ToString().ToThaiNumber(), retireHistorys.Round, retireHistorys.Type, retireHistorys.TypeReport, Total = retireHistorys.Total.ToString().ToThaiNumber(), profiles = mapProfiles }; + return new { SignDate, Detail = retireHistorys.Detail.ToThaiNumber(), retireHistorys.Id, retireHistorys.CreatedAt, Year = retireHistorys.Year.ToThaiYear().ToString().ToThaiNumber(), retireHistorys.Round, retireHistorys.Type, retireHistorys.TypeReport, Total = retireHistorys.Total.ToString().ToThaiNumber(), profiles = mapProfiles }; } } else @@ -312,7 +312,7 @@ namespace BMA.EHR.Application.Repositories.Reports root = (isDuplicateRoot ? "" : profile.root + "\n") + (isDuplicateHospital || !hospital.ToObject>().Contains(profile.child1) ? "" : profile.child1 + "\n") + (isDuplicatePosType ? "" : $"ตำแหน่งประเภท{profile.posTypeName}" + "\n") + - (isDuplicatePosLevel ? "" : $"ระดับ{profile.posLevelName}"), + (isDuplicatePosLevel ? "" : $"ระดับ{profile.posLevelName}").ToThaiNumber(), child = (profile.posExecutiveName == null ? "" : profile.posExecutiveName + "\n") + (profile.child4 == null ? "" : profile.child4 + "\n") + (profile.child3 == null ? "" : profile.child3 + "\n") + @@ -326,7 +326,7 @@ namespace BMA.EHR.Application.Repositories.Reports }).ToList(); } string SignDate = retire.SignDate != null ? DateTime.Parse(retire.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-"; - return new { SignDate, retire.Detail, retire.Id, retire.CreatedAt, Year = retire.Year.ToThaiYear().ToString().ToThaiNumber(), retire.Round, retire.Type, retire.TypeReport, Total = profile_retire.Count.ToString().ToThaiNumber(), profiles = mapProfiles }; + return new { SignDate, Detail = retire.Detail.ToThaiNumber(), retire.Id, retire.CreatedAt, Year = retire.Year.ToThaiYear().ToString().ToThaiNumber(), retire.Round, retire.Type, retire.TypeReport, Total = profile_retire.Count.ToString().ToThaiNumber(), profiles = mapProfiles }; } } #endregion diff --git a/BMA.EHR.Application/Repositories/UserProfileRepository.cs b/BMA.EHR.Application/Repositories/UserProfileRepository.cs index db63e056..4f081f77 100644 --- a/BMA.EHR.Application/Repositories/UserProfileRepository.cs +++ b/BMA.EHR.Application/Repositories/UserProfileRepository.cs @@ -341,6 +341,31 @@ namespace BMA.EHR.Application.Repositories } } + + public async Task GetProfileByProfileIdNoAuthAsync(Guid profileId, string? accessToken) + { + try + { + var apiPath = $"{_configuration["API"]}/org/unauthorize/profile/{profileId}"; + var apiKey = _configuration["API_KEY"]; + + var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey); + if (apiResult != null) + { + var raw = JsonConvert.DeserializeObject(apiResult); + if (raw != null) + return raw.Result; + } + + return null; + } + catch + { + throw; + } + } + + public async Task UpdateDutyTimeAsync(Guid profileId, Guid roundId, DateTime effectiveDate, string? accessToken) { try @@ -739,6 +764,75 @@ namespace BMA.EHR.Application.Repositories } } + public async Task> GetAllOfficerByRootDnaId(string? rootDnaId, DateTime date) + { + try + { + var apiPath = $"{_configuration["API"]}/org/unauthorize/officer-list"; + var apiKey = _configuration["API_KEY"]; + var body = new + { + reqNode = 0, + reqNodeId = rootDnaId, + date = date + }; + //Console.WriteLine(body); + + var profiles = new List(); + + var apiResult = await PostExternalAPIAsync(apiPath, "", body, apiKey); + if (apiResult != null) + { + var raw = JsonConvert.DeserializeObject(apiResult); + if (raw != null) + return raw.Result; + else + return new List(); + } + else + return new List(); + } + catch + { + throw; + } + } + + public async Task> GetAllEmployeeByRootDnaId(string? rootDnaId, DateTime date) + { + try + { + var apiPath = $"{_configuration["API"]}/org/unauthorize/employee-list"; + var apiKey = _configuration["API_KEY"]; + var body = new + { + reqNode = 0, + reqNodeId = rootDnaId, + startDate = date, + endDate = date + }; + //Console.WriteLine(body); + + var profiles = new List(); + + var apiResult = await PostExternalAPIAsync(apiPath, "", body, apiKey); + if (apiResult != null) + { + var raw = JsonConvert.DeserializeObject(apiResult); + if (raw != null) + return raw.Result; + else + return new List(); + } + else + return new List(); + } + catch + { + throw; + } + } + public async Task> GetProfileByAdminRolev4(string? accessToken, int? node, string? nodeId, string role, string? revisionId, int? reqNode, string? reqNodeId, DateTime? startDate, DateTime? endDate) { try @@ -945,7 +1039,7 @@ namespace BMA.EHR.Application.Repositories } } - public async Task SearchProfile(string? citizenId, string? firstName, string? lastName, string accessToken, int page, int pageSize, string? role, string? nodeId, int? node) + public async Task SearchProfile(string? citizenId, string? firstName, string? lastName, string accessToken, int page, int pageSize, string? role, string? nodeId, int? node,string? selectedNodeId,int? selectedNode ) { try { @@ -961,6 +1055,8 @@ namespace BMA.EHR.Application.Repositories node = node, page = page, pageSize = pageSize, + selectedNodeId = selectedNodeId, + selectedNode = selectedNode }; var profiles = new List(); @@ -1163,6 +1259,38 @@ namespace BMA.EHR.Application.Repositories } } + public GetOrganizationResponseDTO? GetOcByNodeId(Guid ocId, int level, string? accessToken) + { + try + { + var apiPath = $"{_configuration["API"]}/org/find/all"; + var apiKey = _configuration["API_KEY"]; + var body = new + { + nodeId = ocId, + node = level + + }; + + var apiResult = PostExternalAPIAsync(apiPath, accessToken ?? "", body, apiKey).Result; + if (apiResult != null) + { + var raw = JsonConvert.DeserializeObject(apiResult); + if (raw != null && raw.Result != null) + { + return raw.Result; + } + } + + return null; + } + catch + { + throw; + } + } + + public GetOrganizationResponseDTO? GetOc(Guid ocId, int level, string? accessToken) { try diff --git a/BMA.EHR.Application/Responses/Leaves/GetPermissionWithActingDto.cs b/BMA.EHR.Application/Responses/Leaves/GetPermissionWithActingDto.cs new file mode 100644 index 00000000..083c4b20 --- /dev/null +++ b/BMA.EHR.Application/Responses/Leaves/GetPermissionWithActingDto.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using BMA.EHR.Domain.Shared; +using Newtonsoft.Json; + +namespace BMA.EHR.Application.Responses.Leaves +{ + public class GetPermissionWithActingDto + { + public string privilege {get; set;} = string.Empty; + public bool isAct {get; set;} = false; + public List posMasterActs {get; set;} = new(); + } + + public class ActingPermission + { + public string posNo {get; set;} = string.Empty; + //public string? privilege {get; set;} = "PARENT"; + [JsonConverter(typeof(PrivilegeConverter))] + public string privilege {get; set;} = "CHILD"; + + public Guid? rootDnaId {get; set;} + public Guid? child1DnaId {get; set;} + public Guid? child2DnaId {get; set;} + public Guid? child3DnaId {get; set;} + public Guid? child4DnaId {get; set;} + } + + public class GetPermissionWithActingResultDto + { + public int status {get; set;} = 0; + public string message {get; set;} = string.Empty; + public GetPermissionWithActingDto result {get; set;} = new(); + } +} \ No newline at end of file diff --git a/BMA.EHR.Application/Responses/Leaves/GetProfileLeaveByKeycloakDto.cs b/BMA.EHR.Application/Responses/Leaves/GetProfileLeaveByKeycloakDto.cs index c6c79bfd..9d13d834 100644 --- a/BMA.EHR.Application/Responses/Leaves/GetProfileLeaveByKeycloakDto.cs +++ b/BMA.EHR.Application/Responses/Leaves/GetProfileLeaveByKeycloakDto.cs @@ -13,7 +13,7 @@ public string Age { get; set; } = string.Empty; public DateTime DateAppoint { get; set; } public DateTime DateCurrent { get; set; } - public int Amount { get; set; } + public int? Amount { get; set; } = 0; public string? TelephoneNumber { get; set; } = string.Empty; public string Position { get; set; } = string.Empty; public string PosLevel { get; set; } = string.Empty; diff --git a/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdDto.cs b/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdDto.cs index 7db0e212..8e319904 100644 --- a/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdDto.cs +++ b/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdDto.cs @@ -44,7 +44,7 @@ namespace BMA.EHR.Application.Responses.Profiles public string? ProfileType { get; set; } public bool? IsLeave { get; set; } - public bool? IsProbatin { get; set; } + public bool? IsProbation { get; set; } public string? Root { get; set; } public string? Child1 { get; set; } diff --git a/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdRootDto.cs b/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdRootDto.cs index 1110ca9e..2eff51dd 100644 --- a/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdRootDto.cs +++ b/BMA.EHR.Application/Responses/Profiles/GetProfileByKeycloakIdRootDto.cs @@ -25,6 +25,12 @@ namespace BMA.EHR.Application.Responses.Profiles public DateTime? DateStart { get; set; } public DateTime? DateAppoint { get; set; } + + public string? RootDnaId { get; set; } + public string? Child1DnaId { get; set; } + public string? Child2DnaId { get; set; } + public string? Child3DnaId { get; set; } + public string? Child4DnaId { get; set; } } public class GetProfileByKeycloakIdRootAddTotalDto diff --git a/BMA.EHR.Discipline.Service/Controllers/DisciplineComplaint_AppealController.cs b/BMA.EHR.Discipline.Service/Controllers/DisciplineComplaint_AppealController.cs index 21204d6b..619756c2 100644 --- a/BMA.EHR.Discipline.Service/Controllers/DisciplineComplaint_AppealController.cs +++ b/BMA.EHR.Discipline.Service/Controllers/DisciplineComplaint_AppealController.cs @@ -786,7 +786,7 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -826,11 +826,11 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers data_search = data_search .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - data_search = data_search - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // data_search = data_search + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { data_search = data_search.Where(x => diff --git a/BMA.EHR.Discipline.Service/Controllers/DisciplineResultController.cs b/BMA.EHR.Discipline.Service/Controllers/DisciplineResultController.cs index e5be6189..85388209 100644 --- a/BMA.EHR.Discipline.Service/Controllers/DisciplineResultController.cs +++ b/BMA.EHR.Discipline.Service/Controllers/DisciplineResultController.cs @@ -1242,14 +1242,22 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command25/report")] - public async Task> PostReportCommand25([FromBody] ReportPersonRequest req) + public async Task> PostReportCommand25([FromBody] ReportPersonAndCommandRequest req) { try { var data = await _context.DisciplineReport_Profiles .Where(x => req.refIds.Contains(x.Id.ToString())) .ToListAsync(); - data.ForEach(profile => profile.Status = req.status.Trim().ToUpper()); + // data.ForEach(profile => profile.Status = req.status.Trim().ToUpper()); + data.ForEach(profile => + { + profile.Status = !string.IsNullOrEmpty(req.status) + ? req.status.Trim().ToUpper() : null; + profile.CommandTypeId = !string.IsNullOrEmpty(req.commandTypeId) && Guid.TryParse(req.commandTypeId, out var cmdTypeId) + ? cmdTypeId : null; + profile.CommandCode = req.commandCode ?? null; + }); await _context.SaveChangesAsync(); return Success(); } @@ -1276,7 +1284,13 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers .Where(x => req.refIds.Contains(x.Id.ToString())) // .Where(x => x.Status.ToUpper() == "REPORT") .ToListAsync(); - data.ForEach(profile => profile.Status = "PENDING"); + // data.ForEach(profile => profile.Status = "PENDING"); + data.ForEach(profile => + { + profile.Status = "PENDING"; + profile.CommandTypeId = null; + profile.CommandCode = null; + }); await _context.SaveChangesAsync(); return Success(); } @@ -1429,14 +1443,22 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("command26/report")] - public async Task> PostReportCommand26([FromBody] ReportPersonRequest req) + public async Task> PostReportCommand26([FromBody] ReportPersonAndCommandRequest req) { try { var data = await _context.DisciplineReport_Profiles .Where(x => req.refIds.Contains(x.Id.ToString())) .ToListAsync(); - data.ForEach(profile => profile.Status = req.status.Trim().ToUpper()); + // data.ForEach(profile => profile.Status = req.status.Trim().ToUpper()); + data.ForEach(profile => + { + profile.Status = !string.IsNullOrEmpty(req.status) + ? req.status.Trim().ToUpper() : null; + profile.CommandTypeId = !string.IsNullOrEmpty(req.commandTypeId) && Guid.TryParse(req.commandTypeId, out var cmdTypeId) + ? cmdTypeId : null; + profile.CommandCode = req.commandCode ?? null; + }); await _context.SaveChangesAsync(); return Success(); } @@ -1463,7 +1485,13 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers .Where(x => req.refIds.Contains(x.Id.ToString())) // .Where(x => x.Status.ToUpper() == "REPORT") .ToListAsync(); - data.ForEach(profile => profile.Status = "PENDING"); + // data.ForEach(profile => profile.Status = "PENDING"); + data.ForEach(profile => + { + profile.Status = "PENDING"; + profile.CommandTypeId = null; + profile.CommandCode = null; + }); await _context.SaveChangesAsync(); return Success(); } diff --git a/BMA.EHR.Discipline.Service/Controllers/DisciplineSuspendController.cs b/BMA.EHR.Discipline.Service/Controllers/DisciplineSuspendController.cs index 732c518b..3e171f9b 100644 --- a/BMA.EHR.Discipline.Service/Controllers/DisciplineSuspendController.cs +++ b/BMA.EHR.Discipline.Service/Controllers/DisciplineSuspendController.cs @@ -71,6 +71,13 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } + + // ถ้า FE ส่ง status = PENDING กรอง start/end suspend not null + bool isPending = + !string.IsNullOrEmpty(profileType) && + !string.IsNullOrEmpty(status) && + status.Trim().ToUpper() == "PENDING"; + // กรองสิทธิ์ string role = jsonData["result"]?.ToString() ?? ""; var nodeId = string.Empty; @@ -102,14 +109,14 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } var data_search = (from x in _context.DisciplineReport_Profiles.Include(x => x.DisciplineDisciplinary) where ( - endDate != null && startDate != null? + endDate != null && startDate != null ? ( (x.StartDateSuspend.Value.Date >= startDate.Value.Date && x.StartDateSuspend.Value.Date <= endDate.Value.Date) || (x.EndDateSuspend.Value.Date >= startDate.Value.Date && x.EndDateSuspend.Value.Date <= endDate.Value.Date) || @@ -137,14 +144,19 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers ( !string.IsNullOrEmpty(status) ? x.Status!.Trim().ToUpper() == status : true ) + // ถ้า FE ส่ง status = PENDING กรอง start/end suspend not null + && + ( + isPending + ? x.StartDateSuspend != null && x.EndDateSuspend != null + : true + ) && ( role == "OWNER" ? true : role == "ROOT" ? x.rootDnaId == nodeId - : role == "PARENT" - ? x.rootDnaId == nodeId && x.child1DnaId != null : role == "CHILD" ? ( profileAdmin.Node == 4 ? x.child4DnaId == nodeId : @@ -177,125 +189,119 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers ) select x).ToList(); var query = data_search - .Select(x => new - { - Id = x.Id, - CitizenId = x.CitizenId, - Prefix = x.Prefix, - FirstName = x.FirstName, - LastName = x.LastName, - ProfileId = x.PersonId, - Organization = x.Organization, - root = x.root, - rootId = x.rootId, - rootDnaId = x.rootDnaId, - rootShortName = x.rootShortName, - child1 = x.child1, - child1Id = x.child1Id, - child1DnaId = x.child1DnaId, - child1ShortName = x.child1ShortName, - child2 = x.child2, - child2Id = x.child2Id, - child2DnaId = x.child2DnaId, - child2ShortName = x.child2ShortName, - child3 = x.child3, - child3Id = x.child3Id, - child3DnaId = x.child3DnaId, - child3ShortName = x.child3ShortName, - child4 = x.child4, - child4Id = x.child4Id, - child4DnaId = x.child4DnaId, - child4ShortName = x.child4ShortName, - posMasterNo = x.posMasterNo, - posTypeId = x.posTypeId, - posTypeName = x.posTypeName, - posLevelId = x.posLevelId, - posLevelName = x.posLevelName, + .Select(x => new + { + Id = x.Id, + CitizenId = x.CitizenId, + Prefix = x.Prefix, + FirstName = x.FirstName, + LastName = x.LastName, + ProfileId = x.PersonId, + Organization = x.Organization, + root = x.root, + rootId = x.rootId, + rootDnaId = x.rootDnaId, + rootShortName = x.rootShortName, + child1 = x.child1, + child1Id = x.child1Id, + child1DnaId = x.child1DnaId, + child1ShortName = x.child1ShortName, + child2 = x.child2, + child2Id = x.child2Id, + child2DnaId = x.child2DnaId, + child2ShortName = x.child2ShortName, + child3 = x.child3, + child3Id = x.child3Id, + child3DnaId = x.child3DnaId, + child3ShortName = x.child3ShortName, + child4 = x.child4, + child4Id = x.child4Id, + child4DnaId = x.child4DnaId, + child4ShortName = x.child4ShortName, + posMasterNo = x.posMasterNo, + posTypeId = x.posTypeId, + posTypeName = x.posTypeName, + posLevelId = x.posLevelId, + posLevelName = x.posLevelName, - Position = x.Position, - PosNo = x.PosNo, - PositionLevel = x.PositionLevel == null ? "" : x.PositionLevel, - PositionType = x.PositionType == null ? "" : x.PositionType, - Salary = x.Salary, - Status = x.Status, - DescriptionSuspend = x.DescriptionSuspend, - StartDateSuspend = x.StartDateSuspend, - EndDateSuspend = x.EndDateSuspend, - Title = x.DisciplineDisciplinary.Title, - OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด - DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด - DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด - profileType = x.profileType, - CreatedAt = x.CreatedAt, - }); + Position = x.Position, + PosNo = x.PosNo, + PositionLevel = x.PositionLevel == null ? "" : x.PositionLevel, + PositionType = x.PositionType == null ? "" : x.PositionType, + Salary = x.Salary, + Status = x.Status, + DescriptionSuspend = x.DescriptionSuspend, + StartDateSuspend = x.StartDateSuspend, + EndDateSuspend = x.EndDateSuspend, + Title = x.DisciplineDisciplinary.Title, + OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด + DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด + DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด + profileType = x.profileType, + CreatedAt = x.CreatedAt, + }); - bool desc = descending ?? false; - if (!string.IsNullOrEmpty(sortBy)) - { - if (sortBy == "title") - { - query = desc ? query.OrderByDescending(x => x.Title) - : query.OrderBy(x => x.Title); - } - else if (sortBy == "prefix" || sortBy == "firstName" || sortBy == "lastName") - { - query = desc ? - query - //.OrderByDescending(x => x.Prefix) - .OrderByDescending(x => x.FirstName) - .ThenByDescending(x => x.LastName) : - query - //.OrderBy(x => x.Prefix) - .OrderBy(x => x.FirstName) - .ThenBy(x => x.LastName); - } - else if (sortBy == "position") - { - query = desc ? query.OrderByDescending(x => x.Position) - : query.OrderBy(x => x.Position); - } - else if (sortBy == "positionType" || sortBy == "positionLevel") - { - query = desc ? - query - .OrderByDescending(x => x.PositionType) - .ThenByDescending(x => x.PositionLevel) : - query - .OrderBy(x => x.PositionType) - .ThenBy(x => x.PositionLevel); - } - else if (sortBy == "organization") - { - query = desc ? query.OrderByDescending(x => x.Organization) - : query.OrderBy(x => x.Organization); - } - else if (sortBy == "startDateSuspend") - { - query = desc ? query.OrderByDescending(x => x.StartDateSuspend) - : query.OrderBy(x => x.StartDateSuspend); - } - else if (sortBy == "endDateSuspend") - { - query = desc ? query.OrderByDescending(x => x.EndDateSuspend) - : query.OrderBy(x => x.EndDateSuspend); - } - else if (sortBy == "descriptionSuspend") - { - query = desc ? query.OrderByDescending(x => x.DescriptionSuspend) - : query.OrderBy(x => x.DescriptionSuspend); - } - else - { - query = query.OrderByDescending(x => x.profileType) - .ThenByDescending(x => x.CreatedAt) - .ThenByDescending(x => x.CitizenId); - } - } + bool desc = descending ?? false; + if (!string.IsNullOrEmpty(sortBy)) + { + if (sortBy == "title") + { + query = desc ? query.OrderByDescending(x => x.Title) + : query.OrderBy(x => x.Title); + } + else if (sortBy == "prefix" || sortBy == "firstName" || sortBy == "lastName") + { + query = desc ? + query.OrderByDescending(x => x.FirstName).ThenByDescending(x => x.LastName) : + query.OrderBy(x => x.FirstName).ThenBy(x => x.LastName); + } + else if (sortBy == "position") + { + query = desc ? query.OrderByDescending(x => x.Position) + : query.OrderBy(x => x.Position); + } + else if (sortBy == "positionType" || sortBy == "positionLevel") + { + query = desc ? + query + .OrderByDescending(x => x.PositionType) + .ThenByDescending(x => x.PositionLevel) : + query + .OrderBy(x => x.PositionType) + .ThenBy(x => x.PositionLevel); + } + else if (sortBy == "organization") + { + query = desc ? query.OrderByDescending(x => x.Organization) + : query.OrderBy(x => x.Organization); + } + else if (sortBy == "startDateSuspend") + { + query = desc ? query.OrderByDescending(x => x.StartDateSuspend) + : query.OrderBy(x => x.StartDateSuspend); + } + else if (sortBy == "endDateSuspend") + { + query = desc ? query.OrderByDescending(x => x.EndDateSuspend) + : query.OrderBy(x => x.EndDateSuspend); + } + else if (sortBy == "descriptionSuspend") + { + query = desc ? query.OrderByDescending(x => x.DescriptionSuspend) + : query.OrderBy(x => x.DescriptionSuspend); + } + else + { + query = query.OrderByDescending(x => x.profileType) + .ThenByDescending(x => x.CreatedAt) + .ThenByDescending(x => x.CitizenId); + } + } - var data = query - .Skip((page - 1) * pageSize) - .Take(pageSize) - .ToList(); + var data = query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .ToList(); return Success(new { data, total = data_search.Count() }); } diff --git a/BMA.EHR.Discipline.Service/Requests/ReportPersonRequest.cs b/BMA.EHR.Discipline.Service/Requests/ReportPersonRequest.cs index 1bd61c56..f7a16efc 100644 --- a/BMA.EHR.Discipline.Service/Requests/ReportPersonRequest.cs +++ b/BMA.EHR.Discipline.Service/Requests/ReportPersonRequest.cs @@ -8,4 +8,12 @@ namespace BMA.EHR.Discipline.Service.Requests public string[] refIds { get; set; } public string? status { get; set; } } + + public class ReportPersonAndCommandRequest + { + public string[] refIds { get; set; } + public string? status { get; set; } + public string? commandTypeId { get; set; } + public string? commandCode { get; set; } + } } diff --git a/BMA.EHR.Domain/Common/BaseController.cs b/BMA.EHR.Domain/Common/BaseController.cs index 44d8dac0..26f71bf5 100644 --- a/BMA.EHR.Domain/Common/BaseController.cs +++ b/BMA.EHR.Domain/Common/BaseController.cs @@ -1,4 +1,5 @@ -using BMA.EHR.Domain.Shared; +using BMA.EHR.Domain.Extensions; +using BMA.EHR.Domain.Shared; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -81,6 +82,20 @@ namespace BMA.EHR.Domain.Common } + #endregion + + #region " Properties " + + protected string? EmpType => User.GetEmpType(); + protected Guid? OrgChild1DnaId => User.GetOrgChild1DnaId(); + protected Guid? OrgChild2DnaId => User.GetOrgChild2DnaId(); + protected Guid? OrgChild3DnaId => User.GetOrgChild3DnaId(); + protected Guid? OrgChild4DnaId => User.GetOrgChild4DnaId(); + protected Guid? OrgRootDnaId => User.GetOrgRootDnaId(); + protected Guid? ProfileId => User.GetProfileId(); + protected string? Prefix => User.GetPrefix(); + protected string? FullNameFromClaim => User.GetName(); + #endregion #endregion diff --git a/BMA.EHR.Domain/Common/TokenUserInfo.cs b/BMA.EHR.Domain/Common/TokenUserInfo.cs new file mode 100644 index 00000000..cdae6fb1 --- /dev/null +++ b/BMA.EHR.Domain/Common/TokenUserInfo.cs @@ -0,0 +1,39 @@ +namespace BMA.EHR.Domain.Common +{ + public class TokenUserInfo + { + // Existing properties + public string KeycloakId { get; set; } = string.Empty; + public string? PreferredUsername { get; set; } + public string? GivenName { get; set; } + public string? FamilyName { get; set; } + + // New properties to add + public string? EmpType { get; set; } + public Guid? OrgChild1DnaId { get; set; } + public Guid? OrgChild2DnaId { get; set; } + public Guid? OrgChild3DnaId { get; set; } + public Guid? OrgChild4DnaId { get; set; } + public Guid? OrgRootDnaId { get; set; } + public Guid? ProfileId { get; set; } + public string? Prefix { get; set; } + public string? Name { get; set; } + } + + // Claim type constants + public static class BmaClaimTypes + { + public const string EmpType = "empType"; + public const string OrgChild1DnaId = "orgChild1DnaId"; + public const string OrgChild2DnaId = "orgChild2DnaId"; + public const string OrgChild3DnaId = "orgChild3DnaId"; + public const string OrgChild4DnaId = "orgChild4DnaId"; + public const string OrgRootDnaId = "orgRootDnaId"; + public const string ProfileId = "profileId"; + public const string Prefix = "prefix"; + public const string Name = "name"; + public const string GivenName = "given_name"; + public const string FamilyName = "family_name"; + public const string PreferredUsername = "preferred_username"; + } +} diff --git a/BMA.EHR.Domain/Extensions/ClaimsPrincipalExtensions.cs b/BMA.EHR.Domain/Extensions/ClaimsPrincipalExtensions.cs new file mode 100644 index 00000000..26a7c189 --- /dev/null +++ b/BMA.EHR.Domain/Extensions/ClaimsPrincipalExtensions.cs @@ -0,0 +1,30 @@ +using BMA.EHR.Domain.Common; +using System.Security.Claims; + +namespace BMA.EHR.Domain.Extensions +{ + public static class ClaimsPrincipalExtensions + { + public static string? GetClaimValue(this ClaimsPrincipal user, string claimType) + { + return user?.FindFirst(claimType)?.Value; + } + + public static Guid? GetGuidClaim(this ClaimsPrincipal user, string claimType) + { + var value = user?.GetClaimValue(claimType); + return Guid.TryParse(value, out var guid) ? guid : null; + } + + // Convenience methods for common claims + public static string? GetEmpType(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.EmpType); + public static Guid? GetOrgChild1DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild1DnaId); + public static Guid? GetOrgChild2DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild2DnaId); + public static Guid? GetOrgChild3DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild3DnaId); + public static Guid? GetOrgChild4DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild4DnaId); + public static Guid? GetOrgRootDnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgRootDnaId); + public static Guid? GetProfileId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.ProfileId); + public static string? GetPrefix(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.Prefix); + public static string? GetName(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.Name); + } +} diff --git a/BMA.EHR.Domain/Extensions/DateTimeExtension.cs b/BMA.EHR.Domain/Extensions/DateTimeExtension.cs index a6a07c79..bbfc0a12 100644 --- a/BMA.EHR.Domain/Extensions/DateTimeExtension.cs +++ b/BMA.EHR.Domain/Extensions/DateTimeExtension.cs @@ -174,6 +174,29 @@ namespace BMA.EHR.Domain.Extensions } } + public static (int Years, int Months, int Days) GetDifference(this DateTime from, DateTime to) + { + if (from > to) (from, to) = (to, from); // swap ถ้าลำดับสลับ + + int years = to.Year - from.Year; + int months = to.Month - from.Month; + int days = to.Day - from.Day; + + if (days < 0) + { + months--; + days += DateTime.DaysInMonth(to.Year, to.Month == 1 ? 12 : to.Month - 1); + } + + if (months < 0) + { + years--; + months += 12; + } + + return (years, months, days); + } + public static int CalculateAge(this DateTime date, int plusYear = 0, int subtractYear = 0) { try diff --git a/BMA.EHR.Domain/Middlewares/CombinedErrorHandlerAndLoggingMiddleware.cs b/BMA.EHR.Domain/Middlewares/CombinedErrorHandlerAndLoggingMiddleware.cs index 15c88592..4216fa43 100644 --- a/BMA.EHR.Domain/Middlewares/CombinedErrorHandlerAndLoggingMiddleware.cs +++ b/BMA.EHR.Domain/Middlewares/CombinedErrorHandlerAndLoggingMiddleware.cs @@ -79,13 +79,39 @@ namespace BMA.EHR.Domain.Middlewares GetProfileByKeycloakIdLocal? pf = null; var tokenUserInfo = await ExtractTokenUserInfoAsync(token); + // Store tokenUserInfo in HttpContext.Items for controllers to use + context.Items["TokenUserInfo"] = tokenUserInfo; + // ดึง keycloakId จาก JWT token keycloakId = tokenUserInfo.KeycloakId; - // ดึง profile จาก cache หรือ API + // ดึง profile จาก claims หรือ cache หรือ API if (Guid.TryParse(keycloakId, out var parsedId) && parsedId != Guid.Empty) { - pf = await GetProfileWithCacheAsync(parsedId, token); + // Build profile from token claims if available + if (tokenUserInfo.OrgRootDnaId.HasValue && tokenUserInfo.ProfileId.HasValue) + { + pf = new GetProfileByKeycloakIdLocal + { + Id = tokenUserInfo.ProfileId.Value, + CitizenId = tokenUserInfo.PreferredUsername, + Prefix = tokenUserInfo.Prefix, + FirstName = tokenUserInfo.GivenName, + LastName = tokenUserInfo.FamilyName, + RootDnaId = tokenUserInfo.OrgRootDnaId, + Child1DnaId = tokenUserInfo.OrgChild1DnaId, + Child2DnaId = tokenUserInfo.OrgChild2DnaId, + Child3DnaId = tokenUserInfo.OrgChild3DnaId, + Child4DnaId = tokenUserInfo.OrgChild4DnaId, + }; + Console.WriteLine($"[INFO] Using claims for profile - OrgRootDnaId: {pf.RootDnaId}, ProfileId: {pf.Id}"); + } + else + { + // Fallback to API only if critical claims are missing + Console.WriteLine("[WARN] Critical claims missing, falling back to API call"); + pf = await GetProfileWithCacheAsync(parsedId, token); + } } try @@ -649,6 +675,87 @@ namespace BMA.EHR.Domain.Middlewares Console.WriteLine($"Extracted family_name: {result.FamilyName}"); } + // ดึง empType + if (jsonDoc.RootElement.TryGetProperty("empType", out var empTypeElement)) + { + result.EmpType = empTypeElement.GetString(); + Console.WriteLine($"Extracted empType: {result.EmpType}"); + } + + // ดึง orgChild1DnaId + if (jsonDoc.RootElement.TryGetProperty("orgChild1DnaId", out var orgChild1Element)) + { + if (Guid.TryParse(orgChild1Element.GetString(), out var orgChild1Guid)) + { + result.OrgChild1DnaId = orgChild1Guid; + Console.WriteLine($"Extracted orgChild1DnaId: {result.OrgChild1DnaId}"); + } + } + + // ดึง orgChild2DnaId + if (jsonDoc.RootElement.TryGetProperty("orgChild2DnaId", out var orgChild2Element)) + { + if (Guid.TryParse(orgChild2Element.GetString(), out var orgChild2Guid)) + { + result.OrgChild2DnaId = orgChild2Guid; + Console.WriteLine($"Extracted orgChild2DnaId: {result.OrgChild2DnaId}"); + } + } + + // ดึง orgChild3DnaId + if (jsonDoc.RootElement.TryGetProperty("orgChild3DnaId", out var orgChild3Element)) + { + if (Guid.TryParse(orgChild3Element.GetString(), out var orgChild3Guid)) + { + result.OrgChild3DnaId = orgChild3Guid; + Console.WriteLine($"Extracted orgChild3DnaId: {result.OrgChild3DnaId}"); + } + } + + // ดึง orgChild4DnaId + if (jsonDoc.RootElement.TryGetProperty("orgChild4DnaId", out var orgChild4Element)) + { + if (Guid.TryParse(orgChild4Element.GetString(), out var orgChild4Guid)) + { + result.OrgChild4DnaId = orgChild4Guid; + Console.WriteLine($"Extracted orgChild4DnaId: {result.OrgChild4DnaId}"); + } + } + + // ดึง orgRootDnaId + if (jsonDoc.RootElement.TryGetProperty("orgRootDnaId", out var orgRootElement)) + { + if (Guid.TryParse(orgRootElement.GetString(), out var orgRootGuid)) + { + result.OrgRootDnaId = orgRootGuid; + Console.WriteLine($"Extracted orgRootDnaId: {result.OrgRootDnaId}"); + } + } + + // ดึง profileId + if (jsonDoc.RootElement.TryGetProperty("profileId", out var profileIdElement)) + { + if (Guid.TryParse(profileIdElement.GetString(), out var profileIdGuid)) + { + result.ProfileId = profileIdGuid; + Console.WriteLine($"Extracted profileId: {result.ProfileId}"); + } + } + + // ดึง prefix + if (jsonDoc.RootElement.TryGetProperty("prefix", out var prefixElement)) + { + result.Prefix = prefixElement.GetString(); + Console.WriteLine($"Extracted prefix: {result.Prefix}"); + } + + // ดึง name + if (jsonDoc.RootElement.TryGetProperty("name", out var nameElement)) + { + result.Name = nameElement.GetString(); + Console.WriteLine($"Extracted name: {result.Name}"); + } + return result; } catch (Exception ex) @@ -767,14 +874,6 @@ namespace BMA.EHR.Domain.Middlewares } // Model classes - public class TokenUserInfo - { - public string KeycloakId { get; set; } = string.Empty; - public string? PreferredUsername { get; set; } - public string? GivenName { get; set; } - public string? FamilyName { get; set; } - } - public class GetProfileByKeycloakIdLocal { public Guid Id { get; set; } diff --git a/BMA.EHR.Domain/Models/Leave/Requests/LeaveBeginning.cs b/BMA.EHR.Domain/Models/Leave/Requests/LeaveBeginning.cs index d68f0229..153b7d22 100644 --- a/BMA.EHR.Domain/Models/Leave/Requests/LeaveBeginning.cs +++ b/BMA.EHR.Domain/Models/Leave/Requests/LeaveBeginning.cs @@ -24,7 +24,7 @@ namespace BMA.EHR.Domain.Models.Leave.Requests [Required, Comment("ปีงบประมาณ")] public int LeaveYear { get; set; } = 0; - [Required, Comment("จำนวนวันลายกมา")] + [Required, Comment("จำนวนวันลาทั้งหมด")] public double LeaveDays { get; set; } = 0.0; [Required, Comment("จำนวนวันลาที่ใช้ไป")] @@ -42,5 +42,11 @@ namespace BMA.EHR.Domain.Models.Leave.Requests public Guid? Child3DnaId { get; set; } public Guid? Child4DnaId { get; set; } + + [Required, Comment("จำนวนวันลายกมา")] + public double BeginningLeaveDays { get; set; } = 0.0; + + [Comment("จำนวนครั้งที่ลายกมา")] + public int BeginningLeaveCount { get; set; } = 0; } } diff --git a/BMA.EHR.Domain/Models/Leave/Requests/LeaveRequest.cs b/BMA.EHR.Domain/Models/Leave/Requests/LeaveRequest.cs index 69088cbb..f6c9ce2d 100644 --- a/BMA.EHR.Domain/Models/Leave/Requests/LeaveRequest.cs +++ b/BMA.EHR.Domain/Models/Leave/Requests/LeaveRequest.cs @@ -210,5 +210,7 @@ namespace BMA.EHR.Domain.Models.Leave.Requests public Guid? Child4DnaId { get; set; } = Guid.Empty; + public DateTime? DateSendLeave { get; set; } + } } diff --git a/BMA.EHR.Domain/Models/Leave/TimeAttendants/LeaveProcessJobStatus.cs b/BMA.EHR.Domain/Models/Leave/TimeAttendants/LeaveProcessJobStatus.cs new file mode 100644 index 00000000..be986189 --- /dev/null +++ b/BMA.EHR.Domain/Models/Leave/TimeAttendants/LeaveProcessJobStatus.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using BMA.EHR.Domain.Models.Base; +using Microsoft.EntityFrameworkCore; + +namespace BMA.EHR.Domain.Models.Leave.TimeAttendants +{ + public class LeaveProcessJobStatus: EntityBase + { + [Required, Comment("วันเริ่มต้น")] + public DateTime StartDate { get; set; } + + [Required, Comment("วันสิ้นสุด")] + public DateTime EndDate { get; set; } + + [Required, Comment("รหัส Root DNA Id")] + public Guid RootDnaId { get; set; } = Guid.Empty; + + [Comment("วันเวลาที่สร้างงาน")] + public DateTime CreatedDate { get; set; } = DateTime.Now; + + [Comment("วันเวลาที่เริ่มประมวลผล")] + public DateTime? ProcessingDate { get; set; } + + [Comment("วันเวลาที่เสร็จสิ้นการประมวลผล")] + public DateTime? CompletedDate { get; set; } + + [Required, Comment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED")] + public string Status { get; set; } = "PENDING"; + + [Comment("ข้อความแสดงข้อผิดพลาด")] + public string? ErrorMessage { get; set; } + } +} \ No newline at end of file diff --git a/BMA.EHR.Domain/Shared/GlobalMessages.cs b/BMA.EHR.Domain/Shared/GlobalMessages.cs index 8746de95..a99dc3c9 100644 --- a/BMA.EHR.Domain/Shared/GlobalMessages.cs +++ b/BMA.EHR.Domain/Shared/GlobalMessages.cs @@ -8,6 +8,8 @@ public static readonly string DataNotFound = "ไม่พบข้อมูลในระบบ"; + public static readonly string ProfileNotFound = "ไม่พบข้อมูลในระบบทะเบียนประวัติ"; + public static readonly string NotAuthorized = "กรุณาเข้าสู่ระบบก่อนใช้งาน!"; public static readonly string ForbiddenAccess = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!"; diff --git a/BMA.EHR.Domain/Shared/PrivilegeConverter.cs b/BMA.EHR.Domain/Shared/PrivilegeConverter.cs new file mode 100644 index 00000000..59f8168c --- /dev/null +++ b/BMA.EHR.Domain/Shared/PrivilegeConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace BMA.EHR.Domain.Shared +{ + public class PrivilegeConverter : JsonConverter +{ + public override bool CanConvert(Type objectType) + { + return objectType == typeof(string); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return "EMPTY"; + } + return reader.Value; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteValue(value); + } +} +} \ No newline at end of file diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.Designer.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.Designer.cs new file mode 100644 index 00000000..934ba1a9 --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.Designer.cs @@ -0,0 +1,1717 @@ +// +using System; +using BMA.EHR.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + [DbContext(typeof(LeaveDbContext))] + [Migration("20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning")] + partial class AddBeginningLeaveandLeaveCounttoLeaveBeginning + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Documents.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)"); + + b.Property("Detail") + .IsRequired() + .HasColumnType("text"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FileSize") + .HasColumnType("int"); + + b.Property("FileType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ObjectRefId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("Document"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Code") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รหัสประเภทการลา"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Limit") + .HasColumnType("int") + .HasComment("จำนวนวันลาสูงสุดประจำปี"); + + b.Property("Name") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อประเภทการลา"); + + b.HasKey("Id"); + + b.ToTable("LeaveTypes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("BeginningLeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลายกมา"); + + b.Property("BeginningLeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลายกมา"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลาสะสม"); + + b.Property("LeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลาทั้งหมด"); + + b.Property("LeaveDaysUsed") + .HasColumnType("double") + .HasComment("จำนวนวันลาที่ใช้ไป"); + + b.Property("LeaveTypeId") + .HasColumnType("char(36)") + .HasComment("รหัสประเภทการลา"); + + b.Property("LeaveYear") + .HasColumnType("int") + .HasComment("ปีงบประมาณ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("LeaveTypeId"); + + b.ToTable("LeaveBeginnings"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DocumentId") + .HasColumnType("char(36)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DocumentId"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveDocuments"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AbsentDayAt") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayGetIn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayLocation") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayRegistorDate") + .HasColumnType("datetime(6)"); + + b.Property("AbsentDaySummon") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Amount") + .HasColumnType("double"); + + b.Property("ApproveStep") + .HasColumnType("longtext") + .HasComment("step การอนุมัติ st1 = จทน.อนุมัตื,st2 = ผู้บังคับบัญชา อนุมัติ "); + + b.Property("BirthDate") + .HasColumnType("datetime(6)"); + + b.Property("CancelLeaveWrote") + .HasColumnType("longtext") + .HasComment("เขียนที่ (ขอยกเลิก)"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CommanderPosition") + .HasColumnType("longtext"); + + b.Property("CoupleDayCountryHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayEndDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDayLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayLevelCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayPosition") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayStartDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDaySumTotalHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayTotalHistory") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DateAppoint") + .HasColumnType("datetime(6)"); + + b.Property("Dear") + .HasColumnType("longtext") + .HasComment("เรียนใคร"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("HajjDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveAddress") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานที่ติดต่อขณะลา"); + + b.Property("LeaveBirthDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveCancelComment") + .HasColumnType("longtext") + .HasComment("เหตุผลในการขอยกเลิก"); + + b.Property("LeaveCancelDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveCancelStatus") + .HasColumnType("longtext") + .HasComment("สถานะของคำขอยกเลิก"); + + b.Property("LeaveComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้บังคับบัญชา"); + + b.Property("LeaveDetail") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รายละเอียดการลา"); + + b.Property("LeaveDirectorComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้อำนวยการสำนัก"); + + b.Property("LeaveDraftDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveEndDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีสิ้นสุดลา"); + + b.Property("LeaveGovernmentDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveLast") + .HasColumnType("datetime(6)"); + + b.Property("LeaveNumber") + .IsRequired() + .HasColumnType("longtext") + .HasComment("หมายเลขที่ติดต่อขณะลา"); + + b.Property("LeaveRange") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันเริ่ม เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveRangeEnd") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันสิ้นสุด เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveSalary") + .HasColumnType("int"); + + b.Property("LeaveSalaryText") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LeaveStartDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีเริ่มต้นลา"); + + b.Property("LeaveStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะของคำร้อง"); + + b.Property("LeaveSubTypeName") + .HasColumnType("longtext"); + + b.Property("LeaveTotal") + .HasColumnType("double"); + + b.Property("LeaveTypeCode") + .HasColumnType("longtext") + .HasComment("code ของประเภทการลา"); + + b.Property("LeaveWrote") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เขียนที่"); + + b.Property("OrdainDayBuddhistLentAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayBuddhistLentName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationNumber") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayOrdination") + .HasColumnType("datetime(6)"); + + b.Property("OrdainDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationName") + .HasColumnType("longtext") + .HasComment("สังกัดผู้ยื่นขอ"); + + b.Property("PositionLevelName") + .HasColumnType("longtext") + .HasComment("ระดับผู้ยื่นขอ"); + + b.Property("PositionName") + .HasColumnType("longtext") + .HasComment("ตำแหน่งผู้ยื่นขอ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("RestDayCurrentTotal") + .HasColumnType("double"); + + b.Property("RestDayOldTotal") + .HasColumnType("double"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.Property("StudyDayCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayDegreeLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayScholarship") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDaySubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingSubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayUniversityName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("TypeId") + .HasColumnType("char(36)"); + + b.Property("WifeDayDateBorn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WifeDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.HasIndex("LeaveCancelDocumentId"); + + b.HasIndex("LeaveDraftDocumentId"); + + b.HasIndex("TypeId"); + + b.ToTable("LeaveRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("ApproveStatus") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ApproveType") + .HasColumnType("longtext"); + + b.Property("Comment") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("KeycloakId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.Property("OrganizationName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สังกัด"); + + b.Property("PosExecutiveName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ตำแหน่งทางการบริหาร"); + + b.Property("PositionLevelName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ประเภทระดับตำแหน่ง"); + + b.Property("PositionName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PositionSign") + .HasColumnType("longtext") + .HasComment("ตำแหน่งใต้ลายเช็นต์"); + + b.Property("Prefix") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("Seq") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveRequestApprovers"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.AdditionalCheckRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckDate") + .HasColumnType("datetime(6)") + .HasComment("*วันที่ลงเวลา"); + + b.Property("CheckInEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงเช้า"); + + b.Property("CheckOutEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงบ่าย"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Comment") + .HasColumnType("longtext") + .HasComment("หมายเหตุในการการอนุมัติ/ไม่อนุมัติ"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("*หมายเหตุขอลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak ที่ร้องขอ"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Latitude") + .HasColumnType("double"); + + b.Property("Longitude") + .HasColumnType("double"); + + b.Property("POI") + .HasColumnType("longtext"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะการอนุมัติ"); + + b.HasKey("Id"); + + b.ToTable("AdditionalCheckRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.CheckInJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AdditionalData") + .HasColumnType("longtext") + .HasComment("ข้อมูลเพิ่มเติม (JSON)"); + + b.Property("CheckInId") + .HasColumnType("char(36)") + .HasComment("CheckInId สำหรับ Check-Out"); + + b.Property("CheckType") + .HasColumnType("longtext") + .HasComment("ประเภทการลงเวลา: CHECK_IN, CHECK_OUT"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.Property("TaskId") + .HasColumnType("char(36)") + .HasComment("Task ID สำหรับติดตามสถานะงาน"); + + b.HasKey("Id"); + + b.ToTable("CheckInJobStatuses"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("คำอธิบาย"); + + b.Property("EndTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงบ่าย"); + + b.Property("EndTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงเช้า"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)") + .HasComment("สถานะการเปิดใช้งาน (เปิด/ปิด)"); + + b.Property("IsDefault") + .HasColumnType("tinyint(1)") + .HasComment("สถานะว่ารอบใดเป็นค่า Default ของข้าราชการ (สำหรับทุกคนที่ยังไม่ได้ทำการเลือกรอบ)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("StartTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงบ่าย"); + + b.Property("StartTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงเช้า"); + + b.HasKey("Id"); + + b.ToTable("DutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckInStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะ Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("CheckOutStatus") + .HasColumnType("longtext") + .HasComment("สถานะ Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EditReason") + .HasColumnType("longtext") + .HasComment("เหตุผลการอนุมัติ/ไม่อนุมัติขอลงเวลาพิเศษ"); + + b.Property("EditStatus") + .HasColumnType("longtext") + .HasComment("สถานะการของลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ProcessUserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserCalendar", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Calendar") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ปฏิทินการทำงานของ ขรก ปกติ หรือ 6 วันต่อสัปดาห์"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.HasKey("Id"); + + b.ToTable("UserCalendars"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DutyTimeId") + .HasColumnType("char(36)") + .HasComment("รหัสรอบการลงเวลา"); + + b.Property("EffectiveDate") + .HasColumnType("datetime(6)") + .HasComment("วันที่มีผล"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("ทำการประมวลผลแล้วหรือยัง"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("Remark") + .HasColumnType("longtext") + .HasComment("หมายเหตุ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DutyTimeId"); + + b.ToTable("UserDutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("UserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "LeaveType") + .WithMany() + .HasForeignKey("LeaveTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveType"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "Document") + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("LeaveDocument") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Document"); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveCancelDocument") + .WithMany() + .HasForeignKey("LeaveCancelDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveDraftDocument") + .WithMany() + .HasForeignKey("LeaveDraftDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "Type") + .WithMany() + .HasForeignKey("TypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveCancelDocument"); + + b.Navigation("LeaveDraftDocument"); + + b.Navigation("Type"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("Approvers") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", "DutyTime") + .WithMany() + .HasForeignKey("DutyTimeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DutyTime"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Navigation("Approvers"); + + b.Navigation("LeaveDocument"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.cs new file mode 100644 index 00000000..a54ad519 --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260210091134_Add BeginningLeave and LeaveCount to LeaveBeginning.cs @@ -0,0 +1,62 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + /// + public partial class AddBeginningLeaveandLeaveCounttoLeaveBeginning : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "LeaveDays", + table: "LeaveBeginnings", + type: "double", + nullable: false, + comment: "จำนวนวันลาทั้งหมด", + oldClrType: typeof(double), + oldType: "double", + oldComment: "จำนวนวันลายกมา"); + + migrationBuilder.AddColumn( + name: "BeginningLeaveCount", + table: "LeaveBeginnings", + type: "int", + nullable: false, + defaultValue: 0, + comment: "จำนวนครั้งที่ลายกมา"); + + migrationBuilder.AddColumn( + name: "BeginningLeaveDays", + table: "LeaveBeginnings", + type: "double", + nullable: false, + defaultValue: 0.0, + comment: "จำนวนวันลายกมา"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "BeginningLeaveCount", + table: "LeaveBeginnings"); + + migrationBuilder.DropColumn( + name: "BeginningLeaveDays", + table: "LeaveBeginnings"); + + migrationBuilder.AlterColumn( + name: "LeaveDays", + table: "LeaveBeginnings", + type: "double", + nullable: false, + comment: "จำนวนวันลายกมา", + oldClrType: typeof(double), + oldType: "double", + oldComment: "จำนวนวันลาทั้งหมด"); + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.Designer.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.Designer.cs new file mode 100644 index 00000000..815f8188 --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.Designer.cs @@ -0,0 +1,1802 @@ +// +using System; +using BMA.EHR.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + [DbContext(typeof(LeaveDbContext))] + [Migration("20260330020909_Add Leave Process Job Status")] + partial class AddLeaveProcessJobStatus + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Documents.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)"); + + b.Property("Detail") + .IsRequired() + .HasColumnType("text"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FileSize") + .HasColumnType("int"); + + b.Property("FileType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ObjectRefId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("Document"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Code") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รหัสประเภทการลา"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Limit") + .HasColumnType("int") + .HasComment("จำนวนวันลาสูงสุดประจำปี"); + + b.Property("Name") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อประเภทการลา"); + + b.HasKey("Id"); + + b.ToTable("LeaveTypes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("BeginningLeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลายกมา"); + + b.Property("BeginningLeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลายกมา"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลาสะสม"); + + b.Property("LeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลาทั้งหมด"); + + b.Property("LeaveDaysUsed") + .HasColumnType("double") + .HasComment("จำนวนวันลาที่ใช้ไป"); + + b.Property("LeaveTypeId") + .HasColumnType("char(36)") + .HasComment("รหัสประเภทการลา"); + + b.Property("LeaveYear") + .HasColumnType("int") + .HasComment("ปีงบประมาณ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("LeaveTypeId"); + + b.ToTable("LeaveBeginnings"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DocumentId") + .HasColumnType("char(36)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DocumentId"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveDocuments"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AbsentDayAt") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayGetIn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayLocation") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayRegistorDate") + .HasColumnType("datetime(6)"); + + b.Property("AbsentDaySummon") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Amount") + .HasColumnType("double"); + + b.Property("ApproveStep") + .HasColumnType("longtext") + .HasComment("step การอนุมัติ st1 = จทน.อนุมัตื,st2 = ผู้บังคับบัญชา อนุมัติ "); + + b.Property("BirthDate") + .HasColumnType("datetime(6)"); + + b.Property("CancelLeaveWrote") + .HasColumnType("longtext") + .HasComment("เขียนที่ (ขอยกเลิก)"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CommanderPosition") + .HasColumnType("longtext"); + + b.Property("CoupleDayCountryHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayEndDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDayLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayLevelCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayPosition") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayStartDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDaySumTotalHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayTotalHistory") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DateAppoint") + .HasColumnType("datetime(6)"); + + b.Property("Dear") + .HasColumnType("longtext") + .HasComment("เรียนใคร"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("HajjDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveAddress") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานที่ติดต่อขณะลา"); + + b.Property("LeaveBirthDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveCancelComment") + .HasColumnType("longtext") + .HasComment("เหตุผลในการขอยกเลิก"); + + b.Property("LeaveCancelDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveCancelStatus") + .HasColumnType("longtext") + .HasComment("สถานะของคำขอยกเลิก"); + + b.Property("LeaveComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้บังคับบัญชา"); + + b.Property("LeaveDetail") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รายละเอียดการลา"); + + b.Property("LeaveDirectorComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้อำนวยการสำนัก"); + + b.Property("LeaveDraftDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveEndDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีสิ้นสุดลา"); + + b.Property("LeaveGovernmentDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveLast") + .HasColumnType("datetime(6)"); + + b.Property("LeaveNumber") + .IsRequired() + .HasColumnType("longtext") + .HasComment("หมายเลขที่ติดต่อขณะลา"); + + b.Property("LeaveRange") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันเริ่ม เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveRangeEnd") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันสิ้นสุด เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveSalary") + .HasColumnType("int"); + + b.Property("LeaveSalaryText") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LeaveStartDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีเริ่มต้นลา"); + + b.Property("LeaveStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะของคำร้อง"); + + b.Property("LeaveSubTypeName") + .HasColumnType("longtext"); + + b.Property("LeaveTotal") + .HasColumnType("double"); + + b.Property("LeaveTypeCode") + .HasColumnType("longtext") + .HasComment("code ของประเภทการลา"); + + b.Property("LeaveWrote") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เขียนที่"); + + b.Property("OrdainDayBuddhistLentAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayBuddhistLentName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationNumber") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayOrdination") + .HasColumnType("datetime(6)"); + + b.Property("OrdainDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationName") + .HasColumnType("longtext") + .HasComment("สังกัดผู้ยื่นขอ"); + + b.Property("PositionLevelName") + .HasColumnType("longtext") + .HasComment("ระดับผู้ยื่นขอ"); + + b.Property("PositionName") + .HasColumnType("longtext") + .HasComment("ตำแหน่งผู้ยื่นขอ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("RestDayCurrentTotal") + .HasColumnType("double"); + + b.Property("RestDayOldTotal") + .HasColumnType("double"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.Property("StudyDayCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayDegreeLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayScholarship") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDaySubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingSubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayUniversityName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("TypeId") + .HasColumnType("char(36)"); + + b.Property("WifeDayDateBorn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WifeDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.HasIndex("LeaveCancelDocumentId"); + + b.HasIndex("LeaveDraftDocumentId"); + + b.HasIndex("TypeId"); + + b.ToTable("LeaveRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("ApproveStatus") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ApproveType") + .HasColumnType("longtext"); + + b.Property("Comment") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("KeycloakId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.Property("OrganizationName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สังกัด"); + + b.Property("PosExecutiveName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ตำแหน่งทางการบริหาร"); + + b.Property("PositionLevelName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ประเภทระดับตำแหน่ง"); + + b.Property("PositionName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PositionSign") + .HasColumnType("longtext") + .HasComment("ตำแหน่งใต้ลายเช็นต์"); + + b.Property("Prefix") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("Seq") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveRequestApprovers"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.AdditionalCheckRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckDate") + .HasColumnType("datetime(6)") + .HasComment("*วันที่ลงเวลา"); + + b.Property("CheckInEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงเช้า"); + + b.Property("CheckOutEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงบ่าย"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Comment") + .HasColumnType("longtext") + .HasComment("หมายเหตุในการการอนุมัติ/ไม่อนุมัติ"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("*หมายเหตุขอลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak ที่ร้องขอ"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Latitude") + .HasColumnType("double"); + + b.Property("Longitude") + .HasColumnType("double"); + + b.Property("POI") + .HasColumnType("longtext"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะการอนุมัติ"); + + b.HasKey("Id"); + + b.ToTable("AdditionalCheckRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.CheckInJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AdditionalData") + .HasColumnType("longtext") + .HasComment("ข้อมูลเพิ่มเติม (JSON)"); + + b.Property("CheckInId") + .HasColumnType("char(36)") + .HasComment("CheckInId สำหรับ Check-Out"); + + b.Property("CheckType") + .HasColumnType("longtext") + .HasComment("ประเภทการลงเวลา: CHECK_IN, CHECK_OUT"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.Property("TaskId") + .HasColumnType("char(36)") + .HasComment("Task ID สำหรับติดตามสถานะงาน"); + + b.HasKey("Id"); + + b.ToTable("CheckInJobStatuses"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("คำอธิบาย"); + + b.Property("EndTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงบ่าย"); + + b.Property("EndTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงเช้า"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)") + .HasComment("สถานะการเปิดใช้งาน (เปิด/ปิด)"); + + b.Property("IsDefault") + .HasColumnType("tinyint(1)") + .HasComment("สถานะว่ารอบใดเป็นค่า Default ของข้าราชการ (สำหรับทุกคนที่ยังไม่ได้ทำการเลือกรอบ)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("StartTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงบ่าย"); + + b.Property("StartTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงเช้า"); + + b.HasKey("Id"); + + b.ToTable("DutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.LeaveProcessJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EndDate") + .HasColumnType("datetime(6)") + .HasComment("วันสิ้นสุด"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("RootDnaId") + .HasColumnType("char(36)") + .HasComment("รหัส Root DNA Id"); + + b.Property("StartDate") + .HasColumnType("datetime(6)") + .HasComment("วันเริ่มต้น"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.HasKey("Id"); + + b.ToTable("LeaveProcessJobStatuses"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckInStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะ Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("CheckOutStatus") + .HasColumnType("longtext") + .HasComment("สถานะ Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EditReason") + .HasColumnType("longtext") + .HasComment("เหตุผลการอนุมัติ/ไม่อนุมัติขอลงเวลาพิเศษ"); + + b.Property("EditStatus") + .HasColumnType("longtext") + .HasComment("สถานะการของลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ProcessUserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserCalendar", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Calendar") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ปฏิทินการทำงานของ ขรก ปกติ หรือ 6 วันต่อสัปดาห์"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.HasKey("Id"); + + b.ToTable("UserCalendars"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DutyTimeId") + .HasColumnType("char(36)") + .HasComment("รหัสรอบการลงเวลา"); + + b.Property("EffectiveDate") + .HasColumnType("datetime(6)") + .HasComment("วันที่มีผล"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("ทำการประมวลผลแล้วหรือยัง"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("Remark") + .HasColumnType("longtext") + .HasComment("หมายเหตุ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DutyTimeId"); + + b.ToTable("UserDutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("UserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "LeaveType") + .WithMany() + .HasForeignKey("LeaveTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveType"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "Document") + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("LeaveDocument") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Document"); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveCancelDocument") + .WithMany() + .HasForeignKey("LeaveCancelDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveDraftDocument") + .WithMany() + .HasForeignKey("LeaveDraftDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "Type") + .WithMany() + .HasForeignKey("TypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveCancelDocument"); + + b.Navigation("LeaveDraftDocument"); + + b.Navigation("Type"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("Approvers") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", "DutyTime") + .WithMany() + .HasForeignKey("DutyTimeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DutyTime"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Navigation("Approvers"); + + b.Navigation("LeaveDocument"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.cs new file mode 100644 index 00000000..1567dc5e --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260330020909_Add Leave Process Job Status.cs @@ -0,0 +1,54 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + /// + public partial class AddLeaveProcessJobStatus : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "LeaveProcessJobStatuses", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false, comment: "PrimaryKey", collation: "ascii_general_ci"), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, comment: "สร้างข้อมูลเมื่อ"), + CreatedUserId = table.Column(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่สร้างข้อมูล") + .Annotation("MySql:CharSet", "utf8mb4"), + LastUpdatedAt = table.Column(type: "datetime(6)", nullable: true, comment: "แก้ไขข้อมูลล่าสุดเมื่อ"), + LastUpdateUserId = table.Column(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่แก้ไขข้อมูลล่าสุด") + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedFullName = table.Column(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่สร้างข้อมูล") + .Annotation("MySql:CharSet", "utf8mb4"), + LastUpdateFullName = table.Column(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่แก้ไขข้อมูลล่าสุด") + .Annotation("MySql:CharSet", "utf8mb4"), + StartDate = table.Column(type: "datetime(6)", nullable: false, comment: "วันเริ่มต้น"), + EndDate = table.Column(type: "datetime(6)", nullable: false, comment: "วันสิ้นสุด"), + RootDnaId = table.Column(type: "char(36)", nullable: false, comment: "รหัส Root DNA Id", collation: "ascii_general_ci"), + CreatedDate = table.Column(type: "datetime(6)", nullable: false, comment: "วันเวลาที่สร้างงาน"), + ProcessingDate = table.Column(type: "datetime(6)", nullable: true, comment: "วันเวลาที่เริ่มประมวลผล"), + CompletedDate = table.Column(type: "datetime(6)", nullable: true, comment: "วันเวลาที่เสร็จสิ้นการประมวลผล"), + Status = table.Column(type: "longtext", nullable: false, comment: "สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED") + .Annotation("MySql:CharSet", "utf8mb4"), + ErrorMessage = table.Column(type: "longtext", nullable: true, comment: "ข้อความแสดงข้อผิดพลาด") + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_LeaveProcessJobStatuses", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LeaveProcessJobStatuses"); + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.Designer.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.Designer.cs new file mode 100644 index 00000000..8e79c20b --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.Designer.cs @@ -0,0 +1,1805 @@ +// +using System; +using BMA.EHR.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + [DbContext(typeof(LeaveDbContext))] + [Migration("20260423083625_Add DateSendLeave")] + partial class AddDateSendLeave + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Documents.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)"); + + b.Property("Detail") + .IsRequired() + .HasColumnType("text"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FileSize") + .HasColumnType("int"); + + b.Property("FileType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ObjectRefId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("Document"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Code") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รหัสประเภทการลา"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Limit") + .HasColumnType("int") + .HasComment("จำนวนวันลาสูงสุดประจำปี"); + + b.Property("Name") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อประเภทการลา"); + + b.HasKey("Id"); + + b.ToTable("LeaveTypes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("BeginningLeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลายกมา"); + + b.Property("BeginningLeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลายกมา"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลาสะสม"); + + b.Property("LeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลาทั้งหมด"); + + b.Property("LeaveDaysUsed") + .HasColumnType("double") + .HasComment("จำนวนวันลาที่ใช้ไป"); + + b.Property("LeaveTypeId") + .HasColumnType("char(36)") + .HasComment("รหัสประเภทการลา"); + + b.Property("LeaveYear") + .HasColumnType("int") + .HasComment("ปีงบประมาณ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("LeaveTypeId"); + + b.ToTable("LeaveBeginnings"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DocumentId") + .HasColumnType("char(36)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DocumentId"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveDocuments"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AbsentDayAt") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayGetIn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayLocation") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("AbsentDayRegistorDate") + .HasColumnType("datetime(6)"); + + b.Property("AbsentDaySummon") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Amount") + .HasColumnType("double"); + + b.Property("ApproveStep") + .HasColumnType("longtext") + .HasComment("step การอนุมัติ st1 = จทน.อนุมัตื,st2 = ผู้บังคับบัญชา อนุมัติ "); + + b.Property("BirthDate") + .HasColumnType("datetime(6)"); + + b.Property("CancelLeaveWrote") + .HasColumnType("longtext") + .HasComment("เขียนที่ (ขอยกเลิก)"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CommanderPosition") + .HasColumnType("longtext"); + + b.Property("CoupleDayCountryHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayEndDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDayLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayLevelCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayPosition") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CoupleDayStartDateHistory") + .HasColumnType("datetime(6)"); + + b.Property("CoupleDaySumTotalHistory") + .HasColumnType("longtext"); + + b.Property("CoupleDayTotalHistory") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DateAppoint") + .HasColumnType("datetime(6)"); + + b.Property("DateSendLeave") + .HasColumnType("datetime(6)"); + + b.Property("Dear") + .HasColumnType("longtext") + .HasComment("เรียนใคร"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("HajjDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveAddress") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานที่ติดต่อขณะลา"); + + b.Property("LeaveBirthDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveCancelComment") + .HasColumnType("longtext") + .HasComment("เหตุผลในการขอยกเลิก"); + + b.Property("LeaveCancelDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveCancelStatus") + .HasColumnType("longtext") + .HasComment("สถานะของคำขอยกเลิก"); + + b.Property("LeaveComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้บังคับบัญชา"); + + b.Property("LeaveDetail") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รายละเอียดการลา"); + + b.Property("LeaveDirectorComment") + .HasColumnType("longtext") + .HasComment("ความเห็นของผู้อำนวยการสำนัก"); + + b.Property("LeaveDraftDocumentId") + .HasColumnType("char(36)"); + + b.Property("LeaveEndDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีสิ้นสุดลา"); + + b.Property("LeaveGovernmentDate") + .HasColumnType("datetime(6)"); + + b.Property("LeaveLast") + .HasColumnType("datetime(6)"); + + b.Property("LeaveNumber") + .IsRequired() + .HasColumnType("longtext") + .HasComment("หมายเลขที่ติดต่อขณะลา"); + + b.Property("LeaveRange") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันเริ่ม เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveRangeEnd") + .HasColumnType("longtext") + .HasComment("ช่วงของการลาของวันสิ้นสุด เช่น ลาทั้งวัน ครึ่งวันเช้า ครึ่งวันบ่าย"); + + b.Property("LeaveSalary") + .HasColumnType("int"); + + b.Property("LeaveSalaryText") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LeaveStartDate") + .HasColumnType("datetime(6)") + .HasComment("วัน เดือน ปีเริ่มต้นลา"); + + b.Property("LeaveStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะของคำร้อง"); + + b.Property("LeaveSubTypeName") + .HasColumnType("longtext"); + + b.Property("LeaveTotal") + .HasColumnType("double"); + + b.Property("LeaveTypeCode") + .HasColumnType("longtext") + .HasComment("code ของประเภทการลา"); + + b.Property("LeaveWrote") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เขียนที่"); + + b.Property("OrdainDayBuddhistLentAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayBuddhistLentName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationAddress") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayLocationNumber") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OrdainDayOrdination") + .HasColumnType("datetime(6)"); + + b.Property("OrdainDayStatus") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationName") + .HasColumnType("longtext") + .HasComment("สังกัดผู้ยื่นขอ"); + + b.Property("PositionLevelName") + .HasColumnType("longtext") + .HasComment("ระดับผู้ยื่นขอ"); + + b.Property("PositionName") + .HasColumnType("longtext") + .HasComment("ตำแหน่งผู้ยื่นขอ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("RestDayCurrentTotal") + .HasColumnType("double"); + + b.Property("RestDayOldTotal") + .HasColumnType("double"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.Property("StudyDayCountry") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayDegreeLevel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayScholarship") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDaySubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayTrainingSubject") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("StudyDayUniversityName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("TypeId") + .HasColumnType("char(36)"); + + b.Property("WifeDayDateBorn") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WifeDayName") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.HasIndex("LeaveCancelDocumentId"); + + b.HasIndex("LeaveDraftDocumentId"); + + b.HasIndex("TypeId"); + + b.ToTable("LeaveRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("ApproveStatus") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ApproveType") + .HasColumnType("longtext"); + + b.Property("Comment") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("KeycloakId") + .HasColumnType("char(36)"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("LeaveRequestId") + .HasColumnType("char(36)"); + + b.Property("OrganizationName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สังกัด"); + + b.Property("PosExecutiveName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ตำแหน่งทางการบริหาร"); + + b.Property("PositionLevelName") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ประเภทระดับตำแหน่ง"); + + b.Property("PositionName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PositionSign") + .HasColumnType("longtext") + .HasComment("ตำแหน่งใต้ลายเช็นต์"); + + b.Property("Prefix") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("Seq") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LeaveRequestId"); + + b.ToTable("LeaveRequestApprovers"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.AdditionalCheckRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckDate") + .HasColumnType("datetime(6)") + .HasComment("*วันที่ลงเวลา"); + + b.Property("CheckInEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงเช้า"); + + b.Property("CheckOutEdit") + .HasColumnType("tinyint(1)") + .HasComment("*ขอลงเวลาช่วงบ่าย"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Comment") + .HasColumnType("longtext") + .HasComment("หมายเหตุในการการอนุมัติ/ไม่อนุมัติ"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("*หมายเหตุขอลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak ที่ร้องขอ"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Latitude") + .HasColumnType("double"); + + b.Property("Longitude") + .HasColumnType("double"); + + b.Property("POI") + .HasColumnType("longtext"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะการอนุมัติ"); + + b.HasKey("Id"); + + b.ToTable("AdditionalCheckRequests"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.CheckInJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("AdditionalData") + .HasColumnType("longtext") + .HasComment("ข้อมูลเพิ่มเติม (JSON)"); + + b.Property("CheckInId") + .HasColumnType("char(36)") + .HasComment("CheckInId สำหรับ Check-Out"); + + b.Property("CheckType") + .HasColumnType("longtext") + .HasComment("ประเภทการลงเวลา: CHECK_IN, CHECK_OUT"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.Property("TaskId") + .HasColumnType("char(36)") + .HasComment("Task ID สำหรับติดตามสถานะงาน"); + + b.HasKey("Id"); + + b.ToTable("CheckInJobStatuses"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("Description") + .IsRequired() + .HasColumnType("longtext") + .HasComment("คำอธิบาย"); + + b.Property("EndTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงบ่าย"); + + b.Property("EndTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาออกงานช่วงเช้า"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)") + .HasComment("สถานะการเปิดใช้งาน (เปิด/ปิด)"); + + b.Property("IsDefault") + .HasColumnType("tinyint(1)") + .HasComment("สถานะว่ารอบใดเป็นค่า Default ของข้าราชการ (สำหรับทุกคนที่ยังไม่ได้ทำการเลือกรอบ)"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("StartTimeAfternoon") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงบ่าย"); + + b.Property("StartTimeMorning") + .IsRequired() + .HasColumnType("longtext") + .HasComment("เวลาเข้างานช่วงเช้า"); + + b.HasKey("Id"); + + b.ToTable("DutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.LeaveProcessJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EndDate") + .HasColumnType("datetime(6)") + .HasComment("วันสิ้นสุด"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("RootDnaId") + .HasColumnType("char(36)") + .HasComment("รหัส Root DNA Id"); + + b.Property("StartDate") + .HasColumnType("datetime(6)") + .HasComment("วันเริ่มต้น"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.HasKey("Id"); + + b.ToTable("LeaveProcessJobStatuses"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckInStatus") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะ Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("CheckOutStatus") + .HasColumnType("longtext") + .HasComment("สถานะ Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EditReason") + .HasColumnType("longtext") + .HasComment("เหตุผลการอนุมัติ/ไม่อนุมัติขอลงเวลาพิเศษ"); + + b.Property("EditStatus") + .HasColumnType("longtext") + .HasComment("สถานะการของลงเวลาพิเศษ"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ProcessUserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserCalendar", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Calendar") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ปฏิทินการทำงานของ ขรก ปกติ หรือ 6 วันต่อสัปดาห์"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.HasKey("Id"); + + b.ToTable("UserCalendars"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("DutyTimeId") + .HasColumnType("char(36)") + .HasComment("รหัสรอบการลงเวลา"); + + b.Property("EffectiveDate") + .HasColumnType("datetime(6)") + .HasComment("วันที่มีผล"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("ทำการประมวลผลแล้วหรือยัง"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProfileId") + .HasColumnType("char(36)") + .HasComment("รหัส Profile ในระบบทะเบียนประวัติ"); + + b.Property("Remark") + .HasColumnType("longtext") + .HasComment("หมายเหตุ"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("DutyTimeId"); + + b.ToTable("UserDutyTimes"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserTimeStamp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CheckIn") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา เข้างาน"); + + b.Property("CheckInImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-In"); + + b.Property("CheckInLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-In"); + + b.Property("CheckInLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-In"); + + b.Property("CheckInLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-In"); + + b.Property("CheckInPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-In"); + + b.Property("CheckInRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-In"); + + b.Property("CheckOut") + .HasColumnType("datetime(6)") + .HasComment("วัน เวลา ออกงาน"); + + b.Property("CheckOutImageUrl") + .IsRequired() + .HasColumnType("longtext") + .HasComment("รูปถ่ายสถานที่ Check-Out"); + + b.Property("CheckOutLat") + .HasColumnType("double") + .HasComment("พิกัดละติจูด Check-Out"); + + b.Property("CheckOutLocationName") + .HasColumnType("longtext") + .HasComment("กรณีเลือกนอกสถานที่ตั้ง ต้องระบุข้อมูลชื่อสถานะที่ Check-Out"); + + b.Property("CheckOutLon") + .HasColumnType("double") + .HasComment("พิกัดลองจิจูด Check-Out"); + + b.Property("CheckOutPOI") + .IsRequired() + .HasColumnType("longtext") + .HasComment("ชื่อสถานที่ ได้มาจากระบบ ArcGis ของกองสารสนเทศภูมิศาสตร์ Check-Out"); + + b.Property("CheckOutRemark") + .HasColumnType("longtext") + .HasComment("ข้อความหมายเหตุที่ต้องการระบุเพิ่ม(มีเผื่อไว้อาจไม่ได้ใช้) Check-Out"); + + b.Property("Child1") + .HasColumnType("longtext"); + + b.Property("Child1DnaId") + .HasColumnType("char(36)"); + + b.Property("Child1Id") + .HasColumnType("char(36)"); + + b.Property("Child2") + .HasColumnType("longtext"); + + b.Property("Child2DnaId") + .HasColumnType("char(36)"); + + b.Property("Child2Id") + .HasColumnType("char(36)"); + + b.Property("Child3") + .HasColumnType("longtext"); + + b.Property("Child3DnaId") + .HasColumnType("char(36)"); + + b.Property("Child3Id") + .HasColumnType("char(36)"); + + b.Property("Child4") + .HasColumnType("longtext"); + + b.Property("Child4DnaId") + .HasColumnType("char(36)"); + + b.Property("Child4Id") + .HasColumnType("char(36)"); + + b.Property("CitizenId") + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("FirstName") + .HasColumnType("longtext"); + + b.Property("Gender") + .HasColumnType("longtext"); + + b.Property("IsLocationCheckIn") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-In"); + + b.Property("IsLocationCheckOut") + .HasColumnType("tinyint(1)") + .HasComment("true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง Check-Out"); + + b.Property("IsProcess") + .HasColumnType("tinyint(1)") + .HasComment("นำไปประมวลผลแล้วหรือยัง"); + + b.Property("KeycloakUserId") + .HasColumnType("char(36)") + .HasComment("รหัส User ของ Keycloak"); + + b.Property("LastName") + .HasColumnType("longtext"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("Prefix") + .HasColumnType("longtext"); + + b.Property("ProfileId") + .HasColumnType("char(36)"); + + b.Property("ProfileType") + .HasColumnType("longtext"); + + b.Property("Root") + .HasColumnType("longtext"); + + b.Property("RootDnaId") + .HasColumnType("char(36)"); + + b.Property("RootId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("UserTimeStamps"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "LeaveType") + .WithMany() + .HasForeignKey("LeaveTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveType"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "Document") + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("LeaveDocument") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Document"); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveCancelDocument") + .WithMany() + .HasForeignKey("LeaveCancelDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Documents.Document", "LeaveDraftDocument") + .WithMany() + .HasForeignKey("LeaveDraftDocumentId"); + + b.HasOne("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", "Type") + .WithMany() + .HasForeignKey("TypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveCancelDocument"); + + b.Navigation("LeaveDraftDocument"); + + b.Navigation("Type"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", "LeaveRequest") + .WithMany("Approvers") + .HasForeignKey("LeaveRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LeaveRequest"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => + { + b.HasOne("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", "DutyTime") + .WithMany() + .HasForeignKey("DutyTimeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DutyTime"); + }); + + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => + { + b.Navigation("Approvers"); + + b.Navigation("LeaveDocument"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.cs new file mode 100644 index 00000000..02d58933 --- /dev/null +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/20260423083625_Add DateSendLeave.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BMA.EHR.Infrastructure.Migrations.LeaveDb +{ + /// + public partial class AddDateSendLeave : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "DateSendLeave", + table: "LeaveRequests", + type: "datetime(6)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "DateSendLeave", + table: "LeaveRequests"); + } + } +} diff --git a/BMA.EHR.Infrastructure/Migrations/LeaveDb/LeaveDbContextModelSnapshot.cs b/BMA.EHR.Infrastructure/Migrations/LeaveDb/LeaveDbContextModelSnapshot.cs index b59264fc..887d4f97 100644 --- a/BMA.EHR.Infrastructure/Migrations/LeaveDb/LeaveDbContextModelSnapshot.cs +++ b/BMA.EHR.Infrastructure/Migrations/LeaveDb/LeaveDbContextModelSnapshot.cs @@ -128,6 +128,14 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb .HasComment("PrimaryKey") .HasAnnotation("Relational:JsonPropertyName", "id"); + b.Property("BeginningLeaveCount") + .HasColumnType("int") + .HasComment("จำนวนครั้งที่ลายกมา"); + + b.Property("BeginningLeaveDays") + .HasColumnType("double") + .HasComment("จำนวนวันลายกมา"); + b.Property("Child1DnaId") .HasColumnType("char(36)"); @@ -190,7 +198,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb b.Property("LeaveDays") .HasColumnType("double") - .HasComment("จำนวนวันลายกมา"); + .HasComment("จำนวนวันลาทั้งหมด"); b.Property("LeaveDaysUsed") .HasColumnType("double") @@ -420,6 +428,9 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb b.Property("DateAppoint") .HasColumnType("datetime(6)"); + b.Property("DateSendLeave") + .HasColumnType("datetime(6)"); + b.Property("Dear") .HasColumnType("longtext") .HasComment("เรียนใคร"); @@ -1064,6 +1075,91 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb b.ToTable("DutyTimes"); }); + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.LeaveProcessJobStatus", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)") + .HasColumnOrder(0) + .HasComment("PrimaryKey") + .HasAnnotation("Relational:JsonPropertyName", "id"); + + b.Property("CompletedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(100) + .HasComment("สร้างข้อมูลเมื่อ"); + + b.Property("CreatedDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่สร้างงาน"); + + b.Property("CreatedFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(104) + .HasComment("ชื่อ User ที่สร้างข้อมูล"); + + b.Property("CreatedUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(101) + .HasComment("User Id ที่สร้างข้อมูล"); + + b.Property("EndDate") + .HasColumnType("datetime(6)") + .HasComment("วันสิ้นสุด"); + + b.Property("ErrorMessage") + .HasColumnType("longtext") + .HasComment("ข้อความแสดงข้อผิดพลาด"); + + b.Property("LastUpdateFullName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .HasColumnOrder(105) + .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdateUserId") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)") + .HasColumnOrder(103) + .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime(6)") + .HasColumnOrder(102) + .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); + + b.Property("ProcessingDate") + .HasColumnType("datetime(6)") + .HasComment("วันเวลาที่เริ่มประมวลผล"); + + b.Property("RootDnaId") + .HasColumnType("char(36)") + .HasComment("รหัส Root DNA Id"); + + b.Property("StartDate") + .HasColumnType("datetime(6)") + .HasComment("วันเริ่มต้น"); + + b.Property("Status") + .IsRequired() + .HasColumnType("longtext") + .HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED"); + + b.HasKey("Id"); + + b.ToTable("LeaveProcessJobStatuses"); + }); + modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b => { b.Property("Id") diff --git a/BMA.EHR.Infrastructure/Persistence/LeaveDbContext.cs b/BMA.EHR.Infrastructure/Persistence/LeaveDbContext.cs index 19848c6b..10064197 100644 --- a/BMA.EHR.Infrastructure/Persistence/LeaveDbContext.cs +++ b/BMA.EHR.Infrastructure/Persistence/LeaveDbContext.cs @@ -40,6 +40,8 @@ namespace BMA.EHR.Infrastructure.Persistence #endregion + public DbSet LeaveProcessJobStatuses { get; set; } + public LeaveDbContext(DbContextOptions options) : base(options) { diff --git a/BMA.EHR.Insignia/Controllers/InsigniaManageController.cs b/BMA.EHR.Insignia/Controllers/InsigniaManageController.cs index 80a8ef31..6c0b809f 100644 --- a/BMA.EHR.Insignia/Controllers/InsigniaManageController.cs +++ b/BMA.EHR.Insignia/Controllers/InsigniaManageController.cs @@ -331,7 +331,7 @@ namespace BMA.EHR.Insignia.Service.Controllers if (req.Total + total > insigniaManage.Total) return Error(GlobalMessages.InsigniaManageOrgLimit); - var ocData = _userProfileRepository.GetOc(req.OrganizationOrganizationId, 0, AccessToken); + var ocData = _userProfileRepository.GetOcByNodeId(req.OrganizationOrganizationId, 0, AccessToken); var root = ocData?.Root ?? null; var rootDnaId = ocData?.RootDnaId ?? null; await _context.InsigniaManageOrganiations.AddAsync( @@ -407,6 +407,10 @@ namespace BMA.EHR.Insignia.Service.Controllers if (uppdated == null) return Error(GlobalMessages.InsigniaManageNotFound); + var ocData = _userProfileRepository.GetOcByNodeId(uppdated.OrganizationId, 0, AccessToken); + var root = ocData?.Root ?? null; + var rootDnaId = ocData?.RootDnaId ?? null; + var insigniaManage = await _context.InsigniaManages.AsQueryable() .Include(x => x.InsigniaManageOrganiations) .FirstOrDefaultAsync(x => x.Id == uppdated.InsigniaManage.Id); @@ -416,6 +420,9 @@ namespace BMA.EHR.Insignia.Service.Controllers if (req.Total + total > insigniaManage.Total) return Error(GlobalMessages.InsigniaManageOrgLimit); + uppdated.Organization = root; + uppdated.RootDnaId = rootDnaId; + uppdated.Total = req.Total; uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateUserId = UserId ?? ""; @@ -639,7 +646,7 @@ namespace BMA.EHR.Insignia.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -724,11 +731,11 @@ namespace BMA.EHR.Insignia.Service.Controllers rawData = rawData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); } - else if (role == "PARENT") - { - rawData = rawData - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // rawData = rawData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { rawData = rawData.Where(x => @@ -943,7 +950,7 @@ namespace BMA.EHR.Insignia.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -1026,11 +1033,11 @@ namespace BMA.EHR.Insignia.Service.Controllers rawData = rawData .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); } - else if (role == "PARENT") - { - rawData = rawData - .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // rawData = rawData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { rawData = rawData.Where(x => diff --git a/BMA.EHR.Insignia/Controllers/InsigniaRequestController.cs b/BMA.EHR.Insignia/Controllers/InsigniaRequestController.cs index 005f9882..415a0de2 100644 --- a/BMA.EHR.Insignia/Controllers/InsigniaRequestController.cs +++ b/BMA.EHR.Insignia/Controllers/InsigniaRequestController.cs @@ -2641,6 +2641,8 @@ namespace BMA.EHR.Insignia.Service.Controllers { if (item.CitizanId == null) continue; var _profile = await _userProfileRepository.GetOfficerProfileByCitizenId(item.CitizanId, AccessToken); + if (_profile == null) + continue; var profile = insigniaNote.InsigniaNoteProfiles.FirstOrDefault(x => x.ProfileId == _profile.Id); if (profile == null) { @@ -3096,7 +3098,7 @@ namespace BMA.EHR.Insignia.Service.Controllers var doc = await _documentService.UploadFileAsync(file, file.FileName); insigniaNoteProfile.DocReturnInsignia = doc; } - var root = _userProfileRepository.GetOc(req.OrgId, 0, AccessToken)?.Root ?? null; + var root = _userProfileRepository.GetOcByNodeId(req.OrgId, 0, AccessToken)?.Root ?? null; if (req.OrgId != Guid.Parse("00000000-0000-0000-0000-000000000000")) { if (root == null) @@ -3146,7 +3148,10 @@ namespace BMA.EHR.Insignia.Service.Controllers var doc = await _documentService.UploadFileAsync(file, file.FileName); insigniaNoteProfile.DocReceiveInsignia = doc; } - var root = _userProfileRepository.GetOc(req.OrgId, 0, AccessToken)?.Root ?? null; + + var orgData = _userProfileRepository.GetOcByNodeId(req.OrgId,0, AccessToken); + var root = orgData?.Root ?? null; + var rootDnaId = orgData?.RootDnaId ?? null; if (req.OrgId != Guid.Parse("00000000-0000-0000-0000-000000000000")) { if (root == null) @@ -3157,6 +3162,7 @@ namespace BMA.EHR.Insignia.Service.Controllers root = "สำนักนายกรัฐมนตรี"; } insigniaNoteProfile.OrgReceiveInsignia = root; + insigniaNoteProfile.RootDnaId = rootDnaId; insigniaNoteProfile.OrgReceiveInsigniaId = req.OrgId; insigniaNoteProfile.DateReceiveInsignia = req.Date; insigniaNoteProfile.LastUpdateFullName = FullName ?? "System Administrator"; diff --git a/BMA.EHR.Insignia/Program.cs b/BMA.EHR.Insignia/Program.cs index a4dd716a..88c1c2ac 100644 --- a/BMA.EHR.Insignia/Program.cs +++ b/BMA.EHR.Insignia/Program.cs @@ -131,7 +131,7 @@ var builder = WebApplication.CreateBuilder(args); { options.ServerName = "Insignia-Server"; // ← ระบุชื่อ server options.WorkerCount = 5; // ← - options.Queues = new[] { "insignia" }; // ← worker จะรันเฉพาะ queue "insignia" + options.Queues = new[] { "insignia","default" }; // ← worker จะรันเฉพาะ queue "insignia" }); diff --git a/BMA.EHR.Insignia/appsettings.json b/BMA.EHR.Insignia/appsettings.json index 4f3d3faf..4e160482 100644 --- a/BMA.EHR.Insignia/appsettings.json +++ b/BMA.EHR.Insignia/appsettings.json @@ -31,10 +31,11 @@ //"DisciplineConnection": "server=hrms.chin.in.th;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=53636;database=hrms_discipline;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" }, "Jwt": { - //"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc", - //"Issuer": "https://hrms-id.chin.in.th/realms/hrms" - "Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI", - "Issuer": "https://id.frappet.synology.me/realms/hrms" + //"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI", + "Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc", + "Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms" + //"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU", + //"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms" }, "EPPlus": { "ExcelPackage": { @@ -55,11 +56,17 @@ "Node": { "API": "https://bma-ehr.frappet.synology.me/api/v1/probation" }, - "API": "https://bma-ehr.frappet.synology.me/api/v1", "RabbitMQ": { "URL": "localhost", "UserName": "frappet", "Password": "FPTadmin2357" }, + "Domain": "https://hrmsbkk.case-collection.com", + "APIPROBATION": "https://hrmsbkk.case-collection.com/api/v1/probation", + "API": "https://hrmsbkk.case-collection.com/api/v1", + "APIV2": "https://hrmsbkk.case-collection.com/api/v2", + "VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com", + //"API": "https://bma-ehr.frappet.synology.me/api/v1", + //"API": "https://bma-hrms.bangkok.go.th/api/v1", "API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz" } diff --git a/BMA.EHR.Leave/BMA.EHR.Leave.csproj b/BMA.EHR.Leave/BMA.EHR.Leave.csproj index 83132dd1..28f42590 100644 --- a/BMA.EHR.Leave/BMA.EHR.Leave.csproj +++ b/BMA.EHR.Leave/BMA.EHR.Leave.csproj @@ -45,6 +45,7 @@ + diff --git a/BMA.EHR.Leave/Controllers/LeaveBeginningController.cs b/BMA.EHR.Leave/Controllers/LeaveBeginningController.cs index 3a3140e8..e580b00a 100644 --- a/BMA.EHR.Leave/Controllers/LeaveBeginningController.cs +++ b/BMA.EHR.Leave/Controllers/LeaveBeginningController.cs @@ -141,7 +141,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -166,11 +166,11 @@ namespace BMA.EHR.Leave.Service.Controllers 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 == "PARENT") + // { + // resData = resData + // .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { resData = resData @@ -202,6 +202,8 @@ namespace BMA.EHR.Leave.Service.Controllers item.LeaveDays, item.LeaveDaysUsed, item.LeaveCount, + item.BeginningLeaveDays, + item.BeginningLeaveCount, item.CreatedAt, item.CreatedFullName, item.LastUpdatedAt, @@ -396,6 +398,8 @@ namespace BMA.EHR.Leave.Service.Controllers leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed; leaveBeginning.LeaveCount = req.LeaveCount; + leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays; + leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount; leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.Prefix = profile.Prefix; @@ -465,6 +469,8 @@ namespace BMA.EHR.Leave.Service.Controllers leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed; leaveBeginning.LeaveCount = req.LeaveCount; + leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays; + leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount; leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.Prefix = profile.Prefix; @@ -492,6 +498,126 @@ namespace BMA.EHR.Leave.Service.Controllers } } + [HttpPut("schedule")] + [AllowAnonymous] + public async Task> ScheduleUpdateLeaveBeginningAsync([FromBody] ScheduleEditLeaveBeginningDto req) + { + try + { + var profile = await _userProfileRepository.GetProfileByProfileIdNoAuthAsync(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("ไม่สามารถบันทึกข้อมูล เนื่องจากมีข้อมูลในระบบแล้ว"); + oldData.LeaveTypeId = req.LeaveTypeId; + oldData.LeaveYear = req.LeaveYear; + oldData.LeaveDays = req.LeaveDays; + // oldData.LeaveDaysUsed = req.LeaveDaysUsed; + // oldData.LeaveCount = req.LeaveCount; + // oldData.BeginningLeaveDays = req.BeginningLeaveDays; + // oldData.BeginningLeaveCount = req.BeginningLeaveCount; + + oldData.ProfileId = req.ProfileId; + oldData.Prefix = profile.Prefix; + oldData.FirstName = profile.FirstName; + oldData.LastName = profile.LastName; + oldData.RootDnaId = profile.RootDnaId; + oldData.Child1DnaId = profile.Child1DnaId; + oldData.Child2DnaId = profile.Child2DnaId; + oldData.Child3DnaId = profile.Child3DnaId; + oldData.Child4DnaId = profile.Child4DnaId; + + oldData.LastUpdateUserId = ""; + oldData.LastUpdateFullName = "System"; + oldData.LastUpdatedAt = DateTime.Now; + + await _leaveBeginningRepository.UpdateAsync(oldData); + } + else + { + var leaveBeginning = new LeaveBeginning(); + leaveBeginning.LeaveTypeId = req.LeaveTypeId; + leaveBeginning.LeaveYear = req.LeaveYear; + leaveBeginning.LeaveDays = req.LeaveDays; + leaveBeginning.LeaveDaysUsed = 0; + leaveBeginning.LeaveCount = 0; + leaveBeginning.BeginningLeaveDays = 0; + leaveBeginning.BeginningLeaveCount = 0; + + 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 = ""; + leaveBeginning.CreatedFullName = "System"; + leaveBeginning.CreatedAt = DateTime.Now; + + await _leaveBeginningRepository.AddAsync(leaveBeginning); + } + return Success(); + } + catch (Exception ex) + { + return Error(ex); + } + } + + + [HttpPut("schedule/update-dna")] + [AllowAnonymous] + public async Task> ScheduleUpdateDnaAsync([FromBody] List req) + { + try + { + foreach(var item in req) + { + // var profile = await _userProfileRepository.GetProfileByProfileIdNoAuthAsync(item.ProfileId, AccessToken); + // if(profile == null) + // { + // return Error("ไม่พบข้อมูลข้าราชการหรือลูกจ้าง", StatusCodes.Status404NotFound); + // } + // check duplicate + var oldData = await _context.LeaveBeginnings.Where(x => x.ProfileId == item.ProfileId).ToListAsync(); + + foreach(var o in oldData) + { + o.RootDnaId = item.RootDnaId; + o.Child1DnaId = item.Child1DnaId; + o.Child2DnaId = item.Child2DnaId; + o.Child3DnaId = item.Child3DnaId; + o.Child4DnaId = item.Child4DnaId; + + o.LastUpdateUserId = ""; + o.LastUpdateFullName = "System"; + o.LastUpdatedAt = DateTime.Now; + + await _leaveBeginningRepository.UpdateAsync(o); + } + } + + + return Success(); + } + catch (Exception ex) + { + return Error(ex); + } + } #endregion } diff --git a/BMA.EHR.Leave/Controllers/LeaveController.cs b/BMA.EHR.Leave/Controllers/LeaveController.cs index 665b209c..c77bad95 100644 --- a/BMA.EHR.Leave/Controllers/LeaveController.cs +++ b/BMA.EHR.Leave/Controllers/LeaveController.cs @@ -3,8 +3,10 @@ using BMA.EHR.Application.Repositories.Commands; using BMA.EHR.Application.Repositories.Leaves.LeaveRequests; using BMA.EHR.Application.Repositories.Leaves.TimeAttendants; using BMA.EHR.Application.Repositories.MessageQueue; +using BMA.EHR.Application.Responses.Leaves; using BMA.EHR.Application.Responses.Profiles; using BMA.EHR.Domain.Common; +using BMA.EHR.Domain.Extensions; using BMA.EHR.Domain.Models.Leave.TimeAttendants; using BMA.EHR.Domain.Models.Notifications; using BMA.EHR.Domain.Shared; @@ -74,6 +76,8 @@ namespace BMA.EHR.Leave.Service.Controllers private readonly HttpClient _httpClient; + private readonly LeaveProcessJobStatusRepository _leaveProcessJobStatusRepository; + #endregion #region " Constuctor and Destructor " @@ -97,7 +101,8 @@ namespace BMA.EHR.Leave.Service.Controllers NotificationRepository notificationRepository, CheckInJobStatusRepository checkInJobStatusRepository, HttpClient httpClient, - ApplicationDBContext appDbContext) + ApplicationDBContext appDbContext, + LeaveProcessJobStatusRepository leaveProcessJobStatusRepository) { _dutyTimeRepository = dutyTimeRepository; _context = context; @@ -116,7 +121,7 @@ namespace BMA.EHR.Leave.Service.Controllers _leaveRequestRepository = leaveRequestRepository; _notificationRepository = notificationRepository; _checkInJobStatusRepository = checkInJobStatusRepository; - + _leaveProcessJobStatusRepository = leaveProcessJobStatusRepository; _objectPool = objectPool; _permission = permission; @@ -144,7 +149,13 @@ namespace BMA.EHR.Leave.Service.Controllers { get { - if (UserId != null || UserId != "") + // First try to get from claims + var ocIdFromClaims = OrgRootDnaId; + if (ocIdFromClaims.HasValue && ocIdFromClaims.Value != Guid.Empty) + return ocIdFromClaims.Value; + + // Fallback to API call for backward compatibility + if (UserId != null && UserId != "") return _userProfileRepository.GetUserOCId(Guid.Parse(UserId!), AccessToken); else return Guid.Empty; @@ -438,7 +449,7 @@ namespace BMA.EHR.Leave.Service.Controllers // Get user's last check-in record and profile in parallel var dataTask = _userTimeStampRepository.GetLastRecord(userId); - var profileTask = _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profileTask = _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); var defaultRoundTask = _dutyTimeRepository.GetDefaultAsync(); await Task.WhenAll(dataTask, profileTask, defaultRoundTask); @@ -927,7 +938,7 @@ namespace BMA.EHR.Leave.Service.Controllers await _checkInJobStatusRepository.UpdateToProcessingAsync(taskId); } - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, data.Token); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, data.Token); if (profile == null) { @@ -957,15 +968,24 @@ namespace BMA.EHR.Leave.Service.Controllers return Error(GlobalMessages.NoFileToUpload, StatusCodes.Status400BadRequest); } + // last check-in record + var lastCheckIn = await _userTimeStampRepository.GetLastRecord(userId); var check_status = data.CheckInId == null ? "check-in-picture" : "check-out-picture"; + var check_out_status = "check-out-picture"; var fileName = $"{_bucketName}/{userId}/{currentDate.ToString("dd-MM-yyyy")}/{check_status}/{data.CheckInFileName}"; + var fileNameCheckOut = $"{_bucketName}/{userId}/{currentDate.ToString("dd-MM-yyyy")}/{check_out_status}/{data.CheckInFileName}"; using (var ms = new MemoryStream(data.CheckInFileBytes ?? new byte[0])) { try { await _minIOService.UploadFileAsync(fileName, ms); + // if (lastCheckIn != null && lastCheckIn.CheckOut == null) + // { + // // ยังไม่เคย check-out มาก่อน หรือ check-out เป็น null ให้ใช้ชื่อไฟล์แบบ check-out + // await _minIOService.UploadFileAsync(fileNameCheckOut, ms); + // } } catch (Exception ex) { @@ -988,6 +1008,42 @@ namespace BMA.EHR.Leave.Service.Controllers } + if (lastCheckIn != null && lastCheckIn.CheckOut == null) + { + using (var ms2 = new MemoryStream(data.CheckInFileBytes ?? new byte[0])) + { + try + { + await _minIOService.UploadFileAsync(fileNameCheckOut, ms2); + // if (lastCheckIn != null && lastCheckIn.CheckOut == null) + // { + // // ยังไม่เคย check-out มาก่อน หรือ check-out เป็น null ให้ใช้ชื่อไฟล์แบบ check-out + // await _minIOService.UploadFileAsync(fileNameCheckOut, ms); + // } + } + catch (Exception ex) + { + await _checkInJobStatusRepository.UpdateToFailedAsync(taskId, $"ไม่สามารถอัปโหลดรูปภาพได้: {ex.Message}"); + + // send notification to user + var noti1 = new Notification + { + Body = $"ประมวลผลการลงเวลาวันที่ {currentDate.ToString("dd-MM-yyyy")} ไม่สำเร็จ \r\nเนื่องจากไม่สามารถอัปโหลดรูปภาพได้ {ex.Message}", + ReceiverUserId = profile.Id, + Type = "", + Payload = "", + }; + _appDbContext.Set().Add(noti1); + await _appDbContext.SaveChangesAsync(); + + + return Error($"ไม่สามารถอัปโหลดรูปภาพได้: {ex.Message}", StatusCodes.Status500InternalServerError); + } + + } + } + + var defaultRound = await _dutyTimeRepository.GetDefaultAsync(); if (defaultRound == null) { @@ -1015,6 +1071,124 @@ namespace BMA.EHR.Leave.Service.Controllers // create check in object if (data.CheckInId == null) { + if (lastCheckIn != null && lastCheckIn.CheckOut == null) + { + var checkout = await _userTimeStampRepository.GetByIdAsync(lastCheckIn!.Id); + if(checkout != null) + { + var currentCheckInProcess = await _processUserTimeStampRepository.GetTimestampByDateAsync(userId, checkout.CheckIn.Date); + var checkout_process = await _processUserTimeStampRepository.GetByIdAsync(currentCheckInProcess!.Id); + var endTime1 = ""; + var startTime1 = ""; + var endTimeMorning1 = ""; + if (!data.IsLocation && data.LocationName == "ไปประชุม / อบรม / สัมมนา") + { + startTime1 = "13:00"; + endTime1 = "14:30"; + endTimeMorning1 = "12:00"; + } + else + { + endTime1 = duty.EndTimeAfternoon; + startTime1 = duty.StartTimeAfternoon; + endTimeMorning1 = duty.EndTimeMorning; + } + + string checkOutStatus = "NORMAL"; + var leaveReq1 = await _leaveRequestRepository.GetLeavePeriodAsync(userId, currentDate.Date); + if (leaveReq1 != null) + { + var leaveRange = leaveReq1.LeaveRangeEnd == null ? "" : leaveReq1.LeaveRangeEnd.ToUpper(); + if (leaveRange == "AFTERNOON" || leaveRange == "ALL") + { + if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) < + DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning1}")) + checkOutStatus = "ABSENT"; + else + checkOutStatus = "NORMAL"; + } + else + { + // fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลาเข้า-ออกงาน (กรณีลงเวลาออกอีกวัน) #921 + var currentDateTime = DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")); + var dutyEndTimeAfternoon = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTime1}"); + var dutyEndTimeMorning = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTimeMorning1}"); + + + if(currentDateTime.Date > checkout.CheckIn.Date) + { + // ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ + checkOutStatus = "NORMAL"; + } + else + { + // ถ้า check-out เป็นวันเดียวกับ check-in + // ตรวจสอบเวลาว่าสิ้นสุดก่อนบ่ายหรือไม่ + if(currentDateTime < dutyEndTimeMorning) // ถ้าออกก่อนเวลาสิ้นสุดตอนเช้า ขาดราชการ + { + checkOutStatus = "ABSENT"; + } + else if(currentDateTime >= dutyEndTimeAfternoon) // ถ้าออกหลังเวลาสิ้นสุดตอนบ่าย ปกติ + { + checkOutStatus = "NORMAL"; + } + else + { + checkOutStatus = "ABSENT"; + } + } + } + } + else + { + // fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลาเข้า-ออกงาน (กรณีลงเวลาออกอีกวัน) #921 + var currentDateTime = DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")); + var dutyEndTimeAfternoon = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTime1}"); + var dutyEndTimeMorning = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTimeMorning1}"); + + + if(currentDateTime.Date > checkout.CheckIn.Date) + { + // ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ + checkOutStatus = "NORMAL"; + } + else + { + // ถ้า check-out เป็นวันเดียวกับ check-in + // ตรวจสอบเวลาว่าสิ้นสุดก่อนบ่ายหรือไม่ + if(currentDateTime < dutyEndTimeMorning) // ถ้าออกก่อนเวลาสิ้นสุดตอนเช้า ขาดราชการ + { + checkOutStatus = "ABSENT"; + } + else if(currentDateTime >= dutyEndTimeAfternoon) // ถ้าออกหลังเวลาสิ้นสุดตอนบ่าย ปกติ + { + checkOutStatus = "NORMAL"; + } + else + { + checkOutStatus = "ABSENT"; + } + } + + } + + if (checkout_process != null) + { + checkout_process.CheckOutLat = data.Lat; + checkout_process.CheckOutLon = data.Lon; + checkout_process.IsLocationCheckOut = data.IsLocation; + checkout_process.CheckOutLocationName = data.LocationName; + checkout_process.CheckOutPOI = data.POI; + checkout_process.CheckOutRemark = data.Remark; + checkout_process.CheckOutImageUrl = fileNameCheckOut; + checkout_process.CheckOut = currentDate; + checkout_process.CheckOutStatus = checkOutStatus; + + await _processUserTimeStampRepository.UpdateAsync(checkout_process); + } + } + } + // validate duplicate check in var currentCheckIn = await _userTimeStampRepository.GetTimestampByDateAsync(userId, currentDate); @@ -1167,6 +1341,7 @@ namespace BMA.EHR.Leave.Service.Controllers else { var checkout = await _userTimeStampRepository.GetByIdAsync(data.CheckInId.Value); + //var currentCheckIn = await _userTimeStampRepository.GetTimestampByDateAsync(userId, currentDate); if (checkout == null) { @@ -1242,11 +1417,20 @@ namespace BMA.EHR.Leave.Service.Controllers var leaveRange = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); if (leaveRange == "AFTERNOON" || leaveRange == "ALL") { - if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) < - DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning}")) - checkOutStatus = "ABSENT"; - else + if (checkout.CheckIn.Date < currentDate.Date) + { + // ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ checkOutStatus = "NORMAL"; + } + else + { + if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) < + DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning}")) + checkOutStatus = "ABSENT"; + else + checkOutStatus = "NORMAL"; + } + } else { @@ -1407,7 +1591,7 @@ namespace BMA.EHR.Leave.Service.Controllers public async Task> CheckInOldAsync([FromForm] CheckTimeDto data) { var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); @@ -1572,7 +1756,7 @@ namespace BMA.EHR.Leave.Service.Controllers { var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); @@ -1598,7 +1782,7 @@ namespace BMA.EHR.Leave.Service.Controllers // var test = await _processUserTimeStampRepository.GetTimeStampHistoryAsync(userId, year); // return Success(test); - var data = (await _processUserTimeStampRepository.GetTimeStampHistoryAsync(userId, year)) + var data = (await _processUserTimeStampRepository.GetTimeStampHistoryAsync2(userId, year)) .Select(d => new CheckInHistoryDto { CheckInId = d.Id, @@ -1714,7 +1898,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -1861,7 +2045,7 @@ namespace BMA.EHR.Leave.Service.Controllers } else { - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(d.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(d.KeycloakUserId, AccessToken); if (profile == null) { return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); @@ -2023,7 +2207,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2269,11 +2453,11 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } - var profile = await _userProfileRepository.SearchProfile(req.CitizenId, req.FirstName, req.LastName, AccessToken ?? "", req.Page, req.PageSize, role, nodeId, profileAdmin?.Node); + var profile = await _userProfileRepository.SearchProfile(req.CitizenId, req.FirstName, req.LastName, AccessToken ?? "", req.Page, req.PageSize, role, nodeId, profileAdmin?.Node, req.SelectedNodeId == null ? null : req.SelectedNodeId.Value.ToString("D"), req.SelectedNode); // Get default round once var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync(); @@ -2317,7 +2501,16 @@ namespace BMA.EHR.Leave.Service.Controllers FullName = $"{p.Prefix ?? ""}{p.FirstName ?? ""} {p.LastName ?? ""}", StartTimeMorning = duty.StartTimeMorning, LeaveTimeAfterNoon = duty.EndTimeAfternoon, - EffectiveDate = effectiveDate?.EffectiveDate?.Date + EffectiveDate = effectiveDate?.EffectiveDate?.Date, + Prefix = p.Prefix ?? "", + FirstName = p.FirstName ?? "", + LastName = p.LastName ?? "", + RootDnaId = p.RootDnaId, + Child1DnaId = p.Child1DnaId, + Child2DnaId = p.Child2DnaId, + Child3DnaId = p.Child3DnaId, + Child4DnaId = p.Child4DnaId + }; resultSet.Add(res); } @@ -2384,6 +2577,64 @@ namespace BMA.EHR.Leave.Service.Controllers } + [HttpPost("round/multiple")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> CreateChangeRoundMultipleAsync([FromBody] List reqs) + { + var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_WORK_ROUND_EDIT"); + var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData["status"]?.ToString() != "200") + { + return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + } + var currentDate = DateTime.Now.Date; + + List dataList = new List(); + + foreach(var req in reqs) + { + // var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken); + // if (profile == null) + // { + // return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + // } + + if (req.EffectiveDate.Date < currentDate) + { + continue; // move to next item if effective date is in the past, not return error + // return Error(new Exception($"กำหนดรอบลงเวลาของ {req.FirstName} {req.LastName} ผิดพลาด เนื่องจากวันที่มีผลต้องมากกว่าหรือเท่ากับวันที่ปัจจุบัน({currentDate.ToString("yyyy-MM-dd")})"), StatusCodes.Status400BadRequest); + } + + var old = await _userDutyTimeRepository.GetExist(req.ProfileId, req.EffectiveDate); + + if (old != null) + { + continue; // move to next item if already exist, not return error + //return Error(new Exception($"กำหนดรอบลงเวลาของ {req.FirstName} {req.LastName} ผิดพลาด เนื่องจากมีการกำหนดรอบการทำงานในวันที่นี้ไว้แล้ว"), StatusCodes.Status400BadRequest); + } + + var data = new UserDutyTime + { + ProfileId = req.ProfileId, + DutyTimeId = req.RoundId, + EffectiveDate = req.EffectiveDate, + Remark = req.Remark, + + RootDnaId = req.RootDnaId, + Child1DnaId = req.Child1DnaId, + Child2DnaId = req.Child2DnaId, + Child3DnaId = req.Child3DnaId, + Child4DnaId = req.Child4DnaId, + }; + dataList.Add(data); + } + + await _userDutyTimeRepository.AddRangeAsync(dataList); + return Success(); + } + /// /// LV1_015 - ประวัติการเปลี่ยนรอบการลงเวลา (ADMIN) /// @@ -2524,7 +2775,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2744,7 +2995,7 @@ namespace BMA.EHR.Leave.Service.Controllers var time = DateTime.Now; var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty; - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -2864,7 +3115,7 @@ namespace BMA.EHR.Leave.Service.Controllers } var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty; - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { throw new Exception(GlobalMessages.DataNotFound); @@ -2913,13 +3164,14 @@ namespace BMA.EHR.Leave.Service.Controllers [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> GetAdditionalCheckRequestAsync([Required] int year, [Required] int month, [Required] int page = 1, [Required] int pageSize = 10, string keyword = "", string? sortBy = "", bool? descending = false) { - var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_CHECKIN_SPECIAL"); - var jsonData = JsonConvert.DeserializeObject(getPermission); - if (jsonData["status"]?.ToString() != "200") + var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_CHECKIN_SPECIAL"); + //var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData!.status != 200) { - return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + return Error(jsonData.message, StatusCodes.Status403Forbidden); } - string role = jsonData["result"]?.ToString(); + //string role = jsonData["result"]?.ToString(); + string role = jsonData.result.privilege; var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); @@ -2949,7 +3201,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2957,6 +3209,82 @@ namespace BMA.EHR.Leave.Service.Controllers //var rawData = await _additionalCheckRequestRepository.GetAdditionalCheckRequests(year, month); var rawData = await _additionalCheckRequestRepository.GetAdditionalCheckRequestsByAdminRole(year, month, role, nodeId, profileAdmin?.Node, keyword); + // ถ้ามีการรักษาการ + if (jsonData.result.isAct) + { + var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY"); + foreach(var act in posActs) + { + var actRole = act.privilege; + string actNodeId = string.Empty; + int? actNode; + + if (actRole == "NORMAL" || actRole == "CHILD") + { + actNodeId = act.child4DnaId != null ? + act.child4DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child1DnaId != null ? + act.child1DnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "BROTHER") + { + actNodeId = act.child4DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child1DnaId!.Value.ToString("D") : + act.child1DnaId != null ? + act.rootDnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "ROOT" /*|| role == "PARENT"*/) + { + actNodeId = act.rootDnaId!.Value.ToString("D"); + actNode = 0; + } + + var rawDataAct = await _additionalCheckRequestRepository.GetAdditionalCheckRequestsByAdminRole(year, month, actRole, actNodeId, profileAdmin?.Node, keyword); + if (rawDataAct != null) + { + if (rawData != null) + rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList(); + else + rawData = rawDataAct; + } + } + } var total = rawData.Count; var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync(); @@ -3027,17 +3355,16 @@ namespace BMA.EHR.Leave.Service.Controllers foreach (var data in rawDataPaged) { - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken); - if (profile == null) + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken); + UserDutyTime? effectiveDate = null; + if (profile != null) { - return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(profile.Id); + //return Error($"{data.Id} PF{data.FirstName} {data.LastName} : {GlobalMessages.DataNotFound}", StatusCodes.Status404NotFound); } //var userRound = await _dutyTimeRepository.GetByIdAsync(profile.DutyTimeId ?? Guid.Empty); - - var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(profile.Id); var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty; var userRound = await _dutyTimeRepository.GetByIdAsync(roundId); - var checkInData = await _userTimeStampRepository.GetTimestampByDateAsync(data.KeycloakUserId, data.CheckDate); var duty = userRound ?? getDefaultRound; @@ -3207,7 +3534,7 @@ namespace BMA.EHR.Leave.Service.Controllers // change user timestamp var processTimeStamp = await _processUserTimeStampRepository.GetTimestampByDateAsync(requestData.KeycloakUserId, requestData.CheckDate.Date); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(requestData.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(requestData.KeycloakUserId, AccessToken); if (processTimeStamp == null) { @@ -3361,7 +3688,7 @@ namespace BMA.EHR.Leave.Service.Controllers requestData.Comment = req.Reason; await _additionalCheckRequestRepository.UpdateAsync(requestData); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(requestData.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(requestData.KeycloakUserId, AccessToken); var recvId = new List { profile.Id }; await _notificationRepository.PushNotificationsAsync(recvId.ToArray(), "ลงเวลากรณีพิเศษ", "การขอลงเวลากรณีพิเศษของคุณไม่ได้รับการอนุมัติ", "", "", true, false); @@ -3405,7 +3732,7 @@ namespace BMA.EHR.Leave.Service.Controllers } else { - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(d.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(d.KeycloakUserId, AccessToken); if (profile == null) { return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); @@ -3499,7 +3826,7 @@ namespace BMA.EHR.Leave.Service.Controllers foreach (var data in rawData) { - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken); if (profile == null) { return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); @@ -3789,7 +4116,7 @@ namespace BMA.EHR.Leave.Service.Controllers //var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); // แก้เป็นมาใช้งาน KeycloakUserId แทน - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken); var defaultRound = await _dutyTimeRepository.GetDefaultAsync(); if (defaultRound == null) { @@ -3859,7 +4186,7 @@ namespace BMA.EHR.Leave.Service.Controllers [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> GetLeaveSummaryByProfileAsync(Guid id, [FromBody] GetLeaveSummaryDto req) { - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(id, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(id, AccessToken); var thisYear = DateTime.Now.Year; var startDate = req.StartDate; @@ -3908,6 +4235,182 @@ namespace BMA.EHR.Leave.Service.Controllers }); } + #endregion + + #region " Process - Leave and Absence " + + + /// + /// สร้าง Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN) + /// + /// + /// + /// เมื่อทำรายการสำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpPost("admin/leave-task/process")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> CreateProcessTaskAsync([FromBody] CreateLeaveProcessJobDto req) + { + var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); + + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); + if (profile == null) + { + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + } + + var task = new LeaveProcessJobStatus + { + RootDnaId = profile.RootDnaId ?? Guid.Empty, + CreatedUserId = profile.Keycloak?.ToString("D") ?? "", + CreatedFullName = profile.FirstName + " " + profile.LastName, + CreatedAt = DateTime.Now, + Status = "PENDING", + StartDate = req.StartDate, + EndDate = req.EndDate + }; + + await _leaveProcessJobStatusRepository.AddAsync(task); + + return Success(); + } + + /// + /// แสดงรายการ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN) + /// + /// + /// + /// เมื่อทำรายการสำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpGet("admin/leave-task/process")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetProcessTaskAsync() + { + var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); + + var tasks = await _leaveProcessJobStatusRepository.GetByUserIdAsync(userId); + + var result = tasks.Select(t => new + { + t.Id, + t.CreatedFullName, + t.CreatedAt, + t.Status, + t.StartDate, + t.EndDate, + t.ProcessingDate, + t.CompletedDate, + t.ErrorMessage + }); + + return Success(result); + } + + + /// + /// แสดงรายการ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN) + /// + /// + /// + /// เมื่อทำรายการสำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpGet("admin/leave-task/process/{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetProcessTaskByIdAsync(Guid id) + { + var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id); + + if (task == null) + { + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + } + + var result = new + { + task.Id, + task.CreatedFullName, + task.CreatedAt, + task.Status, + task.StartDate, + task.EndDate, + task.ProcessingDate, + task.CompletedDate, + task.ErrorMessage + }; + + return Success(result); + } + + /// + /// ลบ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN) + /// + /// + /// + /// เมื่อทำรายการสำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpDelete("admin/leave-task/process/{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> DeleteProcessTaskByIdAsync(Guid id) + { + var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id); + + if (task == null) + { + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + } + + await _leaveProcessJobStatusRepository.DeleteAsync(task); + + return Success(); + } + + /// + /// อัปเดต Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN) + /// + /// + /// + /// เมื่อทำรายการสำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpPut("admin/leave-task/process/{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> UpdateProcessTaskByIdAsync(Guid id,[FromBody] CreateLeaveProcessJobDto req) + { + var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id); + + if (task == null) + { + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + } + + if(task.Status != "PENDING") + { + return Error("ไม่สามารถแก้ไขได้เนื่องจาก Task อยู่ในสถานะกำลังดำเนินการหรือดำเนินการเสร็จสิ้นแล้ว"); + } + + task.StartDate = req.StartDate; + task.EndDate = req.EndDate; + + await _leaveProcessJobStatusRepository.UpdateAsync(task); + + return Success(); + } + + #endregion #endregion diff --git a/BMA.EHR.Leave/Controllers/LeaveReportController.cs b/BMA.EHR.Leave/Controllers/LeaveReportController.cs index 4e5a0961..e726aabd 100644 --- a/BMA.EHR.Leave/Controllers/LeaveReportController.cs +++ b/BMA.EHR.Leave/Controllers/LeaveReportController.cs @@ -7,6 +7,7 @@ using BMA.EHR.Application.Responses.Profiles; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Extensions; using BMA.EHR.Domain.Models.Leave.Requests; +using BMA.EHR.Domain.Models.Leave.TimeAttendants; using BMA.EHR.Domain.Shared; using BMA.EHR.Leave.Service.DTOs.Reports; using Microsoft.AspNetCore.Authorization; @@ -149,14 +150,26 @@ namespace BMA.EHR.Leave.Service.Controllers } var fullName = $"{profile!.Prefix}{profile!.FirstName} {profile!.LastName}"; + var lastLeaveRequest = - await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync(data.KeycloakUserId, - data.Type.Id, data.LeaveStartDate.Date); + await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync2(data.KeycloakUserId, + data.Type.Id, data.CreatedAt); var startFiscalYear = new DateTime(data.LeaveStartDate.Year - 1, 10, 1); - var endFiscalYear = data.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา - var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear); + var endFiscalYear = data.CreatedAt; + + var thisYear = data.LeaveStartDate.Year; + var toDay = data.LeaveStartDate.Date; + if (toDay >= new DateTime(toDay.Year, 10, 1) && toDay <= new DateTime(toDay.Year, 12, 31)) + thisYear = thisYear + 1; + var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, data.Type.Id, data.KeycloakUserId); + var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear); + if (leaveData != null) + { + sumLeave += leaveData.BeginningLeaveDays; + } + var Oc = profile.isCommission == false ? profile.Oc.ToThaiNumber() : profile.Oc.Replace("สำนักงานคณะกรรมการข้าราชการกรุงเทพมหานคร", "สำนักงาน ก.ก.").ToThaiNumber(); @@ -169,7 +182,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -259,7 +272,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -319,7 +332,7 @@ namespace BMA.EHR.Leave.Service.Controllers var fullName = $"{profile!.Prefix}{profile!.FirstName} {profile!.LastName}"; var startFiscalYear = new DateTime(data.LeaveStartDate.Year - 1, 10, 1); - var endFiscalYear = data.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา + var endFiscalYear = data.CreatedAt; var thisYear = data.LeaveStartDate.Year; var toDay = data.LeaveStartDate.Date; @@ -333,7 +346,11 @@ namespace BMA.EHR.Leave.Service.Controllers //var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear); - var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear); + var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear); + if (leaveData != null) + { + sumLeave += leaveData.BeginningLeaveDays; + } //var sumLeave = leaveData == null ? 0.0 : leaveData.LeaveDaysUsed; var leaveLimit = leaveData == null ? 0.0 : leaveData.LeaveDays; @@ -349,7 +366,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -444,7 +461,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -498,7 +515,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -585,7 +602,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -666,7 +683,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -769,7 +786,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -888,7 +905,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -984,7 +1001,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "", dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(), @@ -1210,7 +1227,7 @@ namespace BMA.EHR.Leave.Service.Controllers data = new { leaveWrote = data.CancelLeaveWrote!.ToThaiNumber() ?? "", - dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), + dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(), leaveTypeName = data.Type.Name, fullname = fullName, position = string.IsNullOrEmpty(profile.Position) ? "-" : profile.Position, @@ -1324,7 +1341,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -1954,7 +1971,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2075,20 +2092,68 @@ namespace BMA.EHR.Leave.Service.Controllers case "LV-005": remarkStr += leaveReq.Type.Name; var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper(); - if (leaveRange == "MORNING") - remarkStr += "ครึ่งวันเช้า"; - else if (leaveRange == "AFTERNOON") - remarkStr += "ครึ่งวันบ่าย"; - - var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); - if (leaveRange != leaveRangeEnd) + if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date) { - if (leaveRangeEnd == "MORNING") - remarkStr += " - ครึ่งวันเช้า"; - else if (leaveRangeEnd == "AFTERNOON") - remarkStr += " - ครึ่งวันบ่าย"; + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + + + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRangeEnd == "MORNING") + // remarkStr += "ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += "ครึ่งวันบ่าย"; + + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRange != leaveRangeEnd) + { + if (leaveRangeEnd == "MORNING") + remarkStr += " - ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += " - ครึ่งวันบ่าย"; + } } + else + { + if(dd.date == leaveReq.LeaveStartDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else if(dd.date == leaveReq.LeaveEndDate.Date) + { + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRangeEnd == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else + { + remarkStr += "เต็มวัน"; + } + } + + + // if (leaveRange == "MORNING") + // remarkStr += "ครึ่งวันเช้า"; + // else if (leaveRange == "AFTERNOON") + // remarkStr += "ครึ่งวันบ่าย"; + + + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRange != leaveRangeEnd) + // { + // if (leaveRangeEnd == "MORNING") + // remarkStr += " - ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += " - ครึ่งวันบ่าย"; + // } break; default: remarkStr += leaveReq.Type.Name; @@ -2296,7 +2361,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2405,26 +2470,72 @@ namespace BMA.EHR.Leave.Service.Controllers case "LV-005": remarkStr += leaveReq.Type.Name; var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper(); - if (leaveRange == "MORNING") - remarkStr += "ครึ่งวันเช้า"; - else if (leaveRange == "AFTERNOON") - remarkStr += "ครึ่งวันบ่าย"; + if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; - // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); - // if (leaveRangeEnd == "MORNING") + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRangeEnd == "MORNING") + // remarkStr += "ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += "ครึ่งวันบ่าย"; + + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRange != leaveRangeEnd) + { + if (leaveRangeEnd == "MORNING") + remarkStr += " - ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += " - ครึ่งวันบ่าย"; + } + } + else + { + if(dd.date == leaveReq.LeaveStartDate.Date) + { + if (leaveRange == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRange == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else if(dd.date == leaveReq.LeaveEndDate.Date) + { + var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + if (leaveRangeEnd == "MORNING") + remarkStr += "ครึ่งวันเช้า"; + else if (leaveRangeEnd == "AFTERNOON") + remarkStr += "ครึ่งวันบ่าย"; + } + else + { + remarkStr += "เต็มวัน"; + } + } + + // if (leaveRange == "MORNING") // remarkStr += "ครึ่งวันเช้า"; - // else if (leaveRangeEnd == "AFTERNOON") + // else if (leaveRange == "AFTERNOON") // remarkStr += "ครึ่งวันบ่าย"; - var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); - if (leaveRange != leaveRangeEnd) - { - if (leaveRangeEnd == "MORNING") - remarkStr += " - ครึ่งวันเช้า"; - else if (leaveRangeEnd == "AFTERNOON") - remarkStr += " - ครึ่งวันบ่าย"; - } + + // // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // // if (leaveRangeEnd == "MORNING") + // // remarkStr += "ครึ่งวันเช้า"; + // // else if (leaveRangeEnd == "AFTERNOON") + // // remarkStr += "ครึ่งวันบ่าย"; + + // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper(); + // if (leaveRange != leaveRangeEnd) + // { + // if (leaveRangeEnd == "MORNING") + // remarkStr += " - ครึ่งวันเช้า"; + // else if (leaveRangeEnd == "AFTERNOON") + // remarkStr += " - ครึ่งวันบ่าย"; + // } break; default: remarkStr += leaveReq.Type.Name; @@ -2741,29 +2852,45 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } + var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync(); + if (getDefaultRound == null) + { + return Error("ไม่พบรอบลงเวลา Default", StatusCodes.Status404NotFound); + } var userTimeStamps = await _processUserTimeStampRepository.GetTimestampByDateLateAsync(type.Trim().ToUpper(), role, nodeId, profileAdmin.Node, req.nodeId, req.node, req.StartDate, req.EndDate); foreach (var p in userTimeStamps) { var fullName = $"{p.Prefix}{p.FirstName} {p.LastName}"; - var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id); + UserDutyTime? effectiveDate = null; + + effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.ProfileId ?? Guid.Empty); + //return Error($"{data.Id} PF{data.FirstName} {data.LastName} : {GlobalMessages.DataNotFound}", StatusCodes.Status404NotFound); + + //var userRound = await _dutyTimeRepository.GetByIdAsync(profile.DutyTimeId ?? Guid.Empty); var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty; var userRound = await _dutyTimeRepository.GetByIdAsync(roundId); - var duty = userRound; - if (duty == null) - { - duty = await _dutyTimeRepository.GetDefaultAsync(); - if (duty == null) - { - return Error("ไม่พบรอบการลงเวลา Default", StatusCodes.Status404NotFound); - } - } + var duty = userRound ?? getDefaultRound; + + // var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id); + // var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty; + // var userRound = await _dutyTimeRepository.GetByIdAsync(roundId); + + // var duty = userRound; + // if (duty == null) + // { + // duty = await _dutyTimeRepository.GetDefaultAsync(); + // if (duty == null) + // { + // return Error("ไม่พบรอบการลงเวลา Default", StatusCodes.Status404NotFound); + // } + // } DateTime? checkIn = p.CheckIn; DateTime? checkOut = p.CheckOut ?? null; var emp = new @@ -2862,13 +2989,21 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } var leaveDays = await _leaveRequestRepository.GetSumApproveLeaveByRootAndRange(req.StartDate, req.EndDate, type, jsonData["result"]?.ToString(), nodeId, profileAdmin?.Node, req.nodeId, req.node); var enddate = req.EndDate.Date == req.StartDate.Date ? "" : $" - {req.EndDate.Date.ToThaiShortDate().ToThaiNumber()}"; + + // var thisYear = req.StartDate.Year; + // var toDay = req.StartDate.Date; + // if (toDay >= new DateTime(toDay.Year, 10, 1) && toDay <= new DateTime(toDay.Year, 12, 31)) + // thisYear = thisYear + 1; + + // var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, type, data.KeycloakUserId); + var result = new { template = "leave2", diff --git a/BMA.EHR.Leave/Controllers/LeaveRequestController.cs b/BMA.EHR.Leave/Controllers/LeaveRequestController.cs index 1a00d285..daa2c07c 100644 --- a/BMA.EHR.Leave/Controllers/LeaveRequestController.cs +++ b/BMA.EHR.Leave/Controllers/LeaveRequestController.cs @@ -17,6 +17,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using NodaTime; using Org.BouncyCastle.Asn1.Pkcs; using Sentry; using Swashbuckle.AspNetCore.Annotations; @@ -213,7 +214,7 @@ namespace BMA.EHR.Leave.Service.Controllers var thisYear = DateTime.Now.Year; // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { @@ -501,7 +502,7 @@ namespace BMA.EHR.Leave.Service.Controllers foreach (var leave in leaves) { // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(leave.KeycloakUserId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(leave.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(leave.KeycloakUserId, AccessToken); if (profile != null) { leave.Prefix = profile.Prefix; @@ -562,7 +563,7 @@ namespace BMA.EHR.Leave.Service.Controllers // } // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (profile == null) { @@ -854,10 +855,10 @@ namespace BMA.EHR.Leave.Service.Controllers { var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); - var thisYear = DateTime.Now.Year; + var thisYear = DateTime.Now.Year - 1; var toDay = DateTime.Now.Date; - var startFiscalDate = new DateTime(DateTime.Now.Year, 10, 1); - var endFiscalDate = new DateTime(DateTime.Now.Year + 1, 9, 30); + var startFiscalDate = new DateTime(DateTime.Now.Year - 1, 10, 1); + var endFiscalDate = new DateTime(DateTime.Now.Year, 9, 30); if (toDay >= startFiscalDate && toDay <= endFiscalDate) thisYear = thisYear + 1; @@ -897,12 +898,12 @@ namespace BMA.EHR.Leave.Service.Controllers if (leaveType.Code.Trim().ToUpper() == "LV-005") { - if (govAge < 180) - leaveLimit = 0; - else + // if (profile.IsProbation! == true) + // leaveLimit = 0; + // else { leaveLimit = leaveData == null ? - govAge < 180 ? 0 : 10 + 10 : leaveData.LeaveDays; } } @@ -911,11 +912,11 @@ namespace BMA.EHR.Leave.Service.Controllers var restOldDay = leaveData == null ? 0 : leaveData.LeaveDays - 10; var restCurrentDay = 10.0; - if (govAge < 180) - { - restOldDay = 0; - restCurrentDay = 0; - } + // if (profile.IsProbation! == true) + // { + // restOldDay = 0; + // restCurrentDay = 0; + // } if(restOldDay < 0) restOldDay = 0; var sumLeave = leaveData == null ? 0 : leaveData.LeaveDaysUsed; @@ -924,6 +925,9 @@ namespace BMA.EHR.Leave.Service.Controllers var leaveLast = await _leaveRequestRepository.GetLeaveLastByTypeForUserAsync(userId, req.Type); + var leaveDraftSummary = await _leaveRequestRepository.GetSumDraftLeaveTotalByTypeAndRangeForUser2(userId, req.Type, startFiscalDate, endFiscalDate); + var leaveWaitingSummary = await _leaveRequestRepository.GetSumNewLeaveTotalByTypeAndRangeForUser2(userId, req.Type, startFiscalDate, endFiscalDate); + var result = new GetUserLeaveProfileResultDto { DateSendLeave = DateTime.Now.Date, @@ -959,12 +963,56 @@ namespace BMA.EHR.Leave.Service.Controllers CurrentDistrict = profile.CurrentDistrict ?? "", CurrentProvince = profile.CurrentProvince ?? "", CurrentZipCode = profile.CurrentZipCode ?? "", - GovAge = govAge + GovAge = govAge, + + LeaveDraftSummary = leaveDraftSummary, + LeaveWaitingSummary = leaveWaitingSummary }; return Success(result); } + [HttpGet("time-check")] + [AllowAnonymous] + public async Task> TimeCheckAsync() + { + var startDate = new DateTime(2017, 1, 6); + var govAge = (startDate).DiffDay(DateTime.Now.Date); + var date1Raw = startDate; + var date1 = new LocalDate(date1Raw.Year, date1Raw.Month, date1Raw.Day); + var date2 = new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); + + + var (govAgeYear, govAgeMonth, govAgeDay) = startDate.GetDifference(DateTime.Now.Date); + + var isLeave = false; + var message = string.Empty; + + if (govAgeYear >= 1 || (govAgeYear == 0 && govAgeMonth >= 6)) + { + isLeave = true; + if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด"; + } + else + { + isLeave = false; + if (!isLeave) message = "อายุราชการน้อยกว่า 6 เดือนหรือ 180 วัน"; + } + + return Success(new + { + GovAge = govAge, + GovAgeDay = govAgeDay, + GovAgeMonth = govAgeMonth, + GovAgeYear = govAgeYear, + IsLeave = isLeave, + Message = message + + + + }); + } + /// /// LV2_003 - เช็คการยืนขอลา (USER) /// @@ -984,8 +1032,18 @@ namespace BMA.EHR.Leave.Service.Controllers var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); var govAge = (profile?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date); + var startDate = profile?.DateStart?.Date ?? DateTime.Now.Date; + // var date1Raw = profile?.DateStart?.Date ?? DateTime.Now.Date; + // var date1 = new LocalDate(date1Raw.Year, date1Raw.Month, date1Raw.Day); + // var date2 = new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); + // Period period = Period.Between(date1, date2); + // var govAgeMonth = period.Months; + // var govAgeYear = period.Years; + + var (govAgeYear, govAgeMonth, govAgeDay) = startDate.GetDifference(DateTime.Now.Date); + var thisYear = DateTime.Now.Year; var message = string.Empty; @@ -1018,26 +1076,38 @@ namespace BMA.EHR.Leave.Service.Controllers fiscalYear = req.StartLeaveDate.Year + 1; var sumLeaveDay = await _leaveBeginningRepository.GetByYearAndTypeIdForUserAsync(fiscalYear, req.Type, userId); - - - var minLeave = (await _context.Set().Where(x => x.Type.Id == req.Type && - (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") && - x.KeycloakUserId == userId) - .OrderBy(x => x.LeaveStartDate) - .FirstOrDefaultAsync()); - - var maxLeave = (await _context.Set().Where(x => x.Type.Id == req.Type && - (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") && - x.KeycloakUserId == userId) - .OrderByDescending(x => x.LeaveEndDate) - .FirstOrDefaultAsync()); - var isBetween = false; - if (minLeave != null && maxLeave != null) - { - isBetween = (req.StartLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date) || - (req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.EndLeaveDate.Date <= maxLeave.LeaveEndDate.Date); - } + var existingLeaves = await _context.Set() + .Where(x => x.Type.Id == req.Type && + (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") && + x.KeycloakUserId == userId) + .ToListAsync(); + + isBetween = existingLeaves.Any(leave => + req.StartLeaveDate.Date <= leave.LeaveEndDate.Date && + req.EndLeaveDate.Date >= leave.LeaveStartDate.Date); + + // var minLeave = (await _context.Set().Where(x => x.Type.Id == req.Type && + // (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") && + // x.KeycloakUserId == userId) + // .OrderBy(x => x.LeaveStartDate) + // .FirstOrDefaultAsync()); + + // var maxLeave = (await _context.Set().Where(x => x.Type.Id == req.Type && + // (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") && + // x.KeycloakUserId == userId) + // .OrderByDescending(x => x.LeaveEndDate) + // .FirstOrDefaultAsync()); + + // var isBetween = false; + // if (minLeave != null && maxLeave != null) + // { + // // isBetween = (req.StartLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date) || + // // (req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.EndLeaveDate.Date <= maxLeave.LeaveEndDate.Date); + // isBetween = req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date && + // req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date; + + // } var isLeave = false; var approveDay = sumLeaveDay == null ? 0.0 : sumLeaveDay.LeaveDaysUsed; @@ -1055,12 +1125,11 @@ namespace BMA.EHR.Leave.Service.Controllers case "LV-002": // fix issue : ระบบลา (ขรก.) >> ลากิจส่วนตัว (กรณียื่นขอลาเกิน 45 วัน/ปี) #829 // fix issue : ระบบลา (ขรก.) >> ลากิจส่วนตัว (กรณีผู้เข้ารับราชการไม่เกิน 1 ปี ยื่นขอลาเกิน 15 วัน/ปี) #831 - if (govAge <= 365) + if (govAgeYear <= 1) { isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= 15; if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด"; } - else { isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= 45; @@ -1082,36 +1151,11 @@ namespace BMA.EHR.Leave.Service.Controllers break; case "LV-005": // fix issue : ระบบลา (ขรก.) >> ลาพักผ่อน (กรณีรับราชการไม่ถึง 6 เดือน) #838 - //var leavePrevYear = (await _leaveRequestRepository.GetSumApproveLeaveAsync(fiscalYear - 1)).Where(x => x.LeaveTypeCode == "LV-005" && x.KeycloakUserId == userId).FirstOrDefault(); - //var leavePrevYearRemain = 10 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน - if (profile.IsProbatin! == true) - { - isLeave = false; - if (!isLeave) message = "ยังอยู่ในช่วงทดลองปฏิบัติราชการ ไม่สามารถลาพักผ่อนได้"; - } - else if (govAge >= 180) + if (govAgeYear >= 1 || (govAgeYear == 0 && govAgeMonth >= 6)) { isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= (limitDay); if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด"; } - // else if (govAge >= 3650) - // { - // // ถ้าอายุราชการเกิน 10 ปี ได้บวกเพิ่มอีก 10 วัน - // var leavePrevYearRemain = 30 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน - // if (leavePrevYearRemain >= 20) leavePrevYearRemain = 20; - - // isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= (limitDay); - // if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด"; - // } - // else if - // { - // //var leavePrevYearRemain = 20 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน - // //if (leavePrevYearRemain >= 10) leavePrevYearRemain = 10; - - // isLeave = (totalDay - (sumWorkDay + sumWeekend) + sumApproveLeave) <= (10 + leavePrevYearRemain); - // if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด"; - // } - else { isLeave = false; @@ -1121,7 +1165,7 @@ namespace BMA.EHR.Leave.Service.Controllers break; case "LV-006": // fix issue : ระบบลา(ขรก.) >> ลาอุปสมบทหรือการลาประกอบพิธีฮัจย์ฯ(กรณีรับราชการน้อยกว่า 1 ปี) #840 - if (govAge < 365) + if (govAgeYear < 1) { isLeave = false; if (!isLeave) message = "อายุราชการน้อยกว่า 1 ปีหรือ 365 วัน"; @@ -1147,7 +1191,7 @@ namespace BMA.EHR.Leave.Service.Controllers break; case "LV-008": case "LV-009": - isLeave = govAge >= 365; + isLeave = govAgeYear >= 1; if (!isLeave) message = "อายุราชการน้อยกว่า 1 ปีหรือ 365 วัน"; break; case "LV-010": @@ -1286,7 +1330,7 @@ namespace BMA.EHR.Leave.Service.Controllers Id = d.Id, LeaveTypeId = d.Type.Id, LeaveTypeName = d.Type.Name, - DateSendLeave = d.CreatedAt.Date, + DateSendLeave = d.DateSendLeave != null ? d.DateSendLeave.Value.Date : d.CreatedAt.Date, Status = d.LeaveStatus, FullName = $"{d.Prefix}{d.FirstName} {d.LastName}", LeaveEndDate = d.LeaveEndDate, @@ -1314,14 +1358,14 @@ namespace BMA.EHR.Leave.Service.Controllers public async Task> GetLeaveRequestCalendarAdminAsync( [FromBody] GetLeaveRequestCalendarDto req) { - var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST"); - var jsonData = JsonConvert.DeserializeObject(getPermission); - if (jsonData["status"]?.ToString() != "200") + var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST"); + //var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData!.status != 200) { - return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + return Error(jsonData.message, StatusCodes.Status403Forbidden); } - - string role = jsonData["result"]?.ToString(); + //string role = jsonData["result"]?.ToString(); + string role = jsonData.result.privilege; var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); @@ -1351,12 +1395,93 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } var data = await _leaveRequestRepository.GetLeaveRequestByYearForAdminAsync(req.Year, role, nodeId, profileAdmin.Node); + + // ถ้ามีการรักษาการ + if (jsonData.result.isAct) + { + var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY"); + foreach(var act in posActs) + { + var actRole = act.privilege; + string actNodeId = string.Empty; + int? actNode = null; + + if (actRole == "NORMAL" || actRole == "CHILD") + { + actNodeId = act.child4DnaId != null ? + act.child4DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child1DnaId != null ? + act.child1DnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "BROTHER") + { + actNodeId = act.child4DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child1DnaId!.Value.ToString("D") : + act.child1DnaId != null ? + act.rootDnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "ROOT" /*|| role == "PARENT"*/) + { + actNodeId = act.rootDnaId!.Value.ToString("D"); + actNode = 0; + } + + var rawDataAct = await _leaveRequestRepository.GetLeaveRequestByYearForAdminAsync(req.Year, actRole, actNodeId, actNode); + if (rawDataAct != null) + { + if (data != null) + data = data.Union(rawDataAct).DistinctBy(x => x.Id).ToList(); + else + data = rawDataAct; + } + } + } + + + + var resultData = (from d in data //join p in profileList on d.KeycloakUserId equals p.Keycloak select new GetLeaveRequestCalendarResultDto @@ -1364,7 +1489,7 @@ namespace BMA.EHR.Leave.Service.Controllers Id = d.Id, LeaveTypeId = d.Type.Id, LeaveTypeName = d.Type.Name, - DateSendLeave = d.CreatedAt.Date, + DateSendLeave = d.DateSendLeave != null ? d.DateSendLeave.Value.Date : d.CreatedAt.Date, Status = d.LeaveStatus, FullName = $"{d.Prefix}{d.FirstName} {d.LastName}", LeaveEndDate = d.LeaveEndDate, @@ -1417,7 +1542,7 @@ namespace BMA.EHR.Leave.Service.Controllers LeaveTypeName = item.Type.Name, LeaveSubTypeName = item.LeaveSubTypeName ?? "", FullName = $"{item.Prefix}{item.FirstName} {item.LastName}", - DateSendLeave = item.CreatedAt, + DateSendLeave = item.DateSendLeave ?? item.CreatedAt, IsDelete = item.LeaveStatus == "DELETE", Status = item.LeaveStatus, LeaveStartDate = item.LeaveStartDate, @@ -1539,7 +1664,7 @@ namespace BMA.EHR.Leave.Service.Controllers } // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken); if (profile == null) { @@ -1578,7 +1703,8 @@ namespace BMA.EHR.Leave.Service.Controllers var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUserAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId); - var restDayOld = govAge < 180 ? 0 : leaveData == null ? 0 : leaveData.LeaveDays - 10; + var restDayOld = govAge < 180 ? 0 : leaveData == null ? 0 : (leaveData.LeaveDays + leaveData.BeginningLeaveDays - 10); + if (restDayOld < 0) restDayOld = 0; var restDayCurrent = govAge < 180 ? 0 : 10; @@ -1591,7 +1717,7 @@ namespace BMA.EHR.Leave.Service.Controllers LeaveSubTypeName = rawData.LeaveSubTypeName, LeaveTypeId = rawData.Type.Id, FullName = $"{rawData.Prefix}{rawData.FirstName} {rawData.LastName}", - DateSendLeave = rawData.CreatedAt, + DateSendLeave = rawData.DateSendLeave ?? rawData.CreatedAt, Status = rawData.LeaveStatus, LeaveStartDate = rawData.LeaveStartDate, LeaveEndDate = rawData.LeaveEndDate, @@ -1711,14 +1837,14 @@ namespace BMA.EHR.Leave.Service.Controllers public async Task> GetLeaveRequestForAdminAsync( [FromBody] GetLeaveRequestForAdminDto req) { - var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST"); - var jsonData = JsonConvert.DeserializeObject(getPermission); - if (jsonData["status"]?.ToString() != "200") + var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST"); + //var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData!.status != 200) { - return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + return Error(jsonData.message, StatusCodes.Status403Forbidden); } - - string role = jsonData["result"]?.ToString(); + //string role = jsonData["result"]?.ToString(); + string role = jsonData.result.privilege; var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); @@ -1748,13 +1874,92 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } var rawData = await _leaveRequestRepository.GetListLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, req.StartDate, req.EndDate, role, nodeId, profileAdmin?.Node); + + // ถ้ามีการรักษาการ + if (jsonData.result.isAct) + { + var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY"); + foreach(var act in posActs) + { + var actRole = act.privilege; + string actNodeId = string.Empty; + int? actNode = null; + + if (actRole == "NORMAL" || actRole == "CHILD") + { + actNodeId = act.child4DnaId != null ? + act.child4DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child1DnaId != null ? + act.child1DnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "BROTHER") + { + actNodeId = act.child4DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child1DnaId!.Value.ToString("D") : + act.child1DnaId != null ? + act.rootDnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "ROOT" /*|| role == "PARENT"*/) + { + actNodeId = act.rootDnaId!.Value.ToString("D"); + actNode = 0; + } + + var rawDataAct = await _leaveRequestRepository.GetListLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, req.StartDate, req.EndDate, actRole, actNodeId, actNode); + if (rawDataAct != null) + { + if (rawData != null) + rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList(); + else + rawData = rawDataAct; + } + } + } + + var result = new List(); foreach (var item in rawData) @@ -1787,7 +1992,7 @@ namespace BMA.EHR.Leave.Service.Controllers LeaveSubTypeName = item.LeaveSubTypeName, FullName = $"{item.Prefix}{item.FirstName} {item.LastName}", ProfileType = item.ProfileType ?? "-", - DateSendLeave = item.CreatedAt, + DateSendLeave = item.DateSendLeave ?? item.CreatedAt, Status = item.LeaveStatus, CitizenId = item.CitizenId ?? "", LeaveStartDate = item.LeaveStartDate, @@ -1837,6 +2042,12 @@ namespace BMA.EHR.Leave.Service.Controllers return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); } + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken); + if (profile == null) + { + return Error(GlobalMessages.ProfileNotFound, StatusCodes.Status404NotFound); + } + // change status to delete // แก้จาก DELETE เป็น DELETING ไว้ก่อน รอ approve ค่อยเปลี่ยนเป็น DELETE // data.LeaveStatus = "DELETE"; @@ -1873,7 +2084,7 @@ namespace BMA.EHR.Leave.Service.Controllers // TODO: Send notification to all users who need to approve the cancel leave request var approvers = data.Approvers - .Where(x => x.ApproveStatus!.ToUpper() == "PENDING") + //.Where(x => x.ApproveStatus!.ToUpper() == "PENDING") .OrderBy(x => x.Seq) .ToList(); @@ -1885,11 +2096,33 @@ namespace BMA.EHR.Leave.Service.Controllers Body = $"คำร้องขอยกเลิกการลาของคุณ {data.FirstName} {data.LastName} รอรับการอนุมัติจากคุณ", ReceiverUserId = approver!.ProfileId, Type = "", - Payload = $"{URL}/leave/detail/{id}", + Payload = $"{URL}/leave-reject/detail/{id}", }; _appDbContext.Set().Add(noti1); } + // Get Officer List + var officers = await _userProfileRepository.GetOCStaffAsync(profile.Id, AccessToken); + var approverProfileIdList = approvers.Select(x => x.ProfileId).ToList(); + + if(officers != null && officers.Count > 0) + { + officers = officers.Where(x => !approverProfileIdList.Contains(x.ProfileId)).ToList(); + foreach (var officer in officers) + { + // Send Notification + var noti = new Notification + { + Body = $"คำร้องขอยกเลิกการลาของคุณ {data.FirstName} {data.LastName} รอรับการอนุมัติจากคุณ", + ReceiverUserId = officer.ProfileId, + Type = "", + Payload = $"{URL}/leave-reject/detail/{id}", + }; + _appDbContext.Set().Add(noti); + } + await _appDbContext.SaveChangesAsync(); + } + return Success(); } @@ -1909,14 +2142,14 @@ namespace BMA.EHR.Leave.Service.Controllers public async Task> GetCancelLeaveRequestForAdminAsync( [FromBody] GetLeaveRequestForAdminDto req) { - var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST"); - var jsonData = JsonConvert.DeserializeObject(getPermission); - if (jsonData["status"]?.ToString() != "200") + var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST"); + //var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData!.status != 200) { - return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + return Error(jsonData.message, StatusCodes.Status403Forbidden); } - - string role = jsonData["result"]?.ToString(); + //string role = jsonData["result"]?.ToString(); + string role = jsonData.result.privilege; var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); @@ -1946,7 +2179,7 @@ namespace BMA.EHR.Leave.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -1954,6 +2187,84 @@ namespace BMA.EHR.Leave.Service.Controllers var rawData = await _leaveRequestRepository.GetCancelLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, role, nodeId, profileAdmin?.Node); + // ถ้ามีการรักษาการ + if (jsonData.result.isAct) + { + var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY"); + foreach(var act in posActs) + { + var actRole = act.privilege; + string actNodeId = string.Empty; + int? actNode = null; + + if (actRole == "NORMAL" || actRole == "CHILD") + { + actNodeId = act.child4DnaId != null ? + act.child4DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child1DnaId != null ? + act.child1DnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "BROTHER") + { + actNodeId = act.child4DnaId != null ? + act.child3DnaId.Value.ToString("D") : + act.child3DnaId != null ? + act.child2DnaId.Value.ToString("D") : + act.child2DnaId != null ? + act.child1DnaId!.Value.ToString("D") : + act.child1DnaId != null ? + act.rootDnaId.Value.ToString("D") : + act.rootDnaId != null ? + act.rootDnaId.Value.ToString("D") : + ""; + actNode = act.child4DnaId != null ? + 4 : + act.child3DnaId != null ? + 3 : + act.child2DnaId != null ? + 2 : + act.child1DnaId != null ? + 1 : + act.rootDnaId != null ? + 0 : + null; + } + else if (actRole == "ROOT" /*|| role == "PARENT"*/) + { + actNodeId = act.rootDnaId!.Value.ToString("D"); + actNode = 0; + } + + var rawDataAct = await _leaveRequestRepository.GetCancelLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, actRole, actNodeId, actNode); + if (rawDataAct != null) + { + if (rawData != null) + rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList(); + else + rawData = rawDataAct; + } + } + } + + var recCount = rawData.Count; if (req.Keyword != "") @@ -1976,7 +2287,7 @@ namespace BMA.EHR.Leave.Service.Controllers LeaveSubTypeName = item.LeaveSubTypeName, ProfileType = item.ProfileType ?? "-", FullName = $"{item.Prefix}{item.FirstName} {item.LastName}", - DateSendLeave = item.CreatedAt.Date, + DateSendLeave = item.DateSendLeave != null ? item.DateSendLeave.Value.Date : item.CreatedAt.Date, Status = item.LeaveCancelStatus ?? "" }; result.Add(res); @@ -2073,7 +2384,7 @@ namespace BMA.EHR.Leave.Service.Controllers } // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(Guid.Parse(UserId!), AccessToken); - var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(Guid.Parse(UserId!), AccessToken); + var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(Guid.Parse(UserId!), AccessToken); if (profile == null) { @@ -2321,12 +2632,31 @@ namespace BMA.EHR.Leave.Service.Controllers await _leaveRequestRepository.SendToOfficerAsync(id); // Remove Workflow Integration - // var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); - // var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - // if (profile == null) - // { - // return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); - // } + var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); + var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); + if (profile == null) + { + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + } + + // Get Officer List + var officers = await _userProfileRepository.GetOCStaffAsync(profile.Id, AccessToken); + if(officers != null && officers.Count > 0) + { + foreach (var officer in officers) + { + // Send Notification + var noti = new Notification + { + Body = $"มีคำร้องขอลาจาก {profile.Prefix}{profile.FirstName} {profile.LastName} รอรับการอนุมัติจากคุณ", + ReceiverUserId = officer.ProfileId, + Type = "", + Payload = $"{URL}/leave/detail/{id}", + }; + _appDbContext.Set().Add(noti); + } + await _appDbContext.SaveChangesAsync(); + } // var baseAPIOrg = _configuration["API"]; // var apiUrlOrg = $"{baseAPIOrg}/org/workflow/add-workflow"; // if (profile.ProfileType == "OFFICER") @@ -2469,8 +2799,8 @@ namespace BMA.EHR.Leave.Service.Controllers //var lastSalaryAmount = lastSalary == null ? 0 : lastSalary.Amount ?? 0; var lastLeaveRequest = - await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync(rawData.KeycloakUserId, - rawData.Type.Id, rawData.LeaveStartDate.Date); + await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync2(rawData.KeycloakUserId, + rawData.Type.Id, rawData.CreatedAt); //var rootOc = _userProfileRepository.GetRootOcId(profile.OcId ?? Guid.Empty, AccessToken); //var approver = string.Empty; @@ -2505,9 +2835,17 @@ namespace BMA.EHR.Leave.Service.Controllers var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, rawData.Type.Id, rawData.KeycloakUserId); var startFiscalYear = new DateTime(rawData.LeaveStartDate.Year - 1, 10, 1); - var endFiscalYear = rawData.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา - var leaveSummary = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear); + var endFiscalYear = rawData.CreatedAt; + var endFiscalYear2 = new DateTime(rawData.LeaveStartDate.Year, 9, 30); + var leaveSummary = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear); + + // วันลาแบบร่างและที่ยื่นลาไปแล้ว + var leaveDraftSummary = await _leaveRequestRepository.GetSumDraftLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear2); + var leaveWaitingSummary = await _leaveRequestRepository.GetSumNewLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear2); + //var leaveSummary = leaveData == null ? 0.0 : leaveData.LeaveDaysUsed; + if (leaveData != null) + leaveSummary += leaveData.BeginningLeaveDays; var extendLeave = 0.0; var leaveLimit = (double)rawData.Type.Limit; @@ -2515,7 +2853,7 @@ namespace BMA.EHR.Leave.Service.Controllers if (rawData.Type.Code == "LV-005") { leaveLimit = leaveData == null ? 0.0 : leaveData.LeaveDays; - extendLeave = leaveLimit - 10; + extendLeave = leaveLimit <= 0 ? 0 : leaveLimit - 10; } var result = new GetLeaveRequestForAdminByIdDto @@ -2528,7 +2866,7 @@ namespace BMA.EHR.Leave.Service.Controllers LeaveSubTypeName = rawData.LeaveSubTypeName, LeaveTypeId = rawData.Type.Id, FullName = $"{rawData.Prefix}{rawData.FirstName} {rawData.LastName}", - DateSendLeave = rawData.CreatedAt, + DateSendLeave = rawData.DateSendLeave ?? rawData.CreatedAt, Status = rawData.LeaveStatus, LeaveStartDate = rawData.LeaveStartDate, LeaveEndDate = rawData.LeaveEndDate, @@ -2614,13 +2952,14 @@ namespace BMA.EHR.Leave.Service.Controllers //OrganizationName = rawData.OrganizationName ?? "", // fix SIT ระบบบันทึกการลา>>รายการลา (ข้อมูลผู้สังกัดและเรียนไม่แสดง) #971 - - ApproveStep = rawData.ApproveStep ?? "-", LeaveLimit = rawData.Type.Limit + extendLeave, LeaveSummary = leaveSummary, - LeaveRemain = (rawData.Type.Limit + extendLeave) - leaveSummary + LeaveRemain = (rawData.Type.Limit + extendLeave) - leaveSummary, + + LeaveDraftSummary = leaveDraftSummary, + LeaveWaitingSummary = leaveWaitingSummary }; if (rawData.LeaveDocument != null && rawData.LeaveDocument.Count > 0) @@ -2699,7 +3038,7 @@ namespace BMA.EHR.Leave.Service.Controllers var rejectList = await _leaveRequestRepository.GetSumRejectLeaveAsync(thisYear); var deleteList = await _leaveRequestRepository.GetSumDeleteLeaveAsync(thisYear); // var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); - var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken); + var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken); if (pf == null) { @@ -2741,7 +3080,7 @@ namespace BMA.EHR.Leave.Service.Controllers if (leaveType.Code == "LV-005") { leaveLimit = leaveData?.LeaveDays ?? 0.0; - extendLeave = leaveLimit - 10; + extendLeave = leaveLimit <= 0 ? 0 : leaveLimit - 10; } var data = new diff --git a/BMA.EHR.Leave/DTOs/ChangeRound/CreateChangeRoundDto.cs b/BMA.EHR.Leave/DTOs/ChangeRound/CreateChangeRoundDto.cs index 6ad96fcd..5379abda 100644 --- a/BMA.EHR.Leave/DTOs/ChangeRound/CreateChangeRoundDto.cs +++ b/BMA.EHR.Leave/DTOs/ChangeRound/CreateChangeRoundDto.cs @@ -12,4 +12,25 @@ namespace BMA.EHR.Leave.Service.DTOs.ChangeRound public string Remark { get; set; } } + + public class CreateChangeRoundMultipleDto + { + public Guid ProfileId { get; set; } + + public Guid RoundId { get; set; } + + public DateTime EffectiveDate { get; set; } + + public string Remark { get; set; } + + public Guid? RootDnaId { get; set; } + public Guid? Child1DnaId { get; set; } + public Guid? Child2DnaId { get; set; } + public Guid? Child3DnaId { get; set; } + public Guid? Child4DnaId { get; set; } + + public string? Prefix { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + } } diff --git a/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileDto.cs b/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileDto.cs index 3b05ad29..69f5cbba 100644 --- a/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileDto.cs +++ b/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileDto.cs @@ -17,5 +17,9 @@ public string? sortBy { get; set; } public bool? descending { get; set; } + + public Guid? SelectedNodeId { get; set; } + + public int? SelectedNode { get; set; } } } diff --git a/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileResultDto.cs b/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileResultDto.cs index 83b4d7b9..00df91a9 100644 --- a/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileResultDto.cs +++ b/BMA.EHR.Leave/DTOs/ChangeRound/SearchProfileResultDto.cs @@ -17,5 +17,11 @@ public string LeaveTimeAfterNoon { get;set; } public DateTime? EffectiveDate { get; set; } + + public string? RootDnaId { get; set; } + public string? Child1DnaId { get; set; } + public string? Child2DnaId { get; set; } + public string? Child3DnaId { get; set; } + public string? Child4DnaId { get; set; } } } diff --git a/BMA.EHR.Leave/DTOs/LeaveBeginnings/CreateLeaveBeginningDto.cs b/BMA.EHR.Leave/DTOs/LeaveBeginnings/CreateLeaveBeginningDto.cs index 79d33052..423385ed 100644 --- a/BMA.EHR.Leave/DTOs/LeaveBeginnings/CreateLeaveBeginningDto.cs +++ b/BMA.EHR.Leave/DTOs/LeaveBeginnings/CreateLeaveBeginningDto.cs @@ -14,10 +14,19 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveBeginnings [Required, Comment("ปีงบประมาณ")] public int LeaveYear { get; set; } = 0; - [Required, Comment("จำนวนวันลายกมา")] + [Required, Comment("จำนวนวันลาที่ได้รับ")] public double LeaveDays { get; set; } = 0.0; [Required, Comment("จำนวนวันลาที่ใช้ไป")] public double LeaveDaysUsed { get; set; } = 0.0; + + [Required, Comment("จำนวนครั้งที่ลาสะสม")] + public int LeaveCount { get; set; } = 0; + + [Required, Comment("จำนวนวันลายกมา")] + public double BeginningLeaveDays { get; set; } = 0.0; + + [Comment("จำนวนครั้งที่ลายกมา")] + public int BeginningLeaveCount { get; set; } = 0; } } diff --git a/BMA.EHR.Leave/DTOs/LeaveBeginnings/EditLeaveBeginningDto.cs b/BMA.EHR.Leave/DTOs/LeaveBeginnings/EditLeaveBeginningDto.cs index a73bdfd4..524072ec 100644 --- a/BMA.EHR.Leave/DTOs/LeaveBeginnings/EditLeaveBeginningDto.cs +++ b/BMA.EHR.Leave/DTOs/LeaveBeginnings/EditLeaveBeginningDto.cs @@ -22,5 +22,42 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveBeginnings [Required, Comment("จำนวนครั้งที่ลาสะสม")] public int LeaveCount { get; set; } = 0; + + [Required, Comment("จำนวนวันลายกมา")] + public double BeginningLeaveDays { get; set; } = 0.0; + + [Comment("จำนวนครั้งที่ลายกมา")] + public int BeginningLeaveCount { get; set; } = 0; + } + + + public class ScheduleEditLeaveBeginningDto + { + [Required] + public Guid ProfileId { get; set; } = Guid.Empty; + + [Required] + public Guid LeaveTypeId { get; set; } = Guid.Empty; + + [Required, Comment("ปีงบประมาณ")] + public int LeaveYear { get; set; } = 0; + + [Required, Comment("จำนวนวันลายกมา")] + public double LeaveDays { get; set; } = 0.0; + } + + public class ScheduleUpdateDnaDto + { + [Required] + public Guid ProfileId { get; set; } = Guid.Empty; + + // [Required, Comment("ปีงบประมาณ")] + // public int LeaveYear { get; set; } = 0; + + public Guid? RootDnaId { get; set; } + public Guid? Child1DnaId { get; set; } + public Guid? Child2DnaId { get; set; } + public Guid? Child3DnaId { get; set; } + public Guid? Child4DnaId { get; set; } } } diff --git a/BMA.EHR.Leave/DTOs/LeaveRequest/CreateLeaveProcessJobDto.cs b/BMA.EHR.Leave/DTOs/LeaveRequest/CreateLeaveProcessJobDto.cs new file mode 100644 index 00000000..ae4aacc4 --- /dev/null +++ b/BMA.EHR.Leave/DTOs/LeaveRequest/CreateLeaveProcessJobDto.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest +{ + /// + /// ข้อมูลสำหรับสร้าง Job ประมวลผลวันลา โดยมีช่วงวันที่เริ่มต้นและสิ้นสุดของการประมวลผลวันลา + /// + public class CreateLeaveProcessJobDto + { + /// + /// วันที่เริ่มต้นของการประมวลผลวันลา + /// + public DateTime StartDate { get; set; } + + /// + /// วันที่สิ้นสุดของการประมวลผลวันลา + /// + public DateTime EndDate { get; set; } + } +} \ No newline at end of file diff --git a/BMA.EHR.Leave/DTOs/LeaveRequest/GetLeaveRequestForAdminByIdDto.cs b/BMA.EHR.Leave/DTOs/LeaveRequest/GetLeaveRequestForAdminByIdDto.cs index 88dfe7da..e9bae1bd 100644 --- a/BMA.EHR.Leave/DTOs/LeaveRequest/GetLeaveRequestForAdminByIdDto.cs +++ b/BMA.EHR.Leave/DTOs/LeaveRequest/GetLeaveRequestForAdminByIdDto.cs @@ -147,6 +147,10 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest public List Approvers { get; set; } = new(); public Guid? KeycloakUserId { get; set; } = Guid.Empty; + + + public double LeaveDraftSummary { get; set; } = 0; + public double LeaveWaitingSummary { get; set; } = 0; } public class GetLeaveApproverDto diff --git a/BMA.EHR.Leave/DTOs/LeaveRequest/GetUserLeaveProfileResultDto.cs b/BMA.EHR.Leave/DTOs/LeaveRequest/GetUserLeaveProfileResultDto.cs index e64b5ac3..a59eab85 100644 --- a/BMA.EHR.Leave/DTOs/LeaveRequest/GetUserLeaveProfileResultDto.cs +++ b/BMA.EHR.Leave/DTOs/LeaveRequest/GetUserLeaveProfileResultDto.cs @@ -53,5 +53,8 @@ public string? CurrentZipCode { get; set; } public int GovAge { get; set; } = 0; + + public double LeaveDraftSummary { get; set; } = 0; + public double LeaveWaitingSummary { get; set; } = 0; } } diff --git a/BMA.EHR.Leave/Program.cs b/BMA.EHR.Leave/Program.cs index e25a59fe..c4774831 100644 --- a/BMA.EHR.Leave/Program.cs +++ b/BMA.EHR.Leave/Program.cs @@ -119,7 +119,7 @@ builder.Services.AddHealthChecks(); builder.Services.AddRabbitMqConnectionPooling(builder.Configuration); // Add Hangfire services. -var defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection"); +var hangfireConnection = builder.Configuration.GetConnectionString("defaultConnection"); builder.Services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) @@ -127,19 +127,24 @@ builder.Services.AddHangfire(configuration => configuration .UseRecommendedSerializerSettings() .UseStorage( new MySqlStorage( - defaultConnection, + hangfireConnection, new MySqlStorageOptions { - TransactionIsolationLevel = IsolationLevel.ReadCommitted, QueuePollInterval = TimeSpan.FromSeconds(15), JobExpirationCheckInterval = TimeSpan.FromHours(1), CountersAggregateInterval = TimeSpan.FromMinutes(5), PrepareSchemaIfNecessary = true, DashboardJobListLimit = 50000, TransactionTimeout = TimeSpan.FromMinutes(1), - TablesPrefix = "Hangfire" + InvisibilityTimeout = TimeSpan.FromHours(3), + TablesPrefix = "Hangfire_Leave" }))); -builder.Services.AddHangfireServer(); +builder.Services.AddHangfireServer(options => + { + options.ServerName = "Leave-Server"; // ← ระบุชื่อ server + options.WorkerCount = 5; // ← + options.Queues = new[] { "leave","default" }; // ← worker จะรันเฉพาะ queue "leave" + }); var app = builder.Build(); @@ -190,6 +195,13 @@ if (manager != null) manager.AddOrUpdate("ปรับปรุงรอบการลงเวลาทำงาน", Job.FromExpression(x => x.UpdateUserDutyTime()), "0 1 * * *", bangkokTimeZone); // ทำความสะอาดข้อมูล CheckIn Job Status ที่เก่ากว่า 30 วัน - รันทุกวันเวลา 02:00 น. manager.AddOrUpdate("ทำความสะอาดข้อมูล CheckIn Job Status", Job.FromExpression(x => x.CleanupOldJobsAsync(30)), "0 2 * * *", bangkokTimeZone); + + manager.AddOrUpdate("ประมวลผลงานที่ค้างอยู่ในสถานะ Pending หรือ Processing", Job.FromExpression(x => x.ProcessPendingJobsAsync()), "0 3 * * *", + new RecurringJobOptions + { + TimeZone = bangkokTimeZone, + QueueName = "leave" // ← กำหนด queue + }); } // apply migrations diff --git a/BMA.EHR.Leave/appsettings.json b/BMA.EHR.Leave/appsettings.json index 40b464cf..ee356491 100644 --- a/BMA.EHR.Leave/appsettings.json +++ b/BMA.EHR.Leave/appsettings.json @@ -19,20 +19,19 @@ // "ExamConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", // "LeaveConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" - "DefaultConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", - "ExamConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", - "LeaveConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" + "DefaultConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;", + "ExamConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms_exam;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;", + "LeaveConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms_leave;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;" - // "DefaultConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", - // "ExamConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", - // "LeaveConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" + // "DefaultConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;", + // "ExamConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;", + // "LeaveConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;" }, "Jwt": { - //"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI", "Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc", "Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms" - //"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU", - //"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms" + // "Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU", + // "Issuer": "https://hrms-id.bangkok.go.th/realms/hrms" }, "EPPlus": { "ExcelPackage": { @@ -55,6 +54,11 @@ "Password": "12345678", "Queue": "hrms-checkin-queue-dev", "URL": "http://192.168.1.63:9122/api/queues/%2F/" + // "Host": "172.27.17.68", + // "User": "admin", + // "Password": "admin123456", + // "Queue": "hrms-checkin-queue", + // "URL": "http://172.27.17.68:9122/api/queues/%2F/" }, "Mail": { "Server": "mail.bangkok.go.th", @@ -68,7 +72,10 @@ "API": "https://hrmsbkk.case-collection.com/api/v1", "APIV2": "https://hrmsbkk.case-collection.com/api/v2", "VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com", - //"API": "https://bma-ehr.frappet.synology.me/api/v1", - //"API": "https://bma-hrms.bangkok.go.th/api/v1", + // "Domain": "https://hrms-exam.bangkok.go.th", + // "APIPROBATION": "https://hrms.bangkok.go.th/api/v1/probation", + // "API": "https://hrms.bangkok.go.th/api/v1", + // "APIV2": "https://hrms.bangkok.go.th/api/v2", + // "VITE_URL_MGT": "https://hrms-mgt.bangkok.go.th", "API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz" } diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentController.cs index a98abb74..ff010a2a 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentController.cs @@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -239,11 +239,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementAppointments = placementAppointments .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - placementAppointments = placementAppointments - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementAppointments = placementAppointments + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { placementAppointments = placementAppointments.Where(x => diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentEmployeeController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentEmployeeController.cs index ae8e40ac..971cd526 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentEmployeeController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementAppointmentEmployeeController.cs @@ -110,7 +110,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -232,11 +232,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementAppointments = placementAppointments .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - placementAppointments = placementAppointments - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementAppointments = placementAppointments + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { placementAppointments = placementAppointments.Where(x => diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementController.cs index 51a09094..fbb6e2de 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementController.cs @@ -140,6 +140,7 @@ namespace BMA.EHR.Placement.Service.Controllers public async Task> GetExamByPlacement(Guid examId) { var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(examId.ToString(), "SYS_PLACEMENT_PASS"); + var role = string.Empty; if (getWorkflow == false) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS"); @@ -148,6 +149,7 @@ namespace BMA.EHR.Placement.Service.Controllers { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } + role = jsonData["result"]?.ToString(); } var rootId = ""; @@ -167,7 +169,7 @@ namespace BMA.EHR.Placement.Service.Controllers if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); - if (org.result.isOfficer == false) + if (org.result.isOfficer == false && role?.Trim().ToUpper() != "OWNER") { rootId = org.result.rootId == null ? "" : org.result.rootId; // child1Id = org.result.child1Id == null ? "" : org.result.child1Id; @@ -302,7 +304,7 @@ namespace BMA.EHR.Placement.Service.Controllers } return Success(result1); } - if (org.result.isOfficer == true) + if (org.result.isOfficer == true || role?.Trim().ToUpper() == "OWNER") { var data = await _context.PlacementProfiles.Where(x => x.Placement.Id == examId).Select(x => new { @@ -690,6 +692,13 @@ namespace BMA.EHR.Placement.Service.Controllers public async Task> GetDashboardByPlacement(Guid examId) { + var role = string.Empty; + var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS"); + var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData["status"]?.ToString() == "200") + { + role = jsonData["result"]?.ToString(); + } var rootId = ""; var child1Id = ""; @@ -709,7 +718,7 @@ namespace BMA.EHR.Placement.Service.Controllers if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); - if (org.result.isOfficer == false) + if (org.result.isOfficer == false && role?.Trim().ToUpper() != "OWNER") { rootId = org.result.rootId == null ? "" : org.result.rootId; // child1Id = org.result.child1Id == null ? "" : org.result.child1Id; @@ -733,7 +742,7 @@ namespace BMA.EHR.Placement.Service.Controllers return Success(placement); } - if (org.result.isOfficer == true) + if (org.result.isOfficer == true || role?.Trim().ToUpper() == "OWNER") { var placement = await _context.Placements .Where(x => x.Id == examId) @@ -894,6 +903,49 @@ namespace BMA.EHR.Placement.Service.Controllers return Success(); } + /// + /// API สำหรับยกเลิกการส่งตัว + /// + /// + /// + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpPost("update/draft-status")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> PersonUpdateDraftStatus([FromBody] PersonUpdateStatusRequest req) + { + var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_PLACEMENT_PASS"); + var jsonData = JsonConvert.DeserializeObject(getPermission); + if (jsonData["status"]?.ToString() != "200") + return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + + string role = jsonData["result"]?.ToString(); + if (role != "OWNER") + return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); + + var person = await _context.PlacementProfiles + .FirstOrDefaultAsync(x => x.Id == req.PersonalId); + if (person == null) + return Error(GlobalMessages.DataNotFound, 404); + + if (person.PlacementStatus == "REPORT") + return Error("ไม่สามารถยกเลิกการส่งตัวได้ เนื่องจากส่งไปออกคำสั่งแล้ว"); + + if (person.PlacementStatus == "DONE") + return Error("ไม่สามารถยกเลิกการส่งตัวได้ เนื่องจากบรรจุไปแล้ว"); + + person.Draft = false; + person.LastUpdateFullName = FullName ?? "System Administrator"; + person.LastUpdateUserId = UserId ?? ""; + person.LastUpdatedAt = DateTime.Now; + await _context.SaveChangesAsync(); + return Success(); + } + [HttpGet("pass/deferment/{personalId:length(36)}")] public async Task> GetPersonDeferment(Guid personalId) { @@ -1791,7 +1843,7 @@ namespace BMA.EHR.Placement.Service.Controllers isLeave = false, dateRetire = (DateTime?)null, dateAppoint = r.commandDateAffect, - dateStart = r.commandDateAffect, + dateStart = p.ReportingDate, govAgeAbsent = 0, govAgePlus = 0, birthDate = (p.DateOfBirth == null || p.DateOfBirth == DateTime.MinValue) ? (DateTime?)null : p.DateOfBirth, @@ -1993,7 +2045,7 @@ namespace BMA.EHR.Placement.Service.Controllers .Where(x => req.refIds.Contains(x.Id.ToString())) // .Where(x => x.PlacementStatus.ToUpper() == "REPORT") .ToListAsync(); - placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAI"); + placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN"); await _context.SaveChangesAsync(); return Success(); } diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementOfficerController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementOfficerController.cs index 19cc4e2d..c2033280 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementOfficerController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementOfficerController.cs @@ -111,7 +111,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -193,11 +193,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementOfficers = placementOfficers .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - placementOfficers = placementOfficers - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementOfficers = placementOfficers + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { placementOfficers = placementOfficers.Where(x => diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementReceiveController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementReceiveController.cs index db8a28a7..ab8a508e 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementReceiveController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementReceiveController.cs @@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -231,11 +231,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementReceives = placementReceives .Where(x => (x.rootDnaId == nodeId) || (x.CreatedUserId == UserId)).ToList(); } - else if (role == "PARENT") - { - placementReceives = placementReceives - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementReceives = placementReceives + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { placementReceives = placementReceives.Where(x => diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementRepatriationController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementRepatriationController.cs index 45798f6c..5f5668b7 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementRepatriationController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementRepatriationController.cs @@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -198,11 +198,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementRepatriations = placementRepatriations .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - placementRepatriations = placementRepatriations - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementRepatriations = placementRepatriations + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { placementRepatriations = placementRepatriations.Where(x => diff --git a/BMA.EHR.Placement.Service/Controllers/PlacementTransferController.cs b/BMA.EHR.Placement.Service/Controllers/PlacementTransferController.cs index 68dd42a9..3514e4a5 100644 --- a/BMA.EHR.Placement.Service/Controllers/PlacementTransferController.cs +++ b/BMA.EHR.Placement.Service/Controllers/PlacementTransferController.cs @@ -205,7 +205,7 @@ namespace BMA.EHR.Placement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -285,11 +285,11 @@ namespace BMA.EHR.Placement.Service.Controllers placementTransfers = placementTransfers .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - placementTransfers = placementTransfers - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // placementTransfers = placementTransfers + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { placementTransfers = placementTransfers.Where(x => diff --git a/BMA.EHR.Retirement.Service/BMA.EHR.Retirement.Service.csproj b/BMA.EHR.Retirement.Service/BMA.EHR.Retirement.Service.csproj index 255f2a75..6a820e15 100644 --- a/BMA.EHR.Retirement.Service/BMA.EHR.Retirement.Service.csproj +++ b/BMA.EHR.Retirement.Service/BMA.EHR.Retirement.Service.csproj @@ -40,10 +40,17 @@ + + + + PreserveNewest + + + diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementController.cs index ad3105ba..b7a8b8df 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementController.cs @@ -7,6 +7,7 @@ using BMA.EHR.Domain.Models.Retirement; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Retirement.Service.Requests; +using BMA.EHR.Retirement.Service.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -37,6 +38,7 @@ namespace BMA.EHR.Retirement.Service.Controllers private readonly PermissionRepository _permission; private readonly DisciplineDbContext _contextDiscipline; private readonly RetireReportRepository _service; + private readonly RetirementReportService _reportService; public RetirementController(RetirementRepository repository, NotificationRepository repositoryNoti, ApplicationDBContext context, @@ -46,7 +48,8 @@ namespace BMA.EHR.Retirement.Service.Controllers IHttpContextAccessor httpContextAccessor, PermissionRepository permission, DisciplineDbContext contextDiscipline, - RetireReportRepository service) + RetireReportRepository service, + RetirementReportService reportService) { _repository = repository; _repositoryNoti = repositoryNoti; @@ -58,6 +61,7 @@ namespace BMA.EHR.Retirement.Service.Controllers _permission = permission; _contextDiscipline = contextDiscipline; _service = service; + _reportService = reportService; } #region " Properties " @@ -2213,5 +2217,83 @@ namespace BMA.EHR.Retirement.Service.Controllers } } #endregion + + #region รายงานรายชื่อผู้เกษียณอายุราชการ ข้าราชการ & ลูกจ้างประจำ + /// + /// รายงานรายชื่อผู้เกษียณอายุราชการ ข้าราชการ & ลูกจ้างประจำ + /// + /// Id ของรอบเกษียณ + /// pdf, docx + /// + /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpGet("report/{exportType}/{Id}")] + public async Task> GetReportProfileRetirement([FromRoute] Guid Id, string exportType = "pdf") + { + var retire = await _service.GetProfileRetirementdAsync(Id, token); + if (retire != null) + { + var reportfile = string.Empty; + exportType = exportType.Trim(); + + switch (retire.GetType().GetProperty("Type").GetValue(retire)) + { + case "OFFICER": + if (string.IsNullOrEmpty(retire.GetType().GetProperty("TypeReport").GetValue(retire))) + { + reportfile = $"retire-1"; + } + else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "ADD" || retire.GetType().GetProperty("TypeReport").GetValue(retire) == "EDIT") + { + reportfile = $"retire-2"; + } + else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "REMOVE") + { + reportfile = $"retire-3"; + } + else + { + return Error(retire.GetType().GetProperty("TypeReport").GetValue(retire)); + } + break; + case "EMPLOYEE": + if (string.IsNullOrEmpty(retire.GetType().GetProperty("TypeReport").GetValue(retire))) + { + reportfile = $"retire-emp-1"; + } + else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "ADD" || retire.GetType().GetProperty("TypeReport").GetValue(retire) == "EDIT") + { + reportfile = $"retire-emp-2"; + } + else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "REMOVE") + { + reportfile = $"retire-emp-3"; + } + else + { + return Error(retire.GetType().GetProperty("TypeReport").GetValue(retire)); + } + break; + default: + return Error(retire.GetType().GetProperty("Type").GetValue(retire)); + } + + var reportBytes = await _reportService.GenerateReportAsync(reportfile, retire, exportType); + + var fileName = $"reportRetirement-{DateTime.Now:yyyyMMdd-HHmmss}.{exportType}"; + var contentType = exportType.Trim().ToLower() == "pdf" + ? "application/pdf" + : "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + + return File(reportBytes, contentType, fileName); + + } + else + { + return NotFound(); + } + } + #endregion } } diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementDeceasedController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementDeceasedController.cs index 33808435..cf9f153d 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementDeceasedController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementDeceasedController.cs @@ -116,7 +116,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -177,11 +177,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementDeceaseds = retirementDeceaseds .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementDeceaseds = retirementDeceaseds - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementDeceaseds = retirementDeceaseds + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { retirementDeceaseds = retirementDeceaseds.Where(x => diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementOtherController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementOtherController.cs index 4db9f778..04a01f77 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementOtherController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementOtherController.cs @@ -112,7 +112,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -227,11 +227,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementOthers = retirementOthers .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementOthers = retirementOthers - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementOthers = retirementOthers + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementOthers = retirementOthers.Where(x => diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementOutController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementOutController.cs index 72a7bc91..ce8b0452 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementOutController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementOutController.cs @@ -127,7 +127,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -208,11 +208,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementOuts = retirementOuts .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementOuts = retirementOuts - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementOuts = retirementOuts + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementOuts = retirementOuts.Where(x => diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementResignController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementResignController.cs index 7b33e0fb..147f1adb 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementResignController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementResignController.cs @@ -165,7 +165,7 @@ namespace BMA.EHR.Retirement.Service.Controllers p.ApproveReason, p.RejectReason, p.CancelReason, - p.Status, + status = p.RetirementResignCancels.FirstOrDefault() == null ? p.Status : p.RetirementResignCancels.FirstOrDefault().Status, statusCancel = p.RetirementResignCancels.FirstOrDefault() == null ? null : p.RetirementResignCancels.FirstOrDefault().Status, p.IsActive, }) @@ -271,7 +271,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -336,11 +336,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementResigns = retirementResigns .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementResigns = retirementResigns - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementResigns = retirementResigns + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementResigns = retirementResigns.Where(x => @@ -403,7 +403,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -467,11 +467,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementResigns = retirementResigns .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementResigns = retirementResigns - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementResigns = retirementResigns + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementResigns = retirementResigns.Where(x => @@ -2170,7 +2170,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2228,11 +2228,11 @@ namespace BMA.EHR.Retirement.Service.Controllers data = data .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - data = data - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // data = data + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => @@ -3104,13 +3104,13 @@ namespace BMA.EHR.Retirement.Service.Controllers }).ToList(); var baseAPIOrg = _configuration["API"]; - var reportDone = false; - if (data.Where(profile => profile.Status == "DONE").Any()) - { - reportDone = true; - } - if (reportDone == true) - { + //var reportDone = false; + //if (data.Where(profile => profile.Status == "DONE").Any()) + //{ + // reportDone = true; + //} + //if (reportDone == true) + //{ var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-leave"; using (var client = new HttpClient()) { @@ -3128,27 +3128,27 @@ namespace BMA.EHR.Retirement.Service.Controllers await _context.SaveChangesAsync(); } } - } - else - { - var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign"; - using (var client = new HttpClient()) - { - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); - client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); - var _res = await client.PostAsJsonAsync(apiUrlOrg, new - { - resignId = resultData.Select(x => x.resignId).ToList(), - }); - var _result = await _res.Content.ReadAsStringAsync(); - if (_res.IsSuccessStatusCode) - { - data.ForEach(profile => profile.Status = "DONE"); - data.ForEach(profile => profile.RetirementResign.Status = "CANCEL"); - await _context.SaveChangesAsync(); - } - } - } + //} + //else + //{ + // var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign"; + // using (var client = new HttpClient()) + // { + // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); + // client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); + // var _res = await client.PostAsJsonAsync(apiUrlOrg, new + // { + // resignId = resultData.Select(x => x.resignId).ToList(), + // }); + // var _result = await _res.Content.ReadAsStringAsync(); + // if (_res.IsSuccessStatusCode) + // { + // data.ForEach(profile => profile.Status = "DONE"); + // data.ForEach(profile => profile.RetirementResign.Status = "CANCEL"); + // await _context.SaveChangesAsync(); + // } + // } + //} return Success(); } diff --git a/BMA.EHR.Retirement.Service/Controllers/RetirementResignEmployeeController.cs b/BMA.EHR.Retirement.Service/Controllers/RetirementResignEmployeeController.cs index 8bc6c975..5ad00538 100644 --- a/BMA.EHR.Retirement.Service/Controllers/RetirementResignEmployeeController.cs +++ b/BMA.EHR.Retirement.Service/Controllers/RetirementResignEmployeeController.cs @@ -102,8 +102,8 @@ namespace BMA.EHR.Retirement.Service.Controllers p.Remark, p.ApproveReason, p.RejectReason, - p.CancelReason, - p.Status, + p.CancelReason, + status = p.RetirementResignEmployeeCancels.FirstOrDefault() == null ? p.Status : p.RetirementResignEmployeeCancels.FirstOrDefault().Status, statusCancel = p.RetirementResignEmployeeCancels.FirstOrDefault() == null ? null : p.RetirementResignEmployeeCancels.FirstOrDefault().Status, p.IsActive, }) @@ -208,7 +208,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -273,11 +273,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementResignEmployees = retirementResignEmployees .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementResignEmployees = retirementResignEmployees - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementResignEmployees = retirementResignEmployees + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementResignEmployees = retirementResignEmployees.Where(x => @@ -340,7 +340,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -403,11 +403,11 @@ namespace BMA.EHR.Retirement.Service.Controllers retirementResignEmployees = retirementResignEmployees .Where(x => x.rootDnaOldId == nodeId).ToList(); } - else if (role == "PARENT") - { - retirementResignEmployees = retirementResignEmployees - .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); - } + // else if (role == "PARENT") + // { + // retirementResignEmployees = retirementResignEmployees + // .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList(); + // } else if (role == "NORMAL") { retirementResignEmployees = retirementResignEmployees.Where(x => @@ -2078,7 +2078,7 @@ namespace BMA.EHR.Retirement.Service.Controllers ? profileAdmin?.RootDnaId : ""; } - else if (role == "ROOT" || role == "PARENT") + else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } @@ -2136,11 +2136,11 @@ namespace BMA.EHR.Retirement.Service.Controllers data = data .Where(x => x.rootDnaId == nodeId).ToList(); } - else if (role == "PARENT") - { - data = data - .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); - } + // else if (role == "PARENT") + // { + // data = data + // .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); + // } else if (role == "NORMAL") { data = data.Where(x => @@ -2598,14 +2598,14 @@ namespace BMA.EHR.Retirement.Service.Controllers }).ToList(); var baseAPIOrg = _configuration["API"]; - var reportDone = false; - if (data.Where(profile => profile.Status == "DONE").Any()) - { - reportDone = true; - } + //var reportDone = false; + //if (data.Where(profile => profile.Status == "DONE").Any()) + //{ + // reportDone = true; + //} - if (reportDone == true) - { + //if (reportDone == true) + //{ var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-leave"; using (var client = new HttpClient()) { @@ -2623,27 +2623,27 @@ namespace BMA.EHR.Retirement.Service.Controllers await _context.SaveChangesAsync(); } } - } - else - { - var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign"; - using (var client = new HttpClient()) - { - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); - client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); - var _res = await client.PostAsJsonAsync(apiUrlOrg, new - { - resignId = resultData.Select(x => x.resignId).ToList(), - }); - var _result = await _res.Content.ReadAsStringAsync(); - if (_res.IsSuccessStatusCode) - { - data.ForEach(profile => profile.Status = "DONE"); - data.ForEach(profile => profile.RetirementResignEmployee.Status = "CANCEL"); - await _context.SaveChangesAsync(); - } - } - } + //} + //else + //{ + // var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign"; + // using (var client = new HttpClient()) + // { + // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); + // client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); + // var _res = await client.PostAsJsonAsync(apiUrlOrg, new + // { + // resignId = resultData.Select(x => x.resignId).ToList(), + // }); + // var _result = await _res.Content.ReadAsStringAsync(); + // if (_res.IsSuccessStatusCode) + // { + // data.ForEach(profile => profile.Status = "DONE"); + // data.ForEach(profile => profile.RetirementResignEmployee.Status = "CANCEL"); + // await _context.SaveChangesAsync(); + // } + // } + //} return Success(); } diff --git a/BMA.EHR.Retirement.Service/Program.cs b/BMA.EHR.Retirement.Service/Program.cs index ee807e0a..a55f9674 100644 --- a/BMA.EHR.Retirement.Service/Program.cs +++ b/BMA.EHR.Retirement.Service/Program.cs @@ -3,6 +3,7 @@ using BMA.EHR.Domain.Middlewares; using BMA.EHR.Infrastructure; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Retirement.Service; +using BMA.EHR.Retirement.Service.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; @@ -86,6 +87,7 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplication(); builder.Services.AddLeaveApplication(); builder.Services.AddPersistence(builder.Configuration); + builder.Services.AddScoped(); builder.Services.AddLeavePersistence(builder.Configuration); builder.Services.AddHttpClient(); diff --git a/BMA.EHR.Retirement.Service/Services/RetirementReportService.cs b/BMA.EHR.Retirement.Service/Services/RetirementReportService.cs new file mode 100644 index 00000000..82bf2b27 --- /dev/null +++ b/BMA.EHR.Retirement.Service/Services/RetirementReportService.cs @@ -0,0 +1,638 @@ +using BMA.EHR.Application.Responses; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace BMA.EHR.Retirement.Service.Services +{ + public class RetirementReportService + { + private readonly IWebHostEnvironment _environment; + private readonly ILogger _logger; + private readonly IConfiguration _configuration; + + /// + /// Initializes a new instance of the RetirementReportService class. + /// + public RetirementReportService( + IWebHostEnvironment environment, + ILogger logger, + IConfiguration configuration) + { + _environment = environment; + _logger = logger; + _configuration = configuration; + } + + #region Public Methods + + /// + /// สร้างรายงานจาก Template (.docx) + /// + public async Task GenerateReportAsync(string templateName, dynamic data, string exportType) + { + try + { + var templatePath = GetTemplatePath(templateName); + var docxBytes = await ProcessTemplateAsync(templatePath, data); + + return exportType.ToLower() == "pdf" + ? await ConvertToPdfAsync(docxBytes) + : docxBytes; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error generating report"); + throw; + } + } + + #endregion + + #region Template Processing + + private string GetTemplatePath(string templateName) + { + var path = Path.Combine(_environment.ContentRootPath, "Templates", $"{templateName}.docx"); + if (!File.Exists(path)) + throw new FileNotFoundException($"Template not found: {templateName}"); + return path; + } + + private async Task ProcessTemplateAsync(string templatePath, dynamic data) + { + using var templateStream = File.OpenRead(templatePath); + using var outputStream = new MemoryStream(); + await templateStream.CopyToAsync(outputStream); + outputStream.Position = 0; + + using (var wordDoc = WordprocessingDocument.Open(outputStream, true)) + { + var mainPart = wordDoc.MainDocumentPart; + if (mainPart == null) return Array.Empty(); + + ReplacePlaceholders(mainPart, data); + wordDoc.Save(); + } + + return outputStream.ToArray(); + } + + private void ReplacePlaceholders(MainDocumentPart mainPart, dynamic data) + { + var document = mainPart.Document; + if (document == null) return; + + var processor = CreateDataProcessor(data); + processor.Process(document, new Action(FillTableRows)); + } + + #endregion + + #region Data Processing Strategy + + private IDataProcessor CreateDataProcessor(dynamic data) + { + var dataType = data.GetType(); + var isDictionary = dataType.IsGenericType && + dataType.GetGenericTypeDefinition() == typeof(Dictionary<,>); + + return isDictionary + ? new DictionaryDataProcessor(data) + : new ObjectDataProcessor(data); + } + + #endregion + + #region Table Processing + + private void FillTableRows(Document document, System.Collections.IEnumerable profiles) + { + var table = document.Descendants().FirstOrDefault(); + if (table == null) return; + + var rows = table.Elements().ToList(); + if (rows.Count == 0) return; + + var strategy = CreateTableStrategy(rows); + strategy.Process(table, rows, profiles); + } + + private static ITableStrategy CreateTableStrategy(List rows) + { + // retire-1 format: 1 row, 1 cell, 1 paragraph + if (IsSingleParagraphFormat(rows)) + return new SingleParagraphTableStrategy(); + + // retire-3 format: 2+ rows (header + template) + return new MultiRowTableStrategy(); + } + + private static bool IsSingleParagraphFormat(List rows) => + rows.Count == 1 && + rows[0].Elements().Count() == 1 && + rows[0].Elements().First().Elements().Count() == 1; + + #endregion + + #region PDF Conversion + + private async Task ConvertToPdfAsync(byte[] docxBytes) + { + var tempDocx = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.docx"); + var tempPdf = Path.ChangeExtension(tempDocx, ".pdf"); + + try + { + await File.WriteAllBytesAsync(tempDocx, docxBytes); + await ConvertToPdfInternalAsync(tempDocx, tempPdf); + return await File.ReadAllBytesAsync(tempPdf); + } + finally + { + if (File.Exists(tempDocx)) File.Delete(tempDocx); + if (File.Exists(tempPdf)) File.Delete(tempPdf); + } + } + + private async Task ConvertToPdfInternalAsync(string docxPath, string pdfPath) + { + try + { + var useDocker = _configuration.GetValue("LibreOffice:UseDocker", false); + var timeout = _configuration.GetValue("LibreOffice:Timeout", 180000); + + if (useDocker) + { + await ConvertToPdfViaDockerAsync(docxPath, pdfPath, timeout); + } + else + { + // // PROD: Disabled local LibreOffice conversion + // await ConvertToPdfLocallyAsync(docxPath, pdfPath, timeout); + throw new NotSupportedException("LibreOffice conversion is disabled."); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error converting to PDF"); + throw; + } + } + + private async Task ConvertToPdfViaDockerAsync(string docxPath, string pdfPath, int timeout) + { + var inputDir = _configuration["LibreOffice:InputDirectory"] ?? "/app/libreoffice/input"; + var outputDir = _configuration["LibreOffice:OutputDirectory"] ?? "/app/libreoffice/output"; + var fileName = Path.GetFileName(docxPath); + var pdfName = Path.ChangeExtension(fileName, ".pdf"); + + // Ensure directories exist + Directory.CreateDirectory(inputDir); + Directory.CreateDirectory(outputDir); + + // Copy file to input folder (LibreOffice watcher will pick it up) + var inputPath = Path.Combine(inputDir, fileName).Replace('\\', '/'); + var outputPath = Path.Combine(outputDir, pdfName).Replace('\\', '/'); + + _logger.LogInformation("📤 Sending file to LibreOffice: {FileName}", fileName); + await File.WriteAllBytesAsync(inputPath, await File.ReadAllBytesAsync(docxPath)); + + // Wait for LibreOffice to convert (file watcher handles it) + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + var pollInterval = TimeSpan.FromMilliseconds(500); + + while (stopwatch.ElapsedMilliseconds < timeout) + { + if (File.Exists(outputPath)) + { + _logger.LogInformation("✅ PDF received: {PdfName} (took {ElapsedMs}ms)", pdfName, stopwatch.ElapsedMilliseconds); + + await File.WriteAllBytesAsync(pdfPath, await File.ReadAllBytesAsync(outputPath)); + + // Cleanup + try + { + if (File.Exists(outputPath)) File.Delete(outputPath); + _logger.LogDebug("🗑️ Cleaned up output file: {PdfName}", pdfName); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to cleanup output file"); + } + + return; + } + + await Task.Delay(pollInterval); + } + + throw new TimeoutException($"LibreOffice conversion timed out after {timeout}ms. File not found: {outputPath}"); + } + + // // PROD: Disabled local LibreOffice conversion + // private async Task ConvertToPdfLocallyAsync(string docxPath, string pdfPath, int timeout) + // { + // var libreOfficePath = _configuration["LibreOffice:Path"] ?? GetDefaultLibreOfficePath(); + // var arguments = _configuration["LibreOffice:Arguments"] ?? "--headless --convert-to pdf --nologo --norestore"; + // var outputDir = Path.GetDirectoryName(pdfPath); + + // if (string.IsNullOrEmpty(outputDir)) + // { + // throw new DirectoryNotFoundException("Output directory cannot be determined"); + // } + + // var psi = new ProcessStartInfo + // { + // FileName = libreOfficePath, + // Arguments = $"{arguments} --outdir \"{outputDir}\" \"{docxPath}\"", + // UseShellExecute = false, + // RedirectStandardOutput = true, + // RedirectStandardError = true, + // CreateNoWindow = true + // }; + + // using var process = Process.Start(psi); + // var exited = process.WaitForExit(timeout); + + // if (!exited) + // { + // process.Kill(entireProcessTree: true); + // throw new TimeoutException($"LibreOffice conversion timed out after {timeout}ms"); + // } + + // if (process.ExitCode != 0) + // { + // var error = await process.StandardError.ReadToEndAsync(); + // throw new Exception($"LibreOffice conversion failed: {error}"); + // } + // } + + // // PROD: Disabled local LibreOffice path detection + // private static string GetDefaultLibreOfficePath() + // { + // if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + // { + // var possiblePaths = new[] + // { + // @"C:\Program Files\LibreOffice\program\soffice.exe", + // @"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + // @"C:\Program Files\LibreOffice\program\soffice.com" + // }; + + // return possiblePaths.FirstOrDefault(File.Exists) + // ?? throw new FileNotFoundException("LibreOffice not found. Please install LibreOffice or configure the path in appsettings.json"); + // } + + // // Linux/Docker: use default path + // return "libreoffice"; + // } + + #endregion + } + + #region Data Processor Interfaces & Implementations + + internal interface IDataProcessor + { + void Process(Document document, Action tableFiller); + } + + internal class DictionaryDataProcessor : IDataProcessor + { + private readonly dynamic _data; + + public DictionaryDataProcessor(dynamic data) + { + _data = data; + } + + public void Process(Document document, Action tableFiller) + { + var keys = _data.Keys as System.Collections.ICollection; + if (keys == null) return; + + System.Collections.IEnumerable? profiles = null; + + foreach (string key in keys) + { + if (key.Equals("profiles", StringComparison.OrdinalIgnoreCase)) + { + profiles = _data[key] as System.Collections.IEnumerable; + continue; + } + + var valueObj = _data[key]; + if (valueObj != null && typeof(System.Collections.IEnumerable).IsAssignableFrom(valueObj.GetType()) && + valueObj.GetType() != typeof(string)) + { + continue; + } + + var value = valueObj?.ToString() ?? string.Empty; + var placeholder = $"{{{{{key}}}}}"; + TextReplacer.ReplaceAll(document, placeholder, value); + } + + if (profiles != null) + { + tableFiller(document, profiles); + } + } + } + + internal class ObjectDataProcessor : IDataProcessor + { + private readonly dynamic _data; + + public ObjectDataProcessor(dynamic data) + { + _data = data; + } + + public void Process(Document document, Action tableFiller) + { + var dataType = _data.GetType(); + var allProps = dataType.GetProperties(); + var validProps = new List(); + + foreach (var p in allProps) + { + if (p.GetIndexParameters().Length == 0) + { + validProps.Add(p); + } + } + + System.Collections.IEnumerable? profiles = null; + + foreach (var prop in validProps) + { + var propType = prop.PropertyType; + bool isEnumerable = typeof(System.Collections.IEnumerable).IsAssignableFrom(propType); + bool isString = propType == typeof(string); + + if (isEnumerable && !isString) + { + if (prop.Name.Equals("profiles", StringComparison.OrdinalIgnoreCase)) + { + profiles = prop.GetValue(_data) as System.Collections.IEnumerable; + } + continue; + } + + var value = prop.GetValue(_data)?.ToString() ?? string.Empty; + var placeholder = $"{{{{{prop.Name}}}}}"; + TextReplacer.ReplaceAll(document, placeholder, value); + } + + if (profiles != null) + { + tableFiller(document, profiles); + } + } + } + + #endregion + + #region Text Replacer + + internal static class TextReplacer + { + public static void ReplaceAll(Document document, string oldValue, string newValue) + { + bool found = false; + + // Method 1: Check within single Run + foreach (var run in document.Descendants()) + { + var textElements = run.Elements().ToList(); + if (textElements.Count == 0) continue; + + var combinedText = string.Concat(textElements.Select(t => t.Text)); + if (combinedText.Contains(oldValue)) + { + found = true; + var replacedText = combinedText.Replace(oldValue, newValue); + textElements[0].Text = replacedText; + for (int i = 1; i < textElements.Count; i++) + { + textElements[i].Text = string.Empty; + } + } + } + + // Method 2: Check across all Runs in Paragraph + foreach (var para in document.Descendants()) + { + var allRuns = para.Elements().ToList(); + if (allRuns.Count == 0) continue; + + var combinedParaText = string.Concat(allRuns.SelectMany(r => r.Elements().Select(t => t.Text))); + if (combinedParaText.Contains(oldValue)) + { + found = true; + var replacedText = combinedParaText.Replace(oldValue, newValue); + + var firstRunTexts = allRuns[0].Elements().ToList(); + if (firstRunTexts.Count > 0) + { + firstRunTexts[0].Text = replacedText; + for (int i = 1; i < firstRunTexts.Count; i++) + { + firstRunTexts[i].Text = string.Empty; + } + } + + for (int i = 1; i < allRuns.Count; i++) + { + foreach (var t in allRuns[i].Elements()) + { + t.Text = string.Empty; + } + } + } + } + + // Fallback: Check individual Text elements + if (!found) + { + foreach (var text in document.Descendants()) + { + if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue)) + { + found = true; + text.Text = text.Text.Replace(oldValue, newValue); + } + } + } + } + + public static void ReplaceInRow(TableRow row, string oldValue, string newValue) + { + bool found = false; + + foreach (var cell in row.Descendants()) + { + foreach (var para in cell.Elements()) + { + found = ReplaceInParagraph(para, oldValue, newValue) || found; + } + } + + // Fallback: Check individual Text elements + if (!found) + { + foreach (var text in row.Descendants()) + { + if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue)) + { + found = true; + text.Text = text.Text.Replace(oldValue, newValue); + } + } + } + } + + public static bool ReplaceInParagraph(Paragraph paragraph, string oldValue, string newValue) + { + bool found = false; + + var allTexts = paragraph.Descendants().ToList(); + if (allTexts.Count == 0) return false; + + var combinedParaText = string.Concat(allTexts.Select(t => t.Text)); + + if (combinedParaText.Contains(oldValue)) + { + found = true; + var replacedText = combinedParaText.Replace(oldValue, newValue); + allTexts[0].Text = replacedText; + + for (int i = 1; i < allTexts.Count; i++) + { + allTexts[i].Text = string.Empty; + } + } + + // Fallback: Check individual Text elements + if (!found) + { + foreach (var text in allTexts) + { + if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue)) + { + found = true; + text.Text = text.Text.Replace(oldValue, newValue); + } + } + } + + return found; + } + } + + #endregion + + #region Table Strategy Interfaces & Implementations + + internal interface ITableStrategy + { + void Process(Table table, List rows, System.Collections.IEnumerable profiles); + } + + internal class SingleParagraphTableStrategy : ITableStrategy + { + public void Process(Table table, List rows, System.Collections.IEnumerable profiles) + { + var cell = rows[0].Elements().First(); + var templatePara = cell.Elements().First(); + + var profileList = profiles.Cast().ToList(); + + foreach (var profile in profileList) + { + var props = profile.GetType() + .GetProperties() + .Where(p => p.GetIndexParameters().Length == 0) + .ToList(); + + var newPara = (Paragraph)templatePara.CloneNode(true); + + foreach (var prop in props) + { + var value = prop.GetValue(profile)?.ToString() ?? string.Empty; + var placeholder = $"{{{{{prop.Name}}}}}"; + TextReplacer.ReplaceInParagraph(newPara, placeholder, value); + } + + cell.Append(newPara); + } + + templatePara.Remove(); + } + } + + internal class MultiRowTableStrategy : ITableStrategy + { + public void Process(Table table, List rows, System.Collections.IEnumerable profiles) + { + var templateRowIndex = rows.Count >= 2 ? 1 : 0; + var templateRow = rows[templateRowIndex]; + templateRow.Remove(); + + var profileList = profiles.Cast().ToList(); + + // Process header row if exists + if (rows.Count >= 2) + { + ProcessHeaderRow(rows[0], profileList); + } + + // Process template rows + foreach (var profile in profileList) + { + var newRow = (TableRow)templateRow.CloneNode(true); + var props = profile.GetType() + .GetProperties() + .Where(p => p.GetIndexParameters().Length == 0) + .ToList(); + + foreach (var prop in props) + { + var value = prop.GetValue(profile)?.ToString() ?? string.Empty; + var placeholder = $"{{{{{prop.Name}}}}}"; + TextReplacer.ReplaceInRow(newRow, placeholder, value); + } + + table.AppendChild(newRow); + } + } + + private static void ProcessHeaderRow(TableRow headerRow, List profileList) + { + var firstProfile = profileList.FirstOrDefault(); + if (firstProfile == null) return; + + var props = firstProfile.GetType() + .GetProperties() + .Where(p => p.GetIndexParameters().Length == 0) + .ToList(); + + foreach (var prop in props) + { + var value = prop.GetValue(firstProfile)?.ToString() ?? string.Empty; + var placeholder = $"{{{{{prop.Name}}}}}"; + + if (!string.IsNullOrWhiteSpace(value)) + { + TextReplacer.ReplaceInRow(headerRow, placeholder, value); + } + } + } + } + + #endregion +} diff --git a/BMA.EHR.Retirement.Service/Templates/retire-1.docx b/BMA.EHR.Retirement.Service/Templates/retire-1.docx new file mode 100644 index 00000000..aae58587 Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-1.docx differ diff --git a/BMA.EHR.Retirement.Service/Templates/retire-2.docx b/BMA.EHR.Retirement.Service/Templates/retire-2.docx new file mode 100644 index 00000000..4c9db823 Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-2.docx differ diff --git a/BMA.EHR.Retirement.Service/Templates/retire-3.docx b/BMA.EHR.Retirement.Service/Templates/retire-3.docx new file mode 100644 index 00000000..4257c5f6 Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-3.docx differ diff --git a/BMA.EHR.Retirement.Service/Templates/retire-emp-1.docx b/BMA.EHR.Retirement.Service/Templates/retire-emp-1.docx new file mode 100644 index 00000000..28e5c9ea Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-emp-1.docx differ diff --git a/BMA.EHR.Retirement.Service/Templates/retire-emp-2.docx b/BMA.EHR.Retirement.Service/Templates/retire-emp-2.docx new file mode 100644 index 00000000..3fd290de Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-emp-2.docx differ diff --git a/BMA.EHR.Retirement.Service/Templates/retire-emp-3.docx b/BMA.EHR.Retirement.Service/Templates/retire-emp-3.docx new file mode 100644 index 00000000..622f5b8e Binary files /dev/null and b/BMA.EHR.Retirement.Service/Templates/retire-emp-3.docx differ