261026_01_ENH: 사내 연동 API 추가 및 SurveyProgress 전환·문자열 필터 지원
This commit is contained in:
220
src/lib/filter-expression.ts
Normal file
220
src/lib/filter-expression.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import type { ReportFilter } from "@/types/report";
|
||||
|
||||
type Token = { text: string; position: number } & (
|
||||
| { kind: "word" | "symbol" | "end" }
|
||||
| { kind: "value"; value: string | number }
|
||||
);
|
||||
|
||||
const fail = (position: number, message: string): never => {
|
||||
throw new Error(`필터 ${position + 1}번째 문자: ${message}`);
|
||||
};
|
||||
|
||||
/** A bounded expression grammar, never SQL or JavaScript execution. */
|
||||
function tokenize(source: string): Token[] {
|
||||
if (source.length > 8192) fail(0, "조건식은 8192자 이내로 작성해 주세요.");
|
||||
const tokens: Token[] = [];
|
||||
let position = 0;
|
||||
while (position < source.length) {
|
||||
if (/\s/.test(source[position])) {
|
||||
position++;
|
||||
continue;
|
||||
}
|
||||
if (tokens.length >= 2048) fail(position, "조건식이 너무 복잡합니다.");
|
||||
const start = position;
|
||||
const char = source[position];
|
||||
if (char === "'" || char === '"') {
|
||||
position++;
|
||||
let value = "",
|
||||
closed = false;
|
||||
while (position < source.length) {
|
||||
const next = source[position++];
|
||||
if (next !== char) {
|
||||
value += next;
|
||||
continue;
|
||||
}
|
||||
if (source[position] === char) {
|
||||
value += char;
|
||||
position++;
|
||||
} else {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!closed) fail(start, "문자열의 닫는 따옴표가 필요합니다.");
|
||||
tokens.push({
|
||||
kind: "value",
|
||||
text: source.slice(start, position),
|
||||
value,
|
||||
position: start,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const rest = source.slice(position);
|
||||
const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
|
||||
if (number) {
|
||||
const value = Number(number[0]);
|
||||
if (
|
||||
!Number.isFinite(value) ||
|
||||
(Number.isInteger(value) && !Number.isSafeInteger(value))
|
||||
)
|
||||
fail(
|
||||
start,
|
||||
"숫자 범위를 확인해 주세요. 큰 코드값은 따옴표로 감싸 주세요.",
|
||||
);
|
||||
tokens.push({ kind: "value", text: number[0], value, position: start });
|
||||
position += number[0].length;
|
||||
continue;
|
||||
}
|
||||
const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest);
|
||||
const symbol = /^(?:>=|<=|<>|!=|[=><(),])/.exec(rest);
|
||||
const match = word ?? symbol;
|
||||
if (!match)
|
||||
return fail(
|
||||
start,
|
||||
"지원하지 않는 문자입니다. 문항 ID, 비교식, AND·OR·괄호를 사용해 주세요.",
|
||||
);
|
||||
tokens.push({
|
||||
kind: word ? "word" : "symbol",
|
||||
text: match[0],
|
||||
position: start,
|
||||
});
|
||||
position += match[0].length;
|
||||
}
|
||||
tokens.push({ kind: "end", text: "", position });
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Precedence: parentheses, NOT, AND, OR. Identifiers refer to QIDs. */
|
||||
export function parseFilterExpression(source: string): ReportFilter | null {
|
||||
const tokens = tokenize(source);
|
||||
let cursor = 0;
|
||||
const peek = () => tokens[cursor];
|
||||
const take = (text: string) => {
|
||||
const token = peek();
|
||||
if (token.kind !== "value" && token.text.toUpperCase() === text) {
|
||||
cursor++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const expect = (text: string) => {
|
||||
if (!take(text)) fail(peek().position, `${text} 토큰이 필요합니다.`);
|
||||
};
|
||||
const value = (): string | number => {
|
||||
const token = peek();
|
||||
if (token.kind !== "value")
|
||||
return fail(
|
||||
token.position,
|
||||
"비교할 숫자 또는 따옴표로 감싼 문자열이 필요합니다.",
|
||||
);
|
||||
cursor++;
|
||||
return token.value;
|
||||
};
|
||||
const group = (
|
||||
operator: "AND" | "OR",
|
||||
children: ReportFilter[],
|
||||
): ReportFilter =>
|
||||
children.length === 1 ? children[0] : { operator, children };
|
||||
|
||||
function condition(): ReportFilter {
|
||||
const id = peek();
|
||||
if (
|
||||
id.kind !== "word" ||
|
||||
/^(AND|OR|NOT|IN|BETWEEN|IS|NULL)$/i.test(id.text)
|
||||
)
|
||||
return fail(id.position, "비교할 문항 ID가 필요합니다.");
|
||||
cursor++;
|
||||
const base = { dimensionId: id.text, reference: "QID" as const };
|
||||
if (take("IS")) {
|
||||
const not = take("NOT");
|
||||
expect("NULL");
|
||||
return {
|
||||
...base,
|
||||
operator: not ? "IS_ANSWERED" : "IS_UNANSWERED",
|
||||
values: [],
|
||||
};
|
||||
}
|
||||
const not = take("NOT");
|
||||
if (take("IN")) {
|
||||
expect("(");
|
||||
const values = [value()];
|
||||
while (take(",")) {
|
||||
if (values.length >= 128)
|
||||
fail(peek().position, "IN 목록은 128개 이내로 작성해 주세요.");
|
||||
values.push(value());
|
||||
}
|
||||
expect(")");
|
||||
return { ...base, operator: not ? "NOT_IN" : "IN", values };
|
||||
}
|
||||
if (take("BETWEEN")) {
|
||||
const low = value();
|
||||
expect("AND");
|
||||
const result: ReportFilter = {
|
||||
...base,
|
||||
operator: "BETWEEN",
|
||||
values: [low, value()],
|
||||
};
|
||||
return not ? { operator: "NOT", children: [result] } : result;
|
||||
}
|
||||
if (not)
|
||||
return fail(peek().position, "NOT 뒤에는 IN 또는 BETWEEN이 필요합니다.");
|
||||
const token = peek();
|
||||
const operators: Record<string, ReportFilter["operator"]> = {
|
||||
"=": "EQ",
|
||||
"!=": "NE",
|
||||
"<>": "NE",
|
||||
">": "GT",
|
||||
">=": "GE",
|
||||
"<": "LT",
|
||||
"<=": "LE",
|
||||
};
|
||||
const operator =
|
||||
token.kind === "symbol" ? operators[token.text] : undefined;
|
||||
if (!operator)
|
||||
return fail(
|
||||
token.position,
|
||||
"비교 연산자(=, !=, <>, >, >=, <, <=, IN 등)가 필요합니다.",
|
||||
);
|
||||
cursor++;
|
||||
return { ...base, operator, values: [value()] };
|
||||
}
|
||||
|
||||
function primary(depth: number): ReportFilter {
|
||||
if (depth > 32)
|
||||
return fail(peek().position, "괄호와 NOT은 32단계 이내로 작성해 주세요.");
|
||||
if (take("NOT")) return { operator: "NOT", children: [primary(depth + 1)] };
|
||||
if (!take("(")) return condition();
|
||||
const result = expression(depth + 1);
|
||||
expect(")");
|
||||
return result;
|
||||
}
|
||||
function and(depth: number): ReportFilter {
|
||||
const children = [primary(depth)];
|
||||
while (take("AND")) {
|
||||
if (children.length >= 128)
|
||||
fail(
|
||||
peek().position,
|
||||
"AND 조건은 한 그룹에 128개 이내로 작성해 주세요.",
|
||||
);
|
||||
children.push(primary(depth));
|
||||
}
|
||||
return group("AND", children);
|
||||
}
|
||||
function expression(depth: number): ReportFilter {
|
||||
const children = [and(depth)];
|
||||
while (take("OR")) {
|
||||
if (children.length >= 128)
|
||||
fail(
|
||||
peek().position,
|
||||
"OR 조건은 한 그룹에 128개 이내로 작성해 주세요.",
|
||||
);
|
||||
children.push(and(depth));
|
||||
}
|
||||
return group("OR", children);
|
||||
}
|
||||
if (peek().kind === "end") return null;
|
||||
const result = expression(0);
|
||||
if (peek().kind !== "end")
|
||||
fail(peek().position, "조건 사이의 AND·OR 또는 괄호를 확인해 주세요.");
|
||||
return result;
|
||||
}
|
||||
@@ -14,3 +14,13 @@ export async function createServerApi(authenticated = true) {
|
||||
onResponseError: false,
|
||||
});
|
||||
}
|
||||
|
||||
/** Internal integrations authenticate with their supplied key, never the browser session. */
|
||||
export function createServerApiWithApiKey(apiKey: string) {
|
||||
return createHttpClient(serverEnv.API_SERVER, {
|
||||
defaultHeaders: { "content-type": "application/json", "X-API-Key": apiKey },
|
||||
onUnauthorized: false,
|
||||
onForbidden: false,
|
||||
onResponseError: false,
|
||||
});
|
||||
}
|
||||
|
||||
59
src/lib/kric-internal-policy.ts
Normal file
59
src/lib/kric-internal-policy.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
exportTarget,
|
||||
isQuotaListPath,
|
||||
isQuotaResultPath,
|
||||
isReportStreamPath,
|
||||
} from "@/lib/project-proxy-policy";
|
||||
import { isRecord, validDateRange } from "@/types/kart";
|
||||
import { readReportBatch } from "@/lib/report-contract";
|
||||
import { parseFilterExpression } from "@/lib/filter-expression";
|
||||
|
||||
type Target = { path: string; kind: "list" | "quota" | "report" | "excel" };
|
||||
|
||||
/** Adapt integration input to the existing report contract without coupling the parser to HTTP. */
|
||||
export function readInternalReportBatch(value: unknown) {
|
||||
return readReportBatch(
|
||||
isRecord(value) && typeof value.filter === "string"
|
||||
? { ...value, filter: parseFilterExpression(value.filter) }
|
||||
: value,
|
||||
);
|
||||
}
|
||||
|
||||
/** Only the five approved integration operations; no arbitrary upstream forwarding. */
|
||||
export function internalTarget(method: string, slug: string[]): Target | null {
|
||||
const [area, ...parts] = slug;
|
||||
const path = "/" + slug.map(encodeURIComponent).join("/");
|
||||
if (method === "GET" && area === "quota" && isQuotaListPath(parts))
|
||||
return { path, kind: "list" };
|
||||
if (method !== "POST") return null;
|
||||
if (area === "project" && isReportStreamPath(parts))
|
||||
return { path, kind: "report" };
|
||||
if (area === "quota" && isQuotaResultPath(parts))
|
||||
return { path, kind: "quota" };
|
||||
if (
|
||||
area === "export" &&
|
||||
parts.length === 3 &&
|
||||
["table", "quota"].includes(parts[2])
|
||||
) {
|
||||
const target = exportTarget("POST", parts);
|
||||
if (target) return { path: target.path, kind: "excel" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Broader backend quota contract, without changing the ordinary screen's request policy. */
|
||||
export function readInternalQuotaRequest(value: unknown) {
|
||||
if (!isRecord(value)) throw new Error("쿼터 조회 조건을 확인해 주세요.");
|
||||
const dataScope = value.dataScope ?? "ACTUAL";
|
||||
const startDate = value.startDate ?? "";
|
||||
const endDate = value.endDate ?? "";
|
||||
if (
|
||||
!["ACTUAL", "TEST", "ALL"].includes(String(dataScope)) ||
|
||||
typeof dataScope !== "string" ||
|
||||
typeof startDate !== "string" ||
|
||||
typeof endDate !== "string" ||
|
||||
!validDateRange({ startDate, endDate })
|
||||
)
|
||||
throw new Error("쿼터 데이터 범위와 조회 날짜를 확인해 주세요.");
|
||||
return { dataScope, ...(startDate ? { startDate, endDate } : {}) };
|
||||
}
|
||||
Reference in New Issue
Block a user