/* ============================================================================= * M01_MasterData_UI_Logic_Note.ts * 원문 표 읽기(`loadTable`) · 식 쉬운 말 풀이(`explain`). * * 순수 읽기 — `/elements` 로 표 파일을 찾고 `/table` 로 통째 읽음. * ========================================================================== */ import { API_BASE_URL } from "@config/config_frontend"; import { logicApiPaths, type ElementBrief } from "./M01_MasterData_UI_Logic_Api"; /* ── 원문 표(소요량·계수) 읽기 ─────────────────────────────────────────── */ export interface TableRow { file: string; 키: string; 이름?: string; 원문번호?: string; 출처?: string; 용도?: { 공종?: string; 대상?: string[]; 로직키?: string[] }; 조건?: Record; 값칸?: Record; 줄?: Record[]; } const tableCache = new Map>(); async function getJson(path: string): Promise { try { const res = await fetch(`${API_BASE_URL}${logicApiPaths().read}${path}`); if (!res.ok) return null; return (await res.json()) as T; } catch { return null; } } export function loadTable(key: string): Promise { const cached = tableCache.get(key); if (cached) return cached; const job = (async (): Promise => { for (const group of ["소요량", "계수"]) { const found = await getJson<{ items: ElementBrief[] }>( `/elements?group=${encodeURIComponent(group)}&q=${encodeURIComponent(key)}&limit=5`, ); const file = found?.items?.find((i) => i.ref === key)?.file; if (!file) continue; const got = await getJson<{ table: TableRow }>( `/table?file=${encodeURIComponent(file)}&key=${encodeURIComponent(key)}`, ); if (got?.table) return { ...got.table, file }; } return null; })(); tableCache.set(key, job); return job; } /* ── 식 속 찾기(표, 조건...).칸 ──────────────────────────────────────── */ const FIND_RE = /찾기\(\s*([A-Za-z0-9_]+)\s*,([^)]*)\)\s*\.\s*([A-Za-z0-9_가-힣]+)/g; function splitConds(raw: string): [string, string][] { return raw .split(",") .map((p) => p.trim()) .filter(Boolean) .map((p): [string, string] => { const i = p.indexOf("="); return i < 0 ? [p, p] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; }); } /* ── 쉬운 말 풀이 — 찾기()/만약() 을 문장으로, 안 되면 식 그대로 ─────────── */ function splitTop(s: string): string[] { const out: string[] = []; let depth = 0; let cur = ""; for (const ch of s) { if (ch === "(") depth++; if (ch === ")") depth--; if (ch === "," && depth === 0) { out.push(cur); cur = ""; } else cur += ch; } out.push(cur); return out; } function expandIf(expr: string): string { const at = expr.indexOf("만약("); if (at < 0) return expr; let depth = 0; let j = at + 2; // "만약(" 의 '(' 자리 for (; j < expr.length; j++) { if (expr[j] === "(") depth++; else if (expr[j] === ")") { depth--; if (depth === 0) { j++; break; } } } const [cond, then, els] = splitTop(expr.slice(at + 3, j - 1)).map((p) => p.trim()); const said = `(${expandIf(cond)} 이면 ${expandIf(then)}, 아니면 ${expandIf(els ?? "")})`; return expandIf(expr.slice(0, at) + said + expr.slice(j)); } export function explain(expr: string): string { const withFind = expr.replace(FIND_RE, (_all, table: string, conds: string, col: string) => { const cs = splitConds(conds) .map(([, rhs]) => rhs) .join(" · "); return `[${table} 표에서 ${cs} 에 맞는 「${col}」]`; }); return expandIf(withFind).trim() || expr; }