diff --git a/Controllers/OrganizationReportController.cs b/Controllers/OrganizationReportController.cs index 895eab2..684a5da 100644 --- a/Controllers/OrganizationReportController.cs +++ b/Controllers/OrganizationReportController.cs @@ -1,11 +1,342 @@ -using Microsoft.AspNetCore.Http; +using BMA.EHR.Profile.Service.Controllers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.Annotations; +using Telerik.Reporting.Processing; +using Telerik.Reporting; +using BMA.EHR.Report.Service.Responses; +using BMA.EHR.Report.Service.Data; +using BMA.EHR.Report.Service.Services; namespace BMA.EHR.Report.Service.Controllers { - [Route("api/[controller]")] + [Route("api/v{version:apiVersion}/report/organization")] + [ApiVersion("1.0")] [ApiController] - public class OrganizationReportController : ControllerBase + [Produces("application/json")] + //[Authorize] + [SwaggerTag("รายงานระบบโครงสร้าง")] + public class OrganizationReportController : BaseController { + #region " Fields " + + private readonly EHRDbContext _context; + private readonly IWebHostEnvironment _hostingEnvironment; + private readonly IConfiguration _configuration; + private readonly string space = "ㅤ"; + private readonly OrganizationReportService _organizationReportService; + + #endregion + + #region " Constructor and Destructor " + + public OrganizationReportController(EHRDbContext context, + IWebHostEnvironment hostingEnvironment, + IConfiguration configuration, + OrganizationReportService organizationReportService) + { + this._context = context; + this._hostingEnvironment = hostingEnvironment; + this._configuration = configuration; + this._organizationReportService = organizationReportService; + } + + #endregion + + #region " Methods " + + /// + /// รายงานบัญชี 1 + /// + /// รหัสสำนัก + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + + [HttpGet("account1/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [AllowAnonymous] + public async Task> GetAccount1Report(Guid id) + { + try + { + var data = await _organizationReportService.GetReport1Query(id); + var result_data = new List(); + + foreach (var d in data) + { + result_data.Add(new Account1ResultItem + { + Id = d.Id, + RootOcId = d.RootOcId, + RootOcName = d.RootOcName, + OcFullName = d.OcFullName.Replace($"\r\n{d.OcName}", string.Empty), + OcId = d.OcId, + OcName = d.OcName, + ShortName = d.ShortName, + PositionNumber = d.PositionNumber, + PositionNumberInt = Convert.ToInt32(d.PositionNumber.Replace(d.ShortName, string.Empty)), + PositionName = d.PositionName, + PositionSide = d.PositionSide, + PositionExecutive = d.PositionExecutive, + PositionExecutiveSide = d.PositionExecutiveSide, + OcOrder = d.OcOrder, + PositionLevel = d.PositionLevel, + Remark = d.Remark, + PositionType = d.PositionType, + }); + } + + var items = result_data.OrderBy(x => x.OcOrder).ThenBy(x => x.PositionNumberInt).ToList(); + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Organization", $"rptAccount1.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 = items; + 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 first_record = items.FirstOrDefault(); + + var content = result.DocumentBytes; + return File(content, "application/pdf", $"รายงานบัญชี1_{first_record.RootOcName}_.pdf"); + } + catch (Exception ex) + { + return Error(ex); + } + } + + /// + /// รายงานบัญชี 2 + /// + /// รหัสสำนัก + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + + [HttpGet("account2/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [AllowAnonymous] + public async Task> GetAccount2Report(Guid id) + { + try + { + var data = await _organizationReportService.GetReport2Query(id); + var result_data = new List(); + foreach (var d in data) + { + result_data.Add(new Account2ResultItem + { + Id = d.Id, + RootOcId = d.RootOcId, + RootOcName = d.RootOcName, + OcFullName = d.OcFullName.Replace($"\r\n{d.OcName}", string.Empty), + OcId = d.OcId, + OcName = d.OcName, + ShortName = d.ShortName, + PositionNumber = d.PositionNumber, + PositionNumberInt = d.PositionNumber == "" ? 0 : Convert.ToInt32(d.PositionNumber.Split(".").Last()), + PositionName = d.PositionName, + PositionSide = d.PositionSide, + PositionExecutive = d.PositionExecutive, + PositionExecutiveSide = d.PositionExecutiveSide, + OcOrder = d.OcOrder, + PositionLevel = d.PositionLevel, + Remark = d.Remark, + PositionType = d.PositionType, + + OcIdNew = d.OcIdNew, + OcFullNameNew = d.OcFullNameNew.Replace($"\r\n{d.OcNameNew}", string.Empty), + OcNameNew = d.OcNameNew, + ShortNameNew = d.ShortNameNew, + PositionNumberNew = d.PositionNumberNew, + PositionNumberIntNew = d.PositionNumberNew == "" ? 0 : Convert.ToInt32(d.PositionNumberNew.Split(".").Last()), + PositionLevelNew = d.PositionLevelNew, + PositionNameNew = d.PositionNameNew, + PositionSideNew = d.PositionSideNew, + PositionExecutiveNew = d.PositionExecutiveNew, + PositionExecutiveSideNew = d.PositionExecutiveSideNew, + PositionTypeNew = d.PositionTypeNew, + + Prefix = d.Prefix, + FirstName = d.FirstName, + LastName = d.LastName, + Degree = d.Degree, + + Salary = d.Salary, + SalaryPosition = d.SalaryPosition, + FullName = $"{d.Prefix}{d.FirstName} {d.LastName}".Trim() + }); + } + + + var items = result_data.OrderBy(x => x.OcOrder).ThenBy(x => x.PositionNumberInt).ToList(); + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Organization", $"rptAccount2.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 = items; + 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 first_record = items.FirstOrDefault(); + + var content = result.DocumentBytes; + return File(content, "application/pdf", $"รายงานบัญชี2_{first_record.RootOcName}_.pdf"); + } + catch (Exception ex) + { + return Error(ex); + } + } + + // + /// รายงานบัญชี 3 + /// + /// รหัสสำนัก + /// + /// เมื่อแสดงรายงานสำเร็จ + /// ค่าตัวแปรที่ส่งมาไม่ถูกต้อง + /// ไม่ได้ Login เข้าระบบ + /// เมื่อเกิดข้อผิดพลาดในการทำงาน + + [HttpGet("account3/{id:length(36)}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [AllowAnonymous] + public async Task> GetAccount3Report(Guid id) + { + try + { + try + { + var data = await _organizationReportService.GetReport2Query(id); + var result_data = new List(); + foreach (var d in data) + { + result_data.Add(new Account2ResultItem + { + Id = d.Id, + RootOcId = d.RootOcId, + RootOcName = d.RootOcName, + OcFullName = d.OcFullName.Replace($"\r\n{d.OcName}", string.Empty), + OcId = d.OcId, + OcName = d.OcName, + ShortName = d.ShortName, + PositionNumber = d.PositionNumber, + PositionNumberInt =d.PositionNumber == "" ? 0 : Convert.ToInt32(d.PositionNumber.Split(".").Last()), + PositionName = d.PositionName, + PositionSide = d.PositionSide, + PositionExecutive = d.PositionExecutive, + PositionExecutiveSide = d.PositionExecutiveSide, + OcOrder = d.OcOrder, + PositionLevel = d.PositionLevel, + Remark = d.Remark, + PositionType = d.PositionType, + + OcIdNew = d.OcIdNew, + OcFullNameNew = d.OcFullNameNew.Replace($"\r\n{d.OcNameNew}", string.Empty), + OcNameNew = d.OcNameNew, + ShortNameNew = d.ShortNameNew, + PositionNumberNew = d.PositionNumberNew, + PositionNumberIntNew = d.PositionNumberNew == "" ? 0 : Convert.ToInt32(d.PositionNumberNew.Split(".").Last()), + PositionLevelNew = d.PositionLevelNew, + PositionNameNew = d.PositionNameNew, + PositionSideNew = d.PositionSideNew, + PositionExecutiveNew = d.PositionExecutiveNew, + PositionExecutiveSideNew = d.PositionExecutiveSideNew, + PositionTypeNew = d.PositionTypeNew, + + Prefix = d.Prefix, + FirstName = d.FirstName, + LastName = d.LastName, + Degree = d.Degree, + + Salary = d.Salary, + SalaryPosition = d.SalaryPosition, + FullName = $"{d.Prefix}{d.FirstName} {d.LastName}".Trim() + }); + } + + + var items = result_data.OrderBy(x => x.OcOrder).ThenBy(x => x.PositionNumberInt).ToList(); + + var rptFile = Path.Combine(_hostingEnvironment.ContentRootPath, "Report", "Organization", $"rptAccount3.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 = items; + 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 first_record = items.FirstOrDefault(); + + var content = result.DocumentBytes; + return File(content, "application/pdf", $"รายงานบัญชี3_{first_record.RootOcName}_.pdf"); + } + catch (Exception ex) + { + return Error(ex); + } + } + catch (Exception ex) + { + return Error(ex); + } + } + + #endregion } } diff --git a/Controllers/ProfileReportController.cs b/Controllers/ProfileReportController.cs index b28db77..2a008a2 100644 --- a/Controllers/ProfileReportController.cs +++ b/Controllers/ProfileReportController.cs @@ -17,583 +17,954 @@ 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.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} จังหวัด{profile.RegistrationProvince} เขต/อำเภอ{profile.RegistrationDistrict} ตำบล/แขวง{profile.RegistrationSubDistrict} รหัสไปรษณีย์{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} จังหวัด{profile.RegistrationProvince} เขต/อำเภอ{profile.RegistrationDistrict} ตำบล/แขวง{profile.RegistrationSubDistrict} รหัสไปรษณีย์{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} จังหวัด{profile.RegistrationProvince} เขต/อำเภอ{profile.RegistrationDistrict} ตำบล/แขวง{profile.RegistrationSubDistrict} รหัสไปรษณีย์{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, "ไม่สามารถแสดงผลรายงานได้!!!"); - } - } - - - [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 < 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", $"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); - } - } - - #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.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} ตำบล/แขวง{profile.RegistrationSubDistrict} เขต/อำเภอ{profile.RegistrationDistrict} จังหวัด{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} ตำบล/แขวง{profile.RegistrationSubDistrict} เขต/อำเภอ{profile.RegistrationDistrict} จังหวัด{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} ตำบล/แขวง{profile.RegistrationSubDistrict} เขต/อำเภอ{profile.RegistrationDistrict} จังหวัด{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, "ไม่สามารถแสดงผลรายงานได้!!!"); + } + } + + + [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 < 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", $"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); + } + } + + [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 + } } diff --git a/Data/EHRDbContext.cs b/Data/EHRDbContext.cs index 9abfbfb..569edd4 100644 --- a/Data/EHRDbContext.cs +++ b/Data/EHRDbContext.cs @@ -1,4 +1,5 @@ using BMA.EHR.MetaData.Service.Models; +using BMA.EHR.Organization.Service.Models.Report2; using BMA.EHR.Profile.Service.Models; using BMA.EHR.Profile.Service.Models.HR; using BMA.EHR.Recruit.Service.Models.Documents; @@ -221,5 +222,9 @@ namespace BMA.EHR.Report.Service.Data public DbSet ProfileAvatarHistories { get; set; } public DbSet ProfilePositions { get; set; } + + public DbSet Report2s { get; set; } + public DbSet Report2Histories { get; set; } + public DbSet Report2DetailHistories { get; set; } } } diff --git a/Models/Report2/Report2.cs b/Models/Report2/Report2.cs new file mode 100644 index 0000000..03fcc6b --- /dev/null +++ b/Models/Report2/Report2.cs @@ -0,0 +1,53 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using BMA.EHR.MetaData.Service.Models; + +namespace BMA.EHR.Organization.Service.Models.Report2 +{ + public class Report2 : EntityBase + { + [Comment("รหัสส่วนราชการ")] + public Guid? OrganizationShortNameId { get; set; } + public string? OrganizationShortName { get; set; } + public string? GovernmentCode { get; set; } + + [Comment("ชื่อหน่วยงาน")] + public Guid? OrganizationOrganizationId { get; set; } + public string? OrganizationOrganization { get; set; } + + [Comment("ตำแหน่งเลขที่")] + public Guid? PositionNumId { get; set; } + public string? PositionNum { get; set; } + + [Comment("ประเภทตำแหน่ง")] + public Guid? PositionTypeId { get; set; } + public string? PositionType { get; set; } + + [Comment("ตำแหน่งทางการบริหาร")] + public Guid? PositionExecutiveId { get; set; } + public string? PositionExecutive { get; set; } + + [Comment("ด้านทางบริหาร")] + public Guid? PositionExecutiveSideId { get; set; } + public string? PositionExecutiveSide { get; set; } + + [Comment("ตำแหน่งในสายงาน")] + public Guid? PositionPathId { get; set; } + public string? PositionPath { get; set; } + + [Comment("ด้าน/สาขา")] + public Guid? PositionPathSideId { get; set; } + public string? PositionPathSide { get; set; } + + [Comment("ระดับตำแหน่ง")] + public Guid? PositionLevelId { get; set; } + public string? PositionLevel { get; set; } + + [Comment("สถานะการเปลี่ยนแปลง")] + public string? Status { get; set; } + + [Comment("สังกัดที่ถือครอง")] + public Guid? ProfilePositionId { get; set; } + } +} diff --git a/Models/Report2/Report2DetailHistory.cs b/Models/Report2/Report2DetailHistory.cs new file mode 100644 index 0000000..de07775 --- /dev/null +++ b/Models/Report2/Report2DetailHistory.cs @@ -0,0 +1,12 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using BMA.EHR.MetaData.Service.Models; + +namespace BMA.EHR.Organization.Service.Models.Report2 +{ + public class Report2DetailHistory : EntityBase + { + public string? Detail { get; set; } + } +} diff --git a/Models/Report2/Report2History.cs b/Models/Report2/Report2History.cs new file mode 100644 index 0000000..28d1bc0 --- /dev/null +++ b/Models/Report2/Report2History.cs @@ -0,0 +1,102 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using BMA.EHR.MetaData.Service.Models; + +namespace BMA.EHR.Organization.Service.Models.Report2 +{ + public class Report2History : EntityBase + { + [Comment("ชื่อ-สกุล")] + public string? FullName { get; set; } + [Comment("คุณวุฒิ")] + public string? Education { get; set; } + [Comment("เงินเดือน")] + public double? Salary { get; set; } + [Comment("เงินประจำตำแหน่ง")] + public double? SalaryPosition { get; set; } + [Comment("เงินตอบแทนรายเดือน")] + public double? SalaryMonth { get; set; } + + [Comment("รหัสส่วนราชการ กำหนดเดิม")] + public Guid? OldOrganizationShortNameId { get; set; } + public string? OldOrganizationShortName { get; set; } + public string? OldGovernmentCode { get; set; } + + [Comment("ชื่อหน่วยงาน กำหนดเดิม")] + public Guid? OldOrganizationOrganizationId { get; set; } + public string? OldOrganizationOrganization { get; set; } + + [Comment("ตำแหน่งเลขที่ กำหนดเดิม")] + public Guid? OldPositionNumId { get; set; } + public string? OldPositionNum { get; set; } + + [Comment("ประเภทตำแหน่ง กำหนดเดิม")] + public Guid? OldPositionTypeId { get; set; } + public string? OldPositionType { get; set; } + + [Comment("ตำแหน่งทางการบริหาร กำหนดเดิม")] + public Guid? OldPositionExecutiveId { get; set; } + public string? OldPositionExecutive { get; set; } + + [Comment("ด้านทางบริหาร กำหนดเดิม")] + public Guid? OldPositionExecutiveSideId { get; set; } + public string? OldPositionExecutiveSide { get; set; } + + [Comment("ตำแหน่งในสายงาน กำหนดเดิม")] + public Guid? OldPositionPathId { get; set; } + public string? OldPositionPath { get; set; } + + [Comment("ด้าน/สาขา กำหนดเดิม")] + public Guid? OldPositionPathSideId { get; set; } + public string? OldPositionPathSide { get; set; } + + [Comment("ระดับตำแหน่ง กำหนดเดิม")] + public Guid? OldPositionLevelId { get; set; } + public string? OldPositionLevel { get; set; } + + [Comment("รหัสส่วนราชการ กำหนดใหม่")] + public Guid? NewOrganizationShortNameId { get; set; } + public string? NewOrganizationShortName { get; set; } + public string? NewGovernmentCode { get; set; } + + [Comment("ชื่อหน่วยงาน กำหนดใหม่")] + public Guid? NewOrganizationOrganizationId { get; set; } + public string? NewOrganizationOrganization { get; set; } + + [Comment("ตำแหน่งเลขที่ กำหนดใหม่")] + public Guid? NewPositionNumId { get; set; } + public string? NewPositionNum { get; set; } + + [Comment("ประเภทตำแหน่ง กำหนดใหม่")] + public Guid? NewPositionTypeId { get; set; } + public string? NewPositionType { get; set; } + + [Comment("ตำแหน่งทางการบริหาร กำหนดใหม่")] + public Guid? NewPositionExecutiveId { get; set; } + public string? NewPositionExecutive { get; set; } + + [Comment("ด้านทางบริหาร กำหนดใหม่")] + public Guid? NewPositionExecutiveSideId { get; set; } + public string? NewPositionExecutiveSide { get; set; } + + [Comment("ตำแหน่งในสายงาน กำหนดใหม่")] + public Guid? NewPositionPathId { get; set; } + public string? NewPositionPath { get; set; } + + [Comment("ด้าน/สาขา กำหนดใหม่")] + public Guid? NewPositionPathSideId { get; set; } + public string? NewPositionPathSide { get; set; } + + [Comment("ระดับตำแหน่ง กำหนดใหม่")] + public Guid? NewPositionLevelId { get; set; } + public string? NewPositionLevel { get; set; } + + [Comment("สถานะการเปลี่ยนแปลง")] + public string? Status { get; set; } + + [Comment("สังกัดที่ถือครอง")] + public Guid? ProfilePositionId { get; set; } + public Report2DetailHistory? Report2DetailHistory { get; set; } + } +} diff --git a/Program.cs b/Program.cs index a205bfa..192dc38 100644 --- a/Program.cs +++ b/Program.cs @@ -17,6 +17,7 @@ using BMA.EHR.Report.Service; using Microsoft.AspNetCore.Mvc.ApiExplorer; using BMA.EHR.Recruit.Service.Services; using BMA.EHR.Profile.Service.Services; +using BMA.EHR.Report.Service.Services; var builder = WebApplication.CreateBuilder(args); var issuer = builder.Configuration["Jwt:Issuer"]; @@ -95,7 +96,8 @@ builder.Services.AddCors(options => options.AddDefaultPolicy(builder => // Register Service builder.Services.AddTransient(); builder.Services.AddTransient(); -builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); // Add services to the container. builder.Services.AddControllers(options => diff --git a/Report/Organization/rptAccount1.trdp b/Report/Organization/rptAccount1.trdp index a18371c..e4f7308 100644 Binary files a/Report/Organization/rptAccount1.trdp and b/Report/Organization/rptAccount1.trdp differ diff --git a/Report/Organization/rptAccount2.trdp b/Report/Organization/rptAccount2.trdp new file mode 100644 index 0000000..3cd11e9 Binary files /dev/null and b/Report/Organization/rptAccount2.trdp differ diff --git a/Report/Organization/rptAccount3.trdp b/Report/Organization/rptAccount3.trdp new file mode 100644 index 0000000..c7db9cc Binary files /dev/null and b/Report/Organization/rptAccount3.trdp differ diff --git a/Report/Profile/rptKK1_Page1.trdp b/Report/Profile/rptKK1_Page1.trdp index c0296a9..2978aa7 100644 Binary files a/Report/Profile/rptKK1_Page1.trdp and b/Report/Profile/rptKK1_Page1.trdp differ diff --git a/Report/Profile/rptKP7_Page1.trdp b/Report/Profile/rptKP7_Page1.trdp new file mode 100644 index 0000000..5625024 Binary files /dev/null and b/Report/Profile/rptKP7_Page1.trdp differ diff --git a/Report/Profile/rptKP7_Page2.trdp b/Report/Profile/rptKP7_Page2.trdp new file mode 100644 index 0000000..38c861c Binary files /dev/null and b/Report/Profile/rptKP7_Page2.trdp differ diff --git a/Services/OrganizationReportService.cs b/Services/OrganizationReportService.cs new file mode 100644 index 0000000..2f41bbd --- /dev/null +++ b/Services/OrganizationReportService.cs @@ -0,0 +1,404 @@ +using Amazon.Internal; +using BMA.EHR.Extensions; +using BMA.EHR.Profile.Service.Services; +using BMA.EHR.Report.Service.Data; +using Microsoft.EntityFrameworkCore; + +namespace BMA.EHR.Report.Service.Services +{ + public class OrganizationReportService + { + #region " Fields " + + private readonly EHRDbContext _context; + private readonly EHRDbContext _applicationDbContext; + private readonly ProfileService _profileService; + + #endregion + + #region " Constructor and Destructor " + + public OrganizationReportService(EHRDbContext context, + EHRDbContext applicationDbContext, + ProfileService profileService) + { + _context = context; + _applicationDbContext = applicationDbContext; + _profileService = profileService; + } + + #endregion + + #region " Methods " + + #region " Report Query " + + public async Task> GetReport1Query(Guid ocId) + { + var ocIdList = _profileService.GetAllIdByRoot(ocId); + var RootOcName = _profileService.GetOrganizationNameFullPath(ocId, false, false); + + var organizationPositions = await _context.OrganizationPositions.ToListAsync(); + var positionMasters = await _context.PositionMasters.ToListAsync(); + var organizations = await _context.Organizations.ToListAsync(); + var organizationOrganizations = await _applicationDbContext.OrganizationOrganizations.ToListAsync(); + var organizationShortNames = await _applicationDbContext.OrganizationShortNames.ToListAsync(); + var positionNumbers = await _context.PositionNumbers.ToListAsync(); + var executivePositions = await _applicationDbContext.PositionExecutives.ToListAsync(); + var executivePositionSide = await _applicationDbContext.PositionExecutiveSides.ToListAsync(); + var positionPaths = await _applicationDbContext.PositionPaths.ToListAsync(); + var positionPathSides = await _applicationDbContext.PositionPathSides.ToListAsync(); + var positionTypes = await _applicationDbContext.PositionTypes.ToListAsync(); + + var data = (from op in organizationPositions + join pm in positionMasters on op.PositionMasterId equals pm.Id + join oc in organizations on op.OrganizationId equals oc.Id + join oc_n in organizationOrganizations on oc.OrganizationOrganizationId equals oc_n.Id + join sn in organizationShortNames on oc.OrganizationShortNameId equals sn.Id + join pn in positionNumbers on op.PositionNumberId equals pn.Id + join pp in positionPaths on pm.PositionPathId equals pp.Id + join pps in positionPathSides on pm.PositionPathSideId equals pps.Id into pp_pps_join + from pp_pps in pp_pps_join.DefaultIfEmpty() + join ex_p in executivePositions on pm.PositionExecutiveId equals ex_p.Id into pm_exp_join + from pm_exp in pm_exp_join.DefaultIfEmpty() + join ex_p_s in executivePositionSide on pm.PositionExecutiveSideId equals ex_p_s.Id into pm_exp_s_join + from pm_exp_s in pm_exp_s_join.DefaultIfEmpty() + join pt in positionTypes on pm.PositionTypeId equals pt.Id + where ocIdList.Contains((Guid)op.OrganizationId) + select new Account1ResultItem + { + Id = op.Id, + RootOcId = ocId, + RootOcName = RootOcName, + OcId = op.OrganizationId.Value, + OcFullName = _profileService.FindOCFullPathWithNewLine(op.OrganizationId.Value, false, suppress: RootOcName), + OcName = _profileService.GetOrganizationName(op.OrganizationId.Value), + ShortName = sn.Name, + PositionNumber = pn.Name, + PositionLevel = _profileService.GetPositionLevel(pm.Id), + PositionName = pp.Name, + PositionSide = pp_pps == null ? "" : $"({pp_pps.Name})", + PositionExecutive = pm_exp == null ? "" : pm_exp.Name, + PositionExecutiveSide = pm_exp_s == null ? "" : $"({pm_exp_s.Name})", + Remark = op.PositionUserNote, + OcOrder = oc.OrganizationOrder.Value, + PositionType = pt.Name + }).ToList(); + + return data; + } + + public async Task> GetReport2Query(Guid ocId) + { + try + { + + + var ocIdList = _profileService.GetAllIdByRoot(ocId); + var RootOcName = _profileService.GetOrganizationNameFullPath(ocId, false, false); + + var organizationPositions = await _context.OrganizationPositions.ToListAsync(); + var positionMasters = await _context.PositionMasters.ToListAsync(); + var organizations = await _context.Organizations.ToListAsync(); + var organizationOrganizations = await _applicationDbContext.OrganizationOrganizations.ToListAsync(); + var organizationShortNames = await _applicationDbContext.OrganizationShortNames.ToListAsync(); + var positionNumbers = await _context.PositionNumbers.ToListAsync(); + var executivePositions = await _applicationDbContext.PositionExecutives.ToListAsync(); + var executivePositionSide = await _applicationDbContext.PositionExecutiveSides.ToListAsync(); + var positionPaths = await _applicationDbContext.PositionPaths.ToListAsync(); + var positionPathSides = await _applicationDbContext.PositionPathSides.ToListAsync(); + var positionTypes = await _applicationDbContext.PositionTypes.ToListAsync(); + var profilePositions = await _context.ProfilePositions.ToListAsync(); + var prefixes = await _context.Prefixes.ToListAsync(); + var profiles = await _context.Profiles.ToListAsync(); + var report2 = await _context.Report2s.ToListAsync(); + + var profile_data = (from p in _context.Profiles + join pf in _context.Prefixes on p.PrefixId equals pf.Id + select new + { + p.Id, + p.CitizenId, + Prefix = pf.Name, + p.FirstName, + p.LastName, + p.PositionLine, + p.Position, + p.PositionPathSide, + p.PositionType, + p.PositionLevel, + p.PositionExecutive, + p.PositionExecutiveSide, + p.PosNo, + p.OrganizationShortName, + Degree = p.Educations == null || p.Educations.Count == 0 ? "" : $"{p.Educations.OrderBy(x => x.StartDate).Last().Degree}\r\n({p.Educations.OrderBy(x => x.StartDate).Last().Field})", + Salary = p.Salaries == null || p.Salaries.Count == 0 ? 0 : p.Salaries.OrderBy(x => x.Date).Last().Amount, + SalaryPosition = p.Salaries == null || p.Salaries.Count == 0 ? 0 : p.Salaries.OrderBy(x => x.Date).Last().PositionSalaryAmount, + + }).ToList(); + + + var report2_data = (from org_pos in _context.OrganizationPositions.ToList() + join ppos in _context.ProfilePositions.ToList() on org_pos.Id equals ppos.OrganizationPositionId + join pf in profile_data.ToList() on ppos.ProfileId equals pf.Id + join r_raw in _context.Report2s.ToList() on ppos.Id equals r_raw.ProfilePositionId into r_join + from r in r_join.DefaultIfEmpty() + select new + { + //Id = r.Id, + ProfilePositionId = ppos.Id, + CitizenId = pf.CitizenId, + Prefix = pf.Prefix, + FirstName = pf.FirstName, + LastName = pf.LastName, + OrganizationName = r == null ? "" : r.OrganizationOrganization, + ShortName = r == null ? pf.OrganizationShortName : r.OrganizationShortName, + PositionNumber = r == null ? pf.PosNo : r.PositionNum, + PositionPath = r == null ? pf.Position : r.PositionPath, + PositionPathSide = r == null ? pf.PositionPathSide : r.PositionPathSide, + PositionType = r == null ? pf.PositionType : r.PositionType, + PositionLevel = r == null ? pf.PositionLevel : r.PositionLevel, + PositionExecutive = r == null ? pf.PositionExecutive : r.PositionExecutive, + PositionExecutiveSide = r == null ? pf.PositionExecutiveSide : r.PositionExecutiveSide, + OcId = org_pos.Id, + OrganizationPositionId = ppos.OrganizationPositionId, + Degree = pf.Degree, + Salary = pf.Salary, + SalaryPosition = pf.SalaryPosition, + }).ToList(); + + //var report2_data = (from r in _context.Report2s.ToList() + // join ppos in _context.ProfilePositions.ToList() on r.ProfilePositionId equals ppos.Id + // join org_pos in _context.OrganizationPositions.ToList() on ppos.OrganizationPositionId equals org_pos.Id + // join pf in profile_data.ToList() on ppos.ProfileId equals pf.Id + // select new + // { + // Id = r.Id, + // ProfilePositionId = r.ProfilePositionId, + // CitizenId = pf.CitizenId, + // Prefix = pf.Prefix, + // FirstName = pf.FirstName, + // LastName = pf.LastName, + // OrganizationName = r.OrganizationOrganization, + // ShortName = r.OrganizationShortName, + // PositionNumber = r.PositionNum, + // PositionPath = r.PositionPath, + // PositionPathSide = r.PositionPathSide, + // PositionType = r.PositionType, + // PositionLevel = r.PositionLevel, + // PositionExecutive = r.PositionExecutive, + // PositionExecutiveSide = r.PositionExecutiveSide, + // OcId = org_pos.Id, + // OrganizationPositionId = ppos.OrganizationPositionId, + // Degree = pf.Degree, + // Salary = pf.Salary, + // SalaryPosition = pf.SalaryPosition, + // }).ToList(); + + + + var data = (from op in organizationPositions + join pm in positionMasters on op.PositionMasterId equals pm.Id + join oc in organizations on op.OrganizationId equals oc.Id + join oc_n in organizationOrganizations on oc.OrganizationOrganizationId equals oc_n.Id + join sn in organizationShortNames on oc.OrganizationShortNameId equals sn.Id + join pn in positionNumbers on op.PositionNumberId equals pn.Id + join pp in positionPaths on pm.PositionPathId equals pp.Id + join pps in positionPathSides on pm.PositionPathSideId equals pps.Id into pp_pps_join + from pp_pps in pp_pps_join.DefaultIfEmpty() + join ex_p in executivePositions on pm.PositionExecutiveId equals ex_p.Id into pm_exp_join + from pm_exp in pm_exp_join.DefaultIfEmpty() + join ex_p_s in executivePositionSide on pm.PositionExecutiveSideId equals ex_p_s.Id into pm_exp_s_join + from pm_exp_s in pm_exp_s_join.DefaultIfEmpty() + join pt in positionTypes on pm.PositionTypeId equals pt.Id + join rp2 in report2_data.ToList() on op.Id equals rp2.OrganizationPositionId into rp2_join + from rp2_dt in rp2_join.DefaultIfEmpty() + + where ocIdList.Contains((Guid)op.OrganizationId) + select new Account2ResultItem + { + Id = op.Id, + RootOcId = ocId, + RootOcName = RootOcName, + OcId = op.OrganizationId.Value, + OcFullName = _profileService.FindOCFullPathWithNewLine(op.OrganizationId.Value, false, suppress: RootOcName), + OcName = _profileService.GetOrganizationName(op.OrganizationId.Value), + ShortName = sn.Name, + PositionNumber = pn.Name, + PositionLevel = rp2_dt == null ? _profileService.GetPositionLevel(pm.Id) : rp2_dt.PositionLevel, + + PositionName = pp.Name, + PositionSide = pp_pps == null ? "" : $"({pp_pps.Name})", + PositionExecutive = pm_exp == null ? "" : pm_exp.Name, + PositionExecutiveSide = pm_exp_s == null ? "" : $"({pm_exp_s.Name})", + Remark = op.PositionUserNote, + OcOrder = oc.OrganizationOrder.Value, + PositionType = pt.Name, + + + OcIdNew = rp2_dt == null ? op.OrganizationId.Value : rp2_dt.OcId, + OcFullNameNew = _profileService.FindOCFullPathWithNewLine(op.OrganizationId.Value, false, suppress: RootOcName), + OcNameNew = rp2_dt == null ? _profileService.GetOrganizationName(op.OrganizationId.Value) : _profileService.GetOrganizationName(rp2_dt.OcId), + ShortNameNew = rp2_dt == null ? "" : rp2_dt.ShortName, + PositionNumberNew = rp2_dt == null ? "" : rp2_dt.PositionNumber, + PositionLevelNew = rp2_dt == null ? "" : rp2_dt.PositionLevel, + PositionNameNew = rp2_dt == null ? "" : rp2_dt.PositionPath, + PositionSideNew = rp2_dt == null ? "" : rp2_dt.PositionPathSide, + PositionExecutiveNew = rp2_dt == null ? "" : rp2_dt.PositionExecutive, + PositionExecutiveSideNew = rp2_dt == null ? "" : rp2_dt.PositionExecutiveSide, + PositionTypeNew = rp2_dt == null ? "" : rp2_dt.PositionType, + + Prefix = rp2_dt == null ? "" : rp2_dt.Prefix, + FirstName = rp2_dt == null ? "" : rp2_dt.FirstName, + LastName = rp2_dt == null ? "" : rp2_dt.LastName, + Degree = rp2_dt == null ? "" : rp2_dt.Degree, + + Salary = rp2_dt == null ? 0 : (int)rp2_dt.Salary.Value, + SalaryPosition = rp2_dt == null ? 0 : (int)rp2_dt.SalaryPosition.Value, + + + }).ToList(); + + return data; + } + catch + { + throw; + } + } + + #endregion + + #endregion + } + + public class Account1ResultItem + { + public Guid Id { get; set; } + + public Guid RootOcId { get; set; } + + public string RootOcName { get; set; } = string.Empty; + + public Guid OcId { get; set; } + + public string OcFullName { get; set; } = string.Empty; + + public string OcName { get; set; } = string.Empty; + + public string ShortName { get; set; } = string.Empty; + + public string PositionNumber { get; set; } = string.Empty; + + public string PositionName { get; set; } = string.Empty; + + public string PositionSide { get; set; } = string.Empty; + + public string PositionLevel { get; set; } = string.Empty; + + public string PositionExecutive { get; set; } = string.Empty; + + public string PositionExecutiveSide { get; set; } = string.Empty; + + public string Remark { get; set; } = string.Empty; + + public int OcOrder { get; set; } = 0; + + public int PositionNumberInt { get; set; } = 0; + + public string PositionType { get; set; } = string.Empty; + } + + public class Account2ResultItem + { + public Guid Id { get; set; } + + public Guid RootOcId { get; set; } + + public string RootOcName { get; set; } = string.Empty; + + public Guid OcId { get; set; } + + public string OcFullName { get; set; } = string.Empty; + + public string OcName { get; set; } = string.Empty; + + public string ShortName { get; set; } = string.Empty; + + public string PositionNumber { get; set; } = string.Empty; + + public string PositionName { get; set; } = string.Empty; + + public string PositionSide { get; set; } = string.Empty; + + public string PositionLevel { get; set; } = string.Empty; + + public string PositionExecutive { get; set; } = string.Empty; + + public string PositionExecutiveSide { get; set; } = string.Empty; + + public string Remark { get; set; } = string.Empty; + + public int OcOrder { get; set; } = 0; + + public int PositionNumberInt { get; set; } = 0; + + public string PositionType { get; set; } = string.Empty; + + // new + public Guid RootOcIdNew { get; set; } + + public string RootOcNameNew { get; set; } = string.Empty; + + public Guid OcIdNew { get; set; } + + public string OcFullNameNew { get; set; } = string.Empty; + + public string OcNameNew { get; set; } = string.Empty; + + public string ShortNameNew { get; set; } = string.Empty; + + public string PositionNumberNew { get; set; } = string.Empty; + + public string PositionNameNew { get; set; } = string.Empty; + + public string PositionSideNew { get; set; } = string.Empty; + + public string PositionLevelNew { get; set; } = string.Empty; + + public string PositionExecutiveNew { get; set; } = string.Empty; + + public string PositionExecutiveSideNew { get; set; } = string.Empty; + + public int PositionNumberIntNew { get; set; } = 0; + + public string PositionTypeNew { get; set; } = string.Empty; + + // name + public string Prefix { get; set; } = string.Empty; + + public string FirstName { get; set; } = string.Empty; + + public string LastName { get; set; } = string.Empty; + + public string Degree { get; set; } = string.Empty; + + public int Salary { get; set; } = 0; + + public int SalaryPosition { get; set; } = 0; + + public string FullName { get; set; } = string.Empty; + + } + + + + public class OrganizationItem + { + public Guid Id { get; set; } + + public string Name { get; set; } = string.Empty; + + public int Order { get; set; } = 0; + } +} diff --git a/Services/ProfileService.cs b/Services/ProfileService.cs index cbbbce1..90d8d55 100644 --- a/Services/ProfileService.cs +++ b/Services/ProfileService.cs @@ -1,4 +1,5 @@ -using BMA.EHR.Profile.Service.Models; +using Amazon.S3.Model.Internal.MarshallTransformations; +using BMA.EHR.Profile.Service.Models; using BMA.EHR.Report.Service.Data; using Microsoft.EntityFrameworkCore; using System.Text.RegularExpressions; @@ -115,6 +116,33 @@ namespace BMA.EHR.Profile.Service.Services } } + public string GetOrganizationName(Guid id) + { + try + { + var organizations = _context.Organizations.ToList(); + var organizationOrganizations = _context.OrganizationOrganizations.ToList(); + + + var oc = (from o in organizations + join oc_name in organizationOrganizations on o.OrganizationOrganizationId equals oc_name.Id + select new + { + Id = o.Id, + Name = oc_name.Name, + //o.IsActive, + o.ParentId, + IsRoot = o.ParentId == null + }).FirstOrDefault(x => x.Id == id); + + return oc == null ? "" : oc.Name; + } + catch + { + throw; + } + } + public string GetOrganizationNameFullPath(Guid id, bool showRoot = false, bool descending = false) { try diff --git a/appsettings.Development.json b/appsettings.Development.json index 686aa8e..36b3e68 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -15,7 +15,7 @@ "ConnectionStrings": { "MongoConnection": "mongodb://admin:adminVM123@127.0.0.1:27017", "RecruitConnection": "server=127.0.0.1;user=root;password=P@ssw0rd;port=3308;database=bma_recruit;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", - "EHRConnection": "server=192.168.1.9;user=root;password=adminVM123;port=3306;database=bma_ehr;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", + "EHRConnection": "server=127.0.0.1;user=root;password=P@ssw0rd;port=3308;database=bma_ehr;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;", "ExamConnection": "server=127.0.0.1;user=root;password=P@ssw0rd;port=3308;database=bma_ehr_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" }, "Jwt": {