Files
Aislo/M01_MasterData/M01_MasterData_UI_Combo_Preview.ts
T
eomsangdonandClaude Sonnet 5 ca5c2649e3 feat(M01): 일위대가 조합 화면 뼈대 — 왼쪽 컨테이너 · 목록 · 상세 · 로직 더하기 · 미리 보기
- 왼쪽 패널 「일위대가 조합」 컨테이너(단가산출 로직 아래) · 구분/상세구분 거름 · 새 조합 · 지우기 · 저장
- 상세: 이름·구분·단위·비고 + 담은 로직 표(올리기/내리기/빼기) · 로직 줄을 누르면 단가산출 로직 상세로 감
- 로직 더하기 창: 구분 → 상세구분 → 찾기로 하나씩 고름
- 미리 보기: 담은 로직별 입력값으로 계산해 노무비·재료비·경비 합계(보기만)
- 서버 길(조합 목록·저장·지우기)은 아직 없어 Combo_Api 한 곳에 가정 이름으로 둠

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WRFJmmhPi4exAzHgPZHMT
2026-09-21 23:27:47 +09:00

149 lines
5.9 KiB
TypeScript

/* =============================================================================
* 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<void>;
}
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<void> => {
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<string, unknown> = {};
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<void> => {
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 };
}