/* ============================================================================= * M01_MasterData_UI_Combo_Preview.ts * 조합 미리 보기 — 담은 로직 저마다 입력값으로 `/calc` 를 불러 노무비·재료비·경비로 갈라 합침(보기만 · 저장 없음) * ========================================================================== */ import { createInputField, createSelectField, el } from "@ui/ui_template_elements"; import { fetchLogic, runCalc, type LogicInput } from "./M01_MasterData_UI_Logic_Api"; import type { ComboLogic } from "./M01_MasterData_UI_Combo_Api"; import { tc, type ComboTextKey } from "./M01_MasterData_UI_Combo_Text"; const COSTS = ["노무비", "재료비", "경비"] as const; type Costs = Record<(typeof COSTS)[number], number>; const LABEL: Record<(typeof COSTS)[number], ComboTextKey> = { 노무비: "Prev_Labor", 재료비: "Prev_Material", 경비: "Prev_Expense", }; const num = (v: string): number | string => (v.trim() !== "" && !isNaN(Number(v)) ? Number(v) : v); const fmt = (n: number): string => n.toLocaleString("ko-KR", { maximumFractionDigits: 4 }); const total = (c: Costs): number => c.노무비 + c.재료비 + c.경비; const blank = (): Costs => ({ 노무비: 0, 재료비: 0, 경비: 0 }); /** 로직 입력 정의 → 처음 값(고르기 첫째 · 범위 아래끝) */ const initial = (i: LogicInput): string => String(i.고르기?.[0] ?? i.범위?.[0] ?? ""); /** 입력 칸 — 바꾸면 그 줄의 입력에 바로 적음(조합과 함께 저장됨) */ function inputCell(input: LogicInput, row: ComboLogic): HTMLElement { const value = row.입력[input.이름] ?? initial(input); row.입력[input.이름] = value; const choices = input.고르기?.map((v) => ({ value: String(v), text: String(v) })); const field = choices ? createSelectField({ options: choices, value, compact: true, label: input.이름 }) : createInputField({ type: "text", label: input.이름 }); const control = "select" in field ? field.select : field.input; control.value = value; control.setAttribute("data-input", `${row.키}|${input.이름}`); control.addEventListener("input", () => (row.입력[input.이름] = control.value)); control.addEventListener("change", () => (row.입력[input.이름] = control.value)); return field.root; } export interface PreviewHandle { root: HTMLElement; /** 담은 로직이 바뀐 뒤 입력 칸을 다시 그림 */ redraw: () => Promise; } export function buildPreview(rows: () => ComboLogic[]): PreviewHandle { const inputs = el("div", { className: "m01-logic__stack" }); const out = el("div", { attrs: { "data-combo": "preview" } }); const rowOf = (cells: string[], note = "", bold = false): HTMLElement => el("tr", { className: bold ? "m01lab__subtotal" : "", children: cells.map((t, i) => el("td", { text: i === 0 && note ? `${t} — ${note}` : t })), }); const run = async (): Promise => { out.replaceChildren(el("p", { className: "m01-logic__muted", text: "…" })); const sum = blank(); const trs: HTMLElement[] = []; for (const row of rows()) { const cost = blank(); let name = row.키; let note = ""; try { const one = await fetchLogic(row.키); name = one.logic.이름; const values: Record = {}; for (const i of one.logic.입력) { const raw = row.입력[i.이름] ?? initial(i); if (raw.trim() === "") continue; // 빈 칸은 안 보냄(로직 화면과 같음) values[i.이름] = i.고르기?.find((o) => String(o) === raw) ?? num(raw); } const got = await runCalc({ key: row.키, inputs: values }); if (got.ok) { for (const line of got.lines ?? []) for (const c of COSTS) cost[c] += line.비목?.[c] ?? 0; } else note = `${tc("Prev_Fail")}: ${got.reason}`; } catch (error) { note = `${tc("Prev_Fail")}: ${error instanceof Error ? error.message : ""}`; } for (const c of COSTS) sum[c] += cost[c]; trs.push( rowOf([`${row.키} ${name}`, ...COSTS.map((c) => fmt(cost[c])), fmt(total(cost))], note), ); } trs.push(rowOf([tc("Prev_Sum"), ...COSTS.map((c) => fmt(sum[c])), fmt(total(sum))], "", true)); const heads = [tc("Prev_Row"), ...COSTS.map((c) => tc(LABEL[c])), tc("Prev_Sum")]; out.replaceChildren( el("table", { className: "m01-master__grid", children: [ el("thead", { children: [el("tr", { children: heads.map((t) => el("th", { text: t })) })], }), el("tbody", { children: trs }), ], }), ); }; const button = el("button", { className: "ui-btn ui-btn--filled", text: tc("Prev_Run"), attrs: { type: "button", "data-combo": "run" }, }); button.addEventListener("click", () => void run()); const redraw = async (): Promise => { const blocks: HTMLElement[] = []; for (const row of rows()) { try { const one = await fetchLogic(row.키); blocks.push( el("div", { className: "m01lab__info", children: [ el("strong", { className: "m01lab__cell--wide", text: `${row.키} ${one.logic.이름}`, }), ...one.logic.입력.map((i) => inputCell(i, row)), ], }), ); } catch { /* 못 읽은 로직은 계산 때 까닭이 뜸 */ } } inputs.replaceChildren(...blocks); out.replaceChildren(el("p", { className: "m01-logic__muted", text: tc("Prev_Wait") })); }; const root = el("section", { className: "m01lab__box m01-logic__section", children: [ el("div", { className: "m01-logic__section-head", children: [el("h3", { text: tc("Prev_Title") })], }), el("h4", { text: tc("Prev_Inputs") }), inputs, button, out, ], }); return { root, redraw }; }