Files
Aislo/M01_MasterData/M01_MasterData_UI_Side.ts
T
eomsangdonandClaude Sonnet 5 4b1eeec524 feat(M01): 준용 고르면 값 따라옴 · 인력 상태 거름 · 유가전력 구분·상세구분 거름
- 인력 준용 고르기 — 값 칸이 고른 직종 값으로 바뀌어 노랑 · 비우면 원래 값
- 저장 때 서버가 준용 직종 값을 다시 읽어 값 칸에 채움(화면 값 불신)
- 인력 왼쪽 패널 「상태」 드롭다운(목록은 서버) · 재료 유가전력 2단 거름
- 시험 2개 더함

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WRFJmmhPi4exAzHgPZHMT
2026-09-20 20:03:59 +09:00

330 lines
12 KiB
TypeScript

/* =============================================================================
* M01_MasterData_UI_Side.ts
* 왼쪽 패널 — 공용 접기 컨테이너(`ui-collapsible ui-sidebar-section`) 여덟 개
* 인력 · 재료 · 기계 · 소요량 · 계수 · 환율 · 요율 · 일위대가 로직
* 펼치면 하위 목록(거름 · 파일) · 환율/요율은 누르면 바로 표 · 로직은 안에 로직 목록
* ========================================================================== */
import { createSelectField, el, showToast } from "@ui/ui_template_elements";
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 { renderTree, type MakeRow } from "./M01_MasterData_UI_Tree";
/** 요소 화면에서 열 것 — 파일 · 하위 거름(구분·세부분류) · 상세구분 · 제목 */
export interface Pick {
group: string;
file: FileInfo;
sub: string;
detail: string;
/** 인력 상태 거름 · 비면 전체 */
state?: string;
label: string;
}
export interface SideHandle {
root: HTMLElement;
/** 일위대가 로직 컨테이너 안(로직 목록이 들어갈 자리) */
logicHost: HTMLElement;
/** 그룹의 파일 판본을 다시 받음(저장 뒤) — 돌려받는 것 = 새 목록 */
refresh: (group: string) => Promise<FileInfo[]>;
setActive: (id: string | null) => void;
/** 「전체」 + 드롭다운 거름 한 벌 — 로직 컨테이너도 씀 */
filter: (args: FilterArgs) => HTMLElement;
}
export interface FilterArgs {
/** 「전체」 줄 눌림 표시용 */
id: string;
/** 고른 것을 기억할 sessionStorage 칸 */
store: string;
subs: SubInfo[];
total: number;
subLabel: string;
/** 「전체」 줄 글 · 없으면 「전체」 */
title?: string;
/** 없으면 한 단 */
detailLabel?: string;
/** 있으면 「상태」 드롭다운 한 단 더 — 목록은 서버가 줌 */
states?: string[];
stateLabel?: string;
onPick: (sub: string, detail: string, label: string, state: string) => void;
}
const MATERIAL_NAMES: Record<string, string> = { 유가전력: "유가·전력" };
/** 재료 컨테이너 차례 — 여기 없는 파일은 뒤에 */
const FUEL = "유가전력";
const MATERIAL_ORDER = ["자재품목", "유가전력", "품셈재료"];
/** 파일 이름 → 목록 글자 — 「소요량_건설품셈_10장_창호…」 → 「건설품셈_10장_창호…」 */
export const fileLabel = (file: string): string =>
file.replace(/^[^_]+_/, "").replace(/\.json$/, "");
const GROUP_TITLE = {
인력: "M01_GroupLabor",
재료: "M01_GroupMaterial",
기계: "M01_GroupMachine",
소요량: "M01_GroupQuantity",
계수: "M01_GroupFactor",
환율: "M01_GroupExchange",
요율: "M01_GroupRate",
} as const;
type Group = keyof typeof GROUP_TITLE;
const GROUPS = Object.keys(GROUP_TITLE) as Group[];
const LEAF: Group[] = ["환율", "요율"];
export function buildSide(onOpen: (pick: Pick) => void, onLogic: () => void): SideHandle {
const lists = new Map<Group, FileInfo[]>();
const bodies = new Map<Group, HTMLElement>();
const buttons = new Map<string, HTMLElement>();
// 하위 거름은 서버가 준 목록(파일 머리에 등록된 구분·세부분류) — 새 조사가 늘어도 화면은 그대로
const kinds = new Map<Group, SubInfo[]>();
const states = new Map<Group, string[]>();
const setActive = (id: string | null): void => {
for (const [key, button] of buttons) button.classList.toggle("is-active", key === id);
};
/** 트리 줄 — 부모는 접기/펴기 · 누를 일이 있는 줄만 밝게 */
const make: MakeRow = (node, caret, depth, onClick) => {
const button = el("button", {
className: "m01-side__item",
attrs: { type: "button" },
children: [
el("span", {
children: [
el("span", { className: "m01-tree__caret", text: caret }),
el("span", { text: node.label }),
],
}),
...(node.count === null
? []
: [
el("span", {
className: "m01-side__muted",
text: node.count.toLocaleString("ko-KR"),
}),
]),
],
});
button.style.paddingLeft = `calc(var(--spacing-8) + ${depth} * var(--spacing-16))`;
if (node.run) buttons.set(node.id, button);
button.addEventListener("click", () => {
if (node.run) setActive(node.id);
onClick();
});
return button;
};
/** 「전체」 한 줄 + 구분 → 상세구분 드롭다운 거름(목록은 서버가 준 것 · 고른 것은 기억) —
* detailLabel 없으면 한 단 */
const filter = (a: FilterArgs): HTMLElement => {
const saved = (() => {
try {
return JSON.parse(sessionStorage.getItem(a.store) ?? "[]") as string[];
} catch {
return [];
}
})();
const pickSub = a.subs.find((k) => k.name === saved[0]);
const opts = (values: string[]): { value: string; text: string }[] =>
[L("M01_All"), ...values].map((v, i) => ({ value: i ? v : "", text: v }));
const sub = createSelectField({
options: opts(a.subs.map((k) => k.name)),
value: pickSub?.name ?? "",
compact: true,
label: a.subLabel,
});
const detail = a.detailLabel
? createSelectField({
options: opts(pickSub?.details ?? []),
value: saved[1] ?? "",
compact: true,
label: a.detailLabel,
disabled: !pickSub?.details.length,
})
: null;
const state = a.states?.length
? createSelectField({
options: opts(a.states),
value: a.states.includes(saved[2]) ? saved[2] : "",
compact: true,
label: a.stateLabel ?? "",
})
: null;
const run = (): void => {
const d = detail?.select.value ?? "";
const s = state?.select.value ?? "";
try {
sessionStorage.setItem(a.store, JSON.stringify([sub.select.value, d, s]));
} catch {
/* 기억 못 해도 거름은 됨 */
}
setActive(a.id);
a.onPick(
sub.select.value,
d,
[sub.select.value, d, s].filter(Boolean).join(" · ") || L("M01_All"),
s,
);
};
sub.select.addEventListener("change", () => {
if (detail) {
const details = a.subs.find((k) => k.name === sub.select.value)?.details ?? [];
detail.setOptions(opts(details), "");
detail.select.disabled = details.length === 0;
}
run();
});
detail?.select.addEventListener("change", run);
state?.select.addEventListener("change", run);
const all = make(
{ id: a.id, label: a.title ?? L("M01_All"), count: a.total, run },
"",
0,
() => {
if (state) state.select.value = "";
sub.select.value = "";
sub.select.dispatchEvent(new Event("change"));
},
);
return el("div", {
children: [
all,
el("div", {
className: "m01-side__filter",
children: [sub.root, ...(detail ? [detail.root] : []), ...(state ? [state.root] : [])],
}),
],
});
};
const order = (file: string): number => {
const i = MATERIAL_ORDER.indexOf(fileLabel(file));
return i < 0 ? MATERIAL_ORDER.length : i;
};
const drawGroup = (group: Group): void => {
const files = lists.get(group) ?? [];
const body = bodies.get(group);
if (!body) return;
const open = (file: FileInfo, sub: string, label: string, detail = "", state = ""): void =>
onOpen({ group, file, sub, detail, state, label });
const one = files[0];
const dropped: Partial<Record<Group, { label: string; detail?: string }>> = {
인력: { label: L("M01_LaborSub"), detail: L("M01_LaborDetail") },
기계: { label: L("M01_MachineSub") },
소요량: { label: L("M01_LaborSub"), detail: L("M01_LaborDetail") },
계수: { label: L("M01_LaborSub"), detail: L("M01_LaborDetail") },
};
const drop = dropped[group];
if (drop && one) {
body.replaceChildren(
filter({
id: `${group}|`,
store: `m01.filter.${group}`,
subs: kinds.get(group) ?? [],
total: files.reduce((n, f) => n + f.rows, 0),
subLabel: drop.label,
detailLabel: drop.detail,
states: states.get(group),
stateLabel: L("M01_LaborState"),
onPick: (sub, detail, label, state) => open(one, sub, label, detail, state),
}),
);
return;
}
body.replaceChildren(
...[...files]
.sort((a, b) => order(a.file) - order(b.file))
.flatMap((f) => {
const name = fileLabel(f.file);
const label = group === "재료" ? (MATERIAL_NAMES[name] ?? name) : name;
if (group === "재료" && name === FUEL)
return [
filter({
id: `${group}\n${f.file}`,
store: `m01.filter.${group}.${name}`,
subs: kinds.get(group) ?? [],
total: f.rows,
title: label,
subLabel: L("M01_FuelSub"),
detailLabel: L("M01_FuelDetail"),
onPick: (sub, detail, tail) =>
open(f, sub, sub || detail ? `${label} · ${tail}` : label, detail),
}),
];
return renderTree(
[
{
id: `${group}\n${f.file}`,
label,
count: f.rows,
run: () => open(f, "", label),
},
],
make,
);
}),
);
};
const refresh = async (group: string): Promise<FileInfo[]> => {
const list = await fetchFiles(group);
if (list[0] && (group === "인력" || group === "기계")) {
const got = await fetchSubsAll({ file: list[0].file });
kinds.set(group, got.subs);
states.set(group as Group, got.states ?? []);
} else if (group === "재료") {
const fuel = list.find((f) => fileLabel(f.file) === FUEL);
if (fuel) kinds.set(group, (await fetchSubsAll({ file: fuel.file })).subs);
} else if (group === "소요량" || group === "계수") {
kinds.set(group, (await fetchSubsAll({ group })).subs);
}
lists.set(group as Group, list);
drawGroup(group as Group);
return list;
};
const section = (title: string, body: HTMLElement | null): HTMLElement =>
el("section", {
className: "m01-side__group ui-collapsible ui-sidebar-section is-collapsed",
children: [
el("h3", { className: "ui-collapsible__title", text: title }),
...(body ? [body] : []),
],
});
const groups = GROUPS.map((group) => {
const body = LEAF.includes(group) ? null : el("div", { className: "m01-side__items" });
if (body) bodies.set(group, body);
const root = section(L(GROUP_TITLE[group]), body);
if (!body) {
root.classList.add("m01-side__leaf");
buttons.set(`${group}\n`, root);
root.querySelector(".ui-collapsible__title")?.addEventListener("click", () => {
const one = lists.get(group)?.[0];
if (!one) return;
setActive(`${group}\n`);
onOpen({ group, file: one, sub: "", detail: "", label: L(GROUP_TITLE[group]) });
});
}
return root;
});
const logicHost = el("div", { className: "m01-side__items" });
const logic = section(L("M01_GroupLogic"), logicHost);
logic.querySelector(".ui-collapsible__title")?.addEventListener("click", () => {
setActive(null);
onLogic();
});
const root = el("div", { className: "m01-side", children: [...groups, logic] });
attachCollapsible(root);
void Promise.all(GROUPS.map(refresh)).catch((error) =>
showToast(error instanceof Error ? error.message : L("M01_LoadFailed"), "error"),
);
return { root, logicHost, refresh, setActive, filter };
}