refactor(855-E 2-E1): M01 화면 옛 시험 계산 · 옛 상세 몸 부품 걷음

- 지움(부르는 곳 0 — 저장소 TS · cjs · py · html 다시 찾음): UI_Logic_Drive.ts(driveRun · autoFill) · UI_Logic_CalcPick.ts · UI_LogicLab_Pill.ts · .css
- Logic_Api: runCalc · runText · fetchAuto · searchPrice · CalcAnswer · TextAnswer · TextLine · TextPiece 걷음
- LogicLab_Modal: 옛 재료 · 표 · 참조 · 글 모달 걷음 — 로직 열기 · headWord 만 남김(−550 줄)
- Logic_Note.explain · Side.hasMasterJump · 죽은 CSS 다섯 · 글 키 29(옛 시험 계산 · 모달 · 알약) 걷음
- 시험: 지운 파일 글자만 보던 test_750_2(빈 파일 됨) · test_799_2 구동 시험 · test_734 알약 · 풍선 시험 지움 · helper_717_1 · test_717_1 의 /calc · /text · /logic/auto 화면 길 줄 걷음
- typecheck 0 · 관련 50 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 03:12:11 +09:00
co-authored by Claude Opus 5.5
parent 56650e0291
commit 9c78072971
17 changed files with 5 additions and 1164 deletions
@@ -10,7 +10,6 @@ import type { LogicRow } from "./M01_MasterData_UI_Logic_Api";
import { safeReason, tx } from "./M01_MasterData_UI_Logic_Text";
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
import "./M01_MasterData_UI_LogicLab_Style.css";
import "./M01_MasterData_UI_LogicLab_Pill.css";
/** 원문 절 머리 개정 연도 글 — [2008, 2020, 2025] → 「'08 · '20 · '25」(없으면 빈 글) */
const revisionText = (row: LogicRow): string =>
@@ -1,32 +1,9 @@
/* =============================================================================
* M01_MasterData_UI_LogicLab_Modal.ts
* 자료 모달 둘 —
* ① 줄 모달(`openMaterialModal`) — 줄을 누르면 그 줄의 단가(재료·인력·기계 또는 다른 로직)를
* 바로 보임(알약 목록 없이) · 그 아래 한 줄 풀이 + 원문 수량 식
* 재료 줄 = 위 물가 넷 가로(빈 칸 「-」 · 시험 계산이 쓴 값 굵게) + 후보 목록(찾기 · `onPick` 이면 누르면 고름)
* — 상세 표 줄 · 시험 계산 자재 칸이 같은 모달(711-2) · 기계 고르기는 `Logic_PickTable` 그대로
* ② 표 모달(`openTableModal`) — 수량 칸 안 알약(찾기(...) 표 참조)을 누르면 그 표만 보임
* 표는 표 그대로 + 지금 넣은 값으로 걸린 줄 강조 · 단일 값(단가)은 값과 출처
* 표 읽기 = `/elements` → `/table`(`Logic_Note.loadTable`) · 단가 = 로직 화면이 이미 받은 `prices`
* 로직 알약 → 그 로직 열기(로직 화면이 열기를 등록) · 재료 찾기 글 머리 낱말(`headWord`)
* — 옛 상세 몸 재료 · 표 모달은 855 2-E1 에 걷음(부르는 곳 0)
* ========================================================================== */
import { createButton, createInputField, el } from "@ui/ui_template_elements";
import { openModal } from "@ui/ui_template_modal";
import {
fetchMaterials,
searchElements,
type ElementBrief,
type NamedFormula,
} from "./M01_MasterData_UI_Logic_Api";
import { fetchRows, type Row } from "./M01_MasterData_Api_Fetch";
import { createStat, statGrid } from "@ui/ui_template_stat";
import { formatMoney, formatNumber, formatPrice } from "../common_util/common_util_money";
import { explain, loadTable, type TableRow } from "./M01_MasterData_UI_Logic_Note";
import { hasMasterJump, jumpToMaster, type MasterJump } from "./M01_MasterData_UI_Side";
import { fragmentRow, type Fragment } from "./M01_MasterData_UI_LogicLab_Pill";
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
import { createText } from "@ui/ui_template_text";
/** 로직 알약 → 그 로직 열기 — 로직 화면이 자기 열기를 등록 · 열려 있는 모달은 다 닫음 */
let logicOpener: (key: string) => void = () => {};
export const setLogicOpener = (fn: (key: string) => void): void => {
@@ -37,538 +14,9 @@ export function openLogic(key: string): void {
logicOpener(key);
}
/** 재료 고르기 조건(호표 줄 `요소` 가 글 대신 객체일 때) — 서버 `master_material.PICK_KEYS` 와 같은 칸 */
export interface PickCond {
구분?: string;
상세구분?: string;
이름?: string;
규격?: string;
대표?: string;
[extra: string]: unknown;
}
/** 서버가 `prices` 열쇠로 쓰는 조건 글 — 「구분|상세구분|이름|규격|대표|지역|계약종별」 */
export const condText = (cond: PickCond): string =>
["구분", "상세구분", "이름", "규격", "대표", "지역", "계약종별"]
.map((k) => String(cond[k] ?? ""))
.join("|") + (cond["검색어"] ? `|${cond["검색어"]}` : "");
/** 재료 모달 검색 칸 글 — 검색어 첫 낱말의 괄호 앞(「합판(내수) 12t」 → 「합판」) */
export const headWord = (text: unknown): string =>
String(text ?? "")
.trim()
.split(/\s+/)[0]
.replace(/[((].*$/, "");
/** 고르기 줄 후보 찾기 글 — 검색어 → 이름 → 상세구분 → 구분 차례 첫 낱말 */
export const seedOf = (cond: PickCond): string =>
[cond["검색어"], cond.이름, cond.상세구분, cond.구분].map(headWord).find(Boolean) ?? "";
export interface ModalTarget {
title: string;
/** 수량 식(호표 줄) · 덧줄은 그 식 */
expr: string;
/** 호표 줄의 단가 요소 키 — 덧줄은 없음 */
element?: string;
/** 재료 고르기 줄 — `element` 대신 조건 객체 · 잡힌 품목 단가 + 후보 목록을 보임 */
cond?: PickCond;
/** 호표 줄 단위 — 후보를 같은 단위 줄로만 거름 */
unit?: string;
prices: Record<string, ElementBrief | null>;
middles: NamedFormula[];
/** 시험 계산 칸에 넣은 값 — 걸린 줄을 맞히는 데 씀 */
values: Record<string, string>;
/** 서버 `요소조각` — 단가 자리(요소 · 로직 부르기)를 조각으로 · 없으면 로직 키만 알약으로 */
unitFrag?: Fragment[];
/** 서버가 입력으로 푼 단가 요소 키 · 글 — 자리 표시(`{…}`) 든 줄이 씀 */
unitRef?: string;
unitText?: string;
/** 서버 수량 조각 — 한 줄 풀이를 조각으로(알약 포함) · 없으면 식 풀이 글 */
qtyFrag?: Fragment[];
/** 호표 줄 종류 — 「재료」면 후보 목록(고르기 조건 줄이 아니어도) */
kind?: string;
/** 시험 계산이 쓴 값 칸(계산 답 `품목.값칸`) — 위 물가 넷 가운데 굵게 */
usedSlot?: string;
/** 있으면 후보 줄을 눌러 고름(시험 입력 · 저장 안 함) — 고르면 모달 닫힘 */
onPick?: (item: { ref: string; label: string }) => void;
/** 722-2 그 자리 고침 칸(맨 위) — 받는 것 = 모달 닫기 · 머리 단추 자리(닫기 왼쪽 · 748-1) */
edit?: (close: () => void, head: HTMLElement) => HTMLElement;
}
/** 수량 칸 표 알약 하나가 여는 자료 — 서버 조각 `참조`(키 · 행 · 열)가 곧 찾은 자리 */
export interface TableTarget {
title: string;
table: string;
/** 찾은 줄 — 찾기 조건(예 {구분: 합판}) · 줄의 키·원문번호 글 · 줄 차례(0부터) */
row?: Record<string, unknown> | string | number | null;
/** 찾은 값 칸 이름 */
col?: string | null;
}
const sameCond = (have: unknown, want: unknown, range: boolean): boolean => {
if (range && Array.isArray(have)) {
const n = Number(want);
const [low, high] = have as (number | null)[];
return (low == null || n >= low) && (high == null || n <= high);
}
return String(have) === String(want);
};
function tableView(table: TableRow, target: TableTarget): HTMLElement {
const lines = table.줄 ?? [];
const at = target.row;
const kinds = table.조건 ?? {};
const hit =
at === undefined || at === null
? null
: typeof at === "number"
? (lines[at] ?? null)
: typeof at === "string"
? (lines.find((line) => line["키"] === at || line["원문번호"] === at) ?? null)
: (lines.find((line) =>
Object.entries(at).every(([c, want]) => sameCond(line[c], want, kinds[c] === "범위")),
) ?? null);
const cols = [...Object.keys(table.조건 ?? {}), ...Object.keys(table.값칸 ?? {})];
const rows = lines.map((line) =>
el("tr", {
className: hit === line ? "m01lab__hit" : "",
attrs: hit === line ? { "data-hit": "1" } : {},
children: cols.map((c) =>
el("td", {
// 찾은 줄을 알면 그 줄의 칸만 · 줄을 못 받았으면(표 줄에 키가 없는 표) 값 칸 세로줄만 색
className: c === target.col && (hit === line || !hit) ? "m01lab__hit-cell" : "",
text: formatNumber(line[c]),
}),
),
}),
);
const use = table.용도
? [table.용도.공종, (table.용도.대상 ?? []).join("·")].filter(Boolean).join(" · ")
: "";
return el("div", {
className: "m01lab__data",
attrs: { "data-table": table.키 },
children: [
el("strong", { text: `${table.원문번호 ?? ""} ${table.이름 ?? table.키} · ${table.키}` }),
el("p", {
className: "ui-text ui-text--muted",
text: [`${tl("Modal_Source")} ${table.출처 ?? ""}`, use].filter(Boolean).join(" · "),
}),
el("p", {
className: "ui-text ui-text--muted",
text: hit ? tl("Modal_Hit") : target.col ? tl("Modal_ColOnly") : tl("Modal_NoHit"),
}),
goButton({ kind: "table", key: table.키 }),
el("div", {
className: "m01-logic__scroll",
children: [
el("table", {
className: "ui-table ui-table--data m01-logic__grid m01lab__table",
children: [
el("thead", {
children: [el("tr", { children: cols.map((c) => el("th", { text: c })) })],
}),
el("tbody", { children: rows }),
],
}),
],
}),
],
});
}
const groupOf = (ref: string): string =>
ref.startsWith("LB") ? "인력" : ref.startsWith("M") ? "재료" : ref.startsWith("EQ") ? "기계" : "";
function goButton(target: MasterJump): HTMLElement {
const go = createButton({
label: tl("Pill_Go"),
variant: "ghost",
onClick: () => jumpToMaster(target),
});
go.hidden = !hasMasterJump();
return go;
}
/** 자재품목 사급 값 칸 다섯 — 위 가로 줄(조달청은 뺌 · 830-2) */
const SLOTS = ["물가자료", "유통물가", "물가정보", "거래가격", "일반가격"];
const MARKET_FILE = "재료_자재품목.json";
const marketRows = new Map<string, Promise<Row | null>>();
/** 자재품목 줄 하나(값 칸 넷) — 키로 찾음 · 한 번만 물음 */
const marketRow = (ref: string): Promise<Row | null> => {
if (!marketRows.has(ref))
marketRows.set(
ref,
fetchRows(MARKET_FILE, 1, 5, ref)
.then((got) => got.rows.find((r) => r["키"] === ref) ?? null)
.catch(() => null),
);
return marketRows.get(ref)!;
};
/** 자재품목 줄 단가 — 이름 · 키 · 규격 + 물가 넷 가로(빈 칸 「-」 · 시험 계산이 쓴 값 굵게 · 모르면 낮은 값) */
function marketView(
ref: string,
brief: ElementBrief | null,
usedSlot?: string,
onValue?: (value: unknown) => void,
): HTMLElement {
const head = el("strong");
const spec = el("p", { className: "ui-text ui-text--muted" });
const slots = el("div");
const paint = (name: unknown, size: unknown, values: Record<string, unknown>): void => {
head.textContent = `${String(name ?? ref)} · ${ref}`;
spec.textContent = size ? `${tl("Modal_Spec")} ${String(size)}` : "";
spec.hidden = !size;
const nums = SLOTS.map((s) => values[s]).filter((v): v is number => typeof v === "number");
const used = SLOTS.includes(usedSlot ?? "")
? usedSlot
: SLOTS.find((s) => nums.length && values[s] === Math.min(...nums));
slots.replaceChildren(
statGrid(
SLOTS.map((s) => {
const card = createStat({
label: s,
value: values[s] === null || values[s] === undefined ? "-" : formatPrice(values[s]),
compact: true,
});
card.classList.toggle("is-used", s === used);
return card;
}),
),
);
if (used) onValue?.(values[used]);
};
paint(brief?.이름, brief?.규격, brief?.값들 ?? {});
if (!brief?.값들) void marketRow(ref).then((row) => row && paint(row["이름"], row["규격"], row));
return el("div", {
className: "m01lab__data m01lab__slots",
attrs: { "data-price": ref },
children: [
head,
spec,
slots,
goButton({ kind: "element", group: "재료", ref, file: brief?.file ?? MARKET_FILE }),
],
});
}
function priceView(ref: string, brief: ElementBrief, usedSlot?: string): HTMLElement {
if (ref.startsWith("MT")) return marketView(ref, brief, usedSlot);
const cols = Object.entries(brief.값칸 ?? {});
const slots = Object.entries(brief.값들 ?? {}).filter(([, v]) => v !== null && v !== undefined);
return el("div", {
className: "m01lab__data",
attrs: { "data-price": ref },
children: [
el("strong", { text: `${brief.이름 ?? ref} · ${ref}` }),
el("dl", {
className: "m01-logic__sums",
children: [
...(brief.규격
? [el("dt", { text: tl("Modal_Spec") }), el("dd", { text: brief.규격 })]
: []),
el("dt", { text: tl("Modal_Value") }),
el("dd", { className: "m01-logic__money", text: formatPrice(brief.값) }),
...(brief.file
? [el("dt", { text: tl("Modal_Source") }), el("dd", { text: brief.file })]
: []),
...cols.flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: String(v) })]),
...slots.flatMap(([k, v]) => [
el("dt", { text: k }),
el("dd", { className: "m01-logic__money", text: formatMoney(v) }),
]),
],
}),
goButton({ kind: "element", group: groupOf(ref), ref: brief.ref ?? ref, file: brief.file }),
],
});
}
/** 모달 겉틀(배경·닫기·포커스) — 몸은 `mount` 이 채움(닫기 함수도 받음) */
function openDialog(
title: string,
mount: (body: HTMLElement, close: () => void, head: HTMLElement) => void,
): void {
openModal({
title,
closeLabel: tl("Modal_Close"),
mount,
dialogClass: "m01-logic__pick m01lab__modal",
backdropClass: "m01-logic__backdrop",
});
}
const muted = (text: string): HTMLElement => el("p", { className: "ui-text ui-text--muted", text });
const free = (v: unknown): string => {
const text = String(v ?? "");
return text.includes("{") ? "" : text; // `{입력}` 자리는 계산 때 정해짐 — 거름에 안 씀
};
const squash = (v: unknown): string =>
String(v ?? "")
.replace(/\s+/g, "")
.toLowerCase();
/** 재료 줄 후보 목록 — 고르기 조건 안 후보(`/materials` · 단위 거름) · 조건이 없으면 이름 찾기 ·
* 찾기 칸 = 받은 후보 안에서 거름(없으면 재료 전체 이름 찾기) · 잡힌 품목(`pickedRef`) 노란 줄 맨 위 ·
* `onPick` 이면 줄을 누르면 고름 · 값은 위 가로 칸이 보여 목록엔 값 열 없음 */
function candidateView(target: ModalTarget, pickedRef: string, close: () => void): HTMLElement {
const cond = target.cond;
const sub = free(cond?.구분);
const list = el("div");
const count = el("strong");
const field = createInputField({ type: "search", placeholder: tl("Modal_Find") });
const box = el("div", {
className: "m01lab__data",
attrs: { "data-candidates": "1" },
children: [count, field.root, list],
});
list.append(muted("…"));
let base: ElementBrief[] = [];
const draw = (items: ElementBrief[], total: number): void => {
const sorted = [
...items.filter((it) => it.ref === pickedRef),
...items.filter((it) => it.ref !== pickedRef),
];
const more = total > items.length ? ` (${items.length})` : "";
count.textContent = `${tl(target.onPick ? "Modal_PickList" : "Modal_Candidates")} ${total}${more}`;
const rows = sorted.map((it) => {
const hit = it.ref === pickedRef;
const tr = el("tr", {
className: `${hit ? "m01lab__hit" : ""}${target.onPick ? " m01lab__pickrow" : ""}`,
attrs: { ...(hit ? { "data-hit": "1" } : {}), "data-ref": it.ref },
children: [
el("td", { text: it.이름 ?? it.ref }),
el("td", { text: it.규격 ?? "" }),
el("td", { text: String(it.단위 ?? "") }),
],
});
const onPick = target.onPick;
if (onPick)
tr.addEventListener("click", () => {
close();
onPick({ ref: it.ref, label: `${it.이름 ?? ""} ${it.규격 ?? ""}`.trim() || it.ref });
});
return tr;
});
list.replaceChildren(
rows.length
? el("div", {
className: "m01-logic__scroll m01lab__cands",
children: [
el("table", {
className: "ui-table ui-table--data m01-logic__grid m01lab__table",
children: [
el("thead", {
children: [
el("tr", {
children: [tl("Col_Name"), tl("Modal_Spec"), tl("Col_Unit")].map((h) =>
el("th", { text: h }),
),
}),
],
}),
el("tbody", { children: rows }),
],
}),
],
})
: muted(tl("Pill_NoPick")),
);
};
// 조건 없는 재료 줄 = 그 요소 이름 첫 낱말로 찾음(「모르타르, 서울 1:1」 → 「모르타르」)
const known = target.element ? target.prices[target.element] : null;
const seed = cond ? seedOf(cond) : headWord(known?.이름 ?? target.title).replace(/[,,].*$/, "");
const first = sub
? fetchMaterials({
sub,
detail: free(cond?.상세구분),
spec: free(cond?.규격),
unit: target.unit ?? "",
})
: searchElements("재료", seed);
let total = 0;
let timer = 0;
let seq = 0;
/** 찾기 칸 글로 거름 — 받은 후보 안에서 · 하나도 없으면 재료 전체 이름 찾기 */
const apply = (): void => {
const mine = ++seq;
const q = field.input.value.trim();
const words = q.split(/\s+/).map(squash).filter(Boolean);
if (!words.length) return draw(base, total);
const hits = base.filter((it) =>
words.every((w) => squash(`${it.이름 ?? ""} ${it.규격 ?? ""} ${it.ref}`).includes(w)),
);
if (hits.length) return draw(hits, hits.length);
void searchElements("재료", q)
.then((got) => mine === seq && draw(got.items, got.total))
.catch(() => undefined);
};
void first
.then((got) => {
base = got.items;
total = got.total;
field.input.value = sub ? free(cond?.["검색어"]) : ""; // 엔진이 고르는 검색어로 먼저 거름 · 지우면 조건 안 전부
apply();
})
.catch(() => list.replaceChildren(muted(tl("Pill_NoPick"))));
field.input.addEventListener("input", () => {
window.clearTimeout(timer);
timer = window.setTimeout(apply, 300);
});
return box;
}
/** 고르기 줄에서 시험 계산이 잡은 품목 키 — 대표가 `{입력이름}` 이면 넣은 값 · 글자 키면 그대로 · 없으면 서버 미리보기 줄 */
function pickedOf(cond: PickCond, values: Record<string, string>, fallback: string): string {
const rep = String(cond["대표"] ?? "");
const named = /^\{(.+)\}$/.exec(rep);
return (named ? (values[named[1]] ?? "") : rep) || fallback;
}
/** 줄을 눌렀을 때 — 그 줄의 단가(재료·인력·기계 또는 다른 로직)를 바로 보임(알약 없이) ·
* 재료 고르기 줄(`cond`)은 잡힌 품목 단가 + 후보 목록 */
export function openMaterialModal(target: ModalTarget): void {
openDialog(target.title, (body, close, head) => {
const cond = target.cond;
const element = target.element ?? "";
const base = element.split(".")[0];
// 고르기 줄 = 서버가 조건 글을 열쇠로 준 줄(대표가 안 정해졌으면 없음)
const priced = cond ? target.prices[condText(cond)] : undefined;
const known = cond
? target.unitRef && priced?.ref !== target.unitRef
? undefined // 서버가 잡은 품목이 다르면 그 품목으로
: priced
: element
? (target.prices[element] ?? target.prices[base])
: undefined;
const priceRef = cond
? target.unitRef || pickedOf(cond, target.values, known?.ref ?? "")
: element;
const logicKey = /^로직\((\w+)/.exec(element)?.[1] ?? "";
// 748-1 연결 키 = 제목 오른쪽 (괄호) · 고침 칸이 있으면 요소 단가 정보 칸은 없음(키 · 값은 제목 · 단가 칸에)
const key = logicKey || (cond ? priceRef : element.includes("{") ? target.unitRef : base);
if (key)
body
.closest(".ui-modal")
?.querySelector("h3")
?.append(el("span", { className: "m01lab__modalkey", text: ` (${key})` }));
const info = (ref: string, brief: ElementBrief, slot?: string): HTMLElement =>
target.edit && !ref.startsWith("MT") ? el("span") : priceView(ref, brief, slot);
const sum = el("p", { className: "m01lab__sum" });
const setSum = (price: ElementBrief | null | undefined): void => {
const unit = price ? `${tl("Modal_UnitPrice")} ${formatPrice(price.값)} × ` : "";
if (target.qtyFrag) {
sum.replaceChildren(`${target.title} = ${unit}`, fragmentRow(target.qtyFrag));
} else sum.textContent = `${target.title} = ${unit}${explain(target.expr)}`;
};
setSum(known);
const rate = el("div", { className: "m01lab__modal-body" });
/** `prices` 에 있으면 그대로 · 없으면 키로 찾아 옴 — 못 찾으면 「관리자 값 미확정」 */
const lookup = (ref: string, label: string): void => {
const show = (brief: ElementBrief | null): void => {
rate.replaceChildren(brief ? info(ref, brief) : muted(`${label} — ${tl("Pill_NoValue")}`));
setSum(brief);
};
rate.append(muted("…"));
const cached = target.prices[ref];
if (cached) show(cached);
else
void searchElements(groupOf(ref), ref)
.then((got) => show(got.items.find((it) => it.ref === ref) ?? null))
.catch(() => show(null));
};
if (known && priceRef) {
rate.append(info(priceRef, known, target.usedSlot));
} else if (logicKey) {
rate.append(
el("p", {
children: [
`${tl("Modal_Logic")} · `,
fragmentRow(
target.unitFrag ?? [
{ pill: { label: logicKey, onClick: () => openLogic(logicKey) } },
],
),
],
}),
);
} else if (cond && priceRef) {
// 서버가 잡은 품목 · 고른 품목 — 자재품목 줄을 키로 읽어 물가 넷
rate.append(
marketView(priceRef, null, target.usedSlot, (value) =>
setSum({ ref: priceRef, 값: value } as ElementBrief),
),
);
} else if (cond) {
rate.append(muted(tl("Pill_NoPick")));
} else if (element.includes("{")) {
// 자리 표시 든 요소 — 날글 대신 서버가 푼 키로 단가 · 못 풀면 입력 이름만
const ref = target.unitRef;
if (!ref) {
const names = [...element.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]).join(" · ");
rate.append(muted(`${target.unitText || names} — ${tl("Pill_Unresolved")}`));
} else lookup(ref, target.unitText ?? ref);
} else if (element) {
lookup(element, element); // 더한 줄(M02) 등 `prices` 에 없는 요소 — 키로 찾아 옴(725-4)
}
body.replaceChildren(
...(target.edit ? [target.edit(close, head)] : []),
rate,
...(cond || target.kind === "재료" ? [candidateView(target, priceRef, close)] : []),
muted(tl("Modal_Sum")),
sum,
el("details", {
className: "m01lab__raw",
children: [
el("summary", { text: tl("Modal_Qty") }),
el("pre", {
className: "m01lab__expr",
text: logicKey
? `${element}
${target.expr}`
: target.expr,
}),
],
}),
);
});
}
/** 수량 칸 요소 알약을 눌렀을 때 — 그 요소의 단가 자료(이미 받은 `prices` 에 없으면 키로 찾아 옴) */
export function openRefModal(target: {
title: string;
ref: string;
prices: Record<string, ElementBrief | null>;
}): void {
openDialog(target.title, (body) => {
const show = (brief: ElementBrief | null): void =>
body.replaceChildren(
brief ? priceView(target.ref, brief) : muted(`${target.ref} — ${tl("Pill_NoValue")}`),
);
const known = target.prices[target.ref];
if (known) return show(known);
body.replaceChildren(muted("…"));
void searchElements(groupOf(target.ref), target.ref)
.then((got) => show(got.items.find((it) => it.ref === target.ref) ?? null))
.catch(() => show(null));
});
}
/** 알약이 가리킬 자료를 못 찾을 때(참조 없음) · 다른 로직을 부르는 알약 — 한 마디만 */
export function openNoteModal(title: string, text: string): void {
openDialog(title, (body) => body.replaceChildren(el("p", { text })));
}
/** 수량 칸 표 알약을 눌렀을 때 — 그 표만 보임(걸린 줄 강조) */
export function openTableModal(target: TableTarget): void {
openDialog(target.title, (body) => {
body.replaceChildren(el("p", { className: "ui-text ui-text--muted", text: "…" }));
void loadTable(target.table).then((table) => {
body.replaceChildren(
table ? tableView(table, target) : createText(`${target.table} ?`, "error"),
);
});
});
}
@@ -1,16 +0,0 @@
/* 알약 = 단추 부품(보조 · 24) · 여기는 칸 폭 넘침만 */
.m01lab__pill {
max-width: 100%;
overflow-wrap: anywhere;
}
/* 계산 안 된 만약() 가지 조각 — 흐리게 */
.m01lab__qty-dim {
opacity: 0.45;
}
/* 표 모달 — 찾은 칸(참조.열) 한 번 더 진하게 */
td.m01lab__hit-cell,
.m01lab__hit td.m01lab__hit-cell {
background: color-mix(in srgb, orange 65%, transparent);
}
@@ -1,49 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_LogicLab_Pill.ts
* 알약 단추 — 수량 칸 안 조각(표 찾기 등)을 누르면 곧장 그 자료 모달을 엶.
* (이전에는 알약을 늘어놓고 아래 자리에서 펼쳤으나, 알약이 수량 칸 안으로 들어가며
* 「누르면 모달」 로 바뀜 — 모달 안에 알약 목록을 또 두지 않음.)
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import { createButton } from "@ui/ui_template_button";
import { tl } from "./M01_MasterData_UI_LogicLab_Text";
export interface Pill {
/** 알약 글 — 보기 「표 QF000421」 */
label: string;
/** 누르면 할 일 — 그 자료 모달을 엶 */
onClick: () => void;
}
/** 알약 하나 — 글자 조각 사이에 끼워 쓰는 단추 */
export function pillButton(p: Pill): HTMLButtonElement {
// 알약 = 요소 연결 단추(보조 · 낮은 20 · 정보색 갈래) — data-pill 은 시험 · 촬영이 잡음
const b = createButton({ label: p.label, variant: "ghost", size: 20, tone: "link" });
b.title = tl("Pill_Tone");
b.classList.add("m01lab__pill");
b.dataset.pill = p.label;
b.addEventListener("click", (ev) => {
ev.stopPropagation(); // 줄 전체 누르기(행 모달)와 안 겹치게
p.onClick();
});
return b;
}
/** 수량 칸 조각 — 알약 아니면 그냥 글자(연산기호·숫자·중간값 이름) · `dim` = 계산 안 된 갈래(흐리게) */
export type Fragment = { pill: Pill; dim?: boolean } | { text: string; dim?: boolean };
/** 조각을 이어 그림 — 칸 폭을 넘으면 자동으로 줄바꿈(`flex-wrap`) */
export function fragmentRow(fragments: Fragment[]): HTMLElement {
return el("span", {
className: "m01lab__qty-frags",
children: fragments.map((f) => {
const one =
"pill" in f
? pillButton(f.pill)
: el("span", { className: "m01lab__qty-text", text: f.text });
if (f.dim) one.classList.add("m01lab__qty-dim");
return one;
}),
});
}
@@ -42,42 +42,10 @@
word-break: break-all;
}
.m01lab__qty-frags {
display: inline-flex;
flex-wrap: wrap;
align-items: baseline;
gap: 2px 4px;
min-width: 0;
}
.m01lab__qty-text {
font-family: var(--font-mono, monospace);
font-size: var(--text-body-sm);
white-space: pre-wrap;
}
.m01lab__modal {
overflow: auto;
}
/* 748-1 모달 제목 오른쪽 연결 키 — 제목보다 가볍게 */
.m01lab__modalkey {
font-size: var(--text-body);
font-weight: var(--font-weight-regular, 400);
color: var(--color-text-secondary);
}
.m01lab__modal-body {
display: flex;
flex-direction: column;
gap: var(--spacing-8);
}
.m01lab__hit td {
background: color-mix(in srgb, gold 45%, transparent);
font-weight: 600;
}
.m01lab__calc > h3 {
display: none;
}
@@ -26,40 +26,7 @@ const TEXT = {
Col_Name: ["이름", "Name"],
Col_Unit: ["단위", "Unit"],
Modal_Close: ["닫기", "Close"],
Pill_Tone: ["요소 연결", "Linked element"],
Modal_Sum: ["한 줄 풀이", "In one line"],
Modal_UnitPrice: ["단가", "Unit price"],
Pill_Go: ["마스터 화면에서 보기", "Open in master"],
Pill_Back: ["← 단가산출 기초로 돌아가기", "← Back to unit-price logic"],
Pill_NoPick: [
"고르기 조건에 맞는 마스터 줄이 없음 — 단가를 못 찾음",
"No master row matches the pick conditions",
],
Pill_Unresolved: ["입력이 비어 풀리지 않음", "Not resolved — input empty"],
Pill_NoValue: ["관리자 값 미확보 — 마스터에 단가가 없음", "No price in master yet"],
Modal_Qty: ["수량 식", "Quantity formula"],
Modal_Value: ["값", "Value"],
Modal_Source: ["출처", "Source"],
Modal_Spec: ["규격", "Spec"],
Modal_Candidates: [
"후보 목록 (노란 줄 = 시험 계산이 쓰는 품목)",
"Candidates (yellow = used in the trial)",
],
Modal_PickList: [
"후보 목록 — 줄을 누르면 그 품목으로 시험 계산 (노란 줄 = 지금 쓰는 품목)",
"Candidates — click a row to use it in the trial (yellow = in use)",
],
Modal_Find: ["이름 · 규격으로 찾기", "Search by name or spec"],
Modal_Logic: ["다른 로직을 부름", "Calls another logic"],
Modal_Hit: ["노란 줄 = 지금 넣은 값으로 걸린 줄", "Highlighted row matches the trial values"],
Modal_ColOnly: [
"진한 칸 = 찾은 값 칸 — 서버가 줄 자리는 안 줌",
"Dark cells = the value column found; the server gave no row",
],
Modal_NoHit: [
"지금 값으로는 걸린 줄이 없음 — 값을 바꿔 보거나, 이 표를 안 쓰는 갈래일 수 있음",
"No row matches the current values — change them, or this table is on an unused branch",
],
Copy_Open: ["로직 복사/생성", "Copy / create logic"],
Copy_NeedOpen: ["먼저 로직을 고르세요", "Pick a logic first"],
Copy_Title: ["복사해서 만들기", "Copy to edit"],
@@ -123,66 +123,6 @@ export const pctView = (
x.율 == null
? { name: x.이름, qty: x.수량, unit: x.단위 }
: { name: x.규격 ? `${x.이름} (${x.규격})` : x.이름, qty: x.율, unit: "%" };
export type CalcAnswer =
| {
ok: true;
lines?: CalcLine[];
sums?: Record<string, number>;
result?: unknown;
middle: Record<string, unknown>;
}
| { ok: false; reason: string };
/** `/text` 줄의 조각 — 알약 글 = 조각 글 · `깊이` 있으면 계산 안 된 만약() 가지(흐리게) */
export interface TextPiece {
kind: "요소" | "표" | "로직" | "값" | "기호" | "글";
글: string;
/** 이름 조각(`kind: "값"` · 글 = 이름)이 가진 그 값 — 714-3 입력 단추 */
값?: string | number;
참조?: {
테이블?: string;
키: string;
행?: string | number | null;
줄?: number;
열?: string | null;
};
깊이?: number;
}
export interface TextLine {
이름: string;
글: string;
/** 같은 줄을 변수 이름으로 적은 식 — 왼쪽 칸 */
이름글?: string;
/** 수량 식을 쪼갠 조각 — 알약(요소·표·로직) · 글자(값·기호·글) */
조각?: TextPiece[];
/** 단가 자리(요소 · 로직 부르기)를 쪼갠 조각 — 줄 모달 윗줄 */
요소조각?: TextPiece[];
/** 줄 번호(답 전체에서 하나씩) — 두 칸 줄 맞춤 · 밝히기 */
짝?: number;
금액: number;
까닭?: string;
/** 714-1 계산서 줄 덧칸 — 쓰는 로직 입력 · 묶음(인력 · 재료 · 경비 · 하위) · 장비 · 찾는 표 기준 · 환산 근거 */
쓰는입력?: string[];
묶음?: string | null;
장비?: boolean | null;
기준단위?: string | null;
환산근거?: string;
/** (M02 750-1) SK 셈 답 줄 cid — 상세 줄과 이음 */
cid?: string;
/** (753-1) 옵션으로 빠진 줄(수량 0 이 만약 갈래 탓) — 화면은 그 줄을 안 그림(금액 · 차례 그대로) */
옵션꺼짐?: boolean;
}
/** `POST /text` 답 — 서버가 만든 읽는 식 줄(화면은 그대로 찍음) */
export type TextAnswer =
| {
ok: true;
groups: { 비목: string; 줄: TextLine[]; 소계: number; 끝수: string }[];
계: number;
/** (M02 750-1) 단위 환산 배 ≠ 1 — 식은 바탕 단위 · 금액 · 소계 · 계는 ÷배 */
나눔?: number;
}
| { ok: false; reason: string };
export interface SubBrief {
name: string;
book: string | null;
@@ -268,9 +208,6 @@ export const searchElements = (
): Promise<{ total: number; items: ElementBrief[] }> =>
request(`/elements?${query({ group, q, limit: "100" })}`, undefined, paths.read);
export const searchPrice = (q: string): Promise<{ total: number; items: ElementBrief[] }> =>
request(`/pick?${query({ kind: "price", q, limit: "100" })}`, undefined, paths.read);
export const fetchMaterials = (cond: {
sub: string;
detail?: string;
@@ -281,30 +218,6 @@ export const fetchMaterials = (cond: {
}): Promise<{ total: number; 기본: string | null; items: ElementBrief[] }> =>
request(`/materials?${query({ ...cond, limit: "100" })}`, undefined, paths.read);
/** 자동값 길(`GET /logic/auto`) — 입력 이름 → 견본값 · 서버에 아직 없거나 값이 없으면 빈 채로(화면은 그냥 안 채움) */
export const fetchAuto = (key: string): Promise<Record<string, unknown>> =>
request<{ 값?: Record<string, unknown> }>(`/logic/auto?${query({ key })}`, undefined, paths.read)
.then((d) => d.값 ?? {})
.catch(() => ({}));
export const runCalc = (body: {
key: string;
inputs: Record<string, unknown>;
row?: LogicRow;
file?: string;
/** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */
고름?: Record<string, string>;
}): Promise<CalcAnswer> => request("/calc", body, paths.calc);
export const runText = (body: {
key: string;
inputs: Record<string, unknown>;
row?: LogicRow;
file?: string;
/** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */
고름?: Record<string, string>;
}): Promise<TextAnswer> => request("/text", body, paths.calc);
export const saveFiles = (
files: SaveFile[],
개정확인 = false,
@@ -1,191 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_Logic_CalcPick.ts
* 시험 계산의 재료 · 기계 고르기 — 재료 칸마다 잡힌 품목 이름(누르면 고르기) · 기계 입력은 단추 하나
* 재료 = 상세 표 줄과 같은 재료 모달(`openMaterialModal` · 711-2) · 기계 = 마스터 표 모달(`PickTable`)
* 고른 재료는 `고름`(호표 줄 차례 → 키)에 실어 다시 계산 · 저장 안 함
* ========================================================================== */
import { createButton, el } from "@ui/ui_template_elements";
import { fetchRows, type Row } from "./M01_MasterData_Api_Fetch";
import type { CalcLine, ElementBrief, LogicInput, LogicRow } from "./M01_MasterData_UI_Logic_Api";
import { openPickTable } from "./M01_MasterData_UI_Logic_PickTable";
import { tx } from "./M01_MasterData_UI_Logic_Text";
import { condText, openMaterialModal, type PickCond } from "./M01_MasterData_UI_LogicLab_Modal";
interface Chosen {
ref: string;
label: string;
}
/** 로직마다 넣은 값(`values`)에 딸린 고른 재료 — 다시 그려도 남고 서버에는 계산 요청에만 실림 */
const chosen = new WeakMap<Record<string, string>, Map<number, Chosen>>();
const picksOf = (values: Record<string, string>): Map<number, Chosen> => {
let mine = chosen.get(values);
if (!mine) chosen.set(values, (mine = new Map()));
return mine;
};
/** 재료 고름(시험 입력 · 저장 안 함) — 고른 뒤 `again`(다시 셈) · 상세 표 줄 모달이 씀 */
export function pickMaterial(
values: Record<string, string>,
i: number,
it: Chosen,
again: () => void,
): void {
picksOf(values).set(i, it);
again();
}
/** 계산 요청 몸의 `고름` — 고른 것이 없으면 안 실음 */
export function pickBody(values: Record<string, string>): { 고름?: Record<string, string> } {
const mine = picksOf(values);
return mine.size
? { 고름: Object.fromEntries([...mine].map(([i, c]) => [String(i), c.ref])) }
: {};
}
const nameOf = (row: Row): string => `${row["이름"] ?? ""} ${row["규격"] ?? ""}`.trim();
const MATERIAL_KEYS = /^MT\d{6}$/;
const MACHINE_CODE = /^\d{4}-\d{4}$/;
const MACHINE_KEY = /^EQ\d{6}$/;
/** 재료 키 목록 입력 — 표 모달로 바뀌어 걷음 */
export const isMaterialKeyInput = (spec: LogicInput): boolean =>
!!spec.고르기?.length && spec.고르기.every((o) => MATERIAL_KEYS.test(String(o)));
const isMachineInput = (spec: LogicInput): boolean =>
!!spec.고르기?.length &&
spec.고르기.every((o) => MACHINE_CODE.test(String(o)) || MACHINE_KEY.test(String(o)));
const pickButton = (label: string, onClick: () => void): HTMLButtonElement =>
createButton({ label, variant: "ghost", onClick });
/** 자재 칸 — 이름 + 잡힌 품목(누르면 고르기 모달) · 긴 이름은 두 칸 */
const line = (label: string, current: HTMLElement): HTMLElement =>
el("div", {
className: `m01-logic__field${label.length > 10 ? " m01-logic__field--wide" : ""}`,
children: [el("span", { text: label }), current],
});
/** 재료 줄마다 한 칸 — 지금 잡힌 품목 + 품목 고르기 */
export function materialRows(
row: LogicRow,
prices: Record<string, ElementBrief | null>,
values: Record<string, string>,
again: () => void,
): HTMLElement[] {
const mine = picksOf(values);
return (row.호표 ?? [])
.map((item, i) => ({ item, i }))
.filter((x) => x.item.종류 === "재료")
.map(({ item, i }) => {
const cond =
typeof item.요소 === "object" && item.요소 !== null
? (item.요소 as unknown as PickCond)
: null;
const brief = (cond ? prices[condText(cond)] : prices[item.요소]) ?? null;
const named = item.이름 && !/^[A-Z]{2}\d{6}/.test(item.이름) ? item.이름 : "";
const label = named || (brief?.이름 as string | undefined) || "";
const held = mine.get(i);
const nowName =
held?.label ?? (brief ? `${brief.이름 ?? ""} ${brief.규격 ?? ""}`.trim() : "") ?? "";
// 잡힌 품목 이름 = 링크 단추 — 누르면 고르기 모달([품목 고르기] 단추 걷음)
const current = createButton({
label: nowName || tx("Mat_NoPrice"),
variant: "link",
onClick: () => pick(),
});
current.dataset.matIdx = String(i);
current.dataset.ref = brief?.ref ?? "";
current.title = tx("Pick_Item");
const title = `${label}${item.규격 ? ` ${item.규격}` : ""}`;
const pick = (): void =>
openMaterialModal({
title,
expr: item.수량,
...(cond ? { cond } : { element: item.요소 }),
unit: item.단위,
kind: "재료",
prices,
middles: row.중간 ?? [],
values,
unitRef: mine.get(i)?.ref || current.dataset.ref || undefined,
usedSlot: current.dataset.slot || undefined,
onPick: (it) => {
mine.set(i, it);
current.textContent = it.label;
again();
},
});
return line(title, current);
});
}
/** 계산 답의 `품목` 을 잡힌 품목 글로 — 고른 재료가 있는 줄은 그대로 */
export function showItems(
host: HTMLElement,
values: Record<string, string>,
lines: (CalcLine | undefined)[],
): void {
const mine = picksOf(values);
host.querySelectorAll<HTMLElement>("[data-mat-idx]").forEach((span) => {
const i = Number(span.dataset.matIdx);
const item = lines[i]?.품목;
span.dataset.slot = item?.값칸 ?? ""; // 시험 계산이 쓴 값 칸 — 모달 위 가로 칸 굵게
if (!item || mine.has(i)) return;
span.dataset.ref = item.키;
span.textContent = `${item.이름 ?? ""} ${item.규격 ?? ""}`.trim() || item.키;
});
}
/** 기계 입력 칸 — 표 모달로 고르면 입력값(원문 분류번호 · 키 목록이면 키) */
const machines = new Map<string, Row | null>();
async function machineRow(code: string): Promise<Row | null> {
if (!machines.has(code)) {
let found: Row | null = null;
try {
const got = await fetchRows("기계.json", 1, 5, code);
found = got.rows.find((r) => r["원문번호"] === code || r["키"] === code) ?? null;
} catch {
found = null;
}
machines.set(code, found);
}
return machines.get(code) ?? null;
}
export function machineControl(
spec: LogicInput,
values: Record<string, string>,
again: () => void,
): HTMLElement | null {
if (!isMachineInput(spec)) return null;
const current = el("span", { className: "ui-text ui-text--muted" });
const paint = (): void => {
const code = values[spec.이름] ?? "";
const known = machines.get(code);
current.textContent = `${code ? `${code}${known ? ` · ${nameOf(known)}` : ""}` : tx("Mat_NoPrice")} `;
if (code && !machines.has(code)) void machineRow(code).then(paint);
};
paint();
const button = pickButton(tx("Pick_Machine"), () => {
const code = values[spec.이름] ?? "";
const known = machines.get(code);
openPickTable({
kind: "기계",
title: `${tx("Pick_Machine")} · ${spec.이름}`,
seed: String(known?.["이름"] ?? spec.이름),
isCurrent: (r) => !!code && (r["원문번호"] === code || r["키"] === code),
onPick: (r) => {
const useKey = MACHINE_KEY.test(String(spec.고르기?.[0]));
const value = String(useKey ? r["키"] : r["원문번호"]);
machines.set(value, r);
values[spec.이름] = value;
paint();
again();
},
});
});
return el("div", { children: [current, button] });
}
@@ -1,76 +0,0 @@
/* =============================================================================
* M01_MasterData_UI_Logic_Drive.ts
* 셈 구동(PLAN 799-2) — 화면 없이 「입력값 → 서버 셈 → 답」을 돌림. 시험 계산 칸(`Logic_Calc`)이 씀
* `driveRun` = 한 번 셈(`/calc` + `/text`) · `autoFill` = 자동값 채움 — 로직 상세 구동은 840-1 에 걷음
* 셈 자리 = 서버(CLAUDE.md 5 장 ③) · 화면 · sessionStorage 없음 · 고른 재료(`CalcPick`) 는 값 객체에 딸림
* ========================================================================== */
import {
fetchAuto,
runCalc,
runText,
type CalcAnswer,
type CalcLine,
type LogicRow,
type TextAnswer,
} from "./M01_MasterData_UI_Logic_Api";
import { pickBody } from "./M01_MasterData_UI_Logic_CalcPick";
export interface DriveContext {
/** 저장된 키 — 새 로직은 null */
savedKey: string | null;
/** 저장 전 새 초안이면 비움 — 서버가 임시 자리에 얹어 셈 */
file?: string;
row: LogicRow;
dirty: () => boolean;
/** 로직마다 넣은 값 — 다시 그려도 남음 */
values: Record<string, string>;
onLines?: (lines: CalcLine[] | null) => void;
/** 읽는 식 줄(`/text`)도 같이 받고 싶을 때 — 호출이 `onLines` 보다 먼저 */
onText?: (answer: TextAnswer) => void;
}
/** 칸에 든 값 → 엔진 입력 — 빈 칸은 안 보냄(엔진이 「입력 없음」 으로 멈춤) · 고르기는 원래 값 그대로 */
function inputsOf(row: LogicRow, values: Record<string, string>): Record<string, unknown> {
const inputs: Record<string, unknown> = {};
for (const spec of row.입력 ?? []) {
const raw = (values[spec.이름] ?? "").trim();
if (raw === "") continue;
const option = spec.고르기?.find((o) => String(o) === raw); // 글 "35" 로 보내면 「고르기 밖」
inputs[spec.이름] =
option !== undefined ? option : Number.isNaN(Number(raw)) ? raw : Number(raw);
}
return inputs;
}
const draftBody = (ctx: DriveContext): { row?: LogicRow; file?: string } =>
ctx.dirty() || ctx.savedKey === null ? { row: ctx.row, file: ctx.file } : {};
/** 한 번 셈 — 답을 `onText` → `onLines` 차례로 알리고 돌려줌(`draft` = 저장 전 고침으로 셈) */
export async function driveRun(
ctx: DriveContext,
inputs = inputsOf(ctx.row, ctx.values),
): Promise<{ answer: CalcAnswer; draft: boolean }> {
const draft = ctx.dirty() || ctx.savedKey === null;
const body = {
key: ctx.savedKey ?? ctx.row.키,
inputs,
...pickBody(ctx.values),
...draftBody(ctx),
};
const answer = await runCalc(body);
if (ctx.onText) ctx.onText(await runText(body));
ctx.onLines?.(answer.ok ? (answer.lines ?? null) : null);
return { answer, draft };
}
/** 자동값으로 빈 칸 채움 — 채웠으면 true */
export async function autoFill(ctx: DriveContext): Promise<boolean> {
if (ctx.savedKey === null) return false;
const auto = await fetchAuto(ctx.savedKey);
const names = (ctx.row.입력 ?? [])
.map((spec) => spec.이름)
.filter((n) => auto[n] !== undefined && auto[n] !== null && !(ctx.values[n] ?? "").trim());
for (const n of names) ctx.values[n] = String(auto[n]);
return names.length > 0;
}
+1 -64
View File
@@ -1,6 +1,6 @@
/* =============================================================================
* M01_MasterData_UI_Logic_Note.ts
* 원문 표 읽기(`loadTable`) · 식 쉬운 말 풀이(`explain`).
* 원문 표 읽기(`loadTable`) — 식 쉬운 말 풀이는 옛 상세 몸과 같이 걷음(855 2-E1).
*
* 순수 읽기 — `/elements` 로 표 파일을 찾고 `/table` 로 통째 읽음.
* ========================================================================== */
@@ -54,66 +54,3 @@ export function loadTable(key: string): Promise<TableRow | null> {
tableCache.set(key, job);
return job;
}
/* ── 식 속 찾기(표, 조건...).칸 ──────────────────────────────────────── */
const FIND_RE = /찾기\(\s*([A-Za-z0-9_]+)\s*,([^)]*)\)\s*\.\s*([A-Za-z0-9_가-힣]+)/g;
function splitConds(raw: string): [string, string][] {
return raw
.split(",")
.map((p) => p.trim())
.filter(Boolean)
.map((p): [string, string] => {
const i = p.indexOf("=");
return i < 0 ? [p, p] : [p.slice(0, i).trim(), p.slice(i + 1).trim()];
});
}
/* ── 쉬운 말 풀이 — 찾기()/만약() 을 문장으로, 안 되면 식 그대로 ─────────── */
function splitTop(s: string): string[] {
const out: string[] = [];
let depth = 0;
let cur = "";
for (const ch of s) {
if (ch === "(") depth++;
if (ch === ")") depth--;
if (ch === "," && depth === 0) {
out.push(cur);
cur = "";
} else cur += ch;
}
out.push(cur);
return out;
}
function expandIf(expr: string): string {
const at = expr.indexOf("만약(");
if (at < 0) return expr;
let depth = 0;
let j = at + 2; // "만약(" 의 '(' 자리
for (; j < expr.length; j++) {
if (expr[j] === "(") depth++;
else if (expr[j] === ")") {
depth--;
if (depth === 0) {
j++;
break;
}
}
}
const [cond, then, els] = splitTop(expr.slice(at + 3, j - 1)).map((p) => p.trim());
const said = `(${expandIf(cond)} 이면 ${expandIf(then)}, 아니면 ${expandIf(els ?? "")})`;
return expandIf(expr.slice(0, at) + said + expr.slice(j));
}
export function explain(expr: string): string {
const withFind = expr.replace(FIND_RE, (_all, table: string, conds: string, col: string) => {
const cs = splitConds(conds)
.map(([, rhs]) => rhs)
.join(" · ");
return `[${table} 표에서 ${cs} 에 맞는 「${col}」]`;
});
return expandIf(withFind).trim() || expr;
}
@@ -35,14 +35,8 @@ const TEXT = {
Head_Owner: ["소유", "Owner"],
Head_Note: ["비고", "Note"],
Head_Blocked: ["막힌 까닭", "Why blocked"],
Ho_Title: ["호표", "Unit-cost lines"],
Ho_Qty: ["수량", "Qty"],
Ho_Amount: ["금액", "Amount"],
Middle_Title: ["중간 값", "Intermediate values"],
Formula: ["식", "Formula"],
Calc_Title: ["시험 계산", "Test calculation"],
Calc_Run: ["계산", "Calculate"],
Calc_NoInputs: ["받을 값 없음", "No inputs"],
Calc_Draft: ["고친 줄로 계산(저장 전)", "Using unsaved edits"],
Calc_NoDoc: [
"수식 문서로 못 바꿈 — 고친 식을 확인하세요",
@@ -50,14 +44,9 @@ const TEXT = {
],
Calc_Stopped: ["멈춤", "Stopped"],
Calc_Result: ["결과", "Result"],
Calc_Sum: ["계", "Total"],
Pick_Title: ["요소 찾기", "Find element"],
Pick_Search: ["이름·키·원문번호", "Name · key · source no."],
Pick_Item: ["품목 고르기", "Pick item"],
Pick_Machine: ["기계 고르기", "Pick machine"],
Calc_UnitWarn: ["단위 다름", "Unit differs"],
Pick_Close: ["닫기", "Close"],
Mat_NoPrice: ["단가 없음", "No price"],
Save_Done: ["저장했음", "Saved"],
Save_Stale: [
"그 사이 파일이 바뀜 — 고친 것을 버리고 다시 여세요: {v}",
-1
View File
@@ -84,7 +84,6 @@ export const setMasterJump = (fn: (target: MasterJump) => void): void => {
masterJump = fn;
};
export const jumpToMaster = (target: MasterJump): void => masterJump?.(target);
export const hasMasterJump = (): boolean => masterJump !== null; // 등록 없으면(M02) 이동 단추 숨김
/** 요소 화면에서 열 것 — 파일 · 하위 거름(구분·세부분류) · 상세구분 · 제목 */
export interface Pick {
@@ -24,11 +24,8 @@ const note = load("M01_MasterData", "M01_MasterData_UI_Logic_Note.ts");
async function round(tag) {
await api.fetchLogic("K");
await api.fetchAuto("K");
await api.searchElements("재료", "q");
await api.fetchMaterials({ sub: "s" });
await api.runCalc({ key: "K", inputs: {} });
await api.runText({ key: "K", inputs: {} });
await rows.fetchRows("기계.json", 1, 5, "q");
await rows.fetchPick("price", "q");
await note.loadTable(`T-${tag}`);
+1 -5
View File
@@ -35,11 +35,7 @@ def test_길_주입_없으면_m01_있으면_넘긴_길() -> None:
assert out["before"] == out["after"] # 안 넘기면 지금 그대로
assert all(u.startswith("/m01/") for u in out["before"])
shared, admin = out["injected"][:-2], out["injected"][-2:]
assert all(u.startswith(("/m02/logic-lib/", "/m02/calc-x/")) for u in shared)
assert [u for u in shared if u.startswith("/m02/calc-x/")] == [
"/m02/calc-x/calc",
"/m02/calc-x/text",
]
assert all(u.startswith("/m02/logic-lib/") for u in shared)
assert admin == ["/m01/groups/g/files", "/m01/save"] # 관리자 · 저장 길은 늘 M01
-10
View File
@@ -10,19 +10,9 @@ def _t(p: Path) -> str:
return p.read_text(encoding="utf-8")
def test_알약은_낮은_단과_요소연결_갈래():
s = _t(M01 / "M01_MasterData_UI_LogicLab_Pill.ts")
assert 'size: 20, tone: "link"' in s and 'tl("Pill_Tone")' in s
def test_갈래_색은_공통_값만():
css = _t(ROOT / "ui_template" / "ui_template_button.css")
head = css[css.index("갈래 색(tone)") :]
assert '[data-tone="option"]' in head and "var(--color-warning)" in head
assert '[data-tone="link"]' in head and "var(--color-info)" in head
assert "#" not in head.split("*/", 1)[1] # 날 색 값 없음
def test_풍선_글_두_갈래():
s = _t(M01 / "M01_MasterData_UI_LogicLab_Text.ts")
assert '"요소 연결"' in s # 799-2 — 입력 칩(옵션 풍선)은 텍스트 수식과 함께 걷음
@@ -1,17 +0,0 @@
"""750-2 화면 — 수식 · 단가산출 상세가 SK 셈 답 하나로(바탕 M01 로직 따로 셈 길 걷음 · 799-2 시험 계산 보기는 걷음) · 재료 고름 = 문서 `고름` ·
읽는 식 줄 = cid 로 이음 · 옵션 바꿈 = SK 셈 한 번(원문 대조는 서버 test_750_1)."""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def _ts(rel: str) -> str:
return (ROOT / rel).read_text("utf-8")
def test_calc_drive_is_screenless_and_m02_has_no_calc_hook():
ts = _ts("M01_MasterData/M01_MasterData_UI_Logic_Calc.ts")
assert "ctx.answer" not in ts and "CalcShown" not in ts # 799-2 M02 시험 계산 길 걷음
drive = _ts("M01_MasterData/M01_MasterData_UI_Logic_Drive.ts")
assert "runCalc(body)" in drive and "document." not in drive # 셈 구동 = 화면 없이
+1 -14
View File
@@ -65,20 +65,7 @@ def test_보기는_수식_하나_고르기_없음():
assert "data-view" not in css and "data-block" not in css # 840-1 보기 고르기 규칙 걷음
def test_셈_구동은_화면_없이_상세는_구동만():
drive = _text(M01 / "M01_MasterData_UI_Logic_Drive.ts")
assert "document." not in drive and "sessionStorage." not in drive
assert "export async function driveRun(" in drive and "createDrive" not in drive # 840-1
lab = _text(M01 / "M01_MasterData_UI_LogicLab.ts")
assert "createDrive" not in lab and "buildCalc" not in lab and "data-calc-run" not in lab
detail = _text(M01 / "M01_MasterData_UI_LogicLab_Detail.ts")
assert "calcHost" not in detail and "data-calc-run" not in detail and "rerun" not in detail
m02 = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
assert "buildCalc" not in m02 and "calcHost" not in m02
def test_파일_700줄_안():
for p in (M01 / "M01_MasterData_UI_LogicLab.ts", M01 / "M01_MasterData_UI_LogicLab_Detail.ts",
M02 / "M02_MasterTemplete_Sangeun_Detail.ts", M02 / "M02_MasterTemplete_Sangeun_Tabs.ts",
M01 / "M01_MasterData_UI_Logic_Drive.ts"): # fmt: skip
M02 / "M02_MasterTemplete_Sangeun_Detail.ts", M02 / "M02_MasterTemplete_Sangeun_Tabs.ts"): # fmt: skip
assert len(_text(p).splitlines()) <= 700, p.name