Files
Aislo/M02_MasterTemplete/M02_MasterTemplete_Hopyo_Sheet.ts
T

283 lines
11 KiB
TypeScript

/* =============================================================================
* M02_MasterTemplete_Hopyo_Sheet.ts
* 일위대가 실무자료 엑셀 보기 창(PLAN 329) — 큰 모달 · 왼쪽 = 올린 엑셀을 연 것처럼 읽기 전용 시트(A00 산출근거
* 스프레드시트 · 탭 일위대가 · 단가산출) · 오른쪽 = 호표 목록(체크 · 찾기 · 맞춤 n/m) + [고른 n개 불러오기].
* · 목록 누름 → 시트에서 그 호표 영역(B열 ~ 끝 열) 고름 · 칸 누름 → 그 행 호표를 목록에서 강조 · 영역 고름
* · 불러오기 = 고른 호표마다 차례로 사전조합 만들기(`/hopyo-build`) → 결과 표(사전조합 키 · 빠진 줄 · 값 차이) ·
* `onImport` 가 있으면 호표마다 알림([로직 추가] 참조 줄)
* · 격자 = 서버 `/hopyo-grid/{키}` · 옛 파일(격자 없음)은 시트 자리에 까닭 글 · 목록 · 불러오기는 됨
* ⚠ 부르는 쪽은 `import()` 로 엶 · 스프레드시트도 열 때 불러옴(다른 화면 번들에 안 섞이게).
* ========================================================================== */
import { createButton, el, showToast } from "@ui/ui_template_elements";
import { openModal } from "@ui/ui_template_modal";
import type { Sheet } from "../A00_Common/spreadsheet/spreadsheet_types";
import type { SpreadsheetHandle } from "../A00_Common/spreadsheet/spreadsheet";
import {
buildHopyo,
readHopyo,
readHopyoGrid,
type HopyoBrief,
type HopyoBuilt,
type HopyoGrid,
type HopyoScope,
type HopyoSpan,
} from "./M02_MasterTemplete_Hopyo_Api";
import { builtWord } from "./M02_MasterTemplete_Hopyo_View";
import "./M02_MasterTemplete_Hopyo.css";
export interface HopyoSheetOptions {
/** 실무자료 파일 층 */
scope: HopyoScope;
key: string;
파일: string;
/** 만들 층 쓰기 권한 — 없으면 체크 · 불러오기 없음(보기만) */
canWrite: boolean;
/** 사전조합을 만들 층(없으면 `scope` · [로직 추가] = 문서 층) */
target?: HopyoScope;
/** 처음 고를 호표 번(호표 화면 [엑셀에서 보기]) */
호표?: number;
/** 처음 보일 단가산출 행(330-3 근거 [엑셀에서 보기]) */
단산행?: number | [number, number];
/** 호표 하나를 만들었음 — [로직 추가] 참조 줄 */
onImport?: (got: HopyoBuilt, hopyo: HopyoBrief) => void;
}
const ILWI = "일위대가";
const DANSAN = "단가산출";
const why = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const won = (v: number | null | undefined): string =>
v === null || v === undefined ? "" : v.toLocaleString("ko-KR");
const note = (text: string): HTMLElement => el("span", { className: "m02-hopyo__note", text });
/** 엑셀 행(1부터)이 든 호표 번 · 없으면 null */
export const hopyoAtRow = (list: HopyoSpan[], row: number): number | null =>
list.find((h) => h.행[0] <= row && row <= h.행[1])?.번 ?? null;
/** 호표 영역 A1 — B열 ~ 시트 끝 열(북부청 = `B20:O24`) */
export const spanText = (행: [number, number], last: string): string => `B${행[0]}:${last}${행[1]}`;
/** 시트 끝 열 글자 — 칸 · 열 정보 중 가장 오른쪽 */
export function lastColumn(sheet: Pick<Sheet, "칸" | "열">): string {
let best = "A";
for (const k of [...Object.keys(sheet.칸), ...Object.keys(sheet.열 ?? {})]) {
const c = /^[A-Z]+/.exec(k)?.[0];
if (c && (c.length > best.length || (c.length === best.length && c > best))) best = c;
}
return best;
}
/** 단가산출 행 → 행 전체 범위 A1(`4:9`) */
export const rowsText = (행: number | [number, number]): string =>
typeof 행 === "number" ? `${행}:${행}` : `${행[0]}:${행[1]}`;
export function openHopyoSheet(opt: HopyoSheetOptions): void {
let sheet: SpreadsheetHandle | null = null;
let closed = false;
let briefs: HopyoBrief[] = [];
let spans: HopyoSpan[] = [];
let ilwi = ""; // 일위대가 시트 id
let last = "O";
let at = { 시트: "", 칸: "", 범위: "" }; // 시트 고름
let current: number | null = opt.호표 ?? null;
const checked = new Set<number>();
const items = new Map<number, HTMLElement>();
const left = el("div", {
className: "m02-hopyo-sheet__grid",
children: [note("엑셀을 읽는 중…")],
});
const search = el("input", {
className: "ui-input ui-input--sm",
attrs: { type: "search", placeholder: "호표 · 품명 · 규격 찾기" },
}) as HTMLInputElement;
const list = el("div", { className: "m02-hopyo-sheet__list" });
const count = note("");
const go = createButton({ label: "고른 0개 불러오기", variant: "filled", size: "sm" });
go.disabled = true;
const result = el("div", { className: "m02-hopyo-sheet__result" });
const right = el("div", {
className: "m02-hopyo-sheet__side",
children: [
search,
el("div", { className: "m02-hopyo__bar", children: [count, ...(opt.canWrite ? [go] : [])] }),
list,
result,
],
});
openModal({
title: `엑셀 보기 — ${opt.파일}`,
closeLabel: "닫기",
wide: true,
dialogClass: "m02-modal m02-hopyo-sheet__dialog",
beforeClose: async () => {
closed = true;
sheet?.destroy();
return true;
},
mount: (body) =>
body.append(el("div", { className: "m02-hopyo-sheet", children: [left, right] })),
});
const paintGo = (): void => {
go.querySelector(".ui-btn__label")!.textContent = `고른 ${checked.size}개 불러오기`;
go.disabled = !checked.size;
};
/** 목록 강조 · 보이게(시트 고름은 그대로) */
function mark(no: number | null): void {
items.get(current ?? NaN)?.classList.remove("is-current");
current = no;
const row = items.get(no ?? NaN);
row?.classList.add("is-current");
row?.scrollIntoView({ block: "nearest" });
}
/** 호표 하나 강조 — 목록 · 시트 영역(같은 범위면 다시 안 부름) */
function focus(no: number): void {
mark(no);
const span = spans.find((h) => h.번 === no)?.행 ?? briefs.find((h) => h.번 === no)?.행;
if (!sheet || !span) return;
const text = spanText(span, last);
if (at.시트 !== ilwi || at.범위 !== text) sheet.select(text, ilwi);
}
function paintList(): void {
const q = search.value.trim().toLowerCase();
items.clear();
const shown = briefs.filter(
(h) => !q || `제${h.번}호표 ${h.이름} ${h.규격}`.toLowerCase().includes(q),
);
list.replaceChildren(
...shown.map((h) => {
const box = el("input", { attrs: { type: "checkbox" } }) as HTMLInputElement;
box.checked = checked.has(h.번);
box.hidden = !opt.canWrite;
box.addEventListener("click", (e) => e.stopPropagation());
box.addEventListener("change", () => {
if (box.checked) checked.add(h.번);
else checked.delete(h.번);
paintGo();
});
const row = el("div", {
className: `m02-hopyo-sheet__item${h.번 === current ? " is-current" : ""}`,
attrs: { "data-hopyo-no": String(h.번), title: `${h.이름} ${h.규격}`.trim() },
children: [
box,
el("span", { className: "m02-hopyo-sheet__no", text: `제${h.번}호표` }),
el("span", { className: "m02-hopyo-sheet__name", text: `${h.이름} ${h.규격}`.trim() }),
note(`${h.맞춤[0]}/${h.맞춤[1]}`),
],
});
row.addEventListener("click", () => focus(h.번));
items.set(h.번, row);
return row;
}),
);
count.textContent = q ? `${shown.length} / ${briefs.length}` : `호표 ${briefs.length}`;
}
search.addEventListener("input", paintList);
async function mountSheet(grid: HopyoGrid): Promise<void> {
const { createSpreadsheet } = await import("../A00_Common/spreadsheet/spreadsheet");
if (closed) return;
const book = structuredClone(grid.책);
const first = book.시트.find((s) => s.이름 === ILWI) ?? book.시트[0];
if (!first) return void left.replaceChildren(note("시트 없음"));
ilwi = first.id;
last = lastColumn(first);
book.활성 = first.id;
left.replaceChildren();
sheet = createSpreadsheet(left, book, {
readOnly: true,
onSelect: (s) => {
at = s;
if (s.시트 !== ilwi) return;
const no = hopyoAtRow(spans, Number(/\d+/.exec(s.칸)?.[0]));
if (no !== null && no !== current) mark(no);
},
});
// 칸을 눌러 뗌 → 그 호표 영역 고름(끌기 · 방향키 도중엔 안 바꿈)
left.querySelector(".ss-grid-host")?.addEventListener("mouseup", (e) => {
if ((e as MouseEvent).button !== 0 || at.시트 !== ilwi) return;
const no = hopyoAtRow(spans, Number(/\d+/.exec(at.칸)?.[0]));
if (no !== null) focus(no);
});
}
async function load(): Promise<void> {
try {
const [file, grid] = await Promise.all([
readHopyo(opt.scope, opt.key),
readHopyoGrid(opt.scope, opt.key).catch((error: unknown) => new Error(why(error))),
]);
if (closed) return;
briefs = file.호표;
spans = grid instanceof Error ? [] : grid.호표;
paintList();
if (grid instanceof Error) return void left.replaceChildren(note(grid.message));
await mountSheet(grid);
if (opt.단산행 !== undefined) sheet?.select(rowsText(opt.단산행), DANSAN);
else if (current !== null) focus(current);
} catch (error) {
if (!closed) left.replaceChildren(note(`못 읽음 — ${why(error)}`));
}
}
async function importPicked(): Promise<void> {
const nos = [...checked].sort((a, b) => a - b);
const target = opt.target ?? opt.scope;
const rows: HTMLElement[] = [];
let ok = 0;
go.disabled = true;
for (const no of nos) {
const h = briefs.find((x) => x.번 === no);
if (!h || closed) continue;
const head = el("td", { text: `제${no}호표 ${h.이름}`.trim() });
try {
const from = { 층: opt.scope.layer, 주인: opt.scope.owner, 키: opt.key, 번: no };
const got = await buildHopyo(target, from);
ok += 1;
opt.onImport?.(got, h);
rows.push(
el("tr", {
attrs: { "data-built": got.참조.키 },
children: [
head,
el("td", { text: `${got.참조.키} · ${builtWord(got, false)}` }),
el("td", { text: String(got.빠진줄.length), className: "m02-hopyo__num" }),
el("td", { text: won(got.비교.차이), className: "m02-hopyo__num" }),
],
}),
);
} catch (error) {
rows.push(el("tr", { children: [head, el("td", { text: `실패 — ${why(error)}` })] }));
}
result.replaceChildren(
el("table", {
className: "ui-general-block__table m02-hopyo__table",
children: [
el("thead", {
children: [
el("tr", {
children: ["호표", "사전조합", "빠진 줄", "값 차이"].map((t) =>
el("th", { text: t }),
),
}),
],
}),
el("tbody", { children: rows }),
],
}),
);
}
paintGo();
showToast(`불러옴 ${ok} / ${nos.length}`, ok === nos.length ? "success" : "warning");
}
go.addEventListener("click", () => void importPicked());
void load();
}