diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts index 7d64e9328..9a1a63499 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts @@ -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 => diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts index a1854f2b7..b7b2ef09b 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts @@ -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; - middles: NamedFormula[]; - /** 시험 계산 칸에 넣은 값 — 걸린 줄을 맞히는 데 씀 */ - values: Record; - /** 서버 `요소조각` — 단가 자리(요소 · 로직 부르기)를 조각으로 · 없으면 로직 키만 알약으로 */ - 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 | 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>(); -/** 자재품목 줄 하나(값 칸 넷) — 키로 찾음 · 한 번만 물음 */ -const marketRow = (ref: string): Promise => { - 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): 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, 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; -}): 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"), - ); - }); - }); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css deleted file mode 100644 index b919e6967..000000000 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css +++ /dev/null @@ -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); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts deleted file mode 100644 index 334421ba3..000000000 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts +++ /dev/null @@ -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; - }), - }); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css index 90ee00aa9..db6274746 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css @@ -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; } diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts index 3176231c2..d6002eea5 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts @@ -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"], diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Api.ts b/M01_MasterData/M01_MasterData_UI_Logic_Api.ts index 8667386d1..8685767a5 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Api.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Api.ts @@ -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; - result?: unknown; - middle: Record; - } - | { 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> => - request<{ 값?: Record }>(`/logic/auto?${query({ key })}`, undefined, paths.read) - .then((d) => d.값 ?? {}) - .catch(() => ({})); - -export const runCalc = (body: { - key: string; - inputs: Record; - row?: LogicRow; - file?: string; - /** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */ - 고름?: Record; -}): Promise => request("/calc", body, paths.calc); - -export const runText = (body: { - key: string; - inputs: Record; - row?: LogicRow; - file?: string; - /** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */ - 고름?: Record; -}): Promise => request("/text", body, paths.calc); - export const saveFiles = ( files: SaveFile[], 개정확인 = false, diff --git a/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts b/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts deleted file mode 100644 index 6220b6291..000000000 --- a/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts +++ /dev/null @@ -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, Map>(); -const picksOf = (values: Record): Map => { - let mine = chosen.get(values); - if (!mine) chosen.set(values, (mine = new Map())); - return mine; -}; - -/** 재료 고름(시험 입력 · 저장 안 함) — 고른 뒤 `again`(다시 셈) · 상세 표 줄 모달이 씀 */ -export function pickMaterial( - values: Record, - i: number, - it: Chosen, - again: () => void, -): void { - picksOf(values).set(i, it); - again(); -} - -/** 계산 요청 몸의 `고름` — 고른 것이 없으면 안 실음 */ -export function pickBody(values: Record): { 고름?: Record } { - 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, - values: Record, - 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, - lines: (CalcLine | undefined)[], -): void { - const mine = picksOf(values); - host.querySelectorAll("[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(); -async function machineRow(code: string): Promise { - 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, - 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] }); -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts b/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts deleted file mode 100644 index 80d7d5255..000000000 --- a/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts +++ /dev/null @@ -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; - onLines?: (lines: CalcLine[] | null) => void; - /** 읽는 식 줄(`/text`)도 같이 받고 싶을 때 — 호출이 `onLines` 보다 먼저 */ - onText?: (answer: TextAnswer) => void; -} - -/** 칸에 든 값 → 엔진 입력 — 빈 칸은 안 보냄(엔진이 「입력 없음」 으로 멈춤) · 고르기는 원래 값 그대로 */ -function inputsOf(row: LogicRow, values: Record): Record { - const inputs: Record = {}; - 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 { - 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; -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Note.ts b/M01_MasterData/M01_MasterData_UI_Logic_Note.ts index 9745429ad..67f94a796 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Note.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Note.ts @@ -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 { 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; -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Text.ts b/M01_MasterData/M01_MasterData_UI_Logic_Text.ts index 891a22684..e5b838867 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Text.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Text.ts @@ -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}", diff --git a/M01_MasterData/M01_MasterData_UI_Side.ts b/M01_MasterData/M01_MasterData_UI_Side.ts index 13789912e..ab5a94c1a 100644 --- a/M01_MasterData/M01_MasterData_UI_Side.ts +++ b/M01_MasterData/M01_MasterData_UI_Side.ts @@ -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 { diff --git a/M02_MasterTemplete/M02_Item_Copy.py b/M02_MasterTemplete/M02_Item_Copy.py index 889bfae4b..32940c06b 100644 --- a/M02_MasterTemplete/M02_Item_Copy.py +++ b/M02_MasterTemplete/M02_Item_Copy.py @@ -4,7 +4,7 @@ 복사본 = `{프로젝트}/templates/structures/{구조물 id}/` (`M02_Item_Snapshot`) · 길의 폴더 = 구조물 id. 파일마다 판 = 내용 해시 — 쓸 때 판이 다르면 `Stale`(409). 고치면 manifest 에 `고침` 을 남겨 지울 때 -`_지난/` 에 옮겨 둠. 옛 복사본(새 파일 없음) · 옛 항목 폴더는 읽을 때 채우고 옮겨 받음. +`_지난/` 에 옮겨 둠. 계산은 복사본만 씀(마스터 현재값 안 읽음) — 원본 항목이 바뀌거나 지워져도 그대로. """ @@ -29,10 +29,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( PICKS_FILE, VALUES_FILE, build_snapshot, - complete_old, folder_name, - items_dir, - migrate_items, now_text, retire, same_item, @@ -68,21 +65,13 @@ class Stale(ValueError): self.current = current -def _migrated(project_root: str | Path) -> Path: - """구조물 복사본 뿌리 — 옛 항목 폴더가 남았으면 먼저 옮겨 받음.""" - if items_dir(project_root).is_dir(): - migrate_items(project_root) - return structures_dir(project_root) - - def folder_of(project_root: str | Path, folder: str) -> Path: """구조물 복사본 폴더 — 이름 모양이 틀리거나 없으면 LookupError(404).""" if not FOLDER_PATTERN.match(folder): raise LookupError(f"복사본 폴더 이름 모양이 아님 「{folder}」") - target = _migrated(project_root) / folder + target = structures_dir(project_root) / folder if not (target / MANIFEST_NAME).is_file(): raise LookupError(f"복사본이 없음 「{folder}」") - complete_old(target) return target @@ -97,7 +86,7 @@ def source_changed(manifest: dict[str, Any]) -> bool | None: def list_items(project_root: str | Path, only: str | None = None) -> list[dict[str, Any]]: """복사본 목록 — `only` = 그 폴더 하나만(고르기 모달 · 원본 대조를 그 하나만 · 156-2).""" - base = _migrated(project_root) + base = structures_dir(project_root) out = [] for child in sorted(base.iterdir()) if base.is_dir() else []: if not child.is_dir() or not FOLDER_PATTERN.match(child.name): @@ -106,7 +95,6 @@ def list_items(project_root: str | Path, only: str | None = None) -> list[dict[s continue if not (child / MANIFEST_NAME).is_file(): continue - complete_old(child) manifest = read_json(child / MANIFEST_NAME) or {} origin = manifest.get("원본") or {} changed = source_changed(manifest) @@ -289,7 +277,7 @@ def prefetch(project_root: str | Path, owner_id: str, item: dict[str, Any]) -> d folder = folder_name(owner_id) if not FOLDER_PATTERN.match(folder): raise ValueError(f"구조물 id 모양이 아님 「{owner_id}」") - target = _migrated(project_root) / folder + target = structures_dir(project_root) / folder manifest = read_json(target / MANIFEST_NAME) made = not (isinstance(manifest, dict) and same_item(manifest, item)) if made: diff --git a/M02_MasterTemplete/M02_Item_Snapshot.py b/M02_MasterTemplete/M02_Item_Snapshot.py index cc9ebabaf..a6315b09e 100644 --- a/M02_MasterTemplete/M02_Item_Snapshot.py +++ b/M02_MasterTemplete/M02_Item_Snapshot.py @@ -13,8 +13,6 @@ - 지정을 다른 항목으로 바꾸면 새로 가져옴 · 구조물을 지우거나 지정을 풀면 복사본을 지움 — 프로젝트에서 고친 흔적(`manifest.고침`)이 있으면 지우지 않고 `_지난/` 에 옮겨 둠 - 관 지점을 옮겨도 같은 항목이면 폴더 이름만 바꿈(142-2) · 옵션 그룹 이름 · 가져온이도 굳힘 - - 옛 항목 폴더(`templates/items/{층}_{주인}_{키}/` · 25-2b)는 그 항목을 쓰는 구조물마다 복사해 - 옮겨 받음(고친 값 유지) """ from __future__ import annotations @@ -29,12 +27,11 @@ from B05_Profile.B05_Profile_Structures_Repository import load_structures from B05_Profile.B05_Profile_Structures_Schema import STRUCTURE_ID_RULE from common_util.common_util_drainage_pipes import pipe_points_path_in, read_pipe_points_file from common_util.common_util_json import atomic_write_json -from common_util.common_util_summary_item import GROUP_JOIN, snapshot_folder_name +from common_util.common_util_summary_item import GROUP_JOIN from common_util.common_util_time import kst_now, utc_now_text from M02_MasterTemplete import M02_Template_Layers as layers from M02_MasterTemplete.M02_Item_Source import ( LABOR_FILE, - PRICE_FILE, build_source, item_path, read_json, @@ -44,7 +41,6 @@ from M02_MasterTemplete.M02_Item_Source import ( logger = logging.getLogger(__name__) STRUCTURES_DIRNAME = "structures" -OLD_ITEMS_DIRNAME = "items" # 25-2b 항목 폴더 — 옮겨 받기만 PAST_DIRNAME = "_지난" # 고친 흔적이 있는 복사본을 지우지 않고 옮겨 두는 자리 MANIFEST_NAME = "manifest.json" VALUES_FILE = "입력값.json" # {로직키: {입력이름: {값, 확인}}} @@ -63,11 +59,6 @@ def structures_dir(project_root: str | Path) -> Path: return layers.project_dir(project_root) / STRUCTURES_DIRNAME -def items_dir(project_root: str | Path) -> Path: - """옛 항목 폴더 뿌리(25-2b) — 옮겨 받기에만 씀.""" - return layers.project_dir(project_root) / OLD_ITEMS_DIRNAME - - def folder_name(owner_id: str) -> str: """구조물 id → 복사본 폴더 이름 — id 없는 옛 구조물(`#차례`)은 `n차례`.""" return owner_id.replace("#", "n") @@ -195,42 +186,6 @@ def retire(folder: Path) -> str | None: return None -def migrate_items(project_root: str | Path) -> list[str]: - """옛 항목 폴더 → 그 항목을 쓰는 구조물마다 복사(고친 값 유지) — 옮겨 받은 구조물 폴더 이름. - - 다 옮긴 옛 폴더는 지움 · 쓰는 구조물이 없고 고친 흔적이 있으면 `structures/_지난/` 에 둠.""" - old = items_dir(project_root) - if not old.is_dir(): - return [] - base = structures_dir(project_root) - wanted = assignments(project_root) - moved: list[str] = [] - for child in sorted(p for p in old.iterdir() if p.is_dir()): - manifest = read_json(child / MANIFEST_NAME) - if not isinstance(manifest, dict): - continue - users = [o for o, item in wanted.items() if snapshot_folder_name(item) == child.name] - for owner in users: - target = safe_folder(base, folder_name(owner)) - if target is None or (target / MANIFEST_NAME).is_file(): - continue # 이미 새 복사본이 있음 - shutil.copytree(child, target, dirs_exist_ok=True) - origin = manifest.get("원본") or {} - atomic_write_json( - target / MANIFEST_NAME, - {**manifest, "원본": origin_of(origin), "구조물": [owner], "옮겨받음": now_text()}, - ) - moved.append(target.name) - if users or not manifest.get("고침"): - shutil.rmtree(child) - else: - (base / PAST_DIRNAME).mkdir(parents=True, exist_ok=True) - shutil.move(str(child), str(base / PAST_DIRNAME / f"items_{child.name}")) - if not any(old.iterdir()): - old.rmdir() - return moved - - def rename_moved(base: Path, wanted: dict[str, tuple[str, dict[str, Any]]]) -> list[str]: """관 지점을 옮긴 뒤 [저장] — 새 자리(`pipe@새 측점`)에 복사본이 없고 안 쓰게 된 옛 자리 복사본이 같은 항목 · 같은 그룹 꼬리면 폴더 이름만 바꿈(가까운 측점 먼저 · 142-2) — 가져온날 · @@ -313,9 +268,8 @@ def copied_groups( def sync_snapshots( project_root: str | Path, who: dict[str, Any] | None = None ) -> dict[str, list[str]]: - """구조물 복사본을 지정에 맞춤 — `{만듦, 지움, 못만듦, 옮겨받음, 이름바꿈}` 폴더 이름 · + """구조물 복사본을 지정에 맞춤 — `{만듦, 지움, 못만듦, 이름바꿈}` 폴더 이름 · `who` = 가져온이(manifest · 142-2).""" - moved = migrate_items(project_root) base = structures_dir(project_root) wanted = { folder_name(owner): (owner, item) for owner, item in assignments(project_root).items() @@ -357,7 +311,7 @@ def sync_snapshots( if child.is_dir() and not child.name.startswith("_") and child.name not in wanted: retire(child) removed.append(child.name) - out = {"만듦": made, "지움": removed, "못만듦": failed, "옮겨받음": moved} + out = {"만듦": made, "지움": removed, "못만듦": failed} return {**out, "이름바꿈": renamed} if renamed else out @@ -381,42 +335,6 @@ def safe_sync(project_root: str | Path, who: dict[str, Any] | None = None) -> li return ["*"] -def complete_old(folder: Path) -> bool: - """옛 복사본(21-3 · 새 파일 없음)을 채움 — 단가는 지금 원본에서 · 값은 빈 것. - - 옛 내용 파일(집계 · 도면 …)은 그대로 둠. 채웠으면 True(manifest 에 `옮겨받음` 날).""" - manifest = read_json(folder / MANIFEST_NAME) - if not isinstance(manifest, dict): - return False - lacking = [ - name for name in (PRICE_FILE, VALUES_FILE, PICKS_FILE) if not (folder / name).is_file() - ] - if not lacking and "원본판" in manifest: - return False - need_source = PRICE_FILE in lacking - try: - source = build_source(manifest["원본"]) if need_source else {} - except LookupError: - source = {} # 원본이 지워짐 — 빈 단가로(계산은 멈춤으로 알림) - for name in lacking: - atomic_write_json(folder / name, source.get(name, {})) - kept = { - name: read_json(folder / name) - for name in sorted(p.name for p in folder.glob("*.json")) - if name not in (MANIFEST_NAME, *LOCAL_FILES, "수식.json") # 수식 사본(802-4a) 원본판 밖 - } - atomic_write_json( - folder / MANIFEST_NAME, - { - **manifest, - "가져온날": manifest.get("가져온날") or manifest.get("적용일"), - "원본판": manifest.get("원본판") or version_of(kept), - "옮겨받음": manifest.get("옮겨받음") or now_text(), - }, - ) - return True - - #: 「연결된 사본」 부분 이름 → 파일(있는 것만 `부분` 에 담음) LINKED_PARTS = (("도면", "도면.json"), ("면적", "면적.json"), ("일위대가", LABOR_FILE)) @@ -446,8 +364,6 @@ def linked_snapshots(project_root: str | Path) -> dict[str, dict[str, Any]]: def read_snapshot(project_root: str | Path, owner_id: str) -> dict[str, Any] | None: - """그 구조물 복사본의 `집계.json`(`{줄, 열}`) — 없으면 None(옛 항목 폴더는 먼저 옮겨 받음).""" - if items_dir(project_root).is_dir(): - migrate_items(project_root) + """그 구조물 복사본의 `집계.json`(`{줄, 열}`) — 없으면 None.""" data = read_json(structures_dir(project_root) / folder_name(owner_id) / "집계.json") return data if isinstance(data, dict) else None diff --git a/resources/tester/helper_717_1_logic_api_paths.cjs b/resources/tester/helper_717_1_logic_api_paths.cjs index 56cb7baa9..02691f7cd 100644 --- a/resources/tester/helper_717_1_logic_api_paths.cjs +++ b/resources/tester/helper_717_1_logic_api_paths.cjs @@ -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}`); diff --git a/resources/tester/test_717_1_logic_lib.py b/resources/tester/test_717_1_logic_lib.py index 30544b017..906de3605 100644 --- a/resources/tester/test_717_1_logic_lib.py +++ b/resources/tester/test_717_1_logic_lib.py @@ -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 diff --git a/resources/tester/test_734_calc_buttons.py b/resources/tester/test_734_calc_buttons.py index 4c256f656..b6ce574b2 100644 --- a/resources/tester/test_734_calc_buttons.py +++ b/resources/tester/test_734_calc_buttons.py @@ -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 — 입력 칩(옵션 풍선)은 텍스트 수식과 함께 걷음 diff --git a/resources/tester/test_750_2_views_one_answer.py b/resources/tester/test_750_2_views_one_answer.py deleted file mode 100644 index 09aeaf4d8..000000000 --- a/resources/tester/test_750_2_views_one_answer.py +++ /dev/null @@ -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 # 셈 구동 = 화면 없이 diff --git a/resources/tester/test_799_2_old_tabs_gone.py b/resources/tester/test_799_2_old_tabs_gone.py index 3d484fe68..c547061de 100644 --- a/resources/tester/test_799_2_old_tabs_gone.py +++ b/resources/tester/test_799_2_old_tabs_gone.py @@ -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 diff --git a/resources/tester/test_item_copy_complete.py b/resources/tester/test_item_copy_complete.py index 23f08c5bb..046bf5f8d 100644 --- a/resources/tester/test_item_copy_complete.py +++ b/resources/tester/test_item_copy_complete.py @@ -300,23 +300,6 @@ def test_미리_가져오기(world): copies.prefetch(root, "../x", PIPE) -def test_옛_복사본은_읽을_때_채움(world): - root = world["root"] - _save(root, [_pipe()]) - folder = root / "templates/structures" / FOLDER - for name in ("입력값.json", "고른자재.json", "단가.json"): - (folder / name).unlink() - manifest = _read(folder / "manifest.json") - for key in ("원본판", "가져온날"): - manifest.pop(key) - (folder / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False), "utf-8") - assert copies.read_file(root, FOLDER, "입력값")["내용"] == {} - filled = _read(folder / "manifest.json") - assert filled["가져온날"] == filled["적용일"] and filled["옮겨받음"] - assert (folder / "단가.json").is_file() and copies.calc(root, FOLDER)["빠진입력"] - assert copies.list_items(root)[0]["마스터바뀜"] is False # 원본이 안 바뀐 옛 복사본 - - # ── 길 · 권한 ──────────────────────────────────────── @@ -489,26 +472,6 @@ def test_프로젝트에서_새_항목(world): copies.new_item(root, "c2", 3, 12, [], "", None) # 경로 · 이름 빈 값 -def test_옛_항목_폴더는_쓰는_구조물마다_옮겨_받음(world): - root = world["root"] - _save_all(root, [_wall("d1"), _wall("d2")], []) - base = root / "templates/structures" - old = root / "templates/items/system_none_SS000022" - old.parent.mkdir(parents=True) - shutil.move(str(base / "d1"), str(old)) - shutil.rmtree(base / "d2") - manifest = _read(old / "manifest.json") - manifest.update({"구조물": ["d1", "d2"], "고침": True}) - (old / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False), "utf-8") - (old / "입력값.json").write_text(json.dumps({"GF": {"a": {"값": 1}}}), "utf-8") - assert [i["폴더"] for i in copies.list_items(root)] == ["d1", "d2"] - assert not (root / "templates/items").exists() - for sid in ("d1", "d2"): - assert _read(base / sid / "입력값.json") == {"GF": {"a": {"값": 1}}} # 고친 값 유지 - assert _read(base / sid / "manifest.json")["구조물"] == [sid] - assert _save_all(root, [_wall("d1"), _wall("d2")], [])["만듦"] == [] - - def test_지정을_바꾸면_고친_옛_복사본은_지난에(world): root = world["root"] _save_all(root, [_wall("e1")], []) diff --git a/resources/tester/test_structures_summary_snapshot.py b/resources/tester/test_structures_summary_snapshot.py index 5b7c2b9f5..bae53e40a 100644 --- a/resources/tester/test_structures_summary_snapshot.py +++ b/resources/tester/test_structures_summary_snapshot.py @@ -129,7 +129,7 @@ def test_옛_파일은_칸_없음_그대로_읽고_씀(): def test_지정하면_폴더가_생기고_내용이_원본과_같음(world): root = world["root"] result = _save(root, [_dry(MS), _wet()], [_pipe(PIPE)]) - assert result == {"만듦": ["pipe@40.0", "st0"], "지움": [], "못만듦": [], "옮겨받음": []} + assert result == {"만듦": ["pipe@40.0", "st0"], "지움": [], "못만듦": []} folder = _items(root) / "st0" got = {path.name for path in folder.iterdir()} assert {