261021_01_ENH: 1차 마이그레이션 완료

This commit is contained in:
2026-10-21 16:08:57 +09:00
parent 964269cd82
commit f0c9b02eae
313 changed files with 11557 additions and 344 deletions

75
src/types/bookmark.ts Normal file
View File

@@ -0,0 +1,75 @@
import { isRecord } from "@/types/kart";
/** REPORT_BOOKMARK.BOOKMARK_PAGE values the server accepts. */
export type BookmarkPage = "TABULATION" | "CROSSTAB";
export const isBookmarkPage = (value: unknown): value is BookmarkPage =>
value === "TABULATION" || value === "CROSSTAB";
/** One tab of the legacy bookmark slider (server `bookmark/list` row). */
export type Bookmark = {
bookmarkId: string;
bookmarkTitle: string;
bookmarkInfo: string;
/** Legacy setting JSON stored verbatim and shared with the legacy system. */
bookmarkJson: string;
/** 1 = everyone in the project, 0 = "Just for me". */
isOpen: number | null;
isMine: boolean;
};
/** Body of `POST .../bookmark` (page required) and `PUT .../bookmark/{id}` (page ignored). */
export type BookmarkSaveRequest = {
bookmarkPage?: BookmarkPage;
bookmarkTitle: string;
bookmarkInfo: string;
bookmarkJson: string;
isOpen: 0 | 1;
};
const optionalText = (value: unknown): value is string | null | undefined =>
value === null || value === undefined || typeof value === "string";
export function readBookmarks(value: unknown): Bookmark[] {
if (!Array.isArray(value)) throw new Error("서버 응답 형식을 확인해 주세요.");
return value.map((row) => {
if (
!isRecord(row) ||
typeof row.bookmarkId !== "string" ||
row.bookmarkId === "" ||
!optionalText(row.bookmarkTitle) ||
!optionalText(row.bookmarkInfo) ||
!optionalText(row.bookmarkJson) ||
!optionalText(row.isMine) ||
!(row.isOpen === null || row.isOpen === undefined || Number.isSafeInteger(row.isOpen))
)
throw new Error("서버 응답 형식을 확인해 주세요.");
return {
bookmarkId: row.bookmarkId,
bookmarkTitle: row.bookmarkTitle ?? "",
bookmarkInfo: row.bookmarkInfo ?? "",
bookmarkJson: row.bookmarkJson ?? "",
isOpen: typeof row.isOpen === "number" ? row.isOpen : null,
isMine: row.isMine === "1",
};
});
}
/** Keeps only the server fields; creation also requires the page. */
export function readBookmarkSaveRequest(value: unknown, create: boolean): BookmarkSaveRequest {
if (
!isRecord(value) ||
typeof value.bookmarkTitle !== "string" ||
typeof value.bookmarkInfo !== "string" ||
typeof value.bookmarkJson !== "string" ||
(value.isOpen !== 0 && value.isOpen !== 1) ||
(create && !isBookmarkPage(value.bookmarkPage))
)
throw new Error("북마크 저장 내용을 확인해 주세요.");
return {
...(create && isBookmarkPage(value.bookmarkPage) ? { bookmarkPage: value.bookmarkPage } : {}),
bookmarkTitle: value.bookmarkTitle,
bookmarkInfo: value.bookmarkInfo,
bookmarkJson: value.bookmarkJson,
isOpen: value.isOpen,
};
}

View File

@@ -1,12 +1,3 @@
export type RouteContext = {
params: Promise<{ slug?: string[] }>;
};
export interface ExampleItem {
id: string;
name: string;
}
export interface ExampleRequest {
name: string;
}

215
src/types/derived.ts Normal file
View File

@@ -0,0 +1,215 @@
import { isRecord } from "@/types/kart";
export type DerivedType = "single" | "multi" | "scale" | "num";
export const DERIVED_TYPES: { value: DerivedType; label: string }[] = [
{ value: "single", label: "Single" },
{ value: "multi", label: "Multi" },
{ value: "scale", label: "Scale" },
{ value: "num", label: "Numeric" },
];
const isDerivedType = (value: unknown): value is DerivedType =>
value === "single" || value === "multi" || value === "scale" || value === "num";
/** Server `derived/list` row reduced to what Create Variable needs. */
export type DerivedVariable = {
/** Stored DERIVED_VARIABLE.QID used for update/delete. */
id: string;
title: string;
type: DerivedType;
/** Legacy DERIVEDJSON: `{"1":{…},"2":{…},"ELSE":{…}}`. */
derivedJson: string;
};
/**
* Stored id for update/delete: the server's `variableId` (DERIVED_VARIABLE.QID). Older servers
* omit it and expand numeric (open) variables to `QID_1`, so fall back to dropping that suffix.
*/
export function storedDerivedId(
qid: string,
type: DerivedType,
variableId?: string | null,
): string {
if (variableId) return variableId;
return type === "num" && qid.endsWith("_1") ? qid.slice(0, -2) : qid;
}
const optionalText = (value: unknown): value is string | null | undefined =>
value === null || value === undefined || typeof value === "string";
export function readDerivedVariables(value: unknown): DerivedVariable[] {
if (!Array.isArray(value)) throw new Error("서버 응답 형식을 확인해 주세요.");
return value.map((row) => {
if (
!isRecord(row) ||
typeof row.qid !== "string" ||
row.qid === "" ||
!optionalText(row.variableId) ||
!optionalText(row.title) ||
!optionalText(row.derivedJson) ||
!isDerivedType(row.qtype)
)
throw new Error("서버 응답 형식을 확인해 주세요.");
return {
id: storedDerivedId(row.qid, row.qtype, row.variableId),
title: row.title ?? "",
type: row.qtype,
derivedJson: row.derivedJson ?? "",
};
});
}
/** One legacy value rule (states/Format.js valueJsonFormat) plus any other stored keys. */
export type DerivedValue = {
id: string;
label: string;
value: string;
realCondition: string;
condition: string;
format: string;
/** FILTER_ARRAY text of the rule's condition. */
array: string;
rest: Record<string, unknown>;
};
export type DerivedElse = { isMissing: boolean; value: string; label: string };
const RULE_KEYS = ["label", "value", "realCondition", "condition", "format", "array"] as const;
export const newDerivedValue = (id: string): DerivedValue => ({
id,
label: "",
value: "",
realCondition: "",
condition: "",
format: "",
array: "",
rest: {},
});
/** Legacy selectVariable: numbered rules become rows, ELSE fills the Else box (else Missing). */
export function readDerivedJson(json: string): { values: DerivedValue[]; otherwise: DerivedElse } {
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
throw new Error("파생변수 설정을 읽을 수 없습니다.");
}
if (!isRecord(parsed)) throw new Error("파생변수 설정을 읽을 수 없습니다.");
const text = (value: unknown) =>
typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
const values: DerivedValue[] = [];
let otherwise: DerivedElse = { isMissing: true, value: "", label: "" };
for (const [key, rule] of Object.entries(parsed)) {
if (!isRecord(rule)) throw new Error("파생변수 설정을 읽을 수 없습니다.");
if (key === "ELSE") {
otherwise = { isMissing: false, value: text(rule.value), label: text(rule.label) };
continue;
}
const rest = Object.fromEntries(
Object.entries(rule).filter(([name]) => !(RULE_KEYS as readonly string[]).includes(name)),
);
values.push({
id: "derived_value_" + values.length,
label: text(rule.label),
value: text(rule.value),
realCondition: text(rule.realCondition),
condition: text(rule.condition),
format: text(rule.format),
array: text(rule.array),
rest,
});
}
return { values, otherwise };
}
/** Legacy saveVariable body: rules keyed "1".."n" in row order, then ELSE unless Missing. */
export function writeVariableInfo(
values: DerivedValue[],
otherwise: DerivedElse,
): Record<string, Record<string, unknown>> {
const info: Record<string, Record<string, unknown>> = {};
values.forEach((row, index) => {
info[String(index + 1)] = {
label: row.label.trim(),
value: row.value.trim(),
realCondition: row.realCondition.trim(),
condition: row.condition.trim(),
format: row.format,
array: row.array,
...row.rest,
};
});
if (!otherwise.isMissing)
info.ELSE = {
label: otherwise.label.trim(),
value: otherwise.value.trim(),
realCondition: "ELSE",
condition: "ELSE",
array: "ELSE",
};
return info;
}
/** Legacy saveVariable checks and messages, in the same order. Null when the form can be saved. */
export function derivedFormError(form: {
variableId: string;
title: string;
type: DerivedType;
info: Record<string, Record<string, unknown>>;
}): string | null {
if (form.variableId.trim() === "") return "ID는 필수 입니다.";
if (form.title.trim() === "") return "Title은 필수 입니다.";
const rules = Object.values(form.info);
if (rules.length === 0) return "1개 이상의 값을 지정해 주세요";
const values: unknown[] = [];
const labels: unknown[] = [];
for (const rule of rules) {
if (rule.condition === "") return "Condition은 필수 입니다.";
if (rule.value === "") return "Value는 필수 입니다.";
// Numeric variables have no label input, so only labelled types require one.
if (form.type !== "num" && rule.label === "") return "Label은 필수 입니다.";
if (values.includes(rule.value)) return "Value에 중복이 있습니다.";
if (form.type !== "num" && labels.includes(rule.label)) return "Label에 중복이 있습니다.";
values.push(rule.value);
labels.push(rule.label);
}
return null;
}
/** Body of `POST .../derived` and `PUT .../derived/{variableId}`. */
export type DerivedSaveRequest = {
variableId: string;
variableTitle: string;
variableType: DerivedType;
variableInfo: Record<string, Record<string, unknown>>;
};
export const DERIVED_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,127}$/;
/** Mirrors the server DTO constraints so the BFF forwards only well-formed requests. */
export function readDerivedSaveRequest(value: unknown): DerivedSaveRequest {
const invalid = () => new Error("파생변수 저장 내용을 확인해 주세요.");
if (
!isRecord(value) ||
typeof value.variableId !== "string" ||
!DERIVED_ID_PATTERN.test(value.variableId) ||
typeof value.variableTitle !== "string" ||
value.variableTitle.trim() === "" ||
value.variableTitle.length > 4000 ||
!isDerivedType(value.variableType) ||
!isRecord(value.variableInfo)
)
throw invalid();
const entries = Object.entries(value.variableInfo);
if (entries.length === 0 || entries.length > 1000) throw invalid();
const variableInfo: Record<string, Record<string, unknown>> = {};
for (const [key, rule] of entries) {
if (!(key === "ELSE" || /^\d+$/.test(key)) || !isRecord(rule)) throw invalid();
variableInfo[key] = rule;
}
return {
variableId: value.variableId,
variableTitle: value.variableTitle,
variableType: value.variableType,
variableInfo,
};
}

85
src/types/export.ts Normal file
View File

@@ -0,0 +1,85 @@
import { isRecord } from "@/types/kart";
import type { ExcelTable } from "@/lib/report-excel";
/** Body of `POST .../export/excel/table` and `POST /quota/.../export/excel`. */
export type ExcelRequest = { tables: ExcelTable[]; turn: boolean };
/** Body of `POST .../export/data`: completed (Status=10) or not completed responses. */
export type RawDataRequest = { type: "COMPLETE" | "INCOMPLETE" };
/** Server import summary (`ImportResultDto`). */
export type ImportResult = {
processedRows: number;
affectedRows: number;
removedRows: number;
archivedRows: number;
};
const invalid = () => new Error("Excel 출력 내용을 확인해 주세요.");
const optionalText = (value: unknown): value is string | undefined =>
value === undefined || typeof value === "string";
function readExcelTable(value: unknown): ExcelTable {
if (
!isRecord(value) ||
typeof value.head !== "string" ||
!optionalText(value.vname) ||
!optionalText(value.qtype) ||
!optionalText(value.imagePng) ||
!Array.isArray(value.body) ||
value.body.length < 2
)
throw invalid();
const body = value.body.map((row) => {
if (!isRecord(row)) throw invalid();
const cells: Record<string, string> = {};
for (const [key, cell] of Object.entries(row)) {
if (typeof cell !== "string") throw invalid();
cells[key] = cell;
}
return cells;
});
return {
head: value.head,
vname: value.vname ?? "",
qtype: value.qtype ?? "",
body,
...(value.imagePng ? { imagePng: value.imagePng } : {}),
};
}
/** Keeps only the server fields; the server re-checks sizes, keys and merges. */
export function readExcelRequest(value: unknown): ExcelRequest {
if (
!isRecord(value) ||
!Array.isArray(value.tables) ||
value.tables.length === 0 ||
value.tables.length > 1000 ||
typeof value.turn !== "boolean"
)
throw invalid();
return { tables: value.tables.map(readExcelTable), turn: value.turn };
}
export function readRawDataRequest(value: unknown): RawDataRequest {
if (!isRecord(value) || (value.type !== "COMPLETE" && value.type !== "INCOMPLETE"))
throw new Error("다운로드 조건을 확인해 주세요.");
return { type: value.type };
}
const count = (value: unknown): value is number =>
typeof value === "number" && Number.isSafeInteger(value);
export function readImportResult(value: unknown): ImportResult {
if (
!isRecord(value) ||
!count(value.processedRows) ||
!count(value.affectedRows) ||
!count(value.removedRows) ||
!count(value.archivedRows)
)
throw new Error("서버 응답 형식을 확인해 주세요.");
return {
processedRows: value.processedRows,
affectedRows: value.affectedRows,
removedRows: value.removedRows,
archivedRows: value.archivedRows,
};
}

179
src/types/kart.ts Normal file
View File

@@ -0,0 +1,179 @@
import type { LoginUser } from "@kri/common";
export type ProjectType = 0 | 1;
export type ProjectRef = { projectType: ProjectType; pkey: string };
export type Project = ProjectRef & {
rowNumber: string | null;
title: string | null;
surveyType: string | null;
status: string | null;
gkey: string | null;
mkey: string | null;
createDate: string | null;
};
export type ProjectSummary = ProjectRef & {
title: string | null;
surveyType: string | null;
status: string | null;
createDate: string | null;
allCount: number | null;
ongoingCount: number | null;
screenCount: number | null;
quotaCount: number | null;
completeCount: number | null;
};
export type ProgressDay = {
surveyDate: string | null;
totalCount: number | null;
completeCount: number | null;
screenCount: number | null;
quotaCount: number | null;
};
export type ProgressType = {
totalCount: number | null;
completeCount: number | null;
screenCount: number | null;
quotaCount: number | null;
goingCount: number | null;
};
export type Loi = {
cnt: number | null;
avgLoi: string | null;
avgLoiModify: string | null;
minLoi: string | null;
maxLoi: string | null;
};
export type ProgressScreen = {
qOrder: number | null;
viewTitle: string | null;
pageName: string | null;
cnt: number | null;
};
export type DateRange = { startDate: string; endDate: string };
export const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const text = (value: unknown): value is string | null =>
value === null || typeof value === "string";
const count = (value: unknown): value is number | null =>
value === null || (typeof value === "number" && Number.isSafeInteger(value));
export const isLoginUser = (value: unknown): value is LoginUser =>
isRecord(value) &&
typeof value.userId === "string" &&
value.userId.length > 0 &&
typeof value.userName === "string" &&
typeof value.userCmpn === "string" &&
typeof value.userTeam === "string" &&
typeof value.userRole === "number" &&
Number.isSafeInteger(value.userRole);
export const isProjectType = (value: unknown): value is ProjectType =>
value === 0 || value === 1;
export const isProjectRef = (
value: unknown,
): value is ProjectRef & Record<string, unknown> =>
isRecord(value) &&
isProjectType(value.projectType) &&
typeof value.pkey === "string" &&
value.pkey.length > 0 &&
value.pkey.length <= 20 &&
!/[|/\\]/.test(value.pkey) &&
value.pkey !== "." &&
value.pkey !== "..";
export const isProject = (value: unknown): value is Project =>
isRecord(value) &&
isProjectRef(value) &&
text(value.rowNumber) &&
text(value.title) &&
text(value.surveyType) &&
text(value.status) &&
text(value.gkey) &&
text(value.mkey) &&
text(value.createDate);
export const isProjectSummary = (value: unknown): value is ProjectSummary =>
isRecord(value) &&
isProjectRef(value) &&
text(value.title) &&
text(value.surveyType) &&
text(value.status) &&
text(value.createDate) &&
[
"allCount",
"ongoingCount",
"screenCount",
"quotaCount",
"completeCount",
].every((key) => count(value[key]));
export const isProgressDay = (value: unknown): value is ProgressDay =>
isRecord(value) &&
text(value.surveyDate) &&
["totalCount", "completeCount", "screenCount", "quotaCount"].every((key) =>
count(value[key]),
);
export const isProgressType = (value: unknown): value is ProgressType =>
isRecord(value) &&
[
"totalCount",
"completeCount",
"screenCount",
"quotaCount",
"goingCount",
].every((key) => count(value[key]));
export const isLoi = (value: unknown): value is Loi =>
isRecord(value) &&
count(value.cnt) &&
["avgLoi", "avgLoiModify", "minLoi", "maxLoi"].every((key) =>
text(value[key]),
);
export const isProgressScreen = (value: unknown): value is ProgressScreen =>
isRecord(value) &&
count(value.qOrder) &&
count(value.cnt) &&
text(value.viewTitle) &&
text(value.pageName);
export function readRows<T>(
value: unknown,
guard: (row: unknown) => row is T,
): T[] {
if (!Array.isArray(value) || !value.every(guard))
throw new Error("서버 응답 형식을 확인해 주세요.");
return value;
}
export function projectKey(project: ProjectRef): string {
return project.projectType + ":" + project.pkey;
}
export function readProjectParams(
params: Pick<URLSearchParams, "get">,
): ProjectRef | null {
const type = params.get("projectType");
const project = {
projectType: type === "0" ? 0 : type === "1" ? 1 : null,
pkey: params.get("pkey"),
};
return isProjectRef(project) ? project : null;
}
export function validDateRange(range: DateRange): boolean {
const validDate = (date: string) =>
/^\d{4}-\d{2}-\d{2}$/.test(date) &&
Number.isFinite(Date.parse(date + "T00:00:00Z")) &&
new Date(date + "T00:00:00Z").toISOString().slice(0, 10) === date;
return (
(!range.startDate && !range.endDate) ||
(validDate(range.startDate) &&
validDate(range.endDate) &&
range.startDate <= range.endDate)
);
}
export const projectTypeLabel = (type: ProjectType) =>
type === 0 ? "KON" : "KIWI";
export const statusLabel = (status: string | null) =>
({ "1": "준비", "2": "진행", "3": "완료" })[status ?? ""] ?? status ?? "-";
export const surveyTypeLabel = (type: string | null) =>
({ "1": "온라인", "2": "CAPI", "3": "GANG" })[type ?? ""] ?? type ?? "-";
export const displayCount = (value: number | null | undefined) =>
value == null ? "-" : value.toLocaleString("ko-KR");
export function displayDate(value: string | null): string {
const date = value?.trim() ?? "";
return /^\d{8}$/.test(date)
? date.slice(0, 4) + "-" + date.slice(4, 6) + "-" + date.slice(6, 8)
: date.slice(0, 10) || "-";
}

113
src/types/quota.ts Normal file
View File

@@ -0,0 +1,113 @@
import { isRecord } from "@/types/kart";
import { isRow } from "@/lib/report-contract";
import type { ReportRow } from "@/types/report";
/** Saved quota setting (TB quota set): QSJSON holds ROW / COL / FILTER. */
export type QuotaSet = {
id: number | null;
qsOrder: number;
qsTitle: string | null;
qsJson: string | null;
};
export type QuotaAchievement = "FINITE" | "UNDEFINED" | "POSITIVE_INFINITY";
export type QuotaCell = {
columnIndex: number;
kind: string;
textValue?: string | null;
complete?: number | null;
target?: number | null;
achievementPercent?: number | null;
achievementState?: QuotaAchievement | null;
achievementDisplayText?: string | null;
};
export type QuotaRow = { rowIndex: number; rowId: string; kind: string; cells: QuotaCell[] };
export type QuotaResult = {
title: string | null;
headerRows: ReportRow[];
rows: QuotaRow[];
};
export type QuotaRequest = { dataScope: "ACTUAL" | "TEST" };
const integer = (v: unknown): v is number =>
typeof v === "number" && Number.isSafeInteger(v);
const optional = <T>(v: unknown, guard: (value: unknown) => value is T) =>
v == null || guard(v);
const text = (v: unknown): v is string => typeof v === "string";
const finite = (v: unknown): v is number =>
typeof v === "number" && Number.isFinite(v);
const states = new Set(["FINITE", "UNDEFINED", "POSITIVE_INFINITY"]);
export const isQuotaSet = (v: unknown): v is QuotaSet =>
isRecord(v) &&
integer(v.qsOrder) &&
optional(v.id, integer) &&
optional(v.qsTitle, text) &&
optional(v.qsJson, text);
function isQuotaCell(v: unknown): v is QuotaCell {
return (
isRecord(v) &&
integer(v.columnIndex) &&
v.columnIndex >= 0 &&
text(v.kind) &&
optional(v.textValue, text) &&
optional(v.complete, integer) &&
optional(v.target, integer) &&
optional(v.achievementPercent, finite) &&
(v.achievementState == null ||
(text(v.achievementState) && states.has(v.achievementState))) &&
optional(v.achievementDisplayText, text)
);
}
const isQuotaRow = (v: unknown): v is QuotaRow =>
isRecord(v) &&
integer(v.rowIndex) &&
text(v.rowId) &&
text(v.kind) &&
Array.isArray(v.cells) &&
v.cells.every(isQuotaCell);
export function readQuotaResult(v: unknown): QuotaResult {
if (
!isRecord(v) ||
!optional(v.title, text) ||
!Array.isArray(v.headerRows) ||
!v.headerRows.every(isRow) ||
!Array.isArray(v.rows) ||
!v.rows.every(isQuotaRow)
)
throw new Error("쿼터 결과 형식을 확인해 주세요.");
return {
title: v.title ?? null,
headerRows: v.headerRows,
rows: v.rows,
};
}
/** Only the data scope is forwarded; the server reads ROW/COL/FILTER from the saved setting. */
export function readQuotaRequest(v: unknown): QuotaRequest {
if (!isRecord(v) || (v.dataScope !== "ACTUAL" && v.dataScope !== "TEST"))
throw new Error("쿼터 조회 조건을 확인해 주세요.");
return { dataScope: v.dataScope };
}
/** Legacy QSTOOLTIP: "Column Variable : [ a, b ] / Row Variable : [ q ]". */
export function quotaTooltip(set: QuotaSet): string {
try {
const json: unknown = JSON.parse(set.qsJson ?? "");
if (!isRecord(json)) return "";
const col = Array.isArray(json.COL) ? json.COL.join(", ") : "";
const row = Array.isArray(json.ROW) && json.ROW.length ? String(json.ROW[0]) : "";
return (
// Legacy always pads the column list, even when empty.
"Column Variable : [ " +
col +
" " +
"] / Row Variable : [" +
(row ? " " + row + " " : "") +
"]"
);
} catch {
return "";
}
}

109
src/types/report.ts Normal file
View File

@@ -0,0 +1,109 @@
export type Question = {
qid: string;
qOrder: number | null;
variable: string | null;
title: string | null;
explain: string | null;
qtype: string | null;
vtype: string | null;
labelInfo: string | null;
attrInfo: string | null;
isDerived: string | null;
};
export type FilterOperator =
| "EQ"
| "NE"
| "GT"
| "GE"
| "LT"
| "LE"
| "IN"
| "NOT_IN"
| "BETWEEN"
| "IS_ANSWERED"
| "IS_UNANSWERED";
export type ReportFilter = {
operator: FilterOperator | "AND" | "OR" | "NOT";
dimensionId?: string;
reference?: "QID" | "VARIABLE";
values?: (string | number)[];
children?: ReportFilter[];
};
export type ReportOptions = {
banners: string[][];
filter: ReportFilter | null;
mode: "STANDARD" | "TABULATION_0" | "TABULATION_1";
dataScope: "ACTUAL" | "TEST" | "ALL";
startDate?: string;
endDate?: string;
percentageDecimals: number;
statisticDecimals: number;
headerMode: "NONE" | "FLAT" | "MERGED";
transpose: boolean;
showSubtotals: boolean;
showValueCodes: boolean;
showNumericSum: boolean;
valueGroups: { label: string; values: string[] }[];
};
export type ReportBatch = ReportOptions & { indexes: string[] };
export type ReportCell = {
columnIndex: number;
rowSpan: number;
colSpan: number;
kind: string;
textValue?: string | null;
count?: number | null;
percent?: number | null;
base?: number | null;
statisticValue?: number | null;
/** Unrounded (legacy RoundValue 14) values for Excel cells; display fields stay rounded. */
percentExact?: number | null;
statisticExact?: number | null;
measurement?: string | null;
countDisplayText?: string | null;
percentDisplayText?: string | null;
statisticDisplayText?: string | null;
};
export type ReportRow = {
rowIndex: number;
rowId: string;
kind: string;
cells: ReportCell[];
};
export type ReportResult = {
type: "TABLE" | "TEXT_ANALYSIS";
questionId: string;
title: string | null;
columns: { columnId: string; kind: string; labels: string[] }[];
headerRows: ReportRow[];
rows: ReportRow[];
words: { text: string; tag: string; count: number }[];
appliedOptions?: unknown;
};
export type ReportEvent =
| { type: "result"; position: number; index: string; result: ReportResult }
| {
type: "error";
position: number;
index: string;
status: number;
code: string;
message: string;
}
| { type: "complete"; total: number; succeeded: number; failed: number };
export type DisplayMode = "N" | "PERCENT" | "BOTH";
export type FilterDraft =
| {
id: string;
kind: "group";
operator: "AND" | "OR" | "NOT";
children: FilterDraft[];
}
| {
id: string;
kind: "condition";
operator: FilterOperator;
dimensionId: string;
numeric: boolean;
values: string[];
};

59
src/types/share.ts Normal file
View File

@@ -0,0 +1,59 @@
import type { LoginUser } from "@kri/common";
import { isLoginUser, isProjectRef, isRecord, type ProjectRef } from "./kart";
export const REPORT_MEMBER_ROLE = 9001;
export const EXTERNAL_URL_COPY_ROLE = 9002;
export const EXTERNAL_PAGE_COPY_ROLE = 9003;
export const REPORT_PATHS = [
"/Report/Current", "/Report/Quota", "/Report/Tabulation", "/Report/Crosstab",
] as const;
export type ShareLink = ProjectRef & {
urlKey: string;
url: string;
realUrl: string;
projectTitle: string;
pageOnly: boolean;
};
export type ExternalSession = { user: LoginUser; link: ShareLink };
export function isExternalUser(user: LoginUser | null | undefined): boolean {
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
user.userRole === EXTERNAL_PAGE_COPY_ROLE || user.userTeam === "KART_EXTERNAL" ||
user.userId.startsWith("EXTERNAL:"));
}
export const isUrlKey = (value: unknown): value is string =>
typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
/** Keep only local report navigation; query parameters never select an external project. */
export function reportUrl(value: unknown): string | null {
if (typeof value !== "string" || value.length > 4096 ||
!value.startsWith("/") || value.startsWith("//") || /[\x00-\x20\x7f\\]/.test(value)) return null;
const path = value.split(/[?#]/, 1)[0];
if (!REPORT_PATHS.some((allowed) => allowed === path)) return null;
const url = new URL(value, "https://kart.invalid");
url.searchParams.delete("projectType");
url.searchParams.delete("pkey");
return url.pathname + url.search + url.hash;
}
export function isShareLink(value: unknown): value is ShareLink {
if (!isRecord(value) || !isProjectRef(value) || !isUrlKey(value.urlKey) ||
typeof value.url !== "string" || typeof value.projectTitle !== "string" ||
typeof value.pageOnly !== "boolean" || reportUrl(value.realUrl) === null) return false;
try {
const url = new URL(value.url);
return ["https:", "http:"].includes(url.protocol) && !url.username && !url.password &&
!url.search && !url.hash && url.pathname === "/External/" + value.urlKey;
} catch { return false; }
}
export function isExternalSession(value: unknown): value is ExternalSession {
return isRecord(value) && isLoginUser(value.user) && isShareLink(value.link) &&
value.user.userId === "EXTERNAL:" + value.link.urlKey &&
value.user.userTeam === "KART_EXTERNAL" && value.user.userName === "CLIENT" &&
value.user.userCmpn === "" && value.user.userRole ===
(value.link.pageOnly ? EXTERNAL_PAGE_COPY_ROLE : EXTERNAL_URL_COPY_ROLE);
}
export function externalPageAllowed(link: ShareLink, pathname: string): boolean {
return link.pageOnly
? pathname === link.realUrl.split(/[?#]/, 1)[0]
: REPORT_PATHS.some((path) => path === pathname);
}