diff --git a/A00_Common/line_stack_edit.ts b/A00_Common/line_stack_edit.ts index b68e5e8d6..61f53f667 100644 --- a/A00_Common/line_stack_edit.ts +++ b/A00_Common/line_stack_edit.ts @@ -10,6 +10,7 @@ * 고르면 줄이 생김(닫으면 안 생김) · 있는 줄 = 자원 이름 단추 * ========================================================================== */ +import type { PlacedTable } from "../common_util/common_util_show_digits"; import { createBadge } from "@ui/ui_template_badge"; import { createButton, createIconButton, setUiDiff } from "@ui/ui_template_button"; import { createRowMenu } from "@ui/ui_template_context_menu"; @@ -93,6 +94,8 @@ export interface EditHooks { lists?: (given: Record) => Record | null; /** 845-2 표 한 칸 읽기(캐시) — 「줄 따름」 값의 고른 줄 단위 */ look?: TableLook; + /** 859-3 캐시 표 통째 — 표 값의 원문 글자 자리(보이는 자리) */ + tableCache?: (ref: string) => PlacedTable | undefined; /** 846-2 그 기계 작업량 줄 */ work?: (machine: string) => WorkSpec[]; /** 848-3 ① 위 층 고침(SK 읽기 답 `위덮음` · M01 = 없음) */ diff --git a/A00_Common/line_stack_out.ts b/A00_Common/line_stack_out.ts index 12e322924..3873a1e92 100644 --- a/A00_Common/line_stack_out.ts +++ b/A00_Common/line_stack_out.ts @@ -59,8 +59,9 @@ import { } from "../common_util/common_util_line_stack_unit"; import { workAt } from "../common_util/common_util_line_stack_work"; import { workKey } from "../common_util/common_util_formula_doc_work"; +import { showValue } from "../common_util/common_util_show_digits"; import { partName, partUnit } from "../common_util/common_util_machine_symbol_name"; -import { katexNode, symTex, tex, txt, valTex, type TexCtx } from "./line_stack_tex"; +import { katexNode, symTex, tex, txt, type TexCtx } from "./line_stack_tex"; import { lt } from "./line_stack_text"; import { workQty, workRows } from "./line_stack_work"; @@ -143,9 +144,14 @@ function rows( const alias = tableAlias(doc); // 표 값 기호 화면 이름(요구 683) const machine = doc.부품?.갈래 === "기계경비식"; // 845-2 한 줄 분수 한 층(중간 줄로 나눔) const taken = new Set([...vars.keys(), ...lines.keys(), ...Object.values(alias)]); - /** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 */ + /** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 · 그 밖 = 보이는 자리 규칙(859-3) */ const code = (id: string): boolean => /^S(_|$)/.test(id); - const numText = (id: string, v: number): string => (code(id) ? String(v) : eqText(v)); + const numText = (id: string, v: unknown, u?: string): string => { + if (code(id)) return String(v); + return showValue(doc, id, v, vals, h.cache.tableOf, u); + }; + /** 조판 값 글(천 자리 쉼표 = TeX 「{,}」) */ + const show = (id: string, v: unknown): string => numText(id, v).replace(/,/g, "{,}"); /** 식 줄 「기호 = 기호식 = 값식 = 결과 단위」 — 같은 꼴이 이어지면 한 번만(만약이 수 하나를 탄 줄) */ const formula = ( id: string, @@ -156,13 +162,13 @@ function rows( more: Partial, ): (string | HTMLElement)[] => { const res = isNum(v) - ? katexNode(`${code(id) ? String(v) : valTex(v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음) + ? katexNode(`${show(id, v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음) : typeof v === "string" // 글 값(기계 원문번호 등 · 838-3) = 그 글 · 기계면 이름 ? el("span", { text: machineText(v, () => h.redraw?.()) ?? v }) : missing(a, id); const sym = tex(n, { side: "sym", vals: vs, alias, ...more }); - const val = tex(n, { side: "val", vals: vs, alias, ...more }); - const same = isNum(v) && val === valTex(v); + const val = tex(n, { side: "val", vals: vs, alias, show, ...more }); + const same = isNum(v) && val === show(id, v); return [ katexNode(symTex(alias[id] ?? id)), ...(sym === val ? [] : [" = ", katexNode(sym)]), @@ -342,7 +348,7 @@ function rows( const glue = (...xs: (string | HTMLElement)[]): HTMLElement => el("span", { className: "lstk-pack", children: xs.filter((x) => x !== "") }); // 846-2 작업량 — 「시간당 작업량」 줄 먼저 · 수량 = 「÷ 시간당 작업량」 - const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias); // 줄마다 새 요소 + const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias, show); // 줄마다 새 요소 const byWork = wq() !== null; const workHead = (): void => { if (!w) return; @@ -359,8 +365,8 @@ function rows( glue( " × ", mu.wrap && qn - ? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias })}\\right)`) // prettier-ignore - : exprNode(qty, "val", scope, true, cost, { alias }), + ? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias, show })}\\right)`) // prettier-ignore + : exprNode(qty, "val", scope, true, cost, { alias, show }), mu.qty ? ` ${mu.qty}` : "", ), ]; @@ -383,7 +389,7 @@ function rows( const by = (line as { 비목곱?: Record }).비목곱?.[c]; // 848-7 그 비목만 더 곱함 const byNode = by ? nodeOf(by) : null; const times = byNode - ? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias })}\\right)`))] // prettier-ignore + ? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias, show })}\\right)`))] // prettier-ignore : []; push({ h: [`${COST_SHOW[c]} : `, glue(`${eqText(bundle[c])}${priceUnit}`), ...qtyNode(c), ...times, ` = ${one(part)} ${AMOUNT_UNIT}`], // prettier-ignore @@ -399,9 +405,9 @@ function rows( ? [ exprNode(line.단가, "sym", scope, true, undefined, { place, alias }), " = ", - exprNode(line.단가, "val", scope, true, undefined, { alias }), + exprNode(line.단가, "val", scope, true, undefined, { alias, show }), ] - : [glue(exprNode(line.단가, "val", scope, true, undefined, { alias }), priceUnit)]; + : [glue(exprNode(line.단가, "val", scope, true, undefined, { alias, show }), priceUnit)]; const c = String(line.비목); const bare = !!line.합밖 && !line.비목; // 합 밖 소계(810-2) = 글에만 금액 · 비목 칸 빈칸 workHead(); @@ -462,7 +468,7 @@ function rows( push({ h: [ katexNode(symTex(doc.결과)), - ` = ${isNum(r) ? `${eqText(r)} ${doc.결과단위 ?? ""}` : "—"}`, + ` = ${isNum(r) ? `${numText(doc.결과, r, String(doc.결과단위 ?? ""))} ${doc.결과단위 ?? ""}` : "—"}`, ], cls: "total", }); diff --git a/A00_Common/line_stack_rows.ts b/A00_Common/line_stack_rows.ts index d7a1d1548..024a8d5eb 100644 --- a/A00_Common/line_stack_rows.ts +++ b/A00_Common/line_stack_rows.ts @@ -10,6 +10,7 @@ * 표 값(804-3) = [표 · 칸] 단추 → 표 고르기 창(`line_stack_pick.ts`) · 값 칸 누름 = 그 줄 · 칸(`pickCell`) * ========================================================================== */ +import { showValue } from "../common_util/common_util_show_digits"; import { createButton, createIconButton } from "@ui/ui_template_button"; import { eqText } from "@ui/ui_template_equation"; import { el, showToast } from "@ui/ui_template_elements"; @@ -162,7 +163,11 @@ export function buildBlock( const v = vals[id]; const mach = machineText(v, () => h.change(() => undefined)); // 838-3 기계 원문번호 = 이름 if (mach) return mach; - if (isNum(v) || typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim(); + if (isNum(v)) { + const t = showValue(d, id, v, vals, h.tableCache); // 859-3 보이는 자리 규칙(표 = 원문 글자 자리) + return `${t} ${unitOf(id)}`.trim(); + } + if (typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim(); if (v && typeof v === "object") { const key = vars.get(id)?.연결?.키; // 845-2 묶음 값 = 그 문서 결과 단위(원/시간 등) const u = unitOf(id) || unitText(key ? h.subDoc(key)?.결과단위 : ""); diff --git a/A00_Common/line_stack_screen.ts b/A00_Common/line_stack_screen.ts index 89abd4681..a55dc54f7 100644 --- a/A00_Common/line_stack_screen.ts +++ b/A00_Common/line_stack_screen.ts @@ -444,6 +444,7 @@ export function createStackScreen(opt: StackScreenOptions) { calc: calcSub, lists: (g) => listsOf((q) => cache.links.element(q), g), look: (p) => cache.links.table(p), + tableCache: (k) => cache.tableOf(k), work: (m) => machineWork((q) => cache.links.element(q), m), upper, ctlEdit: !cp && edit(), // 848-3 M01 기초 = 시스템 관리자 diff --git a/A00_Common/line_stack_tex.ts b/A00_Common/line_stack_tex.ts index 78d01d1a3..cffccd88b 100644 --- a/A00_Common/line_stack_tex.ts +++ b/A00_Common/line_stack_tex.ts @@ -27,6 +27,8 @@ export interface TexCtx { decided?: boolean; /** 남은 분수 층(845-2 — 0 이면 안쪽 ÷ 는 한 줄 · 없음 = 끝없음) */ frac?: number; + /** 859-3 값 식의 기호 값 글(보이는 자리 규칙 · TeX 쉼표 「{,}」) — 없으면 `valTex` */ + show?: (id: string, v: unknown) => string; } const HIDE = new Set(["반올림", "올림", "버림"]); @@ -101,8 +103,10 @@ export function tex(n: Node, c: TexCtx): string { const id = c.alias?.[n[1]] ?? n[1]; if (c.side === "sym") return symTex(id); let v = c.vals[n[1]]; - if (v && typeof v === "object" && c.cost) v = (v as Values)[c.cost]; - return v === null || v === undefined || typeof v === "object" ? miss(symTex(id)) : valTex(v); + const part = !!v && typeof v === "object" && !!c.cost; // 묶음 값의 비목(단가 · 자료 그대로) + if (part) v = (v as Values)[c.cost!]; + if (v === null || v === undefined || typeof v === "object") return miss(symTex(id)); + return c.show && isNum(v) && !part ? c.show(n[1], v) : valTex(v); } case "field": { const [, of, key] = n; diff --git a/A00_Common/line_stack_work.ts b/A00_Common/line_stack_work.ts index 179fd06c3..73a69390a 100644 --- a/A00_Common/line_stack_work.ts +++ b/A00_Common/line_stack_work.ts @@ -11,8 +11,8 @@ import { createBadge } from "@ui/ui_template_badge"; import { el } from "@ui/ui_template_elements"; -import { eqText } from "@ui/ui_template_equation"; import { varId, type FormulaDoc, type Node } from "../common_util/common_util_formula_doc"; +import { showDigits, showValue } from "../common_util/common_util_show_digits"; import { calcDoc, isNum, @@ -30,7 +30,7 @@ import { restOfQty, workUnit, } from "../common_util/common_util_line_stack_work"; -import { katexNode, symTex, tex, txt, valTex } from "./line_stack_tex"; +import { katexNode, symTex, tex, txt } from "./line_stack_tex"; import { lt, type LsKey } from "./line_stack_text"; export interface WorkRow { @@ -51,7 +51,15 @@ export function workTag(kind: string, title = ""): HTMLElement { const chain = (...xs: string[]): (string | HTMLElement)[] => xs.flatMap((x, i) => (i ? [" = ", katexNode(x)] : [katexNode(x)])); const unitTex = (u: string): string => (u ? `\\ ${txt(u)}` : ""); -const amount = (v: unknown, u: string): string => `${valTex(v)}${unitTex(u)}`; +/** 859-3 시간당 작업량 Q = 소수 3 자리(건설 8-1 [주]① 계산값의 맺음) */ +const workText = (v: unknown): string => showDigits(v, "식", "Q"); +const workAmount = (v: unknown, u: string): string => + `${workText(v).replace(/,/g, "{,}")}${unitTex(u)}`; +/** 859-3 문서 값 글(보이는 자리 규칙 · TeX 쉼표) */ +const docShow = + (doc: FormulaDoc, vals: Values) => + (id: string, v: unknown): string => + showValue(doc, id, v, vals).replace(/,/g, "{,}"); /** 작업량 틀 풀이 — 값 줄 + 결과 식 줄(없으면 빈 목록) */ export function hourlyRows( @@ -64,13 +72,15 @@ export function hourlyRows( const vals = (a.값 ?? {}) as Values; const vars = new Map((tpl.변수 ?? []).map((v) => [varId(v), v])); const unit = (id: string): string => workUnit(shownUnitOf(vars.get(id), vals, look)); - const pack = parts.uses.map((id) => - katexNode(`${symTex(id)} = ${isNum(vals[id]) ? amount(vals[id], unit(id)) : txt("—")}`), + const show = docShow(tpl, vals); + const pack = parts.uses.map( + (id) => + katexNode(`${symTex(id)} = ${isNum(vals[id]) ? `${show(id, vals[id])}${unitTex(unit(id))}` : txt("—")}`), // prettier-ignore ); const res = vals[parts.id]; const sym = tex(parts.node, { side: "sym", vals, frac: 1 }); - const val = tex(parts.node, { side: "val", vals, frac: 1 }); - const end = isNum(res) ? amount(res, workUnit(tpl.결과단위)) : txt("—"); + const val = tex(parts.node, { side: "val", vals, frac: 1, show }); + const end = isNum(res) ? workAmount(res, workUnit(tpl.결과단위)) : txt("—"); return [ ...(pack.length ? [{ h: pack, cls: "packs" }] : []), { h: chain(symTex(parts.id), sym, val, end), cls: "work" }, @@ -99,14 +109,14 @@ export function workRows(w: WorkInfo, c: WorkCtx): WorkRow[] { c.miss(); } const tag = workTag(w.꼴, tpl?.이름 ?? w.율); - if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${eqText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore + if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${workText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore const a = calcDoc(tpl, c.links!, w.변수 ?? {}, [], new Map(), {}); const name = el("span", { className: "lstk-hint", text: tpl.이름 ?? w.율 }); return [{ h: [tag, name] }, ...hourlyRows(tpl, a, c.look)]; } if (!isNum(w.값)) return []; const tag = workTag(w.꼴 || "일당"); - const res = amount(w.값, u); + const res = workAmount(w.값, u); const parts = w.꼴 === "일당" ? dailyParts(w.율) : null; if (parts) { const val = (n: Node): string => tex(n, { side: "val", vals: c.vals, inline: true }); @@ -130,13 +140,14 @@ export function workQty( w: WorkInfo | null, scope: Values, alias?: Record, + show?: (id: string, v: unknown) => string, ): HTMLElement[] | null { if (!w || !isNum(w.값) || w.값 <= 0) return null; const got = restOfQty(doc, qty); if (!got) return null; - const by = katexNode(`{}\\div ${amount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격 + const by = katexNode(`{}\\div ${workAmount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격 if (!got.rest) return [by]; - return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias })}`)]; // prettier-ignore + return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias, show: show ?? docShow(doc, scope) })}`)]; // prettier-ignore } const nameOf = (doc: FormulaDoc, id: string): string => diff --git a/B09_Estimation/B09_Estimation_Bill_Library.py b/B09_Estimation/B09_Estimation_Bill_Library.py index 2a14b4436..3d9d42e27 100644 --- a/B09_Estimation/B09_Estimation_Bill_Library.py +++ b/B09_Estimation/B09_Estimation_Bill_Library.py @@ -7,9 +7,7 @@ precombo 사전조합 = `일위대가.json` {줄: {담은로직: [{참조, 수량: {손: 1}}]}, 참조사본} · `단가.json`(`M02_Item_Source.price_bundle` — 사본 단가 묶음 한 벌) sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(SK = 수식 사본 · B9-5) -[업데이트](719-2) = 원본판이 다른 사본만 같은 폴더에 다시 굳힘(`changed` · `refresh_copy` · -값 그대로 · 원본판 없는 옛 사본 = 그대로). -사본 = 원본이 바뀌거나 지워져도 그대로(굳힘) · +사본 = 원본이 바뀌거나 지워져도 그대로(굳힘 · 859-2 프로젝트 안 다시 굳힘 없음) · 대가 블록 = `Labor_Source.daega_inputs`(`libs` {폴더: 블록 id}) · 단가 수요 = `Linked.linked_resource_keys` · 줄 연결 = {tab: dg, key: 블록 id, lib: 폴더} · [저장] 때 줄이 안 쓰는 사본은 지움(`prune`) · 층 읽기 권한 = 부르는 쪽(`M02_Layer_Access.grant`). @@ -104,7 +102,7 @@ def _precombo_files(layer: str, owner: str | None, key: str, kind: str = "precom def source_version(files: dict[str, Any]) -> str: """서고 사본 원본판(719-1) = 일위대가.json + 수식 문서(로직 몫 · 855-F B9-6) 지문 — 굳힌 SC · SK - 문서(SK = 수식 사본) · 단가는 뺌(단가 바뀜은 [단가 갱신] 몫) · 값 덮기 전에 셈.""" + 문서(SK = 수식 사본) · 단가는 뺌 · 값 덮기 전에 셈.""" return version_of([files.get(LABOR_FILE), (files.get(doc_b09.FILE) or {}).get("문서")]) @@ -121,39 +119,6 @@ def _build(kind: str, layer: str, owner: str | None, key: str) -> tuple[dict, di return files, files.pop("_원본") -def _source_of(manifest: dict[str, Any]) -> tuple[str, str, str | None, str]: - """manifest → (종류, 층, 주인, 키).""" - kind, origin = str(manifest.get("종류")), manifest.get("원본") or {} - if kind == "combo": - return kind, origin.get("layer"), origin.get("owner"), origin.get("key") - ref = origin.get("참조") or {} - return kind, ref.get("층"), ref.get("주인"), ref.get("키") - - -def changed(project_root: str | Path) -> list[tuple[Path, dict[str, Any], dict, dict]]: - """원본판이 지금 원본과 다른 사본 `(폴더, manifest, 새 파일들, 새 원본 표지)` — 원본판 없는 옛 - 사본 · 원본 없음 = 뺌(그대로).""" - out = [] - for folder, manifest in copies(project_root): - if not manifest.get("원본판"): - continue - try: - files, origin = _build(*_source_of(manifest)) - except (LookupError, ValueError, KeyError): - continue - if source_version(files) != manifest["원본판"]: - out.append((folder, manifest, files, origin)) - return out - - -def refresh_copy(project_root: str | Path, one: tuple) -> None: - """`changed` 한 줄 → 같은 폴더에 다시 굳힘(값 · 가져온이 그대로 · 원본판 새로).""" - folder, manifest, files, origin = one - keep = {k: v for k, v in manifest.items() if k not in ("값", "원값")} - fresh = {**keep, "원본": origin, "원본판": source_version(files), "가져온날": now_text()} - _write(project_root, folder.name, files, fresh, manifest.get("값") or {}) - - # ── 운반 값 사본(263-2) ──────────────────────────────────────────────── def _logic(code: str) -> dict[str, Any]: """M01 기초 이름 · 입력 꼴 — 지금 수식 문서(855-F B9-6) · 없는 기초 = 입력 없음.""" diff --git a/B09_Estimation/B09_Estimation_Copy_Prices.py b/B09_Estimation/B09_Estimation_Copy_Prices.py deleted file mode 100644 index 725490cb4..000000000 --- a/B09_Estimation/B09_Estimation_Copy_Prices.py +++ /dev/null @@ -1,92 +0,0 @@ -"""B09 [단가 갱신] = 프로젝트 사본 자원 단가 줄 갱신(PLAN 841-1 · 요구 854 · 866) — 서버 단독. - -B09 금액 = 프로젝트 사본(구조물 사본 · 서고 사본)을 M02 엔진으로 셈한 값(B09 단가 책으로 다시 안 셈). -그래서 사본 값을 지금 M01 로 올리는 일 = 사본 `단가.json` 자원 줄(LB · MT · EQ · MO · FX)만 지금 M01 줄로 -(로직 줄 · 일위대가 · 입력값 · 고른 자재 · 덮개 그대로 · M01 에서 지워진 키 = 마지막 값 그대로) — -M02 [단가 갱신](`M02_Sangeun_Copy.refresh`)과 같은 뜻 · 사용자가 누를 때만(프로젝트 안은 자동 아님). -미리 보기 = `OVER` 덮개(파일 안 씀 · 사본 읽는 곳이 `bundle` 로 읽음)로 같은 셈. -""" - -from __future__ import annotations - -from contextvars import ContextVar -from pathlib import Path -from typing import Any - -from B09_Estimation import B09_Estimation_Bill_Library as library -from common_util.common_util_json import atomic_write_json -from M01_MasterData import M01_MasterData_Store as m01 -from M02_MasterTemplete import M02_Item_Prices as item_prices -from M02_MasterTemplete import M02_Sangeun_Copy as skc -from M02_MasterTemplete.M02_Item_Snapshot import linked_snapshots, structures_dir -from M02_MasterTemplete.M02_Item_Source import PRICE_FILE, read_json - -#: 미리 보기 덮개 {사본 폴더 글: 새 `단가.json`} — 없으면 파일 -OVER: ContextVar[dict[str, dict] | None] = ContextVar("b09_copy_prices", default=None) - - -def bundle(folder: Path) -> dict[str, Any]: - """사본 `단가.json` — 미리 보기 덮개가 있으면 그것.""" - over = OVER.get() - if over and str(folder) in over: - return over[str(folder)] - return read_json(folder / PRICE_FILE) or {} - - -def folders(root: str | Path) -> list[Path]: - """연결된 구조물 사본 + 서고 사본 폴더.""" - base = structures_dir(root) - out = [base / one["폴더"] for one in linked_snapshots(root).values()] - out += [folder for folder, _manifest in library.copies(root)] - return list(dict.fromkeys(out)) - - -def _shown(row: dict[str, Any]) -> Any: - """미리 보기 값 — 노임 · 유가 = 값 · 기계 = 가격(천원) · 자재 = 출처 값 묶음.""" - value = row.get("값") - if isinstance(value, dict): - return value.get("가격") - if value is not None: - return value - return {k: row.get(k) for k in ("조달청", "물가자료", "유통물가", "물가정보", "거래가격")} - - -def refreshed(root: str | Path) -> tuple[dict[str, dict], list[dict[str, Any]]]: - """({바뀐 사본 폴더 글: 새 `단가.json`}, 바뀐 자원 [{키, 이름, 전, 후}]) — 파일 안 씀.""" - whole = skc.whole_() - news: dict[str, dict] = {} - changed: dict[str, dict[str, Any]] = {} - for folder in folders(root): - data = read_json(folder / PRICE_FILE) - if not isinstance(data, dict): - continue - out, hit = {}, False - for name, part in data.items(): - slot = m01.items_key(part) if isinstance(part, dict) else "" - rows = part.get(slot) if slot else None - if not isinstance(rows, list): - out[name] = part - continue - fresh = [] - for row in rows: - key = str((row or {}).get("키") or "") - live = whole.index.get(key[:2], {}).get(key) if key[:2] in skc.RES else None - new = item_prices.to_json(live) if live is not None else row - if new != row: - hit = True - changed.setdefault( - key, - {"키": key, "이름": new.get("이름"), "전": _shown(row), "후": _shown(new)}, - ) - fresh.append(new) - out[name] = {**part, slot: fresh} - if hit: - news[str(folder)] = out - return news, list(changed.values()) - - -def write(news: dict[str, dict]) -> int: - """새 `단가.json` 을 사본 폴더에 씀 — 쓴 사본 수.""" - for folder, data in news.items(): - atomic_write_json(Path(folder) / PRICE_FILE, data) - return len(news) diff --git a/B09_Estimation/B09_Estimation_Labor_Source.py b/B09_Estimation/B09_Estimation_Labor_Source.py index 09fbbc388..3a2336a8c 100644 --- a/B09_Estimation/B09_Estimation_Labor_Source.py +++ b/B09_Estimation/B09_Estimation_Labor_Source.py @@ -38,7 +38,6 @@ from B09_Estimation import B09_Estimation_Labor_Rule as rule from B09_Estimation import B09_Estimation_Sangeun as sg from B09_Estimation import B09_Estimation_Sangeun_Text as st from B09_Estimation.B09_Estimation_Bill_Items import LAYER_WORD -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from B09_Estimation.B09_Estimation_Linked import sk_answer from B09_Estimation.B09_Estimation_Supply import sk_money, supply_mark from M02_MasterTemplete import M02_Item_Prices as item_prices @@ -53,7 +52,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json mf = item_prices.mf @@ -186,7 +185,7 @@ class Builder: M02 SK 셈과 같은 문서) · 줄 = 문서 답 금액 줄(이름 · 단위 · 수량 · 종류 = 답 · 자원 키 · 하위 부름 = 셈 기록) — 노임 · 자재 · 기계경비(중기) · 하위 단가산출(산근) · % 줄 · 그 밖 = 줄 단가 `fixed` · 합밖 = `out` · cover = `P:` + SK 이름표(SK 를 고쳐 - [재생성] 해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) · + 다시 지정해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) · 수식 사본 없는 SK(형제 · 옛 칸) = None(부르는 줄이 까닭 · M02 처럼 못 셈).""" got = sk_answer(doc) if got is None or got.stopped or "결과" in got.ans: @@ -429,7 +428,7 @@ class Builder: labor = read_json(folder / LABOR_FILE) if not isinstance(labor, dict): return None - prices = bundle(folder) # 841-1 미리 보기 덮개 + prices = read_json(folder / PRICE_FILE) or {} values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3) @@ -489,7 +488,7 @@ class Builder: if not isinstance(doc, dict): return None whole = self.shelf.put_whole( - bundle(folder), dr.docs_of(folder) + (read_json(folder / PRICE_FILE) or {}), dr.docs_of(folder) ) # 사본 수식 문서(B9-3 · B9-6) if manifest["종류"] == "sangeun": # 내 자료집 단가산출(719-2) return self.sangeun(whole, ref, doc, copies, 1) diff --git a/B09_Estimation/B09_Estimation_Linked.py b/B09_Estimation/B09_Estimation_Linked.py index ab5c98588..81268fdab 100644 --- a/B09_Estimation/B09_Estimation_Linked.py +++ b/B09_Estimation/B09_Estimation_Linked.py @@ -17,7 +17,6 @@ from pathlib import Path from typing import Any from B09_Estimation import B09_Estimation_Doc_Run as dr -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Labor_Fixed as fixed from M02_MasterTemplete.M02_Item_Snapshot import ( @@ -26,7 +25,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json #: 원가 단가 목록에 오르는 자원 표 RESOURCE_TABLES = ("LB", "EQ", "MT", "MO") @@ -38,7 +37,7 @@ def used_keys(folder: Path) -> list[str]: if not isinstance(labor, dict): return [] docs = dr.docs_of(folder) # 사본 수식 문서 — 셈 기록의 자원 키(855-F B9-3) - snapshot = dr.load(bundle(folder), docs) + snapshot = dr.load((read_json(folder / PRICE_FILE) or {}), docs) values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} seen: list[str] = [] @@ -113,7 +112,7 @@ def frozen_rows(project_root: str | Path) -> dict[str, dict[str, Any]]: out: dict[str, dict[str, Any]] = {} for folder in _folders(project_root): - got = bundle(folder) # 841-1 미리 보기 덮개 + got = read_json(folder / PRICE_FILE) or {} for name, data in got.items(): if name.startswith("_") or not isinstance(data, dict): continue diff --git a/B09_Estimation/B09_Estimation_Prices.py b/B09_Estimation/B09_Estimation_Prices.py index ada70ecd6..b2be12480 100644 --- a/B09_Estimation/B09_Estimation_Prices.py +++ b/B09_Estimation/B09_Estimation_Prices.py @@ -1,12 +1,11 @@ """B09 자재 단가 책 · 수요 모음(PLAN 144 · 841-1) — 서버 단독(M01 을 읽는 곳은 여기 하나). -841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값 · -`B09_Estimation_Copy_Prices`). +841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값). 책에 남는 것 = 자재단가대비표(4 자재대 · 관급자재대 단가 고르기) 자재 줄. 자재 단가 = 프로젝트 한 벌 — 원가산출에서 한 번 굳힘(`price_book.json`) · 값 = 사본 단가 기준 시점(795-4 · 구조물 지정 때 `단가.json` 자원 줄 · 없는 자원만 지금 M01 + - `now_keys`) · [단가 갱신] 때만 새로. + `now_keys`) · 다시 굳히지 않음(859-2 프로젝트 안 단가 갱신 없음). 줄 = 수요 따라(사용자 승인 ① · 10-9) — 엑셀 목록을 기본으로 깔지 않음: 연결된 사본이 부른 자재 키(`B09_Estimation_Linked` — 143-1 「연결된 사본」 원천 · 없으면 빈 표) + B08 총괄자재수량집계표 자재(M01 짝 없음 → 출처 빈칸 · 적용 단가는 사용자 입력) @@ -16,7 +15,6 @@ from __future__ import annotations -import json from decimal import Decimal from typing import Any @@ -103,58 +101,13 @@ def _convert(master, key: str) -> dict[str, Any]: return material_input(_row(master, key)) -def refresh_book( - keys: list[str], book: dict[str, Any] | None = None, frozen: dict[str, dict] | None = None -) -> dict[str, Any]: - """[단가 갱신] — 수요 키 전부를 지금 M01 값으로 새로 굳힘 · - M01 원본이 지워진 키(296) = 옛 책 줄 그대로(지우지도 바꾸지도 않음) · - `frozen` = 첫 굳힘(795-4) — 사본 단가 기준 시점 값 · 없는 자원 = 지금 값(`now_keys`).""" +def make_book(keys: list[str], frozen: dict[str, dict] | None = None) -> dict[str, Any]: + """첫 굳힘 — 수요 키 전부 · `frozen` = 사본 단가 기준 시점 값(795-4) · 없는 자원 = 지금 값 + (`now_keys`) · None = 지금 M01.""" master = basis(frozen) want = demand(master, keys) rows = {key: _convert(master, key) for key in want["materials"]} - old = (book or {}).get("rows") or {} - rows.update({key: old[key] for key in want["missing"] if key in old}) - return { - "made": utc_now_text(), - "rows": rows, - "labor_edition": labor_editions(keys), # 703-3 미리 보기 「노임 판 전 → 후」 - "now_keys": now_keys(frozen, list(rows)), - } - - -def labor_editions(keys: list[str]) -> dict[str, str]: - """노임 판(703-3) — 수요 노무 줄 구분(건설업 · 산림 …)마다 M01 `인력.json` 그 구분 `판`.""" - files, master = m01.loaded() - groups = (files.get("인력.json") or {}).get("구분") or {} - out: dict[str, str] = {} - for key in [k for k in keys if k.startswith("LB") and _row(master, k)]: - kind = str((_row(master, key) or {}).get("구분") or "") - if (groups.get(kind) or {}).get("판"): - out[kind] = str(groups[kind]["판"]) - return out - - -def book_diff(old: dict[str, Any] | None, new: dict[str, Any]) -> dict[str, int | bool]: - """두 책 견줌(저장 꼴 JSON) — 새 줄 · 바뀐 줄 수(203-1 · 703-3 · 자재 줄만).""" - new = json.loads(json.dumps(new, ensure_ascii=False)) - rows = (old or {}).get("rows") or {} - return { - "new": sum(key not in rows for key in new["rows"]), - "changed": sum(key in rows and rows[key] != row for key, row in new["rows"].items()), - } - - -def book_stale(book: dict[str, Any] | None, keys: list[str]) -> str | None: - """203-1 [업데이트] 배지 — 지금 M01 로 새로 굳힌 책(`refresh_book`)과 견줌 · 다른 것 한 줄(같으면 None).""" - if book is None: - return "단가 아직 안 굳힘" - # 저장 꼴(JSON)로 견줌 · M01 원본이 지워진 줄 = 옛 줄 그대로(낡음 까닭에서 빠짐 · 296) - diff = book_diff(book, refresh_book(keys, book)) - parts = [ - f"새 단가 줄 {diff['new']}" if diff["new"] else "", - f"M01 에서 바뀐 단가 {diff['changed']}" if diff["changed"] else "", - ] - return " · ".join(p for p in parts if p) or None + return {"made": utc_now_text(), "rows": rows, "now_keys": now_keys(frozen, list(rows))} def extend_book( @@ -163,7 +116,7 @@ def extend_book( """[저장] — 책에 없는 새 줄만 더함(있는 줄 · 계수 · 환율은 안 바꿈) · 책이 없으면 새로 굳힘 · 새 줄 값 = 사본 단가 기준 시점(795-4 · `frozen`) · 없는 자원만 지금 M01(`now_keys`).""" if book is None: - return refresh_book(keys, None, frozen or {}) + return make_book(keys, frozen or {}) master = basis(frozen) want = demand(master, keys) rows = dict(book["rows"]) diff --git a/B09_Estimation/B09_Estimation_Refresh.py b/B09_Estimation/B09_Estimation_Refresh.py deleted file mode 100644 index 85904206c..000000000 --- a/B09_Estimation/B09_Estimation_Refresh.py +++ /dev/null @@ -1,173 +0,0 @@ -"""B09 [단가 갱신] · [재생성](PLAN 795-4 · 옛 [업데이트] 703-3) — 사본 로직은 만든 때 그대로 · -[단가 갱신](기본 · 841-1) = 프로젝트 사본 자원 단가 줄(`B09_Estimation_Copy_Prices`) + 자재 단가 책만 - 지금 M01 값 · 미리 보기 `price_preview` = 바뀐 자원 · 총괄 전 → 후 · -[재생성](사용자가 따로) = 아래 옛 [업데이트] — 단가 책 다시 굳힘 + 원본이 바뀐 구조물 사본 [재적용]. - -미리 보기(`preview`) = 바뀌는 단가 줄(새 줄 + 바뀐 줄 · 지금 수요) · 다시 가져올 구조물 사본 - (연결된 것 중 원본이 바뀐 것만 · 원본 없음 = 그대로) · 지킬 고친 칸(덮개 칸 수 · 702-4 — - 재적용 · 새 판 뒤에도 남음) · 노임 판(굳힌 판 → 지금 M01 판 · 옛 책 = 굳힌 날) -적용(`reapply_changed` → 부르는 쪽이 수요 다시 → `prices.refresh_book`) — 사본 먼저(수요가 바뀜) · - 덮개(사용자 값)는 안 건드림 · 사본 하나가 막혀도 나머지는 함(막힌 것 = 알림). -M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 SK 수식 사본을 원본 층에서 다시 굳힘(같은 이름표 · - 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로 · 855-F B9-5) · - 서고 사본도 원본판이 다르면 다시 · - 미리 보기 `단가산출` = 바뀌는 SK 줄 [{사본, 이름, 키, 판(새 · 바뀜 · 빠짐)}]. -""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any - -from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation.B09_Estimation_Calc_Labor import COPY -from M02_MasterTemplete import M02_Item_Copy as item_copy -from M02_MasterTemplete import M02_Item_Sangeun as item_sk -from M02_MasterTemplete.M02_Item_Snapshot import MANIFEST_NAME, linked_snapshots, structures_dir -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, build_source, read_json - -REGEN = "재생성" # POST …/estimation/prices · preview 몸 `job`(795-4) - - -def _value(row: dict[str, Any] | None) -> Any: - return None if row is None else row.get("price", row.get("prices")) - - -def price_preview( - old: dict[str, Any] | None, - new: dict[str, Any], - before: dict, - after: dict, - cells: int, - copies: list[dict[str, Any]] | None = None, -) -> dict[str, Any]: - """[단가 갱신] 미리 보기(795-4 · 841-1) — {할일, 바뀐자원 [{키, 이름, 전, 후}](사본 자원 줄 + - 자재 단가 책), 전, 후(총괄 grand · 빈 줄 있으면 None), 대가 {전, 후}(일위대가 블록 합), 고친칸, - 노임판} · 사본(로직)은 안 바뀜.""" - was = json.loads(json.dumps((old or {}).get("rows") or {}, ensure_ascii=False)) - now = json.loads(json.dumps(new["rows"], ensure_ascii=False)) - rows = [ - {"키": key, "이름": row.get("name") or "", "전": _value(was.get(key)), "후": _value(row)} - for key, row in now.items() - if was.get(key) != row - ] - - def grand(sheets: dict) -> Any: - return (((sheets.get("total") or {}).get("subtotals")) or {}).get("grand") - - def daega(sheets: dict) -> float: - return sum(float(b.get("sum") or 0) for b in sheets.get("daega_blocks") or []) - - seen = {r["키"] for r in copies or []} - return { - "할일": "단가갱신", - "바뀐자원": [*(copies or []), *(r for r in rows if r["키"] not in seen)], - "전": grand(before), - "후": grand(after), - "대가": {"전": daega(before), "후": daega(after)}, - "고친칸": cells, - "노임판": { - "전": edition_text((old or {}).get("labor_edition")), - "후": edition_text(new.get("labor_edition")), - }, - } - - -def changed_copies(root: str | Path) -> list[dict[str, Any]]: - """연결된 구조물 사본 중 원본(층 · 마스터)이 바뀐 것 `[{폴더, 이름}]`.""" - linked = {one["폴더"] for one in linked_snapshots(root).values()} - return [ - {"폴더": it["폴더"], "이름": it["이름"] or it["폴더"]} - for it in item_copy.list_items(root) - if it["폴더"] in linked and it["마스터바뀜"] - ] - - -def _sks(labor: Any) -> dict[str, dict]: - copies = (labor or {}).get("참조사본") or {} - return {rid: doc for rid, doc in copies.items() if item_sk.is_sangeun(doc)} - - -def sk_lines(old: Any, new: Any, where: str) -> list[dict[str, str]]: - """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(SK 문서 · 수식 사본이 다름).""" - was, now = _sks(old), _sks(new) - out = [] - for rid in sorted(set(was) | set(now)): - a, b = was.get(rid) or {}, now.get(rid) or {} - if a == b: - continue - mark = "새" if not a else "빠짐" if not b else "바뀜" - out.append({"사본": where, "이름": (b or a).get("이름") or "", "키": rid.rsplit("|")[-1], - "판": mark}) # fmt: skip - return out - - -def sk_changes(root: str | Path, copies: list[dict], libs: list[tuple]) -> list[dict[str, str]]: - """다시 가져올 구조물 사본(`changed_copies`) · 서고 사본(`library.changed`)의 바뀌는 SK 줄.""" - out = [] - for one in copies: - folder = structures_dir(root) / one["폴더"] - try: - fresh = build_source((read_json(folder / MANIFEST_NAME) or {})["원본"]) - except (LookupError, ValueError, KeyError): - continue - out += sk_lines(read_json(folder / LABOR_FILE), fresh.get(LABOR_FILE), one["이름"]) - for folder, manifest, files, origin in libs: - name = str(origin.get("name") or folder.name) - out += sk_lines(read_json(folder / LABOR_FILE), files.get(LABOR_FILE), name) - return out - - -def cover_cells(cover: dict[str, Any] | None) -> int: - """고친 칸 수 — 덮개 칸(품 · 수량 · 단가) · 복사본 표지 뺌.""" - return sum( - len(cell) for lines in (cover or {}).values() for cid, cell in lines.items() if cid != COPY - ) - - -def edition_text(editions: dict[str, str] | None) -> str: - return " · ".join(f"{kind} {day[:7]}" for kind, day in sorted((editions or {}).items())) - - -def preview( - root: str | Path, book: dict[str, Any] | None, keys: list[str], cover: dict | None -) -> dict[str, Any]: - diff = prices.book_diff(book, prices.refresh_book(keys, book)) - copies, libs = changed_copies(root), library.changed(root) - lib_names = [{"폴더": f.name, "이름": str(o.get("name") or f.name)} for f, _m, _f, o in libs] - before = (book or {}).get("labor_edition") - made = str((book or {}).get("made") or "")[:10] - return { - "단가줄": diff["new"] + diff["changed"], - "새줄": diff["new"], - "바뀐줄": diff["changed"], - "사본": copies + lib_names, - "단가산출": sk_changes(root, copies, libs), - "고친칸": cover_cells(cover), - "노임판": { - "전": edition_text(before) if before else (f"굳힌 날 {made}" if made else "안 굳힘"), - "후": edition_text(prices.labor_editions(keys)), - }, - } - - -def reapply_changed(root: str | Path, who: dict[str, Any] | None = None) -> dict[str, list]: - """원본이 바뀐 연결 사본 재적용 · 서고 사본 다시 굳힘 — - `{다시: [이름], 막힘: [이름 — 까닭]}`.""" - done, stuck = [], [] - for one in library.changed(root): - name = str(one[3].get("name") or one[0].name) - try: - library.refresh_copy(root, one) - done.append(name) - except (LookupError, ValueError, KeyError, OSError) as error: - stuck.append(f"{name} — {error}") - for one in changed_copies(root): - try: - item_copy.reapply(root, one["폴더"], who) - done.append(one["이름"]) - except (LookupError, ValueError, KeyError, OSError) as error: - stuck.append(f"{one['이름']} — {error}") - return {"다시": done, "막힘": stuck} diff --git a/B09_Estimation/B09_Estimation_Router.py b/B09_Estimation/B09_Estimation_Router.py index eeb7b3c45..24a8acab5 100644 --- a/B09_Estimation/B09_Estimation_Router.py +++ b/B09_Estimation/B09_Estimation_Router.py @@ -10,14 +10,6 @@ [초기화](요구 298-2 C1 · C3 · C4 · C5 · 301 · 본문 없음) — 사용자 값 전부(내역 · 자재 · 원가 · 공기) · 단가 책 · `estimation` 설정 구획 지움 · 서고 사본 정리 · 견적서 파일 남김 → 답 = GET 꼴(기준 = 지금 B08 저장본 + 지금 M01 단가) · 단계 = [저장]과 같음 - POST /api/projects/{id}/estimation/prices {user?, job?} - [단가 갱신](795-4 · 기본) — 수요 단가 전부를 지금 M01 값으로 새로 굳힘 · 사본(로직) 그대로 · - job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3 · `B09_Estimation_Refresh`) 먼저 · - user = 화면 캐시(296 · 지운 줄 · 그 사본은 수요에서 뺌 · 저장은 안 함) · - M01 원본이 지워진 줄 = 굳힌 값 그대로 · 덮개 그대로 · 답 notes 첫 줄 = 바뀐 수 - POST /api/projects/{id}/estimation/prices/preview {user?, job?} - 미리 보기(쓰지 않음) — 단가 갱신 = 바뀐 자원 · 총괄 금액 전 → 후(795-4) · - 재생성 = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판(703-3) POST /api/projects/{id}/estimation/calc {user} 조작 중 서버 셈(702-3 · 단가연결 즉시 금액) — 화면 캐시로 GET 꼴 셈 · 저장 안 함 POST /api/projects/{id}/estimation/logic-preview {code, given, rate, picks} @@ -73,13 +65,11 @@ from B08_Quantity.B08_Quantity_Router_Material import once as material_once from B08_Quantity.B08_Quantity_Router_Milestone import read_data as read_milestone from B08_Quantity.B08_Quantity_Router_Milestone import site_info from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Copy_Prices as copy_prices from B09_Estimation import B09_Estimation_Daega_Paste as daega_paste from B09_Estimation import B09_Estimation_Daega_Personal as personal from B09_Estimation import B09_Estimation_Linked as linked from B09_Estimation import B09_Estimation_Past as past from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun from B09_Estimation import B09_Estimation_Sangeun_Cover as sg_cover from B09_Estimation import B09_Estimation_Store as store @@ -246,12 +236,10 @@ async def payload( draft: dict[str, Any] | None = None, reuse_b08: bool = False, keys: list[str] | None = None, - book: dict[str, Any] | None = None, ) -> dict[str, Any]: - """셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만 · - book = 안 쓴 단가 책(795-4 미리 보기 · 없으면 저장본).""" + """셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만.""" with m01_cache.steady(): - return await _payload(project_id, root, draft, reuse_b08, keys, book) + return await _payload(project_id, root, draft, reuse_b08, keys) async def _payload( @@ -260,7 +248,6 @@ async def _payload( draft: dict[str, Any] | None, reuse_b08: bool, keys: list[str] | None, - book: dict[str, Any] | None = None, ) -> dict[str, Any]: notes: list[str] = [] b08 = await _b08_for(project_id, notes, reuse_b08) @@ -269,7 +256,7 @@ async def _payload( notes.append( "연결된 구조물 조합 사본 없음 — 노무 · 경비 · 중기 단가 줄은 사본이 연결되면 생김" ) - book = book or await asyncio.to_thread(store.read_book, root) + book = await asyncio.to_thread(store.read_book, root) frozen = await asyncio.to_thread(linked.frozen_rows, root) # 795-4 사본 단가 기준 시점 inputs = await asyncio.to_thread(prices.build_inputs, book, keys, b08["materials"], frozen) if late := inputs["now"]: @@ -292,9 +279,6 @@ async def _payload( return { "inputs": inputs, "user": user, - "book": {"made": book.get("made")} if book else None, - # 203-1 [업데이트] 배지 까닭(지금 M01 과 다른 것 한 줄 · 같으면 None) - "stale": await asyncio.to_thread(prices.book_stale, book, keys), "sheets": sheets, "rate_candidates": rate_candidates(), "rate_table": rate_table(), @@ -365,67 +349,6 @@ async def estimation_reset(project_id: UUID) -> dict[str, Any]: return await payload(project_id, root) -@router.post("/{project_id}/estimation/prices") -async def refresh_prices( - project_id: UUID, - body: dict[str, Any] | None = Body(None), - session: dict[str, Any] = Depends(verify_session), -) -> dict[str, Any]: - """[단가 갱신](795-4 · 841-1) — 프로젝트 사본 자원 단가 줄 + 자재 단가 책을 지금 M01 값으로 · - 사본 로직 · 덮개 그대로 · job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3) 먼저.""" - root = await _project_root(project_id) - raw = (body or {}).get("user") - draft = store.clean_user(raw) if isinstance(raw, dict) else None # 296 화면 캐시(저장 안 함) - regen = (body or {}).get("job") == refresh.REGEN - again = {"다시": [], "막힘": []} - if regen: - again = await asyncio.to_thread(refresh.reapply_changed, root, importer(session)) - news, changed = await asyncio.to_thread(copy_prices.refreshed, root) - await asyncio.to_thread(copy_prices.write, news) - keys = await _demand(root, draft) - old = await asyncio.to_thread(store.read_book, root) - book = await asyncio.to_thread(prices.refresh_book, keys, old) - await asyncio.to_thread(store.write_book, root, book) - out = await payload(project_id, root, draft) - diff = prices.book_diff(old, book) - kept = draft or out.get("user") or {} - cells = refresh.cover_cells(kept.get("daega_cover")) + refresh.cover_cells(kept.get("sg_cover")) - head = f"재생성 — 구조물 사본 {len(again['다시'])} 다시 가져옴 · " if regen else "단가 갱신 — " - out["notes"] = [ - f"{head}사본 {len(news)} · 자원 {len(changed)} · 자재 단가 줄 " - f"{diff['new'] + diff['changed']} 바뀜 · 고친 칸 {cells} 그대로", - *(f"재적용 못 함 {why}" for why in again["막힘"]), - *(out.get("notes") or []), - ] - return out - - -@router.post("/{project_id}/estimation/prices/preview") -async def refresh_preview( - project_id: UUID, body: dict[str, Any] | None = Body(None) -) -> dict[str, Any]: - """미리 보기 — 단가 갱신(795-4) = 바뀐 자원 · 총괄 금액 전 → 후 · - 재생성(703-3) = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판.""" - root = await _project_root(project_id) - raw = (body or {}).get("user") - draft = store.clean_user(raw) if isinstance(raw, dict) else None - keys = await _demand(root, draft) - book = await asyncio.to_thread(store.read_book, root) - user = draft if draft is not None else await asyncio.to_thread(store.read_user, root) - if (body or {}).get("job") == refresh.REGEN: - return await asyncio.to_thread(refresh.preview, root, book, keys, user.get("daega_cover")) - new = await asyncio.to_thread(prices.refresh_book, keys, book) - news, changed = await asyncio.to_thread(copy_prices.refreshed, root) - before = await payload(project_id, root, draft, True, keys) - token = copy_prices.OVER.set(news) # 841-1 사본 새 단가 = 덮개로만(파일 안 씀) - try: - after = await payload(project_id, root, draft, True, keys, new) - finally: - copy_prices.OVER.reset(token) - cells = refresh.cover_cells(user.get("daega_cover")) + refresh.cover_cells(user.get("sg_cover")) - return refresh.price_preview(book, new, before["sheets"], after["sheets"], cells, changed) - - @router.post("/{project_id}/estimation/calc") async def calc_estimation(project_id: UUID, body: dict[str, Any] = Body(...)) -> dict[str, Any]: """702-3 조작 중 서버 셈 — 화면 캐시(user)로 GET 꼴 셈 · 저장 안 함 · 단가 = 굳힌 책 diff --git a/B09_Estimation/B09_Estimation_Sangeun.py b/B09_Estimation/B09_Estimation_Sangeun.py index 8c3b26d16..c4c9515f7 100644 --- a/B09_Estimation/B09_Estimation_Sangeun.py +++ b/B09_Estimation/B09_Estimation_Sangeun.py @@ -49,7 +49,6 @@ from B09_Estimation import B09_Estimation_Sangeun_Sum as ss from B09_Estimation import B09_Estimation_Sangeun_Text as st from B09_Estimation import B09_Estimation_Sheet as sheet from B09_Estimation.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from B09_Estimation.B09_Estimation_Store import ref_rows from M01_MasterData import M01_MasterData_Store_Combo as combo_store from M02_MasterTemplete import M02_Item_Prices as item_prices @@ -60,7 +59,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json PARTS = ("labor", "material", "expense") @@ -114,7 +113,7 @@ def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[d return [] docs = dr.docs_of(folder) if docs is None else docs if whole is None: - whole = dr.load(bundle(folder), docs) + whole = dr.load((read_json(folder / PRICE_FILE) or {}), docs) values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} copies = labor.get("참조사본") or {} @@ -557,7 +556,7 @@ def collect( solver = Solver(supply) for owner, folder in entries: docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3) - whole = solver.shelf.put_whole(bundle(folder), docs) + whole = solver.shelf.put_whole((read_json(folder / PRICE_FILE) or {}), docs) for src in rows_of(folder, whole, docs): solver.add(whole, src, owner) hand_keys: dict[str, str] = {} diff --git a/B09_Estimation/B09_Estimation_Store.py b/B09_Estimation/B09_Estimation_Store.py index 0247f15c3..c4c5e5fbc 100644 --- a/B09_Estimation/B09_Estimation_Store.py +++ b/B09_Estimation/B09_Estimation_Store.py @@ -2,7 +2,7 @@ price_book.json 굳힌 자재 단가 한 벌 {"made": 시각, "rows": {키: 입력 줄}}(841-1 자재만 · 옛 책의 노무 · 기계 줄 · 계수 · 환율은 안 읽음) - — [단가 갱신] 때만 M01 로 새로 · + — 처음 굳힌 뒤 다시 안 굳힘(859-2) · [저장] 때 책에 없는 새 줄만 더함(있는 줄 안 바꿈) user_values.json 사용자 값 {"materials": {자재 키: {applied?, supply?, quote?, quote_page?, pick?}}, "estimate": {…}, diff --git a/B09_Estimation/B09_Estimation_UI_Check.ts b/B09_Estimation/B09_Estimation_UI_Check.ts index eecf9d837..8ff561297 100644 --- a/B09_Estimation/B09_Estimation_UI_Check.ts +++ b/B09_Estimation/B09_Estimation_UI_Check.ts @@ -1,27 +1,15 @@ /* ============================================================================= * B09_Estimation_UI_Check.ts - * B09 좌측 「데이터 점검」 묶음(PLAN 203-1) — [단가 갱신] · 연결 점검(옛 「연결 점검」 탭 내용). + * B09 좌측 「내역 점검」 묶음(PLAN 203-1) — 연결 점검(옛 「연결 점검」 탭 내용 · 859-2 [단가 갱신] 걷음). * - * [단가 갱신](795-4 · 옛 [업데이트] · 841-1) = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 서버가 낡았다고 보면(`payload.stale` 까닭 한 줄) - * 단추에 점 배지(`is-pending`) · 굳힌 시각 · 까닭 = 공용 호버 - * 미리 보기 고리 = 누름을 먼저 잡아 POST …/estimation/prices/preview(화면 캐시) → - * 「총괄 금액 전 → 후 · 바뀐 자원」 창 → [적용] = 원래 단추 일(단가만 · 사본 · 덮개 그대로) · - * 창의 [재생성] = 재생성 미리 보기(703-3 · 다시 가져올 사본 · 고친 칸 · 노임 판) → [적용] = - * `job: 재생성`(사본 재적용 + 단가) · 닫기 = 안 함 * 연결 점검 = 「빈 줄 n」(설계내역서 금액 모르는 줄 · 안내 · 집계표와 같은 수 · 701-2) 목록 + * 그 밖 확인 목록(일위대가 · 단가산출 · 재료 등 · 탭 · 키마다 하나)(누르면 그 탭 그 줄로 · 까닭 = 공용 호버) + 서버 알림 · M01 에 없는 키 * ========================================================================== */ -import { API_BASE_URL } from "@config/config_frontend"; -import { createButton, showToast } from "@ui/ui_template_elements"; import { attachHoverInfo } from "@ui/ui_template_hover_info"; -import { openModal } from "@ui/ui_template_modal"; import { createBadge } from "@ui/ui_template_badge"; import { createText } from "@ui/ui_template_text"; import type { Row } from "./B09_Estimation_Calc_Base"; -import { dateTimeText } from "../common_util/common_util_time"; -import { readState } from "../A00_Common/b_page_state"; -import { currentProjectId } from "../A00_Common/b_project_switch"; import { blankRows, tabName, type Link, type TabId } from "./B09_Estimation_UI_Tabs"; export interface CheckItem { @@ -63,131 +51,14 @@ export function checkItems( return { items, others, notes }; } -/** [단가 갱신] 호버 글 — 굳힌 시각 + 낡은 까닭 */ -export function refreshTip(payload: Row | null): string { - const made = payload?.book?.made; - const when = made ? `단가 굳힘 ${dateTimeText(String(made))}` : "단가 아직 안 굳힘"; - const stale = payload?.stale; - return `${when} · 누르면 미리 보기 → [적용] = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 사본(로직) · 고친 칸 그대로 · 로직까지 새로 = 미리 보기의 [재생성]${stale ? ` · 단가 갱신 가능 — ${stale}` : ""}`; -} - -/** [재생성] 미리 보기 글 줄(703-3 옛 [업데이트]) */ -export function previewLines(got: Row): string[] { - const copies: Row[] = got.사본 || []; - const sks: Row[] = got.단가산출 || []; - const edition = got.노임판 || {}; - return [ - `바뀌는 자재 단가 줄 ${got.단가줄 ?? 0}(새 줄 ${got.새줄 ?? 0} · 값 바뀜 ${got.바뀐줄 ?? 0})`, - `다시 가져올 사본 ${copies.length}${copies.length ? ` — ${copies.map((c) => c.이름).join(" · ")}` : ""}`, - ...(sks.length - ? [`M02 단가산출 바뀜 ${sks.length} — ${sks.map((s) => `${s.이름}(${s.판})`).join(" · ")}`] - : []), - `고친 칸 ${got.고친칸 ?? 0} 지킴(일위대가 덮개 · 새 판 · 재적용 뒤에도 그대로)`, - `노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`, - ]; -} - -const won = (v: unknown): string => (v == null ? "—" : Number(v).toLocaleString("ko-KR")); - -/** 자원 단가 값 — 노임 · 기계 = 수 · 자재 = 출처별 값 */ -function priceText(v: unknown): string { - if (v == null) return "새 줄"; - if (typeof v !== "object") return won(v); - const got = Object.entries(v as Row).filter(([, x]) => x != null); - return got.length ? got.map(([k, x]) => `${k} ${won(x)}`).join(" / ") : "—"; -} - -/** [단가 갱신] 미리 보기 글 줄(795-4) — 총괄 금액 전 → 후 · 바뀐 자원 */ -export function priceLines(got: Row): string[] { - const rows: Row[] = got.바뀐자원 || []; - const edition = got.노임판 || {}; - const shown = 30; - return [ - `총괄 금액 ${won(got.전)} → ${won(got.후)} 원 · 대가 합 ${won(got.대가?.전)} → ${won(got.대가?.후)} 원`, - `바뀐 자원 ${rows.length}(사본 자원 단가 · 자재 단가)`, - ...rows - .slice(0, shown) - .map((r) => `· ${r.이름 || r.키} ${priceText(r.전)} → ${priceText(r.후)}`), - ...(rows.length > shown ? [`… 외 ${rows.length - shown}`] : []), - `고친 칸 ${got.고친칸 ?? 0} · 구조물 사본(로직) 그대로 — 로직까지 새로는 [재생성]`, - `노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`, - ]; -} - -const REGEN = "재생성"; - -/** [단가 갱신] 누름 앞 미리 보기 — [적용] 이면 원래 단추 일(`data-b09-job` = 할일) · 닫기 = 안 함 · - * [재생성] = 재생성 미리 보기 → [적용] = 사본 재적용 + 단가(795-4 · 사용자가 따로 누를 때만) */ -function attachPreview(refresh: HTMLElement, payload: () => Row | null): void { - let pass = false; - const open = (job?: string): void => { - const projectId = currentProjectId(); - const user = readState("b09-estimation", projectId) ?? payload()?.user ?? {}; - void fetch(`${API_BASE_URL}/projects/${projectId}/estimation/prices/preview`, { - method: "POST", - credentials: "include", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(job ? { user, job } : { user }), - }) - .then(async (response) => { - const got = (await response.json()) as Row; - if (!response.ok) throw new Error(String(got?.detail ?? response.status)); - openModal({ - title: job ? "재생성 미리 보기" : "단가 갱신 미리 보기", - closeLabel: "닫기", - width: "40rem", - mount: (body, close, head) => { - const apply = createButton({ - label: "적용", - variant: "filled", - onClick: () => { - close(); - pass = true; - if (job) refresh.dataset.b09Job = job; - refresh.click(); - delete refresh.dataset.b09Job; - }, - }); - apply.dataset.b09RefreshApply = ""; - if (!job) { - const regen = createButton({ - label: REGEN, - variant: "ghost", - onClick: () => (close(), open(REGEN)), - }); - regen.dataset.b09Regen = ""; - head.append(regen); - } - head.append(apply); - const lines = job ? previewLines(got) : priceLines(got); - body.append(...lines.map((line) => createText(line))); - }, - }); - }) - .catch((error) => showToast(`미리 보기 못 함 — ${String(error)}`, "error")); - }; - refresh.addEventListener( - "click", - (event) => { - if (pass) return void (pass = false); - event.stopImmediatePropagation(); - open(); - }, - true, - ); -} - export interface CheckPanel { /** 묶음 안 연결 점검 자리 */ list: HTMLElement; draw: (payload: Row, sheets: Row) => void; } -export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => void): CheckPanel { - let payload: Row | null = null; +export function createCheckPanel(goto: (link: Link) => void): CheckPanel { let items: CheckItem[] = []; - attachHoverInfo(refresh, () => refreshTip(payload)); - attachPreview(refresh, () => payload); const box = document.createElement("div"); box.className = "b09-check"; attachHoverInfo(box, (row) => items[Number(row.dataset.i)]?.why, "[data-i]"); @@ -219,8 +90,6 @@ export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => voi }; const draw = (next: Row, sheets: Row): void => { - payload = next; - refresh.classList.toggle("is-pending", Boolean(next.stale)); const made = checkItems(sheets, next); items = [...made.items, ...made.others]; const blank = [ diff --git a/B09_Estimation/B09_Estimation_UI_Page.css b/B09_Estimation/B09_Estimation_UI_Page.css index d008489e1..4f9011439 100644 --- a/B09_Estimation/B09_Estimation_UI_Page.css +++ b/B09_Estimation/B09_Estimation_UI_Page.css @@ -143,28 +143,6 @@ html.is-bm-route .b09-estimation > .b09-estimation__tabs:first-child { background: color-mix(in srgb, var(--color-warning) 22%, var(--color-canvas)); } -/* 203-1 좌측 「데이터 점검」 — [업데이트] 필요 = 단추 위 점 배지(B05 [3D 업데이트] 꼴) */ -.b09-options .ui-btn.is-pending { - position: relative; - border-color: var(--color-warning); -} - -.b09-options .ui-btn.is-pending::after { - content: ""; - position: absolute; - top: 4px; - right: 4px; - width: 6px; - height: 6px; - border-radius: 50%; - background: var(--color-warning); -} - -/* 122 데이터 점검 [업데이트] — 제목 아래 틈 = 카드 왼쪽 여유와 같게(공용 카드 틈 8 + 4) */ -.b09-options [data-b09-refresh] { - margin-top: var(--spacing-4); -} - /* 연결 점검 목록 — 이름 · 탭(작게) · 알림 글 */ .b09-check__head, .b09-check__note { diff --git a/B09_Estimation/B09_Estimation_UI_Shell.ts b/B09_Estimation/B09_Estimation_UI_Shell.ts index 3321656c3..76ff16436 100644 --- a/B09_Estimation/B09_Estimation_UI_Shell.ts +++ b/B09_Estimation/B09_Estimation_UI_Shell.ts @@ -7,7 +7,7 @@ * 짝 계산(`…_Calc_*.ts`)으로 바로 다시 셈 · 새 산근(로직 연결) = 뒤에서 서버 셈(702-3 · `…_UI_Live`) · * [저장](702-3 · 왼쪽 아래 [초기화] 옆) = PUT → 서버 정본으로 다시 셈 · 저장 안 하고 단계 옮김 · [>] = 물음(저장 · 버림 · 머묾) * [>] = 물음 → POST …/estimation/complete(단계 6 완료) → `DRAFT.next`(인쇄 미리보기 · 초안) · 실패면 머묾 - * [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값 · [단가 갱신] = POST …/prices(795-4) + * [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값 * 호표 칸 누름 = 그 탭 그 줄로 이동 · 자동 저장 없음 * ========================================================================== */ @@ -338,14 +338,8 @@ export function renderB09Estimation(root: HTMLElement): void { show(current); }; - // keep = 화면 캐시 그대로(296 [업데이트] — 지운 줄 · 고친 칸을 안 되살림) · 참 = 성공 - const run = async ( - path: string, - method: string, - done: string, - init?: Row, - keep = false, - ): Promise => { + // 참 = 성공 + const run = async (path: string, method: string, done: string, init?: Row): Promise => { if (!projectId) return false; showLoadingOverlay(); try { @@ -353,8 +347,8 @@ export function renderB09Estimation(root: HTMLElement): void { method, ...(init ? { body: JSON.stringify(init) } : {}), }); - if (!keep) clearState("b09-estimation", projectId); - apply(next, !keep); + clearState("b09-estimation", projectId); + apply(next, true); showToast(done, "success"); return true; } catch (error) { @@ -372,21 +366,7 @@ export function renderB09Estimation(root: HTMLElement): void { : Promise.resolve(true); DRAFT.save = saveChanged; // 초안 [인쇄 미리보기] = 저장 뒤 이동(506-3) DRAFT.blocked = () => (payload ? unfinished(sheets) : null); // 701-3 인쇄 · 확정 = 빈 줄 0 - // 795-4 [단가 갱신] = 값만 · 미리 보기 창 [재생성] = `data-b09-job`(B09_Estimation_UI_Check) - const refresh = createButton({ - label: "단가 갱신", - variant: "ghost", - onClick: () => - void run( - "/estimation/prices", - "POST", - "단가를 지금 M01 값으로 새로 굳혔습니다.", - { user, ...(refresh.dataset.b09Job ? { job: refresh.dataset.b09Job } : {}) }, - true, - ), - }); - refresh.dataset.b09Refresh = ""; - const check = createCheckPanel(refresh, (link) => show(link.tab, link.key)); + const check = createCheckPanel((link) => show(link.tab, link.key)); // 298-2 [초기화] — 내역 · 단가 · 공기 · 요율 등 사용자 값 · 설정 모두 지움 → B08 수량 셈 값(견적서 파일 남김) const reset = createButton({ label: L("Common_Btn_Reset"), @@ -413,7 +393,7 @@ export function renderB09Estimation(root: HTMLElement): void { save.dataset.b09Save = ""; // 카드 = 좌측 패널 공용 카드(269 · 「구조물 배치」 양식) const section = createPanelCard("내역 점검", true); // 311 기본 접힘 - section.append(refresh, check.list); + section.append(check.list); // 303-1 · 304-1 하단 고정 줄 — [박스보기|호표보기] · [하이퍼링크|팝업] · 초안 단추 · [?][<][>][초기화] const actions = createDock([save, reset], () => isGroupTab(current) && show(current)); const left = document.createElement("div"); diff --git a/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts b/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts index d10a67f4f..7b8d22aee 100644 --- a/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts +++ b/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts @@ -63,7 +63,7 @@ export const buildLabor: TabBuild = ({ sheets }) => priceList( sheets.labor || [], "단가(원/인)", - "대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 [단가 갱신]", + "대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 구조물 다시 지정", ); export const buildExpense: TabBuild = () => gone(priceList([], "기준가(천원)", "").columns); @@ -290,7 +290,7 @@ export const buildMachine: TabBuild = ({ sheets }): TabTable => { ], rows, frozen: 2, - hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 [단가 갱신]", + hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 구조물 다시 지정", }; }; diff --git a/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts b/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts index 35096f463..27ac1eb34 100644 --- a/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts +++ b/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts @@ -287,7 +287,7 @@ function blockCard(ctx: TabContext, block: Row, noOf: Record): H ? [ edit, createText( - `품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · [단가 갱신] · [재생성] 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`, + `품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · 구조물 다시 지정 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`, "muted", ), ] diff --git a/M02_MasterTemplete/M02_MyMachine.py b/M02_MasterTemplete/M02_MyMachine.py index e6137860b..f41ba4c1a 100644 --- a/M02_MasterTemplete/M02_MyMachine.py +++ b/M02_MasterTemplete/M02_MyMachine.py @@ -469,16 +469,44 @@ def update(key: str, raw: Any, ver: str | None = None) -> dict[str, Any]: def delete(key: str) -> dict[str, Any]: - """지움 — 이미 만든 단가산출은 사본의 마지막 값 그대로(「지운키」).""" + """지움 — 쓰던 단가산출은 지우기 직전 값 그대로(`_hold` · 요구 902).""" _user() _old(key) - used = library_uses.machines().get(key, []) with _LOCK: _old(key) + used = library_uses.machines().get(key, []) + _hold(key, used) (_dir() / f"{key}.json").unlink(missing_ok=True) return {"지움": key, "쓰는곳": used} +def _hold(key: str, used: list[dict]) -> None: + """쓰던 단가산출 값 사본(옛 칸 · 수식)의 그 기계 줄 = 지금 따라와 있던 줄로 굳힘 — 지운 키는 사본 + 마지막 줄을 읽음(`M02_Sk_AutoRenew._fresh`) · 굳은 사본(프로젝트 등)은 그대로 · 잠금 안에서 부름.""" + from M02_MasterTemplete import M02_Sangeun_Copy as skc + from M02_MasterTemplete import M02_Sangeun_Doc as sd + from M02_MasterTemplete import M02_Sk_AutoRenew as renew + + if not renew.on(): # 안 따라오는 층 = 사본 그대로 + return + live = skc.whole_() + for one in used: + path = store._path(sd.KIND, str(one["키"])) + doc = json.loads(path.read_bytes()) + if renew.frozen(doc.get(skc.FORM)): + continue + for part in (skc.KEY, skc.FORM): + copy = doc.get(part) + old = copy.get("단가") if isinstance(copy, dict) else None + if isinstance(old, list): + new = [ + renew._fresh(r, live) if isinstance(r, dict) and r.get("키") == key else r + for r in old + ] + copy |= {"단가": new, "단가판": skc._fp(new)} + atomic_write_json(path, doc) + + def same(name: Any, spec: Any, skip: str = "") -> list[dict]: """같은 이름 · 규격 알림 — M01 기계 · 이 층 내 기계(표기 정규화 `M02_Machine_Find.norm`).""" from M02_MasterTemplete.M02_Machine_Find import norm diff --git a/common_util/common_util_formula_doc_cache.ts b/common_util/common_util_formula_doc_cache.ts index 792438dea..88c0a9d21 100644 --- a/common_util/common_util_formula_doc_cache.ts +++ b/common_util/common_util_formula_doc_cache.ts @@ -44,6 +44,8 @@ export interface DocCache { takeMissing: () => boolean; /** 표 하나 넣음(고르기에서 받은 것) */ putTable: (ref: string, table: DocTable) => void; + /** 표 통째(859-3 보이는 자리 — 줄마다 원문 글자 자리 `자리`) · 없으면 undefined */ + tableOf: (ref: string) => (DocTable & { 끊김?: string }) | undefined; } export function createDocCache(): DocCache { @@ -99,5 +101,8 @@ export function createDocCache(): DocCache { putTable(ref, table) { tables.set(ref, table); }, + tableOf(ref) { + return tables.get(ref) ?? undefined; + }, }; } diff --git a/common_util/common_util_show_digits.ts b/common_util/common_util_show_digits.ts new file mode 100644 index 000000000..56b0e6c89 --- /dev/null +++ b/common_util/common_util_show_digits.ts @@ -0,0 +1,154 @@ +/* ============================================================================= + * common_util_show_digits.ts + * 보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) — 셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만 + * ⚠ 짝 = resources/master_data/scripts/master_doc_digits.py(같은 규칙 · 한쪽을 고치면 다른 쪽도) · + * 거울 시험 resources/tester/test_859_3_show_digits.py + * 갈래(`digitKind`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 · 그 밖(요소 · 단가산출) → 「요소」 + * 규칙(자리 값은 `RULE` 한 곳): + * 표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 — 건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」 · + * 서버가 표 캐시에 줄마다 `자리` 를 실음) · 글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로 + * 식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) › + * 단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리(1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) › + * 그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수) + * 입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`) + * 수 꼴 = 천 단위 쉼표 · 반올림(Intl — 짧은 10 진 글 기준 0.5 올림) · 화면 · fetch 없음 + * ========================================================================== */ + +import { varId, type DocVar, type FormulaDoc } from "./common_util_formula_doc"; +import { findRow, type DocTable } from "./common_util_formula_doc_table"; +import { evalNode, tryParse, type Values } from "./common_util_formula_doc_view"; + +/** 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 PY `RULE`) */ +export const RULE = { + /** 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌) */ + plain: 6, + /** 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로 */ + symbol: { Q: 3, n: 2, cm: 3 } as Record, + /** 원 단위 중간 값(율 줄 단가 · 원/… 식 값) */ + money: 1, + /** 단위 없는 비목 값(기계 시간당 식) = 원 */ + moneyNames: ["노무비", "재료비", "경비"], + /** 그 밖 식 값 — 유효숫자 · 소수 최소(정수는 정수) · 최대 */ + sig: 3, + min: 2, + max: 6, +}; + +export type DigitKind = "식" | "표" | "입력" | "요소"; + +/** 서버 표 캐시 줄마다 원문 글자 자리(끝 0 있는 칸만) — `master_doc_record` 가 실음 */ +export type PlacedTable = DocTable & { 자리?: (Record | null)[] | null }; + +const formats = new Map(); +/** 소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표 */ +export function fmt(n: number, lo: number, hi: number): string { + const k = `${lo}:${hi}`; + let f = formats.get(k); + if (!f) { + f = new Intl.NumberFormat("ko-KR", { minimumFractionDigits: lo, maximumFractionDigits: hi }); + formats.set(k, f); + } + return f.format(n); +} + +/** 짧은 10 진 글의 [소수 자리, 맨 앞 자리 지수] — 0.0278 → [4, -2] */ +function digits(n: number): [number, number] { + const [m, e] = Math.abs(n).toExponential().split("e"); + const exp = Number(e); + const frac = (m.split(".")[1] ?? "").length; + return [Math.max(0, frac - exp), exp]; +} + +/** 표 값의 원문 글자 자리 — 지금 조건으로 고른 줄의 그 칸 · 값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = undefined) */ +export function tablePlaces( + v: DocVar | undefined, + value: unknown, + vals: Values, + tableOf?: (ref: string) => PlacedTable | null | undefined, +): number | undefined { + const k = v?.연결; + const ref = String(k?.표 ?? ""); + const col = k?.칸; + if (!tableOf || !ref || !col || ref.includes("{")) return undefined; + const 조건: Record = {}; + for (const [c, t] of Object.entries(k?.조건 ?? {})) { + const n = tryParse(t); + if (n) 조건[c] = evalNode(n, vals); + } + try { + const t = tableOf(ref); + if (!t?.줄) return undefined; + const row = findRow(t, 조건, col); + if (typeof row[col] !== "number" || row[col] !== value) return undefined; + return t.자리?.[t.줄.indexOf(row)]?.[col] ?? undefined; + } catch { + return undefined; + } +} + +/** 값 갈래 — 식 · 표 · 입력 · 요소 */ +export function digitKind(doc: Pick, name: string, v?: DocVar): DigitKind { + if ((doc.식 ?? []).some((x) => String(x.기호 ?? "") === name)) return "식"; + const kind = v?.연결?.갈래; + if (kind === "표") return "표"; + if (kind === "입력" || kind === "선택") return "입력"; + return v ? "요소" : "식"; +} + +/** 보이는 수 글 — `places` = 표 원문 글자 자리(모르면 없음) · 수가 아니면 글 그대로 */ +export function showDigits( + value: unknown, + kind: DigitKind = "요소", + name = "", + unit = "", + places?: number, +): string { + if (value === null || value === undefined || value === "") return ""; + if (typeof value !== "number" || !Number.isFinite(value)) return String(value); + const [own, exp] = digits(value); + if (kind === "표") { + const p = Math.max(places ?? 0, own); + return p <= RULE.plain ? fmt(value, p, p) : fmt(value, 0, RULE.plain); + } + if (kind !== "식") return fmt(value, 0, RULE.plain); + if (Object.prototype.hasOwnProperty.call(RULE.symbol, name)) + return fmt(value, 0, RULE.symbol[name]); + if (unit.trim().startsWith("원") || RULE.moneyNames.includes(name)) + return fmt(value, 0, RULE.money); + if (Number.isInteger(value)) return fmt(value, 0, 0); + const hi = Math.max(RULE.min, Math.min(RULE.max, RULE.sig - 1 - exp)); + return fmt(value, RULE.min, hi); +} + +/** 값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감(K = 만약(K_입력 > 0, K_입력, K_2) → K_2) */ +export function digitSource(doc: Pick, name: string, vals: Values): string { + const lines = new Map((doc.식 ?? []).map((x) => [String(x.기호 ?? ""), x.식])); + let at = name; + for (let hop = 0; hop < 8 && lines.has(at); hop++) { + let n = tryParse(lines.get(at)); + while (n && n[0] === "call" && n[1] === "만약" && n[2].length === 3) { + const t = evalNode(n[2][0], vals); + if (t === undefined) return at; + n = n[2][t ? 1 : 2]; + } + if (!n || n[0] !== "var" || n[1] === at) return at; + at = n[1]; + } + return at; +} + +/** 문서 기호 값 글 한 벌 — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위(`unit` = 부르는 쪽이 정한 단위) */ +export function showValue( + doc: Pick, + name: string, + value: unknown, + vals: Values, + tableOf?: (ref: string) => PlacedTable | null | undefined, + unit?: string, +): string { + const src = digitSource(doc, name, vals); + const v = (doc.변수 ?? []).find((x) => varId(x) === src); + const kind = digitKind(doc, src, v); + const places = kind === "표" ? tablePlaces(v, value, vals, tableOf) : undefined; + return showDigits(value, kind, src, unit ?? String(v?.단위 ?? ""), places); +} diff --git a/resources/master_data/scripts/master_doc_digits.py b/resources/master_data/scripts/master_doc_digits.py new file mode 100644 index 000000000..a848cab76 --- /dev/null +++ b/resources/master_data/scripts/master_doc_digits.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +"""보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) — +셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만. + +⚠ 짝 = `common_util/common_util_show_digits.ts`(같은 규칙 · 한쪽을 고치면 다른 쪽도) · + 거울 시험 `resources/tester/test_859_3_show_digits.py`. +갈래(`kind_of`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 · + 그 밖(요소 · 단가산출) → 「요소」. +규칙(자리 값은 `RULE` 한 곳): + 표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 — + 건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」) · + 글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로 + 식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) › + 단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리 + (1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) › + 그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수) + 입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`) +수 꼴 = 천 단위 쉼표 · 반올림(0.5 올림 · 짧은 10 진 글 기준 — 화면 `Intl` 과 같음). +""" + +from __future__ import annotations + +from decimal import ROUND_HALF_UP, Decimal, InvalidOperation + +#: 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 TS `RULE`) +RULE = { + "plain": 6, # 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌) + "symbol": {"Q": 3, "n": 2, "cm": 3}, # 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로 + "money": 1, # 원 단위 중간 값(율 줄 단가 · 원/… 식 값) + "money_names": ("노무비", "재료비", "경비"), # 단위 없는 비목 값(기계 시간당 식) = 원 + "sig": 3, # 그 밖 식 값 — 유효숫자 + "min": 2, # 〃 소수 최소(정수는 정수) + "max": 6, # 〃 소수 최대 +} + + +def dec(v) -> Decimal | None: + """수 → Decimal(화면 double 의 짧은 10 진 글 · 글 · 참거짓 · 빈 값 = None).""" + if isinstance(v, bool) or v is None or isinstance(v, str): + return None + try: + d = Decimal(repr(float(v))) # 화면 수(double)와 같은 짧은 10 진 글 + except (InvalidOperation, ValueError, TypeError, OverflowError): + return None + return d if d.is_finite() else None + + +def fmt(d: Decimal, lo: int, hi: int) -> str: + """소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표 + (Intl 과 같음 — 0 으로 반올림된 음수 = 「-0」).""" + q = d.quantize(Decimal(1).scaleb(-hi), ROUND_HALF_UP) + sign = "-" if q.is_signed() else "" + whole, _, frac = f"{abs(q):f}".partition(".") + frac = frac.rstrip("0") + frac += "0" * (lo - len(frac)) + head = f"{int(whole):,}" + return f"{sign}{head}.{frac}" if frac else f"{sign}{head}" + + +def places_of(d: Decimal) -> int: + """짧은 10 진 글의 소수 자리(0.10 → 1 · 3.0 → 0).""" + exp = d.normalize().as_tuple().exponent + return -exp if isinstance(exp, int) and exp < 0 else 0 + + +def text_places(d: Decimal) -> int: + """글자 그대로의 소수 자리(Decimal('0.10') → 2 · 표 파일 원문 글자).""" + exp = d.as_tuple().exponent + return -exp if isinstance(exp, int) and exp < 0 else 0 + + +def row_places(row: dict) -> dict: + """표 줄의 칸마다 원문 글자 자리 — 짧은 글보다 길 때만(끝 0 · 화면 캐시 `자리`).""" + out = {} + for col, v in row.items(): + if isinstance(v, Decimal) and v.is_finite() and text_places(v) > places_of(v): + out[col] = text_places(v) + return out + + +def table_places(table: dict) -> list | None: + """표 줄마다 `row_places`(끝 0 없는 줄 = None) · 표 통째 끝 0 없음 = None.""" + got = [row_places(r) if isinstance(r, dict) else {} for r in table.get("줄") or []] + return [x or None for x in got] if any(got) else None + + +def table_value_places(link: dict, value, evaluate, get_table) -> int | None: + """표 값의 원문 글자 자리 — 지금 조건으로 고른 줄(`find`)의 그 칸 글자 · + 값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = None) · + `evaluate(식 나무)` = 조건 값 · `get_table(키)` = 표(못 읽으면 None).""" + import master_doc as md + import master_doc_link as ml + + ref, col = str(link.get("표") or ""), link.get("칸") + if not ref or not col or "{" in ref: + return None + conds = {} + for c, t in (link.get("조건") or {}).items(): + try: + n = md.parse(t) + except md.DocError: + continue + conds[c] = evaluate(n) + try: + table = get_table(ref) + row = ml.find(table, conds, col) if table else None + except Exception: # noqa: BLE001 — 그림용 · 못 찾으면 자료 수 그대로 + return None + if not row or dec(row.get(col)) is None or dec(row.get(col)) != dec(value): + return None + return row_places(row).get(col) + + +def kind_of(doc: dict, name: str, var: dict | None = None) -> str: + """값 갈래 — 식 · 표 · 입력 · 요소.""" + if any(str(x.get("기호") or "") == name for x in doc.get("식") or []): + return "식" + kind = ((var or {}).get("연결") or {}).get("갈래") + if kind == "표": + return "표" + if kind in ("입력", "선택"): + return "입력" + return "요소" if var is not None else "식" + + +def show(v, kind: str = "요소", name: str = "", unit: str = "", places: int | None = None) -> str: + """보이는 수 글 — `places` = 표 원문 글자 자리(모르면 None) · 수가 아니면 글 그대로.""" + if v is None or v == "": + return "" + if isinstance(v, bool): + return "true" if v else "false" + d = dec(v) + if d is None: + return str(v) + if kind == "표": + p = max(places or 0, places_of(d)) + return fmt(d, p, p) if p <= RULE["plain"] else fmt(d, 0, RULE["plain"]) + if kind != "식": + return fmt(d, 0, RULE["plain"]) + if name in RULE["symbol"]: + return fmt(d, 0, RULE["symbol"][name]) + if str(unit or "").strip().startswith("원") or name in RULE["money_names"]: + return fmt(d, 0, RULE["money"]) + if d == d.to_integral_value(): + return fmt(d, 0, 0) + hi = max(RULE["min"], min(RULE["max"], RULE["sig"] - 1 - d.adjusted())) + return fmt(d, RULE["min"], hi) + + +def source(doc: dict, name: str, evaluate) -> str: + """값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감 · + `evaluate(식 나무)` = 그림용 값(모르면 None).""" + import master_doc as md + + lines = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []} + at = name + for _ in range(8): + if at not in lines: + break + try: + n = md.parse(lines[at]) + except md.DocError: + return at + while n and n[0] == "call" and n[1] == "만약" and len(n[2]) == 3: + t = evaluate(n[2][0]) + if t is None: + return at + n = n[2][1 if t else 2] + if not n or n[0] != "var" or n[1] == at: + return at + at = n[1] + return at + + +def show_value(doc: dict, name: str, v, evaluate, get_table, unit: str | None = None) -> str: + """문서 기호 값 글 한 벌(짝 TS `showValue`) — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위.""" + import master_doc as md + + src = source(doc, name, evaluate) + var = next((x for x in doc.get("변수") or [] if md.var_id(x) == src), None) + kind = kind_of(doc, src, var) + places = None + if kind == "표" and var is not None: + places = table_value_places(var.get("연결") or {}, v, evaluate, get_table) + return show(v, kind, src, str((var or {}).get("단위") or "") if unit is None else unit, places) diff --git a/resources/master_data/scripts/master_doc_record.py b/resources/master_data/scripts/master_doc_record.py index ee7b647b3..6ad4247ca 100644 --- a/resources/master_data/scripts/master_doc_record.py +++ b/resources/master_data/scripts/master_doc_record.py @@ -5,15 +5,17 @@ 브라우저가 같은 계산기(`common_util_formula_doc_calc.ts`)로 네트워크 없이 다시 셈. 화면 짝 = `common_util/common_util_formula_doc_cache.ts`(기록 → `DocLinks`). - 요소 = 부른 꼴(payload) 그대로 + {값 | 빈 | 끊김} -- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김} +- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김} · + 줄마다 원문 글자 자리 `자리`(859-3) - 단가산출 = 문서 통째(없으면 null) `prefetch` = 식 · 옵션과 무관하게 글로 적힌 표 · 단가산출 키를 미리 담음(구멍 `{…}` 든 키는 셈 때만). """ from __future__ import annotations -import master_doc_calc as mc import master_base as mf # 바탕 기반(색인 · 오류) +import master_doc_calc as mc +import master_doc_digits as mdd class Rec: @@ -52,6 +54,10 @@ class Rec: return keep = ("키", "원문번호", "이름", "조건", "범위규칙", "값칸", "줄") self.표[ref] = {k: table[k] for k in keep if k in table} + if places := mdd.table_places( + table + ): # 859-3 줄마다 원문 글자 자리(끝 0 · 화면이 수로 받으면 잃음) + self.표[ref]["자리"] = places def table(self, p: dict): self.see_table(str(p.get("표"))) diff --git a/resources/master_data/scripts/master_doc_text.py b/resources/master_data/scripts/master_doc_text.py index 9e1696287..26be79eb5 100644 --- a/resources/master_data/scripts/master_doc_text.py +++ b/resources/master_data/scripts/master_doc_text.py @@ -9,7 +9,8 @@ `common_util/common_util_formula_doc_view.ts`(`offLine` — 선택으로 꺼진 줄). 금액 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」 · 묶음 줄 = 비목마다 「노무비 : …」 · 계 = 「노무비 : 줄 + 줄 = 금액 원」 · 「합계 : 금액 원」. -수 꼴 = 화면과 같음 — 단가 · 수량 = `eqText`(소수 여섯 자리까지 · 셈 값 그대로) · +수 꼴 = 화면과 같음 — 단가 · 수량 = 보이는 자리 규칙(859-3 · `master_doc_digits` · + 짝 `common_util_show_digits.ts`) · 줄 금액 = 소수 한 자리 · 비목 · 합계 = 원(셈 답의 끝수 그대로 · 여기서 자르지 않음). 옮기지 않은 것(화면만) — 식 조판(KaTeX · 수량 식은 값 하나로) · 공식 줄 · 펼침 · 작업량 줄(846-2) · 굳은 기계 이름(847-1) · 비목곱 인수 글(848-7 · 금액은 답 그대로) · @@ -23,6 +24,7 @@ from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation import master_doc as md import master_doc_calc as mc +import master_doc_digits as mdd COSTS = md.COSTS # 노무비 · 재료비 · 경비 COST_SHOW = {"노무비": "노무비", "재료비": "재료비", "경비": "경 비"} @@ -211,6 +213,24 @@ def _num(v) -> Decimal | None: return _dec(v) +def _table_of(links): + """연결의 마스터 표 읽기(`Links.master` · 기록 `Rec.links.master`) — 없으면 None.""" + master = getattr(links, "master", None) or getattr( + getattr(links, "links", None), "master", None + ) + return master.get if master is not None else (lambda ref: None) + + +def shown(doc: dict, node, v, look: "_Look", links, money: bool = False) -> str: + """금액 줄 단가 · 수량 값 글(859-3) — 기호 하나 = 그 변수 갈래 규칙(표 = 원문 글자 자리) · + 상수 = 자료 그대로 · 식 = 식 규칙(`money` = 단가 = 원 단위).""" + if node and node[0] == "var": + return mdd.show_value(doc, node[1], v, look.value, _table_of(links)) + if node and node[0] == "num": + return mdd.show(v) + return mdd.show(v, "식", "", "원" if money else "") + + def _u(text: str, unit: str) -> str: return f"{text} {unit}" if unit else text @@ -236,6 +256,7 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: sub = None mu = money_units(line, node_of(line.get("단가")), node_of(line.get("수량")), pv, sub) qty = got.get("수량") + qty_text = shown(doc, node_of(line.get("수량")), qty, look, links) base = { "i": i, "이름": name, @@ -244,8 +265,9 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: "꺼짐": look.off_line(line), "합밖": bool(got.get("합밖")), "묶음": line.get("묶음") or "", + "수량글": qty_text, } - tail = "" if qty is None else " × " + _u(eq_text(qty), mu["qty"]) + tail = "" if qty is None else " × " + _u(qty_text, mu["qty"]) if got.get("까닭") and got.get("금액") is None: why = got["까닭"] out.append({**base, "비목": line.get("비목"), "단가": None, "금액": None, "까닭": why, @@ -260,12 +282,14 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: price = _u(eq_text(bundle.get(c)), mu["price"]) text = f"{COST_SHOW[c]} : {price}{tail} = {one(part)} {AMOUNT_UNIT}" out.append({**base, "비목": c, "묶음줄": True, "단가": _num(bundle.get(c)), + "단가글": eq_text(bundle.get(c)), "금액": _num(part), "글": text}) # fmt: skip continue amt, price = got.get("금액"), got.get("단가") - text = f"{name} : {_u(eq_text(price), mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}" - out.append({**base, "비목": line.get("비목"), "단가": _num(price), "금액": _num(amt), - "글": text}) # fmt: skip + price_text = shown(doc, node_of(line.get("단가")), price, look, links, money=True) + text = f"{name} : {_u(price_text, mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}" + out.append({**base, "비목": line.get("비목"), "단가": _num(price), "단가글": price_text, + "금액": _num(amt), "글": text}) # fmt: skip return out @@ -307,8 +331,8 @@ def sheet_groups(doc: dict, answer: dict, links) -> list[dict]: if x.get("까닭"): text = f"— {x['까닭']}" else: - price = "—" if x["단가"] is None else _u(eq_text(x["단가"]), mu["price"]) - qty = "" if x["수량"] is None else " * " + _u(eq_text(x["수량"]), mu["qty"]) + price = "—" if x["단가"] is None else _u(x["단가글"], mu["price"]) + qty = "" if x["수량"] is None else " * " + _u(x["수량글"], mu["qty"]) text = f"{price}{qty} = {one(x['금액'] or 0)}" groups[c].append( { diff --git a/resources/tester/helper_859_3_show_digits.cjs b/resources/tester/helper_859_3_show_digits.cjs new file mode 100644 index 000000000..f57f6f134 --- /dev/null +++ b/resources/tester/helper_859_3_show_digits.cjs @@ -0,0 +1,35 @@ +/* 859-3 거울 헬퍼 — 보이는 자리 규칙(TS `common_util_show_digits.ts`)을 Node 로 돌림(`master_doc_digits.py` 짝). + * stdin = {수: [[값, 갈래, 이름, 단위, 자리|null]], 갈래: [{문서: {식}, 이름, 변수}], 표: {키: 표}, 자리: [{변수, 값, 값들}], + * 문서값: [{문서: {식, 변수}, 값들, 기호: [[이름, 값]]}]} + * stdout = {수: [showDigits], 갈래: [digitKind], 자리: [tablePlaces | null], 문서값: [[showValue]]} */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); + +const cache = new Map(); +function load(at) { + if (cache.has(at)) return cache.get(at); + const js = ts.transpileModule(fs.readFileSync(at, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const box = { exports: {} }; + cache.set(at, box.exports); + const need = (p) => (p.startsWith(".") ? load(path.resolve(path.dirname(at), `${p}.ts`)) : require(p)); + new Function("exports", "module", "require", js)(box.exports, box, need); + return box.exports; +} +const dig = load(path.join(__dirname, "..", "..", "common_util", "common_util_show_digits.ts")); + +const input = JSON.parse(fs.readFileSync(0, "utf8")); +const tables = input.표 || {}; +const res = { + 수: (input.수 || []).map(([v, k, n, u, p]) => dig.showDigits(v, k, n, u, p ?? undefined)), + 갈래: (input.갈래 || []).map((x) => dig.digitKind(x.문서, x.이름, x.변수 ?? undefined)), + 문서값: (input.문서값 || []).map((x) => + x.기호.map(([n, v]) => dig.showValue(x.문서, n, v, x.값들, (k) => tables[k])), + ), + 자리: (input.자리 || []).map( + (x) => dig.tablePlaces(x.변수, x.값, x.값들, (k) => tables[k]) ?? null, + ), +}; +process.stdout.write(JSON.stringify(res)); diff --git a/resources/tester/test_144_b09_skeleton.py b/resources/tester/test_144_b09_skeleton.py index 5e5bb8f76..f3234c19a 100644 --- a/resources/tester/test_144_b09_skeleton.py +++ b/resources/tester/test_144_b09_skeleton.py @@ -52,7 +52,7 @@ def test_길_셋(): routes = {(r.path, tuple(sorted(r.methods))) for r in router_mod.router.routes} assert ("/api/projects/{project_id}/estimation", ("GET",)) in routes assert ("/api/projects/{project_id}/estimation", ("PUT",)) in routes - assert ("/api/projects/{project_id}/estimation/prices", ("POST",)) in routes + assert ("/api/projects/{project_id}/estimation/prices", ("POST",)) not in routes # 859-2 main = (ROOT / "main.py").read_text(encoding="utf-8") assert "app.include_router(b09_estimation_router" in main @@ -79,7 +79,7 @@ def test_사용자_값_다듬기_저장_자리(tmp_path): def test_841_1_단가_책_자재만(): """841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책 밖(B09 금액 = 사본 M02 엔진 값) · 자재만 굳힘.""" - book = prices.refresh_book(["EQ000004", "LB000048", "MT000401", "MO000002"]) + book = prices.make_book(["EQ000004", "LB000048", "MT000401", "MO000002"]) rows = book["rows"] assert set(rows) == {"MT000401", "MO000002"} and "driver_factor" not in book assert rows["MO000002"]["prices"]["유가"] > 0 @@ -109,7 +109,6 @@ def test_연결_없으면_빈_표와_연결_없음(tmp_path, monkeypatch): ("compare", "b08:cement"), ] assert any("연결된 구조물 조합 사본 없음" in n for n in body["notes"]) - assert body["book"] is None # GET 은 아무것도 쓰지 않음 assert not (tmp_path / "B09_Estimation").exists() diff --git a/resources/tester/test_203_1_b09_data_check.py b/resources/tester/test_203_1_b09_data_check.py index 5e09a2605..68b609e98 100644 --- a/resources/tester/test_203_1_b09_data_check.py +++ b/resources/tester/test_203_1_b09_data_check.py @@ -1,13 +1,11 @@ """203-1 B09 좌측 「데이터 점검」 묶음(사용자 60번). -- 묶음 이름 = 데이터 점검 · 안 설명 글 없음(굳힌 시각 · 까닭 = [업데이트] 공용 호버) -- [단가 갱신] → [업데이트] · 낡으면(서버 `book_stale` = 지금 M01 로 굳힌 책과 다름) 점 배지(is-pending) +- 묶음 이름 = 내역 점검 · [단가 갱신] · 낡음 점 배지 없음(859-2) - 「연결 점검」 탭 내용 = 묶음 안 목록(누르면 그 탭 그 줄) · 위 탭 줄에서 뺌 - 701-2 첫 화면 = 설계내역서 · 목록 머리 「빈 줄 n」 = 설계내역서 금액 모르는 줄(줄마다 하나 · 까닭 모음) · 그 밖(호표 · 재료) = 「그 밖 확인 n곳」(탭 · 키마다 하나) """ -import json import sys from pathlib import Path @@ -15,24 +13,12 @@ ROOT = Path(__file__).resolve().parents[2] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 from resources.tester.helper_b09_group_cards import TABS, run # noqa: E402 CHECK = "B09_Estimation/B09_Estimation_UI_Check.ts" SHELL = (ROOT / "B09_Estimation/B09_Estimation_UI_Shell.ts").read_text("utf-8") -def test_묶음_이름_단추_글_설명_없음(): - assert ( - 'createPanelCard("내역 점검", true)' in SHELL and "원가 단가" not in SHELL - ) # 269 공용 카드 - assert 'label: "단가 갱신",' in SHELL and 'label: "업데이트"' not in SHELL # 795-4 이름 - # 옛 굳힌 시각 안내 글(made) 없음 · 묶음 = 제목 · [단가 갱신] · 연결 점검 - assert "made.textContent" not in SHELL and "b09-estimation__hint" not in SHELL - assert "section.append(refresh, check.list);" in SHELL # 제목 = 공용 카드(269) - assert "check.draw(payload, sheets);" in SHELL - - def test_연결_점검_탭_없음_첫_화면_설계내역서(): out = run( [TABS], @@ -50,8 +36,7 @@ def test_좌측_목록_이동_호버_배지(): [TABS, CHECK], """ const moves = []; -const refresh = document.createElement("button"); -const panel = createCheckPanel(refresh, (link) => moves.push(link)); +const panel = createCheckPanel((link) => moves.push(link)); const sheets = { bill: { rows: [ { kind: "title", cost: "direct", key: "sec:1", name: "토공사", sum: null }, @@ -68,11 +53,10 @@ const sheets = { { tab: "material", key: "MT9", name: "모래", why: "단가 없음" }, ], }; -const payload = { book: { made: "2026-10-01T09:00:00" }, stale: "M01 에서 바뀐 단가 2", +const payload = { notes: ["B08 자재 집계표 못 읽음"], inputs: { missing: ["EQ1", "LB2"] } }; panel.draw(payload, sheets); const view = () => ({ - pending: refresh.classList.contains("is-pending"), texts: panel.list.children.map((c) => c.text), rows: [1, 3].flatMap((n) => (panel.list.children[n]?.children ?? []).map((r) => [r.dataset.i, r.className, r.text])), @@ -81,19 +65,15 @@ const a = view(); const blankBox = panel.list.children[1]; const rowsBox = panel.list.children[3]; rowsBox.children[1].click(); -const tipRefresh = hoverCalls.find((h) => h.root === refresh).text(); const rowHover = hoverCalls.find((h) => h.root === panel.list); const tipRow = rowHover.text(rowsBox.children[0]); const tipBlank = [0, 1].map((n) => rowHover.text(blankBox.children[n])); -panel.draw({ book: null, stale: null }, { gaps: [] }); +panel.draw({}, { gaps: [] }); const b = view(); -const tipEmpty = refreshTip({ book: null, stale: "단가 아직 안 굳힘" }); -console.log(JSON.stringify({ a, b, moves, tipRefresh, tipRow, tipBlank, selector: rowHover.selector, - tipEmpty })); +console.log(JSON.stringify({ a, b, moves, tipRow, tipBlank, selector: rowHover.selector })); """, ) a, b = out["a"], out["b"] - assert a["pending"] and not b["pending"] # 빈 줄 = 직접공사 항목 중 금액 모름(관급 · 제목 · 아는 줄 빼고) · 같은 줄 까닭은 하나로 assert a["texts"][0] == "금액 빈 줄 2" and a["texts"][2] == "그 밖 확인 2곳" assert a["rows"] == [ @@ -107,28 +87,4 @@ console.log(JSON.stringify({ a, b, moves, tipRefresh, tipRow, tipBlank, selector assert a["texts"][4:] == ["B08 자재 집계표 못 읽음", "M01 에 없는 키 2 — EQ1 · LB2"] assert out["moves"] == [{"tab": "material", "key": "MT9"}] assert out["tipRow"] == "대가 원천 없음" and out["selector"] == "[data-i]" - assert "단가 굳힘 2026-10-01 09:00:00" in out["tipRefresh"] - assert "단가 갱신 가능 — M01 에서 바뀐 단가 2" in out["tipRefresh"] assert b["texts"] == ["금액 빈 줄 0"] and b["rows"] == [] - assert out["tipEmpty"].startswith("단가 아직 안 굳힘") and "단가 갱신 가능" in out["tipEmpty"] - - -def test_배지_조건_서버_book_stale(): - keys = ["MT000401", "MT000338", "LB000002"] # 841-1 책 = 자재만(노임 키는 안 셈) - book = json.loads(json.dumps(prices.refresh_book(keys), ensure_ascii=False)) - assert prices.book_stale(book, keys) is None # 방금 굳힌 책 = 업데이트 필요 없음 - assert prices.book_stale(None, keys) == "단가 아직 안 굳힘" - first, *rest = list(book["rows"]) - old = {**book, "rows": {k: book["rows"][k] for k in rest}} - old["rows"][rest[0]] = {**old["rows"][rest[0]], "prices": {}} - assert prices.book_stale(old, keys) == "새 단가 줄 1 · M01 에서 바뀐 단가 1" - router = (ROOT / "B09_Estimation/B09_Estimation_Router.py").read_text("utf-8") - assert '"stale": await asyncio.to_thread(prices.book_stale, book, keys),' in router - - -def test_배지_꼴_경고_색_토큰(): - css = (ROOT / "B09_Estimation/B09_Estimation_UI_Page.css").read_text("utf-8") - block = css[css.index(".b09-options .ui-btn.is-pending::after") :] - block = block[: block.index("}")] - assert "position: absolute" in block and "border-radius: 50%" in block - assert "background: var(--color-warning)" in block diff --git a/resources/tester/test_253_3_haul_preview.py b/resources/tester/test_253_3_haul_preview.py index 159563ee9..3902b32f6 100644 --- a/resources/tester/test_253_3_haul_preview.py +++ b/resources/tester/test_253_3_haul_preview.py @@ -22,7 +22,7 @@ def test_미리보기_계산_절차(tmp_path): got = logic_preview(tmp_path, PreviewBody(code="GF000134", given=given)) assert got["unit"] == "㎥" and got["price"] and got["price"] > 0 assert "Cm : 109.78 분" in got["lines"] - assert any("60 * 15 * 1 * 0.9 / 109.78" in line for line in got["lines"]) + assert "작업량 = 7.378 ㎥/hr" in got["lines"] # 60 × 15 × 1 × 0.9 ÷ 109.78(B9-4 화면 꼴) assert got["lines"][-1].startswith("계 :") # 거리 늘면 단가도 늘음 far = logic_preview(tmp_path, PreviewBody(code="GF000134", given={**given, "Cm": 200})) diff --git a/resources/tester/test_296_b09_update_skip_deleted.py b/resources/tester/test_296_b09_update_skip_deleted.py deleted file mode 100644 index 2e4ca4563..000000000 --- a/resources/tester/test_296_b09_update_skip_deleted.py +++ /dev/null @@ -1,90 +0,0 @@ -"""296 B09 [업데이트] — 지워진 복사 정보는 업데이트에서 뺌(요구 190-4). - -- ① B09 에서 지운 복사 항목 = 화면 캐시(user)를 같이 보냄 → 그 줄이 안 잇는 서고 사본 = - 수요에서 뺌 · 책에 안 살아남 · 캐시 그대로(지운 줄 안 되살림) · 저장은 안 함 -- ② M01 원본이 지워진 키 = 옛 책 줄 그대로(지우지도 바꾸지도 않음) · 낡음 까닭에서 빠짐 -- 나머지 = 지금처럼 M01 값으로 새로 굳힘 · user 안 보내면 옛 길 그대로 -임시 층(견본 마스터 · 임시 storage) · 실제 마스터 · 프로젝트는 안 씀. -""" - -import asyncio -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from B09_Estimation import B09_Estimation_Bill_Library as library # noqa: E402 -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 -from B09_Estimation import B09_Estimation_Router as router # noqa: E402 -from B09_Estimation import B09_Estimation_Store as store_b09 # noqa: E402 -from B09_Estimation.B09_Estimation_Linked import linked_resource_keys # noqa: E402 -from resources.tester.test_204_2_b09_bill_library import COMBO, world # noqa: E402, F401 - - -def _json(book): - return json.loads(json.dumps(book, ensure_ascii=False)) - - -def _refresh(monkeypatch, root, body): - seen = {} - - async def fake_root(_): - return root - - async def fake_payload(_, at, draft=None): - seen["draft"] = draft - return {} - - monkeypatch.setattr(router, "_project_root", fake_root) - monkeypatch.setattr(router, "payload", fake_payload) - asyncio.run(router.refresh_prices("00000000-0000-0000-0000-000000000001", body)) - return store_b09.read_book(root), seen["draft"] - - -def test_지운_복사_항목_업데이트_뒤_안_살아남(world, monkeypatch): # noqa: F811 - root = world["root"] - a = library.import_copy(root, "precombo", "system", None, world["key"])["폴더"] - b = library.import_copy(root, "combo", "system", None, COMBO)["폴더"] - keep_a = set(prices.refresh_book(linked_resource_keys(root, {a}))["rows"]) - every = set(prices.refresh_book(linked_resource_keys(root))["rows"]) - assert keep_a < every # b 사본만 부르는 줄이 있음 - # 화면 캐시 = b 줄을 지움(아직 [저장] 안 함 · 사본 폴더는 남음) - ref = {"tab": "dg", "key": "DG:x", "lib": a} - user = {"bill": {"v": 2, "rows": [{"key": "hand:1", "name": "줄", "qty": 1, "ref": ref}]}} - book, draft = _refresh(monkeypatch, root, {"user": user}) - assert set(book["rows"]) == keep_a # 지운 사본 단가 줄 안 살아남 - assert draft["bill"]["rows"][0]["ref"]["lib"] == a # 응답 셈도 캐시로 - assert not (store_b09.folder(root) / store_b09.USER).exists() # 저장 안 함 - assert {f.name for f, _ in library.copies(root)} == {a, b} # 사본 정리는 [저장] 몫 - assert prices.book_stale(_json(book), linked_resource_keys(root, {a})) is None - # user 안 보냄 = 옛 길(다 쓴 사본 전부) - book, draft = _refresh(monkeypatch, root, None) - assert set(book["rows"]) == every and draft is None - - -def test_M01_원본_없는_항목_값_그대로_낡음_까닭_빠짐(): - gone = "MT999999" # 841-1 책 = 자재만 — 원본 없는 자재 키 - keys = ["MT000401", "MT000338", gone] - old = _json(prices.refresh_book(["MT000401", "MT000338"])) - kept = {"key": gone, "name": "지워진 자재", "origin": "M01", "prices": {"물가자료": 123.0}} - old["rows"][gone] = kept - old["rows"]["MT000401"] = {**old["rows"]["MT000401"], "prices": {}} # M01 에서 바뀐 단가 - assert prices.book_stale(old, keys) == "M01 에서 바뀐 단가 1" # 원본 없는 줄 = 까닭에 없음 - new = _json(prices.refresh_book(keys, old)) - assert new["rows"][gone] == kept # 지우지도 바꾸지도 않음 - assert new["rows"]["MT000401"]["prices"] != {} # 나머지 = 새로 굳힘 - assert set(new["rows"]) == set(old["rows"]) - assert prices.book_stale(new, keys) is None - assert gone not in prices.refresh_book(keys)["rows"] # 옛 책 없으면 줄 없음(옛 길) - - -def test_화면_업데이트_캐시_보냄_그대로_둠(): - shell = (ROOT / "B09_Estimation/B09_Estimation_UI_Shell.ts").read_text("utf-8") - at = shell.index('"/estimation/prices",') - assert "{ user, ...(refresh.dataset.b09Job" in shell[at : at + 200] # 795-4 할일 덧칸 - assert "\n true," in shell[at : at + 200] - assert 'if (!keep) clearState("b09-estimation", projectId);' in shell - assert "apply(next, !keep);" in shell diff --git a/resources/tester/test_703_3_b09_refresh.py b/resources/tester/test_703_3_b09_refresh.py deleted file mode 100644 index 0f4e59c05..000000000 --- a/resources/tester/test_703_3_b09_refresh.py +++ /dev/null @@ -1,75 +0,0 @@ -"""703-3 B09 [업데이트] 한 곳 — 단가 책 다시 굳힘 + 원본이 바뀐 구조물 사본 재적용. - -- 미리 보기 수(`Refresh.preview`) = 적용 뒤 책 견줌(`Prices.book_diff`) 수 · 노임 판 전 → 후 · 고친 칸 수 -- 재적용 = 연결된 사본 중 원본이 바뀐 것만 · 하나가 막혀도 나머지 · 덮개(사용자 값) 안 건드림 -""" - -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 -from B09_Estimation import B09_Estimation_Refresh as refresh # noqa: E402 -from B09_Estimation import B09_Estimation_Store as store # noqa: E402 - -#: 841-1 책 = 자재만(노임 키 = 노임 판만 셈) — 원목 · 미송각재 + 작업반장(건설업) -KEYS = ["MT000401", "MT000338", "LB000001"] - - -def test_책_견줌_미리보기_수_적용_수_같음(tmp_path, monkeypatch): - monkeypatch.setattr(refresh, "changed_copies", lambda root: []) - new = prices.refresh_book(KEYS) - assert new["labor_edition"] == prices.labor_editions(KEYS) and new["labor_edition"] - old = json.loads(json.dumps(new)) - old["rows"]["MT000401"] = {**old["rows"]["MT000401"], "prices": {}} # 옛 값 - del old["rows"]["MT000338"] # 새 줄 - old["labor_edition"] = {"건설업": "2025-09-01"} - cover = { - "S:a": {"x#0": {"qty": 1, "labor": 2}}, - "K:b": {"@copy": {"from": "S:a"}, "y#0": {"qty": 3}}, - } - got = refresh.preview(tmp_path, old, KEYS, cover) - after = prices.refresh_book(KEYS, old) - diff = prices.book_diff(old, after) - assert (got["새줄"], got["바뀐줄"]) == (diff["new"], diff["changed"]) == (1, 1) - assert got["단가줄"] == 2 and got["고친칸"] == 3 and got["사본"] == [] - assert got["노임판"]["전"] == "건설업 2025-09" - assert got["노임판"]["후"].startswith("건설업 2026") - old.pop("labor_edition") - assert refresh.preview(tmp_path, old, KEYS, None)["노임판"]["전"].startswith("굳힌 날 ") - assert prices.book_diff(after, prices.refresh_book(KEYS, after)) == {"new": 0, "changed": 0} - assert prices.book_stale(after, KEYS) is None - - -def test_재적용_원본_바뀐_사본만_막혀도_나머지_덮개_그대로(tmp_path, monkeypatch): - cover = {"S:a": {"x#0": {"qty": 0.3}}} - store.write_user(tmp_path, {"daega_cover": cover}) - monkeypatch.setattr( - refresh, - "linked_snapshots", - lambda root: {"p1": {"폴더": "a"}, "p2": {"폴더": "b"}, "p3": {"폴더": "c"}}, - ) - items = [ - {"폴더": "a", "이름": "가", "마스터바뀜": True}, - {"폴더": "b", "이름": "나", "마스터바뀜": False}, # 원본 그대로 = 안 함 - {"폴더": "c", "이름": "다", "마스터바뀜": True}, - {"폴더": "z", "이름": "끊김", "마스터바뀜": True}, # 연결 안 됨 = 안 함 - ] - monkeypatch.setattr(refresh.item_copy, "list_items", lambda root: items) - calls = [] - - def fake(root, folder, who=None): - calls.append(folder) - if folder == "c": - raise LookupError("원본 층 없음") - - monkeypatch.setattr(refresh.item_copy, "reapply", fake) - assert [c["이름"] for c in refresh.changed_copies(tmp_path)] == ["가", "다"] - got = refresh.reapply_changed(tmp_path) - assert calls == ["a", "c"] - assert got == {"다시": ["가"], "막힘": ["다 — 원본 층 없음"]} - assert store.read_user(tmp_path)["daega_cover"] == cover diff --git a/resources/tester/test_719_2_sk_project.py b/resources/tester/test_719_2_sk_project.py index c32d51746..e6a6b2684 100644 --- a/resources/tester/test_719_2_sk_project.py +++ b/resources/tester/test_719_2_sk_project.py @@ -1,11 +1,10 @@ -"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · [재생성](업데이트) · 서고(임시 +"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · 구조물 [재적용] · 서고(임시 storage · 실제 M01 읽기만). - 사본 SK(수식 따로 사본) = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 줄 = 문서 답 금액 줄 (M02 에서 고친 문서 그대로) · 금액 = M02 SK 셈 -- [재생성] = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · - 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 - · 미리 보기 SK 줄 +- 구조물 [재적용](다시 지정) = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 + 그대로 · 덮개 밑 값(base) = 새 단가산출 값(859-2 프로젝트 안 [재생성] 걷음) (옛 칸 덮개 · 더한줄 SK · 내 자료집 = 옛 칸 SK 만들기는 855 2-C1 셈 은퇴 — 시험 없음) """ @@ -16,7 +15,6 @@ import pytest from B09_Estimation import B09_Estimation_Bill_Library as library from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun from B09_Estimation.B09_Estimation_Calc_Base import compute_base from B09_Estimation.B09_Estimation_Calc_Labor import compute_labor @@ -154,23 +152,6 @@ def test_구조물_사본_SK_줄_재생성_덮개_입력값_고른자재_그대 assert daega2["owners"]["pipe@100.0"] in done -def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): - key = _mine(world) - root, folder = _lib(world, tmp_path, key) - assert library.changed(root) == [] - before = daega_inputs(root) - cover_key = next(b for b in before["blocks"] if b["id"] == before["libs"][folder])["cover"] - edit(world["personal"], key, 3) - got = refresh.preview(root, None, [], None) - assert [(x["키"], x["판"]) for x in got["단가산출"]] == [(key, "바뀜")] - assert [c["폴더"] for c in got["사본"]] == [folder] - assert refresh.reapply_changed(root)["다시"] == ["내 단가산출"] - assert library.changed(root) == [] and [f.name for f, _ in library.copies(root)] == [folder] - after = daega_inputs(root) - block = next(b for b in after["blocks"] if b["id"] == after["libs"][folder]) - assert block["cover"] == cover_key and block["lines"][0]["qty"] == pytest.approx(0.108) - - def test_SK_하위_단가산출_줄_산근(world, tmp_path): """사본 SK 문서 줄이 부른 하위 단가산출 = 대가 블록 산근 줄 · B09 산근 목록에 그 키(855-F B9-5).""" key = _sk(world["personal"], 바탕={"로직": "GF000206"}) # 합판거푸집 → GF000160 부름 diff --git a/resources/tester/test_795_4_b09_copy.py b/resources/tester/test_795_4_b09_copy.py index c25ced794..09f3b780a 100644 --- a/resources/tester/test_795_4_b09_copy.py +++ b/resources/tester/test_795_4_b09_copy.py @@ -1,25 +1,20 @@ # ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀 -"""795-4 프로젝트(B09) 사본 규칙 — 만든 때 그대로 · [단가 갱신] 값만 · [재생성] 따로 · +"""795-4 프로젝트(B09) 사본 규칙 — 만든 때 그대로 · 시점 섞임 고침(임시 storage · M01 은 메모리 덮개 · 정본 안 고침). ① 구조물 사본 단가 묶음 = M02 일위대가 사본 줄(만든 때) · 뒤에 M01 로직 · 노임이 바뀌어도 사본 금액 그대로 · M01 에서 지워진 키 = 사본 줄 그대로 ② 사본 없는 옛 문서 = 옛 길(지금 M01) ③ [저장] 새 단가 줄 = 사본 기준 시점 값 · 없는 자원만 지금 값 + 표지 · 옛 책 줄 그대로 -④ 연결 사본 `단가.json` 자원 줄 = 기준 시점 원천 ⑤ [단가 갱신] = 값만(사본 재적용 없음) · - [재생성] = 따로 누를 때만 ⑥ 미리 보기 꼴. +④ 연결 사본 `단가.json` 자원 줄 = 기준 시점 원천(859-2 [단가 갱신] · [재생성] 걷음). """ from __future__ import annotations -import asyncio import copy import json -from uuid import uuid4 from B09_Estimation import B09_Estimation_Linked as linked from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh -from B09_Estimation import B09_Estimation_Router as router from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Item_Source as source @@ -125,11 +120,9 @@ def test_book_new_rows_use_copy_basis(): inputs = prices.build_inputs(None, [WOOD, BAR], None, frozen) assert [_price(r) for r in inputs["materials"]] == [111, _price(both["rows"][BAR])] assert inputs["now"] == [BAR] and prices.build_inputs(both, [WOOD, BAR])["now"] == [BAR] - old = _json(prices.refresh_book([WOOD, BAR])) # 옛 책(사본 규칙 전) = 줄 · 값 그대로 + old = _json(prices.make_book([WOOD, BAR])) # 옛 책(사본 규칙 전) = 줄 · 값 그대로 again = _json(prices.extend_book(old, [WOOD, BAR], frozen)) assert again["rows"] == old["rows"] and again["now_keys"] == [] - fresh = _json(prices.refresh_book([WOOD, BAR], both)) # [단가 갱신] = 지금 값 · 표지 없음 - assert _price(fresh["rows"][WOOD]) != 111 and fresh["now_keys"] == [] def test_frozen_rows_from_linked_copy(tmp_path): @@ -143,50 +136,3 @@ def test_frozen_rows_from_linked_copy(tmp_path): ) inside = {r["키"]: r for d in bundle.values() if isinstance(d, dict) for r in d.get("줄") or []} assert all(inside[k] == row for k, row in got.items()) - - -def _router(monkeypatch, tmp_path, calls): - async def root(_): - return tmp_path - - async def demand(*_): - return [LB] - - async def payload(*_a, **_k): - return {"user": {}, "notes": [], "sheets": {}} - - monkeypatch.setattr(router, "_project_root", root) - monkeypatch.setattr(router, "_demand", demand) - monkeypatch.setattr(router, "payload", payload) - monkeypatch.setattr(router.store, "read_book", lambda _r: None) - monkeypatch.setattr(router.store, "write_book", lambda _r, b: calls.append(("book", b))) - monkeypatch.setattr( - router.refresh, - "reapply_changed", - lambda *_a: calls.append("regen") or {"다시": ["A"], "막힘": []}, - ) - - -def test_price_refresh_default_regen_separate(monkeypatch, tmp_path): - """⑤ [단가 갱신] = 값만(사본 재적용 없음) · [재생성] = job 줄 때만.""" - calls = [] - _router(monkeypatch, tmp_path, calls) - out = asyncio.run(router.refresh_prices(uuid4(), {"user": {}}, {})) - assert "regen" not in calls and calls[-1][0] == "book" - assert out["notes"][0].startswith("단가 갱신 — ") - out = asyncio.run(router.refresh_prices(uuid4(), {"user": {}, "job": refresh.REGEN}, {})) - assert calls.count("regen") == 1 - assert out["notes"][0].startswith("재생성 — 구조물 사본 1 다시 가져옴") - - -def test_price_preview_shape(): - """⑥ 미리 보기 — 바뀐 자원(사본 자원 줄 먼저 · 자재 단가 책) · 총괄 전 → 후.""" - old = _json(prices.refresh_book([WOOD, BAR])) - old["rows"][WOOD] = {**old["rows"][WOOD], "prices": {"물가자료": 1}} - new = _json(prices.refresh_book([WOOD, BAR], old)) - sheets = lambda g: {"total": {"subtotals": {"grand": g}}} # noqa: E731 - copies = [{"키": LB, "이름": "사본 노임", "전": 1, "후": 2}] - got = refresh.price_preview(old, new, sheets(10), sheets(20), 3, copies) - assert got["할일"] == "단가갱신" and (got["전"], got["후"], got["고친칸"]) == (10, 20, 3) - assert [(r["키"], r["전"]) for r in got["바뀐자원"]] == [(LB, 1), (WOOD, {"물가자료": 1})] - assert got["바뀐자원"][1]["후"] == new["rows"][WOOD]["prices"] diff --git a/resources/tester/test_821_1_my_machine.py b/resources/tester/test_821_1_my_machine.py index 4399d291e..4ff959be9 100644 --- a/resources/tester/test_821_1_my_machine.py +++ b/resources/tester/test_821_1_my_machine.py @@ -169,6 +169,24 @@ def test_sk_copy_edit_refresh_delete(world): assert float(look["후"]["계"]) == new +def test_auto_sk_keeps_value_after_delete(world, monkeypatch): + """요구 902 — 자동 따라옴 SK 가 따라온 값은 기계를 지워도 그대로(마지막 저장 값으로 안 돌아감).""" + from M02_MasterTemplete import M02_Sk_AutoRenew as renew + + monkeypatch.setattr(renew, "on", lambda: True) + me = world["personal"] + made = _at(me, mym.create, _easy()) + key = made["줄"]["키"] + sk = _sk(me, made["줄"]["원문번호"]) + was = _sum(me, sk) + _at(me, mym.update, key, _easy(가격=3000)) + followed = _sum(me, sk) + assert followed != was # 저장 없이 따라옴 + _at(me, mym.delete, key) + after = _calc(me, _doc(me, sk)) + assert after["기준"]["계"] == followed and after["사본"]["지운키"] == [key] + + def test_m01_only_sk_same(world): """⑤ 내 기계가 있는 층에서도 M01 만 쓰는 SK 금액 · 사본 같음 · 사본 모으기에 내 기계 안 낌.""" me, other = world["personal"], layers.personal_dir(7, 43) diff --git a/resources/tester/test_821_3_my_machine_screen.py b/resources/tester/test_821_3_my_machine_screen.py index 1bbd5e1de..0d62ea329 100644 --- a/resources/tester/test_821_3_my_machine_screen.py +++ b/resources/tester/test_821_3_my_machine_screen.py @@ -113,7 +113,7 @@ def _stack_doc(key, no): def test_stack_line_copy(world): """⑤ 줄 쌓기로 고른 내 기계 — 미리 셈 됨 · 저장 때 값 사본에 박힘 → - 고치면 자동 따라옴(836-2 · 갱신 할 것 없음) → 지워도 저장한 사본 값 + 지운키.""" + 고치면 자동 따라옴(836-2 · 갱신 할 것 없음) → 지워도 지우기 직전 따라온 값 + 지운키(요구 902).""" from M02_MasterTemplete import M02_Doc_Sk_Path as path from M02_MasterTemplete import M02_Labor_Ref as refs @@ -139,7 +139,7 @@ def test_stack_line_copy(world): assert job["바뀐자원"] == [] and job["후"]["계"] == now["셈"]["계"] _at(me, mym.delete, key) gone = _at(me, path.read, sk) - assert gone["셈"]["계"] == was # 지운 키 = 저장한 사본 줄 값 + assert gone["셈"]["계"] == now["셈"]["계"] # 지운 키 = 지우기 직전 따라온 값(요구 902) def _mine_row(): diff --git a/resources/tester/test_845_2_unit_show.py b/resources/tester/test_845_2_unit_show.py index 67c0ca008..f6dbf5d4c 100644 --- a/resources/tester/test_845_2_unit_show.py +++ b/resources/tester/test_845_2_unit_show.py @@ -86,7 +86,8 @@ def test_GC000088_비목_줄_단위_자리(world): "⟦\\text{휴지율}⟧ = ⟦\\dfrac{\\text{월간급여지급일}}{\\text{월간가동일수}}⟧ = ⟦\\dfrac{25}{20}⟧" in sub ) - assert "\\dfrac{1}{8} \\times 1.333333 \\times 1.25⟧ = ⟦0.208333" in sub + # 859-3 식이 낸 값 = 유효숫자 3(그림만 · 금액 59,020.2 그대로) + assert "\\dfrac{1}{8} \\times 1.33 \\times 1.25⟧ = ⟦0.208\\ " in sub assert ( "\\text{노무비 계수}⟧ = ⟦\\dfrac{\\text{일}}{\\text{일일근무시간}} \\times \\text{상여율} \\times \\text{휴지율}⟧" in sub @@ -97,7 +98,7 @@ def test_GC000088_비목_줄_단위_자리(world): assert "⟦\\text{가격}⟧ = 142,069 천원" in sub assert "⟦\\text{직종}⟧ = 1048" in sub # 코드 값 = 쉼표 없음 assert ( - "조종원 : ⟦283{,}297⟧ 원/인 × ⟦\\left(1 \\times 0.208333\\right)⟧ 인 = 59,020.2 원" in sub + "조종원 : ⟦283{,}297⟧ 원/인 × ⟦\\left(1 \\times 0.208\\right)⟧ 인 = 59,020.2 원" in sub ) assert "⟦\\text{가산}⟧ = ⟦0\\ \\text{\\%}⟧" in sub # % = TeX 글(주석으로 안 먹힘) diff --git a/resources/tester/test_859_3_show_digits.py b/resources/tester/test_859_3_show_digits.py new file mode 100644 index 000000000..849169537 --- /dev/null +++ b/resources/tester/test_859_3_show_digits.py @@ -0,0 +1,161 @@ +"""859-3 지킴 — 보이는 수 자릿수 규칙 한 쌍 +(TS `common_util_show_digits.ts` ↔ PY `master_doc_digits.py`). + +① 거울 — 같은 값 · 갈래 · 기호 · 단위 · 표 자리 → 같은 글(헬퍼 `helper_859_3_show_digits.cjs`) · + 갈래 판정 · 표 값 원문 글자 자리(서버 표 캐시 `자리` → 화면 `tablePlaces`) · 문서 기호 값 글 — + M01 수식 문서 전부(기본 입력 셈 답). +② 규칙 결과 — 표 값 끝 0 살림 · 식 품 유효숫자 3 · 원 단위 소수 한 자리 · 8-1 Q 3 자리 · + 입력 · 요소 그대로. +③ 그림만 — 서버 산출근거 글의 금액은 셈 답 그대로(글 끝 「= 금액」 = 줄 금액 소수 한 자리). +""" + +from __future__ import annotations + +import importlib +import json +import os +import subprocess +from decimal import Decimal +from functools import lru_cache + +from M01_MasterData import M01_MasterData_Doc as m01_doc +from M01_MasterData import M01_MasterData_Store as m01 +from M02_MasterTemplete import M02_Logic_Standard as st + +mc = importlib.import_module("master_doc_calc") +md = importlib.import_module("master_doc") +mdd = importlib.import_module("master_doc_digits") +mdt = importlib.import_module("master_doc_text") +rec = importlib.import_module("master_doc_record") + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUMS = [0, 1, -1, 8, 250, 0.5, 1.5, 2.5, -2.5, 0.05, 0.15, 0.25, 0.35, 1.05, 1.005, 2.675, 99.95, + -0.05, 0.1 + 0.2, 1e-7, 0.0004, 0.000417, 0.027778, 0.0285, 0.0995, 0.99999, 1.4552, + 0.606061, 33971.813333, 535.396667, 12987.917773, 2446.08, 1234567.891234567, + 59018.0857142857, 284.42142857142, 123456789012.345, 26890.75, 1502.04999, + 0.1, 3.0] # fmt: skip +KINDS = [("식", "", ""), ("식", "Q", ""), ("식", "n", ""), ("식", "cm", ""), ("식", "", "원/시간"), + ("식", "", "인"), ("표", "", ""), ("입력", "", ""), ("요소", "", "원/인")] # fmt: skip + + +def _js(v): + if isinstance(v, Decimal): + return float(v) + if isinstance(v, dict): + return {k: _js(x) for k, x in v.items()} + if isinstance(v, (list, tuple)): + return [_js(x) for x in v] + if isinstance(v, (mc.Blank, mc.Stop)): + return None + return v + + +@lru_cache(maxsize=1) +def world(): + whole = m01.loaded()[1] + docs = m01_doc.docs() + links = st._links(whole) + answers = {k: mc.calc(d, links, None) for k, d in docs.items() if d.get("금액")} + return docs, links, answers + + +def _helper(payload: dict) -> dict: + run = subprocess.run( + ["node", os.path.join(HERE, "helper_859_3_show_digits.cjs")], + input=json.dumps(payload, ensure_ascii=False), + capture_output=True, + text=True, + encoding="utf-8", + check=True, + ) + return json.loads(run.stdout) + + +@lru_cache(maxsize=1) +def mirror(): + docs, links, answers = world() + nums = [[v, k, n, u, p] for v in NUMS for k, n, u in KINDS for p in (None, 2, 3)] + kinds, places, tables, py = [], [], {}, {"수": [], "갈래": [], "자리": [], "문서값": []} + whole = [] + keep = rec.Rec(links) + for key, a in answers.items(): + doc = docs[key] + vals = a.get("값") or {} + look = mdt._Look(doc, a, links) + shown = {k: _js(v) for k, v in vals.items() if v is not None} + names = [md.var_id(x) for x in doc.get("변수") or []] + names += [str(x.get("기호") or "") for x in doc.get("식") or []] + pairs = [[n, float(vals[n])] for n in names if isinstance(vals.get(n), Decimal)] + get = links.master.get + py["문서값"].append([mdd.show_value(doc, n, vals[n], look.value, get) for n, _ in pairs]) + part = {"식": doc.get("식") or [], "변수": _js(doc.get("변수") or [])} + whole.append({"문서": part, "값들": shown, "기호": pairs}) + for var in doc.get("변수") or []: + name = md.var_id(var) + kinds.append({"문서": {"식": doc.get("식") or []}, "이름": name, "변수": _js(var)}) + py["갈래"].append(mdd.kind_of(doc, name, var)) + v = vals.get(name) + link = var.get("연결") or {} + if link.get("갈래") != "표" or not isinstance(v, Decimal): + continue + ref = str(link.get("표") or "") + keep.see_table(ref) + tables[ref] = _js(keep.표[ref]) + places.append({"변수": _js(var), "값": float(v), "값들": shown}) + py["자리"].append(mdd.table_value_places(link, v, look.value, links.master.get)) + nums.append([float(v), "표", name, "", py["자리"][-1]]) + for v, k, n, u, p in nums: + py["수"].append(mdd.show(v, k, n, u, p)) + every = [v for d in docs.values() for v in d.get("변수") or []] + refs = {str((v.get("연결") or {}).get("표") or "") for v in every} + for ref in refs: + if ref and "{" not in ref and ref not in tables: + keep.see_table(ref) + tables[ref] = _js(keep.표[ref]) + ts = _helper({"수": nums, "갈래": kinds, "표": tables, "자리": places, "문서값": whole}) + return nums, py, ts + + +def test_수_꼴_거울(): + nums, py, ts = mirror() + assert len(nums) > 7000 + bad = [(n, a, b) for n, a, b in zip(nums, py["수"], ts["수"]) if a != b] + assert not bad, bad[:10] + + +def test_갈래_표_자리_거울(): + _, py, ts = mirror() + assert len(py["갈래"]) > 10000 and py["갈래"] == ts["갈래"] + assert len(py["자리"]) > 7000 and py["자리"] == ts["자리"] + assert sum(1 for p in py["자리"] if p) > 500 # 끝 0 글자 자리가 실제로 실려 감 + + +def test_문서_기호_값_글_거울(): + _, py, ts = mirror() + assert sum(map(len, py["문서값"])) > 15000 + bad = [(a, b) for x, y in zip(py["문서값"], ts["문서값"]) for a, b in zip(x, y) if a != b] + assert not bad and py["문서값"] == ts["문서값"], bad[:10] + + +def test_규칙_결과(): + show = mdd.show + assert show(0.1, "표", "Q_수량^표", "인", 2) == "0.10" # 원문 글자 끝 0 + assert show(0.1, "표") == "0.1" and show(3.0, "표", "", "", 1) == "3.0" + assert show(0.027778, "식", "Q_보링공", "인") == "0.0278" # 유효숫자 3 + assert show(1.4552, "식") == "1.46" and show(8, "식") == "8" + assert show(33971.813333, "식", "", "원") == "33,971.8" # 원 단위 한 자리 + assert show(70.12345, "식", "Q") == "70.123" and show(2.456, "식", "n") == "2.46" + assert show(0.027778, "입력") == "0.027778" and show(1846.39, "요소") == "1,846.39" + assert show("5401-0017") == "5401-0017" and show(None) == "" and show(1048, "입력") == "1,048" + + +def test_서버_글_금액_그대로(): + docs, links, answers = world() + for key in ("GF000220", "GC000994", "GC000996"): + for line in mdt.money_lines(docs[key], answers[key], links): + if line.get("금액") is not None: + assert line["글"].endswith(f"= {mdt.one(line['금액'])} 원") + got = {x["이름"]: x for x in mdt.money_lines(docs["GC000994"], answers["GC000994"], links)} + assert got["보링공"]["수량글"] == "0.0278" + rate = [x for x in mdt.money_lines(docs["GC000996"], answers["GC000996"], links)] + assert any(x.get("단가글") == "33,971.8" for x in rate)