first commit

This commit is contained in:
2025-11-06 08:58:00 +09:00
commit 3a69115639
24 changed files with 3605 additions and 0 deletions

412
.gitignore vendored Normal file
View File

@@ -0,0 +1,412 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# JetBrains
.idea/*
#CFG
CFG/
JSAPI_Publish/
JSAPI/TempZip/
JSAPI/Word_Files/

25
JSAPI.sln Normal file
View File

@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32407.343
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JSAPI", "JSAPI\JSAPI.csproj", "{399FD444-BA8C-4B5D-8765-0DAD24FB3824}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{399FD444-BA8C-4B5D-8765-0DAD24FB3824}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{399FD444-BA8C-4B5D-8765-0DAD24FB3824}.Debug|Any CPU.Build.0 = Debug|Any CPU
{399FD444-BA8C-4B5D-8765-0DAD24FB3824}.Release|Any CPU.ActiveCfg = Release|Any CPU
{399FD444-BA8C-4B5D-8765-0DAD24FB3824}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {99708F17-03BA-4624-A20F-EDAFECEA1976}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.2",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Mvc;
using JSAPI.classes;
using System.Data;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
using System.Net;
namespace JSAPI.Controllers
{
[ApiController]
[Route("api/v1/gopark")]
public class GoParkApiController : Controller
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(GoParkApiController));
private IHostingEnvironment _HostEnvironment;
public GoParkApiController(IHostingEnvironment HostEnvironment)
{
_HostEnvironment = HostEnvironment;
}
[HttpPost]
[Route("pcsi/catidata")]
public IActionResult nhisExcel()
{
//var context = hcAccessor.HttpContext;
try
{
GoPark goPark = new GoPark();
string fileName = "[PCSK]data_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
return File(goPark.pcsiDataExcel(), "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > nhisExcel : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
}
}

View File

@@ -0,0 +1,159 @@
using Microsoft.AspNetCore.Mvc;
using JSAPI.classes;
using System.Data;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
using System.Net;
namespace JSAPI.Controllers
{
[ApiController]
[Route("api/v1/kri")]
public class KriApiController : Controller
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(KriApiController));
private IHostingEnvironment _HostEnvironment;
public KriApiController(IHostingEnvironment HostEnvironment)
{
_HostEnvironment = HostEnvironment;
}
[HttpPost]
[Route("nhis/excel")]
public IActionResult nhisExcel(string pkey)
{
//var context = hcAccessor.HttpContext;
try
{
KriMethod kriMethod = new KriMethod();
DataTable excelTable = kriMethod.nhisExportExcel(pkey);
string fileName = "[NHIS]" + pkey + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
return File(Common.DataTableToExcel(excelTable), "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > nhisExcel : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
[HttpPost]
[Route("nhis/record")]
public IActionResult nhisRecord()
{
//var context = hcAccessor.HttpContext;
try
{
KriMethod kriMethod = new KriMethod();
return File(kriMethod.nhisExportRecord(), "application/octet-stream", "NHIS record.zip");
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > nhisRecord : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
[HttpPost]
[Route("pcsi/excel")]
public IActionResult pcsiExcel(string pkey)
{
//var context = hcAccessor.HttpContext;
try
{
KriMethod kriMethod = new KriMethod();
DataTable excelTable = kriMethod.pcsiExportExcel(pkey);
string fileName = "[PCSI]" + pkey + "_" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx";
return File(Common.DataTableToExcel(excelTable), "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > pcsiExcel : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
[HttpPost]
[Route("html/excel")]
public IActionResult htmlToExcel()
{
//var context = hcAccessor.HttpContext;
try
{
KriMethod kriMethod = new KriMethod();
var fileName = Common.GetRequestValue("hdfExcelName");
var fileData = Common.GetRequestValue("hdfExcelData");
if (fileName.EndsWith(".xlsx") == false)
{
fileName += ".xlsx";
}
return File(kriMethod.htmlToExcell(fileData), "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > htmlToExcel : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
[Route("se/{pkey}")]
[HttpGet]
public IActionResult EncryptString(string pkey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
try
{
Security security = new Security();
string returnString = WebUtility.UrlEncode(security.encryptString(pkey, ""));
return Content(returnString);
}
catch (Exception ex)
{
return BadRequest(null);
}
}
[Route("sd/{skey}")]
[HttpGet]
public IActionResult DecryptString(string skey)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
hcAccessor.HttpContext.Response.ContentType = "text/plain";
try
{
Security security = new Security();
string returnString = security.decryptString(WebUtility.UrlDecode(skey), "");
return Content(returnString);
}
catch (Exception ex)
{
return BadRequest(null);
}
}
}
}

View File

@@ -0,0 +1,32 @@
using JSAPI.classes;
using JSAPI.Dtos;
using Microsoft.AspNetCore.Mvc;
namespace JSAPI.Controllers
{
[ApiController]
[Route("api/v1/send/pringo")]
public class SendPringoController : ControllerBase
{
private readonly SendPringoService _sendPringoService;
public SendPringoController(SendPringoService sendPringoService)
{
_sendPringoService = sendPringoService;
}
[HttpPost("send-mail")]
public async Task<IActionResult> SendMail([FromBody] PringoParamDto pringoParam)
{
var (status, body, contentType) = await _sendPringoService.SendMailAsync(pringoParam);
return new ContentResult
{
StatusCode = status,
Content = body,
ContentType = string.IsNullOrWhiteSpace(contentType) ? "application/json" : contentType
};
}
}
}

View File

@@ -0,0 +1,70 @@
using Microsoft.AspNetCore.Http;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using JSAPI.classes;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
using Microsoft.Office.Interop.Word;
namespace JSAPI.Controllers
{
[ApiController]
public class SkuApiController : Controller
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SkuApiController));
private IHostingEnvironment _HostEnvironment;
public SkuApiController(IHostingEnvironment HostEnvironment)
{
_HostEnvironment = HostEnvironment;
}
[HttpPost]
[Route("API/WordExportLG")]
public IActionResult WordExport(string SKUNUM)
{
//var context = hcAccessor.HttpContext;
try
{
MakeWord makeWord = new MakeWord();
string fileName = makeWord.setWordReportLG(SKUNUM);
byte[] fileByteArray = System.IO.File.ReadAllBytes(Common.MapPath("Word_Files/" + fileName));
return File(fileByteArray, "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > WordExport : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
[HttpPost]
[Route("API/WordExportSmell")]
public IActionResult SmellExport(string SKUNUM)
{
//var context = hcAccessor.HttpContext;
try
{
MakeWord makeWord = new MakeWord();
string fileName = makeWord.setWordReportSmell(SKUNUM);
byte[] fileByteArray = System.IO.File.ReadAllBytes(Common.MapPath("Word_Files/" + fileName));
return File(fileByteArray, "application/octet-stream", fileName);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > SmellExport : " + ex.Message);
return BadRequest(ex.Message);
}
finally
{
}
}
}
}

View File

@@ -0,0 +1,29 @@
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using JSAPI.classes;
namespace SwaggerFilter.Filters
{
public class CustomSwaggerFilter : IDocumentFilter
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CustomSwaggerFilter));
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext contextt)
{
/*
var remoteIP = Common.GetRemoteIP();
var localIP = Common.GetLocalIP();
logger.Info("remote ip : " + remoteIP);
logger.Info("local ip : " + localIP);
if(remoteIP != "::1" && remoteIP.StartsWith("1.235.195.") == false)
{
var nonMobileRoutes = swaggerDoc.Paths.ToList();
nonMobileRoutes.ForEach(x => { swaggerDoc.Paths.Remove(x.Key); });
}
*/
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Text.Json.Serialization;
namespace JSAPI.Dtos
{
public class PringoParamDto
{
public string Sender { get; set; } = string.Empty;
public string SenderName { get; set; } = string.Empty;
public string Recipient { get; set; } = string.Empty;
public string RecipientName { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
}
public class SendPringoParamDto
{
[JsonPropertyName("api_key")]
public string ApiKey { get; set; } = string.Empty;
[JsonPropertyName("template_id")]
public string TemplateId { get; set; } = string.Empty;
[JsonPropertyName("sender")]
public string Sender { get; set; } = string.Empty;
[JsonPropertyName("sender_name")]
public string SenderName { get; set; } = string.Empty;
[JsonPropertyName("recipient")]
public string Recipient { get; set; } = string.Empty;
[JsonPropertyName("recipient_name")]
public string RecipientName { get; set; } = string.Empty;
[JsonPropertyName("subject")]
public string Subject { get; set; } = string.Empty;
[JsonPropertyName("body")]
public string Body { get; set; } = string.Empty;
public SendPringoParamDto(string apiKey, string templateId, PringoParamDto pringoParamDto)
{
ApiKey = apiKey;
TemplateId = templateId;
Sender = pringoParamDto.Sender;
SenderName = pringoParamDto.SenderName;
Recipient = pringoParamDto.Recipient;
RecipientName = pringoParamDto.RecipientName;
Subject = pringoParamDto.Subject;
Body = pringoParamDto.Body;
}
}
}

37
JSAPI/JSAPI.csproj Normal file
View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Interop.Word">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>7</VersionMinor>
<VersionMajor>8</VersionMajor>
<Guid>00020905-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<PackageReference Include="Accord" Version="3.8.0" />
<PackageReference Include="Accord.Math" Version="3.8.0" />
<PackageReference Include="Accord.Statistics" Version="3.8.0" />
<PackageReference Include="EPPlus" Version="4.5.3.3" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.46" />
<PackageReference Include="log4net" Version="2.0.14" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="System.Data.OleDb" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
<Folder Include="TempZip\Source\" />
</ItemGroup>
</Project>

76
JSAPI/Program.cs Normal file
View File

@@ -0,0 +1,76 @@
using JSAPI.classes;
using Microsoft.Extensions.WebEncoders;
using SwaggerFilter.Filters;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
var builder = WebApplication.CreateBuilder(args);
var log4netRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
log4net.Config.XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config"));
var services = builder.Services;
// Add services to the container.
services.AddHttpClient<SendPringoService>();
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
//HttpContext <20><><EFBFBD><EFBFBD>
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//Session <20><><EFBFBD><EFBFBD>
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(120);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddSwaggerGen(gen => {
gen.DocumentFilter<CustomSwaggerFilter>();
gen.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
});
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); // <20>ѱ<EFBFBD><D1B1><EFBFBD> <20><><EFBFBD>ڵ<EFBFBD><DAB5>Ǵ<EFBFBD> <20><><EFBFBD><EFBFBD> <20>ذ<EFBFBD>
});
services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
AppDomain.CurrentDomain.SetData("ContentRootPath", Environment.CurrentDirectory);
var app = builder.Build();
app.UseCors("AllowAll");
//Session <20><><EFBFBD><EFBFBD>
app.UseSession();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:22823",
"sslPort": 44333
}
},
"profiles": {
"JSAPI": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7101;http://localhost:5101",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

11
JSAPI/appsettings.json Normal file
View File

@@ -0,0 +1,11 @@
{
"PringoApiURl": "https://m1090.pg.eventmail01.com/api/event/v2/",
"PringoApiKey": "5b2e14c5555479ecb6949ee714422b323b191e7491193ad27266851d7496735f",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

265
JSAPI/classes/Common.cs Normal file
View File

@@ -0,0 +1,265 @@
using System.Data;
using System.Net;
using System.Web;
using OfficeOpenXml;
namespace JSAPI.classes
{
public class Common
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Common));
/// <summary>
/// Request 변수값 반환
/// </summary>
/// <param name="fieldName">필드명</param>
/// <returns>Request 변수값</returns>
public static string GetRequestValue(string fieldName)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
string returnValue = string.Empty;
try
{
returnValue = hcAccessor.HttpContext.Request.Query[fieldName].ToString();
if (String.IsNullOrEmpty(returnValue))
{
returnValue = hcAccessor.HttpContext.Request.Form[fieldName].ToString();
}
}
catch (Exception ex)
{
}
return returnValue;
}
public static string GetRequestValueZero(string fieldName)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var returnValue = "";
try
{
returnValue = hcAccessor.HttpContext.Request.Query[fieldName].ToString();
if (String.IsNullOrEmpty(returnValue))
{
returnValue = hcAccessor.HttpContext.Request.Form[fieldName].ToString();
}
}
catch (Exception ex)
{
}
if (String.IsNullOrEmpty(returnValue) == true)
{
returnValue = "0";
}
return returnValue;
}
public static string GetRemoteIP(bool CheckForward = false)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var ip = hcAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
logger.Info(ip);
ip = ip.Split(',').Last().Trim();
return ip;
}
public static string GetLocalIP(bool CheckForward = false)
{
HttpContextAccessor hcAccessor = new HttpContextAccessor();
var ip = hcAccessor.HttpContext.Connection.LocalIpAddress.ToString();
logger.Info(ip);
ip = ip.Split(',').Last().Trim();
return ip;
}
public static string MapPath(string path)
{
return Path.Combine((string)AppDomain.CurrentDomain.GetData("ContentRootPath"), path);
}
public static bool IsNumeric(string s)
{
float output;
return float.TryParse(s, out output);
}
/// <summary>
/// HTML 엔티티 치환
/// </summary>
/// <param name="input">문자열</param>
/// <returns>HTML 엔티티 치환된 문자열</returns>
public static string StripHTMLChracters(string input)
{
return HttpUtility.HtmlDecode(input);
}
public static string makeUniqueFilename(string filePath, string fileName, string fileExtension)
{
string returnValue = string.Empty;
string[] realFileNameArray = fileName.Split('\\');
string realFileName = realFileNameArray[realFileNameArray.Length - 1].Split('.')[0];
returnValue = realFileName + fileExtension;
int fileCount = 0;
while (File.Exists(filePath + returnValue))
{
fileCount++;
returnValue = realFileName + "_" + fileCount + fileExtension;
}
return returnValue;
}
public static string makeUniqueFilename(string filePath, string fileName, string skuNum, string fileExtension)
{
string returnValue = string.Empty;
string[] realFileNameArray = fileName.Split('\\');
string realFileName = realFileNameArray[realFileNameArray.Length - 1].Split('.')[0];
realFileName = realFileName.Replace("_TEMP", "");
realFileName += " SKU(" + skuNum + ")";
returnValue = realFileName + fileExtension;
int fileCount = 0;
while (File.Exists(filePath + returnValue))
{
fileCount++;
returnValue = realFileName + "_" + fileCount + fileExtension;
}
return returnValue;
}
public static string RoundValue(double inDouble, int roundPointer)
{
string returnValue = inDouble.ToString();
if (roundPointer > -1)
{
string formatString = makeRoundFormat(roundPointer);
double pointConstant = 1;
for (int i = 0; i < roundPointer; i++)
{
pointConstant = pointConstant * 10;
}
returnValue = (Math.Round(inDouble * pointConstant, MidpointRounding.AwayFromZero) / pointConstant).ToString(formatString);
}
return returnValue;
}
public static string makeRoundFormat(int roundPointer)
{
string formatString = "#0";
for (int i = 0; i < roundPointer; i++)
{
if (i == 0)
{
formatString += ".";
}
formatString += "0";
}
return formatString;
}
public static void tableAddColumn(DataTable returnTable, string[] columnName)
{
for (int i = 0; i < columnName.Length; i++)
{
returnTable.Columns.Add(columnName[i], typeof(String));
}
}
public static DataTable SetEnableDataTableForEdit(DataTable listTable)
{
foreach (DataColumn col in listTable.Columns)
{
col.DataType = typeof(String);
col.ReadOnly = false;
}
return listTable;
}
public static void SetEnableDataTableForEdit(ref DataTable listTable, short changeDataType)
{
foreach (DataColumn col in listTable.Columns)
{
if (changeDataType == 1)
{
col.DataType = typeof(String);
}
col.ReadOnly = false;
}
}
/// <summary>
/// 특수 문자열
/// </summary>
/// <param name="strLen">만들 문자 길이 / 기본값 : 8</param>
/// <returns></returns>
public static string GetRandomString(int strLen = 8)
{
Random rand = new Random();
string returnString = string.Empty;
string sourceString = "0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < strLen; i++)
{
int randNumber = rand.Next(sourceString.Length);
returnString += sourceString.Substring(randNumber, 1);
}
return returnString;
}
/// <summary>
/// DataTable을 Excel로 변환
/// </summary>
/// <param name="excelTable">변환할 DataTable</param>
/// <param name="sheetName">만들 Sheet Name / 기본값 : Sheet1</param>
/// <returns>Excel파일</returns>
public static byte[] DataTableToExcel(DataTable excelTable, string sheetName = "Sheet1")
{
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(sheetName);
worksheet.Cells["A1"].LoadFromDataTable(excelTable, true);
return excelPackage.GetAsByteArray();
}
public static string ToRoman(int number)
{
if ((number < 0) || (number > 3999)) throw new ArgumentOutOfRangeException("insert value betwheen 1 and 3999");
if (number < 1) return string.Empty;
if (number >= 1000) return "M" + ToRoman(number - 1000);
if (number >= 900) return "CM" + ToRoman(number - 900);
if (number >= 500) return "D" + ToRoman(number - 500);
if (number >= 400) return "CD" + ToRoman(number - 400);
if (number >= 100) return "C" + ToRoman(number - 100);
if (number >= 90) return "XC" + ToRoman(number - 90);
if (number >= 50) return "L" + ToRoman(number - 50);
if (number >= 40) return "XL" + ToRoman(number - 40);
if (number >= 10) return "X" + ToRoman(number - 10);
if (number >= 9) return "IX" + ToRoman(number - 9);
if (number >= 5) return "V" + ToRoman(number - 5);
if (number >= 4) return "IV" + ToRoman(number - 4);
if (number >= 1) return "I" + ToRoman(number - 1);
throw new ArgumentOutOfRangeException("something bad happened");
}
}
}

73
JSAPI/classes/DAL.cs Normal file
View File

@@ -0,0 +1,73 @@
using System;
using System.Data.SqlClient;
using System.Data;
namespace JSAPI.classes
{
public class DAL
{
const string defaultString = "Persist Security Info=True;Data Source=1.235.195.8,20022;Initial Catalog=KON;User Id=kon;Password=kon#51304;";
public SqlConnection Connect(string connectionString = defaultString)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
public void Disconnect(SqlConnection connection)
{
connection.Close();
connection.Dispose();
}
public DataTable GetDataTable(string sql, SqlConnection connection)
{
DataTable dataTable = new DataTable();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandTimeout = 300;
try
{
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
dataTable.Load(reader);
reader.Close();
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
}
return dataTable;
}
public int ExecuteSQL(string sql, SqlConnection connection)
{
int affectedRow = 0;
try
{
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
affectedRow = -1;
}
return affectedRow;
}
}
}

119
JSAPI/classes/GoPark.cs Normal file
View File

@@ -0,0 +1,119 @@
using System.Data;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Net;
using System.Drawing;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.IO.Compression;
namespace JSAPI.classes
{
public class GoPark
{
public byte[] pcsiDataExcel()
{
ExcelPackage excelPackage = new ExcelPackage();
DAL dal = new DAL();
var connection = dal.Connect("Persist Security Info=True;Data Source=1.235.195.34;Initial Catalog=new_cati;User ID=sa;Password=krco#51304;");
try
{
string[] pkeyArray = new string[] { "2301008_1", "2301008_2", "2301008_3", "2301008_4", "2301008_5", "2301008_6", "2301008_7", "2301008_8", "2301008_9", "2301008_10", "2301008_11", "2301008_12", "2301008_13", "2301008_14", "2301008_15", "2301008_16", "2301008_17", "2301008_18", "2301009_1", "2301009_2", "2301009_3", "2301009_4", "2301009_5", "2301009_6", "2301009_7", "2301009_8", "2301009_9", "2301009_10", "2301009_11", "2301009_12", "2301009_13" };
foreach(string pkey in pkeyArray)
{
string sql = string.Empty;
sql += " SELECT A.prj_code, " + Environment.NewLine;
sql += " A.tel_etc11, " + Environment.NewLine;
sql += " A.tel_etc2, " + Environment.NewLine;
sql += " A.tel_etc3, " + Environment.NewLine;
sql += " A.tel_etc4, " + Environment.NewLine;
sql += " A.tel_cnt, " + Environment.NewLine;
sql += " CASE WHEN A.tel_etc8 = '' THEN A.tel_etc1 ELSE A.tel_etc8 END AS tel_etc8, " + Environment.NewLine;
sql += " CASE " + Environment.NewLine;
sql += " WHEN tel_stat = '1' THEN '성공' " + Environment.NewLine;
sql += " WHEN tel_stat = '6' THEN '재컨택 후 조사예정' " + Environment.NewLine;
sql += " WHEN tel_stat IN('0', '2', '4', '7', '8') THEN '비수신(전화 안받음)' " + Environment.NewLine;
sql += " WHEN tel_stat = '9' THEN '부재(타인 통해 확인)' " + Environment.NewLine;
sql += " WHEN tel_stat = '19' THEN '출장(기간 내 조사불가)' " + Environment.NewLine;
sql += " WHEN tel_stat IN('5', '20', '99') THEN '응답중단(진행 중 고객거절)' " + Environment.NewLine;
sql += " WHEN tel_stat = '17' THEN '조사거절' " + Environment.NewLine;
sql += " WHEN tel_stat = '15' THEN '단순거절' " + Environment.NewLine;
sql += " WHEN tel_stat = '16' THEN '강력거절' " + Environment.NewLine;
sql += " WHEN tel_stat IN('3', '10', '12') THEN '전화번호 틀림(결번/그런사람없음/번호오류 포함)' " + Environment.NewLine;
sql += " WHEN tel_stat = '11' THEN '본인 맞으나 조사대상 아님' " + Environment.NewLine;
sql += " WHEN tel_stat = '50' THEN '기타(검증에러)' " + Environment.NewLine;
sql += " ELSE '100' END AS tel_stat, " + Environment.NewLine;
sql += " A.tel_local + A.tel_kuk + A.tel_no AS tel_num, " + Environment.NewLine;
sql += " A.tel_date, " + Environment.NewLine;
sql += " A.tel_s_time, " + Environment.NewLine;
sql += " A.tel_e_time, " + Environment.NewLine;
sql += " B.tel_inspection_date, " + Environment.NewLine;
sql += " B.tel_client_name, " + Environment.NewLine;
sql += " B.tel_inspection_user, " + Environment.NewLine;
sql += " CASE " + Environment.NewLine;
sql += " WHEN B.tel_del_yn = 'Y' THEN '삭제' " + Environment.NewLine;
sql += " WHEN B.tel_del_yn = 'N' and B.tel_result IS NULL THEN '' " + Environment.NewLine;
sql += " WHEN B.tel_del_yn = 'N' and B.tel_result = '' THEN 'PASS' " + Environment.NewLine;
sql += " WHEN B.tel_del_yn = 'N' and B.tel_result = '2' THEN 'ERROR' " + Environment.NewLine;
sql += " WHEN B.tel_del_yn = 'N' and B.tel_result = '1' THEN 'TOK' " + Environment.NewLine;
sql += " ELSE '' END AS 'ins_result', " + Environment.NewLine;
sql += " CASE " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 1 THEN '서울' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 2 THEN '부산' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 3 THEN '대구' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 4 THEN '인천' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 5 THEN '광주' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 6 THEN '대전' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 7 THEN '울산' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 8 THEN '경기' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 9 THEN '강원' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 10 THEN '충남' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 11 THEN '충북' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 12 THEN '세종' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 13 THEN '전남' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 14 THEN '전북' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 15 THEN '경남' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 16 THEN '경북' " + Environment.NewLine;
sql += " WHEN C.s_fil60 = 17 THEN '제주' END AS 'area', " + Environment.NewLine;
sql += " B.as01, " + Environment.NewLine;
sql += " B.as02, " + Environment.NewLine;
sql += " B.as03, " + Environment.NewLine;
sql += " B.as04, " + Environment.NewLine;
sql += " B.tel_caution, " + Environment.NewLine;
sql += " B.tel_caution_ok, " + Environment.NewLine;
sql += " B.tel_recheck, " + Environment.NewLine;
sql += " B.tel_recheck_ok, " + Environment.NewLine;
sql += " B.tel_error_notice, " + Environment.NewLine;
sql += " D.c8, " + Environment.NewLine;
sql += " B.tel_error_ok " + Environment.NewLine;
sql += " FROM new_cati.dbo.sample_" + pkey + " A " + Environment.NewLine;
sql += " LEFT JOIN(SELECT * FROM (SELECT Row_number() OVER(partition BY tel_cnt ORDER BY id DESC) ridx, * FROM new_cati.dbo.t_inspection_cati WHERE prj_code like '"+pkey+"') CTC WHERE CTC.ridx = 1) B " + Environment.NewLine;
sql += " ON A.tel_cnt = B.tel_cnt " + Environment.NewLine;
sql += " LEFT JOIN(SELECT s_tcnt, s_fil60 FROM sheet1 WHERE prj_code like '"+pkey+"') C " + Environment.NewLine;
sql += " ON A.tel_cnt = C.s_tcnt " + Environment.NewLine;
sql += " LEFT JOIN(SELECT*, (SELECT String_agg(Json_value(A.value, '$.sq') +' - ' + Json_value(A.value, '$.memo'), ', ') AS FUCKYOU " + Environment.NewLine;
sql += " FROM Openjson(tel_cli_error_notice) A) AS c8 " + Environment.NewLine;
sql += " FROM new_cati.dbo.t_inspection_cati f " + Environment.NewLine;
sql += " WHERE prj_code like '"+pkey+"' " + Environment.NewLine;
sql += " AND Isjson(tel_cli_error_notice) = 1) D " + Environment.NewLine;
sql += " ON A.tel_cnt = D.tel_cnt " + Environment.NewLine;
DataTable excelTable = dal.GetDataTable(sql, connection);
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(pkey);
worksheet.Cells["A1"].LoadFromDataTable(excelTable, true);
}
}
catch (Exception ex)
{
}
finally
{
dal.Disconnect(connection);
}
return excelPackage.GetAsByteArray();
}
}
}

386
JSAPI/classes/KriMethod.cs Normal file
View File

@@ -0,0 +1,386 @@
using System.Data;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Net;
using System.Drawing;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.IO.Compression;
namespace JSAPI.classes
{
public class KriMethod
{
public DataTable nhisExportExcel(string pkey)
{
DataTable resultTable = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string sql = string.Empty;
sql += " SELECT NLIST.ID, NLIST.CODE, NLIST.DEPT_CODE as DEPT, NLIST.FEED, NLIST.NAME, NLIST.GENDER, NLIST.AGE, NLIST.PHONE, NLOGIN.USER_ID AS MYUN, ISNULL(JSON_VALUE(DAT.DATJSON, '$.INDEX.CONTACT_NUM'), 0) AS CONTACT, S_DATE" + Environment.NewLine;
sql += " FROM(" + Environment.NewLine;
sql += " SELECT IDKEY, DATJSON, S_DATE" + Environment.NewLine;
sql += " FROM[DATA] WITH(NOLOCK)" + Environment.NewLine;
sql += " CROSS APPLY(" + Environment.NewLine;
sql += " SELECT TOP 1 value AS S_DATE" + Environment.NewLine;
sql += " FROM" + Environment.NewLine;
sql += " (" + Environment.NewLine;
sql += " SELECT ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) AS rn, *" + Environment.NewLine;
sql += " FROM OPENJSON(survey_date)" + Environment.NewLine;
sql += " ) T" + Environment.NewLine;
sql += " ORDER BY rn DESC" + Environment.NewLine;
sql += " ) SD" + Environment.NewLine;
sql += " WHERE PKEY = '" + pkey + "' AND SURVEY_TYPE = 'LIST'" + Environment.NewLine;
sql += " ) DAT" + Environment.NewLine;
sql += " LEFT JOIN(" + Environment.NewLine;
sql += " SELECT id, code, dept_code, feed, gender, name, age, phone" + Environment.NewLine;
sql += " FROM kweb.dbo.NHIS_LIST_2022 WITH(NOLOCK)" + Environment.NewLine;
sql += " ) NLIST ON DAT.IDKEY = NLIST.CODE" + Environment.NewLine;
sql += " LEFT JOIN(" + Environment.NewLine;
sql += " SELECT id, user_id" + Environment.NewLine;
sql += " FROM kweb.dbo.NHIS_LOGIN_2022 WITH(NOLOCK)" + Environment.NewLine;
sql += " )NLOGIN ON JSON_VALUE(DAT.DATJSON, '$.INDEX.PID') = NLOGIN.id" + Environment.NewLine;
sql += " ORDER BY code;" + Environment.NewLine;
resultTable = dal.GetDataTable(sql, connection);
}
catch (Exception ex)
{
}
finally
{
dal.Disconnect(connection);
}
return resultTable;
}
public byte[] nhisExportRecord()
{
DAL dal = new DAL();
var connection = dal.Connect();
try
{
foreach(var dir in Directory.GetDirectories(Common.MapPath(@"TempZip/Source")))
{
Directory.Delete(dir);
}
string sql = string.Empty;
sql += " SELECT *"+Environment.NewLine;
sql += " FROM"+Environment.NewLine;
sql += " ("+Environment.NewLine;
sql += " SELECT CASE WHEN PKEY = '2205001_E' THEN '일반국민' WHEN PKEY = '2205001_F' THEN '사업장' WHEN PKEY = '2205001_G' THEN '장기요양기관' END AS PKEY"+Environment.NewLine;
sql += " , CONVERT(CHAR(8), CAST([Kon].[dbo].FN_LAST_TIME(DA.survey_date) AS date), 112) AS UPLOAD_TIME"+Environment.NewLine;
sql += " , IDKEY"+Environment.NewLine;
sql += " , JSON_VALUE(DA.DATJSON, '$.INDEX.FILENAME') AS [FILE_NAME]"+Environment.NewLine;
sql += " "+Environment.NewLine;
sql += " FROM [Kon].[dbo].[DATA] DA WITH(NOLOCK)"+Environment.NewLine;
sql += " INNER JOIN[kweb].[dbo].[NHIS_LOGIN_2022] NHIS WITH(NOLOCK) ON JSON_VALUE(DA.DATJSON, '$.INDEX.PID') = NHIS.id" + Environment.NewLine;
sql += " "+Environment.NewLine;
sql += " where pkey in ('2205001_E', '2205001_F', '2205001_G') AND SURVEY_TYPE != 'TEST' AND Status = '10' AND NHIS.export_flag = 1"+Environment.NewLine;
sql += " "+Environment.NewLine;
sql += " AND JSON_VALUE(DA.DATJSON,'$.INDEX.FILENAME') IS NOT NULL"+Environment.NewLine;
sql += " ) A"+Environment.NewLine;
sql += " ORDER BY PKEY, UPLOAD_TIME, IDKEY" + Environment.NewLine;
DataTable recordTable = dal.GetDataTable(sql,connection);
WebClient webClient = new WebClient();
for (int i = 0; i < recordTable.Rows.Count; i++)
{
string directoryName = @"TempZip/Source/" + recordTable.Rows[i]["PKEY"].ToString();
if (Directory.Exists(directoryName) == false)
{
Directory.CreateDirectory(directoryName);
}
string serverPath = "https://kon.kric.com/WebProject/PSBU2/NHIS/uploadFile/" + recordTable.Rows[i]["IDKEY"].ToString() + "/" + recordTable.Rows[i]["FILE_NAME"].ToString();
webClient.DownloadFile(new Uri(serverPath), Common.MapPath(directoryName+"/"+ recordTable.Rows[i]["FILE_NAME"].ToString()));
}
ZipFile.CreateFromDirectory(Common.MapPath(@"TempZip/Source"), Common.MapPath(@"TempZip/NHIS record.zip"));
}
catch(Exception ex)
{
}
finally
{
dal.Disconnect(connection);
}
return File.ReadAllBytes(Common.MapPath(@"TempZip/NHIS record.zip"));
}
public DataTable pcsiExportExcel(string pkey)
{
DataTable resultTable = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string sql = string.Empty;
sql = "select qus_field from[No.6].new_cati.dbo.qus where prj_code = '"+ pkey + "' and qus_no = 'aq01'";
DataTable subTable = dal.GetDataTable(sql, connection);
if (subTable.Rows.Count > 0)
{
string qusField = subTable.Rows[0][0].ToString();
sql = string.Empty;
sql += " select dc_id, " + Environment.NewLine;
sql += " dc_list_id, " + Environment.NewLine;
sql += " dc_aq01, " + Environment.NewLine;
sql += " dc_aq02, " + Environment.NewLine;
sql += " dc_pass_division, " + Environment.NewLine;
sql += " dc_client_name, " + Environment.NewLine;
sql += " dc_name, " + Environment.NewLine;
sql += " dc_position, " + Environment.NewLine;
sql += " case when LEN(LEFT(dc_tel1, CHARINDEX(RIGHT(dc_tel1,5) , dc_tel1) -1)) > 9 then LEFT(dc_tel1, CHARINDEX(RIGHT(dc_tel1,5) , dc_tel1) -1) else dc_tel1 end as 'dc_tel1' , " + Environment.NewLine;
sql += " dc_tel2, " + Environment.NewLine;
sql += " dc_client_division, " + Environment.NewLine;
sql += " dc_tel_stat, " + Environment.NewLine;
sql += " pcsi.pcsi_stat_label as 'dc_tel_label', " + Environment.NewLine;
sql += " dc_comp_client, " + Environment.NewLine;
sql += " dc_comp_explain , " + Environment.NewLine;
sql += " dc_sample_division, " + Environment.NewLine;
sql += " dc_reliability, " + Environment.NewLine;
sql += " dc_tel_user, " + Environment.NewLine;
sql += " dc_tel_datetime, " + Environment.NewLine;
sql += " dc_ps " + Environment.NewLine;
sql += " from " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select spt.id as 'dc_id', " + Environment.NewLine;
sql += " spt.tel_cnt as 'dc_list_id', " + Environment.NewLine;
sql += " tqt.label_aq01 as 'dc_aq01', " + Environment.NewLine;
sql += " tqt.label_aq02 as 'dc_aq02', " + Environment.NewLine;
sql += " '' as 'dc_pass_division', " + Environment.NewLine;
sql += " '' as 'dc_client_name', " + Environment.NewLine;
sql += " tel_etc1 + '' + tel_etc8 as 'dc_name', " + Environment.NewLine;
sql += " '' as 'dc_position', " + Environment.NewLine;
sql += " tel_local + '' + tel_kuk + '' + tel_no as 'dc_tel1', " + Environment.NewLine;
sql += " tel_allno2 as 'dc_tel2', " + Environment.NewLine;
sql += " tel_etc10 as 'dc_client_division', " + Environment.NewLine;
sql += " tel_etc9 as 'dc_sample_division', " + Environment.NewLine;
sql += " ps.tel_stat as 'dc_tel_stat', " + Environment.NewLine;
sql += " isnull(opn.o_open, '') as 'dc_comp_client', " + Environment.NewLine;
sql += " case sq.dc_comp_explain when '01' then '예' " + Environment.NewLine;
sql += " when '02' then '아니오' " + Environment.NewLine;
sql += " else '' end as 'dc_comp_explain', " + Environment.NewLine;
sql += " '' as 'dc_reliability', " + Environment.NewLine;
sql += " isnull((select m_name from[No.6].project2.dbo.man with(nolock) where id = spt.tel_user),'') as 'dc_tel_user', " + Environment.NewLine;
sql += " isnull(spt.tel_date, '') + ' ' + isnull(spt.tel_s_time, '') as 'dc_tel_datetime', " + Environment.NewLine;
sql += " '' as 'dc_ps' " + Environment.NewLine;
sql += " from[No.6].new_cati.dbo.sample_" + pkey + " spt with(nolock) " + Environment.NewLine;
sql += " left join[No.6].new_cati.dbo.T_QUOTA_TABLE tqt with(nolock) " + Environment.NewLine;
sql += " on spt.prj_code = tqt.prj_code " + Environment.NewLine;
sql += " and isnull(spt.aq01,'') = isnull(tqt.value_aq01, '') " + Environment.NewLine;
sql += " and isnull(spt.aq02,'') = isnull(tqt.value_aq02, '') " + Environment.NewLine;
sql += " left join[No.6].new_cati.dbo.cati_stat cs with(nolock) " + Environment.NewLine;
sql += " on spt.tel_stat = cs.tel_stat " + Environment.NewLine;
sql += " left join " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select case when tel_stat = '1' then '1' " + Environment.NewLine;
sql += " when tel_stat = '1-1' then '1-1' " + Environment.NewLine;
sql += " when tel_stat = '1-2' then '1-2' " + Environment.NewLine;
sql += " when tel_stat = '6' then '2' " + Environment.NewLine;
sql += " when tel_stat IN('0', '2', '4', '7', '8') then '3' " + Environment.NewLine;
sql += " when tel_stat = '9' then '4' " + Environment.NewLine;
sql += " when tel_stat = '19' then '5' " + Environment.NewLine;
sql += " when tel_stat IN('5', '20', '99') then '6' " + Environment.NewLine;
sql += " when tel_stat = '17' then '7' " + Environment.NewLine;
sql += " when tel_stat = '15' then '7-1' " + Environment.NewLine;
sql += " when tel_stat = '16' then '7-2' " + Environment.NewLine;
sql += " when tel_stat IN('3', '10', '12') then '8' " + Environment.NewLine;
sql += " when tel_stat = '11' then '9' " + Environment.NewLine;
sql += " when tel_stat = '50' then '10' " + Environment.NewLine;
sql += " else '100' end as tel_stat, " + Environment.NewLine;
sql += " tel_cnt " + Environment.NewLine;
sql += " from " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select cast(tel_stat as varchar(20)) as tel_stat, tel_cnt from[No.6].new_cati.dbo.sample_" + pkey + " with(nolock) " + Environment.NewLine;
sql += " where tel_stat not in ('1', '5', '20', '99') " + Environment.NewLine;
sql += " union all " + Environment.NewLine;
sql += " select tel_stat, tel_cnt from " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select(case when(left(sh.s_oktelno, 2) <> '01' and sh.s_fil" + qusField + " = '02') then '1-2' else '1-1' end) as tel_stat, tel_cnt " + Environment.NewLine;
sql += " from( " + Environment.NewLine;
sql += " select * from[No.6].new_cati.dbo.sample_" + pkey + " with(nolock) " + Environment.NewLine;
sql += " ) sp " + Environment.NewLine;
sql += " left join[No.6].new_cati.dbo.sheet1 sh with(nolock) " + Environment.NewLine;
sql += " on sp.prj_code = sh.prj_code and sp.tel_cnt = sh.s_tcnt " + Environment.NewLine;
sql += " where sp.tel_stat = '1' " + Environment.NewLine;
sql += " ) spo " + Environment.NewLine;
sql += " union all " + Environment.NewLine;
sql += " select cast((case when v_cnt is not null then '50' else tel_stat end) as varchar(20)) as tel_stat, tel_cnt from( " + Environment.NewLine;
sql += " select sp.tel_cnt, sp.tel_stat, ins.tel_cnt as v_cnt from( " + Environment.NewLine;
sql += " select * " + Environment.NewLine;
sql += " from[No.6].new_cati.dbo.sample_" + pkey + " with(nolock) " + Environment.NewLine;
sql += " where tel_stat in ('5', '20', '99') " + Environment.NewLine;
sql += " ) sp " + Environment.NewLine;
sql += " left join( " + Environment.NewLine;
sql += " select tel_cnt from[No.6].new_cati.dbo.t_inspection_cati with(nolock) " + Environment.NewLine;
sql += " where prj_code = '" + pkey + "' " + Environment.NewLine;
sql += " and tel_del_yn = 'N' " + Environment.NewLine;
sql += " and tel_result = 2 " + Environment.NewLine;
sql += " ) ins on sp.tel_cnt = ins.tel_cnt " + Environment.NewLine;
sql += " ) spo2 " + Environment.NewLine;
sql += " ) ts " + Environment.NewLine;
sql += " ) ps " + Environment.NewLine;
sql += " on spt.tel_cnt = ps.tel_cnt " + Environment.NewLine;
sql += " left join " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select prj_code, o_tcnt, o_qno, o_open from [No.6].new_cati.dbo.sheopen with(nolock) where prj_code = '" + pkey + "' and o_qno = 'eq1_a' " + Environment.NewLine;
sql += " ) opn " + Environment.NewLine;
sql += " on spt.tel_cnt = opn.o_tcnt " + Environment.NewLine;
sql += " left join " + Environment.NewLine;
sql += " ( " + Environment.NewLine;
sql += " select s_tcnt, isnull(s_fil" + qusField + ",'') as dc_comp_explain from[No.6].new_cati.dbo.sheet1 with(nolock) where prj_code = '" + pkey + "' " + Environment.NewLine;
sql += " ) sq " + Environment.NewLine;
sql += " on spt.tel_cnt = sq.s_tcnt " + Environment.NewLine;
sql += " ) dc " + Environment.NewLine;
sql += " left join " + Environment.NewLine;
sql += " [No.6].new_cati.dbo.pcsi_stat pcsi with(nolock) " + Environment.NewLine;
sql += " on dc.dc_tel_stat = pcsi.pcsi_stat " + Environment.NewLine;
sql += " order by dc.dc_list_id; " + Environment.NewLine;
resultTable = dal.GetDataTable(sql, connection);
}
}
catch (Exception ex)
{
}
finally
{
dal.Disconnect(connection);
}
return resultTable;
}
public byte[] htmlToExcell(string htmlTable)
{
DataTable textTable = new DataTable();
Regex imgRegex = new Regex("<\\s*img[^>]+src\\s*=\\s*\"([^\">]+)");//알파벳으로 시작하고 숫자 또는 언더바
Regex srcRegex = new Regex("<\\s*img[^>]+src\\s*=\\s*\"");//알파벳으로 시작하고 숫자 또는 언더바
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlTable);
var headers = doc.DocumentNode.SelectNodes("//tr/th");
// create columns from th
foreach (HtmlNode header in headers)
{
string headString = Common.StripHTMLChracters(header.InnerText).Replace("¸", ",").Trim();
textTable.Columns.Add(headString);
}
List<List<string>[]> imgList = new List<List<string>[]>();
imgList.Add(new List<string>[headers.Count]);
// select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
{
textTable.Rows.Add(row.SelectNodes("td").Select(td => String.Join(' ', Common.StripHTMLChracters(td.InnerText).Replace("&nbsp;", " ").Replace("¸", ",").Trim().Split(' ').Where(x => x.Length > 0).Select(x => x.ToString().Trim()).ToArray())).ToArray());
imgList.Add(row.SelectNodes("td").Select(td => Common.StripHTMLChracters(td.InnerHtml).Replace("¸", ",").Replace("\"\"", "\"").Trim()).Select(x => imgRegex.Matches(x).OfType<Match>().Select(m => srcRegex.Replace(m.Groups[0].Value, string.Empty)).ToList<string>()).ToArray());
}
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].LoadFromDataTable(textTable, true);
var cellRange = worksheet.Cells[1, 1, textTable.Rows.Count+1, textTable.Columns.Count];
cellRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
cellRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
cellRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
cellRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
cellRange = worksheet.Cells[1, 1, 1, textTable.Columns.Count];
cellRange.Style.Font.Bold = true;
cellRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
cellRange.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0xE8EAED));
for(int rloop = 0; rloop < textTable.Rows.Count; rloop++)
{
for (int cloop = 0; cloop < textTable.Columns.Count; cloop++)
{
string[] cellArray = textTable.Rows[rloop][cloop].ToString().Split('|');
if (cellArray.Length > 1)
{
int colSpan = 0;
int rowSpan = 0;
for (int ci = 1; ci < cellArray.Length; ci++)
{
if(cellArray[ci].IndexOf("#C#") == 0)
{
colSpan = Convert.ToInt32(cellArray[ci].Replace("#C#", "")) - 1;
}
else if (cellArray[ci].IndexOf("#R#") == 0)
{
rowSpan = Convert.ToInt32(cellArray[ci].Replace("#R#", "")) - 1;
}
}
if(colSpan > 0 || rowSpan > 0)
{
var mergeRange = worksheet.Cells[2 + rloop, 1 + cloop, 2 + rloop + rowSpan, 1 + cloop + colSpan];
mergeRange.Value = cellArray[0];
mergeRange.Merge = true;
mergeRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
mergeRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
}
}
}
for (int i = 0; i < imgList.Count; i++)
{
List<string>[] listRow = imgList[i];
for(int j = 0; j < listRow.Length; j++)
{
worksheet.Column(j+1).AutoFit();
var imgs = listRow[j];
if(imgs != null && imgs.Count > 0)
{
for (int k = 0; k < imgs.Count; k++)
{
insertPicture(worksheet, imgs[k], (i + 1), (j + 1),k, imgs.Count);
}
}
}
}
return excelPackage.GetAsByteArray();
}
public void insertPicture(ExcelWorksheet worksheet, string imagePath, int cellY, int cellX, int imgIndex, int imageCount)
{
WebClient webClient = new WebClient();
byte[] imageData = webClient.DownloadData(imagePath);
MemoryStream imgStream = new MemoryStream(imageData);
Image img = Image.FromStream(imgStream);
string imgName = cellY + "_" + cellX + "_" + imgIndex;
int newHeight = (imageCount - 1) * 105 + 100;
if(worksheet.Row(cellY).Height < newHeight)
{
worksheet.Row(cellY).Height = newHeight;
}
worksheet.Column(cellX).Width = 70;
worksheet.Row(cellY).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
int offsetY = (130 * imgIndex + 5) + (imgIndex * 5);
//int offsetX = 100;
var picture = worksheet.Drawings.AddPicture(imgName, img);
picture.SetSize(130, 130);
picture.SetPosition(cellY - 1, offsetY, cellX - 1, 5);
}
}
}

862
JSAPI/classes/LGSKU.cs Normal file
View File

@@ -0,0 +1,862 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace JSAPI.classes
{
public class LGSKU
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(LGSKU));
public class SkuReport
{
public string skuName { get; set; } = string.Empty;
public string pName { get; set; } = string.Empty;
public string pDiv { get; set; } = string.Empty;
public string pDivCode { get; set; } = string.Empty;
public string effects { get; set; } = string.Empty;
public string sDate { get; set; } = string.Empty;
public string eDate { get; set; } = string.Empty;
public string sampleSize { get; set; } = string.Empty;
public string minYear { get; set; } = string.Empty;
public string maxYear { get; set; } = string.Empty;
public string minAge { get; set; } = string.Empty;
public string maxAge { get; set; } = string.Empty;
public string meanAge { get; set; } = string.Empty;
public string gender { get; set; } = string.Empty;
}
////////////////////////////////////////////SC1_IDKEY : 64392B8AWBX165226 -> 전희수 테스트 용 -> 20230602 박근오 요청으로 삭제///////////////////////////////////////////////////////
public string[] getQidList(string skuNum, string part)
{
List<string> qidList = new List<string>();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string selectString = string.Empty;
selectString += "SELECT [" + part + "_QID] FROM [kweb].[dbo].[LGHNH_REPORT_QS_VARIABLE] WITH(NOLOCK) WHERE SKU_NUM = '" + skuNum + "'";
DataTable qidTable = dal.GetDataTable(selectString, connection);
if (qidTable.Rows.Count > 0)
{
string[] qidArray = qidTable.Rows[0][0].ToString().Split('/');
for (int i = 0; i < qidArray.Length; i++)
{
if(String.IsNullOrEmpty(qidArray[i].Trim()) == false)
{
qidList.Add(qidArray[i]);
}
}
}
if (part == "A")
{
qidList.AddRange(new string[] {"B0", "B1", "B2", "B3" });
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getQidList : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return qidList.ToArray();
}
public DataTable getSkuInfo(string skuNum)
{
DataTable skuInfo = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string selectString = string.Empty;
selectString += "SELECT [name2] AS PNAME, [name] AS PDIV, [division_code] AS PDIV_CODE, gender, CONVERT(CHAR(10),[start_date],111) AS SDATE, CONVERT(CHAR(10),DATEADD(DAY, 14, start_date),111) as EDATE FROM kweb.dbo.LGHNH_SKU_LIST WITH(NOLOCK) WHERE sku_num = '" + skuNum + "'";
skuInfo = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getSkuInfo : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return skuInfo;
}
public SkuReport getSkuReportInfo(string skuNum)
{
SkuReport skuReport = new SkuReport();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
DataTable skuInfo = getSkuInfo(skuNum);
string selectString = string.Empty;
selectString += "SELECT" + Environment.NewLine;
selectString += " MAX(QYEAR) as maxYear" + Environment.NewLine;
selectString += " , MIN(QYEAR) as minYear" + Environment.NewLine;
selectString += " , MAX(QAGE) as maxAge" + Environment.NewLine;
selectString += " , MIN(QAGE) as minAge" + Environment.NewLine;
selectString += " , AVG(QAGE) as meanAge" + Environment.NewLine;
selectString += " , COUNT(1) as sampleSize" + Environment.NewLine;
selectString += "FROM" + Environment.NewLine;
selectString += "(" + Environment.NewLine;
selectString += " SELECT" + Environment.NewLine;
selectString += " json_value(A.DATJSON, '$.Q2.Q2_1') as QYEAR" + Environment.NewLine;
selectString += " , YEAR(GETDATE()) - cast(json_value(A.DATJSON, '$.Q2.Q2_1') as int) AS QAGE" + Environment.NewLine;
selectString += " FROM [kon].[dbo].[DATA] A WITH(NOLOCK)" + Environment.NewLine;
selectString += " inner join[kon].[dbo].[DATA] B WITH(NOLOCK) on JSON_VALUE(A.[DATJSON], '$.INDEX.SKUNUM')= JSON_VALUE(B.[DATJSON], '$.INDEX.SKUNUM')"+Environment.NewLine;
selectString += " and JSON_VALUE(A.[DATJSON], '$.INDEX.SC1_IDKEY') = JSON_VALUE(B.[DATJSON], '$.INDEX.SC1_IDKEY')"+Environment.NewLine;
selectString += " WHERE A.PKEY = '2201018_H' AND JSON_VALUE(A.[DATJSON], '$.INDEX.SKUNUM') = '" + skuNum + "' AND A.Status = '10' " + Environment.NewLine;
selectString += " and B.PKEY = '2201018_E' and B.Status = '10' " + Environment.NewLine;
selectString += ") A" + Environment.NewLine;
DataTable respondentInfo = dal.GetDataTable(selectString, connection);
if (skuInfo.Rows.Count > 0 && respondentInfo.Rows.Count > 0)
{
string[] sdateArray = skuInfo.Rows[0]["SDATE"].ToString().Split('/');
string[] edateArray = skuInfo.Rows[0]["EDATE"].ToString().Split('/');
string sdate = sdateArray[1] + "월 " + sdateArray[2] + "일";
string edate = edateArray[1] + "월 " + edateArray[2] + "일";
skuReport.pName = skuInfo.Rows[0]["PNAME"].ToString();
skuReport.pDiv = skuInfo.Rows[0]["PDIV"].ToString();
skuReport.pDivCode = skuInfo.Rows[0]["PDIV_CODE"].ToString();
skuReport.sDate = sdate;
skuReport.eDate = edate;
skuReport.maxYear = respondentInfo.Rows[0]["maxYear"].ToString();
skuReport.minYear = respondentInfo.Rows[0]["minYear"].ToString();
skuReport.maxAge = respondentInfo.Rows[0]["maxAge"].ToString();
skuReport.minAge = respondentInfo.Rows[0]["minAge"].ToString();
skuReport.meanAge = respondentInfo.Rows[0]["meanAge"].ToString();
skuReport.sampleSize = respondentInfo.Rows[0]["sampleSize"].ToString();
skuReport.gender = skuInfo.Rows[0]["gender"].ToString();
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getSkuReportInfo : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return skuReport;
}
public DataTable getSQTable(string skuNum, double sampleSize)
{
DataTable sqData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string selectString = string.Empty;
selectString += " SELECT QT.VNAME AS QID, QT.QVALUE" + Environment.NewLine;
selectString += " , SUM(CASE WHEN DT.QVALUE IS NULL THEN 0 ELSE 1 END) CNT" + Environment.NewLine;
selectString += " FROM(" + Environment.NewLine;
selectString += " SELECT QID, JSON_VALUE(QU.[QUESTIONJSON],'$.variable') AS VNAME, JSON_VALUE(QV.[VALUE], '$.value') AS QVALUE" + Environment.NewLine;
selectString += " FROM[Kon].[dbo].[QUESTION] QU WITH(NOLOCK)" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(QU.[QUESTIONJSON]) QJ" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(JSON_QUERY(QJ.[VALUE], '$.single')) QV" + Environment.NewLine;
selectString += " where PKEY = '2201018_H' AND QID IN('Q4', 'Q5', 'Q6') AND QJ.[KEY] = 'dataset'" + Environment.NewLine;
selectString += " ) QT" + Environment.NewLine;
selectString += " LEFT JOIN(" + Environment.NewLine;
selectString += " SELECT DV.[KEY] COLLATE Korean_Wansung_CI_AS AS QID, DV.[VALUE] COLLATE Korean_Wansung_CI_AS AS QVALUE" + Environment.NewLine;
selectString += " FROM [Kon].[dbo].[DATA] DA WITH(NOLOCK)" + Environment.NewLine;
selectString += " inner join[kon].[dbo].[DATA] B WITH(NOLOCK) on JSON_VALUE(DA.[DATJSON], '$.INDEX.SKUNUM')= JSON_VALUE(B.[DATJSON], '$.INDEX.SKUNUM')" + Environment.NewLine;
selectString += " and JSON_VALUE(DA.[DATJSON], '$.INDEX.SC1_IDKEY') = JSON_VALUE(B.[DATJSON], '$.INDEX.SC1_IDKEY')" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DA.DATJSON) DJ" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DJ.[VALUE]) DV" + Environment.NewLine;
selectString += " where DA.PKEY = '2201018_H' AND DA.SURVEY_TYPE != 'TEST' AND DA.[Status] = '10' " + Environment.NewLine;
selectString += " AND JSON_VALUE(DA.[DATJSON], '$.INDEX.SKUNUM') = '" + skuNum + "'" + Environment.NewLine;
selectString += " and B.PKEY = '2201018_E' and B.SURVEY_TYPE != 'TEST' and B.Status = '10' " + Environment.NewLine;
selectString += " ) DT ON QT.QID = DT.QID AND QT.QVALUE = DT.QVALUE" + Environment.NewLine;
selectString += " GROUP BY QT.VNAME, QT.QVALUE,DT.QVALUE" + Environment.NewLine;
selectString += " ORDER BY QT.VNAME, QT.QVALUE" + Environment.NewLine;
sqData = dal.GetDataTable(selectString, connection);
Common.tableAddColumn(sqData, new string[] { "sqResult" });
for (int i = 0; i < sqData.Rows.Count; i++)
{
sqData.Rows[i]["sqResult"] = Common.RoundValue(100 * Convert.ToDouble(sqData.Rows[i]["CNT"]) / sampleSize, 1);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getSQTable : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return sqData;
}
public DataTable getQTable(string skuNum, string[] qids, DataTable qAllTable, double sampleSize)
{
List<DataRow> deleteRowList = new List<DataRow>();
DataTable qData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
string qidString = String.Join("','", qids);
qidString = "'" + qidString + "'";
try
{
string selectString = string.Empty;
selectString += " SELECT QID, QTITLE " + Environment.NewLine;
selectString += " , CAST(SUM(CASE WHEN QVALUE_0 IN('5', '6', '7') THEN 1 ELSE 0 END) as NVARCHAR(max)) TOP3_0 " + Environment.NewLine;
selectString += " , ROUND(AVG(CAST(QVALUE_0 AS FLOAT)),2) AS MEAN_0 " + Environment.NewLine;
selectString += " , CAST(SUM(CASE WHEN QVALUE_14 IN('5', '6', '7') THEN 1 ELSE 0 END) as NVARCHAR(max)) TOP3_14 " + Environment.NewLine;
selectString += " , ROUND(AVG(CAST(QVALUE_14 AS FLOAT)),2) AS MEAN_14 " + Environment.NewLine;
selectString += " FROM " + Environment.NewLine;
selectString += " ( " + Environment.NewLine;
selectString += " select SCID,JSON_VALUE(QU.QUESTIONJSON,'$.variable') as QID, REPLACE(REPLACE(REPLACE(JSON_VALUE(QU.QUESTIONJSON, '$.description'), '<STRONG>', ''), '</STRONG>', ''), '▶', '') AS QTITLE " + Environment.NewLine;
selectString += " , CASE WHEN DT.PKEY = '2201018_C' THEN DT.QVALUE ELSE NULL END AS QVALUE_0 " + Environment.NewLine;
selectString += " , CASE WHEN DT.PKEY = '2201018_E' THEN DT.QVALUE ELSE NULL END AS QVALUE_14 " + Environment.NewLine;
selectString += " from( " + Environment.NewLine;
selectString += " SELECT PKEY,JSON_VALUE(DA.[DATJSON], '$.INDEX.SC1_IDKEY') AS SCID, DV.[KEY] COLLATE Korean_Wansung_CI_AS AS QID, DV.[VALUE] COLLATE Korean_Wansung_CI_AS AS QVALUE " + Environment.NewLine;
selectString += " FROM[Kon].[dbo].[DATA] DA WITH(NOLOCK) " + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DA.DATJSON) DJ " + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DJ.[VALUE]) DV " + Environment.NewLine;
selectString += " where PKEY IN('2201018_C', '2201018_E') AND SURVEY_TYPE != 'TEST' AND [Status] = '10' " + Environment.NewLine;
selectString += " AND JSON_VALUE([DATJSON], '$.INDEX.SKUNUM') = '" + skuNum + "' " + Environment.NewLine;
selectString += " " + Environment.NewLine;
selectString += " ) DT " + Environment.NewLine;
selectString += " INNER JOIN[Kon].[dbo].[QUESTION] QU WITH(NOLOCK) ON DT.PKEY = QU.PKEY AND DT.QID = QU.QID " + Environment.NewLine;
selectString += " where JSON_VALUE(QU.QUESTIONJSON,'$.variable') IN( " + qidString + ") " + Environment.NewLine;
selectString += " ) A " + Environment.NewLine;
selectString += "inner join (select * from [Kon].[dbo].FN_SPLIT('"+String.Join(",", qids) +"' ,',')) B on a.QID=b.VAL1" + Environment.NewLine;
selectString += "INNER JOIN("+Environment.NewLine;
selectString += " SELECT JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') AS SCID"+Environment.NewLine;
selectString += " FROM[Kon].[dbo].[DATA] WITH(NOLOCK)"+Environment.NewLine;
selectString += " where PKEY = '2201018_E' AND SURVEY_TYPE != 'TEST' AND [Status] = '10' AND JSON_VALUE([DATJSON], '$.INDEX.SKUNUM') = '" + skuNum + "'" + Environment.NewLine;
selectString += ") H ON A.SCID = H.SCID" + Environment.NewLine;
selectString += "where (ISNUMERIC(QVALUE_0) = 1 or QVALUE_0 is null) and(ISNUMERIC(QVALUE_14) = 1 or QVALUE_14 is null)" + Environment.NewLine;
selectString += " GROUP BY B.POS, QID, QTITLE " + Environment.NewLine;
selectString += " ORDER BY B.POS " + Environment.NewLine;
qData = dal.GetDataTable(selectString, connection);
//////부호 순위 검정 붙이기
Common.SetEnableDataTableForEdit(ref qData, 0);
Common.tableAddColumn(qData, new string[] { "MRANKSUM", "DF", "P_VALUE", "P_CONDITION" });
LGSKU sku = new LGSKU();
for (int i = 0; i < qData.Rows.Count; i++)
{
string qid = qData.Rows[i]["QID"].ToString();
List<Statistics.WSRList> wsrList = new List<Statistics.WSRList>();
foreach (DataRow qAllRow in qAllTable.Rows)
{
Statistics.WSRList wsrListItem = new Statistics.WSRList();
wsrListItem.id = qAllRow["SCID_0"].ToString();
wsrListItem.xValue1 = Convert.ToDouble(qAllRow[qid + "_0"]);
wsrListItem.xValue2 = Convert.ToDouble(qAllRow[qid + "_14"]);
wsrList.Add(wsrListItem);
}
var wsrTest = Statistics.getWilcoxonSignedRanksTest(wsrList);
string pCondition = ">0.1";
if (wsrTest.pValue < 0.001)
{
pCondition = "<0.001";
}
else if (wsrTest.pValue >= 0.001 && wsrTest.pValue < 0.01)
{
pCondition = "<0.01";
}
else if (wsrTest.pValue >= 0.01 && wsrTest.pValue < 0.05)
{
pCondition = "<0.05";
}
else if (wsrTest.pValue >= 0.05 && wsrTest.pValue < 0.1)
{
pCondition = "<0.1";
}
qData.Rows[i]["MRANKSUM"] = wsrTest.minusRankSum.ToString();
qData.Rows[i]["DF"] = (sampleSize - 1).ToString();
qData.Rows[i]["P_VALUE"] = wsrTest.pValue.ToString();
qData.Rows[i]["P_CONDITION"] = pCondition;
qData.Rows[i]["TOP3_0"] = Common.RoundValue(100 * Convert.ToDouble(qData.Rows[i]["TOP3_0"]) / sampleSize, 1);
qData.Rows[i]["TOP3_14"] = Common.RoundValue(100 * Convert.ToDouble(qData.Rows[i]["TOP3_14"]) / sampleSize, 1);
///top3 가 > 42.9, P_VALUE 가 < 0.05 0일차 Mean이 14일차 보다 작아야함
if (wsrTest.pValue >= 0.05 || Convert.ToDouble(qData.Rows[i]["TOP3_14"]) <= 42.9 || Convert.ToDouble(qData.Rows[i]["MEAN_14"]) < Convert.ToDouble(qData.Rows[i]["MEAN_0"]))
{
deleteRowList.Add(qData.Rows[i]);
}
}
foreach (DataRow deleteRow in deleteRowList)
{
qData.Rows.Remove(deleteRow);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getQTable : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return qData;
}
public DataTable getABTable(string skuNum, string[] qids, double sampleSize)
{
DataTable abData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
string qidString = String.Join("','", qids);
qidString = "'" + qidString + "'";
try
{
string selectString = string.Empty;
selectString += " SELECT QID, QTITLE" + Environment.NewLine;
selectString += " , CAST(SUM(CASE WHEN QVALUE_14 IN('5', '6', '7') THEN 1 ELSE 0 END) as NVARCHAR(max)) TOP3_14" + Environment.NewLine;
selectString += " , ROUND(AVG(CAST(QVALUE_14 AS FLOAT)),2) AS MEAN_14" + Environment.NewLine;
selectString += " FROM" + Environment.NewLine;
selectString += " (" + Environment.NewLine;
selectString += " select CASE WHEN CHARINDEX('_', DT.QID) > 0 THEN JSON_VALUE(QU.QUESTIONJSON,'$.variable') + SUBSTRING(DT.QID,CHARINDEX('_', DT.QID),LEN(DT.QID)) ELSE JSON_VALUE(QU.QUESTIONJSON,'$.variable') END as QID " + Environment.NewLine;
selectString += ", CASE WHEN CHARINDEX('_', DT.QID) > 0 THEN SUBSTRING(DT.QID,0,CHARINDEX('_', DT.QID)) ELSE DT.QID END as RQID " + Environment.NewLine;
selectString += ", TRIM(CASE WHEN JSON_VALUE(QU.QUESTIONJSON, '$.qtype') = 'attr' THEN" + Environment.NewLine;
selectString += " JSON_VALUE(QU.QUESTIONJSON, '$.dataset.attr.\"' + SUBSTRING(DT.QID, LEN(DT.PQID) + 2, LEN(DT.QID)) + '\".label')" + Environment.NewLine;
selectString += "ELSE" + Environment.NewLine;
selectString += " REPLACE(REPLACE(REPLACE(JSON_VALUE(QU.QUESTIONJSON, '$.description'), '<STRONG>', ''), '</STRONG>', ''), '▶', '')" + Environment.NewLine;
selectString += "END) AS QTITLE" + Environment.NewLine;
selectString += " , DT.QVALUE AS QVALUE_14" + Environment.NewLine;
selectString += " from(" + Environment.NewLine;
selectString += " SELECT PKEY,DJ.[KEY] COLLATE Korean_Wansung_CI_AS AS PQID, DV.[KEY] COLLATE Korean_Wansung_CI_AS AS QID, DV.[VALUE] COLLATE Korean_Wansung_CI_AS AS QVALUE" + Environment.NewLine;
selectString += " FROM[Kon].[dbo].[DATA] DA WITH(NOLOCK)" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DA.DATJSON) DJ" + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DJ.[VALUE]) DV" + Environment.NewLine;
selectString += " where PKEY IN('2201018_E') AND SURVEY_TYPE != 'TEST' AND[Status] = '10' " + Environment.NewLine;
selectString += " AND JSON_VALUE([DATJSON], '$.INDEX.SKUNUM') = '" + skuNum + "'" + Environment.NewLine;
selectString += " " + Environment.NewLine;
selectString += " ) DT" + Environment.NewLine;
selectString += " INNER JOIN[Kon].[dbo].[QUESTION] QU WITH(NOLOCK) ON DT.PKEY = QU.PKEY AND DT.PQID = QU.QID" + Environment.NewLine;
selectString += " WHERE JSON_VALUE(QU.QUESTIONJSON,'$.variable') IN(" + qidString + ")" + Environment.NewLine;
selectString += " ) A" + Environment.NewLine;
selectString += " GROUP BY QID, RQID, QTITLE" + Environment.NewLine;
selectString += " ORDER BY RQID,CAST(REPLACE(REPLACE(REPLACE(QID,'A',''),'B',''),'_','0') as int)" + Environment.NewLine;
abData = dal.GetDataTable(selectString, connection);
Common.SetEnableDataTableForEdit(ref abData, 0);
for (int i = 0; i < abData.Rows.Count; i++)
{
abData.Rows[i]["TOP3_14"] = Common.RoundValue(100 * Convert.ToDouble(abData.Rows[i]["TOP3_14"]) / sampleSize, 1);
}
//순서 바꾸기
string[] bPartArray = new string[] { "B0", "B1", "B2", "B3" };
foreach(string bQid in bPartArray)
{
List<DataRow> selectRows = (from DataRow dr in abData.Rows
where dr.Field<string>("QID") == bQid
select dr).ToList();
if(selectRows.Count > 0)
{
DataRow selectRow = selectRows[0];
DataRow newRow = abData.NewRow();
newRow.ItemArray = selectRow.ItemArray;
abData.Rows.Remove(selectRow);
abData.Rows.Add(newRow);
}
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getABTable : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return abData;
}
public DataTable getQpartAllData(string skuNum, string[] qids)
{
DataTable qAllData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string day0String = " select JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') AS SCID_0" + Environment.NewLine;
string day14String = " select JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') AS SCID_14" + Environment.NewLine;
for (int i = 0; i < qids.Length; i++)
{
string qidString = " SELECT PKEY, QID FROM[Kon].[dbo].[QUESTION] WITH(NOLOCK) WHERE PKEY IN('2201018_C', '2201018_E') AND JSON_VALUE(QUESTIONJSON,'$.variable') = '" + qids[i] + "' ORDER BY PKEY";
DataTable qidTable = dal.GetDataTable(qidString, connection);
string day0Qid = qidTable.Rows[0]["QID"].ToString();
string day14Qid = qidTable.Rows[1]["QID"].ToString();
day0String += " , JSON_VALUE([DATJSON],'$." + day0Qid + "." + day0Qid + "') AS " + qids[i] + "_0" + Environment.NewLine;
day14String += " , JSON_VALUE([DATJSON],'$." + day14Qid + "." + day14Qid + "') AS " + qids[i] + "_14" + Environment.NewLine;
}
day0String += " FROM [Kon].[dbo].[DATA] DA WITH(NOLOCK) " + Environment.NewLine;
day0String += " where PKEY = '2201018_C' AND SURVEY_TYPE != 'TEST' AND [Status]='10' AND JSON_VALUE([DATJSON],'$.INDEX.SKUNUM') = '" + skuNum + "' " + Environment.NewLine;
day14String += " FROM [Kon].[dbo].[DATA] DA WITH(NOLOCK) " + Environment.NewLine;
day14String += " where PKEY = '2201018_E' AND SURVEY_TYPE != 'TEST' AND [Status]='10' AND JSON_VALUE([DATJSON],'$.INDEX.SKUNUM') = '" + skuNum + "' " + Environment.NewLine;
string selectString = string.Empty;
selectString += " select * " + Environment.NewLine;
selectString += " from " + Environment.NewLine;
selectString += " ( " + Environment.NewLine;
selectString += day0String;
selectString += " )DAY0 " + Environment.NewLine;
selectString += " inner join " + Environment.NewLine;
selectString += " ( " + Environment.NewLine;
selectString += day14String;
selectString += " )DAY14 " + Environment.NewLine;
selectString += " on DAY0.SCID_0 = DAY14.SCID_14 " + Environment.NewLine;
selectString += " ORDER BY SCID_0 " + Environment.NewLine;
qAllData = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getQpartAllData : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return qAllData;
}
public DataTable getABpartAllData(string skuNum, string[] qids)
{
DataTable abAllData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string selectString = string.Empty;
selectString += " select JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') AS SCID" + Environment.NewLine;
for (int i = 0; i < qids.Length; i++)
{
string qidString = " SELECT PKEY, QID FROM[Kon].[dbo].[QUESTION] WITH(NOLOCK) WHERE PKEY IN('2201018_E') AND JSON_VALUE(QUESTIONJSON,'$.variable') = '" + qids[i] + "' ORDER BY PKEY";
DataTable qidTable = dal.GetDataTable(qidString, connection);
string qid = qidTable.Rows[0]["QID"].ToString();
string selectAttr = string.Empty;
selectAttr += " SELECT QW.*" + Environment.NewLine;
selectAttr += " FROM QUESTION QU" + Environment.NewLine;
selectAttr += " CROSS APPLY OPENJSON(QU.[QUESTIONJSON]) QJ" + Environment.NewLine;
selectAttr += " CROSS APPLY OPENJSON(QJ.[VALUE]) QV" + Environment.NewLine;
selectAttr += " CROSS APPLY OPENJSON(QV.[VALUE]) QW" + Environment.NewLine;
selectAttr += " WHERE PKEY = '2201018_E' and QID = '" + qid + "' and QJ.[KEY] = 'dataset' and QV.[KEY] = 'attr'" + Environment.NewLine;
DataTable attrTable = dal.GetDataTable(selectAttr, connection);
if (attrTable.Rows.Count > 0)
{
for (int j = 1; j <= attrTable.Rows.Count; j++)
{
selectString += " , JSON_VALUE([DATJSON],'$." + qid + "." + qid + "_" + j + "') AS " + qids[i] + "_" + j + " " + Environment.NewLine;
}
}
else
{
selectString += " , JSON_VALUE([DATJSON],'$." + qid + "." + qid + "') AS " + qids[i] + " " + Environment.NewLine;
}
}
selectString += " FROM [Kon].[dbo].[DATA] DA WITH(NOLOCK) " + Environment.NewLine;
selectString += " WHERE PKEY = '2201018_E' AND SURVEY_TYPE != 'TEST' AND [Status]='10' AND JSON_VALUE([DATJSON],'$.INDEX.SKUNUM') = '" + skuNum + "' " + Environment.NewLine;
selectString += " order by JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') ";
abAllData = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getABpartAllData : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return abAllData;
}
public DataTable getEffectTable(string[] qPartQID)
{
DataTable effectTable = new DataTable();
List<string> effectName = new List<string>();
List<string> qids = new List<string>();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string selectString = string.Empty;
selectString += " SELECT [EFFECT_NAME],[EFFECT_QIDS] " + Environment.NewLine;
selectString += " FROM[kweb].[dbo].[LGHNH_REPORT_EFFECT] WITH(NOLOCK) " + Environment.NewLine;
DataTable originTable = dal.GetDataTable(selectString, connection);
foreach (string qid in qPartQID)
{
DataTable selectTable = (from DataRow dr in originTable.Rows
where Array.IndexOf(dr.Field<string>("EFFECT_QIDS").Split(','), qid) > -1
select dr).CopyToDataTable();
string eName = selectTable.Rows[0]["EFFECT_NAME"].ToString();
int eIndex = effectName.IndexOf(eName);
if (eIndex > -1)
{
qids[eIndex] += "," + qid;
}
else
{
effectName.Add(eName);
qids.Add(qid);
}
}
Common.tableAddColumn(effectTable, new string[] { "EFFECT_NAME", "EFFECT_QIDS", "RESULT_0", "RESULT_1", "RESULT_2" });
for (int i = 0; i < effectName.Count; i++)
{
string[] itemArray = new string[] { effectName[i], qids[i] };
effectTable.Rows.Add(itemArray);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getEffectTable : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return effectTable;
}
public void makeResult(DataTable effectTable, DataTable qSTable, SkuReport skuReport)
{
string target = string.Empty;
if (skuReport.pDivCode != "13" && skuReport.pDivCode != "14")
{
target = "피부의 ";
}
try
{
List<DataRow> deleteRowList = new List<DataRow>();
for (int i = 0; i < effectTable.Rows.Count; i++)
{
string[] qids = effectTable.Rows[i]["EFFECT_QIDS"].ToString().Split(',');
string effectName = effectTable.Rows[i]["EFFECT_NAME"].ToString();
string result0 = string.Empty;
string result1 = string.Empty;
string result2 = string.Empty;
string p_condition = string.Empty;
string[] result1Array = new string[qids.Length];
string[] result2Array = new string[qids.Length];
for (int j = 0; j < qids.Length; j++)
{
List<DataRow> qSRowList = (from DataRow dr in qSTable.Rows
where dr.Field<string>("QID") == qids[j]
select dr).ToList();
if (qSRowList.Count > 0)
{
DataRow qSRow = qSRowList[0];
string qtitle = qSRow["QTITLE"].ToString().Replace("현재 ", "");
double top3_0 = Convert.ToDouble(qSRow["TOP3_0"]);
double mean_0 = Convert.ToDouble(qSRow["MEAN_0"]);
double top3_14 = Convert.ToDouble(qSRow["TOP3_14"]);
double mean_14 = Convert.ToDouble(qSRow["MEAN_14"]);
p_condition = qSRow["P_CONDITION"].ToString().Replace("<", "< ");
if (String.IsNullOrEmpty(result0))
{
result0 = "본 평가제품은 체감 " + effectName.Replace("개선", "") + " 개선에 도움을 주는 것으로 판단된다.";
}
result1Array[j] = qtitle + "가 사용 0일차 " + mean_0 + "에서 사용 14일차 " + mean_14 + "로";
result2Array[j] = qtitle + "의 만족도는 " + top3_14 + "%로";
}
}
result1 = target+"체감 " + effectName + " 관련해서는 " + String.Join(", ", result1Array) + " 유의하게 증가하였다(p " + p_condition + ").";
result2 = "사용 14일차에 평가된 " + String.Join(", ", result2Array) + " 나타났다.";
effectTable.Rows[i]["RESULT_0"] = result0.Replace(" ", " ");
effectTable.Rows[i]["RESULT_1"] = result1.Replace(" ", " ");
effectTable.Rows[i]["RESULT_2"] = result2.Replace(" ", " ");
if (String.IsNullOrEmpty(effectTable.Rows[i]["RESULT_0"].ToString()))
{
deleteRowList.Add(effectTable.Rows[i]);
}
}
foreach (DataRow deleteRow in deleteRowList)
{
effectTable.Rows.Remove(deleteRow);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > makeResult : " + ex.Message);
}
}
public DataTable getSmellQAllData(string skuNum, string[] smellKey, string[] smellTime)
{
DataTable qAllData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
try
{
string onString = "on ";
string selectString = string.Empty;
string whereString = "where ";
string orderbyString = "order by ";
selectString += " select * " + Environment.NewLine;
selectString += " from " + Environment.NewLine;
for(int i = 0; i < smellKey.Length; i++)
{
if (i > 0)
{
selectString+= " full join " + Environment.NewLine;
}
selectString += " ( " + Environment.NewLine;
selectString+=" select JSON_VALUE([DATJSON], '$.INDEX.SC1_IDKEY') AS SCID_"+ smellTime[i] + Environment.NewLine;
selectString+=" , JSON_VALUE([DATJSON],'$.Q1.Q1') AS S1_"+ smellTime[i] + Environment.NewLine;
selectString+=" FROM[Kon].[dbo].[DATA] DA WITH(NOLOCK)"+Environment.NewLine;
selectString+=" where PKEY = '2201018_"+ smellKey[i] + "' AND SURVEY_TYPE != 'TEST' AND[Status] = '10' AND JSON_VALUE([DATJSON],'$.INDEX.SKUNUM') = '" + skuNum + "'"+ Environment.NewLine;
selectString += " ) TIME" + smellTime[i] + Environment.NewLine;
if (i > 0)
{
if(i > 1)
{
onString += " and";
}
onString += " TIME" + smellTime[i - 1] + ".SCID_" + smellTime[i - 1] + " = TIME" + smellTime[i] + ".SCID_" + smellTime[i] + " " + Environment.NewLine;
selectString += onString;
whereString += " or ";
orderbyString += ", ";
}
whereString += "SCID_"+ smellTime[i] + " is not null";
orderbyString += "SCID_" + smellTime[i];
}
selectString += whereString + Environment.NewLine;
selectString += orderbyString + Environment.NewLine;
qAllData = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getSmellQAllData : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return qAllData;
}
public DataTable getSmellQTable(string skuNum, string[] smellKey, string[] smellTime, string[] qids, DataTable qAllTable, double sampleSize)
{
List<DataRow> deleteRowList = new List<DataRow>();
DataTable qData = new DataTable();
DAL dal = new DAL();
var connection = dal.Connect();
string qidString = String.Join("','", qids);
qidString = "'" + qidString + "'";
try
{
string selectString = string.Empty;
selectString += " SELECT QID, QTITLE " + Environment.NewLine;
selectString += " , CAST(SUM(CASE WHEN QVALUE IN('5', '6', '7') THEN 1 ELSE 0 END) as NVARCHAR(max)) TOP3 " + Environment.NewLine;
selectString += " , ROUND(AVG(CAST(QVALUE AS FLOAT)), 2) AS MEAN " + Environment.NewLine;
selectString += " FROM " + Environment.NewLine;
selectString += " ( " + Environment.NewLine;
selectString += " select CASE WHEN DT.PKEY = '2201018_K' THEN 12 WHEN DT.PKEY = '2201018_L' THEN 24 WHEN DT.PKEY = '2201018_J' THEN 48 END AS QTITLE " + Environment.NewLine;
selectString += " , DT.QID " + Environment.NewLine;
selectString += " , DT.QVALUE AS QVALUE " + Environment.NewLine;
selectString += " from( " + Environment.NewLine;
selectString += " SELECT PKEY, DV.[KEY] COLLATE Korean_Wansung_CI_AS AS QID, DV.[VALUE] COLLATE Korean_Wansung_CI_AS AS QVALUE " + Environment.NewLine;
selectString += " FROM[Kon].[dbo].[DATA] DA WITH(NOLOCK) " + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DA.DATJSON) DJ " + Environment.NewLine;
selectString += " CROSS APPLY OPENJSON(DJ.[VALUE]) DV " + Environment.NewLine;
selectString += " where PKEY IN('2201018_K', '2201018_L', '2201018_J') AND SURVEY_TYPE != 'TEST' AND[Status] = '10' " + Environment.NewLine;
selectString += " AND JSON_VALUE([DATJSON], '$.INDEX.SKUNUM') = '"+skuNum+"' " + Environment.NewLine;
selectString += " ) DT " + Environment.NewLine;
selectString += " INNER JOIN[Kon].[dbo].[QUESTION] QU WITH(NOLOCK) ON DT.PKEY = QU.PKEY AND DT.QID = QU.QID " + Environment.NewLine;
selectString += " where JSON_VALUE(QU.QUESTIONJSON,'$.variable') IN("+ qidString + ") " + Environment.NewLine;
selectString += " ) A " + Environment.NewLine;
selectString += " where ISNUMERIC(QVALUE) = 1 or QVALUE is null " + Environment.NewLine;
selectString += " GROUP BY QID, QTITLE " + Environment.NewLine;
selectString += " ORDER BY QID " + Environment.NewLine;
qData = dal.GetDataTable(selectString, connection);
//////부호 순위 검정 붙이기
Common.SetEnableDataTableForEdit(ref qData, 0);
Common.tableAddColumn(qData, new string[] { "MRANKSUM", "DF", "P_VALUE", "P_CONDITION" });
LGSKU sku = new LGSKU();
for (int i = 0; i < qData.Rows.Count; i++)
{
string qtime = qData.Rows[i]["QTITLE"].ToString();
List<Statistics.WSRList> wsrList = new List<Statistics.WSRList>();
foreach (DataRow qAllRow in qAllTable.Rows)
{
Statistics.WSRList wsrListItem = new Statistics.WSRList();
wsrListItem.id = qAllRow["SCID_"+ qtime].ToString();
wsrListItem.xValue1 = Convert.ToDouble(qAllRow["S1_" + qtime]);
wsrListItem.xValue2 = 1.0;
wsrList.Add(wsrListItem);
}
var wsrTest = Statistics.getWilcoxonSignedRanksTest(wsrList);
string pCondition = ">0.1";
if (wsrTest.pValue < 0.001)
{
pCondition = "<0.001";
}
else if (wsrTest.pValue >= 0.001 && wsrTest.pValue < 0.01)
{
pCondition = "<0.01";
}
else if (wsrTest.pValue >= 0.01 && wsrTest.pValue < 0.05)
{
pCondition = "<0.05";
}
else if (wsrTest.pValue >= 0.05 && wsrTest.pValue < 0.1)
{
pCondition = "<0.1";
}
qData.Rows[i]["MRANKSUM"] = wsrTest.minusRankSum.ToString();
qData.Rows[i]["DF"] = (sampleSize - 1).ToString();
qData.Rows[i]["P_VALUE"] = wsrTest.pValue.ToString();
qData.Rows[i]["P_CONDITION"] = pCondition;
qData.Rows[i]["TOP3"] = Common.RoundValue(100 * Convert.ToDouble(qData.Rows[i]["TOP3"]) / sampleSize, 1);
///P_VALUE 가 < 0.05
if (wsrTest.pValue >= 0.05)
{
deleteRowList.Add(qData.Rows[i]);
}
}
foreach (DataRow deleteRow in deleteRowList)
{
qData.Rows.Remove(deleteRow);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > getSmellQTable : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return qData;
}
public DataTable makeSmellResult(DataTable qSTable, SkuReport skuReport)
{
/*
본 평가제품은 12시간 잔향 지속력이 있는 것으로 판단된다.
건조 12시간 후 향취 강도\r\n건조 12시간 후 느껴지는 실험군의 향취 강도는 0.00 수준으로 대조군 대비 유의하게 증가하였다(p < 0.001).
skuReport.pName은 12시간 잔향 지속력이 있는 것으로 판단된다.
*/
DataTable returnTable = new DataTable();
Common.tableAddColumn(returnTable, new string[] { "time", "RESULT_1", "RESULT_2", "RESULT_3" });
try
{
for(int i = 0; i < qSTable.Rows.Count; i++)
{
DataRow row = returnTable.NewRow();
row["time"] = qSTable.Rows[i]["QTITLE"].ToString();
row["RESULT_1"] = "본 평가제품은 "+ qSTable.Rows[i]["QTITLE"].ToString() + "시간 잔향 지속력이 있는 것으로 판단된다.";
row["RESULT_2"] = "건조 " + qSTable.Rows[i]["QTITLE"].ToString() + "시간 후 향취 강도\v건조 " + qSTable.Rows[i]["QTITLE"].ToString() + "시간 후 느껴지는 실험군의 향취 강도는 "+ Convert.ToDouble(qSTable.Rows[i]["MEAN"]).ToString("#0.00") + " 수준으로 대조군 대비 유의하게 증가하였다 (p "+ qSTable.Rows[i]["P_CONDITION"].ToString().Replace("<","< ") + ").";
row["RESULT_3"] = skuReport.pName+"은 "+ qSTable.Rows[i]["QTITLE"].ToString() + "시간 잔향 지속력이 있는 것으로 판단된다.";
returnTable.Rows.Add(row);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > makeSmellResult : " + ex.Message);
}
return returnTable;
}
}
}

554
JSAPI/classes/MakeWord.cs Normal file
View File

@@ -0,0 +1,554 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Office.Interop.Word;
namespace JSAPI.classes
{
public class MakeWord
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MakeWord));
//public string setWordReportLG(string skuNum, string rootPath)
public string setWordReportLG(string skuNum)
{
#region 필요한 데이터 가져오기
LGSKU sku = new LGSKU();
string[] qPartQID = sku.getQidList(skuNum, "Q");
string[] aPartQID = sku.getQidList(skuNum, "A");
LGSKU.SkuReport skuReport = sku.getSkuReportInfo(skuNum);
System.Data.DataTable effectTable = sku.getEffectTable(qPartQID);
System.Data.DataTable sqSTable = sku.getSQTable(skuNum, Convert.ToDouble(skuReport.sampleSize));
System.Data.DataTable qAllTable = sku.getQpartAllData(skuNum, qPartQID);
System.Data.DataTable qSTable = sku.getQTable(skuNum, qPartQID, qAllTable, Convert.ToDouble(skuReport.sampleSize));
System.Data.DataTable abAllTable = sku.getABpartAllData(skuNum, aPartQID);
System.Data.DataTable abSTable = sku.getABTable(skuNum, aPartQID, Convert.ToDouble(skuReport.sampleSize));
sku.makeResult(effectTable, qSTable, skuReport);
for (int i = 0; i < effectTable.Rows.Count; i++)
{
string separate2 = ", ";
if (String.IsNullOrEmpty(skuReport.effects))
{
separate2 = string.Empty;
}
skuReport.effects += separate2 + effectTable.Rows[i]["EFFECT_NAME"].ToString();
}
#endregion
object missing = System.Reflection.Missing.Value;
object outFileName = "소비자 사용테스트 결과보고서 SKU(" + skuNum + ").docx";
object wordFileName = Common.MapPath("Word_Files/소비자 사용테스트 결과보고서_TEMP.docx");
object tempFileName = Common.MapPath("Word_Files/" + Common.GetRandomString(16) + ".docx");
File.Copy(wordFileName.ToString(), tempFileName.ToString());
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Document doc = new Document();
try
{
doc = word.Documents.Open(ref tempFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.Activate();
#region 텍스트 치환
//RESULT1 -> 숫자. 내용
//RESULT2 -> 로마자. 내용
string[] originArray = new string[] { "[#PNAME#]", "[#PDIVI#]", "[#SDATE#]", "[#EDATE#]", "[#MINYEAR#]", "[#MAXYEAR#]", "[#MINAGE#]", "[#MAXAGE#]", "[#MAGE#]", "[#N#]", "[#GENDER#]", "[#EFFECTS#]" };
string[] replaceArray = new string[] { skuReport.pName, skuReport.pDiv, skuReport.sDate, skuReport.eDate, skuReport.minYear, skuReport.maxYear, skuReport.minAge, skuReport.maxAge, skuReport.meanAge, skuReport.sampleSize, skuReport.gender, skuReport.effects};
for (int i = 0; i < originArray.Length; i++)
{
FindAndReplace(doc.Application, originArray[i], replaceArray[i]);
}
for (int i = 0; i < 10; i++)
{
string replaceString1 = string.Empty;
string replaceString2 = string.Empty;
if (i < effectTable.Rows.Count)
{
replaceString1 = (i + 1) + ". " + effectTable.Rows[i]["RESULT_0"].ToString();
replaceString2 = Common.ToRoman(i + 1) + ". " + effectTable.Rows[i]["RESULT_0"].ToString();
}
FindAndReplace(doc.Application, "[#RESULT1_" + (i + 1) + "#]", replaceString1);
FindAndReplace(doc.Application, "[#RESULT2_" + (i + 1) + "#]", replaceString2);
}
/////여기 수정해야함
for (int i = 0; i < effectTable.Rows.Count; i++)
{
FindAndReplace(doc.Application, "[#BEAUTY" + (i + 1) + "#]", effectTable.Rows[i]["EFFECT_NAME"].ToString());
FindAndReplace(doc.Application, "[#B1RESULT" + (i + 1) + "#]", effectTable.Rows[i]["RESULT_1"].ToString());
FindAndReplace(doc.Application, "[#B2RESULT" + (i + 1) + "#]", effectTable.Rows[i]["RESULT_2"].ToString());
}
#endregion
#region Table 처리
for (int i = 0; i < doc.Tables.Count; i++)
{
Table table = doc.Tables[i + 1];
switch (i)
{
case 0:
//Table 안에 Table
Table subTable = table.Cell(7, 2).Tables[1];
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
subTable.Rows.Add(ref missing);
subTable.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
subTable.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 4).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 1).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString();
subTable.Cell(ti + 3, 2).Range.Text = qSTable.Rows[ti]["MEAN_0"].ToString();
subTable.Cell(ti + 3, 3).Range.Text = qSTable.Rows[ti]["MEAN_14"].ToString();
subTable.Cell(ti + 3, 4).Range.Text = qSTable.Rows[ti]["P_CONDITION"].ToString();
}
break;
case 1:
for (int ti = 0; ti < sqSTable.Rows.Count; ti++)
{
table.Cell(4 + ti, 3).Range.Text = sqSTable.Rows[ti]["sqResult"].ToString() + "%";
}
break;
case 2:
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 4).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 5).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 6).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString();
table.Cell(ti + 3, 2).Range.Text = qSTable.Rows[ti]["MEAN_0"].ToString();
table.Cell(ti + 3, 3).Range.Text = qSTable.Rows[ti]["MEAN_14"].ToString();
table.Cell(ti + 3, 4).Range.Text = qSTable.Rows[ti]["MRANKSUM"].ToString();
table.Cell(ti + 3, 5).Range.Text = qSTable.Rows[ti]["DF"].ToString();
table.Cell(ti + 3, 6).Range.Text = qSTable.Rows[ti]["P_CONDITION"].ToString();
}
break;
case 3:
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString();
table.Cell(ti + 3, 2).Range.Text = qSTable.Rows[ti]["TOP3_0"].ToString() + "%";
table.Cell(ti + 3, 3).Range.Text = qSTable.Rows[ti]["TOP3_14"].ToString() + "%";
}
break;
case 4:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Font.Size = 10;
table.Cell(ti + 3, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = abSTable.Rows[ti]["QTITLE"].ToString();
table.Cell(ti + 3, 2).Range.Text = abSTable.Rows[ti]["MEAN_14"].ToString();
table.Cell(ti + 3, 3).Range.Text = abSTable.Rows[ti]["TOP3_14"].ToString() + "%";
}
break;
case 5:
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = "Q" + (ti + 1);
table.Cell(ti + 3, 2).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString();
}
break;
case 6:
var cCnt = 2;
for (int wi = 0; wi < 2; wi++)
{
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows[1].Cells.Add(ref missing);
table.Rows[2].Cells.Add(ref missing);
if (ti == 0)
{
table.Cell(1, cCnt).Range.Text = (wi * 14) + "일차";
}
table.Cell(2, cCnt).Range.Text = "Q" + (ti + 1);
cCnt++;
}
}
//참가자 머지
table.Cell(1, 1).Merge(table.Cell(2, 1));
table.Cell(1, 2).Merge(table.Cell(1, qSTable.Rows.Count + 1));
table.Cell(1, 3).Merge(table.Cell(1, qSTable.Rows.Count + 2));
for (int ti = 0; ti < qAllTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Text = "P" + (ti + 1);
int cCnt2 = 2;
for (int wj = 0; wj < 2; wj++)
{
for (int tj = 0; tj < qSTable.Rows.Count; tj++)
{
string qQID = qSTable.Rows[tj]["QID"].ToString();
table.Cell(ti + 3, cCnt2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, cCnt2).Range.Text = qAllTable.Rows[ti][qQID + "_" + (wj * 14)].ToString();
cCnt2++;
}
}
}
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
break;
case 7:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = "Q" + (ti + 1);
table.Cell(ti + 3, 2).Range.Text = abSTable.Rows[ti]["QTITLE"].ToString();
}
break;
case 8:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows[1].Cells.Add(ref missing);
table.Cell(1, ti + 2).Range.Text = "Q" + (ti + 1);
}
for (int ti = 0; ti < abAllTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 2, 1).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 2, 1).Range.Text = "P" + (ti + 1);
for (int tj = 0; tj < abSTable.Rows.Count; tj++)
{
string abQID = abSTable.Rows[tj]["QID"].ToString();
table.Cell(ti + 2, tj + 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 2, tj + 2).Range.Text = abAllTable.Rows[ti][abQID].ToString();
}
}
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
break;
}
}
#endregion
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > setWordReportLG : " + ex.Message);
}
finally
{
//SAVE
doc.SaveAs(Common.MapPath("Word_Files/"+ outFileName), missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
File.Delete(tempFileName.ToString());
((_Document)doc).Close();
((_Application)word).Quit();
}
return outFileName.ToString();
}
public string setWordReportSmell(string skuNum)
{
#region 필요한 데이터 가져오기
LGSKU sku = new LGSKU();
string[] smellKey = new string[] { "K", "L", "J" };
string[] smellTime = new string[] { "12", "24", "48" };
string[] qPartQID = new string[] { "S1" };
string[] aPartQID = new string[] { "B0", "B1", "B2", "B3" };
LGSKU.SkuReport skuReport = sku.getSkuReportInfo(skuNum);
System.Data.DataTable sqSTable = sku.getSQTable(skuNum, Convert.ToDouble(skuReport.sampleSize));
System.Data.DataTable qAllTable = sku.getSmellQAllData(skuNum, smellKey, smellTime);
System.Data.DataTable qSTable = sku.getSmellQTable(skuNum, smellKey, smellTime, qPartQID, qAllTable, Convert.ToDouble(skuReport.sampleSize));
System.Data.DataTable abAllTable = sku.getABpartAllData(skuNum, aPartQID);
System.Data.DataTable abSTable = sku.getABTable(skuNum, aPartQID, Convert.ToDouble(skuReport.sampleSize));
System.Data.DataTable resultTable = sku.makeSmellResult(qSTable, skuReport);
#endregion
object missing = System.Reflection.Missing.Value;
object outFileName = "소비자 잔향 지속력평가 결과보고서 SKU(" + skuNum + ").docx";
object wordFileName = Common.MapPath("Word_Files/소비자 잔향 지속력평가 결과보고서_TEMP.docx");
object tempFileName = Common.MapPath("Word_Files/" + Common.GetRandomString(16) + ".docx");
File.Copy(wordFileName.ToString(), tempFileName.ToString());
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Document doc = new Document();
try
{
doc = word.Documents.Open(ref tempFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.Activate();
#region 텍스트 치환
string ptime = string.Empty;
foreach(DataRow row in qSTable.Rows)
{
if(String.IsNullOrEmpty(ptime) == false)
{
ptime += ", ";
}
ptime += row["QTITLE"].ToString() + "시간";
}
//RESULT1 -> 숫자. 내용
//RESULT2 -> 로마자. 내용
string[] originArray = new string[] { "[#PNAME#]", "[#SDATE#]", "[#PTIME#]", "[#MINYEAR#]", "[#MAXYEAR#]", "[#MINAGE#]", "[#MAXAGE#]", "[#MAGE#]", "[#N#]", "[#GENDER#]" };
string[] replaceArray = new string[] { skuReport.pName, skuReport.sDate, ptime, skuReport.minYear, skuReport.maxYear, skuReport.minAge, skuReport.maxAge, skuReport.meanAge, skuReport.sampleSize, skuReport.gender };
for (int i = 0; i < originArray.Length; i++)
{
FindAndReplace(doc.Application, originArray[i], replaceArray[i]);
}
for (int i = 0; i < 10; i++)
{
string replaceString1 = string.Empty;
string replaceString2 = string.Empty;
string replaceString3 = string.Empty;
if (i < resultTable.Rows.Count)
{
replaceString1 = resultTable.Rows[i]["RESULT_1"].ToString();
replaceString2 = resultTable.Rows[i]["RESULT_2"].ToString();
replaceString3 = resultTable.Rows[i]["RESULT_3"].ToString();
}
FindAndReplace(doc.Application, "[#RESULT1_" + (i + 1) + "#]", replaceString1);
FindAndReplace(doc.Application, "[#RESULT2_" + (i + 1) + "#]", replaceString2);
FindAndReplace(doc.Application, "[#RESULT3_" + (i + 1) + "#]", replaceString3);
}
#endregion
#region Table 처리
for (int i = 0; i < doc.Tables.Count; i++)
{
Table table = doc.Tables[i + 1];
switch (i)
{
case 0:
//Table 안에 Table
Table subTable = table.Cell(7, 2).Tables[1];
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
subTable.Rows.Add(ref missing);
subTable.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
subTable.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 4).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
subTable.Cell(ti + 3, 1).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString() + "시간 후";
subTable.Cell(ti + 3, 2).Range.Text = "1.00";
subTable.Cell(ti + 3, 3).Range.Text = qSTable.Rows[ti]["MEAN"].ToString();
subTable.Cell(ti + 3, 4).Range.Text = qSTable.Rows[ti]["P_CONDITION"].ToString();
}
break;
case 1:
for (int ti = 0; ti < sqSTable.Rows.Count; ti++)
{
table.Cell(4 + ti, 3).Range.Text = sqSTable.Rows[ti]["sqResult"].ToString() + "%";
}
break;
case 2:
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 4).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 5).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 6).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Text = qSTable.Rows[ti]["QTITLE"].ToString()+"시간 후";
table.Cell(ti + 3, 2).Range.Text = "1.00";
table.Cell(ti + 3, 3).Range.Text = qSTable.Rows[ti]["MEAN"].ToString();
table.Cell(ti + 3, 4).Range.Text = qSTable.Rows[ti]["MRANKSUM"].ToString();
table.Cell(ti + 3, 5).Range.Text = qSTable.Rows[ti]["DF"].ToString();
table.Cell(ti + 3, 6).Range.Text = qSTable.Rows[ti]["P_CONDITION"].ToString();
}
break;
case 3:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 3).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Font.Size = 10;
table.Cell(ti + 3, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = abSTable.Rows[ti]["QTITLE"].ToString();
table.Cell(ti + 3, 2).Range.Text = abSTable.Rows[ti]["MEAN_14"].ToString();
table.Cell(ti + 3, 3).Range.Text = abSTable.Rows[ti]["TOP3_14"].ToString() + "%";
}
break;
case 4:
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = "Q" + (ti + 1);
table.Cell(ti + 3, 2).Range.Text = "제품 사용 후 "+ qSTable.Rows[ti]["QTITLE"].ToString() + "시간동안 향기가 지속되는 것 같다";
}
break;
case 5:
var cCnt = 3;
for (int ti = 0; ti < qSTable.Rows.Count; ti++)
{
table.Rows[1].Cells.Add(ref missing);
table.Rows[2].Cells.Add(ref missing);
if (ti == 0)
{
table.Cell(1, cCnt).Range.Text = "실험군";
}
table.Cell(2, cCnt).Range.Text = "Q" + (ti + 1);
cCnt++;
}
//참가자 머지
table.Cell(1, 1).Merge(table.Cell(2, 1));
table.Cell(1, 2).Merge(table.Cell(2, 2));
if(qSTable.Rows.Count > 2)
{
table.Cell(1, 3).Merge(table.Cell(1, qSTable.Rows.Count + 2));
}
for (int ti = 0; ti < qAllTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 1).Range.Text = "P" + (ti + 1);
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 2).Range.Text = "1";
int cCnt2 = 3;
for (int tj = 0; tj < qSTable.Rows.Count; tj++)
{
string time = qSTable.Rows[tj]["QTITLE"].ToString();
table.Cell(ti + 3, cCnt2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, cCnt2).Range.Text = qAllTable.Rows[ti]["S1_"+ time].ToString();
cCnt2++;
}
}
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
break;
case 6:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 3, 1).Range.Shading.BackgroundPatternColor = WdColor.wdColorGray10;
table.Cell(ti + 3, 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 3, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Cell(ti + 3, 1).Range.Text = "Q" + (ti + 1);
table.Cell(ti + 3, 2).Range.Text = abSTable.Rows[ti]["QTITLE"].ToString();
}
break;
case 7:
for (int ti = 0; ti < abSTable.Rows.Count; ti++)
{
table.Rows[1].Cells.Add(ref missing);
table.Cell(1, ti + 2).Range.Text = "Q" + (ti + 1);
}
for (int ti = 0; ti < abAllTable.Rows.Count; ti++)
{
table.Rows.Add(ref missing);
table.Cell(ti + 2, 1).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 2, 1).Range.Text = "P" + (ti + 1);
for (int tj = 0; tj < abSTable.Rows.Count; tj++)
{
string abQID = abSTable.Rows[tj]["QID"].ToString();
table.Cell(ti + 2, tj + 2).Range.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
table.Cell(ti + 2, tj + 2).Range.Text = abAllTable.Rows[ti][abQID].ToString();
}
}
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
break;
}
}
#endregion
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > setWordReportSmell : " + ex.Message);
}
finally
{
//SAVE
doc.SaveAs(Common.MapPath("Word_Files/" + outFileName), missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
File.Delete(tempFileName.ToString());
((_Document)doc).Close();
((_Application)word).Quit();
}
return outFileName.ToString();
}
private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
{
//options
object matchCase = false;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundsLike = false;
object matchAllWordForms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiacritics = false;
object matchAlefHamza = false;
object matchControl = false;
object read_only = false;
object visible = true;
object replace = 2;
object wrap = 1;
//execute find and replace
doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
}
}
}

105
JSAPI/classes/Security.cs Normal file
View File

@@ -0,0 +1,105 @@
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Security.Claims;
namespace JSAPI.classes
{
public class Security
{
string kriString = "2023KRI";
/// <summary>
/// 문자열 암호화(AES256)
/// </summary>
/// <param name="InputText">암호화 할 String</param>
/// <param name="keyValue">암호화 Key값</param>
/// <returns></returns>
public string encryptString(string InputText, string keyValue)
{
string EncryptedData = "";
if(keyValue == "")
{
keyValue = kriString;
}
try
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(keyValue.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(keyValue, Salt);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainText, 0, PlainText.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
EncryptedData = Convert.ToBase64String(CipherBytes);
}
catch (Exception ex)
{
}
return EncryptedData;
}
/// <summary>
/// 문자열 복호화(AES256)
/// </summary>
/// <param name="InputText">복호화 할 String</param>
/// <param name="keyValue">복호화 Key</param>
/// <returns></returns>
public string decryptString(string InputText, string keyValue)
{
string DecryptedData = "";
if (keyValue == "")
{
keyValue = kriString;
}
try
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(keyValue.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(keyValue, Salt);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainText = new byte[EncryptedData.Length];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
}
catch (Exception ex)
{
}
return DecryptedData;
}
}
}

View File

@@ -0,0 +1,40 @@
using JSAPI.Dtos;
using System.Text;
using System.Text.Json;
namespace JSAPI.classes
{
public class SendPringoService
{
private readonly HttpClient _http;
private readonly string _apiUrl;
private readonly string _apiKey;
public SendPringoService(HttpClient http, IConfiguration config)
{
_http = http;
_apiUrl = config["PringoApiURl"] ?? config["PringoApiUrl"]
?? throw new InvalidOperationException("appsettings.json: PringoApiURl 이(가) 없습니다.");
_apiKey = config["PringoApiKey"]
?? throw new InvalidOperationException("appsettings.json: PringoApiKey 이(가) 없습니다.");
if (_http.BaseAddress is null)
_http.BaseAddress = new Uri(_apiUrl, UriKind.Absolute);
}
public async Task<(int Status, string Body, string? ContentType)> SendMailAsync(PringoParamDto pringoParam)
{
// 외부 사양과 완전히 동일한 바디 구성
var bodyParam = new SendPringoParamDto(_apiKey, "11", pringoParam);
var json = JsonSerializer.Serialize(bodyParam);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await _http.PostAsync("json-send", content);
var respBody = await resp.Content.ReadAsStringAsync();
var contentType = resp.Content.Headers.ContentType?.ToString();
return ((int)resp.StatusCode, respBody, contentType);
}
}
}

177
JSAPI/classes/Statistics.cs Normal file
View File

@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace JSAPI.classes
{
public class Statistics
{
public static double getMax(List<double> doubleList)
{
return doubleList.Max();
}
public static double getMin(List<double> doubleList)
{
return doubleList.Min();
}
public static double getStandardDeviation(List<double> doubleList)
{
double returnValue = 0.0;
double average = doubleList.Average();
double varianceSum = 0;
foreach (double value in doubleList)
{
varianceSum += (value) * (value);
}
double varianceAverage = varianceSum / doubleList.Count;
returnValue = Math.Sqrt(varianceAverage - (average * average));
return returnValue;
}
public static double getMode(List<double> doubleList)
{
double returnValue = 0.0;
returnValue = doubleList.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
return returnValue;
}
public static double getMedian(List<double> doubleList)
{
double returnValue = 0.0;
int size = doubleList.Count;
int mid = size / 2;
doubleList.Sort();
returnValue = (size % 2 != 0) ? doubleList[mid] : (doubleList[mid] + doubleList[mid - 1]) / 2;
return returnValue;
}
public class WilcoxonSignedRanks
{
public double minusRankMean { get; set; } = 0.0;
public double plusRankMean { get; set; } = 0.0;
public double minusRankSum { get; set; } = 0.0;
public double plusRankSum { get; set; } = 0.0;
public double minRankSum { get; set; } = 0.0;
public double sampleSize { get; set; } = 0.0;
public double zValue { get; set; } = 0.0;
public double pValue { get; set; } = 0.0;
}
public class WSRList
{
public string id { get; set; } = string.Empty;
public double xValue1 { get; set; } = 0.0;
public double xValue2 { get; set; } = 0.0;
public double diff { get; set; } = 0.0;
public double absDiff { get; set; } = 0.0;
}
public class RankList
{
public double value { get; set; } = 0.0;
public double rank { get; set; } = 0.0;
public double frequency { get; set; } = 0.0;
}
static public WilcoxonSignedRanks getWilcoxonSignedRanksTest(List<WSRList> wsrList)
{
WilcoxonSignedRanks wilcoxonSignedRanks = new WilcoxonSignedRanks();
//xList = xList.OrderBy(x => x.id).ToList();
#region 차이, 차이 절댓값 계산
for (int i = 0; i < wsrList.Count; i++)
{
wsrList[i].diff = wsrList[i].xValue2 - wsrList[i].xValue1;
wsrList[i].absDiff = Math.Abs(wsrList[i].diff);
}
#endregion
#region 차이가 0인 샘플 삭제
wsrList = wsrList.Where(x => x.diff != 0.0).ToList();
#endregion
#region rank 기입
List<double> absDiffList = wsrList.Select(x => x.absDiff).Distinct().OrderBy(x => x).ToList();
List<RankList> rankList = new List<RankList>();
double accumulateCount = 0.0;
double frequencySum = 0.0;
for (int i = 0; i < absDiffList.Count(); i++)
{
double xValue = absDiffList[i];
double xCount = wsrList.Where(x => x.absDiff == xValue).ToList().Count();
double frequency = (Math.Pow(xCount, 3) - xCount) / 48;
RankList rankListItem = new RankList();
rankListItem.value = xValue;
rankListItem.rank = (accumulateCount + 1) + ((xCount - 1) / 2);
rankListItem.frequency = frequency;
rankList.Add(rankListItem);
frequencySum += frequency;
accumulateCount += xCount;
}
#endregion
#region 계산
double sampleSize = wsrList.Count;
double plusCount = 0.0;
double plusRankSum = 0.0;
double minusCount = 0.0;
double minusRankSum = 0.0;
double minRankSum = 0.0;
double denominator = 0.0; // 분모
double numerator = 0.0; //분자
for (int i = 0; i < wsrList.Count; i++)
{
double xRank = rankList.Where(x => x.value == wsrList[i].absDiff).Select(x => x.rank).ToList()[0];
if (wsrList[i].diff > 0)
{
plusCount++;
plusRankSum += xRank;
}
else if (wsrList[i].diff < 0)
{
minusCount++;
minusRankSum += xRank;
}
}
if (plusRankSum > minusRankSum)
{
minRankSum = minusRankSum;
}
else
{
minRankSum = plusRankSum;
}
denominator = Math.Sqrt(((sampleSize * (sampleSize + 1) * (2 * sampleSize + 1)) / 24) - frequencySum);
numerator = minRankSum - (sampleSize * (sampleSize + 1)) / 4;
#endregion
wilcoxonSignedRanks.plusRankSum = plusRankSum;
wilcoxonSignedRanks.plusRankMean = plusRankSum / plusCount;
wilcoxonSignedRanks.minusRankSum = minusRankSum;
wilcoxonSignedRanks.minusRankMean = minusRankSum / minusCount;
wilcoxonSignedRanks.minRankSum = minRankSum;
wilcoxonSignedRanks.sampleSize = sampleSize;
wilcoxonSignedRanks.zValue = numerator / denominator;
wilcoxonSignedRanks.pValue = Accord.Math.Special.Erfc(Math.Abs(wilcoxonSignedRanks.zValue) / Math.Sqrt(2));
return wilcoxonSignedRanks;
}
}
}

25
JSAPI/log4net.config Normal file
View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs/" />
<datepattern value="yyyy-MM-dd.'txt'"/>
<maxSizeRollBackups value="10" />
<maximumFileSize value="1024KB" />
<staticlogfilename value="false"/>
<appendtofile value="true"/>
<rollingstyle value="Composite"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>