Files
Aislo/M01_MasterData/M01_MasterData_UI_Combo_Preview.ts
T

204 lines
7.4 KiB
TypeScript

/* =============================================================================
* M01_MasterData_UI_Combo_Preview.ts
* 조합 미리 보기 — 담은 로직 저마다 받은 입력값을 서버 미리 보기(`POST /combo/preview`)에 실어 비목별 합계를 받음
* 입력값(수량)은 이 화면 안에만 두고 조합에 저장하지 않음(계약 9장)
* ========================================================================== */
import { createInputField, createSelectField, el } from "@ui/ui_template_elements";
import { fetchAuto, 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";
import { formatMoney } from "./M01_MasterData_UI_Logic_Money";
import { tx } from "./M01_MasterData_UI_Logic_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 = formatMoney;
/** 로직 입력 정의 → 처음 값(고르기 첫째 · 범위 아래끝) */
const initial = (i: LogicInput): string => String(i.고르기?.[0] ?? i.범위?.[0] ?? "");
/** 입력 칸 — 바꾼 값은 `values`(이 화면 메모)에만 적음 */
function inputCell(
input: LogicInput,
key: string,
values: Record<string, Record<string, string>>,
sample: Set<string>,
onEdit: () => void,
): 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.이름}`);
const tag = sample.has(`${key}|${input.이름}`)
? el("span", { className: "m01-logic__tag", text: tx("Calc_Sample") })
: undefined;
if (tag) field.root.append(tag);
const edit = (): void => {
mine[input.이름] = control.value;
sample.delete(`${key}|${input.이름}`);
tag?.remove();
};
control.addEventListener("input", edit);
control.addEventListener("change", () => {
edit();
onEdit(); // 바꾸면 다시 미리 보기 계산
});
return field.root;
}
export interface PreviewHandle {
root: HTMLElement;
/** 담은 로직이 바뀐 뒤 입력 칸을 다시 그림 */
redraw: () => Promise<void>;
}
export function buildPreview(combo: () => Combo): PreviewHandle {
const values: Record<string, Record<string, string>> = {};
/** 서버가 받을 꼴 — 원래 숫자·고르기 값으로 되돌림 */
const inputs = new Map<string, LogicInput[]>();
/** 견본(자동값)으로 채운 칸 `로직|입력` — 사용자가 고치면 빠짐 · 로직마다 자동값은 한 번만 받음 */
const sample = new Set<string>();
const asked = new Set<string>();
const form = el("div", { className: "m01-logic__stack" });
const out = el("div", {
className: "m01-master__grid-wrap",
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 send: Record<string, Record<string, unknown>> = {};
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<void> => {
const blocks: HTMLElement[] = [];
inputs.clear();
for (const row of combo().담은로직) {
try {
const [one, auto] = await Promise.all([
fetchLogic(row.로직),
asked.has(row.로직) ? Promise.resolve({}) : fetchAuto(row.로직),
]);
asked.add(row.로직);
const mine = (values[row.로직] ??= {});
for (const i of one.logic.입력) {
const got = (auto as Record<string, unknown>)[i.이름];
if (got === undefined || got === null || (mine[i.이름] ?? "").trim() !== "") continue;
mine[i.이름] = String(got);
sample.add(`${row.로직}|${i.이름}`);
}
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, sample, () => void run()),
),
],
}),
);
} catch {
/* 못 읽은 로직은 미리 보기에서 그 줄만 까닭이 뜸 */
}
}
form.replaceChildren(...blocks);
if (blocks.length)
await run(); // 열자마자 한 번 미리 보기 계산
else 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 };
}