369 lines
11 KiB
TypeScript
369 lines
11 KiB
TypeScript
import { isRecord, validDateRange } from "@/types/kart";
|
|
import type {
|
|
Question,
|
|
ReportBatch,
|
|
ReportCell,
|
|
ReportFilter,
|
|
ReportResult,
|
|
ReportRow,
|
|
ReportEvent,
|
|
FilterDraft,
|
|
DisplayMode,
|
|
} from "@/types/report";
|
|
|
|
const optionalText = (v: unknown) => v == null || typeof v === "string";
|
|
const optionalNumber = (v: unknown) =>
|
|
v == null || (typeof v === "number" && Number.isFinite(v));
|
|
const integer = (v: unknown): v is number =>
|
|
typeof v === "number" && Number.isSafeInteger(v);
|
|
const strings = (v: unknown): v is string[] =>
|
|
Array.isArray(v) && v.every((s) => typeof s === "string");
|
|
const conditions = new Set([
|
|
"EQ",
|
|
"NE",
|
|
"GT",
|
|
"GE",
|
|
"LT",
|
|
"LE",
|
|
"IN",
|
|
"NOT_IN",
|
|
"BETWEEN",
|
|
"IS_ANSWERED",
|
|
"IS_UNANSWERED",
|
|
]);
|
|
export const isQuestion = (v: unknown): v is Question =>
|
|
isRecord(v) &&
|
|
typeof v.qid === "string" &&
|
|
v.qid.length > 0 &&
|
|
(v.qOrder == null || integer(v.qOrder)) &&
|
|
[
|
|
"variable",
|
|
"title",
|
|
"explain",
|
|
"qtype",
|
|
"vtype",
|
|
"labelInfo",
|
|
"attrInfo",
|
|
"isDerived",
|
|
].every((key) => optionalText(v[key]));
|
|
function isCell(v: unknown): v is ReportCell {
|
|
return (
|
|
isRecord(v) &&
|
|
integer(v.columnIndex) &&
|
|
v.columnIndex >= 0 &&
|
|
integer(v.rowSpan) &&
|
|
v.rowSpan > 0 &&
|
|
integer(v.colSpan) &&
|
|
v.colSpan > 0 &&
|
|
typeof v.kind === "string" &&
|
|
[
|
|
"textValue",
|
|
"measurement",
|
|
"countDisplayText",
|
|
"percentDisplayText",
|
|
"statisticDisplayText",
|
|
].every((key) => optionalText(v[key])) &&
|
|
["count", "base"].every((key) => v[key] == null || integer(v[key])) &&
|
|
["percent", "statisticValue", "percentExact", "statisticExact"].every((key) =>
|
|
optionalNumber(v[key]),
|
|
)
|
|
);
|
|
}
|
|
export function isRow(v: unknown): v is ReportRow {
|
|
return (
|
|
isRecord(v) &&
|
|
integer(v.rowIndex) &&
|
|
v.rowIndex >= 0 &&
|
|
typeof v.rowId === "string" &&
|
|
typeof v.kind === "string" &&
|
|
Array.isArray(v.cells) &&
|
|
v.cells.every(isCell)
|
|
);
|
|
}
|
|
export function isReportResult(v: unknown): v is ReportResult {
|
|
return (
|
|
isRecord(v) &&
|
|
(v.type === "TABLE" || v.type === "TEXT_ANALYSIS") &&
|
|
typeof v.questionId === "string" &&
|
|
optionalText(v.title) &&
|
|
Array.isArray(v.columns) &&
|
|
v.columns.every(
|
|
(c) =>
|
|
isRecord(c) &&
|
|
typeof c.columnId === "string" &&
|
|
typeof c.kind === "string" &&
|
|
strings(c.labels),
|
|
) &&
|
|
Array.isArray(v.headerRows) &&
|
|
v.headerRows.every(isRow) &&
|
|
Array.isArray(v.rows) &&
|
|
v.rows.every(isRow) &&
|
|
Array.isArray(v.words) &&
|
|
v.words.every(
|
|
(w) =>
|
|
isRecord(w) &&
|
|
typeof w.text === "string" &&
|
|
typeof w.tag === "string" &&
|
|
integer(w.count) &&
|
|
w.count >= 0,
|
|
)
|
|
);
|
|
}
|
|
export function readReportEvent(v: unknown): ReportEvent {
|
|
if (isRecord(v)) {
|
|
if (
|
|
v.type === "complete" &&
|
|
integer(v.total) &&
|
|
v.total >= 0 &&
|
|
integer(v.succeeded) &&
|
|
v.succeeded >= 0 &&
|
|
integer(v.failed) &&
|
|
v.failed >= 0 &&
|
|
v.succeeded + v.failed === v.total
|
|
)
|
|
return {
|
|
type: "complete",
|
|
total: v.total,
|
|
succeeded: v.succeeded,
|
|
failed: v.failed,
|
|
};
|
|
if (integer(v.position) && v.position >= 0 && typeof v.index === "string") {
|
|
if (v.type === "result" && isReportResult(v.result))
|
|
return {
|
|
type: "result",
|
|
position: v.position,
|
|
index: v.index,
|
|
result: v.result,
|
|
};
|
|
if (
|
|
v.type === "error" &&
|
|
integer(v.status) &&
|
|
v.status >= 400 &&
|
|
v.status <= 599 &&
|
|
typeof v.code === "string" &&
|
|
typeof v.message === "string"
|
|
) {
|
|
return {
|
|
type: "error",
|
|
position: v.position,
|
|
index: v.index,
|
|
status: v.status,
|
|
code: v.code,
|
|
message: v.message,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
throw new Error("집계 스트림의 응답 형식이 올바르지 않습니다.");
|
|
}
|
|
export function readFilter(v: unknown, depth = 0): ReportFilter {
|
|
if (!isRecord(v) || depth > 32) throw new Error("필터 구조를 확인해 주세요.");
|
|
const { operator } = v;
|
|
if (operator === "AND" || operator === "OR" || operator === "NOT") {
|
|
if (
|
|
!Array.isArray(v.children) ||
|
|
!v.children.length ||
|
|
v.children.length > 128 ||
|
|
(operator === "NOT" && v.children.length !== 1) ||
|
|
(v.values != null && (!Array.isArray(v.values) || v.values.length)) ||
|
|
v.dimensionId
|
|
)
|
|
throw new Error("필터 그룹의 조건을 확인해 주세요.");
|
|
return {
|
|
operator,
|
|
children: v.children.map((child) => readFilter(child, depth + 1)),
|
|
};
|
|
}
|
|
if (
|
|
typeof operator !== "string" ||
|
|
!conditions.has(operator) ||
|
|
typeof v.dimensionId !== "string" ||
|
|
!v.dimensionId.trim() ||
|
|
v.dimensionId.includes("#") ||
|
|
(v.reference != null &&
|
|
v.reference !== "QID" &&
|
|
v.reference !== "VARIABLE") ||
|
|
(v.children != null && (!Array.isArray(v.children) || v.children.length))
|
|
)
|
|
throw new Error("필터 문항과 비교 방식을 확인해 주세요.");
|
|
const values = v.values ?? [];
|
|
if (
|
|
!Array.isArray(values) ||
|
|
!values.every(
|
|
(value) =>
|
|
typeof value === "string" ||
|
|
(typeof value === "number" && Number.isFinite(value)),
|
|
)
|
|
)
|
|
throw new Error("필터 비교 값을 확인해 주세요.");
|
|
const expected =
|
|
operator === "IS_ANSWERED" || operator === "IS_UNANSWERED"
|
|
? 0
|
|
: operator === "BETWEEN"
|
|
? 2
|
|
: operator === "IN" || operator === "NOT_IN"
|
|
? -1
|
|
: 1;
|
|
if (expected === -1 ? values.length < 1 : values.length !== expected)
|
|
throw new Error("필터 값의 개수를 확인해 주세요.");
|
|
return {
|
|
operator: operator as ReportFilter["operator"],
|
|
dimensionId: v.dimensionId,
|
|
reference: v.reference ?? "QID",
|
|
values,
|
|
};
|
|
}
|
|
export function readReportBatch(v: unknown): ReportBatch {
|
|
if (!isRecord(v) || !strings(v.indexes) || !v.indexes.length)
|
|
throw new Error("집계할 문항을 선택해 주세요.");
|
|
const mode = v.mode ?? "STANDARD";
|
|
if (
|
|
!["STANDARD", "TABULATION_0", "TABULATION_1"].includes(String(mode)) ||
|
|
(mode === "STANDARD"
|
|
? v.indexes.some((id) => !id.trim())
|
|
: v.indexes.some((id) => id !== ""))
|
|
)
|
|
throw new Error("집계 모드와 문항을 확인해 주세요.");
|
|
const banners = v.banners ?? [];
|
|
if (
|
|
!Array.isArray(banners) ||
|
|
!banners.every(
|
|
(group) =>
|
|
strings(group) &&
|
|
group.length > 0 &&
|
|
group.length <= 5 &&
|
|
group.every((id) => id.trim()),
|
|
)
|
|
)
|
|
throw new Error("배너 묶음은 문항 1~5개를 선택해 주세요.");
|
|
const startDate = v.startDate ?? "",
|
|
endDate = v.endDate ?? "";
|
|
if (
|
|
typeof startDate !== "string" ||
|
|
typeof endDate !== "string" ||
|
|
!validDateRange({ startDate, endDate })
|
|
)
|
|
throw new Error("조회 날짜 범위를 확인해 주세요.");
|
|
const dataScope = v.dataScope ?? "ACTUAL",
|
|
headerMode = v.headerMode ?? "MERGED";
|
|
const percentageDecimals = v.percentageDecimals ?? 14,
|
|
statisticDecimals = v.statisticDecimals ?? 14;
|
|
if (
|
|
!["ACTUAL", "TEST", "ALL"].includes(String(dataScope)) ||
|
|
!["NONE", "FLAT", "MERGED"].includes(String(headerMode)) ||
|
|
!integer(percentageDecimals) ||
|
|
percentageDecimals < 0 ||
|
|
percentageDecimals > 14 ||
|
|
!integer(statisticDecimals) ||
|
|
statisticDecimals < 0 ||
|
|
statisticDecimals > 14
|
|
)
|
|
throw new Error("집계 표시 옵션을 확인해 주세요.");
|
|
for (const key of [
|
|
"transpose",
|
|
"showSubtotals",
|
|
"showValueCodes",
|
|
"showNumericSum",
|
|
])
|
|
if (v[key] != null && typeof v[key] !== "boolean")
|
|
throw new Error("집계 옵션을 확인해 주세요.");
|
|
const groups = v.valueGroups ?? [];
|
|
if (
|
|
!Array.isArray(groups) ||
|
|
!groups.every(
|
|
(g) =>
|
|
isRecord(g) &&
|
|
typeof g.label === "string" &&
|
|
g.label.trim() &&
|
|
strings(g.values) &&
|
|
g.values.length &&
|
|
g.values.every((value) => value.trim()),
|
|
)
|
|
)
|
|
throw new Error("보기 묶음의 이름과 값을 확인해 주세요.");
|
|
return {
|
|
indexes: [...v.indexes],
|
|
mode: mode as ReportBatch["mode"],
|
|
banners: banners.map((group) => [...group]),
|
|
filter: v.filter == null ? null : readFilter(v.filter),
|
|
dataScope: dataScope as ReportBatch["dataScope"],
|
|
headerMode: headerMode as ReportBatch["headerMode"],
|
|
...(startDate ? { startDate, endDate } : {}),
|
|
percentageDecimals,
|
|
statisticDecimals,
|
|
transpose: v.transpose === true,
|
|
showSubtotals: v.showSubtotals !== false,
|
|
showValueCodes: v.showValueCodes === true,
|
|
showNumericSum: v.showNumericSum === true,
|
|
valueGroups: groups.map((g) => ({ label: g.label, values: [...g.values] })),
|
|
};
|
|
}
|
|
export function compileFilter(draft: FilterDraft | null): ReportFilter | null {
|
|
if (!draft) return null;
|
|
if (draft.kind === "group")
|
|
return readFilter({
|
|
operator: draft.operator,
|
|
children: draft.children.map(compileFilter),
|
|
});
|
|
const noValues =
|
|
draft.operator === "IS_ANSWERED" || draft.operator === "IS_UNANSWERED";
|
|
const values = noValues
|
|
? []
|
|
: draft.values.map((value) => {
|
|
if (!draft.numeric) return value;
|
|
if (!value.trim() || !Number.isFinite(Number(value)))
|
|
throw new Error("숫자 필터 값을 확인해 주세요.");
|
|
return Number(value);
|
|
});
|
|
return readFilter({
|
|
operator: draft.operator,
|
|
dimensionId: draft.dimensionId,
|
|
reference: "QID",
|
|
values,
|
|
});
|
|
}
|
|
export function cellDisplay(cell: ReportCell, mode: DisplayMode): string {
|
|
if (cell.kind === "TEXT" || cell.kind === "EMPTY")
|
|
return cell.textValue ?? "";
|
|
if (cell.kind === "STATISTIC" || cell.kind === "MISSING")
|
|
return cell.statisticDisplayText ?? "-";
|
|
const n =
|
|
cell.countDisplayText ?? (cell.count == null ? "-" : String(cell.count));
|
|
const raw =
|
|
cell.percentDisplayText ??
|
|
(cell.percent == null ? "-" : String(cell.percent));
|
|
const percent = raw === "-" || !raw ? "-" : raw + "%";
|
|
return mode === "N"
|
|
? n
|
|
: mode === "PERCENT"
|
|
? percent
|
|
: n + " (" + percent + ")";
|
|
}
|
|
export function choices(
|
|
question: Question,
|
|
): { value: string; label: string }[] {
|
|
if (!question.labelInfo) return [];
|
|
const parsed: unknown = JSON.parse(question.labelInfo);
|
|
if (!isRecord(parsed)) throw new Error("문항 보기 정보를 확인해 주세요.");
|
|
return Object.entries(parsed).flatMap(([key, value]) =>
|
|
isRecord(value)
|
|
? [
|
|
{
|
|
value:
|
|
typeof value.value === "string"
|
|
? value.value
|
|
: typeof value.value === "number" &&
|
|
Number.isFinite(value.value)
|
|
? String(value.value)
|
|
: key,
|
|
label: typeof value.label === "string" ? value.label : key,
|
|
},
|
|
]
|
|
: [],
|
|
);
|
|
}
|
|
export const canIndex = (q: Question) =>
|
|
q.qtype !== "com" && q.qtype !== "come";
|
|
export const canBanner = (q: Question) =>
|
|
canIndex(q) && q.qtype !== "num" && q.qtype !== "text";
|