261028_01_ENH: 새로운 KART 연동
This commit is contained in:
@@ -329,7 +329,7 @@
|
||||
<button name="btn_search" id="btn_search" class="btn btn-sm btn-secondary">조회</button>
|
||||
</div>
|
||||
-->
|
||||
<div class="ml-2 position-relative" >
|
||||
<div class="ml-2 position-relative d-flex align-items-center" id="progress-toolbar" >
|
||||
</div>
|
||||
<div class="flex-fill"></div>
|
||||
<div onclick="window.location.reload()" style="cursor: pointer;" class=" text-right"><i class="fa fa-refresh" aria-hidden="true"></i> 새로고침</div>
|
||||
@@ -337,6 +337,9 @@
|
||||
<div class="p-2 main-box rounded bg-light h-100 d-flex flex-row shadow-sm" style="overflow-x: auto;">
|
||||
<div class="p-2 flex-fill border bg-white rounded shadow-sm " style="overflow:auto;">
|
||||
<div class="d-flex flex-column p-2 flex-fill" id="content" style="overflow:auto;">
|
||||
<div id="progress-status" role="status" aria-live="polite"></div>
|
||||
<div id="progress-reports"></div>
|
||||
<div id="progress-quota-result"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -344,303 +347,521 @@
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script>
|
||||
$("document").ready(function(){
|
||||
showLoadingBar()
|
||||
setTimeout(() => {
|
||||
view_type()
|
||||
hideLoadingBar()
|
||||
}, 500);
|
||||
})
|
||||
<script>
|
||||
// 배포 시 이 설정 또는 앞서 선언한 window.KRIC_INTERNAL_CONFIG를 지정합니다.
|
||||
// 실제 API Key를 소스 관리에 기록하지 마세요. 브라우저에 전달된 키는 열람 가능합니다.
|
||||
var progressConfig = Object.assign({
|
||||
apiBase: KART_BASE_URL, // 예: https://<KART_FRONT_HOST>/api/kric-internal
|
||||
apiKey: KON_API_KEY,
|
||||
projectType: KART_PROJECT_TYPE, // KON: 0, KIWI: 1
|
||||
|
||||
$("button[name=btn_search]").on("click", function(e){
|
||||
showLoadingBar()
|
||||
setTimeout(() => {
|
||||
view_type()
|
||||
hideLoadingBar()
|
||||
}, 500);
|
||||
})
|
||||
useExcelExport: false, // Excel 다운로드 버튼 사용 여부
|
||||
|
||||
function showLoadingBar(){
|
||||
var maskHeight = $(document).height();
|
||||
var maskWidth = window.document.body.clientWidth;
|
||||
var mask = "<div id='mask' style='position:absolute; z-index:9000; background-color:#ffffff; display:none; left:0; top:0;'></div>";
|
||||
var loadingImg = '';
|
||||
loadingImg += "<div id='loadingImg' style='position:absolute; left:calc(50% - 100px); top:40%; display:none; z-index:10000;'>";
|
||||
loadingImg += " <img src='/img/load.gif'/>";
|
||||
loadingImg += "</div>";
|
||||
$('body').append(mask).append(loadingImg);
|
||||
$('#mask').css({ 'width' : maskWidth , 'vertical-align' : 'middle', 'height': maskHeight, 'opacity' : '0.7'});
|
||||
$('#mask').show(); $('#loadingImg').show();
|
||||
}
|
||||
pkey: "2608013_B", // 빈 값이면 기존처럼 현재 /Project/{pkey}/... 경로에서 추출
|
||||
indexes: ["Q2"], // 예: ["Q1", "Q2"]
|
||||
|
||||
function hideLoadingBar() {
|
||||
$('#mask, #loadingImg').hide();
|
||||
$('#mask, #loadingImg').remove();
|
||||
}
|
||||
titles: [], // indexes와 같은 순서. 생략하면 서버 결과 제목 사용
|
||||
banners: [], // 예: [["Q3"], ["Q4", "Q5"]]
|
||||
|
||||
function view_type(){
|
||||
$("#content").empty();
|
||||
// 빈 문자열이면 추가 응답 조건 없이 조회합니다. TEST/날짜 조건은 options에서 지정합니다.
|
||||
// 예: "Q1 = 1 AND (Q2 = 2 OR Q3 = 3)"
|
||||
// 예: "Q1 IN (1, 2) AND Q2 >= 20 AND Q2 < 40"
|
||||
// 예: "Q1 NOT IN (1, 2)" 또는 "Q1 IS NOT NULL"
|
||||
// 문자/앞자리 0을 보존할 코드는 작은따옴표로 감쌉니다. 예: "Q1 = '서울' OR Q2 = '001'"
|
||||
filter: "",
|
||||
|
||||
options: {
|
||||
percentageDecimals: 1, // 비율: 소수점 1자리. 예: 60.0 (0~14)
|
||||
statisticDecimals: 2, // 평균 등 통계값: 소수점 1자리. 예: 3.5 (0~14)
|
||||
// 필요할 때 아래 설정을 추가합니다. 날짜는 시작/종료를 함께 지정합니다.
|
||||
// dataScope: "ACTUAL", // 실제 응답만. "TEST": 테스트만, "ALL": 둘 다
|
||||
// startDate: "2026-01-01",
|
||||
// endDate: "2026-12-31",
|
||||
// transpose: false, // 기본: 항목이 세로, 배너가 가로. true면 행과 열을 서로 바꿉니다.
|
||||
},
|
||||
//loadQuotas: false // 목록을 가져오지 않음. Report만 사용할 때
|
||||
loadQuotas: true // 쿼터 목록을 가져옴
|
||||
}, window.KRIC_INTERNAL_CONFIG || {});
|
||||
var activeProgressRequest = null;
|
||||
|
||||
function progressNode(tag, text, className) {
|
||||
var node = document.createElement(tag);
|
||||
if (text != null) node.textContent = String(text);
|
||||
if (className) node.className = className;
|
||||
return node;
|
||||
}
|
||||
|
||||
// Render only basic title formatting; never copy attributes or active content.
|
||||
function progressTitleNode(title, className) {
|
||||
var host = progressNode("div", null, className);
|
||||
var html = title == null ? "" : String(title);
|
||||
// Handle entity-encoded titles without decoding text inside existing HTML tags.
|
||||
for (var pass = 0; pass < 2 && !/<\/?[a-z][^>]*>/i.test(html); pass++) {
|
||||
var decoder = document.createElement("textarea");
|
||||
decoder.innerHTML = html;
|
||||
var decoded = decoder.value;
|
||||
if (decoded === html) break;
|
||||
html = decoded;
|
||||
}
|
||||
var template = document.createElement("template");
|
||||
template.innerHTML = html;
|
||||
var allowed = ["B", "STRONG", "EM", "I", "U", "BR", "SPAN", "SUB", "SUP"];
|
||||
var blocked = ["SCRIPT", "STYLE", "IFRAME", "OBJECT", "EMBED", "TEMPLATE", "NOSCRIPT"];
|
||||
function append(parent, child) {
|
||||
if (child.nodeType === 3) {
|
||||
parent.appendChild(document.createTextNode(child.nodeValue));
|
||||
return;
|
||||
}
|
||||
if (child.nodeType !== 1 || child.namespaceURI !== "http://www.w3.org/1999/xhtml" || blocked.includes(child.tagName)) return;
|
||||
var target = allowed.includes(child.tagName) ? document.createElement(child.tagName.toLowerCase()) : parent;
|
||||
if (target !== parent) parent.appendChild(target);
|
||||
Array.from(child.childNodes).forEach(function (node) { append(target, node); });
|
||||
}
|
||||
Array.from(template.content.childNodes).forEach(function (node) { append(host, node); });
|
||||
return host;
|
||||
}
|
||||
|
||||
function progressStatus(message, failed) {
|
||||
var node = document.getElementById("progress-status");
|
||||
node.textContent = message;
|
||||
node.className = failed ? "text-danger p-2" : "text-muted p-2";
|
||||
}
|
||||
|
||||
function progressProject() {
|
||||
var loc = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'));
|
||||
var pkey = loc.split("/")[2];
|
||||
var isKiwi = "0"; //KIWI 프로젝트는 "1"
|
||||
var reportToken = getReportToken();/////인증 - Report API로 부터 인증 키를 받아야만 다른 기능을 사용 가능
|
||||
var pkey = progressConfig.pkey || loc.split('/')[2];
|
||||
if (![0, 1].includes(progressConfig.projectType) || typeof pkey !== "string" ||
|
||||
!pkey || pkey.length > 20 || /[|/\\]/.test(pkey) || pkey === "." || pkey === "..") {
|
||||
throw new Error("projectType과 원본 pkey 설정을 확인해 주세요.");
|
||||
}
|
||||
return progressConfig.projectType + "/" + encodeURIComponent(pkey);
|
||||
}
|
||||
|
||||
if(reportToken != ""){
|
||||
///테이블 상단에 붙일 제목
|
||||
var titleArray = [
|
||||
/*
|
||||
"성별"
|
||||
,"연령"
|
||||
,"지역"
|
||||
*/
|
||||
];
|
||||
async function progressFetch(path, body, signal) {
|
||||
var base = progressConfig.apiBase.replace(/\/$/, "");
|
||||
if (!base || !progressConfig.apiKey) throw new Error("API 주소와 API Key를 설정해 주세요.");
|
||||
var response = await fetch(base + path, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
mode: "cors", credentials: "omit", cache: "no-store", signal: signal,
|
||||
headers: { "Content-Type": "application/json", "X-API-Key": progressConfig.apiKey },
|
||||
body: body === undefined ? undefined : JSON.stringify(body)
|
||||
});
|
||||
if (!response.ok) {
|
||||
var error = await response.json().catch(function () { return null; });
|
||||
throw new Error(error && typeof error.message === "string" ? error.message : "API 요청 실패 (" + response.status + ")");
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
//"index":"Q1"
|
||||
//순위의 경우 Q1_1 : 1순위만 / Q1_7 1~7순위
|
||||
//Attr의 경우 Q1 모든 속성에 대한 결과 단, 배너 사용 불가
|
||||
// Q1_1, Q1_3, Q1_9 : 1,3,9 속성에 대한 결과만 출력 배너 사용 가능
|
||||
var indexArray = [/*"Q1","Q2","Q3"*/];
|
||||
function showLoadingBar() {
|
||||
var mask = progressNode("div");
|
||||
mask.id = "mask";
|
||||
mask.style.cssText = "position:fixed;inset:100px 0 0;z-index:9000;background:#fff;opacity:.7;pointer-events:none";
|
||||
// 취소 버튼은 로딩 중에도 사용할 수 있습니다.
|
||||
document.getElementById("content").appendChild(mask);
|
||||
var image = progressNode("img");
|
||||
image.id = "loadingImg";
|
||||
image.src = "/img/load.gif";
|
||||
image.alt = "조회 중";
|
||||
image.style.cssText = "position:fixed;left:calc(50% - 100px);top:40%;z-index:10000";
|
||||
document.getElementById("content").appendChild(image);
|
||||
}
|
||||
|
||||
//"banner":"Q1,Q2|Q3" ','옆으로 붙이기 / '|'단으로 쌓기
|
||||
//index가 Attr인 경우 해당 결과물엔 배너가 반영 되지 않음
|
||||
var bannerParam = "";
|
||||
function hideLoadingBar() {
|
||||
$("#mask, #loadingImg").remove();
|
||||
}
|
||||
|
||||
//"filter":"Q|(Q1>3)" SQL WHERE 문 처럼 단 =, <> 대신 in (), not in () 으로 작성 할 것
|
||||
//꼭 Q|로 시작해야 함 Q|를 안붙이면 QID가 아닌 변수명으로 사용해야 함
|
||||
var filterParam = "";
|
||||
async function progressRun(work) {
|
||||
if (activeProgressRequest) activeProgressRequest.abort();
|
||||
var controller = new AbortController();
|
||||
activeProgressRequest = controller;
|
||||
$("[data-progress-action]").prop("disabled", true);
|
||||
$("#progress-cancel").prop("disabled", false);
|
||||
hideLoadingBar();
|
||||
showLoadingBar();
|
||||
progressStatus("요청 중입니다.", false);
|
||||
try {
|
||||
await work(controller.signal);
|
||||
} catch (error) {
|
||||
if (activeProgressRequest === controller) {
|
||||
progressStatus(error.name === "AbortError" ? "요청을 취소했습니다. 수신한 결과는 유지합니다." : error.message, error.name !== "AbortError");
|
||||
}
|
||||
} finally {
|
||||
if (activeProgressRequest === controller) {
|
||||
activeProgressRequest = null;
|
||||
hideLoadingBar();
|
||||
$("[data-progress-action]").prop("disabled", false);
|
||||
$("#progress-cancel").prop("disabled", true);
|
||||
$("#progress-quota-view").prop("disabled", !$("#progress-quota").val());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//// 옵션은 항목이 많아 별도의 함수에 정의
|
||||
var optionParam = getOption();
|
||||
$.each(indexArray, function(i,e){
|
||||
var indexParam = e;
|
||||
////HTML 테이블 생성
|
||||
var tableA = createnode("table", "" , {"id" : "result_"+i, "class" : "table table-sm text-center table-bordered col-8", "style" : "table-layout:fixed;font-size:20px;"});
|
||||
$("#content").append(tableA);
|
||||
function progressOptions() {
|
||||
return Object.assign({ dataScope: "ACTUAL", transpose: false }, progressConfig.options || {});
|
||||
}
|
||||
|
||||
////Report API에서 결과를 받아옴
|
||||
var resultData = getResultData(reportToken.Token,pkey,isKiwi,indexParam, bannerParam, filterParam, optionParam);
|
||||
function reportCellText(cell, row, result, excel) {
|
||||
if (cell.kind === "TEXT" || cell.kind === "EMPTY") return cell.textValue || "";
|
||||
if (cell.kind === "STATISTIC" || cell.kind === "MISSING") {
|
||||
return excel && cell.statisticExact != null ? pointedNumber(cell.statisticExact) : (cell.statisticDisplayText || "");
|
||||
}
|
||||
var transposed = result.appliedOptions && result.appliedOptions.transpose === true;
|
||||
var column = result.columns[cell.columnIndex];
|
||||
var base = (transposed ? column && column.kind : row.kind) === "TOTAL";
|
||||
if (base) return cell.countDisplayText != null ? cell.countDisplayText : String(cell.count == null ? "" : cell.count);
|
||||
return excel && cell.percentExact != null ? pointedNumber(cell.percentExact) :
|
||||
(cell.percentDisplayText != null ? cell.percentDisplayText : String(cell.percent == null ? "" : cell.percent));
|
||||
}
|
||||
|
||||
////TABLE에 TR로 타이틀을 붙임
|
||||
tableA.prepend(createnode("tr", [createnode("th", titleArray[i], {"colspan":Object.keys(resultData[resultData.length-1]).length,"class":"bg-navy-2 text-white"})]));
|
||||
function pointedNumber(value) {
|
||||
var text = String(value);
|
||||
if (/e/i.test(text)) text = value.toFixed(14).replace(/0+$/, "");
|
||||
if (text.endsWith(".")) text += "0";
|
||||
return text.includes(".") ? text : text + ".0";
|
||||
}
|
||||
|
||||
///결과 값을 Table 형태로 그려주는 함수
|
||||
//(Table 객체, Report 결과, 옵션 파라미터, Round 할 소수점 자리 수)
|
||||
makeTable(tableA, resultData, optionParam,1);
|
||||
function resultWidth(rows) {
|
||||
return rows.reduce(function (width, row) {
|
||||
return row.cells.reduce(function (size, cell) {
|
||||
return Math.max(size, cell.columnIndex + (cell.colSpan || 1));
|
||||
}, width);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function quotaCellText(cell, excel) {
|
||||
if (cell.kind !== "QUOTA") return cell.textValue || "";
|
||||
var text = (cell.complete == null ? 0 : cell.complete) + "/" + (cell.target == null ? 0 : cell.target);
|
||||
return excel ? text + "/" + (cell.achievementDisplayText || "-") : text;
|
||||
}
|
||||
|
||||
function makeTable(table, result, quota) {
|
||||
if (!quota && result.type === "TEXT_ANALYSIS") {
|
||||
var head = progressNode("tr");
|
||||
["단어", "빈도"].forEach(function (text) { head.appendChild(progressNode("th", text, "bg-navy-4 text-white")); });
|
||||
table.appendChild(head);
|
||||
result.words.forEach(function (word) {
|
||||
var tr = progressNode("tr");
|
||||
tr.appendChild(progressNode("td", word.text));
|
||||
tr.appendChild(progressNode("td", word.count));
|
||||
table.appendChild(tr);
|
||||
});
|
||||
|
||||
///fillCellColor(tableID); ///쿼터를 그린 후 각 셀별로 진척도에 따라서 색을 채워주는 함수
|
||||
}
|
||||
}
|
||||
|
||||
function getReportToken(){
|
||||
var reportToken = "";
|
||||
$.ajax({
|
||||
url: 'https://rapi.kric.com/api/v1/encrypt/external',
|
||||
type: "POST",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
data: JSON.stringify({ "external": "KON"}),
|
||||
cache: false,
|
||||
async: false,
|
||||
success: function (data) {
|
||||
reportToken = JSON.parse(data);
|
||||
},
|
||||
error: function (x, h, r) {
|
||||
console.log(x);
|
||||
console.log(h);
|
||||
console.log(r);
|
||||
}
|
||||
});
|
||||
return reportToken;
|
||||
|
||||
}
|
||||
|
||||
function getSkey(token,pkey,iskiwi){
|
||||
var skey = "";
|
||||
$.ajax({
|
||||
url: 'https://rapi.kric.com/api/v1/encrypt/pkey',
|
||||
type: "GET",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
cache: false,
|
||||
async: false,
|
||||
beforeSend : function(xhr){
|
||||
xhr.setRequestHeader("token", token);
|
||||
xhr.setRequestHeader("pkey",pkey);
|
||||
xhr.setRequestHeader("iskiwi",iskiwi);
|
||||
},
|
||||
success: function (data) {
|
||||
skey = data;
|
||||
},
|
||||
error: function (x, h, r) {
|
||||
console.log(x);
|
||||
console.log(h);
|
||||
console.log(r);
|
||||
}
|
||||
});
|
||||
return skey;
|
||||
}
|
||||
|
||||
function getOption(){
|
||||
var reportOption = {
|
||||
if (!result.words.length) table.appendChild(progressNode("caption", "결과가 없습니다."));
|
||||
return;
|
||||
}
|
||||
///일반적인 결과 테이블 사용
|
||||
/*
|
||||
{
|
||||
"POINTER":"10", //출력 소수점(0~14)
|
||||
"MPOINTER":"10", //평균(Mean) 출력 소수점(0~14)
|
||||
"PRTMODE":"0",// 출력 내용 ("1" -> cell은 N만 Total은 N 만/ "2" -> cell은 %,N Total은 %,N / default -> cell은 %만 Total은 N 만)
|
||||
"VGROUP":{"카테고리1":"1,2,3", "카테고리2":"4,5,6", "카테고리3":"7,8,9"}, // 값 그룹화(특정 값을 하나의 라벨로 묶어서 출력)
|
||||
"SDATE":"2022-01-25", // 출력 데이터 기간 설정 - 시작 날짜(마지막 문항 기준)
|
||||
"EDATE":"2022-01-26", // 출력 데이터 기간 설정 - 끝 날짜(마지막 문항 기준)
|
||||
"TEST":"",//"TEST" 테스트 데이터 사용, "ALL" TEST와 실제 데이터 같이 사용 이외의 문자열 테스트 데이터 사용X
|
||||
"TURN":"",// "1" 행 열 전환 이외의 문자열 행 열 전환X
|
||||
"PRTHEAD":"",//"0" 헤더 출력 안함 이외의 문자열 헤더 출력
|
||||
"PRTSUB":"",// "0" sub total 출력 안함 이외의 문자열 sub total 출력
|
||||
}
|
||||
///쿼터에서 사용
|
||||
{
|
||||
"QUOTA":"1" // 쿼터인경우 QSORDER(설정된 쿼터 번째 수)
|
||||
"SDATE":"2022-01-25", // 출력 데이터 기간 설정 - 시작 날짜(마지막 문항 기준)
|
||||
"EDATE":"2022-01-26", // 출력 데이터 기간 설정 - 끝 날짜(마지막 문항 기준)
|
||||
"TEST":"",//"TEST" 테스트 데이터 사용, "ALL" TEST와 실제 데이터 같이 사용 이외의 문자열 테스트 데이터 사용X
|
||||
}
|
||||
*/
|
||||
return reportOption;
|
||||
}
|
||||
|
||||
function getResultData(token,pkey,iskiwi,indexParam, bannerParam, filterParam, optionParam){
|
||||
var resultData = '';
|
||||
var skey = getSkey(token,pkey,iskiwi);
|
||||
$.ajax({
|
||||
url: 'https://rapi.kric.com/api/v1/report/result',
|
||||
type: "POST",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
data: JSON.stringify({ "indexParam": indexParam, "bannerParam": bannerParam, "filterParam": filterParam, "optionParam" : JSON.stringify(optionParam)}),
|
||||
cache: false,
|
||||
async: false,
|
||||
beforeSend : function(xhr){
|
||||
xhr.setRequestHeader("token", token);
|
||||
xhr.setRequestHeader("skey",skey);
|
||||
},
|
||||
success: function (data) {
|
||||
resultData = data;
|
||||
},
|
||||
error: function (x, h, r) {
|
||||
console.log(x);
|
||||
console.log(h);
|
||||
console.log(r);
|
||||
}
|
||||
});
|
||||
return resultData;
|
||||
}
|
||||
|
||||
function makeTable(table, data, options, fixedValue){
|
||||
if (Array.isArray(data)) {
|
||||
/////일반 Data
|
||||
var header = 0;
|
||||
var mean = 0;
|
||||
$.each(data, function (i1, e1) {
|
||||
var tr = [];
|
||||
var i2Cnt = 0;
|
||||
var roundPointer = 10 ** fixedValue;
|
||||
$.each(data[i1], function (i2, e2) {
|
||||
var val = e2;
|
||||
if (val == null) {
|
||||
val = "";
|
||||
}
|
||||
|
||||
var tdJson = {};
|
||||
|
||||
if (val.indexOf("|") > -1) {
|
||||
var splitArray = val.split('|');
|
||||
var rowSpan = splitArray[1];
|
||||
var colSpan = splitArray[2];
|
||||
val = splitArray[0];
|
||||
|
||||
if (rowSpan != "") {
|
||||
tdJson["rowspan"] = rowSpan;
|
||||
}
|
||||
|
||||
if (colSpan != "") {
|
||||
tdJson["colspan"] = colSpan;
|
||||
}
|
||||
|
||||
if (i1 == 0 && i2Cnt == 0) {
|
||||
if (options["TURN"] == "1") {
|
||||
header = parseInt(colSpan);
|
||||
}
|
||||
else {
|
||||
header = parseInt(rowSpan);
|
||||
}
|
||||
var rows = result.headerRows.concat(result.rows);
|
||||
var width = resultWidth(rows);
|
||||
var covered = new Set();
|
||||
rows.forEach(function (row, rowIndex) {
|
||||
var tr = progressNode("tr");
|
||||
var cells = new Map(row.cells.map(function (cell) { return [cell.columnIndex, cell]; }));
|
||||
for (var col = 0; col < width; col++) {
|
||||
var key = rowIndex + ":" + col;
|
||||
if (covered.has(key)) continue;
|
||||
var cell = cells.get(col);
|
||||
var header = rowIndex < result.headerRows.length;
|
||||
var text = cell ? (header ? (cell.textValue || "") : quota ? quotaCellText(cell, false) : reportCellText(cell, row, result, false)) : "";
|
||||
var td = progressNode(header ? "th" : "td", text, header ? "bg-navy-4 text-white" : "");
|
||||
if (cell) {
|
||||
td.rowSpan = cell.rowSpan || 1;
|
||||
td.colSpan = cell.colSpan || 1;
|
||||
for (var r = 0; r < td.rowSpan; r++) {
|
||||
for (var c = 0; c < td.colSpan; c++) {
|
||||
if (r || c) covered.add((rowIndex + r) + ":" + (col + c));
|
||||
}
|
||||
}
|
||||
|
||||
if (val.trim() != "") {
|
||||
var node = "td";
|
||||
|
||||
if (options["TURN"] != "1" && header > i1 || options["TURN"] == "1" && header > i2Cnt) {
|
||||
node = "th";
|
||||
tdJson["class"] = "bg-navy-4 text-white";
|
||||
}
|
||||
|
||||
if (i2Cnt > 0 && val.indexOf(".") > 0 && isNaN(val) == false) {
|
||||
//val = (Math.round(val * roundPointer) / roundPointer).toFixed(fixedValue) + '<input type="hidden" value = "' + val + '">';
|
||||
val = (Math.round(val * roundPointer) / roundPointer).toFixed(fixedValue)
|
||||
}
|
||||
else{
|
||||
|
||||
}
|
||||
|
||||
tr.push(createnode(node, val, tdJson));
|
||||
if (quota && cell.kind === "QUOTA") {
|
||||
if (cell.achievementState === "FINITE" && cell.achievementPercent != null) {
|
||||
var percent = Math.max(0, Math.min(100, cell.achievementPercent));
|
||||
td.style.color = cell.achievementPercent > 100 ? "#FF0000" : "#008000";
|
||||
td.style.background = "linear-gradient(to right," + (cell.achievementPercent > 100 ? "#FFCCCC" : "#E4FFE4") + " " + percent + "%,#fff 0%)";
|
||||
} else if (cell.achievementState === "POSITIVE_INFINITY") td.style.color = "#FF0000";
|
||||
td.title = "달성률: " + (cell.achievementDisplayText || "-");
|
||||
}
|
||||
|
||||
i2Cnt++;
|
||||
});
|
||||
table.append(createnode("tr", tr));
|
||||
});
|
||||
|
||||
}
|
||||
else {
|
||||
var tr = [];
|
||||
tr.push(createnode("td", data, { "class": "" }));
|
||||
table.append(createnode("tr", tr));
|
||||
}
|
||||
}
|
||||
|
||||
function fillCellColor(tableID) {
|
||||
var row = $("#"+tableID+" tr:first th:first").attr("rowspan");
|
||||
var col = $("#"+tableID+" tr:first th:first").attr("colspan");
|
||||
|
||||
if (row == undefined) {
|
||||
row = 1;
|
||||
}
|
||||
|
||||
if (col == undefined) {
|
||||
col = 1;
|
||||
}
|
||||
|
||||
$("#"+tableID+" tr:gt(" + (+row - 1) + ")").each(function (i1, e1) {
|
||||
$(e1).find(":gt(" + (+col - 1) + ")").each(function (i2, e2) {
|
||||
if ($(e2).html().includes("/")) {
|
||||
var tdValues = $(e2).html().split("/");
|
||||
var spanColor = "";
|
||||
|
||||
if (isNaN(tdValues[2]) == false && +tdValues[2] > 0) {
|
||||
if (+tdValues[2] <= 100) {
|
||||
spanColor = "color:#008000"
|
||||
$(e2).css("background", "linear-gradient(to right, #E4FFE4 " + tdValues[2] + "%, #fff 0%)");
|
||||
}
|
||||
else{
|
||||
spanColor = "color:#FF0000"
|
||||
$(e2).css("background", "linear-gradient(to right, #FFCCCC " + tdValues[2] + "%, #fff 0%)");
|
||||
}
|
||||
}
|
||||
|
||||
$(e2).html("<span style='" + spanColor+"'>" + tdValues[0] + "</span>/" + tdValues[1]);
|
||||
}
|
||||
tr.appendChild(td);
|
||||
}
|
||||
table.appendChild(tr);
|
||||
});
|
||||
if (!result.rows.length) table.appendChild(progressNode("caption", "결과가 없습니다."));
|
||||
}
|
||||
|
||||
function excelBody(result, quota) {
|
||||
if (!quota && result.type === "TEXT_ANALYSIS") {
|
||||
if (!result.words.length) return null;
|
||||
return [{ Text: "Text", Count: "Count" }].concat(result.words.slice(0, 100).map(function (word) {
|
||||
return { Text: word.text, Count: String(word.count) };
|
||||
}));
|
||||
}
|
||||
var rows = result.headerRows.concat(result.rows);
|
||||
var width = resultWidth(rows);
|
||||
if (rows.length < 2 || width < 2) return null;
|
||||
return rows.map(function (row, index) {
|
||||
var values = {};
|
||||
for (var col = 0; col < width; col++) values["c" + col] = "";
|
||||
row.cells.forEach(function (cell) {
|
||||
var header = index < result.headerRows.length;
|
||||
var text = header ? (cell.textValue || "") : quota ? quotaCellText(cell, true) : reportCellText(cell, row, result, true);
|
||||
if (header || (cell.rowSpan || 1) > 1 || (cell.colSpan || 1) > 1) {
|
||||
text += "|" + (cell.rowSpan > 1 ? cell.rowSpan : "") + "|" + (cell.colSpan > 1 ? cell.colSpan : "");
|
||||
}
|
||||
values["c" + cell.columnIndex] = text;
|
||||
});
|
||||
return values;
|
||||
});
|
||||
}
|
||||
|
||||
function downloadName(header) {
|
||||
var extended = /filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(header || "");
|
||||
if (extended) {
|
||||
try { return decodeURIComponent(extended[2].trim().replace(/^"|"$/g, "")); } catch (_) { /* 일반 filename으로 대체 */ }
|
||||
}
|
||||
var plain = /filename\s*=\s*("([^"]*)"|[^;]+)/i.exec(header || "");
|
||||
return plain ? (plain[2] || plain[1]).trim() : "result.xlsx";
|
||||
}
|
||||
|
||||
async function downloadResult(result, title, quota, signal) {
|
||||
var body = excelBody(result, quota);
|
||||
if (!body) throw new Error("다운로드할 결과가 없습니다.");
|
||||
var qtype = !quota && result.type === "TEXT_ANALYSIS" ? "text" : "";
|
||||
var response = await progressFetch("/export/" + progressProject() + (quota ? "/quota" : "/table"), {
|
||||
tables: [{ head: title, vname: quota ? "" : result.questionId, qtype: qtype, body: body }],
|
||||
turn: !quota && !!(result.appliedOptions && result.appliedOptions.transpose)
|
||||
}, signal);
|
||||
var disposition = response.headers.get("content-disposition");
|
||||
if (!disposition || /json|text\/html/i.test(response.headers.get("content-type") || "")) {
|
||||
throw new Error("다운로드 응답 형식을 확인해 주세요.");
|
||||
}
|
||||
var blob = await response.blob();
|
||||
signal.throwIfAborted();
|
||||
var url = URL.createObjectURL(blob);
|
||||
var link = progressNode("a");
|
||||
link.href = url;
|
||||
link.download = downloadName(disposition).replace(/[\\/:*?"<>|\x00-\x1f\x7f]/g, "_");
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
|
||||
progressStatus("Excel 파일을 다운로드했습니다.", false);
|
||||
}
|
||||
|
||||
function renderResult(host, result, title, quota) {
|
||||
host.textContent = "";
|
||||
var heading = progressTitleNode(title, "bg-navy-2 text-white p-2");
|
||||
var button = progressNode("button", "Excel 다운로드", "btn btn-sm btn-secondary my-2");
|
||||
button.type = "button";
|
||||
button.setAttribute("data-progress-action", "");
|
||||
button.disabled = !!activeProgressRequest;
|
||||
button.addEventListener("click", function () {
|
||||
progressRun(function (signal) { return downloadResult(result, title, quota, signal); });
|
||||
});
|
||||
host.appendChild(heading);
|
||||
|
||||
if(progressConfig.useExcelExport){
|
||||
host.appendChild(button);
|
||||
}
|
||||
|
||||
var table = progressNode("table", null, "table table-sm text-center table-bordered");
|
||||
table.style.cssText = "table-layout:fixed;font-size:20px";
|
||||
host.appendChild(table);
|
||||
makeTable(table, result, quota);
|
||||
}
|
||||
|
||||
function assertResult(result, quota) {
|
||||
var validRow = function (row) {
|
||||
return row && Array.isArray(row.cells) && row.cells.every(function (cell) {
|
||||
return cell && Number.isSafeInteger(cell.columnIndex) && cell.columnIndex >= 0 && typeof cell.kind === "string" &&
|
||||
(cell.rowSpan == null || Number.isSafeInteger(cell.rowSpan) && cell.rowSpan > 0) &&
|
||||
(cell.colSpan == null || Number.isSafeInteger(cell.colSpan) && cell.colSpan > 0);
|
||||
});
|
||||
};
|
||||
if (!result || !Array.isArray(result.headerRows) || !result.headerRows.every(validRow) ||
|
||||
!Array.isArray(result.rows) || !result.rows.every(validRow) ||
|
||||
(!quota && (!["TABLE", "TEXT_ANALYSIS"].includes(result.type) || !Array.isArray(result.columns) || !Array.isArray(result.words)))) {
|
||||
throw new Error("집계 결과 형식을 확인해 주세요.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function readReportStream(response, indexes, onEvent, signal) {
|
||||
if (!response.body || !(response.headers.get("content-type") || "").includes("application/x-ndjson")) {
|
||||
if (response.body) await response.body.cancel();
|
||||
throw new Error("집계 스트림 응답을 확인해 주세요.");
|
||||
}
|
||||
var reader = response.body.getReader();
|
||||
var decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
var pending = "", position = 0, succeeded = 0, failed = 0, complete = false;
|
||||
function accept(line) {
|
||||
if (!line.trim()) return;
|
||||
if (complete) throw new Error("완료 이후에 스트림 이벤트가 수신되었습니다.");
|
||||
var event = JSON.parse(line);
|
||||
if (event.type === "complete") {
|
||||
if (event.total !== indexes.length || event.succeeded !== succeeded || event.failed !== failed || position !== indexes.length) {
|
||||
throw new Error("집계 스트림의 완료 건수가 일치하지 않습니다.");
|
||||
}
|
||||
complete = true;
|
||||
return;
|
||||
}
|
||||
if (event.position !== position || event.index !== indexes[position] || position >= indexes.length) {
|
||||
throw new Error("집계 스트림의 문항 순서가 올바르지 않습니다.");
|
||||
}
|
||||
if (event.type === "result") { assertResult(event.result, false); succeeded++; }
|
||||
else if (event.type === "error" && typeof event.message === "string" && Number.isInteger(event.status) && event.status >= 400 && event.status <= 599) failed++;
|
||||
else throw new Error("집계 스트림 이벤트 형식을 확인해 주세요.");
|
||||
onEvent(event);
|
||||
position++;
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
var chunk = await reader.read();
|
||||
signal.throwIfAborted();
|
||||
pending += decoder.decode(chunk.value, { stream: !chunk.done });
|
||||
var newline;
|
||||
while ((newline = pending.indexOf("\n")) >= 0) {
|
||||
accept(pending.slice(0, newline));
|
||||
pending = pending.slice(newline + 1);
|
||||
}
|
||||
if (chunk.done) break;
|
||||
}
|
||||
if (pending.trim()) accept(pending);
|
||||
if (!complete) throw new Error("집계 스트림이 완료 전에 종료되었습니다. 수신한 결과는 유지합니다.");
|
||||
return { succeeded: succeeded, failed: failed };
|
||||
} finally {
|
||||
await reader.cancel().catch(function () {});
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadReports(signal) {
|
||||
var section = document.getElementById("progress-reports");
|
||||
section.textContent = "";
|
||||
var indexes = progressConfig.indexes;
|
||||
if (!Array.isArray(indexes) || !indexes.length) {
|
||||
section.appendChild(progressNode("p", "조회할 문항이 없습니다. indexes를 설정해 주세요.", "text-muted"));
|
||||
return { succeeded: 0, failed: 0 };
|
||||
}
|
||||
var hosts = indexes.map(function (index) {
|
||||
var host = progressNode("section", "조회 중: " + index, "mb-3");
|
||||
host.dataset.pending = "true";
|
||||
section.appendChild(host);
|
||||
return host;
|
||||
});
|
||||
try {
|
||||
var response = await progressFetch("/project/" + progressProject() + "/statistics/result", Object.assign({}, progressOptions(), {
|
||||
indexes: indexes, mode: "STANDARD", banners: progressConfig.banners, filter: progressConfig.filter
|
||||
}), signal);
|
||||
return await readReportStream(response, indexes, function (event) {
|
||||
var host = hosts[event.position];
|
||||
delete host.dataset.pending;
|
||||
if (event.type === "error") {
|
||||
host.textContent = event.index + ": " + event.message;
|
||||
host.className = "text-danger mb-3";
|
||||
} else {
|
||||
renderResult(host, event.result, progressConfig.titles[event.position] || event.result.title || event.index, false);
|
||||
}
|
||||
}, signal);
|
||||
} finally {
|
||||
hosts.forEach(function (host) {
|
||||
if (host.dataset.pending) { host.textContent = "결과를 수신하지 못했습니다."; delete host.dataset.pending; }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadQuotaList(signal) {
|
||||
var select = document.getElementById("progress-quota");
|
||||
|
||||
if(!select) return;
|
||||
|
||||
select.textContent = "";
|
||||
select.appendChild(progressNode("option", "쿼터 없음"));
|
||||
select.options[0].value = "";
|
||||
document.getElementById("progress-quota-result").textContent = "";
|
||||
if (!progressConfig.loadQuotas) return;
|
||||
var response = await progressFetch("/quota/" + progressProject() + "/list", undefined, signal);
|
||||
var sets = await response.json();
|
||||
signal.throwIfAborted();
|
||||
if (!Array.isArray(sets) || !sets.every(function (set) { return set && Number.isInteger(set.qsOrder); })) {
|
||||
throw new Error("쿼터 목록 형식을 확인해 주세요.");
|
||||
}
|
||||
if (sets.length) select.options[0].textContent = "쿼터 선택";
|
||||
sets.forEach(function (set) {
|
||||
var option = progressNode("option", set.qsTitle || "쿼터 " + set.qsOrder);
|
||||
option.value = String(set.qsOrder);
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
|
||||
async function view_type() {
|
||||
return progressRun(async function (signal) {
|
||||
// Bluebird in the legacy Header does not provide Promise.allSettled.
|
||||
var outcomes = await Promise.all([loadReports(signal), loadQuotaList(signal)].map(function (request) {
|
||||
return Promise.resolve(request).then(
|
||||
function (value) { return { status: "fulfilled", value: value }; },
|
||||
function (reason) { return { status: "rejected", reason: reason }; }
|
||||
);
|
||||
}));
|
||||
signal.throwIfAborted();
|
||||
var errors = outcomes.filter(function (outcome) { return outcome.status === "rejected"; });
|
||||
if (errors.length) throw new Error(errors.map(function (outcome) { return outcome.reason.message; }).join(" / "));
|
||||
var reports = outcomes[0].value;
|
||||
progressStatus("조회 완료: Report 성공 " + reports.succeeded + "건, 실패 " + reports.failed + "건", reports.failed > 0);
|
||||
});
|
||||
}
|
||||
|
||||
async function viewQuota() {
|
||||
return progressRun(async function (signal) {
|
||||
var select = document.getElementById("progress-quota");
|
||||
|
||||
if(!select) return;
|
||||
if (!select.value) throw new Error("쿼터를 선택해 주세요.");
|
||||
|
||||
var options = progressOptions();
|
||||
var response = await progressFetch("/quota/" + progressProject() + "/" + encodeURIComponent(select.value) + "/result", {
|
||||
dataScope: options.dataScope, startDate: options.startDate, endDate: options.endDate
|
||||
}, signal);
|
||||
var result = assertResult(await response.json(), true);
|
||||
signal.throwIfAborted();
|
||||
renderResult(document.getElementById("progress-quota-result"), result, result.title || select.options[select.selectedIndex].text, true);
|
||||
progressStatus("쿼터 조회를 완료했습니다.", false);
|
||||
});
|
||||
}
|
||||
|
||||
$(document).ready(function () {
|
||||
var toolbar = document.getElementById("progress-toolbar");
|
||||
var query = progressNode("button", "조회", "btn btn-sm btn-secondary mr-2");
|
||||
query.type = "button";
|
||||
query.setAttribute("data-progress-action", "");
|
||||
query.addEventListener("click", view_type);
|
||||
toolbar.appendChild(query);
|
||||
|
||||
if(progressConfig.loadQuotas){
|
||||
var select = progressNode("select", null, "form-control form-control-sm mr-2");
|
||||
select.id = "progress-quota";
|
||||
select.style.width = "auto";
|
||||
select.setAttribute("aria-label", "쿼터 선택");
|
||||
select.setAttribute("data-progress-action", "");
|
||||
select.addEventListener("change", function () { $("#progress-quota-view").prop("disabled", !select.value); });
|
||||
toolbar.appendChild(select);
|
||||
var quota = progressNode("button", "쿼터 조회", "btn btn-sm btn-secondary mr-2");
|
||||
quota.type = "button";
|
||||
quota.id = "progress-quota-view";
|
||||
quota.disabled = true;
|
||||
quota.setAttribute("data-progress-action", "");
|
||||
quota.addEventListener("click", viewQuota);
|
||||
toolbar.appendChild(quota);
|
||||
}
|
||||
|
||||
var cancel = progressNode("button", "취소", "btn btn-sm btn-outline-secondary");
|
||||
cancel.id = "progress-cancel";
|
||||
cancel.type = "button";
|
||||
cancel.disabled = true;
|
||||
cancel.addEventListener("click", function () { if (activeProgressRequest) activeProgressRequest.abort(); });
|
||||
toolbar.appendChild(cancel);
|
||||
window.addEventListener("pagehide", function () { if (activeProgressRequest) activeProgressRequest.abort(); });
|
||||
if (!progressConfig.apiBase || !progressConfig.apiKey) {
|
||||
progressStatus("API 주소와 API Key를 설정한 후 조회해 주세요.", false);
|
||||
} else view_type();
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- #include Virtual="/include/Footer.asp"-->
|
||||
|
||||
Reference in New Issue
Block a user