diff --git a/Controllers/ProfileReportController.cs b/Controllers/ProfileReportController.cs index 952fbe2..7c7feaf 100644 --- a/Controllers/ProfileReportController.cs +++ b/Controllers/ProfileReportController.cs @@ -17,973 +17,973 @@ using Telerik.Reporting.Processing; namespace BMA.EHR.Report.Service.Controllers { - [Route("api/v{version:apiVersion}/report/profile")] - [ApiVersion("1.0")] - [ApiController] - [Produces("application/json")] - //[Authorize] - [SwaggerTag("รายงานระบบทะเบียนประวัติ")] - public class ProfileReportController : BaseController - { - #region " Fields " - - private readonly EHRDbContext _context; - private readonly IWebHostEnvironment _hostingEnvironment; - private readonly IConfiguration _configuration; - private readonly string space = "ㅤ"; - private readonly ProfileService _profileService; - private readonly MinIOService _minioService; - - - #endregion - - #region " Constructor and Destructor " - - public ProfileReportController(EHRDbContext context, - IWebHostEnvironment hostingEnvironment, - IConfiguration configuration, - ProfileService profileService, - MinIOService minioService) - { - this._context = context; - this._hostingEnvironment = hostingEnvironment; - this._configuration = configuration; - this._profileService = profileService; - this._minioService = minioService; - } - - #endregion - - #region " Methods " - - /// - /// แสดงประวัติการรับราชการแบบย่อ - /// - /// รหัสข้อมูลข้าราชการ - /// - /// เมื่อแสดงรายงานสำเร็จ - /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง - /// ไม่ได้ Login เข้าระบบ - /// เมื่อเกิดข้อผิดพลาดในการทำงาน - - [HttpGet("kp7-short/{id:length(36)}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public async Task> GetKp7ShortReport(Guid id) - { - try - { - var profile_salaries = (from ps in _context.ProfileSalaries - join pos in _context.PositionPaths - on ps.PositionId equals pos.Id - where ps.Profile.Id == id - select new - { - ProfileId = ps.Profile.Id, - PositionName = pos.Name, - ps.OcId, - SalaryDateAnnounce = ps.Date, - ps.Amount, - ps.PositionSalaryAmount - }).ToList(); - - var profiles = _context.Profiles.AsQueryable() - .Include(x => x.Avatar) - .Include(x => x.Salaries) - .Include(x => x.Educations) - .ToList(); - var prefixes = _context.Prefixes.ToList(); - var profile = (from p in profiles - join pf in prefixes on p.PrefixId equals pf.Id - where p.Id == id - select new - { - CitizenId = p.CitizenId, - Prefix = pf.Name, - p.FirstName, - p.LastName, - DateOfBirth = p.BirthDate.ToThaiShortDate(), - RegistrationAddress = p.RegistrationAddress, - RegistrationProvince = _context.Provinces.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationProvinceId)?.Name, - RegistrationDistrict = _context.Districts.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationDistrictId)?.Name, - RegistrationSubDistrict = _context.SubDistricts.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationSubDistrictId)?.Name, - RegistrationZipCode = p.RegistrationZipCode, - OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), - DateAppoint = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), - Salaries = profile_salaries, - SalaryAmount = p.Salaries.Count == 0 ? "-" - : $"{p.Salaries.OrderByDescending(s => s.Date.Value).FirstOrDefault().Amount.Value.ToString("#,##0")}", - Education = p.Educations.Count == 0 ? "-" - : $"{p.Educations.OrderByDescending(e => e.EndDate.Value.Year).FirstOrDefault().Degree} {p.Educations.OrderByDescending(e => e.EndDate.Value.Year).FirstOrDefault().Field}", - AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") - }).FirstOrDefault(); - // _context.PositionPaths.AsQueryable().FirstOrDefault(x => x.Id == p.PositionId)?.Name, - - var data = new List(); - var c = 1; - if (profile.Salaries.Count == 0) - { - var ret2 = new - { - CitizenId = profile.CitizenId, - Prefix = profile.Prefix, - FirstName = profile.FirstName, - LastName = profile.LastName, - DateOfBirth = profile.DateOfBirth, - RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", - SalaryAmount = profile.SalaryAmount, - Education = profile.Education, - AppointText = "", - SalaryDate = profile.DateAppoint, - PositionName = "", - OCFullPath = profile.OcFullPath - }; - data.Add(ret2); - } - var old_date = DateTime.Now; - var old_position = ""; - var old_ocid = Guid.NewGuid(); - dynamic ret; - - foreach (var s in profile.Salaries) - { - //if((old_date.Date != s.SalaryDateAnnounce.Value.Date)) - //{ - // old_date = s.SalaryDateAnnounce.Value; - // old_position= s.PositionName; - // old_ocid = s.OcId; - - // ret = new - // { - // CitizenId = profile.CitizenId, - // Prefix = profile.Prefix, - // FirstName = profile.FirstName, - // LastName = profile.LastName, - // DateOfBirth = profile.DateOfBirth, - // RegistrationAddress = profile.RegistrationAddress, - // SalaryAmount = profile.SalaryAmount, - // Education = profile.Education, - // AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", - // SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), - // PositionName = s.PositionName, - // OCFullPath = CoreCommandReport.GetOrganizationNameFullPath(s.OcId, false, false) - // }; - // data.Add(ret); - //} - if (old_position != s.PositionName) - { - old_date = s.SalaryDateAnnounce.Value; - old_position = s.PositionName; - old_ocid = s.OcId.Value; - ret = new - { - CitizenId = profile.CitizenId, - Prefix = profile.Prefix, - FirstName = profile.FirstName, - LastName = profile.LastName, - DateOfBirth = profile.DateOfBirth, - RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", - SalaryAmount = profile.SalaryAmount, - Education = profile.Education, - AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", - SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), - PositionName = s.PositionName, - OCFullPath = _profileService.GetOrganizationNameFullPath(s.OcId.Value, false, false) - }; - data.Add(ret); - } - else if (old_ocid != s.OcId) - { - old_date = s.SalaryDateAnnounce.Value; - old_position = s.PositionName; - old_ocid = s.OcId.Value; - ret = new - { - CitizenId = profile.CitizenId, - Prefix = profile.Prefix, - FirstName = profile.FirstName, - LastName = profile.LastName, - DateOfBirth = profile.DateOfBirth, - RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", - SalaryAmount = profile.SalaryAmount, - Education = profile.Education, - AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", - SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), - PositionName = s.PositionName, - OCFullPath = _profileService.GetOrganizationNameFullPath(s.OcId.Value, false, false), - - }; - data.Add(ret); - } - - c++; - } - - var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptShortKp7.trdp"); - - ReportPackager reportPackager = new ReportPackager(); - Telerik.Reporting.Report? report = null; - using (var sourceStream = System.IO.File.OpenRead(rptFile)) - { - report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); - } - - report.DataSource = data; - - if (profile.AvatarId != "") - { - try - { - // Get avatar Image - var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.AvatarId))).FileContent; - var pictureBox = (Telerik.Reporting.PictureBox)report.Items["groupHeaderSection"].Items["picAvatar"]; - pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); - } - catch { } - } - - System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); - - InstanceReportSource instanceReportSource = new InstanceReportSource() - { - ReportDocument = report - }; - - - ReportProcessor reportProcessor = new ReportProcessor(_configuration); - RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); - - var content = result.DocumentBytes; - return File(content, "application/pdf", $"ประวัติการรับราชการอย่างย่อ_{profile.CitizenId}.pdf"); - - - - } - catch (Exception ex) - { - return Error(ex, "ไม่สามารถแสดงผลรายงานได้!!!"); - } - } - - /// - /// แสดงรายงาน กก.1 - /// - /// รหัสข้อมูลข้าราชการ - /// - /// เมื่อแสดงรายงานสำเร็จ - /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง - /// ไม่ได้ Login เข้าระบบ - /// เมื่อเกิดข้อผิดพลาดในการทำงาน - [HttpGet("kk1/{id:length(36)}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public async Task> GetKK1Report(Guid id) - { - try - { - var profile = (from p in _context.Profiles - join pf in _context.Prefixes on p.PrefixId equals pf.Id into p_pf_join - from p_pf in p_pf_join.DefaultIfEmpty() - join cpf in _context.Prefixes on p.CouplePrefixId equals cpf.Id into c_pf_join - from c_pf in c_pf_join.DefaultIfEmpty() - join fpf in _context.Prefixes on p.FatherPrefixId equals fpf.Id into f_pf_join - from f_pf in f_pf_join.DefaultIfEmpty() - join mpf in _context.Prefixes on p.MotherPrefixId equals mpf.Id into m_pf_join - from m_pf in m_pf_join.DefaultIfEmpty() - where p.Id == id - select new - { - p.CitizenId, - Prefix = p_pf == null ? "" : p_pf.Name, - p.FirstName, - p.LastName, - FullName = $"{p.FirstName} {p.LastName}", - BirthDay = p.BirthDate.Day, - BirthDayText = Convert.ToDecimal(p.BirthDate.Day).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), - BirthMonth = p.BirthDate.Month.ToThaiMonth(), - BirthYear = p.BirthDate.Year.ToThaiYear(), - BirthYearText = Convert.ToDecimal(p.BirthDate.Year.ToThaiYear()).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), - Address = "", - District = "", - Area = "", - Province = "", - Telephone = p.TelephoneNumber, - CouplePrefix = c_pf == null ? "" : c_pf.Name, - CoupleFullName = $"{p.CoupleFirstName} {p.CoupleLastName}".Trim(), - FatherPrefix = f_pf == null ? "" : f_pf.Name, - FatherFullName = $"{p.FatherFirstName} {p.FatherLastName}".Trim(), - MotherPrefix = m_pf == null ? "" : m_pf.Name, - MotherFullName = $"{p.MotherFirstName} {p.MotherLastName}".Trim(), - OcId = p.OcId, - OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), - Division = "", - Institute = "", - StartDate = p.DateStart == null ? "" : p.DateStart.Value.ToThaiShortDate(), - AppointDate = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), - BirthDate = p.BirthDate.ToThaiShortDate(), - RetireDate = p.BirthDate.CalculateRetireDate().ToThaiShortDate(), - AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") - }).ToList(); - - if (!profile.Any()) - return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); - - // certificate - var cert = (from c in _context.ProfileCertificates.AsQueryable() - where c.Profile.Id == id - orderby c.IssueDate.Value.Year - select new - { - c.CertificateType, - c.Issuer, - c.CertificateNo, - IssueDate = c.IssueDate == null ? "" : c.IssueDate.Value.ToThaiShortDate() - }).ToList(); - - // add temp rows - while (cert.Count < 3) - { - cert.Add(new - { - CertificateType = "", - Issuer = "", - CertificateNo = "", - IssueDate = "" - }); - } - - // training - var training = (from t in _context.ProfileTrainings.AsQueryable() - where t.Profile.Id == id - orderby t.StartDate.Value.Year - select new - { - Institute = t.Host, - Start = t.StartDate == null ? "" : t.StartDate.Value.Year.ToThaiYear().ToString(), - End = t.EndDate == null ? "" : t.EndDate.Value.Year.ToThaiYear().ToString(), - Level = "", - Degree = t.Subject, - Field = "" - }).ToList(); - - while (training.Count < 3) - { - training.Add(new - { - Institute = "", - Start = "", - End = "", - Level = "", - Degree = "", - Field = "" - }); - } - - // disciplines - var discipline = (from d in _context.ProfileDisciplines.AsQueryable() - where d.Profile.Id == id - orderby d.Date.Value.Year - select new - { - DisciplineYear = d.Date == null ? "" : d.Date.Value.Year.ToThaiYear().ToString(), - DisciplineDetail = d.Detail, - RefNo = d.RefCommandNo - }).ToList(); - - while (discipline.Count < 3) - { - discipline.Add(new - { - DisciplineYear = "", - DisciplineDetail = "", - RefNo = "" - }); - } - - // education - var education = (from e in _context.ProfileEducations.AsQueryable() - where e.Profile.Id == id - orderby e.StartDate.Value.Year - select new - { - Institute = e.Institute, - Start = e.StartDate == null ? "" : e.StartDate.Value.Year.ToThaiYear().ToString(), - End = e.EndDate == null ? "" : e.EndDate.Value.Year.ToThaiYear().ToString(), - Level = e.EducationLevel, - Degree = e.Degree, - Field = e.Field.Trim() == "-" ? "" : e.Field - }).ToList(); - - while (education.Count < 4) - { - education.Add(new - { - Institute = "", - Start = "", - End = "", - Level = "", - Degree = "", - Field = "" - }); - } - - var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Page1.trdp"); - - ReportPackager reportPackager = new ReportPackager(); - Telerik.Reporting.Report? report = null; - using (var sourceStream = System.IO.File.OpenRead(rptFile)) - { - report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); - } - report.DataSource = profile; - - // binding to table - var tblCertificate = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblCertificate"]; - tblCertificate.DataSource = cert; - - var tblTraining = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblTraining"]; - tblTraining.DataSource = training; - - var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; - tblDiscipline.DataSource = discipline; - - var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; - tblEducation.DataSource = education; - - if (profile.First().AvatarId != "") - { - try - { - // Get avatar Image - var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.First().AvatarId))).FileContent; - var pictureBox = (Telerik.Reporting.PictureBox)report.Items["pageFooterSection1"].Items["picAvatar"]; - pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); - } - catch { } - } - - System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); - - InstanceReportSource instanceReportSource = new InstanceReportSource() - { - ReportDocument = report - }; - - - ReportProcessor reportProcessor = new ReportProcessor(_configuration); - RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); - - // byte array waiting for merge pdf - var content = result.DocumentBytes; - - // page2 - var profile2 = (from p in _context.Profiles - join pf in _context.Prefixes on p.PrefixId equals pf.Id - where p.Id == id - select new - { - FullName = $"{pf.Name}{p.FirstName} {p.LastName}", - OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), - }).FirstOrDefault(); - - var salary = (from s in _context.ProfileSalaries - join pos in _context.PositionPaths on s.PositionId equals pos.Id - join pos_no in _context.PositionNumbers on s.PosNoId equals pos_no.Id - join pos_lv in _context.PositionLevels on s.PositionLevelId equals pos_lv.Id - join pos_type in _context.PositionTypes on s.PositionTypeId equals pos_type.Id - where s.Profile.Id == id - orderby s.Date.Value - select new - { - SalaryDate = s.Date == null ? "" : s.Date == new DateTime(1, 1, 1) ? "" : s.Date.Value.ToThaiShortDate(), - Position = s.SalaryClass, - PosNo = pos_no.Name, - Rank = pos_lv.Name, - Salary = s.Amount == null ? "" : s.Amount.ToString().ToInteger().ToNumericText(), - RefAll = s.SalaryRef, - PositionType = pos_type.Name, - PositionLevel = pos_lv.Name, - PositionAmount = s.PositionSalaryAmount == null ? "" : s.PositionSalaryAmount.Value.ToString().ToInteger().ToNumericText(), - FullName = profile2.FullName, - OcFullPath = profile2.OcFullPath - }).ToList(); - - //while (salary.Count < 60) - //{ - // salary.Add(new - // { - // SalaryDate = "", - // Position = "", - // PosNo = "", - // Rank = "", - // Salary = "", - // RefAll = "", - // PositionType = "", - // PositionLevel = "", - // PositionAmount = "", - // FullName = profile2.FullName, - // OcFullPath = profile2.OcFullPath - // }); - //} - - var rptFile2 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Page2.trdp"); - - ReportPackager reportPackager2 = new ReportPackager(); - Telerik.Reporting.Report? report2 = null; - using (var sourceStream = System.IO.File.OpenRead(rptFile2)) - { - report2 = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); - } - - report2.ReportParameters["FullName"].Value = profile2.FullName; - report2.ReportParameters["OcFullPath"].Value = profile2.OcFullPath; - - // binding to table - var tblSalary = (Telerik.Reporting.Table)report2.Items["detailSection1"].Items["tblSalary"]; - tblSalary.DataSource = salary; - - System.Collections.Hashtable deviceInfo2 = new System.Collections.Hashtable(); - - InstanceReportSource instanceReportSource2 = new InstanceReportSource() - { - ReportDocument = report2 - }; - - - ReportProcessor reportProcessor2 = new ReportProcessor(_configuration); - RenderingResult result2 = reportProcessor2.RenderReport("PDF", instanceReportSource2, deviceInfo2); - - // byte array waiting for merge pdf - var content2 = result2.DocumentBytes; - - // merge pdf - using (MemoryStream ms = new MemoryStream()) - { - using (PdfDocument pdf = new PdfDocument(new PdfWriter(ms).SetSmartMode(true))) - { - // Create reader from bytes - using (MemoryStream memoryStream = new MemoryStream(content)) - { - // Create reader from bytes - using (PdfReader reader = new PdfReader(memoryStream)) - { - PdfDocument srcDoc = new PdfDocument(reader); - srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); - } - } - - // Create reader from bytes - if (content2 != null) - { - using (MemoryStream memoryStream = new MemoryStream(content2)) - { - // Create reader from bytes - using (PdfReader reader = new PdfReader(memoryStream)) - { - PdfDocument srcDoc = new PdfDocument(reader); - srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); - } - } - } - - pdf.Close(); - } - - var fileContent = ms.ToArray(); - return File(fileContent, "application/pdf", $"กก_1_{id}.pdf"); - } - } - catch (Exception ex) - { - return Error(ex); - } - } - - - /// - /// แสดงรายงาน กพ.7 - /// - /// รหัสข้อมูลข้าราชการ - /// - /// เมื่อแสดงรายงานสำเร็จ - /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง - /// ไม่ได้ Login เข้าระบบ - /// เมื่อเกิดข้อผิดพลาดในการทำงาน - [HttpGet("kp7/{id:length(36)}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] - public async Task> GetKP7Report(Guid id) - { - try - { - var profile = (from p in _context.Profiles - join pf in _context.Prefixes on p.PrefixId equals pf.Id into p_pf_join - from p_pf in p_pf_join.DefaultIfEmpty() - join cpf in _context.Prefixes on p.CouplePrefixId equals cpf.Id into c_pf_join - from c_pf in c_pf_join.DefaultIfEmpty() - join fpf in _context.Prefixes on p.FatherPrefixId equals fpf.Id into f_pf_join - from f_pf in f_pf_join.DefaultIfEmpty() - join mpf in _context.Prefixes on p.MotherPrefixId equals mpf.Id into m_pf_join - from m_pf in m_pf_join.DefaultIfEmpty() - where p.Id == id - select new - { - p.CitizenId, - Prefix = p_pf == null ? "" : p_pf.Name, - p.FirstName, - p.LastName, - FullName = $"{p.FirstName} {p.LastName}", - BirthDay = p.BirthDate.Day, - BirthDayText = Convert.ToDecimal(p.BirthDate.Day).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), - BirthMonth = p.BirthDate.Month.ToThaiMonth(), - BirthYear = p.BirthDate.Year.ToThaiYear(), - BirthYearText = Convert.ToDecimal(p.BirthDate.Year.ToThaiYear()).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), - Address = "", - District = "", - Area = "", - Province = "", - Telephone = p.TelephoneNumber, - CouplePrefix = c_pf == null ? "" : c_pf.Name, - CoupleFullName = $"{p.CoupleFirstName} {p.CoupleLastName}".Trim(), - FatherPrefix = f_pf == null ? "" : f_pf.Name, - FatherFullName = $"{p.FatherFirstName} {p.FatherLastName}".Trim(), - MotherPrefix = m_pf == null ? "" : m_pf.Name, - MotherFullName = $"{p.MotherFirstName} {p.MotherLastName}".Trim(), - OcId = p.OcId, - OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), - Division = "", - Institute = "", - StartDate = p.DateStart == null ? "" : p.DateStart.Value.ToThaiShortDate(), - AppointDate = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), - BirthDate = p.BirthDate.ToThaiShortDate(), - RetireDate = p.BirthDate.CalculateRetireDate().ToThaiShortDate(), - AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") - }).ToList(); - - if (!profile.Any()) - return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); - - // certificate - var cert = (from c in _context.ProfileCertificates.AsQueryable() - where c.Profile.Id == id - orderby c.IssueDate.Value.Year - select new - { - c.CertificateType, - c.Issuer, - c.CertificateNo, - IssueDate = c.IssueDate == null ? "" : c.IssueDate.Value.ToThaiShortDate() - }).ToList(); - - // add temp rows - while (cert.Count < 3) - { - cert.Add(new - { - CertificateType = "", - Issuer = "", - CertificateNo = "", - IssueDate = "" - }); - } - - // training - var training = (from t in _context.ProfileTrainings.AsQueryable() - where t.Profile.Id == id - orderby t.StartDate.Value.Year - select new - { - Institute = t.Host, - Start = t.StartDate == null ? "" : t.StartDate.Value.Year.ToThaiYear().ToString(), - End = t.EndDate == null ? "" : t.EndDate.Value.Year.ToThaiYear().ToString(), - Level = "", - Degree = t.Subject, - Field = "" - }).ToList(); - - - - // disciplines - var discipline = (from d in _context.ProfileDisciplines.AsQueryable() - where d.Profile.Id == id - orderby d.Date.Value.Year - select new - { - DisciplineYear = d.Date == null ? "" : d.Date.Value.Year.ToThaiYear().ToString(), - DisciplineDetail = d.Detail, - RefNo = d.RefCommandNo - }).ToList(); - - while (discipline.Count < 3) - { - discipline.Add(new - { - DisciplineYear = "", - DisciplineDetail = "", - RefNo = "" - }); - } - - // nopaind - var nopaid = (from c in _context.ProfileNopaids.AsQueryable() - where c.Profile.Id == id - orderby c.Date.Value.Year - select new - { - Year = c.Date == null ? "" : c.Date.Value.Year.ToThaiYear().ToString(), - Detail = c.Detail, - RefNo = c.Reference - }).ToList(); - - while (nopaid.Count < 3) - { - nopaid.Add(new - { - Year = "", - Detail = "", - RefNo = "" - }); - } - - // education - var education = (from e in _context.ProfileEducations.AsQueryable() - where e.Profile.Id == id - orderby e.StartDate.Value.Year - select new - { - Institute = e.Institute, - Start = e.StartDate == null ? "" : e.StartDate.Value.Year.ToThaiYear().ToString(), - End = e.EndDate == null ? "" : e.EndDate.Value.Year.ToThaiYear().ToString(), - Level = e.EducationLevel, - Degree = e.Degree, - Field = e.Field.Trim() == "-" ? "" : e.Field - }).ToList(); - - var education_all = education.Union(training).ToList(); - - while (education_all.Count < 6) - { - education_all.Add(new - { - Institute = "", - Start = "", - End = "", - Level = "", - Degree = "", - Field = "" - }); - } - - var row = 0; - var education_report = new List(); - foreach (var e in education_all) - { - if (row % 2 == 0) - { - var last_row = education_report.Last(); - last_row.Institute2 = e.Institute; - last_row.Start2 = e.Start; - last_row.End2 = e.End; - last_row.Level2 = e.Level; - last_row.Degree2 = e.Degree; - last_row.Field2 = e.Field; - } - else - { - education_report.Add(new - { - Institute1 = e.Institute, - Start1 = e.Start, - End1 = e.End, - Level1 = e.Level, - Degree1 = e.Degree, - Field1 = e.Field, - Institute2 = "", - Start2 = "", - End2 = "", - Level2 = "", - Degree2 = "", - Field2 = "" - }); - } - row++; - } - - var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKP7_Page1.trdp"); - - ReportPackager reportPackager = new ReportPackager(); - Telerik.Reporting.Report? report = null; - using (var sourceStream = System.IO.File.OpenRead(rptFile)) - { - report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); - } - report.DataSource = profile; - - var tblNopaid = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblNopaid"]; - tblNopaid.DataSource = nopaid; - - var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; - tblDiscipline.DataSource = discipline; - - var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; - tblEducation.DataSource = education_report; - - if (profile.First().AvatarId != "") - { - try - { - // Get avatar Image - var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.First().AvatarId))).FileContent; - var pictureBox = (Telerik.Reporting.PictureBox)report.Items["pageFooterSection1"].Items["picAvatar"]; - pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); - } - catch { } - } - - System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); - - InstanceReportSource instanceReportSource = new InstanceReportSource() - { - ReportDocument = report - }; - - - ReportProcessor reportProcessor = new ReportProcessor(_configuration); - RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); - - // byte array waiting for merge pdf - var content = result.DocumentBytes; - - // page2 - var profile2 = (from p in _context.Profiles - join pf in _context.Prefixes on p.PrefixId equals pf.Id - where p.Id == id - select new - { - FullName = $"{pf.Name}{p.FirstName} {p.LastName}", - OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), - }).FirstOrDefault(); - - var salary = (from s in _context.ProfileSalaries - join pos in _context.PositionPaths on s.PositionId equals pos.Id - join pos_no in _context.PositionNumbers on s.PosNoId equals pos_no.Id - join pos_lv in _context.PositionLevels on s.PositionLevelId equals pos_lv.Id - join pos_type in _context.PositionTypes on s.PositionTypeId equals pos_type.Id - where s.Profile.Id == id - orderby s.Date.Value - select new - { - SalaryDate = s.Date == null ? "" : s.Date == new DateTime(1, 1, 1) ? "" : s.Date.Value.ToThaiShortDate(), - Position = s.SalaryClass, - PosNo = pos_no.Name, - Rank = pos_lv.Name, - Salary = s.Amount == null ? "" : s.Amount.ToString().ToInteger().ToNumericText(), - RefAll = s.SalaryRef, - PositionType = pos_type.Name, - PositionLevel = pos_lv.Name, - PositionAmount = s.PositionSalaryAmount == null ? "" : s.PositionSalaryAmount.Value.ToString().ToInteger().ToNumericText(), - FullName = profile2.FullName, - OcFullPath = profile2.OcFullPath - }).ToList(); - - while (salary.Count < 30) - { - salary.Add(new - { - SalaryDate = "", - Position = "", - PosNo = "", - Rank = "", - Salary = "", - RefAll = "", - PositionType = "", - PositionLevel = "", - PositionAmount = "", - FullName = profile2.FullName, - OcFullPath = profile2.OcFullPath - }); - } - - var rptFile2 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKP7_Page2.trdp"); - - ReportPackager reportPackager2 = new ReportPackager(); - Telerik.Reporting.Report? report2 = null; - using (var sourceStream = System.IO.File.OpenRead(rptFile2)) - { - report2 = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); - } - - report2.ReportParameters["FullName"].Value = profile2.FullName; - report2.ReportParameters["OcFullPath"].Value = profile2.OcFullPath; - - // binding to table - var tblSalary = (Telerik.Reporting.Table)report2.Items["detailSection1"].Items["tblSalary"]; - tblSalary.DataSource = salary; - - System.Collections.Hashtable deviceInfo2 = new System.Collections.Hashtable(); - - InstanceReportSource instanceReportSource2 = new InstanceReportSource() - { - ReportDocument = report2 - }; - - - ReportProcessor reportProcessor2 = new ReportProcessor(_configuration); - RenderingResult result2 = reportProcessor2.RenderReport("PDF", instanceReportSource2, deviceInfo2); - - // byte array waiting for merge pdf - var content2 = result2.DocumentBytes; - - // merge pdf - using (MemoryStream ms = new MemoryStream()) - { - using (PdfDocument pdf = new PdfDocument(new PdfWriter(ms).SetSmartMode(true))) - { - // Create reader from bytes - using (MemoryStream memoryStream = new MemoryStream(content)) - { - // Create reader from bytes - using (PdfReader reader = new PdfReader(memoryStream)) - { - PdfDocument srcDoc = new PdfDocument(reader); - srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); - } - } - - // Create reader from bytes - if (content2 != null) - { - using (MemoryStream memoryStream = new MemoryStream(content2)) - { - // Create reader from bytes - using (PdfReader reader = new PdfReader(memoryStream)) - { - PdfDocument srcDoc = new PdfDocument(reader); - srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); - } - } - } - - pdf.Close(); - } - - var fileContent = ms.ToArray(); - return File(fileContent, "application/pdf", $"กก_1_{id}.pdf"); - } - - } - catch (Exception ex) - { - return Error(ex); - } - } - - #endregion - } + [Route("api/v{version:apiVersion}/report/profile")] + [ApiVersion("1.0")] + [ApiController] + [Produces("application/json")] + //[Authorize] + [SwaggerTag("รายงานระบบทะเบียนประวัติ")] + public class ProfileReportController : BaseController + { + #region " Fields " + + private readonly EHRDbContext _context; + private readonly IWebHostEnvironment _hostingEnvironment; + private readonly IConfiguration _configuration; + private readonly string space = "ㅤ"; + private readonly ProfileService _profileService; + private readonly MinIOService _minioService; + + + #endregion + + #region " Constructor and Destructor " + + public ProfileReportController(EHRDbContext context, + IWebHostEnvironment hostingEnvironment, + IConfiguration configuration, + ProfileService profileService, + MinIOService minioService) + { + this._context = context; + this._hostingEnvironment = hostingEnvironment; + this._configuration = configuration; + this._profileService = profileService; + this._minioService = minioService; + } + + #endregion + + #region " Methods " + + /// + /// แสดงประวัติการรับราชการแบบย่อ + /// + /// รหัสข้อมูลข้าราชการ + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + + [HttpGet("kp7-short/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetKp7ShortReport(Guid id) + { + try + { + var profile_salaries = (from ps in _context.ProfileSalaries + join pos in _context.PositionPaths + on ps.PositionId equals pos.Id + where ps.Profile.Id == id + select new + { + ProfileId = ps.Profile.Id, + PositionName = pos.Name, + ps.OcId, + SalaryDateAnnounce = ps.Date, + ps.Amount, + ps.PositionSalaryAmount + }).ToList(); + + var profiles = _context.Profiles.AsQueryable() + .Include(x => x.Avatar) + .Include(x => x.Salaries) + .Include(x => x.Educations) + .ToList(); + var prefixes = _context.Prefixes.ToList(); + var profile = (from p in profiles + join pf in prefixes on p.PrefixId equals pf.Id + where p.Id == id + select new + { + CitizenId = p.CitizenId, + Prefix = pf.Name, + p.FirstName, + p.LastName, + DateOfBirth = p.BirthDate.ToThaiShortDate(), + RegistrationAddress = p.RegistrationAddress, + RegistrationProvince = _context.Provinces.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationProvinceId)?.Name, + RegistrationDistrict = _context.Districts.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationDistrictId)?.Name, + RegistrationSubDistrict = _context.SubDistricts.AsQueryable().FirstOrDefault(x => x.Id == p.RegistrationSubDistrictId)?.Name, + RegistrationZipCode = p.RegistrationZipCode, + OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), + DateAppoint = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), + Salaries = profile_salaries, + SalaryAmount = p.Salaries.Count == 0 ? "-" + : $"{p.Salaries.OrderByDescending(s => s.Date.Value).FirstOrDefault().Amount.Value.ToString("#,##0")}", + Education = p.Educations.Count == 0 ? "-" + : $"{p.Educations.OrderByDescending(e => e.EndDate.Value.Year).FirstOrDefault().Degree} {p.Educations.OrderByDescending(e => e.EndDate.Value.Year).FirstOrDefault().Field}", + AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") + }).FirstOrDefault(); + // _context.PositionPaths.AsQueryable().FirstOrDefault(x => x.Id == p.PositionId)?.Name, + + var data = new List(); + var c = 1; + if (profile.Salaries.Count == 0) + { + var ret2 = new + { + CitizenId = profile.CitizenId, + Prefix = profile.Prefix, + FirstName = profile.FirstName, + LastName = profile.LastName, + DateOfBirth = profile.DateOfBirth, + RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", + SalaryAmount = profile.SalaryAmount, + Education = profile.Education, + AppointText = "", + SalaryDate = profile.DateAppoint, + PositionName = "", + OCFullPath = profile.OcFullPath + }; + data.Add(ret2); + } + var old_date = DateTime.Now; + var old_position = ""; + var old_ocid = Guid.NewGuid(); + dynamic ret; + + foreach (var s in profile.Salaries) + { + //if((old_date.Date != s.SalaryDateAnnounce.Value.Date)) + //{ + // old_date = s.SalaryDateAnnounce.Value; + // old_position= s.PositionName; + // old_ocid = s.OcId; + + // ret = new + // { + // CitizenId = profile.CitizenId, + // Prefix = profile.Prefix, + // FirstName = profile.FirstName, + // LastName = profile.LastName, + // DateOfBirth = profile.DateOfBirth, + // RegistrationAddress = profile.RegistrationAddress, + // SalaryAmount = profile.SalaryAmount, + // Education = profile.Education, + // AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", + // SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), + // PositionName = s.PositionName, + // OCFullPath = CoreCommandReport.GetOrganizationNameFullPath(s.OcId, false, false) + // }; + // data.Add(ret); + //} + if (old_position != s.PositionName) + { + old_date = s.SalaryDateAnnounce.Value; + old_position = s.PositionName; + old_ocid = s.OcId.Value; + ret = new + { + CitizenId = profile.CitizenId, + Prefix = profile.Prefix, + FirstName = profile.FirstName, + LastName = profile.LastName, + DateOfBirth = profile.DateOfBirth, + RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", + SalaryAmount = profile.SalaryAmount, + Education = profile.Education, + AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", + SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), + PositionName = s.PositionName, + OCFullPath = _profileService.GetOrganizationNameFullPath(s.OcId.Value, false, false) + }; + data.Add(ret); + } + else if (old_ocid != s.OcId) + { + old_date = s.SalaryDateAnnounce.Value; + old_position = s.PositionName; + old_ocid = s.OcId.Value; + ret = new + { + CitizenId = profile.CitizenId, + Prefix = profile.Prefix, + FirstName = profile.FirstName, + LastName = profile.LastName, + DateOfBirth = profile.DateOfBirth, + RegistrationAddress = $"{profile.RegistrationAddress}\r\nตำบล/แขวง {profile.RegistrationSubDistrict}\r\nเขต/อำเภอ {profile.RegistrationDistrict}\r\nจังหวัด {profile.RegistrationProvince} รหัสไปรษณีย์ {profile.RegistrationZipCode}", + SalaryAmount = profile.SalaryAmount, + Education = profile.Education, + AppointText = c == 1 ? "(เริ่มรับราชการ)" : "", + SalaryDate = s.SalaryDateAnnounce.Value.ToThaiShortDate(), + PositionName = s.PositionName, + OCFullPath = _profileService.GetOrganizationNameFullPath(s.OcId.Value, false, false), + + }; + data.Add(ret); + } + + c++; + } + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptShortKp7.trdp"); + + ReportPackager reportPackager = new ReportPackager(); + Telerik.Reporting.Report? report = null; + using (var sourceStream = System.IO.File.OpenRead(rptFile)) + { + report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); + } + + report.DataSource = data; + + if (profile.AvatarId != "") + { + try + { + // Get avatar Image + var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.AvatarId))).FileContent; + var pictureBox = (Telerik.Reporting.PictureBox)report.Items["groupHeaderSection"].Items["picAvatar"]; + pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); + } + catch { } + } + + System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); + + InstanceReportSource instanceReportSource = new InstanceReportSource() + { + ReportDocument = report + }; + + + ReportProcessor reportProcessor = new ReportProcessor(_configuration); + RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); + + var content = result.DocumentBytes; + return File(content, "application/pdf", $"ประวัติการรับราชการอย่างย่อ_{profile.CitizenId}.pdf"); + + + + } + catch (Exception ex) + { + return Error(ex, "ไม่สามารถแสดงผลรายงานได้!!!"); + } + } + + /// + /// แสดงรายงาน กก.1 + /// + /// รหัสข้อมูลข้าราชการ + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpGet("kk1/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetKK1Report(Guid id) + { + try + { + var profile = (from p in _context.Profiles + join pf in _context.Prefixes on p.PrefixId equals pf.Id into p_pf_join + from p_pf in p_pf_join.DefaultIfEmpty() + join cpf in _context.Prefixes on p.CouplePrefixId equals cpf.Id into c_pf_join + from c_pf in c_pf_join.DefaultIfEmpty() + join fpf in _context.Prefixes on p.FatherPrefixId equals fpf.Id into f_pf_join + from f_pf in f_pf_join.DefaultIfEmpty() + join mpf in _context.Prefixes on p.MotherPrefixId equals mpf.Id into m_pf_join + from m_pf in m_pf_join.DefaultIfEmpty() + where p.Id == id + select new + { + p.CitizenId, + Prefix = p_pf == null ? "" : p_pf.Name, + p.FirstName, + p.LastName, + FullName = $"{p.FirstName} {p.LastName}", + BirthDay = p.BirthDate.Day, + BirthDayText = Convert.ToDecimal(p.BirthDate.Day).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), + BirthMonth = p.BirthDate.Month.ToThaiMonth(), + BirthYear = p.BirthDate.Year.ToThaiYear(), + BirthYearText = Convert.ToDecimal(p.BirthDate.Year.ToThaiYear()).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), + Address = "", + District = "", + Area = "", + Province = "", + Telephone = p.TelephoneNumber, + CouplePrefix = c_pf == null ? "" : c_pf.Name, + CoupleFullName = $"{p.CoupleFirstName} {p.CoupleLastName}".Trim(), + FatherPrefix = f_pf == null ? "" : f_pf.Name, + FatherFullName = $"{p.FatherFirstName} {p.FatherLastName}".Trim(), + MotherPrefix = m_pf == null ? "" : m_pf.Name, + MotherFullName = $"{p.MotherFirstName} {p.MotherLastName}".Trim(), + OcId = p.OcId, + OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), + Division = "", + Institute = "", + StartDate = p.DateStart == null ? "" : p.DateStart.Value.ToThaiShortDate(), + AppointDate = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), + BirthDate = p.BirthDate.ToThaiShortDate(), + RetireDate = p.BirthDate.CalculateRetireDate().ToThaiShortDate(), + AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") + }).ToList(); + + if (!profile.Any()) + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + + // certificate + var cert = (from c in _context.ProfileCertificates.AsQueryable() + where c.Profile.Id == id + orderby c.IssueDate.Value.Year + select new + { + c.CertificateType, + c.Issuer, + c.CertificateNo, + IssueDate = c.IssueDate == null ? "" : c.IssueDate.Value.ToThaiShortDate() + }).ToList(); + + // add temp rows + while (cert.Count < 3) + { + cert.Add(new + { + CertificateType = "", + Issuer = "", + CertificateNo = "", + IssueDate = "" + }); + } + + // training + var training = (from t in _context.ProfileTrainings.AsQueryable() + where t.Profile.Id == id + orderby t.StartDate.Value.Year + select new + { + Institute = t.Department, + Start = t.StartDate == null ? "" : t.StartDate.Value.Year.ToThaiYear().ToString(), + End = t.EndDate == null ? "" : t.EndDate.Value.Year.ToThaiYear().ToString(), + Level = "", + Degree = t.Name, + Field = "" + }).ToList(); + + while (training.Count < 3) + { + training.Add(new + { + Institute = "", + Start = "", + End = "", + Level = "", + Degree = "", + Field = "" + }); + } + + // disciplines + var discipline = (from d in _context.ProfileDisciplines.AsQueryable() + where d.Profile.Id == id + orderby d.Date.Value.Year + select new + { + DisciplineYear = d.Date == null ? "" : d.Date.Value.Year.ToThaiYear().ToString(), + DisciplineDetail = d.Detail, + RefNo = d.RefCommandNo + }).ToList(); + + while (discipline.Count < 3) + { + discipline.Add(new + { + DisciplineYear = "", + DisciplineDetail = "", + RefNo = "" + }); + } + + // education + var education = (from e in _context.ProfileEducations.AsQueryable() + where e.Profile.Id == id + orderby e.StartDate.Value.Year + select new + { + Institute = e.Institute, + Start = e.StartDate == null ? "" : e.StartDate.Value.Year.ToThaiYear().ToString(), + End = e.EndDate == null ? "" : e.EndDate.Value.Year.ToThaiYear().ToString(), + Level = e.EducationLevel, + Degree = e.Degree, + Field = e.Field.Trim() == "-" ? "" : e.Field + }).ToList(); + + while (education.Count < 4) + { + education.Add(new + { + Institute = "", + Start = "", + End = "", + Level = "", + Degree = "", + Field = "" + }); + } + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Page1.trdp"); + + ReportPackager reportPackager = new ReportPackager(); + Telerik.Reporting.Report? report = null; + using (var sourceStream = System.IO.File.OpenRead(rptFile)) + { + report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); + } + report.DataSource = profile; + + // binding to table + var tblCertificate = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblCertificate"]; + tblCertificate.DataSource = cert; + + var tblTraining = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblTraining"]; + tblTraining.DataSource = training; + + var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; + tblDiscipline.DataSource = discipline; + + var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; + tblEducation.DataSource = education; + + if (profile.First().AvatarId != "") + { + try + { + // Get avatar Image + var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.First().AvatarId))).FileContent; + var pictureBox = (Telerik.Reporting.PictureBox)report.Items["pageFooterSection1"].Items["picAvatar"]; + pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); + } + catch { } + } + + System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); + + InstanceReportSource instanceReportSource = new InstanceReportSource() + { + ReportDocument = report + }; + + + ReportProcessor reportProcessor = new ReportProcessor(_configuration); + RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); + + // byte array waiting for merge pdf + var content = result.DocumentBytes; + + // page2 + var profile2 = (from p in _context.Profiles + join pf in _context.Prefixes on p.PrefixId equals pf.Id + where p.Id == id + select new + { + FullName = $"{pf.Name}{p.FirstName} {p.LastName}", + OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), + }).FirstOrDefault(); + + var salary = (from s in _context.ProfileSalaries + join pos in _context.PositionPaths on s.PositionId equals pos.Id + join pos_no in _context.PositionNumbers on s.PosNoId equals pos_no.Id + join pos_lv in _context.PositionLevels on s.PositionLevelId equals pos_lv.Id + join pos_type in _context.PositionTypes on s.PositionTypeId equals pos_type.Id + where s.Profile.Id == id + orderby s.Date.Value + select new + { + SalaryDate = s.Date == null ? "" : s.Date == new DateTime(1, 1, 1) ? "" : s.Date.Value.ToThaiShortDate(), + Position = s.SalaryClass, + PosNo = pos_no.Name, + Rank = pos_lv.Name, + Salary = s.Amount == null ? "" : s.Amount.ToString().ToInteger().ToNumericText(), + RefAll = s.SalaryRef, + PositionType = pos_type.Name, + PositionLevel = pos_lv.Name, + PositionAmount = s.PositionSalaryAmount == null ? "" : s.PositionSalaryAmount.Value.ToString().ToInteger().ToNumericText(), + FullName = profile2.FullName, + OcFullPath = profile2.OcFullPath + }).ToList(); + + //while (salary.Count < 60) + //{ + // salary.Add(new + // { + // SalaryDate = "", + // Position = "", + // PosNo = "", + // Rank = "", + // Salary = "", + // RefAll = "", + // PositionType = "", + // PositionLevel = "", + // PositionAmount = "", + // FullName = profile2.FullName, + // OcFullPath = profile2.OcFullPath + // }); + //} + + var rptFile2 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Page2.trdp"); + + ReportPackager reportPackager2 = new ReportPackager(); + Telerik.Reporting.Report? report2 = null; + using (var sourceStream = System.IO.File.OpenRead(rptFile2)) + { + report2 = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); + } + + report2.ReportParameters["FullName"].Value = profile2.FullName; + report2.ReportParameters["OcFullPath"].Value = profile2.OcFullPath; + + // binding to table + var tblSalary = (Telerik.Reporting.Table)report2.Items["detailSection1"].Items["tblSalary"]; + tblSalary.DataSource = salary; + + System.Collections.Hashtable deviceInfo2 = new System.Collections.Hashtable(); + + InstanceReportSource instanceReportSource2 = new InstanceReportSource() + { + ReportDocument = report2 + }; + + + ReportProcessor reportProcessor2 = new ReportProcessor(_configuration); + RenderingResult result2 = reportProcessor2.RenderReport("PDF", instanceReportSource2, deviceInfo2); + + // byte array waiting for merge pdf + var content2 = result2.DocumentBytes; + + // merge pdf + using (MemoryStream ms = new MemoryStream()) + { + using (PdfDocument pdf = new PdfDocument(new PdfWriter(ms).SetSmartMode(true))) + { + // Create reader from bytes + using (MemoryStream memoryStream = new MemoryStream(content)) + { + // Create reader from bytes + using (PdfReader reader = new PdfReader(memoryStream)) + { + PdfDocument srcDoc = new PdfDocument(reader); + srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); + } + } + + // Create reader from bytes + if (content2 != null) + { + using (MemoryStream memoryStream = new MemoryStream(content2)) + { + // Create reader from bytes + using (PdfReader reader = new PdfReader(memoryStream)) + { + PdfDocument srcDoc = new PdfDocument(reader); + srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); + } + } + } + + pdf.Close(); + } + + var fileContent = ms.ToArray(); + return File(fileContent, "application/pdf", $"กก_1_{id}.pdf"); + } + } + catch (Exception ex) + { + return Error(ex); + } + } + + + /// + /// แสดงรายงาน กพ.7 + /// + /// รหัสข้อมูลข้าราชการ + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + [HttpGet("kp7/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task> GetKP7Report(Guid id) + { + try + { + var profile = (from p in _context.Profiles + join pf in _context.Prefixes on p.PrefixId equals pf.Id into p_pf_join + from p_pf in p_pf_join.DefaultIfEmpty() + join cpf in _context.Prefixes on p.CouplePrefixId equals cpf.Id into c_pf_join + from c_pf in c_pf_join.DefaultIfEmpty() + join fpf in _context.Prefixes on p.FatherPrefixId equals fpf.Id into f_pf_join + from f_pf in f_pf_join.DefaultIfEmpty() + join mpf in _context.Prefixes on p.MotherPrefixId equals mpf.Id into m_pf_join + from m_pf in m_pf_join.DefaultIfEmpty() + where p.Id == id + select new + { + p.CitizenId, + Prefix = p_pf == null ? "" : p_pf.Name, + p.FirstName, + p.LastName, + FullName = $"{p.FirstName} {p.LastName}", + BirthDay = p.BirthDate.Day, + BirthDayText = Convert.ToDecimal(p.BirthDate.Day).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), + BirthMonth = p.BirthDate.Month.ToThaiMonth(), + BirthYear = p.BirthDate.Year.ToThaiYear(), + BirthYearText = Convert.ToDecimal(p.BirthDate.Year.ToThaiYear()).ThaiBahtText(UsesEt.Always, GreatFriends.ThaiBahtText.Unit.Baht, 2, false).Replace("บาท", ""), + Address = "", + District = "", + Area = "", + Province = "", + Telephone = p.TelephoneNumber, + CouplePrefix = c_pf == null ? "" : c_pf.Name, + CoupleFullName = $"{p.CoupleFirstName} {p.CoupleLastName}".Trim(), + FatherPrefix = f_pf == null ? "" : f_pf.Name, + FatherFullName = $"{p.FatherFirstName} {p.FatherLastName}".Trim(), + MotherPrefix = m_pf == null ? "" : m_pf.Name, + MotherFullName = $"{p.MotherFirstName} {p.MotherLastName}".Trim(), + OcId = p.OcId, + OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), + Division = "", + Institute = "", + StartDate = p.DateStart == null ? "" : p.DateStart.Value.ToThaiShortDate(), + AppointDate = p.DateAppoint == null ? "" : p.DateAppoint.Value.ToThaiShortDate(), + BirthDate = p.BirthDate.ToThaiShortDate(), + RetireDate = p.BirthDate.CalculateRetireDate().ToThaiShortDate(), + AvatarId = p.Avatar == null ? "" : p.Avatar.Id.ToString("D") + }).ToList(); + + if (!profile.Any()) + return Error(GlobalMessages.DataNotFound, StatusCodes.Status404NotFound); + + // certificate + var cert = (from c in _context.ProfileCertificates.AsQueryable() + where c.Profile.Id == id + orderby c.IssueDate.Value.Year + select new + { + c.CertificateType, + c.Issuer, + c.CertificateNo, + IssueDate = c.IssueDate == null ? "" : c.IssueDate.Value.ToThaiShortDate() + }).ToList(); + + // add temp rows + while (cert.Count < 3) + { + cert.Add(new + { + CertificateType = "", + Issuer = "", + CertificateNo = "", + IssueDate = "" + }); + } + + // training + var training = (from t in _context.ProfileTrainings.AsQueryable() + where t.Profile.Id == id + orderby t.StartDate.Value.Year + select new + { + Institute = t.Department, + Start = t.StartDate == null ? "" : t.StartDate.Value.Year.ToThaiYear().ToString(), + End = t.EndDate == null ? "" : t.EndDate.Value.Year.ToThaiYear().ToString(), + Level = "", + Degree = t.Name, + Field = "" + }).ToList(); + + + + // disciplines + var discipline = (from d in _context.ProfileDisciplines.AsQueryable() + where d.Profile.Id == id + orderby d.Date.Value.Year + select new + { + DisciplineYear = d.Date == null ? "" : d.Date.Value.Year.ToThaiYear().ToString(), + DisciplineDetail = d.Detail, + RefNo = d.RefCommandNo + }).ToList(); + + while (discipline.Count < 3) + { + discipline.Add(new + { + DisciplineYear = "", + DisciplineDetail = "", + RefNo = "" + }); + } + + // nopaind + var nopaid = (from c in _context.ProfileNopaids.AsQueryable() + where c.Profile.Id == id + orderby c.Date.Value.Year + select new + { + Year = c.Date == null ? "" : c.Date.Value.Year.ToThaiYear().ToString(), + Detail = c.Detail, + RefNo = c.Reference + }).ToList(); + + while (nopaid.Count < 3) + { + nopaid.Add(new + { + Year = "", + Detail = "", + RefNo = "" + }); + } + + // education + var education = (from e in _context.ProfileEducations.AsQueryable() + where e.Profile.Id == id + orderby e.StartDate.Value.Year + select new + { + Institute = e.Institute, + Start = e.StartDate == null ? "" : e.StartDate.Value.Year.ToThaiYear().ToString(), + End = e.EndDate == null ? "" : e.EndDate.Value.Year.ToThaiYear().ToString(), + Level = e.EducationLevel, + Degree = e.Degree, + Field = e.Field.Trim() == "-" ? "" : e.Field + }).ToList(); + + var education_all = education.Union(training).ToList(); + + while (education_all.Count < 6) + { + education_all.Add(new + { + Institute = "", + Start = "", + End = "", + Level = "", + Degree = "", + Field = "" + }); + } + + var row = 0; + var education_report = new List(); + foreach (var e in education_all) + { + if (row % 2 == 0) + { + var last_row = education_report.Last(); + last_row.Institute2 = e.Institute; + last_row.Start2 = e.Start; + last_row.End2 = e.End; + last_row.Level2 = e.Level; + last_row.Degree2 = e.Degree; + last_row.Field2 = e.Field; + } + else + { + education_report.Add(new + { + Institute1 = e.Institute, + Start1 = e.Start, + End1 = e.End, + Level1 = e.Level, + Degree1 = e.Degree, + Field1 = e.Field, + Institute2 = "", + Start2 = "", + End2 = "", + Level2 = "", + Degree2 = "", + Field2 = "" + }); + } + row++; + } + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKP7_Page1.trdp"); + + ReportPackager reportPackager = new ReportPackager(); + Telerik.Reporting.Report? report = null; + using (var sourceStream = System.IO.File.OpenRead(rptFile)) + { + report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); + } + report.DataSource = profile; + + var tblNopaid = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblNopaid"]; + tblNopaid.DataSource = nopaid; + + var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; + tblDiscipline.DataSource = discipline; + + var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; + tblEducation.DataSource = education_report; + + if (profile.First().AvatarId != "") + { + try + { + // Get avatar Image + var picContent = (await _minioService.DownloadFileAsync(Guid.Parse(profile.First().AvatarId))).FileContent; + var pictureBox = (Telerik.Reporting.PictureBox)report.Items["pageFooterSection1"].Items["picAvatar"]; + pictureBox.Value = Image.FromStream(new MemoryStream(picContent)); + } + catch { } + } + + System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); + + InstanceReportSource instanceReportSource = new InstanceReportSource() + { + ReportDocument = report + }; + + + ReportProcessor reportProcessor = new ReportProcessor(_configuration); + RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); + + // byte array waiting for merge pdf + var content = result.DocumentBytes; + + // page2 + var profile2 = (from p in _context.Profiles + join pf in _context.Prefixes on p.PrefixId equals pf.Id + where p.Id == id + select new + { + FullName = $"{pf.Name}{p.FirstName} {p.LastName}", + OcFullPath = _profileService.GetOrganizationNameFullPath(p.OcId.Value, false, false), + }).FirstOrDefault(); + + var salary = (from s in _context.ProfileSalaries + join pos in _context.PositionPaths on s.PositionId equals pos.Id + join pos_no in _context.PositionNumbers on s.PosNoId equals pos_no.Id + join pos_lv in _context.PositionLevels on s.PositionLevelId equals pos_lv.Id + join pos_type in _context.PositionTypes on s.PositionTypeId equals pos_type.Id + where s.Profile.Id == id + orderby s.Date.Value + select new + { + SalaryDate = s.Date == null ? "" : s.Date == new DateTime(1, 1, 1) ? "" : s.Date.Value.ToThaiShortDate(), + Position = s.SalaryClass, + PosNo = pos_no.Name, + Rank = pos_lv.Name, + Salary = s.Amount == null ? "" : s.Amount.ToString().ToInteger().ToNumericText(), + RefAll = s.SalaryRef, + PositionType = pos_type.Name, + PositionLevel = pos_lv.Name, + PositionAmount = s.PositionSalaryAmount == null ? "" : s.PositionSalaryAmount.Value.ToString().ToInteger().ToNumericText(), + FullName = profile2.FullName, + OcFullPath = profile2.OcFullPath + }).ToList(); + + while (salary.Count < 30) + { + salary.Add(new + { + SalaryDate = "", + Position = "", + PosNo = "", + Rank = "", + Salary = "", + RefAll = "", + PositionType = "", + PositionLevel = "", + PositionAmount = "", + FullName = profile2.FullName, + OcFullPath = profile2.OcFullPath + }); + } + + var rptFile2 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKP7_Page2.trdp"); + + ReportPackager reportPackager2 = new ReportPackager(); + Telerik.Reporting.Report? report2 = null; + using (var sourceStream = System.IO.File.OpenRead(rptFile2)) + { + report2 = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream); + } + + report2.ReportParameters["FullName"].Value = profile2.FullName; + report2.ReportParameters["OcFullPath"].Value = profile2.OcFullPath; + + // binding to table + var tblSalary = (Telerik.Reporting.Table)report2.Items["detailSection1"].Items["tblSalary"]; + tblSalary.DataSource = salary; + + System.Collections.Hashtable deviceInfo2 = new System.Collections.Hashtable(); + + InstanceReportSource instanceReportSource2 = new InstanceReportSource() + { + ReportDocument = report2 + }; + + + ReportProcessor reportProcessor2 = new ReportProcessor(_configuration); + RenderingResult result2 = reportProcessor2.RenderReport("PDF", instanceReportSource2, deviceInfo2); + + // byte array waiting for merge pdf + var content2 = result2.DocumentBytes; + + // merge pdf + using (MemoryStream ms = new MemoryStream()) + { + using (PdfDocument pdf = new PdfDocument(new PdfWriter(ms).SetSmartMode(true))) + { + // Create reader from bytes + using (MemoryStream memoryStream = new MemoryStream(content)) + { + // Create reader from bytes + using (PdfReader reader = new PdfReader(memoryStream)) + { + PdfDocument srcDoc = new PdfDocument(reader); + srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); + } + } + + // Create reader from bytes + if (content2 != null) + { + using (MemoryStream memoryStream = new MemoryStream(content2)) + { + // Create reader from bytes + using (PdfReader reader = new PdfReader(memoryStream)) + { + PdfDocument srcDoc = new PdfDocument(reader); + srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); + } + } + } + + pdf.Close(); + } + + var fileContent = ms.ToArray(); + return File(fileContent, "application/pdf", $"กก_1_{id}.pdf"); + } + + } + catch (Exception ex) + { + return Error(ex); + } + } + + #endregion + } } diff --git a/Models/HR/ProfileTraining.cs b/Models/HR/ProfileTraining.cs index adbcad2..a202457 100644 --- a/Models/HR/ProfileTraining.cs +++ b/Models/HR/ProfileTraining.cs @@ -7,18 +7,21 @@ namespace BMA.EHR.Profile.Service.Models.HR { public class ProfileTraining : EntityBase { - [MaxLength(100)] - public string? Subject { get; set; } - [Column(TypeName = "text")] - public string? Detail { get; set; } [MaxLength(200)] - public string? Host { get; set; } + public string? Name { get; set; } [MaxLength(200)] - public string? ClassName { get; set; } + public string? Topic { get; set; } + [MaxLength(200)] + public int? Yearly { get; set; } [MaxLength(200)] public string? Place { get; set; } - [MaxLength(50)] - public string? Reference { get; set; } + [MaxLength(200)] + public string? Duration { get; set; } + [MaxLength(200)] + public string? Department { get; set; } + [MaxLength(200)] + public string? NumberOrder { get; set; } + public DateTime? DateOrder { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } // public string? Course { get; set; } diff --git a/Models/HR/ProfileTrainingHistory.cs b/Models/HR/ProfileTrainingHistory.cs index 171428d..2ec9a55 100644 --- a/Models/HR/ProfileTrainingHistory.cs +++ b/Models/HR/ProfileTrainingHistory.cs @@ -7,18 +7,21 @@ namespace BMA.EHR.Profile.Service.Models.HR { public class ProfileTrainingHistory : EntityBase { - [MaxLength(100)] - public string? Subject { get; set; } - [Column(TypeName = "text")] - public string? Detail { get; set; } [MaxLength(200)] - public string? Host { get; set; } + public string? Name { get; set; } [MaxLength(200)] - public string? ClassName { get; set; } + public string? Topic { get; set; } + [MaxLength(200)] + public int? Yearly { get; set; } [MaxLength(200)] public string? Place { get; set; } - [MaxLength(50)] - public string? Reference { get; set; } + [MaxLength(200)] + public string? Duration { get; set; } + [MaxLength(200)] + public string? Department { get; set; } + [MaxLength(200)] + public string? NumberOrder { get; set; } + public DateTime? DateOrder { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } // public string? Course { get; set; }