using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using REPORT_API_ver6.Models;
namespace REPORT_API_ver6.Services
{
public class Project
{
static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Project));
///
/// KON 프로젝트 리스트 반환
///
/// KRI 팀
/// USER
/// 1:KRI사람, 2:외부인
/// KON 프로젝트 리스트
public DataTable getProjectList(string gkey, string mkey, string isAdmin)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
for (int i = 0; i < 2; i++)
{
string sqlString = "select " + i + " as [iskiwi], '' AS ROWN,";
if (i == 1)
{
sqlString += " '|K|W|' +";
}
sqlString += " PKEY as PKEY,";
sqlString += " cast('' as nvarchar(max)) as security,";
sqlString += " ";
if (i == 1)
{
sqlString += " 'KIWI - ' +";
}
sqlString += " JSON_VALUE(PROJECTJSON, '$.title_inner') as title,"; ///타이틀 여기
sqlString += " JSON_VALUE(PROJECTJSON, '$.surveytype') as [surveytype],";
sqlString += " JSON_VALUE(PROJECTJSON, '$.status') as [status],";
sqlString += " GKEY,";
sqlString += " MKEY,";
sqlString += " create_date";
sqlString += " from" + Environment.NewLine;
sqlString += " (" + Environment.NewLine;
sqlString += " SELECT PKEY, GKEY, MKEY, JSON_QUERY(PROJECTJSON, '$.must') as PROJECTJSON, create_date" + Environment.NewLine;
sqlString += " FROM PROJECT with(nolock) where PKEY <> ''" + Environment.NewLine;
sqlString += " and (create_date >= CONVERT(CHAR(10), DATEADD(YEAR, -1, GETDATE()), 23)";
if (i == 1)
{
sqlString += " or JSON_VALUE(PROJECTJSON, '$.must.surveyclass') = '1'";
}
sqlString += ")";
sqlString += " and JSON_VALUE(PROJECTJSON, '$.must.title_inner') not like '%사례비%'" + Environment.NewLine;
sqlString += " and JSON_VALUE(PROJECTJSON, '$.must.companytype') not in ('4', '5')" + Environment.NewLine;
if (gkey != "M101" && isAdmin != "0")
{
sqlString += " AND GKEY <> 'M101'" + Environment.NewLine;
}
else if (isAdmin == "4")//BC팀(M101이면서 JOB이 제작)은 KIWI 퀵서베이는 보이게
{
//sqlString += " and JSON_VALUE(PROJECTJSON, '$.must.title_inner') like '%kiwisurvey%' ";
}
else if (gkey.StartsWith("R") || gkey == "M101")//AI 빅데이터 제외
{
sqlString += " and GKEY = '" + gkey + "'" + Environment.NewLine;
}
//if (gkey.StartsWith("R") || gkey == "M101" || gkey.StartsWith("A"))//AI 빅데이터 포함
if (Convert.ToInt32(isAdmin) > 5)
{
sqlString += " and pkey in (" + getAssignPkeys(mkey) + ")" + Environment.NewLine;
}
sqlString += " ) a" + Environment.NewLine;
sqlString += " where JSON_VALUE(PROJECTJSON, '$.status') in (2, 3)" + Environment.NewLine;
sqlString += " and MKEY not in (" + User.getDinIDs() + ")" + Environment.NewLine;
sqlString += " order by create_date desc" + Environment.NewLine;
var connection = dal.ConnectKonKiwi(i);
try
{
if (returnTable.Rows.Count.Equals(0)) returnTable = dal.GetDataTable(sqlString, connection);
else returnTable.Merge(dal.GetDataTable(sqlString, connection));
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
}
if (returnTable.Rows.Count > 0)
{
Security security = new Security();
returnTable = returnTable.Select("", "create_date DESC").CopyToDataTable();
//키위를 이어 붙였기 때문에 다시 오더바이
for (int i = 0; i < returnTable.Rows.Count; i++)
{
returnTable.Rows[i]["ROWN"] = (i + 1).ToString();
string encPkey = security.encryptString(returnTable.Rows[i]["PKEY"].ToString());
returnTable.Rows[i]["security"] = WebUtility.UrlEncode(encPkey);
}
}
return returnTable;
}
public DataTable getProjectList(string intranetCd, string gkey, int iskiwi, string keyword)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
string sqlString = "";
sqlString += $" SELECT pkey," + Environment.NewLine;
sqlString += $" JSON_VALUE(PROJECTJSON, '$.must.title_inner') as title," + Environment.NewLine;
sqlString += $" JSON_VALUE(PROJECTJSON, '$.must.surveytype') as [surveyType]," + Environment.NewLine;
sqlString += $" JSON_VALUE(PROJECTJSON, '$.must.status') as [status]," + Environment.NewLine;
sqlString += $" gkey, mkey, create_date as createDate " + Environment.NewLine;
sqlString += $" FROM PROJECT with(nolock) " + Environment.NewLine;
sqlString += $" WHERE PKEY <> '' " + Environment.NewLine;
if (gkey.StartsWith("R"))
{
sqlString += $" AND GKEY = '{gkey}' " + Environment.NewLine;
}
else
{
sqlString += $" AND GKEY <> 'M101'" + Environment.NewLine;
}
if (String.IsNullOrEmpty(keyword))
{
sqlString += $" AND PKEY like '%{intranetCd}%' " + Environment.NewLine;
}
else
{
sqlString += $" AND ( " + Environment.NewLine;
sqlString += $" PKEY like '%{keyword}%'" + Environment.NewLine;
sqlString += $" OR JSON_VALUE(PROJECTJSON, '$.must.title_inner') like '%{keyword}%'" + Environment.NewLine;
sqlString += $" )" + Environment.NewLine;
}
sqlString += " ORDER BY create_date DESC" + Environment.NewLine;
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// KON 프로젝트 상세 정보 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// KON 프로젝트 상세 정보
public DataTable getProjectInfo(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
string sqlString = "";
sqlString += " select PKEY, GKEY, MKEY" + Environment.NewLine;
sqlString += " ,JSON_value(PROJECTJSON, '$.title_inner') as title" + Environment.NewLine; ///타이틀 여기
sqlString += " ,JSON_value(PROJECTJSON, '$.surveytype') as surveytype" + Environment.NewLine;
sqlString += " ,JSON_value(PROJECTJSON, '$.status') as [status]" + Environment.NewLine;
sqlString += " ,JSON_value(PROJECTJSON, '$.description') as [description]" + Environment.NewLine;
sqlString += " from (" + Environment.NewLine;
sqlString += " SELECT PKEY, GKEY, MKEY, JSON_QUERY(PROJECTJSON, '$.must') as PROJECTJSON, create_date" + Environment.NewLine;
sqlString += " FROM PROJECT with(nolock) where PKEY <> ''" + Environment.NewLine;
sqlString += " ) a where PKEY = '" + pkey + "'";
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 팀 코드로 팀명 반환
///
/// 팀 코드
/// 팀명
public string getProjectTeamName(string gkey)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectIntra();
try
{
returnValue = dal.GetDataTable("SELECT T_Name FROM project2.dbo.v_Department with(nolock) where Code='" + gkey + "'", connection).Rows[0]["T_Name"].ToString();
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 진행중 이거나 완료인 상위 6개 프로젝트 반환
///
/// 팀코드
/// USER
/// 0:admin, 1:DCO, 5:다른 팀, 7:client, 9:외부 링크
/// 가져올 프로젝트 개수
/// 진행중 이거나 완료인 상위 6개 프로젝트
public DataTable lastProjectCount(string team, string mkey, string isAdmin, int getCount)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
int isKiwi = 0;
string sqlString = "";
if (isAdmin == "4" || isAdmin == "6") isKiwi = 1;//BC팀(M101이면서 JOB이 제작)은 KIWI 퀵서베이는 보이게
sqlString += " select" + Environment.NewLine;
sqlString += " top("+ getCount + ") *" + Environment.NewLine;
sqlString += " from(" + Environment.NewLine;
sqlString += " select" + Environment.NewLine;
if (isKiwi == 1) sqlString += " '|K|W|' +";
sqlString += " b.PKEY as PKEY" + Environment.NewLine;
sqlString += " ,cast('' as nvarchar(max)) as security" + Environment.NewLine;
sqlString += " , sum(isnull(allCount, 0)) as allCount" + Environment.NewLine;
sqlString += " , sum(isnull(ongoingCount, 0)) as ongoingCount" + Environment.NewLine;
sqlString += " , sum(isnull(screenCount, 0)) as screenCount" + Environment.NewLine;
sqlString += " , sum(isnull(quotaCount, 0)) as quotaCount" + Environment.NewLine;
sqlString += " , sum(isnull(completeCount, 0)) as completeCount" + Environment.NewLine;
sqlString += " , JSON_value(PROJECTJSON, '$.must.title_inner') as [title]" + Environment.NewLine; ///타이틀 여기
sqlString += " , JSON_value(PROJECTJSON, '$.must.surveytype') as [surveytype]" + Environment.NewLine;
sqlString += " , JSON_value(PROJECTJSON, '$.must.status') as [status]" + Environment.NewLine;
sqlString += " , b.ID" + Environment.NewLine;
sqlString += " from(" + Environment.NewLine;
sqlString += " SELECT PKEY" + Environment.NewLine;
sqlString += " , count(*) as allCount" + Environment.NewLine;
sqlString += " ,case when[Status] = 1 then count(*) end as ongoingCount" + Environment.NewLine;
sqlString += " ,case when[Status] = 99 then count(*) end as screenCount" + Environment.NewLine;
sqlString += " ,case when[Status] = 98 then count(*) end as quotaCount" + Environment.NewLine;
sqlString += " ,case when[Status] = 10 then count(*) end as completeCount" + Environment.NewLine;
sqlString += " FROM [DATA] with(nolock)" + Environment.NewLine;
sqlString += " where SURVEY_TYPE != 'TEST' and[Status] != 999" + Environment.NewLine;
sqlString += " group by PKEY, [Status]" + Environment.NewLine;
sqlString += " ) a" + Environment.NewLine;
sqlString += " inner join (select top(50) * from PROJECT with(nolock)" + Environment.NewLine;
sqlString += " where JSON_value(JSON_QUERY(PROJECTJSON, '$.must'), '$.status') != 1" + Environment.NewLine;
sqlString += " and JSON_VALUE(PROJECTJSON, '$.must.companytype') not in ('4', '5')" + Environment.NewLine;
sqlString += " and MKEY not in (" + User.getDinIDs() + ")" + Environment.NewLine;
if (team != "M101" && isAdmin != "0")
{
sqlString += " AND GKEY <> 'M101' " + Environment.NewLine;
}
else if (isAdmin == "4")//BC팀(M101이면서 JOB이 제작)은 KIWI 퀵서베이는 보이게
{
sqlString += " and JSON_value(PROJECTJSON, '$.must.title_inner') like '%kiwisurvey%' ";
}
else if (team.StartsWith("R") || team == "M101")//AI 빅데이터 제외
{
sqlString += " and GKEY = '" + team + "'" + Environment.NewLine;
}
//if (team.StartsWith("R") || team.StartsWith("A"))//AI 빅데이터 포함
if (Convert.ToInt32(isAdmin) > 5)
{
sqlString += " and pkey in (" + getAssignPkeys(mkey) + ")" + Environment.NewLine;
}
sqlString += " order by ID desc" + Environment.NewLine;
sqlString += " ) b on a.PKEY = b.PKEY" + Environment.NewLine;
sqlString += " group by b.PKEY, b.ID, b.PROJECTJSON" + Environment.NewLine;
sqlString += " )out_a" + Environment.NewLine;
sqlString += " where [status] != 1" + Environment.NewLine;
sqlString += " order by [status], ID desc" + Environment.NewLine;
var connection = dal.ConnectKonKiwi(isKiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
Security security = new Security();
for (int i = 0; i < returnTable.Rows.Count; i++)
{
string encPkey = security.encryptString(returnTable.Rows[i]["PKEY"].ToString());
returnTable.Rows[i]["security"] = WebUtility.UrlEncode(encPkey);
returnTable.Rows[i]["surveytype"] = setProjectTypeStatus(0, returnTable.Rows[i]["surveytype"].ToString());
returnTable.Rows[i]["status"] = setProjectTypeStatus(1, returnTable.Rows[i]["status"].ToString());
}
return returnTable;
}
///
/// User에게 배정된 프로젝트 개수 반환
///
/// User
/// User에게 배정된 프로젝트 개수
public short getAssignCount(string mkey)
{
short returnValue = 0;
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
var assignCountTable = dal.GetDataTable("SELECT count(*) as p_cnt FROM [REPORT_ASSIGN] where member_mail = '" + mkey + "'", connection);
if (assignCountTable.Rows.Count > 0)
{
returnValue = Convert.ToInt16(assignCountTable.Rows[0][0]);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// User에게 배정된 프로젝트 Key들 반환
///
/// User
/// User에게 배정된 프로젝트 Key들
public string getAssignPkeys(string mkey)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
//var assignTable = dal.GetDataTable("SELECT [pkey] FROM [REPORT_ASSIGN] where member_mail = '" + mkey + "' and is_use = 1", connection);
var assignTable = dal.GetDataTable("SELECT [pkey] FROM [REPORT_ASSIGN] where member_mail = '" + mkey + "'", connection);
if (assignTable.Rows.Count > 0)
{
returnValue = string.Join(",", assignTable.Rows.OfType().Select(r => "'" + r["pkey"].ToString() + "'"));
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// KON에 등록된 현황페이지 URL 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// KON에 등록된 현황페이지 URL
public DataTable getKonReportURL(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
string sqlString = "";
sqlString += " SELECT 0 as [append_order], 1 as [append_type], JSON_VALUE([PROJECTJSON],'$.must.report') as [file_name] ";
sqlString += " FROM [PROJECT] with(nolock) ";
sqlString += " where pkey = '" + pkey + "' and JSON_VALUE([PROJECTJSON],'$.must.report') <> '' ";
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// Report에 등록한 현황 페이지 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// Report에 등록한 현황 페이지
public DataTable projectIncludeFiles(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
string sqlString = "";
sqlString += " select append_order,append_type,";
sqlString += " case when append_type = 0 then'../report_append/' +[pkey] + '/' +[file_name]";
sqlString += " when append_type = 1 then 'https://kon.kric.com/project/' +[pkey] + '/' +[file_name]";
sqlString += " when append_type = 2 then[file_name] end as [file_name]";
sqlString += " FROM [REPORT_KON].[dbo].[REPORT_APPEND] with(nolock)";
sqlString += " where pkey = '" + pkey + "'";
sqlString += " order by append_order";
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 프로젝트의 상태별 Sample Count 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 일자 범위 JSON
/// 프로젝트의 상태별 Sample Count
public DataTable projectStateCount(string pkey, int iskiwi, string selectDate)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
string sqlString = "";
sqlString += " select";
sqlString += " sum(isnull(allCount, 0)) as allCount";
sqlString += " ,sum(isnull(ongoingCount, 0)) as ongoingCount";
sqlString += " ,sum(isnull(screenCount, 0)) as screenCount";
sqlString += " ,sum(isnull(quotaCount, 0)) as quotaCount";
sqlString += " ,sum(isnull(completeCount, 0)) as completeCount";
sqlString += " from(";
sqlString += " SELECT PKEY";
sqlString += " , count(*) as allCount";
sqlString += " ,case when[Status] = 1 then count(*) end as ongoingCount";
sqlString += " ,case when[Status] = 99 then count(*) end as screenCount";
sqlString += " ,case when[Status] = 98 then count(*) end as quotaCount";
sqlString += " ,case when[Status] = 10 then count(*) end as completeCount";
sqlString += " FROM [DATA] with(nolock)";
sqlString += " where SURVEY_TYPE != 'TEST' and [Status] != 999 and PKEY = '" + pkey + "'";
if (Common.IsJson(selectDate))
{
JObject sqlDate = Common.GetJObjectFromString(selectDate);
if(sqlDate.Count > 0)
{
sqlString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) >= CONVERT(DATE,'" + sqlDate["sDate"].ToString() + "')";
sqlString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) <= CONVERT(DATE,'" + sqlDate["eDate"].ToString() + "')";
}
}
sqlString += " group by PKEY, [Status]";
sqlString += " ) a";
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 프로젝트의 일자별 완료 개수 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 프로젝트의 일자별 완료 개수
public DataTable getDayComplete(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += " select";
sqlString += " CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112) as survey_date";
sqlString += " ,count(*) as complete_count";
sqlString += " from [data] with(nolock)";
sqlString += " where pkey = '" + pkey + "' and survey_type<>'test' and status = 10";
sqlString += " group by CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112)";
sqlString += " order by CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112)";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 프로젝트의 일자별 상태별 개수 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 일자 범위 JSON
/// 프로젝트의 상태별 개수
public DataTable getTypeByState(string pkey, int iskiwi, string selectDate)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += " select";
//sqlString += " survey_type";
sqlString += " count(1) as total_count";
sqlString += " ,ISNULL(SUM(case when [Status] = '10' then 1 else 0 end), 0) as complete_count";
sqlString += " ,ISNULL(SUM(case when [Status] = '99' then 1 else 0 end), 0) as screen_count";
sqlString += " ,ISNULL(SUM(case when [Status] = '98' then 1 else 0 end), 0) as quota_count";
sqlString += " ,ISNULL(SUM(case when [Status] = '1' then 1 else 0 end), 0) as going_count";
sqlString += " from[data] with(nolock)";
sqlString += " where pkey = '" + pkey + "' and survey_type <>'test' and [Status] in ('10', '99', '98', '1')";
if (Common.IsJson(selectDate))
{
JObject sqlDate = Common.GetJObjectFromString(selectDate);
if (sqlDate.Count > 0)
{
sqlString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) >= CONVERT(DATE,'" + sqlDate["sDate"].ToString() + "')";
sqlString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) <= CONVERT(DATE,'" + sqlDate["eDate"].ToString() + "')";
}
}
//sqlString += " group by survey_type";
//sqlString += " order by survey_type";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// LOI 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 일자 범위 JSON
/// LOI
public DataTable getLOI(string pkey, int iskiwi, string selectDate)
{
DataTable returnTable = new DataTable();
string sqlString = "";
string dateString = "";
if (Common.IsJson(selectDate))
{
JObject sqlDate = Common.GetJObjectFromString(selectDate);
if (sqlDate.Count > 0)
{
dateString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) >= CONVERT(DATE,'" + sqlDate["sDate"].ToString() + "')";
dateString += " and CONVERT(DATE, dbo.FN_LAST_TIME(survey_date)) <= CONVERT(DATE,'" + sqlDate["eDate"].ToString() + "')";
}
}
sqlString += "SELECT" + Environment.NewLine;
sqlString += "SUM(CNT) AS CNT" + Environment.NewLine;
sqlString += ", CAST(SUM(AVG_LOI) AS NVARCHAR(16)) AS AVG_LOI" + Environment.NewLine;
sqlString += ", CAST(SUM(AVG_LOI_MODIFY) AS NVARCHAR(16)) AS AVG_LOI_MODIFY" + Environment.NewLine;
sqlString += ", CAST(SUM(MIN_LOI) AS NVARCHAR(16)) AS MIN_LOI" + Environment.NewLine;
sqlString += ", CAST(SUM(MAX_LOI) AS NVARCHAR(16)) AS MAX_LOI" + Environment.NewLine;
sqlString += "FROM (" + Environment.NewLine;
sqlString += " SELECT 0 AS CNT" + Environment.NewLine;
sqlString += " , 0 AS AVG_LOI" + Environment.NewLine;
sqlString += " , 0 AS AVG_LOI_MODIFY" + Environment.NewLine;
sqlString += " , 0 AS MIN_LOI" + Environment.NewLine;
sqlString += " , 0 AS MAX_LOI" + Environment.NewLine;
sqlString += " UNION ALL" + Environment.NewLine;
sqlString += " SELECT CNT" + Environment.NewLine;
sqlString += " , AVG(LOI) AS AVG_LOI" + Environment.NewLine;
sqlString += " , AVG(CASE WHEN ROWNUM < (CNT - CNT * 0.025) AND ROWNUM > CNT * 0.025 THEN LOI ELSE NULL END) AS AVG_LOI_MODIFY" + Environment.NewLine;
sqlString += " , MIN(LOI) AS MIN_LOI" + Environment.NewLine;
sqlString += " , MAX(LOI) AS MAX_LOI" + Environment.NewLine;
sqlString += " FROM("+Environment.NewLine;
sqlString += " SELECT"+Environment.NewLine;
sqlString += " ROW_NUMBER() OVER(ORDER BY LOI) AS ROWNUM"+Environment.NewLine;
sqlString += " , LOI"+Environment.NewLine;
sqlString += " , CNT"+Environment.NewLine;
sqlString += " FROM("+Environment.NewLine;
sqlString += " SELECT"+Environment.NewLine;
sqlString += " DATEDIFF(ss, CONVERT(DATETIME, dbo.FN_START_TIME(survey_date)), CONVERT(DATETIME, dbo.FN_LAST_TIME(survey_date))) as LOI"+Environment.NewLine;
sqlString += " , ("+Environment.NewLine;
sqlString += " SELECT COUNT(1)"+Environment.NewLine;
sqlString += " FROM[DATA] with(nolock)"+Environment.NewLine;
sqlString += " WHERE PKEY = '" + pkey + "' and SURVEY_TYPE <> 'test' and[Status] = '10'" + Environment.NewLine;
if (String.IsNullOrEmpty(dateString) == false)
{
sqlString += dateString + Environment.NewLine;
}
sqlString += " ) AS CNT"+Environment.NewLine;
sqlString += " FROM[DATA] with(nolock)"+Environment.NewLine;
sqlString += " WHERE PKEY = '" + pkey + "' and SURVEY_TYPE <> 'test' and[Status] = '10'" + Environment.NewLine;
if (String.IsNullOrEmpty(dateString) == false)
{
sqlString += dateString + Environment.NewLine;
}
sqlString += " )IN_A"+Environment.NewLine;
sqlString += " ) OUT_A"+Environment.NewLine;
sqlString += " GROUP BY CNT" + Environment.NewLine;
sqlString += ") LOI";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
if(returnTable.Rows.Count > 0)
{
for (int column = 1; column < 5; column++)
{
returnTable.Rows[0][column] = Common.SecondToTime(returnTable.Rows[0][column].ToString());
}
}
return returnTable;
}
///
/// 프로젝트의 일자별 상태별 개수 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 프로젝트의 상태별 개수
public DataTable getDayByState(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += " select";
sqlString += " CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112) as survey_date";
sqlString += " ,count(1) as total_count";
sqlString += " ,sum(case when[Status] = '10' then 1 else 0 end) as complete_count";
sqlString += " ,sum(case when[Status] = '99' then 1 else 0 end) as screen_count";
sqlString += " ,sum(case when[Status] = '98' then 1 else 0 end) as quota_count";
sqlString += " from [data] with(nolock)";
sqlString += " where pkey = '" + pkey + "' and survey_type<>'test' and [Status] in ('10', '99', '98', '1') and json_value(survey_date, '$.INDEX') is not null";
sqlString += " group by CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112)";
sqlString += " order by CONVERT(CHAR(10), dbo.FN_LAST_TIME(survey_date), 112)";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 프로젝트의 문항별 스크린 아웃 개수 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 일자 범위 JSON
/// 프로젝트의 문항별 스크린 아웃 개수
public DataTable getQidByScreen(string pkey, int iskiwi, string selectDate)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += $"WITH SD AS ( " + Environment.NewLine;
sqlString += $" SELECT " + Environment.NewLine;
sqlString += $" IN_DA.pkey, " + Environment.NewLine;
sqlString += $" IN_DA.idkey, " + Environment.NewLine;
sqlString += $" IN_SD.[key] AS last_key, " + Environment.NewLine;
sqlString += $" IN_SD.[value] AS last_time, " + Environment.NewLine;
sqlString += $" ROW_NUMBER() OVER ( " + Environment.NewLine;
sqlString += $" PARTITION BY IN_DA.pkey, IN_DA.idkey " + Environment.NewLine;
sqlString += $" ORDER BY IN_SD.[value] DESC -- MAX 기준 " + Environment.NewLine;
sqlString += $" ) AS rn " + Environment.NewLine;
sqlString += $" FROM [data] IN_DA WITH (NOLOCK) " + Environment.NewLine;
sqlString += $" CROSS APPLY OPENJSON(IN_DA.survey_date) AS IN_SD " + Environment.NewLine;
sqlString += $" WHERE IN_DA.pkey = '{pkey}' " + Environment.NewLine;
sqlString += $" AND IN_DA.survey_type <> 'test' " + Environment.NewLine;
sqlString += $" AND IN_DA.[Status] = '99' " + Environment.NewLine;
sqlString += $") " + Environment.NewLine;
sqlString += $" SELECT Qorder " + Environment.NewLine;
sqlString += $" , JSON_VALUE(QUESTIONJSON,'$.variable') + '. '+ CASE WHEN JSON_VALUE(QUESTIONJSON, '$.explain') = '' THEN JSON_VALUE(QUESTIONJSON,'$.title') ELSE JSON_VALUE(QUESTIONJSON,'$.explain') END as VIEWTITLE " + Environment.NewLine;
sqlString += $" , JSON_VALUE(QUESTIONJSON,'$.variable') as PAGENAME " + Environment.NewLine;
sqlString += $" , count(1) as CNT " + Environment.NewLine;
sqlString += $" FROM ( " + Environment.NewLine;
sqlString += $" SELECT SD.IDKEY, Qorder, QUESTIONJSON " + Environment.NewLine;
sqlString += $" from SD " + Environment.NewLine;
sqlString += $" inner join [QUESTION] QU with(nolock) on SD.PKEY = QU.PKEY and SD.last_key COLLATE Korean_Wansung_CI_AS = QU.QID " + Environment.NewLine;
sqlString += $" WHERE SD.rn = 1 " + Environment.NewLine;
if (Common.IsJson(selectDate))
{
JObject sqlDate = Common.GetJObjectFromString(selectDate);
if (sqlDate.Count > 0)
{
sqlString += " and CONVERT(DATE, SD.LAST_TIME) >= CONVERT(DATE,'" + sqlDate["sDate"].ToString() + "')" + Environment.NewLine;
sqlString += " and CONVERT(DATE, SD.LAST_TIME) <= CONVERT(DATE,'" + sqlDate["eDate"].ToString() + "')" + Environment.NewLine;
}
}
sqlString += $" ) OUT_A " + Environment.NewLine;
sqlString += $" group by Qorder,QUESTIONJSON " + Environment.NewLine;
sqlString += $" order by Qorder " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// KON에서 저장된 실제 QID로 변환
///
/// 프로젝트 Key
/// 변환할 String
/// 1:키위 프로젝트, 0:KON 프로젝트
/// KON에서 저장된 실제 QID
public string convertQID(string pkey, string inputString, int iskiwi)
{
//보류
if (String.IsNullOrEmpty(inputString) == false)
{
DataTable questionTable = getQuestionList(pkey, "", iskiwi,"0");
string[] opArray = { "and", "or", "in", "between" };
Regex qidRegex = new Regex(@"((? qidMatches = qidRegex.Matches(inputString).OfType().Select(m => m.Groups[0].Value).Distinct().ToList();
for (int i = 0; i < qidMatches.Count; i++)
{
var qidString = qidMatches[i].ToLower();
if (Array.IndexOf(opArray, qidString) < 0)
{
/*
var qidList = (from DataRow dr in questionTable.Rows
where dr.Field("VARIABLE").ToUpper() == qidMatches[i].ToUpper()
select dr.Field("QID")).ToList();
*/
var qidList = questionTable.AsEnumerable().Where(dr => dr.Field("VARIABLE").ToUpper() == qidMatches[i].ToUpper()).Select(dr => dr.Field("QID")).ToList();
if (qidList.Count > 0)
{
inputString = Regex.Replace(inputString, @"((?
/// 문항 List 반환
///
/// 프로젝트 Key
/// KON QID
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 문항 List
public DataTable getQuestionList(string pkey, string qID, int iskiwi, string isAdmin, int isGuid = 0)
{
DataTable qlistTable = new DataTable();
string sqlString = "";
sqlString += " SELECT " + Environment.NewLine;
sqlString += " QID " + Environment.NewLine;
sqlString += " , Qorder " + Environment.NewLine;
sqlString += " , VARIABLE " + Environment.NewLine;
sqlString += " , TITLE " + Environment.NewLine;
sqlString += " , case when EXPLAIN = '' then TITLE else EXPLAIN end as EXPLAIN " + Environment.NewLine;
sqlString += " , case when QTYPE = 'attr' or QTYPE = 'com' then QTYPE else 'normal' end as VTYPE" + Environment.NewLine;
sqlString += " , case when QTYPE = 'attr' then QTYPE2 else QTYPE end as QTYPE" + Environment.NewLine;
sqlString += " , IS_NPS" + Environment.NewLine;
sqlString += " , IS_REVERSE" + Environment.NewLine;
sqlString += " , MISSING_VALUE" + Environment.NewLine;
sqlString += " , ATTR_INFO " + Environment.NewLine;
sqlString += " , RANK_INFO " + Environment.NewLine;
sqlString += " , JSON_query([QUESTIONJSON],'$.dataset.' + QTYPE2) as LABEL_INFO " + Environment.NewLine;
sqlString += " , AFTER_LOGIC " + Environment.NewLine;
sqlString += " , IS_DERIVED, DERIVEDJSON, GKEY, MKEY" + Environment.NewLine;
sqlString += " FROM " + Environment.NewLine;
sqlString += " ( " + Environment.NewLine;
sqlString += " SELECT QID " + Environment.NewLine;
sqlString += " , Qorder " + Environment.NewLine;
sqlString += " , QUESTIONJSON " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.variable'), '') as VARIABLE " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.title'),'') as TITLE " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.explain'),'') as EXPLAIN " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.qtype'),'') as QTYPE " + Environment.NewLine;
sqlString += " , isnull(JSON_query([QUESTIONJSON], '$.dataset.attr'),'') as ATTR_INFO " + Environment.NewLine;
sqlString += " , isnull(JSON_query([QUESTIONJSON], '$.dataset.rank'),'') as RANK_INFO " + Environment.NewLine;
sqlString += " , case when JSON_query([QUESTIONJSON],'$.dataset.single') is not null then 'single' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.scale') is not null then 'scale' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.multi') is not null then 'multi' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.open') is not null then 'open' end as QTYPE2 " + Environment.NewLine;
sqlString += " , isnull(JSON_value([QUESTIONJSON], '$.option.npsFlag'),'0') as IS_NPS " + Environment.NewLine;
sqlString += " , isnull(JSON_value([QUESTIONJSON], '$.option.reverseFlag'),'0') as IS_REVERSE " + Environment.NewLine;
sqlString += " , isnull(JSON_value([QUESTIONJSON], '$.option.missingValue'),'') as MISSING_VALUE " + Environment.NewLine;
sqlString += " , JSON_query([QUESTIONJSON],'$.dataset') as DATASET " + Environment.NewLine;
sqlString += " ,case when isjson(LOGICJSON) = 1 then JSON_QUERY([LOGICJSON],'$.n') else '' end as AFTER_LOGIC" + Environment.NewLine;
sqlString += " ,IS_DERIVED, DERIVEDJSON, GKEY, MKEY" + Environment.NewLine;
sqlString += " FROM " + Environment.NewLine;
sqlString += " ( " + Environment.NewLine;
sqlString += " select QID, Qorder, QUESTIONJSON, LOGICJSON, '0' as IS_DERIVED,'' as DERIVEDJSON,'' as GKEY,'' as MKEY from[QUESTION] with(nolock) " + Environment.NewLine;
sqlString += " where pkey = '" + pkey + "' and JSON_VALUE([QUESTIONJSON], '$.qtype') <> 'description' and JSON_VALUE([QUESTIONJSON],'$.stype') <> 'MM_FILE' " + Environment.NewLine;
sqlString += " union all " + Environment.NewLine;
sqlString += " SELECT QID, Qorder, QUESTIONJSON, '' as LOGICJSON,'1' as IS_DERIVED, DERIVEDJSON, GKEY, MKEY FROM [DERIVED_VARIABLE] with(nolock) " + Environment.NewLine;
sqlString += " where pkey = '" + pkey + "' " + Environment.NewLine;
if (iskiwi == 1 && isGuid == 0 && (isAdmin == "0" || isAdmin == "1"))
{
sqlString += " union all " + Environment.NewLine;
sqlString += " SELECT case when pkey = 'kiwi_profile_001' then REPLACE(QID,'Q','PF') else REPLACE(QID,'Q','PS') end as QID" + Environment.NewLine;
sqlString += " , case when pkey = 'kiwi_profile_001' then Qorder+1000 else Qorder+2000 end as Qorder " + Environment.NewLine;
sqlString += " , QUESTIONJSON " + Environment.NewLine;
sqlString += " ,case when pkey = 'kiwi_profile_001' then REPLACE(LOGICJSON,'Q','PF') else REPLACE(LOGICJSON,'Q','PS') end as LOGICJSON" + Environment.NewLine;
sqlString += " , '2' as IS_DERIVED,'' as DERIVEDJSON,'' as GKEY,'' as MKEY " + Environment.NewLine;
sqlString += " from [QUESTION] with(nolock) " + Environment.NewLine;
sqlString += " where pkey in ('kiwi_profile_001', 'kiwi_profile_002') and JSON_VALUE([QUESTIONJSON], '$.qtype') <> 'description' and JSON_VALUE([QUESTIONJSON],'$.stype') <> 'MM_FILE' " + Environment.NewLine;
}
sqlString += " ) in_a " + Environment.NewLine;
sqlString += " ) a " + Environment.NewLine;
sqlString += " order by IS_DERIVED, Qorder " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
qlistTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
DataTable returnTable = new DataTable();
if (isGuid == 1)
{
returnTable = qlistTable;
}
else
{
returnTable = organizeQuestionList(qlistTable, qID);
}
return returnTable;
}
///
/// 문항 List 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 소속 팀
/// 0:admin, 1:DCO, 5:다른 팀, 7:client, 9:외부 링크
/// 문항 List
public DataTable getOnlyDerivedList(string pkey, int iskiwi, string team, string isAdmin)
{
DataTable qlistTable = new DataTable();
string sqlString = "";
sqlString += " SELECT " + Environment.NewLine;
sqlString += " QID " + Environment.NewLine;
sqlString += " , Qorder " + Environment.NewLine;
sqlString += " , VARIABLE " + Environment.NewLine;
sqlString += " , TITLE " + Environment.NewLine;
sqlString += " , case when EXPLAIN = '' then TITLE else EXPLAIN end as EXPLAIN " + Environment.NewLine;
sqlString += " , case when QTYPE = 'attr' or QTYPE = 'com' then QTYPE else 'normal' end as VTYPE" + Environment.NewLine;
sqlString += " , case when QTYPE = 'attr' then QTYPE2 else QTYPE end as QTYPE" + Environment.NewLine;
sqlString += " , IS_NPS" + Environment.NewLine;
sqlString += " , ATTR_INFO " + Environment.NewLine;
sqlString += " , RANK_INFO " + Environment.NewLine;
sqlString += " , JSON_query([QUESTIONJSON],'$.dataset.' + QTYPE2) as LABEL_INFO " + Environment.NewLine;
sqlString += " , AFTER_LOGIC " + Environment.NewLine;
sqlString += " , IS_DERIVED, DERIVEDJSON, GKEY, MKEY" + Environment.NewLine;
sqlString += " FROM " + Environment.NewLine;
sqlString += " ( " + Environment.NewLine;
sqlString += " SELECT QID " + Environment.NewLine;
sqlString += " , Qorder " + Environment.NewLine;
sqlString += " , QUESTIONJSON " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.variable'), '') as VARIABLE " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.title'),'') as TITLE " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.explain'),'') as EXPLAIN " + Environment.NewLine;
sqlString += " , isnull(JSON_VALUE([QUESTIONJSON], '$.qtype'),'') as QTYPE " + Environment.NewLine;
sqlString += " , isnull(JSON_query([QUESTIONJSON], '$.dataset.attr'),'') as ATTR_INFO " + Environment.NewLine;
sqlString += " , isnull(JSON_query([QUESTIONJSON], '$.dataset.rank'),'') as RANK_INFO " + Environment.NewLine;
sqlString += " , case when JSON_query([QUESTIONJSON],'$.dataset.single') is not null then 'single' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.scale') is not null then 'scale' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.multi') is not null then 'multi' " + Environment.NewLine;
sqlString += " when JSON_query([QUESTIONJSON],'$.dataset.open') is not null then 'open' end as QTYPE2 " + Environment.NewLine;
sqlString += " , isnull(JSON_value([QUESTIONJSON], '$.option.npsFlag'),'0') as IS_NPS " + Environment.NewLine;
sqlString += " , JSON_query([QUESTIONJSON],'$.dataset') as DATASET " + Environment.NewLine;
sqlString += " , '' as AFTER_LOGIC" + Environment.NewLine;
sqlString += " ,'1' as IS_DERIVED" + Environment.NewLine;
sqlString += " , DERIVEDJSON, GKEY, MKEY" + Environment.NewLine;
sqlString += " FROM [DERIVED_VARIABLE] in_a with(nolock) " + Environment.NewLine;
sqlString += " WHERE pkey = '" + pkey + "' " + Environment.NewLine;
if (isAdmin != "0" && isAdmin != "1")
{
sqlString += " and GKEY = '" + team + "' " + Environment.NewLine;
}
sqlString += " ) a " + Environment.NewLine;
sqlString += " order by IS_DERIVED, Qorder " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
qlistTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
DataTable returnTable = organizeQuestionList(qlistTable, "");
return returnTable;
}
///
/// Question/Derived List 정리
///
/// Question/Derived List
/// QID
/// 정규화된 Question/Derived List
public DataTable organizeQuestionList(DataTable qlistTable, string qID)
{
DataTable returnTable = qlistTable.Clone();
returnTable.Columns[0].MaxLength = 32;
returnTable.Columns[2].MaxLength = 64;
for (int i = 0; i < qlistTable.Rows.Count; i++)
{
string qtype = qlistTable.Rows[i]["QTYPE"].ToString();
if (qtype == "open")
{
JObject openLabel = Common.GetJObjectFromString(qlistTable.Rows[i]["LABEL_INFO"].ToString());
JObject attrLabel = Common.GetJObjectFromString(qlistTable.Rows[i]["ATTR_INFO"].ToString());
for (int j = 0; j < openLabel.Count; j++)
{
string oType = Common.GetNullString(openLabel[(j + 1).ToString()]["option"]);
if (oType != "num")
{
oType = "text";
}
object[] qinfo = qlistTable.Rows[i].ItemArray;
string qid = qinfo[0].ToString() + "_" + (j + 1);
string vname = qinfo[2].ToString() + "_" + (j + 1);
string qtitle = qinfo[3].ToString();
string qexplain = qinfo[4].ToString();
if (String.IsNullOrEmpty(Common.GetNullString(openLabel[(j + 1).ToString()]["label"])) == false)
{
qtitle += " - " + openLabel[(j + 1).ToString()]["label"].ToString();
qexplain += " - " + openLabel[(j + 1).ToString()]["label"].ToString();
}
qinfo[0] = qid;
qinfo[2] = vname;
qinfo[3] = qtitle;
qinfo[4] = qexplain;
qinfo[6] = oType;
qinfo[12] = openLabel[(j + 1).ToString()].ToString().Replace(Environment.NewLine, "");
returnTable.Rows.Add(qinfo);
if (qlistTable.Rows[i]["VTYPE"].ToString() == "attr")
{
for (int k = 0; k < attrLabel.Count; k++)
{
qinfo[0] = qid + "_" + (k + 1);
qinfo[2] = vname + "_" + (k + 1);
qinfo[3] = qtitle + " - " + attrLabel[(k + 1).ToString()]["label"].ToString();
qinfo[4] = qexplain + " - " + attrLabel[(k + 1).ToString()]["label"].ToString();
qinfo[10] = attrLabel[(k + 1).ToString()].ToString().Replace(Environment.NewLine, "");
returnTable.Rows.Add(qinfo);
}
}
}
}
else if (qtype == "rank")
{
var rankCount = Convert.ToInt32(Common.GetJObjectFromString(qlistTable.Rows[i]["RANK_INFO"].ToString())["val"]);
for (int j = 1; j <= rankCount; j++)
{
List rankTitle = new List();
for (int k = 1; k <= j; k++)
{
rankTitle.Add(k.ToString());
}
object[] qinfo = qlistTable.Rows[i].ItemArray;
qinfo[0] = qinfo[0] + "_" + j;
qinfo[2] = qinfo[2] + "_" + j;
qinfo[3] = qinfo[3].ToString() + " - " + String.Join("+", rankTitle) + "순위 까지";
qinfo[4] = qinfo[4].ToString() + " - " + String.Join("+", rankTitle) + "순위 까지";
qinfo[11] = qinfo[11].ToString().Replace(Environment.NewLine, "").Replace("\"val\":\"" + rankCount + "\"", "\"val\":\"" + j + "\"");
returnTable.Rows.Add(qinfo);//순위 만큼 부풀리기
}
}
else
{
returnTable.Rows.Add(qlistTable.Rows[i].ItemArray);
if (qlistTable.Rows[i]["VTYPE"].ToString() == "attr")
{
JObject attrLabel = Common.GetJObjectFromString(qlistTable.Rows[i]["ATTR_INFO"].ToString());
for (int j = 0; j < attrLabel.Count; j++)
{
object[] qinfo = qlistTable.Rows[i].ItemArray;
qinfo[0] = qinfo[0].ToString() + "_" + attrLabel[(j + 1).ToString()]["value"].ToString();
qinfo[2] = qinfo[2].ToString() + "_" + attrLabel[(j + 1).ToString()]["value"].ToString();
qinfo[3] = qinfo[3].ToString() + " - " + attrLabel[(j + 1).ToString()]["label"].ToString();
qinfo[4] = qinfo[4].ToString() + " - " + attrLabel[(j + 1).ToString()]["label"].ToString();
qinfo[10] = attrLabel[(j + 1).ToString()].ToString().Replace(Environment.NewLine, "");
returnTable.Rows.Add(qinfo);
}
}
}
}
if (String.IsNullOrEmpty(qID) == false)
{
/*
var selectVariable = (from DataRow dr in returnTable.Copy().Rows
where dr.Field("QID") == qID
select dr).ToList();
*/
var selectVariable = returnTable.Copy().AsEnumerable().Where(dr => dr.Field("QID") == qID).ToList();
returnTable.Clear();
if (selectVariable.Count > 0)
{
object[] variableInfo = selectVariable[0].ItemArray;
returnTable.Rows.Add(variableInfo);
}
}
return returnTable;
}
///
/// KON에서 설정한 Quota List 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// KON에서 설정한 Quota List
public DataTable getQuotaList(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += " SELECT [ID] " + Environment.NewLine;
sqlString += " ,[QSORDER] " + Environment.NewLine;
sqlString += " ,case when[EXPLAINS] <> '' then[EXPLAINS] else 'Quota ' + cast([QSORDER] as nvarchar(max)) end as [QSTITLE] " + Environment.NewLine;
sqlString += " ,[QSJSON] " + Environment.NewLine;
sqlString += " FROM [QUOTASET] " + Environment.NewLine;
sqlString += " where pkey = '" + pkey + "' " + Environment.NewLine;
sqlString += " order by QSORDER " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 쿼터 정보 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 설정한 쿼터 Order값
/// 쿼터 정보
public DataTable getQuota(string pkey, int iskiwi, string qsOrder)
{
DataTable returnTable = new DataTable();
string sqlString = "";
sqlString += " SELECT [id],[cnt],[ori_cnt] " + Environment.NewLine;
sqlString += " ,[QUOTAJSON],[IS_USE] " + Environment.NewLine;
sqlString += " FROM [QUOTA] " + Environment.NewLine;
sqlString += " where pkey = '" + pkey + "' and QSORDER = " + qsOrder + " " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 프로젝트 Data 반환
///
/// 프로젝트 Key
/// 필터 쿼리문
/// 특정 QID 없으면 모든 DATA
/// 시작 시간
/// 끝 시간
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 1:다운로드 형식의 Data
/// Test:Test DATA, ALL:ALL, 그 외 문자열:실제 DATA
/// com:완료 DATA, not:완료 외 DATA
/// 프로젝트 Data
public DataTable getProjectData(string pkey, string filter, string selectQID, string startDate, string endDate, int isKiwi, int isExport, string isTest, string idkeys, string type)
{
DataTable returnTable = new DataTable();
DataTable pinfo = getProjectInfo(pkey, isKiwi);
string comString = " and Status = '10'";
if(type == "not")
{
comString = " and Status <> '10'";
}
string testString = " and SURVEY_TYPE <> 'TEST'";
if (isTest == "TEST")
{
testString = " and SURVEY_TYPE = 'TEST'";
}
else if (isTest == "ALL")
{
testString = "";
}
string idkeyString = "";
if (String.IsNullOrEmpty(idkeys) == false)
{
idkeyString = " and in_a.IDKEY in (" + idkeys + ")";
}
string sqlString = "";
sqlString += " select IDKEY, Status, DAT " + Environment.NewLine;
if (isExport == 1)
{
sqlString += " , start_date, end_date, interval_min" + Environment.NewLine;
if (pinfo.Rows[0]["surveytype"].ToString() == "2")
{
sqlString += " , INTERVIEWER_INFO " + Environment.NewLine;
sqlString += " , INTERVIEWER_CODE " + Environment.NewLine;
}
}
sqlString += " from ( " + Environment.NewLine;
sqlString += " select * " + Environment.NewLine;
sqlString += " from ( " + Environment.NewLine;
sqlString += " select in_a.IDKEY" + Environment.NewLine;
//sqlString += " , case when in_b.DATJSON is not null and REPLACE(in_b.DATJSON,' ','') <> '{}' then LEFT(in_a.DATJSON,LEN(in_a.DATJSON)-1) +','+RIGHT(in_b.DATJSON,len(in_b.DATJSON)-1) else in_a.DATJSON end as [DATJSON]" + Environment.NewLine;
sqlString += " ,Replace('{' " + Environment.NewLine;
sqlString += " + SUBSTRING(in_a.DATJSON, 2, LEN(in_a.DATJSON) - 2) " + Environment.NewLine;
sqlString += " + case when in_b.DATJSON is not null and REPLACE(in_b.DATJSON, ' ', '') <> '{}' then ',' + SUBSTRING(in_b.DATJSON, 2, LEN(in_b.DATJSON) - 2) COLLATE Korean_Wansung_CI_AS else '' end " + Environment.NewLine;
if (isKiwi == 1 && (selectQID.IndexOf("PF") > -1 || selectQID.IndexOf("PS") > -1))
{
sqlString += " + case when P.P_DATJSON is not null and REPLACE(P.P_DATJSON, ' ', '') <> '{}' then ',' + SUBSTRING(P.P_DATJSON, 2, LEN(P.P_DATJSON) - 2) COLLATE Korean_Wansung_CI_AS else '' end " + Environment.NewLine;
}
sqlString += " + '}', '\\n', '') as DATJSON " + Environment.NewLine;
sqlString += " , Status, survey_date " + Environment.NewLine;
sqlString += " from DATA in_a with (nolock) " + Environment.NewLine;
sqlString += " left join (select distinct IDKEY, PKEY, DATJSON, DERIVED_DATE from [DERIVED_DATA] with(nolock)) in_b on in_a.PKEY=in_b.PKEY and in_a.IDKEY=in_b.IDKEY " + Environment.NewLine;
//sqlString += " left join [DERIVED_DATA] in_b with (nolock) on in_a.PKEY=in_b.PKEY and in_a.IDKEY=in_b.IDKEY " + Environment.NewLine;
if (isKiwi == 1 && (selectQID.IndexOf("PF") > -1 || selectQID.IndexOf("PS") > -1))
{
sqlString += " left join (select * from [KIWI_SURVEY].[dbo].[V_PROFILE] with(nolock) where [PKEY] = '" + pkey + "') P ON in_a.IDKEY = P.[IDKEY] " + Environment.NewLine;
}
sqlString += " where in_a.PKEY = '" + pkey + "'" + comString + testString + idkeyString + Environment.NewLine;
if (String.IsNullOrEmpty(startDate) == false)
{
if (String.IsNullOrEmpty(endDate))
{
sqlString += " and CONVERT(DATE, (select [dbo].[FN_LAST_TIME](survey_date))) = CONVERT(DATE,'" + startDate + "')" + Environment.NewLine;
}
else
{
sqlString += " and CONVERT(DATE, (select [dbo].[FN_LAST_TIME](survey_date))) >= CONVERT(DATE,'" + startDate + "')" + Environment.NewLine;
sqlString += " and CONVERT(DATE, (select [dbo].[FN_LAST_TIME](survey_date))) <= CONVERT(DATE,'" + endDate + "')" + Environment.NewLine;
}
}
sqlString += " ) a " + Environment.NewLine;
if (String.IsNullOrEmpty(filter) == false)
{
sqlString += makeFilterString(pkey, filter, isKiwi);
}
sqlString += " ) IA CROSS APPLY( " + Environment.NewLine;
sqlString += " select DISTINCT '{ \"IDKEY\":\"' + IDKEY + '\",' + STUFF((SELECT ',' + UPPER(SUBSTRING(INDAT.value, 2, LEN(INDAT.value) - 2)) FROM OPENJSON(IA.DATJSON) INDAT where INDAT.[value] <> '{}' " + Environment.NewLine;
if (selectQID != "''" && String.IsNullOrEmpty(selectQID) == false)
{
sqlString += " and UPPER(INDAT.[key]) in (SELECT UPPER(INDAT.[KEY]) FROM OPENJSON(INDAT.[VALUE]) INDJ WHERE UPPER(SUBSTRING(INDJ.[KEY],0, CHARINDEX('_',INDJ.[KEY]))) in (" + selectQID + ") or UPPER(INDJ.[KEY]) in (" + selectQID + ")) " + Environment.NewLine;
}
sqlString += " FOR XML PATH('')), 1, 1, ' ') +'}' AS DAT " + Environment.NewLine;
if (isExport == 1)
{
sqlString += " ,( select [dbo].[FN_START_TIME](IA.survey_date) ) as start_date " + Environment.NewLine;
sqlString += " ,( select [dbo].[FN_LAST_TIME](IA.survey_date) ) as end_date " + Environment.NewLine;
sqlString += " ,convert(varchar(20), datediff(minute, ( select [dbo].[FN_START_TIME](IA.survey_date) ), ( select [dbo].[FN_LAST_TIME](IA.survey_date) ))) AS interval_min " + Environment.NewLine;
if (pinfo.Rows[0]["surveytype"].ToString() == "2")
{
sqlString += " ,(select USERNAME + '_' + USERPHONE FROM KON_CAPI_TB WHERE USERID = LEFT(IA.IDKEY,9) ) as INTERVIEWER_INFO " + Environment.NewLine;
sqlString += " ,(select ISNULL(JSON_VALUE([INFO],'$.INTERVIEWER_CODE'),'') FROM KON_CAPI_TB WHERE USERID = LEFT(IA.IDKEY,9) ) as INTERVIEWER_CODE " + Environment.NewLine;
}
}
sqlString += " ) DAT " + Environment.NewLine;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(isKiwi);
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
public string makeFilterString(string pkey, string filter, int isKiwi)
{
string filterString = " where ";
List filterList = new List();
List andOrList = new List();
Regex qidRegex = new Regex(@"((?" };
string[] notConvertArray = { "IN", "IS NOT NULL", "=", "=" };
bool isVname = true;
filter = filter.ToUpper();
/////filterString이 Q|로 시작하면 vname이 아닌 QID로 작성된 필터문
if (filter.IndexOf("Q|") == 0)
{
isVname = false;
filter = filter.Replace("Q|", "");
}
while (filter.IndexOf(" ") > -1)
{
filter = filter.Replace(" ", " ");
}
filter.Replace("< >", "<>");
filter.Replace("! =", "!=");
List betweenMatches = Regex.Matches(filter, @"BETWEEN \d AND \d").OfType().Select(m => m.Groups[0].Value).Distinct().ToList();
for (int i = 0; i < betweenMatches.Count; i++)
{
string betweenString = betweenMatches[i].Replace(" AND ", " && ");
filter = filter.Replace(betweenMatches[i], betweenString);
}
string[] andArray = filter.Replace(" AND ", " & ").Replace(" && ", " AND ").Split('&');
andOrList.Add("");
for (int i = 0; i < andArray.Length; i++)
{
if (i > 0)
{
andOrList.Add("AND");
}
if (andArray[i].IndexOf("OR") > -1)
{
string[] orArray = andArray[i].Replace(" OR ", " | ").Split('|');
for (int j = 0; j < orArray.Length; j++)
{
if (j > 0)
{
andOrList.Add("OR");
}
filterList.Add(orArray[j].Trim());
}
}
else
{
filterList.Add(andArray[i].Trim());
}
}
for (int i = 0; i < filterList.Count; i++)
{
string isNot = string.Empty;
for (int j = 0; j < notArray.Length; j++)
{
if (filterList[i].IndexOf(notArray[j]) > -1)
{
//not in, is null, <>, !=
filterList[i] = filterList[i].Replace(notArray[j], notConvertArray[j]);
isNot = "not ";
break;
}
}
if (String.IsNullOrEmpty(andOrList[i]) == false)
{
filterString += " " + andOrList[i] + " ";
}
List qidMatches = qidRegex.Matches(filterList[i]).OfType().Select(m => m.Groups[0].Value).Distinct().ToList();
for (int j = 0; j < qidMatches.Count; j++)
{
string qidString = string.Empty;
string qidMatch = qidMatches[j];
if (Array.IndexOf(opArray, qidMatch) < 0)
{
//////VARIABLE_NAME -> QID
if (isVname)
{
qidMatch = getQidWithVname(pkey, qidMatch, isKiwi);
}
var qidArray = qidMatch.Split('_');
qidString = " UPPER(FIL2.[key]) = '" + qidMatch + "'";
if (qidString.IndexOf("_") < 0)
{
qidString = " (" + qidString + " OR UPPER(FIL2.[key]) like '" + qidMatch + "[_]%')";
}
else if (qidArray.Length == 2)
{
qidString = " (" + qidString + " OR UPPER(FIL2.[key]) like '" + qidArray[0] + "[_]%[_]" + qidArray[1] + "') ";
}
filterList[i] = Regex.Replace(filterList[i], @"((? 0)
{
vnameArray[0] = qidTable.Rows[0]["QID"].ToString();
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
string qid = String.Join("_", vnameArray);
return qid;
}
///
/// 프로젝트 DATA를 Json형식으로 반환
///
/// 프로젝트 Key
/// 필터 쿼리문
/// 특정 QID 없으면 모든 DATA
/// 시작 시간
/// 끝 시간
/// 1:키위 프로젝트, 0:KON 프로젝트
/// Test:Test DATA, ALL:ALL, 그 외 문자열:실제 DATA
/// Json형식의 DATA
public string getProjectDataJson(string pkey, string filter, string selectQID, string startDate, string endDate, int iskiwi, string isTest, string idkeys)
{
string returnValue = string.Empty;
DataTable resultTable = getProjectData(pkey, filter, selectQID, startDate, endDate, iskiwi, 0, isTest, idkeys, "com");
try
{
returnValue = "[" + string.Join(",", resultTable.AsEnumerable().Where(x => x.Field("DAT") != null).Select(x => x.Field("DAT").ToString()).ToArray()) + "]";
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
return returnValue;
}
///
/// 실제로 저장된 QID 문자열 반환
///
/// 프로젝트 Key
/// Index QID들
/// Banner QID들
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 'QID1','QID2'...
public string makeSelectQID(string pkey, string indexString, string bannerString, int isKiwi)
{
DAL dal = new DAL();
string returnString = string.Empty;
List qidList = new List();
qidList.Add(Regex.Replace(indexString, @"_\w+", ""));
if (String.IsNullOrEmpty(bannerString) == false)
{
string splitString = bannerString.Replace("|", ",");
string[] bannerArray = splitString.Split(',').Distinct().ToArray();
for (int i = 0; i < bannerArray.Length; i++)
{
qidList.Add(Regex.Replace(bannerArray[i], @"_\w+", ""));
}
}
qidList = qidList.Distinct().ToList();
//var connection = dal.ConnectKonKiwi(isKiwi);
//try
//{
// for (int i = 0; i < qidList.Count; i++)
// {
// string selectString = string.Empty;
// selectString += " select " + Environment.NewLine;
// selectString += " case when JSON_VALUE([QUESTIONJSON], '$.qgroup') != '' " + Environment.NewLine;
// selectString += " then (select top(1) QID from QUESTION QU2 where PKEY = '" + pkey + "' and JSON_VALUE(QU2.[QUESTIONJSON], '$.qgroup') = JSON_VALUE(QU1.[QUESTIONJSON], '$.qgroup') order by Qorder desc) " + Environment.NewLine;
// selectString += " else QID end as QID " + Environment.NewLine;
// selectString += " from QUESTION QU1 where PKEY = '" + pkey + "' and QID = '" + qidList[i] + "' " + Environment.NewLine;
//
// DataTable qidTable = dal.GetDataTable(selectString, connection);
// if (qidTable.Rows.Count > 0)
// {
// qidList[i] = qidTable.Rows[0][0].ToString();
// }
// }
//}
//catch (Exception ex)
//{
// logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
//}
//finally
//{
// dal.Disconnect(connection);
//}
returnString = "'" + String.Join("','", qidList) + "'";
return returnString;
}
public DataTable getExportExplain(string pkey, int iskiwi)
{
DataTable returnTable = new DataTable();
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
string selectString = string.Empty;
selectString += " SELECT "+Environment.NewLine;
selectString += " [QID] "+Environment.NewLine;
selectString += " ,isnull(JSON_VALUE([QUESTIONJSON], '$.variable'),'') as '문번' "+Environment.NewLine;
selectString += " ,isnull(JSON_VALUE([QUESTIONJSON], '$.title'),'') as '문항' "+Environment.NewLine;
selectString += " ,isnull(JSON_VALUE([QUESTIONJSON], '$.explain'),'') as 'Title' "+Environment.NewLine;
selectString += " FROM [QUESTION] "+Environment.NewLine;
selectString += " WHERE pkey = '"+ pkey + "' and JSON_VALUE([QUESTIONJSON], '$.qtype') <> 'description' and JSON_VALUE([QUESTIONJSON],'$.stype') <> 'MM_FILE' "+Environment.NewLine;
selectString += " ORDER BY Qorder " + Environment.NewLine;
returnTable = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// DATA 다운로드용 Header정보 반환
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 0:admin, 1:DCO, 5:다른 팀, 7:client, 9:외부 링크
/// Header정보
public DataTable getExportHeader(string pkey, int iskiwi, string isAdmin)
{
DataTable returnTable = new DataTable();
Common.tableAddColumn(returnTable, new string[] { "qid", "variable", "value" });
string[] header = new string[] { "IDKEY", "Status", "start_date", "end_date", "interval_min", "INTERVIEWER_INFO", "INTERVIEWER_CODE" };
for (int i = 0; i < header.Length; i++)
{
returnTable.Rows.Add(new object[] { header[i], header[i], header[i] });
}
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
DataTable addColumns = dal.GetDataTable(" select ISNULL(JSON_QUERY(PROJECTJSON, '$.add_column'),'[]') as addColumn from PROJECT where PKEY = '" + pkey + "' ", connection);
if (addColumns.Rows[0][0].ToString() != "[]")
{
string[] addColumnArray = addColumns.Rows[0][0].ToString().Replace("[", "").Replace("]", "").Split(',');
for (int i = 0; i < addColumnArray.Length; i++)
{
string addString = addColumnArray[i].Trim().Replace("\"", "");
returnTable.Rows.Add(new object[] { addString, addString, addString });
}
}
if (isAdmin == "0" || isAdmin == "1")
{
string derivedString = string.Empty;
derivedString += " SELECT DV.QID, QV.[key] as qtype, QV.[value] as linfo ";
derivedString += " FROM DERIVED_VARIABLE DV ";
derivedString += " CROSS APPLY OPENJSON(QUESTIONJSON) QJ ";
derivedString += " CROSS APPLY OPENJSON(QJ.[value]) QV ";
derivedString += " where QJ.[key] = 'dataset' and PKEY = '" + pkey + "' ";
derivedString += " order by DV.Qorder ";
DataTable derivedTable = dal.GetDataTable(derivedString, connection);
for (int i = 0; i < derivedTable.Rows.Count; i++)
{
var qid = derivedTable.Rows[i]["QID"].ToString();
var subID = qid;
var qtype = derivedTable.Rows[i]["qtype"].ToString();
if (qtype == "multi")
{
subID = string.Empty;
var labelInfo = Common.GetJObjectFromString(derivedTable.Rows[i]["linfo"].ToString());
for (int j = 0; j < labelInfo.Count; j++)
{
subID += qid + "_" + labelInfo[(j + 1).ToString()]["value"].ToString() + ",";
}
if (subID.Length > 1)
{
subID = subID.Remove(subID.Length - 1);
}
}
else if (qtype == "num")
{
subID += "_1";
}
returnTable.Rows.Add(new object[] { qid, qid, subID });
}
}
string sqlString = string.Empty;
sqlString += " select [key] as qid ,variable,REPLACE(SUBSTRING([value],2,LEN([value])-2),'\"','') as [value]";
sqlString += " from OPENJSON((SELECT QINFO fROM [STRUCTURE] where PKEY = '" + pkey + "')) A";
sqlString += " CROSS APPLY(SELECT QORDER,JSON_VALUE(QUESTIONJSON,'$.variable') as variable FROM QUESTION B WHERE PKEY = '" + pkey + "' and A.[key] collate Korean_Wansung_CI_AS = B.QID) C";
sqlString += " where [value] <> '[]'";
sqlString += " ORDER BY QORDER";
DataTable qheadTable = dal.GetDataTable(sqlString, connection);
returnTable.Merge(qheadTable);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
public DataTable makeExportTable(DataTable headerTable, DataTable bodyTable = null)
{
JArray excelJson = new JArray();
JObject headerJson = new JObject();
string[] fixHeader = new string[] { "Status", "start_date", "end_date", "interval_min", "INTERVIEWER_INFO", "INTERVIEWER_CODE" };
for(int i = 0; i < headerTable.Rows.Count; i++)
{
string[] valueArray = headerTable.Rows[i]["value"].ToString().Split(',');
string qid = headerTable.Rows[i]["qid"].ToString();
foreach (string value in valueArray)
{
headerJson[value] = value.Replace(qid, headerTable.Rows[i]["variable"].ToString());
}
}
excelJson.Add(headerJson);
if(bodyTable != null)
{
for (int i = 0; i < bodyTable.Rows.Count; i++)
{
string datString = Common.ReplaceUnicodeEmpty(bodyTable.Rows[i]["DAT"].ToString());
if (String.IsNullOrEmpty(datString) == false)
{
JObject bodyJson = new JObject();
JObject dataJson = Common.GetJObjectFromString(datString);
foreach (var item in headerJson)
{
var value = item.Key.ToString();
string dataValue = string.Empty;
if(Array.IndexOf(fixHeader,value) > -1 && bodyTable.Columns.Contains(value))
{
dataValue = bodyTable.Rows[i][value].ToString();
}
else if (dataJson[value.ToUpper()] != null)
{
dataValue = dataJson[value.ToUpper()].ToString();
}
bodyJson[value] = dataValue;
}
excelJson.Add(bodyJson);
}
}
}
DataTable returnTable = Common.GetDataTableFromJArray(excelJson);
return returnTable;
}
///
/// 변수 가이드 Table 생성
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
///
public DataTable makeGuideTable(string pkey, int iskiwi, string isAdmin)
{
DataTable returnTable = new DataTable();
Common.tableAddColumn(returnTable, new string[] { "문항 타입", "문항 / 보기번호", "내용", "VALUE LABEL", "VARIABLE LABEL" });
DataTable qsTable = getQuestionList(pkey, "", iskiwi, "1", 1);
foreach(DataRow qsRow in qsTable.Rows)
{
int rankMax = 0;
string vname = qsRow["VARIABLE"].ToString();
string title = Common.StripHTML(qsRow["TITLE"].ToString()).Replace("\r", string.Empty).Replace("\n", " ");
string vtype = qsRow["VTYPE"].ToString();
string qtype = qsRow["QTYPE"].ToString();
string outType = qtype;
int attrLoop = 1;
JObject attrInfo = Common.GetJObjectFromString(qsRow["ATTR_INFO"].ToString());
JObject labelInfo = Common.GetJObjectFromString(qsRow["LABEL_INFO"].ToString());
if (vtype == "attr")
{
attrLoop = attrInfo.Count;
outType = vtype;
}
for(int i = 0; i < attrLoop; i++)
{
string outTitle = title;
string outName = string.Empty;
string attrString = string.Empty;
string variableLabel = string.Empty;
if (vtype == "attr")
{
JObject attrLabel = Common.GetJObjectFromString(attrInfo[(i + 1).ToString()].ToString());
outTitle = title + attrLabel["label"].ToString();
attrString = "_" + attrLabel["value"].ToString();
}
if(qtype == "multi" || qtype == "rank" || qtype == "open")
{
string start = string.Empty;
string end = string.Empty;
switch (qtype)
{
case "rank":
JObject rankInfo = Common.GetJObjectFromString(qsRow["RANK_INFO"].ToString());
start = "_1";
end = "_" + rankInfo["val"].ToString();
rankMax = Convert.ToInt32(rankInfo["val"]);
break;
case "multi":
start = "_" + Common.GetJObjectFromString(labelInfo["1"].ToString())["value"].ToString();
end = "_" + Common.GetJObjectFromString(labelInfo[labelInfo.Count.ToString()].ToString())["value"].ToString();
break;
case "open":
start = "_1";
end = "_" + labelInfo.Count;
break;
}
outName = vname + start+attrString + " To " + vname + end+ attrString;
}
else
{
outName = vname + attrString;
}
if(qtype == "single" || qtype == "scale" || vtype == "attr")
{
variableLabel = "/" + outName + " '" + outTitle + "'";
}
DataRow newRow = returnTable.NewRow();
newRow.ItemArray = new object[] { outType, outName, outTitle, "/"+ outName, variableLabel };
returnTable.Rows.Add(newRow);
int j = 0;
foreach(var labelObject in labelInfo)
{
string value = string.Empty;
string label = string.Empty;
string valueLabel = string.Empty;
variableLabel = string.Empty;
var labelDetail = Common.GetJObjectFromString(labelObject.Value.ToString());
if (qtype == "open")
{
value = (j + 1).ToString();
label = value.ToString();
valueLabel = (j + 1).ToString("0000") + "''";
}
else
{
value = labelDetail["value"].ToString();
label = labelDetail["label"].ToString();
valueLabel = Convert.ToInt32(value).ToString("0000") + "'" + label + "'";
}
if (qtype == "open" || qtype == "multi")
{
variableLabel = "/" + vname + "_" + value + attrString + " '" + outTitle + "'";
}
else if (qtype == "rank" && j < rankMax)
{
variableLabel = "/" + vname + "_" + (j + 1) + attrString + " '" + outTitle + "'";
}
DataRow labelRow = returnTable.NewRow();
labelRow.ItemArray = new object[] { "", value, label, valueLabel, variableLabel };
returnTable.Rows.Add(labelRow);
j++;
}
}
}
return returnTable;
}
///
/// 저장된 북마크 정보 반환
///
/// 프로젝트 Key
/// TABULATION, CROSSTAB
/// 팀코드
/// User
/// 북마크 정보
public DataTable getBookmark(string pkey, string getPage, string gkey, string mkey)
{
DataTable returnTable = new DataTable();
string sqlString = string.Empty;
sqlString += " SELECT BOOKMARK_ID, BOOKMARK_TITLE, BOOKMARK_INFO, BOOKMARK_JSON, GKEY, MKEY, IS_OPEN , CASE WHEN MKEY='" + mkey + "' THEN '1' ELSE '0' END as IS_MINE";
sqlString += " FROM REPORT_BOOKMARK ";
sqlString += " where pkey = '" + pkey + "' and BOOKMARK_PAGE = '" + getPage + "' and(IS_OPEN = 1 or(IS_OPEN = 0 and MKEY = '" + mkey + "')) ";
sqlString += " order by BOOKMARK_ORDER ";
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
returnTable = dal.GetDataTable(sqlString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnTable;
}
///
/// 북마크 정보 수정
///
/// 프로젝트 Key
/// 북마크 정보
/// 팀코드
/// User
/// 북마크 ID
public string updateBookmark(string pkey, BookmarkParam bookmarkParam, string gkey, string mkey)
{
string returnValue = "";
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
string upsertString = string.Empty;
DataTable originInfo = dal.GetDataTable("SELECT BOOKMARK_TITLE ,BOOKMARK_INFO ,BOOKMARK_JSON, IS_OPEN FROM REPORT_BOOKMARK WHERE BOOKMARK_ID= '" + bookmarkParam.BookmarkID + "'", connection);
upsertString += " update a set BOOKMARK_TITLE = '" + bookmarkParam.BookmarkTitle + "', BOOKMARK_INFO = '" + bookmarkParam.BookmarkInfo + "', BOOKMARK_JSON = '" + bookmarkParam.BookmarkJson + "', IS_OPEN = '" + bookmarkParam.IsOpen + "'";
upsertString += " from REPORT_BOOKMARK a";
upsertString += " where BOOKMARK_ID = '" + bookmarkParam.BookmarkID + "'";
dal.ExecuteSQL(upsertString, connection);
returnValue = bookmarkParam.BookmarkID;
string logContent = "{\"ORIGIN\": { \"BOOKMARK_ID\": " + bookmarkParam.BookmarkID + ", \"BOOKMARK_TITLE\": " + originInfo.Rows[0]["BOOKMARK_TITLE"].ToString() + ", \"BOOKMARK_INFO\": " + originInfo.Rows[0]["BOOKMARK_INFO"].ToString() + ", \"BOOKMARK_JSON\": " + originInfo.Rows[0]["BOOKMARK_JSON"].ToString() + ", \"IS_OPEN\": " + originInfo.Rows[0]["IS_OPEN"].ToString() + "},";
logContent += "\"NEW\": { \"BOOKMARK_ID\": " + bookmarkParam.BookmarkID + ", \"BOOKMARK_TITLE\": " + bookmarkParam.BookmarkTitle + ", \"BOOKMARK_INFO\": " + bookmarkParam.BookmarkInfo + ", \"BOOKMARK_JSON\": " + bookmarkParam.BookmarkJson + ", \"IS_OPEN\": " + bookmarkParam.IsOpen + "}}";
Log.InsertSiteLog(mkey, pkey, "Update Bookmark", logContent);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 북마크 정보 등록
///
/// 프로젝트 Key
/// 북마크 정보
/// 팀코드
/// User
/// 북마크 ID
public string insertBookmark(string pkey, BookmarkParam bookmarkParam, string gkey, string mkey)
{
string returnValue = "";
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
bookmarkParam.BookmarkID = pkey + "_" + bookmarkParam.BookmarkPage.Substring(0, 1) + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff");
string upsertString = string.Empty;
upsertString += " insert into REPORT_BOOKMARK (PKEY,BOOKMARK_PAGE,BOOKMARK_ID,BOOKMARK_ORDER,BOOKMARK_TITLE,BOOKMARK_INFO,BOOKMARK_JSON,GKEY,MKEY,IS_OPEN)";
upsertString += " values ('" + pkey + "','" + bookmarkParam.BookmarkPage + "','" + bookmarkParam.BookmarkID + "',(select isnull(max(BOOKMARK_ORDER),0)+1 as BOOKMARK_ORDER from REPORT_BOOKMARK where pkey = '" + pkey + "' and BOOKMARK_PAGE='" + bookmarkParam.BookmarkPage + "'),'" + bookmarkParam.BookmarkTitle + "','" + bookmarkParam.BookmarkInfo + "','" + bookmarkParam.BookmarkJson + "','" + gkey + "','" + mkey + "'," + bookmarkParam.IsOpen + ")";
dal.ExecuteSQL(upsertString, connection);
returnValue = bookmarkParam.BookmarkID;
string logContent = "{\"NEW\": { \"BOOKMARK_ID\": " + bookmarkParam.BookmarkID + ", \"BOOKMARK_TITLE\": " + bookmarkParam.BookmarkTitle + ", \"BOOKMARK_INFO\": " + bookmarkParam.BookmarkInfo + ", \"BOOKMARK_JSON\": " + bookmarkParam.BookmarkJson + ", \"IS_OPEN\": " + bookmarkParam.IsOpen + "}}";
Log.InsertSiteLog(mkey, pkey, "Insert Bookmark", logContent);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 북마크 삭제
///
/// 프로젝트 Key
/// 북마크 ID
/// User
/// message
public string deleteBookmark(string pkey, string bookmarkID, string mkey)
{
string returnValue = "삭제했습니다.";
DAL dal = new DAL();
var connection = dal.ConnectReport();
try
{
DataTable originInfo = dal.GetDataTable("SELECT BOOKMARK_TITLE ,BOOKMARK_INFO ,BOOKMARK_JSON, IS_OPEN FROM REPORT_BOOKMARK WHERE BOOKMARK_ID= '" + bookmarkID + "'", connection);
string logContent = "{\"ORIGIN\": { \"BOOKMARK_ID\": " + bookmarkID + ", \"BOOKMARK_TITLE\": " + originInfo.Rows[0]["BOOKMARK_TITLE"].ToString() + ", \"BOOKMARK_INFO\": " + originInfo.Rows[0]["BOOKMARK_INFO"].ToString() + ", \"BOOKMARK_JSON\": " + originInfo.Rows[0]["BOOKMARK_JSON"].ToString() + ", \"IS_OPEN\": " + originInfo.Rows[0]["IS_OPEN"].ToString() + "}}";
Log.InsertSiteLog(mkey, pkey, "Delete Bookmark", logContent);
dal.ExecuteSQL("update a set BOOKMARK_ORDER = (BOOKMARK_ORDER - 1) FROM REPORT_BOOKMARK a where PKEY = '" + pkey + "' and BOOKMARK_ORDER > (select BOOKMARK_ORDER from REPORT_BOOKMARK b where pkey = a.PKEY and BOOKMARK_ID = '" + bookmarkID + "')", connection);
dal.ExecuteSQL("delete FROM REPORT_BOOKMARK where PKEY = '" + pkey + "' and BOOKMARK_ID = '" + bookmarkID + "'", connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "삭제 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 변수명 중복 체크
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// I:insert, U:update
/// 변수명
/// true/false
public bool checkDuplicateVariable(string pkey, int iskiwi, string upsertMode, string variableID)
{
bool returnValue = true;
string sqlString = string.Empty;
sqlString += " select distinct QID ";
sqlString += " from ";
sqlString += " ( ";
sqlString += " select distinct DV.[key] COLLATE Korean_Wansung_CI_AS as QID ";
sqlString += " from DATA ";
sqlString += " CROSS APPLY(select *from openjson(DATJSON)) DJ ";
sqlString += " CROSS APPLY(select * from openjson(DJ.value)) DV where PKEY = '" + pkey + "' ";
sqlString += " union all ";
sqlString += " select QID from QUESTION where pkey = '" + pkey + "' ";
sqlString += " union all ";
sqlString += " select QID from DERIVED_VARIABLE where PKEY = '" + pkey + "' ";
sqlString += " ) a ";
sqlString += " where QID = '" + variableID + "' ";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
var returnTable = dal.GetDataTable(sqlString, connection);
if (upsertMode == "I" && returnTable.Rows.Count > 0 || upsertMode == "U" && returnTable.Rows.Count > 1)
{
returnValue = false;
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 모든 파생변수 Update
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// User
/// message
public string updateAllDerived(string pkey, int iskiwi, string mkey)
{
string returnString = "";
DataTable questionInfo = getQuestionList(pkey, "", iskiwi,"0");
//var derivedList = (from DataRow dr in questionInfo.Rows where dr.Field("IS_DERIVED") == "1" select dr.Field("QID")).ToList();
var derivedList = questionInfo.AsEnumerable().Where(dr => dr.Field("IS_DERIVED") == "1").Select(dr => dr.Field("QID")).ToList();
foreach (var derived in derivedList)
{
returnString = setDerivedData(pkey, iskiwi, derived);
if (returnString.IndexOf("오류") > -1)
{
returnString += " / " + derived;
break;
}
}
string logContent = "{\"COUNT\": \"" + derivedList.Count + "\"}";
Log.InsertSiteLog(mkey, pkey, "Update All Derived Variable", logContent);
return returnString;
}
///
/// 파생변수 삭제
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파생변수명
/// User
/// message
public string deleteDerivedVariable(string pkey, int iskiwi, string variableID, string mkey)
{
string returnValue = "삭제했습니다.";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
DataTable originInfo = dal.GetDataTable("select QUESTIONJSON, DERIVEDJSON from DERIVED_VARIABLE where PKEY = '" + pkey + "' and QID = '" + variableID + "' ", connection);
string logContent = "{\"ORIGIN\": { \"QUESTIONJSON\": " + originInfo.Rows[0]["QUESTIONJSON"].ToString() + ", \"DERIVEDJSON\": " + originInfo.Rows[0]["DERIVEDJSON"].ToString() + "}}";
Log.InsertSiteLog(mkey, pkey, "Delete Derived Variable", logContent);
dal.ExecuteSQL("update a set Qorder = (Qorder - 1) FROM DERIVED_VARIABLE a where PKEY = '" + pkey + "' and Qorder > (select qorder from DERIVED_VARIABLE b where pkey = a.PKEY and QID = '" + variableID + "')", connection);
dal.ExecuteSQL("delete FROM DERIVED_VARIABLE where PKEY = '" + pkey + "' and QID = '" + variableID + "'", connection);
dal.ExecuteSQL("update a set a.DATJSON = JSON_MODIFY(a.DATJSON, '$." + variableID + "', null) from DERIVED_DATA a where PKEY = '" + pkey + "'", connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "삭제 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 파생변수 수정
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파생변수 정보
/// 팀코드
/// User
/// message
public string updateDerivedVariable(string pkey, int iskiwi, DerivedParam derivedParam, string gkey, string mkey)
{
string returnValue = "성공적으로 저장했습니다.";
if (checkDuplicateVariable(pkey, iskiwi, "U", derivedParam.VariableID))
{
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
string infoString = getDeriveInfoString(derivedParam);
string qjson = getDerivedQjson(derivedParam, infoString);
DataTable originInfo = dal.GetDataTable("select QUESTIONJSON, DERIVEDJSON from DERIVED_VARIABLE where PKEY = '" + pkey + "' and QID = '" + derivedParam.OriginID + "' ", connection);
string upsertString = "";
upsertString += " update DV set QID = '" + derivedParam.VariableID + "', QUESTIONJSON = '" + qjson + "', DERIVEDJSON = '" + infoString + "', GKEY = '" + gkey + "', MKEY = '" + mkey + "' ";
upsertString += " from DERIVED_VARIABLE DV ";
upsertString += " where PKEY = '" + pkey + "' and QID = '" + derivedParam.OriginID + "' ";
if (derivedParam.OriginID != derivedParam.VariableID)
{
upsertString += "update a set DATJSON=JSON_MODIFY(DATJSON, '$." + derivedParam.OriginID + "', null) from DERIVED_DATA a where PKEY='" + pkey + "'";
}
dal.ExecuteSQL(upsertString, connection);
string logContent = "{\"NEW\": { \"QUESTIONJSON\": " + qjson + ", \"DERIVEDJSON\": " + infoString + "}";
logContent += "\"ORIGIN\": { \"QUESTIONJSON\": " + originInfo.Rows[0]["QUESTIONJSON"].ToString() + ", \"DERIVEDJSON\": " + originInfo.Rows[0]["DERIVEDJSON"].ToString() + "}," + logContent;
logContent += "}";
Log.InsertSiteLog(mkey, pkey, "Update Derived Variable", logContent);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
returnValue = setDerivedData(pkey, iskiwi, derivedParam.VariableID);
}
else
{
returnValue = "ID가 중복됩니다.";
}
//값 만들기
return returnValue;
}
///
/// 파생변수 등록
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파생변수 정보
/// 팀코드
/// User
/// message
public string insertDerivedVariable(string pkey, int iskiwi, DerivedParam derivedParam, string gkey, string mkey)
{
string returnValue = "성공적으로 저장했습니다.";
if (checkDuplicateVariable(pkey, iskiwi, "I", derivedParam.VariableID))
{
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
string infoString = getDeriveInfoString(derivedParam);
string qjson = getDerivedQjson(derivedParam, infoString);
string insertString = "";
insertString += " insert into DERIVED_VARIABLE([PKEY], [QID], [Qorder], [QUESTIONJSON], [DERIVEDJSON], [GKEY], [MKEY]) ";
insertString += " values('" + pkey + "', '" + derivedParam.VariableID + "', (select count(1) + 1 from DERIVED_VARIABLE where PKEY = '" + pkey + "'),'" + qjson + "','" + infoString + "','" + gkey + "','" + mkey + "') ";
dal.ExecuteSQL(insertString, connection);
string logContent = "{\"NEW\": { \"QUESTIONJSON\": " + qjson + ", \"DERIVEDJSON\": " + infoString + "}}";
Log.InsertSiteLog(mkey, pkey, "Insert Derived Variable", logContent);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
returnValue = setDerivedData(pkey, iskiwi, derivedParam.VariableID);
}
else
{
returnValue = "ID가 중복됩니다.";
}
//값 만들기
return returnValue;
}
///
/// infoString 생성
///
/// 파생변수 정보
/// infoString 반환
public string getDeriveInfoString(DerivedParam derivedParam)
{
string infoString = derivedParam.VariableInfo.Replace("\r\n", "");
while (infoString.IndexOf(" ") > 0)
{
infoString = infoString.Replace(" ", " ");
}
return infoString;
}
///
/// qjosn 생성
///
/// 파생변수 정보
/// infoString
/// qjson 반환
public string getDerivedQjson(DerivedParam derivedParam, string infoString)
{
string qjson = string.Empty;
if (derivedParam.VariableType == "num")
{
qjson = "{\"variable\":\"" + derivedParam.VariableID + "\",\"explain\":\"\",\"title\":\"" + derivedParam.VariableTitle + "\",\"dataset\":{\"open\":{\"1\":{\"label\":\"\",\"option\":\"num\"}}},\"qtype\":\"open\"}";
}
else
{
var regexString = "(, \"condition\": \"[\\s\\S][^\"]*\")|(, \"format\": \"[\\s\\S][^\"]*\")";
var labelString = Regex.Replace(infoString, @regexString, "").Replace("\"ELSE\"", "\"" + Common.GetJObjectFromString(derivedParam.VariableInfo).Count.ToString() + "\"");
qjson = "{\"variable\":\"" + derivedParam.VariableID + "\",\"explain\":\"\",\"title\":\"" + derivedParam.VariableTitle + "\",\"dataset\":{\"" + derivedParam.VariableType + "\":" + labelString + "},\"qtype\":\"" + derivedParam.VariableType + "\"}";
}
return qjson;
}
///
/// 파생변수 DATA 생성/수정
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파생변수명
/// message
public string setDerivedData(string pkey, int iskiwi, string variableID)
{
string returnValue = "성공적으로 저장했습니다.";
JObject variableInfo = new JObject();
string variableType = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
DataTable insertIDKEYS = new DataTable();
try
{
DataTable derivedVariable = dal.GetDataTable("select json_value([QUESTIONJSON],'$.qtype') as QTYPE, DERIVEDJSON from [DERIVED_VARIABLE] with(nolock) where PKEY = '" + pkey + "' and QID='" + variableID + "'", connection);
variableInfo = Common.GetJObjectFromString(derivedVariable.Rows[0]["DERIVEDJSON"].ToString());
variableType = derivedVariable.Rows[0]["QTYPE"].ToString();
//DERIVED_DATA에 해당 변수가 있으면 값을 '{}'로
string updateString = "update a set DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "', JSON_QUERY(N'{}')) from DERIVED_DATA a where PKEY='" + pkey + "'";
dal.ExecuteSQL(updateString, connection);
//DERIVED_DATA가 아예 없는 애들
string selectString = "select a.idkey from DATA a with(nolock) left join DERIVED_DATA b with(nolock) on a.PKEY=b.PKEY and a.IDKEY=b.IDKEY where a.PKEY='" + pkey + "' and a.SURVEY_TYPE <> 'TEST' and a.Status = '10' and b.IDKEY is null";
insertIDKEYS = dal.GetDataTable(selectString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
for (int i = 0; i < insertIDKEYS.Rows.Count; i++)
{
//DERIVED_DATA가 없는 애들 해당 변수 이름으로 '{}'값 저장
string insertString = "insert into DERIVED_DATA (IDKEY,PKEY,DATJSON,DERIVED_DATE) values ('" + insertIDKEYS.Rows[i]["idkey"] + "','" + pkey + "',JSON_QUERY(N'{ \"" + variableID + "\" : {}}'),'{}')";
connection = dal.ConnectKonKiwi(iskiwi);
try
{
dal.ExecuteSQL(insertString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
}
// 데이터 만들기
List variableKeys = variableInfo.Properties().Select(p => p.Name).ToList();
for (int i = 0; i < variableInfo.Count; i++)
{
string valueID = variableID;
connection = dal.ConnectKonKiwi(iskiwi);
try
{
string condition = string.Empty;
if (variableKeys[i].ToUpper() == "ELSE")
{
condition = variableID + " IS NULL";
}
else
{
condition = variableInfo[variableKeys[i]]["condition"].ToString();
if (variableType != "multi")
{
condition += " AND " + variableID + " IS NULL";
}
}
if (variableType == "multi")
{
valueID += "_" + variableInfo[variableKeys[i]]["value"].ToString();
}
else if (variableType == "num")
{
valueID += "_1";
}
JArray matchData = Common.GetJArrayFromString(getProjectDataJson(pkey, condition, "", "", "", iskiwi, "", string.Empty));
if (matchData != null && matchData.Count > 0)
{
string idkeyList = string.Join(",", matchData.Select(x => "\'" + x.Value("IDKEY") + "\'").ToArray());
string dataString = "update a set DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "." + valueID + "', '" + variableInfo[variableKeys[i]]["value"].ToString() + "') from DERIVED_DATA a where PKEY='" + pkey + "' and IDKEY in (" + idkeyList + ")";
dal.ExecuteSQL(dataString, connection);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
}
connection = dal.ConnectKonKiwi(iskiwi);
try
{
// 빈값 제거
dal.ExecuteSQL("update a set DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "', null) from DERIVED_DATA a where PKEY='" + pkey + "' and JSON_QUERY(DATJSON, '$." + variableID + "') = '{}'", connection);
// 데이터 만들어진 애들 시간 갱신
string dateString = "update a set DERIVED_DATE=JSON_MODIFY(DERIVED_DATE, '$." + variableID + "', cast(convert(varchar,getdate(),20) as varchar)) from DERIVED_DATA a where PKEY='" + pkey + "' and JSON_QUERY(DATJSON, '$." + variableID + "') is not null ";
dal.ExecuteSQL(dateString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
public string setDerivedDataWithID(string pkey, int iskiwi, string idkey)
{
string returnValue = "성공적으로 저장했습니다.";
JObject variableInfo = new JObject();
string variableType = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
if (dal.GetDataTable("SELECT * FROM [DERIVED_DATA] with(nolock) where PKEY = '"+ pkey + "' and IDKEY = '"+idkey+"'", connection).Rows.Count == 0)
{
string insertString = "insert into DERIVED_DATA (IDKEY,PKEY,DATJSON,DERIVED_DATE) values ('" + idkey + "','" + pkey + "','{}','{}')";
dal.ExecuteSQL(insertString, connection);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
DataTable questionInfo = getQuestionList(pkey, "", iskiwi, "0");
//var derivedList = (from DataRow dr in questionInfo.Rows where dr.Field("IS_DERIVED") == "1" select dr.Field("QID")).ToList();
var derivedList = questionInfo.AsEnumerable().Where(dr => dr.Field("IS_DERIVED") == "1").Select(dr => dr.Field("QID")).ToList();
foreach (var variableID in derivedList)
{
connection = dal.ConnectKonKiwi(iskiwi);
try
{
DataTable derivedVariable = dal.GetDataTable("select json_value([QUESTIONJSON],'$.qtype') as QTYPE, DERIVEDJSON from [DERIVED_VARIABLE] with(nolock) where PKEY = '" + pkey + "' and QID='" + variableID + "'", connection);
variableInfo = Common.GetJObjectFromString(derivedVariable.Rows[0]["DERIVEDJSON"].ToString());
variableType = derivedVariable.Rows[0]["QTYPE"].ToString();
string updateString = "update a set DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "', JSON_QUERY(N'{}')) from DERIVED_DATA a where PKEY='" + pkey + "' and IDKEY = '" + idkey + "'";
dal.ExecuteSQL(updateString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
// 데이터 만들기
List variableKeys = variableInfo.Properties().Select(p => p.Name).ToList();
for (int i = 0; i < variableInfo.Count; i++)
{
string valueID = variableID;
connection = dal.ConnectKonKiwi(iskiwi);
try
{
string condition = string.Empty;
if (variableKeys[i].ToUpper() == "ELSE")
{
condition = variableID + " IS NULL";
}
else
{
condition = variableInfo[variableKeys[i]]["condition"].ToString();
if (variableType != "multi")
{
condition += " AND " + variableID + " IS NULL";
}
}
if (variableType == "multi")
{
valueID += "_" + variableInfo[variableKeys[i]]["value"].ToString();
}
else if (variableType == "num")
{
valueID += "_1";
}
JArray matchData = Common.GetJArrayFromString(getProjectDataJson(pkey, condition, "", "", "", iskiwi, "", "'" + idkey + "'"));///////////여기 수정
if (matchData != null && matchData.Count > 0)
{
string dataString = string.Empty;
dataString += " update a set" + Environment.NewLine;
dataString += " DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "." + valueID + "', '" + variableInfo[variableKeys[i]]["value"].ToString() + "')" + Environment.NewLine;
dataString += " , DERIVED_DATE=JSON_MODIFY(DERIVED_DATE, '$." + variableID + "', cast(convert(varchar,getdate(),20) as varchar))" + Environment.NewLine;
dataString += " from DERIVED_DATA a" + Environment.NewLine;
dataString += " where PKEY='" + pkey + "' and IDKEY ='" + idkey + "'" + Environment.NewLine;
dal.ExecuteSQL(dataString, connection);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
connection = dal.ConnectKonKiwi(iskiwi);
try
{
// 빈값 제거
dal.ExecuteSQL("update a set DATJSON=JSON_MODIFY(DATJSON, '$." + variableID + "', null) from DERIVED_DATA a where PKEY='" + pkey + "' and JSON_QUERY(DATJSON, '$." + variableID + "') = '{}'", connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "저장 중 오류가 발생했습니다.";
}
finally
{
dal.Disconnect(connection);
}
}
}
return returnValue;
}
///
/// 프로젝트 DATA File Upload
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파일 Path
/// 파일 확장자
/// message
public string uploadProjectData(string pkey, int iskiwi, string fileName, string extension)
{
string returnValue = "업로드 성공";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
//응답값 초기화
try
{
dal.ExecuteSQL(" delete from [DATA] where pkey = '" + pkey + "' and SURVEY_TYPE = 'UPLOAD' ", connection);
dal.ExecuteSQL(" update a set a.PKEY = 'DEL_'+PKEY FROM [DATA] a where PKEY = '" + pkey + "' and SURVEY_TYPE != 'TEST' and status = '10' ", connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
return "응답 초기화 실패";
}
finally
{
dal.Disconnect(connection);
}
// 파일 정리 후 넣기
try
{
DataTable excelData = new DataTable();
string[] headerArray;
string[] passArray = { "idkey", "status", "start_date", "end_date", "interval_min", "interviewer_info/interviewer_code" };///keyArray에서 _로 스플릿한 다음에 중복 제거를 하기 때문에
if (extension.ToLower() == ".xlsx")
{
excelData = Common.ExceltoDataTable(fileName);
}
else
{
excelData = Common.textToDataTable(fileName, extension);
}
if (excelData.Columns[0].ColumnName == "error")
{
return excelData.Rows[0][0].ToString();
}
else if (excelData.Rows.Count < 2)
{
return "파일을 확인해 주세요.";
}
else
{
excelData.Rows.Remove(excelData.Rows[0]); //KON DATA 파일은 header가 2줄 한줄 버리기
headerArray = Common.getColumnNames(excelData);
}
string[] keyArray = headerArray.Select(x => x.Split('_')[0].Replace("TQ", "Q")).Distinct().ToArray();
for (int i = 0; i < passArray.Length; i++)
{
keyArray = keyArray.Where((source, index) => index != 0).ToArray();
}
//여기서 multi인 QID 색출
/*
List multiQlist = (from DataRow dr in getQuestionList(pkey, "", iskiwi,"0").Rows
where dr.Field("QTYPE").ToLower() == "multi"
select dr.Field("QID").Split('_')[0]).Distinct().ToList();
*/
List multiQlist = getQuestionList(pkey, "", iskiwi, "0").AsEnumerable().Where(dr => dr.Field("QTYPE").ToLower() == "multi").Select(dr => dr.Field("QID").Split('_')[0]).Distinct().ToList();
string insertPre = "insert into [DATA] ([IDKEY], [PKEY], [PAGENAME], [SURVEY_TYPE], [Status], [DATJSON], [survey_date])";
string pageName = string.Empty;
string surveyType = "UPLOAD";
for (int i = 0; i < excelData.Rows.Count; i++)
{
string[] dataArray = new string[keyArray.Length];
string[] timeArray = new string[keyArray.Length];
string idkey = excelData.Rows[i]["IDKEY"].ToString();
string status = excelData.Rows[i]["Status"].ToString();
string stime = excelData.Rows[i]["start_date"].ToString();
string etime = excelData.Rows[i]["end_date"].ToString();
if (String.IsNullOrEmpty(status))
{
status = "10";
}
if (String.IsNullOrEmpty(stime))
{
stime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
if (String.IsNullOrEmpty(etime))
{
etime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
string meanTime = new DateTime((Convert.ToDateTime(etime).Ticks + Convert.ToDateTime(stime).Ticks)/2).ToString("yyyy-MM-dd HH:mm:ss");
for (int j = 0; j < keyArray.Length; j++)
{
string[] dataKeyArray = headerArray.Where(x => x == keyArray[j] || x.StartsWith(keyArray[j] + "_") || x.StartsWith("T" + keyArray[j] + "_")).ToArray();
string[] dataJsonArray = new string[dataKeyArray.Length];
for (int k = 0; k < dataKeyArray.Length; k++)
{
string cellValue = excelData.Rows[i][dataKeyArray[k]].ToString().Trim().Replace(".00", "");
if (String.IsNullOrEmpty(cellValue) == false)
{
string dataKey = dataKeyArray[k];
//모든 multi는 QID_Value_Attr(당겨쳐진 multi처리)
if (multiQlist.Contains(keyArray[j]) && Common.IsNumeric(cellValue))
{
string[] dataKeyDetail = dataKey.Split('_');
dataKeyDetail[1] = cellValue;
dataKey = String.Join("_", dataKeyDetail);
}
dataJsonArray[k] = "\"" + dataKey + "\":\"" + cellValue.Replace("\n", " ").Replace("\"",""").Replace("'", "‘") + "\"";
}
}
dataJsonArray = dataJsonArray.Where(x => x != null).ToArray();
string dataJson = string.Join(",", dataJsonArray);
if (String.IsNullOrEmpty(dataJson) == false)
{
pageName = keyArray[j];
dataArray[j] = "\"" + keyArray[j] + "\":{" + dataJson + "}";
timeArray[j] = "\"" + keyArray[j] + "\":\"" + meanTime + "\"";
}
}
dataArray = dataArray.Where(x => x != null).ToArray();
timeArray = timeArray.Where(x => x != null).ToArray();
var lastTime = timeArray[timeArray.Length - 1].Split("\":\"");
timeArray[timeArray.Length - 1] = lastTime[0] + "\":\"" + etime + "\"";
string dataString = "{ \"INDEX\":{\"USERAGENT\":\"\",\"USERIP\":\"\",\"TK\":\"\"}," + string.Join(",", dataArray) + "}";
string timeString = "{ \"INDEX\":\"" + stime + "\"," + string.Join(",", timeArray) + "}";
string insertString = insertPre + " values ('" + idkey + "','" + pkey + "','" + pageName + "','" + surveyType + "','" + status + "',N'" + dataString + "','" + timeString + "')";
connection = dal.ConnectKonKiwi(iskiwi);
dal.ExecuteSQL(insertString, connection);
dal.Disconnect(connection);
}
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "실패";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 파일로 문항 등록
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파일 Path
/// 파일 확장자
/// message
public string uploadQuestion(string pkey, int iskiwi, string fileName, string extension)
{
string returnValue = "업로드 성공";
try
{
#region 파일 정리
DataTable excelData = new DataTable();
string[] headerArray = new string[] { "variable", "explain", "qtype", "attr_value", "max_value", "title" };
if (extension.ToLower() == ".xlsx")
{
excelData = Common.ExceltoDataTable(fileName, "", headerArray);
}
else
{
excelData = Common.textToDataTable(fileName, extension, headerArray);
}
if (excelData.Columns[0].ColumnName == "error")
{
return excelData.Rows[0][0].ToString();
}
else if (excelData.Rows.Count < 1)
{
return "파일을 확인해 주세요.";
}
else
{
Regex qidRegex = new Regex(@"((? -1)
{
excelData.Rows[i]["title"] = excelData.Rows[i]["title"].ToString().Replace("{t}", "").Replace("{T}", "");
labelJSON.Add("etc", "1");
}
else
{
labelJSON.Add("etc", "0");
}
labelJSON.Add("except", "0");
labelJSON.Add("label", excelData.Rows[i]["title"].ToString());
labelJSON.Add("value", excelData.Rows[i]["attr_value"].ToString());
JObject attrObject = qinfo.attrJson["attr"] as JObject;
attrObject.Add(attrOrder.ToString(), labelJSON);
attrOrder++;
}
else if (String.IsNullOrEmpty(excelData.Rows[i]["title"].ToString()) == false)
{
if (qinfo.itemJson.HasValues == false)
{
itemOrder = 1;
qinfo.itemJson.Add(qinfo.itemType, new JObject());
}
labelJSON.Add("label", excelData.Rows[i]["title"].ToString().Replace("{t}", "").Replace("{T}", ""));
if (qinfo.itemType == "open")
{
if (qinfo.variableType == "n")
{
labelJSON.Add("option", "num");
}
else
{
labelJSON.Add("option", "all");
}
labelJSON.Add("must", "1");
}
else
{
labelJSON.Add("value", excelData.Rows[i]["max_value"].ToString());
if (qinfo.itemType != "scale") // single, multi
{
if (excelData.Rows[i]["title"].ToString().ToLower().IndexOf("{t}") > -1)
{
excelData.Rows[i]["title"] = excelData.Rows[i]["title"].ToString();
labelJSON.Add("etc", "1");
}
else
{
labelJSON.Add("etc", "0");
}
labelJSON.Add("except", "0");
}
}
JObject itemObject = qinfo.itemJson[qinfo.itemType] as JObject;
itemObject.Add(itemOrder.ToString(), labelJSON);
itemOrder++;
}
#endregion
}
if (excelData.Rows.Count - 1 == i || String.IsNullOrEmpty(excelData.Rows[i + 1]["variable"].ToString()) == false)
{
JObject optionObject = new JObject();
if (qinfo.variableType == "r")
{
qinfo.itemJson.Add("rank", JObject.Parse("{\"val\":\"" + qinfo.maxCount + "\",\"max\":\"" + qinfo.maxCount + "\"}"));
}
else if (qinfo.variableType == "m" || qinfo.variableType == "o" || qinfo.variableType == "n")
{
if (qinfo.variableType == "m" && qinfo.maxCount != "")
{
optionObject.Add("max", qinfo.maxCount);
}
}
else if (qinfo.variableType == "nps")
{
optionObject.Add("arrow", "");
optionObject.Add("under_label", "");
optionObject.Add("reverse", "");
optionObject.Add("break", "");
optionObject.Add("npsFlag", "1");
}
if (optionObject.Count > 0)
{
qinfo.optionJson.Add("option", optionObject);
}
// 문항 업로드
string qid = saveQuestion(pkey, qinfo, iskiwi);
if (qid == "FAIL")
{
return "초기화 완료 / 저장 실패";
}
List qinfoList = new List();
JObject linfoJson = new JObject();
if (String.IsNullOrEmpty(qinfo.itemType) == false)
{
string linfoString = "";
int attrCount = 1;
int itemLoop = 1;
if (qinfo.attrJson["attr"] != null)
{
attrCount = qinfo.attrJson["attr"].Count();
}
if (qinfo.itemType == "scale" || qinfo.itemType == "single" || qinfo.itemType == "rank")
{
List linfoList = new List();
if (qinfo.itemType == "rank")
{
itemLoop = Convert.ToInt32(qinfo.maxCount);
}
for (int li = 0; li < qinfo.itemJson[qinfo.itemType].Count(); li++)
{
linfoList.Add("\"" + qinfo.itemJson[qinfo.itemType][(li + 1).ToString()]["value"] + "\":\"" + qinfo.itemJson[qinfo.itemType][(li + 1).ToString()]["label"].ToString().Replace("\"", "\\\"") + "\"");
}
linfoString = "{" + string.Join(",", linfoList) + "}";
}
else if (qinfo.itemType == "open")
{
itemLoop = Convert.ToInt32(qinfo.itemJson[qinfo.itemType].Count());
//open은 Label상관없이 open
linfoString = "open";
}
else if (qinfo.itemType == "multi")
{
itemLoop = Convert.ToInt32(qinfo.itemJson[qinfo.itemType].Count());
}
for (int ai = 0; ai < attrCount; ai++)
{
string attrString = string.Empty;
if (qinfo.attrJson["attr"] != null)
{
attrString = "_" + qinfo.attrJson["attr"][(ai + 1).ToString()]["value"].ToString();
}
for (int ii = 0; ii < itemLoop; ii++)
{
string multiString = string.Empty;
string itemValue = string.Empty;
string itemLabel = string.Empty;
if (qinfo.itemType == "multi")
{
multiString = "_" + qinfo.itemJson[qinfo.itemType][(ii + 1).ToString()]["value"].ToString();
linfoString = "{\"" + qinfo.itemJson[qinfo.itemType][(ii + 1).ToString()]["value"] + "\":\"" + qinfo.itemJson[qinfo.itemType][(ii + 1).ToString()]["label"].ToString().Replace("\"", "\\\"") + "\"}";
}
else if (qinfo.itemType == "open")
{
multiString = "_" + (ii + 1);
}
else if (qinfo.itemType == "rank")
{
multiString = "_" + (ii + 1);
}
string sqid = qid + multiString + attrString;
qinfoList.Add(sqid);
linfoJson.Add(sqid, Common.GetJObjectFromString(linfoString));
if (qinfo.itemType == "multi" && Common.GetNullString(qinfo.itemJson[qinfo.itemType][(ii + 1).ToString()]["etc"]) == "1")//멀티만 기타가 있으면
{
string tqid = "T" + qid + multiString + attrString; ;
qinfoList.Add(tqid);
linfoJson.Add(tqid, qinfo.itemJson[qinfo.itemType][(ii + 1).ToString()]["label"].ToString() + "(기타)");
}
}
if (qinfo.itemType == "single" || qinfo.itemType == "rank")
{
// 기타 개수대로
List etcValues = qinfo.itemJson[qinfo.itemType].Where(x => x.Children()["etc"].ToList()[0].ToString() == "1").Select(x => x.Children()["value"].ToList()[0].ToString()).ToList();
for (int ei = 0; ei < etcValues.Count; ei++)
{
string tqid = "T" + qid + "_" + etcValues[ei] + attrString; ;
qinfoList.Add(tqid);
linfoJson.Add(tqid, qinfo.itemJson[qinfo.itemType][etcValues[ei]]["label"].ToString() + "(기타)");
}
}
if (qinfo.attrJson["attr"] != null && Common.GetNullString(qinfo.attrJson["attr"][(ai + 1).ToString()]["etc"]) == "1")//기타가 있으면
{
string tqid = qid + attrString + "_AT";
qinfoList.Add(tqid);
linfoJson.Add(tqid, qinfo.attrJson["attr"][(ai + 1).ToString()]["label"] + "_기타");
}
}
}
// QINFO {"qid":["변수 목록"], ...} QID_multi_attr // info 문항은 "qid":[]
string sturctureMessage = saveStructure(pkey, qid, qinfoList, linfoJson, iskiwi);
if (String.IsNullOrEmpty(sturctureMessage) == false)
{
return "초기화 완료 / STRUCTUIRE 저장 실패";
}
qinfo = new QuestionInfo();
}
}
#endregion
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "실패";
}
return returnValue;
}
///
/// 프로젝트의 문항과 관련된 모든 정보 초기화
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// message
public string resetQuestion(string pkey, int iskiwi)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
#region 문항 초기화
try
{
//QOPTION, QUOTASET, QUOTA은 엉킬수 있으므로 같이 제거
//어떻게 할까? 테이블에 콘에서 만들어진 건지 리포트에서 만들어 진건지 구별하는 칼럼을 추가할까?
dal.ExecuteSQL(" delete from [QUESTION] where pkey = '" + pkey + "' ", connection);
dal.ExecuteSQL(" delete from [QOPTION] where pkey = '" + pkey + "' ", connection);
dal.ExecuteSQL(" delete from [QUOTASET] where pkey = '" + pkey + "' ", connection);
dal.ExecuteSQL(" delete from [QUOTA] where pkey = '" + pkey + "' and (QSORDER is not null or QSORDER <> '') ", connection);
dal.ExecuteSQL(" update a set QINFO = N'{}', LINFO = N'{}' from [STRUCTURE] a where pkey = '" + pkey + "' ", connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "응답 초기화 실패";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
#endregion
}
///
/// 파일로 Explain 등록
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// 파일 Path
/// 파일 확장자
/// message
public string uploadExplain(string pkey, int iskiwi, string fileName, string extension)
{
string returnValue = "업로드 성공";
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
try
{
#region 파일 정리
DataTable excelData = new DataTable();
string[] headerArray = new string[] { "qid", "variable", "title", "explain" };
if (extension.ToLower() == ".xlsx")
{
excelData = Common.ExceltoDataTable(fileName, "", headerArray);
}
else
{
excelData = Common.textToDataTable(fileName, extension, headerArray);
}
if (excelData.Columns[0].ColumnName == "error")
{
return excelData.Rows[0][0].ToString();
}
else if (excelData.Rows.Count < 1)
{
return "파일을 확인해 주세요.";
}
#endregion
#region explain 등록
foreach(DataRow row in excelData.Rows)
{
string updateString = string.Empty;
updateString += " UPDATE a SET [QUESTIONJSON] = JSON_MODIFY([QUESTIONJSON],'$.explain','"+ row["explain"].ToString() + "')" + Environment.NewLine;
updateString += " from [QUESTION] a" + Environment.NewLine;
updateString += " where pkey = '" + pkey + "' and qid='" + row["qid"].ToString() + "'" + Environment.NewLine;
dal.ExecuteSQL(updateString, connection);
}
#endregion
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "실패";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
}
///
/// 프로젝트 문항의 Explain 공백으로 변경
///
/// 프로젝트 Key
/// 1:키위 프로젝트, 0:KON 프로젝트
/// message
public string resetExplain(string pkey, int iskiwi)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
#region 문항 초기화
try
{
string updateString = string.Empty;
updateString += " UPDATE a SET [QUESTIONJSON] = JSON_MODIFY([QUESTIONJSON],'$.explain','')" + Environment.NewLine;
updateString += " from [QUESTION] a" + Environment.NewLine;
updateString += " where pkey = '" + pkey + "' and JSON_VALUE([QUESTIONJSON], '$.qtype') <> 'description' and JSON_VALUE([QUESTIONJSON],'$.stype') <> 'MM_FILE'";
dal.ExecuteSQL(updateString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "Title 초기화 실패";
}
finally
{
dal.Disconnect(connection);
}
return returnValue;
#endregion
}
///
/// 문항 저장
///
/// 프로젝트 Key
/// 문항 정보
/// 1:키위 프로젝트, 0:KON 프로젝트
/// QID
public string saveQuestion(string pkey, QuestionInfo qinfo, int iskiwi)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
#region 문항 저장
try
{
JObject dataSet = new JObject();
JObject question = new JObject();
question.Add("qgroup", "");
question.Add("rota", "");
question.Add("variable", qinfo.variableName);
question.Add("explain", qinfo.explain);
question.Add("title", qinfo.questionTitle);
question.Add("stype", qinfo.structureType);
question.Add("description", "");
if (qinfo.itemJson.Count > 0)
{
dataSet.Merge(qinfo.itemJson);
}
if (qinfo.attrJson.Count > 0)
{
dataSet.Merge(qinfo.attrJson);
}
if (dataSet.Count > 0)
{
question.Add("dataset", dataSet);
}
else
{
question.Add("dataset", new JObject());
}
question.Add("datagroup", "");
question.Add("qtype", qinfo.questionType);
if (qinfo.optionJson.Count > 0)
{
question.Add("option", qinfo.optionJson);
}
else
{
question.Add("option", "");
}
string newQID = "Q1";
string newQorder = "1";
DataTable newQIDTable = dal.GetDataTable("select 'Q'+cast(max(cast(replace(QID,'Q','') as int))+1 as nvarchar(max)) as QID, (max(Qorder) + 1) as Qorder FROM [QUESTION] where PKEY = '" + pkey + "'", connection);
if (newQIDTable.Rows.Count > 0 && String.IsNullOrEmpty(newQIDTable.Rows[0]["QID"].ToString()) == false)
{
newQID = newQIDTable.Rows[0]["QID"].ToString();
newQorder = newQIDTable.Rows[0]["Qorder"].ToString();
}
string insertString = " insert into [QUESTION]([PKEY], [QID], [Qorder], [QUESTIONJSON], [LOGICJSON])" + Environment.NewLine;
insertString += " values('" + pkey + "', '" + newQID + "', " + newQorder + ", json_query(N'" + Common.GetStringFromJson(question) + "'), '')";
dal.ExecuteSQL(insertString, connection);
returnValue = newQID;
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "FAIL";
}
finally
{
dal.Disconnect(connection);
}
#endregion
return returnValue;
}
///
/// Structure Table 수정
///
/// 프로젝트 Key
/// Kon QID
/// QINFO 내용
/// LINFO 내용
/// 1:키위 프로젝트, 0:KON 프로젝트
/// message
public string saveStructure(string pkey, string qid, List qinfoList, JObject linfoJson, int iskiwi)
{
string returnValue = string.Empty;
DAL dal = new DAL();
var connection = dal.ConnectKonKiwi(iskiwi);
#region structure저장
try
{
string updateString = string.Empty;
string qinfoString = string.Empty;
string linfoString = string.Empty;
if (qinfoList.Count > 0)
{
qinfoString = "\"" + string.Join("\",\"", qinfoList) + "\"";
}
qinfoString = "[" + qinfoString + "]";
linfoString = Common.GetStringFromJson(linfoJson);
updateString += " update a set" + Environment.NewLine;
updateString += " QINFO = JSON_MODIFY(QINFO,'$." + qid + "',N'" + qinfoString + "')" + Environment.NewLine;
updateString += " , LINFO = JSON_MODIFY(LINFO,'$." + qid + "',N'" + linfoString + "')" + Environment.NewLine;
updateString += " from [STRUCTURE] a" + Environment.NewLine;
updateString += " where pkey = '" + pkey + "'";
dal.ExecuteSQL(updateString, connection);
}
catch (Exception ex)
{
logger.Fatal(this.GetType().Name + " > " + System.Reflection.MethodBase.GetCurrentMethod().Name + " : " + ex.Message);
returnValue = "FAIL";
}
finally
{
dal.Disconnect(connection);
}
#endregion
return returnValue;
}
///
/// 문항 타입별 QTYPE 세팅
///
/// QuestionInfo
/// 문항 타입
/// QuestionInfo
public QuestionInfo setQTYPE(QuestionInfo qinfo, string typeString)
{
qinfo.variableType = typeString.ToLower();
switch (typeString.ToLower())
{
case "i":
qinfo.structureType = "DM1";
qinfo.questionType = "description";
qinfo.itemType = string.Empty;
break;
case "s":
qinfo.structureType = "SM2";
qinfo.questionType = "single";
qinfo.itemType = "single";
break;
case "m":
qinfo.structureType = "MM2";
qinfo.questionType = "multi";
qinfo.itemType = "multi";
break;
case "r":
qinfo.structureType = "RM1";
qinfo.questionType = "rank";
qinfo.itemType = "multi";
break;
case "c":
qinfo.structureType = "SCM1";
qinfo.questionType = "scale";
qinfo.itemType = "scale";
break;
case "nps":
qinfo.structureType = "SCM1";
qinfo.questionType = "scale";
qinfo.itemType = "scale";
break;
case "n":
qinfo.structureType = "OM1";
qinfo.questionType = "open";
qinfo.itemType = "open";
break;
case "o":
qinfo.structureType = "OM1";
qinfo.questionType = "open";
qinfo.itemType = "open";
break;
}
return qinfo;
}
///
/// 프로젝트 타입 or Status 반환
///
/// 0:타입, 그외:Status
/// index 값
/// 프로젝트 타입 or Status
public string setProjectTypeStatus(int type, string value)
{
string returnValue = string.Empty;
if (Common.IsNumeric(value))
{
int index = Convert.ToInt32(value);
if (index > 0 && index < 4)
{
string[] labelArray = new string[3];
if (type == 0)
{
labelArray = new string[] { "온라인", "CAPI", "GANG" };
}
else
{
labelArray = new string[] { "준비", "진행", "완료" };
}
returnValue = labelArray[(index - 1)];
}
}
return returnValue;
}
}
}