diff --git a/BMA.EHR.Recurit.Exam.Service.csproj b/BMA.EHR.Recurit.Exam.Service.csproj
index eaab20c..4b65862 100644
--- a/BMA.EHR.Recurit.Exam.Service.csproj
+++ b/BMA.EHR.Recurit.Exam.Service.csproj
@@ -26,6 +26,7 @@
+
@@ -55,6 +56,7 @@
+
diff --git a/Controllers/BaseController.cs b/Controllers/BaseController.cs
index 53be98b..9dda347 100644
--- a/Controllers/BaseController.cs
+++ b/Controllers/BaseController.cs
@@ -42,6 +42,17 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
return Success(GlobalMessages.Success, result);
}
+ protected virtual ActionResult Error(string message, string result, int statusCode = StatusCodes.Status500InternalServerError)
+ {
+ return StatusCode((int)statusCode, new ResponseObject
+ {
+ Status = statusCode,
+ Message = message,
+ Result = result
+ });
+ }
+
+
protected virtual ActionResult Error(string message, int statusCode = StatusCodes.Status500InternalServerError)
{
return StatusCode((int)statusCode, new ResponseObject
@@ -51,6 +62,19 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
});
}
+ protected virtual ActionResult Error(Exception exception, string message, int statusCode = StatusCodes.Status500InternalServerError)
+ {
+ var msg = exception.Message;
+ var inner = exception.InnerException;
+ while (inner != null)
+ {
+ msg += $" {inner.Message}\r\n";
+ inner = inner.InnerException;
+ }
+
+ return Error(message, msg, statusCode);
+ }
+
protected virtual ActionResult Error(Exception exception, int statusCode = StatusCodes.Status500InternalServerError)
{
var msg = exception.Message;
diff --git a/Controllers/DisableController.cs b/Controllers/DisableController.cs
new file mode 100644
index 0000000..ad1c8f7
--- /dev/null
+++ b/Controllers/DisableController.cs
@@ -0,0 +1,1819 @@
+using Amazon.S3.Model;
+using BMA.EHR.Extensions;
+using BMA.EHR.Recurit.Exam.Service.Controllers;
+using BMA.EHR.Recurit.Exam.Service.Core;
+using BMA.EHR.Recurit.Exam.Service.Data;
+using BMA.EHR.Recurit.Exam.Service.Extensions;
+using BMA.EHR.Recurit.Exam.Service.Models;
+using BMA.EHR.Recurit.Exam.Service.Models.Disables;
+using BMA.EHR.Recurit.Exam.Service.Request.Disables;
+using BMA.EHR.Recurit.Exam.Service.Response;
+using BMA.EHR.Recurit.Exam.Service.Responses;
+using BMA.EHR.Recurit.Exam.Service.Services;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using MySqlConnector;
+using OfficeOpenXml;
+using Org.BouncyCastle.Ocsp;
+using Sentry;
+using Swashbuckle.AspNetCore.Annotations;
+using System.Data;
+using System.Net;
+using System.Net.WebSockets;
+using System.Security.Claims;
+using System.Text;
+
+namespace BMA.EHR.Recurit.Exam.Service.Controllers
+{
+ [Route("api/v{version:apiVersion}/disable-exam")]
+ [ApiVersion("1.0")]
+ [ApiController]
+ [Produces("application/json")]
+ [Authorize]
+ [SwaggerTag("จัดการข้อมูลการสอบคัดเลือกคนพิการ")]
+ public class DisableController : BaseController
+ {
+ #region " Fields "
+
+ private readonly ApplicationDbContext _context;
+ private readonly MinIOService _minioService;
+ private readonly IWebHostEnvironment _webHostEnvironment;
+ private readonly DisableService _disableService;
+
+ private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly ILogger _logger;
+
+ #endregion
+
+ #region " Constructor and Destructor "
+
+ public DisableController(ApplicationDbContext context,
+ MinIOService minioService,
+ IWebHostEnvironment webHostEnvironment,
+ DisableService disableService,
+ IHttpContextAccessor httpContextAccessor,
+ ILogger logger)
+ {
+ _context = context;
+ _minioService = minioService;
+ _webHostEnvironment = webHostEnvironment;
+ _disableService = disableService;
+ _httpContextAccessor = httpContextAccessor;
+ _logger = logger;
+ }
+
+ #endregion
+
+ #region " Properties "
+
+ private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
+
+ private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
+
+ #endregion
+
+ #region " Methods "
+
+ #region " Private "
+
+ private int GetColumnIndex(string[] columns, string name, bool partial = false)
+ {
+ try
+ {
+ if (partial)
+ return Array.FindIndex(columns, x => x.Contains(name)) + 1;
+ else
+ return Array.FindIndex(columns, x => x == name) + 1;
+ }
+ catch
+ {
+ return 0;
+ }
+
+ }
+
+ private string CalculateDiff(DateTime d1, DateTime d2)
+ {
+ if (d1 > d2) return "ข้อมูลไม่ถูกต้อง";
+
+ TimeSpan sp = d2.Subtract(d1);
+ int yy = sp.Days / 365;
+ int mm = (sp.Days - (yy * 365)) / 30;
+ int dd = (sp.Days - (yy * 365) - (mm * 30));
+
+ var sb = new StringBuilder();
+ sb.Clear();
+ sb.Append(yy == 0 ? "" : $"{yy} ปี ");
+ sb.Append(mm == 0 ? "" : $"{mm} เดือน ");
+ //sb.Append(dd == 0 ? "" : $"{dd} วัน ");
+
+ return sb.ToString();
+ }
+
+ private async Task GetExamCount(Guid exam)
+ {
+ try
+ {
+ return await _context.DisablePayments.AsQueryable()
+ .Include(x => x.Disable)
+ .ThenInclude(x => x.PeriodExam)
+ .Where(x => x.Disable.PeriodExam.Id == exam)
+ .Where(x => x.Disable.PeriodExam.CheckDisability == true)
+ .CountAsync();
+ }
+ catch
+ {
+ throw;
+ }
+ }
+
+ private async Task GetPassExamCount(Guid exam)
+ {
+ try
+ {
+ return await _context.DisableScores.AsQueryable()
+ .Include(x => x.ScoreImport)
+ .Where(x => x.ScoreImport.Id == exam)
+ .Where(x => x.ExamStatus == "ผ่าน")
+ .CountAsync();
+ }
+ catch
+ {
+ throw;
+ }
+ }
+
+ private async Task GetScoreCount(Guid exam)
+ {
+ try
+ {
+ return await _context.DisableScores.AsQueryable()
+ .Include(x => x.ScoreImport)
+ .Where(x => x.ScoreImport.Id == exam)
+ .CountAsync();
+ }
+ catch
+ {
+ throw;
+ }
+ }
+
+ #endregion
+
+ #region " Ex. Upload, Download and Delete file "
+
+ ///
+ /// ตัวอย่างในการเขียน api เพื่อทำการ upload file
+ ///
+ ///
+ /// เมื่อทำการ upload สำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpPost("upload"), DisableRequestSizeLimit]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ [AllowAnonymous]
+ public async Task> UploadFile()
+ {
+ try
+ {
+ if (Request.Form.Files == null || Request.Form.Files.Count == 0)
+ {
+ return Error(GlobalMessages.NoFileToUpload);
+ }
+
+ var file = Request.Form.Files[0];
+ var doc = await _minioService.UploadFileAsync(file);
+
+ return Success(doc);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ ///
+ /// ตัวอย่างในการเขียน api เพื่อทำการ delete file
+ ///
+ /// รหัสไฟล์ในฐานข้อมูล
+ ///
+ /// เมื่อทำการ delete file สำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("delete/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ [AllowAnonymous]
+ public async Task> DeleteFile(Guid id)
+ {
+ try
+ {
+ await _minioService.DeleteFileAsync(id);
+
+ return Success();
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ ///
+ /// ตัวอย่างในการเขียน api เพื่อทำการ download file
+ ///
+ /// รหัสไฟล์ในฐานข้อมูล
+ ///
+ /// เมื่อทำการ download file สำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("download/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ [AllowAnonymous]
+ public async Task> DownloadFile(Guid id)
+ {
+ try
+ {
+ var file_data = await _minioService.DownloadFileAsync(id);
+
+ Response.Headers["Content-Disposition"] = $"inline; filename={file_data.FileName}";
+
+ var ret = new FileContentResult(file_data.FileContent, file_data.FileType)
+ {
+ FileDownloadName = file_data.FileName
+ };
+
+ return ret;
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+
+ #endregion
+
+ #region " จัดการรอบการสมัครสอบคัดเลือกผู้พิการ "
+
+ ///
+ /// แสดงข้อมูลรอบการสอบคัดเลือกผู้พิการ
+ ///
+ ///
+ /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("period")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> GetPeriodsAsync()
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.ImportFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .OrderByDescending(x => x.Year)
+ .ThenByDescending(x => x.Round)
+ .Select(x => new
+ {
+ x.Id,
+ x.Year,
+ x.Name,
+ x.Round,
+ ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
+ ExamCount = x.Disables.Count(),
+ Score = x.ScoreImport == null ? null :
+ new
+ {
+ ID = x.ScoreImport.Id,
+ ImportYear = x.ScoreImport.Year,
+ ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
+ ScoreCount = x.ScoreImport.Scores.Count(),
+
+ }
+ })
+ .ToListAsync();
+
+ return Success(data);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ ///
+ /// แสดงข้อมูลรอบการสอบคัดเลือกผู้พิการเป็นรายการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ ///
+ /// เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("period/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> GetPeriodByIdAsync(Guid id)
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Addresses)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Occupations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Certificates)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Educations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Payments)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Documents)
+ .ThenInclude(x => x.DocumentFile)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ return Success(data);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+
+ ///
+ /// เพิ่มข้อมูลรอบการจัดสอบคัดเลือกผู้พิการ
+ ///
+ /// Request parameters
+ ///
+ /// เมื่อทำการเพิ่มข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpPost("period")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> PostPeriodAsync([FromBody] PostDisableImportRequest req)
+ {
+ try
+ {
+ if (req == null)
+ return Error(GlobalMessages.InvalidRequestParam, (int)HttpStatusCode.BadRequest);
+
+ await _context.PeriodExams.AddAsync(new PeriodExam
+ {
+ Year = req.Year,
+ Name = req.Name,
+ Round = req.Round,
+ Detail = req.Detail,
+ Fee = req.Fee,
+ AnnouncementStartDate = req.AnnouncementStartDate,
+ AnnouncementEndDate = req.AnnouncementEndDate,
+ RegisterStartDate = req.RegisterStartDate,
+ RegisterEndDate = req.RegisterEndDate,
+ ExamDate = req.ExamDate,
+ PaymentStartDate = req.PaymentStartDate,
+ PaymentEndDate = req.PaymentEndDate,
+ Note = req.Note,
+ AnnouncementDate = req.AnnouncementDate,
+ CheckDisability = true,
+ });
+
+ await _context.SaveChangesAsync();
+
+ return Success();
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ ///
+ /// แก้ไขข้อมูลรอบการจัดสอบคัดเลือกผู้พิการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ /// Request parameters
+ ///
+ /// เมื่อทำการเพิ่มข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpPut("period/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> PutPeriodAsync(Guid id, [FromBody] PostDisableImportRequest req)
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (data == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ data.Name = req.Name;
+ data.Year = req.Year;
+ data.Round = req.Round;
+ data.Detail = req.Detail;
+ data.Fee = req.Fee;
+ data.AnnouncementEndDate = req.AnnouncementEndDate;
+ data.AnnouncementStartDate = req.AnnouncementStartDate;
+ data.RegisterStartDate = req.RegisterStartDate;
+ data.RegisterEndDate = req.RegisterEndDate;
+ data.PaymentEndDate = req.PaymentEndDate;
+ data.PaymentStartDate = req.PaymentStartDate;
+ data.ExamDate = req.ExamDate;
+ data.Note = req.Note;
+ data.AnnouncementDate = req.AnnouncementDate;
+
+ await _context.SaveChangesAsync();
+
+ return Success();
+
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+
+ ///
+ /// ลบข้อมูลรอบการจัดสอบคัดเลือกผู้พิการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ ///
+ /// เมื่อทำการลบข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpDelete("period/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> DeletePeriodAsync(Guid id)
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Addresses)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Occupations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Certificates)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Educations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Payments)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Documents)
+ .ThenInclude(x => x.DocumentFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.ImportFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ _context.PeriodExams.Remove(data);
+ await _context.SaveChangesAsync();
+
+ return Success();
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ #endregion
+
+ #region " Candidate Files "
+
+ ///
+ /// แสดงข้อมูลสำหรับหน้าจอ รายการนำเข้าข้อมูลผู้สมัครสอบคัดเลือกผู้พิการ
+ ///
+ ///
+ /// เมื่อแสดงรายการข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("candidate")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> GetCandidateFilesAsync()
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.ImportFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .OrderByDescending(x => x.Year)
+ .ThenByDescending(x => x.Round)
+ .Select(x => new
+ {
+ x.Id,
+ x.Year,
+ x.Name,
+ x.Round,
+ ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
+ ExamCount = x.Disables.Count(),
+ Score = x.ScoreImport == null ? null :
+ new
+ {
+ ID = x.ScoreImport.Id,
+ ImportYear = x.ScoreImport.Year,
+ ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
+ ScoreCount = x.ScoreImport.Scores.Count(),
+
+ }
+ })
+ .ToListAsync();
+
+ return Success(data);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+
+ ///
+ /// นำเข้ารายชื่อผู้สมัครสอบคัดเลือกผู้พิการ
+ ///
+ ///
+ /// เมื่อทำนำเข้าข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpPost("candidate"), DisableRequestSizeLimit]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> ImportCandidateFileAsync([FromForm] PostDisableImportRequest req)
+ {
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var importFile = Path.Combine(tmpDir, $"c_{DateTime.Now.ToString("ddMMyyyyHHmmss")}.xlsx");
+ var import_doc_id = "";
+
+ try
+ {
+ if (Request.Form.Files == null || Request.Form.Files.Count == 0)
+ {
+ return Error(GlobalMessages.NoFileToUpload);
+ }
+
+ var file = Request.Form.Files[0];
+ var doc = await _minioService.UploadFileAsync(file);
+ import_doc_id = doc.Id.ToString("D");
+
+ var fileContent = (await _minioService.DownloadFileAsync(doc.Id)).FileContent;
+
+ // สร้างรอบการบรรจุ โดยเอาเข้ามูลมาใส่จาก Request
+ var imported = new PeriodExam
+ {
+ Year = req.Year,
+ Round = req.Round,
+ Name = req.Name,
+ ImportFile = doc,
+ CheckDisability = true,
+ CreatedAt = DateTime.Now,
+ CreatedUserId = UserId ?? "",
+ CreatedFullName = FullName ?? "System Administrator",
+ ImportHostories = new List
+ {
+ new DisableImportHistory
+ {
+ Description = "นำเข้าข้อมูลผู้สมัครสอบคัดเลือกผู้พิการ",
+ CreatedAt = DateTime.Now,
+ CreatedUserId = UserId ?? "",
+ CreatedFullName = FullName ?? "System Administrator",
+ }
+ }
+ };
+
+ await _context.PeriodExams.AddAsync(imported);
+
+ // import datafile
+ System.IO.File.WriteAllBytes(importFile, fileContent);
+
+ using (var c_package = new ExcelPackage(new FileInfo(importFile)))
+ {
+ // loop from sheet2 to end
+
+ for (int i = 1; i < c_package.Workbook.Worksheets.Count; i++)
+ {
+ var workSheet = c_package.Workbook.Worksheets[i];
+ var totalRows = workSheet.Dimension.Rows;
+ var cols = workSheet.GetHeaderColumns();
+
+ int row = 2;
+
+ while (row <= totalRows)
+ {
+ var cell1 = workSheet?.Cells[row, 1]?.GetValue();
+ if (cell1 == "" || cell1 == null) break;
+
+ var r = new Recurit.Exam.Service.Models.Disables.Disable();
+ r.ExamId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ExamID)]?.GetValue();
+ r.CitizenId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalID)]?.GetValue();
+ r.Prefix = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Prefix)]?.GetValue();
+ r.FirstName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.FirstName)]?.GetValue();
+ r.LastName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.LastName)]?.GetValue();
+ r.Gendor = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Gender)]?.GetValue();
+ r.National = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.National)]?.GetValue().IsNull("");
+ r.Race = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Race)]?.GetValue().IsNull("");
+ r.Religion = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Religion)]?.GetValue().IsNull("");
+ r.DateOfBirth = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.DateOfBirth)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"));
+ r.Marry = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Marry)]?.GetValue();
+ r.Isspecial = "N";
+ r.CitizenCardIssuer = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardIssue)]?.GetValue();
+ r.CitizenCardExpireDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardExpireDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"));
+ r.ApplyDate = (DateTime)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ApplyDate)]?.GetValue();
+ r.PositionName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PositionName)]?.GetValue().IsNull("");
+
+
+ // address
+ r.Addresses.Add(new DisableAddress()
+ {
+ Address = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address)]?.GetValue() ?? "",
+ Moo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo)]?.GetValue() ?? "",
+ Soi = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi)]?.GetValue() ?? "",
+ Road = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road)]?.GetValue() ?? "",
+ District = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District)]?.GetValue() ?? "",
+ Amphur = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur)]?.GetValue() ?? "",
+ Province = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Province)]?.GetValue() ?? "",
+ ZipCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode)]?.GetValue() ?? "",
+ Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Telephone)]?.GetValue() ?? "",
+ Mobile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Mobile)]?.GetValue() ?? "",
+ Address1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address1)]?.GetValue() ?? "",
+ Moo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo1)]?.GetValue() ?? "",
+ Soi1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi1)]?.GetValue() ?? "",
+ Road1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road1)]?.GetValue() ?? "",
+ District1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District1)]?.GetValue() ?? "",
+ Amphur1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur1)]?.GetValue() ?? "",
+ Province1 = "",
+ ZipCode1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode1)]?.GetValue() ?? "",
+ });
+
+ // payment
+ r.Payments.Add(new DisablePayment()
+ {
+ PaymentId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PaymentID)]?.GetValue() ?? "",
+ CompanyCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CompanyCode)]?.GetValue() ?? "",
+ TextFile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TextFile)]?.GetValue() ?? "",
+ BankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BankCode)]?.GetValue() ?? "",
+ AccountNumber = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.AccouontNumer)]?.GetValue() ?? "",
+ TransDate = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransDate)]?.GetValue() ?? "",
+ TransTime = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransTime)]?.GetValue() ?? "",
+ CustomerName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CustomerName)]?.GetValue() ?? "",
+ RefNo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.RefNo1)]?.GetValue() ?? "",
+ TermBranch = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TermBranch)]?.GetValue() ?? "",
+ TellerId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TellerID)]?.GetValue() ?? "",
+ CreditDebit = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CreditDebit)]?.GetValue() ?? "",
+ PaymentType = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Type)]?.GetValue(),
+ ChequeNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChequeNo)]?.GetValue() ?? "",
+ Amount = (decimal)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amount)]?.GetValue(),
+ ChqueBankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChqBankCode)]?.GetValue() ?? ""
+ });
+
+ // occupation
+ r.Occupations.Add(new DisableOccupation()
+ {
+ Occupation = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Occupation)]?.GetValue() ?? "",
+ Position = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Position)]?.GetValue() ?? "",
+ Workplace = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Workplace)]?.GetValue() ?? "",
+ Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkplaceTelephone)]?.GetValue() ?? "",
+ WorkAge = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkAge)]?.GetValue() ?? "",
+ });
+
+ // certificate
+ r.Certificates.Add(new DisableCertificate()
+ {
+ CertificateNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateNo)]?.GetValue() ?? "",
+ Description = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateDesc)]?.GetValue() ?? "",
+ IssueDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateIssueDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-")),
+ ExpiredDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateExpireDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"))
+ });
+
+ r.Educations.Add(new DisableEducation()
+ {
+ Degree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Degree)]?.GetValue() ?? "",
+ Major = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Major)]?.GetValue() ?? "",
+ MajorGroupId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupID)]?.GetValue() ?? "",
+ MajorGroupName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupName)]?.GetValue() ?? "",
+ University = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.University)]?.GetValue() ?? "",
+ GPA = (double)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.GPA)]?.GetValue(),
+ Specialist = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.SpecialList)]?.GetValue() ?? "",
+ HighDegree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.HighDegree)]?.GetValue() ?? "",
+ BachelorDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BachelorDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"))
+ });
+
+ r.PeriodExam = imported;
+ _context.Disables.Add(r);
+
+ //imported.Disables.Add(r);
+ row++;
+
+ }
+ }
+ }
+
+ // finally save to database
+
+ _context.SaveChanges();
+
+ return Success();
+
+ }
+ catch (Exception ex)
+ {
+ await _minioService.DeleteFileAsync(Guid.Parse(import_doc_id));
+ return Error(ex);
+ }
+ finally
+ {
+ if (System.IO.File.Exists(importFile))
+ System.IO.File.Delete(importFile);
+ }
+ }
+
+ ///
+ /// ลบข้อมูลนำข้อมูลผู้สมัครสอบคัดเลือกผู้พิการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ ///
+ /// เมื่อทำนำเข้าข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpDelete("candidate/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> DeleteCandidateFileAsync(Guid id)
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportHostories)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Addresses)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Occupations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Certificates)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Educations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Payments)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Documents)
+ .ThenInclude(x => x.DocumentFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.ImportFile)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (data == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ var rec_import_id = data.ImportFile.Id.ToString("D");
+ var score_import_id = data.ScoreImport != null ? data.ScoreImport.ImportFile.Id.ToString("D") : "-";
+
+ _context.PeriodExams.Remove(data);
+ await _context.SaveChangesAsync();
+
+ // delete upload candidate file
+ await _minioService.DeleteFileAsync(Guid.Parse(rec_import_id));
+
+ // delete score file
+ if (score_import_id != "-")
+ await _minioService.DeleteFileAsync(Guid.Parse(score_import_id));
+
+ return Success();
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ ///
+ /// แสดงประวัติการนำเข้าข้อมูลการสอบคัดเลือกผู้พิการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ ///
+ /// เมื่อทำนำเข้าข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("history/{id:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> GetImportHistoryAsync(Guid id)
+ {
+ try
+ {
+ var data = await _context.DisableImportHistories.AsQueryable()
+ .Include(x => x.PeriodExam)
+ .Where(x => x.PeriodExam.Id == id)
+ .Where(x => x.PeriodExam.CheckDisability == true)
+ .OrderByDescending(x => x.CreatedAt)
+ .ToListAsync();
+
+ return Success(data);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+
+ ///
+ /// นำเข้ารายชื่อผู้สมัครสอบคัดเลือกผู้พิการ
+ ///
+ /// รหัสรอบการสอบคัดเลือกผู้พิการ
+ ///
+ /// เมื่อทำนำเข้าข้อมูลสำเร็จ
+ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpPost("candidate/{id:length(36)}"), DisableRequestSizeLimit]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> ImportCandidateFileByIdAsync(Guid id)
+ {
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var importFile = Path.Combine(tmpDir, $"c_{DateTime.Now.ToString("ddMMyyyyHHmmss")}.xlsx");
+ var import_doc_id = "";
+
+ try
+ {
+ if (Request.Form.Files == null || Request.Form.Files.Count == 0)
+ {
+ return Error(GlobalMessages.NoFileToUpload);
+ }
+
+ var imported = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ImportHostories)
+ .Include(x => x.ImportFile)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Addresses)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Occupations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Certificates)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Educations)
+ .Include(x => x.Disables)
+ .ThenInclude(x => x.Payments)
+ .Include(x => x.Disables)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (imported == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ if (imported.Disables != null)
+ {
+ // remove old score data
+ _context.Disables.RemoveRange(imported.Disables);
+ await _context.SaveChangesAsync();
+ }
+
+ var file = Request.Form.Files[0];
+ var doc = await _minioService.UploadFileAsync(file);
+ import_doc_id = doc.Id.ToString("D");
+
+ var fileContent = (await _minioService.DownloadFileAsync(doc.Id)).FileContent;
+
+ // สร้างรอบการบรรจุ โดยเอาเข้ามูลมาใส่จาก Request
+ imported.ImportHostories.Add(new DisableImportHistory
+ {
+ Description = "นำเข้าข้อมูลผู้สมัครสอบคัดเลือกผู้พิการ",
+ CreatedAt = DateTime.Now,
+ CreatedUserId = UserId ?? "",
+ CreatedFullName = FullName ?? "System Administrator",
+ });
+
+ //await _context.DisableImports.AddAsync(imported);
+
+ // import datafile
+ System.IO.File.WriteAllBytes(importFile, fileContent);
+
+ using (var c_package = new ExcelPackage(new FileInfo(importFile)))
+ {
+ // loop from sheet2 to end
+
+ for (int i = 1; i < c_package.Workbook.Worksheets.Count; i++)
+ {
+ var workSheet = c_package.Workbook.Worksheets[i];
+ var totalRows = workSheet.Dimension.Rows;
+ var cols = workSheet.GetHeaderColumns();
+
+ int row = 2;
+
+ while (row <= totalRows)
+ {
+ var cell1 = workSheet?.Cells[row, 1]?.GetValue();
+ if (cell1 == "" || cell1 == null) break;
+
+ var r = new Recurit.Exam.Service.Models.Disables.Disable();
+ r.ExamId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ExamID)]?.GetValue();
+ r.CitizenId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalID)]?.GetValue();
+ r.Prefix = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Prefix)]?.GetValue();
+ r.FirstName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.FirstName)]?.GetValue();
+ r.LastName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.LastName)]?.GetValue();
+ r.Gendor = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Gender)]?.GetValue();
+ r.National = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.National)]?.GetValue().IsNull("");
+ r.Race = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Race)]?.GetValue().IsNull("");
+ r.Religion = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Religion)]?.GetValue().IsNull("");
+ r.DateOfBirth = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.DateOfBirth)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"));
+ r.Marry = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Marry)]?.GetValue();
+ r.Isspecial = "N";
+ r.CitizenCardIssuer = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardIssue)]?.GetValue();
+ r.CitizenCardExpireDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardExpireDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"));
+ r.ApplyDate = (DateTime)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ApplyDate)]?.GetValue();
+ r.PositionName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PositionName)]?.GetValue().IsNull("");
+
+ // address
+ r.Addresses.Add(new DisableAddress()
+ {
+ Address = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address)]?.GetValue() ?? "",
+ Moo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo)]?.GetValue() ?? "",
+ Soi = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi)]?.GetValue() ?? "",
+ Road = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road)]?.GetValue() ?? "",
+ District = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District)]?.GetValue() ?? "",
+ Amphur = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur)]?.GetValue() ?? "",
+ Province = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Province)]?.GetValue() ?? "",
+ ZipCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode)]?.GetValue() ?? "",
+ Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Telephone)]?.GetValue() ?? "",
+ Mobile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Mobile)]?.GetValue() ?? "",
+ Address1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address1)]?.GetValue() ?? "",
+ Moo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo1)]?.GetValue() ?? "",
+ Soi1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi1)]?.GetValue() ?? "",
+ Road1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road1)]?.GetValue() ?? "",
+ District1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District1)]?.GetValue() ?? "",
+ Amphur1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur1)]?.GetValue() ?? "",
+ Province1 = "",
+ ZipCode1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode1)]?.GetValue() ?? "",
+ });
+
+ // payment
+ r.Payments.Add(new DisablePayment()
+ {
+ PaymentId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PaymentID)]?.GetValue() ?? "",
+ CompanyCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CompanyCode)]?.GetValue() ?? "",
+ TextFile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TextFile)]?.GetValue() ?? "",
+ BankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BankCode)]?.GetValue() ?? "",
+ AccountNumber = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.AccouontNumer)]?.GetValue() ?? "",
+ TransDate = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransDate)]?.GetValue() ?? "",
+ TransTime = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransTime)]?.GetValue() ?? "",
+ CustomerName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CustomerName)]?.GetValue() ?? "",
+ RefNo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.RefNo1)]?.GetValue() ?? "",
+ TermBranch = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TermBranch)]?.GetValue() ?? "",
+ TellerId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TellerID)]?.GetValue() ?? "",
+ CreditDebit = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CreditDebit)]?.GetValue() ?? "",
+ PaymentType = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Type)]?.GetValue(),
+ ChequeNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChequeNo)]?.GetValue() ?? "",
+ Amount = (decimal)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amount)]?.GetValue(),
+ ChqueBankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChqBankCode)]?.GetValue() ?? ""
+ });
+
+ // occupation
+ r.Occupations.Add(new DisableOccupation()
+ {
+ Occupation = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Occupation)]?.GetValue() ?? "",
+ Position = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Position)]?.GetValue() ?? "",
+ Workplace = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Workplace)]?.GetValue() ?? "",
+ Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkplaceTelephone)]?.GetValue() ?? "",
+ WorkAge = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkAge)]?.GetValue() ?? "",
+ });
+
+ // certificate
+ r.Certificates.Add(new DisableCertificate()
+ {
+ CertificateNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateNo)]?.GetValue() ?? "",
+ Description = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateDesc)]?.GetValue() ?? "",
+ IssueDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateIssueDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-")),
+ ExpiredDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateExpireDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"))
+ });
+
+ r.Educations.Add(new DisableEducation()
+ {
+ Degree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Degree)]?.GetValue() ?? "",
+ Major = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Major)]?.GetValue() ?? "",
+ MajorGroupId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupID)]?.GetValue() ?? "",
+ MajorGroupName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupName)]?.GetValue() ?? "",
+ University = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.University)]?.GetValue() ?? "",
+ GPA = (double)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.GPA)]?.GetValue(),
+ Specialist = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.SpecialList)]?.GetValue() ?? "",
+ HighDegree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.HighDegree)]?.GetValue() ?? "",
+ BachelorDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BachelorDate)]?.GetValue().ToDateTime(DateTimeFormat.Ymd, "-"))
+ });
+
+ r.PeriodExam = imported;
+ _context.Disables.Add(r);
+
+ //imported.Disables.Add(r);
+ row++;
+
+ }
+ }
+ }
+
+ // finally save to database
+
+ _context.SaveChanges();
+
+ return Success();
+
+ }
+ catch (Exception ex)
+ {
+ await _minioService.DeleteFileAsync(Guid.Parse(import_doc_id));
+ return Error(ex);
+ }
+ finally
+ {
+ if (System.IO.File.Exists(importFile))
+ System.IO.File.Delete(importFile);
+ }
+ }
+
+ #endregion
+
+ #region " Score File "
+
+ [HttpPost("score/{id:length(36)}"), DisableRequestSizeLimit]
+ public async Task> ImportScoreFileAsync(Guid id)
+ {
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var importFile = Path.Combine(tmpDir, $"s_{DateTime.Now.ToString("ddMMyyyyHHmmss")}.xlsx");
+ var import_doc_id = "";
+
+ try
+ {
+ if (Request.Form.Files == null || Request.Form.Files.Count == 0)
+ {
+ return Error(GlobalMessages.NoFileToUpload);
+ }
+
+ var rec_import = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .Include(x => x.ImportHostories)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (rec_import == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ if (rec_import.ScoreImport != null)
+ {
+ // remove old score data
+ if (rec_import.ScoreImport.Scores != null)
+ {
+ _context.DisableScores.RemoveRange(rec_import.ScoreImport.Scores);
+ await _context.SaveChangesAsync();
+ }
+ }
+
+ var file = Request.Form.Files[0];
+ var doc = await _minioService.UploadFileAsync(file);
+ import_doc_id = doc.Id.ToString("D");
+ var fileContent = (await _minioService.DownloadFileAsync(doc.Id)).FileContent;
+
+ // create import history
+ rec_import.ImportHostories.Add(new DisableImportHistory
+ {
+ Description = "นำเข้าข้อมูลผลคะแนนสอบ",
+ CreatedAt = DateTime.Now,
+ CreatedUserId = UserId ?? "",
+ CreatedFullName = FullName ?? "System Administrator",
+ });
+
+ // create new file import
+ var imported = new ScoreImport
+ {
+ Year = rec_import.Year,
+ ImportFile = doc,
+ Scores = new List()
+ };
+
+ // import datafile
+ System.IO.File.WriteAllBytes(importFile, fileContent);
+
+ using (var c_package = new ExcelPackage(new FileInfo(importFile)))
+ {
+ // loop from sheet2 to end
+ for (int i = 1; i < c_package.Workbook.Worksheets.Count; i++)
+ {
+ var workSheet = c_package.Workbook.Worksheets[i];
+ var totalRows = workSheet.Dimension.Rows;
+ var cols = workSheet.GetHeaderColumns();
+
+ int row = 8;
+
+ while (row <= totalRows)
+ {
+ var cell1 = workSheet?.Cells[row, 1]?.GetValue();
+ if (cell1 == "" || cell1 == null) break;
+
+ var r = new DisableScore();
+ r.ExamId = workSheet?.Cells[row, 2]?.GetValue();
+
+ r.FullA = (int)workSheet?.Cells[7, 7]?.GetValue().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
+ r.SumA = workSheet?.Cells[row, 7]?.GetValue() == "ขส." ? 0 : (int)workSheet?.Cells[row, 7]?.GetValue().Replace(".00", "").ToInteger();
+ r.PercentageA = workSheet?.Cells[row, 8]?.GetValue() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 8]?.GetValue();
+ r.AStatus = workSheet?.Cells[row, 9]?.GetValue();
+
+ r.FullB = (int)workSheet?.Cells[7, 12]?.GetValue().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
+ r.SumB = workSheet?.Cells[row, 12]?.GetValue() == "ขส." ? 0 : (int)workSheet?.Cells[row, 12]?.GetValue().Replace(".00", "").ToInteger();
+ r.PercentageB = workSheet?.Cells[row, 13]?.GetValue() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 13]?.GetValue();
+ r.BStatus = workSheet?.Cells[row, 14]?.GetValue();
+
+ r.SumAB = workSheet?.Cells[row, 15]?.GetValue() == "ขส." ? 0 : (int)workSheet?.Cells[row, 15]?.GetValue().Replace(".00", "").ToInteger();
+ r.ABStatus = workSheet?.Cells[row, 17]?.GetValue();
+
+ r.FullC = (int)workSheet?.Cells[7, 20]?.GetValue().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
+ r.SumC = workSheet?.Cells[row, 20]?.GetValue() == "ขส." ? 0 : (int)workSheet?.Cells[row, 20]?.GetValue().Replace(".00", "").ToInteger();
+ r.PercentageC = workSheet?.Cells[row, 21]?.GetValue() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 21]?.GetValue();
+ r.CStatus = workSheet?.Cells[row, 22]?.GetValue();
+
+ r.ExamStatus = workSheet?.Cells[row, 24]?.GetValue();
+ r.Number = workSheet?.Cells[row, 25]?.GetValue() ?? "";
+ r.Major = workSheet.Name;
+
+
+ imported.Scores.Add(r);
+ row++;
+ }
+ }
+ }
+
+ // finally save to database
+ rec_import.ScoreImport = imported;
+ await _context.SaveChangesAsync();
+
+ return Success();
+
+ }
+ catch (Exception ex)
+ {
+ await _minioService.DeleteFileAsync(Guid.Parse(import_doc_id));
+ return Error(ex);
+ }
+ finally
+ {
+ if (System.IO.File.Exists(importFile))
+ System.IO.File.Delete(importFile);
+ }
+ }
+
+ #endregion
+
+ #region " Exam Information "
+
+ ///
+ /// แสดงข้อมูลสำหรับหน้าจอ : รายการข้อมูลผู้สมัครสอบ
+ ///
+ [HttpGet("exam")]
+ public async Task> GetExamResultAsync()
+ {
+ try
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .OrderByDescending(x => x.Year)
+ .ThenByDescending(x => x.Round)
+ .Select(x => new
+ {
+ x.Id,
+ ExamYear = x.Year == null ? 0 : x.Year.Value.ToThaiYear(),
+ ExamOrder = x.Round,
+ Description = x.Name,
+ })
+ .ToListAsync();
+
+ var result = new List();
+
+ foreach (var d in data)
+ {
+ result.Add(new
+ {
+ ExamYear = d.ExamYear,
+ Decription = d.Description,
+ ExamCount = await GetExamCount(d.Id),
+ PassCount = await GetPassExamCount(d.Id),
+ NotPassCount = (await GetExamCount(d.Id) - await GetPassExamCount(d.Id))
+ });
+ }
+
+ return Success(result);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ [HttpPost("exam/{id:length(36)}")]
+ public ActionResult GetExamResultById([FromBody] DisableExamRequest req, Guid id)
+ {
+ try
+ {
+ var periodExam = _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .FirstOrDefault(x => x.Id == id);
+
+ if (periodExam == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ var p_Id = new MySqlParameter("@id", id);
+ var data = new List();
+ using (var cmd = _context.Database.GetDbConnection().CreateCommand())
+ {
+ cmd.CommandTimeout = 0;
+ var sb = new StringBuilder();
+ cmd.Parameters.Clear();
+ sb.Clear();
+ sb.Append(" SELECT * ");
+ sb.Append(" FROM exam_info ");
+ sb.Append(" WHERE disable_import_id = @id ");
+ cmd.Parameters.Add(p_Id);
+
+ if (req.ExamAttribute != null && req.ExamAttribute != "")
+ {
+ sb.Append(" AND examAttribute = @a ");
+ cmd.Parameters.Add(new MySqlParameter("@a", req.ExamAttribute));
+ }
+
+ if (req.ExamResult != null && req.ExamResult != "")
+ {
+ sb.Append(" AND result = @r ");
+ cmd.Parameters.Add(new MySqlParameter("@r", req.ExamResult));
+ }
+
+ cmd.CommandText = sb.ToString();
+
+ _context.Database.OpenConnection();
+ var da = new MySqlDataAdapter(cmd as MySqlCommand);
+ var dt = new DataTable();
+ da.Fill(dt);
+
+ foreach (DataRow dr in dt.Rows)
+ {
+ data.Add(new
+ {
+ examID = dr["examID"].ToString(),
+ profileID = dr["profileID"].ToString(),
+ prefix = dr["prefix"].ToString(),
+ fullName = dr["fullName"].ToString(),
+ dateOfBirth = dr["dateofbirth"] == null ? "" : Convert.ToDateTime(dr["dateofbirth"]).ToThaiShortDate(),
+ gender = dr["gender"].ToString(),
+ degree = dr["degree"].ToString(),
+ major = dr["major"].ToString(),
+ majorgroup = dr["majorgroup"].ToString(),
+ certificateNo = dr["certificateno"].ToString(),
+ certificateIssueDate = dr["certificateIssueDate"] == null ? "" : Convert.ToDateTime(dr["certificateIssueDate"]).ToThaiShortDate(),
+ ExamScore = dr["score"] == null ? 0 : dr["score"].ToString().ToInteger(),
+ ExamResult = dr["result"].ToString(),
+ ExamAttribute = dr["examAttribute"].ToString(),
+ Remark = dr["remark"].ToString(),
+ IsSpecial = dr["isspecial"].ToString(),
+ applyDate = dr["applydate"] == null ? "" : Convert.ToDateTime(dr["applydate"]).ToThaiShortDate(),
+ university = dr["university"].ToString(),
+ position_name = dr["position_name"].ToString(),
+ exam_name = dr["exam_name"].ToString(),
+ exam_order = dr["exam_order"].ToString(),
+ score_year = Convert.ToInt32(dr["score_year"]).ToThaiYear().ToString(),
+ });
+ }
+
+ }
+
+ dynamic header = null;
+ using (var cmd = _context.Database.GetDbConnection().CreateCommand())
+ {
+ var sb = new StringBuilder();
+ cmd.CommandTimeout = 0;
+ cmd.Parameters.Clear();
+ sb.Clear();
+ sb.Append(" SELECT * ");
+ sb.Append(" FROM sum_exam_info ");
+ sb.Append(" WHERE disable_import_id = @id ");
+ cmd.Parameters.Add(p_Id);
+
+ cmd.CommandText = sb.ToString();
+
+
+ _context.Database.OpenConnection();
+ MySqlDataAdapter da = new MySqlDataAdapter(cmd as MySqlCommand);
+ DataTable dt = new DataTable();
+ da.Fill(dt);
+ if (dt.Rows.Count == 0)
+ {
+ header = new
+ {
+ count = 0,
+ pass = 0,
+ notpass = 0
+ };
+ }
+ else
+ {
+ var dr = dt.Rows[0];
+ header = new
+ {
+ count = dr["count"].ToString().ToInteger(),
+ pass = dr["pass"].ToString().ToInteger(),
+ notpass = dr["notpass"].ToString().ToInteger()
+ };
+ }
+ }
+
+ return Success(new
+ {
+ data = data,
+ header = header,
+ round = periodExam.Round,
+ year = periodExam.Year
+ });
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ [HttpGet("exam/{id:length(36)}/{examId}")]
+ public async Task> GetExamResultByPersonAsync(Guid id, string examId)
+ {
+ try
+ {
+ var data = await _context.Disables.AsQueryable()
+ .Include(x => x.PeriodExam)
+ .Include(x => x.Documents)
+ .ThenInclude(x => x.DocumentFile)
+ .Where(x => x.PeriodExam.Id == id)
+ .Where(x => x.PeriodExam.CheckDisability == true)
+ .Where(x => x.ExamId == examId)
+ .Join(_context.DisableScores.AsQueryable()
+ .Include(x => x.ScoreImport),
+ rc => new { rc.PeriodExam.Year, rc.ExamId },
+ sc => new { sc.ScoreImport.Year, sc.ExamId },
+ (p, sr) => new
+ {
+ ExamID = p.ExamId,
+ ProfileID = p.CitizenId,
+ p.Prefix,
+ FullName = $"{p.FirstName} {p.LastName}",
+ DateOfBirth = p.DateOfBirth.ToThaiShortDate(),
+ Gender = p.Gendor,
+ Degree = p.Educations.First().Degree,
+ Major = p.Educations.First().Major,
+ CertificateNo = p.Certificates.First().CertificateNo,
+ CertificateIssueDate = p.Certificates.First().IssueDate.ToThaiShortDate(),
+ ExamResult = sr == null ? "" : sr.ExamStatus,
+ ExamAttribute = _disableService.CheckValidCertificate(p.Certificates.First().IssueDate, 5) ? "มีคุณสมบัติ" : "ไม่มีคุณสมบัติ",
+ IsSpecial = p.Isspecial,
+ Remark = p.Remark,
+ University = p.Educations.First().University,
+ PositionName = p.PositionName,
+ ExamName = p.PeriodExam.Name,
+ ExamOrder = p.PeriodExam.Round,
+ ExamYear = p.PeriodExam.Year == null ? 0 : p.PeriodExam.Year.Value.ToThaiYear(),
+ Score = sr == null ? 0 : sr.SumA + sr.SumB + sr.SumC,
+ Number = sr == null ? "" : sr.Number,
+ ExamCount = _disableService.GetExamCount(p.CitizenId),
+ ScoreExpire = p.PeriodExam.AnnouncementDate == null ? "" : p.PeriodExam.AnnouncementDate.AddYears(2).ToThaiShortDate(),
+ ScoreResult = sr == null ? null : new
+ {
+ ScoreAFull = sr.FullA,
+ ScoreA = sr.SumA,
+ ScoreBFull = sr.FullB,
+ ScoreB = sr.SumB,
+ ScoreCFull = sr.FullC,
+ ScoreC = sr.SumC,
+ ScoreSumFull = sr.FullA + sr.FullB + sr.FullC,
+ ScoreSum = sr.SumA + sr.SumB + sr.SumC,
+ ExamResult = sr.ExamStatus
+ },
+ Attachments = p.Documents.Select(a => new
+ {
+ FileName = a.DocumentFile.FileName,
+ DocumentId = a.DocumentFile.Id
+ })
+ })
+ .FirstOrDefaultAsync();
+
+ return Success(data);
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
+ #endregion
+
+ #region " For CMS "
+
+ [HttpGet("competitive")]
+ [AllowAnonymous]
+ public IActionResult GetPeriodForCMS()
+ {
+ try
+ {
+ var periods = _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Select(r => new
+ {
+ id = r.Id,
+ title = $"{r.Name} ครั้งที่ {r.Round}/{r.Year.Value.ToThaiYear()}",
+ category = "สำนักงาน ก.ก.",
+ category_id = 1,
+ announcement_startDate = r.AnnouncementStartDate == null ? "" : r.AnnouncementStartDate.ToString("yyyy-mm-dd"),
+ announcement_endDate = r.AnnouncementEndDate == null ? "" : r.AnnouncementEndDate.ToString("yyyy-MM-dd"),
+ announcementExam = true,
+ register_startDate = r.RegisterStartDate == null ? "" : r.RegisterStartDate.ToString("yyyy-MM-dd"),
+ register_endDate = r.RegisterEndDate == null ? "" : r.RegisterEndDate.ToString("yyyy-MM-dd"),
+ payment_startDate = r.PaymentStartDate == null ? "" : r.PaymentStartDate.ToString("yyyy-MM-dd"),
+ payment_endDate = r.PaymentEndDate == null ? "" : r.PaymentEndDate.ToString("yyyy-MM-dd"),
+ exam_date = r.ExamDate == null ? "" : r.ExamDate.ToString("yyyy-MM-dd")
+
+ })
+ .ToList();
+
+ return Ok(periods);
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ #endregion
+
+ #region " Export Excel "
+
+ [HttpGet("export/exam/{id:length(36)}")]
+ public async Task> ExportExamAsync(Guid id)
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.Disables)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (data == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ var header = $"{data.Name} ครั้งที่ {data.Round}/{data.Year.Value.ToThaiYear()}";
+
+ var template_dir = Path.Combine(_webHostEnvironment.ContentRootPath, "Templates");
+
+ var template_file = Path.Combine(template_dir, "ExamList.xlsx");
+
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var exportFile = Path.Combine(tmpDir, $"ExamList_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
+ try
+ {
+ // copy template
+ System.IO.File.Copy(template_file, exportFile);
+
+ using (var excel = new ExcelPackage(new FileInfo(exportFile)))
+ {
+ var workSheet = excel.Workbook.Worksheets[0];
+
+
+ workSheet.Cells[1, 2].Value = header;
+ var disables = data.Disables.OrderBy(x => x.ExamId).ToList();
+
+ var row = 4; // start at row 4
+ foreach (var item in disables)
+ {
+ workSheet.Cells[row, 1].Value = item.ExamId;
+ workSheet.Cells[row, 2].Value = item.CitizenId;
+ workSheet.Cells[row, 3].Value = $"{item.Prefix}{item.FirstName} {item.LastName}";
+ workSheet.Cells[row, 4].Value = item.PositionName;
+
+ row++;
+ }
+
+ excel.Save();
+
+ using (FileStream fs = new FileStream(exportFile, FileMode.Open, FileAccess.Read))
+ {
+ byte[] bytes = System.IO.File.ReadAllBytes(exportFile);
+ fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length));
+ fs.Close();
+
+ var fname = Path.GetFileName(exportFile);
+
+ Response.Headers["Content-Disposition"] = $"inline; filename={fname}";
+
+ var ret = new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ {
+ FileDownloadName = fname
+ };
+
+ return ret;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ return Error(ex, "ไม่สามารถส่งออกรายชื่อผู้มีสิทธิ์สอบได้!!");
+ }
+ finally
+ {
+ if (System.IO.File.Exists(exportFile))
+ System.IO.File.Delete(exportFile);
+ }
+ }
+
+ [HttpGet("export/pass-exam/{id:length(36)}")]
+ public async Task> ExportPassExamAsync(Guid id)
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.Disables)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ var data_pass = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (data == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ if (data_pass == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ var header = $"{data.Name} ครั้งที่ {data.Round}/{data.Year.Value.ToThaiYear()}";
+
+ var template_dir = Path.Combine(_webHostEnvironment.ContentRootPath, "Templates");
+
+ var template_file = Path.Combine(template_dir, "PassAExamList.xlsx");
+
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var exportFile = Path.Combine(tmpDir, $"PassExamList_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
+
+ try
+ {
+ var result = (from r in data.Disables.ToList()
+ join s in data_pass.ScoreImport.Scores.Where(x => x.AStatus == "ผ่าน").ToList() on r.ExamId equals s.ExamId
+ select new
+ {
+ r.ExamId,
+ r.CitizenId,
+ r.Prefix,
+ r.FirstName,
+ r.LastName,
+ s.FullA,
+ s.SumA,
+ s.AStatus,
+
+ }).ToList();
+
+ // copy template
+ System.IO.File.Copy(template_file, exportFile);
+
+ using (var excel = new ExcelPackage(new FileInfo(exportFile)))
+ {
+ var workSheet = excel.Workbook.Worksheets[0];
+
+
+ workSheet.Cells[1, 2].Value = header;
+ var disables = data.Disables.OrderBy(x => x.ExamId).ToList();
+
+ var row = 4; // start at row 4
+ foreach (var item in result)
+ {
+ workSheet.Cells[row, 1].Value = item.ExamId;
+ workSheet.Cells[row, 2].Value = item.CitizenId;
+ workSheet.Cells[row, 3].Value = $"{item.Prefix}{item.FirstName} {item.LastName}";
+ workSheet.Cells[row, 4].Value = item.FullA;
+ workSheet.Cells[row, 5].Value = item.SumA;
+ workSheet.Cells[row, 6].Value = item.AStatus;
+
+ row++;
+ }
+
+ excel.Save();
+
+ using (FileStream fs = new FileStream(exportFile, FileMode.Open, FileAccess.Read))
+ {
+ byte[] bytes = System.IO.File.ReadAllBytes(exportFile);
+ fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length));
+ fs.Close();
+
+ var fname = Path.GetFileName(exportFile);
+
+ Response.Headers["Content-Disposition"] = $"inline; filename={fname}";
+
+ var ret = new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ {
+ FileDownloadName = fname
+ };
+
+ return ret;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ return Error(ex, "ไม่สามารถส่งออกรายชื่อผู้สอบผ่านได้!!");
+ }
+ finally
+ {
+ if (System.IO.File.Exists(exportFile))
+ System.IO.File.Delete(exportFile);
+ }
+ }
+
+ [HttpGet("export/pass/{id:length(36)}")]
+ public async Task> ExportPassExamResultAsync(Guid id)
+ {
+ var data = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.Disables)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ var data_pass = await _context.PeriodExams.AsQueryable()
+ .Where(x => x.CheckDisability == true)
+ .Include(x => x.ScoreImport)
+ .ThenInclude(x => x.Scores)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (data == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ if (data_pass == null)
+ return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
+
+ var header = $"{data.Name} ครั้งที่ {data.Round}/{data.Year.Value.ToThaiYear()}";
+
+ var template_dir = Path.Combine(_webHostEnvironment.ContentRootPath, "Templates");
+
+ var template_file = Path.Combine(template_dir, "PassExamList.xlsx");
+
+ var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
+ if (!Directory.Exists(tmpDir))
+ Directory.CreateDirectory(tmpDir);
+
+ var exportFile = Path.Combine(tmpDir, $"PassExamList_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
+
+ try
+ {
+ var result = (from r in data.Disables.ToList()
+ join s in data_pass.ScoreImport.Scores.Where(x => x.ExamStatus == "ผ่าน").ToList() on r.ExamId equals s.ExamId
+ select new
+ {
+ r.ExamId,
+ r.CitizenId,
+ r.Prefix,
+ r.FirstName,
+ r.LastName,
+ Full = s.FullA + s.FullB + s.FullC,
+ Sum = s.SumA + s.SumB + s.SumC,
+ Status = s.ExamStatus,
+ r.PositionName,
+ s.Number
+ }).ToList();
+
+ // copy template
+ System.IO.File.Copy(template_file, exportFile);
+
+ using (var excel = new ExcelPackage(new FileInfo(exportFile)))
+ {
+ var workSheet = excel.Workbook.Worksheets[0];
+
+
+ workSheet.Cells[1, 2].Value = header;
+ var disables = data.Disables.OrderBy(x => x.ExamId).ToList();
+
+ var row = 4; // start at row 4
+ foreach (var item in result)
+ {
+ workSheet.Cells[row, 1].Value = item.ExamId;
+ workSheet.Cells[row, 2].Value = item.CitizenId;
+ workSheet.Cells[row, 3].Value = $"{item.Prefix}{item.FirstName} {item.LastName}";
+ workSheet.Cells[row, 4].Value = item.Full;
+ workSheet.Cells[row, 5].Value = item.Sum;
+ workSheet.Cells[row, 6].Value = item.Status;
+ workSheet.Cells[row, 7].Value = item.Number;
+ workSheet.Cells[row, 8].Value = item.PositionName;
+
+ row++;
+ }
+
+ excel.Save();
+
+ using (FileStream fs = new FileStream(exportFile, FileMode.Open, FileAccess.Read))
+ {
+ byte[] bytes = System.IO.File.ReadAllBytes(exportFile);
+ fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length));
+ fs.Close();
+
+ var fname = Path.GetFileName(exportFile);
+
+ Response.Headers["Content-Disposition"] = $"inline; filename={fname}";
+
+ var ret = new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ {
+ FileDownloadName = fname
+ };
+
+ return ret;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ return Error(ex, "ไม่สามารถส่งออกรายชื่อผู้สอบผ่านได้!!");
+ }
+ finally
+ {
+ if (System.IO.File.Exists(exportFile))
+ System.IO.File.Delete(exportFile);
+ }
+ }
+
+ #endregion
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/Controllers/PeriodExamController.cs b/Controllers/PeriodExamController.cs
index 9ff61a1..7802a5e 100644
--- a/Controllers/PeriodExamController.cs
+++ b/Controllers/PeriodExamController.cs
@@ -670,6 +670,34 @@ namespace BMA.EHR.Recurit.Exam.Service.Controllers
}
}
+ ///
+ /// โหลดผู้สมัครสอบ(รายละเอียด)
+ ///
+ /// รหัสรอบสมัคร
+ ///
+ /// เมื่อทำการอ่านโหลดผู้สมัครสอบ(รายละเอียด)สำเร็จ
+ /// ไม่ได้ Login เข้าระบบ
+ /// เมื่อเกิดข้อผิดพลาดในการทำงาน
+ [HttpGet("download/detail/{examId:length(36)}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(StatusCodes.Status500InternalServerError)]
+ public async Task> DownloadCandidateAllAsync(string examId)
+ {
+ try
+ {
+ var stream = await _periodExamService.DownloadCandidateAllAsync(examId);
+
+ string excelName = $"Candidate_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
+ return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
+ // return Success();
+ }
+ catch (Exception ex)
+ {
+ return Error(ex);
+ }
+ }
+
///
/// ข้อมูลตำแหน่งสมัครสอบ
/// รหัสรอบสมัคร
diff --git a/Core/GlobalMessages.cs b/Core/GlobalMessages.cs
index c67c8df..9e512c4 100644
--- a/Core/GlobalMessages.cs
+++ b/Core/GlobalMessages.cs
@@ -3,6 +3,7 @@
public class GlobalMessages
{
public const string Success = "Success";
+ public const string DataNotFound = "ไม่พบข้อมูลในระบบ";
public const string FileNotFoundOnServer = "ไม่พบไฟล์ในระบบ!!";
public const string CannotInsertToDatabase = "ไม่สามารถบันทึกลงฐานข้อมูลได้!!";
public const string InvalidRequestParam = "Request parameter ไม่ถูกต้อง!!";
diff --git a/Data/ApplicationDbContext.cs b/Data/ApplicationDbContext.cs
index dda6300..479e369 100644
--- a/Data/ApplicationDbContext.cs
+++ b/Data/ApplicationDbContext.cs
@@ -1,4 +1,5 @@
using BMA.EHR.Recurit.Exam.Service.Models;
+using BMA.EHR.Recurit.Exam.Service.Models.Disables;
using BMA.EHR.Recurit.Exam.Service.Models.Documents;
using Microsoft.EntityFrameworkCore;
@@ -13,6 +14,13 @@ namespace BMA.EHR.Recurit.Exam.Service.Data
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
+ // disable relation setup
+ modelBuilder.Entity().HasMany(x => x.Disables).WithOne(x => x.PeriodExam).OnDelete(DeleteBehavior.Cascade);
+ modelBuilder.Entity().HasMany(x => x.Educations).WithOne(x => x.Disable).OnDelete(DeleteBehavior.Cascade);
+ modelBuilder.Entity().HasMany(x => x.Occupations).WithOne(x => x.Disable).OnDelete(DeleteBehavior.Cascade);
+ modelBuilder.Entity().HasMany(x => x.Addresses).WithOne(x => x.Disable).OnDelete(DeleteBehavior.Cascade);
+ modelBuilder.Entity().HasMany(x => x.Certificates).WithOne(x => x.Disable).OnDelete(DeleteBehavior.Cascade);
+ modelBuilder.Entity().HasMany(x => x.Payments).WithOne(x => x.Disable).OnDelete(DeleteBehavior.Cascade);
}
// public DbSet Prefixes { get; set; }
@@ -55,5 +63,25 @@ namespace BMA.EHR.Recurit.Exam.Service.Data
public DbSet CMSGovernments { get; set; }
+ public DbSet Disables { get; set; }
+
+ public DbSet DisableAddresses { get; set; }
+
+ public DbSet DisableOccupations { get; set; }
+
+ public DbSet DisableCertificates { get; set; }
+
+ public DbSet DisableEducations { get; set; }
+
+ public DbSet ScoreImports { get; set; }
+
+ public DbSet DisableScores { get; set; }
+
+ public DbSet DisablePayments { get; set; }
+
+ public DbSet DisableDocuments { get; set; }
+
+ public DbSet DisableImportHistories { get; set; }
+
}
}
diff --git a/Data/Migrations/ApplicationDbContextModelSnapshot.cs b/Data/Migrations/ApplicationDbContextModelSnapshot.cs
index 8c87867..d7899de 100644
--- a/Data/Migrations/ApplicationDbContextModelSnapshot.cs
+++ b/Data/Migrations/ApplicationDbContextModelSnapshot.cs
@@ -572,6 +572,10 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
.HasColumnOrder(3)
.HasComment("สัญชาติ");
+ b.Property("Number")
+ .HasColumnType("longtext")
+ .HasComment("ลำดับที่สอบได้");
+
b.Property("OccupationCompany")
.HasColumnType("longtext")
.HasComment("สำนัก/บริษัท บริษัท");
@@ -681,11 +685,11 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.Property("RelationshipId")
.HasColumnType("char(36)")
- .HasComment("Id ศาสนา");
+ .HasComment("Id สถานภาพ");
b.Property("RelationshipName")
.HasColumnType("longtext")
- .HasComment("ศาสนา");
+ .HasComment("สถานภาพ");
b.Property("ResultB")
.HasColumnType("longtext")
@@ -882,6 +886,1014 @@ namespace BMA.EHR.Recurit.Exam.Service.Data.Migrations
b.ToTable("Careers");
});
+ modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.Disables.Disable", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("char(36)")
+ .HasColumnOrder(0)
+ .HasComment("PrimaryKey")
+ .HasAnnotation("Relational:JsonPropertyName", "id");
+
+ b.Property("ApplyDate")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CitizenCardExpireDate")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CitizenCardIssuer")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("CitizenId")
+ .IsRequired()
+ .HasMaxLength(13)
+ .HasColumnType("varchar(13)")
+ .HasComment("เลขประจำตัวประชาชน");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime(6)")
+ .HasColumnOrder(100)
+ .HasComment("สร้างข้อมูลเมื่อ");
+
+ b.Property("CreatedDate")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CreatedFullName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)")
+ .HasColumnOrder(104)
+ .HasComment("ชื่อ User ที่สร้างข้อมูล");
+
+ b.Property("CreatedUserId")
+ .IsRequired()
+ .HasMaxLength(40)
+ .HasColumnType("varchar(40)")
+ .HasColumnOrder(101)
+ .HasComment("User Id ที่สร้างข้อมูล");
+
+ b.Property("DateOfBirth")
+ .HasColumnType("datetime(6)");
+
+ b.Property("ExamId")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("varchar(50)");
+
+ b.Property("FirstName")
+ .IsRequired()
+ .HasMaxLength(150)
+ .HasColumnType("varchar(150)");
+
+ b.Property("Gendor")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("varchar(20)");
+
+ b.Property("Isspecial")
+ .IsRequired()
+ .HasMaxLength(1)
+ .HasColumnType("varchar(1)");
+
+ b.Property("LastName")
+ .IsRequired()
+ .HasMaxLength(150)
+ .HasColumnType("varchar(150)");
+
+ b.Property("LastUpdateFullName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)")
+ .HasColumnOrder(105)
+ .HasComment("ชื่อ User ที่แก้ไขข้อมูลล่าสุด");
+
+ b.Property("LastUpdateUserId")
+ .IsRequired()
+ .HasMaxLength(40)
+ .HasColumnType("varchar(40)")
+ .HasColumnOrder(103)
+ .HasComment("User Id ที่แก้ไขข้อมูลล่าสุด");
+
+ b.Property("LastUpdatedAt")
+ .HasColumnType("datetime(6)")
+ .HasColumnOrder(102)
+ .HasComment("แก้ไขข้อมูลล่าสุดเมื่อ");
+
+ b.Property("Marry")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("varchar(20)");
+
+ b.Property("ModifiedDate")
+ .HasColumnType("datetime(6)");
+
+ b.Property("National")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("PeriodExamId")
+ .HasColumnType("char(36)");
+
+ b.Property("PositionName")
+ .HasColumnType("longtext");
+
+ b.Property("Prefix")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("varchar(50)");
+
+ b.Property("Qualified")
+ .IsRequired()
+ .HasMaxLength(1)
+ .HasColumnType("varchar(1)");
+
+ b.Property("Race")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("RefNo")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("varchar(20)");
+
+ b.Property("Religion")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("Remark")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("PeriodExamId");
+
+ b.ToTable("Disables");
+ });
+
+ modelBuilder.Entity("BMA.EHR.Recurit.Exam.Service.Models.Disables.DisableAddress", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("char(36)")
+ .HasColumnOrder(0)
+ .HasComment("PrimaryKey")
+ .HasAnnotation("Relational:JsonPropertyName", "id");
+
+ b.Property("Address")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("Address1")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("Amphur")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("Amphur1")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime(6)")
+ .HasColumnOrder(100)
+ .HasComment("สร้างข้อมูลเมื่อ");
+
+ b.Property("CreatedFullName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("varchar(200)")
+ .HasColumnOrder(104)
+ .HasComment("ชื่อ User ที่สร้างข้อมูล");
+
+ b.Property("CreatedUserId")
+ .IsRequired()
+ .HasMaxLength(40)
+ .HasColumnType("varchar(40)")
+ .HasColumnOrder(101)
+ .HasComment("User Id ที่สร้างข้อมูล");
+
+ b.Property