Add github action script and fixbug

This commit is contained in:
Suphonchai Phoonsawat 2023-04-06 16:38:26 +07:00
parent f2dcf9bb49
commit 4c0ae730df
49 changed files with 6687 additions and 338 deletions

View file

@ -1,5 +1,8 @@
using Amazon.S3.Model;
using BMA.EHR.Extensions;
using BMA.EHR.Recruit.Service.Core;
using BMA.EHR.Recruit.Service.Data;
using BMA.EHR.Recruit.Service.Extensions;
using BMA.EHR.Recruit.Service.Models.Recruits;
using BMA.EHR.Recruit.Service.Requests.Recruits;
using BMA.EHR.Recruit.Service.Responses;
@ -7,7 +10,12 @@ using BMA.EHR.Recruit.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.Text;
@ -256,8 +264,32 @@ namespace BMA.EHR.Recruit.Service.Controllers
try
{
var data = await _context.RecruitImports.AsQueryable()
.Include(x => x.ImportFile)
.Include(x => x.Recruits)
.Include(x => x.ScoreImport)
.ThenInclude(x => x.ImportFile)
.Include(x => x.ScoreImport)
.ThenInclude(x => x.Scores)
.OrderByDescending(x => x.Year)
.ThenByDescending(x => x.Order)
.Select(x => new
{
x.Id,
x.Year,
x.Name,
x.Order,
ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
ExamCount = x.Recruits.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);
@ -384,6 +416,10 @@ namespace BMA.EHR.Recruit.Service.Controllers
.Include(x => x.Recruits)
.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.RecruitImports.Remove(data);
@ -399,6 +435,649 @@ namespace BMA.EHR.Recruit.Service.Controllers
#endregion
#region " Candidate Files "
/// <summary>
/// แสดงข้อมูลสำหรับหน้าจอ รายการนำเข้าข้อมูลผู้สมัครสอบแข่งขัน
/// </summary>
/// <returns></returns>
/// <response code="200">เมื่อแสดงรายการข้อมูลสำเร็จ</response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("candidate")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetCandidateFilesAsync()
{
try
{
var data = await _context.RecruitImports.AsQueryable()
.Include(x => x.ImportFile)
.Include(x => x.Recruits)
.Include(x => x.ScoreImport)
.ThenInclude(x => x.ImportFile)
.Include(x => x.ScoreImport)
.ThenInclude(x => x.Scores)
.OrderByDescending(x => x.Year)
.ThenByDescending(x => x.Order)
.Select(x => new
{
x.Id,
x.Year,
x.Name,
x.Order,
ImportDate = x.CreatedAt.Date.ToThaiShortDate(),
ExamCount = x.Recruits.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);
}
}
/// <summary>
/// นำเข้ารายชื่อผู้สมัครสอบแข่งขัน
/// </summary>
/// <returns></returns>
/// <response code="200">เมื่อทำนำเข้าข้อมูลสำเร็จ</response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost("candidate"), DisableRequestSizeLimit]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> ImportCandidateFileAsync([FromForm] PostRecruitImportRequest 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 RecruitImport
{
Year = req.Year,
Order = req.Order,
Name = req.Name,
ImportFile = doc,
//Recruits = new List<Models.Recruits.Recruit>(),
};
await _context.RecruitImports.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<string>();
if (cell1 == "" || cell1 == null) break;
var r = new Models.Recruits.Recruit();
r.ExamId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ExamID)]?.GetValue<string>();
r.CitizenId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalID)]?.GetValue<string>();
r.Prefix = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Prefix)]?.GetValue<string>();
r.FirstName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.FirstName)]?.GetValue<string>();
r.LastName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.LastName)]?.GetValue<string>();
r.Gendor = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Gender)]?.GetValue<string>();
r.National = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.National)]?.GetValue<string>().IsNull("");
r.Race = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Race)]?.GetValue<string>().IsNull("");
r.Religion = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Religion)]?.GetValue<string>().IsNull("");
r.DateOfBirth = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.DateOfBirth)]?.GetValue<string>().ToDateTime(DateTimeFormat.Ymd, "-"));
r.Marry = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Marry)]?.GetValue<string>();
r.Isspecial = "N";
r.CitizenCardIssuer = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardIssue)]?.GetValue<string>();
r.CitizenCardExpireDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PersonalCardExpireDate)]?.GetValue<string>().ToDateTime(DateTimeFormat.Ymd, "-"));
r.ApplyDate = (DateTime)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ApplyDate)]?.GetValue<DateTime>();
// address
r.Addresses.Add(new RecruitAddress()
{
Address = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address)]?.GetValue<string>() ?? "",
Moo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo)]?.GetValue<string>() ?? "",
Soi = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi)]?.GetValue<string>() ?? "",
Road = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road)]?.GetValue<string>() ?? "",
District = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District)]?.GetValue<string>() ?? "",
Amphur = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur)]?.GetValue<string>() ?? "",
Province = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Province)]?.GetValue<string>() ?? "",
ZipCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode)]?.GetValue<string>() ?? "",
Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Telephone)]?.GetValue<string>() ?? "",
Mobile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Mobile)]?.GetValue<string>() ?? "",
Address1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Address1)]?.GetValue<string>()??"",
Moo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Moo1)]?.GetValue<string>() ?? "",
Soi1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Soi1)]?.GetValue<string>() ?? "",
Road1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Road1)]?.GetValue<string>() ?? "",
District1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.District1)]?.GetValue<string>() ?? "",
Amphur1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amphur1)]?.GetValue<string>() ?? "",
Province1 = "",
ZipCode1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ZipCode1)]?.GetValue<string>() ?? "",
});
// payment
r.Payments.Add(new RecruitPayment()
{
PaymentId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.PaymentID)]?.GetValue<string>() ?? "",
CompanyCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CompanyCode)]?.GetValue<string>() ?? "",
TextFile = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TextFile)]?.GetValue<string>() ?? "",
BankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BankCode)]?.GetValue<string>() ?? "",
AccountNumber = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.AccouontNumer)]?.GetValue<string>() ?? "",
TransDate = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransDate)]?.GetValue<string>() ?? "",
TransTime = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TransTime)]?.GetValue<string>() ?? "",
CustomerName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CustomerName)]?.GetValue<string>() ?? "",
RefNo1 = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.RefNo1)]?.GetValue<string>() ?? "",
TermBranch = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TermBranch)]?.GetValue<string>() ?? "",
TellerId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.TellerID)]?.GetValue<string>() ?? "",
CreditDebit = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CreditDebit)]?.GetValue<string>() ?? "",
PaymentType = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Type)]?.GetValue<string>() ,
ChequeNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChequeNo)]?.GetValue<string>() ?? "",
Amount = (decimal)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Amount)]?.GetValue<decimal>(),
ChqueBankCode = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.ChqBankCode)]?.GetValue<string>() ?? ""
});
// occupation
r.Occupations.Add(new RecruitOccupation()
{
Occupation = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Occupation)]?.GetValue<string>() ?? "",
Position = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Position)]?.GetValue<string>()??"",
Workplace = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Workplace)]?.GetValue<string>() ?? "",
Telephone = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkplaceTelephone)]?.GetValue<string>() ?? "",
WorkAge = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.WorkAge)]?.GetValue<string>() ?? "",
});
// certificate
r.Certificates.Add(new RecruitCertificate()
{
CertificateNo = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateNo)]?.GetValue<string>() ?? "",
Description = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateDesc)]?.GetValue<string>() ?? "",
IssueDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateIssueDate)]?.GetValue<string>().ToDateTime(DateTimeFormat.Ymd, "-")),
ExpiredDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.CertificateExpireDate)]?.GetValue<string>().ToDateTime(DateTimeFormat.Ymd, "-"))
});
r.Educations.Add(new RecruitEducation()
{
Degree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Degree)]?.GetValue<string>() ?? "",
Major = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.Major)]?.GetValue<string>() ?? "",
MajorGroupId = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupID)]?.GetValue<string>() ?? "",
MajorGroupName = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.MajorGroupName)]?.GetValue<string>() ?? "",
University = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.University)]?.GetValue<string>() ?? "",
GPA = (double)workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.GPA)]?.GetValue<double>(),
Specialist = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.SpecialList)]?.GetValue<string>() ?? "",
HighDegree = workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.HighDegree)]?.GetValue<string>() ?? "",
BachelorDate = Convert.ToDateTime(workSheet?.Cells[row, GetColumnIndex(cols, CandidateFileHeader.BachelorDate)]?.GetValue<string>().ToDateTime(DateTimeFormat.Ymd, "-"))
});
r.RecruitImport = imported;
_context.Recruits.Add(r);
//imported.Recruits.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);
}
}
/// <summary>
/// ลบข้อมูลนำข้อมูลผู้สมัครสอบแข่งขัน
/// </summary>
/// <param name="id">รหัสรอบการสอบแข่งขัน</param>
/// <returns></returns>
/// <response code="200">เมื่อทำนำเข้าข้อมูลสำเร็จ</response>
/// <response code="400">ค่าตัวแปรที่ส่งมาไม่ถูกต้อง</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("candidate/{id:length(36)}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> DeleteCandidateFileAsync(Guid id)
{
try
{
var data = await _context.RecruitImports.AsQueryable()
.Include(x => x.ImportFile)
.Include(x => x.Recruits)
.ThenInclude(x => x.Addresses)
.Include(x => x.Recruits)
.ThenInclude(x => x.Occupations)
.Include(x => x.Recruits)
.ThenInclude(x => x.Certificates)
.Include(x => x.Recruits)
.ThenInclude(x => x.Educations)
.Include(x => x.Recruits)
.ThenInclude(x => x.Payments)
.Include(x => x.Recruits)
.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.RecruitImports.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);
}
}
#endregion
#region " Score File "
[HttpPost("score/{id:length(36)}"), DisableRequestSizeLimit]
public async Task<ActionResult<ResponseObject>> 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.RecruitImports.AsQueryable()
.Include(x => x.ScoreImport)
.FirstOrDefaultAsync(x => x.Id == id);
if (rec_import == null)
return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound);
if (rec_import.ScoreImport != null)
return Error($"มีการนำเข้าข้อมูลเอาไว้ก่อนหน้านี้แล้ว ไม่สามารถนำเข้าได้!!");
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 new file import
var imported = new ScoreImport
{
Year = rec_import.Year,
ImportFile = doc,
Scores = new List<RecruitScore>()
};
// 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<string>();
if (cell1 == "" || cell1 == null) break;
var r = new RecruitScore();
r.ExamId = workSheet?.Cells[row, 2]?.GetValue<string>();
r.FullA = (int)workSheet?.Cells[7, 7]?.GetValue<string>().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
r.SumA = workSheet?.Cells[row, 7]?.GetValue<string>() == "ขส." ? 0 : (int)workSheet?.Cells[row, 7]?.GetValue<string>().Replace(".00", "").ToInteger();
r.PercentageA = workSheet?.Cells[row, 8]?.GetValue<string>() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 8]?.GetValue<double>();
r.FullB = (int)workSheet?.Cells[7, 12]?.GetValue<string>().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
r.SumB = workSheet?.Cells[row, 12]?.GetValue<string>() == "ขส." ? 0 : (int)workSheet?.Cells[row, 12]?.GetValue<string>().Replace(".00", "").ToInteger();
r.PercentageB = workSheet?.Cells[row, 13]?.GetValue<string>() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 13]?.GetValue<double>();
r.SumAB = workSheet?.Cells[row, 15]?.GetValue<string>() == "ขส." ? 0 : (int)workSheet?.Cells[row, 15]?.GetValue<string>().Replace(".00", "").ToInteger();
r.ABStatus = workSheet?.Cells[row, 17]?.GetValue<string>();
r.FullC = (int)workSheet?.Cells[7, 20]?.GetValue<string>().Replace("(", "").Replace(")", "").Replace("คะแนน", "").Trim().ToInteger();
r.SumC = workSheet?.Cells[row, 20]?.GetValue<string>() == "ขส." ? 0 : (int)workSheet?.Cells[row, 20]?.GetValue<string>().Replace(".00", "").ToInteger();
r.PercentageC = workSheet?.Cells[row, 21]?.GetValue<string>() == "ขส." ? 0.0 : (double)workSheet?.Cells[row, 21]?.GetValue<double>();
r.ExamStatus = workSheet?.Cells[row, 24]?.GetValue<string>();
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)
{
return Error(ex);
}
finally
{
if (System.IO.File.Exists(importFile))
System.IO.File.Delete(importFile);
}
}
#endregion
#region " Exam Information "
/// <summary>
/// แสดงข้อมูลสำหรับหน้าจอ : รายการข้อมูลผู้สมัครสอบ
/// </summary>
[HttpGet("exam")]
public async Task<ActionResult<ResponseObject>> GetExamResultAsync()
{
try
{
var data = await _context.RecruitImports.AsQueryable()
.OrderByDescending(x => x.Year)
.ThenByDescending(x => x.Order)
.Select(x => new
{
x.Id,
ExamYear = x.Year.ToThaiYear(),
ExamOrder = x.Order,
Description = x.Name,
})
.ToListAsync();
var result = new List<dynamic>();
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<ResponseObject> GetExamResultById([FromBody] RecruitExamRequest req, Guid id)
{
try
{
var p_Id = new MySqlParameter("@id", id);
var data = new List<dynamic>();
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 recruit_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(),
});
}
}
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 recruit_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,
});
}
catch (Exception ex)
{
return Error(ex);
}
}
[HttpGet("exam/{id:length(36)}/{examId}")]
public async Task<ActionResult<ResponseObject>> GetExamResultByPersonAsync(Guid id, string examId)
{
try
{
var data = await _context.Recruits.AsQueryable()
.Include(x => x.RecruitImport)
.Include(x => x.Documents)
.ThenInclude(x => x.DocumentFile)
.Where(x => x.RecruitImport.Id == id)
.Where(x => x.ExamId == examId)
.Join(_context.RecruitScores.AsQueryable()
.Include(x => x.ScoreImport),
rc => new { rc.RecruitImport.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 = _recruitService.CheckValidCertificate(p.Certificates.First().IssueDate, 5) ? "มีคุณสมบัติ" : "ไม่มีคุณสมบัติ",
IsSpecial = p.Isspecial,
Remark = p.Remark,
Score = sr == null ? 0 : sr.SumA + sr.SumB + sr.SumC,
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
#endregion
}
}