Compare commits

...
Sign in to create a new pull request.

96 commits
develop ... dev

Author SHA1 Message Date
Suphonchai Phoonsawat
c65a4a04ac Merge branch 'develop' into working
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m44s
Build & Deploy Placement Service / build (push) Successful in 2m8s
2026-04-23 19:12:24 +07:00
Suphonchai Phoonsawat
d58c7dc07e Logic การคำนวนวันลา แบบร่าง และ นะหว่างพิจาณา #1567 2026-04-23 19:11:54 +07:00
Suphonchai Phoonsawat
bb329f86de เพิ่ม DateSendLeave และปรับ Logic การดึงค่าวันที่ยื่นลา #1567 2026-04-23 15:48:20 +07:00
harid
b3298e88c6 fix path separator
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 1m49s
2026-04-21 10:34:21 +07:00
harid
04d0067ee8 ถ้ามีรักษาการแก้สิทธิ์ BROTHER
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m58s
2026-04-20 16:38:58 +07:00
harid
c035c13405 check runtime
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 1m47s
2026-04-20 14:31:28 +07:00
harid
2e9db2d42c รายงานประกาศเกษียณ #2262, #2261
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 1m50s
2026-04-20 12:37:06 +07:00
Suphonchai Phoonsawat
1389df0225 แก้ไข
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m54s
ถ้าไม่ได้ Add สิทธิ์มา จะข้ามตำแหน่งนั้นไป
แก้บั้กการแสดงข้อมูล กรณี "ROOT"

#2431
2026-04-20 11:42:41 +07:00
Suphonchai Phoonsawat
058027ea29 เปลี่ยน DEFAULT สิทธิ์เป็น "CHILD" กรณีไม่ตั้งค่ามา #2431
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m53s
2026-04-17 20:11:18 +07:00
Suphonchai Phoonsawat
ee2d16925a แก้ไข รักษาการ ถ้าไม่ได้ใส่ privilage มาจะให้ default = "PARENT" #2431
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 2m7s
2026-04-17 19:21:30 +07:00
Suphonchai Phoonsawat
42f3813a7a Merge branch 'develop' into working
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 2m2s
2026-04-17 15:42:36 +07:00
Suphonchai Phoonsawat
7bafbf5001 เพิ่มรายการรักษาการ #2431 2026-04-17 15:35:29 +07:00
harid
db99630e0d fix #2430
All checks were successful
Build & Deploy Placement Service / build (push) Successful in 1m59s
2026-04-17 15:18:30 +07:00
Suphonchai Phoonsawat
34ec9bb77c Remove Check Pending Status For Cancel Leave #2432
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m54s
2026-04-17 10:31:09 +07:00
Suphonchai Phoonsawat
5606e8b50a Change GetProfileByKeycloakIdNewAsync To GetProfileByKeycloakIdNew2Async 2026-04-17 09:41:52 +07:00
Suphonchai Phoonsawat
ee4e9c3699 แก้ leave/detail เป็น leave-reject/detail สำหรับรายการยกเลิก #2432
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m51s
2026-04-16 21:30:17 +07:00
Suphonchai Phoonsawat
6efeec3f1f เพิ่ม List ของการเจ้หน้าที่ ส่ง noti ขอยกเลิกการลา #2432
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m52s
2026-04-16 19:05:26 +07:00
harid
c34fe35506 API ยกเลิกการส่งตัวบรรจุผู้สอบผ่าน
All checks were successful
Build & Deploy Placement Service / build (push) Successful in 1m57s
2026-04-16 11:57:47 +07:00
adisak
678329b5df #2392 fix departmentName null
All checks were successful
Build & Deploy Insignia Service / build (push) Successful in 2m13s
2026-04-16 11:31:03 +07:00
Suphonchai Phoonsawat
057b51390e add some code
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m50s
2026-04-09 12:07:11 +07:00
harid
8950073485 ส่งรายชื่อไปออกคำสั่ง C-PM-25, C-PM-26 ให้ปั๊ม commandCode #2377
All checks were successful
Build & Deploy Discipline Service / build (push) Successful in 1m56s
2026-04-03 16:03:01 +07:00
Suphonchai Phoonsawat
bf92f6933e Refactor user profile retrieval method in InsigniaRequestController #2390
All checks were successful
Build & Deploy Insignia Service / build (push) Successful in 1m41s
2026-04-03 12:17:39 +07:00
Suphonchai Phoonsawat
cea1c4b64e Merge branch 'develop' into working
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m39s
2026-04-03 12:09:32 +07:00
Suphonchai Phoonsawat
cef41506a8 Change Amount property to nullable int in GetProfileLeaveByKeycloakDto #2411 2026-04-03 12:09:00 +07:00
bceb4d3096 update emp status resign
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 1m41s
2026-04-03 11:45:52 +07:00
adisak
06956284d7 #2381
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 2m1s
2026-04-02 17:50:18 +07:00
Suphonchai Phoonsawat
6b8eddcbc0 Add Insignia launch configuration and improve null checks in InsigniaRequestController #2388
All checks were successful
Build & Deploy Insignia Service / build (push) Successful in 1m54s
2026-04-02 11:36:59 +07:00
Suphonchai Phoonsawat
a4a5d13203 Update InsigniaRequestController to use GetOcByNodeId and include RootDnaId in insigniaNoteProfile #2390
All checks were successful
Build & Deploy Insignia Service / build (push) Successful in 2m3s
2026-04-02 11:09:36 +07:00
Suphonchai Phoonsawat
69b89dfc90 Add GetOcByNodeId method to UserProfileRepository and update InsigniaManageController to use it #2389 2026-04-02 11:00:14 +07:00
Suphonchai Phoonsawat
ea694bfda2 Fix effective date retrieval in LeaveReportController by using ProfileId instead of Id #2400
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m48s
2026-04-02 09:51:45 +07:00
Suphonchai Phoonsawat
6691303ea7 Merge branch 'working' into develop
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m52s
2026-04-01 12:35:00 +07:00
Suphonchai Phoonsawat
8ea572d46c Refactor LeaveReportController to improve duty time retrieval and handle default round logic 2026-04-01 12:30:42 +07:00
Suphonchai Phoonsawat
2ecef0792c Merge branch 'working' into develop
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m46s
2026-04-01 12:24:45 +07:00
Suphonchai Phoonsawat
1cf780ecd0 Refactor LeaveController to streamline profile retrieval and duty time handling 2026-04-01 12:24:00 +07:00
harid
bf6ea555fc fix รายงานมาสาย ข้อมูลไม่แสดง #2395
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m44s
2026-03-31 14:23:51 +07:00
Suphonchai Phoonsawat
8fa105606b Refactor LeaveProcessJobStatusRepository to filter employee records by status and ensure proper task processing
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m48s
2026-03-31 11:45:48 +07:00
Suphonchai Phoonsawat
47c0cfc62a Refactor leave remark generation logic in LeaveReportController to handle single and multi-day leave requests more accurately 2026-03-31 11:32:17 +07:00
Suphonchai Phoonsawat
932d5e75c7 Refactor LeaveProcessJobStatusRepository to update API endpoint paths and comment out JSON file writing logic 2026-03-31 11:28:12 +07:00
Suphonchai Phoonsawat
a50153f32c Refactor LeaveProcessJobStatusRepository to enhance leave remark generation logic and update file export functionality with environment path handling 2026-03-31 11:26:28 +07:00
Suphonchai Phoonsawat
d85bab11b2 Add ProcessEmpTaskAsync method to handle employee task processing and integrate with external API for attendance reporting 2026-03-31 10:20:30 +07:00
Suphonchai Phoonsawat
82c31a0f57 Refactor GenericRepository and GenericLeaveRepository to expose PostExternalAPIAsync method and enhance LeaveProcessJobStatusRepository with API integration for processing employee records 2026-03-31 10:18:06 +07:00
Suphonchai Phoonsawat
2cd7798dd9 Add admin endpoints for processing leave tasks, including retrieval, deletion, and updates 2026-03-31 09:46:44 +07:00
Suphonchai Phoonsawat
759a51ab58 Enhance LeaveProcessJobStatusRepository with detailed processing logic and add new methods in UserProfileRepository for fetching officer and employee profiles by RootDnaId 2026-03-30 15:53:33 +07:00
Suphonchai Phoonsawat
3dee5f7166 Refactor LeaveProcessJobStatusRepository methods and update Hangfire configuration for improved job processing 2026-03-30 12:08:30 +07:00
Suphonchai Phoonsawat
8732c34564 Add scheduled job to process pending jobs in LeaveProcessJobStatusRepository 2026-03-30 10:06:21 +07:00
Suphonchai Phoonsawat
91e6b1b35b Add methods to process pending jobs and update their statuses in LeaveProcessJobStatusRepository 2026-03-30 10:02:57 +07:00
Suphonchai Phoonsawat
c1ac687101 Add CreateLeaveProcessJobDto and implement CreateProcessTaskAsync in LeaveController 2026-03-30 09:52:27 +07:00
Suphonchai Phoonsawat
de1773880b Add LeaveProcessJobStatusRepository and register it in ApplicationServicesRegistration 2026-03-30 09:31:19 +07:00
Suphonchai Phoonsawat
c91e6c8030 Add migration for LeaveProcessJobStatuses table
- Created a new migration to add the LeaveProcessJobStatuses table.
- The table includes fields for job status, timestamps, user information, and error messages.
- Supports tracking of leave process job statuses with relevant metadata.
2026-03-30 09:23:13 +07:00
harid
d8f1126764 fix ส่งรายชื่อผู้ถูกพักราชการไปออกคำสั่ง #2364
All checks were successful
Build & Deploy Discipline Service / build (push) Successful in 2m7s
2026-03-27 14:31:42 +07:00
Suphonchai Phoonsawat
7ba429bb64 Refactor checkout status logic in LeaveController for improved clarity and handling of check-in dates
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m46s
2026-03-27 09:48:10 +07:00
Suphonchai Phoonsawat
3e3bfff7ba Refactor leave date overlap check in LeaveRequestController for improved readability and performance
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m51s
2026-03-26 14:10:37 +07:00
Suphonchai Phoonsawat
19b79a162d Add leave subtype name and couple day level country to leave approval response (Employee)#2366
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m47s
2026-03-26 10:33:44 +07:00
Suphonchai Phoonsawat
a09d5937f9 Add leave subtype and couple day level country to leave approval response #2366 2026-03-26 10:33:00 +07:00
Suphonchai Phoonsawat
aef81e9f4e Add support for multiple child DNA IDs in leave processing and enhance batch creation of duty time changes
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m45s
2026-03-25 15:17:54 +07:00
Suphonchai Phoonsawat
6427cb4344 Comment out probation-related leave limit checks in LeaveRequestController and update appsettings.json to disable unused database connections
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m45s
2026-03-24 09:00:06 +07:00
Suphonchai Phoonsawat
252d8b5fa3 Update SearchProfile method parameters to use string for SelectedNodeId #1555
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m40s
2026-03-23 10:40:54 +07:00
Suphonchai Phoonsawat
58aca3a328 Add SelectedNode parameter to SearchProfile method for enhanced profile retrieval #1555
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m44s
2026-03-23 10:13:13 +07:00
Suphonchai Phoonsawat
818ff38e99 Add SelectedNodeId parameter to SearchProfile method and update related DTO #1555 2026-03-23 10:04:09 +07:00
Suphonchai Phoonsawat
23bbd9791e Add CreateChangeRoundMultipleAsync method for batch processing of duty time changes #1555
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m51s
Build & Deploy Placement Service / build (push) Successful in 1m54s
Build & Deploy Insignia Service / build (push) Successful in 1m51s
Build & Deploy Discipline Service / build (push) Successful in 1m51s
2026-03-23 09:49:17 +07:00
Suphonchai Phoonsawat
7e0f0485fd Add TokenUserInfo class and extend ClaimsPrincipal with methods for user claims retrieval
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m49s
2026-03-17 15:47:03 +07:00
harid
b1df33dc20 fix bug #2183
All checks were successful
Build & Deploy Retirement Service / build (push) Successful in 1m56s
2026-03-11 14:01:34 +07:00
Suphonchai Phoonsawat
6902236f48 Add GetTimeStampHistoryAsync2 method for fiscal year timestamp retrieval
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m50s
2026-03-11 11:57:00 +07:00
Suphonchai Phoonsawat
4562029e6e Update GetTimeStampHistoryAsync call to include pagination and keyword filtering
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 2m8s
2026-03-10 14:10:35 +07:00
Suphonchai Phoonsawat
4650f7a2ab Refactor ScheduleUpdateDnaAsync to handle a list of ScheduleUpdateDnaDto and streamline profile updates #2341
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m59s
2026-02-26 20:36:48 +07:00
Suphonchai Phoonsawat
f866435897 Refactor LeaveBeginningController to simplify duplicate check and comment out LeaveYear property in EditLeaveBeginningDto #2341
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m41s
2026-02-25 16:26:28 +07:00
Suphonchai Phoonsawat
006cea048d Add ScheduleUpdateDna endpoint and DTO for updating DNA information in LeaveBeginningController
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m35s
2026-02-25 15:26:49 +07:00
Suphonchai Phoonsawat
9a74b690cd ทดสอบ
Some checks failed
Build & Deploy Leave Service / build (push) Has been cancelled
2026-02-25 10:13:27 +07:00
Suphonchai Phoonsawat
2ee36af763 Test 2026-02-24 19:43:58 +07:00
Suphonchai Phoonsawat
cd99179621 Enhance leave eligibility check in LeaveRequestController with detailed messaging 2026-02-24 10:24:24 +07:00
Suphonchai Phoonsawat
c20e1b48bd Add GetDifference method to DateTimeExtension and implement TimeCheck endpoint in LeaveRequestController
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m35s
2026-02-23 10:09:36 +07:00
Suphonchai Phoonsawat
5b054f9948 Merge branch 'develop' into working
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m50s
2026-02-20 16:33:33 +07:00
Suphonchai Phoonsawat
3e34aaa178 Refactor file upload logic in LeaveController to handle check-in scenarios more effectively
#2328
2026-02-20 16:32:57 +07:00
harid
ddb35f525a Fix #2319
All checks were successful
Build & Deploy Placement Service / build (push) Successful in 1m50s
2026-02-20 13:36:50 +07:00
harid
ecca345407 รายชื่อผู้สอบผ่าน กรณี OWNER ให้เห็นรายชื่อเหมือน สกจ. #2319
All checks were successful
Build & Deploy Placement Service / build (push) Successful in 1m48s
2026-02-20 10:46:15 +07:00
Suphonchai Phoonsawat
7e613ab2e6 Merge branch 'develop' into working
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m43s
2026-02-19 17:34:10 +07:00
Suphonchai Phoonsawat
7eade164e9 Update LeaveRequestController to use GetLastLeaveRequestByTypeForUserAsync2 method with CreatedAt for fetching last leave request 2026-02-19 17:33:37 +07:00
harid
256da24caf แก้ไขสิทธิ์ PARENT ให้เห็นข้อมูลทั้งหมดทุกหน่วยงาน #54
All checks were successful
Build & Deploy Discipline Service / build (push) Successful in 1m55s
Build & Deploy Insignia Service / build (push) Successful in 1m48s
Build & Deploy Leave Service / build (push) Successful in 1m49s
Build & Deploy Placement Service / build (push) Successful in 1m46s
Build & Deploy Retirement Service / build (push) Successful in 1m50s
2026-02-19 17:01:44 +07:00
Suphonchai Phoonsawat
869defcc7e Update LeaveRequestRepository to order leave requests by creation date instead of start date #2305
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m44s
2026-02-19 15:19:41 +07:00
Suphonchai Phoonsawat
65feb994ee Add GetLastLeaveRequestByTypeForUserAsync2 method and update LeaveReportController to use new method for fetching last leave request #2305
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 2m0s
2026-02-19 15:10:44 +07:00
Suphonchai Phoonsawat
d748308419 Enhance LeaveController to implement check-out logic and status validation based on last check-in record 2026-02-19 15:07:04 +07:00
Suphonchai Phoonsawat
b8df2d4024 Add NodaTime package and update LeaveRequestController to use LocalDate for date calculations
#2324
2026-02-19 14:06:59 +07:00
Suphonchai Phoonsawat
c42aaa38f6 Fix API path in UserProfileRepository to remove redundant versioning
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m45s
2026-02-19 10:11:39 +07:00
Suphonchai Phoonsawat
ddaa339e9f Refactor LeaveRequestController and LeaveReportController to use GetSumApproveLeaveTotalByTypeAndRangeForUser2 method and update fiscal year end date calculation #2305
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m41s
2026-02-18 20:24:30 +07:00
Suphonchai Phoonsawat
d70ed254c0 Enhance LeaveRequestController to restore profile checks and implement officer notification logic #2164
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m34s
2026-02-18 16:56:48 +07:00
Suphonchai Phoonsawat
de91fd0fa2 Refactor LeaveBeginningController to restore profile checks and reset leave days to zero 2026-02-18 16:47:14 +07:00
Suphonchai Phoonsawat
7d3ec6c74e Refactor ScheduleUpdateLeaveBeginningAsync to use ScheduleEditLeaveBeginningDto and remove unused profile checks 2026-02-18 16:34:35 +07:00
1b7bdd82e6 #2313
All checks were successful
Build & Deploy Placement Service / build (push) Successful in 1m10s
2026-02-13 13:04:29 +07:00
Suphonchai Phoonsawat
a8271c8d79 Update leave summary calculation to use BeginningLeaveDays instead of LeaveDaysUsed #2305
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m12s
2026-02-12 20:09:05 +07:00
Suphonchai Phoonsawat
14fd9d5262 Refactor leave limit logic to use IsProbation property instead of govAge check
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m17s
2026-02-11 12:14:44 +07:00
Suphonchai Phoonsawat
c81220a049 Remove unnecessary whitespace and comment out unused code in LeaveReportController
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m18s
2026-02-11 11:56:04 +07:00
Suphonchai Phoonsawat
e5e7c77880 Add GetProfileByProfileIdNoAuthAsync method and update related controller logic 2026-02-11 11:47:49 +07:00
Suphonchai Phoonsawat
a2ac05ed61 Add BeginningLeaveDays and BeginningLeaveCount to LeaveBeginning DTOs and update controller logic #2304 #2305 2026-02-11 11:11:19 +07:00
Suphonchai Phoonsawat
2410574d42 Fix typo in IsProbatin property name and update related condition check in LeaveRequestController #2306 2026-02-11 10:47:01 +07:00
Suphonchai Phoonsawat
682c88c2db Add BeginningLeaveCount and BeginningLeaveDays to LeaveBeginnings table
- Altered LeaveDays column to update its comment.
- Added BeginningLeaveCount column to track the number of leave occurrences.
- Added BeginningLeaveDays column to store the total days of leave carried over.
2026-02-11 09:44:18 +07:00
harid
05ec0cccce Fix Bug จำนวนคนลาไม่แสดงในรายงาน #2299
All checks were successful
Build & Deploy Leave Service / build (push) Successful in 1m18s
2026-02-10 15:29:35 +07:00
81 changed files with 9736 additions and 625 deletions

25
.vscode/launch.json vendored
View file

@ -26,6 +26,31 @@
"/Views": "${workspaceFolder}/Views"
}
},
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
"name": ".NET Core Launch (web) - Insignia",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/BMA.EHR.Insignia/bin/Debug/net7.0/BMA.EHR.Insignia.dll",
"args": [],
"cwd": "${workspaceFolder}/BMA.EHR.Insignia",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",

View file

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

View file

@ -115,7 +115,7 @@ namespace BMA.EHR.Application.Repositories
}
protected async Task<string> PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default)
public async Task<string> PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey, CancellationToken cancellationToken = default)
{
try
{

View file

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

View file

@ -80,7 +80,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task UpdateLeaveUsageAsync(int year, Guid typeId, Guid userId, double day)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -102,7 +102,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task UpdateLeaveCountAsync(int year, Guid typeId, Guid userId, int count)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -124,7 +124,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUserAsync(int year, Guid typeId, Guid userId)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -263,7 +263,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<LeaveBeginning?> GetByYearAndTypeIdForUser2Async(int year, Guid typeId, Guid userId)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
return null;

View file

@ -254,7 +254,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<List<LeaveRequest>> GetLeaveRequestByYearAsync(int year, Guid userId)
{
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
@ -307,11 +307,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!));
}
else if (role == "PARENT")
{
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
}
// else if (role == "PARENT")
// {
// rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// }
else if (role == "NORMAL")
{
rawData = rawData
@ -354,7 +354,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x => x.CreatedAt)
.OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt))
.AsQueryable();
if (year != 0)
@ -380,7 +380,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x => x.CreatedAt)
.OrderByDescending(x => (x.DateSendLeave ?? x.CreatedAt))
.AsQueryable();
// fix issue : 1830
if (year != 0)
@ -421,11 +421,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!));
}
else if (role == "PARENT")
{
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
}
// else if (role == "PARENT")
// {
// rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// }
else if (role == "NORMAL")
{
rawData = rawData
@ -447,7 +447,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Include(x => x.Type)
.Where(x => keycloakIdList.Contains(x.KeycloakUserId))
.Where(x => x.LeaveStatus != "DRAFT")
.OrderByDescending(x => x.CreatedAt)
.OrderByDescending(x =>(x.DateSendLeave ?? x.CreatedAt))
.AsQueryable();
if (year != 0)
@ -497,7 +497,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
public async Task<double> GetSumLeaveByTypeForUserAsync(Guid keycloakUserId, Guid leaveTypeId, int year)
{
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(keycloakUserId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(keycloakUserId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(keycloakUserId, AccessToken);
if (pf == null)
throw new Exception(GlobalMessages.DataNotFound);
@ -558,6 +558,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
.Include(x => x.Type)
.Where(x => x.LeaveStartDate.Date < beforeDate.Date)
//.Where(x => x.CreatedAt < beforeDate)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
@ -568,6 +569,22 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
return data;
}
public async Task<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)
{
var rawData = _dbContext.Set<LeaveRequest>().AsNoTracking()
@ -610,11 +627,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!));
}
else if (role == "PARENT")
{
rawData = rawData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
}
// else if (role == "PARENT")
// {
// rawData = rawData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null);
// }
else if (role == "NORMAL")
{
rawData = rawData
@ -634,7 +651,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
try
{
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(data.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken ?? "");
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -659,6 +676,9 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
thisYear = thisYear + 1;
}
await _leaveBeginningRepository.UpdateLeaveUsageAsync(thisYear, data.Type.Id, data.KeycloakUserId, -1 * data.LeaveTotal);
// update leave count ลดลง 1 ครั้ง
await _leaveBeginningRepository.UpdateLeaveCountAsync(thisYear, data.Type.Id, data.KeycloakUserId, -1);
var _baseAPI = _configuration["API"];
var apiUrlSalary = $"{_baseAPI}/org/profile/leave/cancel/{data.Id}";
@ -708,7 +728,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
}
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? "");
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -797,7 +817,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
}
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken ?? "");
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken ?? "");
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -884,6 +904,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
rawData.LeaveStatus = "NEW";
rawData.DateSendLeave = DateTime.Now; // Update วันที่ยื่นลาเป็นวันที่ปัจจุบัน
//rawData.ApproveStep = "st2";
await UpdateAsync(rawData);
@ -1222,7 +1243,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
else
{
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken);
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -1268,6 +1289,8 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
status = "approve",
reason = rawData.LeaveDetail,
leaveId = rawData.Id,
leaveSubTypeName = rawData.LeaveSubTypeName,
coupleDayLevelCountry = rawData.CoupleDayLevelCountry,
});
// var _result = await _res.Content.ReadAsStringAsync();
}
@ -1291,6 +1314,8 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
status = "approve",
reason = rawData.LeaveDetail,
leaveId = rawData.Id,
leaveSubTypeName = rawData.LeaveSubTypeName,
coupleDayLevelCountry = rawData.CoupleDayLevelCountry,
});
}
}
@ -1388,7 +1413,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
else
{
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken);
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -1675,10 +1700,10 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
{
data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId)).ToList();
}
else if (role == "PARENT")
{
data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>
@ -1694,7 +1719,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT")
{
data = data
.Where(x => nodeByReq == 4 ? x.Child4Id == Guid.Parse(nodeIdByReq) : nodeByReq == 3 ? x.Child3Id == Guid.Parse(nodeIdByReq) : nodeByReq == 2 ? x.Child2Id == Guid.Parse(nodeIdByReq) : nodeByReq == 1 ? x.Child1Id == Guid.Parse(nodeIdByReq) : nodeByReq == 0 ? x.RootId == Guid.Parse(nodeIdByReq) : true)
.Where(x => nodeByReq == 4 ? x.Child4DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 3 ? x.Child3DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 2 ? x.Child2DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 1 ? x.Child1DnaId == Guid.Parse(nodeIdByReq) : nodeByReq == 0 ? x.RootDnaId == Guid.Parse(nodeIdByReq) : true)
.ToList();
}
// รายงานการลางานจำแนกตามเพศฯ Template ให้หน่วยงานแสดงก่อนส่วนราชการ
@ -1835,6 +1860,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Include(x => x.Type)
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
//.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync();
@ -1845,6 +1871,74 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
return 0;
}
public async Task<double> GetSumApproveLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate)
{
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).Date >= startDate && (x.DateSendLeave ??x.CreatedAt).Date < endDate)
//.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync();
if (data.Count > 0)
return data.Sum(x => x.LeaveTotal);
else
return 0;
}
/// <summary>
/// วันลาที่สร้างแบบร่างยังไม่ได้ยื่น
/// </summary>
/// <param name="keycloakUserId"></param>
/// <param name="leaveTypeId"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public async Task<double> GetSumDraftLeaveTotalByTypeAndRangeForUser2(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate)
{
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).Date >= startDate
&& (x.DateSendLeave ?? x.CreatedAt).Date < endDate)
//.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "DRAFT")
.ToListAsync();
if (data.Count > 0)
return data.Sum(x => x.LeaveTotal);
else
return 0;
}
/// <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)
{
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).Date >= startDate && (x.DateSendLeave ??x.CreatedAt).Date < endDate)
//.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
.Where(x => x.LeaveStatus == "NEW")
.ToListAsync();
if (data.Count > 0)
return data.Sum(x => x.LeaveTotal);
else
return 0;
}
public async Task<int> GetCountApproveLeaveByTypeAndRangeForUser(Guid keycloakUserId, Guid leaveTypeId, DateTime startDate, DateTime endDate)
{
var data = await _dbContext.Set<LeaveRequest>().AsQueryable().AsNoTracking()
@ -1852,6 +1946,7 @@ namespace BMA.EHR.Application.Repositories.Leaves.LeaveRequests
.Where(x => x.KeycloakUserId == keycloakUserId)
.Where(x => x.Type.Id == leaveTypeId)
.Where(x => x.LeaveStartDate.Date >= startDate.Date && x.LeaveStartDate.Date <= endDate.Date)
//.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate)
.Where(x => x.LeaveStatus == "APPROVE" || x.LeaveStatus == "DELETING")
.ToListAsync();

View file

@ -185,11 +185,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
data = data
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
}
else if (role == "PARENT")
{
data = data
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList();
}
// else if (role == "PARENT")
// {
// data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null && x.Child1DnaId != Guid.Empty).ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>

View file

@ -0,0 +1,795 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;
using System.IO;
using BMA.EHR.Application.Common.Interfaces;
using BMA.EHR.Application.Repositories.Leaves.LeaveRequests;
using BMA.EHR.Application.Repositories.MetaData;
using BMA.EHR.Application.Responses.Profiles;
using BMA.EHR.Domain.Extensions;
using BMA.EHR.Domain.Models.Leave.TimeAttendants;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
{
public class LeaveProcessJobStatusRepository: GenericLeaveRepository<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();
}
else if (role == "PARENT")
{
data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// data = data.Where(x => x.RootDnaId == Guid.Parse(nodeId) && x.Child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>
@ -191,11 +191,11 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
if (role == "ROOT" || role == "OWNER" || role == "CHILD" || role == "BROTHER" || role == "PARENT")
{
data = data.Where(x =>
nodeByReq == 4 ? x.Child4Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 3 ? x.Child3Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 2 ? x.Child2Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 1 ? x.Child1Id == Guid.Parse(nodeIdByReq) :
nodeByReq == 0 ? x.RootId == Guid.Parse(nodeIdByReq) : true
nodeByReq == 4 ? x.Child4DnaId == Guid.Parse(nodeIdByReq) :
nodeByReq == 3 ? x.Child3DnaId == Guid.Parse(nodeIdByReq) :
nodeByReq == 2 ? x.Child2DnaId == Guid.Parse(nodeIdByReq) :
nodeByReq == 1 ? x.Child1DnaId == Guid.Parse(nodeIdByReq) :
nodeByReq == 0 ? x.RootDnaId == Guid.Parse(nodeIdByReq) : true
).ToList();
}
return data;
@ -227,6 +227,19 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
return data;
}
public async Task<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)
{
var data = await _dbContext.Set<ProcessUserTimeStamp>()
@ -288,12 +301,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
.Where(x => x.RootDnaId == Guid.Parse(nodeId!))
.ToList();
}
else if (role == "PARENT")
{
data = data
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
.ToList();
}
// else if (role == "PARENT")
// {
// data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
// .ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>

View file

@ -140,12 +140,12 @@ namespace BMA.EHR.Application.Repositories.Leaves.TimeAttendants
.Where(x => x.RootDnaId == Guid.Parse(nodeId!))
.ToList();
}
else if (role == "PARENT")
{
data = data
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
.ToList();
}
// else if (role == "PARENT")
// {
// data = data
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null)
// .ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>

View file

@ -10,6 +10,7 @@ using System.Net.Http.Headers;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
using System.Net.Http.Json;
using BMA.EHR.Application.Responses.Leaves;
namespace BMA.EHR.Application.Repositories
{
@ -76,6 +77,39 @@ namespace BMA.EHR.Application.Repositories
}
}
public async Task<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)
{
try

View file

@ -893,7 +893,7 @@ namespace BMA.EHR.Application.Repositories.Reports
select new
{
RowNo = 1,
DepartmentName = _userProfileRepository.GetOc(g.Key.OcId, 0, AccessToken).Root, //_organizationCommonRepository.GetOrganizationNameFullPath(g.Key.OcId, false, false),
DepartmentName = _userProfileRepository.GetOc(g.Key.OcId, 0, AccessToken)?.Root ?? "-", //_organizationCommonRepository.GetOrganizationNameFullPath(g.Key.OcId, false, false),
G1Male = g.Sum(x => x.Gendor == "ชาย" && x.RequestInsigniaName == "เหรียญจักรพรรดิมาลา" ? 1 : 0),
G1Female = g.Sum(x => x.Gendor == "หญิง" && x.RequestInsigniaName == "เหรียญจักรพรรดิมาลา" ? 1 : 0),
G2Male = g.Sum(x => x.Gendor == "ชาย" ? 1 : 0),

View file

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

View file

@ -341,6 +341,31 @@ 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)
{
try
@ -739,6 +764,75 @@ 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)
{
try
@ -945,7 +1039,7 @@ namespace BMA.EHR.Application.Repositories
}
}
public async Task<GetProfileByKeycloakIdRootAddTotalDto> SearchProfile(string? citizenId, string? firstName, string? lastName, string accessToken, int page, int pageSize, string? role, string? nodeId, int? node)
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
{
@ -961,6 +1055,8 @@ namespace BMA.EHR.Application.Repositories
node = node,
page = page,
pageSize = pageSize,
selectedNodeId = selectedNodeId,
selectedNode = selectedNode
};
var profiles = new List<GetProfileByKeycloakIdRootDto>();
@ -1163,6 +1259,38 @@ namespace BMA.EHR.Application.Repositories
}
}
public GetOrganizationResponseDTO? GetOcByNodeId(Guid ocId, int level, string? accessToken)
{
try
{
var apiPath = $"{_configuration["API"]}/org/find/all";
var apiKey = _configuration["API_KEY"];
var body = new
{
nodeId = ocId,
node = level
};
var apiResult = PostExternalAPIAsync(apiPath, accessToken ?? "", body, apiKey).Result;
if (apiResult != null)
{
var raw = JsonConvert.DeserializeObject<GetOrganizationResponseResultDTO>(apiResult);
if (raw != null && raw.Result != null)
{
return raw.Result;
}
}
return null;
}
catch
{
throw;
}
}
public GetOrganizationResponseDTO? GetOc(Guid ocId, int level, string? accessToken)
{
try

View file

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BMA.EHR.Domain.Shared;
using Newtonsoft.Json;
namespace BMA.EHR.Application.Responses.Leaves
{
public class GetPermissionWithActingDto
{
public string privilege {get; set;} = string.Empty;
public bool isAct {get; set;} = false;
public List<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

@ -13,7 +13,7 @@
public string Age { get; set; } = string.Empty;
public DateTime DateAppoint { get; set; }
public DateTime DateCurrent { get; set; }
public int Amount { get; set; }
public int? Amount { get; set; } = 0;
public string? TelephoneNumber { get; set; } = string.Empty;
public string Position { get; set; } = string.Empty;
public string PosLevel { get; set; } = string.Empty;

View file

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

View file

@ -25,6 +25,12 @@ namespace BMA.EHR.Application.Responses.Profiles
public DateTime? DateStart { get; set; }
public DateTime? DateAppoint { get; set; }
public string? RootDnaId { get; set; }
public string? Child1DnaId { get; set; }
public string? Child2DnaId { get; set; }
public string? Child3DnaId { get; set; }
public string? Child4DnaId { get; set; }
}
public class GetProfileByKeycloakIdRootAddTotalDto

View file

@ -786,7 +786,7 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -826,11 +826,11 @@ namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers
data_search = data_search
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
data_search = data_search
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// data_search = data_search
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
data_search = data_search.Where(x =>

View file

@ -1242,14 +1242,22 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("command25/report")]
public async Task<ActionResult<ResponseObject>> PostReportCommand25([FromBody] ReportPersonRequest req)
public async Task<ActionResult<ResponseObject>> PostReportCommand25([FromBody] ReportPersonAndCommandRequest req)
{
try
{
var data = await _context.DisciplineReport_Profiles
.Where(x => req.refIds.Contains(x.Id.ToString()))
.ToListAsync();
data.ForEach(profile => profile.Status = req.status.Trim().ToUpper());
// data.ForEach(profile => profile.Status = req.status.Trim().ToUpper());
data.ForEach(profile =>
{
profile.Status = !string.IsNullOrEmpty(req.status)
? req.status.Trim().ToUpper() : null;
profile.CommandTypeId = !string.IsNullOrEmpty(req.commandTypeId) && Guid.TryParse(req.commandTypeId, out var cmdTypeId)
? cmdTypeId : null;
profile.CommandCode = req.commandCode ?? null;
});
await _context.SaveChangesAsync();
return Success();
}
@ -1276,7 +1284,13 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers
.Where(x => req.refIds.Contains(x.Id.ToString()))
// .Where(x => x.Status.ToUpper() == "REPORT")
.ToListAsync();
data.ForEach(profile => profile.Status = "PENDING");
// data.ForEach(profile => profile.Status = "PENDING");
data.ForEach(profile =>
{
profile.Status = "PENDING";
profile.CommandTypeId = null;
profile.CommandCode = null;
});
await _context.SaveChangesAsync();
return Success();
}
@ -1429,14 +1443,22 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("command26/report")]
public async Task<ActionResult<ResponseObject>> PostReportCommand26([FromBody] ReportPersonRequest req)
public async Task<ActionResult<ResponseObject>> PostReportCommand26([FromBody] ReportPersonAndCommandRequest req)
{
try
{
var data = await _context.DisciplineReport_Profiles
.Where(x => req.refIds.Contains(x.Id.ToString()))
.ToListAsync();
data.ForEach(profile => profile.Status = req.status.Trim().ToUpper());
// data.ForEach(profile => profile.Status = req.status.Trim().ToUpper());
data.ForEach(profile =>
{
profile.Status = !string.IsNullOrEmpty(req.status)
? req.status.Trim().ToUpper() : null;
profile.CommandTypeId = !string.IsNullOrEmpty(req.commandTypeId) && Guid.TryParse(req.commandTypeId, out var cmdTypeId)
? cmdTypeId : null;
profile.CommandCode = req.commandCode ?? null;
});
await _context.SaveChangesAsync();
return Success();
}
@ -1463,7 +1485,13 @@ namespace BMA.EHR.DisciplineResult.Service.Controllers
.Where(x => req.refIds.Contains(x.Id.ToString()))
// .Where(x => x.Status.ToUpper() == "REPORT")
.ToListAsync();
data.ForEach(profile => profile.Status = "PENDING");
// data.ForEach(profile => profile.Status = "PENDING");
data.ForEach(profile =>
{
profile.Status = "PENDING";
profile.CommandTypeId = null;
profile.CommandCode = null;
});
await _context.SaveChangesAsync();
return Success();
}

View file

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

View file

@ -8,4 +8,12 @@ namespace BMA.EHR.Discipline.Service.Requests
public string[] refIds { get; set; }
public string? status { get; set; }
}
public class ReportPersonAndCommandRequest
{
public string[] refIds { get; set; }
public string? status { get; set; }
public string? commandTypeId { get; set; }
public string? commandCode { get; set; }
}
}

View file

@ -1,4 +1,5 @@
using BMA.EHR.Domain.Shared;
using BMA.EHR.Domain.Extensions;
using BMA.EHR.Domain.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -81,6 +82,20 @@ namespace BMA.EHR.Domain.Common
}
#endregion
#region " Properties "
protected string? EmpType => User.GetEmpType();
protected Guid? OrgChild1DnaId => User.GetOrgChild1DnaId();
protected Guid? OrgChild2DnaId => User.GetOrgChild2DnaId();
protected Guid? OrgChild3DnaId => User.GetOrgChild3DnaId();
protected Guid? OrgChild4DnaId => User.GetOrgChild4DnaId();
protected Guid? OrgRootDnaId => User.GetOrgRootDnaId();
protected Guid? ProfileId => User.GetProfileId();
protected string? Prefix => User.GetPrefix();
protected string? FullNameFromClaim => User.GetName();
#endregion
#endregion

View file

@ -0,0 +1,39 @@
namespace BMA.EHR.Domain.Common
{
public class TokenUserInfo
{
// Existing properties
public string KeycloakId { get; set; } = string.Empty;
public string? PreferredUsername { get; set; }
public string? GivenName { get; set; }
public string? FamilyName { get; set; }
// New properties to add
public string? EmpType { get; set; }
public Guid? OrgChild1DnaId { get; set; }
public Guid? OrgChild2DnaId { get; set; }
public Guid? OrgChild3DnaId { get; set; }
public Guid? OrgChild4DnaId { get; set; }
public Guid? OrgRootDnaId { get; set; }
public Guid? ProfileId { get; set; }
public string? Prefix { get; set; }
public string? Name { get; set; }
}
// Claim type constants
public static class BmaClaimTypes
{
public const string EmpType = "empType";
public const string OrgChild1DnaId = "orgChild1DnaId";
public const string OrgChild2DnaId = "orgChild2DnaId";
public const string OrgChild3DnaId = "orgChild3DnaId";
public const string OrgChild4DnaId = "orgChild4DnaId";
public const string OrgRootDnaId = "orgRootDnaId";
public const string ProfileId = "profileId";
public const string Prefix = "prefix";
public const string Name = "name";
public const string GivenName = "given_name";
public const string FamilyName = "family_name";
public const string PreferredUsername = "preferred_username";
}
}

View file

@ -0,0 +1,30 @@
using BMA.EHR.Domain.Common;
using System.Security.Claims;
namespace BMA.EHR.Domain.Extensions
{
public static class ClaimsPrincipalExtensions
{
public static string? GetClaimValue(this ClaimsPrincipal user, string claimType)
{
return user?.FindFirst(claimType)?.Value;
}
public static Guid? GetGuidClaim(this ClaimsPrincipal user, string claimType)
{
var value = user?.GetClaimValue(claimType);
return Guid.TryParse(value, out var guid) ? guid : null;
}
// Convenience methods for common claims
public static string? GetEmpType(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.EmpType);
public static Guid? GetOrgChild1DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild1DnaId);
public static Guid? GetOrgChild2DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild2DnaId);
public static Guid? GetOrgChild3DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild3DnaId);
public static Guid? GetOrgChild4DnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgChild4DnaId);
public static Guid? GetOrgRootDnaId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.OrgRootDnaId);
public static Guid? GetProfileId(this ClaimsPrincipal user) => user.GetGuidClaim(BmaClaimTypes.ProfileId);
public static string? GetPrefix(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.Prefix);
public static string? GetName(this ClaimsPrincipal user) => user.GetClaimValue(BmaClaimTypes.Name);
}
}

View file

@ -174,6 +174,29 @@ namespace BMA.EHR.Domain.Extensions
}
}
public static (int Years, int Months, int Days) GetDifference(this DateTime from, DateTime to)
{
if (from > to) (from, to) = (to, from); // swap ถ้าลำดับสลับ
int years = to.Year - from.Year;
int months = to.Month - from.Month;
int days = to.Day - from.Day;
if (days < 0)
{
months--;
days += DateTime.DaysInMonth(to.Year, to.Month == 1 ? 12 : to.Month - 1);
}
if (months < 0)
{
years--;
months += 12;
}
return (years, months, days);
}
public static int CalculateAge(this DateTime date, int plusYear = 0, int subtractYear = 0)
{
try

View file

@ -79,13 +79,39 @@ namespace BMA.EHR.Domain.Middlewares
GetProfileByKeycloakIdLocal? pf = null;
var tokenUserInfo = await ExtractTokenUserInfoAsync(token);
// Store tokenUserInfo in HttpContext.Items for controllers to use
context.Items["TokenUserInfo"] = tokenUserInfo;
// ดึง keycloakId จาก JWT token
keycloakId = tokenUserInfo.KeycloakId;
// ดึง profile จาก cache หรือ API
// ดึง profile จาก claims หรือ cache หรือ API
if (Guid.TryParse(keycloakId, out var parsedId) && parsedId != Guid.Empty)
{
pf = await GetProfileWithCacheAsync(parsedId, token);
// Build profile from token claims if available
if (tokenUserInfo.OrgRootDnaId.HasValue && tokenUserInfo.ProfileId.HasValue)
{
pf = new GetProfileByKeycloakIdLocal
{
Id = tokenUserInfo.ProfileId.Value,
CitizenId = tokenUserInfo.PreferredUsername,
Prefix = tokenUserInfo.Prefix,
FirstName = tokenUserInfo.GivenName,
LastName = tokenUserInfo.FamilyName,
RootDnaId = tokenUserInfo.OrgRootDnaId,
Child1DnaId = tokenUserInfo.OrgChild1DnaId,
Child2DnaId = tokenUserInfo.OrgChild2DnaId,
Child3DnaId = tokenUserInfo.OrgChild3DnaId,
Child4DnaId = tokenUserInfo.OrgChild4DnaId,
};
Console.WriteLine($"[INFO] Using claims for profile - OrgRootDnaId: {pf.RootDnaId}, ProfileId: {pf.Id}");
}
else
{
// Fallback to API only if critical claims are missing
Console.WriteLine("[WARN] Critical claims missing, falling back to API call");
pf = await GetProfileWithCacheAsync(parsedId, token);
}
}
try
@ -649,6 +675,87 @@ namespace BMA.EHR.Domain.Middlewares
Console.WriteLine($"Extracted family_name: {result.FamilyName}");
}
// ดึง empType
if (jsonDoc.RootElement.TryGetProperty("empType", out var empTypeElement))
{
result.EmpType = empTypeElement.GetString();
Console.WriteLine($"Extracted empType: {result.EmpType}");
}
// ดึง orgChild1DnaId
if (jsonDoc.RootElement.TryGetProperty("orgChild1DnaId", out var orgChild1Element))
{
if (Guid.TryParse(orgChild1Element.GetString(), out var orgChild1Guid))
{
result.OrgChild1DnaId = orgChild1Guid;
Console.WriteLine($"Extracted orgChild1DnaId: {result.OrgChild1DnaId}");
}
}
// ดึง orgChild2DnaId
if (jsonDoc.RootElement.TryGetProperty("orgChild2DnaId", out var orgChild2Element))
{
if (Guid.TryParse(orgChild2Element.GetString(), out var orgChild2Guid))
{
result.OrgChild2DnaId = orgChild2Guid;
Console.WriteLine($"Extracted orgChild2DnaId: {result.OrgChild2DnaId}");
}
}
// ดึง orgChild3DnaId
if (jsonDoc.RootElement.TryGetProperty("orgChild3DnaId", out var orgChild3Element))
{
if (Guid.TryParse(orgChild3Element.GetString(), out var orgChild3Guid))
{
result.OrgChild3DnaId = orgChild3Guid;
Console.WriteLine($"Extracted orgChild3DnaId: {result.OrgChild3DnaId}");
}
}
// ดึง orgChild4DnaId
if (jsonDoc.RootElement.TryGetProperty("orgChild4DnaId", out var orgChild4Element))
{
if (Guid.TryParse(orgChild4Element.GetString(), out var orgChild4Guid))
{
result.OrgChild4DnaId = orgChild4Guid;
Console.WriteLine($"Extracted orgChild4DnaId: {result.OrgChild4DnaId}");
}
}
// ดึง orgRootDnaId
if (jsonDoc.RootElement.TryGetProperty("orgRootDnaId", out var orgRootElement))
{
if (Guid.TryParse(orgRootElement.GetString(), out var orgRootGuid))
{
result.OrgRootDnaId = orgRootGuid;
Console.WriteLine($"Extracted orgRootDnaId: {result.OrgRootDnaId}");
}
}
// ดึง profileId
if (jsonDoc.RootElement.TryGetProperty("profileId", out var profileIdElement))
{
if (Guid.TryParse(profileIdElement.GetString(), out var profileIdGuid))
{
result.ProfileId = profileIdGuid;
Console.WriteLine($"Extracted profileId: {result.ProfileId}");
}
}
// ดึง prefix
if (jsonDoc.RootElement.TryGetProperty("prefix", out var prefixElement))
{
result.Prefix = prefixElement.GetString();
Console.WriteLine($"Extracted prefix: {result.Prefix}");
}
// ดึง name
if (jsonDoc.RootElement.TryGetProperty("name", out var nameElement))
{
result.Name = nameElement.GetString();
Console.WriteLine($"Extracted name: {result.Name}");
}
return result;
}
catch (Exception ex)
@ -767,14 +874,6 @@ namespace BMA.EHR.Domain.Middlewares
}
// Model classes
public class TokenUserInfo
{
public string KeycloakId { get; set; } = string.Empty;
public string? PreferredUsername { get; set; }
public string? GivenName { get; set; }
public string? FamilyName { get; set; }
}
public class GetProfileByKeycloakIdLocal
{
public Guid Id { get; set; }

View file

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

View file

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

View file

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using BMA.EHR.Domain.Models.Base;
using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Domain.Models.Leave.TimeAttendants
{
public class LeaveProcessJobStatus: EntityBase
{
[Required, Comment("วันเริ่มต้น")]
public DateTime StartDate { get; set; }
[Required, Comment("วันสิ้นสุด")]
public DateTime EndDate { get; set; }
[Required, Comment("รหัส Root DNA Id")]
public Guid RootDnaId { get; set; } = Guid.Empty;
[Comment("วันเวลาที่สร้างงาน")]
public DateTime CreatedDate { get; set; } = DateTime.Now;
[Comment("วันเวลาที่เริ่มประมวลผล")]
public DateTime? ProcessingDate { get; set; }
[Comment("วันเวลาที่เสร็จสิ้นการประมวลผล")]
public DateTime? CompletedDate { get; set; }
[Required, Comment("สถานะงาน: PENDING, PROCESSING, COMPLETED, FAILED")]
public string Status { get; set; } = "PENDING";
[Comment("ข้อความแสดงข้อผิดพลาด")]
public string? ErrorMessage { get; set; }
}
}

View file

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

View file

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BMA.EHR.Domain.Shared
{
public class PrivilegeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return "EMPTY";
}
return reader.Value;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value);
}
}
}

View file

@ -0,0 +1,62 @@
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

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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
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

@ -128,6 +128,14 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
.HasComment("PrimaryKey")
.HasAnnotation("Relational:JsonPropertyName", "id");
b.Property<int>("BeginningLeaveCount")
.HasColumnType("int")
.HasComment("จำนวนครั้งที่ลายกมา");
b.Property<double>("BeginningLeaveDays")
.HasColumnType("double")
.HasComment("จำนวนวันลายกมา");
b.Property<Guid?>("Child1DnaId")
.HasColumnType("char(36)");
@ -190,7 +198,7 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.Property<double>("LeaveDays")
.HasColumnType("double")
.HasComment("จำนวนวันลายกมา");
.HasComment("จำนวนวันลาทั้งหมด");
b.Property<double>("LeaveDaysUsed")
.HasColumnType("double")
@ -420,6 +428,9 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.Property<DateTime?>("DateAppoint")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("DateSendLeave")
.HasColumnType("datetime(6)");
b.Property<string>("Dear")
.HasColumnType("longtext")
.HasComment("เรียนใคร");
@ -1064,6 +1075,91 @@ namespace BMA.EHR.Infrastructure.Migrations.LeaveDb
b.ToTable("DutyTimes");
});
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.LeaveProcessJobStatus", b =>
{
b.Property<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");
});
modelBuilder.Entity("BMA.EHR.Domain.Models.Leave.TimeAttendants.ProcessUserTimeStamp", b =>
{
b.Property<Guid>("Id")

View file

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

View file

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

View file

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

View file

@ -31,10 +31,11 @@
//"DisciplineConnection": "server=hrms.chin.in.th;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=53636;database=hrms_discipline;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
},
"Jwt": {
//"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc",
//"Issuer": "https://hrms-id.chin.in.th/realms/hrms"
"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Issuer": "https://id.frappet.synology.me/realms/hrms"
//"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc",
"Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms"
//"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU",
//"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms"
},
"EPPlus": {
"ExcelPackage": {
@ -55,11 +56,17 @@
"Node": {
"API": "https://bma-ehr.frappet.synology.me/api/v1/probation"
},
"API": "https://bma-ehr.frappet.synology.me/api/v1",
"RabbitMQ": {
"URL": "localhost",
"UserName": "frappet",
"Password": "FPTadmin2357"
},
"Domain": "https://hrmsbkk.case-collection.com",
"APIPROBATION": "https://hrmsbkk.case-collection.com/api/v1/probation",
"API": "https://hrmsbkk.case-collection.com/api/v1",
"APIV2": "https://hrmsbkk.case-collection.com/api/v2",
"VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com",
//"API": "https://bma-ehr.frappet.synology.me/api/v1",
//"API": "https://bma-hrms.bangkok.go.th/api/v1",
"API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz"
}

View file

@ -45,6 +45,7 @@
<PackageReference Include="Microsoft.IdentityModel.Logging" Version="6.31.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<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="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />

View file

@ -141,7 +141,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -166,11 +166,11 @@ namespace BMA.EHR.Leave.Service.Controllers
resData = resData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!)).ToList();
}
else if (role == "PARENT")
{
resData = resData
.Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// resData = resData
// .Where(x => x.RootDnaId == Guid.Parse(nodeId!) && x.Child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
resData = resData
@ -202,6 +202,8 @@ namespace BMA.EHR.Leave.Service.Controllers
item.LeaveDays,
item.LeaveDaysUsed,
item.LeaveCount,
item.BeginningLeaveDays,
item.BeginningLeaveCount,
item.CreatedAt,
item.CreatedFullName,
item.LastUpdatedAt,
@ -396,6 +398,8 @@ namespace BMA.EHR.Leave.Service.Controllers
leaveBeginning.LeaveDays = req.LeaveDays;
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.LeaveCount = req.LeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
leaveBeginning.ProfileId = req.ProfileId;
leaveBeginning.Prefix = profile.Prefix;
@ -465,6 +469,8 @@ namespace BMA.EHR.Leave.Service.Controllers
leaveBeginning.LeaveDays = req.LeaveDays;
leaveBeginning.LeaveDaysUsed = req.LeaveDaysUsed;
leaveBeginning.LeaveCount = req.LeaveCount;
leaveBeginning.BeginningLeaveDays = req.BeginningLeaveDays;
leaveBeginning.BeginningLeaveCount = req.BeginningLeaveCount;
leaveBeginning.ProfileId = req.ProfileId;
leaveBeginning.Prefix = profile.Prefix;
@ -492,6 +498,126 @@ namespace BMA.EHR.Leave.Service.Controllers
}
}
[HttpPut("schedule")]
[AllowAnonymous]
public async Task<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
}

View file

@ -3,8 +3,10 @@ using BMA.EHR.Application.Repositories.Commands;
using BMA.EHR.Application.Repositories.Leaves.LeaveRequests;
using BMA.EHR.Application.Repositories.Leaves.TimeAttendants;
using BMA.EHR.Application.Repositories.MessageQueue;
using BMA.EHR.Application.Responses.Leaves;
using BMA.EHR.Application.Responses.Profiles;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Extensions;
using BMA.EHR.Domain.Models.Leave.TimeAttendants;
using BMA.EHR.Domain.Models.Notifications;
using BMA.EHR.Domain.Shared;
@ -74,6 +76,8 @@ namespace BMA.EHR.Leave.Service.Controllers
private readonly HttpClient _httpClient;
private readonly LeaveProcessJobStatusRepository _leaveProcessJobStatusRepository;
#endregion
#region " Constuctor and Destructor "
@ -97,7 +101,8 @@ namespace BMA.EHR.Leave.Service.Controllers
NotificationRepository notificationRepository,
CheckInJobStatusRepository checkInJobStatusRepository,
HttpClient httpClient,
ApplicationDBContext appDbContext)
ApplicationDBContext appDbContext,
LeaveProcessJobStatusRepository leaveProcessJobStatusRepository)
{
_dutyTimeRepository = dutyTimeRepository;
_context = context;
@ -116,7 +121,7 @@ namespace BMA.EHR.Leave.Service.Controllers
_leaveRequestRepository = leaveRequestRepository;
_notificationRepository = notificationRepository;
_checkInJobStatusRepository = checkInJobStatusRepository;
_leaveProcessJobStatusRepository = leaveProcessJobStatusRepository;
_objectPool = objectPool;
_permission = permission;
@ -144,7 +149,13 @@ namespace BMA.EHR.Leave.Service.Controllers
{
get
{
if (UserId != null || UserId != "")
// First try to get from claims
var ocIdFromClaims = OrgRootDnaId;
if (ocIdFromClaims.HasValue && ocIdFromClaims.Value != Guid.Empty)
return ocIdFromClaims.Value;
// Fallback to API call for backward compatibility
if (UserId != null && UserId != "")
return _userProfileRepository.GetUserOCId(Guid.Parse(UserId!), AccessToken);
else
return Guid.Empty;
@ -438,7 +449,7 @@ namespace BMA.EHR.Leave.Service.Controllers
// Get user's last check-in record and profile in parallel
var dataTask = _userTimeStampRepository.GetLastRecord(userId);
var profileTask = _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profileTask = _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
var defaultRoundTask = _dutyTimeRepository.GetDefaultAsync();
await Task.WhenAll(dataTask, profileTask, defaultRoundTask);
@ -927,7 +938,7 @@ namespace BMA.EHR.Leave.Service.Controllers
await _checkInJobStatusRepository.UpdateToProcessingAsync(taskId);
}
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, data.Token);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, data.Token);
if (profile == null)
{
@ -957,15 +968,24 @@ namespace BMA.EHR.Leave.Service.Controllers
return Error(GlobalMessages.NoFileToUpload, StatusCodes.Status400BadRequest);
}
// last check-in record
var lastCheckIn = await _userTimeStampRepository.GetLastRecord(userId);
var check_status = data.CheckInId == null ? "check-in-picture" : "check-out-picture";
var check_out_status = "check-out-picture";
var fileName = $"{_bucketName}/{userId}/{currentDate.ToString("dd-MM-yyyy")}/{check_status}/{data.CheckInFileName}";
var fileNameCheckOut = $"{_bucketName}/{userId}/{currentDate.ToString("dd-MM-yyyy")}/{check_out_status}/{data.CheckInFileName}";
using (var ms = new MemoryStream(data.CheckInFileBytes ?? new byte[0]))
{
try
{
await _minIOService.UploadFileAsync(fileName, ms);
// if (lastCheckIn != null && lastCheckIn.CheckOut == null)
// {
// // ยังไม่เคย check-out มาก่อน หรือ check-out เป็น null ให้ใช้ชื่อไฟล์แบบ check-out
// await _minIOService.UploadFileAsync(fileNameCheckOut, ms);
// }
}
catch (Exception ex)
{
@ -988,6 +1008,42 @@ namespace BMA.EHR.Leave.Service.Controllers
}
if (lastCheckIn != null && lastCheckIn.CheckOut == null)
{
using (var ms2 = new MemoryStream(data.CheckInFileBytes ?? new byte[0]))
{
try
{
await _minIOService.UploadFileAsync(fileNameCheckOut, ms2);
// if (lastCheckIn != null && lastCheckIn.CheckOut == null)
// {
// // ยังไม่เคย check-out มาก่อน หรือ check-out เป็น null ให้ใช้ชื่อไฟล์แบบ check-out
// await _minIOService.UploadFileAsync(fileNameCheckOut, ms);
// }
}
catch (Exception ex)
{
await _checkInJobStatusRepository.UpdateToFailedAsync(taskId, $"ไม่สามารถอัปโหลดรูปภาพได้: {ex.Message}");
// send notification to user
var noti1 = new Notification
{
Body = $"ประมวลผลการลงเวลาวันที่ {currentDate.ToString("dd-MM-yyyy")} ไม่สำเร็จ \r\nเนื่องจากไม่สามารถอัปโหลดรูปภาพได้ {ex.Message}",
ReceiverUserId = profile.Id,
Type = "",
Payload = "",
};
_appDbContext.Set<Notification>().Add(noti1);
await _appDbContext.SaveChangesAsync();
return Error($"ไม่สามารถอัปโหลดรูปภาพได้: {ex.Message}", StatusCodes.Status500InternalServerError);
}
}
}
var defaultRound = await _dutyTimeRepository.GetDefaultAsync();
if (defaultRound == null)
{
@ -1015,6 +1071,124 @@ namespace BMA.EHR.Leave.Service.Controllers
// create check in object
if (data.CheckInId == null)
{
if (lastCheckIn != null && lastCheckIn.CheckOut == null)
{
var checkout = await _userTimeStampRepository.GetByIdAsync(lastCheckIn!.Id);
if(checkout != null)
{
var currentCheckInProcess = await _processUserTimeStampRepository.GetTimestampByDateAsync(userId, checkout.CheckIn.Date);
var checkout_process = await _processUserTimeStampRepository.GetByIdAsync(currentCheckInProcess!.Id);
var endTime1 = "";
var startTime1 = "";
var endTimeMorning1 = "";
if (!data.IsLocation && data.LocationName == "ไปประชุม / อบรม / สัมมนา")
{
startTime1 = "13:00";
endTime1 = "14:30";
endTimeMorning1 = "12:00";
}
else
{
endTime1 = duty.EndTimeAfternoon;
startTime1 = duty.StartTimeAfternoon;
endTimeMorning1 = duty.EndTimeMorning;
}
string checkOutStatus = "NORMAL";
var leaveReq1 = await _leaveRequestRepository.GetLeavePeriodAsync(userId, currentDate.Date);
if (leaveReq1 != null)
{
var leaveRange = leaveReq1.LeaveRangeEnd == null ? "" : leaveReq1.LeaveRangeEnd.ToUpper();
if (leaveRange == "AFTERNOON" || leaveRange == "ALL")
{
if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) <
DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning1}"))
checkOutStatus = "ABSENT";
else
checkOutStatus = "NORMAL";
}
else
{
// fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลาเข้า-ออกงาน (กรณีลงเวลาออกอีกวัน) #921
var currentDateTime = DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm"));
var dutyEndTimeAfternoon = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTime1}");
var dutyEndTimeMorning = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTimeMorning1}");
if(currentDateTime.Date > checkout.CheckIn.Date)
{
// ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ
checkOutStatus = "NORMAL";
}
else
{
// ถ้า check-out เป็นวันเดียวกับ check-in
// ตรวจสอบเวลาว่าสิ้นสุดก่อนบ่ายหรือไม่
if(currentDateTime < dutyEndTimeMorning) // ถ้าออกก่อนเวลาสิ้นสุดตอนเช้า ขาดราชการ
{
checkOutStatus = "ABSENT";
}
else if(currentDateTime >= dutyEndTimeAfternoon) // ถ้าออกหลังเวลาสิ้นสุดตอนบ่าย ปกติ
{
checkOutStatus = "NORMAL";
}
else
{
checkOutStatus = "ABSENT";
}
}
}
}
else
{
// fix issue : SIT ระบบบันทึกเวลาปฏิบัติงาน>>ลงเวลาเข้า-ออกงาน (กรณีลงเวลาออกอีกวัน) #921
var currentDateTime = DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm"));
var dutyEndTimeAfternoon = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTime1}");
var dutyEndTimeMorning = DateTime.Parse($"{checkout.CheckIn.ToString("yyyy-MM-dd")} {endTimeMorning1}");
if(currentDateTime.Date > checkout.CheckIn.Date)
{
// ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ
checkOutStatus = "NORMAL";
}
else
{
// ถ้า check-out เป็นวันเดียวกับ check-in
// ตรวจสอบเวลาว่าสิ้นสุดก่อนบ่ายหรือไม่
if(currentDateTime < dutyEndTimeMorning) // ถ้าออกก่อนเวลาสิ้นสุดตอนเช้า ขาดราชการ
{
checkOutStatus = "ABSENT";
}
else if(currentDateTime >= dutyEndTimeAfternoon) // ถ้าออกหลังเวลาสิ้นสุดตอนบ่าย ปกติ
{
checkOutStatus = "NORMAL";
}
else
{
checkOutStatus = "ABSENT";
}
}
}
if (checkout_process != null)
{
checkout_process.CheckOutLat = data.Lat;
checkout_process.CheckOutLon = data.Lon;
checkout_process.IsLocationCheckOut = data.IsLocation;
checkout_process.CheckOutLocationName = data.LocationName;
checkout_process.CheckOutPOI = data.POI;
checkout_process.CheckOutRemark = data.Remark;
checkout_process.CheckOutImageUrl = fileNameCheckOut;
checkout_process.CheckOut = currentDate;
checkout_process.CheckOutStatus = checkOutStatus;
await _processUserTimeStampRepository.UpdateAsync(checkout_process);
}
}
}
// validate duplicate check in
var currentCheckIn = await _userTimeStampRepository.GetTimestampByDateAsync(userId, currentDate);
@ -1167,6 +1341,7 @@ namespace BMA.EHR.Leave.Service.Controllers
else
{
var checkout = await _userTimeStampRepository.GetByIdAsync(data.CheckInId.Value);
//var currentCheckIn = await _userTimeStampRepository.GetTimestampByDateAsync(userId, currentDate);
if (checkout == null)
{
@ -1242,11 +1417,20 @@ namespace BMA.EHR.Leave.Service.Controllers
var leaveRange = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRange == "AFTERNOON" || leaveRange == "ALL")
{
if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) <
DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning}"))
checkOutStatus = "ABSENT";
else
if (checkout.CheckIn.Date < currentDate.Date)
{
// ถ้า check-out เป็นวันถัดไป สถานะปกติเสมอ
checkOutStatus = "NORMAL";
}
else
{
if(DateTime.Parse(currentDate.ToString("yyyy-MM-dd HH:mm")) <
DateTime.Parse($"{currentDate.ToString("yyyy-MM-dd")} {endTimeMorning}"))
checkOutStatus = "ABSENT";
else
checkOutStatus = "NORMAL";
}
}
else
{
@ -1407,7 +1591,7 @@ namespace BMA.EHR.Leave.Service.Controllers
public async Task<ActionResult<ResponseObject>> CheckInOldAsync([FromForm] CheckTimeDto data)
{
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
@ -1572,7 +1756,7 @@ namespace BMA.EHR.Leave.Service.Controllers
{
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
@ -1598,7 +1782,7 @@ namespace BMA.EHR.Leave.Service.Controllers
// var test = await _processUserTimeStampRepository.GetTimeStampHistoryAsync(userId, year);
// return Success(test);
var data = (await _processUserTimeStampRepository.GetTimeStampHistoryAsync(userId, year))
var data = (await _processUserTimeStampRepository.GetTimeStampHistoryAsync2(userId, year))
.Select(d => new CheckInHistoryDto
{
CheckInId = d.Id,
@ -1714,7 +1898,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -1861,7 +2045,7 @@ namespace BMA.EHR.Leave.Service.Controllers
}
else
{
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(d.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(d.KeycloakUserId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
@ -2023,7 +2207,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2269,11 +2453,11 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
var profile = await _userProfileRepository.SearchProfile(req.CitizenId, req.FirstName, req.LastName, AccessToken ?? "", req.Page, req.PageSize, role, nodeId, profileAdmin?.Node);
var profile = await _userProfileRepository.SearchProfile(req.CitizenId, req.FirstName, req.LastName, AccessToken ?? "", req.Page, req.PageSize, role, nodeId, profileAdmin?.Node, req.SelectedNodeId == null ? null : req.SelectedNodeId.Value.ToString("D"), req.SelectedNode);
// Get default round once
var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync();
@ -2317,7 +2501,16 @@ namespace BMA.EHR.Leave.Service.Controllers
FullName = $"{p.Prefix ?? ""}{p.FirstName ?? ""} {p.LastName ?? ""}",
StartTimeMorning = duty.StartTimeMorning,
LeaveTimeAfterNoon = duty.EndTimeAfternoon,
EffectiveDate = effectiveDate?.EffectiveDate?.Date
EffectiveDate = effectiveDate?.EffectiveDate?.Date,
Prefix = p.Prefix ?? "",
FirstName = p.FirstName ?? "",
LastName = p.LastName ?? "",
RootDnaId = p.RootDnaId,
Child1DnaId = p.Child1DnaId,
Child2DnaId = p.Child2DnaId,
Child3DnaId = p.Child3DnaId,
Child4DnaId = p.Child4DnaId
};
resultSet.Add(res);
}
@ -2384,6 +2577,64 @@ namespace BMA.EHR.Leave.Service.Controllers
}
[HttpPost("round/multiple")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> CreateChangeRoundMultipleAsync([FromBody] List<CreateChangeRoundMultipleDto> reqs)
{
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_WORK_ROUND_EDIT");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
var currentDate = DateTime.Now.Date;
List<UserDutyTime> dataList = new List<UserDutyTime>();
foreach(var req in reqs)
{
// var profile = await _userProfileRepository.GetProfileByProfileIdAsync(req.ProfileId, AccessToken);
// if (profile == null)
// {
// return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
// }
if (req.EffectiveDate.Date < currentDate)
{
continue; // move to next item if effective date is in the past, not return error
// return Error(new Exception($"กำหนดรอบลงเวลาของ {req.FirstName} {req.LastName} ผิดพลาด เนื่องจากวันที่มีผลต้องมากกว่าหรือเท่ากับวันที่ปัจจุบัน({currentDate.ToString("yyyy-MM-dd")})"), StatusCodes.Status400BadRequest);
}
var old = await _userDutyTimeRepository.GetExist(req.ProfileId, req.EffectiveDate);
if (old != null)
{
continue; // move to next item if already exist, not return error
//return Error(new Exception($"กำหนดรอบลงเวลาของ {req.FirstName} {req.LastName} ผิดพลาด เนื่องจากมีการกำหนดรอบการทำงานในวันที่นี้ไว้แล้ว"), StatusCodes.Status400BadRequest);
}
var data = new UserDutyTime
{
ProfileId = req.ProfileId,
DutyTimeId = req.RoundId,
EffectiveDate = req.EffectiveDate,
Remark = req.Remark,
RootDnaId = req.RootDnaId,
Child1DnaId = req.Child1DnaId,
Child2DnaId = req.Child2DnaId,
Child3DnaId = req.Child3DnaId,
Child4DnaId = req.Child4DnaId,
};
dataList.Add(data);
}
await _userDutyTimeRepository.AddRangeAsync(dataList);
return Success();
}
/// <summary>
/// LV1_015 - ประวัติการเปลี่ยนรอบการลงเวลา (ADMIN)
/// </summary>
@ -2524,7 +2775,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2744,7 +2995,7 @@ namespace BMA.EHR.Leave.Service.Controllers
var time = DateTime.Now;
var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty;
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -2864,7 +3115,7 @@ namespace BMA.EHR.Leave.Service.Controllers
}
var userId = UserId != null ? Guid.Parse(UserId) : Guid.Empty;
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
@ -2913,13 +3164,14 @@ namespace BMA.EHR.Leave.Service.Controllers
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetAdditionalCheckRequestAsync([Required] int year, [Required] int month, [Required] int page = 1, [Required] int pageSize = 10, string keyword = "", string? sortBy = "", bool? descending = false)
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_CHECKIN_SPECIAL");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_CHECKIN_SPECIAL");
//var jsonData = JsonConvert.DeserializeObject<GetPermissionWithActingResultDto>(getPermission);
if (jsonData!.status != 200)
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
return Error(jsonData.message, StatusCodes.Status403Forbidden);
}
string role = jsonData["result"]?.ToString();
//string role = jsonData["result"]?.ToString();
string role = jsonData.result.privilege;
var nodeId = string.Empty;
var profileAdmin = new GetUserOCAllDto();
profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken);
@ -2949,7 +3201,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2957,6 +3209,82 @@ namespace BMA.EHR.Leave.Service.Controllers
//var rawData = await _additionalCheckRequestRepository.GetAdditionalCheckRequests(year, month);
var rawData = await _additionalCheckRequestRepository.GetAdditionalCheckRequestsByAdminRole(year, month, role, nodeId, profileAdmin?.Node, keyword);
// ถ้ามีการรักษาการ
if (jsonData.result.isAct)
{
var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY");
foreach(var act in posActs)
{
var actRole = act.privilege;
string actNodeId = string.Empty;
int? actNode;
if (actRole == "NORMAL" || actRole == "CHILD")
{
actNodeId = act.child4DnaId != null ?
act.child4DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child1DnaId != null ?
act.child1DnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "BROTHER")
{
actNodeId = act.child4DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child1DnaId!.Value.ToString("D") :
act.child1DnaId != null ?
act.rootDnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "ROOT" /*|| role == "PARENT"*/)
{
actNodeId = act.rootDnaId!.Value.ToString("D");
actNode = 0;
}
var rawDataAct = await _additionalCheckRequestRepository.GetAdditionalCheckRequestsByAdminRole(year, month, actRole, actNodeId, profileAdmin?.Node, keyword);
if (rawDataAct != null)
{
if (rawData != null)
rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList();
else
rawData = rawDataAct;
}
}
}
var total = rawData.Count;
var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync();
@ -3027,17 +3355,16 @@ namespace BMA.EHR.Leave.Service.Controllers
foreach (var data in rawDataPaged)
{
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken);
if (profile == null)
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken);
UserDutyTime? effectiveDate = null;
if (profile != null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(profile.Id);
//return Error($"{data.Id} PF{data.FirstName} {data.LastName} : {GlobalMessages.DataNotFound}", StatusCodes.Status404NotFound);
}
//var userRound = await _dutyTimeRepository.GetByIdAsync(profile.DutyTimeId ?? Guid.Empty);
var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(profile.Id);
var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty;
var userRound = await _dutyTimeRepository.GetByIdAsync(roundId);
var checkInData = await _userTimeStampRepository.GetTimestampByDateAsync(data.KeycloakUserId, data.CheckDate);
var duty = userRound ?? getDefaultRound;
@ -3207,7 +3534,7 @@ namespace BMA.EHR.Leave.Service.Controllers
// change user timestamp
var processTimeStamp = await _processUserTimeStampRepository.GetTimestampByDateAsync(requestData.KeycloakUserId, requestData.CheckDate.Date);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(requestData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(requestData.KeycloakUserId, AccessToken);
if (processTimeStamp == null)
{
@ -3361,7 +3688,7 @@ namespace BMA.EHR.Leave.Service.Controllers
requestData.Comment = req.Reason;
await _additionalCheckRequestRepository.UpdateAsync(requestData);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(requestData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(requestData.KeycloakUserId, AccessToken);
var recvId = new List<Guid> { profile.Id };
await _notificationRepository.PushNotificationsAsync(recvId.ToArray(), "ลงเวลากรณีพิเศษ", "การขอลงเวลากรณีพิเศษของคุณไม่ได้รับการอนุมัติ", "", "", true, false);
@ -3405,7 +3732,7 @@ namespace BMA.EHR.Leave.Service.Controllers
}
else
{
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(d.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(d.KeycloakUserId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
@ -3499,7 +3826,7 @@ namespace BMA.EHR.Leave.Service.Controllers
foreach (var data in rawData)
{
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
@ -3789,7 +4116,7 @@ namespace BMA.EHR.Leave.Service.Controllers
//var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
// แก้เป็นมาใช้งาน KeycloakUserId แทน
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(data.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken);
var defaultRound = await _dutyTimeRepository.GetDefaultAsync();
if (defaultRound == null)
{
@ -3859,7 +4186,7 @@ namespace BMA.EHR.Leave.Service.Controllers
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetLeaveSummaryByProfileAsync(Guid id, [FromBody] GetLeaveSummaryDto req)
{
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(id, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(id, AccessToken);
var thisYear = DateTime.Now.Year;
var startDate = req.StartDate;
@ -3908,6 +4235,182 @@ namespace BMA.EHR.Leave.Service.Controllers
});
}
#endregion
#region " Process - Leave and Absence "
/// <summary>
/// สร้าง Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("admin/leave-task/process")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> CreateProcessTaskAsync([FromBody] CreateLeaveProcessJobDto req)
{
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
var task = new LeaveProcessJobStatus
{
RootDnaId = profile.RootDnaId ?? Guid.Empty,
CreatedUserId = profile.Keycloak?.ToString("D") ?? "",
CreatedFullName = profile.FirstName + " " + profile.LastName,
CreatedAt = DateTime.Now,
Status = "PENDING",
StartDate = req.StartDate,
EndDate = req.EndDate
};
await _leaveProcessJobStatusRepository.AddAsync(task);
return Success();
}
/// <summary>
/// แสดงรายการ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("admin/leave-task/process")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetProcessTaskAsync()
{
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var tasks = await _leaveProcessJobStatusRepository.GetByUserIdAsync(userId);
var result = tasks.Select(t => new
{
t.Id,
t.CreatedFullName,
t.CreatedAt,
t.Status,
t.StartDate,
t.EndDate,
t.ProcessingDate,
t.CompletedDate,
t.ErrorMessage
});
return Success(result);
}
/// <summary>
/// แสดงรายการ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("admin/leave-task/process/{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetProcessTaskByIdAsync(Guid id)
{
var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id);
if (task == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
var result = new
{
task.Id,
task.CreatedFullName,
task.CreatedAt,
task.Status,
task.StartDate,
task.EndDate,
task.ProcessingDate,
task.CompletedDate,
task.ErrorMessage
};
return Success(result);
}
/// <summary>
/// ลบ Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("admin/leave-task/process/{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> DeleteProcessTaskByIdAsync(Guid id)
{
var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id);
if (task == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
await _leaveProcessJobStatusRepository.DeleteAsync(task);
return Success();
}
/// <summary>
/// อัปเดต Task สำหรับ Process ข้อมูลวันลาและขาดราชการ (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("admin/leave-task/process/{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> UpdateProcessTaskByIdAsync(Guid id,[FromBody] CreateLeaveProcessJobDto req)
{
var task = await _leaveProcessJobStatusRepository.GetByTaskIdAsync(id);
if (task == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
if(task.Status != "PENDING")
{
return Error("ไม่สามารถแก้ไขได้เนื่องจาก Task อยู่ในสถานะกำลังดำเนินการหรือดำเนินการเสร็จสิ้นแล้ว");
}
task.StartDate = req.StartDate;
task.EndDate = req.EndDate;
await _leaveProcessJobStatusRepository.UpdateAsync(task);
return Success();
}
#endregion
#endregion

View file

@ -7,6 +7,7 @@ using BMA.EHR.Application.Responses.Profiles;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Extensions;
using BMA.EHR.Domain.Models.Leave.Requests;
using BMA.EHR.Domain.Models.Leave.TimeAttendants;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Leave.Service.DTOs.Reports;
using Microsoft.AspNetCore.Authorization;
@ -149,14 +150,26 @@ namespace BMA.EHR.Leave.Service.Controllers
}
var fullName = $"{profile!.Prefix}{profile!.FirstName} {profile!.LastName}";
var lastLeaveRequest =
await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync(data.KeycloakUserId,
data.Type.Id, data.LeaveStartDate.Date);
await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync2(data.KeycloakUserId,
data.Type.Id, data.CreatedAt);
var startFiscalYear = new DateTime(data.LeaveStartDate.Year - 1, 10, 1);
var endFiscalYear = data.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา
var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear);
var endFiscalYear = data.CreatedAt;
var thisYear = data.LeaveStartDate.Year;
var toDay = data.LeaveStartDate.Date;
if (toDay >= new DateTime(toDay.Year, 10, 1) && toDay <= new DateTime(toDay.Year, 12, 31))
thisYear = thisYear + 1;
var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, data.Type.Id, data.KeycloakUserId);
var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear);
if (leaveData != null)
{
sumLeave += leaveData.BeginningLeaveDays;
}
var Oc = profile.isCommission == false
? profile.Oc.ToThaiNumber()
: profile.Oc.Replace("สำนักงานคณะกรรมการข้าราชการกรุงเทพมหานคร", "สำนักงาน ก.ก.").ToThaiNumber();
@ -169,7 +182,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -259,7 +272,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -319,7 +332,7 @@ namespace BMA.EHR.Leave.Service.Controllers
var fullName = $"{profile!.Prefix}{profile!.FirstName} {profile!.LastName}";
var startFiscalYear = new DateTime(data.LeaveStartDate.Year - 1, 10, 1);
var endFiscalYear = data.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา
var endFiscalYear = data.CreatedAt;
var thisYear = data.LeaveStartDate.Year;
var toDay = data.LeaveStartDate.Date;
@ -333,7 +346,11 @@ namespace BMA.EHR.Leave.Service.Controllers
//var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear);
var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear);
var sumLeave = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(data.KeycloakUserId, data.Type.Id, startFiscalYear, endFiscalYear);
if (leaveData != null)
{
sumLeave += leaveData.BeginningLeaveDays;
}
//var sumLeave = leaveData == null ? 0.0 : leaveData.LeaveDaysUsed;
var leaveLimit = leaveData == null ? 0.0 : leaveData.LeaveDays;
@ -349,7 +366,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -444,7 +461,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -498,7 +515,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -585,7 +602,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -666,7 +683,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -769,7 +786,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -888,7 +905,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -984,7 +1001,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.LeaveWrote.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
leaveSubTypeName = data.LeaveSubTypeName != null ? data.LeaveSubTypeName.ToThaiNumber() : "",
dear = data.CommanderPosition == null ? data.Dear : data.CommanderPosition.ToThaiNumber(),
@ -1210,7 +1227,7 @@ namespace BMA.EHR.Leave.Service.Controllers
data = new
{
leaveWrote = data.CancelLeaveWrote!.ToThaiNumber() ?? "",
dateSendLeave = data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
dateSendLeave = data.DateSendLeave != null ? data.DateSendLeave.Value.Date.ToThaiShortDate().ToThaiNumber() : data.CreatedAt.Date.ToThaiShortDate().ToThaiNumber(),
leaveTypeName = data.Type.Name,
fullname = fullName,
position = string.IsNullOrEmpty(profile.Position) ? "-" : profile.Position,
@ -1324,7 +1341,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -1954,7 +1971,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2075,20 +2092,68 @@ namespace BMA.EHR.Leave.Service.Controllers
case "LV-005":
remarkStr += leaveReq.Type.Name;
var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper();
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRange != leaveRangeEnd)
if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date)
{
if (leaveRangeEnd == "MORNING")
remarkStr += " - ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += " - ครึ่งวันบ่าย";
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
// var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// if (leaveRangeEnd == "MORNING")
// remarkStr += "ครึ่งวันเช้า";
// else if (leaveRangeEnd == "AFTERNOON")
// remarkStr += "ครึ่งวันบ่าย";
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRange != leaveRangeEnd)
{
if (leaveRangeEnd == "MORNING")
remarkStr += " - ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += " - ครึ่งวันบ่าย";
}
}
else
{
if(dd.date == leaveReq.LeaveStartDate.Date)
{
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
}
else if(dd.date == leaveReq.LeaveEndDate.Date)
{
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRangeEnd == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
}
else
{
remarkStr += "เต็มวัน";
}
}
// if (leaveRange == "MORNING")
// remarkStr += "ครึ่งวันเช้า";
// else if (leaveRange == "AFTERNOON")
// remarkStr += "ครึ่งวันบ่าย";
// var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// if (leaveRange != leaveRangeEnd)
// {
// if (leaveRangeEnd == "MORNING")
// remarkStr += " - ครึ่งวันเช้า";
// else if (leaveRangeEnd == "AFTERNOON")
// remarkStr += " - ครึ่งวันบ่าย";
// }
break;
default:
remarkStr += leaveReq.Type.Name;
@ -2296,7 +2361,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2405,26 +2470,72 @@ namespace BMA.EHR.Leave.Service.Controllers
case "LV-005":
remarkStr += leaveReq.Type.Name;
var leaveRange = leaveReq.LeaveRange == null ? "" : leaveReq.LeaveRange.ToUpper();
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
if(leaveReq.LeaveStartDate.Date == leaveReq.LeaveEndDate.Date)
{
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
// var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// if (leaveRangeEnd == "MORNING")
// var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// if (leaveRangeEnd == "MORNING")
// remarkStr += "ครึ่งวันเช้า";
// else if (leaveRangeEnd == "AFTERNOON")
// remarkStr += "ครึ่งวันบ่าย";
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRange != leaveRangeEnd)
{
if (leaveRangeEnd == "MORNING")
remarkStr += " - ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += " - ครึ่งวันบ่าย";
}
}
else
{
if(dd.date == leaveReq.LeaveStartDate.Date)
{
if (leaveRange == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRange == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
}
else if(dd.date == leaveReq.LeaveEndDate.Date)
{
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRangeEnd == "MORNING")
remarkStr += "ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += "ครึ่งวันบ่าย";
}
else
{
remarkStr += "เต็มวัน";
}
}
// if (leaveRange == "MORNING")
// remarkStr += "ครึ่งวันเช้า";
// else if (leaveRangeEnd == "AFTERNOON")
// else if (leaveRange == "AFTERNOON")
// remarkStr += "ครึ่งวันบ่าย";
var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
if (leaveRange != leaveRangeEnd)
{
if (leaveRangeEnd == "MORNING")
remarkStr += " - ครึ่งวันเช้า";
else if (leaveRangeEnd == "AFTERNOON")
remarkStr += " - ครึ่งวันบ่าย";
}
// // var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// // if (leaveRangeEnd == "MORNING")
// // remarkStr += "ครึ่งวันเช้า";
// // else if (leaveRangeEnd == "AFTERNOON")
// // remarkStr += "ครึ่งวันบ่าย";
// var leaveRangeEnd = leaveReq.LeaveRangeEnd == null ? "" : leaveReq.LeaveRangeEnd.ToUpper();
// if (leaveRange != leaveRangeEnd)
// {
// if (leaveRangeEnd == "MORNING")
// remarkStr += " - ครึ่งวันเช้า";
// else if (leaveRangeEnd == "AFTERNOON")
// remarkStr += " - ครึ่งวันบ่าย";
// }
break;
default:
remarkStr += leaveReq.Type.Name;
@ -2741,29 +2852,45 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
var getDefaultRound = await _dutyTimeRepository.GetDefaultAsync();
if (getDefaultRound == null)
{
return Error("ไม่พบรอบลงเวลา Default", StatusCodes.Status404NotFound);
}
var userTimeStamps = await _processUserTimeStampRepository.GetTimestampByDateLateAsync(type.Trim().ToUpper(), role, nodeId, profileAdmin.Node, req.nodeId, req.node, req.StartDate, req.EndDate);
foreach (var p in userTimeStamps)
{
var fullName = $"{p.Prefix}{p.FirstName} {p.LastName}";
var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id);
UserDutyTime? effectiveDate = null;
effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.ProfileId ?? Guid.Empty);
//return Error($"{data.Id} PF{data.FirstName} {data.LastName} : {GlobalMessages.DataNotFound}", StatusCodes.Status404NotFound);
//var userRound = await _dutyTimeRepository.GetByIdAsync(profile.DutyTimeId ?? Guid.Empty);
var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty;
var userRound = await _dutyTimeRepository.GetByIdAsync(roundId);
var duty = userRound;
if (duty == null)
{
duty = await _dutyTimeRepository.GetDefaultAsync();
if (duty == null)
{
return Error("ไม่พบรอบการลงเวลา Default", StatusCodes.Status404NotFound);
}
}
var duty = userRound ?? getDefaultRound;
// var effectiveDate = await _userDutyTimeRepository.GetLastEffectRound(p.Id);
// var roundId = effectiveDate != null ? effectiveDate.DutyTimeId : Guid.Empty;
// var userRound = await _dutyTimeRepository.GetByIdAsync(roundId);
// var duty = userRound;
// if (duty == null)
// {
// duty = await _dutyTimeRepository.GetDefaultAsync();
// if (duty == null)
// {
// return Error("ไม่พบรอบการลงเวลา Default", StatusCodes.Status404NotFound);
// }
// }
DateTime? checkIn = p.CheckIn;
DateTime? checkOut = p.CheckOut ?? null;
var emp = new
@ -2862,13 +2989,21 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
var leaveDays = await _leaveRequestRepository.GetSumApproveLeaveByRootAndRange(req.StartDate, req.EndDate, type, jsonData["result"]?.ToString(), nodeId, profileAdmin?.Node, req.nodeId, req.node);
var enddate = req.EndDate.Date == req.StartDate.Date ? "" : $" - {req.EndDate.Date.ToThaiShortDate().ToThaiNumber()}";
// var thisYear = req.StartDate.Year;
// var toDay = req.StartDate.Date;
// if (toDay >= new DateTime(toDay.Year, 10, 1) && toDay <= new DateTime(toDay.Year, 12, 31))
// thisYear = thisYear + 1;
// var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, type, data.KeycloakUserId);
var result = new
{
template = "leave2",

View file

@ -17,6 +17,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NodaTime;
using Org.BouncyCastle.Asn1.Pkcs;
using Sentry;
using Swashbuckle.AspNetCore.Annotations;
@ -213,7 +214,7 @@ namespace BMA.EHR.Leave.Service.Controllers
var thisYear = DateTime.Now.Year;
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
@ -501,7 +502,7 @@ namespace BMA.EHR.Leave.Service.Controllers
foreach (var leave in leaves)
{
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(leave.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(leave.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(leave.KeycloakUserId, AccessToken);
if (profile != null)
{
leave.Prefix = profile.Prefix;
@ -562,7 +563,7 @@ namespace BMA.EHR.Leave.Service.Controllers
// }
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (profile == null)
{
@ -854,10 +855,10 @@ namespace BMA.EHR.Leave.Service.Controllers
{
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var thisYear = DateTime.Now.Year;
var thisYear = DateTime.Now.Year - 1;
var toDay = DateTime.Now.Date;
var startFiscalDate = new DateTime(DateTime.Now.Year, 10, 1);
var endFiscalDate = new DateTime(DateTime.Now.Year + 1, 9, 30);
var startFiscalDate = new DateTime(DateTime.Now.Year - 1, 10, 1);
var endFiscalDate = new DateTime(DateTime.Now.Year, 9, 30);
if (toDay >= startFiscalDate && toDay <= endFiscalDate)
thisYear = thisYear + 1;
@ -897,12 +898,12 @@ namespace BMA.EHR.Leave.Service.Controllers
if (leaveType.Code.Trim().ToUpper() == "LV-005")
{
if (govAge < 180)
leaveLimit = 0;
else
// if (profile.IsProbation! == true)
// leaveLimit = 0;
// else
{
leaveLimit = leaveData == null ?
govAge < 180 ? 0 : 10
10
: leaveData.LeaveDays;
}
}
@ -911,11 +912,11 @@ namespace BMA.EHR.Leave.Service.Controllers
var restOldDay = leaveData == null ? 0 : leaveData.LeaveDays - 10;
var restCurrentDay = 10.0;
if (govAge < 180)
{
restOldDay = 0;
restCurrentDay = 0;
}
// if (profile.IsProbation! == true)
// {
// restOldDay = 0;
// restCurrentDay = 0;
// }
if(restOldDay < 0)
restOldDay = 0;
var sumLeave = leaveData == null ? 0 : leaveData.LeaveDaysUsed;
@ -924,6 +925,9 @@ namespace BMA.EHR.Leave.Service.Controllers
var leaveLast = await _leaveRequestRepository.GetLeaveLastByTypeForUserAsync(userId, req.Type);
var leaveDraftSummary = await _leaveRequestRepository.GetSumDraftLeaveTotalByTypeAndRangeForUser2(userId, req.Type, startFiscalDate, endFiscalDate);
var leaveWaitingSummary = await _leaveRequestRepository.GetSumNewLeaveTotalByTypeAndRangeForUser2(userId, req.Type, startFiscalDate, endFiscalDate);
var result = new GetUserLeaveProfileResultDto
{
DateSendLeave = DateTime.Now.Date,
@ -959,12 +963,56 @@ namespace BMA.EHR.Leave.Service.Controllers
CurrentDistrict = profile.CurrentDistrict ?? "",
CurrentProvince = profile.CurrentProvince ?? "",
CurrentZipCode = profile.CurrentZipCode ?? "",
GovAge = govAge
GovAge = govAge,
LeaveDraftSummary = leaveDraftSummary,
LeaveWaitingSummary = leaveWaitingSummary
};
return Success(result);
}
[HttpGet("time-check")]
[AllowAnonymous]
public async Task<ActionResult<ResponseObject>> TimeCheckAsync()
{
var startDate = new DateTime(2017, 1, 6);
var govAge = (startDate).DiffDay(DateTime.Now.Date);
var date1Raw = startDate;
var date1 = new LocalDate(date1Raw.Year, date1Raw.Month, date1Raw.Day);
var date2 = new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
var (govAgeYear, govAgeMonth, govAgeDay) = startDate.GetDifference(DateTime.Now.Date);
var isLeave = false;
var message = string.Empty;
if (govAgeYear >= 1 || (govAgeYear == 0 && govAgeMonth >= 6))
{
isLeave = true;
if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด";
}
else
{
isLeave = false;
if (!isLeave) message = "อายุราชการน้อยกว่า 6 เดือนหรือ 180 วัน";
}
return Success(new
{
GovAge = govAge,
GovAgeDay = govAgeDay,
GovAgeMonth = govAgeMonth,
GovAgeYear = govAgeYear,
IsLeave = isLeave,
Message = message
});
}
/// <summary>
/// LV2_003 - เช็คการยืนขอลา (USER)
/// </summary>
@ -984,8 +1032,18 @@ namespace BMA.EHR.Leave.Service.Controllers
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
var govAge = (profile?.DateStart?.Date ?? DateTime.Now.Date).DiffDay(DateTime.Now.Date);
var startDate = profile?.DateStart?.Date ?? DateTime.Now.Date;
// var date1Raw = profile?.DateStart?.Date ?? DateTime.Now.Date;
// var date1 = new LocalDate(date1Raw.Year, date1Raw.Month, date1Raw.Day);
// var date2 = new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
// Period period = Period.Between(date1, date2);
// var govAgeMonth = period.Months;
// var govAgeYear = period.Years;
var (govAgeYear, govAgeMonth, govAgeDay) = startDate.GetDifference(DateTime.Now.Date);
var thisYear = DateTime.Now.Year;
var message = string.Empty;
@ -1018,26 +1076,38 @@ namespace BMA.EHR.Leave.Service.Controllers
fiscalYear = req.StartLeaveDate.Year + 1;
var sumLeaveDay = await _leaveBeginningRepository.GetByYearAndTypeIdForUserAsync(fiscalYear, req.Type, userId);
var minLeave = (await _context.Set<LeaveRequest>().Where(x => x.Type.Id == req.Type &&
(x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") &&
x.KeycloakUserId == userId)
.OrderBy(x => x.LeaveStartDate)
.FirstOrDefaultAsync());
var maxLeave = (await _context.Set<LeaveRequest>().Where(x => x.Type.Id == req.Type &&
(x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") &&
x.KeycloakUserId == userId)
.OrderByDescending(x => x.LeaveEndDate)
.FirstOrDefaultAsync());
var isBetween = false;
if (minLeave != null && maxLeave != null)
{
isBetween = (req.StartLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date) ||
(req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.EndLeaveDate.Date <= maxLeave.LeaveEndDate.Date);
}
var existingLeaves = await _context.Set<LeaveRequest>()
.Where(x => x.Type.Id == req.Type &&
(x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") &&
x.KeycloakUserId == userId)
.ToListAsync();
isBetween = existingLeaves.Any(leave =>
req.StartLeaveDate.Date <= leave.LeaveEndDate.Date &&
req.EndLeaveDate.Date >= leave.LeaveStartDate.Date);
// var minLeave = (await _context.Set<LeaveRequest>().Where(x => x.Type.Id == req.Type &&
// (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") &&
// x.KeycloakUserId == userId)
// .OrderBy(x => x.LeaveStartDate)
// .FirstOrDefaultAsync());
// var maxLeave = (await _context.Set<LeaveRequest>().Where(x => x.Type.Id == req.Type &&
// (x.LeaveStatus == "PENDING" || x.LeaveStatus == "APPROVE") &&
// x.KeycloakUserId == userId)
// .OrderByDescending(x => x.LeaveEndDate)
// .FirstOrDefaultAsync());
// var isBetween = false;
// if (minLeave != null && maxLeave != null)
// {
// // isBetween = (req.StartLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date) ||
// // (req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date && req.EndLeaveDate.Date <= maxLeave.LeaveEndDate.Date);
// isBetween = req.StartLeaveDate.Date <= maxLeave.LeaveEndDate.Date &&
// req.EndLeaveDate.Date >= minLeave.LeaveStartDate.Date;
// }
var isLeave = false;
var approveDay = sumLeaveDay == null ? 0.0 : sumLeaveDay.LeaveDaysUsed;
@ -1055,12 +1125,11 @@ namespace BMA.EHR.Leave.Service.Controllers
case "LV-002":
// fix issue : ระบบลา (ขรก.) >> ลากิจส่วนตัว (กรณียื่นขอลาเกิน 45 วัน/ปี) #829
// fix issue : ระบบลา (ขรก.) >> ลากิจส่วนตัว (กรณีผู้เข้ารับราชการไม่เกิน 1 ปี ยื่นขอลาเกิน 15 วัน/ปี) #831
if (govAge <= 365)
if (govAgeYear <= 1)
{
isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= 15;
if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด";
}
else
{
isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= 45;
@ -1082,36 +1151,11 @@ namespace BMA.EHR.Leave.Service.Controllers
break;
case "LV-005":
// fix issue : ระบบลา (ขรก.) >> ลาพักผ่อน (กรณีรับราชการไม่ถึง 6 เดือน) #838
//var leavePrevYear = (await _leaveRequestRepository.GetSumApproveLeaveAsync(fiscalYear - 1)).Where(x => x.LeaveTypeCode == "LV-005" && x.KeycloakUserId == userId).FirstOrDefault();
//var leavePrevYearRemain = 10 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน
if (profile.IsProbatin! == true)
{
isLeave = false;
if (!isLeave) message = "ยังอยู่ในช่วงทดลองปฏิบัติราชการ ไม่สามารถลาพักผ่อนได้";
}
else if (govAge >= 180)
if (govAgeYear >= 1 || (govAgeYear == 0 && govAgeMonth >= 6))
{
isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= (limitDay);
if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด";
}
// else if (govAge >= 3650)
// {
// // ถ้าอายุราชการเกิน 10 ปี ได้บวกเพิ่มอีก 10 วัน
// var leavePrevYearRemain = 30 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน
// if (leavePrevYearRemain >= 20) leavePrevYearRemain = 20;
// isLeave = (totalDay - (sumWorkDay + sumWeekend) + approveDay) <= (limitDay);
// if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด";
// }
// else if
// {
// //var leavePrevYearRemain = 20 - (leavePrevYear == null ? 0 : leavePrevYear.SumLeaveDay); // หายอดวันลาที่เหลือของปีก่อน
// //if (leavePrevYearRemain >= 10) leavePrevYearRemain = 10;
// isLeave = (totalDay - (sumWorkDay + sumWeekend) + sumApproveLeave) <= (10 + leavePrevYearRemain);
// if (!isLeave) message = "จำนวนวันลาเกินที่กำหนด";
// }
else
{
isLeave = false;
@ -1121,7 +1165,7 @@ namespace BMA.EHR.Leave.Service.Controllers
break;
case "LV-006":
// fix issue : ระบบลา(ขรก.) >> ลาอุปสมบทหรือการลาประกอบพิธีฮัจย์ฯ(กรณีรับราชการน้อยกว่า 1 ปี) #840
if (govAge < 365)
if (govAgeYear < 1)
{
isLeave = false;
if (!isLeave) message = "อายุราชการน้อยกว่า 1 ปีหรือ 365 วัน";
@ -1147,7 +1191,7 @@ namespace BMA.EHR.Leave.Service.Controllers
break;
case "LV-008":
case "LV-009":
isLeave = govAge >= 365;
isLeave = govAgeYear >= 1;
if (!isLeave) message = "อายุราชการน้อยกว่า 1 ปีหรือ 365 วัน";
break;
case "LV-010":
@ -1286,7 +1330,7 @@ namespace BMA.EHR.Leave.Service.Controllers
Id = d.Id,
LeaveTypeId = d.Type.Id,
LeaveTypeName = d.Type.Name,
DateSendLeave = d.CreatedAt.Date,
DateSendLeave = d.DateSendLeave != null ? d.DateSendLeave.Value.Date : d.CreatedAt.Date,
Status = d.LeaveStatus,
FullName = $"{d.Prefix}{d.FirstName} {d.LastName}",
LeaveEndDate = d.LeaveEndDate,
@ -1314,14 +1358,14 @@ namespace BMA.EHR.Leave.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetLeaveRequestCalendarAdminAsync(
[FromBody] GetLeaveRequestCalendarDto req)
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST");
//var jsonData = JsonConvert.DeserializeObject<GetPermissionWithActingResultDto>(getPermission);
if (jsonData!.status != 200)
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
return Error(jsonData.message, StatusCodes.Status403Forbidden);
}
string role = jsonData["result"]?.ToString();
//string role = jsonData["result"]?.ToString();
string role = jsonData.result.privilege;
var nodeId = string.Empty;
var profileAdmin = new GetUserOCAllDto();
profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken);
@ -1351,12 +1395,93 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
var data = await _leaveRequestRepository.GetLeaveRequestByYearForAdminAsync(req.Year, role, nodeId, profileAdmin.Node);
// ถ้ามีการรักษาการ
if (jsonData.result.isAct)
{
var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY");
foreach(var act in posActs)
{
var actRole = act.privilege;
string actNodeId = string.Empty;
int? actNode = null;
if (actRole == "NORMAL" || actRole == "CHILD")
{
actNodeId = act.child4DnaId != null ?
act.child4DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child1DnaId != null ?
act.child1DnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "BROTHER")
{
actNodeId = act.child4DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child1DnaId!.Value.ToString("D") :
act.child1DnaId != null ?
act.rootDnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "ROOT" /*|| role == "PARENT"*/)
{
actNodeId = act.rootDnaId!.Value.ToString("D");
actNode = 0;
}
var rawDataAct = await _leaveRequestRepository.GetLeaveRequestByYearForAdminAsync(req.Year, actRole, actNodeId, actNode);
if (rawDataAct != null)
{
if (data != null)
data = data.Union(rawDataAct).DistinctBy(x => x.Id).ToList();
else
data = rawDataAct;
}
}
}
var resultData = (from d in data
//join p in profileList on d.KeycloakUserId equals p.Keycloak
select new GetLeaveRequestCalendarResultDto
@ -1364,7 +1489,7 @@ namespace BMA.EHR.Leave.Service.Controllers
Id = d.Id,
LeaveTypeId = d.Type.Id,
LeaveTypeName = d.Type.Name,
DateSendLeave = d.CreatedAt.Date,
DateSendLeave = d.DateSendLeave != null ? d.DateSendLeave.Value.Date : d.CreatedAt.Date,
Status = d.LeaveStatus,
FullName = $"{d.Prefix}{d.FirstName} {d.LastName}",
LeaveEndDate = d.LeaveEndDate,
@ -1417,7 +1542,7 @@ namespace BMA.EHR.Leave.Service.Controllers
LeaveTypeName = item.Type.Name,
LeaveSubTypeName = item.LeaveSubTypeName ?? "",
FullName = $"{item.Prefix}{item.FirstName} {item.LastName}",
DateSendLeave = item.CreatedAt,
DateSendLeave = item.DateSendLeave ?? item.CreatedAt,
IsDelete = item.LeaveStatus == "DELETE",
Status = item.LeaveStatus,
LeaveStartDate = item.LeaveStartDate,
@ -1539,7 +1664,7 @@ namespace BMA.EHR.Leave.Service.Controllers
}
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(rawData.KeycloakUserId, AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(rawData.KeycloakUserId, AccessToken);
if (profile == null)
{
@ -1578,7 +1703,8 @@ namespace BMA.EHR.Leave.Service.Controllers
var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUserAsync(thisYear, rawData.Type.Id, rawData.KeycloakUserId);
var restDayOld = govAge < 180 ? 0 : leaveData == null ? 0 : leaveData.LeaveDays - 10;
var restDayOld = govAge < 180 ? 0 : leaveData == null ? 0 : (leaveData.LeaveDays + leaveData.BeginningLeaveDays - 10);
if (restDayOld < 0) restDayOld = 0;
var restDayCurrent = govAge < 180 ? 0 : 10;
@ -1591,7 +1717,7 @@ namespace BMA.EHR.Leave.Service.Controllers
LeaveSubTypeName = rawData.LeaveSubTypeName,
LeaveTypeId = rawData.Type.Id,
FullName = $"{rawData.Prefix}{rawData.FirstName} {rawData.LastName}",
DateSendLeave = rawData.CreatedAt,
DateSendLeave = rawData.DateSendLeave ?? rawData.CreatedAt,
Status = rawData.LeaveStatus,
LeaveStartDate = rawData.LeaveStartDate,
LeaveEndDate = rawData.LeaveEndDate,
@ -1711,14 +1837,14 @@ namespace BMA.EHR.Leave.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetLeaveRequestForAdminAsync(
[FromBody] GetLeaveRequestForAdminDto req)
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST");
//var jsonData = JsonConvert.DeserializeObject<GetPermissionWithActingResultDto>(getPermission);
if (jsonData!.status != 200)
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
return Error(jsonData.message, StatusCodes.Status403Forbidden);
}
string role = jsonData["result"]?.ToString();
//string role = jsonData["result"]?.ToString();
string role = jsonData.result.privilege;
var nodeId = string.Empty;
var profileAdmin = new GetUserOCAllDto();
profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken);
@ -1748,13 +1874,92 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
var rawData = await _leaveRequestRepository.GetListLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, req.StartDate, req.EndDate, role, nodeId, profileAdmin?.Node);
// ถ้ามีการรักษาการ
if (jsonData.result.isAct)
{
var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY");
foreach(var act in posActs)
{
var actRole = act.privilege;
string actNodeId = string.Empty;
int? actNode = null;
if (actRole == "NORMAL" || actRole == "CHILD")
{
actNodeId = act.child4DnaId != null ?
act.child4DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child1DnaId != null ?
act.child1DnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "BROTHER")
{
actNodeId = act.child4DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child1DnaId!.Value.ToString("D") :
act.child1DnaId != null ?
act.rootDnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "ROOT" /*|| role == "PARENT"*/)
{
actNodeId = act.rootDnaId!.Value.ToString("D");
actNode = 0;
}
var rawDataAct = await _leaveRequestRepository.GetListLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, req.StartDate, req.EndDate, actRole, actNodeId, actNode);
if (rawDataAct != null)
{
if (rawData != null)
rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList();
else
rawData = rawDataAct;
}
}
}
var result = new List<GetLeaveRequestForAdminResultDto>();
foreach (var item in rawData)
@ -1787,7 +1992,7 @@ namespace BMA.EHR.Leave.Service.Controllers
LeaveSubTypeName = item.LeaveSubTypeName,
FullName = $"{item.Prefix}{item.FirstName} {item.LastName}",
ProfileType = item.ProfileType ?? "-",
DateSendLeave = item.CreatedAt,
DateSendLeave = item.DateSendLeave ?? item.CreatedAt,
Status = item.LeaveStatus,
CitizenId = item.CitizenId ?? "",
LeaveStartDate = item.LeaveStartDate,
@ -1837,6 +2042,12 @@ namespace BMA.EHR.Leave.Service.Controllers
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(data.KeycloakUserId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.ProfileNotFound, StatusCodes.Status404NotFound);
}
// change status to delete
// แก้จาก DELETE เป็น DELETING ไว้ก่อน รอ approve ค่อยเปลี่ยนเป็น DELETE
// data.LeaveStatus = "DELETE";
@ -1873,7 +2084,7 @@ namespace BMA.EHR.Leave.Service.Controllers
// TODO: Send notification to all users who need to approve the cancel leave request
var approvers = data.Approvers
.Where(x => x.ApproveStatus!.ToUpper() == "PENDING")
//.Where(x => x.ApproveStatus!.ToUpper() == "PENDING")
.OrderBy(x => x.Seq)
.ToList();
@ -1885,11 +2096,33 @@ namespace BMA.EHR.Leave.Service.Controllers
Body = $"คำร้องขอยกเลิกการลาของคุณ {data.FirstName} {data.LastName} รอรับการอนุมัติจากคุณ",
ReceiverUserId = approver!.ProfileId,
Type = "",
Payload = $"{URL}/leave/detail/{id}",
Payload = $"{URL}/leave-reject/detail/{id}",
};
_appDbContext.Set<Notification>().Add(noti1);
}
// Get Officer List
var officers = await _userProfileRepository.GetOCStaffAsync(profile.Id, AccessToken);
var approverProfileIdList = approvers.Select(x => x.ProfileId).ToList();
if(officers != null && officers.Count > 0)
{
officers = officers.Where(x => !approverProfileIdList.Contains(x.ProfileId)).ToList();
foreach (var officer in officers)
{
// Send Notification
var noti = new Notification
{
Body = $"คำร้องขอยกเลิกการลาของคุณ {data.FirstName} {data.LastName} รอรับการอนุมัติจากคุณ",
ReceiverUserId = officer.ProfileId,
Type = "",
Payload = $"{URL}/leave-reject/detail/{id}",
};
_appDbContext.Set<Notification>().Add(noti);
}
await _appDbContext.SaveChangesAsync();
}
return Success();
}
@ -1909,14 +2142,14 @@ namespace BMA.EHR.Leave.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetCancelLeaveRequestForAdminAsync(
[FromBody] GetLeaveRequestForAdminDto req)
{
var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_LEAVE_LIST");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
var jsonData = await _permission.GetPermissionWithActingAPIAsync("LIST", "SYS_LEAVE_LIST");
//var jsonData = JsonConvert.DeserializeObject<GetPermissionWithActingResultDto>(getPermission);
if (jsonData!.status != 200)
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
return Error(jsonData.message, StatusCodes.Status403Forbidden);
}
string role = jsonData["result"]?.ToString();
//string role = jsonData["result"]?.ToString();
string role = jsonData.result.privilege;
var nodeId = string.Empty;
var profileAdmin = new GetUserOCAllDto();
profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken);
@ -1946,7 +2179,7 @@ namespace BMA.EHR.Leave.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -1954,6 +2187,84 @@ namespace BMA.EHR.Leave.Service.Controllers
var rawData =
await _leaveRequestRepository.GetCancelLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, role, nodeId, profileAdmin?.Node);
// ถ้ามีการรักษาการ
if (jsonData.result.isAct)
{
var posActs = jsonData.result.posMasterActs.Where(x => x.privilege != "EMPTY");
foreach(var act in posActs)
{
var actRole = act.privilege;
string actNodeId = string.Empty;
int? actNode = null;
if (actRole == "NORMAL" || actRole == "CHILD")
{
actNodeId = act.child4DnaId != null ?
act.child4DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child1DnaId != null ?
act.child1DnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "BROTHER")
{
actNodeId = act.child4DnaId != null ?
act.child3DnaId.Value.ToString("D") :
act.child3DnaId != null ?
act.child2DnaId.Value.ToString("D") :
act.child2DnaId != null ?
act.child1DnaId!.Value.ToString("D") :
act.child1DnaId != null ?
act.rootDnaId.Value.ToString("D") :
act.rootDnaId != null ?
act.rootDnaId.Value.ToString("D") :
"";
actNode = act.child4DnaId != null ?
4 :
act.child3DnaId != null ?
3 :
act.child2DnaId != null ?
2 :
act.child1DnaId != null ?
1 :
act.rootDnaId != null ?
0 :
null;
}
else if (actRole == "ROOT" /*|| role == "PARENT"*/)
{
actNodeId = act.rootDnaId!.Value.ToString("D");
actNode = 0;
}
var rawDataAct = await _leaveRequestRepository.GetCancelLeaveRequestForAdminAsync(req.Year, req.Type, req.Status, actRole, actNodeId, actNode);
if (rawDataAct != null)
{
if (rawData != null)
rawData = rawData.Union(rawDataAct).DistinctBy(x => x.Id).ToList();
else
rawData = rawDataAct;
}
}
}
var recCount = rawData.Count;
if (req.Keyword != "")
@ -1976,7 +2287,7 @@ namespace BMA.EHR.Leave.Service.Controllers
LeaveSubTypeName = item.LeaveSubTypeName,
ProfileType = item.ProfileType ?? "-",
FullName = $"{item.Prefix}{item.FirstName} {item.LastName}",
DateSendLeave = item.CreatedAt.Date,
DateSendLeave = item.DateSendLeave != null ? item.DateSendLeave.Value.Date : item.CreatedAt.Date,
Status = item.LeaveCancelStatus ?? ""
};
result.Add(res);
@ -2073,7 +2384,7 @@ namespace BMA.EHR.Leave.Service.Controllers
}
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(Guid.Parse(UserId!), AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(Guid.Parse(UserId!), AccessToken);
var profile = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(Guid.Parse(UserId!), AccessToken);
if (profile == null)
{
@ -2321,12 +2632,31 @@ namespace BMA.EHR.Leave.Service.Controllers
await _leaveRequestRepository.SendToOfficerAsync(id);
// Remove Workflow Integration
// var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
// var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
// if (profile == null)
// {
// return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
// }
var userId = UserId == null ? Guid.Empty : Guid.Parse(UserId);
var profile = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
if (profile == null)
{
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
}
// Get Officer List
var officers = await _userProfileRepository.GetOCStaffAsync(profile.Id, AccessToken);
if(officers != null && officers.Count > 0)
{
foreach (var officer in officers)
{
// Send Notification
var noti = new Notification
{
Body = $"มีคำร้องขอลาจาก {profile.Prefix}{profile.FirstName} {profile.LastName} รอรับการอนุมัติจากคุณ",
ReceiverUserId = officer.ProfileId,
Type = "",
Payload = $"{URL}/leave/detail/{id}",
};
_appDbContext.Set<Notification>().Add(noti);
}
await _appDbContext.SaveChangesAsync();
}
// var baseAPIOrg = _configuration["API"];
// var apiUrlOrg = $"{baseAPIOrg}/org/workflow/add-workflow";
// if (profile.ProfileType == "OFFICER")
@ -2469,8 +2799,8 @@ namespace BMA.EHR.Leave.Service.Controllers
//var lastSalaryAmount = lastSalary == null ? 0 : lastSalary.Amount ?? 0;
var lastLeaveRequest =
await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync(rawData.KeycloakUserId,
rawData.Type.Id, rawData.LeaveStartDate.Date);
await _leaveRequestRepository.GetLastLeaveRequestByTypeForUserAsync2(rawData.KeycloakUserId,
rawData.Type.Id, rawData.CreatedAt);
//var rootOc = _userProfileRepository.GetRootOcId(profile.OcId ?? Guid.Empty, AccessToken);
//var approver = string.Empty;
@ -2505,9 +2835,17 @@ namespace BMA.EHR.Leave.Service.Controllers
var leaveData = await _leaveBeginningRepository.GetByYearAndTypeIdForUser2Async(thisYear, rawData.Type.Id, rawData.KeycloakUserId);
var startFiscalYear = new DateTime(rawData.LeaveStartDate.Year - 1, 10, 1);
var endFiscalYear = rawData.LeaveStartDate.Date.AddDays(-1); // นับจากวันที่ยื่นลา
var leaveSummary = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear);
var endFiscalYear = rawData.CreatedAt;
var endFiscalYear2 = new DateTime(rawData.LeaveStartDate.Year, 9, 30);
var leaveSummary = await _leaveRequestRepository.GetSumApproveLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear);
// วันลาแบบร่างและที่ยื่นลาไปแล้ว
var leaveDraftSummary = await _leaveRequestRepository.GetSumDraftLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear2);
var leaveWaitingSummary = await _leaveRequestRepository.GetSumNewLeaveTotalByTypeAndRangeForUser2(rawData.KeycloakUserId, rawData.Type.Id, startFiscalYear, endFiscalYear2);
//var leaveSummary = leaveData == null ? 0.0 : leaveData.LeaveDaysUsed;
if (leaveData != null)
leaveSummary += leaveData.BeginningLeaveDays;
var extendLeave = 0.0;
var leaveLimit = (double)rawData.Type.Limit;
@ -2515,7 +2853,7 @@ namespace BMA.EHR.Leave.Service.Controllers
if (rawData.Type.Code == "LV-005")
{
leaveLimit = leaveData == null ? 0.0 : leaveData.LeaveDays;
extendLeave = leaveLimit - 10;
extendLeave = leaveLimit <= 0 ? 0 : leaveLimit - 10;
}
var result = new GetLeaveRequestForAdminByIdDto
@ -2528,7 +2866,7 @@ namespace BMA.EHR.Leave.Service.Controllers
LeaveSubTypeName = rawData.LeaveSubTypeName,
LeaveTypeId = rawData.Type.Id,
FullName = $"{rawData.Prefix}{rawData.FirstName} {rawData.LastName}",
DateSendLeave = rawData.CreatedAt,
DateSendLeave = rawData.DateSendLeave ?? rawData.CreatedAt,
Status = rawData.LeaveStatus,
LeaveStartDate = rawData.LeaveStartDate,
LeaveEndDate = rawData.LeaveEndDate,
@ -2614,13 +2952,14 @@ namespace BMA.EHR.Leave.Service.Controllers
//OrganizationName = rawData.OrganizationName ?? "",
// fix SIT ระบบบันทึกการลา>>รายการลา (ข้อมูลผู้สังกัดและเรียนไม่แสดง) #971
ApproveStep = rawData.ApproveStep ?? "-",
LeaveLimit = rawData.Type.Limit + extendLeave,
LeaveSummary = leaveSummary,
LeaveRemain = (rawData.Type.Limit + extendLeave) - leaveSummary
LeaveRemain = (rawData.Type.Limit + extendLeave) - leaveSummary,
LeaveDraftSummary = leaveDraftSummary,
LeaveWaitingSummary = leaveWaitingSummary
};
if (rawData.LeaveDocument != null && rawData.LeaveDocument.Count > 0)
@ -2699,7 +3038,7 @@ namespace BMA.EHR.Leave.Service.Controllers
var rejectList = await _leaveRequestRepository.GetSumRejectLeaveAsync(thisYear);
var deleteList = await _leaveRequestRepository.GetSumDeleteLeaveAsync(thisYear);
// var pf = await _userProfileRepository.GetProfileByKeycloakIdAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNewAsync(userId, AccessToken);
var pf = await _userProfileRepository.GetProfileByKeycloakIdNew2Async(userId, AccessToken);
if (pf == null)
{
@ -2741,7 +3080,7 @@ namespace BMA.EHR.Leave.Service.Controllers
if (leaveType.Code == "LV-005")
{
leaveLimit = leaveData?.LeaveDays ?? 0.0;
extendLeave = leaveLimit - 10;
extendLeave = leaveLimit <= 0 ? 0 : leaveLimit - 10;
}
var data = new

View file

@ -12,4 +12,25 @@ namespace BMA.EHR.Leave.Service.DTOs.ChangeRound
public string Remark { get; set; }
}
public class CreateChangeRoundMultipleDto
{
public Guid ProfileId { get; set; }
public Guid RoundId { get; set; }
public DateTime EffectiveDate { get; set; }
public string Remark { get; set; }
public Guid? RootDnaId { get; set; }
public Guid? Child1DnaId { get; set; }
public Guid? Child2DnaId { get; set; }
public Guid? Child3DnaId { get; set; }
public Guid? Child4DnaId { get; set; }
public string? Prefix { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
}
}

View file

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

View file

@ -17,5 +17,11 @@
public string LeaveTimeAfterNoon { get;set; }
public DateTime? EffectiveDate { get; set; }
public string? RootDnaId { get; set; }
public string? Child1DnaId { get; set; }
public string? Child2DnaId { get; set; }
public string? Child3DnaId { get; set; }
public string? Child4DnaId { get; set; }
}
}

View file

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

View file

@ -22,5 +22,42 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveBeginnings
[Required, Comment("จำนวนครั้งที่ลาสะสม")]
public int LeaveCount { get; set; } = 0;
[Required, Comment("จำนวนวันลายกมา")]
public double BeginningLeaveDays { get; set; } = 0.0;
[Comment("จำนวนครั้งที่ลายกมา")]
public int BeginningLeaveCount { get; set; } = 0;
}
public class ScheduleEditLeaveBeginningDto
{
[Required]
public Guid ProfileId { get; set; } = Guid.Empty;
[Required]
public Guid LeaveTypeId { get; set; } = Guid.Empty;
[Required, Comment("ปีงบประมาณ")]
public int LeaveYear { get; set; } = 0;
[Required, Comment("จำนวนวันลายกมา")]
public double LeaveDays { get; set; } = 0.0;
}
public class ScheduleUpdateDnaDto
{
[Required]
public Guid ProfileId { get; set; } = Guid.Empty;
// [Required, Comment("ปีงบประมาณ")]
// public int LeaveYear { get; set; } = 0;
public Guid? RootDnaId { get; set; }
public Guid? Child1DnaId { get; set; }
public Guid? Child2DnaId { get; set; }
public Guid? Child3DnaId { get; set; }
public Guid? Child4DnaId { get; set; }
}
}

View file

@ -0,0 +1,23 @@
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

@ -147,6 +147,10 @@ namespace BMA.EHR.Leave.Service.DTOs.LeaveRequest
public List<GetLeaveApproverDto> Approvers { get; set; } = new();
public Guid? KeycloakUserId { get; set; } = Guid.Empty;
public double LeaveDraftSummary { get; set; } = 0;
public double LeaveWaitingSummary { get; set; } = 0;
}
public class GetLeaveApproverDto

View file

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

View file

@ -119,7 +119,7 @@ builder.Services.AddHealthChecks();
builder.Services.AddRabbitMqConnectionPooling(builder.Configuration);
// Add Hangfire services.
var defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
var hangfireConnection = builder.Configuration.GetConnectionString("defaultConnection");
builder.Services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
@ -127,19 +127,24 @@ builder.Services.AddHangfire(configuration => configuration
.UseRecommendedSerializerSettings()
.UseStorage(
new MySqlStorage(
defaultConnection,
hangfireConnection,
new MySqlStorageOptions
{
TransactionIsolationLevel = IsolationLevel.ReadCommitted,
QueuePollInterval = TimeSpan.FromSeconds(15),
JobExpirationCheckInterval = TimeSpan.FromHours(1),
CountersAggregateInterval = TimeSpan.FromMinutes(5),
PrepareSchemaIfNecessary = true,
DashboardJobListLimit = 50000,
TransactionTimeout = TimeSpan.FromMinutes(1),
TablesPrefix = "Hangfire"
InvisibilityTimeout = TimeSpan.FromHours(3),
TablesPrefix = "Hangfire_Leave"
})));
builder.Services.AddHangfireServer();
builder.Services.AddHangfireServer(options =>
{
options.ServerName = "Leave-Server"; // ← ระบุชื่อ server
options.WorkerCount = 5; // ←
options.Queues = new[] { "leave","default" }; // ← worker จะรันเฉพาะ queue "leave"
});
var app = builder.Build();
@ -190,6 +195,13 @@ if (manager != null)
manager.AddOrUpdate("ปรับปรุงรอบการลงเวลาทำงาน", Job.FromExpression<UserDutyTimeRepository>(x => x.UpdateUserDutyTime()), "0 1 * * *", bangkokTimeZone);
// ทำความสะอาดข้อมูล CheckIn Job Status ที่เก่ากว่า 30 วัน - รันทุกวันเวลา 02:00 น.
manager.AddOrUpdate("ทำความสะอาดข้อมูล CheckIn Job Status", Job.FromExpression<CheckInJobStatusRepository>(x => x.CleanupOldJobsAsync(30)), "0 2 * * *", bangkokTimeZone);
manager.AddOrUpdate("ประมวลผลงานที่ค้างอยู่ในสถานะ Pending หรือ Processing", Job.FromExpression<LeaveProcessJobStatusRepository>(x => x.ProcessPendingJobsAsync()), "0 3 * * *",
new RecurringJobOptions
{
TimeZone = bangkokTimeZone,
QueueName = "leave" // ← กำหนด queue
});
}
// apply migrations

View file

@ -19,20 +19,19 @@
// "ExamConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
// "LeaveConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
"DefaultConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"ExamConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"LeaveConnection": "server=192.168.1.63;user=root;password=12345678;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
"DefaultConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;",
"ExamConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms_exam;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;",
"LeaveConnection": "Server=192.168.1.63;User ID=root;Password=12345678;Port=3306;Database=hrms_leave;Allow User Variables=True;Convert Zero Datetime=True;Pooling=True;"
// "DefaultConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
// "ExamConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
// "LeaveConnection": "server=172.27.17.68;user=user;password=cDldaqkwESWvuZ37Gr0n;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
// "DefaultConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;",
// "ExamConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;",
// "LeaveConnection": "server=172.27.17.68;user=root;password=ey2qVVyyqGYw8CyA7h8X72559r2Ad84K;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;Connection Timeout=180;"
},
"Jwt": {
//"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Key": "j7C9RO_p4nRtuwCH4z9Db_A_6We42tkD_p4lZtDrezc",
"Issuer": "https://hrmsbkk-id.case-collection.com/realms/hrms"
//"Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU",
//"Issuer": "https://hrms-id.bangkok.go.th/realms/hrms"
// "Key": "xY2VR-EFvvNPsMs39u8ooVBWQL6mPwrNJOh3koJFTgU",
// "Issuer": "https://hrms-id.bangkok.go.th/realms/hrms"
},
"EPPlus": {
"ExcelPackage": {
@ -55,6 +54,11 @@
"Password": "12345678",
"Queue": "hrms-checkin-queue-dev",
"URL": "http://192.168.1.63:9122/api/queues/%2F/"
// "Host": "172.27.17.68",
// "User": "admin",
// "Password": "admin123456",
// "Queue": "hrms-checkin-queue",
// "URL": "http://172.27.17.68:9122/api/queues/%2F/"
},
"Mail": {
"Server": "mail.bangkok.go.th",
@ -68,7 +72,10 @@
"API": "https://hrmsbkk.case-collection.com/api/v1",
"APIV2": "https://hrmsbkk.case-collection.com/api/v2",
"VITE_URL_MGT": "https://hrmsbkk-mgt.case-collection.com",
//"API": "https://bma-ehr.frappet.synology.me/api/v1",
//"API": "https://bma-hrms.bangkok.go.th/api/v1",
// "Domain": "https://hrms-exam.bangkok.go.th",
// "APIPROBATION": "https://hrms.bangkok.go.th/api/v1/probation",
// "API": "https://hrms.bangkok.go.th/api/v1",
// "APIV2": "https://hrms.bangkok.go.th/api/v2",
// "VITE_URL_MGT": "https://hrms-mgt.bangkok.go.th",
"API_KEY": "fKRL16yyEgbyTEJdsMw2h64tGSCmkW685PRtM3CygzX1JOSdptT9UJtpgWwKM8FybRTJups3GTFwj27ZRvlPdIkv3XgCoVJaD5LmR06ozuEPvCCRSdp2WFthg08V5xHc56fTPfZLpr1VmXrhd6dvYhHIqKkQUJR02Rlkss11cLRWEQOssEFVA4xdu2J5DIRO1EM5m7wRRvEwcDB4mYRXD9HH52SMq6iYqUWEWsMwLdbk7QW9yYESUEuzMW5gWrb6vIeWZxJV5bTz1PcWUyR7eO9Fyw1F5DiQYc9JgzTC1mW7cv31fEtTtrfbJYKIb5EbWilqIEUKC6A0UKBDDek35ML0006cqRVm0pvdOH6jeq7VQyYrhdXe59dBEyhYGUIfozoVBvW7Up4QBuOMjyPjSqJPlMBKwaseptfrblxQV1AOOivSBpf1ZcQyOZ8JktRtKUDSuXsmG0lsXwFlI3JCeSHdpVdgZWFYcJPegqfrB6KotR02t9AVkpLs1ZWrixwz"
}

View file

@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -239,11 +239,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementAppointments = placementAppointments
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
placementAppointments = placementAppointments.Where(x =>

View file

@ -110,7 +110,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -232,11 +232,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
placementAppointments = placementAppointments
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementAppointments = placementAppointments
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
placementAppointments = placementAppointments.Where(x =>

View file

@ -140,6 +140,7 @@ namespace BMA.EHR.Placement.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetExamByPlacement(Guid examId)
{
var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(examId.ToString(), "SYS_PLACEMENT_PASS");
var role = string.Empty;
if (getWorkflow == false)
{
var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS");
@ -148,6 +149,7 @@ namespace BMA.EHR.Placement.Service.Controllers
{
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
}
role = jsonData["result"]?.ToString();
}
var rootId = "";
@ -167,7 +169,7 @@ namespace BMA.EHR.Placement.Service.Controllers
if (_res.IsSuccessStatusCode)
{
var org = JsonConvert.DeserializeObject<OrgRequestAct>(_result);
if (org.result.isOfficer == false)
if (org.result.isOfficer == false && role?.Trim().ToUpper() != "OWNER")
{
rootId = org.result.rootId == null ? "" : org.result.rootId;
// child1Id = org.result.child1Id == null ? "" : org.result.child1Id;
@ -302,7 +304,7 @@ namespace BMA.EHR.Placement.Service.Controllers
}
return Success(result1);
}
if (org.result.isOfficer == true)
if (org.result.isOfficer == true || role?.Trim().ToUpper() == "OWNER")
{
var data = await _context.PlacementProfiles.Where(x => x.Placement.Id == examId).Select(x => new
{
@ -690,6 +692,13 @@ namespace BMA.EHR.Placement.Service.Controllers
public async Task<ActionResult<ResponseObject>> GetDashboardByPlacement(Guid examId)
{
var role = string.Empty;
var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_PLACEMENT_PASS");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() == "200")
{
role = jsonData["result"]?.ToString();
}
var rootId = "";
var child1Id = "";
@ -709,7 +718,7 @@ namespace BMA.EHR.Placement.Service.Controllers
if (_res.IsSuccessStatusCode)
{
var org = JsonConvert.DeserializeObject<OrgRequestAct>(_result);
if (org.result.isOfficer == false)
if (org.result.isOfficer == false && role?.Trim().ToUpper() != "OWNER")
{
rootId = org.result.rootId == null ? "" : org.result.rootId;
// child1Id = org.result.child1Id == null ? "" : org.result.child1Id;
@ -733,7 +742,7 @@ namespace BMA.EHR.Placement.Service.Controllers
return Success(placement);
}
if (org.result.isOfficer == true)
if (org.result.isOfficer == true || role?.Trim().ToUpper() == "OWNER")
{
var placement = await _context.Placements
.Where(x => x.Id == examId)
@ -894,6 +903,49 @@ namespace BMA.EHR.Placement.Service.Controllers
return Success();
}
/// <summary>
/// API สำหรับยกเลิกการส่งตัว
/// </summary>
/// <returns></returns>
/// <response code="200"></response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("update/draft-status")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> PersonUpdateDraftStatus([FromBody] PersonUpdateStatusRequest req)
{
var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_PLACEMENT_PASS");
var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
if (jsonData["status"]?.ToString() != "200")
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
string role = jsonData["result"]?.ToString();
if (role != "OWNER")
return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
var person = await _context.PlacementProfiles
.FirstOrDefaultAsync(x => x.Id == req.PersonalId);
if (person == null)
return Error(GlobalMessages.DataNotFound, 404);
if (person.PlacementStatus == "REPORT")
return Error("ไม่สามารถยกเลิกการส่งตัวได้ เนื่องจากส่งไปออกคำสั่งแล้ว");
if (person.PlacementStatus == "DONE")
return Error("ไม่สามารถยกเลิกการส่งตัวได้ เนื่องจากบรรจุไปแล้ว");
person.Draft = false;
person.LastUpdateFullName = FullName ?? "System Administrator";
person.LastUpdateUserId = UserId ?? "";
person.LastUpdatedAt = DateTime.Now;
await _context.SaveChangesAsync();
return Success();
}
[HttpGet("pass/deferment/{personalId:length(36)}")]
public async Task<ActionResult<ResponseObject>> GetPersonDeferment(Guid personalId)
{
@ -1791,7 +1843,7 @@ namespace BMA.EHR.Placement.Service.Controllers
isLeave = false,
dateRetire = (DateTime?)null,
dateAppoint = r.commandDateAffect,
dateStart = r.commandDateAffect,
dateStart = p.ReportingDate,
govAgeAbsent = 0,
govAgePlus = 0,
birthDate = (p.DateOfBirth == null || p.DateOfBirth == DateTime.MinValue) ? (DateTime?)null : p.DateOfBirth,
@ -1993,7 +2045,7 @@ namespace BMA.EHR.Placement.Service.Controllers
.Where(x => req.refIds.Contains(x.Id.ToString()))
// .Where(x => x.PlacementStatus.ToUpper() == "REPORT")
.ToListAsync();
placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAI");
placementProfiles.ForEach(profile => profile.PlacementStatus = "PREPARE-CONTAIN");
await _context.SaveChangesAsync();
return Success();
}

View file

@ -111,7 +111,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -193,11 +193,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementOfficers = placementOfficers
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
placementOfficers = placementOfficers
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementOfficers = placementOfficers
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
placementOfficers = placementOfficers.Where(x =>

View file

@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -231,11 +231,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementReceives = placementReceives
.Where(x => (x.rootDnaId == nodeId) || (x.CreatedUserId == UserId)).ToList();
}
else if (role == "PARENT")
{
placementReceives = placementReceives
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementReceives = placementReceives
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
placementReceives = placementReceives.Where(x =>

View file

@ -112,7 +112,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -198,11 +198,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementRepatriations = placementRepatriations
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
placementRepatriations = placementRepatriations
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementRepatriations = placementRepatriations
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
placementRepatriations = placementRepatriations.Where(x =>

View file

@ -205,7 +205,7 @@ namespace BMA.EHR.Placement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -285,11 +285,11 @@ namespace BMA.EHR.Placement.Service.Controllers
placementTransfers = placementTransfers
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
placementTransfers = placementTransfers
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// placementTransfers = placementTransfers
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
placementTransfers = placementTransfers.Where(x =>

View file

@ -40,10 +40,17 @@
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BMA.EHR.Infrastructure\BMA.EHR.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="Templates\**\*.docx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View file

@ -7,6 +7,7 @@ using BMA.EHR.Domain.Models.Retirement;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Infrastructure.Persistence;
using BMA.EHR.Retirement.Service.Requests;
using BMA.EHR.Retirement.Service.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@ -37,6 +38,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
private readonly PermissionRepository _permission;
private readonly DisciplineDbContext _contextDiscipline;
private readonly RetireReportRepository _service;
private readonly RetirementReportService _reportService;
public RetirementController(RetirementRepository repository,
NotificationRepository repositoryNoti,
ApplicationDBContext context,
@ -46,7 +48,8 @@ namespace BMA.EHR.Retirement.Service.Controllers
IHttpContextAccessor httpContextAccessor,
PermissionRepository permission,
DisciplineDbContext contextDiscipline,
RetireReportRepository service)
RetireReportRepository service,
RetirementReportService reportService)
{
_repository = repository;
_repositoryNoti = repositoryNoti;
@ -58,6 +61,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
_permission = permission;
_contextDiscipline = contextDiscipline;
_service = service;
_reportService = reportService;
}
#region " Properties "
@ -2213,5 +2217,83 @@ namespace BMA.EHR.Retirement.Service.Controllers
}
}
#endregion
#region &
/// <summary>
/// รายงานรายชื่อผู้เกษียณอายุราชการ ข้าราชการ & ลูกจ้างประจำ
/// </summary>
/// <param name="Id">Id ของรอบเกษียณ</param>
/// <param name="exportType">pdf, docx</param>
/// <returns></returns>
/// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("report/{exportType}/{Id}")]
public async Task<ActionResult<ResponseObject>> GetReportProfileRetirement([FromRoute] Guid Id, string exportType = "pdf")
{
var retire = await _service.GetProfileRetirementdAsync(Id, token);
if (retire != null)
{
var reportfile = string.Empty;
exportType = exportType.Trim();
switch (retire.GetType().GetProperty("Type").GetValue(retire))
{
case "OFFICER":
if (string.IsNullOrEmpty(retire.GetType().GetProperty("TypeReport").GetValue(retire)))
{
reportfile = $"retire-1";
}
else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "ADD" || retire.GetType().GetProperty("TypeReport").GetValue(retire) == "EDIT")
{
reportfile = $"retire-2";
}
else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "REMOVE")
{
reportfile = $"retire-3";
}
else
{
return Error(retire.GetType().GetProperty("TypeReport").GetValue(retire));
}
break;
case "EMPLOYEE":
if (string.IsNullOrEmpty(retire.GetType().GetProperty("TypeReport").GetValue(retire)))
{
reportfile = $"retire-emp-1";
}
else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "ADD" || retire.GetType().GetProperty("TypeReport").GetValue(retire) == "EDIT")
{
reportfile = $"retire-emp-2";
}
else if (retire.GetType().GetProperty("TypeReport").GetValue(retire) == "REMOVE")
{
reportfile = $"retire-emp-3";
}
else
{
return Error(retire.GetType().GetProperty("TypeReport").GetValue(retire));
}
break;
default:
return Error(retire.GetType().GetProperty("Type").GetValue(retire));
}
var reportBytes = await _reportService.GenerateReportAsync(reportfile, retire, exportType);
var fileName = $"reportRetirement-{DateTime.Now:yyyyMMdd-HHmmss}.{exportType}";
var contentType = exportType.Trim().ToLower() == "pdf"
? "application/pdf"
: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
return File(reportBytes, contentType, fileName);
}
else
{
return NotFound();
}
}
#endregion
}
}

View file

@ -116,7 +116,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -177,11 +177,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementDeceaseds = retirementDeceaseds
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementDeceaseds = retirementDeceaseds
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementDeceaseds = retirementDeceaseds
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementDeceaseds = retirementDeceaseds.Where(x =>

View file

@ -112,7 +112,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -227,11 +227,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementOthers = retirementOthers
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementOthers = retirementOthers
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementOthers = retirementOthers
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementOthers = retirementOthers.Where(x =>

View file

@ -127,7 +127,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -208,11 +208,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementOuts = retirementOuts
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementOuts = retirementOuts
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementOuts = retirementOuts
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementOuts = retirementOuts.Where(x =>

View file

@ -165,7 +165,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
p.ApproveReason,
p.RejectReason,
p.CancelReason,
p.Status,
status = p.RetirementResignCancels.FirstOrDefault() == null ? p.Status : p.RetirementResignCancels.FirstOrDefault().Status,
statusCancel = p.RetirementResignCancels.FirstOrDefault() == null ? null : p.RetirementResignCancels.FirstOrDefault().Status,
p.IsActive,
})
@ -271,7 +271,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -336,11 +336,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementResigns = retirementResigns
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementResigns = retirementResigns
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementResigns = retirementResigns
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementResigns = retirementResigns.Where(x =>
@ -403,7 +403,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -467,11 +467,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementResigns = retirementResigns
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementResigns = retirementResigns
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementResigns = retirementResigns
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementResigns = retirementResigns.Where(x =>
@ -2170,7 +2170,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2228,11 +2228,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
data = data
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
data = data
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// data = data
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>
@ -3104,13 +3104,13 @@ namespace BMA.EHR.Retirement.Service.Controllers
}).ToList();
var baseAPIOrg = _configuration["API"];
var reportDone = false;
if (data.Where(profile => profile.Status == "DONE").Any())
{
reportDone = true;
}
if (reportDone == true)
{
//var reportDone = false;
//if (data.Where(profile => profile.Status == "DONE").Any())
//{
// reportDone = true;
//}
//if (reportDone == true)
//{
var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-leave";
using (var client = new HttpClient())
{
@ -3128,27 +3128,27 @@ namespace BMA.EHR.Retirement.Service.Controllers
await _context.SaveChangesAsync();
}
}
}
else
{
var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _res = await client.PostAsJsonAsync(apiUrlOrg, new
{
resignId = resultData.Select(x => x.resignId).ToList(),
});
var _result = await _res.Content.ReadAsStringAsync();
if (_res.IsSuccessStatusCode)
{
data.ForEach(profile => profile.Status = "DONE");
data.ForEach(profile => profile.RetirementResign.Status = "CANCEL");
await _context.SaveChangesAsync();
}
}
}
//}
//else
//{
// var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign";
// using (var client = new HttpClient())
// {
// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
// client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
// var _res = await client.PostAsJsonAsync(apiUrlOrg, new
// {
// resignId = resultData.Select(x => x.resignId).ToList(),
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// data.ForEach(profile => profile.RetirementResign.Status = "CANCEL");
// await _context.SaveChangesAsync();
// }
// }
//}
return Success();
}

View file

@ -102,8 +102,8 @@ namespace BMA.EHR.Retirement.Service.Controllers
p.Remark,
p.ApproveReason,
p.RejectReason,
p.CancelReason,
p.Status,
p.CancelReason,
status = p.RetirementResignEmployeeCancels.FirstOrDefault() == null ? p.Status : p.RetirementResignEmployeeCancels.FirstOrDefault().Status,
statusCancel = p.RetirementResignEmployeeCancels.FirstOrDefault() == null ? null : p.RetirementResignEmployeeCancels.FirstOrDefault().Status,
p.IsActive,
})
@ -208,7 +208,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -273,11 +273,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementResignEmployees = retirementResignEmployees
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementResignEmployees = retirementResignEmployees
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementResignEmployees = retirementResignEmployees
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementResignEmployees = retirementResignEmployees.Where(x =>
@ -340,7 +340,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -403,11 +403,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
retirementResignEmployees = retirementResignEmployees
.Where(x => x.rootDnaOldId == nodeId).ToList();
}
else if (role == "PARENT")
{
retirementResignEmployees = retirementResignEmployees
.Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
}
// else if (role == "PARENT")
// {
// retirementResignEmployees = retirementResignEmployees
// .Where(x => x.rootDnaOldId == nodeId && x.child1DnaOldId != null).ToList();
// }
else if (role == "NORMAL")
{
retirementResignEmployees = retirementResignEmployees.Where(x =>
@ -2078,7 +2078,7 @@ namespace BMA.EHR.Retirement.Service.Controllers
? profileAdmin?.RootDnaId
: "";
}
else if (role == "ROOT" || role == "PARENT")
else if (role == "ROOT" /*|| role == "PARENT"*/)
{
nodeId = profileAdmin?.RootDnaId;
}
@ -2136,11 +2136,11 @@ namespace BMA.EHR.Retirement.Service.Controllers
data = data
.Where(x => x.rootDnaId == nodeId).ToList();
}
else if (role == "PARENT")
{
data = data
.Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
}
// else if (role == "PARENT")
// {
// data = data
// .Where(x => x.rootDnaId == nodeId && x.child1DnaId != null).ToList();
// }
else if (role == "NORMAL")
{
data = data.Where(x =>
@ -2598,14 +2598,14 @@ namespace BMA.EHR.Retirement.Service.Controllers
}).ToList();
var baseAPIOrg = _configuration["API"];
var reportDone = false;
if (data.Where(profile => profile.Status == "DONE").Any())
{
reportDone = true;
}
//var reportDone = false;
//if (data.Where(profile => profile.Status == "DONE").Any())
//{
// reportDone = true;
//}
if (reportDone == true)
{
//if (reportDone == true)
//{
var apiUrlOrg = $"{baseAPIOrg}/org/command/excexute/salary-employee-leave";
using (var client = new HttpClient())
{
@ -2623,27 +2623,27 @@ namespace BMA.EHR.Retirement.Service.Controllers
await _context.SaveChangesAsync();
}
}
}
else
{
var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
var _res = await client.PostAsJsonAsync(apiUrlOrg, new
{
resignId = resultData.Select(x => x.resignId).ToList(),
});
var _result = await _res.Content.ReadAsStringAsync();
if (_res.IsSuccessStatusCode)
{
data.ForEach(profile => profile.Status = "DONE");
data.ForEach(profile => profile.RetirementResignEmployee.Status = "CANCEL");
await _context.SaveChangesAsync();
}
}
}
//}
//else
//{
// var apiUrlOrg = $"{baseAPIOrg}/org/command/cancel-resign";
// using (var client = new HttpClient())
// {
// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
// client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]);
// var _res = await client.PostAsJsonAsync(apiUrlOrg, new
// {
// resignId = resultData.Select(x => x.resignId).ToList(),
// });
// var _result = await _res.Content.ReadAsStringAsync();
// if (_res.IsSuccessStatusCode)
// {
// data.ForEach(profile => profile.Status = "DONE");
// data.ForEach(profile => profile.RetirementResignEmployee.Status = "CANCEL");
// await _context.SaveChangesAsync();
// }
// }
//}
return Success();
}

View file

@ -3,6 +3,7 @@ using BMA.EHR.Domain.Middlewares;
using BMA.EHR.Infrastructure;
using BMA.EHR.Infrastructure.Persistence;
using BMA.EHR.Retirement.Service;
using BMA.EHR.Retirement.Service.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
@ -86,6 +87,7 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApplication();
builder.Services.AddLeaveApplication();
builder.Services.AddPersistence(builder.Configuration);
builder.Services.AddScoped<RetirementReportService>();
builder.Services.AddLeavePersistence(builder.Configuration);
builder.Services.AddHttpClient();

View file

@ -0,0 +1,638 @@
using BMA.EHR.Application.Responses;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
namespace BMA.EHR.Retirement.Service.Services
{
public class RetirementReportService
{
private readonly IWebHostEnvironment _environment;
private readonly ILogger<RetirementReportService> _logger;
private readonly IConfiguration _configuration;
/// <summary>
/// Initializes a new instance of the RetirementReportService class.
/// </summary>
public RetirementReportService(
IWebHostEnvironment environment,
ILogger<RetirementReportService> logger,
IConfiguration configuration)
{
_environment = environment;
_logger = logger;
_configuration = configuration;
}
#region Public Methods
/// <summary>
/// สร้างรายงานจาก Template (.docx)
/// </summary>
public async Task<byte[]> GenerateReportAsync(string templateName, dynamic data, string exportType)
{
try
{
var templatePath = GetTemplatePath(templateName);
var docxBytes = await ProcessTemplateAsync(templatePath, data);
return exportType.ToLower() == "pdf"
? await ConvertToPdfAsync(docxBytes)
: docxBytes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating report");
throw;
}
}
#endregion
#region Template Processing
private string GetTemplatePath(string templateName)
{
var path = Path.Combine(_environment.ContentRootPath, "Templates", $"{templateName}.docx");
if (!File.Exists(path))
throw new FileNotFoundException($"Template not found: {templateName}");
return path;
}
private async Task<byte[]> ProcessTemplateAsync(string templatePath, dynamic data)
{
using var templateStream = File.OpenRead(templatePath);
using var outputStream = new MemoryStream();
await templateStream.CopyToAsync(outputStream);
outputStream.Position = 0;
using (var wordDoc = WordprocessingDocument.Open(outputStream, true))
{
var mainPart = wordDoc.MainDocumentPart;
if (mainPart == null) return Array.Empty<byte>();
ReplacePlaceholders(mainPart, data);
wordDoc.Save();
}
return outputStream.ToArray();
}
private void ReplacePlaceholders(MainDocumentPart mainPart, dynamic data)
{
var document = mainPart.Document;
if (document == null) return;
var processor = CreateDataProcessor(data);
processor.Process(document, new Action<Document, System.Collections.IEnumerable>(FillTableRows));
}
#endregion
#region Data Processing Strategy
private IDataProcessor CreateDataProcessor(dynamic data)
{
var dataType = data.GetType();
var isDictionary = dataType.IsGenericType &&
dataType.GetGenericTypeDefinition() == typeof(Dictionary<,>);
return isDictionary
? new DictionaryDataProcessor(data)
: new ObjectDataProcessor(data);
}
#endregion
#region Table Processing
private void FillTableRows(Document document, System.Collections.IEnumerable profiles)
{
var table = document.Descendants<Table>().FirstOrDefault();
if (table == null) return;
var rows = table.Elements<TableRow>().ToList();
if (rows.Count == 0) return;
var strategy = CreateTableStrategy(rows);
strategy.Process(table, rows, profiles);
}
private static ITableStrategy CreateTableStrategy(List<TableRow> rows)
{
// retire-1 format: 1 row, 1 cell, 1 paragraph
if (IsSingleParagraphFormat(rows))
return new SingleParagraphTableStrategy();
// retire-3 format: 2+ rows (header + template)
return new MultiRowTableStrategy();
}
private static bool IsSingleParagraphFormat(List<TableRow> rows) =>
rows.Count == 1 &&
rows[0].Elements<TableCell>().Count() == 1 &&
rows[0].Elements<TableCell>().First().Elements<Paragraph>().Count() == 1;
#endregion
#region PDF Conversion
private async Task<byte[]> ConvertToPdfAsync(byte[] docxBytes)
{
var tempDocx = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.docx");
var tempPdf = Path.ChangeExtension(tempDocx, ".pdf");
try
{
await File.WriteAllBytesAsync(tempDocx, docxBytes);
await ConvertToPdfInternalAsync(tempDocx, tempPdf);
return await File.ReadAllBytesAsync(tempPdf);
}
finally
{
if (File.Exists(tempDocx)) File.Delete(tempDocx);
if (File.Exists(tempPdf)) File.Delete(tempPdf);
}
}
private async Task ConvertToPdfInternalAsync(string docxPath, string pdfPath)
{
try
{
var useDocker = _configuration.GetValue<bool>("LibreOffice:UseDocker", false);
var timeout = _configuration.GetValue<int>("LibreOffice:Timeout", 180000);
if (useDocker)
{
await ConvertToPdfViaDockerAsync(docxPath, pdfPath, timeout);
}
else
{
// // PROD: Disabled local LibreOffice conversion
// await ConvertToPdfLocallyAsync(docxPath, pdfPath, timeout);
throw new NotSupportedException("LibreOffice conversion is disabled.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error converting to PDF");
throw;
}
}
private async Task ConvertToPdfViaDockerAsync(string docxPath, string pdfPath, int timeout)
{
var inputDir = _configuration["LibreOffice:InputDirectory"] ?? "/app/libreoffice/input";
var outputDir = _configuration["LibreOffice:OutputDirectory"] ?? "/app/libreoffice/output";
var fileName = Path.GetFileName(docxPath);
var pdfName = Path.ChangeExtension(fileName, ".pdf");
// Ensure directories exist
Directory.CreateDirectory(inputDir);
Directory.CreateDirectory(outputDir);
// Copy file to input folder (LibreOffice watcher will pick it up)
var inputPath = Path.Combine(inputDir, fileName).Replace('\\', '/');
var outputPath = Path.Combine(outputDir, pdfName).Replace('\\', '/');
_logger.LogInformation("📤 Sending file to LibreOffice: {FileName}", fileName);
await File.WriteAllBytesAsync(inputPath, await File.ReadAllBytesAsync(docxPath));
// Wait for LibreOffice to convert (file watcher handles it)
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var pollInterval = TimeSpan.FromMilliseconds(500);
while (stopwatch.ElapsedMilliseconds < timeout)
{
if (File.Exists(outputPath))
{
_logger.LogInformation("✅ PDF received: {PdfName} (took {ElapsedMs}ms)", pdfName, stopwatch.ElapsedMilliseconds);
await File.WriteAllBytesAsync(pdfPath, await File.ReadAllBytesAsync(outputPath));
// Cleanup
try
{
if (File.Exists(outputPath)) File.Delete(outputPath);
_logger.LogDebug("🗑️ Cleaned up output file: {PdfName}", pdfName);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to cleanup output file");
}
return;
}
await Task.Delay(pollInterval);
}
throw new TimeoutException($"LibreOffice conversion timed out after {timeout}ms. File not found: {outputPath}");
}
// // PROD: Disabled local LibreOffice conversion
// private async Task ConvertToPdfLocallyAsync(string docxPath, string pdfPath, int timeout)
// {
// var libreOfficePath = _configuration["LibreOffice:Path"] ?? GetDefaultLibreOfficePath();
// var arguments = _configuration["LibreOffice:Arguments"] ?? "--headless --convert-to pdf --nologo --norestore";
// var outputDir = Path.GetDirectoryName(pdfPath);
// if (string.IsNullOrEmpty(outputDir))
// {
// throw new DirectoryNotFoundException("Output directory cannot be determined");
// }
// var psi = new ProcessStartInfo
// {
// FileName = libreOfficePath,
// Arguments = $"{arguments} --outdir \"{outputDir}\" \"{docxPath}\"",
// UseShellExecute = false,
// RedirectStandardOutput = true,
// RedirectStandardError = true,
// CreateNoWindow = true
// };
// using var process = Process.Start(psi);
// var exited = process.WaitForExit(timeout);
// if (!exited)
// {
// process.Kill(entireProcessTree: true);
// throw new TimeoutException($"LibreOffice conversion timed out after {timeout}ms");
// }
// if (process.ExitCode != 0)
// {
// var error = await process.StandardError.ReadToEndAsync();
// throw new Exception($"LibreOffice conversion failed: {error}");
// }
// }
// // PROD: Disabled local LibreOffice path detection
// private static string GetDefaultLibreOfficePath()
// {
// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
// {
// var possiblePaths = new[]
// {
// @"C:\Program Files\LibreOffice\program\soffice.exe",
// @"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
// @"C:\Program Files\LibreOffice\program\soffice.com"
// };
// return possiblePaths.FirstOrDefault(File.Exists)
// ?? throw new FileNotFoundException("LibreOffice not found. Please install LibreOffice or configure the path in appsettings.json");
// }
// // Linux/Docker: use default path
// return "libreoffice";
// }
#endregion
}
#region Data Processor Interfaces & Implementations
internal interface IDataProcessor
{
void Process(Document document, Action<Document, System.Collections.IEnumerable> tableFiller);
}
internal class DictionaryDataProcessor : IDataProcessor
{
private readonly dynamic _data;
public DictionaryDataProcessor(dynamic data)
{
_data = data;
}
public void Process(Document document, Action<Document, System.Collections.IEnumerable> tableFiller)
{
var keys = _data.Keys as System.Collections.ICollection;
if (keys == null) return;
System.Collections.IEnumerable? profiles = null;
foreach (string key in keys)
{
if (key.Equals("profiles", StringComparison.OrdinalIgnoreCase))
{
profiles = _data[key] as System.Collections.IEnumerable;
continue;
}
var valueObj = _data[key];
if (valueObj != null && typeof(System.Collections.IEnumerable).IsAssignableFrom(valueObj.GetType()) &&
valueObj.GetType() != typeof(string))
{
continue;
}
var value = valueObj?.ToString() ?? string.Empty;
var placeholder = $"{{{{{key}}}}}";
TextReplacer.ReplaceAll(document, placeholder, value);
}
if (profiles != null)
{
tableFiller(document, profiles);
}
}
}
internal class ObjectDataProcessor : IDataProcessor
{
private readonly dynamic _data;
public ObjectDataProcessor(dynamic data)
{
_data = data;
}
public void Process(Document document, Action<Document, System.Collections.IEnumerable> tableFiller)
{
var dataType = _data.GetType();
var allProps = dataType.GetProperties();
var validProps = new List<PropertyInfo>();
foreach (var p in allProps)
{
if (p.GetIndexParameters().Length == 0)
{
validProps.Add(p);
}
}
System.Collections.IEnumerable? profiles = null;
foreach (var prop in validProps)
{
var propType = prop.PropertyType;
bool isEnumerable = typeof(System.Collections.IEnumerable).IsAssignableFrom(propType);
bool isString = propType == typeof(string);
if (isEnumerable && !isString)
{
if (prop.Name.Equals("profiles", StringComparison.OrdinalIgnoreCase))
{
profiles = prop.GetValue(_data) as System.Collections.IEnumerable;
}
continue;
}
var value = prop.GetValue(_data)?.ToString() ?? string.Empty;
var placeholder = $"{{{{{prop.Name}}}}}";
TextReplacer.ReplaceAll(document, placeholder, value);
}
if (profiles != null)
{
tableFiller(document, profiles);
}
}
}
#endregion
#region Text Replacer
internal static class TextReplacer
{
public static void ReplaceAll(Document document, string oldValue, string newValue)
{
bool found = false;
// Method 1: Check within single Run
foreach (var run in document.Descendants<Run>())
{
var textElements = run.Elements<Text>().ToList();
if (textElements.Count == 0) continue;
var combinedText = string.Concat(textElements.Select(t => t.Text));
if (combinedText.Contains(oldValue))
{
found = true;
var replacedText = combinedText.Replace(oldValue, newValue);
textElements[0].Text = replacedText;
for (int i = 1; i < textElements.Count; i++)
{
textElements[i].Text = string.Empty;
}
}
}
// Method 2: Check across all Runs in Paragraph
foreach (var para in document.Descendants<Paragraph>())
{
var allRuns = para.Elements<Run>().ToList();
if (allRuns.Count == 0) continue;
var combinedParaText = string.Concat(allRuns.SelectMany(r => r.Elements<Text>().Select(t => t.Text)));
if (combinedParaText.Contains(oldValue))
{
found = true;
var replacedText = combinedParaText.Replace(oldValue, newValue);
var firstRunTexts = allRuns[0].Elements<Text>().ToList();
if (firstRunTexts.Count > 0)
{
firstRunTexts[0].Text = replacedText;
for (int i = 1; i < firstRunTexts.Count; i++)
{
firstRunTexts[i].Text = string.Empty;
}
}
for (int i = 1; i < allRuns.Count; i++)
{
foreach (var t in allRuns[i].Elements<Text>())
{
t.Text = string.Empty;
}
}
}
}
// Fallback: Check individual Text elements
if (!found)
{
foreach (var text in document.Descendants<Text>())
{
if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue))
{
found = true;
text.Text = text.Text.Replace(oldValue, newValue);
}
}
}
}
public static void ReplaceInRow(TableRow row, string oldValue, string newValue)
{
bool found = false;
foreach (var cell in row.Descendants<TableCell>())
{
foreach (var para in cell.Elements<Paragraph>())
{
found = ReplaceInParagraph(para, oldValue, newValue) || found;
}
}
// Fallback: Check individual Text elements
if (!found)
{
foreach (var text in row.Descendants<Text>())
{
if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue))
{
found = true;
text.Text = text.Text.Replace(oldValue, newValue);
}
}
}
}
public static bool ReplaceInParagraph(Paragraph paragraph, string oldValue, string newValue)
{
bool found = false;
var allTexts = paragraph.Descendants<Text>().ToList();
if (allTexts.Count == 0) return false;
var combinedParaText = string.Concat(allTexts.Select(t => t.Text));
if (combinedParaText.Contains(oldValue))
{
found = true;
var replacedText = combinedParaText.Replace(oldValue, newValue);
allTexts[0].Text = replacedText;
for (int i = 1; i < allTexts.Count; i++)
{
allTexts[i].Text = string.Empty;
}
}
// Fallback: Check individual Text elements
if (!found)
{
foreach (var text in allTexts)
{
if (!string.IsNullOrEmpty(text.Text) && text.Text.Contains(oldValue))
{
found = true;
text.Text = text.Text.Replace(oldValue, newValue);
}
}
}
return found;
}
}
#endregion
#region Table Strategy Interfaces & Implementations
internal interface ITableStrategy
{
void Process(Table table, List<TableRow> rows, System.Collections.IEnumerable profiles);
}
internal class SingleParagraphTableStrategy : ITableStrategy
{
public void Process(Table table, List<TableRow> rows, System.Collections.IEnumerable profiles)
{
var cell = rows[0].Elements<TableCell>().First();
var templatePara = cell.Elements<Paragraph>().First();
var profileList = profiles.Cast<object>().ToList();
foreach (var profile in profileList)
{
var props = profile.GetType()
.GetProperties()
.Where(p => p.GetIndexParameters().Length == 0)
.ToList();
var newPara = (Paragraph)templatePara.CloneNode(true);
foreach (var prop in props)
{
var value = prop.GetValue(profile)?.ToString() ?? string.Empty;
var placeholder = $"{{{{{prop.Name}}}}}";
TextReplacer.ReplaceInParagraph(newPara, placeholder, value);
}
cell.Append(newPara);
}
templatePara.Remove();
}
}
internal class MultiRowTableStrategy : ITableStrategy
{
public void Process(Table table, List<TableRow> rows, System.Collections.IEnumerable profiles)
{
var templateRowIndex = rows.Count >= 2 ? 1 : 0;
var templateRow = rows[templateRowIndex];
templateRow.Remove();
var profileList = profiles.Cast<object>().ToList();
// Process header row if exists
if (rows.Count >= 2)
{
ProcessHeaderRow(rows[0], profileList);
}
// Process template rows
foreach (var profile in profileList)
{
var newRow = (TableRow)templateRow.CloneNode(true);
var props = profile.GetType()
.GetProperties()
.Where(p => p.GetIndexParameters().Length == 0)
.ToList();
foreach (var prop in props)
{
var value = prop.GetValue(profile)?.ToString() ?? string.Empty;
var placeholder = $"{{{{{prop.Name}}}}}";
TextReplacer.ReplaceInRow(newRow, placeholder, value);
}
table.AppendChild(newRow);
}
}
private static void ProcessHeaderRow(TableRow headerRow, List<object> profileList)
{
var firstProfile = profileList.FirstOrDefault();
if (firstProfile == null) return;
var props = firstProfile.GetType()
.GetProperties()
.Where(p => p.GetIndexParameters().Length == 0)
.ToList();
foreach (var prop in props)
{
var value = prop.GetValue(firstProfile)?.ToString() ?? string.Empty;
var placeholder = $"{{{{{prop.Name}}}}}";
if (!string.IsNullOrWhiteSpace(value))
{
TextReplacer.ReplaceInRow(headerRow, placeholder, value);
}
}
}
}
#endregion
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.