// using BMA.EHR.Core; using BMA.EHR.Organization.Service.Extensions; using BMA.EHR.Profile.Service.Controllers; using BMA.EHR.Profile.Service.Services; using BMA.EHR.Recruit.Service.Services; using BMA.EHR.Report.Service.Data; using BMA.EHR.Report.Service.Responses; using GreatFriends.ThaiBahtText; using iText.Kernel.Pdf; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Swashbuckle.AspNetCore.Annotations; using System.Drawing; using System.Net.Http.Headers; using Telerik.Reporting; 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; private readonly IHttpContextAccessor _httpContextAccessor; #endregion #region " Constructor and Destructor " public ProfileReportController(EHRDbContext context, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, ProfileService profileService, MinIOService minioService, IHttpContextAccessor httpContextAccessor) { this._context = context; this._hostingEnvironment = hostingEnvironment; this._configuration = configuration; this._profileService = profileService; this._minioService = minioService; this._httpContextAccessor = httpContextAccessor; } private string? token => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; #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 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); //} //var CitizenId = ""; var apiUrl = $"{_configuration["API"]}/org/profile/kp7-short/{id}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(_result); if (data == null || data.result == null) { return Error("ไม่พบข้อมูลนี้ในระบบ", 404); } var result = new { template = "kp7", reportName = "docx-report", data = new { FullName = data.result.Prefix != null && data.result.FirstName != null && data.result.LastName != null ? $"{data.result.Prefix}{data.result.FirstName} {data.result.LastName}" : "-", Prefix = data.result.Prefix != null ? data.result.Prefix : "-", FirstName = data.result.FirstName != null ? data.result.FirstName : "-", LastName = data.result.LastName != null ? data.result.LastName : "-", CitizenId = data.result.CitizenId != null ? data.result.CitizenId : "-", DateOfBirth = data.result.DateOfBirth != null ? data.result.DateOfBirth : "-", DateRetire = data.result.DateRetire != null ? data.result.DateRetire : "-", SalaryAmount = data.result.SalaryAmount != null ? data.result.SalaryAmount : "-", RegistrationAddress = data.result.RegistrationAddress != null ? data.result.RegistrationAddress : "-", SalaryDate = data.result.SalaryDate != null ? data.result.SalaryDate : "-", PositionName = data.result.PositionName != null ? data.result.PositionName : "-", AppointText = data.result.AppointText != null ? data.result.AppointText : "-", OcFullPath = data.result.OcFullPath != null ? data.result.OcFullPath : "-", Educations = data.result.Education != null && data.result.Education.Count > 0 ? data.result.Education : new List { new Educations { Institute = "-", Date = "-", Degree = "-", }, }, Url = data.result.ImgUrl != null ? data.result.ImgUrl : "-", } }; return Success(result); //report.DataSource = org.result; //CitizenId = org.result.CitizenId; //var tblEducation = (Telerik.Reporting.Table)report.Items["groupHeaderSection"].Items["tblEducation"]; //tblEducation.DataSource = org.result.Education; //// report.DataSource = data; //// if (profile.AvatarId != "") //// { //// try //// { //// // Get avatar Image //// var picContent = (await _minioService.DownloadFileAsync(Guid.Parse("00000000-0000-0000-0000-000000000000"))).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", $"ประวัติการรับราชการอย่างย่อ_.pdf"); } } catch (Exception ex) { return Error(ex, "ไม่สามารถแสดงผลรายงานได้!!!"); } } /// /// แสดงประวัติการรับราชการแบบย่อ (ลูกจ้างประจำ) /// /// รหัสข้อมูลข้าราชการ /// /// เมื่อแสดงรายงานสำเร็จ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("kp7-short-employee/{id:length(36)}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> GetKp7EmpShortReport(Guid id) { try { var apiUrl = $"{_configuration["API"]}/org/profile-employee/kp7-short/{id}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(_result); if (data == null || data.result == null) { return Error("ไม่พบข้อมูลนี้ในระบบ", 404); } var result = new { template = "kp7", reportName = "docx-report", data = new { FullName = data.result.Prefix != null && data.result.FirstName != null && data.result.LastName != null ? $"{data.result.Prefix}{data.result.FirstName} {data.result.LastName}" : "-", Prefix = data.result.Prefix != null ? data.result.Prefix : "-", FirstName = data.result.FirstName != null ? data.result.FirstName : "-", LastName = data.result.LastName != null ? data.result.LastName : "-", CitizenId = data.result.CitizenId != null ? data.result.CitizenId : "-", DateOfBirth = data.result.DateOfBirth != null ? data.result.DateOfBirth : "-", DateRetire = data.result.DateRetire != null ? data.result.DateRetire : "-", SalaryAmount = data.result.SalaryAmount != null ? data.result.SalaryAmount : "-", RegistrationAddress = data.result.RegistrationAddress != null ? data.result.RegistrationAddress : "-", SalaryDate = data.result.SalaryDate != null ? data.result.SalaryDate : "-", PositionName = data.result.PositionName != null ? data.result.PositionName : "-", AppointText = data.result.AppointText != null ? data.result.AppointText : "-", OcFullPath = data.result.OcFullPath != null ? data.result.OcFullPath : "-", Educations = data.result.Education != null && data.result.Education.Count > 0 ? data.result.Education : new List { new Educations { Institute = "-", Date = "-", Degree = "-", }, }, Url = data.result.ImgUrl != null ? data.result.ImgUrl : "-", } }; return Success(result); } } 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 rptFile0 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Page0.trdp"); //ReportPackager reportPackager0 = new ReportPackager(); //Telerik.Reporting.Report? report0 = null; //using (var sourceStream0 = System.IO.File.OpenRead(rptFile0)) //{ // report0 = (Telerik.Reporting.Report)reportPackager0.UnpackageDocument(sourceStream0); //} //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); //} //var CitizenId = ""; //var FullName = ""; //var OcFullPath = ""; var apiUrl = $"{_configuration["API"]}/org/profile/kk1/{id}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(_result); if (data == null || data.Result == null) { return Error("ไม่พบข้อมูลนี้ในระบบ", 404); } var result = new { template = "kk1", reportName = "docx-report", data = new { FullName = data.Result.Profile.Count > 0 ? $"{data.Result.Profile[0].Prefix}{data.Result.Profile[0].FirstName} {data.Result.Profile[0].LastName}" : "-", Prefix = data.Result.Profile.Count > 0 ? data.Result.Profile[0].Prefix : "-", FirstName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].FirstName : "-", LastName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].LastName : "-", OcFullPath = data.Result.Profile.Count > 0 ? data.Result.Profile[0].OcFullPath : "-", BirthDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].BirthDate : "-", RetireDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].RetireDate : "-", AppointDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].AppointDate : "-", CitizenId = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CitizenId : "-", FatherFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].FatherFullName : "-", MotherFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].MotherFullName : "-", CoupleFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CoupleFullName : "-", CoupleLastNameOld = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CoupleLastNameOld : "-", CurrentAddress = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentAddress : "-", CurrentSubDistrict = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentSubDistrict : "-", CurrentDistrict = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentDistrict : "-", CurrentProvince = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentProvince : "-", Telephone = data.Result.Profile.Count > 0 ? data.Result.Profile[0].Telephone : "-", Url = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl : "-", Url1 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl1 : null, Url2 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl2 : null, Url3 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl3 : null, Url4 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl4 : null, Url5 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl5 : null, Url6 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl6 : null, Url7 = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl7 : null, Insignias = data.Result.Insignia, Leaves = data.Result.Leave, Certs = data.Result.Cert, Trainings = data.Result.Training, Disciplines = data.Result.Discipline, Educations = data.Result.Education, Salarys = data.Result.Salary, } }; return Success(result); //report0.DataSource = org.result.Profile; //var tblInsignia = (Telerik.Reporting.Table)report0.Items["detailSection1"].Items["tblInsignia"]; //tblInsignia.DataSource = org.result.Insignia; //var tblLeave = (Telerik.Reporting.Table)report0.Items["detailSection1"].Items["tblLeave"]; //tblLeave.DataSource = org.result.Leave; //report.DataSource = org.result.Profile; //// binding to table //var tblCertificate = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblCertificate"]; //tblCertificate.DataSource = org.result.Cert; //var tblTraining = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblTraining"]; //tblTraining.DataSource = org.result.Training; //var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; //tblDiscipline.DataSource = org.result.Discipline; //var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; //tblEducation.DataSource = org.result.Education; //var salary = org.result.Salary; //CitizenId = org.result.Profile[0].CitizenId; //FullName = org.result.Profile[0].FullName; //OcFullPath = org.result.Profile[0].OcFullPath; //// 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 deviceInfo0 = new System.Collections.Hashtable(); //InstanceReportSource instanceReportSource0 = new InstanceReportSource() //{ // ReportDocument = report0 //}; //ReportProcessor reportProcessor0 = new ReportProcessor(_configuration); //RenderingResult result0 = reportProcessor0.RenderReport("PDF", instanceReportSource0, deviceInfo0); //var content0 = result0.DocumentBytes; //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 //// .Include(x => x.PositionLevel) //// join pos in _context.PositionPaths.AsQueryable() //// 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 = $"{pos.Name} ประเภท{pos_type.Name} ระดับ{s.PositionLevel.Name}", //// PosNo = pos_no.Name, //// Rank = s.PositionLevel == null ? null : s.PositionLevel.Name, //// Salary = s.Amount == null ? "" : s.Amount == 0 ? "-" : s.Amount.ToString().ToInteger().ToNumericText(), //// RefAll = s.SalaryRef, //// PositionType = pos_type.Name, //// PositionLevel = s.PositionLevel == null ? null : s.PositionLevel.Name, //// PositionAmount = s.PositionSalaryAmount == null ? "" : s.PositionSalaryAmount.Value == 0 ? "-" : 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 = FullName; //report2.ReportParameters["OcFullPath"].Value = 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))) // { // using (MemoryStream memoryStream = new MemoryStream(content0)) // { // using (PdfReader reader = new PdfReader(memoryStream)) // { // PdfDocument srcDoc = new PdfDocument(reader); // srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); // } // } // // 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_{CitizenId}.pdf"); //} } } catch (Exception ex) { return Error(ex); } } /// /// แสดงรายงาน กก.1 (ลูกจ้างประจำ) /// /// รหัสข้อมูลลูกจ้างประจำ /// /// เมื่อแสดงรายงานสำเร็จ /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง /// ไม่ได้ Login เข้าระบบ /// เมื่อเกิดข้อผิดพลาดในการทำงาน [HttpGet("kk1-employee/{id:length(36)}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task> GetKK1EmpReport(Guid id) { try { //var rptFile0 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Emp_Page0.trdp"); //ReportPackager reportPackager0 = new ReportPackager(); //Telerik.Reporting.Report? report0 = null; //using (var sourceStream0 = System.IO.File.OpenRead(rptFile0)) //{ // report0 = (Telerik.Reporting.Report)reportPackager0.UnpackageDocument(sourceStream0); //} //var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Emp_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); //} //var CitizenId = ""; //var FullName = ""; //var OcFullPath = ""; var apiUrl = $"{_configuration["API"]}/org/profile-employee/kk1/{id}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(_result); if (data == null || data.Result == null) { return Error("ไม่พบข้อมูลนี้ในระบบ", 404); } var result = new { template = "kk1-emp", reportName = "docx-report", data = new { FullName = data.Result.Profile.Count > 0 ? $"{data.Result.Profile[0].Prefix}{data.Result.Profile[0].FirstName} {data.Result.Profile[0].LastName}" : "-", Prefix = data.Result.Profile.Count > 0 ? data.Result.Profile[0].Prefix : "-", FirstName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].FirstName : "-", LastName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].LastName : "-", OcFullPath = data.Result.Profile.Count > 0 ? data.Result.Profile[0].OcFullPath : "-", BirthDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].BirthDate : "-", RetireDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].RetireDate : "-", AppointDate = data.Result.Profile.Count > 0 ? data.Result.Profile[0].AppointDate : "-", CitizenId = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CitizenId : "-", FatherFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].FatherFullName : "-", MotherFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].MotherFullName : "-", CoupleFullName = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CoupleFullName : "-", CoupleLastNameOld = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CoupleLastNameOld : "-", CurrentAddress = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentAddress : "-", CurrentSubDistrict = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentSubDistrict : "-", CurrentDistrict = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentDistrict : "-", CurrentProvince = data.Result.Profile.Count > 0 ? data.Result.Profile[0].CurrentProvince : "-", Telephone = data.Result.Profile.Count > 0 ? data.Result.Profile[0].Telephone : "-", Url = data.Result.Profile.Count > 0 ? data.Result.Profile[0].ImgUrl : "-", Insignias = data.Result.Insignia, Leaves = data.Result.Leave, Certs = data.Result.Cert, Trainings = data.Result.Training, Disciplines = data.Result.Discipline, Educations = data.Result.Education, Salarys = data.Result.Salary, } }; return Success(result); //report0.DataSource = org.result.Profile; //var tblInsignia = (Telerik.Reporting.Table)report0.Items["detailSection1"].Items["tblInsignia"]; //tblInsignia.DataSource = org.result.Insignia; //var tblLeave = (Telerik.Reporting.Table)report0.Items["detailSection1"].Items["tblLeave"]; //tblLeave.DataSource = org.result.Leave; //report.DataSource = org.result.Profile; //// binding to table //var tblCertificate = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblCertificate"]; //tblCertificate.DataSource = org.result.Cert; //var tblTraining = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblTraining"]; //tblTraining.DataSource = org.result.Training; //var tblDiscipline = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblDiscipline"]; //tblDiscipline.DataSource = org.result.Discipline; //var tblEducation = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblEducation"]; //tblEducation.DataSource = org.result.Education; //var salary = org.result.Salary; //CitizenId = org.result.Profile[0].CitizenId; //FullName = org.result.Profile[0].FullName; //OcFullPath = org.result.Profile[0].OcFullPath; //System.Collections.Hashtable deviceInfo0 = new System.Collections.Hashtable(); //InstanceReportSource instanceReportSource0 = new InstanceReportSource() //{ // ReportDocument = report0 //}; //ReportProcessor reportProcessor0 = new ReportProcessor(_configuration); //RenderingResult result0 = reportProcessor0.RenderReport("PDF", instanceReportSource0, deviceInfo0); //var content0 = result0.DocumentBytes; //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; //var rptFile2 = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Profile", $"rptKK1_Emp_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 = FullName; //report2.ReportParameters["OcFullPath"].Value = 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))) // { // using (MemoryStream memoryStream = new MemoryStream(content0)) // { // using (PdfReader reader = new PdfReader(memoryStream)) // { // PdfDocument srcDoc = new PdfDocument(reader); // srcDoc.CopyPagesTo(1, srcDoc.GetNumberOfPages(), pdf); // } // } // // 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_{CitizenId}.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("ไม่พบข้อมูลในระบบ", 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.Include(x => x.PositionLevel) 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 = s.PositionLevel == null ? null : s.PositionLevel.Name, Salary = s.Amount == null ? "" : s.Amount.ToString().ToInteger().ToNumericText(), RefAll = s.SalaryRef, PositionType = pos_type.Name, PositionLevel = s.PositionLevel == null ? null : s.PositionLevel.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 } }