261021_01_ENH: 1차 마이그레이션 완료
This commit is contained in:
129
src/lib/bookmark-json.ts
Normal file
129
src/lib/bookmark-json.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import { isRecord } from "@/types/kart";
|
||||
import {
|
||||
filterCondition,
|
||||
readFilterArray,
|
||||
realFilterCondition,
|
||||
writeFilterArray,
|
||||
type LegacyFilterLine,
|
||||
} from "@/lib/legacy-filter";
|
||||
|
||||
/**
|
||||
* Legacy BOOKMARK_JSON (states/Format.js bookmarkJsonFormat). The legacy KART reads and rewrites
|
||||
* the same REPORT_BOOKMARK rows, so this module is the only place that knows the stored shape:
|
||||
* `{"INDEX":"a,b","BANNER":"a|b,c","FILTER_CONDITION":"…","REAL_FILTER_CONDITION":"…",
|
||||
* "FILTER_ARRAY":"[…]","OPTION":{"TEST":"TEST","TURN":"1"}}`.
|
||||
*/
|
||||
|
||||
/** The filter edit tree with the two condition strings stored beside it. */
|
||||
export type BookmarkFilter = {
|
||||
lines: LegacyFilterLine[];
|
||||
array: string;
|
||||
condition: string;
|
||||
realCondition: string;
|
||||
};
|
||||
|
||||
export type BookmarkSetting = {
|
||||
index: string[];
|
||||
banners: string[][];
|
||||
filter: BookmarkFilter;
|
||||
/** Stored OPTION object; TEST / TURN map to the checks, other keys (legacy PRTHEAD) are kept. */
|
||||
option: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export const emptyBookmarkFilter: BookmarkFilter = {
|
||||
lines: [],
|
||||
array: "",
|
||||
condition: "",
|
||||
realCondition: "",
|
||||
};
|
||||
|
||||
export const emptyBookmarkSetting: BookmarkSetting = {
|
||||
index: [],
|
||||
banners: [],
|
||||
filter: emptyBookmarkFilter,
|
||||
option: {},
|
||||
};
|
||||
|
||||
/** Never throws: unreadable parts load as empty, like a fresh "New" tab. */
|
||||
export function readBookmarkSetting(json: string): BookmarkSetting {
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(json);
|
||||
} catch {
|
||||
// Treated as an empty setting below.
|
||||
}
|
||||
const source = isRecord(parsed) ? parsed : {};
|
||||
const text = (key: string) => {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value : "";
|
||||
};
|
||||
const array = text("FILTER_ARRAY");
|
||||
let lines: LegacyFilterLine[] = [];
|
||||
try {
|
||||
lines = readFilterArray(array);
|
||||
} catch {
|
||||
// Keep the stored strings so saving an untouched filter does not drop them.
|
||||
}
|
||||
return {
|
||||
index: text("INDEX")
|
||||
.split(",")
|
||||
.filter((qid) => qid !== ""),
|
||||
banners: text("BANNER")
|
||||
.split(",")
|
||||
.map((group) => group.split("|").filter((qid) => qid !== ""))
|
||||
.filter((group) => group.length > 0),
|
||||
filter: {
|
||||
lines,
|
||||
array,
|
||||
condition: text("FILTER_CONDITION"),
|
||||
realCondition: text("REAL_FILTER_CONDITION"),
|
||||
},
|
||||
option: isRecord(source.OPTION) ? { ...source.OPTION } : {},
|
||||
};
|
||||
}
|
||||
|
||||
export const bookmarkTest = (option: Record<string, unknown>) => option.TEST === "TEST";
|
||||
export const bookmarkAxis = (option: Record<string, unknown>) => option.TURN === "1";
|
||||
|
||||
/**
|
||||
* Filter to store for the current edit tree. An untouched loaded filter keeps its stored strings
|
||||
* verbatim; an edited one regenerates all three from the tree so they stay consistent.
|
||||
*/
|
||||
export function bookmarkFilter(lines: LegacyFilterLine[], loaded: BookmarkFilter): BookmarkFilter {
|
||||
if (lines === loaded.lines) return loaded;
|
||||
return {
|
||||
lines,
|
||||
array: writeFilterArray(lines),
|
||||
condition: filterCondition(lines),
|
||||
realCondition: realFilterCondition(lines),
|
||||
};
|
||||
}
|
||||
|
||||
export function writeBookmarkJson(setting: {
|
||||
index: string[];
|
||||
banners: string[][];
|
||||
filter: BookmarkFilter;
|
||||
option: Record<string, unknown>;
|
||||
isTest: boolean;
|
||||
isAxis: boolean;
|
||||
}): string {
|
||||
const rest = Object.fromEntries(
|
||||
Object.entries(setting.option).filter(([key]) => key !== "TEST" && key !== "TURN"),
|
||||
);
|
||||
return JSON.stringify({
|
||||
INDEX: setting.index.join(","),
|
||||
BANNER: setting.banners
|
||||
.filter((group) => group.length > 0)
|
||||
.map((group) => group.join("|"))
|
||||
.join(","),
|
||||
FILTER_CONDITION: setting.filter.condition,
|
||||
REAL_FILTER_CONDITION: setting.filter.realCondition,
|
||||
FILTER_ARRAY: setting.filter.array,
|
||||
// Legacy key order: TEST, TURN, then the rest (PRTHEAD); unchecked options are omitted.
|
||||
OPTION: {
|
||||
...(setting.isTest ? { TEST: "TEST" } : {}),
|
||||
...(setting.isAxis ? { TURN: "1" } : {}),
|
||||
...rest,
|
||||
},
|
||||
});
|
||||
}
|
||||
54
src/lib/download-name.ts
Normal file
54
src/lib/download-name.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
/**
|
||||
* Legacy front-made download name `"{prefix} {project title} {date}.xlsx"`, with the date as
|
||||
* `YYYY-MM-DD HHmmss` in browser time (legacy DateTimeString added year+month+day as numbers).
|
||||
* Characters a file name cannot hold become `_`, like the server's Content-Disposition names.
|
||||
*/
|
||||
export function exportFileName(prefix: string, title: string, now: Date): string {
|
||||
const date =
|
||||
now.getFullYear() +
|
||||
"-" +
|
||||
pad(now.getMonth() + 1) +
|
||||
"-" +
|
||||
pad(now.getDate()) +
|
||||
" " +
|
||||
pad(now.getHours()) +
|
||||
pad(now.getMinutes()) +
|
||||
pad(now.getSeconds());
|
||||
const safe = (prefix + " " + title + " " + date).replace(/[\u0000-\u001f\u007f\\/:*?"<>|]/g, "_");
|
||||
return safe + ".xlsx";
|
||||
}
|
||||
|
||||
/** Prefixes of the legacy download names. */
|
||||
export const EXPORT_PREFIX = {
|
||||
table: "[TABLE]",
|
||||
quota: "[QUOTA]",
|
||||
data: "(DATA)",
|
||||
dataIncomplete: "(DATA_N)",
|
||||
guide: "(GUIDE)",
|
||||
header: "(Header)",
|
||||
title: "[Explain]",
|
||||
} as const;
|
||||
/** Legacy fixed name of the question upload template. */
|
||||
export const QUESTION_FORM_NAME = "KON 문항 등록 양식.xlsx";
|
||||
|
||||
/**
|
||||
* File name from a Content-Disposition header. Prefers the RFC 5987 `filename*=UTF-8''…` form the
|
||||
* server sends for Korean names, then a plain `filename`, then the fallback.
|
||||
*/
|
||||
export function contentDispositionName(header: string | null, fallback: string): string {
|
||||
if (!header) return fallback;
|
||||
const extended = /filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(header);
|
||||
if (extended) {
|
||||
try {
|
||||
const name = decodeURIComponent(extended[2].trim().replace(/^"|"$/g, ""));
|
||||
if (name) return name;
|
||||
} catch {
|
||||
// Malformed percent-encoding: try the plain form below.
|
||||
}
|
||||
}
|
||||
const plain = /filename\s*=\s*("([^"]*)"|[^;]+)/i.exec(header);
|
||||
const name = (plain?.[2] ?? plain?.[1] ?? "").trim();
|
||||
return name || fallback;
|
||||
}
|
||||
@@ -2,6 +2,11 @@ import { createHttpClient } from "@kri/common/http";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
|
||||
const resolveBaseUrl = () =>
|
||||
typeof window === "undefined" ? clientEnv.API_BASE : new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||
typeof window === "undefined"
|
||||
? clientEnv.API_BASE
|
||||
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||
|
||||
export const nextApi = createHttpClient(resolveBaseUrl());
|
||||
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
||||
onForbidden: false,
|
||||
onResponseError: false,
|
||||
});
|
||||
|
||||
@@ -3,11 +3,14 @@ import { createHttpClient } from "@kri/common/http";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
|
||||
export async function createServerApi() {
|
||||
export async function createServerApi(authenticated = true) {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value ?? null;
|
||||
const accessToken = authenticated ? cookieStore.get(CookieKeys.AuthToken)?.value ?? null : null;
|
||||
return createHttpClient(serverEnv.API_SERVER, {
|
||||
getToken: () => accessToken,
|
||||
defaultHeaders: { "content-type": "application/json" },
|
||||
onUnauthorized: false,
|
||||
onForbidden: false,
|
||||
onResponseError: false,
|
||||
});
|
||||
}
|
||||
|
||||
203
src/lib/legacy-filter.ts
Normal file
203
src/lib/legacy-filter.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { isRecord } from "@/types/kart";
|
||||
import type { ReportFilter } from "@/types/report";
|
||||
|
||||
/**
|
||||
* Legacy FilterPopup line (states/Format.js filterFormat). Bookmarks persist this tree as
|
||||
* FILTER_ARRAY JSON in a database shared with the legacy system, so the shape is kept verbatim.
|
||||
*/
|
||||
export type LegacyFilterOp =
|
||||
| "IN"
|
||||
| "NOT IN"
|
||||
| "<"
|
||||
| "<="
|
||||
| ">"
|
||||
| ">="
|
||||
| "IS NOT NULL"
|
||||
| "IS NULL";
|
||||
export type AndOr = "" | "AND" | "OR";
|
||||
export type LegacyFilterLine = {
|
||||
id: string;
|
||||
qid: string;
|
||||
vname: string;
|
||||
op: LegacyFilterOp;
|
||||
/** Comma-separated codes for IN / NOT IN, a single value for comparisons. */
|
||||
value: string;
|
||||
preAndOr: AndOr;
|
||||
postAndOr: AndOr;
|
||||
childList: LegacyFilterLine[];
|
||||
};
|
||||
|
||||
export const FILTER_OPERATORS: { value: LegacyFilterOp; label: string }[] = [
|
||||
{ value: "IN", label: "=" },
|
||||
{ value: "NOT IN", label: "≠" },
|
||||
{ value: "<", label: "<" },
|
||||
{ value: "<=", label: "≤" },
|
||||
{ value: ">", label: ">" },
|
||||
{ value: ">=", label: "≥" },
|
||||
{ value: "IS NOT NULL", label: "Has Value" },
|
||||
{ value: "IS NULL", label: "Has No Value" },
|
||||
];
|
||||
|
||||
export const newFilterLine = (id: string, preAndOr: AndOr = ""): LegacyFilterLine => ({
|
||||
id,
|
||||
qid: "",
|
||||
vname: "",
|
||||
op: "IN",
|
||||
value: "",
|
||||
preAndOr,
|
||||
postAndOr: "",
|
||||
childList: [],
|
||||
});
|
||||
|
||||
const isActive = (line: LegacyFilterLine) => line.qid !== "";
|
||||
|
||||
/** Legacy FilterPopup.makeFilterString; mode "v" names variables, "r" the [UK:n] form. */
|
||||
export function makeFilterString(
|
||||
list: LegacyFilterLine[],
|
||||
mode: "v" | "r",
|
||||
): string {
|
||||
let text = "(";
|
||||
for (const line of list) {
|
||||
if (!isActive(line)) continue;
|
||||
const bracket = line.op.includes("IN");
|
||||
text += line.preAndOr !== "" ? " " + line.preAndOr : "";
|
||||
text +=
|
||||
" " +
|
||||
(mode === "r"
|
||||
? line.qid.replace(
|
||||
/(\d+)((?:\[\w+\])*)/g,
|
||||
(_match, number: string, suffix: string) =>
|
||||
"[UK:" + number + "]" + suffix,
|
||||
)
|
||||
: line.vname);
|
||||
text += " " + line.op + " ";
|
||||
if (bracket) text += "(";
|
||||
text += line.value;
|
||||
if (bracket) text += ")";
|
||||
if (line.childList.length > 0 && isActive(line.childList[0])) {
|
||||
text += line.postAndOr !== "" ? " " + line.postAndOr + " " : "";
|
||||
text += makeFilterString(line.childList, mode);
|
||||
}
|
||||
}
|
||||
return text + " )";
|
||||
}
|
||||
|
||||
/** Condition text shown in the Filter box; empty when no line has a question. */
|
||||
export const filterCondition = (list: LegacyFilterLine[]) =>
|
||||
list.length > 0 && isActive(list[0]) ? makeFilterString(list, "v") : "";
|
||||
export const realFilterCondition = (list: LegacyFilterLine[]) =>
|
||||
list.length > 0 && isActive(list[0]) ? makeFilterString(list, "r") : "";
|
||||
|
||||
/** Numeric tokens become numbers (server compares them numerically, like LegacyFilterService). */
|
||||
const filterValue = (token: string): string | number => {
|
||||
const text = token.trim();
|
||||
return /^[+-]?(\d+(\.\d*)?|\.\d+)$/.test(text) ? Number(text) : text;
|
||||
};
|
||||
|
||||
function condition(line: LegacyFilterLine): ReportFilter {
|
||||
const base = { dimensionId: line.qid, reference: "QID" as const };
|
||||
if (line.op === "IS NOT NULL")
|
||||
return { ...base, operator: "IS_ANSWERED", values: [] };
|
||||
if (line.op === "IS NULL")
|
||||
return { ...base, operator: "IS_UNANSWERED", values: [] };
|
||||
const values = line.value
|
||||
.split(",")
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token !== "");
|
||||
if (!values.length) throw new Error("필터 값을 선택해 주세요.");
|
||||
if (line.op === "IN" || line.op === "NOT IN")
|
||||
return {
|
||||
...base,
|
||||
operator: line.op === "IN" ? "IN" : "NOT_IN",
|
||||
values: values.map(filterValue),
|
||||
};
|
||||
const operator = ({ "<": "LT", "<=": "LE", ">": "GT", ">=": "GE" } as const)[
|
||||
line.op
|
||||
];
|
||||
return { ...base, operator, values: [filterValue(values[0])] };
|
||||
}
|
||||
|
||||
const group = (operator: "AND" | "OR", children: ReportFilter[]): ReportFilter =>
|
||||
children.length === 1 ? children[0] : { operator, children };
|
||||
|
||||
/**
|
||||
* Converts the legacy tree into the statistics filter AST with the same meaning as the legacy
|
||||
* condition string: siblings are joined by their preAndOr, a child list follows its line with
|
||||
* postAndOr as a parenthesised operand, and AND binds tighter than OR.
|
||||
*/
|
||||
export function toServerFilter(list: LegacyFilterLine[]): ReportFilter | null {
|
||||
const operands: ReportFilter[] = [];
|
||||
const operators: ("AND" | "OR")[] = [];
|
||||
const push = (operator: AndOr, operand: ReportFilter) => {
|
||||
if (operands.length) operators.push(operator === "OR" ? "OR" : "AND");
|
||||
operands.push(operand);
|
||||
};
|
||||
for (const line of list) {
|
||||
if (!isActive(line)) continue;
|
||||
push(line.preAndOr, condition(line));
|
||||
if (line.childList.length > 0 && isActive(line.childList[0])) {
|
||||
const child = toServerFilter(line.childList);
|
||||
if (child) push(line.postAndOr, child);
|
||||
}
|
||||
}
|
||||
if (!operands.length) return null;
|
||||
const orGroups: ReportFilter[][] = [[operands[0]]];
|
||||
operators.forEach((operator, index) => {
|
||||
if (operator === "OR") orGroups.push([operands[index + 1]]);
|
||||
else orGroups[orGroups.length - 1].push(operands[index + 1]);
|
||||
});
|
||||
return group(
|
||||
"OR",
|
||||
orGroups.map((children) => group("AND", children)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Legacy filterFormat key order; `postAndOr` is appended only once a child list exists. */
|
||||
function legacyLine(line: LegacyFilterLine): Record<string, unknown> {
|
||||
return {
|
||||
id: line.id,
|
||||
qid: line.qid,
|
||||
vname: line.vname,
|
||||
op: line.op,
|
||||
value: line.value,
|
||||
preAndOr: line.preAndOr,
|
||||
PostAndOr: "",
|
||||
childList: line.childList.map(legacyLine),
|
||||
...(line.postAndOr ? { postAndOr: line.postAndOr } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** FILTER_ARRAY text as the legacy FilterPopup stores it (bookmarks, derived variable rules). */
|
||||
export const writeFilterArray = (list: LegacyFilterLine[]) =>
|
||||
list.length ? JSON.stringify(list.map(legacyLine)) : "";
|
||||
|
||||
/** Reads a saved FILTER_ARRAY (legacy JSON, may use the PostAndOr spelling). */
|
||||
export function readFilterArray(json: string): LegacyFilterLine[] {
|
||||
if (!json) return [];
|
||||
const parsed: unknown = JSON.parse(json);
|
||||
if (!Array.isArray(parsed)) throw new Error("저장된 필터 형식을 확인해 주세요.");
|
||||
return parsed.map(readLine);
|
||||
}
|
||||
function readLine(line: unknown): LegacyFilterLine {
|
||||
if (!isRecord(line)) throw new Error("저장된 필터 형식을 확인해 주세요.");
|
||||
const text = (key: string) => {
|
||||
const raw = line[key];
|
||||
return typeof raw === "string" ? raw : "";
|
||||
};
|
||||
const andOr = (key: string): AndOr => {
|
||||
const raw = text(key);
|
||||
return raw === "AND" || raw === "OR" ? raw : "";
|
||||
};
|
||||
const op = FILTER_OPERATORS.find((item) => item.value === line.op)?.value;
|
||||
if (!op) throw new Error("저장된 필터 연산자를 확인해 주세요.");
|
||||
return {
|
||||
id: text("id"),
|
||||
qid: text("qid"),
|
||||
vname: text("vname"),
|
||||
op,
|
||||
value: text("value"),
|
||||
preAndOr: andOr("preAndOr"),
|
||||
postAndOr: andOr("postAndOr") || andOr("PostAndOr"),
|
||||
childList: Array.isArray(line.childList) ? line.childList.map(readLine) : [],
|
||||
};
|
||||
}
|
||||
37
src/lib/progress-zoom.ts
Normal file
37
src/lib/progress-zoom.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { isRecord, validDateRange, type DateRange } from "@/types/kart";
|
||||
|
||||
export type ZoomWindow = { start: number; end: number };
|
||||
|
||||
/** Reads start/end percentages from an ECharts `datazoom` event (direct or batched). */
|
||||
export function readZoomEvent(event: unknown): ZoomWindow | null {
|
||||
if (!isRecord(event)) return null;
|
||||
const item = Array.isArray(event.batch) ? event.batch[0] : event;
|
||||
if (!isRecord(item)) return null;
|
||||
const { start, end } = item;
|
||||
return typeof start === "number" &&
|
||||
typeof end === "number" &&
|
||||
Number.isFinite(start) &&
|
||||
Number.isFinite(end)
|
||||
? { start, end }
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy Current.js onDataZoom: label index = round((n - 1) * percent / 100).
|
||||
* `labels` are display dates (yyyy-mm-dd); returns null when they are not valid dates.
|
||||
*/
|
||||
export function zoomDateRange(
|
||||
labels: string[],
|
||||
zoom: ZoomWindow,
|
||||
): DateRange | null {
|
||||
if (!labels.length) return null;
|
||||
const at = (percent: number) =>
|
||||
labels[
|
||||
Math.min(
|
||||
labels.length - 1,
|
||||
Math.max(0, Math.round(((labels.length - 1) * percent) / 100)),
|
||||
)
|
||||
];
|
||||
const range = { startDate: at(zoom.start), endDate: at(zoom.end) };
|
||||
return range.startDate && validDateRange(range) ? range : null;
|
||||
}
|
||||
155
src/lib/project-proxy-policy.ts
Normal file
155
src/lib/project-proxy-policy.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
const progress = new Set(["day", "type", "loi", "screen"]);
|
||||
/** Browser inputs select only these implemented read operations, never an arbitrary upstream URL. */
|
||||
export function isProjectReadPath(slug: string[]): boolean {
|
||||
if (slug.length === 1) return slug[0] === "list" || slug[0] === "summary";
|
||||
return (
|
||||
slug.length === 4 &&
|
||||
(slug[0] === "0" || slug[0] === "1") &&
|
||||
slug[1] !== "." &&
|
||||
slug[1] !== ".." &&
|
||||
slug[1].length > 0 &&
|
||||
slug[1].length <= 20 &&
|
||||
!/[|/\\]/.test(slug[1]) &&
|
||||
((slug[2] === "progress" && progress.has(slug[3])) ||
|
||||
(slug[2] === "question" && slug[3] === "list"))
|
||||
);
|
||||
}
|
||||
export function projectReadQuery(
|
||||
slug: string[],
|
||||
input: URLSearchParams,
|
||||
): Record<string, string> {
|
||||
const allowed =
|
||||
slug[0] === "list"
|
||||
? ["projectType", "intranetCode", "userTeam", "keyword"]
|
||||
: slug.length === 4 && slug[2] === "progress" && slug[3] !== "day"
|
||||
? ["startDate", "endDate"]
|
||||
: [];
|
||||
const result: Record<string, string> = {};
|
||||
for (const key of allowed) {
|
||||
const value = input.get(key);
|
||||
if (value !== null) result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Quota BFF: `{type}/{pkey}/list` (GET) and `{type}/{pkey}/{quotaOrder}/result` (POST) only. */
|
||||
export function isQuotaListPath(slug: string[]): boolean {
|
||||
return (
|
||||
slug.length === 3 &&
|
||||
slug[2] === "list" &&
|
||||
isProjectReadPath([slug[0], slug[1], "question", "list"])
|
||||
);
|
||||
}
|
||||
export function isQuotaResultPath(slug: string[]): boolean {
|
||||
return (
|
||||
slug.length === 4 &&
|
||||
/^\d{1,4}$/.test(slug[2]) &&
|
||||
slug[3] === "result" &&
|
||||
isProjectReadPath([slug[0], slug[1], "question", "list"])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bookmark BFF: `{type}/{pkey}/list?page=` (GET), `{type}/{pkey}` (POST) and
|
||||
* `{type}/{pkey}/{bookmarkId}` (PUT/DELETE), forwarded under `/project/{type}/{pkey}/bookmark`.
|
||||
*/
|
||||
const isProjectSlug = (slug: string[]) =>
|
||||
isProjectReadPath([slug[0], slug[1], "question", "list"]);
|
||||
export function isBookmarkListPath(slug: string[]): boolean {
|
||||
return slug.length === 3 && slug[2] === "list" && isProjectSlug(slug);
|
||||
}
|
||||
export function isBookmarkCreatePath(slug: string[]): boolean {
|
||||
return slug.length === 2 && isProjectSlug(slug);
|
||||
}
|
||||
export function isBookmarkItemPath(slug: string[]): boolean {
|
||||
const id = slug[2] ?? "";
|
||||
return (
|
||||
slug.length === 3 &&
|
||||
id !== "list" &&
|
||||
id !== "." &&
|
||||
id !== ".." &&
|
||||
id.length > 0 &&
|
||||
id.length <= 100 &&
|
||||
!/[\s|/\\]/.test(id) &&
|
||||
isProjectSlug(slug)
|
||||
);
|
||||
}
|
||||
export function bookmarkUpstreamPath(slug: string[]): string {
|
||||
return (
|
||||
"/project/" +
|
||||
slug.slice(0, 2).map(encodeURIComponent).join("/") +
|
||||
"/bookmark" +
|
||||
slug.slice(2).map((part) => "/" + encodeURIComponent(part)).join("")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derived variable BFF: `{type}/{pkey}/list` (GET), `{type}/{pkey}` (POST) and
|
||||
* `{type}/{pkey}/{variableId}` (PUT/DELETE) under `/project/{type}/{pkey}/derived`.
|
||||
* Recalculation endpoints stay closed (the legacy screen never calls them).
|
||||
*/
|
||||
export function isDerivedListPath(slug: string[]): boolean {
|
||||
return slug.length === 3 && slug[2] === "list" && isProjectSlug(slug);
|
||||
}
|
||||
export function isDerivedCreatePath(slug: string[]): boolean {
|
||||
return slug.length === 2 && isProjectSlug(slug);
|
||||
}
|
||||
export function isDerivedItemPath(slug: string[]): boolean {
|
||||
return (
|
||||
slug.length === 3 &&
|
||||
slug[2] !== "list" &&
|
||||
slug[2] !== "recalculate" &&
|
||||
/^[A-Za-z][A-Za-z0-9_]{0,127}$/.test(slug[2]) &&
|
||||
isProjectSlug(slug)
|
||||
);
|
||||
}
|
||||
export function derivedUpstreamPath(slug: string[]): string {
|
||||
return (
|
||||
"/project/" +
|
||||
slug.slice(0, 2).map(encodeURIComponent).join("/") +
|
||||
"/derived" +
|
||||
slug.slice(2).map((part) => "/" + encodeURIComponent(part)).join("")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download BFF (`/api/export/...`): fixed file endpoints only. Returns the upstream path and the
|
||||
* request body kind, or null when the method/path is not an implemented download.
|
||||
*/
|
||||
export type ExportTarget = { path: string; body: "none" | "excel" | "data" };
|
||||
export function exportTarget(method: "GET" | "POST", slug: string[]): ExportTarget | null {
|
||||
if (method === "GET" && slug.join("/") === "form/question")
|
||||
return { path: "/export/form/question", body: "none" };
|
||||
if (slug.length !== 3 && slug.length !== 4) return null;
|
||||
if (!isProjectSlug(slug)) return null;
|
||||
const project = slug.slice(0, 2).map(encodeURIComponent).join("/");
|
||||
const action = slug.slice(2).join("/");
|
||||
if (method === "GET") {
|
||||
if (action === "form/data" || action === "form/title" || action === "guide")
|
||||
return { path: "/project/" + project + "/export/" + action, body: "none" };
|
||||
return null;
|
||||
}
|
||||
if (action === "table")
|
||||
return { path: "/project/" + project + "/export/excel/table", body: "excel" };
|
||||
if (action === "quota") return { path: "/quota/" + project + "/export/excel", body: "excel" };
|
||||
if (action === "data") return { path: "/project/" + project + "/export/data", body: "data" };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Import BFF: `{type}/{pkey}/{title|question|data}` multipart uploads. */
|
||||
export function isImportPath(slug: string[]): boolean {
|
||||
return (
|
||||
slug.length === 3 &&
|
||||
(slug[2] === "title" || slug[2] === "question" || slug[2] === "data") &&
|
||||
isProjectSlug(slug)
|
||||
);
|
||||
}
|
||||
|
||||
export function isReportStreamPath(slug: string[]): boolean {
|
||||
return (
|
||||
slug.length === 4 &&
|
||||
slug[2] === "statistics" &&
|
||||
slug[3] === "result" &&
|
||||
isProjectReadPath([slug[0], slug[1], "question", "list"])
|
||||
);
|
||||
}
|
||||
22
src/lib/quota-ui.ts
Normal file
22
src/lib/quota-ui.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { QuotaCell } from "@/types/quota";
|
||||
|
||||
// Legacy QuotaThTd colours: under target, over target, exactly met.
|
||||
const UNDER = { text: "#1cae81", gauge: "#F0F7DF" };
|
||||
const OVER = { text: "#ff2500", gauge: "#FFE5E1" };
|
||||
const MET = { text: "#0066ff", gauge: "#E1EDFF" };
|
||||
|
||||
/**
|
||||
* Picks the legacy colour and gauge from the server's achievement fields. A target of 0 has no
|
||||
* percentage: UNDEFINED (nothing completed) reads as met, POSITIVE_INFINITY as over, both without
|
||||
* a gauge bar.
|
||||
*/
|
||||
export function quotaCellStyle(cell: QuotaCell): { color: string; background?: string } {
|
||||
if (cell.achievementState === "UNDEFINED") return { color: MET.text };
|
||||
if (cell.achievementState === "POSITIVE_INFINITY") return { color: OVER.text };
|
||||
const percent = cell.achievementPercent ?? 0;
|
||||
const tone = percent < 100 ? UNDER : percent > 100 ? OVER : MET;
|
||||
return {
|
||||
color: tone.text,
|
||||
background: `linear-gradient(to right, ${tone.gauge} ${percent}%, #FAFAFA 0%)`,
|
||||
};
|
||||
}
|
||||
368
src/lib/report-contract.ts
Normal file
368
src/lib/report-contract.ts
Normal file
@@ -0,0 +1,368 @@
|
||||
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";
|
||||
121
src/lib/report-excel.ts
Normal file
121
src/lib/report-excel.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import type { ReportCell, ReportResult, ReportRow } from "@/types/report";
|
||||
import type { QuotaCell, QuotaResult } from "@/types/quota";
|
||||
import { isTransposed, legacyCellText } from "@/lib/report-ui";
|
||||
|
||||
/**
|
||||
* Excel export input (`AggregateExcelTableDto`). The server writes the legacy MakeExcel layout
|
||||
* from the legacy report body: one object per row with the same keys, header and merged cells as
|
||||
* `"text|rowSpan|colSpan"` (empty span = 1), cells covered by a merge as `""`, and the remaining
|
||||
* cells as their value: N as count text (written "(n)"), percentages and statistics as unrounded
|
||||
* numbers with a dot (numeric cells formatted 0.0, Mean 0.00), labels as text.
|
||||
*/
|
||||
export type ExcelTable = {
|
||||
head: string;
|
||||
vname: string;
|
||||
qtype: string;
|
||||
body: Record<string, string>[];
|
||||
imagePng?: string;
|
||||
};
|
||||
export type ExcelRow = Record<string, string>;
|
||||
|
||||
/** Legacy Report.cs span text: 1 is written as an empty span. */
|
||||
const span = (value: number | undefined) => (value && value > 1 ? String(value) : "");
|
||||
const anchor = (text: string, rowSpan?: number, colSpan?: number) =>
|
||||
text + "|" + span(rowSpan) + "|" + span(colSpan);
|
||||
|
||||
const columnKey = (index: number) => "c" + index;
|
||||
|
||||
/** Places cells on a full grid so every row has the same keys; merged-over cells stay "". */
|
||||
function grid(rows: { cells: { columnIndex: number }[] }[], width: number, text: (row: number, cell: number) => string): ExcelRow[] {
|
||||
return rows.map((row, rowIndex) => {
|
||||
const values: ExcelRow = {};
|
||||
for (let column = 0; column < width; column++) values[columnKey(column)] = "";
|
||||
row.cells.forEach((cell, cellIndex) => {
|
||||
values[columnKey(cell.columnIndex)] = text(rowIndex, cellIndex);
|
||||
});
|
||||
return values;
|
||||
});
|
||||
}
|
||||
|
||||
const tableWidth = (rows: { cells: { columnIndex: number; colSpan?: number }[] }[]) =>
|
||||
Math.max(
|
||||
0,
|
||||
...rows.flatMap((row) => row.cells.map((cell) => cell.columnIndex + (cell.colSpan ?? 1))),
|
||||
);
|
||||
|
||||
/**
|
||||
* Number text that always has a decimal point, so the server writes a numeric cell (formatted
|
||||
* 0.0, Mean 0.00) instead of the "(n)" count text; legacy sent "100.0" for whole percentages.
|
||||
*/
|
||||
export function pointedNumber(value: number): string {
|
||||
let 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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Excel value of one result cell. The base (N) line keeps the count text; percentages and
|
||||
* statistics use the unrounded server values (legacy kept full precision and only formatted the
|
||||
* cell), falling back to the screen text when an older server omits them.
|
||||
*/
|
||||
function excelText(cell: ReportCell, row: ReportRow, result: ReportResult): string {
|
||||
if (cell.kind === "TEXT") return cell.textValue ?? "";
|
||||
const columnKind = result.columns[cell.columnIndex]?.kind;
|
||||
const transposed = isTransposed(result);
|
||||
const shown = legacyCellText(cell, row.kind, columnKind, transposed);
|
||||
if (cell.kind === "EMPTY") return shown;
|
||||
if (cell.kind === "STATISTIC" || cell.kind === "MISSING")
|
||||
return cell.statisticExact == null ? shown : pointedNumber(cell.statisticExact);
|
||||
if ((transposed ? columnKind : row.kind) === "TOTAL") return shown;
|
||||
return cell.percentExact == null ? shown : pointedNumber(cell.percentExact);
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy table body for an ordinary result. Header rows are all anchors (like setHeader); body
|
||||
* cells are anchors only when they merge, otherwise the plain displayed text (labels included).
|
||||
* Null when the result has no rows to export.
|
||||
*/
|
||||
export function reportExcelBody(result: ReportResult): ExcelRow[] | null {
|
||||
if (result.type === "TEXT_ANALYSIS") return wordExcelBody(result);
|
||||
const rows = [...result.headerRows, ...result.rows];
|
||||
const width = tableWidth(rows);
|
||||
if (rows.length < 2 || width < 2) return null;
|
||||
const headerCount = result.headerRows.length;
|
||||
return grid(rows, width, (rowIndex, cellIndex) => {
|
||||
const row = rows[rowIndex];
|
||||
const cell = row.cells[cellIndex];
|
||||
const text = excelText(cell, row, result);
|
||||
return rowIndex < headerCount || (cell.rowSpan ?? 1) > 1 || (cell.colSpan ?? 1) > 1
|
||||
? anchor(text, cell.rowSpan, cell.colSpan)
|
||||
: text;
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy NLP getWordTag: a "Text / Count" row, then the top 100 words. */
|
||||
export function wordExcelBody(result: ReportResult): ExcelRow[] | null {
|
||||
if (!result.words.length) return null;
|
||||
return [
|
||||
{ Text: "Text", Count: "Count" },
|
||||
...result.words.slice(0, 100).map((word) => ({ Text: word.text, Count: String(word.count) })),
|
||||
];
|
||||
}
|
||||
|
||||
/** Legacy quota cell "complete/target/percent"; the server keeps "complete/target". */
|
||||
const quotaText = (cell: QuotaCell) =>
|
||||
(cell.complete ?? 0) + "/" + (cell.target ?? 0) + "/" + (cell.achievementDisplayText ?? "-");
|
||||
|
||||
export function quotaExcelBody(result: QuotaResult): ExcelRow[] | null {
|
||||
const rows = [...result.headerRows, ...result.rows];
|
||||
const width = tableWidth(rows);
|
||||
if (rows.length < 2 || width < 2) return null;
|
||||
const headerCount = result.headerRows.length;
|
||||
return grid(rows, width, (rowIndex, cellIndex) => {
|
||||
if (rowIndex < headerCount) {
|
||||
const cell = result.headerRows[rowIndex].cells[cellIndex];
|
||||
return anchor(cell.textValue ?? "", cell.rowSpan, cell.colSpan);
|
||||
}
|
||||
const cell = result.rows[rowIndex - headerCount].cells[cellIndex];
|
||||
return cell.kind === "QUOTA" ? quotaText(cell) : (cell.textValue ?? "");
|
||||
});
|
||||
}
|
||||
20
src/lib/report-navigation.ts
Normal file
20
src/lib/report-navigation.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { Route } from "next";
|
||||
|
||||
export function isProjectPage(path: string): boolean {
|
||||
return [
|
||||
"/Report/Current",
|
||||
"/Report/Quota",
|
||||
"/Report/Tabulation",
|
||||
"/Report/Crosstab",
|
||||
"/Management/Derived",
|
||||
"/Management/Exim",
|
||||
].includes(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project pages carry no project in the address (legacy KART kept it in client state); the
|
||||
* selected project lives in useSelectedProject. Other paths open the progress page.
|
||||
*/
|
||||
export function projectPagePath(path: string): Route {
|
||||
return (isProjectPage(path) ? path : "/Report/Current") as Route;
|
||||
}
|
||||
80
src/lib/report-stream.ts
Normal file
80
src/lib/report-stream.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { readReportEvent } from "@/lib/report-contract";
|
||||
import type { ReportEvent } from "@/types/report";
|
||||
|
||||
/** Domain NDJSON framing; shared @kri/common owns HTTP, abort and transport timeouts. */
|
||||
export async function consumeReportStream(
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
indexes: string[],
|
||||
onEvent: (event: ReportEvent) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!body) throw new Error("집계 스트림이 비어 있습니다.");
|
||||
const reader = body.getReader();
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
let pending = "",
|
||||
position = 0,
|
||||
succeeded = 0,
|
||||
failed = 0,
|
||||
complete = false,
|
||||
ended = false;
|
||||
const abort = () => {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
};
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
const checkAbort = () => {
|
||||
if (signal?.aborted)
|
||||
throw new DOMException("집계를 중단했습니다.", "AbortError");
|
||||
};
|
||||
const line = (text: string) => {
|
||||
if (!text.trim()) return;
|
||||
if (complete)
|
||||
throw new Error("완료 이벤트 뒤에 추가 집계 결과가 있습니다.");
|
||||
const event = readReportEvent(JSON.parse(text));
|
||||
if (event.type === "complete") {
|
||||
if (
|
||||
position !== indexes.length ||
|
||||
event.total !== indexes.length ||
|
||||
event.succeeded !== succeeded ||
|
||||
event.failed !== failed
|
||||
)
|
||||
throw new Error("집계 완료 건수가 일치하지 않습니다.");
|
||||
complete = true;
|
||||
} else {
|
||||
if (event.position !== position || event.index !== indexes[position])
|
||||
throw new Error("집계 결과의 문항 순서가 일치하지 않습니다.");
|
||||
position++;
|
||||
if (event.type === "result") succeeded++;
|
||||
else failed++;
|
||||
}
|
||||
onEvent(event);
|
||||
};
|
||||
try {
|
||||
for (;;) {
|
||||
checkAbort();
|
||||
const chunk = await reader.read();
|
||||
checkAbort();
|
||||
if (chunk.done) {
|
||||
ended = true;
|
||||
pending += decoder.decode();
|
||||
break;
|
||||
}
|
||||
pending += decoder.decode(chunk.value, { stream: true });
|
||||
let boundary;
|
||||
while ((boundary = pending.indexOf("\n")) >= 0) {
|
||||
line(pending.slice(0, boundary));
|
||||
pending = pending.slice(boundary + 1);
|
||||
}
|
||||
if (pending.length > 64 * 1024 * 1024)
|
||||
throw new Error(
|
||||
"한 문항의 집계 결과가 너무 큽니다. 배너 수를 줄여 주세요.",
|
||||
);
|
||||
}
|
||||
if (pending.trim()) line(pending);
|
||||
if (!complete)
|
||||
throw new Error("집계가 완료되기 전에 연결이 종료되었습니다.");
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
if (!ended) await reader.cancel().catch(() => undefined);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
59
src/lib/report-ui.ts
Normal file
59
src/lib/report-ui.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { isRecord } from "@/types/kart";
|
||||
import type { Question, ReportCell, ReportResult } from "@/types/report";
|
||||
|
||||
/** Legacy VIEWTITLE: "VARIABLE. EXPLAIN" (falls back to QID / TITLE). May contain HTML. */
|
||||
export function questionViewTitle(question: Question): string {
|
||||
return (
|
||||
(question.variable || question.qid) +
|
||||
". " +
|
||||
(question.explain || question.title || "")
|
||||
);
|
||||
}
|
||||
|
||||
/** Legacy result heading (EXPLAIN). May contain HTML. */
|
||||
export function questionHead(question: Question): string {
|
||||
return question.explain || question.title || question.variable || question.qid;
|
||||
}
|
||||
|
||||
export const isDerivedQuestion = (question: Question) =>
|
||||
question.isDerived !== "0";
|
||||
|
||||
/**
|
||||
* Legacy ChildBox checkLoc: text/numeric questions, attribute roots and vtype 2/3 can be
|
||||
* aggregated as a table ("row") but never used as a banner ("all" allows both).
|
||||
*/
|
||||
export function dragLocation(question: Question): "row" | "all" {
|
||||
const vtype = question.vtype ?? "";
|
||||
return question.qtype === "text" ||
|
||||
question.qtype === "num" ||
|
||||
(vtype === "attr" && !question.qid.includes("_")) ||
|
||||
vtype === "2" ||
|
||||
vtype === "3"
|
||||
? "row"
|
||||
: "all";
|
||||
}
|
||||
|
||||
/** True when the server applied 세로 테이블 (transpose) to this result. */
|
||||
export const isTransposed = (result: ReportResult) =>
|
||||
isRecord(result.appliedOptions) && result.appliedOptions.transpose === true;
|
||||
|
||||
/**
|
||||
* Legacy default PRTMODE: ordinary cells show the server percent text, the 사례수 (base) line
|
||||
* shows N. The base line is the TOTAL row, or the TOTAL column when the table is transposed.
|
||||
* Values are the server's display strings; nothing is re-rounded here.
|
||||
*/
|
||||
export function legacyCellText(
|
||||
cell: ReportCell,
|
||||
rowKind: string,
|
||||
columnKind = "",
|
||||
transposed = false,
|
||||
): string {
|
||||
if (cell.kind === "TEXT" || cell.kind === "EMPTY") return cell.textValue ?? "";
|
||||
if (cell.kind === "STATISTIC" || cell.kind === "MISSING")
|
||||
return cell.statisticDisplayText ?? "";
|
||||
if ((transposed ? columnKind : rowKind) === "TOTAL")
|
||||
return cell.countDisplayText ?? (cell.count == null ? "" : String(cell.count));
|
||||
return (
|
||||
cell.percentDisplayText ?? (cell.percent == null ? "" : String(cell.percent))
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user