using BMA.EHR.Application.Repositories; using BMA.EHR.Application.Repositories.MessageQueue; using BMA.EHR.Application.Responses.Profiles; using BMA.EHR.Discipline.Service.Requests; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Extensions; using BMA.EHR.Domain.Models.Discipline; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; // using BMA.EHR.Placement.Service.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Swashbuckle.AspNetCore.Annotations; using System.Net.Http.Headers; using System.Security.Claims; namespace BMA.EHR.DisciplineComplaint_Appeal.Service.Controllers { [Route("api/v{version:apiVersion}/discipline/complaint_appeal")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบย่อย อุทธรณ์/ร้องทุกข์")] public class DisciplineComplaint_AppealController : BaseController { private readonly DisciplineDbContext _context; private readonly ApplicationDBContext _contextMain; private readonly MinIODisciplineService _documentService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly NotificationRepository _repositoryNoti; private readonly IConfiguration _configuration; private readonly UserProfileRepository _userProfileRepository; private readonly PermissionRepository _permission; public DisciplineComplaint_AppealController(DisciplineDbContext context, NotificationRepository repositoryNoti, ApplicationDBContext contextMain, MinIODisciplineService documentService, IHttpContextAccessor httpContextAccessor, IConfiguration configuration, UserProfileRepository userProfileRepository, PermissionRepository permission) { // _repository = repository; _context = context; _contextMain = contextMain; _repositoryNoti = repositoryNoti; _documentService = documentService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; _userProfileRepository = userProfileRepository; _permission = permission; } #region " Properties " private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value; private string? token => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; private string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; private static string StatusDisciplineComplaintAppeal(string value) { switch (value) { case "NEW": return "ใหม่"; case "RECEIVE_DOC": return "ได้รับเอกสารแล้ว"; case "RECEIVE_APPEAL": return "รับอุทธรณ์/ร้องทุกข์"; case "NO_RECEIVE_APPEAL": return "ไม่รับอุทธรณ์/ร้องทุกข์"; case "DIAGNOSTIC": return "ตั้งองค์คณะวินิจฉัย"; case "SUMMARY": return "สรุปผลการพิจารณา"; case "DONE": return "ปิดคำร้อง"; default: return ""; } } #endregion /// /// List รายการยื่นอุทธรณ์/ร้องทุกข์ (USER) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("user")] public async Task> GetDisciplineUser(string status = "ALL", string type = "ALL", int year = 0, int page = 1, int pageSize = 25, string keyword = "", string? sortBy = null, bool descending = false) { var id = ""; //var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return Success(new { data = new List(), total = 0 }); id = org.result.profileId; if (id == "") return Success(new { data = new List(), total = 0 }); var data_search = (from x in _context.DisciplineComplaint_Appeals where x.Title.Contains(keyword) || //x.Description.Contains(keyword) || x.CaseType.Contains(keyword) || x.CaseNumber.Contains(keyword) || x.Fullname.Contains(keyword) || x.CitizenId.Contains(keyword) where x.ProfileId == id select x).ToList(); if (status.Trim().ToUpper() != "ALL") data_search = data_search.Where(x => x.Status == status).ToList(); if (type.Trim().ToUpper() != "ALL") data_search = data_search.Where(x => x.Type == type).ToList(); if (year != 0) data_search = data_search.Where(x => x.Year == year).ToList(); var query = data_search .Select(x => new { Id = x.Id, Title = x.Title, Description = x.Description, Status = x.Status, Type = x.Type, Year = x.Year, CaseType = x.CaseType, CaseNumber = x.CaseNumber, Fullname = x.Fullname, CitizenId = x.CitizenId, ProfileId = x.ProfileId, LastUpdatedAt = x.LastUpdatedAt, CreatedAt = x.CreatedAt }); if (!string.IsNullOrEmpty(sortBy)) { { if (sortBy == "title") query = descending ? query.OrderByDescending(x => x.Title) : query.OrderBy(x => x.Title); else if (sortBy == "year") query = descending ? query.OrderByDescending(x => x.Year) : query.OrderBy(x => x.Year); else if (sortBy == "status") query = descending ? query.OrderByDescending(x => x.Status) : query.OrderBy(x => x.Status); else if (sortBy == "description") query = descending ? query.OrderByDescending(x => x.Description) : query.OrderBy(x => x.Description); else if (sortBy == "type") query = descending ? query.OrderByDescending(x => x.Type) : query.OrderBy(x => x.Type); else if (sortBy == "caseType") query = descending ? query.OrderByDescending(x => x.CaseType) : query.OrderBy(x => x.CaseType); else if (sortBy == "caseNumber") query = descending ? query.OrderByDescending(x => x.CaseNumber) : query.OrderBy(x => x.CaseNumber); else if (sortBy == "fullname") query = descending ? query.OrderByDescending(x => x.Fullname) : query.OrderBy(x => x.Fullname); else if (sortBy == "citizenId") query = descending ? query.OrderByDescending(x => x.CitizenId) : query.OrderBy(x => x.CitizenId); else if (sortBy == "lastUpdatedAt") query = descending ? query.OrderByDescending(x => x.LastUpdatedAt) : query.OrderBy(x => x.LastUpdatedAt); else if (sortBy == "createdAt") query = descending ? query.OrderByDescending(x => x.CreatedAt) : query.OrderBy(x => x.CreatedAt); else query = query.OrderByDescending(x => x.CreatedAt); // default } } else { query = query.OrderByDescending(x => x.CreatedAt); } var data = query .Skip((page - 1) * pageSize) .Take(pageSize) .ToList(); return Success(new { data, total = data_search.Count() }); } } /// /// รายละเอียดยื่นอุทธรณ์/ร้องทุกข์ (USER) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("{id:guid}")] public async Task> GetByDiscipline(Guid id) { var _data = await _context.DisciplineComplaint_Appeals .Include(x => x.DisciplineComplaint_Appeal_Docs) .Include(x => x.DisciplineComplaint_Appeal_Historys) .Select(x => new { Id = x.Id, Title = x.Title, Description = x.Description, Status = x.Status, Type = x.Type, Year = x.Year, CaseType = x.CaseType, CaseNumber = x.CaseNumber, Fullname = x.Fullname, CitizenId = x.CitizenId, ProfileId = x.ProfileId, Oc = x.Oc, Position = x.Position, LastUpdatedAt = x.LastUpdatedAt, HistoryStatus = x.DisciplineComplaint_Appeal_Historys.Select(p => new { Status = p.Status, CreatedAt = p.CreatedAt, CreatedFullName = p.CreatedFullName, }), DisciplineComplaint_Appeal_Docs = x.DisciplineComplaint_Appeal_Docs.Where(d => d.Document != null).Select(d => new { d.Document.Id, d.Document.FileName }), }) .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (_data == null) return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound); var disciplineComplaint_Appeal_Docs = new List(); foreach (var doc in _data.DisciplineComplaint_Appeal_Docs) { var _doc = new { doc.Id, doc.FileName, PathName = await _documentService.ImagesPath(doc.Id) }; disciplineComplaint_Appeal_Docs.Add(_doc); } var data = new { _data.Id, _data.Title, _data.Description, _data.Status, _data.Type, _data.Year, _data.CaseType, _data.CaseNumber, _data.Fullname, _data.CitizenId, _data.ProfileId, _data.Oc, _data.Position, _data.LastUpdatedAt, _data.HistoryStatus, disciplineComplaint_Appeal_Docs, }; return Success(data); } /// /// รายละเอียดยื่นอุทธรณ์/ร้องทุกข์ (ADMIN) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("admin/{id:guid}")] public async Task> GetByDisciplineByAdmin(Guid id) { var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_DISCIPLINE_APPEAL"); if (getWorkflow == false) { var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_DISCIPLINE_APPEAL"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } } var _data = await _context.DisciplineComplaint_Appeals .Include(x => x.DisciplineComplaint_Appeal_Docs) .Include(x => x.DisciplineComplaint_Appeal_Historys) .Select(x => new { Id = x.Id, Title = x.Title, Description = x.Description, Status = x.Status, Type = x.Type, Year = x.Year, CaseType = x.CaseType, CaseNumber = x.CaseNumber, Fullname = x.Fullname, CitizenId = x.CitizenId, ProfileId = x.ProfileId, Oc = x.Oc, Position = x.Position, LastUpdatedAt = x.LastUpdatedAt, profileType = x.profileType, HistoryStatus = x.DisciplineComplaint_Appeal_Historys.Select(p => new { Status = p.Status, CreatedAt = p.CreatedAt, CreatedFullName = p.CreatedFullName, }), DisciplineComplaint_Appeal_Docs = x.DisciplineComplaint_Appeal_Docs.Where(d => d.Document != null).Select(d => new { d.Document.Id, d.Document.FileName }), }) .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (_data == null) return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound); var disciplineComplaint_Appeal_Docs = new List(); foreach (var doc in _data.DisciplineComplaint_Appeal_Docs) { var _doc = new { doc.Id, doc.FileName, PathName = await _documentService.ImagesPath(doc.Id) }; disciplineComplaint_Appeal_Docs.Add(_doc); } var data = new { _data.Id, _data.Title, _data.Description, _data.Status, _data.Type, _data.Year, _data.CaseType, _data.CaseNumber, _data.Fullname, _data.CitizenId, _data.ProfileId, _data.Oc, _data.Position, _data.LastUpdatedAt, _data.profileType, _data.HistoryStatus, disciplineComplaint_Appeal_Docs, }; return Success(data); } /// /// สร้างรายการยื่นอุทธรณ์/ร้องทุกข์ (USER) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost()] public async Task> CreateDiscipline([FromForm] DisciplineComplaint_AppealRequest req) { //var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId"; var id = ""; var type = ""; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return Success(new { data = new List(), total = 0 }); id = org.result.profileId; if (id == "") return Success(new { data = new List(), total = 0 }); type = org.result.profileType; } var disciplineComplaint_Appeal = new Domain.Models.Discipline.DisciplineComplaint_Appeal { Title = req.Title, Description = req.Description, Status = "NEW", Type = req.Type.Trim().ToUpper(), Year = req.Year == null ? DateTime.Now.CalculateFisicalYear() : req.Year, CaseType = req.CaseType, CaseNumber = req.CaseNumber, Fullname = req.Fullname, CitizenId = req.CitizenId, ProfileId = id, Position = req.Position, Oc = req.Oc, profileType = type, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _apiUrl = $"{_configuration["API"]}/org/profile/profileid/position/{id}"; var _req = new HttpRequestMessage(HttpMethod.Get, _apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return Error("ไม่พบหน่วยงานของผู้ใช้งานคนนี้", 404); disciplineComplaint_Appeal.root = org.result.root; disciplineComplaint_Appeal.rootId = org.result.rootId; disciplineComplaint_Appeal.rootDnaId = org.result.rootDnaId; disciplineComplaint_Appeal.child1 = org.result.child1; disciplineComplaint_Appeal.child1Id = org.result.child1Id; disciplineComplaint_Appeal.child1DnaId = org.result.child1DnaId; disciplineComplaint_Appeal.child2 = org.result.child2; disciplineComplaint_Appeal.child2Id = org.result.child2Id; disciplineComplaint_Appeal.child2DnaId = org.result.child2DnaId; disciplineComplaint_Appeal.child3 = org.result.child3; disciplineComplaint_Appeal.child3Id = org.result.child3Id; disciplineComplaint_Appeal.child3DnaId = org.result.child3DnaId; disciplineComplaint_Appeal.child4 = org.result.child4; disciplineComplaint_Appeal.child4Id = org.result.child4Id; disciplineComplaint_Appeal.child4DnaId = org.result.child4DnaId; } var disciplineComplaint_Appeal_History = new DisciplineComplaint_Appeal_History { DisciplineComplaint_Appeal = disciplineComplaint_Appeal, Status = "NEW", CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; // await _context.DisciplineComplaint_Appeals.AddAsync(disciplineComplaint_Appeal); await _context.DisciplineComplaint_Appeal_Historys.AddAsync(disciplineComplaint_Appeal_History); await _context.SaveChangesAsync(); if (Request.Form.Files != null && Request.Form.Files.Count != 0) { foreach (var file in Request.Form.Files) { var fileExtension = Path.GetExtension(file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) { var disciplineComplaint_Appeal_Doc = new DisciplineComplaint_Appeal_Doc { DisciplineComplaint_Appeal = disciplineComplaint_Appeal, Document = _doc, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.DisciplineComplaint_Appeal_Docs.AddAsync(disciplineComplaint_Appeal_Doc); } } } var baseAPIOrg = _configuration["API"]; var system = "SYS_DISCIPLINE_APPEAL"; var apiUrlOrg = $"{baseAPIOrg}/org/workflow/find/director/{system}"; var refId = new List(); 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 { refId = new List { Guid.Parse(id) }, }); var __result = await __res.Content.ReadAsStringAsync(); var __org = JsonConvert.DeserializeObject(__result); if (__res.IsSuccessStatusCode) { refId = __org.result.Select(x => Guid.Parse(x.id)).ToList(); } await _repositoryNoti.PushNotificationsAsync( refId.ToArray(), $"มีคำขอยื่นอุทธรณ์/ร้องทุกข์จาก {req.Fullname}", $"มีคำขอยื่นอุทธรณ์/ร้องทุกข์จาก {req.Fullname}", "", "", true, true ); } await _context.SaveChangesAsync(); return Success(disciplineComplaint_Appeal.Id); } /// /// สร้างรายการยื่นอุทธรณ์/ร้องทุกข์ (ADMIN) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPost("admin")] public async Task> CreateDisciplineAdmin([FromForm] DisciplineComplaint_AppealRequest req) { var disciplineComplaint_Appeal = new Domain.Models.Discipline.DisciplineComplaint_Appeal { Title = req.Title, Description = req.Description, Status = "NEW", Type = req.Type.Trim().ToUpper(), Year = req.Year == null ? DateTime.Now.Year : req.Year, CaseType = req.CaseType, CaseNumber = req.CaseNumber, Fullname = req.Fullname, CitizenId = req.CitizenId, ProfileId = req.ProfileId, Position = req.Position, Oc = req.Oc, profileType = req.profileType, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var apiUrl = $"{_configuration["API"]}/org/profile/profileid/position/{req.ProfileId}"; var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return Error("ไม่พบหน่วยงานของผู้ใช้งานคนนี้", 404); disciplineComplaint_Appeal.root = org.result.root; disciplineComplaint_Appeal.rootId = org.result.rootId; disciplineComplaint_Appeal.rootDnaId = org.result.rootDnaId; disciplineComplaint_Appeal.child1 = org.result.child1; disciplineComplaint_Appeal.child1Id = org.result.child1Id; disciplineComplaint_Appeal.child1DnaId = org.result.child1DnaId; disciplineComplaint_Appeal.child2 = org.result.child2; disciplineComplaint_Appeal.child2Id = org.result.child2Id; disciplineComplaint_Appeal.child2DnaId = org.result.child2DnaId; disciplineComplaint_Appeal.child3 = org.result.child3; disciplineComplaint_Appeal.child3Id = org.result.child3Id; disciplineComplaint_Appeal.child3DnaId = org.result.child3DnaId; disciplineComplaint_Appeal.child4 = org.result.child4; disciplineComplaint_Appeal.child4Id = org.result.child4Id; disciplineComplaint_Appeal.child4DnaId = org.result.child4DnaId; } var disciplineComplaint_Appeal_History = new DisciplineComplaint_Appeal_History { DisciplineComplaint_Appeal = disciplineComplaint_Appeal, Status = "NEW", CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; // await _context.DisciplineComplaint_Appeals.AddAsync(disciplineComplaint_Appeal); await _context.DisciplineComplaint_Appeal_Historys.AddAsync(disciplineComplaint_Appeal_History); await _context.SaveChangesAsync(); if (Request.Form.Files != null && Request.Form.Files.Count != 0) { foreach (var file in Request.Form.Files) { var fileExtension = Path.GetExtension(file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) { var disciplineComplaint_Appeal_Doc = new DisciplineComplaint_Appeal_Doc { DisciplineComplaint_Appeal = disciplineComplaint_Appeal, Document = _doc, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.DisciplineComplaint_Appeal_Docs.AddAsync(disciplineComplaint_Appeal_Doc); } } } var baseAPIOrg = _configuration["API"]; var system = "SYS_DISCIPLINE_APPEAL"; var apiUrlOrg = $"{baseAPIOrg}/org/workflow/find/director/{system}"; var refId = new List(); 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 { refId = new List { Guid.Parse(req.ProfileId) }, }); var __result = await __res.Content.ReadAsStringAsync(); var __org = JsonConvert.DeserializeObject(__result); if (__res.IsSuccessStatusCode) { refId = __org.result.Select(x => Guid.Parse(x.id)).ToList(); } await _repositoryNoti.PushNotificationsAsync( refId.ToArray(), $"มีคำขอยื่นอุทธรณ์/ร้องทุกข์จาก {req.Fullname}", $"มีคำขอยื่นอุทธรณ์/ร้องทุกข์จาก {req.Fullname}", "", "", true, true ); } await _context.SaveChangesAsync(); return Success(disciplineComplaint_Appeal.Id); } /// /// อัพไฟล์เอกสารอุทธรณ์/ร้องทุกข์ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("file/{id:guid}")] public async Task> UploadFileComplaintAppeals([FromForm] DisciplineFileRequest req, Guid id) { var data = await _context.DisciplineComplaint_Appeals .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (data == null) return Error(new Exception(GlobalMessages.DataNotFound), (int)StatusCodes.Status404NotFound); if (Request.Form.Files != null && Request.Form.Files.Count != 0) { foreach (var file in Request.Form.Files) { var fileExtension = Path.GetExtension(file.FileName); var doc = await _documentService.UploadFileAsync(file, file.FileName); var _doc = await _context.Documents.AsQueryable() .FirstOrDefaultAsync(x => x.Id == doc.Id); if (_doc != null) { var disciplineComplaint_Appeal_Doc = new DisciplineComplaint_Appeal_Doc { DisciplineComplaint_Appeal = data, Document = _doc, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.DisciplineComplaint_Appeal_Docs.AddAsync(disciplineComplaint_Appeal_Doc); } } } data.LastUpdateFullName = FullName ?? "System Administrator"; data.LastUpdateUserId = UserId ?? ""; data.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// ลบไฟล์เอกสารอุทธรณ์/ร้องทุกข์ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpDelete("file/{id:guid}/{docId:guid}")] public async Task> DeleteFileComplaintAppeals(Guid id, Guid docId) { var getPermission = await _permission.GetPermissionAPIAsync("DELETE", "SYS_DISCIPLINE_APPEAL"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var data = await _context.DisciplineComplaint_Appeals .Include(x => x.DisciplineComplaint_Appeal_Docs) .ThenInclude(x => x.Document) .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (data == null) return Error(new Exception(GlobalMessages.DataNotFound), (int)StatusCodes.Status404NotFound); var dataDoc = data.DisciplineComplaint_Appeal_Docs.Where(x => x.Document.Id == docId).FirstOrDefault(); if (dataDoc != null) { _context.DisciplineComplaint_Appeal_Docs.Remove(dataDoc); await _context.SaveChangesAsync(); var dataDocComplaint = data.DisciplineComplaint_Appeal_Docs.Where(x => x.Document.Id == docId).FirstOrDefault(); if (dataDocComplaint == null) { await _documentService.DeleteFileAsync(docId); data.LastUpdateFullName = FullName ?? "System Administrator"; data.LastUpdateUserId = UserId ?? ""; data.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); } return Success(); } else { return Error(new Exception("ไม่พบไฟล์นี้ในระบบ"), (int)StatusCodes.Status404NotFound); } } /// /// List รายการยื่นอุทธรณ์/ร้องทุกข์ (ADMIN) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("admin")] public async Task> GetDisciplineAdmin(string status = "ALL", string type = "ALL", int year = 0, int page = 1, int pageSize = 25, string keyword = "", string? sortBy = "", bool? descending = false) { var getPermission = await _permission.GetPermissionAPIAsync("LIST", "SYS_DISCIPLINE_APPEAL"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } string role = jsonData["result"]?.ToString(); var nodeId = string.Empty; var profileAdmin = new GetUserOCAllDto(); profileAdmin = await _userProfileRepository.GetUserOCAll(Guid.Parse(UserId!), AccessToken); if (role == "NORMAL" || role == "CHILD") { nodeId = profileAdmin?.Node == 4 ? profileAdmin?.Child4DnaId : profileAdmin?.Node == 3 ? profileAdmin?.Child3DnaId : profileAdmin?.Node == 2 ? profileAdmin?.Child2DnaId : profileAdmin?.Node == 1 ? profileAdmin?.Child1DnaId : profileAdmin?.Node == 0 ? profileAdmin?.RootDnaId : ""; } if (role == "BROTHER") { nodeId = profileAdmin?.Node == 4 ? profileAdmin?.Child3DnaId : profileAdmin?.Node == 3 ? profileAdmin?.Child2DnaId : profileAdmin?.Node == 2 ? profileAdmin?.Child1DnaId : profileAdmin?.Node == 1 || profileAdmin?.Node == 0 ? profileAdmin?.RootDnaId : ""; } else if (role == "ROOT" /*|| role == "PARENT"*/) { nodeId = profileAdmin?.RootDnaId; } var node = profileAdmin?.Node; var data_search = (from x in _context.DisciplineComplaint_Appeals where (x.Title == null ? false : x.Title.Contains(keyword)) || (x.Description == null ? false : x.Description.Contains(keyword)) || (x.CaseType == null ? false : x.CaseType.Contains(keyword)) || (x.CaseNumber == null ? false : x.CaseNumber.Contains(keyword)) || (x.Fullname == null ? false : x.Fullname.Contains(keyword)) || (x.CitizenId == null ? false : x.CitizenId.Contains(keyword)) select x).ToList(); if (status.Trim().ToUpper() != "ALL") data_search = data_search.Where(x => x.Status == status).ToList(); if (type.Trim().ToUpper() != "ALL") data_search = data_search.Where(x => x.Type == type).ToList(); if (year != 0) data_search = data_search.Where(x => x.Year == year).ToList(); if (role == "OWNER") { node = null; } if (role == "OWNER" || role == "CHILD") { data_search = data_search .Where(x => node == 4 ? x.child4DnaId == nodeId : (node == 3 ? x.child3DnaId == nodeId : (node == 2 ? x.child2DnaId == nodeId : (node == 1 ? x.child1DnaId == nodeId : (node == 0 ? x.rootDnaId == nodeId : (node == null ? true : true)))))).ToList(); } else if (role == "BROTHER") { data_search = data_search .Where(x => node == 4 ? x.child3DnaId == nodeId : (node == 3 ? x.child2DnaId == nodeId : (node == 2 ? x.child1DnaId == nodeId : (node == 1 || node == 0 ? x.rootDnaId == nodeId : (node == null ? true : true))))).ToList(); } else if (role == "ROOT") { 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 == "NORMAL") { data_search = data_search.Where(x => node == 0 ? x.rootDnaId == nodeId && x.child1DnaId == null : node == 1 ? x.child1DnaId == nodeId && x.child2DnaId == null : node == 2 ? x.child2DnaId == nodeId && x.child3DnaId == null : node == 3 ? x.child3DnaId == nodeId && x.child4DnaId == null : node == 4 ? x.child4DnaId == nodeId : true ).ToList(); } var query = data_search .Select(x => new { Id = x.Id, Title = x.Title, Description = x.Description, Status = x.Status, Type = x.Type, Year = x.Year, CaseType = x.CaseType, CaseNumber = x.CaseNumber, Fullname = x.Fullname, CitizenId = x.CitizenId, ProfileId = x.ProfileId, LastUpdatedAt = x.LastUpdatedAt, profileType = x.profileType }); bool desc = descending ?? false; if (!string.IsNullOrEmpty(sortBy)) { switch (sortBy) { case "title": query = desc ? query.OrderByDescending(x => x.Title) : query.OrderBy(x => x.Title); break; case "description": query = desc ? query.OrderByDescending(x => x.Description) : query.OrderBy(x => x.Description); break; case "status": query = desc ? query.OrderByDescending(x => x.Status) : query.OrderBy(x => x.Status); break; case "type": query = desc ? query.OrderByDescending(x => x.Type) : query.OrderBy(x => x.Type); break; case "year": query = desc ? query.OrderByDescending(x => x.Year) : query.OrderBy(x => x.Year); break; case "caseType": query = desc ? query.OrderByDescending(x => x.CaseType) : query.OrderBy(x => x.CaseType); break; case "caseNumber": query = desc ? query.OrderByDescending(x => x.CaseNumber) : query.OrderBy(x => x.CaseNumber); break; case "fullname": query = desc ? query.OrderByDescending(x => x.Fullname) : query.OrderBy(x => x.Fullname); break; case "lastUpdatedAt": query = desc ? query.OrderByDescending(x => x.LastUpdatedAt) : query.OrderBy(x => x.LastUpdatedAt); break; case "profileType": query = desc ? query.OrderByDescending(x => x.profileType) : query.OrderBy(x => x.profileType); break; default: query = query .OrderByDescending(x => x.profileType) .ThenByDescending(x => x.LastUpdatedAt); break; } } var data = query .Skip((page - 1) * pageSize) .Take(pageSize) .ToList(); return Success(new { data, total = data_search.Count() }); } /// /// แก้ไขรายการยื่นอุทธรณ์/ร้องทุกข์ (ADMIN) /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpPut("{id:guid}")] public async Task> UpdateDiscipline(Guid id, [FromBody] DisciplineComplaint_AppealUpdateRequest req) { var getPermission = await _permission.GetPermissionAPIAsync("UPDATE", "SYS_DISCIPLINE_APPEAL"); var jsonData = JsonConvert.DeserializeObject(getPermission); if (jsonData["status"]?.ToString() != "200") { return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden); } var data = await _context.DisciplineComplaint_Appeals .Where(x => x.Id == id) .FirstOrDefaultAsync(); if (data == null) return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound); data.Title = req.Title; data.Description = req.Description; if (data.Status != req.Status.Trim().ToUpper()) { var disciplineComplaint_Appeal_History = new DisciplineComplaint_Appeal_History { DisciplineComplaint_Appeal = data, Status = req.Status.Trim().ToUpper(), CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }; await _context.DisciplineComplaint_Appeal_Historys.AddAsync(disciplineComplaint_Appeal_History); // await _repositoryNoti.PushNotificationAsync( // data.ProfileId, // $"มีการแก้ไขสถานะคำขออุทธรณ์/ร้องทุกข์จาก {data.Fullname} เป็น {StatusDisciplineComplaintAppeal(req.Status.Trim().ToUpper())}", // $"มีการแก้ไขสถานะคำขออุทธรณ์/ร้องทุกข์จาก {data.Fullname} เป็น {StatusDisciplineComplaintAppeal(req.Status.Trim().ToUpper())}", // "", // true, // true // ); } data.Status = req.Status.Trim().ToUpper(); data.Type = req.Type.Trim().ToUpper(); data.Year = req.Year; data.CaseType = req.CaseType; data.CaseNumber = req.CaseNumber; data.LastUpdateFullName = FullName ?? "System Administrator"; data.LastUpdateUserId = UserId ?? ""; data.LastUpdatedAt = DateTime.Now; await _context.SaveChangesAsync(); return Success(); } /// /// Export Report อุทธรณ์/ร้องทุกข์ /// /// /// /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("report/{id:guid}")] public async Task> ReportDiscipline(Guid id) { var data = await _context.DisciplineComplaint_Appeals .Where(x => x.Id == id) .Select(x => new { template = x.Type.Contains("APPEAL") ? "อุทธรณ์" : "ร้องทุกข์", reportName = "docx-report", data = new { Oc = x.Oc, Position = x.Position, Fullname = x.Fullname, Title = x.Title, Description = x.Description, Date = DateTime.Now.ToThaiFullDate2(), } }) .FirstOrDefaultAsync(); if (data == null) return Error(new Exception(GlobalMessages.DataNotFound), StatusCodes.Status404NotFound); return Success(data); } } }