refactor(M02): 일위대가 조합 화면 부품 M01 → M02 옮김 — Labor_Api(층 · 키 하나 · 세 층 · 나무 · 담을 로직) · Pick · Preview · Text · css(PLAN 27-2b 앞)

- 조합 Api 가 층 길(/api/m02/layers/{layer}/combos) · 키 하나는 /api/m02/combos/key 로 — 회사 · 개인 조합도 읽음
- 로직 고르기 · 미리 보기는 /api/m02/logic-lib(로그인) 로 읽음
- M01 조합 화면 · M02 구조물 조합 쪽 부름을 새 자리로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BU9gbNE3aWFUvE61pS2WGt
This commit is contained in:
2026-09-30 13:22:13 +09:00
co-authored by Claude Opus 5.5
parent 6c0210ebc5
commit f8302149a9
11 changed files with 224 additions and 148 deletions
@@ -1,14 +0,0 @@
/* 일위대가 조합 화면 — 표는 칸 폭을 채움 · 미리 보기 금액은 오른쪽 맞춤 ·
흐린 안내 글은 보조 글색(뮤트 글색은 밝은 테마에서 대비 3.1 로 모자람) */
.m01-combo .m01-master__grid {
width: 100%;
}
.m01-combo [data-combo="preview"] th:not(:first-child),
.m01-combo [data-combo="preview"] td:not(:first-child) {
text-align: right;
}
.m01-combo .m01-logic__muted {
color: var(--color-text-secondary);
}
+5 -5
View File
@@ -21,14 +21,14 @@ import {
newCombo,
type Combo,
type ComboSummary,
} from "./M01_MasterData_UI_Combo_Api";
import { openLogicPicker } from "./M01_MasterData_UI_Combo_Pick";
import { buildPreview } from "./M01_MasterData_UI_Combo_Preview";
import { tc } from "./M01_MasterData_UI_Combo_Text";
} from "../M02_MasterTemplete/M02_MasterTemplete_Labor_Api";
import { openLogicPicker } from "../M02_MasterTemplete/M02_MasterTemplete_Labor_Pick";
import { buildPreview } from "../M02_MasterTemplete/M02_MasterTemplete_Labor_Preview";
import { tc } from "../M02_MasterTemplete/M02_MasterTemplete_Labor_Text";
import type { SideHandle } from "./M01_MasterData_UI_Side";
import "./M01_MasterData_UI_Logic_Style.css";
import "./M01_MasterData_UI_LogicLab_Style.css";
import "./M01_MasterData_UI_Combo.css";
import "../M02_MasterTemplete/M02_MasterTemplete_Labor.css";
const FILTER_ID = "조합|";
const blankCombo = (): Combo => ({
@@ -1,122 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_Combo_Api.ts
* 일위대가 조합 화면이 부르는 서버 길 — 조합 마스터 `일위대가조합.json`(키 UA)
* 길 = M02 층 길(`/api/m02/layers/system/combos` · PLAN 27-2a) · 모양 = `_화면_계약.md` 9장
* ========================================================================== */
import { API_BASE_URL } from "@config/config_frontend";
import { ApiError } from "./M01_MasterData_UI_Logic_Api";
/** 담은 로직 한 줄 — 로직 키와 메모뿐(수량·계산은 마스터에 두지 않음 · 계약 9장) */
export interface ComboLogic {
로직: string;
메모: string | null;
}
/** 조합 한 줄 통째 — `_틀.md` 10장 · 키·소유는 서버 것이 이김 */
export interface Combo {
키: string;
이름: string;
구분: string | null;
상세구분: string | null;
단위: string | null;
담은로직: ComboLogic[];
출처: string | null;
소유: string | null;
/** 이 조합을 본떠 만든 원본 키 — 비면 원본(M02 가 갈라 낸 조합에 채워짐) */
본뜬키: string | null;
비고: string | null;
}
export interface ComboSummary extends Combo {
count: number;
blocked: boolean;
reasons: string[];
}
/** `GET /combo` 의 `줄` — 담은 로직에 이름을 붙인 것 */
export interface ComboLine {
차례: number;
로직: string;
메모: string | null;
ok: boolean;
까닭?: string;
이름?: string;
구분?: string;
상세구분?: string;
결과단위?: string;
}
export interface ComboOne {
file: string;
version: string;
combo: Combo;
줄: ComboLine[];
}
export interface PreviewLine {
차례: number;
로직: string;
이름: string;
ok: boolean;
까닭?: string;
갈래?: string;
결과?: number;
노무비?: number;
재료비?: number;
경비?: number;
계?: number;
}
export interface PreviewAnswer {
줄: PreviewLine[];
노무비: number;
재료비: number;
경비: number;
계: number;
멈춤: string[];
}
/** 조합 길 = M02 층 길 마스터(`/api/m02/layers/system/combos` · PLAN 27-2a) */
async function request<T>(path: string, method = "GET", body?: unknown): Promise<T> {
const response = await fetch(`${API_BASE_URL}/m02/layers/system/combos${path}`, {
method,
credentials: "include",
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = (await response.json().catch(() => ({}))) as { detail?: unknown } & T;
if (!response.ok) throw new ApiError(response.status, data.detail ?? response.statusText);
return data;
}
const FILE = "일위대가조합.json";
const q = (key: string): string => `/${encodeURIComponent(key)}`;
export const fetchCombos = (): Promise<ComboSummary[]> =>
request<{ 줄: ComboSummary[] }>("").then((d) => d.줄);
export const fetchCombo = (key: string): Promise<ComboOne> =>
request<Omit<ComboOne, "file" | "version"> & { 판: string }>(q(key)).then((d) => ({
...d,
file: FILE,
version: d.판,
}));
export const newCombo = (combo: Combo): Promise<{ file: string; version: string; key: string }> =>
request<{ 키: string; 판: string }>("", "POST", { combo: { ...combo, 소유: "현장" } }).then(
(d) => ({ file: FILE, version: d.판, key: d.키 }),
);
export const editCombo = (
key: string,
version: string,
combo: Combo,
): Promise<{ file: string; version: string }> =>
request<{ 판: string }>(q(key), "PUT", { combo, 판: version }).then((d) => ({
file: FILE,
version: d.판,
}));
export const deleteCombo = (key: string, version: string): Promise<unknown> =>
request(`${q(key)}?판=${encodeURIComponent(version)}`, "DELETE");
/** 보기만 — 수량(inputs)은 이 부름에만 실림 · 저장 안 함 */
export const previewCombo = (
combo: Combo | string,
inputs: Record<string, Record<string, unknown>>,
): Promise<PreviewAnswer> => request("/preview", "POST", { combo, inputs });
@@ -1,120 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_Combo_Pick.ts
* [로직 더하기] 창 — 구분 → 상세구분 → 찾기로 사용자가 로직을 하나씩 고름(자동 추천 없음)
* ========================================================================== */
import {
createButton,
createInputField,
createSelectField,
el,
showToast,
} from "@ui/ui_template_elements";
import { t as L } from "@ui/ui_template_locale";
import {
fetchLogics,
fetchLogicSubs,
type LogicSummary,
type SubBrief,
} from "./M01_MasterData_UI_Logic_Api";
import { tc } from "./M01_MasterData_UI_Combo_Text";
import "./M01_MasterData_UI_Logic_Style.css"; // 창 겉틀 — M02 에서 열 때도 이 모듈이 불러옴
import "./M01_MasterData_UI_Combo.css";
const opts = (values: string[]): { value: string; text: string }[] =>
[L("M01_All"), ...values].map((v, i) => ({ value: i ? v : "", text: v }));
export function openLogicPicker(done: (logic: LogicSummary) => void): void {
const subs: SubBrief[] = [];
let all: LogicSummary[] = [];
const sub = createSelectField({ options: opts([]), compact: true, label: tc("Sub") });
const detail = createSelectField({ options: opts([]), compact: true, label: tc("Detail") });
detail.select.disabled = true;
const searchField = createInputField({ type: "search", placeholder: tc("Pick_Search") });
const list = el("div", { className: "m01-logic__pick-list" });
const hint = el("p", { className: "m01-logic__muted", text: tc("Pick_Hint") });
const close = (): void => backdrop.remove();
const find = (): void => {
const q = searchField.input.value.trim().toLowerCase();
const found = all.filter(
(x) =>
(!sub.select.value || x.구분 === sub.select.value) &&
(!detail.select.value || x.상세구분 === detail.select.value) &&
(!q || `${x.키} ${x.이름}`.toLowerCase().includes(q)),
);
hint.textContent = found.length ? `${found.length} / ${all.length}` : tc("Pick_None");
list.replaceChildren(
...found.slice(0, 100).map((x) => {
const row = el("button", {
className: "m01-logic__pick-row m01-logic__pick-row--button",
attrs: { type: "button", "data-pick": x.키 },
children: [
el("div", {
className: "m01-logic__stack",
children: [
el("strong", { text: x.이름 }),
el("span", {
className: "m01-logic__muted",
text: `${x.키} · ${x.구분} ${x.상세구분}`.trim(),
}),
],
}),
el("span", { text: `${x.결과단위}${x.blocked ? ` · ${tc("Pick_Blocked")}` : ""}` }),
],
});
row.addEventListener("click", () => {
close();
done(x);
});
return row;
}),
);
};
sub.select.addEventListener("change", () => {
const d = subs.find((s) => s.name === sub.select.value)?.details ?? [];
detail.setOptions(opts(d), "");
detail.select.disabled = d.length === 0;
});
const dialog = el("div", {
className: "m01-logic__pick m01-combo",
attrs: { role: "dialog", "aria-label": tc("Pick_Title") },
children: [
el("div", {
className: "m01-logic__section-head",
children: [
el("h3", { text: tc("Pick_Title") }),
createButton({ label: tc("Pick_Close"), variant: "ghost", onClick: close }),
],
}),
el("div", {
className: "m01-logic__filters",
children: [
sub.root,
detail.root,
searchField.root,
createButton({ label: tc("Pick_Find"), variant: "filled", onClick: find }),
],
}),
hint,
list,
],
});
const backdrop = el("div", { className: "m01-logic__backdrop", children: [dialog] });
backdrop.addEventListener("click", (ev) => ev.target === backdrop && close());
backdrop.addEventListener("keydown", (ev) => ev.key === "Escape" && close());
document.body.append(backdrop);
searchField.input.addEventListener("keydown", (ev) => ev.key === "Enter" && find());
searchField.input.focus();
void Promise.all([fetchLogicSubs(), fetchLogics()])
.then(([s, l]) => {
subs.push(...s);
all = l;
sub.setOptions(opts(s.map((x) => x.name)), "");
})
.catch((error) =>
showToast(error instanceof Error ? error.message : tc("Load_Failed"), "error"),
);
}
@@ -1,194 +0,0 @@
/* =============================================================================
* 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";
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>>,
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.이름, compact: true });
const control = "select" in field ? field.select : field.input;
control.value = value;
control.setAttribute("data-input", `${key}|${input.이름}`);
const edit = (): void => {
mine[input.이름] = control.value;
};
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 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) => {
const text = i === 0 && note ? `${t} — ${note}` : t;
return el("td", { text, attrs: { title: text } });
}),
});
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);
}
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, () => 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 };
}
@@ -1,81 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_Combo_Text.ts
* 일위대가 조합 화면 글자 — [한국어, 영어]
* ========================================================================== */
import { currentLanguageIndex } from "@ui/ui_template_locale";
const TEXT = {
Title: ["일위대가 조합", "Unit-price combination"],
Sub: ["구분", "Category"],
Detail: ["상세구분", "Detail"],
All: ["전체", "All"],
Empty: ["조합이 없음 — [새 조합]으로 만듦", "No combinations — press [New combination]"],
New: ["새 조합", "New combination"],
Delete: ["지우기", "Delete"],
Save: ["저장", "Save"],
DeleteAsk: ["이 조합을 지울까요?", "Delete this combination?"],
Saved: ["저장함", "Saved"],
Deleted: ["지움", "Deleted"],
Stale: ["그 사이 조합 파일이 바뀜 — 다시 열어 주세요", "The file changed — reopen it"],
Loading: ["불러오는 중…", "Loading…"],
LeaveAsk: [
"저장 안 한 고침이 있음 — 로직 상세로 가면 이 화면에서는 그대로 두고 옮겨 감. 갈까요?",
"Unsaved edits — go to the logic anyway?",
],
BackAsk: [
"저장 안 한 고침이 있음 — 버리고 목록으로 갈까요?",
"Unsaved edits — discard and go back to the list?",
],
Search: ["이름 · 키로 찾기", "Search by name or key"],
NoMatch: ["찾은 조합 없음 — 거름 · 찾기 글을 바꿔 봄", "No match — change the filter or search"],
NeedName: ["이름을 적어야 저장됨", "A name is required"],
Load_Failed: ["불러오지 못함", "Load failed"],
Head_Key: ["키", "Key"],
Head_Name: ["이름", "Name"],
Head_Unit: ["단위", "Unit"],
Head_Note: ["비고", "Note"],
Head_Count: ["로직 수", "Logics"],
Head_Origin: ["본뜬키", "Copied from"],
Origin_Self: ["원본", "Original"],
Logics_Title: ["담은 로직", "Logics in it"],
Col_Order: ["차례", "No."],
Col_Key: ["로직 키", "Logic key"],
Col_Name: ["이름", "Name"],
Col_Unit: ["결과 단위", "Result unit"],
Col_Memo: ["메모", "Memo"],
Col_Move: ["순서", "Move"],
Up: ["올리기", "Up"],
Down: ["내리기", "Down"],
Remove: ["빼기", "Remove"],
AddLogic: ["로직 더하기", "Add logic"],
NoLogic: ["담은 로직 없음", "No logics yet"],
Open: ["열기", "Open"],
Pick_Title: ["로직 고르기", "Pick a logic"],
Pick_Search: ["이름·키로 찾기", "Search by name or key"],
Pick_Find: ["찾기", "Find"],
Pick_Hint: [
"구분 → 상세구분을 고르고 [찾기]를 누름 — 하나씩 직접 고름",
"Choose category, detail, then Find — pick one by one",
],
Pick_None: ["찾은 로직 없음", "No logics found"],
Pick_Close: ["닫기", "Close"],
Pick_Blocked: ["막힘", "Blocked"],
Prev_Title: ["미리 보기 (보기만 · 저장 안 함)", "Preview (view only)"],
Prev_Inputs: ["넣을 값", "Inputs"],
Prev_Run: ["미리 보기 계산", "Run preview"],
Prev_Labor: ["노무비", "Labor"],
Prev_Material: ["재료비", "Material"],
Prev_Expense: ["경비", "Expense"],
Prev_Sum: ["합계", "Total"],
Prev_Row: ["로직", "Logic"],
Prev_Fail: ["못 셈", "Failed"],
Prev_Wait: ["미리 보기 계산을 누르면 값이 나옴", "Press the button to see values"],
} as const satisfies Record<string, readonly [string, string]>;
export type ComboTextKey = keyof typeof TEXT;
export function tc(key: ComboTextKey): string {
const entry = TEXT[key];
return entry[currentLanguageIndex as 0 | 1] ?? entry[0];
}
+1 -1
View File
@@ -10,7 +10,7 @@ import { attachCollapsible } from "@ui/ui_template_collapsible";
import { t as L } from "@ui/ui_template_locale";
import { fetchFiles, fetchSubsAll, type FileInfo, type SubInfo } from "./M01_MasterData_Api_Fetch";
import { tx } from "./M01_MasterData_UI_Logic_Text";
import { tc } from "./M01_MasterData_UI_Combo_Text";
import { tc } from "../M02_MasterTemplete/M02_MasterTemplete_Labor_Text";
import { renderTree, type MakeRow } from "./M01_MasterData_UI_Tree";
/** 컨테이너마다 기억하는 화면 상태 — 찾기 글 · 쪽 · 소요량·계수 표의 용도 대상 거름 (거름은 `m01.filter.*`) */