Compare commits

..

No commits in common. "dev" and "placement-dev1.0.21" have entirely different histories.

135 changed files with 2250 additions and 63315 deletions

6
.gitignore vendored
View file

@ -374,9 +374,3 @@ MigrationBackup/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd FodyWeavers.xsd
# VS Code C# Dev Kit cache
*.lscache
# Claude Code
.claude/

25
.vscode/launch.json vendored
View file

@ -26,31 +26,6 @@
"/Views": "${workspaceFolder}/Views" "/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", "name": ".NET Core Attach",
"type": "coreclr", "type": "coreclr",

View file

@ -61,8 +61,6 @@ namespace BMA.EHR.Application
services.AddTransient<MinIOLeaveService>(); services.AddTransient<MinIOLeaveService>();
services.AddTransient<LeaveProcessJobStatusRepository>();
return services; return services;
} }

View file

@ -53,18 +53,15 @@ namespace BMA.EHR.Application.Repositories
#region " For Call External API " #region " For Call External API "
protected async Task<string> GetExternalAPIAsync(string apiPath, string accessToken, string apiKey, CancellationToken cancellationToken = default) protected async Task<string> GetExternalAPIAsync(string apiPath, string accessToken, string apiKey)
{ {
try try
{ {
// กำหนด timeout เป็น 30 นาที
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", apiKey); client.DefaultRequestHeaders.Add("api-key", apiKey);
var _res = await client.GetAsync(apiPath,cancellationToken: combinedCts.Token); var _res = await client.GetAsync(apiPath);
if (_res.IsSuccessStatusCode) if (_res.IsSuccessStatusCode)
{ {
var _result = await _res.Content.ReadAsStringAsync(); var _result = await _res.Content.ReadAsStringAsync();
@ -80,13 +77,10 @@ namespace BMA.EHR.Application.Repositories
} }
} }
protected async Task<string> SendExternalAPIAsync(HttpMethod method, string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) protected async Task<string> SendExternalAPIAsync(HttpMethod method, string apiPath, string accessToken, object? body, string apiKey)
{ {
try try
{ {
// กำหนด timeout เป็น 30 นาที
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
// สร้าง request message // สร้าง request message
var request = new HttpRequestMessage(method, apiPath); var request = new HttpRequestMessage(method, apiPath);
@ -98,7 +92,7 @@ namespace BMA.EHR.Application.Repositories
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", apiKey); client.DefaultRequestHeaders.Add("api-key", apiKey);
var _res = await client.SendAsync(request, combinedCts.Token); var _res = await client.SendAsync(request);
if (_res.IsSuccessStatusCode) if (_res.IsSuccessStatusCode)
{ {
var _result = await _res.Content.ReadAsStringAsync(); var _result = await _res.Content.ReadAsStringAsync();
@ -115,13 +109,11 @@ namespace BMA.EHR.Application.Repositories
} }
public async Task<string> PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) protected async Task<string> PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey)
{ {
try 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 json = JsonConvert.SerializeObject(body);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
//stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
@ -130,7 +122,7 @@ namespace BMA.EHR.Application.Repositories
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", apiKey); client.DefaultRequestHeaders.Add("api-key", apiKey);
var _res = await client.PostAsync(apiPath, stringContent, combinedCts.Token); var _res = await client.PostAsync(apiPath, stringContent);
if (_res.IsSuccessStatusCode) if (_res.IsSuccessStatusCode)
{ {
var _result = await _res.Content.ReadAsStringAsync(); var _result = await _res.Content.ReadAsStringAsync();
@ -146,13 +138,10 @@ namespace BMA.EHR.Application.Repositories
} }
} }
protected async Task<bool> PostExternalAPIBooleanAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default) protected async Task<bool> PostExternalAPIBooleanAsync(string apiPath, string accessToken, object? body, string apiKey)
{ {
try 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 json = JsonConvert.SerializeObject(body);
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
@ -161,7 +150,7 @@ namespace BMA.EHR.Application.Repositories
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", apiKey); client.DefaultRequestHeaders.Add("api-key", apiKey);
var _res = await client.PostAsync(apiPath, stringContent, combinedCts.Token); var _res = await client.PostAsync(apiPath, stringContent);
return _res.IsSuccessStatusCode; return _res.IsSuccessStatusCode;
} }
} }

View file

@ -280,8 +280,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -425,8 +425,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -571,8 +571,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevel == null PositionLevelId = p.PosLevel == null
? Guid.Parse("00000000-0000-0000-0000-000000000000") ? Guid.Parse("00000000-0000-0000-0000-000000000000")
@ -794,8 +794,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -939,8 +939,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -1081,8 +1081,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -1301,8 +1301,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo ?? "", PosNo = p.PosNo ?? "",
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,
@ -1443,8 +1443,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -1591,8 +1591,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -1738,8 +1738,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -1992,8 +1992,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -2139,8 +2139,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -2358,8 +2358,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -2510,8 +2510,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -2730,8 +2730,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -2883,8 +2883,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -3045,8 +3045,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -3292,8 +3292,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -3498,8 +3498,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -3657,8 +3657,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -3819,8 +3819,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -4065,8 +4065,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -4207,8 +4207,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -4442,8 +4442,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -4602,8 +4602,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -4764,8 +4764,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5008,8 +5008,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5176,8 +5176,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5344,8 +5344,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5594,8 +5594,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5762,8 +5762,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -5930,8 +5930,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -6176,8 +6176,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -6334,8 +6334,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -6563,8 +6563,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -6725,8 +6725,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? "" : p.Position, Position = p.Position == null ? "" : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -6888,8 +6888,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -7130,8 +7130,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -7292,8 +7292,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -7454,8 +7454,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -7667,8 +7667,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -7835,8 +7835,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -8003,8 +8003,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix == null ? null : p.Prefix)}{p.FirstName} {p.LastName}",
Position = p.Position == null ? null : p.Position, Position = p.Position == null ? null : p.Position,
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" : LastInsignia = p.ProfileInsignia == null || p.ProfileInsignia.Count == 0 ? "" :
p.ProfileInsignia p.ProfileInsignia
.Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id) .Where(x => x.InsigniaId.HasValue && x.InsigniaId.Value != GetInsigniaByName("เหรียญจักรพรรดิมาลา")?.Id)
@ -8625,8 +8625,8 @@ namespace BMA.EHR.Application.Repositories
FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}", FullName = $"{(p.Prefix ?? "")}{p.FirstName} {p.LastName}",
Position = p.Position ?? "", Position = p.Position ?? "",
Rank = p.PosLevel ?? "", Rank = p.PosLevel ?? "",
ProfileDateAppoint = p.DateAppoint!.Value, ProfileDateAppoint = p.DateAppoint.Value,
GovAge = p.DateStart!.Value.CalculateGovAgeStr(0, 0), GovAge = p.DateAppoint.Value.CalculateGovAgeStr(0, 0),
PosNo = p.PosNo, PosNo = p.PosNo,
PositionLevelId = p.PosLevelId, PositionLevelId = p.PosLevelId,
PositionLevelName = p.PosLevel, PositionLevelName = p.PosLevel,

View file

@ -2,11 +2,8 @@
using BMA.EHR.Domain.Models.Base; using BMA.EHR.Domain.Models.Base;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.IO.Pipes; using System.IO.Pipes;
using System.Net.Http.Headers;
using System.Security.Claims; using System.Security.Claims;
using System.Text;
namespace BMA.EHR.Application.Repositories.Leaves namespace BMA.EHR.Application.Repositories.Leaves
{ {
@ -46,38 +43,6 @@ namespace BMA.EHR.Application.Repositories.Leaves
#region " Methods " #region " Methods "
public async Task<string> 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<IReadOnlyList<T>> GetAllAsync() public virtual async Task<IReadOnlyList<T>> GetAllAsync()
{ {
return await _dbSet.ToListAsync(); return await _dbSet.ToListAsync();
@ -103,24 +68,6 @@ namespace BMA.EHR.Application.Repositories.Leaves
return entity; return entity;
} }
public virtual async Task<IReadOnlyList<T>> AddRangeAsync(List<T> 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<T> UpdateAsync(T entity) public virtual async Task<T> UpdateAsync(T entity)
{ {
if (entity is EntityBase) if (entity is EntityBase)

View file

@ -9,7 +9,6 @@ using BMA.EHR.Domain.Shared;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System.Collections.Concurrent;
namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
{ {
@ -24,12 +23,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly EmailSenderService _emailSenderService; private readonly EmailSenderService _emailSenderService;
/// <summary>
/// Keyed locks to serialize get-or-create for LeaveBeginning rows by (ProfileId, LeaveYear, LeaveTypeId).
/// Prevents duplicate inserts when concurrent requests (e.g. UI calling /user/check twice) hit the same key.
/// </summary>
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _getOrAddLocks = new();
#endregion #endregion
#region " Constructor and Destuctor " #region " Constructor and Destuctor "
@ -86,8 +79,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task UpdateLeaveUsageAsync(int year, Guid typeId, Guid userId, double day) public async Task UpdateLeaveUsageAsync(int year, Guid typeId, Guid userId, double day)
{ {
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null) if (pf == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -106,81 +98,34 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
} }
public async Task UpdateLeaveCountAsync(int year, Guid typeId, Guid userId, int count) public async Task<LeaveBeginning?> GetByYearAndTypeIdForUserAsync(int year, Guid typeId, Guid userId)
{ {
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null) if (pf == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
} }
var govAge = (pf?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date);
var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId);
var data = await _dbContext.Set<LeaveBeginning>() var data = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType) .Include(x => x.LeaveType)
.FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == pf.Id); .FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
if (data == null) if (data == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
data.LeaveCount += count;
await _dbContext.SaveChangesAsync();
}
public async Task ProcessEarlyLeaveRequest(int year)
{
// Get Early Leave Request (กรองตามปีงบประมาณ: 1 ต.ค. (year-1) 30 ก.ย. (year))
var fiscalStart = new DateTime(year - 1, 10, 1);
var fiscalEnd = new DateTime(year, 9, 30);
var leaveReq = await _dbContext.Set<LeaveRequest>()
.Include(x => x.Type)
.Where(x => x.LeaveStatus == "APPROVE")
.Where(x => x.LeaveStartDate.Date <= fiscalEnd && x.LeaveEndDate.Date >= fiscalStart)
.ToListAsync();
foreach (var leave in leaveReq)
{
await GetByYearAndTypeIdForUserWithUpdateAsync(year, leave.Type.Id, leave.KeycloakUserId);
}
}
public async Task ProcessEarlyLeaveRequestSchedule()
{
int year = DateTime.Now.Year;
await ProcessEarlyLeaveRequest(year);
}
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUserAsync(int year, Guid typeId, Guid userId)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
var govAge = (pf?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date);
var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId);
LeaveBeginning Factory()
{ {
var limit = 0.0; var limit = 0.0;
var prev = _dbContext.Set<LeaveBeginning>() var prev = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType) .Include(x => x.LeaveType)
.FirstOrDefault(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id); .FirstOrDefaultAsync(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
// คำนวณปีงบประมาณจาก startDate (ปีงบประมาณเริ่ม 1 ต.ค. และสิ้นสุด 30 ก.ย.)
var isCurrentYear = DateTime.Now.Year == year;
var prevRemain = 0.0; var prevRemain = 0.0;
if (prev != null) if (prev != null)
{ {
prevRemain = isCurrentYear ? prev.LeaveDays - (prev.LeaveDaysUsed ?? 0.0) : 0.0; prevRemain = prev.LeaveDays - prev.LeaveDaysUsed;
} }
if (govAge >= 180) if (govAge >= 180)
@ -201,7 +146,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
limit = 0.0; limit = 0.0;
} }
return new LeaveBeginning data = new LeaveBeginning
{ {
LeaveYear = year, LeaveYear = year,
LeaveTypeId = typeId, LeaveTypeId = typeId,
@ -217,110 +162,36 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
Child3DnaId = pf.Child3DnaId, Child3DnaId = pf.Child3DnaId,
Child4DnaId = pf.Child4DnaId Child4DnaId = pf.Child4DnaId
}; };
}
return await GetOrAddForUserAsync(year, typeId, pf.Id, Factory); _dbContext.Set<LeaveBeginning>().Add(data);
}
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUserWithUpdateAsync(int year, Guid typeId, Guid userId)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
var govAge = (pf?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date);
var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId);
var limit = 0.0;
var prev = _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType)
.FirstOrDefault(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
var prevRemain = 0.0;
if (prev != null)
{
prevRemain = prev.LeaveDays - (prev.LeaveDaysUsed ?? 0.0);
}
if (govAge >= 180)
{
if (govAge >= 3650)
{
limit = 10 + prevRemain;
if (limit > 30) limit = 30;
}
else
{
limit = 10 + prevRemain;
if (limit > 20) limit = 20;
}
}
else
{
limit = 0.0;
}
var data = await _dbContext.Set<LeaveBeginning>()
.Where(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == pf.Id)
.FirstOrDefaultAsync();
if (data != null)
{
data.LeaveDays = leaveType?.Code == "LV-005" ? limit : 0;
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
} }
// return new LeaveBeginning
// {
// LeaveYear = year,
// LeaveTypeId = typeId,
// ProfileId = pf.Id,
// Prefix = pf.Prefix,
// FirstName = pf.FirstName,
// LastName = pf.LastName,
// LeaveDaysUsed = 0,
// LeaveDays = leaveType?.Code == "LV-005" ? limit : 0,
// RootDnaId = pf.RootDnaId,
// Child1DnaId = pf.Child1DnaId,
// Child2DnaId = pf.Child2DnaId,
// Child3DnaId = pf.Child3DnaId,
// Child4DnaId = pf.Child4DnaId
// };
return data; return data;
} }
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUser(int year, Guid typeId, GetProfileByKeycloakIdDto? pf) public async Task<LeaveBeginning?> GetByYearAndTypeIdForUser(int year, Guid typeId, GetProfileByKeycloakIdDto? pf)
{ {
var govAge = (pf?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date); var govAge = (pf?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date);
var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId); var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId);
LeaveBeginning Factory() var data = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType)
.FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
if (data == null)
{ {
var limit = 0.0; var limit = 0.0;
var prev = _dbContext.Set<LeaveBeginning>() var prev = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType) .Include(x => x.LeaveType)
.FirstOrDefault(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id); .FirstOrDefaultAsync(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
// คำนวณปีงบประมาณจาก startDate (ปีงบประมาณเริ่ม 1 ต.ค. และสิ้นสุด 30 ก.ย.)
var isCurrentYear = DateTime.Now.Year == year;
var prevRemain = 0.0; var prevRemain = 0.0;
if (prev != null) if (prev != null)
{ {
prevRemain = isCurrentYear ? prev.LeaveDays - (prev.LeaveDaysUsed ?? 0.0) : 0.0; prevRemain = prev.LeaveDays - prev.LeaveDaysUsed;
} }
if (govAge >= 180) if (govAge >= 180)
@ -341,7 +212,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
limit = 0.0; limit = 0.0;
} }
return new LeaveBeginning data = new LeaveBeginning
{ {
LeaveYear = year, LeaveYear = year,
LeaveTypeId = typeId, LeaveTypeId = typeId,
@ -357,15 +228,17 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
Child3DnaId = pf.Child3DnaId, Child3DnaId = pf.Child3DnaId,
Child4DnaId = pf.Child4DnaId Child4DnaId = pf.Child4DnaId
}; };
_dbContext.Set<LeaveBeginning>().Add(data);
await _dbContext.SaveChangesAsync();
} }
return await GetOrAddForUserAsync(year, typeId, pf.Id, Factory); return data;
} }
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUser2Async(int year, Guid typeId, Guid userId) public async Task<LeaveBeginning?> GetByYearAndTypeIdForUser2Async(int year, Guid typeId, Guid userId)
{ {
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null) if (pf == null)
{ {
return null; return null;
@ -375,21 +248,22 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId); var leaveType = await _dbContext.Set<LeaveType>().FirstOrDefaultAsync(x => x.Id == typeId);
LeaveBeginning Factory() var data = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType)
.FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
if (data == null)
{ {
var limit = 0.0; var limit = 0.0;
var prev = _dbContext.Set<LeaveBeginning>() var prev = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType) .Include(x => x.LeaveType)
.FirstOrDefault(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id); .FirstOrDefaultAsync(x => x.LeaveYear == year - 1 && x.LeaveTypeId == typeId && x.ProfileId == pf.Id);
// คำนวณปีงบประมาณจาก startDate (ปีงบประมาณเริ่ม 1 ต.ค. และสิ้นสุด 30 ก.ย.)
var isCurrentYear = DateTime.Now.Year == year;
var prevRemain = 0.0; var prevRemain = 0.0;
if (prev != null) if (prev != null)
{ {
prevRemain = isCurrentYear ? prev.LeaveDays - (prev.LeaveDaysUsed ?? 0.0) : 0.0; prevRemain = prev.LeaveDays - prev.LeaveDaysUsed;
} }
if (govAge >= 180) if (govAge >= 180)
@ -410,7 +284,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
limit = 0.0; limit = 0.0;
} }
return new LeaveBeginning data = new LeaveBeginning
{ {
LeaveYear = year, LeaveYear = year,
LeaveTypeId = typeId, LeaveTypeId = typeId,
@ -426,60 +300,18 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
Child3DnaId = pf.Child3DnaId, Child3DnaId = pf.Child3DnaId,
Child4DnaId = pf.Child4DnaId Child4DnaId = pf.Child4DnaId
}; };
_dbContext.Set<LeaveBeginning>().Add(data);
await _dbContext.SaveChangesAsync();
} }
return await GetOrAddForUserAsync(year, typeId, pf.Id, Factory); return data;
}
/// <summary>
/// Get-or-create a LeaveBeginning row for (ProfileId, LeaveYear, LeaveTypeId) with concurrency protection.
/// Uses a keyed SemaphoreSlim to serialize within-process requests, and re-queries after acquiring the lock.
/// If a cross-process insert wins (unique index violation), the duplicate key exception is caught and the row
/// created by the winner is returned.
/// </summary>
private async Task<LeaveBeginning?> GetOrAddForUserAsync(int year, Guid typeId, Guid profileId, Func<LeaveBeginning> factory)
{
var key = $"{profileId}_{year}_{typeId}";
var semaphore = _getOrAddLocks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync();
try
{
// Re-query inside the lock — another thread may have created it while we waited.
var existing = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType)
.FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == profileId);
if (existing != null)
{
return existing;
}
var entity = factory();
_dbContext.Set<LeaveBeginning>().Add(entity);
try
{
await _dbContext.SaveChangesAsync();
return entity;
}
catch (DbUpdateException)
{
// Cross-process/cross-server race hit the unique index (IX_LeaveBeginnings_ProfileId_LeaveYear_LeaveTypeId).
// Detach the failed insert and return the row created by the winner.
_dbContext.Detach(entity);
var winner = await _dbContext.Set<LeaveBeginning>()
.Include(x => x.LeaveType)
.FirstOrDefaultAsync(x => x.LeaveYear == year && x.LeaveTypeId == typeId && x.ProfileId == profileId);
return winner;
}
}
finally
{
semaphore.Release();
}
} }
public async Task<List<LeaveBeginning>> GetAllByYearAndTypeAsync(int year, Guid typeId, List<ProfileData> userIdList) public async Task<List<LeaveBeginning>> GetAllByYearAndTypeAsync(int year, Guid typeId, List<ProfileData> userIdList)
{ {
var updateList = new List<LeaveBeginning>(); var updateList = new List<LeaveBeginning>();
var result = new List<LeaveBeginning>(); var result = new List<LeaveBeginning>();
@ -519,7 +351,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var prevRemain = 0.0; var prevRemain = 0.0;
if (prev != null) if (prev != null)
{ {
prevRemain = prev.LeaveDays - (prev.LeaveDaysUsed ?? 0.0); prevRemain = prev.LeaveDays - prev.LeaveDaysUsed;
} }
if (govAge >= 180) if (govAge >= 180)
@ -581,7 +413,5 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public string LastName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty;
public DateTime? DateStart { get; set; } = null; public DateTime? DateStart { get; set; } = null;
public DateTime? DateAppoint { get; set; } = null;
} }
} }

View file

@ -11,8 +11,6 @@ using Microsoft.Extensions.Configuration;
using System.IO.Compression; using System.IO.Compression;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Http.Json; using System.Net.Http.Json;
using BMA.EHR.Application.Repositories.Leaves.TimeAttendants;
using BMA.EHR.Domain.Models.Leave.TimeAttendants;
namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
{ {
@ -31,7 +29,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
private readonly MinIOLeaveService _minIOService; private readonly MinIOLeaveService _minIOService;
private readonly LeaveBeginningRepository _leaveBeginningRepository; private readonly LeaveBeginningRepository _leaveBeginningRepository;
private readonly ProcessUserTimeStampRepository _processUserTimeStampRepository;
private readonly string URL = string.Empty; private readonly string URL = string.Empty;
@ -47,8 +44,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
EmailSenderService emailSenderService, EmailSenderService emailSenderService,
IApplicationDBContext appDbContext, IApplicationDBContext appDbContext,
MinIOLeaveService minIOService, MinIOLeaveService minIOService,
LeaveBeginningRepository leaveBeginningRepository, LeaveBeginningRepository leaveBeginningRepository) : base(dbContext, httpContextAccessor)
ProcessUserTimeStampRepository processUserTimeStampRepository) : base(dbContext, httpContextAccessor)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
@ -62,7 +58,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
Console.WriteLine($"URL : {URL}"); Console.WriteLine($"URL : {URL}");
_minIOService = minIOService; _minIOService = minIOService;
_leaveBeginningRepository = leaveBeginningRepository; _leaveBeginningRepository = leaveBeginningRepository;
_processUserTimeStampRepository = processUserTimeStampRepository;
} }
#endregion #endregion
@ -258,8 +253,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<List<LeaveRequest>> GetLeaveRequestByYearAsync(int year, Guid userId) public async Task<List<LeaveRequest>> GetLeaveRequestByYearAsync(int year, Guid userId)
{ {
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null) if (profile == null)
{ {
@ -312,11 +306,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)); .Where(x => x.RootDnaId == Guid.Parse(nodeId!));
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// rawData = rawData rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
rawData = rawData rawData = rawData
@ -359,7 +353,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking() var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
.Include(x => x.Type) .Include(x => x.Type)
.Where(x => x.LeaveStatus != "DRAFT") .Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt)) .OrderByDescending(x => x.CreatedAt)
.AsQueryable(); .AsQueryable();
if (year != 0) if (year != 0)
@ -385,7 +379,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking() var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
.Include(x => x.Type) .Include(x => x.Type)
.Where(x => x.LeaveStatus != "DRAFT") .Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt)) .OrderByDescending(x => x.CreatedAt)
.AsQueryable(); .AsQueryable();
// fix issue : 1830 // fix issue : 1830
if (year != 0) if (year != 0)
@ -426,11 +420,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)); .Where(x => x.RootDnaId == Guid.Parse(nodeId!));
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// rawData = rawData rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
rawData = rawData rawData = rawData
@ -452,7 +446,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Include(x => x.Type) .Include(x => x.Type)
.Where(x => keycloakIdList.Contains(x.KeycloakUserId)) .Where(x => keycloakIdList.Contains(x.KeycloakUserId))
.Where(x => x.LeaveStatus != "DRAFT") .Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x =>(x.DateSendLeave ?? x.CreatedAt)) .OrderByDescending(x => x.CreatedAt)
.AsQueryable(); .AsQueryable();
if (year != 0) if (year != 0)
@ -501,8 +495,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<double> GetSumLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year) public async Task<double> GetSumLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year)
{ {
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(keycloakUserId, AccessToken); var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(keycloakUserId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(keycloakUserId, AccessToken);
if (pf == null) if (pf == null)
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -527,7 +520,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
//.Where(x => x.LeaveStatus != "REJECT" && x.LeaveStatus != "DELETE") //.Where(x => x.LeaveStatus != "REJECT" && x.LeaveStatus != "DELETE")
.ToListAsync(); .ToListAsync();
return data.Sum(x => x.LeaveTotal) + (beginningLeave == null ? 0 : (beginningLeave.LeaveDaysUsed ?? 0.0)); return data.Sum(x => x.LeaveTotal) + (beginningLeave == null ? 0 : beginningLeave.LeaveDaysUsed);
} }
//public async Task<double> GetSumApproveLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year) //public async Task<double> GetSumApproveLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year)
@ -563,7 +556,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking() var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type) .Include(x => x.Type)
.Where(x => x.LeaveStartDate.Date < beforeDate.Date) .Where(x => x.LeaveStartDate.Date < beforeDate.Date)
//.Where(x => x.CreatedAt < beforeDate)
.Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId) .Where(x => x.Type.Id == leaveTypeId)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
@ -574,22 +566,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
return data; return data;
} }
public async Task<LeaveRequest?> GetLastLeaveRequestByTypeForUserAsync2(Guid keycloakUserId, Guid leaveTypeId, DateTime beforeDate)
{
var data = await _dbContext.Set<LeaveRequest>().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<List<LeaveRequest>> GetCancelLeaveRequestForAdminAsync(int year, Guid type, string status, string role, string? nodeId, int? node) public async Task<List<LeaveRequest>> GetCancelLeaveRequestForAdminAsync(int year, Guid type, string status, string role, string? nodeId, int? node)
{ {
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking() var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
@ -632,11 +608,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)); .Where(x => x.RootDnaId == Guid.Parse(nodeId!));
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// rawData = rawData rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
rawData = rawData rawData = rawData
@ -655,8 +631,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
{ {
try try
{ {
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(data.KeycloakUserId, AccessToken ?? ""); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(data.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken ?? "");
if (profile == null) if (profile == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -681,9 +656,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
thisYear = thisYear + 1; thisYear = thisYear + 1;
} }
await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, data.Type.Id, data.KeycloakUserId, -1 * data.LeaveTotal); 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 _baseAPI = _configuration["API"];
var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{data.Id}"; var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{data.Id}";
@ -732,8 +704,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
} }
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? ""); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? "");
if (profile == null) if (profile == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -758,8 +729,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
} }
await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, -1 * rawData.LeaveTotal); await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, -1 * rawData.LeaveTotal);
// update leave count ลดลง 1 ครั้ง
await _leaveBeginningRepository.UpdateLeaveCountAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, -1);
var _baseAPI = _configuration["API"]; var _baseAPI = _configuration["API"];
var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{rawData.Id}"; var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{rawData.Id}";
@ -821,8 +790,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
} }
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? ""); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? "");
if (profile == null) if (profile == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -909,7 +877,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData.LeaveStatus = "NEW"; rawData.LeaveStatus = "NEW";
rawData.DateSendLeave = DateTime.Now; // Update วันที่ยื่นลาเป็นวันที่ปัจจุบัน
//rawData.ApproveStep = "st2"; //rawData.ApproveStep = "st2";
await UpdateAsync(rawData); await UpdateAsync(rawData);
@ -1247,8 +1214,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
} }
else else
{ {
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken);
if (profile == null) if (profile == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -1269,8 +1235,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
// TODO : Update ไปตาราง beginning // TODO : Update ไปตาราง beginning
await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, rawData.LeaveTotal); await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, rawData.LeaveTotal);
// update leave count เพิ่มขึ้น 1 ครั้ง
await _leaveBeginningRepository.UpdateLeaveCountAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId, 1);
var _baseAPI = _configuration["API"]; var _baseAPI = _configuration["API"];
@ -1294,8 +1258,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
status = "approve", status = "approve",
reason = rawData.LeaveDetail, reason = rawData.LeaveDetail,
leaveId = rawData.Id, leaveId = rawData.Id,
leaveSubTypeName = rawData.LeaveSubTypeName,
coupleDayLevelCountry = rawData.CoupleDayLevelCountry,
}); });
// var _result = await _res.Content.ReadAsStringAsync(); // var _result = await _res.Content.ReadAsStringAsync();
} }
@ -1319,8 +1281,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
status = "approve", status = "approve",
reason = rawData.LeaveDetail, reason = rawData.LeaveDetail,
leaveId = rawData.Id, leaveId = rawData.Id,
leaveSubTypeName = rawData.LeaveSubTypeName,
coupleDayLevelCountry = rawData.CoupleDayLevelCountry,
}); });
} }
} }
@ -1330,68 +1290,9 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
} }
await _appDbContext.SaveChangesAsync(); await _appDbContext.SaveChangesAsync();
// ปรับสถานะการลงเวลา // insert to process timestamp
if (rawData.LeaveStartDate.Date == rawData.LeaveEndDate.Date)
{
var processCheckIn = await _dbContext.Set<ProcessUserTimeStamp>()
.Where(x => x.KeycloakUserId == rawData.KeycloakUserId)
.Where(x => x.CheckIn.Date == rawData.LeaveStartDate.Date)
.FirstOrDefaultAsync();
if (processCheckIn is not null)
{
switch (rawData.LeaveRange.Trim().ToUpper())
{
case "MORNING":
processCheckIn.CheckInStatus = "NORMAL";
break;
case "AFTERNOON":
processCheckIn.CheckOutStatus = "NORMAL";
break;
case "ALL":
processCheckIn.CheckInStatus = "NORMAL";
processCheckIn.CheckOutStatus = "NORMAL";
break;
default:
break;
}
}
await _dbContext.SaveChangesAsync();
}
else
{
var from = rawData.LeaveStartDate.Date;
var to = rawData.LeaveEndDate.Date;
for (var day = from.Date; day <= to.Date; day = day.AddDays(1))
{
var processCheckIn = await _dbContext.Set<ProcessUserTimeStamp>()
.Where(x => x.KeycloakUserId == rawData.KeycloakUserId)
.Where(x => x.CheckIn.Date == day.Date)
.FirstOrDefaultAsync();
if (processCheckIn is not null)
{
switch (rawData.LeaveRange.Trim().ToUpper())
{
case "MORNING":
processCheckIn.CheckInStatus = "NORMAL";
break;
case "AFTERNOON":
processCheckIn.CheckOutStatus = "NORMAL";
break;
case "ALL":
processCheckIn.CheckInStatus = "NORMAL";
processCheckIn.CheckOutStatus = "NORMAL";
break;
default:
break;
}
}
}
await _dbContext.SaveChangesAsync();
}
// Send Noti // Send Noti
var noti = new Notification var noti = new Notification
{ {
@ -1476,8 +1377,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
} }
else else
{ {
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken);
if (profile == null) if (profile == null)
{ {
throw new Exception(GlobalMessages.DataNotFound); throw new Exception(GlobalMessages.DataNotFound);
@ -1550,7 +1450,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
KeycloakUserId = pf.Keycloak == null ? Guid.Empty : pf.Keycloak.Value, KeycloakUserId = pf.Keycloak == null ? Guid.Empty : pf.Keycloak.Value,
LeaveTypeId = b.LeaveTypeId, LeaveTypeId = b.LeaveTypeId,
LeaveTypeCode = b.LeaveType!.Code, LeaveTypeCode = b.LeaveType!.Code,
SumLeaveDay = b.LeaveDaysUsed ?? 0.0 SumLeaveDay = b.LeaveDaysUsed
}); });
} }
} }
@ -1764,10 +1664,10 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
{ {
data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList(); data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data = data.Where(x => data = data.Where(x =>
@ -1783,7 +1683,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT") if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT")
{ {
data = data data = data
.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) .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)
.ToList(); .ToList();
} }
// รายงานการลางานจำแนกตามเพศฯ Template ให้หน่วยงานแสดงก่อนส่วนราชการ // รายงานการลางานจำแนกตามเพศฯ Template ให้หน่วยงานแสดงก่อนส่วนราชการ
@ -1924,7 +1824,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Include(x => x.Type) .Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId) .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.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING") .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync(); .ToListAsync();
@ -1935,139 +1834,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
return 0; return 0;
} }
public async Task<double> GetSumApproveLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate, DateTime sendLeaveDate)
{
// startDate/endDate คือขอบเขตปีงบประมาณ (fiscalStart/fiscalEnd) ที่ caller ส่งมา
// ใช้ LeaveStartDate เป็นหลักในการ filter เพื่อให้กรณียื่นลาล่วงหน้าข้ามปีงบประมาณ
// ถูกนับในปีงบประมาณของวันลาจริง (ไม่ใช้วันที่ยื่นลา)
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.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<double> GetSumApproveLeaveTotalByTypeAndRangeForUserBefore(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate,DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.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<double> GetSumApproveLeaveTotalByTypeAndRangeForUserByProfile(Guid profileId, Guid leaveTypeId, DateTime startDate, DateTime endDate,DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.ProfileId == profileId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.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<int> GetSumApproveLeaveCountByTypeAndRangeForUserByProfile(Guid profileId, Guid leaveTypeId, DateTime startDate, DateTime endDate, DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.ProfileId == profileId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync();
return data.Count;
}
public async Task<int> GetSumApproveLeaveCountByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate, DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync();
return data.Count;
}
/// <summary>
/// วันลาที่สร้างแบบร่างยังไม่ได้ยื่น
/// </summary>
/// <param name="keycloakUserId"></param>
/// <param name="leaveTypeId"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="sendLeaveDate"></param>
/// <returns></returns>
public async Task<double> GetSumDraftLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate, DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.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;
}
/// <summary>
/// วันลาที่ยื่นแล้วรอพิจารณา
/// </summary>
/// <param name="keycloakUserId"></param>
/// <param name="leaveTypeId"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public async Task<double> GetSumNewLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate,DateTime sendLeaveDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => (x.DateSendLeave ?? x.CreatedAt) < sendLeaveDate)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => (x.LeaveStatus == "NEW" || x.LeaveStatus == "PENDING"))
.ToListAsync();
if (data.Count > 0)
return data.Sum(x => x.LeaveTotal);
else
return 0;
}
public async Task<int> GetCountApproveLeaveByTypeAndRangeForUser(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate) public async Task<int> GetCountApproveLeaveByTypeAndRangeForUser(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate)
{ {
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking() var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
@ -2075,7 +1841,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Where(x => x.KeycloakUserId == keycloakUserId) .Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId) .Where(x => x.Type.Id == leaveTypeId)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date) .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") .Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync(); .ToListAsync();

View file

@ -74,8 +74,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
await base.AddAsync(entity); await base.AddAsync(entity);
var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty; var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty;
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken ?? ""); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken ?? "");
// fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลากรณีพิเศษ (ไม่มีแจ้งเตือนไปยังผู้บังคับบัญชา) #969 // fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลากรณีพิเศษ (ไม่มีแจ้งเตือนไปยังผู้บังคับบัญชา) #969
// send noti + inbox + mail // send noti + inbox + mail
@ -145,7 +144,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
} }
} }
public async Task<List<AdditionalCheckRequest>> GetAdditionalCheckRequestsByAdminRole(int year, int month, string role, string nodeId, int? node, string? keyword) public async Task<List<AdditionalCheckRequest>> GetAdditionalCheckRequestsByAdminRole(int year, int month, string role, string nodeId, int? node)
{ {
try try
{ {
@ -153,17 +152,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
.Where(x => (x.CheckDate.Year == year && x.CheckDate.Month == month)) .Where(x => (x.CheckDate.Year == year && x.CheckDate.Month == month))
.OrderByDescending(x => x.CreatedAt.Date) .OrderByDescending(x => x.CreatedAt.Date)
.ToListAsync(); .ToListAsync();
if (!string.IsNullOrEmpty(keyword))
{
data = data.Where(x =>
(
(x.Prefix ?? "") + (x.FirstName ?? "") + " " + (x.LastName ?? "")).Contains(keyword)
|| x.Description.Contains(keyword)
).ToList();
}
if (role == "OWNER") if (role == "OWNER")
{ {
node = null; node = null;
@ -185,11 +173,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
data = data data = data
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data = data data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data = data.Where(x => data = data.Where(x =>
@ -213,79 +201,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
} }
} }
public async Task<List<AdditionalCheckRequest>> GetAdditionalCheckRequestsByAdminRole2(DateTime startDate, DateTime endDate, string role, string nodeId, int? node, string? keyword, string? status)
{
try
{
var data = await _dbContext.Set<AdditionalCheckRequest>().AsQueryable()
.Where(x => (x.CheckDate.Date >= startDate.Date && x.CheckDate.Date <= endDate.Date))
.OrderByDescending(x => x.CreatedAt.Date)
.ToListAsync();
if(!string.IsNullOrEmpty(status))
data = data.Where(x => x.Status == status).ToList();
if (!string.IsNullOrEmpty(keyword))
{
data = data.Where(x =>
(
(x.Prefix ?? "") + (x.FirstName ?? "") + " " + (x.LastName ?? "")).Contains(keyword)
|| x.Description.Contains(keyword)
).ToList();
}
if (role == "OWNER")
{
node = null;
}
if (role == "OWNER" || role == "CHILD")
{
data = data
.Where(x => node == 4 ? x.Child4DnaId == Guid.Parse(nodeId!) : (node == 3 ? x.Child3DnaId == Guid.Parse(nodeId!) : (node == 2 ? x.Child2DnaId == Guid.Parse(nodeId!) : (node == 1 ? x.Child1DnaId == Guid.Parse(nodeId!) : (node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) : (node == null ? true : true))))))
.ToList();
}
else if (role == "BROTHER")
{
data = data
.Where(x => node == 4 ? x.Child3DnaId == Guid.Parse(nodeId!) : (node == 3 ? x.Child2DnaId == Guid.Parse(nodeId!) : (node == 2 ? x.Child1DnaId == Guid.Parse(nodeId!) : (node == 1 || node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) : (node == null ? true : true)))))
.ToList();
}
else if (role == "ROOT")
{
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 == "NORMAL")
{
data = data.Where(x =>
node == 0 ? x.RootDnaId == Guid.Parse(nodeId!) &&
(x.Child1DnaId == Guid.Empty || x.Child1DnaId == null) :
node == 1 ? x.Child1DnaId == Guid.Parse(nodeId!) &&
(x.Child2DnaId == Guid.Empty || x.Child2DnaId == null) :
node == 2 ? x.Child2DnaId == Guid.Parse(nodeId!) &&
(x.Child3DnaId == Guid.Empty || x.Child3DnaId == null) :
node == 3 ? x.Child3DnaId == Guid.Parse(nodeId!) &&
(x.Child4DnaId == Guid.Empty || x.Child4DnaId == null) :
node == 4 ? x.Child4DnaId == Guid.Parse(nodeId!) :
true
).ToList();
}
return data;
}
catch
{
throw;
}
}
#endregion #endregion
} }
} }

View file

@ -64,17 +64,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return data; return data;
} }
public async Task<List<CheckInJobStatus>> GetPendingOrProcessingJobsByDateAsync(DateTime date)
{
var data = await _dbContext.Set<CheckInJobStatus>()
.Where(x => x.CreatedDate.Date == date.Date &&
(x.Status == "PENDING" || x.Status == "PROCESSING"))
.OrderByDescending(x => x.CreatedDate)
.ToListAsync();
return data;
}
/// <summary> /// <summary>
/// อัปเดตสถานะเป็น Processing /// อัปเดตสถานะเป็น Processing
/// </summary> /// </summary>
@ -125,62 +114,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return job!; return job!;
} }
/// <summary>
/// ดึงข้อมูลงานที่ค้างอยู่ในสถานะ PENDING หรือ PROCESSING เกินเวลาที่กำหนด (นาที)
/// </summary>
public async Task<List<CheckInJobStatus>> GetStalePendingOrProcessingJobsAsync(int timeoutMinutes = 30)
{
//var cutoffDate = DateTime.Now.AddMinutes(-timeoutMinutes);
var cutoffDate = DateTime.Now.AddMinutes(-timeoutMinutes);
var staleJobs = await _dbContext.Set<CheckInJobStatus>()
.Where(x => (x.Status == "PENDING" || x.Status == "PROCESSING")
&& x.CreatedDate <= cutoffDate)
.OrderBy(x => x.CreatedDate)
.ToListAsync();
return staleJobs;
}
/// <summary>
/// ดึงข้อมูลงานที่ค้างอยู่ในสถานะ PENDING หรือ PROCESSING เกินเวลาที่กำหนด (นาที) ของ user คนใดคนหนึ่ง
/// </summary>
public async Task<List<CheckInJobStatus>> GetStalePendingOrProcessingJobsByUserAsync(Guid userId, int timeoutMinutes = 30)
{
var cutoffDate = DateTime.Now.AddMinutes(-timeoutMinutes);
//var cutoffDate = new DateTime(2026, 5, 28, 23, 59, 59);
var staleJobs = await _dbContext.Set<CheckInJobStatus>()
.Where(x => x.KeycloakUserId == userId
&& (x.Status == "PENDING" || x.Status == "PROCESSING")
&& x.CreatedDate < cutoffDate)
.OrderBy(x => x.CreatedDate)
.ToListAsync();
return staleJobs;
}
/// <summary>
/// Mark งานที่ค้างเกินเวลาที่กำหนดเป็น FAILED
/// </summary>
public async Task<int> MarkStaleJobsAsFailedAsync(int timeoutMinutes = 30)
{
var staleJobs = await GetStalePendingOrProcessingJobsAsync(timeoutMinutes);
foreach (var job in staleJobs)
{
job.Status = "FAILED";
job.CompletedDate = DateTime.Now;
job.ErrorMessage = $"งานค้างในสถานะ {job.Status} เกิน {timeoutMinutes} นาที ระบบทำเครื่องหมายเป็น FAILED อัตโนมัติ";
}
if (staleJobs.Any())
{
_dbContext.Set<CheckInJobStatus>().UpdateRange(staleJobs);
await _dbContext.SaveChangesAsync();
}
return staleJobs.Count;
}
/// <summary> /// <summary>
/// ล้างข้อมูล Job Status ที่เก่าเกิน X วัน /// ล้างข้อมูล Job Status ที่เก่าเกิน X วัน
/// </summary> /// </summary>

View file

@ -61,12 +61,9 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return await _dbContext.Set<DutyTime>().Where(x => x.IsActive).ToListAsync(); return await _dbContext.Set<DutyTime>().Where(x => x.IsActive).ToListAsync();
} }
public async Task<DutyTime?> GetDefaultAsync(CancellationToken cancellationToken = default) public async Task<DutyTime?> GetDefaultAsync()
{ {
// กำหนด timeout เป็น 30 นาที return await _dbContext.Set<DutyTime>().Where(x => x.IsDefault).FirstOrDefaultAsync();
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
return await _dbContext.Set<DutyTime>().Where(x => x.IsDefault).FirstOrDefaultAsync(combinedCts.Token);
} }
#endregion #endregion

View file

@ -1,795 +0,0 @@
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<Guid, LeaveProcessJobStatus>
{
#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 "
/// <summary>
/// ดึงข้อมูล Job Status จาก TaskId
/// </summary>
public async Task<LeaveProcessJobStatus?> GetByTaskIdAsync(Guid id)
{
var data = await _dbContext.Set<LeaveProcessJobStatus>()
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
return data;
}
/// <summary>
/// ดึงข้อมูล Job Status จาก UserId และสถานะ
/// </summary>
public async Task<List<LeaveProcessJobStatus>> GetByUserIdAndStatusAsync(Guid userId, string status)
{
var data = await _dbContext.Set<LeaveProcessJobStatus>()
.Where(x => x.CreatedUserId == userId.ToString("D") && x.Status == status)
.OrderByDescending(x => x.CreatedDate)
.ToListAsync();
return data;
}
/// <summary>
/// ดึงข้อมูล Job Status จาก UserId
/// </summary>
public async Task<List<LeaveProcessJobStatus>> GetByUserIdAsync(Guid userId)
{
var data = await _dbContext.Set<LeaveProcessJobStatus>()
.Where(x => x.CreatedUserId == userId.ToString("D"))
.OrderByDescending(x => x.CreatedDate)
.ToListAsync();
return data;
}
/// <summary>
/// ดึงข้อมูล Job Status ที่ยัง pending หรือ processing
/// </summary>
public async Task<List<LeaveProcessJobStatus>> GetPendingOrProcessingJobsAsync(Guid userId)
{
var data = await _dbContext.Set<LeaveProcessJobStatus>()
.Where(x => x.CreatedUserId == userId.ToString("D") &&
(x.Status == "PENDING" || x.Status == "PROCESSING"))
//.OrderByDescending(x => x.CreatedDate)
.ToListAsync();
return data;
}
public async Task<List<LeaveProcessJobStatus>> GetPendingJobsAsync()
{
var data = await _dbContext.Set<LeaveProcessJobStatus>()
.Where(x => x.Status == "PENDING")
.ToListAsync();
return data;
}
/// <summary>
/// อัปเดตสถานะเป็น Processing
/// </summary>
public async Task<LeaveProcessJobStatus> UpdateToProcessingAsync(Guid id)
{
var job = await GetByTaskIdAsync(id);
if (job != null)
{
job.Status = "PROCESSING";
job.ProcessingDate = DateTime.Now;
await UpdateAsync(job);
}
return job!;
}
/// <summary>
/// อัปเดตสถานะเป็น Completed
/// </summary>
public async Task<LeaveProcessJobStatus> 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!;
}
/// <summary>
/// อัปเดตสถานะเป็น Failed
/// </summary>
public async Task<LeaveProcessJobStatus> 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<GetProfileByKeycloakIdRootDto>();
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<LoopDate>();
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<DateResultReport>();
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<GetProfileByKeycloakIdRootDto>();
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<LoopDate>();
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<DateResultReport>();
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; }
}
}

View file

@ -172,10 +172,10 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
{ {
data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList(); data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList(); data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data = data.Where(x => 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") if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT")
{ {
data = data.Where(x => data = data.Where(x =>
nodeByReq == 4 ? x.Child4DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 4 ? x.Child4Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 3 ? x.Child3DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 3 ? x.Child3Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 2 ? x.Child2DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 2 ? x.Child2Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 1 ? x.Child1DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 1 ? x.Child1Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 0 ? x.RootDnaId == Guid.Parse(nodeIdByReq) : true nodeByReq == 0 ? x.RootId == Guid.Parse(nodeIdByReq) : true
).ToList(); ).ToList();
} }
return data; return data;
@ -227,19 +227,6 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return data; return data;
} }
public async Task<List<ProcessUserTimeStamp>> 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<ProcessUserTimeStamp>()
.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<int> GetTimeStampHistoryForAdminCountAsync(DateTime startDate, DateTime endDate) public async Task<int> GetTimeStampHistoryForAdminCountAsync(DateTime startDate, DateTime endDate)
{ {
var data = await _dbContext.Set<ProcessUserTimeStamp>() var data = await _dbContext.Set<ProcessUserTimeStamp>()
@ -301,12 +288,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)) .Where(x => x.RootDnaId == Guid.Parse(nodeId!))
.ToList(); .ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data = data data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
// .ToList(); .ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data = data.Where(x => data = data.Where(x =>

View file

@ -101,17 +101,14 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return data; return data;
} }
public async Task<UserDutyTime?> GetLastEffectRound(Guid profileId, DateTime? effectiveDate = null, CancellationToken cancellationToken = default) public async Task<UserDutyTime?> GetLastEffectRound(Guid profileId, DateTime? effectiveDate = null)
{ {
// กำหนด timeout เป็น 30 นาที
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
effectiveDate ??= DateTime.Now; effectiveDate ??= DateTime.Now;
var data = await _dbContext.Set<UserDutyTime>() var data = await _dbContext.Set<UserDutyTime>()
.Where(x => x.ProfileId == profileId) .Where(x => x.ProfileId == profileId)
.Where(x => x.EffectiveDate.Value.Date <= effectiveDate.Value.Date) .Where(x => x.EffectiveDate.Value.Date <= effectiveDate.Value.Date)
.OrderByDescending(x => x.EffectiveDate) .OrderByDescending(x => x.EffectiveDate)
.FirstOrDefaultAsync(combinedCts.Token); .FirstOrDefaultAsync();
return data; return data;
} }

View file

@ -74,16 +74,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return data; return data;
} }
public async Task<UserTimeStamp?> GetLastRecord(Guid keycloakId, CancellationToken cancellationToken = default) public async Task<UserTimeStamp?> GetLastRecord(Guid keycloakId)
{ {
// กำหนด timeout เป็น 30 นาที
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
var data = await _dbContext.Set<UserTimeStamp>() var data = await _dbContext.Set<UserTimeStamp>()
.Where(u => u.KeycloakUserId == keycloakId) .Where(u => u.KeycloakUserId == keycloakId)
.OrderByDescending(u => u.CheckIn) .OrderByDescending(u => u.CheckIn)
.FirstOrDefaultAsync(combinedCts.Token); .FirstOrDefaultAsync();
return data; return data;
} }
@ -140,12 +136,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)) .Where(x => x.RootDnaId == Guid.Parse(nodeId!))
.ToList(); .ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data = data data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null) .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
// .ToList(); .ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data = data.Where(x => data = data.Where(x =>

View file

@ -51,8 +51,7 @@ namespace BMA.EHR.Application.Repositories.MessageQueue
// // throw new Exception(GlobalMessages.DataNotFound); // // throw new Exception(GlobalMessages.DataNotFound);
// } // }
//var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position";
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
var profileId = ""; var profileId = "";
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {

View file

@ -55,8 +55,7 @@ namespace BMA.EHR.Application.Repositories.MessageQueue
// // throw new Exception(GlobalMessages.DataNotFound); // // throw new Exception(GlobalMessages.DataNotFound);
// } // }
//var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position";
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
var profileId = ""; var profileId = "";
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
@ -132,8 +131,7 @@ namespace BMA.EHR.Application.Repositories.MessageQueue
// { // {
// return 0; // return 0;
// } // }
//var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position";
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
var profileId = ""; var profileId = "";
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
@ -187,44 +185,6 @@ namespace BMA.EHR.Application.Repositories.MessageQueue
} }
} }
private async Task<string> GetMyProfileIdAsync()
{
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
var response = await GetExternalAPIAsync(apiUrl, AccessToken!, _configuration["API_KEY"]!);
if (string.IsNullOrWhiteSpace(response))
return string.Empty;
var org = JsonConvert.DeserializeObject<OrgRequest>(response);
if (org == null || org.result == null)
return string.Empty;
return org.result.profileId ?? string.Empty;
}
public async Task<int> DeleteAllMyNotificationsAsync()
{
try
{
var profileId = await GetMyProfileIdAsync();
if (string.IsNullOrEmpty(profileId))
return 0;
var notifications = await _dbContext.Set<Notification>()
.Where(x => x.ReceiverUserId == Guid.Parse(profileId))
.Where(x => x.DeleteDate == null)
.ToListAsync();
_dbContext.Set<Notification>().RemoveRange(notifications);
await _dbContext.SaveChangesAsync();
return notifications.Count;
}
catch
{
throw;
}
}
public async Task PushNotificationAsync(Guid ReceiverUserId, string Subject, string Body, string Payload = "", string NotiLink = "", bool IsSendInbox = false, bool IsSendMail = false) public async Task PushNotificationAsync(Guid ReceiverUserId, string Subject, string Body, string Payload = "", string NotiLink = "", bool IsSendInbox = false, bool IsSendMail = false)
{ {
try try

View file

@ -49,16 +49,12 @@ namespace BMA.EHR.Application.Repositories.MetaData
public async Task<int> GetHolidayCountAsync(DateTime startDate, DateTime endDate, string category = "NORMAL") public async Task<int> GetHolidayCountAsync(DateTime startDate, DateTime endDate, string category = "NORMAL")
{ {
var query = _dbContext.Set<Holiday>().AsQueryable() var data = await _dbContext.Set<Holiday>().AsQueryable()
.Where(x => x.Category == category) .Where(x => x.Category == category)
.Where(x => x.HolidayDate.Date >= startDate && x.HolidayDate.Date <= endDate); .Where(x => x.HolidayDate.Date >= startDate && x.HolidayDate.Date <= endDate)
.CountAsync();
if (category == "NORMAL") return data;
query = query.Where(x => x.HolidayDate.DayOfWeek != DayOfWeek.Saturday && x.HolidayDate.DayOfWeek != DayOfWeek.Sunday);
else
query = query.Where(x => x.HolidayDate.DayOfWeek != DayOfWeek.Sunday);
return await query.CountAsync();
} }
public List<DateTime> GetWeekEnd(DateTime startDate, DateTime endDate, string category = "NORMAL") public List<DateTime> GetWeekEnd(DateTime startDate, DateTime endDate, string category = "NORMAL")

View file

@ -10,7 +10,6 @@ using System.Net.Http.Headers;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System.Security.Claims; using System.Security.Claims;
using System.Net.Http.Json; using System.Net.Http.Json;
using BMA.EHR.Application.Responses.Leaves;
namespace BMA.EHR.Application.Repositories namespace BMA.EHR.Application.Repositories
{ {
@ -63,10 +62,6 @@ namespace BMA.EHR.Application.Repositories
new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var req = await client.GetAsync(apiPath); var req = await client.GetAsync(apiPath);
if (!req.IsSuccessStatusCode)
{
throw new Exception("Error calling permission API");
}
var res = await req.Content.ReadAsStringAsync(); var res = await req.Content.ReadAsStringAsync();
return res; return res;
} }
@ -77,39 +72,6 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<GetPermissionWithActingResultDto?> 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<GetPermissionWithActingResultDto>(apiResult);
return raw;
}
return null;
}
}
catch
{
throw;
}
}
public async Task<dynamic> GetPermissionOrgAPIAsync(string action, string system, string profileId) public async Task<dynamic> GetPermissionOrgAPIAsync(string action, string system, string profileId)
{ {
try try

View file

@ -2,40 +2,24 @@
using BMA.EHR.Domain.Models.Placement; using BMA.EHR.Domain.Models.Placement;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace BMA.EHR.Application.Repositories namespace BMA.EHR.Application.Repositories
{ {
/// <summary>
/// Response model จาก Org API (check-isLeave)
/// </summary>
public class OrgProfileResult
{
public string citizenId { get; set; } = "";
public string? profileId { get; set; }
public bool isLeave { get; set; }
public bool isActive { get; set; }
}
public class PlacementRepository : GenericRepository<Guid, Placement> public class PlacementRepository : GenericRepository<Guid, Placement>
{ {
#region " Fields " #region " Fields "
private readonly IApplicationDBContext _dbContext; private readonly IApplicationDBContext _dbContext;
private readonly IHttpContextAccessor _httpContextAccessor; private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
#endregion #endregion
#region " Constructor and Destructor " #region " Constructor and Destructor "
public PlacementRepository(IApplicationDBContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) : base(dbContext, httpContextAccessor) public PlacementRepository(IApplicationDBContext dbContext, IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
_configuration = configuration;
} }
#endregion #endregion
@ -92,148 +76,6 @@ namespace BMA.EHR.Application.Repositories
return data; return data;
} }
/// <summary>
/// Job อัพเดทสถานะผู้สอบผ่านที่ลาออกไปแล้วแต่ยังไม่ส่งไปออกคำสั่ง
/// และอัพเดทบุคคลภายนอกที่เข้ามาอยู่ในระบบแล้ว
/// ทำงานทุกวันเวลา 05:00 น.
/// </summary>
public async Task UpdateStatusPlacementProfiles()
{
Console.WriteLine("[Job:UpdateStatusPlacementProfiles] === STARTED ===");
// 1. Query ทั้ง 2 กรณี: ทุกคนที่ยังไม่ DONE
var allCitizenIds = await _dbContext.Set<PlacementProfile>()
.Where(p => !string.IsNullOrEmpty(p.CitizenId)
&& p.PlacementStatus != "DONE"
// && p.CitizenId == "2536721883131"
)
.Select(p => new { p.CitizenId, p.IsOfficer })
.ToListAsync();
if (!allCitizenIds.Any())
{
Console.WriteLine("[Job:UpdateStatusPlacementProfiles] No profiles to process");
return;
}
var officerCount = allCitizenIds.Count(x => x.IsOfficer == true);
var notOfficerCount = allCitizenIds.Count(x => x.IsOfficer == false);
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] พบข้าราชการ {officerCount} คน, บุคคลภายนอก {notOfficerCount} คน");
// 2. ส่ง citizenIds ทั้งหมดไป Org API ครั้งเดียว
var citizenIds = allCitizenIds.Select(x => x.CitizenId).Distinct().ToList();
var apiUrl = $"{_configuration["API"]}/org/dotnet/check-isLeave";
List<OrgProfileResult> orgResults = new();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var payload = new { citizenIds };
var jsonPayload = JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync(apiUrl, content);
var result = await response.Content.ReadAsStringAsync();
var responseObj = JsonConvert.DeserializeAnonymousType(result, new
{
status = 0,
message = "",
result = new List<OrgProfileResult>()
});
orgResults = responseObj?.result ?? new();
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] Org API ตอบกลับ {orgResults.Count} รายการ");
}
catch (Exception ex)
{
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] Call API failed: {ex.Message}");
return;
}
}
if (!orgResults.Any())
{
Console.WriteLine("[Job:UpdateStatusPlacementProfiles] ไม่มีรายการต้องอัปเดต");
Console.WriteLine("[Job:UpdateStatusPlacementProfiles] === COMPLETED ===");
return;
}
// 3. แยกข้อมูลตามเงื่อนไข
var leaveCitizenIds = orgResults.Where(x => x.isLeave).Select(x => x.citizenId).ToList();
var inSystemProfiles = orgResults.Where(x => x.isActive && !x.isLeave && !string.IsNullOrEmpty(x.profileId)).ToList();
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] ลาออก {leaveCitizenIds.Count} รายการ, อยู่ที่ทะเบียนประวัติ {inSystemProfiles.Count} รายการ");
// 4. Split Batch Update (500 รายการ/batch)
var batchSize = 500;
var totalUpdated = 0;
// 4.1 Update คนลาออก → IsOfficer = false
if (leaveCitizenIds.Any())
{
var totalBatches = (int)Math.Ceiling((double)leaveCitizenIds.Count / batchSize);
for (int i = 0; i < totalBatches; i++)
{
var batch = leaveCitizenIds.Skip(i * batchSize).Take(batchSize).ToList();
var profilesToUpdate = await _dbContext.Set<PlacementProfile>()
.Where(p => !string.IsNullOrEmpty(p.CitizenId)
&& batch.Contains(p.CitizenId)
&& p.IsOfficer == true)
.ToListAsync();
foreach (var profile in profilesToUpdate)
{
profile.profileId = null;
profile.IsOfficer = false;
}
await _dbContext.SaveChangesAsync();
totalUpdated += profilesToUpdate.Count;
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] [ลาออก] Batch {i + 1}/{totalBatches} → อัปเดต {profilesToUpdate.Count} รายการ");
}
}
// 4.2 Update คนที่อยู่ในทะเบียนประวัติ → profileId + IsOfficer = true
if (inSystemProfiles.Any())
{
var totalBatches = (int)Math.Ceiling((double)inSystemProfiles.Count / batchSize);
for (int i = 0; i < totalBatches; i++)
{
var batch = inSystemProfiles.Skip(i * batchSize).Take(batchSize).ToList();
var batchCitizenIds = batch.Select(x => x.citizenId).ToList();
var profilesToUpdate = await _dbContext.Set<PlacementProfile>()
.Where(p => !string.IsNullOrEmpty(p.CitizenId)
&& batchCitizenIds.Contains(p.CitizenId)
&& p.IsOfficer == false)
.ToListAsync();
foreach (var profile in profilesToUpdate)
{
var orgProfile = batch.FirstOrDefault(x => x.citizenId == profile.CitizenId);
if (orgProfile != null)
{
profile.profileId = orgProfile.profileId;
profile.IsOfficer = true;
}
}
await _dbContext.SaveChangesAsync();
totalUpdated += profilesToUpdate.Count;
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] [เข้าระบบ] Batch {i + 1}/{totalBatches} → อัปเดต {profilesToUpdate.Count} รายการ");
}
}
Console.WriteLine($"[Job:UpdateStatusPlacementProfiles] อัปเดตรวมทั้งหมด {totalUpdated} รายการ");
Console.WriteLine("[Job:UpdateStatusPlacementProfiles] === COMPLETED ===");
}
#endregion #endregion
} }
} }

View file

@ -893,7 +893,7 @@ namespace BMA.EHR.Application.Repositories.Reports
select new select new
{ {
RowNo = 1, 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), G1Male = g.Sum(x => x.Gendor == "ชาย" && x.RequestInsigniaName == "เหรียญจักรพรรดิมาลา" ? 1 : 0),
G1Female = 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), G2Male = g.Sum(x => x.Gendor == "ชาย" ? 1 : 0),

View file

@ -192,7 +192,7 @@ namespace BMA.EHR.Application.Repositories.Reports
}).ToList(); }).ToList();
} }
string SignDate = retireHistorys.SignDate != null ? DateTime.Parse(retireHistorys.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-"; string SignDate = retireHistorys.SignDate != null ? DateTime.Parse(retireHistorys.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-";
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 }; 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 };
} }
} }
else else
@ -312,7 +312,7 @@ namespace BMA.EHR.Application.Repositories.Reports
root = (isDuplicateRoot ? "" : profile.root + "\n") + root = (isDuplicateRoot ? "" : profile.root + "\n") +
(isDuplicateHospital || !hospital.ToObject<List<string>>().Contains(profile.child1) ? "" : profile.child1 + "\n") + (isDuplicateHospital || !hospital.ToObject<List<string>>().Contains(profile.child1) ? "" : profile.child1 + "\n") +
(isDuplicatePosType ? "" : $"ตำแหน่งประเภท{profile.posTypeName}" + "\n") + (isDuplicatePosType ? "" : $"ตำแหน่งประเภท{profile.posTypeName}" + "\n") +
(isDuplicatePosLevel ? "" : $"ระดับ{profile.posLevelName}").ToThaiNumber(), (isDuplicatePosLevel ? "" : $"ระดับ{profile.posLevelName}"),
child = (profile.posExecutiveName == null ? "" : profile.posExecutiveName + "\n") + child = (profile.posExecutiveName == null ? "" : profile.posExecutiveName + "\n") +
(profile.child4 == null ? "" : profile.child4 + "\n") + (profile.child4 == null ? "" : profile.child4 + "\n") +
(profile.child3 == null ? "" : profile.child3 + "\n") + (profile.child3 == null ? "" : profile.child3 + "\n") +
@ -326,7 +326,7 @@ namespace BMA.EHR.Application.Repositories.Reports
}).ToList(); }).ToList();
} }
string SignDate = retire.SignDate != null ? DateTime.Parse(retire.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-"; string SignDate = retire.SignDate != null ? DateTime.Parse(retire.SignDate.ToString()).ToThaiFullDate().ToString().ToThaiNumber() : "-";
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 }; 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 };
} }
} }
#endregion #endregion

View file

@ -186,78 +186,6 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<GetProfileByKeycloakIdDto?> GetProfileByKeycloakIdNewAsync(Guid keycloakId, string? accessToken,CancellationToken cancellationToken = default)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/by-keycloak/{keycloakId}";
var apiKey = _configuration["API_KEY"];
var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey, cancellationToken);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetProfileByKeycloakIdResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<GetProfileByKeycloakIdDto?> GetProfileByKeycloakIdNew2Async(Guid keycloakId, string? accessToken)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/by-keycloak2/{keycloakId}";
var apiKey = _configuration["API_KEY"];
var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetProfileByKeycloakIdResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<GetProfileByKeycloakIdDto?> GetProfileByCheckInAsync(Guid keycloakId, string? accessToken)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/check-keycloak/{keycloakId}";
var apiKey = _configuration["API_KEY"];
var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetProfileByKeycloakIdResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<GetProfileLeaveByKeycloakDto?> GetProfileLeaveByKeycloakIdAsync(Guid keycloakId, string? accessToken) public async Task<GetProfileLeaveByKeycloakDto?> GetProfileLeaveByKeycloakIdAsync(Guid keycloakId, string? accessToken)
{ {
try try
@ -281,66 +209,6 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<List<GetOcStaff>?> GetOCStaffAsync(Guid profileId, string? accessToken)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/find-staff";
var apiKey = _configuration["API_KEY"];
var body = new
{
assignId = "SYS_LEAVE_LIST",
profileId = profileId
};
//var profiles = new List<GetOcStaff>();
var apiResult = await PostExternalAPIAsync(apiPath, accessToken ?? "", body, apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetOcStaffResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<GetProfileLeaveByKeycloakDto?> GetProfileLeaveReportByKeycloakIdAsync(Guid keycloakId, string? accessToken, string? report)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/profile-leave/keycloak";
var apiKey = _configuration["API_KEY"];
var body = new
{
keycloakId = keycloakId,
report = report
};
//var profiles = new List<SearchProfileDto>();
var apiResult = await PostExternalAPIAsync(apiPath, accessToken, body, apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetProfileLeaveByKeycloakResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<GetProfileByKeycloakIdDto?> GetProfileByProfileIdAsync(Guid profileId, string? accessToken) public async Task<GetProfileByKeycloakIdDto?> GetProfileByProfileIdAsync(Guid profileId, string? accessToken)
{ {
try try
@ -364,31 +232,6 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<GetProfileByKeycloakIdDto?> 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<GetProfileByKeycloakIdResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return null;
}
catch
{
throw;
}
}
public async Task<bool> UpdateDutyTimeAsync(Guid profileId, Guid roundId, DateTime effectiveDate, string? accessToken) public async Task<bool> UpdateDutyTimeAsync(Guid profileId, Guid roundId, DateTime effectiveDate, string? accessToken)
{ {
try try
@ -787,75 +630,6 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<List<GetProfileByKeycloakIdRootDto>> 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<SearchProfileDto>();
var apiResult = await PostExternalAPIAsync(apiPath, "", body, apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetListProfileByKeycloakIdRootResultDto>(apiResult);
if (raw != null)
return raw.Result;
else
return new List<GetProfileByKeycloakIdRootDto>();
}
else
return new List<GetProfileByKeycloakIdRootDto>();
}
catch
{
throw;
}
}
public async Task<List<GetProfileByKeycloakIdRootDto>> 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<SearchProfileDto>();
var apiResult = await PostExternalAPIAsync(apiPath, "", body, apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetListProfileByKeycloakIdRootResultDto>(apiResult);
if (raw != null)
return raw.Result;
else
return new List<GetProfileByKeycloakIdRootDto>();
}
else
return new List<GetProfileByKeycloakIdRootDto>();
}
catch
{
throw;
}
}
public async Task<List<GetProfileByKeycloakIdRootDto>> GetProfileByAdminRolev4(string? accessToken, int? node, string? nodeId, string role, string? revisionId, int? reqNode, string? reqNodeId, DateTime? startDate, DateTime? endDate) public async Task<List<GetProfileByKeycloakIdRootDto>> GetProfileByAdminRolev4(string? accessToken, int? node, string? nodeId, string role, string? revisionId, int? reqNode, string? reqNodeId, DateTime? startDate, DateTime? endDate)
{ {
try try
@ -1062,43 +836,7 @@ namespace BMA.EHR.Application.Repositories
} }
} }
public async Task<List<GetProfileByKeycloakIdRootDto>> GetEmployeeByAdminRolev2(string? accessToken, int? node, string? nodeId, string role, string? revisionId, int? reqNode, string? reqNodeId, DateTime? startDate, DateTime? endDate) public async Task<GetProfileByKeycloakIdRootAddTotalDto> SearchProfile(string? citizenId, string? firstName, string? lastName, string accessToken, int page, int pageSize, string? role, string? nodeId, int? node)
{
try
{
var apiPath = $"{_configuration["API"]}/org/dotnet/employee-by-admin-rolev2";
var apiKey = _configuration["API_KEY"];
var body = new
{
node = node,
nodeId = nodeId,
role = role,
// isRetirement
reqNode = reqNode,
reqNodeId = reqNodeId,
date = endDate
};
Console.WriteLine(body);
var profiles = new List<SearchProfileDto>();
var apiResult = await PostExternalAPIAsync(apiPath, accessToken, body, apiKey);
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetListProfileByKeycloakIdRootResultDto>(apiResult);
if (raw != null)
return raw.Result;
}
return new List<GetProfileByKeycloakIdRootDto>();
}
catch
{
throw;
}
}
public async Task<GetProfileByKeycloakIdRootAddTotalDto> SearchProfile(string? citizenId, string? firstName, string? lastName, string accessToken, int page, int pageSize, string? role, string? nodeId, int? node,string? selectedNodeId,int? selectedNode )
{ {
try try
{ {
@ -1114,8 +852,6 @@ namespace BMA.EHR.Application.Repositories
node = node, node = node,
page = page, page = page,
pageSize = pageSize, pageSize = pageSize,
selectedNodeId = selectedNodeId,
selectedNode = selectedNode
}; };
var profiles = new List<GetProfileByKeycloakIdRootDto>(); var profiles = new List<GetProfileByKeycloakIdRootDto>();
@ -1318,38 +1054,6 @@ 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<GetOrganizationResponseResultDTO>(apiResult);
if (raw != null && raw.Result != null)
{
return raw.Result;
}
}
return null;
}
catch
{
throw;
}
}
public GetOrganizationResponseDTO? GetOc(Guid ocId, int level, string? accessToken) public GetOrganizationResponseDTO? GetOc(Guid ocId, int level, string? accessToken)
{ {
try try

View file

@ -1,37 +0,0 @@
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<ActingPermission> 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();
}
}

View file

@ -2,27 +2,19 @@
{ {
public class GetProfileLeaveByKeycloakDto public class GetProfileLeaveByKeycloakDto
{ {
public string ProfileType { get; set; }
public string Prefix { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CitizenId { get; set; }
public DateTime BirthDate { get; set; } public DateTime BirthDate { get; set; }
public DateTime RetireDate { get; set; } public DateTime RetireDate { get; set; }
public string GovAge { get; set; } = string.Empty; public string GovAge { get; set; } = string.Empty;
public string Age { get; set; } = string.Empty; public string Age { get; set; } = string.Empty;
public DateTime DateAppoint { get; set; } public DateTime DateAppoint { get; set; }
public DateTime DateCurrent { get; set; } public DateTime DateCurrent { get; set; }
public int? Amount { get; set; } = 0; public int Amount { get; set; }
public string? TelephoneNumber { get; set; } = string.Empty; public string? TelephoneNumber { get; set; } = string.Empty;
public string Position { get; set; } = string.Empty; public string PositionName { get; set; } = string.Empty;
public string PosLevel { get; set; } = string.Empty; public string PosLevel { get; set; } = string.Empty;
public string PosType { get; set; } = string.Empty; public string PosType { get; set; } = string.Empty;
public string? PositionLeaveName { get; set; }
public string? PosExecutiveName { get; set; }
public string CurrentAddress { get; set; } = string.Empty; public string CurrentAddress { get; set; } = string.Empty;
public string Oc { get; set; } = string.Empty; public string Oc { get; set; } = string.Empty;
public bool isCommission { get; set; } = false;
public string Root { get; set; } = string.Empty; public string Root { get; set; } = string.Empty;
public string? Child1 { get; set; } public string? Child1 { get; set; }
public string? Child2 { get; set; } public string? Child2 { get; set; }

View file

@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BMA.EHR.Application.Responses.Profiles
{
public class GetOcStaff
{
public Guid ProfileId { get; set; }
public Guid Keycloak { get; set; }
public string FullName { get; set; } = null!;
public Guid? RootId { get; set; }
public Guid? OrgChild1Id { get; set; }
public Guid? OrgChild2Id { get; set; }
public Guid? OrgChild3Id { get; set; }
public Guid? OrgChild4Id { 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 class GetOcStaffResultDto
{
public string Message { get; set; } = string.Empty;
public int Status { get; set; } = -1;
public List<GetOcStaff> Result { get; set; } = new();
}
}

View file

@ -44,8 +44,6 @@ namespace BMA.EHR.Application.Responses.Profiles
public string? ProfileType { get; set; } public string? ProfileType { get; set; }
public bool? IsLeave { get; set; } public bool? IsLeave { get; set; }
public bool? IsProbation { get; set; }
public string? Root { get; set; } public string? Root { get; set; }
public string? Child1 { get; set; } public string? Child1 { get; set; }
public string? Child2 { get; set; } public string? Child2 { get; set; }

View file

@ -25,12 +25,6 @@ namespace BMA.EHR.Application.Responses.Profiles
public DateTime? DateStart { get; set; } public DateTime? DateStart { get; set; }
public DateTime? DateAppoint { 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 public class GetProfileByKeycloakIdRootAddTotalDto

View file

@ -1,24 +0,0 @@
# Build artifacts
bin/
obj/
# IDE / tooling
Properties/
.vs/
.vscode/
.idea/
# Source control
.git/
.gitignore
# Documentation
*.md
# Docker
Dockerfile
.dockerignore
# OS files
.DS_Store
Thumbs.db

View file

@ -1,83 +0,0 @@
# สรุปการปรับปรุงระบบลงเวลา (CheckInConsumer)
วันที่แก้ไข: 23 มิถุนายน 2026
---
## ปัญหาเดิม
ตอนที่พนักงานลงเวลาพร้อมกันจำนวนมาก (ประมาณ 2,000 รายการ) ระบบประมวลผลทีละรายการ ทำให้ต้องรอคิวนานถึง **22 นาที** กว่าจะประมวลผลเสร็จทั้งหมด
เปรียบเทียบเหมือน **โต๊ะบัญชี 1 คน รับคิวทีละคน** ทั้งที่มีคนรอ 2,000 คน → คิวยาวมาก
---
## วิธีที่แก้ (เข้าใจง่าย ๆ)
### 1. เพิ่มคนช่วยประมวลผลพร้อมกัน (Concurrency)
- **ก่อน:** ประมวลผลทีละรายการ (เหมือนมีโต๊ะบัญชี 1 โต๊ะ)
- **หลัง:** ประมวลผลพร้อมกันได้สูงสุด **5 รายการ** (เหมือนเปิดโต๊ะบัญชี 5 โต๊ะ)
> ผลที่ได้: เวลารอคิวลดลงจาก **22 นาที → ประมาณ 45 นาที**
### 2. จัดคิวล่วงหน้าให้ RabbitMQ (Prefetch)
- **ก่อน:** ระบบดึงข้อมูลมาทีละชิ้น ทำให้เสียเวลารอส่งต่อ
- **หลัง:** ระบบดึงข้อมูลมาเป็นชุด ๆ ละ 20 ชิ้นไว้เตรียมพร้อม → ลดเวลารอระหว่างรายการ
### 3. ลดเวลารอเมื่อ API มีปัญหา (Timeout)
- **ก่อน:** ถ้า API ค้าง ระบบจะรอนานถึง **5 นาที** ต่อรายการ
- **หลัง:** ลดเหลือ **1 นาที** → รายการที่มีปัญหาจะถูกปฏิเสธเร็วขึ้น ไม่ทำให้คิวค้าง
### 4. ปรับปรุงการเชื่อมต่อ HTTP
- เปลี่ยนระบบเชื่อมต่อให้รองรับการส่งคำขอหลายรายการพร้อมกันโดยไม่สะดุด
---
## ตัวเลขเปรียบเทียบ
| รายการ | ก่อนแก้ | หลังแก้ |
|---|---|---|
| จำนวนรายการที่ประมวลผลพร้อมกัน | 1 | 5 |
| เวลารอคิวสูงสุด (2,000 รายการ) | ~22 นาที | ~45 นาที |
| เวลารอเมื่อ API มีปัญหา | 5 นาที | 1 นาที |
---
## ไฟล์ที่แก้ไข
1. **`Program.cs`** — โค้ดหลักของตัวประมวลผลคิว
2. **`appsettings.json`** — ไฟล์ตั้งค่าระบบ
---
## วิธีปรับความเร็วเพิ่มเติม (ไม่ต้องเขียนโค้ดใหม่)
ถ้าหลังทดสอบแล้วเห็นว่าระบบรับได้ และอยากให้เร็วขึ้นอีก ให้แก้ไขไฟล์ `appsettings.json` แล้ว restart โปรแกรมได้เลย:
```json
{
"MaxConcurrency": 10, ← เพิ่มจาก 5 เป็น 10 (ประมวลผลพร้อมกัน 10 รายการ)
"PrefetchCount": 50, ← ควรตั้งเป็น ประมาณ MaxConcurrency × 2 ขึ้นไป
"HttpTimeoutSeconds": 60 ← เวลารอ API วินาที
}
```
**ค่าที่ใช้และผลที่คาดการณ์:**
- `MaxConcurrency = 5` → ใช้เวลา ~45 นาที (ค่าเริ่มต้นปลอดภัย)
- `MaxConcurrency = 10` → ใช้เวลา ~23 นาที
- `MaxConcurrency = 20` → ใช้เวลา ~12 นาที (ต้องตรวจสอบว่าระบบหลังบ้านรับไหวก่อน)
---
## ข้อควรระวัง / คำแนะนำ
1. **ควรทดสอบในระบบทดสอบก่อน** โดยดูว่า
- ไม่มี error ในระบบหลัก (API)
- ฐานข้อมูลไม่ช้าผิดปกติ
- ไม่พบปัญหาลงเวลาซ้ำซ้อน
2. ถ้าพบปัญหา เช่น
- มี error ใน API → **ลด** `MaxConcurrency` เหลือ 2 หรือ 3
- ลงเวลาซ้ำ → แจ้งทีมเทคนิคเพื่อแก้ฝั่ง API เพิ่มเติม
3. **ค่า `MaxConcurrency = 5` เป็นค่าปลอดภัย** เพราะระบบ API ด้านหลังยังมีข้อจำกัดอยู่บางส่วน หากต้องการเพิ่มให้สูงกว่านี้ (เช่น 2050) ควรปรึกษาทีมเทคนิคเพื่อปรับปรุงฝั่ง API ก่อน

View file

@ -1,4 +1,4 @@
## See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. ## See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
# #
## This stage is used when running from VS in fast mode (Default for Debug configuration) ## This stage is used when running from VS in fast mode (Default for Debug configuration)
#FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base #FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
@ -21,7 +21,6 @@
#ARG BUILD_CONFIGURATION=Release #ARG BUILD_CONFIGURATION=Release
#RUN dotnet publish "BMA.EHR.CheckInConsumer.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false #RUN dotnet publish "BMA.EHR.CheckInConsumer.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# #
## This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration) ## This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
#FROM base AS final #FROM base AS final
#WORKDIR /app #WORKDIR /app
@ -30,25 +29,30 @@
# ใช้ official .NET SDK image สำหรับการ build # ใช้ official .NET SDK image สำหรับการ build
# Note: Build context = repository root (ตามที่ GitHub Actions ใช้)
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
# กำหนด working directory ภายใน container
WORKDIR /src WORKDIR /src
# copy เฉพาะ .csproj ก่อน เพื่อใช้ layer caching (restore เร็ว เก็บ cache นาน) # คัดลอกไฟล์ .csproj และ restore dependencies
COPY BMA.EHR.CheckInConsumer/BMA.EHR.CheckInConsumer.csproj ./BMA.EHR.CheckInConsumer/ # COPY *.csproj ./
WORKDIR /src/BMA.EHR.CheckInConsumer COPY . ./
RUN dotnet restore "BMA.EHR.CheckInConsumer.csproj" RUN dotnet restore
# คัดลอก source ที่เหลือแล้ว publish # คัดลอกไฟล์ทั้งหมดและ build
COPY BMA.EHR.CheckInConsumer/ ./ COPY . ./
RUN dotnet publish "BMA.EHR.CheckInConsumer.csproj" -c Release -o /app/publish /p:UseAppHost=false RUN dotnet build -c Release -o /app/build
# WORKDIR "/src/BMA.EHR.CheckInConsumer"
# RUN dotnet build "BMA.EHR.CheckInConsumer.csproj" -c Release -o /app/build
# ใช้ stage ใหม่สำหรับ runtime (image เล็กลง) # ใช้ stage ใหม่สำหรับการ runtime
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime
# กำหนด working directory สำหรับ runtime
WORKDIR /app WORKDIR /app
COPY --from=build /app/publish . # คัดลอกไฟล์จาก build stage มายัง runtime stage
COPY --from=build /app/build .
# ระบุ entry point ของแอปพลิเคชัน
ENTRYPOINT ["dotnet", "BMA.EHR.CheckInConsumer.dll"] ENTRYPOINT ["dotnet", "BMA.EHR.CheckInConsumer.dll"]

View file

@ -1,4 +1,4 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using RabbitMQ.Client; using RabbitMQ.Client;
using RabbitMQ.Client.Events; using RabbitMQ.Client.Events;
using System.Text; using System.Text;
@ -18,133 +18,80 @@ var user = configuration["Rabbit:User"] ?? "";
var pass = configuration["Rabbit:Password"] ?? ""; var pass = configuration["Rabbit:Password"] ?? "";
var queue = configuration["Rabbit:Queue"] ?? "basic-queue"; var queue = configuration["Rabbit:Queue"] ?? "basic-queue";
// Concurrency & prefetch (configurable via appsettings.json)
var maxConcurrency = int.TryParse(configuration["MaxConcurrency"], out var c) && c > 0 ? c : 5;
var prefetchCount = ushort.TryParse(configuration["PrefetchCount"], out var p) && p > 0 ? p : (ushort)20;
var httpTimeoutSec = int.TryParse(configuration["HttpTimeoutSeconds"], out var t) && t > 0 ? t : 60;
WriteToConsole($"Config -> MaxConcurrency: {maxConcurrency}, PrefetchCount: {prefetchCount}, HttpTimeout: {httpTimeoutSec}s");
// create connection // create connection
var factory = new ConnectionFactory() var factory = new ConnectionFactory()
{ {
HostName = host, //Uri = new Uri("amqp://admin:P@ssw0rd@192.168.4.11:5672")
UserName = user, HostName = host,// หรือ hostname ของ RabbitMQ Server ที่คุณใช้
Password = pass, UserName = user, // ใส่ชื่อผู้ใช้ของคุณ
DispatchConsumersAsync = true Password = pass // ใส่รหัสผ่านของคุณ
}; };
using var connection = factory.CreateConnection(); using var connection = factory.CreateConnection();
using var channel = connection.CreateModel(); using var channel = connection.CreateModel();
//channel.QueueDeclare(queue: "bma-checkin-queue", durable: true, exclusive: false, autoDelete: false, arguments: null);
channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
// Prefetch: RabbitMQ จะส่ง message หลายตัวมาที่ consumer พร้อมกัน (ลด network round-trip) var consumer = new EventingBasicConsumer(channel);
channel.BasicQos(prefetchSize: 0, prefetchCount: prefetchCount, global: false);
// HttpClient แบบ SocketsHttpHandler พร้อม connection pooling รองรับ concurrent requests consumer.Received += async (model, ea) =>
var socketsHandler = new SocketsHttpHandler
{ {
MaxConnectionsPerServer = maxConcurrency * 2, var body = ea.Body.ToArray();
PooledConnectionLifetime = TimeSpan.FromMinutes(2), var message = Encoding.UTF8.GetString(body);
PooledConnectionIdleTimeout = TimeSpan.FromSeconds(30) await CallRestApi(message);
};
using var httpClient = new HttpClient(socketsHandler);
httpClient.Timeout = TimeSpan.FromSeconds(httpTimeoutSec);
// SemaphoreSlim คุมจำนวน message ที่ประมวลผลพร้อมกัน (เนื่องจาก API มีข้อจำกัดเรื่อง concurrency) // convert string into object
using var semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency); //var request = JsonConvert.DeserializeObject<CheckInRequest>(message);
//using (var db = new ApplicationDbContext())
//{
// var item = new AttendantItem
// {
// Name = request.Name,
// CheckInDateTime = request.CheckInDateTime,
// };
// db.AttendantItems.Add(item);
// db.SaveChanges();
var consumer = new AsyncEventingBasicConsumer(channel); // WriteToConsole($"ได้รับคำขอจาก Queue: {message}");
// WriteToConsole($"ตอบกลับจาก REST API: {JsonConvert.SerializeObject(item)}");
//}
consumer.Received += (model, ea) => WriteToConsole($"ได้รับคำขอจาก Queue: {message}");
{ //WriteToConsole($"ตอบกลับจาก REST API: {JsonConvert.SerializeObject(item)}");
// รอ semaphore ก่อนเริ่มประมวลผล
semaphore.WaitAsync().ContinueWith(async _ =>
{
try
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
WriteToConsole($"Received message: {message}");
var success = await CallRestApi(message, httpClient, configuration);
if (success)
{
channel.BasicAck(ea.DeliveryTag, multiple: false);
WriteToConsole("Message processed successfully");
}
else
{
channel.BasicNack(ea.DeliveryTag, multiple: false, requeue: false);
WriteToConsole("Message processing failed - message rejected");
}
}
catch (Exception ex)
{
WriteToConsole($"Error processing message: {ex.Message}");
channel.BasicNack(ea.DeliveryTag, multiple: false, requeue: false);
}
finally
{
semaphore.Release();
}
}, TaskScheduler.Default).ConfigureAwait(false);
return Task.CompletedTask;
}; };
channel.BasicConsume(queue: queue, autoAck: false, consumer: consumer); //channel.BasicConsume(queue: "bma-checkin-queue", autoAck: true, consumer: consumer);
channel.BasicConsume(queue: queue, autoAck: true, consumer: consumer);
WriteToConsole("Consumer started. Waiting for messages..."); //Console.WriteLine("\nPress 'Enter' to exit the process...");
// Keep the application running
await Task.Delay(-1); await Task.Delay(-1);
static void WriteToConsole(string message) static void WriteToConsole(string message)
{ {
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} : {message}"); Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} : {message}");
} }
static async Task<bool> CallRestApi(string requestData, HttpClient client, IConfiguration configuration) async Task CallRestApi(string requestData)
{ {
try using var client = new HttpClient();
{ var apiPath = $"{configuration["API"]}/leave/process-check-in";
var apiPath = $"{configuration["API"]}/leave/process-check-in";
var content = new StringContent(requestData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiPath, content); var content = new StringContent(requestData, Encoding.UTF8, "application/json");
if (response.IsSuccessStatusCode) var response = await client.PostAsync(apiPath, content);
{
var responseContent = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode)
WriteToConsole($"API Success: {responseContent}");
return true;
}
else
{
var errorMessage = await response.Content.ReadAsStringAsync();
var res = JsonSerializer.Deserialize<ResponseObject>(errorMessage);
WriteToConsole($"API Error ({response.StatusCode}): {res?.Message ?? errorMessage}");
return false;
}
}
catch (HttpRequestException ex)
{ {
WriteToConsole($"HTTP Error: {ex.Message}"); var responseContent = await response.Content.ReadAsStringAsync();
return false; WriteToConsole(responseContent);
} }
catch (TaskCanceledException ex) else
{ {
WriteToConsole($"Timeout: {ex.Message}"); var errorMessage = await response.Content.ReadAsStringAsync();
return false; var res = JsonSerializer.Deserialize<ResponseObject>(errorMessage);
} WriteToConsole($"Error: {res.Message}");
catch (Exception ex)
{
WriteToConsole($"Unexpected Error: {ex.Message}");
return false;
} }
} }
@ -163,14 +110,28 @@ public class ResponseObject
public class CheckTimeDtoRB public class CheckTimeDtoRB
{ {
public Guid? CheckInId { get; set; } public Guid? CheckInId { get; set; }
public double Lat { get; set; } = 0; public double Lat { get; set; } = 0;
public double Lon { get; set; } = 0; public double Lon { get; set; } = 0;
public string POI { get; set; } = string.Empty; public string POI { get; set; } = string.Empty;
public bool IsLocation { get; set; } = true; public bool IsLocation { get; set; } = true;
public string? LocationName { get; set; } = string.Empty; public string? LocationName { get; set; } = string.Empty;
public string? Remark { get; set; } = string.Empty; public string? Remark { get; set; } = string.Empty;
public Guid? UserId { get; set; } public Guid? UserId { get; set; }
public DateTime? CurrentDate { get; set; } public DateTime? CurrentDate { get; set; }
public string? CheckInFileName { get; set; } public string? CheckInFileName { get; set; }
public byte[]? CheckInFileBytes { get; set; } public byte[]? CheckInFileBytes { get; set; }
} }

View file

@ -5,8 +5,5 @@
"Password": "12345678", "Password": "12345678",
"Queue": "hrms-checkin-queue-dev" "Queue": "hrms-checkin-queue-dev"
}, },
"API": "https://localhost:7283/api/v1", "API": "https://localhost:7283/api/v1"
"MaxConcurrency": 5,
"PrefetchCount": 20,
"HttpTimeoutSeconds": 60
} }

View file

@ -93,8 +93,7 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetDisciplineUser(string status = "ALL", string type = "ALL", int year = 0, int page = 1, int pageSize = 25, string keyword = "", string? sortBy = null, bool descending = false) public async Task<ActionResult<ResponseObject>> GetDisciplineUser(string status = "ALL", string type = "ALL", int year = 0, int page = 1, int pageSize = 25, string keyword = "", string? sortBy = null, bool descending = false)
{ {
var id = ""; var id = "";
//var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position";
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
@ -358,8 +357,7 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
[HttpPost()] [HttpPost()]
public async Task<ActionResult<ResponseObject>> CreateDiscipline([FromForm] DisciplineComplaint_AppealRequest req) public async Task<ActionResult<ResponseObject>> CreateDiscipline([FromForm] DisciplineComplaint_AppealRequest req)
{ {
//var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position";
var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId";
var id = ""; var id = "";
var type = ""; var type = "";
using (var client = new HttpClient()) using (var client = new HttpClient())
@ -786,7 +784,7 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -826,11 +824,11 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
data_search = data_search data_search = data_search
.Where(x => x.rootDnaId == nodeId).ToList(); .Where(x => x.rootDnaId == nodeId).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// data_search = data_search data_search = data_search
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
data_search = data_search.Where(x => data_search = data_search.Where(x =>

View file

@ -392,7 +392,7 @@ namespace BMA.EHR.DisciplineDirector.Service.Controllers
return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound); return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound);
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, token.Replace("Bearer ", "")); var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, token.Replace("Bearer ", ""));
if (profile == null) if (profile == null)
return Error(GlobalMessages.DataNotFound); return Error(GlobalMessages.DataNotFound);

View file

@ -71,13 +71,6 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers
{ {
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); 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() ?? ""; string role = jsonData["result"]?.ToString() ?? "";
var nodeId = string.Empty; var nodeId = string.Empty;
@ -109,14 +102,14 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
var data_search = (from x in _context.DisciplineReport_Profiles.Include(x => x.DisciplineDisciplinary) var data_search = (from x in _context.DisciplineReport_Profiles.Include(x => x.DisciplineDisciplinary)
where where
( (
endDate != null && startDate != null ? endDate != null && startDate != null?
( (
(x.StartDateSuspend.Value.Date >= startDate.Value.Date && x.StartDateSuspend.Value.Date <= endDate.Value.Date) || (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) || (x.EndDateSuspend.Value.Date >= startDate.Value.Date && x.EndDateSuspend.Value.Date <= endDate.Value.Date) ||
@ -144,19 +137,14 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers
( (
!string.IsNullOrEmpty(status) ? x.Status!.Trim().ToUpper() == status : true !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" role == "OWNER"
? true ? true
: role == "ROOT" : role == "ROOT"
? x.rootDnaId == nodeId ? x.rootDnaId == nodeId
: role == "PARENT"
? x.rootDnaId == nodeId && x.child1DnaId != null
: role == "CHILD" : role == "CHILD"
? ( ? (
profileAdmin.Node == 4 ? x.child4DnaId == nodeId : profileAdmin.Node == 4 ? x.child4DnaId == nodeId :
@ -189,119 +177,125 @@ namespace BMA.EHR.DisciplineSuspend.Service.Controllers
) )
select x).ToList(); select x).ToList();
var query = data_search var query = data_search
.Select(x => new .Select(x => new
{ {
Id = x.Id, Id = x.Id,
CitizenId = x.CitizenId, CitizenId = x.CitizenId,
Prefix = x.Prefix, Prefix = x.Prefix,
FirstName = x.FirstName, FirstName = x.FirstName,
LastName = x.LastName, LastName = x.LastName,
ProfileId = x.PersonId, ProfileId = x.PersonId,
Organization = x.Organization, Organization = x.Organization,
root = x.root, root = x.root,
rootId = x.rootId, rootId = x.rootId,
rootDnaId = x.rootDnaId, rootDnaId = x.rootDnaId,
rootShortName = x.rootShortName, rootShortName = x.rootShortName,
child1 = x.child1, child1 = x.child1,
child1Id = x.child1Id, child1Id = x.child1Id,
child1DnaId = x.child1DnaId, child1DnaId = x.child1DnaId,
child1ShortName = x.child1ShortName, child1ShortName = x.child1ShortName,
child2 = x.child2, child2 = x.child2,
child2Id = x.child2Id, child2Id = x.child2Id,
child2DnaId = x.child2DnaId, child2DnaId = x.child2DnaId,
child2ShortName = x.child2ShortName, child2ShortName = x.child2ShortName,
child3 = x.child3, child3 = x.child3,
child3Id = x.child3Id, child3Id = x.child3Id,
child3DnaId = x.child3DnaId, child3DnaId = x.child3DnaId,
child3ShortName = x.child3ShortName, child3ShortName = x.child3ShortName,
child4 = x.child4, child4 = x.child4,
child4Id = x.child4Id, child4Id = x.child4Id,
child4DnaId = x.child4DnaId, child4DnaId = x.child4DnaId,
child4ShortName = x.child4ShortName, child4ShortName = x.child4ShortName,
posMasterNo = x.posMasterNo, posMasterNo = x.posMasterNo,
posTypeId = x.posTypeId, posTypeId = x.posTypeId,
posTypeName = x.posTypeName, posTypeName = x.posTypeName,
posLevelId = x.posLevelId, posLevelId = x.posLevelId,
posLevelName = x.posLevelName, posLevelName = x.posLevelName,
Position = x.Position, Position = x.Position,
PosNo = x.PosNo, PosNo = x.PosNo,
PositionLevel = x.PositionLevel == null ? "" : x.PositionLevel, PositionLevel = x.PositionLevel == null ? "" : x.PositionLevel,
PositionType = x.PositionType == null ? "" : x.PositionType, PositionType = x.PositionType == null ? "" : x.PositionType,
Salary = x.Salary, Salary = x.Salary,
Status = x.Status, Status = x.Status,
DescriptionSuspend = x.DescriptionSuspend, DescriptionSuspend = x.DescriptionSuspend,
StartDateSuspend = x.StartDateSuspend, StartDateSuspend = x.StartDateSuspend,
EndDateSuspend = x.EndDateSuspend, EndDateSuspend = x.EndDateSuspend,
Title = x.DisciplineDisciplinary.Title, Title = x.DisciplineDisciplinary.Title,
OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด OffenseDetails = x.DisciplineDisciplinary.OffenseDetails,//ลักษณะความผิด
DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด DisciplinaryFaultLevel = x.DisciplineDisciplinary.DisciplinaryFaultLevel,//ระดับโทษความผิด
DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด DisciplinaryCaseFault = x.DisciplineDisciplinary.DisciplinaryCaseFault,//กรณีความผิด
profileType = x.profileType, profileType = x.profileType,
CreatedAt = x.CreatedAt, CreatedAt = x.CreatedAt,
}); });
bool desc = descending ?? false; bool desc = descending ?? false;
if (!string.IsNullOrEmpty(sortBy)) if (!string.IsNullOrEmpty(sortBy))
{ {
if (sortBy == "title") if (sortBy == "title")
{ {
query = desc ? query.OrderByDescending(x => x.Title) query = desc ? query.OrderByDescending(x => x.Title)
: query.OrderBy(x => x.Title); : query.OrderBy(x => x.Title);
} }
else if (sortBy == "prefix" || sortBy == "firstName" || sortBy == "lastName") else if (sortBy == "prefix" || sortBy == "firstName" || sortBy == "lastName")
{ {
query = desc ? query = desc ?
query.OrderByDescending(x => x.FirstName).ThenByDescending(x => x.LastName) : query
query.OrderBy(x => x.FirstName).ThenBy(x => x.LastName); //.OrderByDescending(x => x.Prefix)
} .OrderByDescending(x => x.FirstName)
else if (sortBy == "position") .ThenByDescending(x => x.LastName) :
{ query
query = desc ? query.OrderByDescending(x => x.Position) //.OrderBy(x => x.Prefix)
: query.OrderBy(x => x.Position); .OrderBy(x => x.FirstName)
} .ThenBy(x => x.LastName);
else if (sortBy == "positionType" || sortBy == "positionLevel") }
{ else if (sortBy == "position")
query = desc ? {
query query = desc ? query.OrderByDescending(x => x.Position)
.OrderByDescending(x => x.PositionType) : query.OrderBy(x => x.Position);
.ThenByDescending(x => x.PositionLevel) : }
query else if (sortBy == "positionType" || sortBy == "positionLevel")
.OrderBy(x => x.PositionType) {
.ThenBy(x => x.PositionLevel); query = desc ?
} query
else if (sortBy == "organization") .OrderByDescending(x => x.PositionType)
{ .ThenByDescending(x => x.PositionLevel) :
query = desc ? query.OrderByDescending(x => x.Organization) query
: query.OrderBy(x => x.Organization); .OrderBy(x => x.PositionType)
} .ThenBy(x => x.PositionLevel);
else if (sortBy == "startDateSuspend") }
{ else if (sortBy == "organization")
query = desc ? query.OrderByDescending(x => x.StartDateSuspend) {
: query.OrderBy(x => x.StartDateSuspend); query = desc ? query.OrderByDescending(x => x.Organization)
} : query.OrderBy(x => x.Organization);
else if (sortBy == "endDateSuspend") }
{ else if (sortBy == "startDateSuspend")
query = desc ? query.OrderByDescending(x => x.EndDateSuspend) {
: query.OrderBy(x => x.EndDateSuspend); query = desc ? query.OrderByDescending(x => x.StartDateSuspend)
} : query.OrderBy(x => x.StartDateSuspend);
else if (sortBy == "descriptionSuspend") }
{ else if (sortBy == "endDateSuspend")
query = desc ? query.OrderByDescending(x => x.DescriptionSuspend) {
: query.OrderBy(x => x.DescriptionSuspend); query = desc ? query.OrderByDescending(x => x.EndDateSuspend)
} : query.OrderBy(x => x.EndDateSuspend);
else }
{ else if (sortBy == "descriptionSuspend")
query = query.OrderByDescending(x => x.profileType) {
.ThenByDescending(x => x.CreatedAt) query = desc ? query.OrderByDescending(x => x.DescriptionSuspend)
.ThenByDescending(x => x.CitizenId); : query.OrderBy(x => x.DescriptionSuspend);
} }
} else
{
query = query.OrderByDescending(x => x.profileType)
.ThenByDescending(x => x.CreatedAt)
.ThenByDescending(x => x.CitizenId);
}
}
var data = query var data = query
.Skip((page - 1) * pageSize) .Skip((page - 1) * pageSize)
.Take(pageSize) .Take(pageSize)
.ToList(); .ToList();
return Success(new { data, total = data_search.Count() }); return Success(new { data, total = data_search.Count() });
} }

View file

@ -8,12 +8,4 @@ namespace BMA.EHR.Discipline.Service.Requests
public string[] refIds { get; set; } public string[] refIds { get; set; }
public string? status { 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; }
}
} }

View file

@ -1,5 +1,4 @@
using BMA.EHR.Domain.Extensions; using BMA.EHR.Domain.Shared;
using BMA.EHR.Domain.Shared;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -82,23 +81,6 @@ 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();
protected string? FirstName => User.GetFirstName();
protected string? LastName => User.GetLastName();
#endregion #endregion
#endregion #endregion

View file

@ -1,39 +0,0 @@
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";
}
}

View file

@ -1,32 +0,0 @@
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);
public static string? GetFirstName(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.GivenName);
public static string? GetLastName(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.FamilyName);
}
}

View file

@ -174,29 +174,6 @@ 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) public static int CalculateAge(this DateTime date, int plusYear = 0, int subtractYear = 0)
{ {
try try

View file

@ -79,39 +79,13 @@ namespace BMA.EHR.Domain.Middlewares
GetProfileByKeycloakIdLocal? pf = null; GetProfileByKeycloakIdLocal? pf = null;
var tokenUserInfo = await ExtractTokenUserInfoAsync(token); var tokenUserInfo = await ExtractTokenUserInfoAsync(token);
// Store tokenUserInfo in HttpContext.Items for controllers to use
context.Items["TokenUserInfo"] = tokenUserInfo;
// ดึง keycloakId จาก JWT token // ดึง keycloakId จาก JWT token
keycloakId = tokenUserInfo.KeycloakId; keycloakId = tokenUserInfo.KeycloakId;
// ดึง profile จาก claims หรือ cache หรือ API // ดึง profile จาก cache หรือ API
if (Guid.TryParse(keycloakId, out var parsedId) && parsedId != Guid.Empty) if (Guid.TryParse(keycloakId, out var parsedId) && parsedId != Guid.Empty)
{ {
// Build profile from token claims if available pf = await GetProfileWithCacheAsync(parsedId, token);
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 try
@ -170,47 +144,25 @@ namespace BMA.EHR.Domain.Middlewares
{ {
stopwatch.Stop(); stopwatch.Stop();
// อ่านข้อมูล response ก่อนที่ stream จะถูก dispose // ทำ logging แบบ fire-and-forget เพื่อไม่ block response
string? responseBodyForLogging = null; _ = Task.Run(async () =>
if (memoryStream.Length > 0)
{ {
memoryStream.Seek(0, SeekOrigin.Begin); try
using var reader = new StreamReader(memoryStream, leaveOpen: true); {
responseBodyForLogging = await reader.ReadToEndAsync(); await LogRequestAsync(context, _elasticClient!, startTime, stopwatch, pf, keycloakId, requestBodyJson, memoryStream, caughtException);
memoryStream.Seek(0, SeekOrigin.Begin); }
} catch (Exception ex)
{
Console.WriteLine($"Background logging error: {ex.Message}");
}
});
// เก็บข้อมูลที่จำเป็นจาก HttpContext ก่อนที่มันจะถูก dispose // เขียนข้อมูลกลับไปยัง original Response body
var logData = new
{
RemoteIpAddress = context.Connection.RemoteIpAddress?.ToString(),
HostValue = context.Request.Host.Value,
Method = context.Request.Method,
Path = context.Request.Path.ToString(),
QueryString = context.Request.QueryString.ToString(),
StatusCode = context.Response.StatusCode,
ContentType = context.Response.ContentType ?? ""
};
// เขียนข้อมูลกลับไปยัง original Response body ก่อน
if (memoryStream.Length > 0) if (memoryStream.Length > 0)
{ {
memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(originalBodyStream); await memoryStream.CopyToAsync(originalBodyStream);
} }
// ทำ logging แบบ await
Console.WriteLine("[DEBUG] Starting logging...");
try
{
await LogRequestAsync(_elasticClient!, startTime, stopwatch, pf, keycloakId, requestBodyJson, responseBodyForLogging, caughtException, logData);
Console.WriteLine("[DEBUG] Logging completed successfully");
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Logging error: {ex.Message}");
Console.WriteLine($"[ERROR] Stack trace: {ex.StackTrace}");
}
} }
} }
@ -440,16 +392,15 @@ namespace BMA.EHR.Domain.Middlewares
} }
} }
private async Task LogRequestAsync(ElasticClient client, DateTime startTime, Stopwatch stopwatch, private async Task LogRequestAsync(HttpContext context, ElasticClient client, DateTime startTime, Stopwatch stopwatch,
GetProfileByKeycloakIdLocal? pf, string keycloakId, string? requestBodyJson, string? responseBodyForLogging, Exception? caughtException, dynamic contextData) GetProfileByKeycloakIdLocal? pf, string keycloakId, string? requestBodyJson, MemoryStream memoryStream, Exception? caughtException)
{ {
Console.WriteLine("[DEBUG] LogRequestAsync called");
try try
{ {
var processTime = stopwatch.ElapsedMilliseconds; var processTime = stopwatch.ElapsedMilliseconds;
var endTime = DateTime.UtcNow; var endTime = DateTime.UtcNow;
var statusCode = caughtException != null ? (int)HttpStatusCode.InternalServerError : (int)contextData.StatusCode; var statusCode = caughtException != null ? (int)HttpStatusCode.InternalServerError : context.Response.StatusCode;
var logType = caughtException != null ? "error" : statusCode switch var logType = caughtException != null ? "error" : statusCode switch
{ {
@ -461,41 +412,48 @@ namespace BMA.EHR.Domain.Middlewares
string? message = null; string? message = null;
string? responseBodyJson = null; string? responseBodyJson = null;
// ใช้ response body ที่ส่งมาจากการอ่านก่อนหน้า // อ่านข้อมูลจาก Response (ลด serialization ที่ซ้ำ)
if (!string.IsNullOrEmpty(responseBodyForLogging)) if (memoryStream.Length > 0)
{ {
var contentType = (string)contextData.ContentType; memoryStream.Seek(0, SeekOrigin.Begin);
var isFileResponse = !contentType.StartsWith("application/json") && !contentType.StartsWith("text/html") && ( var responseBody = new StreamReader(memoryStream).ReadToEnd();
contentType.StartsWith("application/") ||
contentType.StartsWith("image/") ||
contentType.StartsWith("audio/")
);
if (isFileResponse) if (!string.IsNullOrEmpty(responseBody))
{ {
responseBodyJson = ""; var contentType = context.Response.ContentType ?? "";
message = "success"; var isFileResponse = !contentType.StartsWith("application/json") && !contentType.StartsWith("text/html") && (
} contentType.StartsWith("application/") ||
else contentType.StartsWith("image/") ||
{ contentType.StartsWith("audio/") ||
// ใช้ response body ที่มีอยู่แล้วโดยไม่ serialize ซ้ำ context.Response.Headers.ContainsKey("Content-Disposition")
responseBodyJson = responseBodyForLogging; );
try if (isFileResponse)
{ {
var json = JsonSerializer.Deserialize<JsonElement>(responseBodyForLogging); responseBodyJson = "";
if (json.ValueKind == JsonValueKind.Array) message = "success";
{
message = "success";
}
else if (json.TryGetProperty("message", out var messageElement))
{
message = messageElement.GetString();
}
} }
catch else
{ {
message = caughtException?.Message ?? "Unknown error"; // ใช้ response body ที่มีอยู่แล้วโดยไม่ serialize ซ้ำ
responseBodyJson = responseBody;
try
{
var json = JsonSerializer.Deserialize<JsonElement>(responseBody);
if (json.ValueKind == JsonValueKind.Array)
{
message = "success";
}
else if (json.TryGetProperty("message", out var messageElement))
{
message = messageElement.GetString();
}
}
catch
{
message = caughtException?.Message ?? "Unknown error";
}
} }
} }
} }
@ -508,16 +466,15 @@ namespace BMA.EHR.Domain.Middlewares
var logData = new var logData = new
{ {
logType = logType, logType = logType,
ip = (string)contextData.RemoteIpAddress, ip = context.Connection.RemoteIpAddress?.ToString(),
//rootId = pf?.RootId, rootId = pf?.RootId,
rootId = pf?.RootDnaId,
systemName = SystemName, systemName = SystemName,
startTimeStamp = startTime.ToString("o"), startTimeStamp = startTime.ToString("o"),
endTimeStamp = endTime.ToString("o"), endTimeStamp = endTime.ToString("o"),
processTime = processTime, processTime = processTime,
host = (string)contextData.HostValue, host = context.Request.Host.Value,
method = (string)contextData.Method, method = context.Request.Method,
endpoint = (string)contextData.Path + (string)contextData.QueryString, endpoint = context.Request.Path + context.Request.QueryString,
responseCode = statusCode == 304 ? "200" : statusCode.ToString(), responseCode = statusCode == 304 ? "200" : statusCode.ToString(),
responseDescription = message, responseDescription = message,
input = requestBodyJson, input = requestBodyJson,
@ -528,19 +485,11 @@ namespace BMA.EHR.Domain.Middlewares
exception = caughtException?.ToString() exception = caughtException?.ToString()
}; };
Console.WriteLine($"[DEBUG] Sending log to Elasticsearch: {logType} - {(string)contextData.Method} {(string)contextData.Path}"); await client.IndexDocumentAsync(logData);
var response = await client.IndexDocumentAsync(logData);
Console.WriteLine($"[DEBUG] Elasticsearch response: IsValid={response.IsValid}, Index={response.Index}");
if (!response.IsValid)
{
Console.WriteLine($"[ERROR] Elasticsearch error: {response.OriginalException?.Message ?? response.ServerError?.ToString()}");
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"[ERROR] Error logging request: {ex.Message}"); Console.WriteLine($"Error logging request: {ex.Message}");
Console.WriteLine($"[ERROR] Stack trace: {ex.StackTrace}");
} }
} }
@ -675,87 +624,6 @@ namespace BMA.EHR.Domain.Middlewares
Console.WriteLine($"Extracted family_name: {result.FamilyName}"); 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; return result;
} }
catch (Exception ex) catch (Exception ex)
@ -792,8 +660,7 @@ namespace BMA.EHR.Domain.Middlewares
{ {
try try
{ {
//var apiPath = $"{_configuration["API"]}/org/dotnet/by-keycloak/{keycloakId}"; var apiPath = $"{_configuration["API"]}/org/dotnet/keycloak/{keycloakId}";
var apiPath = $"{_configuration["API"]}/org/dotnet/user-logs/{keycloakId}";
var apiKey = _configuration["API_KEY"]; var apiKey = _configuration["API_KEY"];
var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey); var apiResult = await GetExternalAPIAsync(apiPath, accessToken ?? "", apiKey);
@ -874,6 +741,14 @@ namespace BMA.EHR.Domain.Middlewares
} }
// Model classes // 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 class GetProfileByKeycloakIdLocal
{ {
public Guid Id { get; set; } public Guid Id { get; set; }

View file

@ -24,14 +24,11 @@ namespace BMA.EHR.Domain.Models.Leave.Requests
[Required, Comment("ปีงบประมาณ")] [Required, Comment("ปีงบประมาณ")]
public int LeaveYear { get; set; } = 0; public int LeaveYear { get; set; } = 0;
[Required, Comment("จำนวนวันลาทั้งหมด")] [Required, Comment("จำนวนวันลายกมา")]
public double LeaveDays { get; set; } = 0.0; public double LeaveDays { get; set; } = 0.0;
[Comment("จำนวนวันลาที่ใช้ไป")] [Required, Comment("จำนวนวันลาที่ใช้ไป")]
public double? LeaveDaysUsed { get; set; } = 0.0; public double LeaveDaysUsed { get; set; } = 0.0;
[Comment("จำนวนครั้งที่ลาสะสม")]
public int? LeaveCount { get; set; } = 0;
public Guid? RootDnaId { get; set; } public Guid? RootDnaId { get; set; }
@ -42,11 +39,5 @@ namespace BMA.EHR.Domain.Models.Leave.Requests
public Guid? Child3DnaId { get; set; } public Guid? Child3DnaId { get; set; }
public Guid? Child4DnaId { get; set; } public Guid? Child4DnaId { get; set; }
[Required, Comment("จำนวนวันลายกมา")]
public double BeginningLeaveDays { get; set; } = 0.0;
[Comment("จำนวนครั้งที่ลายกมา")]
public int BeginningLeaveCount { get; set; } = 0;
} }
} }

View file

@ -210,7 +210,5 @@ namespace BMA.EHR.Domain.Models.Leave.Requests
public Guid? Child4DnaId { get; set; } = Guid.Empty; public Guid? Child4DnaId { get; set; } = Guid.Empty;
public DateTime? DateSendLeave { get; set; }
} }
} }

View file

@ -38,10 +38,5 @@ namespace BMA.EHR.Domain.Models.Leave.Requests
public string Comment { get; set; } = string.Empty; public string Comment { get; set; } = string.Empty;
public string? ApproveType { get; set; } = string.Empty; // ผู้บังคับบัญชา = commander, ผู้มีอำนาจอนุมัติ = Approver public string? ApproveType { get; set; } = string.Empty; // ผู้บังคับบัญชา = commander, ผู้มีอำนาจอนุมัติ = Approver
public bool IsAct { get; set; } = false;
public string KeyId { get; set; } = string.Empty;
} }
} }

View file

@ -1,37 +0,0 @@
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; }
}
}

View file

@ -119,10 +119,6 @@ namespace BMA.EHR.Domain.Models.Placement
public string? position { get; set; } public string? position { get; set; }
[Comment("ตำแหน่งทางการบริหาร")] [Comment("ตำแหน่งทางการบริหาร")]
public string? PositionExecutive { get; set; } public string? PositionExecutive { get; set; }
[Comment("id ตำแหน่งทางการบริหาร")]
public string? posExecutiveId { get; set; }
[Comment("id ประเภทตำแหน่ง")] [Comment("id ประเภทตำแหน่ง")]
public string? posTypeId { get; set; } public string? posTypeId { get; set; }
[Comment("ชื่อประเภทตำแหน่ง")] [Comment("ชื่อประเภทตำแหน่ง")]

View file

@ -321,10 +321,6 @@ namespace BMA.EHR.Domain.Models.Placement
public string? positionName { get; set; } public string? positionName { get; set; }
[Comment("ตำแหน่งทางการบริหาร")] [Comment("ตำแหน่งทางการบริหาร")]
public string? PositionExecutive { get; set; } public string? PositionExecutive { get; set; }
[Comment("id ตำแหน่งทางการบริหาร")]
public string? posExecutiveId { get; set; }
[Comment("สายงาน")] [Comment("สายงาน")]
public string? positionField { get; set; } public string? positionField { get; set; }
[Comment("id ประเภทตำแหน่ง")] [Comment("id ประเภทตำแหน่ง")]

View file

@ -64,10 +64,6 @@ namespace BMA.EHR.Domain.Models.Placement
public string? profileId { get; set; } public string? profileId { get; set; }
[Comment("คำนำหน้า")] [Comment("คำนำหน้า")]
public string? prefix { get; set; } public string? prefix { get; set; }
[Comment("ยศ")]
public string? rank { get; set; }
[Comment("ชื่อ")] [Comment("ชื่อ")]
public string? firstName { get; set; } public string? firstName { get; set; }
[Comment("นามสกุล")] [Comment("นามสกุล")]
@ -132,10 +128,6 @@ namespace BMA.EHR.Domain.Models.Placement
public string? position { get; set; } public string? position { get; set; }
[Comment("ตำแหน่งทางการบริหาร")] [Comment("ตำแหน่งทางการบริหาร")]
public string? PositionExecutive { get; set; } public string? PositionExecutive { get; set; }
[Comment("id ตำแหน่งทางการบริหาร")]
public string? posExecutiveId { get; set; }
[Comment("id ประเภทตำแหน่ง")] [Comment("id ประเภทตำแหน่ง")]
public string? posTypeId { get; set; } public string? posTypeId { get; set; }
[Comment("ชื่อประเภทตำแหน่ง")] [Comment("ชื่อประเภทตำแหน่ง")]

View file

@ -173,10 +173,6 @@ namespace BMA.EHR.Domain.Models.Retirement
public string? position { get; set; } public string? position { get; set; }
[Comment("ตำแหน่งทางการบริหาร")] [Comment("ตำแหน่งทางการบริหาร")]
public string? PositionExecutive { get; set; } public string? PositionExecutive { get; set; }
[Comment("id ตำแหน่งทางการบริหาร")]
public string? posExecutiveId { get; set; }
[Comment("id ประเภทตำแหน่ง")] [Comment("id ประเภทตำแหน่ง")]
public string? posTypeId { get; set; } public string? posTypeId { get; set; }
[Comment("ชื่อประเภทตำแหน่ง")] [Comment("ชื่อประเภทตำแหน่ง")]

View file

@ -8,8 +8,6 @@
public static readonly string DataNotFound = "ไม่พบข้อมูลในระบบ"; public static readonly string DataNotFound = "ไม่พบข้อมูลในระบบ";
public static readonly string ProfileNotFound = "ไม่พบข้อมูลในระบบทะเบียนประวัติ";
public static readonly string NotAuthorized = "กรุณาเข้าสู่ระบบก่อนใช้งาน!"; public static readonly string NotAuthorized = "กรุณาเข้าสู่ระบบก่อนใช้งาน!";
public static readonly string ForbiddenAccess = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!"; public static readonly string ForbiddenAccess = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!";

View file

@ -1,30 +0,0 @@
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);
}
}
}

View file

@ -1,30 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class update_PlacementReceives_add_rank : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "rank",
table: "PlacementReceives",
type: "longtext",
nullable: true,
comment: "ยศ")
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "rank",
table: "PlacementReceives");
}
}
}

View file

@ -1,66 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class update_Tables_add_posExecutiveId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "posExecutiveId",
table: "RetirementOthers",
type: "longtext",
nullable: true,
comment: "id ตำแหน่งทางการบริหาร")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "posExecutiveId",
table: "PlacementReceives",
type: "longtext",
nullable: true,
comment: "id ตำแหน่งทางการบริหาร")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "posExecutiveId",
table: "PlacementProfiles",
type: "longtext",
nullable: true,
comment: "id ตำแหน่งทางการบริหาร")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "posExecutiveId",
table: "PlacementAppointments",
type: "longtext",
nullable: true,
comment: "id ตำแหน่งทางการบริหาร")
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "posExecutiveId",
table: "RetirementOthers");
migrationBuilder.DropColumn(
name: "posExecutiveId",
table: "PlacementReceives");
migrationBuilder.DropColumn(
name: "posExecutiveId",
table: "PlacementProfiles");
migrationBuilder.DropColumn(
name: "posExecutiveId",
table: "PlacementAppointments");
}
}
}

View file

@ -11721,10 +11721,6 @@ namespace BMA.EHR.Infrastructure.Migrations
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id revision"); .HasComment("id revision");
b.Property<string>("posExecutiveId")
.HasColumnType("longtext")
.HasComment("id ตำแหน่งทางการบริหาร");
b.Property<string>("posLevelId") b.Property<string>("posLevelId")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id ระดับตำแหน่ง"); .HasComment("id ระดับตำแหน่ง");
@ -13112,10 +13108,6 @@ namespace BMA.EHR.Infrastructure.Migrations
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("ชื่อหน่วยงาน"); .HasComment("ชื่อหน่วยงาน");
b.Property<string>("posExecutiveId")
.HasColumnType("longtext")
.HasComment("id ตำแหน่งทางการบริหาร");
b.Property<string>("posLevelId") b.Property<string>("posLevelId")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id ระดับตำแหน่ง"); .HasComment("id ระดับตำแหน่ง");
@ -13621,10 +13613,6 @@ namespace BMA.EHR.Infrastructure.Migrations
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id revision"); .HasComment("id revision");
b.Property<string>("posExecutiveId")
.HasColumnType("longtext")
.HasComment("id ตำแหน่งทางการบริหาร");
b.Property<string>("posLevelId") b.Property<string>("posLevelId")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id ระดับตำแหน่ง"); .HasComment("id ระดับตำแหน่ง");
@ -13705,10 +13693,6 @@ namespace BMA.EHR.Infrastructure.Migrations
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("profile Id"); .HasComment("profile Id");
b.Property<string>("rank")
.HasColumnType("longtext")
.HasComment("ยศ");
b.Property<string>("root") b.Property<string>("root")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("ชื่อหน่วยงาน root"); .HasComment("ชื่อหน่วยงาน root");
@ -15815,10 +15799,6 @@ namespace BMA.EHR.Infrastructure.Migrations
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id revision"); .HasComment("id revision");
b.Property<string>("posExecutiveId")
.HasColumnType("longtext")
.HasComment("id ตำแหน่งทางการบริหาร");
b.Property<string>("posLevelId") b.Property<string>("posLevelId")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("id ระดับตำแหน่ง"); .HasComment("id ระดับตำแหน่ง");

View file

@ -1,30 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class AddLeaveCounttoLeaveBeginning : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "LeaveCount",
table: "LeaveBeginnings",
type: "int",
nullable: false,
defaultValue: 0,
comment: "จำนวนครั้งที่ลาสะสม");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "LeaveCount",
table: "LeaveBeginnings");
}
}
}

View file

@ -1,62 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class AddBeginningLeaveandLeaveCounttoLeaveBeginning : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<double>(
name: "LeaveDays",
table: "LeaveBeginnings",
type: "double",
nullable: false,
comment: "จำนวนวันลาทั้งหมด",
oldClrType: typeof(double),
oldType: "double",
oldComment: "จำนวนวันลายกมา");
migrationBuilder.AddColumn<int>(
name: "BeginningLeaveCount",
table: "LeaveBeginnings",
type: "int",
nullable: false,
defaultValue: 0,
comment: "จำนวนครั้งที่ลายกมา");
migrationBuilder.AddColumn<double>(
name: "BeginningLeaveDays",
table: "LeaveBeginnings",
type: "double",
nullable: false,
defaultValue: 0.0,
comment: "จำนวนวันลายกมา");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BeginningLeaveCount",
table: "LeaveBeginnings");
migrationBuilder.DropColumn(
name: "BeginningLeaveDays",
table: "LeaveBeginnings");
migrationBuilder.AlterColumn<double>(
name: "LeaveDays",
table: "LeaveBeginnings",
type: "double",
nullable: false,
comment: "จำนวนวันลายกมา",
oldClrType: typeof(double),
oldType: "double",
oldComment: "จำนวนวันลาทั้งหมด");
}
}
}

View file

@ -1,54 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class AddLeaveProcessJobStatus : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "LeaveProcessJobStatuses",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false, comment: "PrimaryKey", collation: "ascii_general_ci"),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "สร้างข้อมูลเมื่อ"),
CreatedUserId = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่สร้างข้อมูล")
.Annotation("MySql:CharSet", "utf8mb4"),
LastUpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "แก้ไขข้อมูลล่าสุดเมื่อ"),
LastUpdateUserId = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false, comment: "User Id ที่แก้ไขข้อมูลล่าสุด")
.Annotation("MySql:CharSet", "utf8mb4"),
CreatedFullName = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่สร้างข้อมูล")
.Annotation("MySql:CharSet", "utf8mb4"),
LastUpdateFullName = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: false, comment: "ชื่อ User ที่แก้ไขข้อมูลล่าสุด")
.Annotation("MySql:CharSet", "utf8mb4"),
StartDate = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "วันเริ่มต้น"),
EndDate = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "วันสิ้นสุด"),
RootDnaId = table.Column<Guid>(type: "char(36)", nullable: false, comment: "รหัส Root DNA Id", collation: "ascii_general_ci"),
CreatedDate = table.Column<DateTime>(type: "datetime(6)", nullable: false, comment: "วันเวลาที่สร้างงาน"),
ProcessingDate = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "วันเวลาที่เริ่มประมวลผล"),
CompletedDate = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "วันเวลาที่เสร็จสิ้นการประมวลผล"),
Status = table.Column<string>(type: "longtext", nullable: false, comment: "สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED")
.Annotation("MySql:CharSet", "utf8mb4"),
ErrorMessage = table.Column<string>(type: "longtext", nullable: true, comment: "ข้อความแสดงข้อผิดพลาด")
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_LeaveProcessJobStatuses", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LeaveProcessJobStatuses");
}
}
}

View file

@ -1,29 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class AddDateSendLeave : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateSendLeave",
table: "LeaveRequests",
type: "datetime(6)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateSendLeave",
table: "LeaveRequests");
}
}
}

View file

@ -1,62 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class ChangeField : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<double>(
name: "LeaveDaysUsed",
table: "LeaveBeginnings",
type: "double",
nullable: true,
comment: "จำนวนวันลาที่ใช้ไป",
oldClrType: typeof(double),
oldType: "double",
oldComment: "จำนวนวันลาที่ใช้ไป");
migrationBuilder.AlterColumn<int>(
name: "LeaveCount",
table: "LeaveBeginnings",
type: "int",
nullable: true,
comment: "จำนวนครั้งที่ลาสะสม",
oldClrType: typeof(int),
oldType: "int",
oldComment: "จำนวนครั้งที่ลาสะสม");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<double>(
name: "LeaveDaysUsed",
table: "LeaveBeginnings",
type: "double",
nullable: false,
defaultValue: 0.0,
comment: "จำนวนวันลาที่ใช้ไป",
oldClrType: typeof(double),
oldType: "double",
oldNullable: true,
oldComment: "จำนวนวันลาที่ใช้ไป");
migrationBuilder.AlterColumn<int>(
name: "LeaveCount",
table: "LeaveBeginnings",
type: "int",
nullable: false,
defaultValue: 0,
comment: "จำนวนครั้งที่ลาสะสม",
oldClrType: typeof(int),
oldType: "int",
oldNullable: true,
oldComment: "จำนวนครั้งที่ลาสะสม");
}
}
}

View file

@ -1,40 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
{
/// <inheritdoc />
public partial class AddApproverField : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsAct",
table: "LeaveRequestApprovers",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<string>(
name: "KeyId",
table: "LeaveRequestApprovers",
type: "longtext",
nullable: false)
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsAct",
table: "LeaveRequestApprovers");
migrationBuilder.DropColumn(
name: "KeyId",
table: "LeaveRequestApprovers");
}
}
}

View file

@ -50,7 +50,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Document", (string)null); b.ToTable("Document");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Commons.LeaveType", b =>
@ -116,7 +116,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("LeaveTypes", (string)null); b.ToTable("LeaveTypes");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b =>
@ -128,14 +128,6 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
.HasComment("PrimaryKey") .HasComment("PrimaryKey")
.HasAnnotation("Relational:JsonPropertyName", "id"); .HasAnnotation("Relational:JsonPropertyName", "id");
b.Property<int>("BeginningLeaveCount")
.HasColumnType("int")
.HasComment("จำนวนครั้งที่ลายกมา");
b.Property<double>("BeginningLeaveDays")
.HasColumnType("double")
.HasComment("จำนวนวันลายกมา");
b.Property<Guid?>("Child1DnaId") b.Property<Guid?>("Child1DnaId")
.HasColumnType("char(36)"); .HasColumnType("char(36)");
@ -192,15 +184,11 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
.HasColumnOrder(102) .HasColumnOrder(102)
.HasComment("แก้ไขข้อมูลล่าสุดเมื่อ"); .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ");
b.Property<int?>("LeaveCount")
.HasColumnType("int")
.HasComment("จำนวนครั้งที่ลาสะสม");
b.Property<double>("LeaveDays") b.Property<double>("LeaveDays")
.HasColumnType("double") .HasColumnType("double")
.HasComment("จำนวนวันลาทั้งหมด"); .HasComment("จำนวนวันลายกมา");
b.Property<double?>("LeaveDaysUsed") b.Property<double>("LeaveDaysUsed")
.HasColumnType("double") .HasColumnType("double")
.HasComment("จำนวนวันลาที่ใช้ไป"); .HasComment("จำนวนวันลาที่ใช้ไป");
@ -226,7 +214,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasIndex("LeaveTypeId"); b.HasIndex("LeaveTypeId");
b.ToTable("LeaveBeginnings", (string)null); b.ToTable("LeaveBeginnings");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveDocument", b =>
@ -288,7 +276,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasIndex("LeaveRequestId"); b.HasIndex("LeaveRequestId");
b.ToTable("LeaveDocuments", (string)null); b.ToTable("LeaveDocuments");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequest", b =>
@ -428,9 +416,6 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.Property<DateTime?>("DateAppoint") b.Property<DateTime?>("DateAppoint")
.HasColumnType("datetime(6)"); .HasColumnType("datetime(6)");
b.Property<DateTime?>("DateSendLeave")
.HasColumnType("datetime(6)");
b.Property<string>("Dear") b.Property<string>("Dear")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasComment("เรียนใคร"); .HasComment("เรียนใคร");
@ -667,7 +652,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasIndex("TypeId"); b.HasIndex("TypeId");
b.ToTable("LeaveRequests", (string)null); b.ToTable("LeaveRequests");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveRequestApprover", b =>
@ -713,13 +698,6 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
.IsRequired() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<bool>("IsAct")
.HasColumnType("tinyint(1)");
b.Property<string>("KeyId")
.IsRequired()
.HasColumnType("longtext");
b.Property<Guid>("KeycloakId") b.Property<Guid>("KeycloakId")
.HasColumnType("char(36)"); .HasColumnType("char(36)");
@ -786,7 +764,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasIndex("LeaveRequestId"); b.HasIndex("LeaveRequestId");
b.ToTable("LeaveRequestApprovers", (string)null); b.ToTable("LeaveRequestApprovers");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.AdditionalCheckRequest", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.AdditionalCheckRequest", b =>
@ -901,7 +879,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("AdditionalCheckRequests", (string)null); b.ToTable("AdditionalCheckRequests");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.CheckInJobStatus", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.CheckInJobStatus", b =>
@ -994,7 +972,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("CheckInJobStatuses", (string)null); b.ToTable("CheckInJobStatuses");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.DutyTime", b =>
@ -1079,92 +1057,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("DutyTimes", (string)null); b.ToTable("DutyTimes");
});
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.LeaveProcessJobStatus", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)")
.HasColumnOrder(0)
.HasComment("PrimaryKey")
.HasAnnotation("Relational:JsonPropertyName", "id");
b.Property<DateTime?>("CompletedDate")
.HasColumnType("datetime(6)")
.HasComment("วันเวลาที่เสร็จสิ้นการประมวลผล");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)")
.HasColumnOrder(100)
.HasComment("สร้างข้อมูลเมื่อ");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime(6)")
.HasComment("วันเวลาที่สร้างงาน");
b.Property<string>("CreatedFullName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)")
.HasColumnOrder(104)
.HasComment("ชื่อ User ที่สร้างข้อมูล");
b.Property<string>("CreatedUserId")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)")
.HasColumnOrder(101)
.HasComment("User Id ที่สร้างข้อมูล");
b.Property<DateTime>("EndDate")
.HasColumnType("datetime(6)")
.HasComment("วันสิ้นสุด");
b.Property<string>("ErrorMessage")
.HasColumnType("longtext")
.HasComment("ข้อความแสดงข้อผิดพลาด");
b.Property<string>("LastUpdateFullName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)")
.HasColumnOrder(105)
.HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด");
b.Property<string>("LastUpdateUserId")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)")
.HasColumnOrder(103)
.HasComment("User Id ที่แก้ไขข้อมูลล่าสุด");
b.Property<DateTime?>("LastUpdatedAt")
.HasColumnType("datetime(6)")
.HasColumnOrder(102)
.HasComment("แก้ไขข้อมูลล่าสุดเมื่อ");
b.Property<DateTime?>("ProcessingDate")
.HasColumnType("datetime(6)")
.HasComment("วันเวลาที่เริ่มประมวลผล");
b.Property<Guid>("RootDnaId")
.HasColumnType("char(36)")
.HasComment("รหัส Root DNA Id");
b.Property<DateTime>("StartDate")
.HasColumnType("datetime(6)")
.HasComment("วันเริ่มต้น");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext")
.HasComment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED");
b.HasKey("Id");
b.ToTable("LeaveProcessJobStatuses", (string)null);
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b =>
@ -1375,7 +1268,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("ProcessUserTimeStamps", (string)null); b.ToTable("ProcessUserTimeStamps");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserCalendar", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserCalendar", b =>
@ -1436,7 +1329,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("UserCalendars", (string)null); b.ToTable("UserCalendars");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserDutyTime", b =>
@ -1525,7 +1418,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasIndex("DutyTimeId"); b.HasIndex("DutyTimeId");
b.ToTable("UserDutyTimes", (string)null); b.ToTable("UserDutyTimes");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserTimeStamp", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.UserTimeStamp", b =>
@ -1719,7 +1612,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("UserTimeStamps", (string)null); b.ToTable("UserTimeStamps");
}); });
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b => modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.Requests.LeaveBeginning", b =>

View file

@ -40,8 +40,6 @@ namespace BMA.EHR.Infrastructure.Persistence
#endregion #endregion
public DbSet<LeaveProcessJobStatus> LeaveProcessJobStatuses { get; set; }
public LeaveDbContext(DbContextOptions<LeaveDbContext> options) : base(options) public LeaveDbContext(DbContextOptions<LeaveDbContext> options) : base(options)
{ {

View file

@ -331,7 +331,7 @@ namespace BMA.EHR.Insignia.Service.Controllers
if (req.Total + total > insigniaManage.Total) if (req.Total + total > insigniaManage.Total)
return Error(GlobalMessages.InsigniaManageOrgLimit); return Error(GlobalMessages.InsigniaManageOrgLimit);
var ocData = _userProfileRepository.GetOcByNodeId(req.OrganizationOrganizationId, 0, AccessToken); var ocData = _userProfileRepository.GetOc(req.OrganizationOrganizationId, 0, AccessToken);
var root = ocData?.Root ?? null; var root = ocData?.Root ?? null;
var rootDnaId = ocData?.RootDnaId ?? null; var rootDnaId = ocData?.RootDnaId ?? null;
await _context.InsigniaManageOrganiations.AddAsync( await _context.InsigniaManageOrganiations.AddAsync(
@ -407,10 +407,6 @@ namespace BMA.EHR.Insignia.Service.Controllers
if (uppdated == null) if (uppdated == null)
return Error(GlobalMessages.InsigniaManageNotFound); 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() var insigniaManage = await _context.InsigniaManages.AsQueryable()
.Include(x => x.InsigniaManageOrganiations) .Include(x => x.InsigniaManageOrganiations)
.FirstOrDefaultAsync(x => x.Id == uppdated.InsigniaManage.Id); .FirstOrDefaultAsync(x => x.Id == uppdated.InsigniaManage.Id);
@ -420,9 +416,6 @@ namespace BMA.EHR.Insignia.Service.Controllers
if (req.Total + total > insigniaManage.Total) if (req.Total + total > insigniaManage.Total)
return Error(GlobalMessages.InsigniaManageOrgLimit); return Error(GlobalMessages.InsigniaManageOrgLimit);
uppdated.Organization = root;
uppdated.RootDnaId = rootDnaId;
uppdated.Total = req.Total; uppdated.Total = req.Total;
uppdated.LastUpdateFullName = FullName ?? "System Administrator"; uppdated.LastUpdateFullName = FullName ?? "System Administrator";
uppdated.LastUpdateUserId = UserId ?? ""; uppdated.LastUpdateUserId = UserId ?? "";
@ -646,7 +639,7 @@ namespace BMA.EHR.Insignia.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -731,11 +724,11 @@ namespace BMA.EHR.Insignia.Service.Controllers
rawData = rawData rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// rawData = rawData rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
rawData = rawData.Where(x => rawData = rawData.Where(x =>
@ -950,7 +943,7 @@ namespace BMA.EHR.Insignia.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -1033,11 +1026,11 @@ namespace BMA.EHR.Insignia.Service.Controllers
rawData = rawData rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// rawData = rawData rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
rawData = rawData.Where(x => rawData = rawData.Where(x =>

View file

@ -2641,8 +2641,6 @@ namespace BMA.EHR.Insignia.Service.Controllers
{ {
if (item.CitizanId == null) continue; if (item.CitizanId == null) continue;
var _profile = await _userProfileRepository.GetOfficerProfileByCitizenId(item.CitizanId, AccessToken); var _profile = await _userProfileRepository.GetOfficerProfileByCitizenId(item.CitizanId, AccessToken);
if (_profile == null)
continue;
var profile = insigniaNote.InsigniaNoteProfiles.FirstOrDefault(x => x.ProfileId == _profile.Id); var profile = insigniaNote.InsigniaNoteProfiles.FirstOrDefault(x => x.ProfileId == _profile.Id);
if (profile == null) if (profile == null)
{ {
@ -3098,7 +3096,7 @@ namespace BMA.EHR.Insignia.Service.Controllers
var doc = await _documentService.UploadFileAsync(file, file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName);
insigniaNoteProfile.DocReturnInsignia = doc; insigniaNoteProfile.DocReturnInsignia = doc;
} }
var root = _userProfileRepository.GetOcByNodeId(req.OrgId, 0, AccessToken)?.Root ?? null; var root = _userProfileRepository.GetOc(req.OrgId, 0, AccessToken)?.Root ?? null;
if (req.OrgId != Guid.Parse("00000000-0000-0000-0000-000000000000")) if (req.OrgId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
{ {
if (root == null) if (root == null)
@ -3148,10 +3146,7 @@ namespace BMA.EHR.Insignia.Service.Controllers
var doc = await _documentService.UploadFileAsync(file, file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName);
insigniaNoteProfile.DocReceiveInsignia = doc; 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 (req.OrgId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
{ {
if (root == null) if (root == null)
@ -3162,7 +3157,6 @@ namespace BMA.EHR.Insignia.Service.Controllers
root = "สำนักนายกรัฐมนตรี"; root = "สำนักนายกรัฐมนตรี";
} }
insigniaNoteProfile.OrgReceiveInsignia = root; insigniaNoteProfile.OrgReceiveInsignia = root;
insigniaNoteProfile.RootDnaId = rootDnaId;
insigniaNoteProfile.OrgReceiveInsigniaId = req.OrgId; insigniaNoteProfile.OrgReceiveInsigniaId = req.OrgId;
insigniaNoteProfile.DateReceiveInsignia = req.Date; insigniaNoteProfile.DateReceiveInsignia = req.Date;
insigniaNoteProfile.LastUpdateFullName = FullName ?? "System Administrator"; insigniaNoteProfile.LastUpdateFullName = FullName ?? "System Administrator";

View file

@ -131,7 +131,7 @@ var builder = WebApplication.CreateBuilder(args);
{ {
options.ServerName = "Insignia-Server"; // ← ระบุชื่อ server options.ServerName = "Insignia-Server"; // ← ระบุชื่อ server
options.WorkerCount = 5; // ← options.WorkerCount = 5; // ←
options.Queues = new[] { "insignia","default" }; // ← worker จะรันเฉพาะ queue "insignia" options.Queues = new[] { "insignia" }; // ← worker จะรันเฉพาะ queue "insignia"
}); });

View file

@ -9,8 +9,8 @@
} }
}, },
"ElasticConfiguration": { "ElasticConfiguration": {
"Uri": "http://192.168.1.63:9200", "Uri": "http://192.168.1.40:9200",
"IndexFormat": "hrms-log-index", "IndexFormat": "bma-ehr-log-index",
"SystemName": "insignia" "SystemName": "insignia"
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
@ -31,11 +31,10 @@
//"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;" //"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": { "Jwt": {
//"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI", //"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc",
"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc", //"Issuer": "https://hrms-id.chin.in.th/realms/hrms"
"Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms" "Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
//"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU", "Issuer": "https://id.frappet.synology.me/realms/hrms"
//"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms"
}, },
"EPPlus": { "EPPlus": {
"ExcelPackage": { "ExcelPackage": {
@ -56,17 +55,11 @@
"Node": { "Node": {
"API": "https://bma-ehr.frappet.synology.me/api/v1/probation" "API": "https://bma-ehr.frappet.synology.me/api/v1/probation"
}, },
"API": "https://bma-ehr.frappet.synology.me/api/v1",
"RabbitMQ": { "RabbitMQ": {
"URL": "localhost", "URL": "localhost",
"UserName": "frappet", "UserName": "frappet",
"Password": "FPTadmin2357" "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" "API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz"
} }

View file

@ -45,7 +45,6 @@
<PackageReference Include="Microsoft.IdentityModel.Logging" Version="6.31.0" /> <PackageReference Include="Microsoft.IdentityModel.Logging" Version="6.31.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="NEST" Version="7.17.5" /> <PackageReference Include="NEST" Version="7.17.5" />
<PackageReference Include="NodaTime" Version="3.3.0" />
<PackageReference Include="runtime.osx.10.10-x64.CoreCompat.System.Drawing" Version="6.0.5.128" /> <PackageReference Include="runtime.osx.10.10-x64.CoreCompat.System.Drawing" Version="6.0.5.128" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
@ -74,9 +73,6 @@
<Content Update="wwwroot\keycloak.json"> <Content Update="wwwroot\keycloak.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
<Content Update="wwwroot\blank.jpeg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -33,7 +33,6 @@ namespace BMA.EHR.Leave.Service.Controllers
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly UserProfileRepository _userProfileRepository; private readonly UserProfileRepository _userProfileRepository;
private readonly PermissionRepository _permission; private readonly PermissionRepository _permission;
private readonly LeaveRequestRepository _leaveRequestRepository;
#endregion #endregion
@ -45,8 +44,7 @@ namespace BMA.EHR.Leave.Service.Controllers
IWebHostEnvironment hostingEnvironment, IWebHostEnvironment hostingEnvironment,
IConfiguration configuration, IConfiguration configuration,
UserProfileRepository userProfileRepository, UserProfileRepository userProfileRepository,
PermissionRepository permission, PermissionRepository permission)
LeaveRequestRepository leaveRequestRepository)
{ {
_leaveBeginningRepository = leaveBeginningRepository; _leaveBeginningRepository = leaveBeginningRepository;
_context = context; _context = context;
@ -55,7 +53,6 @@ namespace BMA.EHR.Leave.Service.Controllers
_configuration = configuration; _configuration = configuration;
_userProfileRepository = userProfileRepository; _userProfileRepository = userProfileRepository;
_permission = permission; _permission = permission;
_leaveRequestRepository = leaveRequestRepository;
} }
#endregion #endregion
@ -144,7 +141,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -169,11 +166,11 @@ namespace BMA.EHR.Leave.Service.Controllers
resData = resData resData = resData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// resData = resData resData = resData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList(); .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
resData = resData resData = resData
@ -204,9 +201,6 @@ namespace BMA.EHR.Leave.Service.Controllers
item.LeaveYear, item.LeaveYear,
item.LeaveDays, item.LeaveDays,
item.LeaveDaysUsed, item.LeaveDaysUsed,
item.LeaveCount,
item.BeginningLeaveDays,
item.BeginningLeaveCount,
item.CreatedAt, item.CreatedAt,
item.CreatedFullName, item.CreatedFullName,
item.LastUpdatedAt, item.LastUpdatedAt,
@ -378,15 +372,6 @@ namespace BMA.EHR.Leave.Service.Controllers
try try
{ {
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
// var profileId = ProfileId ?? Guid.Empty;
// var prefix = Prefix ?? "";
// var firstName = FirstName ?? "";
// var lastName = LastName ?? "";
// var rootDnaId = OrgRootDnaId ?? Guid.Empty;
// var child1DnaId = OrgChild1DnaId ?? Guid.Empty;
// var child2DnaId = OrgChild2DnaId ?? Guid.Empty;
// var child3DnaId = OrgChild3DnaId ?? Guid.Empty;
// var child4DnaId = OrgChild4DnaId ?? Guid.Empty;
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_LEAVE_HISTORY"); var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_LEAVE_HISTORY");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission); var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
@ -398,41 +383,17 @@ namespace BMA.EHR.Leave.Service.Controllers
if (leaveBeginning == null) if (leaveBeginning == null)
return Error("ไม่พบข้อมูลที่ต้องการแก้ไข", StatusCodes.Status404NotFound); return Error("ไม่พบข้อมูลที่ต้องการแก้ไข", StatusCodes.Status404NotFound);
var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken); var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken);
if (profile == null) if (profile == null)
{ {
return Error("ไม่พบข้อมูลข้าราชการหรือลูกจ้าง", StatusCodes.Status404NotFound); return Error("ไม่พบข้อมูลข้าราชการหรือลูกจ้าง", StatusCodes.Status404NotFound);
} }
var startFiscalDate = new DateTime(DateTime.Now.Year - 1, 10, 1);
var endFiscalDate = new DateTime(DateTime.Now.Year, 9, 30);
if (req.LeaveDaysUsed is null || req.LeaveCount is null)
{
var systemLeaveDays = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUserByProfile(req.ProfileId, req.LeaveTypeId, startFiscalDate, endFiscalDate,endFiscalDate.AddDays(1));
var systemLeaveCount = await _leaveRequestRepository.GetSumApproveLeaveCountByTypeAndRangeForUserByProfile(req.ProfileId, req.LeaveTypeId, startFiscalDate, endFiscalDate,endFiscalDate.AddDays(1));
leaveBeginning.LeaveDaysUsed = req.BeginningLeaveDays + systemLeaveDays;
leaveBeginning.LeaveCount = req.BeginningLeaveCount + systemLeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
}
else
{
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.LeaveCount = req.LeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
//var systemLeaveDays = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(profile.Keycloak ?? Guid.Empty, req.LeaveTypeId, startFiscalDate, endFiscalDate);
//var systemLeaveCount = await _leaveRequestRepository.GetSumApproveLeaveCountByTypeAndRangeForUser2(profile.Keycloak ?? Guid.Empty, req.LeaveTypeId, startFiscalDate, endFiscalDate);
}
leaveBeginning.LeaveTypeId = req.LeaveTypeId; leaveBeginning.LeaveTypeId = req.LeaveTypeId;
leaveBeginning.LeaveYear = req.LeaveYear; leaveBeginning.LeaveYear = req.LeaveYear;
leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDays = req.LeaveDays;
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.ProfileId = req.ProfileId;
leaveBeginning.Prefix = profile.Prefix; leaveBeginning.Prefix = profile.Prefix;
@ -473,17 +434,6 @@ namespace BMA.EHR.Leave.Service.Controllers
try try
{ {
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId); var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
// var profileId = ProfileId ?? Guid.Empty;
// var prefix = Prefix ?? "";
// var firstName = FirstName ?? "";
// var lastName = LastName ?? "";
// var rootDnaId = OrgRootDnaId ?? Guid.Empty;
// var child1DnaId = OrgChild1DnaId ?? Guid.Empty;
// var child2DnaId = OrgChild2DnaId ?? Guid.Empty;
// var child3DnaId = OrgChild3DnaId ?? Guid.Empty;
// var child4DnaId = OrgChild4DnaId ?? Guid.Empty;
var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_LEAVE_HISTORY"); var getPermission = await _permission.GetPermissionAPIAsync("CREATE", "SYS_LEAVE_HISTORY");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission); var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200") if (jsonData["status"]?.ToString() != "200")
@ -508,26 +458,10 @@ namespace BMA.EHR.Leave.Service.Controllers
} }
var leaveBeginning = new LeaveBeginning(); var leaveBeginning = new LeaveBeginning();
if (req.LeaveDaysUsed is null || req.LeaveCount is null)
{
leaveBeginning.LeaveDaysUsed = req.BeginningLeaveDays;
leaveBeginning.LeaveCount = req.BeginningLeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
}
else
{
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.LeaveCount = req.LeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
}
leaveBeginning.LeaveTypeId = req.LeaveTypeId; leaveBeginning.LeaveTypeId = req.LeaveTypeId;
leaveBeginning.LeaveYear = req.LeaveYear; leaveBeginning.LeaveYear = req.LeaveYear;
leaveBeginning.LeaveDays = req.LeaveDays; leaveBeginning.LeaveDays = req.LeaveDays;
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.ProfileId = req.ProfileId; leaveBeginning.ProfileId = req.ProfileId;
leaveBeginning.Prefix = profile.Prefix; leaveBeginning.Prefix = profile.Prefix;
@ -555,126 +489,6 @@ namespace BMA.EHR.Leave.Service.Controllers
} }
} }
[HttpPut("schedule")]
[AllowAnonymous]
public async Task<ActionResult<ResponseObject>> 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<ActionResult<ResponseObject>> ScheduleUpdateDnaAsync([FromBody] List<ScheduleUpdateDnaDto> 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 #endregion
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -12,21 +12,4 @@
public string Reason { get; set; } public string Reason { get; set; }
} }
public class ApproveRequestListItemDto
{
/// <summary>
/// id ของ record รายการคำขอลงเวลาพิเศษนั้นๆ
/// </summary>
public Guid RecId { get; set; }
public string CheckInTime { get; set; }
public string CheckOutTime { get; set; }
public string CheckInStatus { get; set; }
public string CheckOutStatus { get; set; }
public string Reason { get; set; }
}
} }

View file

@ -12,25 +12,4 @@ namespace BMA.EHR.Leave.Service.DTOs.ChangeRound
public string Remark { get; set; } 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; }
}
} }

View file

@ -17,9 +17,5 @@
public string? sortBy { get; set; } public string? sortBy { get; set; }
public bool? descending { get; set; } public bool? descending { get; set; }
public Guid? SelectedNodeId { get; set; }
public int? SelectedNode { get; set; }
} }
} }

View file

@ -17,11 +17,5 @@
public string LeaveTimeAfterNoon { get;set; } public string LeaveTimeAfterNoon { get;set; }
public DateTime? EffectiveDate { 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; }
} }
} }

View file

@ -14,19 +14,10 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveBeginnings
[Required, Comment("ปีงบประมาณ")] [Required, Comment("ปีงบประมาณ")]
public int LeaveYear { get; set; } = 0; public int LeaveYear { get; set; } = 0;
[Required, Comment("จำนวนวันลาที่ได้รับ")] [Required, Comment("จำนวนวันลายกมา")]
public double LeaveDays { get; set; } = 0.0; public double LeaveDays { get; set; } = 0.0;
[Required, Comment("จำนวนวันลาที่ใช้ไป")] [Required, Comment("จำนวนวันลาที่ใช้ไป")]
public double LeaveDaysUsed { get; set; } = 0.0; 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;
} }
} }

View file

@ -17,47 +17,7 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveBeginnings
[Required, Comment("จำนวนวันลายกมา")] [Required, Comment("จำนวนวันลายกมา")]
public double LeaveDays { get; set; } = 0.0; public double LeaveDays { get; set; } = 0.0;
[Comment("จำนวนวันลาที่ใช้ไป")] [Required, Comment("จำนวนวันลาที่ใช้ไป")]
public double? LeaveDaysUsed { get; set; } public double LeaveDaysUsed { get; set; } = 0.0;
[Comment("จำนวนครั้งที่ลาสะสม")]
public int? LeaveCount { get; set; }
[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; }
} }
} }

View file

@ -1,23 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest
{
/// <summary>
/// ข้อมูลสำหรับสร้าง Job ประมวลผลวันลา โดยมีช่วงวันที่เริ่มต้นและสิ้นสุดของการประมวลผลวันลา
/// </summary>
public class CreateLeaveProcessJobDto
{
/// <summary>
/// วันที่เริ่มต้นของการประมวลผลวันลา
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
/// วันที่สิ้นสุดของการประมวลผลวันลา
/// </summary>
public DateTime EndDate { get; set; }
}
}

View file

@ -19,7 +19,5 @@
public DateTime LeaveEndDate { get; set; } public DateTime LeaveEndDate { get; set; }
public Guid KeycloakId { get; set; } public Guid KeycloakId { get; set; }
public double LeaveTotal { get; set; }
} }
} }

View file

@ -147,10 +147,6 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest
public List<GetLeaveApproverDto> Approvers { get; set; } = new(); public List<GetLeaveApproverDto> Approvers { get; set; } = new();
public Guid? KeycloakUserId { get; set; } = Guid.Empty; public Guid? KeycloakUserId { get; set; } = Guid.Empty;
public double LeaveDraftSummary { get; set; } = 0;
public double LeaveWaitingSummary { get; set; } = 0;
} }
public class GetLeaveApproverDto public class GetLeaveApproverDto
@ -174,8 +170,5 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest
public string ApproveStatus { get; set; } = string.Empty; public string ApproveStatus { get; set; } = string.Empty;
public string Comment { get; set; } = string.Empty; public string Comment { get; set; } = string.Empty;
public bool isAct { get; set; } = false;
public string keyId { get; set; } = string.Empty;
} }
} }

View file

@ -37,7 +37,5 @@
public bool? HajjDayStatus { get; set; } public bool? HajjDayStatus { get; set; }
public string? ProfileType { get; set; } public string? ProfileType { get; set; }
public double LeaveTotal { get; set; }
} }
} }

View file

@ -51,10 +51,5 @@
public string? CurrentProvince { get; set; } public string? CurrentProvince { get; set; }
public string? CurrentZipCode { get; set; } public string? CurrentZipCode { get; set; }
public int GovAge { get; set; } = 0;
public double LeaveDraftSummary { get; set; } = 0;
public double LeaveWaitingSummary { get; set; } = 0;
} }
} }

View file

@ -37,11 +37,5 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest
[JsonProperty("organizationName")] [JsonProperty("organizationName")]
public string OrganizationName { get; set; } = string.Empty; public string OrganizationName { get; set; } = string.Empty;
[JsonProperty("isAct")]
public bool isAct { get; set; } = false;
[JsonProperty("keyId")]
public string keyId { get; set; } = string.Empty;
} }
} }

View file

@ -18,13 +18,11 @@ using System.Text;
using Hangfire; using Hangfire;
using Hangfire.MySql; using Hangfire.MySql;
using System.Transactions; using System.Transactions;
using BMA.EHR.Application.Repositories.Leaves.LeaveRequests;
using BMA.EHR.Leave.Service.Filters; using BMA.EHR.Leave.Service.Filters;
using Hangfire.Common; using Hangfire.Common;
using BMA.EHR.Application.Repositories.Leaves.TimeAttendants; using BMA.EHR.Application.Repositories.Leaves.TimeAttendants;
using BMA.EHR.Leave.Service.Extensions; using BMA.EHR.Leave.Service.Extensions;
using BMA.EHR.Leave.Service.Services; using BMA.EHR.Leave.Service.Services;
using BMA.EHR.Leave.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// ตั้ง TimeZone เป็น Asia/Bangkok ในโค้ด // ตั้ง TimeZone เป็น Asia/Bangkok ในโค้ด
@ -97,16 +95,8 @@ builder.Services.AddLeaveApplication();
builder.Services.AddPersistence(builder.Configuration); builder.Services.AddPersistence(builder.Configuration);
builder.Services.AddLeavePersistence(builder.Configuration); builder.Services.AddLeavePersistence(builder.Configuration);
builder.Services.AddTransient<HolidayService>(); builder.Services.AddTransient<HolidayService>();
builder.Services.AddTransient<NotificationService>();
// Configure HttpClient with increased timeout for long-running operations (e.g., RabbitMQ Management API)
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
builder.Services.AddTransient(sp =>
{
var httpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient();
httpClient.Timeout = TimeSpan.FromMinutes(10); // Set timeout to 10 minutes
return httpClient;
});
builder.Services.AddControllers(options => builder.Services.AddControllers(options =>
{ {
@ -122,7 +112,7 @@ builder.Services.AddHealthChecks();
builder.Services.AddRabbitMqConnectionPooling(builder.Configuration); builder.Services.AddRabbitMqConnectionPooling(builder.Configuration);
// Add Hangfire services. // Add Hangfire services.
var hangfireConnection = builder.Configuration.GetConnectionString("defaultConnection"); var defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddHangfire(configuration => configuration builder.Services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
@ -130,24 +120,19 @@ builder.Services.AddHangfire(configuration => configuration
.UseRecommendedSerializerSettings() .UseRecommendedSerializerSettings()
.UseStorage( .UseStorage(
new MySqlStorage( new MySqlStorage(
hangfireConnection, defaultConnection,
new MySqlStorageOptions new MySqlStorageOptions
{ {
TransactionIsolationLevel = IsolationLevel.ReadCommitted,
QueuePollInterval = TimeSpan.FromSeconds(15), QueuePollInterval = TimeSpan.FromSeconds(15),
JobExpirationCheckInterval = TimeSpan.FromHours(1), JobExpirationCheckInterval = TimeSpan.FromHours(1),
CountersAggregateInterval = TimeSpan.FromMinutes(5), CountersAggregateInterval = TimeSpan.FromMinutes(5),
PrepareSchemaIfNecessary = true, PrepareSchemaIfNecessary = true,
DashboardJobListLimit = 50000, DashboardJobListLimit = 50000,
TransactionTimeout = TimeSpan.FromMinutes(1), TransactionTimeout = TimeSpan.FromMinutes(1),
InvisibilityTimeout = TimeSpan.FromHours(3), TablesPrefix = "Hangfire"
TablesPrefix = "Hangfire_Leave"
}))); })));
builder.Services.AddHangfireServer(options => builder.Services.AddHangfireServer();
{
options.ServerName = "Leave-Server"; // ← ระบุชื่อ server
options.WorkerCount = 5; // ←
options.Queues = new[] { "leave","default" }; // ← worker จะรันเฉพาะ queue "leave"
});
var app = builder.Build(); var app = builder.Build();
@ -195,42 +180,9 @@ app.UseHangfireDashboard("/hangfire", new DashboardOptions()
var manager = new RecurringJobManager(); var manager = new RecurringJobManager();
if (manager != null) if (manager != null)
{ {
manager.AddOrUpdate("ปรับปรุงรอบการลงเวลาทำงาน", Job.FromExpression<UserDutyTimeRepository>(x => x.UpdateUserDutyTime()), "0 1 * * *", manager.AddOrUpdate("ปรับปรุงรอบการลงเวลาทำงาน", Job.FromExpression<UserDutyTimeRepository>(x => x.UpdateUserDutyTime()), "0 1 * * *", bangkokTimeZone);
new RecurringJobOptions
{
TimeZone = bangkokTimeZone,
QueueName = "leave"
});
// ทำความสะอาดข้อมูล CheckIn Job Status ที่เก่ากว่า 30 วัน - รันทุกวันเวลา 02:00 น. // ทำความสะอาดข้อมูล CheckIn Job Status ที่เก่ากว่า 30 วัน - รันทุกวันเวลา 02:00 น.
manager.AddOrUpdate("ทำความสะอาดข้อมูล CheckIn Job Status", Job.FromExpression<CheckInJobStatusRepository>(x => x.CleanupOldJobsAsync(30)), "0 2 * * *", manager.AddOrUpdate("ทำความสะอาดข้อมูล CheckIn Job Status", Job.FromExpression<CheckInJobStatusRepository>(x => x.CleanupOldJobsAsync(30)), "0 2 * * *", bangkokTimeZone);
new RecurringJobOptions
{
TimeZone = bangkokTimeZone,
QueueName = "leave"
});
manager.AddOrUpdate("Proceess Beginning สำหรับการลาล่วงหน้า", Job.FromExpression<LeaveBeginningRepository>(x => x.ProcessEarlyLeaveRequestSchedule()), "0 1 1 10 *",
new RecurringJobOptions
{
TimeZone = bangkokTimeZone,
QueueName = "leave"
});
// ตรวจสอบและ mark งาน CheckIn ที่ค้างเกิน 30 นาทีเป็น FAILED - รันทุก 15 นาที
// manager.AddOrUpdate("ตรวจสอบงาน CheckIn ที่ค้างเกินเวลา", Job.FromExpression<CheckInJobStatusRepository>(x => x.MarkStaleJobsAsFailedAsync(30)), "*/15 * * * *",
// new RecurringJobOptions
// {
// TimeZone = bangkokTimeZone,
// QueueName = "leave"
// });
//
// manager.AddOrUpdate("ประมวลผลงานที่ค้างอยู่ในสถานะ Pending หรือ Processing", Job.FromExpression<LeaveProcessJobStatusRepository>(x => x.ProcessPendingJobsAsync()), "0 3 * * *",
// new RecurringJobOptions
// {
// TimeZone = bangkokTimeZone,
// QueueName = "leave" // ← กำหนด queue
// });
} }
// apply migrations // apply migrations

View file

@ -1,58 +0,0 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BMA.EHR.Leave.Services;
public class NotificationService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<NotificationService> _logger;
private readonly IConfiguration _configuration;
private const string NotifyEndpoint = "https://hrmsbkk.case-collection.com/api/v1/org/through-socket/notify-from-token";
public NotificationService(IHttpClientFactory httpClientFactory, ILogger<NotificationService> logger, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configuration = configuration;
}
public async Task SendNotificationAsync(string? token, bool error, string message)
{
if (string.IsNullOrEmpty(token))
{
_logger.LogWarning("Cannot send import notification: token is null or empty.");
return;
}
try
{
var client = _httpClientFactory.CreateClient("default");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
var payload = new
{
error,
message
};
var json = JsonConvert.SerializeObject(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(NotifyEndpoint, content);
if (!response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogWarning("Import notification failed with status {StatusCode}: {Body}", response.StatusCode, responseBody);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send import notification: {Message}", ex.Message);
}
}
}

View file

@ -9,8 +9,8 @@
} }
}, },
"ElasticConfiguration": { "ElasticConfiguration": {
"Uri": "http://192.168.1.63:9200", "Uri": "http://192.168.1.40:9200",
"IndexFormat": "hrms-log-index", "IndexFormat": "bma-ehr-log-index",
"SystemName": "leave" "SystemName": "leave"
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
@ -19,19 +19,20 @@
// "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;", // "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;" // "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 ID=root;Password=12345678;Port=3306;Database=hrms;Allow User Variables=True;Convert Zero Datetime=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 ID=root;Password=12345678;Port=3306;Database=hrms_exam;Allow User Variables=True;Convert Zero Datetime=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 ID=root;Password=12345678;Port=3306;Database=hrms_leave;Allow User Variables=True;Convert Zero Datetime=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=127.0.0.1;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=13306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;", //"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=127.0.0.1;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=13306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;", //"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=127.0.0.1;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=13306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;" //"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;"
}, },
"Jwt": { "Jwt": {
//"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc", "Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc",
"Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms" "Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms"
// "Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU", //"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU",
// "Issuer": "https://hrms-id.bangkok.go.th/realms/hrms" //"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms"
}, },
"EPPlus": { "EPPlus": {
"ExcelPackage": { "ExcelPackage": {
@ -43,10 +44,6 @@
"AccessKey": "iwvzjyjgz0BKtLPmMpPu", "AccessKey": "iwvzjyjgz0BKtLPmMpPu",
"SecretKey": "Yv56vwctYdIspDknRJ46xztcBDzteGF3elZiDcAr", "SecretKey": "Yv56vwctYdIspDknRJ46xztcBDzteGF3elZiDcAr",
"BucketName": "hrms-fpt" "BucketName": "hrms-fpt"
// "Endpoint": "https://hrms-s3.bangkok.go.th/",
// "AccessKey": "frappet",
// "SecretKey": "FPTadmin2357",
// "BucketName": "bma-ehr-fpt"
}, },
"Protocol": "HTTPS", "Protocol": "HTTPS",
"Node": { "Node": {
@ -58,11 +55,6 @@
"Password": "12345678", "Password": "12345678",
"Queue": "hrms-checkin-queue-dev", "Queue": "hrms-checkin-queue-dev",
"URL": "http://192.168.1.63:9122/api/queues/%2F/" "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": { "Mail": {
"Server": "mail.bangkok.go.th", "Server": "mail.bangkok.go.th",
@ -76,10 +68,7 @@
"API": "https://hrmsbkk.case-collection.com/api/v1", "API": "https://hrmsbkk.case-collection.com/api/v1",
"APIV2": "https://hrmsbkk.case-collection.com/api/v2", "APIV2": "https://hrmsbkk.case-collection.com/api/v2",
"VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com", "VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com",
// "Domain": "https://hrms.bangkok.go.th", //"API": "https://bma-ehr.frappet.synology.me/api/v1",
// "APIPROBATION": "https://hrms.bangkok.go.th/api/v1/probation", //"API": "https://bma-hrms.bangkok.go.th/api/v1",
// "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" "API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz"
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View file

@ -184,31 +184,6 @@ namespace BMA.EHR.Placement.Service.Controllers
} }
} }
/// <summary>
/// ลบ Notification ทั้งหมดของ user ที่ login (Hard delete)
/// </summary>
/// <returns>จำนวนรายการที่ถูกลบ</returns>
/// <response code="200">เมื่อทำการลบข้อมูลจาก Relational Database สำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("my-notifications")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> PermanentDeleteAllMyNotificationsAsync()
{
try
{
var affectedRows = await _notificationRepository.DeleteAllMyNotificationsAsync();
return Success(affectedRows);
}
catch
{
throw;
}
}
#endregion #endregion
} }

View file

@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -239,11 +239,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointments = placementAppointments placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId).ToList(); .Where(x => x.rootDnaId == nodeId).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// placementAppointments = placementAppointments placementAppointments = placementAppointments
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
placementAppointments = placementAppointments.Where(x => placementAppointments = placementAppointments.Where(x =>
@ -554,7 +554,7 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointment.positionAreaOld = org.result.positionArea; placementAppointment.positionAreaOld = org.result.positionArea;
placementAppointment.PositionLevelOld = org.result.posLevelName; placementAppointment.PositionLevelOld = org.result.posLevelName;
placementAppointment.PositionTypeOld = org.result.posTypeName; placementAppointment.PositionTypeOld = org.result.posTypeName;
placementAppointment.PositionNumberOld = org.result.posNo; placementAppointment.PositionNumberOld = org.result.nodeShortName + " " + org.result.posMasterNo;
placementAppointment.OrganizationOld = (org.result.child4 == null ? "" : org.result.child4 + "\n") + placementAppointment.OrganizationOld = (org.result.child4 == null ? "" : org.result.child4 + "\n") +
(org.result.child3 == null ? "" : org.result.child3 + "\n") + (org.result.child3 == null ? "" : org.result.child3 + "\n") +
(org.result.child2 == null ? "" : org.result.child2 + "\n") + (org.result.child2 == null ? "" : org.result.child2 + "\n") +
@ -676,7 +676,6 @@ namespace BMA.EHR.Placement.Service.Controllers
uppdated.posMasterNo = req.posMasterNo; uppdated.posMasterNo = req.posMasterNo;
uppdated.position = req.positionName; uppdated.position = req.positionName;
uppdated.PositionExecutive = req.posExecutiveName; uppdated.PositionExecutive = req.posExecutiveName;
uppdated.posExecutiveId = req.posExecutiveId;
uppdated.positionExecutiveField = req.positionExecutiveField; uppdated.positionExecutiveField = req.positionExecutiveField;
uppdated.positionArea = req.positionArea; uppdated.positionArea = req.positionArea;
uppdated.positionField = req.positionField; uppdated.positionField = req.positionField;
@ -1011,14 +1010,10 @@ namespace BMA.EHR.Placement.Service.Controllers
positionExecutive = p.PositionExecutive, positionExecutive = p.PositionExecutive,
positionExecutiveField = p.positionExecutiveField, positionExecutiveField = p.positionExecutiveField,
positionArea = p.positionArea, positionArea = p.positionArea,
positionTypeId = p.posTypeId,
positionType = p.posTypeName, positionType = p.posTypeName,
positionLevelId = p.posLevelId,
positionLevel = p.posLevelName, positionLevel = p.posLevelName,
posmasterId = p.posmasterId, posmasterId = p.posmasterId,
positionId = p.positionId, positionId = p.positionId,
posExecutiveId = p.posExecutiveId,
positionField = p.positionField,
commandId = r.commandId, commandId = r.commandId,
orgRoot = p.root, orgRoot = p.root,
orgChild1 = p.child1, orgChild1 = p.child1,
@ -1041,39 +1036,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
/// <summary> /// <summary>
@ -1242,14 +1222,10 @@ namespace BMA.EHR.Placement.Service.Controllers
positionExecutive = p.PositionExecutive, positionExecutive = p.PositionExecutive,
positionExecutiveField = p.positionExecutiveField, positionExecutiveField = p.positionExecutiveField,
positionArea = p.positionArea, positionArea = p.positionArea,
positionTypeId = p.posTypeId,
positionType = p.posTypeName, positionType = p.posTypeName,
positionLevelId = p.posLevelId,
positionLevel = p.posLevelName, positionLevel = p.posLevelName,
posmasterId = p.posmasterId, posmasterId = p.posmasterId,
positionId = p.positionId, positionId = p.positionId,
posExecutiveId = p.posExecutiveId,
positionField = p.positionField,
commandId = r.commandId, commandId = r.commandId,
orgRoot = p.root, orgRoot = p.root,
orgChild1 = p.child1, orgChild1 = p.child1,
@ -1272,39 +1248,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
/// <summary> /// <summary>
@ -1487,39 +1448,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
/// <summary> /// <summary>
@ -1707,39 +1653,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
/// <summary> /// <summary>
@ -1920,14 +1851,10 @@ namespace BMA.EHR.Placement.Service.Controllers
positionExecutive = p.PositionExecutive, positionExecutive = p.PositionExecutive,
positionExecutiveField = p.positionExecutiveField, positionExecutiveField = p.positionExecutiveField,
positionArea = p.positionArea, positionArea = p.positionArea,
positionTypeId = p.posTypeId,
positionType = p.posTypeName, positionType = p.posTypeName,
positionLevelId = p.posLevelId,
positionLevel = p.posLevelName, positionLevel = p.posLevelName,
posmasterId = p.posmasterId, posmasterId = p.posmasterId,
positionId = p.positionId, positionId = p.positionId,
posExecutiveId = p.posExecutiveId,
positionField = p.positionField,
commandId = r.commandId, commandId = r.commandId,
orgRoot = p.root, orgRoot = p.root,
orgChild1 = p.child1, orgChild1 = p.child1,
@ -1950,39 +1877,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
/// <summary> /// <summary>
@ -2074,7 +1986,7 @@ namespace BMA.EHR.Placement.Service.Controllers
} }
/// <summary> /// <summary>
/// ออกคำสั่ง C-PM-47 โปรดเกล้าฯ แต่งตั้งให้ดำรงตำแหน่ง /// ออกคำสั่ง C-PM-47
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
/// <response code="200"></response> /// <response code="200"></response>
@ -2104,8 +2016,6 @@ namespace BMA.EHR.Placement.Service.Controllers
positionLevel = p.posLevelName, positionLevel = p.posLevelName,
posmasterId = p.posmasterId, posmasterId = p.posmasterId,
positionId = p.positionId, positionId = p.positionId,
posExecutiveId = p.posExecutiveId,
positionField = p.positionField,
commandId = r.commandId, commandId = r.commandId,
orgRoot = p.root, orgRoot = p.root,
orgChild1 = p.child1, orgChild1 = p.child1,
@ -2128,39 +2038,24 @@ namespace BMA.EHR.Placement.Service.Controllers
remark = r.remark, remark = r.remark,
}).ToList(); }).ToList();
#region Old: Circular Flow var baseAPIOrg = _configuration["API"];
// var baseAPIOrg = _configuration["API"]; var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current";
// var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-current"; using (var client = new HttpClient())
// 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
// {
// data = resultData,
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// await _context.SaveChangesAsync();
// }
// }
#endregion
// New: Linear Flow - Task #224 ปรับให้เป็น process ที่ควรบันทึกตามลำดับ
var now = DateTime.Now;
data.ForEach(profile =>
{ {
profile.Status = "DONE"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
profile.LastUpdateFullName = FullName ?? "System Administrator"; client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
profile.LastUpdateUserId = UserId ?? ""; var _res = await client.PostAsJsonAsync(apiUrlOrg, new
profile.LastUpdatedAt = now; {
}); data = resultData,
await _context.SaveChangesAsync(); });
var _result = await _res.Content.ReadAsStringAsync();
// Return resultData for Node to process directly (Linear Flow) if (_res.IsSuccessStatusCode)
return Success(resultData); {
data.ForEach(profile => profile.Status = "DONE");
await _context.SaveChangesAsync();
}
}
return Success();
} }
} }
} }

View file

@ -110,7 +110,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId ? profileAdmin?.RootDnaId
: ""; : "";
} }
else if (role == "ROOT" /*|| role == "PARENT"*/) else if (role == "ROOT" || role == "PARENT")
{ {
nodeId = profileAdmin?.RootDnaId; nodeId = profileAdmin?.RootDnaId;
} }
@ -232,11 +232,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointments = placementAppointments placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId).ToList(); .Where(x => x.rootDnaId == nodeId).ToList();
} }
// else if (role == "PARENT") else if (role == "PARENT")
// { {
// placementAppointments = placementAppointments placementAppointments = placementAppointments
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList(); .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// } }
else if (role == "NORMAL") else if (role == "NORMAL")
{ {
placementAppointments = placementAppointments.Where(x => placementAppointments = placementAppointments.Where(x =>
@ -542,7 +542,7 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointment.positionOld = org.result.position; placementAppointment.positionOld = org.result.position;
placementAppointment.PositionLevelOld = org.result.posLevelName; placementAppointment.PositionLevelOld = org.result.posLevelName;
placementAppointment.PositionTypeOld = org.result.posTypeName; placementAppointment.PositionTypeOld = org.result.posTypeName;
placementAppointment.PositionNumberOld = org.result.posNo; placementAppointment.PositionNumberOld = org.result.nodeShortName + " " + org.result.posMasterNo;
placementAppointment.OrganizationOld = (org.result.child4 == null ? "" : org.result.child4 + "\n") + placementAppointment.OrganizationOld = (org.result.child4 == null ? "" : org.result.child4 + "\n") +
(org.result.child3 == null ? "" : org.result.child3 + "\n") + (org.result.child3 == null ? "" : org.result.child3 + "\n") +
(org.result.child2 == null ? "" : org.result.child2 + "\n") + (org.result.child2 == null ? "" : org.result.child2 + "\n") +

Some files were not shown because too many files have changed in this diff Show more