/* ============================================================================= * M01_MasterData_UI_Combo_Preview.ts * 조합 미리 보기 — 담은 로직 저마다 받은 입력값을 서버 미리 보기(`POST /combo/preview`)에 실어 비목별 합계를 받음 * 입력값(수량)은 이 화면 안에만 두고 조합에 저장하지 않음(계약 9장) * ========================================================================== */ import { createInputField, createSelectField, el } from "@ui/ui_template_elements"; import { fetchLogic, type LogicInput } from "./M01_MasterData_UI_Logic_Api"; import { previewCombo, type Combo } from "./M01_MasterData_UI_Combo_Api"; import { tc, type ComboTextKey } from "./M01_MasterData_UI_Combo_Text"; const COSTS = ["노무비", "재료비", "경비"] as const; 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 initial = (i: LogicInput): string => String(i.고르기?.[0] ?? i.범위?.[0] ?? ""); /** 입력 칸 — 바꾼 값은 `values`(이 화면 메모)에만 적음 */ function inputCell( input: LogicInput, key: string, values: Record>, ): HTMLElement { const mine = (values[key] ??= {}); const value = mine[input.이름] ?? initial(input); mine[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", `${key}|${input.이름}`); control.addEventListener("input", () => (mine[input.이름] = control.value)); control.addEventListener("change", () => (mine[input.이름] = control.value)); return field.root; } export interface PreviewHandle { root: HTMLElement; /** 담은 로직이 바뀐 뒤 입력 칸을 다시 그림 */ redraw: () => Promise; } export function buildPreview(combo: () => Combo): PreviewHandle { const values: Record> = {}; /** 서버가 받을 꼴 — 원래 숫자·고르기 값으로 되돌림 */ const inputs = new Map(); const form = 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 send: Record> = {}; for (const [key, defs] of inputs) { send[key] = {}; for (const i of defs) { const raw = values[key]?.[i.이름] ?? initial(i); if (raw.trim() === "") continue; // 빈 칸은 안 보냄(로직 화면과 같음) send[key][i.이름] = i.고르기?.find((o) => String(o) === raw) ?? num(raw); } } let got; try { got = await previewCombo(combo(), send); } catch (error) { out.replaceChildren( el("p", { text: `${tc("Prev_Fail")}: ${error instanceof Error ? error.message : ""}` }), ); return; } const trs = got.줄.map((l) => rowOf( [ `${l.로직} ${l.이름}`, fmt(l.노무비 ?? 0), fmt(l.재료비 ?? 0), fmt(l.경비 ?? 0), fmt(l.계 ?? 0), ], l.ok ? "" : `${tc("Prev_Fail")}: ${l.까닭 ?? ""}`, ), ); trs.push( rowOf( [tc("Prev_Sum"), fmt(got.노무비), fmt(got.재료비), fmt(got.경비), fmt(got.계)], "", 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[] = []; inputs.clear(); for (const row of combo().담은로직) { try { const one = await fetchLogic(row.로직); inputs.set(row.로직, one.logic.입력); 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.로직, values)), ], }), ); } catch { /* 못 읽은 로직은 미리 보기에서 그 줄만 까닭이 뜸 */ } } form.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") }), form, button, out, ], }); return { root, redraw }; }