From bfe29acf604a2a32c3a0eb4f4beb1b073984c35e Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:46:38 +0900 Subject: [PATCH 1/4] =?UTF-8?q?refactor(855-2-D):=20=EB=8B=A8=EA=B0=80?= =?UTF-8?q?=EC=82=B0=EC=B6=9C=20=EC=B8=B5=20=EC=A0=80=EC=9E=A5=20=EA=BC=B4?= =?UTF-8?q?=20=3D=20=EB=82=A8=EB=8A=94=20=EC=B9=B8=EB=A7=8C=20=E2=80=94=20?= =?UTF-8?q?=EA=B0=92=20=EC=82=AC=EB=B3=B8=20=3D=20=EC=88=98=EC=8B=9D=20?= =?UTF-8?q?=ED=95=9C=20=EB=B2=8C(=EC=82=AC=EB=B3=B8=20=EC=95=88=20?= =?UTF-8?q?=EC=94=80)=20=C2=B7=20=EB=B9=88=20=EC=98=9B=20=EC=B9=B8=20?= =?UTF-8?q?=C2=B7=20M01=ED=8C=90=20=EC=95=88=20=EC=94=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 저장 관문 `Copy_Slim.trim`(층 저장만 · 프로젝트 층은 안 탐) — `사본` 값을 `수식` 값 몫에 얹고 `사본` 뺌 · 빈 옛 칸(입력값 · 열린입력 · 고름 · 자재표시 · 켜쌓기율 · 덮개 · 뺀줄 · 뺀더한줄 · 상수덮개 · 표값덮개 · 글줄 · 까닭 · 수식고침 · 변수줄 · 식덮개) 뺌 · 값 든 옛 칸 = 그대로(못 셈 + 까닭) · `더한줄` = 서고 뼈대 표지라 남김 - `Sangeun_Copy.held` = 값 사본 한 곳(셈 중 `사본` › 층 파일 `수식` 값 몫) — `over` · `settle`(저장본 · 받은 문서) · `same_part` 가 씀 · `Copy.logic` = 사본 줄 › M01 › 속 색인이 따로 내주는 줄(굳힌 사본 `_Over`) - `Sangeun_Const.stamp` = `바탕판` 만(화면 「기초가 바뀜」 이 읽음) · `M01판`(읽던 시트 2-C1 에서 걷음) 안 적음 - 층 서고 SK 14 + SC 6 다시 저장(임시 복사본 · `resave.py`): 셈 답 같음 20 / 20 · SK 칸 18 → 12(가져온 식 12 · 그 밖 11) · 크기 408 → 309 KB - 시험: 파일 `사본` 을 읽던 줄 = `skc.held`(795_1 · 821_1 · 821_4 · 826_3 — 826_3 「두 칸 같음」 → `사본` 없음 + 수식 값 몫) · m02_858_shelf_golden 다시 뜸(SK 읽기 답 = 파일 칸 바뀜) Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Copy_Slim.py | 25 +++++++++- M02_MasterTemplete/M02_Sangeun_Const.py | 18 ++----- M02_MasterTemplete/M02_Sangeun_Copy.py | 47 ++++++++++++++----- .../tester/fixtures/m02_858_shelf_golden.json | 2 +- resources/tester/test_795_1_sk_copy.py | 10 ++-- resources/tester/test_821_1_my_machine.py | 4 +- .../tester/test_821_4_import_my_machine.py | 2 +- resources/tester/test_826_3_copy_slim.py | 20 ++++---- 8 files changed, 83 insertions(+), 45 deletions(-) diff --git a/M02_MasterTemplete/M02_Copy_Slim.py b/M02_MasterTemplete/M02_Copy_Slim.py index 1aa3dde11..2297a5826 100644 --- a/M02_MasterTemplete/M02_Copy_Slim.py +++ b/M02_MasterTemplete/M02_Copy_Slim.py @@ -7,6 +7,7 @@ 이 문서 셈 = 사본 줄 묶음이 이 문서 사본 안에 드는 색인(남의 SK · SC 참조 셈 = 제 사본 → 안 셈). 파일 꼴 그대로 — 옛 코드는 사본에 없는 줄을 지금 M01 로 읽음(지금 옵션에서 안 읽는 줄 = 금액 같음). 읽은 줄 없음(셈 안 돎) · 프로젝트 층 = 그대로 · 이미 저장된 파일은 다음 [저장] 때 줄어듦. +층 저장 꼴(`trim` · 855 2-D) = 남는 칸만 — 값 사본 = `수식` 값 몫 한 벌(`사본` 안 씀) · 단가산출 빈 옛 칸 뺌. """ from __future__ import annotations @@ -104,4 +105,26 @@ def saved(kind: str, make: Callable[[], Any]) -> Any: _record(kind, out) finally: skc.READS.reset(token) - return cut_doc(out, reads) + return trim(kind, cut_doc(out, reads)) + + +#: 단가산출 옛 칸 · 서버 칸 — 빈 값이면 층 파일에 안 씀(855 2-D · 셈 · 화면이 안 읽음 · 읽을 때 `sd.clean` 이 +#: 빈 값으로 채움) · `더한줄` = 서고 뼈대 표지(`layers.check_skeleton`)라 빈 목록도 씀 · +#: 값 든 옛 칸 = 그대로(못 셈 + 까닭 · 2-C1) +EMPTY_GONE = ( + "입력값", "열린입력", "고름", "자재표시", "켜쌓기율", "덮개", "뺀줄", "뺀더한줄", + "상수덮개", "표값덮개", "글줄", "까닭", "수식고침", "변수줄", "식덮개", +) # fmt: skip + + +def trim(kind: str, doc: Any) -> Any: + """층 저장 꼴 = 남는 칸만(855 2-D) — 값 사본 = `수식` 값 몫 한 벌(`사본` 은 셈 중 칸 · 파일엔 안 씀) · + 단가산출 빈 옛 칸 · `M01판`(읽는 곳 없음) 뺌 · 프로젝트 층은 이 길을 안 탐(`saved`).""" + if kind != "sangeun" or not isinstance(doc, dict): + return doc + out = {k: v for k, v in doc.items() if not (k in EMPTY_GONE and v in (None, {}, [], ""))} + out.pop("M01판", None) + form = out.get(dc.KEY) + if skc.has(out) and isinstance(form, dict) and isinstance(form.get("로직"), list): + out[dc.KEY] = {**form, **dc.values_of(out.pop(skc.KEY))} + return out diff --git a/M02_MasterTemplete/M02_Sangeun_Const.py b/M02_MasterTemplete/M02_Sangeun_Const.py index c9f02132e..b52f7c8db 100644 --- a/M02_MasterTemplete/M02_Sangeun_Const.py +++ b/M02_MasterTemplete/M02_Sangeun_Const.py @@ -8,8 +8,7 @@ 표값덮개 {자리: {n: 값}} 자리 식의 n 번째 표 찾기 값(`찾기(…).칸`) → 값 · 그 줄만 표 연결 끊김 글줄 [{자리, 글}] 셈 없는 글 줄(근거 · ※ 조건) · 자리 뒤에 찍힘("" = 맨 위) 까닭 {열쇠: 글} 덮개 · 더한줄 · 뺀줄 · 새 덮개마다(예정가격작성기준 제2조 ②) - M01판 {자리: 지문} 저장 때 서버가 바탕 줄마다 적음(`stamp` · `sd.clean` 은 버림 = - 바탕판처럼) · 셈 때 받은 값과 지금 바탕이 다르면 「M01바뀜」 + M01판 {자리: 지문} (옛 칸 — 읽던 시트를 2-C1 에서 걷어 855 2-D 부터 안 적음 · 옛 파일 칸은 `sd.clean` 이 버림) 자리 = 바탕 줄 cid(호표 · 덧줄 `kind:키#n`) · 중간 줄 `mid:이름` · 열쇠 = 자리 · `add:#k` · `add:#k/세부 cid` · 식 칸 = 중간 「식」 · 호표 「수량」 · 덧줄 「식」. 셈 = `M02_Sangeun_Doc.patched` 첫머리 `formulas`(바탕 줄 식을 바꾼 사본) → 모든 셈 길(화면 · 저장 @@ -21,8 +20,6 @@ from __future__ import annotations import functools -import hashlib -import json import re from typing import Any @@ -220,14 +217,9 @@ def clean_more(raw: Any, out: dict) -> dict: return imp.clean(raw, fx.clean(raw, out)) # 식 칸(792-1) · 가져온 식(793-2) -def _print(one: Any) -> str: - raw = json.dumps(one, ensure_ascii=False, sort_keys=True, default=str) - return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12] - - def stamp(row: dict, doc: dict | None = None) -> dict[str, Any]: - """저장 때 서버 칸 — 바탕판(옛 칸 그대로) + M01판(자리마다 지문) · `doc` = 식 칸(792-1)을 - 엔진 식으로 바꿔 넣음(제자리 · 틀린 식 = `DocError`).""" + """저장 때 서버 칸 — 바탕판(바탕 줄 지문 · 화면 「기초가 바뀜」) · `doc` = 식 칸(792-1)을 + 엔진 식으로 바꿔 넣음(제자리 · 틀린 식 = `DocError`) · 옛 `M01판`(자리마다 지문 — 읽던 시트 걷음)은 안 적음(855 2-D).""" from M02_MasterTemplete import M02_Sangeun_Calc as calc if doc is not None and fx.has(doc): @@ -236,9 +228,7 @@ def stamp(row: dict, doc: dict | None = None) -> dict[str, Any]: if doc is not None and imp.is_imported(doc): # 가져온 식 검산(793-2) = 서버가 다시 doc[imp.KEY]["검산"] = imp.check(doc) - lines = [*(row.get("중간") or []), *(row.get("호표") or []), *(row.get("덧줄") or [])] - spots = [f"mid:{s.get('이름')}" for s in row.get("중간") or []] + sd.line_ids(row) - return {"바탕판": calc.fingerprint(row), "M01판": dict(zip(spots, map(_print, lines)))} + return {"바탕판": calc.fingerprint(row)} # ── 고치기 ────────────────────────────────────── diff --git a/M02_MasterTemplete/M02_Sangeun_Copy.py b/M02_MasterTemplete/M02_Sangeun_Copy.py index b13faf544..1e7569c5c 100644 --- a/M02_MasterTemplete/M02_Sangeun_Copy.py +++ b/M02_MasterTemplete/M02_Sangeun_Copy.py @@ -1,6 +1,7 @@ """M02 단가산출(SK) 로직 사본(PLAN 795-1 · 요구 655 · 656 · 요구서_655 0 · 1 장) — 서버 단독. -사본 = 저장 때 서버가 찍는 M01 닫힌 묶음(`M02_Item_Prices.collect` 다시 씀) — 문서 칸 `사본`: +사본 = 저장 때 서버가 찍는 M01 닫힌 묶음(`M02_Item_Prices.collect` 다시 씀) — 셈 중 문서 칸 `사본` · +층 저장 파일 = `수식` 의 값 몫 한 벌(`held` · 855 2-D — 파일엔 `사본` 안 씀 · 프로젝트 사본 꼴은 그대로): {판, 시점, 로직 [M01 줄], 단가판, 단가시점, 단가 [M01 줄], 빠진?} 로직 = 바탕 로직 · 더한줄 로직 · 가져온 식 이음 · 하위 로직 · 찾기 표 · 그 밖 요소(요율 등) 단가 = 자원 단가 줄(`RES` 노임 · 자재 · 기계 · 유가전력 · 환율) = 단가 기준 시점 묶음. @@ -66,12 +67,36 @@ def has(doc: Any) -> bool: return isinstance(copy, dict) and isinstance(copy.get("로직"), list) +FORM = "수식" # 수식 사본 칸(`M02_Doc_Copy.KEY`) — 층 저장 파일의 값 사본 자리(855 2-D) +VALUES = ("판", "시점", "로직", "단가판", "단가시점", "단가") + + +def held(doc: Any) -> dict | None: + """문서의 값 사본 — 셈 · 저장 중 `settle` 이 붙인 `사본` › 층 저장 파일 `수식` 의 값 몫(855 2-D · + 층 파일엔 `사본` 을 안 씀 · 프로젝트 사본은 `사본` 그대로) · 없음 = None.""" + if has(doc): + return doc[KEY] + form = doc.get(FORM) if isinstance(doc, dict) else None + if isinstance(form, dict) and isinstance(form.get("로직"), list): + return {k: form[k] for k in VALUES if k in form} + return None + + # ── 셈 색인 ────────────────────────────────────────────────────────── class Copy: """M01 색인 위 사본 줄 — `get` · `logic` · `value` · `label` = 엔진 `Master` 한 벌 (사본 줄 먼저) · 그 밖 칸(자재 색인 · 찾기 답)은 속 M01 것을 읽음.""" - label, value, logic = _MASTER.label, _MASTER.value, _MASTER.logic + label, value = _MASTER.label, _MASTER.value + + def logic(self, key: str) -> dict: + """사본 줄 › M01 색인 · 둘 다 없으면 속 색인이 따로 내주는 줄(굳힌 사본 `_Over` 등 · 855 2-D).""" + try: + return _MASTER.logic(self, key) + except prices.mf.FormulaError: + if getattr(type(self._whole), "logic", None) is _MASTER.logic: + raise # 속 = 맨 M01 색인 — 없는 키 그대로 + return self._whole.logic(key) def __init__(self, whole: Any, rows: list[dict], tag: Any = None) -> None: self._whole, self._tag, self.twice = whole, tag, whole.twice @@ -134,10 +159,11 @@ def _auto(doc: Any, copy: dict) -> dict: def over(doc: Any, whole: Any) -> Any: - """사본 있는 문서 = 사본 색인 · 없으면 `whole` 그대로(옛 길).""" - if not has(doc): + """값 사본(`held`) 있는 문서 = 사본 색인 · 없으면 `whole` 그대로.""" + copy = held(doc) + if copy is None: return whole - copy = _auto(doc, doc[KEY]) + copy = _auto(doc, copy) tag = (copy.get("판"), copy.get("단가판")) if isinstance(whole, Copy) and whole._tag == tag: return whole @@ -279,8 +305,7 @@ def stored_doc(key: Any) -> dict | None: def _stored(key: Any) -> dict | None: - got = stored_doc(key) - return got[KEY] if has(got) else None + return held(stored_doc(key)) def settle(doc: Any, save: bool = False) -> Any: @@ -291,7 +316,7 @@ def settle(doc: Any, save: bool = False) -> Any: out = {k: v for k, v in doc.items() if k not in (KEY, JOB)} if "참조" in (doc.get("바탕") or {}): return out - copy = _stored(doc.get("키")) or taken(doc.get(KEY)) + copy = _stored(doc.get("키")) or taken(held(doc)) if job == REGEN or (copy is None and save): copy = stamp(out) elif job == PRICE and copy: @@ -354,9 +379,9 @@ def mark(ans: dict, doc: dict) -> dict: def same_part(doc: Any) -> str | None: """같은 내용 지문 몫 — 지금 M01 과 같은 사본 = None(새로 찍을 문서와 같음) · 다르면 판.""" - if not has(doc): + copy = held(doc) + if copy is None: return None - copy = doc[KEY] seen = state(copy, whole_()) fresh = not (seen["M01새판"] or seen["지운키"] or seen["단가새값"]) return None if fresh else f"{copy.get('판')}:{copy.get('단가판')}" @@ -390,7 +415,7 @@ def preview(doc: Any, job: str, given: dict | None = None) -> dict[str, Any]: ]: out["끊은기초"] = cut # 줄은 그대로 · 자원 단가만(요구 656-1) if job == PRICE: - copy = _stored(doc.get("키")) or taken(doc.get(KEY)) + copy = _stored(doc.get("키")) or taken(held(doc)) out["바뀐자원"] = refresh(copy, whole_())[1] if copy else [] else: was = _lost(before) diff --git a/resources/tester/fixtures/m02_858_shelf_golden.json b/resources/tester/fixtures/m02_858_shelf_golden.json index a680c7260..4c4f06cd4 100644 --- a/resources/tester/fixtures/m02_858_shelf_golden.json +++ b/resources/tester/fixtures/m02_858_shelf_golden.json @@ -20,7 +20,7 @@ "sangeun.복사": "40edbd4d0644186f", "sangeun.붙여넣기": "57cfb7bb522a80d3", "sangeun.쓰는곳": "2c9ec1824709481f", - "sangeun.읽기": "2b7850af819535c2", + "sangeun.읽기": "19662ccd4c5ae0c0", "sangeun.중복": "2c9378c6e9c61251", "sangeun.지우기": "db8b1e8ad9bef9eb", "sangeun.합치기": "b8f7720e8a1e1bbb", diff --git a/resources/tester/test_795_1_sk_copy.py b/resources/tester/test_795_1_sk_copy.py index 879d1cd2e..c6ed834dc 100644 --- a/resources/tester/test_795_1_sk_copy.py +++ b/resources/tester/test_795_1_sk_copy.py @@ -91,7 +91,7 @@ def test_copy_stamped_and_logic_change_kept(world, monkeypatch): """① · ④ 저장 때 사본(로직 · 단가 갈래) · M01 로직 바꿔도 금액 그대로 · 배지만.""" me = world["personal"] key = _sk(me, 바탕={"로직": PCT}) - got = _doc(me, key)["사본"] + got = skc.held(_doc(me, key)) assert PCT in {r["키"] for r in got["로직"]} assert got["단가"] and all(r["키"][:2] in skc.RES for r in got["단가"]) assert not any(r["키"][:2] in skc.RES for r in got["로직"]) @@ -111,7 +111,7 @@ def test_price_refresh_only_on_press(world, monkeypatch): me = world["personal"] key = _sk(me, 바탕={"로직": PCT}) was = _sum(me, key) - lb = next(r["키"] for r in _doc(me, key)["사본"]["단가"] if r["키"].startswith("LB")) + lb = next(r["키"] for r in skc.held(_doc(me, key))["단가"] if r["키"].startswith("LB")) row = copy.deepcopy(_live().get(lb)) row["값"] = row["값"] * 2 _fake(monkeypatch, [row]) @@ -126,7 +126,7 @@ def test_price_refresh_only_on_press(world, monkeypatch): _save(me, key, got["문서"]) # [저장] = 서버가 할일 적용 saved = _doc(me, key) assert skc.JOB not in saved and _sum(me, key) == fresh - assert saved["사본"]["단가시점"] >= saved["사본"]["시점"] + assert skc.held(saved)["단가시점"] >= skc.held(saved)["시점"] def test_deleted_keys_keep_last_value(world, monkeypatch): @@ -134,7 +134,7 @@ def test_deleted_keys_keep_last_value(world, monkeypatch): me = world["personal"] key = _sk(me, 바탕={"로직": PCT}) was = _sum(me, key) - lb = next(r["키"] for r in _doc(me, key)["사본"]["단가"] if r["키"].startswith("LB")) + lb = next(r["키"] for r in skc.held(_doc(me, key))["단가"] if r["키"].startswith("LB")) _fake(monkeypatch, drop=[PCT, lb]) with pytest.raises(Exception): m01.loaded()[1].logic(PCT) @@ -186,7 +186,7 @@ def test_imported_same_rule(world, monkeypatch): with store.at(me): key = imp.create(_imported_row(), None, "sub2임시 가져온")["이름"] doc = _doc(me, key) - assert MAN in {r["키"] for r in doc["사본"]["단가"]} + assert MAN in {r["키"] for r in skc.held(doc)["단가"]} with store.at(me): ours = imp.to_price(doc, "우리")["문서"] _save(me, key, ours) diff --git a/resources/tester/test_821_1_my_machine.py b/resources/tester/test_821_1_my_machine.py index 813cd3f77..5e24d133c 100644 --- a/resources/tester/test_821_1_my_machine.py +++ b/resources/tester/test_821_1_my_machine.py @@ -137,7 +137,7 @@ def test_sk_copy_edit_refresh_delete(world): made = _at(me, mym.create, _easy()) key, no = made["줄"]["키"], made["줄"]["원문번호"] sk = _sk(me, no) - copy = _doc(me, sk)["사본"] + copy = skc.held(_doc(me, sk)) assert key in {r["키"] for r in copy["단가"]} was = _sum(me, sk) assert float(was) == made["시간당"]["계"] @@ -174,7 +174,7 @@ def test_m01_only_sk_same(world): plain = _at(other, lambda: refs.create("sangeun", base)["이름"]) _at(me, mym.create, _easy()) mine = _at(me, lambda: refs.create("sangeun", base)["이름"]) - a, b = _doc(other, plain)["사본"], _doc(me, mine)["사본"] + a, b = skc.held(_doc(other, plain)), skc.held(_doc(me, mine)) assert json.dumps(a["단가"], sort_keys=True) == json.dumps(b["단가"], sort_keys=True) assert a["판"] == b["판"] and _sum(other, plain) == _sum(me, mine) diff --git a/resources/tester/test_821_4_import_my_machine.py b/resources/tester/test_821_4_import_my_machine.py index 947923914..07ebd3a7f 100644 --- a/resources/tester/test_821_4_import_my_machine.py +++ b/resources/tester/test_821_4_import_my_machine.py @@ -168,7 +168,7 @@ def test_make_flow(world) -> None: ours = imp.to_price(doc, "우리") # [우리 단가로] = 내 기계 값 assert ours["후"]["계"] is not None and ours["후"] != ours["전"] assert not [u for u in ours["이음없음"] if "파워트로웰" in u["이름"]] - assert one["키"] in {r["키"] for r in (doc.get(skc.KEY) or {}).get("단가") or []} # 사본 + assert one["키"] in {r["키"] for r in (skc.held(doc) or {}).get("단가") or []} # 사본 conv = dim.derive(doc, None, imp._whole()) assert f"내 기계 {one['키']}" in json.dumps( conv["변수"], ensure_ascii=False, default=str diff --git a/resources/tester/test_826_3_copy_slim.py b/resources/tester/test_826_3_copy_slim.py index 3a67e8939..36e7f1c5b 100644 --- a/resources/tester/test_826_3_copy_slim.py +++ b/resources/tester/test_826_3_copy_slim.py @@ -70,7 +70,7 @@ def test_base_logic_read_rows_only(world): me = world["personal"] key = _sk(me, 바탕={"로직": DIG_BASE}, 단위="㎥") doc = _file(me, key) - have = doc[skc.KEY] + have = skc.held(doc) assert _closed(doc) >= 3 * len(_keys(have)) assert len(_keys(have)) <= 12 and len(have["단가"]) < 10 assert _keys(have) == _keys(doc["수식"]) # 두 자리 같은 줄(꼴 그대로) @@ -89,7 +89,7 @@ def test_m01_change_kept_then_price(world, monkeypatch): me = world["personal"] key = _sk(me, 바탕={"로직": DIG_BASE}, 단위="㎥") was = _sum(me, key) - read = set(_keys(_file(me, key)[skc.KEY])) + read = set(_keys(skc.held(_file(me, key)))) moved = [k for k in read if k[:2] in ("EQ", "LB", "MO")] assert moved _move(monkeypatch, *moved) @@ -97,7 +97,7 @@ def test_m01_change_kept_then_price(world, monkeypatch): assert _at(me, path.read, key)["사본"]["단가새값"] is True got = _price(me, key) assert set(got["바뀐"]) == set(moved) and got["후"] > was - assert set(_keys(_file(me, key)[skc.KEY])) == read + assert set(_keys(skc.held(_file(me, key)))) == read def test_machine_swap_preview_then_save(world, monkeypatch): @@ -146,11 +146,11 @@ def test_regen_slim(world, monkeypatch): """[재생성] — 지금 M01 로 다시 찍어도 읽은 줄만 · 그 뒤 M01 바뀌어도 그대로.""" me = world["personal"] key = _sk(me, 바탕={"로직": DIG_BASE}, 단위="㎥") - read = [k for k in _keys(_file(me, key)[skc.KEY]) if k[:2] in ("EQ", "MO")] + read = [k for k in _keys(skc.held(_file(me, key))) if k[:2] in ("EQ", "MO")] _move(monkeypatch, *read) 판 = _at(me, path.read, key)["판"] _at(me, path.save, key, {"할일": skc.REGEN, "판": 판}) - after = _file(me, key)[skc.KEY] + after = skc.held(_file(me, key)) assert len(_keys(after)) <= 12 was = _sum(me, key) _move(monkeypatch, *read) @@ -162,13 +162,13 @@ def test_layer_copy_slim(world, monkeypatch): me, co = world["personal"], world["company"] key = _sk(me, 바탕={"로직": DIG_BASE}, 단위="㎥") was = _sum(me, key) - _move(monkeypatch, DIG, *[k for k in _keys(_file(me, key)[skc.KEY]) if k[:2] == "EQ"]) + _move(monkeypatch, DIG, *[k for k in _keys(skc.held(_file(me, key))) if k[:2] == "EQ"]) ref = {"층": "personal", "주인": "7/42", "키": key} with store.at(co): doc = refs.read_ref(ref) new = refs.create("sangeun", refs.carry(refs.origin_mark(doc, ref), ("personal", "7/42"))) assert _sum(co, new["이름"]) == was - assert _keys(_file(co, new["이름"])[skc.KEY]) == _keys(_file(me, key)[skc.KEY]) + assert _keys(skc.held(_file(co, new["이름"]))) == _keys(skc.held(_file(me, key))) def test_labor_and_combo_slim(world, monkeypatch): @@ -206,7 +206,7 @@ def test_old_big_copy_reads_then_slims(world): with store.at(me): got = store.read("sangeun", key) store.write("sangeun", key, got["판"], got["문서"]) - assert len(_keys(_file(me, key)[skc.KEY])) * 3 <= len(big["로직"]) + len(big["단가"]) + assert len(_keys(skc.held(_file(me, key)))) * 3 <= len(big["로직"]) + len(big["단가"]) assert _sum(me, key) == was @@ -253,6 +253,6 @@ def test_doc_path_save_keeps_both_slots(world): assert look["사본"]["사본없음"] > 0 _at(me, path.save, key, {"문서": doc, "판": got["판"]}) after = _file(me, key) - assert set(_keys(after[skc.KEY])) == set(_keys(after["수식"])) - assert len(_keys(after[skc.KEY])) >= 6 + assert skc.KEY not in after # 층 파일 값 사본 = `수식` 한 벌(855 2-D) + assert len(_keys(skc.held(after))) >= 6 assert _sum(me, key) == look["셈"]["계"] != got["셈"]["계"] From 7d586c502113049af0775e94536bd533c3b5603e Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:50:54 +0900 Subject: [PATCH 2/4] =?UTF-8?q?refactor(855-2-D):=20=EA=B0=92=20=EC=82=AC?= =?UTF-8?q?=EB=B3=B8=20=EC=9D=BD=EA=B8=B0=20=ED=95=9C=20=EA=B3=B3=20?= =?UTF-8?q?=E2=80=94=20Doc=5FSk=20=EC=9D=98=20=EC=82=AC=EB=B3=B8=20=C2=B7?= =?UTF-8?q?=20=EC=88=98=EC=8B=9D=20=EA=B0=88=EB=9E=98=EB=A5=BC=20skc.held?= =?UTF-8?q?=20=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `Doc_Sk.seed` · `copy_of` · `settle` = `skc.held`(셈 중 `사본` › 층 파일 `수식` 값 몫) 하나로 읽음 — `사본` 있나 · 없나 갈래 걷음 - 자동 따라옴 「지운 키 마지막 값」 = 그 값 사본(층 파일 = `수식` 값 몫 한 벌) — `Sk_AutoRenew.rows` 그대로 · 머리 글 고침 - 남김: `Doc_Sk.OLD_FIELDS`(따로 문서 옛 칸 고침 409 지킴 · 빈 칸은 지문에 안 듦) · `Doc_Gap.fill_imported` · `Copy_Slim.cut_doc` 의 `사본`(저장 중 메모리 칸 · 파일엔 `trim` 이 안 씀) · `Library_Flat`(740-1 넣기 · 화면 부름 0 · 옛 몸 칸만 읽음 — 2-E2) Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Doc_Sk.py | 10 +++++----- M02_MasterTemplete/M02_Sk_AutoRenew.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/M02_MasterTemplete/M02_Doc_Sk.py b/M02_MasterTemplete/M02_Doc_Sk.py index dc6a90e19..da13a46ab 100644 --- a/M02_MasterTemplete/M02_Doc_Sk.py +++ b/M02_MasterTemplete/M02_Doc_Sk.py @@ -177,8 +177,8 @@ def seed(sk: dict) -> dict | None: 가져온 식 = 빈 부름(문서는 셈마다 지음).""" if dim.is_imported(sk): return {"부름": {}} - if skc.has(sk): - return {**dc.values_of(sk[skc.KEY]), "부름": {}} + if (held := skc.held(sk)) is not None: + return {**dc.values_of(held), "부름": {}} if sk.get("바탕") or sk.get("더한줄"): return None empty = {"판": skc._fp([]), "로직": [], "단가판": skc._fp([]), "단가": [], "부름": {}} @@ -240,7 +240,7 @@ def copy_of(sk: dict, whole: Any = None) -> dict | None: root = renew.carry(got, derive(sk, whole)) # 맡긴 기계 덮음(836-2) except dc._ERR as e: root = {**dc.md.blank(str(sk.get("키"))), "_틀림": str(e)} - values = dc.values_of(sk[skc.KEY]) if skc.has(sk) else dc.values_of(got) # 서버가 정한 값 + values = dc.values_of(skc.held(sk) or got) # 서버가 정한 값(셈 중 사본 › 수식 값 몫 · 855 2-D) values = renew.rows(values) if renew.is_sk(sk) else values # 836-2 whole = dc.over(values) calls = dc.closure(whole, [*dc.calls(root), *dc.upper_calls(got)], got.get("부름")) @@ -300,11 +300,11 @@ def settle(out: dict, whole: Any, job: Any, raw: Any) -> dict: slim = skc.READS.get() is not None # 저장 관문이 셈 한 번으로 박음(826-3) return {**out, KEY: norm(copy if slim else gap.fill(copy))} # 빈틈 = 지금 값(822-1) # 빈 SK(바탕 · 줄 없음) = 빈 문서(요구서_664 0 장) · 수식 길로 고친 빈 SK = 위 따로(804-4) - if not skc.has(out) and not dim.is_imported(out): + if skc.held(out) is None and not dim.is_imported(out): empty = seed(out) return {**out, KEY: norm(empty)} if empty else out calls = {} if job == skc.REGEN else (have or {}).get("부름") or {} - first = {**(dc.values_of(out[skc.KEY]) if skc.has(out) else {}), "부름": calls} + first = {**dc.values_of(skc.held(out) or {}), "부름": calls} if job != skc.REGEN and (have or {}).get("끊음"): # 안 바뀐 항목 고침 = 그대로(836-2) first["끊음"] = have["끊음"] if job != skc.REGEN: # 맡긴 기계 고침 · 옵션 값 · 지킨 칸 바탕(848-2) diff --git a/M02_MasterTemplete/M02_Sk_AutoRenew.py b/M02_MasterTemplete/M02_Sk_AutoRenew.py index b6d597cf3..1b5436fda 100644 --- a/M02_MasterTemplete/M02_Sk_AutoRenew.py +++ b/M02_MasterTemplete/M02_Sk_AutoRenew.py @@ -1,7 +1,7 @@ """M02 단가산출(SK) M01 자동 따라옴(PLAN 836-2 · 848-2 · 요구 854 · 요구서_889 3 절) — 서버 단독. 프로젝트 층 밖 SK(마스터 · 회사 · 개인) = 셈 · 열기 · 목록 · 일위대가 펼침이 모두 - 사본 줄 = 지금 M01(+ 층 내 기계) 줄(`rows` · 지운 키 = 사본 마지막 줄) · + 사본 줄 = 지금 M01(+ 층 내 기계) 줄(`rows` · 지운 키 = 값 사본 마지막 줄 — 층 파일 = `수식` 값 몫 한 벌 · 855 2-D) · 부름 문서 = 지금 M01 수식 문서(`form`)로 봄 — 묻지 않음 · [단가 갱신] · [재생성] 없음. 파일(작업본)은 [저장] · 알림 [확인](= 저장 · `confirm`) 때만 새 것으로 씀 — 읽기 길은 안 씀. 판정 = 칸 단위(848-2): From efc881ad12fe42b8cc2eacf90fb9b053ac99324a Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:53:03 +0900 Subject: [PATCH 3/4] =?UTF-8?q?refactor(855-F=20B9-4):=20B09=20=EC=82=B0?= =?UTF-8?q?=EC=B6=9C=EA=B7=BC=EA=B1=B0=20=EA=B8=80=EC=9D=B4=20=EC=98=9B=20?= =?UTF-8?q?=EC=97=94=EC=A7=84=20=C2=B7=20master=5Ftext=20=EB=8C=80?= =?UTF-8?q?=EC=8B=A0=20=ED=92=80=EC=9D=B4=20=EB=B8=94=EB=A1=9D=20+=20?= =?UTF-8?q?=EB=AC=B8=EC=84=9C=20=EC=85=88=20=EB=8B=B5=EC=9C=BC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sangeun_Text 새 render · foot — 풀이 블록 줄 값(B09 수량 · 단가 · 금액) + 문서 셈 답(입력 · 공식 · 표 값 · 단위) · 수 꼴 · 단위 · 금액 줄 꼴 = master_doc_text(화면 줄 쌓기 산출근거 규칙) - Sangeun _env · _captured · _Prices · price_of 지움 · Solver._text = render 한 번(못 지으면 빈 글 · 값 그대로) - Sangeun_Sum 옛 shown · _cut · places · sums · scope · extra · totals 지움(doc_* 만) - helper_855_engine 옛 대조 기준 _old_env · _old_captured(test_855_trace) - test_155_5 · test_157_1 · test_155_b09_sources — 엑셀 꼴 글자 대신 새 규칙 결과(글 금액 = 블록 · 계 · Q 공식 줄 · 값 넣은 수량 식 · ÷ 배 · 원) - 골든 855_b09 글 5 갈래 다시 뜸(전 → 후 견본 tmp 표) · 값 10 갈래 같음 · 옛 글이 블록 값과 어긋나던 자리(옛 키 단가 0) 바로잡힘 - B09 옛 엔진 부름 37 → 0 Co-Authored-By: Claude Opus 5.5 --- B09_Estimation/B09_Estimation_Sangeun.py | 111 +--- B09_Estimation/B09_Estimation_Sangeun_Sum.py | 79 +-- B09_Estimation/B09_Estimation_Sangeun_Text.py | 607 +++++++----------- resources/tester/golden_855_b09.json | 10 +- resources/tester/helper_855_engine.py | 50 +- resources/tester/test_155_5_sangeun_text.py | 121 ++-- resources/tester/test_155_b09_sources.py | 4 +- resources/tester/test_157_1_sangeun_steps.py | 85 +-- resources/tester/test_855_trace.py | 2 +- 9 files changed, 409 insertions(+), 660 deletions(-) diff --git a/B09_Estimation/B09_Estimation_Sangeun.py b/B09_Estimation/B09_Estimation_Sangeun.py index 2f0bbc4fa..09a09420e 100644 --- a/B09_Estimation/B09_Estimation_Sangeun.py +++ b/B09_Estimation/B09_Estimation_Sangeun.py @@ -10,7 +10,7 @@ 로직 줄이 부르는 다른 돈 로직(기계경비 밖) = 하위 산근(그 산근도 목록에 · 산근 → 산근). 풀이 = 사본 수식 문서(`수식.json`)를 M02 와 같은 계산기로 셈한 답 + 셈 기록(`B09_Estimation_Doc_Run` · 855-F B9-3)에서 줄마다 수량 · 단가 · 자원 키 · 하위 산근 · % 줄 율 · 끝수를 읽음(옛 엔진 안 부름) · - 줄 이름 · 단위 · 종류 = 사본 로직 줄 글(B9-5 에서 문서로) · 산출근거 글 = 옛 길(B9-4 · `_env` · `_captured`) · + 줄 이름 · 단위 · 종류 = 사본 로직 줄 글(B9-5 에서 문서로) · 산출근거 글 = 풀이 블록 + 문서 셈 답(B9-4) · 단가 = B09 프로젝트 한 벌 굳힌 단가(144 · `compute_base` 표) — 노무 = 노무비목록표 · 중기 = 중기목록표 노 · 재 · 경 · 재료 = 자재단가대비표 적용 단가 · % 줄(덧줄) = 엔진 식에 B09 비목 합. @@ -45,6 +45,7 @@ from typing import Any from B08_Quantity.B08_Quantity_Haul_Cycle import fill_given from B09_Estimation import B09_Estimation_Doc_Run as dr from B09_Estimation import B09_Estimation_Sangeun_Sum as ss +from B09_Estimation import B09_Estimation_Sangeun_Text as st 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 @@ -66,7 +67,6 @@ import master_sheet_line as msl # noqa: E402 — 계산서 줄 덧칸(714-1) · PARTS = ("labor", "material", "expense") COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"} PART_COST = {v: k for k, v in COST_PART.items()} -PART_NAMES = tuple((p, k) for k, p in COST_PART.items()) # 글 계 줄 차례(노 · 재 · 경) PCT_OF = {**COST_PART, "인건비": "people"} # % 덧줄 밑수 → 덮개 다시 셈(719-3) DEPTH = 4 # 하위 산근 깊이 상한 NO_SOURCE = "조합 밖 토공 · 운반 · 사토 · 준비공은 산근 없음" @@ -172,17 +172,6 @@ def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[d # ── 풀이 ────────────────────────────────────────────────────────────── -class _Prices: - """엔진 단가(841-1) — M02 엔진이 사본 단가 묶음으로 낸 줄 금액 ÷ 수량 · 텍스트 수식 글이 읽음 - (노무 · 자재 = 수 · 중기 = 노 · 재 · 경). B09 단가 책 · 바탕 표는 안 읽음.""" - - def __init__(self) -> None: - # ponytail: 키 하나 = 단가 하나(사본마다 기준 시점이 달라도 마지막 본 값) — 글 짓기 전용 - self.labor: dict[str, float | None] = {} - self.material: dict[str, float | None] = {} - self.machine: dict[str, dict[str, float | None]] = {} - - def _unit(row: dict) -> tuple[str, Decimal]: """결과단위 1 단위 — (단위, 배)(「원/10㎡」 = ㎡ · 10) · 알약 규칙(`combo_pills`) 그대로 · 줄 = 사본 단가 묶음 것(M01 다시 안 읽음 · 719-2).""" @@ -201,21 +190,6 @@ def unit_of(whole: Any, code: str) -> str: return "" -def _env(whole: Any, row: dict, given: dict) -> dict: - """입력(빈 입력 = 자동값) + 중간값 · 작업량 Q = ROUND(식, 2)(엑셀 자리) — 산출근거 글 몫만 - (`B09_Estimation_Sangeun_Text` · B9-4 에서 걷음 · 풀이 금액은 `Doc_Run`).""" - auto = {k: v for k, v in m01.mau.values(whole, row).items() if v is not None} - env = mf._inputs(row, {**auto, **m01._dec(given or {})}) - for step in row.get("중간", []): - try: - value = mf.evaluate(mf.parse(step["식"]), env, whole, 0) - except mf.EmptyInput as e: - env[step["이름"]] = mf.Blank(str(e)) - continue - env[step["이름"]] = ss.shown(row, step, value) # 표시 · Q ROUND 2(792-3) - return env - - def is_money(whole: Any, code: str) -> bool: """돈 로직(호표 줄 꼴)인지 — 없는 로직 · 흐름 · 결과 로직 = 아님.""" try: @@ -286,28 +260,6 @@ def line_calls( } -def _captured(whole: Any, node: Any, env: dict) -> list[str]: - """식을 돌리며 부른 기계 키(EQ) — 기계경비 로직 줄의 기계 · 산출근거 글 몫만(B9-4).""" - seen: list[str] = [] - base = whole.get - - def get(ref: str) -> dict[str, Any]: - row = base(ref) - key = str(row.get("키") or "") - if key.startswith("EQ") and key not in seen: - seen.append(key) - return row - - whole.get = get - try: - mf.evaluate(node, env, whole, 1) - except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): - pass # 기계 단가를 못 셈 — 키만 있으면 됨(단가는 B09 중기목록표) - finally: - whole.get = base - return seen - - def spec_text(whole: Any, given: dict[str, Any]) -> tuple[str, str]: """규격 글(157-3) → (보일 글, 원문번호 글) — 기계 · 직종 번호 = 「이름 규격」(M02 85-1).""" @@ -343,7 +295,6 @@ class Solver: def __init__(self, supply: Any = None) -> None: self.supply = supply or (lambda key: None) # 자재 키 → 관급 · 별도 · None(841-1) - self.prices = _Prices() self.eng: list[dict[str, Any]] = [] # 지금 푸는 로직의 문서 셈 줄(금액 줄 차례 · 841-1) self.blocks: dict[str, dict[str, Any]] = {} self.shelf = dr.Shelf() # 값 색인 → 사본 수식 문서(`collect` 가 사본마다 둠) @@ -388,19 +339,17 @@ class Solver: lines.append(self._line(whole, item, n, times, rate, depth)) ss.doc_places(row, lines) # 줄 자리(792-3) self._extras(row, per or eng, lines) + head = self._text(whole, eng, lines, times, src.get("rate")) self._aside(lines) _annotate(whole, row, eng.env, lines) except (ArithmeticError, KeyError, TypeError, ValueError) as e: return self._stop(code, name, str(e) or type(e).__name__) sums = ss.doc_totals(eng, lines) # 끝수 · 끝전 · 조정 = 문서 답 끝수(792-3) why = next((ln["why"] for ln in lines if ln.get("why")), None) - head, foot = self._text(whole, src, times, lines) - for ln in lines: # 글 = 엔진 단가 셈 그대로 · 별도계상 재료 줄은 끝에 0 원 표시(841-1) + foot = st.foot(sums) + for ln in lines: # 글 = 풀이 단가 셈 그대로 · 별도계상 재료 줄은 끝에 0 원 표시(841-1) if "aside" in ln and ln.get("text"): - ln["text"] = [*ln["text"][:-1], f"{ln['text'][-1]} · 별도계상 = 0.0"] - if foot and any("aside" in ln for ln in lines) and sums.get("sum") is not None: - parts = " + ".join(f"{st_name} {sums[p]:,.0f}" for p, st_name in PART_NAMES) - foot = f"계 : {parts} = {sums['sum']:,.0f}" + ln["text"] = [*ln["text"][:-1], f"{ln['text'][-1]} · 별도계상 = 0.0 원"] spec, spec_raw = spec_text(whole, src["given"]) return { "logic": code, @@ -423,37 +372,21 @@ class Solver: "lines": [], **dict.fromkeys(PARTS), "sum": None, "why": why, "head": [], "foot": ""} # fmt: skip - def price_of(self, key: str) -> Any: - """글 짓기 단가(`Sangeun_Text` 꼴) — 노무 · 자재 = 수 · 중기 · 산근 = 비목 단가 묶음.""" - if key in self.prices.labor: - return self.prices.labor[key] - if key in self.prices.material: - return self.prices.material[key] - if key in self.prices.machine: - return {p: num(self.prices.machine[key].get(p)) for p in PARTS} - block = self.blocks.get(key) - return {k: block.get(k) for k in (*PARTS, "sum", "no")} if block else None - - def _text(self, whole, src, times, lines) -> tuple[list[str], str]: - """텍스트 수식(155-5) → (머리 줄들, 계) · 줄마다 `text` 를 얹음(중기 = 세 줄 · 그 밖 한 줄). - 줄 수가 안 맞으면 모두 머리에(값 칸과 어긋나게 얹지 않음).""" - from B09_Estimation.B09_Estimation_Sangeun_Text import render_sangeun_text - + def _text(self, whole, eng, lines, times, rate) -> list[str]: + """산출근거 글(155-5 · B9-4 `Sangeun_Text.render`) — 줄마다 `text` 를 얹고 머리 줄들 · 글을 못 지으면 + 빈 글(값은 그대로).""" try: - text = render_sangeun_text(whole, src["code"], src["given"], self.price_of, - times=times, rate=src.get("rate"), - picks=src.get("picks")) # fmt: skip - except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): - return [], "" - counts = [3 if ln["kind"] == "machine" and not ln.get("why") else 1 for ln in lines] - start = len(text) - 1 - sum(counts) - if start < 1: - return text, "" - at = start - for ln, n in zip(lines, counts): - ln["text"] = text[at : at + n] - at += n - return text[:start], text[-1] + head, texts = st.render(whole, eng, lines, times=times, rate=rate, no_of=self._no) + except Exception: # noqa: BLE001 — 글은 보기 · 못 지어도 풀이 값은 살림 + return [] + for ln, text in zip(lines, texts): + ln["text"] = text + return head + + def _no(self, key: Any) -> int | None: + """하위 산근 호표 번호(글).""" + block = self.blocks.get(str(key or "")) + return block.get("no") if block else None def _aside(self, lines: list[dict[str, Any]]) -> None: """관급 · 별도계상 재료 = 산근 안 0원(841-1 · % 덧줄 밑수는 엔진 값 그대로 · 자재대 · 관급 단락).""" @@ -492,7 +425,6 @@ class Solver: if kind == "인력": key = str(x.get("키") or "") # 노임 키 = 셈 기록(부른 노임 줄) price = self._each(n, "labor", q) - self.prices.labor[key] = price why = None if price is not None else f"노임 단가 없음(M02 엔진) 「{key}」" return {**base, **zero, "kind": "labor", "ref": {"tab": "labor", "key": key}, "price": {"labor": price}, "labor": _money(price, q), "why": why} # fmt: skip @@ -500,7 +432,6 @@ class Solver: key = str(x.get("키") or "") part = COST_PART.get(item.get("비목"), "material") price = self._each(n, part, q) - self.prices.material[key] = price why = None if price is not None else f"자재 단가 없음(M02 엔진) 「{key}」" spec = goods.get("규격") or "" ref = {"tab": "compare", "key": key} @@ -514,8 +445,6 @@ class Solver: keys = [call["machine"]] if call["machine"] else [] price = {p: self._each(n, p, q) for p in PARTS} # 기계 시간당 = M02 엔진 값(841-1) m = None not in price.values() - if keys: - self.prices.machine[keys[0]] = price why = ( None if m diff --git a/B09_Estimation/B09_Estimation_Sangeun_Sum.py b/B09_Estimation/B09_Estimation_Sangeun_Sum.py index 64d8528d1..4b2af7432 100644 --- a/B09_Estimation/B09_Estimation_Sangeun_Sum.py +++ b/B09_Estimation/B09_Estimation_Sangeun_Sum.py @@ -1,8 +1,7 @@ -"""B09 산근 풀이 셈 의미(PLAN 792-3) — 791-1 엔진 새 의미(줄 자리 · 합밖 · 번지 · 단계 · 블록 끝전 · -결과 조정 · 변수 표시)를 쓰는 로직만 엔진 규칙(`master_cut` · `master_formula_sum`) 그대로 · -새 칸 없는 로직 = 옛 B09 규칙(작업량 Q = ROUND 2 · 줄 ROUNDDOWN 1 · 총계 비목마다 ROUNDDOWN 0). -쓰는 곳 = 산출근거 글(`B09_Estimation_Sangeun_Text` · B9-4 에서 걷음) · 풀이 금액(`Sangeun.Solver`) = -아래 `doc_*`(855-F B9-3 · 문서 셈 답 `끝수` · `합밖` · 새 계산기 `master_doc_calc.cut` · `_settle`) · 지킴 시험 = `test_792_3_engine_paths.py`(엔진 · M02 SK · +"""B09 산근 풀이 셈 의미(PLAN 792-3 · 855-F B9-3) — 줄 자리 · 합밖 · 블록 끝전 · 결과 조정 = 문서 셈 답의 +`끝수` · `합밖`(새 계산기 `master_doc_calc.cut` · `_settle`) · 기본 = 줄 ROUNDDOWN 1 · 총계 비목마다 +ROUNDDOWN 0 · 중간값 표시 자리(`표시` · 옛 로직 작업량 Q = ROUND 2 · 엑셀 자리) = 문서 식에 반올림. +쓰는 곳 = `B09_Estimation_Sangeun.Solver` · 지킴 시험 = `test_792_3_engine_paths.py`(엔진 · M02 SK · SC · B09 산근 네 길 같은 금액). """ @@ -13,10 +12,9 @@ import re from decimal import Decimal from typing import Any -from B09_Estimation.B09_Estimation_Calc_Base import round_half, rounddown, total +from B09_Estimation.B09_Estimation_Calc_Base import rounddown, total from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠 -mcut = importlib.import_module("master_cut") mc = importlib.import_module("master_doc_calc") ms = importlib.import_module("master_formula_sum") @@ -25,73 +23,6 @@ COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"} _Q = re.compile(r"Q\d*") # 작업량 중간값 이름(산림품셈 09장 토공 · 07장 집재 …) -def shown(row: dict, step: dict, value: Any) -> Any: - """중간값 — `표시` 칸 · 새 의미 로직 = 엔진 그대로(`표시` 자리 반올림) · 옛 = Q ROUND 2.""" - if step.get("표시") is not None or ms.uses(row): - return ms.shown(step, value) - if _Q.fullmatch(step["이름"]) and isinstance(value, (Decimal, int, float)): - return Decimal(str(round_half(float(value), 2))) - return value - - -def _cut(value: float, rule: dict | None) -> float: - return float(mcut._line(value, rule)) if rule else rounddown(value, 1) - - -def places(row: dict, lines: list[dict]) -> None: - """호표 줄 `자리`(줄 자리) — 그 줄 금액만 단가 × 수량을 그 규칙으로 다시 버림(제자리).""" - for item, ln in zip(row.get("호표", []), lines): - rule = item.get("자리") - if not rule or ln.get("qty") is None: - continue - for part, price in (ln.get("price") or {}).items(): - if part in PARTS and price is not None: - ln[part] = _cut(price * ln["qty"], rule) - - -def _engine(lines: list[dict]) -> list[dict]: - """B09 줄 → 엔진 줄 꼴 `{비목}`(번지 · 단계 셈).""" - return [ - {"비목": {k: Decimal(str(ln.get(p) or 0)) for k, p in COST_PART.items()}} for ln in lines - ] - - -def sums(row: dict, lines: list[dict]) -> dict[str, float | None]: - """덧줄 밑 비목 합 — 새 의미 로직은 합밖 · 제외 단계 줄을 뺌.""" - skip = ms.skipped(row) if ms.uses(row) else set() - kept = [ln for n, ln in enumerate(lines) if n not in skip] - return {name: total([ln[p] for ln in kept]) for name, p in COST_PART.items()} - - -def scope(row: dict, lines: list[dict], env: dict) -> None: - """덧줄 식 이름 `번지` · `단계`(지금까지 줄) — 새 의미 로직만.""" - if ms.uses(row): - env.update(ms.scope(row, _engine(lines))) - - -def extra(row: dict, item: dict, value: float, env: dict) -> float: - """덧줄 금액 — 줄 `자리` 면 그 규칙 · 아니면 ROUNDDOWN 1 · - 새 의미 로직은 뒤 덧줄이 그 값을 부름.""" - money = _cut(value, item.get("자리")) - if ms.uses(row): - env[item["이름"]] = Decimal(str(money)) - return money - - -def totals(row: dict, lines: list[dict]) -> dict[str, float | None] | None: - """총계 — 새 의미 로직 = 합밖 · 제외 빼고 블록 끝전 · `끝수` · 조정(`master_cut.settle`) · - 옛 로직 · 빈칸 비목 있음 = None(옛 `block_totals`).""" - if not ms.uses(row): - return None - got = sums(row, lines) - if any(v is None for v in got.values()): - return None - costs = mcut.settle(row, {k: Decimal(str(v)) for k, v in got.items()}) - out = {COST_PART[k]: float(v) for k, v in costs.items()} - return {**out, "sum": sum(out.values())} - - -# ── 문서 셈 답 길(855-F B9-3 · `Sangeun.Solver`) — 위 옛 길 = 산출근거 글 몫 ────────── def doc_cut(value: float, rule: dict | None) -> float: """줄 끝수 — 줄 `자리` 면 그 규칙(새 계산기 `master_doc_calc.cut`) · 없으면 ROUNDDOWN 1.""" return float(mc.cut(Decimal(str(value)), rule)) if rule else rounddown(value, 1) diff --git a/B09_Estimation/B09_Estimation_Sangeun_Text.py b/B09_Estimation/B09_Estimation_Sangeun_Text.py index 868d66ccc..72e5f7200 100644 --- a/B09_Estimation/B09_Estimation_Sangeun_Text.py +++ b/B09_Estimation/B09_Estimation_Sangeun_Text.py @@ -1,419 +1,292 @@ -"""B09 산근 한 항목 → 엑셀 단가산출근거 꼴 텍스트 수식 줄들(PLAN 155-5) — 서버 단독(③ · 순수 함수). +"""B09 산근 한 블록 → 산출근거 글 줄들(PLAN 155-5 · 855-F B9-4) — 서버 단독(③ · 순수 함수 · 셈 안 함). -꼴 = 엑셀 단가산출근거 탭 산출내역 한 칸 글: - 머리 「이름 / 단위」 · 출처 「… 적용」 · 입력 「이름 : 설명 = 값 단위」(157-1 · 설명 없으면 - 「이름 : 값 단위」 · 기계 · 직종 번호 = 「이름 규격」 157-3 `M02_Labor_Inputs._labels`) · - 함수(M01 흐름도 함수 상자 · 157-1) = 계산 차례대로 「이름 = 이름식 = 값 넣은 식 = 값」 — - 중간 · 결과(돈 아닌 로직) · 호표 수량(이름식이 값 꼴과 다를 때 「이름 수량 = …」) · - 찾기 = 「표 이름(조건 = 값).칸」 · 만약 = 걸린 갈래만 · 하위 로직 = 로직 이름(산근 n호표) · - 돈 아닌 하위 로직은 그 풀이를 「└ 」 줄로 이어 씀(작업량 Q = ROUND 2 — `Sangeun._env`) · - 함수 줄은 모두 머리(호표 줄 수 그대로) · - 줄 「보통인부 : 172,068 * 0.022 = 3,785.4」(단가 * 수량식 값 꼴[ / 배][ * 율 %] = 금액) · - 중기 = 노무비 · 재료비 · 경비 세 줄 · 하위 산근 = 「산근 n호표 단가 * 수량」 · - % 덧줄 = 「이름 (노무비의 %) : 밑수 * n % = 금액」(규격 = 149-4 `pct_extras`) · - 끝 = 「계 : 노무비 + 재료비 + 경비 = 합」. -식 풀이 = 엔진 `master_text` 낮은 부품(render · _names · fmt) · 단가 = 인자 `price_of(key)`(B09 굳힌 - 단가 · 엔진 단가 글은 안 씀) · 단가 없음 = 「단가 없음」 글. -끝수 = 엑셀 자리 — 줄 ROUNDDOWN 1 · 계 비목마다 ROUNDDOWN 0(`Sangeun._money` · `block_totals`). -`price_of(key)` — 인력 · 자재 키 → 수 | None · 기계(EQ) · 하위 산근(SG:) → {labor, material, expense - [, sum, no]} | None. +재료 = 산근 풀이 블록 줄(`B09_Estimation_Sangeun.Solver` · B09 수량 · 단가 · 금액) + 그 로직 문서 셈 답 +(`B09_Estimation_Doc_Run.Answer` · 입력 · 중간 값 · 단위) — 옛 엔진 · `master_text` 안 부름. +수 꼴 · 단위 · 금액 줄 꼴 = 화면 줄 쌓기 산출근거 규칙(`master_doc_text` · 짝 `A00_Common/line_stack_out.ts`): + 머리 = 「이름 / 단위」 · 「출처 적용」 · 입력 「이름 : 설명 = 값 단위」(기계 · 직종 번호 = 「이름 규격」 157-3) · + 공식 줄 「이름 = 이름식 = 값식 = 값 단위」(식 변수 · 같은 꼴은 한 번) · 표 · 하위 결과 값 「이름 = 값 단위」 + 줄 = 「이름 : 단가 원/단위 × 수량 단위[ ÷ 배][ × 율 %] = 금액 원」(B09 단가 · 1 단위 수량 = 문서 수량 ÷ 배 × 율) · + 중기 = 노무비 · 재료비 · 경비 세 줄 · 하위 산근 = 「산근 n호표 단가 × 수량」 · + % 덧줄 = 「이름 (노무비의 %) : 밑수 × n % = 금액 원」 · 못 셈 = 「이름 : — 까닭」 + 끝 = 「계 : 노무비 + 재료비 + 경비 = 합」(블록 합 · B09 끝수). +화면만인 것(옮기지 않음) = 식 조판 · 표 조건 글 · 만약 갈래 글 · 하위 결과 펼침 · 쌓기 묶음. """ from __future__ import annotations -import re -from collections.abc import Callable +import importlib from decimal import Decimal from typing import Any -from B09_Estimation import B09_Estimation_Sangeun as sg -from B09_Estimation import B09_Estimation_Sangeun_Sum as ss -from M01_MasterData import M01_MasterData_Store as m01 -from M02_MasterTemplete import M02_Labor_Doc as labor_doc from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs -mf = sg.mf -mtx = m01.mtx +md = importlib.import_module("master_doc") +mdt = importlib.import_module("master_doc_text") +ml = importlib.import_module("master_doc_link") + PART_NAME = {"labor": "노무비", "material": "재료비", "expense": "경비"} -_ERRORS = (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError) +PARTS = tuple(PART_NAME) NO_PRICE = "단가 없음" - -PriceOf = Callable[[str], Any] +GAP = "—" +INPUTS = ("입력", "선택") +VALUES = ("표", "단가산출", "숫자") # 값만 줄(표 찾기 · 하위 결과 · 손 수) +PACK = 4 # 값만 줄 = 넷까지 한 줄(화면 공식 묶음) -def _money(value: float | None) -> str: - return "빈칸" if value is None else f"{value:,.1f}" +def _dec(v: Any) -> Decimal | None: + return mdt._dec(v) -def _price(value: Any) -> str: - return NO_PRICE if value is None else mtx.fmt_price(Decimal(str(value))) - - -def _qty_text(item: dict, env: dict, whole: Any, times: Decimal, rate: Decimal | None) -> str: - """수량식 값 꼴 — 덧셈 묶음이면 괄호 · 결과단위 배 「/ 배」 · 켜쌓기율 「* 율 %」.""" - text = mtx._times(mtx.render(mf.parse(item["수량"]), env, whole), item, env, whole) - if times != 1: - text += f" / {mtx.fmt(times)}" - if rate is not None: - text += f" * {mtx.fmt(rate * 100)} %" - return text - - -def _line(name: str, price: Any, qty_text: str, q: float, rule=None) -> tuple[str, float | None]: - money = None if price is None else ss._cut(float(price) * q, rule) # 줄 자리(792-3) - return f"{name} : {_price(price)} * {qty_text} = {_money(money)}", money - - -def _head(row: dict, env: dict, whole: Any, times: Decimal, price_of: PriceOf) -> list[str]: - unit = str(row.get("결과단위") or "").removeprefix("원/") - if times != 1: - unit = unit.removeprefix(mtx.fmt(times)) - out = [f"{row.get('이름') or row.get('키')} / {unit}"] - if row.get("출처"): - out.append(f"{row['출처']} 적용") - return out + _steps(whole, row, env, price_of, 0) +def _won(v: Any) -> str: + return GAP if v is None else f"{v:,.0f}" def _word(whole: Any, name: str, value: Any) -> str: - """값 글 — 수 = 보이는 자릿수 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미).""" - if isinstance(value, Decimal): - return mtx.fmt(value) + """값 글 — 수 = 화면 수 꼴 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미).""" if isinstance(value, str): return labor_inputs._labels(whole, {"이름": name, "고르기": [value]}).get(value, value) - return str(value) + return mdt.eq_text(value) if _dec(value) is not None else str(value) -def _shown(whole: Any, name: str, value: Any) -> str | None: - if value is None or isinstance(value, mf.Blank): - return "값 없음" - return None if isinstance(value, dict) else _word(whole, name, value) +# ── 머리(입력 · 공식) ──────────────────────────────────────────────── +def _bare(node: tuple) -> tuple: + """표시 자리 감싸개(`반올림(식, n)` · B09 작업량 Q) — 식 글은 속 식으로.""" + if node and node[0] == "call" and node[1] in ("반올림", "올림", "버림") and len(node[2]) == 2: + return node[2][0] + return node -def _marks(row: dict, whole: Any) -> list[dict]: - """별칭(찾기 · 로직 부르기 → 짧은 이름 · `master_copy.aliases`) — 못 지으면 빈 목록.""" - try: - return mtx.mc.aliases(row, whole) - except _ERRORS: - return [] +def _swap(node: Any, put) -> Any: + """식 나무의 기호 바꿈 — `put(이름)` 이 None 이면 그대로.""" + if not isinstance(node, tuple): + return node + if node[0] == "var": + got = put(node[1]) + return node if got is None else got + if node[0] == "call": + return ("call", node[1], [_swap(x, put) for x in node[2]]) + return tuple(_swap(x, put) for x in node) -def _call_text(whole: Any, mark: dict, env: dict, price_of: PriceOf) -> str | None: - """별칭 자리 글 — 찾기 = 「표 이름(조건 = 값)」 · 로직 = 「로직 이름(산근 n호표)」.""" - try: - node = mf.parse(mark["원문"]) - ref = mf.fill(node[1], env) - args = [(k, mf.evaluate(v, env, whole, 0)) for k, v in node[2]] - except _ERRORS: - return None - if mark["종류"] == "찾기": - conds = ", ".join(f"{k} = {_word(whole, k, v)}" for k, v in args) - return f"{mark.get('밑이름') or mark['이름']}{f'({conds})' if conds else ''}" - try: - name = str(whole.logic(ref).get("이름") or ref) - except mf.FormulaError: - return None - got = ( - price_of(sg.sangeun_key(ref, sg._clean_given(dict(args)))) - if sg.is_money(whole, ref) - else None - ) - return f"{name}(산근 {got['no']}호표)" if isinstance(got, dict) and got.get("no") else name +def _label(i: str, var: dict) -> str: + """기호 화면 이름 — 원래 이름(열쇠) · 지은 기호(열쇠 = 기호 · 표 칸)면 변수 이름(「표 이름.칸」).""" + key = str(var.get("열쇠") or "") + return key if key and key != i else str(var.get("이름") or i) -def _named(text: str, env: dict, whole: Any, marks: list[dict], price_of: PriceOf) -> str: - """이름 꼴 식 — 별칭은 찾기 표 이름(조건) · 로직 이름으로 바꿔 씀.""" - named = mtx._names(text, env, whole, mtx.mc.names(marks)) - for mark in sorted(marks, key=lambda m: -len(m["이름"])): - pattern = rf"(? None: + self.whole, self.answer = whole, answer + self.doc, self.values = answer.doc, answer.ans.get("값") or {} + self.vars = {md.var_id(v): v for v in self.doc.get("변수") or []} + self.names = {i: _label(i, v) for i, v in self.vars.items()} + def unit(self, i: str) -> str: + return mdt.unit_text((self.vars.get(i) or {}).get("단위")) -def _valued(show, real, env: dict, whole: Any, depth: int = 0) -> str: - """값 꼴 식 — 엔진 `render` 와 같되 반올림 · 최소 · 최대 부르기는 값 넣은 인자째 · - 만약 = 걸린 갈래.""" - if show[0] == "call" and show[1] != "만약": - args = ", ".join(_valued(s, r, env, whole, depth) for s, r in zip(show[2], real[2])) - return f"{show[1]}({args})" - if show[0] == "call": - at = 1 if mf.evaluate(real[2][0], env, whole, depth) else 2 - return _valued(show[2][at], real[2][at], env, whole, depth) - if show[0] == "bin": - return mtx._bin(show, real, env, whole, depth, _valued) - if show[0] == "neg": - return "-" + _valued(show[1], real[1], env, whole, depth) - return mtx._draw(show, real, env, whole, depth) + def value(self, i: str) -> str: + v = self.values.get(i) + if v is None: + return "값 없음" + if isinstance(v, dict): + return " · ".join(f"{c} {mdt.eq_text(v.get(c))}" for c in mdt.COSTS) + return " ".join(x for x in (_word(self.whole, self.names.get(i, i), v), self.unit(i)) if x) - -def _formula(name, text, value, env, whole, marks, price_of, unit="") -> str: - """함수 한 줄 「이름 = 이름식 = 값 넣은 식 = 값」 — 같은 글이 이어지면 한 번만 · - 글 값(기계 원문번호 따위)은 따옴표 글을 빼고 「이름 규격」 만(157-3).""" - parts = [name] - literal = f"'{value}'" if isinstance(value, str) else None - for make in ( - lambda: _named(text, env, whole, marks, price_of), - lambda: _valued(*[mf.parse(text)] * 2, env, whole), - lambda: _shown(whole, name, value), - ): - try: - got = make() - except _ERRORS: - got = None - if got and got != parts[-1] and got != literal: - parts.append(got) - tail = f" {unit}" if unit and unit != "-" and isinstance(value, Decimal) else "" - return " = ".join(parts) + tail - - -def _expand(whole, mark: dict, env: dict, price_of: PriceOf, depth: int) -> list[str]: - """돈 아닌 하위 로직 풀이 — 그 로직의 입력 · 중간 · 결과를 「└ 」 줄로(돈 로직 = 산근 호표).""" - if mark["종류"] != "로직" or depth > 3: - return [] - try: - node = mf.parse(mark["원문"]) - ref = mf.fill(node[1], env) - row = whole.logic(ref) - if "결과" not in row or isinstance(row.get("흐름"), dict): - return [] - sub = mf._inputs(row, {k: mf.evaluate(v, env, whole, 0) for k, v in node[2]}) - for step in row.get("중간", []): - try: - sub[step["이름"]] = mf.evaluate(mf.parse(step["식"]), sub, whole, depth + 1) - except mf.EmptyInput as e: - sub[step["이름"]] = mf.Blank(str(e)) - except _ERRORS: - return [] - lead = " " * depth + "└ " - return [lead + line for line in _steps(whole, row, sub, price_of, depth + 1)] - - -def _steps(whole, row: dict, env: dict, price_of: PriceOf, depth: int) -> list[str]: - """흐름도 함수 상자 차례 — 입력(약어 뜻) · 중간 · 결과 · 호표 수량(맨 위만) · 하위 로직 풀이.""" - out: list[str] = [] - for spec in row.get("입력", []): - value = env.get(spec["이름"]) - if value is None: - continue - tail = f" {spec['단위']}" if spec.get("단위") else "" - about = f"{spec['설명']} = " if spec.get("설명") else "" - out.append(f"{spec['이름']} : {about}{_word(whole, spec['이름'], value)}{tail}") - marks = _marks(row, whole) - done: set[str] = set() - - def subs(where: str) -> list[str]: - lines = [] - for mark in marks: - if mark["이름"] not in done and where in mark.get("자리", []): - done.add(mark["이름"]) - lines += _expand(whole, mark, env, price_of, depth) - return lines - - for n, step in enumerate(row.get("중간", [])): - value = env.get(step["이름"]) - if value is None or isinstance(value, mf.Blank): - out.append(f"{step['이름']} = 값 없음") - continue - unit = step.get("단위") or _find_unit(step["식"], marks) - out.append(_formula(step["이름"], step["식"], value, env, whole, marks, price_of, unit)) - out += subs(f"중간[{n}].식") - if "결과" in row: - try: - value = mf.cut(row, mf.evaluate(mf.parse(row["결과"]["식"]), env, whole, depth), "결과") - except _ERRORS: - value = None - out.append(_formula("결과", row["결과"]["식"], value, env, whole, marks, price_of)) - out += subs("결과.식") - if depth: - return out - for n, item in enumerate(row.get("호표", [])): - try: - raw = mf.evaluate(mf.parse(item["수량"]), env, whole, 0) - named = _named(item["수량"], env, whole, marks, price_of) - valued = _valued(*[mf.parse(item["수량"])] * 2, env, whole) - except _ERRORS: - continue - if named != valued: - name = f"{item.get('이름', '')} 수량" - out.append( - _formula(name, item["수량"], raw, env, whole, marks, price_of, item.get("단위")) + def formula(self, i: str, text: str) -> str: + """「이름 = 이름식 = 값식 = 값 단위」 — 같은 글이 이어지면 한 번만.""" + node = _decide(mdt.node_of(text), self.answer) # 만약 = 걸린 갈래 + parts = [self.names.get(i, i)] + if node is not None: + node = _bare(node) + named = md.text_of( + _swap(node, lambda n: ("var", self.names[n]) if n in self.names else None) ) - out += subs(f"호표[{n}].수량") - return out + valued = md.text_of(_swap(node, self._num)) + parts += [named, valued] + v = self.values.get(i) + bare = mdt.eq_text(v) if _dec(v) is not None else f"'{v}'" if isinstance(v, str) else None + out = [parts[0]] + for p in parts[1:]: # 같은 글 · 값 그대로인 식 = 한 번만(화면 공식 줄) + if p and p != out[-1] and p != bare: + out.append(p) + out.append(self.value(i)) + return " = ".join(out) + def _num(self, name: str): + v = self.values.get(name) + d = _dec(v) + return ("var", mdt.eq_text(d)) if d is not None else None -def _find_unit(text: str, marks: list[dict]) -> str: - """식이 표 찾기 한 칸뿐이면 그 칸 단위(별칭 `값칸`) · 그 밖 = 빈 글.""" - for mark in marks: - head = mark["원문"] - if mark["종류"] == "찾기" and text.replace(" ", "").startswith(head.replace(" ", "") + "."): - unit = (mark.get("값칸") or {}).get(text.rpartition(".")[2], "") - return "" if unit in ("글", "구분 따름") else unit - return "" + def lines(self, times: Decimal) -> list[str]: + doc = self.doc + out = [f"{doc.get('이름') or doc.get('키')} / {mdt.unit_text(_per_unit(doc, times))}"] + if doc.get("출처"): + out.append(f"{doc['출처']} 적용") + steps = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []} + pack: list[str] = [] + def flush() -> None: + if pack: + out.append(" · ".join(pack)) + pack.clear() -def _material_key(whole: Any, item: dict, ref: Any, env: dict, n: int) -> tuple[str, str]: - """자재 줄 (대비표 키, 규격) — 자리표시 글(「MO:경유:전국평균」)은 그 요소의 실제 키로.""" - _p, source, _w, extra = mf.mp.priced(whole, item, ref, env, n) - goods = (extra or {}).get("품목") or {} - key = str( - goods.get("키") or (source or "").split(".")[0] or (ref if isinstance(ref, str) else "") - ) - if ":" in key: - try: - key = str(whole.get(key).get("키") or key) - except _ERRORS: - pass - return key, str(goods.get("규격") or "") - - -def _logic_lines(whole, item, env, qty_text, q, price_of) -> list[tuple[str, dict]]: - """로직 부르기 줄 — 기계경비 = 중기 노 · 재 · 경 세 줄 · 그 밖 = 하위 산근 한 줄 · - 금액 끝수 = 줄 `자리`(792-4 · `Sangeun_Sum.places` 와 같음).""" - node = mf.parse(item["요소"]) - called = node[1] if node and node[0] == "logic" else None - try: - target = whole.logic(called) if called else None - except mf.FormulaError: - target = None - name = item.get("이름", "") - if mf.mb.is_machine(target): # 기계경비 판별 한 곳(712-1) - keys = sg._captured(whole, node, env) - got = price_of(keys[0]) if keys else None - if not got: - return [(f"{name} : {NO_PRICE} * {qty_text}", dict.fromkeys(sg.PARTS))] - out = [] - for part in sg.PARTS: - text, money = _line( - f"{name} {PART_NAME[part]}", got.get(part), qty_text, q, item.get("자리") - ) - out.append((text, {part: money})) + for i, v in self.vars.items(): + kind = (v.get("연결") or {}).get("갈래") + if kind in INPUTS and self.values.get(i) is not None: + about = f"{v['설명']} = " if v.get("설명") else "" + flush() + out.append(f"{v.get('열쇠') or self.names[i]} : {about}{self.value(i)}") + elif kind == "식" and i in steps: + flush() + out.append(self.formula(i, steps[i])) + elif kind in VALUES and _dec(self.values.get(i)) is not None: + pack.append(f"{self.names[i]} = {self.value(i)}") + if len(pack) >= PACK: + flush() + flush() return out - if not target: - return [(f"{name} : 하위 로직을 못 펼침", dict.fromkeys(sg.PARTS))] - given = {k: mf.evaluate(expr, env, whole, 1) for k, expr in node[2]} - got = price_of(sg.sangeun_key(called, sg._clean_given(given))) or {} - parts = {p: got.get(p) for p in sg.PARTS} - if any(v is None for v in parts.values()): - return [(f"{name} : {NO_PRICE} * {qty_text}", dict.fromkeys(sg.PARTS))] - amounts = {p: ss._cut(float(v) * q, item.get("자리")) for p, v in parts.items()} - head = f"산근 {got['no']}호표 " if got.get("no") else "" - unit = sum(float(v) for v in parts.values()) - text = f"{name} : {head}{_price(unit)} * {qty_text} = {_money(sum(amounts.values()))}" - return [(text, amounts)] -def _pct_specs(whole, row, env) -> list[str]: - """% 덧줄마다 규격(「노무비의 %」 · 149-4 `M02_Labor_Doc.pct_extras`) · % 아닌 덧줄 = 빈 글.""" - head = [{} for _ in row.get("호표", [])] - tail = [{} for _ in row.get("덧줄", [])] - got = labor_doc.pct_extras(whole, row, head + tail, dict(env))[len(head) :] - return [str(one.get("규격") or "") for one in got] +def _per_unit(doc: dict, times: Decimal) -> str: + """결과단위 1 단위 이름(「원/10㎡」 = ㎡ · 배 1 = 그대로 「원/1기」 = 1기).""" + unit = str(doc.get("결과단위") or "").removeprefix("원/") + return unit.removeprefix(mdt.eq_text(times)) if times != 1 else unit -def _full(amounts: list[dict]) -> list[dict]: - return [{**dict.fromkeys(sg.PARTS, 0.0), **a} for a in amounts] +# ── 금액 줄 ─────────────────────────────────────────────────────────── +class _Docs: + """`master_doc_text.money_units` 의 하위 문서 읽기 — 사본 문서 묶음에서.""" + + def __init__(self, docs: dict) -> None: + self.docs = docs + + def doc(self, key: str) -> dict | None: + return self.docs.get(key) -def _extra_lines(whole, row, env, amounts: list[dict]) -> list[tuple[str, dict]]: - """% 줄(덧줄) — 밑수 = 그때까지 B09 비목 합(`Sangeun._extras` 와 같음) · 금액 ROUNDDOWN 1.""" - out: list[tuple[str, dict]] = [] - specs = _pct_specs(whole, row, env) - for extra, spec in zip(row.get("덧줄", []), specs): - part = sg.COST_PART.get(extra.get("비목"), "material") - sums = ss.sums(row, _full(amounts)) # 합밖 · 제외(792-3) - head = f"{extra['이름']}{f' ({spec})' if spec else ''} : " - if any(v is None for v in sums.values()): - out.append((f"{head}밑수 빈칸", {part: None})) - amounts.append({part: None}) - continue - env.update({k: Decimal(str(v)) for k, v in sums.items()}) - ss.scope(row, _full(amounts), env) # 번지 · 단계(792-3) - try: - node = mf.parse(extra["식"]) - value = float(mf.evaluate(node, env, whole, 0)) - shown = mtx.render(node, env, whole) - except _ERRORS as e: - out.append((f"{head}계산 못 함 — {e}", {part: None})) - amounts.append({part: None}) - continue - money = ss.extra(row, extra, value, env) # 줄 자리(792-3) - out.append((f"{head}{shown} = {_money(money)}", {part: money})) - amounts.append({part: money}) - return out +def _units(answer: Any, n: int) -> dict: + doc = answer.doc + line = (doc.get("금액") or [])[n] + sym = mdt.price_sym(line) + var = answer.vars.get(sym) if sym else None + link = (var or {}).get("연결") or {} + sub = (answer.docs or {}).get(str(link.get("키"))) if link.get("갈래") == "단가산출" else None + qty = mdt.node_of(line.get("수량")) + return mdt.money_units(line, mdt.node_of(line.get("단가")), qty, var, sub) -def render_sangeun_text( +def _qty(answer: Any, n: int, units: dict, times: Decimal, rate: Decimal | None) -> str: + """수량 글 — 값 넣은 수량 식(화면 금액 줄 「× (수량 식) 단위」 · 식이면 괄호) 단위[ ÷ 배][ × 율 %].""" + raw = (answer.ans.get("줄") or [{}] * (n + 1))[n].get("수량") + node = _decide(mdt.node_of(((answer.doc.get("금액") or [])[n]).get("수량")), answer) + values = answer.ans.get("값") or {} + shown = mdt.eq_text(raw) + if node is not None and not mdt.is_atom(node): + put = lambda s: ("var", mdt.eq_text(values[s])) if _dec(values.get(s)) is not None else None # noqa: E731 + shown = f"({md.text_of(_swap(_bare(node), put))})" + text = mdt._u(shown, units["qty"]) + if times != 1: + text += f" ÷ {mdt.eq_text(times)}" + if rate is not None: + text += f" × {mdt.eq_text(rate * 100)} %" + return text + + +def _decide(node: Any, answer: Any) -> Any: + """만약 = 걸린 갈래만(화면 `decide` · 조건 = 셈 답 값 · `master_doc_text._Look`).""" + if node is None: + return None + look = getattr(answer, "_look", None) + if look is None: + look = answer._look = mdt._Look(answer.doc, answer.ans, ml.Links(answer.whole, answer.docs)) + + def walk(n: Any) -> Any: + if not isinstance(n, tuple): + return n + if (pick := look.taken(n)) and n[0] == "call": + return walk(n[2][pick]) + if n[0] == "call": + return ("call", n[1], [walk(x) for x in n[2]]) + return tuple(walk(x) for x in n) + + return walk(node) + + +def _price(v: Any, unit: str) -> str: + return NO_PRICE if v is None else mdt._u(mdt.eq_text(v), unit) + + +def _amount(v: Any) -> str: + return GAP if v is None else f"{mdt.one(v)} {mdt.AMOUNT_UNIT}" + + +def _line_texts( + ln: dict, answer: Any, n: int, times: Decimal, rate: Decimal | None, no_of +) -> list[str]: + name, kind = ln.get("name") or "", ln.get("kind") + if kind == "blank": + return [f"{name} : {GAP} {ln.get('why') or '못 셈'}"] + units = _units(answer, n) + qty = _qty(answer, n, units, times, rate) + price = ln.get("price") or {} + if kind == "machine" and ln.get("why"): # 기계 시간당 없음 = 한 줄(풀이 줄 글 수와 같게) + return [f"{name} : {NO_PRICE} × {qty} = {GAP}"] + if kind == "machine": + return [ + f"{name} {PART_NAME[p]} : {_price(price.get(p), units['price'])} × {qty} = " + f"{_amount(ln.get(p))}" + for p in PARTS + ] + if kind == "sangeun": + no = no_of((ln.get("ref") or {}).get("key")) + unit = None if any(price.get(p) is None for p in PARTS) else sum(price[p] for p in PARTS) + money = None if unit is None else sum(ln.get(p) or 0 for p in PARTS) + head = f"산근 {no}호표 " if no else "" + return [f"{name} : {head}{_price(unit, units['price'])} × {qty} = {_amount(money)}"] + part = next(iter(price), None) or next((p for p in PARTS if ln.get(p)), "material") + shown = ln.get(part) + label = f"{name}({ln['spec']})" if kind == "material" and ln.get("spec") else name + return [f"{label} : {_price(price.get(part), units['price'])} × {qty} = {_amount(shown)}"] + + +def _extra_text(ln: dict) -> str: + """% 덧줄 · 고정 덧줄 — 밑수 × 율 % · 값 하나.""" + spec = f" ({ln.get('spec')})" if ln.get("unit") == "%" and ln.get("spec") else "" + head = f"{ln['name']}{spec} : " + part = next(iter(ln.get("price") or {}), None) + if part is None or ln.get(part) is None: + return f"{head}{GAP} {ln.get('why') or '밑수 빈칸'}" + value, money = ln["price"][part], ln[part] + if ln.get("unit") == "%" and ln.get("qty"): + base = Decimal(str(value)) * 100 / Decimal(str(ln["qty"])) + return f"{head}{mdt.eq_text(base)} × {mdt.eq_text(ln['qty'])} % = {_amount(money)}" + return f"{head}{mdt.eq_text(value)} = {_amount(money)}" + + +def render( whole: Any, - logic_id: str, - inputs: dict | None, - price_of: PriceOf, + answer: Any, + lines: list[dict], *, times: Any = 1, rate: Any = None, - picks: dict | None = None, -) -> list[str]: - """산근 한 항목(로직 + 입력값 + 단가) → 엑셀 꼴 글 줄들. - - whole = 사본 단가 묶음(`item_prices.load_prices`) · inputs = 입력값(빈 칸 = 자동값) · - price_of = B09 단가 조회 · times = 결과단위 배(「원/10㎡」 = 10) · - rate = 켜쌓기율 %(100 · None = 없음) · picks = 고른 자재.""" - try: - row = whole.logic(logic_id) - except mf.FormulaError as e: - return [f"{logic_id} : 로직 없음 — {e}"] + no_of=lambda _key: None, +) -> tuple[list[str], list[list[str]]]: + """산근 한 블록 → (머리 줄들, 블록 줄마다 글 줄들 · 중기 = 셋) — `answer` = 그 로직 문서 셈 답 + (켜쌓기율 없이 · 결과단위 몫) · `lines` = 풀이 블록 줄(관급 0 원 앞) · times = 결과단위 배 · + rate = 켜쌓기율 % · `no_of(산근 키)` = 하위 산근 호표 번호.""" times = Decimal(str(times or 1)) scale = Decimal(str(rate)) / 100 if rate not in (None, 100) else None - try: - env = sg._env(whole, row, sg._clean_given(inputs)) - except _ERRORS as e: - return [f"{row.get('이름') or logic_id} : 입력을 못 읽음 — {e}"] - out = _head(row, env, whole, times, price_of) - amounts: list[dict] = [] - with mf.mp.choosing(picks): - for n, item in enumerate(row.get("호표", [])): - name = item.get("이름", "") - try: - raw = mf.evaluate(mf.parse(item["수량"]), env, whole, 0) - qty_text = _qty_text(item, env, whole, times, scale) - except mf.EmptyInput as e: - out.append(f"{name} : 수량 없음 — {e}") - amounts.append({sg.COST_PART.get(item.get("비목"), "material"): None}) - continue - q = float(Decimal(str(raw)) / times * (scale or 1)) - kind = item.get("종류") - if kind == "로직": - merged: dict = {} # 줄 하나 = 금액 하나(중기 세 줄 · 792-3 합밖 · 번지 차례) - for text, money in _logic_lines(whole, item, env, qty_text, q, price_of): - out.append(text) - merged.update(money) - amounts.append(merged) - continue - if kind == "인력": - key = mf.fill(item["요소"], env) if isinstance(item["요소"], str) else "" - text, money = _line(name, price_of(key), qty_text, q, item.get("자리")) - out.append(text) - amounts.append({"labor": money}) - continue - ref = ( - {k: mf.fill(v, env) if isinstance(v, str) else v for k, v in item["요소"].items()} - if isinstance(item["요소"], dict) - else mf.fill(item["요소"], env) - ) - key, spec = _material_key(whole, item, ref, env, n) - price = price_of(key) - if q == 0 and price is None: - price = 0.0 # 안 쓰는 재료 줄 — 금액 0(`Sangeun._line` 과 같음) - label = f"{name}({spec})" if spec else name - text, money = _line(label, price, qty_text, q, item.get("자리")) - out.append(text) - amounts.append({sg.COST_PART.get(item.get("비목"), "material"): money}) - for text, _money_part in _extra_lines(whole, row, env, amounts): - out.append(text) - sums = ss.totals(row, _full(amounts)) or sg.block_totals(_full(amounts)) # 끝전 · 조정(792-3) - parts = " + ".join( - f"{PART_NAME[p]} {'빈칸' if sums[p] is None else f'{sums[p]:,.0f}'}" for p in sg.PARTS - ) - out.append(f"계 : {parts} = {'빈칸' if sums['sum'] is None else f'{sums["sum"]:,.0f}'}") - return out + head = _Head(whole, answer).lines(times) + heads = len([x for x in lines if x.get("kind") != "extra"]) + texts = [ + _line_texts(ln, answer, n, times, scale, no_of) if n < heads else [_extra_text(ln)] + for n, ln in enumerate(lines) + ] + return head, texts + + +def foot(sums: dict) -> str: + """계 줄 — 블록 비목 합(B09 끝수 · 관급 0 원 뒤).""" + parts = " + ".join(f"{PART_NAME[p]} {_won(sums.get(p))}" for p in PARTS) + return f"계 : {parts} = {_won(sums.get('sum'))}" diff --git a/resources/tester/golden_855_b09.json b/resources/tester/golden_855_b09.json index 36d1c81f4..45cc43183 100644 --- a/resources/tester/golden_855_b09.json +++ b/resources/tester/golden_855_b09.json @@ -6,15 +6,15 @@ "daega_inputs": "a06884bce408c602", "수요": "5fdf7c49052e322c", "산근 값": "38455c2edce885ff", - "산근 글": "c41b0c2e4ae200fb", + "산근 글": "f5b884a2c49c91c6", "산근 관급 값": "d154925ee64c985c", - "산근 관급 글": "396194c98b10b525", + "산근 관급 글": "9397c1d1a5fe0dcd", "미리보기 hand:rate 값": "091690571b7dc54b", - "미리보기 hand:rate 글": "c49b1bc692d59fe5", + "미리보기 hand:rate 글": "d17615784f25e4f5", "미리보기 hand:pick 값": "6c7f426d37e31998", - "미리보기 hand:pick 글": "96a9de9a02e3d124", + "미리보기 hand:pick 글": "7836022de46b3072", "미리보기 hand:net 값": "b1c2c650567a14ae", - "미리보기 hand:net 글": "9846e15ac6f0f663", + "미리보기 hand:net 글": "0254ea22d7a23e43", "B08 단위수량": "896710398b04b4fd" } } diff --git a/resources/tester/helper_855_engine.py b/resources/tester/helper_855_engine.py index 8eeb49b12..d16764d13 100644 --- a/resources/tester/helper_855_engine.py +++ b/resources/tester/helper_855_engine.py @@ -164,6 +164,52 @@ def fingerprint(key: str, row: dict, options: bool = True) -> str: return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] +def _old_env(whole, row: dict, given: dict) -> dict: + """옛 B09 `Sangeun._env`(B9-4 에서 B09 는 걷음 · 대조 기준만) — 입력(빈 입력 = 자동값) + 중간값 · + 작업량 Q = ROUND 2 · `표시` 자리.""" + import re + + from B09_Estimation.B09_Estimation_Calc_Base import round_half + + ms = importlib.import_module("master_formula_sum") + auto = {k: v for k, v in m01.mau.values(whole, row).items() if v is not None} + env = mf._inputs(row, {**auto, **m01._dec(given or {})}) + for step in row.get("중간", []): + try: + value = mf.evaluate(mf.parse(step["식"]), env, whole, 0) + except mf.EmptyInput as e: + env[step["이름"]] = mf.Blank(str(e)) + continue + if step.get("표시") is not None or ms.uses(row): + value = ms.shown(step, value) + elif re.fullmatch(r"Q\d*", step["이름"]) and isinstance(value, Decimal): + value = Decimal(str(round_half(float(value), 2))) + env[step["이름"]] = value + return env + + +def _old_captured(whole, node, env: dict) -> list[str]: + """옛 B09 `Sangeun._captured` — 식을 돌리며 부른 기계 키(EQ).""" + seen: list[str] = [] + base = whole.get + + def get(ref): + row = base(ref) + key = str(row.get("키") or "") + if key.startswith("EQ") and key not in seen: + seen.append(key) + return row + + whole.get = get + try: + mf.evaluate(node, env, whole, 1) + except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): + pass + finally: + whole.get = base + return seen + + def old_line_calls(whole, code: str, given) -> dict: """옛 엔진 하위 부름(855-F B9-3 전 `B09 line_calls` · 대조 기준 · 2-E4 에서 은퇴) — 로직 호표 줄 차례 → 기계경비 {machine} · 돈 로직 {code, given} · 못 셈 = None.""" @@ -171,7 +217,7 @@ def old_line_calls(whole, code: str, given) -> dict: try: row = whole.logic(code) - env = sg._env(whole, row, sg._clean_given(given)) + env = _old_env(whole, row, sg._clean_given(given)) except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): return {} out: dict = {} @@ -185,7 +231,7 @@ def old_line_calls(whole, code: str, given) -> dict: if not target: out[n] = None elif mf.mb.is_machine(target): - keys = sg._captured(whole, node, env) + keys = _old_captured(whole, node, env) out[n] = {"machine": keys[0] if keys else None} else: given_ = {name: mf.evaluate(expr, env, whole, 1) for name, expr in node[2]} diff --git a/resources/tester/test_155_5_sangeun_text.py b/resources/tester/test_155_5_sangeun_text.py index 240e8c576..5fa3f51f4 100644 --- a/resources/tester/test_155_5_sangeun_text.py +++ b/resources/tester/test_155_5_sangeun_text.py @@ -1,11 +1,10 @@ -"""155-5 산근 텍스트 수식 — 엑셀 단가산출근거 꼴 글 줄(`B09_Estimation_Sangeun_Text`). +"""155-5 · 855-F B9-4 산근 산출근거 글(`B09_Estimation_Sangeun_Text.render`) — 풀이 블록 + 문서 셈 답. -- 엑셀 6호표 뒷채움: 「보통인부 : 165,545 * 0.018 = 2,979.8」 · 중기 노 · 재 · 경 세 줄 · - 「계 : 노무비 6,878 + 재료비 538 + 경비 912 = 8,328」(줄 ROUNDDOWN 1 · 계 ROUNDDOWN 0) -- 엑셀 7호표 막자갈채집: 작업량 Q = ROUND 2 중간 줄 · 「55,700 * 1 / 21.59 * 2 = 5,159.7」 -- % 덧줄 = 「공구손료 (노무비의 %) : 6,878.8 * 3 % = 206.3」(규격 = 149-4 `pct_extras`) -- 단가 없음 = 「단가 없음」 글 · 계 그 비목 빈칸 · 글 속 금액 = 산근 풀이(`Sangeun.Solver` · 841-1 M02 엔진 - 단가) 줄 값 +- 머리 = 「이름 / 단위」 · 「출처 적용」 · 입력 「이름 : 값 단위」(801-5 단위) +- 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」(화면 줄 쌓기 산출근거 꼴 · `master_doc_text`) · + 중기 노 · 재 · 경 세 줄 · 결과단위 배 「÷ 배」 · 켜쌓기율 「× 율 %」 · 글 속 금액 = 풀이 블록 줄 값 +- 작업량 Q = ROUND 2 공식 줄 「Q = 21.594 = 21.59」 · 수량 식 = 값 넣은 식 「(1 ÷ 21.59 × 2)」 +- % 덧줄 = 「공구손료 (노무비의 %) : 밑수 × 3 % = 금액 원」 · 계 = 블록 합 """ import copy @@ -17,12 +16,10 @@ if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from B09_Estimation import B09_Estimation_Sangeun as sg # noqa: E402 -from B09_Estimation import B09_Estimation_Sangeun_Text as st # noqa: E402 from M02_MasterTemplete import M02_Item_Prices as item_prices # noqa: E402 BASE = "GF000218" # 기초다짐 및 뒷채움(기계) — 보통인부 + 굴착기 0.2㎥ 로직 줄 GIVEN = {"규격": 150, "지역": "전국평균", "보정작업": "해당 없음"} -EXCEL_EQ = {"labor": 55700, "material": 7695, "expense": 13041} # 중기목록표 굴삭기 0.2㎥ def _whole(edit=None): @@ -46,76 +43,82 @@ def _excel(qty_labor: str, qty_eq: str, mids=(), extras=()): return edit -def _prices(labor): - return lambda key: EXCEL_EQ if key.startswith("EQ") else labor.get(key) +def _block(edit, code=BASE, given=GIVEN, **src): + return sg.Solver().add( + _whole(edit) if edit else _whole(), {"code": code, "given": given, **src}, "s1" + ) -def test_엑셀_6호표_뒷채움_같은_글(): - whole = _whole(_excel("0.018", "0.07")) - got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545})) - assert got[:3] == [ +def _texts(block) -> list[str]: + return [t for ln in block["lines"] for t in ln.get("text") or []] + + +def _foot(block) -> str: + parts = " + ".join( + f"{n} {block[p]:,.0f}" for p, n in zip(sg.PARTS, ("노무비", "재료비", "경비")) + ) + return f"계 : {parts} = {block['sum']:,.0f}" + + +def test_머리_줄_중기_세_줄_계(): + block = _block(_excel("0.018", "0.07")) + assert block["head"][:3] == [ "기초다짐 및 뒷채움(기계) / ㎥", "산림품셈 13-3-2 적용", "규격 : 150 ㎜", - ] # 801-5 단위 - assert got[-5:] == [ - "보통인부 : 165,545 * 0.018 = 2,979.8", - "굴착기(무한궤도) 0.2㎥ 노무비 : 55,700 * 0.07 = 3,899.0", - "굴착기(무한궤도) 0.2㎥ 재료비 : 7,695 * 0.07 = 538.6", - "굴착기(무한궤도) 0.2㎥ 경비 : 13,041 * 0.07 = 912.8", - "계 : 노무비 6,878 + 재료비 538 + 경비 912 = 8,328", ] + labor, eq = block["lines"] + assert labor["text"] == [ + f"보통인부 : {labor['price']['labor']:,.0f} 원/인 × 0.018 인 = {labor['labor']:,.1f} 원" + ] + assert [t.split(" : ")[0] for t in eq["text"]] == [ + f"굴착기(무한궤도) 0.2㎥ {n}" for n in ("노무비", "재료비", "경비") + ] + assert [t.endswith(f"= {eq[p]:,.1f} 원") for t, p in zip(eq["text"], sg.PARTS)] == [True] * 3 + assert block["foot"] == _foot(block) -def test_엑셀_7호표_작업량_Q_중간_줄(): - whole = _whole(_excel("0", "1 / Q * 2", mids=[("Q", "21.594")])) - got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545})) - assert "Q = 21.594 = 21.59" in got # ROUND(식, 2) 뒤 쓰임 - assert "굴착기(무한궤도) 0.2㎥ 노무비 : 55,700 * 1 / 21.59 * 2 = 5,159.7" in got +def test_작업량_Q_공식_줄_값_넣은_수량식(): + block = _block(_excel("0", "1 / Q * 2", mids=[("Q", "21.594")])) + assert "Q = 21.594 = 21.59 ㎥/hr" in block["head"] # ROUND(식, 2) 뒤 쓰임 + assert all("× (1 ÷ 21.59 × 2) 시간 = " in t for t in block["lines"][1]["text"]) def test_퍼센트_덧줄_노무비의_퍼센트(): tool = {"이름": "공구손료", "식": "노무비 * 3 / 100", "비목": "경비"} - whole = _whole(_excel("0.018", "0.07", extras=[tool])) - got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545})) - assert got[-2:] == [ - "공구손료 (노무비의 %) : 6,878.8 * 3 % = 206.3", # 밑수 = 인력 + 중기 노무비 - "계 : 노무비 6,878 + 재료비 538 + 경비 1,119 = 8,535", - ] + block = _block(_excel("0.018", "0.07", extras=[tool])) + pct = block["lines"][-1] + base = sum(ln["labor"] for ln in block["lines"][:-1]) # 밑수 = 인력 + 중기 노무비 + assert pct["text"] == [f"공구손료 (노무비의 %) : {base:,.1f} × 3 % = {pct['expense']:,.1f} 원"] + assert block["foot"] == _foot(block) -def test_배_켜쌓기율_꼬리_단가_없음(): - whole = _whole(_excel("0.018", "0.07")) - got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({}), times=10, rate=90) - assert "보통인부 : 단가 없음 * 0.018 / 10 * 90 % = 빈칸" in got - assert got[-1] == "계 : 노무비 빈칸 + 재료비 48 + 경비 82 = 빈칸" +def test_켜쌓기율_꼬리(): + block = _block(_excel("0.018", "0.07"), rate=90) + assert block["lines"][0]["text"][0].startswith("보통인부 : ") + assert "× 0.018 인 × 90 % = " in block["lines"][0]["text"][0] + assert block["foot"] == _foot(block) def test_글_속_금액은_산근_풀이_값과_같음(): for code, given in ((BASE, GIVEN), ("GF000288", {})): # 중기 · 노무 · % 덧줄 · 배 1,000 whole = item_prices.load_prices(item_prices.to_json(item_prices.collect([code]))) - solver = sg.Solver() # 841-1 단가 = M02 엔진 · 글 단가 = 풀이가 쓴 그 단가 - block = solver.add(whole, {"code": code, "given": given}, "s1") - price_of = solver.price_of - # 결과단위 배(「원/1,000㎡」) — 산근 풀이와 같은 1 단위 - times = sg._unit(whole.logic(code))[1] - got = st.render_sangeun_text(whole, code, given, price_of, times=times) - parts = " + ".join(f"{st.PART_NAME[p]} {block[p]:,.0f}" for p in sg.PARTS) - assert got[-1] == f"계 : {parts} = {block['sum']:,.0f}", code + block = sg.Solver().add(whole, {"code": code, "given": given}, "s1") + assert block["foot"] == _foot(block), code + for ln in block["lines"]: + if ln["kind"] in ("labor", "material"): + part = next(iter(ln["price"])) + assert ln["text"][0].endswith(f"= {ln[part]:,.1f} 원"), (code, ln["text"]) + if sg._unit(whole.logic(code))[1] != 1: + assert all(" ÷ 1,000" in t for t in _texts(block)[:2]), code def test_자재_자리표시_키는_실제_키로(): - """「MO:휘발유:{지역}」 자리표시 = 대비표 키(MO…)로 물음 — 산근 풀이 흠(H4 · 155 데스크탑 보조가 - 고침)과 달리 단가가 나옴 · Q 중간 줄 · 「줄.'이름'」 % 덧줄.""" + """「MO:휘발유:{지역}」 자리표시 = 대비표 키(MO…) · 수집량 공식 줄 · 「× (6.5 × 0.125)」 · % 덧줄.""" whole = item_prices.load_prices(item_prices.to_json(item_prices.collect(["GF000062"]))) - asked = [] - - def price_of(key): - asked.append(key) - return 1000.0 - - got = st.render_sangeun_text(whole, "GF000062", {}, price_of) - assert not [k for k in asked if ":" in k] and any(k.startswith("MO") for k in asked) - assert "Q = 아키야윈치(임업용 윈치) 집재(집재거리 = 50m 내외).수집량 = 8 ㎥" in got # 157-1 - assert "일수 = 1 / Q = 1 / 8 = 0.125" in got - assert "휘발유(아키아윈치(휘발유)) : 1,000 * 6.5 * 0.125 = 812.5" in got + block = sg.Solver().add(whole, {"code": "GF000062", "given": {}}, "s1") + fuel = next(ln for ln in block["lines"] if ln["name"].startswith("휘발유")) + assert fuel["ref"]["key"].startswith("MO") and ":" not in fuel["ref"]["key"] + assert "일수 = 1 ÷ 수집량 = 1 ÷ 8 = 0.125 일/㎥" in block["head"] + assert "× (6.5 × 0.125) ℓ = " in fuel["text"][0] + assert block["lines"][3]["text"][0].startswith("잡품 (재료비의 %) : ") diff --git a/resources/tester/test_155_b09_sources.py b/resources/tester/test_155_b09_sources.py index 8e8465286..54791d24b 100644 --- a/resources/tester/test_155_b09_sources.py +++ b/resources/tester/test_155_b09_sources.py @@ -124,9 +124,9 @@ def test_155_5_산근_글_줄마다_덧줄_퍼센트_표기(tmp_path): for b in (crane, pile): for ln in b["lines"]: money = sum(ln[p] or 0 for p in sg.PARTS) - assert ln["text"][-1].endswith(f"= {money:,.1f}") or ln["kind"] == "machine" + assert ln["text"][-1].endswith(f"= {money:,.1f} 원") or ln["kind"] == "machine" assert b["foot"] == ( f"계 : 노무비 {b['labor']:,.0f} + 재료비 {b['material']:,.0f}" f" + 경비 {b['expense']:,.0f} = {b['sum']:,.0f}" ) - assert " / 10 = " in pile["lines"][0]["text"][0] # 배 10 로직 꼬리 + assert " ÷ 10 = " in pile["lines"][0]["text"][0] # 배 10 로직 꼬리(B9-4 화면 꼴 「÷」) diff --git a/resources/tester/test_157_1_sangeun_steps.py b/resources/tester/test_157_1_sangeun_steps.py index a2cf661cd..19770af1d 100644 --- a/resources/tester/test_157_1_sangeun_steps.py +++ b/resources/tester/test_157_1_sangeun_steps.py @@ -1,9 +1,9 @@ -"""157-1 산근 글 = M01 흐름도 함수 상자 빠짐없이 · 157-3 기계 번호 = 「이름 규격」(`Sangeun_Text`). +"""157-1 · 855-F B9-4 산근 글 머리 = 문서 공식 줄 · 157-3 기계 번호 = 「이름 규격」(`Sangeun_Text`). -- 중간 여럿 · 중간이 중간을 부름 = 「이름 = 이름식 = 값 넣은 식 = 값」(GF000064 일수) -- 찾기 = 「이름 = 표 이름(조건 = 값).칸 = 값 단위」 · 돈 아닌 하위 로직 = 이름 + 「└ 」 풀이 -- 돈 하위 로직 = 「로직 이름(산근 n호표)」 · 만약 = 걸린 갈래만 · 입력 = 「이름 : 설명 = 값 단위」 -- 함수 줄은 머리에만 — 호표 줄 · 계 = 산근 풀이(`Sangeun.Solver`) 줄 글 · 금액 그대로 +- 공식 줄 = 「이름 = 이름식 = 값 넣은 식 = 값 단위」(GF000064 일수 · 중간이 중간을 부름) · 만약 = 걸린 갈래만 +- 표 · 하위 결과 값 = 「이름 = 값 단위」(넷까지 한 줄 · 화면 공식 묶음) · 입력 = 「이름 : 설명 = 값 단위」 +- 수량 식 = 금액 줄 안 값 넣은 식 「× (2 × 0.098302)」(머리 「… 수량 =」 줄 없음) +- 호표 줄 · 계 = 산근 풀이(`Sangeun.Solver`) 줄 글 · 금액 그대로 """ import copy @@ -15,11 +15,8 @@ if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from B09_Estimation import B09_Estimation_Sangeun as sg # noqa: E402 -from B09_Estimation import B09_Estimation_Sangeun_Text as st # noqa: E402 from M02_MasterTemplete import M02_Item_Prices as item_prices # noqa: E402 -EQ = {"labor": 55700, "material": 7695, "expense": 13041} - def _whole(codes, edit=None): files = copy.deepcopy(item_prices.to_json(item_prices.collect(codes))) @@ -31,63 +28,31 @@ def _whole(codes, edit=None): return item_prices.load_prices(files) -def _price_of(key): - if key.startswith("SG:"): - return {"no": 3, "labor": 1000.0, "material": 0.0, "expense": 0.0, "sum": 1000.0} - return EQ if key.startswith("EQ") else 1000.0 - - def test_중간이_중간을_부름_값_넣은_식까지(): - got = st.render_sangeun_text(_whole(["GF000064"]), "GF000064", {}, _price_of) - assert "일수 = 1 / Q * (1 + 할증 %) = 1 / 11.19 * (1 + 10 %) = 0.0983" in got - assert "할증 = 소형가선 집재 숲가꾸기 주 속 수(구분 = 총 소요인력 할증).적용 = 10" in got - assert "보통인부 수량 = 2 * 일수 = 2 * 0.0983 = 0.1966 인" in got # 호표 수량 함수 - - -def test_돈_아닌_하위_로직_풀이_찾기_결과식(): - got = st.render_sangeun_text(_whole(["GF000089"]), "GF000089", {}, _price_of) - at = got.index("작업량 = 토사깍기(기계 · 굴착기 0.7㎥) 시간당 작업량 = 39.293") - assert got[at + 1 : at + 8] == [ - "└ E입력 : 0.45", - "└ q = 토사깍기 장비(구분 = 무한궤도 굴착기).적용 = 0.7 ㎥", - "└ K = 토사깍기 기계(구분 = K).적용 = 0.9", - "└ f = 토사깍기 체적환산계수(구분 = f).적용 = 0.77", - "└ E = E입력 = 0.45", - "└ Cm = 토사깍기 기계(구분 = ㎝(sec)).적용 = 20 sec", # 801-5 M01 단위 표기 - "└ 결과 = 반올림(3,600 * q * K * f * E / Cm, 3) = " - "반올림(3,600 * 0.7 * 0.9 * 0.77 * 0.45 / 20, 3) = 39.293", - ] - assert "굴착기(무한궤도) 0.7㎥ 노무비 : 55,700 * 1 / 39.293 = 1,417.5" in got - - -def test_결과_로직_맨_위(): - got = st.render_sangeun_text(_whole(["GF000088"]), "GF000088", {}, _price_of) + block = _solver(_whole(["GF000064"]), "GF000064", {}) assert ( - "결과 = 반올림(3,600 * q * K * f * E / Cm, 3) = " - "반올림(3,600 * 0.7 * 0.9 * 0.77 * 0.45 / 20, 3) = 39.293" - ) in got + "일수 = 1 ÷ 수집량 × (1 + 할증 ÷ 100) = 1 ÷ 11.19 × (1 + 10 ÷ 100) = 0.098302 일/㎥" + ) in block["head"] + assert "할증 = 소형가선 집재 숲가꾸기 주 속 수 총 소요인력 할증 = 10 %" in block["head"] + worker = next(ln for ln in block["lines"] if ln["name"] == "보통인부") + assert "× (2 × 0.098302) 인 = " in worker["text"][0] # 수량 식 = 금액 줄 안 -def test_돈_하위_로직_산근_호표_번호(): - def edit(row): - row["중간"].append( - {"이름": "참고", "식": "로직(GF000123, 지역=지역, 보정작업=보정작업).노무비"} - ) - - got = st.render_sangeun_text(_whole(["GF000089", "GF000123"], edit), "GF000089", {}, _price_of) - line = next(t for t in got if t.startswith("참고 = ")) - assert line.startswith("참고 = 층따기(산근 3호표).노무비 = ") +def test_하위_결과_값_줄(): + block = _solver(_whole(["GF000089"]), "GF000089", {}) + assert "작업량 = 39.293 ㎥/hr" in block["head"] + assert "E입력 : 0.45" in block["head"] + assert all("× (1 ÷ 39.293) 시간 = " in t for t in block["lines"][0]["text"]) def test_만약_걸린_갈래_입력_설명_기계_이름(): - got = st.render_sangeun_text(_whole(["GF000297"]), "GF000297", {"흉고직경": 20}, _price_of) - assert "흉고직경 : 가슴높이(1.2m) 지름(표 구간 안 값) = 20 ㎝" in got - assert "굴착기 = 굴착기(무한궤도) 0.6㎥" in got # 157-3 원문번호 '0201-0060' 대신 - assert "기계 = 1" in got and not [t for t in got if "0201-" in t] - assert ( - "특별인부 수량 = 식재작업 교목식재(흉고직경)(흉고직경(㎝) = 20).특별인부 * (1 - 감 %)" - " = 0.56 * (1 - 0 %) = 0.56 인" - ) in got + block = _solver(_whole(["GF000297"]), "GF000297", {"흉고직경": 20}) + head = block["head"] + assert "흉고직경 : 가슴높이(1.2m) 지름(표 구간 안 값) = 20 ㎝" in head + assert "굴착기 = 굴착기(무한궤도) 0.6㎥" in head # 157-3 원문번호 '0201-0060' 대신 + assert "기계 = 1" in head and not [t for t in head if "0201-" in t] + labor = next(ln for ln in block["lines"] if ln["name"] == "특별인부") + assert "× (0.56 × (1 - 0 ÷ 100)) 인 = " in labor["text"][0] def _solver(whole, code, given): @@ -100,7 +65,9 @@ def test_호표_줄_계는_산근_풀이와_같음(): for code, given in (("GF000089", {}), ("GF000064", {}), ("GF000297", {"흉고직경": 20})): whole = _whole([code]) block = _solver(whole, code, given) - parts = " + ".join(f"{st.PART_NAME[p]} {block[p]:,.0f}" for p in sg.PARTS) + parts = " + ".join( + f"{n} {block[p]:,.0f}" for p, n in zip(sg.PARTS, ("노무비", "재료비", "경비")) + ) assert block["foot"] == f"계 : {parts} = {block['sum']:,.0f}", code assert all(ln.get("text") for ln in block["lines"]), code assert any(" 수량 = " in t or " = " in t for t in block["head"]), code diff --git a/resources/tester/test_855_trace.py b/resources/tester/test_855_trace.py index b6e711607..52710c2b1 100644 --- a/resources/tester/test_855_trace.py +++ b/resources/tester/test_855_trace.py @@ -112,7 +112,7 @@ def survey() -> dict: out["하위"][key] = (sorted(a), sorted(b)) if not lines: try: - sg()._env(whole, row, sg()._clean_given(given)) + h._old_env(whole, row, sg()._clean_given(given)) except Exception: out["옛 빈 답"].add(key) for c in got["부름"]: From 9c78072971c49d623484a40aee36b298b300187e Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 03:12:11 +0900 Subject: [PATCH 4/4] =?UTF-8?q?refactor(855-E=202-E1):=20M01=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=20=EC=98=9B=20=EC=8B=9C=ED=97=98=20=EA=B3=84=EC=82=B0?= =?UTF-8?q?=20=C2=B7=20=EC=98=9B=20=EC=83=81=EC=84=B8=20=EB=AA=B8=20?= =?UTF-8?q?=EB=B6=80=ED=92=88=20=EA=B1=B7=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 지움(부르는 곳 0 — 저장소 TS · cjs · py · html 다시 찾음): UI_Logic_Drive.ts(driveRun · autoFill) · UI_Logic_CalcPick.ts · UI_LogicLab_Pill.ts · .css - Logic_Api: runCalc · runText · fetchAuto · searchPrice · CalcAnswer · TextAnswer · TextLine · TextPiece 걷음 - LogicLab_Modal: 옛 재료 · 표 · 참조 · 글 모달 걷음 — 로직 열기 · headWord 만 남김(−550 줄) - Logic_Note.explain · Side.hasMasterJump · 죽은 CSS 다섯 · 글 키 29(옛 시험 계산 · 모달 · 알약) 걷음 - 시험: 지운 파일 글자만 보던 test_750_2(빈 파일 됨) · test_799_2 구동 시험 · test_734 알약 · 풍선 시험 지움 · helper_717_1 · test_717_1 의 /calc · /text · /logic/auto 화면 길 줄 걷음 - typecheck 0 · 관련 50 통과 Co-Authored-By: Claude Opus 5.5 --- .../M01_MasterData_UI_LogicLab_Detail.ts | 1 - .../M01_MasterData_UI_LogicLab_Modal.ts | 556 +----------------- .../M01_MasterData_UI_LogicLab_Pill.css | 16 - .../M01_MasterData_UI_LogicLab_Pill.ts | 49 -- .../M01_MasterData_UI_LogicLab_Style.css | 32 - .../M01_MasterData_UI_LogicLab_Text.ts | 33 -- M01_MasterData/M01_MasterData_UI_Logic_Api.ts | 87 --- .../M01_MasterData_UI_Logic_CalcPick.ts | 191 ------ .../M01_MasterData_UI_Logic_Drive.ts | 76 --- .../M01_MasterData_UI_Logic_Note.ts | 65 +- .../M01_MasterData_UI_Logic_Text.ts | 11 - M01_MasterData/M01_MasterData_UI_Side.ts | 1 - .../tester/helper_717_1_logic_api_paths.cjs | 3 - resources/tester/test_717_1_logic_lib.py | 6 +- resources/tester/test_734_calc_buttons.py | 10 - .../tester/test_750_2_views_one_answer.py | 17 - resources/tester/test_799_2_old_tabs_gone.py | 15 +- 17 files changed, 5 insertions(+), 1164 deletions(-) delete mode 100644 M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css delete mode 100644 M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts delete mode 100644 M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts delete mode 100644 M01_MasterData/M01_MasterData_UI_Logic_Drive.ts delete mode 100644 resources/tester/test_750_2_views_one_answer.py diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts index 7d64e9328..9a1a63499 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Detail.ts @@ -10,7 +10,6 @@ import type { LogicRow } from "./M01_MasterData_UI_Logic_Api"; import { safeReason, tx } from "./M01_MasterData_UI_Logic_Text"; import { tl } from "./M01_MasterData_UI_LogicLab_Text"; import "./M01_MasterData_UI_LogicLab_Style.css"; -import "./M01_MasterData_UI_LogicLab_Pill.css"; /** 원문 절 머리 개정 연도 글 — [2008, 2020, 2025] → 「'08 · '20 · '25」(없으면 빈 글) */ const revisionText = (row: LogicRow): string => diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts index a1854f2b7..b7b2ef09b 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Modal.ts @@ -1,32 +1,9 @@ /* ============================================================================= * M01_MasterData_UI_LogicLab_Modal.ts - * 자료 모달 둘 — - * ① 줄 모달(`openMaterialModal`) — 줄을 누르면 그 줄의 단가(재료·인력·기계 또는 다른 로직)를 - * 바로 보임(알약 목록 없이) · 그 아래 한 줄 풀이 + 원문 수량 식 - * 재료 줄 = 위 물가 넷 가로(빈 칸 「-」 · 시험 계산이 쓴 값 굵게) + 후보 목록(찾기 · `onPick` 이면 누르면 고름) - * — 상세 표 줄 · 시험 계산 자재 칸이 같은 모달(711-2) · 기계 고르기는 `Logic_PickTable` 그대로 - * ② 표 모달(`openTableModal`) — 수량 칸 안 알약(찾기(...) 표 참조)을 누르면 그 표만 보임 - * 표는 표 그대로 + 지금 넣은 값으로 걸린 줄 강조 · 단일 값(단가)은 값과 출처 - * 표 읽기 = `/elements` → `/table`(`Logic_Note.loadTable`) · 단가 = 로직 화면이 이미 받은 `prices` + * 로직 알약 → 그 로직 열기(로직 화면이 열기를 등록) · 재료 찾기 글 머리 낱말(`headWord`) + * — 옛 상세 몸 재료 · 표 모달은 855 2-E1 에 걷음(부르는 곳 0) * ========================================================================== */ -import { createButton, createInputField, el } from "@ui/ui_template_elements"; -import { openModal } from "@ui/ui_template_modal"; -import { - fetchMaterials, - searchElements, - type ElementBrief, - type NamedFormula, -} from "./M01_MasterData_UI_Logic_Api"; -import { fetchRows, type Row } from "./M01_MasterData_Api_Fetch"; -import { createStat, statGrid } from "@ui/ui_template_stat"; -import { formatMoney, formatNumber, formatPrice } from "../common_util/common_util_money"; -import { explain, loadTable, type TableRow } from "./M01_MasterData_UI_Logic_Note"; -import { hasMasterJump, jumpToMaster, type MasterJump } from "./M01_MasterData_UI_Side"; -import { fragmentRow, type Fragment } from "./M01_MasterData_UI_LogicLab_Pill"; -import { tl } from "./M01_MasterData_UI_LogicLab_Text"; -import { createText } from "@ui/ui_template_text"; - /** 로직 알약 → 그 로직 열기 — 로직 화면이 자기 열기를 등록 · 열려 있는 모달은 다 닫음 */ let logicOpener: (key: string) => void = () => {}; export const setLogicOpener = (fn: (key: string) => void): void => { @@ -37,538 +14,9 @@ export function openLogic(key: string): void { logicOpener(key); } -/** 재료 고르기 조건(호표 줄 `요소` 가 글 대신 객체일 때) — 서버 `master_material.PICK_KEYS` 와 같은 칸 */ -export interface PickCond { - 구분?: string; - 상세구분?: string; - 이름?: string; - 규격?: string; - 대표?: string; - [extra: string]: unknown; -} - -/** 서버가 `prices` 열쇠로 쓰는 조건 글 — 「구분|상세구분|이름|규격|대표|지역|계약종별」 */ -export const condText = (cond: PickCond): string => - ["구분", "상세구분", "이름", "규격", "대표", "지역", "계약종별"] - .map((k) => String(cond[k] ?? "")) - .join("|") + (cond["검색어"] ? `|${cond["검색어"]}` : ""); - /** 재료 모달 검색 칸 글 — 검색어 첫 낱말의 괄호 앞(「합판(내수) 12t」 → 「합판」) */ export const headWord = (text: unknown): string => String(text ?? "") .trim() .split(/\s+/)[0] .replace(/[((].*$/, ""); - -/** 고르기 줄 후보 찾기 글 — 검색어 → 이름 → 상세구분 → 구분 차례 첫 낱말 */ -export const seedOf = (cond: PickCond): string => - [cond["검색어"], cond.이름, cond.상세구분, cond.구분].map(headWord).find(Boolean) ?? ""; - -export interface ModalTarget { - title: string; - /** 수량 식(호표 줄) · 덧줄은 그 식 */ - expr: string; - /** 호표 줄의 단가 요소 키 — 덧줄은 없음 */ - element?: string; - /** 재료 고르기 줄 — `element` 대신 조건 객체 · 잡힌 품목 단가 + 후보 목록을 보임 */ - cond?: PickCond; - /** 호표 줄 단위 — 후보를 같은 단위 줄로만 거름 */ - unit?: string; - prices: Record; - middles: NamedFormula[]; - /** 시험 계산 칸에 넣은 값 — 걸린 줄을 맞히는 데 씀 */ - values: Record; - /** 서버 `요소조각` — 단가 자리(요소 · 로직 부르기)를 조각으로 · 없으면 로직 키만 알약으로 */ - unitFrag?: Fragment[]; - /** 서버가 입력으로 푼 단가 요소 키 · 글 — 자리 표시(`{…}`) 든 줄이 씀 */ - unitRef?: string; - unitText?: string; - /** 서버 수량 조각 — 한 줄 풀이를 조각으로(알약 포함) · 없으면 식 풀이 글 */ - qtyFrag?: Fragment[]; - /** 호표 줄 종류 — 「재료」면 후보 목록(고르기 조건 줄이 아니어도) */ - kind?: string; - /** 시험 계산이 쓴 값 칸(계산 답 `품목.값칸`) — 위 물가 넷 가운데 굵게 */ - usedSlot?: string; - /** 있으면 후보 줄을 눌러 고름(시험 입력 · 저장 안 함) — 고르면 모달 닫힘 */ - onPick?: (item: { ref: string; label: string }) => void; - /** 722-2 그 자리 고침 칸(맨 위) — 받는 것 = 모달 닫기 · 머리 단추 자리(닫기 왼쪽 · 748-1) */ - edit?: (close: () => void, head: HTMLElement) => HTMLElement; -} - -/** 수량 칸 표 알약 하나가 여는 자료 — 서버 조각 `참조`(키 · 행 · 열)가 곧 찾은 자리 */ -export interface TableTarget { - title: string; - table: string; - /** 찾은 줄 — 찾기 조건(예 {구분: 합판}) · 줄의 키·원문번호 글 · 줄 차례(0부터) */ - row?: Record | string | number | null; - /** 찾은 값 칸 이름 */ - col?: string | null; -} - -const sameCond = (have: unknown, want: unknown, range: boolean): boolean => { - if (range && Array.isArray(have)) { - const n = Number(want); - const [low, high] = have as (number | null)[]; - return (low == null || n >= low) && (high == null || n <= high); - } - return String(have) === String(want); -}; - -function tableView(table: TableRow, target: TableTarget): HTMLElement { - const lines = table.줄 ?? []; - const at = target.row; - const kinds = table.조건 ?? {}; - const hit = - at === undefined || at === null - ? null - : typeof at === "number" - ? (lines[at] ?? null) - : typeof at === "string" - ? (lines.find((line) => line["키"] === at || line["원문번호"] === at) ?? null) - : (lines.find((line) => - Object.entries(at).every(([c, want]) => sameCond(line[c], want, kinds[c] === "범위")), - ) ?? null); - const cols = [...Object.keys(table.조건 ?? {}), ...Object.keys(table.값칸 ?? {})]; - const rows = lines.map((line) => - el("tr", { - className: hit === line ? "m01lab__hit" : "", - attrs: hit === line ? { "data-hit": "1" } : {}, - children: cols.map((c) => - el("td", { - // 찾은 줄을 알면 그 줄의 칸만 · 줄을 못 받았으면(표 줄에 키가 없는 표) 값 칸 세로줄만 색 - className: c === target.col && (hit === line || !hit) ? "m01lab__hit-cell" : "", - text: formatNumber(line[c]), - }), - ), - }), - ); - const use = table.용도 - ? [table.용도.공종, (table.용도.대상 ?? []).join("·")].filter(Boolean).join(" · ") - : ""; - return el("div", { - className: "m01lab__data", - attrs: { "data-table": table.키 }, - children: [ - el("strong", { text: `${table.원문번호 ?? ""} ${table.이름 ?? table.키} · ${table.키}` }), - el("p", { - className: "ui-text ui-text--muted", - text: [`${tl("Modal_Source")} ${table.출처 ?? ""}`, use].filter(Boolean).join(" · "), - }), - el("p", { - className: "ui-text ui-text--muted", - text: hit ? tl("Modal_Hit") : target.col ? tl("Modal_ColOnly") : tl("Modal_NoHit"), - }), - goButton({ kind: "table", key: table.키 }), - el("div", { - className: "m01-logic__scroll", - children: [ - el("table", { - className: "ui-table ui-table--data m01-logic__grid m01lab__table", - children: [ - el("thead", { - children: [el("tr", { children: cols.map((c) => el("th", { text: c })) })], - }), - el("tbody", { children: rows }), - ], - }), - ], - }), - ], - }); -} - -const groupOf = (ref: string): string => - ref.startsWith("LB") ? "인력" : ref.startsWith("M") ? "재료" : ref.startsWith("EQ") ? "기계" : ""; - -function goButton(target: MasterJump): HTMLElement { - const go = createButton({ - label: tl("Pill_Go"), - variant: "ghost", - onClick: () => jumpToMaster(target), - }); - go.hidden = !hasMasterJump(); - return go; -} - -/** 자재품목 사급 값 칸 다섯 — 위 가로 줄(조달청은 뺌 · 830-2) */ -const SLOTS = ["물가자료", "유통물가", "물가정보", "거래가격", "일반가격"]; -const MARKET_FILE = "재료_자재품목.json"; -const marketRows = new Map>(); -/** 자재품목 줄 하나(값 칸 넷) — 키로 찾음 · 한 번만 물음 */ -const marketRow = (ref: string): Promise => { - if (!marketRows.has(ref)) - marketRows.set( - ref, - fetchRows(MARKET_FILE, 1, 5, ref) - .then((got) => got.rows.find((r) => r["키"] === ref) ?? null) - .catch(() => null), - ); - return marketRows.get(ref)!; -}; - -/** 자재품목 줄 단가 — 이름 · 키 · 규격 + 물가 넷 가로(빈 칸 「-」 · 시험 계산이 쓴 값 굵게 · 모르면 낮은 값) */ -function marketView( - ref: string, - brief: ElementBrief | null, - usedSlot?: string, - onValue?: (value: unknown) => void, -): HTMLElement { - const head = el("strong"); - const spec = el("p", { className: "ui-text ui-text--muted" }); - const slots = el("div"); - const paint = (name: unknown, size: unknown, values: Record): void => { - head.textContent = `${String(name ?? ref)} · ${ref}`; - spec.textContent = size ? `${tl("Modal_Spec")} ${String(size)}` : ""; - spec.hidden = !size; - const nums = SLOTS.map((s) => values[s]).filter((v): v is number => typeof v === "number"); - const used = SLOTS.includes(usedSlot ?? "") - ? usedSlot - : SLOTS.find((s) => nums.length && values[s] === Math.min(...nums)); - slots.replaceChildren( - statGrid( - SLOTS.map((s) => { - const card = createStat({ - label: s, - value: values[s] === null || values[s] === undefined ? "-" : formatPrice(values[s]), - compact: true, - }); - card.classList.toggle("is-used", s === used); - return card; - }), - ), - ); - if (used) onValue?.(values[used]); - }; - paint(brief?.이름, brief?.규격, brief?.값들 ?? {}); - if (!brief?.값들) void marketRow(ref).then((row) => row && paint(row["이름"], row["규격"], row)); - return el("div", { - className: "m01lab__data m01lab__slots", - attrs: { "data-price": ref }, - children: [ - head, - spec, - slots, - goButton({ kind: "element", group: "재료", ref, file: brief?.file ?? MARKET_FILE }), - ], - }); -} - -function priceView(ref: string, brief: ElementBrief, usedSlot?: string): HTMLElement { - if (ref.startsWith("MT")) return marketView(ref, brief, usedSlot); - const cols = Object.entries(brief.값칸 ?? {}); - const slots = Object.entries(brief.값들 ?? {}).filter(([, v]) => v !== null && v !== undefined); - return el("div", { - className: "m01lab__data", - attrs: { "data-price": ref }, - children: [ - el("strong", { text: `${brief.이름 ?? ref} · ${ref}` }), - el("dl", { - className: "m01-logic__sums", - children: [ - ...(brief.규격 - ? [el("dt", { text: tl("Modal_Spec") }), el("dd", { text: brief.규격 })] - : []), - el("dt", { text: tl("Modal_Value") }), - el("dd", { className: "m01-logic__money", text: formatPrice(brief.값) }), - ...(brief.file - ? [el("dt", { text: tl("Modal_Source") }), el("dd", { text: brief.file })] - : []), - ...cols.flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: String(v) })]), - ...slots.flatMap(([k, v]) => [ - el("dt", { text: k }), - el("dd", { className: "m01-logic__money", text: formatMoney(v) }), - ]), - ], - }), - goButton({ kind: "element", group: groupOf(ref), ref: brief.ref ?? ref, file: brief.file }), - ], - }); -} - -/** 모달 겉틀(배경·닫기·포커스) — 몸은 `mount` 이 채움(닫기 함수도 받음) */ -function openDialog( - title: string, - mount: (body: HTMLElement, close: () => void, head: HTMLElement) => void, -): void { - openModal({ - title, - closeLabel: tl("Modal_Close"), - mount, - dialogClass: "m01-logic__pick m01lab__modal", - backdropClass: "m01-logic__backdrop", - }); -} - -const muted = (text: string): HTMLElement => el("p", { className: "ui-text ui-text--muted", text }); - -const free = (v: unknown): string => { - const text = String(v ?? ""); - return text.includes("{") ? "" : text; // `{입력}` 자리는 계산 때 정해짐 — 거름에 안 씀 -}; -const squash = (v: unknown): string => - String(v ?? "") - .replace(/\s+/g, "") - .toLowerCase(); - -/** 재료 줄 후보 목록 — 고르기 조건 안 후보(`/materials` · 단위 거름) · 조건이 없으면 이름 찾기 · - * 찾기 칸 = 받은 후보 안에서 거름(없으면 재료 전체 이름 찾기) · 잡힌 품목(`pickedRef`) 노란 줄 맨 위 · - * `onPick` 이면 줄을 누르면 고름 · 값은 위 가로 칸이 보여 목록엔 값 열 없음 */ -function candidateView(target: ModalTarget, pickedRef: string, close: () => void): HTMLElement { - const cond = target.cond; - const sub = free(cond?.구분); - const list = el("div"); - const count = el("strong"); - const field = createInputField({ type: "search", placeholder: tl("Modal_Find") }); - const box = el("div", { - className: "m01lab__data", - attrs: { "data-candidates": "1" }, - children: [count, field.root, list], - }); - list.append(muted("…")); - let base: ElementBrief[] = []; - const draw = (items: ElementBrief[], total: number): void => { - const sorted = [ - ...items.filter((it) => it.ref === pickedRef), - ...items.filter((it) => it.ref !== pickedRef), - ]; - const more = total > items.length ? ` (${items.length})` : ""; - count.textContent = `${tl(target.onPick ? "Modal_PickList" : "Modal_Candidates")} ${total}${more}`; - const rows = sorted.map((it) => { - const hit = it.ref === pickedRef; - const tr = el("tr", { - className: `${hit ? "m01lab__hit" : ""}${target.onPick ? " m01lab__pickrow" : ""}`, - attrs: { ...(hit ? { "data-hit": "1" } : {}), "data-ref": it.ref }, - children: [ - el("td", { text: it.이름 ?? it.ref }), - el("td", { text: it.규격 ?? "" }), - el("td", { text: String(it.단위 ?? "") }), - ], - }); - const onPick = target.onPick; - if (onPick) - tr.addEventListener("click", () => { - close(); - onPick({ ref: it.ref, label: `${it.이름 ?? ""} ${it.규격 ?? ""}`.trim() || it.ref }); - }); - return tr; - }); - list.replaceChildren( - rows.length - ? el("div", { - className: "m01-logic__scroll m01lab__cands", - children: [ - el("table", { - className: "ui-table ui-table--data m01-logic__grid m01lab__table", - children: [ - el("thead", { - children: [ - el("tr", { - children: [tl("Col_Name"), tl("Modal_Spec"), tl("Col_Unit")].map((h) => - el("th", { text: h }), - ), - }), - ], - }), - el("tbody", { children: rows }), - ], - }), - ], - }) - : muted(tl("Pill_NoPick")), - ); - }; - // 조건 없는 재료 줄 = 그 요소 이름 첫 낱말로 찾음(「모르타르, 서울 1:1」 → 「모르타르」) - const known = target.element ? target.prices[target.element] : null; - const seed = cond ? seedOf(cond) : headWord(known?.이름 ?? target.title).replace(/[,,].*$/, ""); - const first = sub - ? fetchMaterials({ - sub, - detail: free(cond?.상세구분), - spec: free(cond?.규격), - unit: target.unit ?? "", - }) - : searchElements("재료", seed); - let total = 0; - let timer = 0; - let seq = 0; - /** 찾기 칸 글로 거름 — 받은 후보 안에서 · 하나도 없으면 재료 전체 이름 찾기 */ - const apply = (): void => { - const mine = ++seq; - const q = field.input.value.trim(); - const words = q.split(/\s+/).map(squash).filter(Boolean); - if (!words.length) return draw(base, total); - const hits = base.filter((it) => - words.every((w) => squash(`${it.이름 ?? ""} ${it.규격 ?? ""} ${it.ref}`).includes(w)), - ); - if (hits.length) return draw(hits, hits.length); - void searchElements("재료", q) - .then((got) => mine === seq && draw(got.items, got.total)) - .catch(() => undefined); - }; - void first - .then((got) => { - base = got.items; - total = got.total; - field.input.value = sub ? free(cond?.["검색어"]) : ""; // 엔진이 고르는 검색어로 먼저 거름 · 지우면 조건 안 전부 - apply(); - }) - .catch(() => list.replaceChildren(muted(tl("Pill_NoPick")))); - field.input.addEventListener("input", () => { - window.clearTimeout(timer); - timer = window.setTimeout(apply, 300); - }); - return box; -} - -/** 고르기 줄에서 시험 계산이 잡은 품목 키 — 대표가 `{입력이름}` 이면 넣은 값 · 글자 키면 그대로 · 없으면 서버 미리보기 줄 */ -function pickedOf(cond: PickCond, values: Record, fallback: string): string { - const rep = String(cond["대표"] ?? ""); - const named = /^\{(.+)\}$/.exec(rep); - return (named ? (values[named[1]] ?? "") : rep) || fallback; -} - -/** 줄을 눌렀을 때 — 그 줄의 단가(재료·인력·기계 또는 다른 로직)를 바로 보임(알약 없이) · - * 재료 고르기 줄(`cond`)은 잡힌 품목 단가 + 후보 목록 */ -export function openMaterialModal(target: ModalTarget): void { - openDialog(target.title, (body, close, head) => { - const cond = target.cond; - const element = target.element ?? ""; - const base = element.split(".")[0]; - // 고르기 줄 = 서버가 조건 글을 열쇠로 준 줄(대표가 안 정해졌으면 없음) - const priced = cond ? target.prices[condText(cond)] : undefined; - const known = cond - ? target.unitRef && priced?.ref !== target.unitRef - ? undefined // 서버가 잡은 품목이 다르면 그 품목으로 - : priced - : element - ? (target.prices[element] ?? target.prices[base]) - : undefined; - const priceRef = cond - ? target.unitRef || pickedOf(cond, target.values, known?.ref ?? "") - : element; - const logicKey = /^로직\((\w+)/.exec(element)?.[1] ?? ""; - // 748-1 연결 키 = 제목 오른쪽 (괄호) · 고침 칸이 있으면 요소 단가 정보 칸은 없음(키 · 값은 제목 · 단가 칸에) - const key = logicKey || (cond ? priceRef : element.includes("{") ? target.unitRef : base); - if (key) - body - .closest(".ui-modal") - ?.querySelector("h3") - ?.append(el("span", { className: "m01lab__modalkey", text: ` (${key})` })); - const info = (ref: string, brief: ElementBrief, slot?: string): HTMLElement => - target.edit && !ref.startsWith("MT") ? el("span") : priceView(ref, brief, slot); - const sum = el("p", { className: "m01lab__sum" }); - const setSum = (price: ElementBrief | null | undefined): void => { - const unit = price ? `${tl("Modal_UnitPrice")} ${formatPrice(price.값)} × ` : ""; - if (target.qtyFrag) { - sum.replaceChildren(`${target.title} = ${unit}`, fragmentRow(target.qtyFrag)); - } else sum.textContent = `${target.title} = ${unit}${explain(target.expr)}`; - }; - setSum(known); - const rate = el("div", { className: "m01lab__modal-body" }); - /** `prices` 에 있으면 그대로 · 없으면 키로 찾아 옴 — 못 찾으면 「관리자 값 미확정」 */ - const lookup = (ref: string, label: string): void => { - const show = (brief: ElementBrief | null): void => { - rate.replaceChildren(brief ? info(ref, brief) : muted(`${label} — ${tl("Pill_NoValue")}`)); - setSum(brief); - }; - rate.append(muted("…")); - const cached = target.prices[ref]; - if (cached) show(cached); - else - void searchElements(groupOf(ref), ref) - .then((got) => show(got.items.find((it) => it.ref === ref) ?? null)) - .catch(() => show(null)); - }; - if (known && priceRef) { - rate.append(info(priceRef, known, target.usedSlot)); - } else if (logicKey) { - rate.append( - el("p", { - children: [ - `${tl("Modal_Logic")} · `, - fragmentRow( - target.unitFrag ?? [ - { pill: { label: logicKey, onClick: () => openLogic(logicKey) } }, - ], - ), - ], - }), - ); - } else if (cond && priceRef) { - // 서버가 잡은 품목 · 고른 품목 — 자재품목 줄을 키로 읽어 물가 넷 - rate.append( - marketView(priceRef, null, target.usedSlot, (value) => - setSum({ ref: priceRef, 값: value } as ElementBrief), - ), - ); - } else if (cond) { - rate.append(muted(tl("Pill_NoPick"))); - } else if (element.includes("{")) { - // 자리 표시 든 요소 — 날글 대신 서버가 푼 키로 단가 · 못 풀면 입력 이름만 - const ref = target.unitRef; - if (!ref) { - const names = [...element.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]).join(" · "); - rate.append(muted(`${target.unitText || names} — ${tl("Pill_Unresolved")}`)); - } else lookup(ref, target.unitText ?? ref); - } else if (element) { - lookup(element, element); // 더한 줄(M02) 등 `prices` 에 없는 요소 — 키로 찾아 옴(725-4) - } - body.replaceChildren( - ...(target.edit ? [target.edit(close, head)] : []), - rate, - ...(cond || target.kind === "재료" ? [candidateView(target, priceRef, close)] : []), - muted(tl("Modal_Sum")), - sum, - el("details", { - className: "m01lab__raw", - children: [ - el("summary", { text: tl("Modal_Qty") }), - el("pre", { - className: "m01lab__expr", - text: logicKey - ? `${element} -${target.expr}` - : target.expr, - }), - ], - }), - ); - }); -} - -/** 수량 칸 요소 알약을 눌렀을 때 — 그 요소의 단가 자료(이미 받은 `prices` 에 없으면 키로 찾아 옴) */ -export function openRefModal(target: { - title: string; - ref: string; - prices: Record; -}): void { - openDialog(target.title, (body) => { - const show = (brief: ElementBrief | null): void => - body.replaceChildren( - brief ? priceView(target.ref, brief) : muted(`${target.ref} — ${tl("Pill_NoValue")}`), - ); - const known = target.prices[target.ref]; - if (known) return show(known); - body.replaceChildren(muted("…")); - void searchElements(groupOf(target.ref), target.ref) - .then((got) => show(got.items.find((it) => it.ref === target.ref) ?? null)) - .catch(() => show(null)); - }); -} - -/** 알약이 가리킬 자료를 못 찾을 때(참조 없음) · 다른 로직을 부르는 알약 — 한 마디만 */ -export function openNoteModal(title: string, text: string): void { - openDialog(title, (body) => body.replaceChildren(el("p", { text }))); -} - -/** 수량 칸 표 알약을 눌렀을 때 — 그 표만 보임(걸린 줄 강조) */ -export function openTableModal(target: TableTarget): void { - openDialog(target.title, (body) => { - body.replaceChildren(el("p", { className: "ui-text ui-text--muted", text: "…" })); - void loadTable(target.table).then((table) => { - body.replaceChildren( - table ? tableView(table, target) : createText(`${target.table} ?`, "error"), - ); - }); - }); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css deleted file mode 100644 index b919e6967..000000000 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.css +++ /dev/null @@ -1,16 +0,0 @@ -/* 알약 = 단추 부품(보조 · 24) · 여기는 칸 폭 넘침만 */ -.m01lab__pill { - max-width: 100%; - overflow-wrap: anywhere; -} - -/* 계산 안 된 만약() 가지 조각 — 흐리게 */ -.m01lab__qty-dim { - opacity: 0.45; -} - -/* 표 모달 — 찾은 칸(참조.열) 한 번 더 진하게 */ -td.m01lab__hit-cell, -.m01lab__hit td.m01lab__hit-cell { - background: color-mix(in srgb, orange 65%, transparent); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts deleted file mode 100644 index 334421ba3..000000000 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Pill.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* ============================================================================= - * M01_MasterData_UI_LogicLab_Pill.ts - * 알약 단추 — 수량 칸 안 조각(표 찾기 등)을 누르면 곧장 그 자료 모달을 엶. - * (이전에는 알약을 늘어놓고 아래 자리에서 펼쳤으나, 알약이 수량 칸 안으로 들어가며 - * 「누르면 모달」 로 바뀜 — 모달 안에 알약 목록을 또 두지 않음.) - * ========================================================================== */ - -import { el } from "@ui/ui_template_elements"; -import { createButton } from "@ui/ui_template_button"; -import { tl } from "./M01_MasterData_UI_LogicLab_Text"; - -export interface Pill { - /** 알약 글 — 보기 「표 QF000421」 */ - label: string; - /** 누르면 할 일 — 그 자료 모달을 엶 */ - onClick: () => void; -} - -/** 알약 하나 — 글자 조각 사이에 끼워 쓰는 단추 */ -export function pillButton(p: Pill): HTMLButtonElement { - // 알약 = 요소 연결 단추(보조 · 낮은 20 · 정보색 갈래) — data-pill 은 시험 · 촬영이 잡음 - const b = createButton({ label: p.label, variant: "ghost", size: 20, tone: "link" }); - b.title = tl("Pill_Tone"); - b.classList.add("m01lab__pill"); - b.dataset.pill = p.label; - b.addEventListener("click", (ev) => { - ev.stopPropagation(); // 줄 전체 누르기(행 모달)와 안 겹치게 - p.onClick(); - }); - return b; -} - -/** 수량 칸 조각 — 알약 아니면 그냥 글자(연산기호·숫자·중간값 이름) · `dim` = 계산 안 된 갈래(흐리게) */ -export type Fragment = { pill: Pill; dim?: boolean } | { text: string; dim?: boolean }; - -/** 조각을 이어 그림 — 칸 폭을 넘으면 자동으로 줄바꿈(`flex-wrap`) */ -export function fragmentRow(fragments: Fragment[]): HTMLElement { - return el("span", { - className: "m01lab__qty-frags", - children: fragments.map((f) => { - const one = - "pill" in f - ? pillButton(f.pill) - : el("span", { className: "m01lab__qty-text", text: f.text }); - if (f.dim) one.classList.add("m01lab__qty-dim"); - return one; - }), - }); -} diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css index 90ee00aa9..db6274746 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Style.css @@ -42,42 +42,10 @@ word-break: break-all; } -.m01lab__qty-frags { - display: inline-flex; - flex-wrap: wrap; - align-items: baseline; - gap: 2px 4px; - min-width: 0; -} - -.m01lab__qty-text { - font-family: var(--font-mono, monospace); - font-size: var(--text-body-sm); - white-space: pre-wrap; -} - .m01lab__modal { overflow: auto; } -/* 748-1 모달 제목 오른쪽 연결 키 — 제목보다 가볍게 */ -.m01lab__modalkey { - font-size: var(--text-body); - font-weight: var(--font-weight-regular, 400); - color: var(--color-text-secondary); -} - -.m01lab__modal-body { - display: flex; - flex-direction: column; - gap: var(--spacing-8); -} - -.m01lab__hit td { - background: color-mix(in srgb, gold 45%, transparent); - font-weight: 600; -} - .m01lab__calc > h3 { display: none; } diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts index 3176231c2..d6002eea5 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Text.ts @@ -26,40 +26,7 @@ const TEXT = { Col_Name: ["이름", "Name"], Col_Unit: ["단위", "Unit"], Modal_Close: ["닫기", "Close"], - Pill_Tone: ["요소 연결", "Linked element"], - Modal_Sum: ["한 줄 풀이", "In one line"], - Modal_UnitPrice: ["단가", "Unit price"], - Pill_Go: ["마스터 화면에서 보기", "Open in master"], Pill_Back: ["← 단가산출 기초로 돌아가기", "← Back to unit-price logic"], - Pill_NoPick: [ - "고르기 조건에 맞는 마스터 줄이 없음 — 단가를 못 찾음", - "No master row matches the pick conditions", - ], - Pill_Unresolved: ["입력이 비어 풀리지 않음", "Not resolved — input empty"], - Pill_NoValue: ["관리자 값 미확보 — 마스터에 단가가 없음", "No price in master yet"], - Modal_Qty: ["수량 식", "Quantity formula"], - Modal_Value: ["값", "Value"], - Modal_Source: ["출처", "Source"], - Modal_Spec: ["규격", "Spec"], - Modal_Candidates: [ - "후보 목록 (노란 줄 = 시험 계산이 쓰는 품목)", - "Candidates (yellow = used in the trial)", - ], - Modal_PickList: [ - "후보 목록 — 줄을 누르면 그 품목으로 시험 계산 (노란 줄 = 지금 쓰는 품목)", - "Candidates — click a row to use it in the trial (yellow = in use)", - ], - Modal_Find: ["이름 · 규격으로 찾기", "Search by name or spec"], - Modal_Logic: ["다른 로직을 부름", "Calls another logic"], - Modal_Hit: ["노란 줄 = 지금 넣은 값으로 걸린 줄", "Highlighted row matches the trial values"], - Modal_ColOnly: [ - "진한 칸 = 찾은 값 칸 — 서버가 줄 자리는 안 줌", - "Dark cells = the value column found; the server gave no row", - ], - Modal_NoHit: [ - "지금 값으로는 걸린 줄이 없음 — 값을 바꿔 보거나, 이 표를 안 쓰는 갈래일 수 있음", - "No row matches the current values — change them, or this table is on an unused branch", - ], Copy_Open: ["로직 복사/생성", "Copy / create logic"], Copy_NeedOpen: ["먼저 로직을 고르세요", "Pick a logic first"], Copy_Title: ["복사해서 만들기", "Copy to edit"], diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Api.ts b/M01_MasterData/M01_MasterData_UI_Logic_Api.ts index 8667386d1..8685767a5 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Api.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Api.ts @@ -123,66 +123,6 @@ export const pctView = ( x.율 == null ? { name: x.이름, qty: x.수량, unit: x.단위 } : { name: x.규격 ? `${x.이름} (${x.규격})` : x.이름, qty: x.율, unit: "%" }; -export type CalcAnswer = - | { - ok: true; - lines?: CalcLine[]; - sums?: Record; - result?: unknown; - middle: Record; - } - | { ok: false; reason: string }; - -/** `/text` 줄의 조각 — 알약 글 = 조각 글 · `깊이` 있으면 계산 안 된 만약() 가지(흐리게) */ -export interface TextPiece { - kind: "요소" | "표" | "로직" | "값" | "기호" | "글"; - 글: string; - /** 이름 조각(`kind: "값"` · 글 = 이름)이 가진 그 값 — 714-3 입력 단추 */ - 값?: string | number; - 참조?: { - 테이블?: string; - 키: string; - 행?: string | number | null; - 줄?: number; - 열?: string | null; - }; - 깊이?: number; -} -export interface TextLine { - 이름: string; - 글: string; - /** 같은 줄을 변수 이름으로 적은 식 — 왼쪽 칸 */ - 이름글?: string; - /** 수량 식을 쪼갠 조각 — 알약(요소·표·로직) · 글자(값·기호·글) */ - 조각?: TextPiece[]; - /** 단가 자리(요소 · 로직 부르기)를 쪼갠 조각 — 줄 모달 윗줄 */ - 요소조각?: TextPiece[]; - /** 줄 번호(답 전체에서 하나씩) — 두 칸 줄 맞춤 · 밝히기 */ - 짝?: number; - 금액: number; - 까닭?: string; - /** 714-1 계산서 줄 덧칸 — 쓰는 로직 입력 · 묶음(인력 · 재료 · 경비 · 하위) · 장비 · 찾는 표 기준 · 환산 근거 */ - 쓰는입력?: string[]; - 묶음?: string | null; - 장비?: boolean | null; - 기준단위?: string | null; - 환산근거?: string; - /** (M02 750-1) SK 셈 답 줄 cid — 상세 줄과 이음 */ - cid?: string; - /** (753-1) 옵션으로 빠진 줄(수량 0 이 만약 갈래 탓) — 화면은 그 줄을 안 그림(금액 · 차례 그대로) */ - 옵션꺼짐?: boolean; -} -/** `POST /text` 답 — 서버가 만든 읽는 식 줄(화면은 그대로 찍음) */ -export type TextAnswer = - | { - ok: true; - groups: { 비목: string; 줄: TextLine[]; 소계: number; 끝수: string }[]; - 계: number; - /** (M02 750-1) 단위 환산 배 ≠ 1 — 식은 바탕 단위 · 금액 · 소계 · 계는 ÷배 */ - 나눔?: number; - } - | { ok: false; reason: string }; - export interface SubBrief { name: string; book: string | null; @@ -268,9 +208,6 @@ export const searchElements = ( ): Promise<{ total: number; items: ElementBrief[] }> => request(`/elements?${query({ group, q, limit: "100" })}`, undefined, paths.read); -export const searchPrice = (q: string): Promise<{ total: number; items: ElementBrief[] }> => - request(`/pick?${query({ kind: "price", q, limit: "100" })}`, undefined, paths.read); - export const fetchMaterials = (cond: { sub: string; detail?: string; @@ -281,30 +218,6 @@ export const fetchMaterials = (cond: { }): Promise<{ total: number; 기본: string | null; items: ElementBrief[] }> => request(`/materials?${query({ ...cond, limit: "100" })}`, undefined, paths.read); -/** 자동값 길(`GET /logic/auto`) — 입력 이름 → 견본값 · 서버에 아직 없거나 값이 없으면 빈 채로(화면은 그냥 안 채움) */ -export const fetchAuto = (key: string): Promise> => - request<{ 값?: Record }>(`/logic/auto?${query({ key })}`, undefined, paths.read) - .then((d) => d.값 ?? {}) - .catch(() => ({})); - -export const runCalc = (body: { - key: string; - inputs: Record; - row?: LogicRow; - file?: string; - /** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */ - 고름?: Record; -}): Promise => request("/calc", body, paths.calc); - -export const runText = (body: { - key: string; - inputs: Record; - row?: LogicRow; - file?: string; - /** 시험 계산에서 고른 재료 — 호표 줄 차례 → 자재품목 키 · 저장 안 함 */ - 고름?: Record; -}): Promise => request("/text", body, paths.calc); - export const saveFiles = ( files: SaveFile[], 개정확인 = false, diff --git a/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts b/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts deleted file mode 100644 index 6220b6291..000000000 --- a/M01_MasterData/M01_MasterData_UI_Logic_CalcPick.ts +++ /dev/null @@ -1,191 +0,0 @@ -/* ============================================================================= - * M01_MasterData_UI_Logic_CalcPick.ts - * 시험 계산의 재료 · 기계 고르기 — 재료 칸마다 잡힌 품목 이름(누르면 고르기) · 기계 입력은 단추 하나 - * 재료 = 상세 표 줄과 같은 재료 모달(`openMaterialModal` · 711-2) · 기계 = 마스터 표 모달(`PickTable`) - * 고른 재료는 `고름`(호표 줄 차례 → 키)에 실어 다시 계산 · 저장 안 함 - * ========================================================================== */ - -import { createButton, el } from "@ui/ui_template_elements"; -import { fetchRows, type Row } from "./M01_MasterData_Api_Fetch"; -import type { CalcLine, ElementBrief, LogicInput, LogicRow } from "./M01_MasterData_UI_Logic_Api"; -import { openPickTable } from "./M01_MasterData_UI_Logic_PickTable"; -import { tx } from "./M01_MasterData_UI_Logic_Text"; -import { condText, openMaterialModal, type PickCond } from "./M01_MasterData_UI_LogicLab_Modal"; - -interface Chosen { - ref: string; - label: string; -} - -/** 로직마다 넣은 값(`values`)에 딸린 고른 재료 — 다시 그려도 남고 서버에는 계산 요청에만 실림 */ -const chosen = new WeakMap, Map>(); -const picksOf = (values: Record): Map => { - let mine = chosen.get(values); - if (!mine) chosen.set(values, (mine = new Map())); - return mine; -}; - -/** 재료 고름(시험 입력 · 저장 안 함) — 고른 뒤 `again`(다시 셈) · 상세 표 줄 모달이 씀 */ -export function pickMaterial( - values: Record, - i: number, - it: Chosen, - again: () => void, -): void { - picksOf(values).set(i, it); - again(); -} - -/** 계산 요청 몸의 `고름` — 고른 것이 없으면 안 실음 */ -export function pickBody(values: Record): { 고름?: Record } { - const mine = picksOf(values); - return mine.size - ? { 고름: Object.fromEntries([...mine].map(([i, c]) => [String(i), c.ref])) } - : {}; -} - -const nameOf = (row: Row): string => `${row["이름"] ?? ""} ${row["규격"] ?? ""}`.trim(); - -const MATERIAL_KEYS = /^MT\d{6}$/; -const MACHINE_CODE = /^\d{4}-\d{4}$/; -const MACHINE_KEY = /^EQ\d{6}$/; - -/** 재료 키 목록 입력 — 표 모달로 바뀌어 걷음 */ -export const isMaterialKeyInput = (spec: LogicInput): boolean => - !!spec.고르기?.length && spec.고르기.every((o) => MATERIAL_KEYS.test(String(o))); - -const isMachineInput = (spec: LogicInput): boolean => - !!spec.고르기?.length && - spec.고르기.every((o) => MACHINE_CODE.test(String(o)) || MACHINE_KEY.test(String(o))); - -const pickButton = (label: string, onClick: () => void): HTMLButtonElement => - createButton({ label, variant: "ghost", onClick }); - -/** 자재 칸 — 이름 + 잡힌 품목(누르면 고르기 모달) · 긴 이름은 두 칸 */ -const line = (label: string, current: HTMLElement): HTMLElement => - el("div", { - className: `m01-logic__field${label.length > 10 ? " m01-logic__field--wide" : ""}`, - children: [el("span", { text: label }), current], - }); - -/** 재료 줄마다 한 칸 — 지금 잡힌 품목 + 품목 고르기 */ -export function materialRows( - row: LogicRow, - prices: Record, - values: Record, - again: () => void, -): HTMLElement[] { - const mine = picksOf(values); - return (row.호표 ?? []) - .map((item, i) => ({ item, i })) - .filter((x) => x.item.종류 === "재료") - .map(({ item, i }) => { - const cond = - typeof item.요소 === "object" && item.요소 !== null - ? (item.요소 as unknown as PickCond) - : null; - const brief = (cond ? prices[condText(cond)] : prices[item.요소]) ?? null; - const named = item.이름 && !/^[A-Z]{2}\d{6}/.test(item.이름) ? item.이름 : ""; - const label = named || (brief?.이름 as string | undefined) || ""; - const held = mine.get(i); - const nowName = - held?.label ?? (brief ? `${brief.이름 ?? ""} ${brief.규격 ?? ""}`.trim() : "") ?? ""; - // 잡힌 품목 이름 = 링크 단추 — 누르면 고르기 모달([품목 고르기] 단추 걷음) - const current = createButton({ - label: nowName || tx("Mat_NoPrice"), - variant: "link", - onClick: () => pick(), - }); - current.dataset.matIdx = String(i); - current.dataset.ref = brief?.ref ?? ""; - current.title = tx("Pick_Item"); - const title = `${label}${item.규격 ? ` ${item.규격}` : ""}`; - const pick = (): void => - openMaterialModal({ - title, - expr: item.수량, - ...(cond ? { cond } : { element: item.요소 }), - unit: item.단위, - kind: "재료", - prices, - middles: row.중간 ?? [], - values, - unitRef: mine.get(i)?.ref || current.dataset.ref || undefined, - usedSlot: current.dataset.slot || undefined, - onPick: (it) => { - mine.set(i, it); - current.textContent = it.label; - again(); - }, - }); - return line(title, current); - }); -} - -/** 계산 답의 `품목` 을 잡힌 품목 글로 — 고른 재료가 있는 줄은 그대로 */ -export function showItems( - host: HTMLElement, - values: Record, - lines: (CalcLine | undefined)[], -): void { - const mine = picksOf(values); - host.querySelectorAll("[data-mat-idx]").forEach((span) => { - const i = Number(span.dataset.matIdx); - const item = lines[i]?.품목; - span.dataset.slot = item?.값칸 ?? ""; // 시험 계산이 쓴 값 칸 — 모달 위 가로 칸 굵게 - if (!item || mine.has(i)) return; - span.dataset.ref = item.키; - span.textContent = `${item.이름 ?? ""} ${item.규격 ?? ""}`.trim() || item.키; - }); -} - -/** 기계 입력 칸 — 표 모달로 고르면 입력값(원문 분류번호 · 키 목록이면 키) */ -const machines = new Map(); -async function machineRow(code: string): Promise { - if (!machines.has(code)) { - let found: Row | null = null; - try { - const got = await fetchRows("기계.json", 1, 5, code); - found = got.rows.find((r) => r["원문번호"] === code || r["키"] === code) ?? null; - } catch { - found = null; - } - machines.set(code, found); - } - return machines.get(code) ?? null; -} - -export function machineControl( - spec: LogicInput, - values: Record, - again: () => void, -): HTMLElement | null { - if (!isMachineInput(spec)) return null; - const current = el("span", { className: "ui-text ui-text--muted" }); - const paint = (): void => { - const code = values[spec.이름] ?? ""; - const known = machines.get(code); - current.textContent = `${code ? `${code}${known ? ` · ${nameOf(known)}` : ""}` : tx("Mat_NoPrice")} `; - if (code && !machines.has(code)) void machineRow(code).then(paint); - }; - paint(); - const button = pickButton(tx("Pick_Machine"), () => { - const code = values[spec.이름] ?? ""; - const known = machines.get(code); - openPickTable({ - kind: "기계", - title: `${tx("Pick_Machine")} · ${spec.이름}`, - seed: String(known?.["이름"] ?? spec.이름), - isCurrent: (r) => !!code && (r["원문번호"] === code || r["키"] === code), - onPick: (r) => { - const useKey = MACHINE_KEY.test(String(spec.고르기?.[0])); - const value = String(useKey ? r["키"] : r["원문번호"]); - machines.set(value, r); - values[spec.이름] = value; - paint(); - again(); - }, - }); - }); - return el("div", { children: [current, button] }); -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts b/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts deleted file mode 100644 index 80d7d5255..000000000 --- a/M01_MasterData/M01_MasterData_UI_Logic_Drive.ts +++ /dev/null @@ -1,76 +0,0 @@ -/* ============================================================================= - * M01_MasterData_UI_Logic_Drive.ts - * 셈 구동(PLAN 799-2) — 화면 없이 「입력값 → 서버 셈 → 답」을 돌림. 시험 계산 칸(`Logic_Calc`)이 씀 - * `driveRun` = 한 번 셈(`/calc` + `/text`) · `autoFill` = 자동값 채움 — 로직 상세 구동은 840-1 에 걷음 - * 셈 자리 = 서버(CLAUDE.md 5 장 ③) · 화면 · sessionStorage 없음 · 고른 재료(`CalcPick`) 는 값 객체에 딸림 - * ========================================================================== */ - -import { - fetchAuto, - runCalc, - runText, - type CalcAnswer, - type CalcLine, - type LogicRow, - type TextAnswer, -} from "./M01_MasterData_UI_Logic_Api"; -import { pickBody } from "./M01_MasterData_UI_Logic_CalcPick"; - -export interface DriveContext { - /** 저장된 키 — 새 로직은 null */ - savedKey: string | null; - /** 저장 전 새 초안이면 비움 — 서버가 임시 자리에 얹어 셈 */ - file?: string; - row: LogicRow; - dirty: () => boolean; - /** 로직마다 넣은 값 — 다시 그려도 남음 */ - values: Record; - onLines?: (lines: CalcLine[] | null) => void; - /** 읽는 식 줄(`/text`)도 같이 받고 싶을 때 — 호출이 `onLines` 보다 먼저 */ - onText?: (answer: TextAnswer) => void; -} - -/** 칸에 든 값 → 엔진 입력 — 빈 칸은 안 보냄(엔진이 「입력 없음」 으로 멈춤) · 고르기는 원래 값 그대로 */ -function inputsOf(row: LogicRow, values: Record): Record { - const inputs: Record = {}; - for (const spec of row.입력 ?? []) { - const raw = (values[spec.이름] ?? "").trim(); - if (raw === "") continue; - const option = spec.고르기?.find((o) => String(o) === raw); // 글 "35" 로 보내면 「고르기 밖」 - inputs[spec.이름] = - option !== undefined ? option : Number.isNaN(Number(raw)) ? raw : Number(raw); - } - return inputs; -} - -const draftBody = (ctx: DriveContext): { row?: LogicRow; file?: string } => - ctx.dirty() || ctx.savedKey === null ? { row: ctx.row, file: ctx.file } : {}; - -/** 한 번 셈 — 답을 `onText` → `onLines` 차례로 알리고 돌려줌(`draft` = 저장 전 고침으로 셈) */ -export async function driveRun( - ctx: DriveContext, - inputs = inputsOf(ctx.row, ctx.values), -): Promise<{ answer: CalcAnswer; draft: boolean }> { - const draft = ctx.dirty() || ctx.savedKey === null; - const body = { - key: ctx.savedKey ?? ctx.row.키, - inputs, - ...pickBody(ctx.values), - ...draftBody(ctx), - }; - const answer = await runCalc(body); - if (ctx.onText) ctx.onText(await runText(body)); - ctx.onLines?.(answer.ok ? (answer.lines ?? null) : null); - return { answer, draft }; -} - -/** 자동값으로 빈 칸 채움 — 채웠으면 true */ -export async function autoFill(ctx: DriveContext): Promise { - if (ctx.savedKey === null) return false; - const auto = await fetchAuto(ctx.savedKey); - const names = (ctx.row.입력 ?? []) - .map((spec) => spec.이름) - .filter((n) => auto[n] !== undefined && auto[n] !== null && !(ctx.values[n] ?? "").trim()); - for (const n of names) ctx.values[n] = String(auto[n]); - return names.length > 0; -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Note.ts b/M01_MasterData/M01_MasterData_UI_Logic_Note.ts index 9745429ad..67f94a796 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Note.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Note.ts @@ -1,6 +1,6 @@ /* ============================================================================= * M01_MasterData_UI_Logic_Note.ts - * 원문 표 읽기(`loadTable`) · 식 쉬운 말 풀이(`explain`). + * 원문 표 읽기(`loadTable`) — 식 쉬운 말 풀이는 옛 상세 몸과 같이 걷음(855 2-E1). * * 순수 읽기 — `/elements` 로 표 파일을 찾고 `/table` 로 통째 읽음. * ========================================================================== */ @@ -54,66 +54,3 @@ export function loadTable(key: string): Promise { tableCache.set(key, job); return job; } - -/* ── 식 속 찾기(표, 조건...).칸 ──────────────────────────────────────── */ - -const FIND_RE = /찾기\(\s*([A-Za-z0-9_]+)\s*,([^)]*)\)\s*\.\s*([A-Za-z0-9_가-힣]+)/g; - -function splitConds(raw: string): [string, string][] { - return raw - .split(",") - .map((p) => p.trim()) - .filter(Boolean) - .map((p): [string, string] => { - const i = p.indexOf("="); - return i < 0 ? [p, p] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; - }); -} - -/* ── 쉬운 말 풀이 — 찾기()/만약() 을 문장으로, 안 되면 식 그대로 ─────────── */ - -function splitTop(s: string): string[] { - const out: string[] = []; - let depth = 0; - let cur = ""; - for (const ch of s) { - if (ch === "(") depth++; - if (ch === ")") depth--; - if (ch === "," && depth === 0) { - out.push(cur); - cur = ""; - } else cur += ch; - } - out.push(cur); - return out; -} - -function expandIf(expr: string): string { - const at = expr.indexOf("만약("); - if (at < 0) return expr; - let depth = 0; - let j = at + 2; // "만약(" 의 '(' 자리 - for (; j < expr.length; j++) { - if (expr[j] === "(") depth++; - else if (expr[j] === ")") { - depth--; - if (depth === 0) { - j++; - break; - } - } - } - const [cond, then, els] = splitTop(expr.slice(at + 3, j - 1)).map((p) => p.trim()); - const said = `(${expandIf(cond)} 이면 ${expandIf(then)}, 아니면 ${expandIf(els ?? "")})`; - return expandIf(expr.slice(0, at) + said + expr.slice(j)); -} - -export function explain(expr: string): string { - const withFind = expr.replace(FIND_RE, (_all, table: string, conds: string, col: string) => { - const cs = splitConds(conds) - .map(([, rhs]) => rhs) - .join(" · "); - return `[${table} 표에서 ${cs} 에 맞는 「${col}」]`; - }); - return expandIf(withFind).trim() || expr; -} diff --git a/M01_MasterData/M01_MasterData_UI_Logic_Text.ts b/M01_MasterData/M01_MasterData_UI_Logic_Text.ts index 891a22684..e5b838867 100644 --- a/M01_MasterData/M01_MasterData_UI_Logic_Text.ts +++ b/M01_MasterData/M01_MasterData_UI_Logic_Text.ts @@ -35,14 +35,8 @@ const TEXT = { Head_Owner: ["소유", "Owner"], Head_Note: ["비고", "Note"], Head_Blocked: ["막힌 까닭", "Why blocked"], - Ho_Title: ["호표", "Unit-cost lines"], - Ho_Qty: ["수량", "Qty"], - Ho_Amount: ["금액", "Amount"], - Middle_Title: ["중간 값", "Intermediate values"], Formula: ["식", "Formula"], Calc_Title: ["시험 계산", "Test calculation"], - Calc_Run: ["계산", "Calculate"], - Calc_NoInputs: ["받을 값 없음", "No inputs"], Calc_Draft: ["고친 줄로 계산(저장 전)", "Using unsaved edits"], Calc_NoDoc: [ "수식 문서로 못 바꿈 — 고친 식을 확인하세요", @@ -50,14 +44,9 @@ const TEXT = { ], Calc_Stopped: ["멈춤", "Stopped"], Calc_Result: ["결과", "Result"], - Calc_Sum: ["계", "Total"], Pick_Title: ["요소 찾기", "Find element"], Pick_Search: ["이름·키·원문번호", "Name · key · source no."], - Pick_Item: ["품목 고르기", "Pick item"], - Pick_Machine: ["기계 고르기", "Pick machine"], - Calc_UnitWarn: ["단위 다름", "Unit differs"], Pick_Close: ["닫기", "Close"], - Mat_NoPrice: ["단가 없음", "No price"], Save_Done: ["저장했음", "Saved"], Save_Stale: [ "그 사이 파일이 바뀜 — 고친 것을 버리고 다시 여세요: {v}", diff --git a/M01_MasterData/M01_MasterData_UI_Side.ts b/M01_MasterData/M01_MasterData_UI_Side.ts index 13789912e..ab5a94c1a 100644 --- a/M01_MasterData/M01_MasterData_UI_Side.ts +++ b/M01_MasterData/M01_MasterData_UI_Side.ts @@ -84,7 +84,6 @@ export const setMasterJump = (fn: (target: MasterJump) => void): void => { masterJump = fn; }; export const jumpToMaster = (target: MasterJump): void => masterJump?.(target); -export const hasMasterJump = (): boolean => masterJump !== null; // 등록 없으면(M02) 이동 단추 숨김 /** 요소 화면에서 열 것 — 파일 · 하위 거름(구분·세부분류) · 상세구분 · 제목 */ export interface Pick { diff --git a/resources/tester/helper_717_1_logic_api_paths.cjs b/resources/tester/helper_717_1_logic_api_paths.cjs index 56cb7baa9..02691f7cd 100644 --- a/resources/tester/helper_717_1_logic_api_paths.cjs +++ b/resources/tester/helper_717_1_logic_api_paths.cjs @@ -24,11 +24,8 @@ const note = load("M01_MasterData", "M01_MasterData_UI_Logic_Note.ts"); async function round(tag) { await api.fetchLogic("K"); - await api.fetchAuto("K"); await api.searchElements("재료", "q"); await api.fetchMaterials({ sub: "s" }); - await api.runCalc({ key: "K", inputs: {} }); - await api.runText({ key: "K", inputs: {} }); await rows.fetchRows("기계.json", 1, 5, "q"); await rows.fetchPick("price", "q"); await note.loadTable(`T-${tag}`); diff --git a/resources/tester/test_717_1_logic_lib.py b/resources/tester/test_717_1_logic_lib.py index 30544b017..906de3605 100644 --- a/resources/tester/test_717_1_logic_lib.py +++ b/resources/tester/test_717_1_logic_lib.py @@ -35,11 +35,7 @@ def test_길_주입_없으면_m01_있으면_넘긴_길() -> None: assert out["before"] == out["after"] # 안 넘기면 지금 그대로 assert all(u.startswith("/m01/") for u in out["before"]) shared, admin = out["injected"][:-2], out["injected"][-2:] - assert all(u.startswith(("/m02/logic-lib/", "/m02/calc-x/")) for u in shared) - assert [u for u in shared if u.startswith("/m02/calc-x/")] == [ - "/m02/calc-x/calc", - "/m02/calc-x/text", - ] + assert all(u.startswith("/m02/logic-lib/") for u in shared) assert admin == ["/m01/groups/g/files", "/m01/save"] # 관리자 · 저장 길은 늘 M01 diff --git a/resources/tester/test_734_calc_buttons.py b/resources/tester/test_734_calc_buttons.py index 4c256f656..b6ce574b2 100644 --- a/resources/tester/test_734_calc_buttons.py +++ b/resources/tester/test_734_calc_buttons.py @@ -10,19 +10,9 @@ def _t(p: Path) -> str: return p.read_text(encoding="utf-8") -def test_알약은_낮은_단과_요소연결_갈래(): - s = _t(M01 / "M01_MasterData_UI_LogicLab_Pill.ts") - assert 'size: 20, tone: "link"' in s and 'tl("Pill_Tone")' in s - - def test_갈래_색은_공통_값만(): css = _t(ROOT / "ui_template" / "ui_template_button.css") head = css[css.index("갈래 색(tone)") :] assert '[data-tone="option"]' in head and "var(--color-warning)" in head assert '[data-tone="link"]' in head and "var(--color-info)" in head assert "#" not in head.split("*/", 1)[1] # 날 색 값 없음 - - -def test_풍선_글_두_갈래(): - s = _t(M01 / "M01_MasterData_UI_LogicLab_Text.ts") - assert '"요소 연결"' in s # 799-2 — 입력 칩(옵션 풍선)은 텍스트 수식과 함께 걷음 diff --git a/resources/tester/test_750_2_views_one_answer.py b/resources/tester/test_750_2_views_one_answer.py deleted file mode 100644 index 09aeaf4d8..000000000 --- a/resources/tester/test_750_2_views_one_answer.py +++ /dev/null @@ -1,17 +0,0 @@ -"""750-2 화면 — 수식 · 단가산출 상세가 SK 셈 답 하나로(바탕 M01 로직 따로 셈 길 걷음 · 799-2 시험 계산 보기는 걷음) · 재료 고름 = 문서 `고름` · -읽는 식 줄 = cid 로 이음 · 옵션 바꿈 = SK 셈 한 번(원문 대조는 서버 test_750_1).""" - -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] - - -def _ts(rel: str) -> str: - return (ROOT / rel).read_text("utf-8") - - -def test_calc_drive_is_screenless_and_m02_has_no_calc_hook(): - ts = _ts("M01_MasterData/M01_MasterData_UI_Logic_Calc.ts") - assert "ctx.answer" not in ts and "CalcShown" not in ts # 799-2 M02 시험 계산 길 걷음 - drive = _ts("M01_MasterData/M01_MasterData_UI_Logic_Drive.ts") - assert "runCalc(body)" in drive and "document." not in drive # 셈 구동 = 화면 없이 diff --git a/resources/tester/test_799_2_old_tabs_gone.py b/resources/tester/test_799_2_old_tabs_gone.py index 3d484fe68..c547061de 100644 --- a/resources/tester/test_799_2_old_tabs_gone.py +++ b/resources/tester/test_799_2_old_tabs_gone.py @@ -65,20 +65,7 @@ def test_보기는_수식_하나_고르기_없음(): assert "data-view" not in css and "data-block" not in css # 840-1 보기 고르기 규칙 걷음 -def test_셈_구동은_화면_없이_상세는_구동만(): - drive = _text(M01 / "M01_MasterData_UI_Logic_Drive.ts") - assert "document." not in drive and "sessionStorage." not in drive - assert "export async function driveRun(" in drive and "createDrive" not in drive # 840-1 - lab = _text(M01 / "M01_MasterData_UI_LogicLab.ts") - assert "createDrive" not in lab and "buildCalc" not in lab and "data-calc-run" not in lab - detail = _text(M01 / "M01_MasterData_UI_LogicLab_Detail.ts") - assert "calcHost" not in detail and "data-calc-run" not in detail and "rerun" not in detail - m02 = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts") - assert "buildCalc" not in m02 and "calcHost" not in m02 - - def test_파일_700줄_안(): for p in (M01 / "M01_MasterData_UI_LogicLab.ts", M01 / "M01_MasterData_UI_LogicLab_Detail.ts", - M02 / "M02_MasterTemplete_Sangeun_Detail.ts", M02 / "M02_MasterTemplete_Sangeun_Tabs.ts", - M01 / "M01_MasterData_UI_Logic_Drive.ts"): # fmt: skip + M02 / "M02_MasterTemplete_Sangeun_Detail.ts", M02 / "M02_MasterTemplete_Sangeun_Tabs.ts"): # fmt: skip assert len(_text(p).splitlines()) <= 700, p.name