From 44728c0e01f866ed508fd1312c5487cc2326c13a Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:06:47 +0900 Subject: [PATCH 1/6] =?UTF-8?q?test(855-M):=20826-1=20M01=20=EA=B0=92=20?= =?UTF-8?q?=EB=B0=94=EB=80=9C=20=EC=8B=9C=ED=97=98=20=E2=80=94=20=EC=98=9B?= =?UTF-8?q?=20=EA=BC=B4=20=EA=B2=AC=EB=B3=B8=20=EB=8C=80=EC=8B=A0=20?= =?UTF-8?q?=EC=88=98=EC=8B=9D=20=EC=82=AC=EB=B3=B8=20=EC=9E=88=EB=8A=94=20?= =?UTF-8?q?SK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 까닭: 2-C1 뒤 옛 칸(더한줄)으로 고치고 사본을 뗀 SK = 「못 셈 + 까닭」 → 기준금액 None - 견본을 화면이 만드는 새 꼴(바탕 로직 PCT · 수식 사본)로 · 바꾸는 M01 인력 = 바탕 줄 보통인부(LB000002) - 뜻 그대로: 개인 층 SK 목록 기준금액이 M01 값 바뀜 뒤 다시 셈됨(자동 따라옴) - 옛 꼴 만드는 도우미 `_unfreeze` 걷음(부르는 곳 0) Co-Authored-By: Claude Opus 5.5 --- resources/tester/test_826_1_layer_index.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/resources/tester/test_826_1_layer_index.py b/resources/tester/test_826_1_layer_index.py index c285e2302..4953b8a38 100644 --- a/resources/tester/test_826_1_layer_index.py +++ b/resources/tester/test_826_1_layer_index.py @@ -18,6 +18,7 @@ from resources.tester.test_m02_labor_ref import COMPANY, world # noqa: F401 — PCT = "GC001109" # 원/㎡ · 인력 둘 + 덧줄 % WAGE = "LB000001" +PCT_WAGE = "LB000002" # 보통인부 — PCT 바탕 줄 LIB = ("sangeun", "precombo", "labor") @@ -111,13 +112,6 @@ def test_same_and_no_reads_when_stamps_same(fresh, reads): assert company[0]["쓰는곳수"] == 1 -def _unfreeze(folder, key): - """옛 꼴(사본 뗌) — M01 을 지금 값으로 셈(사본 있으면 만든 때 값 그대로).""" - doc = json.loads(layers.template_path(folder, "sangeun", key).read_bytes()) - old = {k: v for k, v in doc.items() if k not in ("사본", "수식", "M01판", "바탕판")} - layers.write_template(folder, "sangeun", key, old) - - def test_edit_delete_add_and_dep_change(fresh, reads): up, a, b, sc = _shelf(fresh) mine = fresh["personal"] @@ -162,13 +156,12 @@ def test_m01_change_recounts_amount(fresh, tmp_path, monkeypatch): shutil.copytree(Path(m01.FOLDER) / "기계", copy / "기계") # 기계 = 폴더(826-2) monkeypatch.setattr(m01, "FOLDER", copy) mine = fresh["personal"] - a = _sk(mine, "가", [_wage_line()]) - _unfreeze(mine, a) + a = _sk(mine, "가") # 수식 사본 있는 SK — 개인 층 = M01 자동 따라옴(836-2) one = next(r for r in _same(mine) if r["이름"] == a)["기준금액"] assert one is not None wages = json.loads((copy / "인력.json").read_text(encoding="utf-8")) for row in wages["줄"]: - if row.get("키") == WAGE: + if row.get("키") == PCT_WAGE: row["값"] = float(row["값"]) * 2 (copy / "인력.json").write_text(json.dumps(wages, ensure_ascii=False), encoding="utf-8") two = next(r for r in _same(mine) if r["이름"] == a)["기준금액"] From 19640b3f89aa77fc4d3d62658328cc13d48d8731 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:17:30 +0900 Subject: [PATCH 2/6] =?UTF-8?q?refactor(855-E=20L2a):=20/logic=20=EC=A7=80?= =?UTF-8?q?=EB=AC=B8=EC=9D=84=20=EC=88=98=EC=8B=9D=20=EB=AC=B8=EC=84=9C=20?= =?UTF-8?q?=EC=85=88=20=EC=B9=B8=20=EC=A7=80=EB=AC=B8=EC=9C=BC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 옛 정본 줄 지문(Store_Revise.row_print · 로직 줄 셈 칸) → M02_Doc_Copy.doc_fp(수식 문서) · 읽는 화면 0 - 개정 확인 409(guard · changed)는 /save 가 로직 줄을 쓰는 동안 그대로(L3) - test_713_1: 지문 시험을 문서 기준으로 — 비고 고침은 같음 · 문서 금액 줄 고침은 바뀜 - 라우터 쪽 시험 28 파일 267 통과 Co-Authored-By: Claude Opus 5.5 --- M01_MasterData/M01_MasterData_Router.py | 7 ++++--- resources/tester/test_713_1_revise.py | 15 ++++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/M01_MasterData/M01_MasterData_Router.py b/M01_MasterData/M01_MasterData_Router.py index c16cebed8..f90545143 100644 --- a/M01_MasterData/M01_MasterData_Router.py +++ b/M01_MasterData/M01_MasterData_Router.py @@ -21,7 +21,6 @@ from M01_MasterData import M01_MasterData_Store as store from M01_MasterData import M01_MasterData_Store_List as store_list from M01_MasterData import M01_MasterData_RateSheet as rate_sheet from M01_MasterData import M01_MasterData_Store_Make as make -from M01_MasterData import M01_MasterData_Store_Revise as revise from M01_MasterData import M01_MasterData_Store_Sheet as sheet import master_basis as mbs # noqa: E402 (`store` 가 scripts 를 길에 둠) @@ -174,9 +173,11 @@ def get_parts(group: str, detail: str = "") -> dict: @router.get("/logic") def get_logic(key: str) -> dict: - """`지문` = 줄 바탕 지문(계산 칸 · `Store_Revise.row_print`) — M02 덮개 「M01 개정」 비교 값.""" + """`지문` = 수식 문서 셈 칸 지문(`M02_Doc_Copy.doc_fp` · 855 L2 ⓐ) — 이름표 · 비고 고침은 안 바꿈.""" + from M02_MasterTemplete import M02_Doc_Copy as doc_copy # M02 가 M01 을 부름 — 늦게 + out = _call(store.logic, key) - return {**out, "지문": revise.row_print(out["logic"])} + return {**out, "지문": doc_copy.doc_fp(doc_screen.docs().get(key))} @router.get("/logic/source") diff --git a/resources/tester/test_713_1_revise.py b/resources/tester/test_713_1_revise.py index 837b0b9fd..859b384c3 100644 --- a/resources/tester/test_713_1_revise.py +++ b/resources/tester/test_713_1_revise.py @@ -73,17 +73,22 @@ def test_같은_줄_다시_보냄은_그대로(client: TestClient) -> None: def test_확인하면_저장_지문은_계산_칸만(client: TestClient) -> None: + """`/logic` 지문 = 수식 문서 셈 칸 지문(855 L2 ⓐ) — 비고 고침은 그대로 · 문서 금액 줄 고침은 바뀜.""" + from M02_MasterTemplete import M02_Doc_Copy as doc_copy + one = client.get("/api/m01/logic", params={"key": KEY}).json() base, print0 = one["logic"], one["지문"] - assert print0 == revise.row_print(base) + doc = client.get("/api/m01/logic/doc", params={"key": KEY}).json() + assert print0 == doc_copy.doc_fp(doc["문서"]) body = {"files": [_part(client, "edit", {**base, "비고": "개정 시험"})], "개정확인": True} assert client.post("/api/m01/save", json=body).status_code == 200 again = client.get("/api/m01/logic", params={"key": KEY}).json() assert again["logic"]["비고"] == "개정 시험" and again["지문"] == print0 # 비고 = 지문 밖 - hop = [dict(x) for x in base["호표"]] - hop[0]["수량"] = f"({hop[0]['수량']}) * 2" - body = {"files": [_part(client, "edit", {**again["logic"], "호표": hop})], "개정확인": True} - assert client.post("/api/m01/save", json=body).status_code == 200, "계산 칸 고침" + doc = client.get("/api/m01/logic/doc", params={"key": KEY}).json() + line = doc["문서"]["금액"][0] + line["수량"] = f"({line['수량']}) × 2" + res = client.post("/api/m01/logic/doc/save", json={"문서": doc["문서"], "판": doc["판"]}) + assert res.status_code == 200, res.text assert client.get("/api/m01/logic", params={"key": KEY}).json()["지문"] != print0 From a1ecc1df3f47e3cc7dfd0346a89d15f4c1407ae7 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:22:06 +0900 Subject: [PATCH 3/6] =?UTF-8?q?refactor(855-F=20B9-5):=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=EC=A0=9D=ED=8A=B8=20=EC=98=9B=20=EC=82=AC=EB=B3=B8=20?= =?UTF-8?q?=EA=BC=B4=20=EC=9D=BD=EA=B8=B0=20=EA=B1=B7=EC=9D=8C=20=E2=80=94?= =?UTF-8?q?=20=EC=98=9B=20=ED=95=AD=EB=AA=A9=20=ED=8F=B4=EB=8D=94=20?= =?UTF-8?q?=EC=98=AE=EA=B2=A8=20=EB=B0=9B=EA=B8=B0=20=C2=B7=20=EC=98=9B=20?= =?UTF-8?q?=EB=B3=B5=EC=82=AC=EB=B3=B8=20=EC=B1=84=EC=9A=B0=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - M02_Item_Snapshot: migrate_items · items_dir · OLD_ITEMS_DIRNAME · complete_old 지움 · 맞춤 답 「옮겨받음」 칸 뺌 - M02_Item_Copy: _migrated 대신 structures_dir · 읽을 때 complete_old 안 부름 - 까닭: 프로젝트 사본 0 · templates/items 0(보충 3-1 · 판단 거리 3 = 걷음) · 옛 꼴 호환 안 만듦(요구 898 · 899) - 시험: test_item_copy_complete 옛 꼴 둘(옛 복사본 채움 · 옛 항목 폴더 옮겨 받음) 지움 — 죽은 길만 붙듦 · test_structures_summary_snapshot 맞춤 답 칸 하나 고침 - 검증: 관련 시험 270 — 통과 267 · 실패 3 = test_719_2 셋(고치기 전부터 같은 실패 · 묶음 3 몫) Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Item_Copy.py | 20 +--- M02_MasterTemplete/M02_Item_Snapshot.py | 92 +------------------ resources/tester/test_item_copy_complete.py | 37 -------- .../test_structures_summary_snapshot.py | 2 +- 4 files changed, 9 insertions(+), 142 deletions(-) diff --git a/M02_MasterTemplete/M02_Item_Copy.py b/M02_MasterTemplete/M02_Item_Copy.py index 889bfae4b..32940c06b 100644 --- a/M02_MasterTemplete/M02_Item_Copy.py +++ b/M02_MasterTemplete/M02_Item_Copy.py @@ -4,7 +4,7 @@ 복사본 = `{프로젝트}/templates/structures/{구조물 id}/` (`M02_Item_Snapshot`) · 길의 폴더 = 구조물 id. 파일마다 판 = 내용 해시 — 쓸 때 판이 다르면 `Stale`(409). 고치면 manifest 에 `고침` 을 남겨 지울 때 -`_지난/` 에 옮겨 둠. 옛 복사본(새 파일 없음) · 옛 항목 폴더는 읽을 때 채우고 옮겨 받음. +`_지난/` 에 옮겨 둠. 계산은 복사본만 씀(마스터 현재값 안 읽음) — 원본 항목이 바뀌거나 지워져도 그대로. """ @@ -29,10 +29,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( PICKS_FILE, VALUES_FILE, build_snapshot, - complete_old, folder_name, - items_dir, - migrate_items, now_text, retire, same_item, @@ -68,21 +65,13 @@ class Stale(ValueError): self.current = current -def _migrated(project_root: str | Path) -> Path: - """구조물 복사본 뿌리 — 옛 항목 폴더가 남았으면 먼저 옮겨 받음.""" - if items_dir(project_root).is_dir(): - migrate_items(project_root) - return structures_dir(project_root) - - def folder_of(project_root: str | Path, folder: str) -> Path: """구조물 복사본 폴더 — 이름 모양이 틀리거나 없으면 LookupError(404).""" if not FOLDER_PATTERN.match(folder): raise LookupError(f"복사본 폴더 이름 모양이 아님 「{folder}」") - target = _migrated(project_root) / folder + target = structures_dir(project_root) / folder if not (target / MANIFEST_NAME).is_file(): raise LookupError(f"복사본이 없음 「{folder}」") - complete_old(target) return target @@ -97,7 +86,7 @@ def source_changed(manifest: dict[str, Any]) -> bool | None: def list_items(project_root: str | Path, only: str | None = None) -> list[dict[str, Any]]: """복사본 목록 — `only` = 그 폴더 하나만(고르기 모달 · 원본 대조를 그 하나만 · 156-2).""" - base = _migrated(project_root) + base = structures_dir(project_root) out = [] for child in sorted(base.iterdir()) if base.is_dir() else []: if not child.is_dir() or not FOLDER_PATTERN.match(child.name): @@ -106,7 +95,6 @@ def list_items(project_root: str | Path, only: str | None = None) -> list[dict[s continue if not (child / MANIFEST_NAME).is_file(): continue - complete_old(child) manifest = read_json(child / MANIFEST_NAME) or {} origin = manifest.get("원본") or {} changed = source_changed(manifest) @@ -289,7 +277,7 @@ def prefetch(project_root: str | Path, owner_id: str, item: dict[str, Any]) -> d folder = folder_name(owner_id) if not FOLDER_PATTERN.match(folder): raise ValueError(f"구조물 id 모양이 아님 「{owner_id}」") - target = _migrated(project_root) / folder + target = structures_dir(project_root) / folder manifest = read_json(target / MANIFEST_NAME) made = not (isinstance(manifest, dict) and same_item(manifest, item)) if made: diff --git a/M02_MasterTemplete/M02_Item_Snapshot.py b/M02_MasterTemplete/M02_Item_Snapshot.py index cc9ebabaf..a6315b09e 100644 --- a/M02_MasterTemplete/M02_Item_Snapshot.py +++ b/M02_MasterTemplete/M02_Item_Snapshot.py @@ -13,8 +13,6 @@ - 지정을 다른 항목으로 바꾸면 새로 가져옴 · 구조물을 지우거나 지정을 풀면 복사본을 지움 — 프로젝트에서 고친 흔적(`manifest.고침`)이 있으면 지우지 않고 `_지난/` 에 옮겨 둠 - 관 지점을 옮겨도 같은 항목이면 폴더 이름만 바꿈(142-2) · 옵션 그룹 이름 · 가져온이도 굳힘 - - 옛 항목 폴더(`templates/items/{층}_{주인}_{키}/` · 25-2b)는 그 항목을 쓰는 구조물마다 복사해 - 옮겨 받음(고친 값 유지) """ from __future__ import annotations @@ -29,12 +27,11 @@ from B05_Profile.B05_Profile_Structures_Repository import load_structures from B05_Profile.B05_Profile_Structures_Schema import STRUCTURE_ID_RULE from common_util.common_util_drainage_pipes import pipe_points_path_in, read_pipe_points_file from common_util.common_util_json import atomic_write_json -from common_util.common_util_summary_item import GROUP_JOIN, snapshot_folder_name +from common_util.common_util_summary_item import GROUP_JOIN from common_util.common_util_time import kst_now, utc_now_text from M02_MasterTemplete import M02_Template_Layers as layers from M02_MasterTemplete.M02_Item_Source import ( LABOR_FILE, - PRICE_FILE, build_source, item_path, read_json, @@ -44,7 +41,6 @@ from M02_MasterTemplete.M02_Item_Source import ( logger = logging.getLogger(__name__) STRUCTURES_DIRNAME = "structures" -OLD_ITEMS_DIRNAME = "items" # 25-2b 항목 폴더 — 옮겨 받기만 PAST_DIRNAME = "_지난" # 고친 흔적이 있는 복사본을 지우지 않고 옮겨 두는 자리 MANIFEST_NAME = "manifest.json" VALUES_FILE = "입력값.json" # {로직키: {입력이름: {값, 확인}}} @@ -63,11 +59,6 @@ def structures_dir(project_root: str | Path) -> Path: return layers.project_dir(project_root) / STRUCTURES_DIRNAME -def items_dir(project_root: str | Path) -> Path: - """옛 항목 폴더 뿌리(25-2b) — 옮겨 받기에만 씀.""" - return layers.project_dir(project_root) / OLD_ITEMS_DIRNAME - - def folder_name(owner_id: str) -> str: """구조물 id → 복사본 폴더 이름 — id 없는 옛 구조물(`#차례`)은 `n차례`.""" return owner_id.replace("#", "n") @@ -195,42 +186,6 @@ def retire(folder: Path) -> str | None: return None -def migrate_items(project_root: str | Path) -> list[str]: - """옛 항목 폴더 → 그 항목을 쓰는 구조물마다 복사(고친 값 유지) — 옮겨 받은 구조물 폴더 이름. - - 다 옮긴 옛 폴더는 지움 · 쓰는 구조물이 없고 고친 흔적이 있으면 `structures/_지난/` 에 둠.""" - old = items_dir(project_root) - if not old.is_dir(): - return [] - base = structures_dir(project_root) - wanted = assignments(project_root) - moved: list[str] = [] - for child in sorted(p for p in old.iterdir() if p.is_dir()): - manifest = read_json(child / MANIFEST_NAME) - if not isinstance(manifest, dict): - continue - users = [o for o, item in wanted.items() if snapshot_folder_name(item) == child.name] - for owner in users: - target = safe_folder(base, folder_name(owner)) - if target is None or (target / MANIFEST_NAME).is_file(): - continue # 이미 새 복사본이 있음 - shutil.copytree(child, target, dirs_exist_ok=True) - origin = manifest.get("원본") or {} - atomic_write_json( - target / MANIFEST_NAME, - {**manifest, "원본": origin_of(origin), "구조물": [owner], "옮겨받음": now_text()}, - ) - moved.append(target.name) - if users or not manifest.get("고침"): - shutil.rmtree(child) - else: - (base / PAST_DIRNAME).mkdir(parents=True, exist_ok=True) - shutil.move(str(child), str(base / PAST_DIRNAME / f"items_{child.name}")) - if not any(old.iterdir()): - old.rmdir() - return moved - - def rename_moved(base: Path, wanted: dict[str, tuple[str, dict[str, Any]]]) -> list[str]: """관 지점을 옮긴 뒤 [저장] — 새 자리(`pipe@새 측점`)에 복사본이 없고 안 쓰게 된 옛 자리 복사본이 같은 항목 · 같은 그룹 꼬리면 폴더 이름만 바꿈(가까운 측점 먼저 · 142-2) — 가져온날 · @@ -313,9 +268,8 @@ def copied_groups( def sync_snapshots( project_root: str | Path, who: dict[str, Any] | None = None ) -> dict[str, list[str]]: - """구조물 복사본을 지정에 맞춤 — `{만듦, 지움, 못만듦, 옮겨받음, 이름바꿈}` 폴더 이름 · + """구조물 복사본을 지정에 맞춤 — `{만듦, 지움, 못만듦, 이름바꿈}` 폴더 이름 · `who` = 가져온이(manifest · 142-2).""" - moved = migrate_items(project_root) base = structures_dir(project_root) wanted = { folder_name(owner): (owner, item) for owner, item in assignments(project_root).items() @@ -357,7 +311,7 @@ def sync_snapshots( if child.is_dir() and not child.name.startswith("_") and child.name not in wanted: retire(child) removed.append(child.name) - out = {"만듦": made, "지움": removed, "못만듦": failed, "옮겨받음": moved} + out = {"만듦": made, "지움": removed, "못만듦": failed} return {**out, "이름바꿈": renamed} if renamed else out @@ -381,42 +335,6 @@ def safe_sync(project_root: str | Path, who: dict[str, Any] | None = None) -> li return ["*"] -def complete_old(folder: Path) -> bool: - """옛 복사본(21-3 · 새 파일 없음)을 채움 — 단가는 지금 원본에서 · 값은 빈 것. - - 옛 내용 파일(집계 · 도면 …)은 그대로 둠. 채웠으면 True(manifest 에 `옮겨받음` 날).""" - manifest = read_json(folder / MANIFEST_NAME) - if not isinstance(manifest, dict): - return False - lacking = [ - name for name in (PRICE_FILE, VALUES_FILE, PICKS_FILE) if not (folder / name).is_file() - ] - if not lacking and "원본판" in manifest: - return False - need_source = PRICE_FILE in lacking - try: - source = build_source(manifest["원본"]) if need_source else {} - except LookupError: - source = {} # 원본이 지워짐 — 빈 단가로(계산은 멈춤으로 알림) - for name in lacking: - atomic_write_json(folder / name, source.get(name, {})) - kept = { - name: read_json(folder / name) - for name in sorted(p.name for p in folder.glob("*.json")) - if name not in (MANIFEST_NAME, *LOCAL_FILES, "수식.json") # 수식 사본(802-4a) 원본판 밖 - } - atomic_write_json( - folder / MANIFEST_NAME, - { - **manifest, - "가져온날": manifest.get("가져온날") or manifest.get("적용일"), - "원본판": manifest.get("원본판") or version_of(kept), - "옮겨받음": manifest.get("옮겨받음") or now_text(), - }, - ) - return True - - #: 「연결된 사본」 부분 이름 → 파일(있는 것만 `부분` 에 담음) LINKED_PARTS = (("도면", "도면.json"), ("면적", "면적.json"), ("일위대가", LABOR_FILE)) @@ -446,8 +364,6 @@ def linked_snapshots(project_root: str | Path) -> dict[str, dict[str, Any]]: def read_snapshot(project_root: str | Path, owner_id: str) -> dict[str, Any] | None: - """그 구조물 복사본의 `집계.json`(`{줄, 열}`) — 없으면 None(옛 항목 폴더는 먼저 옮겨 받음).""" - if items_dir(project_root).is_dir(): - migrate_items(project_root) + """그 구조물 복사본의 `집계.json`(`{줄, 열}`) — 없으면 None.""" data = read_json(structures_dir(project_root) / folder_name(owner_id) / "집계.json") return data if isinstance(data, dict) else None diff --git a/resources/tester/test_item_copy_complete.py b/resources/tester/test_item_copy_complete.py index 23f08c5bb..046bf5f8d 100644 --- a/resources/tester/test_item_copy_complete.py +++ b/resources/tester/test_item_copy_complete.py @@ -300,23 +300,6 @@ def test_미리_가져오기(world): copies.prefetch(root, "../x", PIPE) -def test_옛_복사본은_읽을_때_채움(world): - root = world["root"] - _save(root, [_pipe()]) - folder = root / "templates/structures" / FOLDER - for name in ("입력값.json", "고른자재.json", "단가.json"): - (folder / name).unlink() - manifest = _read(folder / "manifest.json") - for key in ("원본판", "가져온날"): - manifest.pop(key) - (folder / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False), "utf-8") - assert copies.read_file(root, FOLDER, "입력값")["내용"] == {} - filled = _read(folder / "manifest.json") - assert filled["가져온날"] == filled["적용일"] and filled["옮겨받음"] - assert (folder / "단가.json").is_file() and copies.calc(root, FOLDER)["빠진입력"] - assert copies.list_items(root)[0]["마스터바뀜"] is False # 원본이 안 바뀐 옛 복사본 - - # ── 길 · 권한 ──────────────────────────────────────── @@ -489,26 +472,6 @@ def test_프로젝트에서_새_항목(world): copies.new_item(root, "c2", 3, 12, [], "", None) # 경로 · 이름 빈 값 -def test_옛_항목_폴더는_쓰는_구조물마다_옮겨_받음(world): - root = world["root"] - _save_all(root, [_wall("d1"), _wall("d2")], []) - base = root / "templates/structures" - old = root / "templates/items/system_none_SS000022" - old.parent.mkdir(parents=True) - shutil.move(str(base / "d1"), str(old)) - shutil.rmtree(base / "d2") - manifest = _read(old / "manifest.json") - manifest.update({"구조물": ["d1", "d2"], "고침": True}) - (old / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False), "utf-8") - (old / "입력값.json").write_text(json.dumps({"GF": {"a": {"값": 1}}}), "utf-8") - assert [i["폴더"] for i in copies.list_items(root)] == ["d1", "d2"] - assert not (root / "templates/items").exists() - for sid in ("d1", "d2"): - assert _read(base / sid / "입력값.json") == {"GF": {"a": {"값": 1}}} # 고친 값 유지 - assert _read(base / sid / "manifest.json")["구조물"] == [sid] - assert _save_all(root, [_wall("d1"), _wall("d2")], [])["만듦"] == [] - - def test_지정을_바꾸면_고친_옛_복사본은_지난에(world): root = world["root"] _save_all(root, [_wall("e1")], []) diff --git a/resources/tester/test_structures_summary_snapshot.py b/resources/tester/test_structures_summary_snapshot.py index 5b7c2b9f5..bae53e40a 100644 --- a/resources/tester/test_structures_summary_snapshot.py +++ b/resources/tester/test_structures_summary_snapshot.py @@ -129,7 +129,7 @@ def test_옛_파일은_칸_없음_그대로_읽고_씀(): def test_지정하면_폴더가_생기고_내용이_원본과_같음(world): root = world["root"] result = _save(root, [_dry(MS), _wet()], [_pipe(PIPE)]) - assert result == {"만듦": ["pipe@40.0", "st0"], "지움": [], "못만듦": [], "옮겨받음": []} + assert result == {"만듦": ["pipe@40.0", "st0"], "지움": [], "못만듦": []} folder = _items(root) / "st0" got = {path.name for path in folder.iterdir()} assert { From efc881ad12fe42b8cc2eacf90fb9b053ac99324a Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:53:03 +0900 Subject: [PATCH 4/6] =?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 5/6] =?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 From 11d348492ee58d8467b8739daeed71fe79309187 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 03:24:52 +0900 Subject: [PATCH 6/6] =?UTF-8?q?refactor(855-F=20B9-5):=20=EC=82=AC?= =?UTF-8?q?=EB=B3=B8=20=EB=8B=A8=EA=B0=80=EC=82=B0=EC=B6=9C=20=EA=B5=B3?= =?UTF-8?q?=ED=9E=98=20=EA=B1=B7=EC=9D=8C=20=E2=80=94=20=EA=B5=B3=ED=9E=8C?= =?UTF-8?q?=20=EB=A1=9C=EC=A7=81=20=EC=A4=84(GX9)=20=EB=8C=80=EC=8B=A0=20M?= =?UTF-8?q?02=20=EB=AC=B8=EC=84=9C=20+=20=EC=88=98=EC=8B=9D=20=EB=94=B0?= =?UTF-8?q?=EB=A1=9C=20=EC=82=AC=EB=B3=B8=20=C2=B7=20B09=20=EB=8C=80?= =?UTF-8?q?=EA=B0=80=EA=B0=80=20=EB=AC=B8=EC=84=9C=20=EC=85=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - M02_Item_Sangeun: freeze = SK 마다 지금 M02 셈 사본(Doc_Sk.copy_of · 덮음 반영)을 수식에 따로 · 굳힘 표지로 굳힘 · 원본 · 처음 · 덮음바탕(M01 따라옴 기록) 뺌 · 옛 GX9 키 · 굳힌줄 · 정체 · 원본 · SC 굳힌 덮개 줄 지움 · bundle_keys = SK 셈이 읽는 바탕 로직 · 부름 문서 키 · 값 사본 자원 키 · 가져온 식 줄 - M02_Item_Source: 단가.json 에 로직_단가산출.json(GX9) 없음 · SK 줄은 bundle_keys 로 모음 - B09 Labor_Source.sangeun: SK 대가 블록 = 수식 사본 문서 답(줄 이름 · 단위 · 종류 · 자원 키 · 하위 부름) · 셈법(792-4)은 줄이 기초 줄과 맞을 때만 · cid 열쇠 = SK 이름표 · 줄 덮개(패치) = M02 처럼 못 셈 - B09 Linked: sk_answer(사본 SK 문서 셈 · 가져온 식 = 단가기준) · 수요 키 = 셈 기록 - B09 Refresh: 바뀐 SK = SK 문서 · 수식 사본 대조 · Supply.sk_money: 배 = 바탕 줄(바탕 없음 = 1) - 골든 test_855_b09_golden 다시 뜸 — daega_inputs · 수요 두 갈래만(calc_user · 산근 · 미리보기 · B08 같음): SK 블록 origin · cid 열쇠(GX9 → SK 이름표) · 재료 단위 = 문서 표기(kg → ㎏) · 따로 고친 SK 줄 수량 = M02 문서(0.018 → 0.036 · 옛 굳힘은 고친 문서를 못 봄) · 옛 칸(율 더한줄) SK = M02 처럼 못 셈 → 그 SK 자원 키 둘(LB000038 · EQ000153) 빠짐 - 시험: test_719_1 · 719_2 견본을 수식 사본 있는 SK(M02 에서 고친 문서)로 · 단언을 새 사본 꼴로 · 719_2 옛 칸 견본 셋 지움(단가 덮개 · SC 더한줄 펼침 · 내 자료집 둘 — 옛 칸 SK 만들기 = 2-C1 셈 은퇴) · test_778_4 옛 칸 율 더한줄 SK 블록 하나 지움 · test_792_3 ⑤ · test_793_2 = 새 사본 꼴(793_2 우리 단가 = 사본 굳힘) - 검증: 관련 + 핵심 672 — 통과 671 · test_848_1 ㉦ 하나 = sub4 2-D 굳힘 표지 읽기 두 줄 뒤 통과(브레인 정함) · 사본 칸(골든 견본) SK 굳힌줄 · GX9 10 → 0 · 수식 따로 2 → 9 · typecheck 0 · 빌더 --check 같음 · 서버 뜸 로그 오류 0 Co-Authored-By: Claude Opus 5.5 --- B09_Estimation/B09_Estimation_Bill_Library.py | 6 +- B09_Estimation/B09_Estimation_Labor_Source.py | 196 +++++++++--------- B09_Estimation/B09_Estimation_Linked.py | 43 ++-- B09_Estimation/B09_Estimation_Refresh.py | 9 +- B09_Estimation/B09_Estimation_Supply.py | 2 +- M02_MasterTemplete/M02_Doc_B09.py | 4 +- M02_MasterTemplete/M02_Item_Sangeun.py | 183 ++++------------ M02_MasterTemplete/M02_Item_Source.py | 16 +- resources/tester/golden_855_b09.json | 4 +- resources/tester/test_719_1_sk_freeze.py | 111 ++++++---- resources/tester/test_719_2_sk_project.py | 163 +++------------ resources/tester/test_778_4_rate_line.py | 14 -- resources/tester/test_792_3_engine_paths.py | 33 ++- .../tester/test_793_2_sangeun_imported.py | 13 +- 14 files changed, 310 insertions(+), 487 deletions(-) diff --git a/B09_Estimation/B09_Estimation_Bill_Library.py b/B09_Estimation/B09_Estimation_Bill_Library.py index b9895c5a2..a37e44a3f 100644 --- a/B09_Estimation/B09_Estimation_Bill_Library.py +++ b/B09_Estimation/B09_Estimation_Bill_Library.py @@ -6,7 +6,7 @@ 도면 · 면적 · 일위대가 · 단가 · 입력값 · 고른자재 첫 값) precombo 사전조합 = `일위대가.json` {줄: {담은로직: [{참조, 수량: {손: 1}}]}, 참조사본} · `단가.json`(`M02_Item_Source.price_bundle` — 사본 단가 묶음 한 벌) - sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(참조사본 = 풀어 굳힌 SK) + sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(SK = 수식 사본 · B9-5) [업데이트](719-2) = 원본판이 다른 사본만 같은 폴더에 다시 굳힘(`changed` · `refresh_copy` · 값 그대로 · 원본판 없는 옛 사본 = 그대로). 사본 = 원본이 바뀌거나 지워져도 그대로(굳힘) · @@ -106,8 +106,8 @@ def _precombo_files(layer: str, owner: str | None, key: str, kind: str = "precom def source_version(files: dict[str, Any]) -> str: - """서고 사본 원본판(719-1) = 일위대가.json 지문 — 굳힌 SC · SK 문서 + 풀어 굳힌 SK 줄(바탕 - M01 줄 · 바탕판) · 단가는 뺌(단가 바뀜은 [업데이트] 단가 굳힘 몫) · 값 덮기 전에 셈.""" + """서고 사본 원본판(719-1) = 일위대가.json 지문 — 굳힌 SC · SK 문서(SK = 수식 사본) · + 단가는 뺌(단가 바뀜은 [업데이트] 단가 굳힘 몫) · 값 덮기 전에 셈.""" return version_of(files.get(LABOR_FILE)) diff --git a/B09_Estimation/B09_Estimation_Labor_Source.py b/B09_Estimation/B09_Estimation_Labor_Source.py index 99d4c6205..a1dfa349e 100644 --- a/B09_Estimation/B09_Estimation_Labor_Source.py +++ b/B09_Estimation/B09_Estimation_Labor_Source.py @@ -40,10 +40,12 @@ from B09_Estimation import B09_Estimation_Sangeun as sg from B09_Estimation import B09_Estimation_Sangeun_Text as st from B09_Estimation.B09_Estimation_Bill_Items import LAYER_WORD from B09_Estimation.B09_Estimation_Copy_Prices import bundle +from B09_Estimation.B09_Estimation_Linked import sk_answer from B09_Estimation.B09_Estimation_Supply import sk_money, supply_mark from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Labor_Doc as labor_doc from M02_MasterTemplete import M02_Labor_Fixed as fixed +from M02_MasterTemplete import M02_Labor_Patch as patch from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete.M02_Item_Snapshot import ( MANIFEST_NAME, @@ -184,64 +186,79 @@ class Builder: "_items": items, } - # ── 단가산출(SK · 719-2) ──────────────────────────────────────────── + # ── 단가산출(SK · 719-2 · 855-F B9-5) ────────────────────────────────── def sangeun(self, whole: Any, ref: dict, doc: dict, copies: dict, depth: int = 0) -> str | None: - """굳힌 SK(사본 `단가.json` 로직 줄 · 719-1) = 품셈 블록 꼴 대가 — 셈 = 굳힌 줄 그대로 · - 단가산출 속 일위대가 · SK 줄(참조) = 그 대가 블록을 부르는 줄(펼침 · B09 차례 그대로) · - 고정 줄 = `fixed` · 단가 고친 줄(덮개 · 더한줄 단가 · 값묶음) = `fixed`(줄 단가 = M02 셈) · - cover = `P:` + SK 이름표(SK 를 고쳐 [업데이트] 해도 B09 덮개 그대로) · - 속 일위대가 안 줄 수량 없음(723-4) = 엔진엔 0 값묶음 · 그 줄 = 사전조합 블록(이 공사 입력) · - 줄 `sk` · `poom`(M02 에서 고친 줄의 품셈 값 = 원본 덮개 `원값`).""" - from M02_MasterTemplete import M02_Item_Sangeun as item_sk - from M02_MasterTemplete import M02_Sangeun_Calc as calc - from M02_MasterTemplete import M02_Sangeun_Doc as sd - + """사본 SK = 품셈 꼴 대가 — 셈 = 그 수식 사본 문서 셈(`Linked.sk_answer` · + M02 SK 셈과 같은 문서) · 줄 = 문서 답 금액 줄(이름 · 단위 · 수량 · 종류 = 답 · + 자원 키 · 하위 부름 = 셈 기록) — 노임 · 자재 · 기계경비(중기) · 하위 단가산출(산근) · + % 줄 · 그 밖 = 줄 단가 `fixed` · 합밖 = `out` · cover = `P:` + SK 이름표(SK 를 고쳐 + [재생성] 해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) · + 수식 사본 없는 SK(형제 · 옛 칸) = None(부르는 줄이 까닭 · M02 처럼 못 셈).""" + got = sk_answer(doc) + if got is None or got.stopped or "결과" in got.ans: + return None rid = refs.ref_id(ref) - key = str((doc.get("바탕") or {}).get("로직") or "") - if item_sk.ROW not in doc or not key: - return None # 못 푼 SK(없는 바탕 · 순환) — 부르는 줄이 까닭 + lines = [{**self._doc_line(got, n, x), "sk": True} for n, x in enumerate(got.lines)] + base = str((doc.get("바탕") or {}).get("로직") or "") + law = _law(doc, base, whole, lines, got.lines) # 새 의미 로직 줄 자리 · 합밖 · % 밑(792-4) + expand = _Loose(whole, lambda r: copies.get(refs.ref_id(r))) + m02 = sk_money(doc, whole, expand, rid) + given = doc.get("입력값") or {} + block = { + "kind": "품셈", + "name": doc.get("이름") or got.doc.get("이름") or "", + "spec": " · ".join( + f"{k} {st._word(got.whole, k, v) if isinstance(v, str) else v}" + for k, v in sorted(given.items()) + ), + "spec_raw": " · ".join(f"{k} {v}" for k, v in sorted(given.items())), + "unit": str(got.doc.get("결과단위") or "").replace("원/", "") or doc.get("단위") or "", + "cite": f"단가산출 {ref.get('키')}", + "origin": {"참조": rid, "단가산출": rid, "바탕": base}, # cid 열쇠 = SK 이름표 + "lines": lines, + **({"rule": law} if law else {}), + **({"m02": m02} if m02 else {}), + } + return self.put(block, f"P:{_digest({'단가산출': rid})}") - def read(r: dict) -> dict | None: - return copies.get(refs.ref_id(r)) - - try: - got = calc.resolve(doc, whole, read, (rid,)) - row = {**got["줄"], "키": key, "호표": [dict(x) for x in got["줄"]["호표"]]} - if calc._bundles(row, whole, _Loose(whole, read), (rid,)): - return None - except (sd.DocError, mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): - return None - one = {"로직": key, "입력값": got["입력값"], "켜쌓기율": got["켜쌓기율"], - "자재표시": got.get("자재표시")} # fmt: skip - where = {c: n for n, c in enumerate(got["정체"])} # 율 기준 줄 목록(778-4) → 블록 차례 - block = self._poomsem(calc._Over(whole, key, row), {**one, "고름": got["고름"]}) - if block is None: - return None - ids = list(doc.get("정체") or []) - was = {c: v.get("원값") for c, v in ((doc.get("원본") or {}).get("덮개") or {}).items()} - lines = [] - for n, (line, x) in enumerate(zip(block["lines"], block.pop("_engine"))): - item = block["_items"][n] if n < len(block["_items"]) else {} - qty, keep = _f(x.get("수량")), {k: line[k] for k in rule.FLAGS if k in line} - head = {"name": line.get("name") or "", "spec": "", "unit": line.get("unit") or ""} - if isinstance(item.get("참조"), dict) and depth < refs.DEPTH: - line = {**self.line_of(whole, item, qty, 1, head["name"], copies, depth), **head} - elif isinstance(item.get("고정"), dict): - line = {**fixed_line(item["고정"], qty, where, whole), **head} - elif qty and ("단가" in item or item.get("값묶음")): - own = {PART[k]: _f(v) / qty for k, v in (x.get("비목") or {}).items() if k in PART} - line = {**head, "kind": "fixed", "qty": qty, "own": own, "link": {}} - poom = was.get(ids[n]) if n < len(ids) else None - lines.append({**line, **keep, "sk": True, **({"poom": poom} if poom else {})}) - block.pop("_items") - name = doc.get("이름") or block["name"] - m02 = sk_money(doc, whole, _Loose(whole, read), rid) # 841-1 블록 합 = M02 SK 셈 - block = {**block, **({"m02": m02} if m02 else {})} - origin = {**block["origin"], "단가산출": rid} - cover = f"P:{_digest({'단가산출': rid})}" - return self.put({**block, "name": name, - "cite": f"단가산출 {ref.get('키')}", "origin": origin, - "lines": lines}, cover) # fmt: skip + def _doc_line(self, got: Any, n: int, x: dict) -> dict[str, Any]: + """문서 답 금액 줄 하나 → 블록 줄(855-F B9-5).""" + head = {"name": x.get("이름") or "", "spec": "", "unit": x.get("단위") or ""} + qty, key, call = _f(x.get("수량")), str(x.get("키") or ""), x.get("부름") or {} + out = {"out": True} if x.get("합밖") else {} + if pct := got.pct(n): + word = pct[1].removesuffix("의 %") + base = {"노무비": "part:labor", "재료비": "part:material", "경비": "part:expense", + "인건비": "lines:labor"}.get(word, f"line:{word}") # fmt: skip + if not word: # 밑을 모르는 덧줄 — 옛 길과 같게 빈 줄 + return { + **head, + **out, + "kind": "blank", + "qty": qty, + "why": "덧줄 — 대가 단가로 못 셈", + } + part = PART.get(str((got.doc.get("금액") or [])[n].get("비목")), "expense") + return {**head, **out, "kind": "pct", "part": part, "base": base, + "spec": pct[1], "unit": "%", "qty": float(pct[0])} # fmt: skip + own = _own(x, qty) + if call.get("machine") or key[:2] == "EQ": + key = call.get("machine") or key + spec = (_row(got.whole, key)).get("규격") or "" + return {**head, **out, "kind": "machine", "key": key, "spec": spec, "qty": qty, + "own": own} # fmt: skip + if call.get("code"): + return {**head, **out, "kind": "sangeun", "qty": qty, + "key": sg.sangeun_key(call["code"], call.get("given") or {})} # fmt: skip + if key[:2] == "LB": + return {**head, **out, "kind": "labor", "key": key, "qty": qty, "own": own} + if (x.get("품목") or {}).get("키") or key[:2] in ("MT", "MO", "PM"): + goods = x.get("품목") or {} + return {**head, **out, "kind": "material", "key": goods.get("키") or key, + "spec": goods.get("규격") or "", "qty": qty, "own": own} # fmt: skip + if own is None or (not key and x.get("단가") is None): # 값 없는 재료 찾기 · 못 셈 + return {**head, **out, "kind": "blank", "qty": qty, "why": x.get("까닭") or "품목 없음"} + return {**head, **out, "kind": "fixed", "qty": qty, "own": own, "link": {}} def _engine_line( self, item: dict | None, x: dict, logic: dict, extra: int, bases: dict, call: dict | None @@ -295,6 +312,8 @@ class Builder: each = None if q is None else q / t if fixed.is_fixed(one): return fixed_line(one[fixed.FIXED], q, None, whole) + if one.get(patch.FIELD): # 줄 덮개(715-3) = M02 처럼 못 셈(855 2-C5) + return {"kind": "blank", "name": name, "qty": each, "why": patch.WHY} ref = one.get("참조") if isinstance(ref, dict): doc = copies.get(refs.ref_id(ref)) @@ -305,16 +324,16 @@ class Builder: "qty": each, "why": f"없는 참조 「{ref.get('키')}」", } - if refs.kind_of(ref.get("키")) == "sangeun": # 단가산출(719-2) = 굳힌 줄 대가 + if refs.kind_of(ref.get("키")) == "sangeun": # 단가산출(719-2) = 수식 사본 대가 bid = self.sangeun(whole, ref, doc, copies, depth + 1) if bid is None: - why = "단가산출을 못 셈(바탕 없음 · 순환)" + why = "단가산출을 못 셈(수식 사본 없음 · 못 돈 문서)" return {"kind": "blank", "name": name, "qty": each, "why": why} from M02_MasterTemplete import M02_Sangeun_Calc as sc block = self.blocks[bid] # 블록 = 굳힌 줄 결과단위(배) 몫 · M02 참조 줄 = 1 단위 try: # 배 = 바탕 기준단위 → SK 단위(728-2) - per = float(sc.ratio_of(doc, whole.logic(doc["바탕"]["로직"]), whole)) + per = float(sc.ratio_of(doc, sc._row_of(doc, whole), whole)) except sc.sd.DocError as e: return {"kind": "blank", "name": name, "qty": each, "why": str(e)} return {"kind": "daega", "key": bid, "name": block["name"], "unit": block["unit"], @@ -329,16 +348,6 @@ class Builder: bid = self.precombo(whole, ref, doc, copies, depth + 1, use) return {"kind": "daega", "key": bid, "name": doc.get("이름") or name, "unit": doc.get("단위") or "", "qty": each} # fmt: skip - fz = one.get("굳힌") - if isinstance(fz, dict) and fz.get("키"): # 덮개 줄(740-1) = 굳힌 줄 단가산출 대가 - bid = self.sangeun( - whole, {"층": "project", "키": fz["키"]}, _sk_of(one), copies, depth + 1 - ) - if bid is None: - return {"kind": "blank", "name": name, "qty": each, "why": "덮개 줄을 못 셈"} - block = self.blocks[bid] # 블록 = 결과단위(배) 몫 · 수량 = 수량 ÷ 배 - return {"kind": "daega", "key": bid, "name": block["name"], "unit": block["unit"], - "qty": each} # fmt: skip code = str(one.get("로직") or "") if one.get("승격") is not True: # 단가산출 줄 = 산근 if not sg.is_money(whole, code): @@ -490,36 +499,6 @@ class Builder: return self.precombo(whole, ref, doc, copies, 1) -def _sk_of(one: dict) -> dict[str, Any]: - """굳힌 덮개 줄(740-1) → 굳힌 SK 꼴(`Builder.sangeun` 이 읽음) — 고름 · 자재표시 = 굳힌 줄 cid · - `원본.덮개` = 그 줄 패치 덮개(원값 = M02 에서 고친 줄의 품셈 값).""" - from M02_MasterTemplete import M02_Item_Sangeun as item_sk - from M02_MasterTemplete import M02_Sangeun_Doc as sd - - fz = one["굳힌"] - ids = sd.line_ids(fz["줄"]) - keyed = { - k: {ids[int(n)]: v for n, v in (fz.get(k) or {}).items() if int(n) < len(ids)} - for k in ("고름", "자재표시") - } - return { - "종류": "단가산출", - "키": fz["키"], - "이름": one.get("별칭") or fz["줄"].get("이름") or "", - "단위": "", - "바탕": {"로직": fz["키"]}, - "입력값": fz.get("입력값") or {}, - **({"켜쌓기율": fz["켜쌓기율"]} if fz.get("켜쌓기율") is not None else {}), - **keyed, - "덮개": {}, - "더한줄": [], - "뺀줄": [], - item_sk.ROW: fz["줄"], - "원본": {"덮개": (one.get("패치") or {}).get("덮개") or {}}, - "정체": list(fz.get("정체") or []), - } - - def _Loose(whole: Any, read: Any) -> Any: """B09 SK 속 펼침(723-4) — 사전조합 안 줄 수량 없음 = 0 값묶음(엔진 차례 · 수량만 씀 · 그 줄 값 = B09 사전조합 블록 · 이 공사에서 입력) · 그 밖 까닭은 그대로.""" @@ -535,6 +514,27 @@ def _Loose(whole: Any, read: Any) -> Any: return Loose(whole, read) +def _row(whole: Any, key: str) -> dict[str, Any]: + try: + return whole.get(key) or {} + except Exception: # noqa: BLE001 — 없는 키 = 빈 줄 + return {} + + +def _law(doc: dict, base: str, whole: Any, lines: list, engine: list) -> dict | None: + """SK 블록 셈법(792-4) — 줄이 기초 줄(가져온 식 = 가져온 줄 · 그 밖 = 바탕 로직)과 하나하나 + 맞을 때만 `rule.mark`(새 의미 로직 = 줄 자리 · 합밖 · % 밑) · 안 맞음(따로 고친 문서) = None.""" + from M02_MasterTemplete import M02_Doc_Import as dim + + try: + row = (doc.get("가져온") or {}).get("로직") if dim.is_imported(doc) else whole.logic(base) + except Exception: # noqa: BLE001 — 바탕 없음 · 없는 로직 + return None + if not isinstance(row, dict) or len(rule.ms.items(row)) != len(lines): + return None + return rule.mark(row, lines, engine) + + def fixed_line(fx: dict, qty: Any, where: dict | None = None, whole: Any = None) -> dict[str, Any]: """고정 줄(705-1) → 블록 줄 `fixed` — 수량 그대로(배 1) · 단가 = M02 엔진 고정 줄 셈(`whole` = 사본 단가 묶음 · 이은 노임 · 자재 = 묶음 값 · 841-1) · 없으면(붙인 줄) 줄 단가 · diff --git a/B09_Estimation/B09_Estimation_Linked.py b/B09_Estimation/B09_Estimation_Linked.py index d813e6e21..755df9188 100644 --- a/B09_Estimation/B09_Estimation_Linked.py +++ b/B09_Estimation/B09_Estimation_Linked.py @@ -6,7 +6,7 @@ 855-F B9-3)만 모음 — 단가 묶음 통째 (고르기 후보 전부)는 안 씀 · 값은 쓰지 않음(단가는 원가 한 벌 `price_book.json` 이 맡음) · 사본 일위대가 자재 · 굳힌 사전조합 자재 코드 · 고정 줄 이음 키도(183-1 · 705-1 · 로직을 안 돌아 `get` 에 안 걸림). -굳힌 SK(719-2) = 굳힌 키 로직 줄로 돌림(사본 `단가.json` · M01 안 읽음). +사본 SK(719-2) = 그 수식 사본 문서 셈 기록의 자원 키(`sk_answer` · 855-F B9-5). 고르기가 훑은 후보 줄도 걸림 → 원가 길이 두 번 셈해 쓰는 줄만 남김(`Summary.used_materials`). 구조물 조합 사본 없으면 그 구조물은 없음 · 일위대가 없는 사본은 자원 없음. """ @@ -48,9 +48,8 @@ def used_keys(folder: Path) -> list[str]: # 굳힌 참조사본 안 로직까지 doc = item_prices.with_values(labor.get("줄") or {}, values, picks) inner = [d for d in (labor.get("참조사본") or {}).values() if isinstance(d, dict)] - sks = [_sk_line(d) for d in inner if d.get("종류") == "단가산출" and "굳힌줄" in d] lines = [*(doc.get("담은로직") or []), *(x for d in inner for x in d.get("담은로직") or [])] - for one in [*lines, *sks]: + for one in lines: # 못 돈 로직 — 부른 데까지만(까닭은 안 봄) if isinstance(one, dict) and one.get("로직"): got = dr.solve( @@ -64,28 +63,36 @@ def used_keys(folder: Path) -> list[str]: mats = [*(doc.get("자재") or []), *(m for d in inner for m in d.get("자재") or [])] codes = [str(mat.get("코드") or "") if isinstance(mat, dict) else "" for mat in mats] codes += [k for d in [doc, *inner] for k in fixed.link_keys(d)] # 705-1 고정 줄 이음 - codes += [ # 굳힌 SK 고정 더한줄 이음(719-2) - k - for d in inner - for x in (d.get("굳힌줄") or {}).get("호표") or [] - if isinstance(x.get("고정"), dict) - for k in fixed.link_keys({"담은로직": [{"고정": x["고정"]}]}) - ] + for d in inner: # 사본 SK = 수식 사본 셈 기록(855-F B9-5) + got = sk_answer(d) + codes += got.resources if got else [] for code in codes: if code[:2] in RESOURCE_TABLES and code not in seen: seen.append(code) return seen -def _sk_line(doc: dict[str, Any]) -> dict[str, Any]: - """굳힌 SK(719-1) → 로직 줄 꼴 — 굳힌 키(사본 `단가.json` 로직) · 고름 cid → 차례.""" - from M02_MasterTemplete.M02_Sangeun_Doc import line_ids +def sk_answer(doc: Any) -> Any: + """사본 단가산출(SK · 855-F B9-5) 문서 셈 답(`Doc_Run.Answer` · 셈 기록) — 그 수식 사본(따로 · + M02 SK 셈과 같은 길 `M02_Doc_Sk.run` · 값 사본 · 덮음) · 수식 사본 없음(형제 · 옛 칸) · + 못 셈 = None.""" + from M02_MasterTemplete import M02_Doc_Copy as dc + from M02_MasterTemplete import M02_Doc_Sk as dsk - chosen = doc.get("고름") or {} - ids = line_ids(doc["굳힌줄"]) - picks = {str(n): chosen[cid] for n, cid in enumerate(ids) if cid in chosen} - one = {"로직": (doc.get("바탕") or {}).get("로직"), "입력값": doc.get("입력값")} - return {**one, "켜쌓기율": doc.get("켜쌓기율"), "고름": picks or None} + if not isinstance(doc, dict) or doc.get("종류") != "단가산출": + return None + try: + copy = dsk.copy_of(doc) + if copy is None or not isinstance(copy.get("문서"), dict): + return None + docs, whole = dc.docs_of(copy), dc.over(copy) + if dsk.dim.is_imported(doc): # 가져온 식 = 단가기준 셈(엑셀 값 · 기록 없음 = 줄 단가) + ans = dsk.run(doc, copy, whole) + else: + ans = dr.mt.calc(copy["문서"], dr.mt.Trace(whole, docs), {}, dc.cover_of(copy)) + except Exception: # noqa: BLE001 — 계산기 틈 · 못 짓는 사본 = 못 셈 + return None + return dr.Answer(whole, copy["문서"], ans, docs, {}) def _folders(project_root: str | Path, keep: set[str] | None = None) -> list[Path]: diff --git a/B09_Estimation/B09_Estimation_Refresh.py b/B09_Estimation/B09_Estimation_Refresh.py index dae1f2b4d..85904206c 100644 --- a/B09_Estimation/B09_Estimation_Refresh.py +++ b/B09_Estimation/B09_Estimation_Refresh.py @@ -8,8 +8,9 @@ 재적용 · 새 판 뒤에도 남음) · 노임 판(굳힌 판 → 지금 M01 판 · 옛 책 = 굳힌 날) 적용(`reapply_changed` → 부르는 쪽이 수요 다시 → `prices.refresh_book`) — 사본 먼저(수요가 바뀜) · 덮개(사용자 값)는 안 건드림 · 사본 하나가 막혀도 나머지는 함(막힌 것 = 알림). -M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 굳힌 SK 를 원본 층에서 다시 풀어 굳힘(같은 굳힌 키 · - 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로) · 서고 사본도 원본판이 다르면 다시 굳힘 · +M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 SK 수식 사본을 원본 층에서 다시 굳힘(같은 이름표 · + 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로 · 855-F B9-5) · + 서고 사본도 원본판이 다르면 다시 · 미리 보기 `단가산출` = 바뀌는 SK 줄 [{사본, 이름, 키, 판(새 · 바뀜 · 빠짐)}]. """ @@ -90,12 +91,12 @@ def _sks(labor: Any) -> dict[str, dict]: def sk_lines(old: Any, new: Any, where: str) -> list[dict[str, str]]: - """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(굳힌 줄 · 원본 SK 문서가 다름).""" + """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(SK 문서 · 수식 사본이 다름).""" was, now = _sks(old), _sks(new) out = [] for rid in sorted(set(was) | set(now)): a, b = was.get(rid) or {}, now.get(rid) or {} - if all(a.get(k) == b.get(k) for k in (item_sk.ROW, "원본")): + if a == b: continue mark = "새" if not a else "빠짐" if not b else "바뀜" out.append({"사본": where, "이름": (b or a).get("이름") or "", "키": rid.rsplit("|")[-1], diff --git a/B09_Estimation/B09_Estimation_Supply.py b/B09_Estimation/B09_Estimation_Supply.py index 63f727217..0f6a305a3 100644 --- a/B09_Estimation/B09_Estimation_Supply.py +++ b/B09_Estimation/B09_Estimation_Supply.py @@ -83,7 +83,7 @@ def sk_money(doc: dict, whole: Any, expand: Any, rid: str) -> dict[str, float] | try: got = calc.unit(doc, whole, expand, (rid,)).get("기준") - per = float(calc.ratio_of(doc, whole.logic(doc["바탕"]["로직"]), whole)) + per = float(calc.ratio_of(doc, calc._row_of(doc, whole), whole)) # 바탕 없음 = 1 except Exception: # noqa: BLE001 — M02 셈이 못 돌면 줄 합(옛 길) 그대로 return None if not got: diff --git a/M02_MasterTemplete/M02_Doc_B09.py b/M02_MasterTemplete/M02_Doc_B09.py index 8ac08fc40..3143da594 100644 --- a/M02_MasterTemplete/M02_Doc_B09.py +++ b/M02_MasterTemplete/M02_Doc_B09.py @@ -1,11 +1,11 @@ """B09 사본(구조물 · 서고)의 수식 문서 사본 `수식.json`(PLAN 802-4a 2 · 브레인 802-4a ①) — 서버 단독. 사본을 만들 때(`M02_Item_Source.build_source`) 단가 묶음 `단가.json` 옆에 함께 굳힘 — - {그룹: 수식문서, 문서: {키: 문서}} = 그 묶음의 로직 줄(담은 로직 · 하위 로직 · 굳힌 단가산출 GX9)이 + {그룹: 수식문서, 문서: {키: 문서}} = 그 묶음의 로직 줄(담은 로직 · 하위 로직 · SK 바탕 로직)이 닿는 닫힌 묶음 · 원본 일위대가 문서의 수식 사본 부름이 먼저(만든 때 것) · 없으면 묶음 줄 = 지금 M01 줄이면 M01 문서 · 다르면 그 줄 변환(`M02_Doc_Copy.doc_of`). [단가 갱신](값만) = 이 파일 안 고침 · [재생성](재적용) = 새로 찍음. -B09 셈은 지금 풀이(`단가.json` · 단가 책) 그대로 — 산근을 문서 셈으로 바꾸는 것은 802-6. +단가산출(SK) 셈 문서 = 참조사본 SK `수식`(따로 사본 · 855-F B9-5) — 이 파일엔 없음. 원본판(`version_of`)에는 안 듦(로직 줄은 `단가.json` 이 이미 잼 · 옛 사본이 거짓 「원본 바뀜」 안 뜸). """ diff --git a/M02_MasterTemplete/M02_Item_Sangeun.py b/M02_MasterTemplete/M02_Item_Sangeun.py index 8b0ad87b2..10d8acd82 100644 --- a/M02_MasterTemplete/M02_Item_Sangeun.py +++ b/M02_MasterTemplete/M02_Item_Sangeun.py @@ -1,42 +1,21 @@ -"""프로젝트 사본 — M02 단가산출(SK) 풀어 굳힘(PLAN 719-1 · 요구서 내역12 원칙 3 · 4장 14). +"""프로젝트 사본 — M02 단가산출(SK) 수식 문서 사본(PLAN 855-F B9-5 · 719-1). -사본을 만들 때(구조물 사본 `M02_Item_Source.build_source` · B09 서고 사본 `Bill_Library`) 굳힌 -참조사본 안 SK 문서마다 고친 줄(`M02_Sangeun_Calc.resolve` = 바탕 사슬 + 덮개 · 더한줄 · 뺀줄)을 -풀어 사본 `단가.json` 로직 줄 하나로 굳힘 — 사본 SK 문서는 그 줄만 바탕으로 가리킴(덮개 0 · -연결 끊김). 셈은 그대로 `M02_Sangeun_Calc` 한 벌(사본 색인 = 사본 `단가.json`). - -굳힌 키 = SK 참조 이름표(`ref_id` = 층 · 주인 · 키)에서 정해지는 `GX9#####`(해시 · 겹치면 -이름표 차례로 다음 번호) — 같은 SK = 같은 굳힌 키([업데이트] 때 B09 덮개 cover · cid · 입력값 · -고른자재가 짝을 안 잃음). 원본 층 문서는 읽기만. -사본 SK 문서 = {종류 · 키 · 이름 · 단위 · 구분 · 상세구분, 바탕 {로직: 굳힌 키}, 입력값(사슬 합), -열린입력, 켜쌓기율, 고름 · 자재표시(굳힌 줄 cid), 덮개 {}, 더한줄 [], 뺀줄 [], -굳힌줄(= 단가.json 줄), 원본(원래 SK 문서 · 「M02 에서 고침」 근거), 정체(굳힌 줄 차례 → 원본 -cid · 더한줄 = `add:#k`), 바탕판, 짝잃음}. -단가산출 속 일위대가(SC) · SK 더한줄 = 참조 줄 그대로 → 사본 셈이 굳힌 참조사본으로 펼침. +사본을 만들 때(구조물 사본 `M02_Item_Source.build_source` · B09 서고 사본 `Bill_Library`) +참조사본 안 SK 문서마다 지금 M02 셈 사본(`M02_Doc_Sk.copy_of` — 파생 · 따로 · 가져온 식 · +위 층 덮음 반영)을 `수식` 칸에 「따로」 로 굳힘 — 사본 셈 = M02 SK 셈 한 벌(따로 = 굳힌 문서 +그대로 · 기초 M01 문서를 다시 안 지음) · 수식 사본을 못 짓는 SK(바탕 참조 형제 · 옛 칸 고침) = +그대로(M02 처럼 못 셈 + 까닭). 원본 층 문서는 읽기만 · 굳힌 로직 줄(옛 `GX9…`) 없음. """ from __future__ import annotations -import hashlib from typing import Any -from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_Sangeun_Doc as sd -#: 사본 `단가.json` 안 굳힌 SK 줄 파일(`master_formula.Master` 가 그룹 「로직」 으로 읽음) -FILE = "로직_단가산출.json" -ROW = "굳힌줄" -_IMPORTED = "가져온" # 가져온 식 머리(`M02_Sangeun_Imported.KEY`) -_HEAD, _LOW, _SPAN = "GX", 900000, 99999 # GX900000 ~ GX999998(999999 = M01 저장 전 초안) - - -def frozen_key(rid: str, taken: set[str]) -> str: - """SK 이름표 → 굳힌 로직 키 — 해시 자리 · 이미 쓴 키면 다음 번호(제자리 `taken` 에 더함).""" - at = int(hashlib.sha256(rid.encode("utf-8")).hexdigest(), 16) % _SPAN - while (key := f"{_HEAD}{_LOW + at:06d}") in taken: - at = (at + 1) % _SPAN - taken.add(key) - return key +#: 사본 표지 — 셈이 위덮음 · M01 따라옴을 안 바꿈(`Doc_Sk.upper` · `Sk_AutoRenew.form` 이 읽음) +LOCK = "굳힘" +_FOLLOW = ("원본", "처음", "덮음바탕") # M02 자동 따라옴 기록(`M02_Sk_AutoRenew` FIRST · BASE) def is_sangeun(doc: Any) -> bool: @@ -44,133 +23,41 @@ def is_sangeun(doc: Any) -> bool: def freeze(copies: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: - """참조사본 `{ref_id: 문서}` → SK 를 풀어 굳힌 참조사본(새 묶음 · 받은 것 안 고침) · - 못 푼 SK(없는 바탕 · 순환) = 그대로(사본 셈이 까닭을 냄).""" - from M01_MasterData import M01_MasterData_Store as m01 - from M02_MasterTemplete import M02_Item_Prices as prices - from M02_MasterTemplete import M02_Sangeun_Calc as calc + """참조사본 `{ref_id: 문서}` → SK 마다 `수식` = 굳힌 따로 사본(새 묶음 · 받은 것 안 고침) · + SK 없음 = 받은 묶음 그대로.""" + from M02_MasterTemplete import M02_Doc_Sk as dsk sks = sorted(rid for rid, doc in copies.items() if is_sangeun(doc)) - if not sks and not any(_patched(doc) for doc in copies.values()): + if not sks: return copies - whole = m01.loaded()[1] - - def read(ref: dict) -> dict | None: - return copies.get(refs.ref_id(ref)) - - out, taken = dict(copies), set() + out = dict(copies) for rid in sks: doc = copies[rid] try: - got = calc.resolve(doc, whole, read, (rid,)) - except sd.DocError: - continue - key = frozen_key(rid, taken) - row = prices.to_json({**got["줄"], "키": key}) - ids = sd.line_ids(row) - frozen = {k: doc.get(k) for k in ("종류", "키", "이름", "단위", "구분", "상세구분")} - frozen |= { - "바탕": {"로직": key}, - "입력값": prices.to_json(got["입력값"]), - "열린입력": list(doc.get("열린입력") or []), - "고름": {ids[int(n)]: mt for n, mt in got["고름"].items()}, - "자재표시": {ids[int(n)]: one for n, one in got["자재표시"].items()}, - "덮개": {}, - "더한줄": [], - "뺀줄": [], - ROW: row, - "원본": doc, - "정체": list(got["정체"]), # 굳힌 줄 차례 → 원본 cid(B09 덮개 · 내 자료집 · 719-2) - "바탕판": got["바탕판"], - "짝잃음": got["짝잃음"], - } - if got["켜쌓기율"] is not None: - frozen["켜쌓기율"] = prices.to_json(got["켜쌓기율"]) - if isinstance(doc.get("수식"), dict): # 841-1 수식 문서(기계덮음) — 사본 셈 = M02 - frozen["수식"] = _upper(doc) # 848-1 ① 위덮음 = 굳힐 때 기초 것 - # 848-7 가져온 식 수식 고침(저장 문서) = 사본도 가져온 식 셈(단가기준 · 가져온 값 층) - if doc.get(_IMPORTED) and doc["수식"].get("따로"): - frozen[_IMPORTED] = doc[_IMPORTED] - out[rid] = frozen - for rid in sorted(rid for rid, doc in copies.items() if _patched(doc)): - out[rid] = _freeze_lines(rid, copies[rid], whole, read, taken) + got = dsk.copy_of(doc) + except Exception: # noqa: BLE001 — 못 짓는 사본 = 그대로(사본 셈이 M02 처럼 까닭을 냄) + got = None + if got is not None: # 따로 · M01 원본 표지 · 따라옴 기록 뺌(사본 = 굳힘 · 새 값 = [재생성]) + got = {k: v for k, v in got.items() if k not in _FOLLOW} + out[rid] = {**doc, dsk.KEY: dsk.norm({**got, "따로": True, LOCK: True})} return out -def _upper(doc: dict) -> dict: - """SK `수식` — ① 위 층 덮음을 굳힐 때 기초 것으로(848-1 · 가져온 식 · 기초 문서 없음 = 저장본).""" +def bundle_keys(copies: dict[str, Any]) -> tuple[list[str], list[str], list[dict]]: + """SK 사본 셈이 사본 단가 묶음(`단가.json`)에서 읽는 것 `(로직 키, 자원 키, 줄)` — + 바탕 로직(배 · 728-2) · 수식 사본 부름 문서 키(기계 덮음 작업량 식 포함) · 값 사본 자원 줄 키 · + 가져온 식 줄(셈 = 단가기준 · 사본 묶음 색인).""" + from M02_MasterTemplete import M02_Doc_Import as dim - from M02_MasterTemplete import M02_Doc_Sk as dsk - return doc["수식"] if dim.is_imported(doc) else dsk.with_upper(doc, doc["수식"], keep=True) - - -def _patched(doc: Any) -> list[int]: - """일위대가(SC) 사본의 덮개 줄(로직 줄 + `패치` · 740-1 SK 넣기 꼴) 차례.""" - if not isinstance(doc, dict) or doc.get("종류") != refs.TITLE["precombo"]: - return [] - lines = doc.get("담은로직") or [] - return [ - n for n, x in enumerate(lines) if isinstance(x, dict) and x.get("로직") and x.get("패치") - ] - - -def _freeze_lines(rid: str, doc: dict, whole: Any, read: Any, taken: set[str]) -> dict: - """SC 사본 덮개 줄마다 고친 줄을 풀어 굳힘(740-1 · B09 대가 · 사본 셈이 덮개를 읽게) — - 줄은 그대로 두고 덧칸 `굳힌 {키, 줄, 입력값, 켜쌓기율, 고름, 자재표시, 정체}`(고름 · - 자재표시 = 굳힌 줄 차례) · 못 푼 줄 = 그대로(사본 셈이 옛 길).""" - from M02_MasterTemplete import M02_Item_Prices as prices - from M02_MasterTemplete import M02_Labor_Patch as patch - from M02_MasterTemplete import M02_Sangeun_Calc as calc - from M02_MasterTemplete.M02_Labor_Expand import Expand - - lines = list(doc.get("담은로직") or []) - for n in _patched(doc): - one = lines[n] - try: - doc_ = sd.clean(patch.as_doc(one, whole), None, whole) - got = calc.resolve(doc_, whole, read, (rid,), line=True) # 일위대가 기본 별도계상 - row = {**got["줄"], "호표": [dict(x) for x in got["줄"]["호표"]]} - calc._bundles(row, whole, Expand(whole, read), (rid,)) # 고정 더한줄 = 값묶음 - except sd.DocError: - continue - key = frozen_key(f"{rid}#{n}", taken) - fz = {"키": key, "줄": prices.to_json({**row, "키": key}), "정체": list(got["정체"])} - fz |= { - "입력값": prices.to_json(got["입력값"]), - "고름": got["고름"], - "자재표시": got["자재표시"], - } - if got["켜쌓기율"] is not None: - fz["켜쌓기율"] = prices.to_json(got["켜쌓기율"]) - lines[n] = {**one, FROZEN: fz} - return {**doc, "담은로직": lines} - - -FROZEN = "굳힌" - - -def rows(copies: dict[str, Any]) -> list[dict[str, Any]]: - """굳힌 SK 줄 + SC 덮개 줄 굳힌 줄(740-1) — 사본 `단가.json` `FILE` 에 넣음(이름표 차례).""" - out = [doc[ROW] for _, doc in sorted(copies.items()) if is_sangeun(doc) and ROW in doc] - for _, doc in sorted(copies.items()): - out += [ - x[FROZEN]["줄"] - for x in doc.get("담은로직") or [] - if isinstance(x, dict) and x.get(FROZEN) - ] - return out - - -def materials(copies: dict[str, Any]) -> list[str]: - """굳힌 SK 고른 자재 키 — 단가 묶음에 담음.""" - out = [ - str(mt) - for doc in copies.values() - if is_sangeun(doc) - for mt in (doc.get("고름") or {}).values() - ] + logic, res, rows = [], [], [] for doc in copies.values(): - lines = [x for x in doc.get("담은로직") or [] if isinstance(x, dict) and x.get(FROZEN)] - out += [str(mt) for x in lines for mt in (x[FROZEN].get("고름") or {}).values()] - return out + if not is_sangeun(doc): + continue + copy = doc.get("수식") if isinstance(doc.get("수식"), dict) else {} + logic += [str((doc.get("바탕") or {}).get("로직") or "")] + logic += [str(k) for k in (copy.get("부름") or {})] + res += [str(r.get("키")) for r in copy.get("단가") or [] if isinstance(r, dict)] + if dim.is_imported(doc) and isinstance((doc.get("가져온") or {}).get("로직"), dict): + rows.append(doc["가져온"]["로직"]) + return [k for k in dict.fromkeys(logic) if k], list(dict.fromkeys(res)), rows diff --git a/M02_MasterTemplete/M02_Item_Source.py b/M02_MasterTemplete/M02_Item_Source.py index 6ac0aa147..3e4dcf009 100644 --- a/M02_MasterTemplete/M02_Item_Source.py +++ b/M02_MasterTemplete/M02_Item_Source.py @@ -5,7 +5,7 @@ `일위대가.json` = 층 `labor/<열id>.json` 문서(39-1c · 없으면 옛 UA 조합 줄 · 규격 열 = summary_item `spec` 열 수량을 손으로 굳힘 · 704-4) + 담은 로직 줄(M01 시스템) + 알약(가져온 때 그대로) + - 참조사본(단가승격 · 사전조합을 값으로 굳힘 · 단가산출 SK = 풀어 굳힌 로직 줄 719-1) · + 참조사본(단가승격 · 사전조합을 값으로 굳힘 · 단가산출 SK = 수식 문서 사본 따로 · 855-F B9-5) · `단가.json` 계산에 닿는 마스터 줄 전부(담은 로직 + 일위대가 자재 MT) `원본판` = 모은 내용의 해시 — 지금 층 · 마스터에서 다시 모은 판과 대어 「마스터가 바뀜」 을 앎. 프로젝트가 고치는 값(`입력값.json` · `고른자재.json`)은 원본이 아니라 여기서 안 모음. @@ -98,7 +98,7 @@ def labor_doc_rows(doc: dict[str, Any]) -> dict[str, Any]: from M02_MasterTemplete import M02_Labor_Ref as refs rows = {**logic_rows(doc), "알약": labor_doc.pills(doc)} - copies = sk.freeze(refs.frozen(doc)) # 단가산출(SK) = 풀어 굳힌 로직 줄(719-1) + copies = sk.freeze(refs.frozen(doc)) # 단가산출(SK) = 수식 문서 사본(855-F B9-5) return {**rows, "참조사본": copies} if copies else rows @@ -160,17 +160,19 @@ def build_source(item: dict[str, Any]) -> dict[str, Any]: def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: - """사본 단가 묶음(`단가.json`) — 담은 로직 · 굳힌 참조 로직 · 자재 · 고른 자재 · 사전조합 자재 · - 개인 자재(`root` = 원본 층 · B09 설계내역서 서고 사본도 이 길 · 204-2).""" + """사본 단가 묶음(`단가.json`) — 담은 로직 · 굳힌 참조 로직 · SK 바탕 로직 · 자재 · 고른 자재 · + 사전조합 자재 · 개인 자재(`root` = 원본 층 · B09 설계내역서 서고 사본도 이 길 · 204-2) · + SK 셈 = 그 수식 사본(굳힌 SK 로직 줄 없음 · 855-F B9-5).""" from M02_MasterTemplete import M02_Item_Prices as prices from M02_MasterTemplete import M02_Item_Sangeun as sk from M02_MasterTemplete import M02_Labor_Fixed as fixed from M02_MasterTemplete import M02_Labor_Ref as refs copies = (labor or {}).get("참조사본") or {} - sk_rows = sk.rows(copies) # 굳힌 단가산출 줄(719-1) — 그 줄이 닿는 마스터 줄도 모음 logic_keys = [str(one.get("키")) for one in (labor or {}).get("로직", [])] logic_keys += refs.frozen_logics(copies) # 굳힌 단가승격 로직 + sk_logic, sk_res, sk_rows = sk.bundle_keys(copies) # SK 수식 사본 셈이 읽는 줄(855-F B9-5) + logic_keys += sk_logic doc = (labor or {}).get("줄") or {} materials = [str(m.get("코드")) for m in doc.get("자재") or []] materials += [ # 고른 로직 자재(103-1) 품목 줄도 — 복사본 계산이 그 단가를 씀 @@ -178,7 +180,7 @@ def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: ] materials += refs.frozen_materials((labor or {}).get("참조사본") or {}) # 175-2 사전조합 자재 materials += fixed.link_keys(doc) # 705-1 고정 줄이 잇는 노임 · 자재 · 기계 - materials += sk.materials(copies) + materials += sk_res wanted = logic_keys + [code for code in materials if code] over = copy_rows([doc, *copies.values()]) # M02 로직 사본(795-4) = 만든 때 줄 먼저 bundle = ( @@ -186,8 +188,6 @@ def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: if wanted or sk_rows else {} ) - if sk_rows: - bundle[sk.FILE] = {"그룹": "로직", "원문": "자체", "줄": sk_rows} if mine := own.bundle( [c for c in materials if own.is_own(c)], root ): # 개인 자재(148-3 · 사전조합 것도 175-2) — 원본 목록이 바뀌어도 사본 그대로 diff --git a/resources/tester/golden_855_b09.json b/resources/tester/golden_855_b09.json index 36d1c81f4..41a824a0b 100644 --- a/resources/tester/golden_855_b09.json +++ b/resources/tester/golden_855_b09.json @@ -3,8 +3,8 @@ "지문": { "키": "e68369418202e5ee", "calc_user": "6d74551273d6735f", - "daega_inputs": "a06884bce408c602", - "수요": "5fdf7c49052e322c", + "daega_inputs": "f9269299e609306d", + "수요": "23b0132a8a7f46f7", "산근 값": "38455c2edce885ff", "산근 글": "c41b0c2e4ae200fb", "산근 관급 값": "d154925ee64c985c", diff --git a/resources/tester/test_719_1_sk_freeze.py b/resources/tester/test_719_1_sk_freeze.py index fd82867e7..913efac26 100644 --- a/resources/tester/test_719_1_sk_freeze.py +++ b/resources/tester/test_719_1_sk_freeze.py @@ -1,18 +1,22 @@ -"""719-1 프로젝트 사본 — M02 단가산출(SK) 풀어 굳힘(`M02_Item_Sangeun` · `M02_Item_Source` · -`M02_Item_Prices` · `B09_Estimation_Bill_Library`) — 임시 storage(견본 층 · 실제 M01 읽기만). +"""719-1 · 855-F B9-5 프로젝트 사본 — M02 단가산출(SK) 수식 문서 사본(`M02_Item_Sangeun` · +`M02_Item_Source` · `M02_Item_Prices` · `B09_Estimation_Bill_Library`) — 임시 storage(견본 층 · +실제 M01 읽기만). -구조물 사본 · B09 서고 사본 셈 = M02 층 SK 셈 · 굳힌 줄은 사본 `단가.json` 로직 줄 · 원본 SK 를 -지워도 같은 값 · 같은 SK = 같은 굳힌 키(다시 복사 · SK 고친 뒤도) · 원본 층 지문 그대로 · -서고 manifest 원본판 = SK 바뀌면 다름. +사본 SK = 원래 SK 문서 + `수식` 따로 사본(덮음 · 고친 문서 반영) · 굳힌 로직 줄(옛 GX9 · +`로직_단가산출.json`) 없음 · 구조물 사본 · B09 서고 사본 셈 = M02 층 SK 셈 · 원본 SK 를 지우거나 +M02 에서 고쳐도 사본 값 그대로([재생성] = 새 값) · 원본 층 지문 그대로 · 서고 원본판 = 다시 모아도 +같음 · SK 고치면 다름 · 수식 사본을 못 짓는 SK(옛 칸) = 그대로(M02 처럼 못 셈). """ # ruff: noqa: F811 — 임시 층 fixture `world` 를 들여 씀 +import copy import hashlib import json import pytest from B09_Estimation import B09_Estimation_Bill_Library as library +from M02_MasterTemplete import M02_Doc_Sk_Path as sk_path from M02_MasterTemplete import M02_Item_Prices as prices from M02_MasterTemplete import M02_Item_Sangeun as sk from M02_MasterTemplete import M02_Item_Source as source @@ -22,9 +26,6 @@ from M02_MasterTemplete import M02_MasterTemplete_Store as store from resources.tester.test_715_sangeun_store import PCT, _sk from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층 -COVER = {"labor:LB000036#0": {"qty": 0.5}} -ADD = [{"종류": "인력", "요소": "LB000002", "수량": 0.1}] - def _print(folder): """층 폴더 지문 — 파일 이름 · 바이트.""" @@ -40,12 +41,33 @@ def _top(ref, qty=2): return doc, labor.calc(doc, {})["줄"][0] +def edit(folder, key, times=2): + """M02 수식 길에서 SK 문서를 고침(따로) — 첫 금액 줄 수량 × times.""" + with store.at(folder): + read = sk_path.read(key) + doc = copy.deepcopy(read["문서"]) + doc["금액"][0]["수량"] = f"({doc['금액'][0].get('수량') or 1}) × {times}" + sk_path.save(key, {"문서": doc, "판": read["판"]}) + + def _mine(world): - key = _sk(world["personal"], 바탕={"로직": PCT}, 덮개=COVER, 더한줄=ADD) + """SK = 바탕 로직 + M02 에서 고친 문서(따로).""" + key = _sk(world["personal"], 바탕={"로직": PCT}) + edit(world["personal"], key) return key, {"folder": world["personal"], "ref": {**MINE, "키": key}} -def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): +def _rows(bundle): + return [ + row + for part in bundle.values() + if isinstance(part, dict) + for row in part.get("줄") or part.get("표") or [] + if isinstance(row, dict) + ] + + +def test_구조물_사본_수식_사본_값_같음_원본_지우고_고쳐도(world): key, ref = _mine(world) doc, live = _top(ref) assert not live["까닭"] and live["기준"]["계"] > 0 @@ -53,16 +75,20 @@ def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): rows = source.labor_doc_rows(doc) bundle = source.price_bundle(rows, world["personal"]) assert _print(world["personal"]) == before # 원본 층 안 건드림 - rid = refs.ref_id(ref["ref"]) - frozen = rows["참조사본"][rid] - fk = frozen["바탕"]["로직"] - assert fk == sk.frozen_key(rid, set()) and fk.startswith("GX9") - assert frozen["덮개"] == {} and frozen["더한줄"] == [] and frozen["뺀줄"] == [] - assert frozen["원본"]["덮개"]["labor:LB000036#0"]["qty"] == 0.5 # 고친 근거 - assert [r["키"] for r in bundle[sk.FILE]["줄"]] == [fk] + frozen = rows["참조사본"][refs.ref_id(ref["ref"])] + assert ( + frozen["바탕"] == {"로직": PCT} + and frozen["수식"]["따로"] is True + and frozen["수식"][sk.LOCK] + ) + assert "굳힌줄" not in frozen and "원본" not in frozen + assert "로직_단가산출.json" not in bundle + assert not [r for r in _rows(bundle) if str(r.get("키")).startswith("GX9")] json.dumps(rows["참조사본"], ensure_ascii=False) # 사본 파일로 쓸 수 있는 꼴(Decimal 없음) + saved = json.loads(json.dumps(bundle, ensure_ascii=False)) + edit(world["personal"], key, 3) # M02 에서 다시 고침 → 사본 그대로 (world["personal"] / "sangeun" / f"{key}.json").unlink() # 원본이 사라져도 사본만 봄 - got = prices.calc(rows, json.loads(json.dumps(bundle, ensure_ascii=False)), {}, {}, None) + got = prices.calc(rows, saved, {}, {}, None) line = got["줄"][0] assert not line["까닭"] for part in ("노무비", "재료비", "경비", "계"): @@ -70,30 +96,28 @@ def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): assert line["반영"]["계"] == pytest.approx(live["반영"]["계"], rel=1e-9) -def test_같은_SK_같은_굳힌_키_다른_SK_다른_키(world): +def test_재생성은_M02_새_값(world): key, ref = _mine(world) doc, _ = _top(ref) + first = source.labor_doc_rows(doc) + edit(world["personal"], key, 3) + _, live = _top(ref) + again = source.labor_doc_rows(doc) + bundle = source.price_bundle(again, world["personal"]) + got = prices.calc(again, json.loads(json.dumps(bundle, ensure_ascii=False)), {}, {}, None) + assert got["줄"][0]["기준"]["계"] == pytest.approx(live["기준"]["계"], rel=1e-9) rid = refs.ref_id(ref["ref"]) - first = source.labor_doc_rows(doc)["참조사본"][rid]["바탕"]["로직"] - with store.at(world["personal"]): # SK 를 고쳐도 굳힌 키 그대로(B09 덮개 짝 지킴) - now = store.read("sangeun", key) - store.write("sangeun", key, now["판"], {**now["문서"], "덮개": {}}) - again = source.labor_doc_rows(doc)["참조사본"][rid] - assert again["바탕"]["로직"] == first and again["원본"]["덮개"] == {} - other = refs.ref_id({"층": "company", "주인": "7", "키": key}) # 같은 번호 다른 층 - assert sk.frozen_key(other, set()) != first - taken = {first} - assert sk.frozen_key(rid, taken) != first and len(taken) == 2 # 겹치면 다음 번호 + assert first["참조사본"][rid]["수식"]["문서"] != again["참조사본"][rid]["수식"]["문서"] def test_B09_서고_사본_값_같음_원본판(world, tmp_path): - _, ref = _mine(world) + key, ref = _mine(world) with store.at(world["personal"]): sc = refs.create( "precombo", {"이름": "조합", "단위": "㎡", "담은로직": [{"참조": ref["ref"], "수량": {"손": 2}}]}, )["이름"] - # 742-1 = SC 안 줄 수량(손 2) 저장 → 굳힌 사본 = 저장 2 · 쓰는 쪽 알약 값(2)이 앞섬(층 · 사본 같은 값) + # 742-1 = SC 안 줄 수량(손 2) 저장 → 사본 = 저장 2 · 쓰는 쪽 알약 값(2)이 앞섬(층 · 사본 같은 값) pill = f"{refs.ref_id({**MINE, '키': sc})}#0" with store.at(world["personal"]): top = labor.clean( @@ -119,15 +143,28 @@ def test_B09_서고_사본_값_같음_원본판(world, tmp_path): assert library.source_version(built) == mark # 다시 모아도 같은 판 again = library.import_copy(root, "precombo", "personal", "7/42", sc) assert again == {"폴더": made["폴더"], "만듦": False} - with store.at( - world["personal"] - ): # 811-1 — SC 안 SK = 참조 한 행(안 펼침) → SK 고치면 원본판 바뀜 = 사본 [업데이트] 대상 - now = store.read("sangeun", ref["ref"]["키"]) - store.write("sangeun", ref["ref"]["키"], now["판"], {**now["문서"], "덮개": {}}) + edit( + world["personal"], key, 3 + ) # 811-1 SC 안 SK = 참조 한 행 → SK 고치면 원본판 바뀜 = [재생성] 대상 assert library.source_version(library._build("precombo", "personal", "7/42", sc)[0]) != mark def test_SK_없는_사본_그대로(): """SK 없는 참조사본 = 받은 묶음 그대로(기존 사본 · 공사 금액 전후 같음).""" copies = {"x": {"종류": "사전조합", "담은로직": []}} - assert sk.freeze(copies) is copies and sk.rows(copies) == [] and sk.materials(copies) == [] + assert sk.freeze(copies) is copies and sk.bundle_keys(copies) == ([], [], []) + + +def test_옛_칸_SK_는_그대로_못_셈(world): + """수식 사본을 못 짓는 SK(옛 칸 덮개 · 855 2-C1) = 그대로 · 사본 셈 = M02 처럼 까닭.""" + key = _sk(world["personal"], 바탕={"로직": PCT}, 덮개={"labor:LB000036#0": {"qty": 0.5}}) + ref = {"folder": world["personal"], "ref": {**MINE, "키": key}} + doc, live = _top(ref) + rows = source.labor_doc_rows(doc) + frozen = rows["참조사본"][refs.ref_id(ref["ref"])] + assert not (frozen.get("수식") or {}).get("따로") + bundle = json.loads( + json.dumps(source.price_bundle(rows, world["personal"]), ensure_ascii=False) + ) + got = prices.calc(rows, bundle, {}, {}, None)["줄"][0] + assert live["까닭"] and got["까닭"] and got["기준"] is None diff --git a/resources/tester/test_719_2_sk_project.py b/resources/tester/test_719_2_sk_project.py index 5593213fb..4d304fe6d 100644 --- a/resources/tester/test_719_2_sk_project.py +++ b/resources/tester/test_719_2_sk_project.py @@ -1,12 +1,12 @@ -"""719-2 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · 산근 · [업데이트] · 내 자료집 SK(임시 storage · -실제 M01 읽기만). +"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · [재생성](업데이트) · 서고(임시 +storage · 실제 M01 읽기만). -- 굳힌 SK = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 금액 = M02 SK 셈 · 단가산출 속 일위대가 줄 = - 사전조합 블록을 부르는 줄 · 로직 더한줄의 하위 로직 = 산근 목록(`Sangeun.rows_of`) -- [업데이트] = SK 고친 뒤 다시 굳힘 — 굳힌 키 · cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · - 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 · - 미리 보기 SK 줄 -- 내 자료집 = SK 블록 · 품셈 블록 → 개인 층 SK(B09 덮개 = SK 덮개) → 서고로 다시 불러와 같은 금액 +- 사본 SK(수식 따로 사본) = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 줄 = 문서 답 금액 줄 + (M02 에서 고친 문서 그대로) · 금액 = M02 SK 셈 +- [재생성] = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · + 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 + · 미리 보기 SK 줄 +(옛 칸 덮개 · 더한줄 SK · 내 자료집 = 옛 칸 SK 만들기는 855 2-C1 셈 은퇴 — 시험 없음) """ # ruff: noqa: F811 — 임시 층 fixture `world` 를 들여 씀 @@ -15,7 +15,6 @@ import json import pytest from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Daega_Personal as personal from B09_Estimation import B09_Estimation_Prices as prices from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun @@ -28,13 +27,12 @@ from M02_MasterTemplete import M02_Item_Snapshot as snapshots from M02_MasterTemplete import M02_Item_Source as source from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_MasterTemplete_Store as store -from resources.tester.test_145_2_b09_labor_calc import STONE, _item, _project, _snap +from resources.tester.test_145_2_b09_labor_calc import STONE, _item, _project from resources.tester.test_715_sangeun_store import PCT, _calc, _sk +from resources.tester.test_719_1_sk_freeze import edit from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층 TWO_MATS = "GC000565" # 재료 줄 둘(고른자재 열쇠) -COVER = {"labor:LB000036#0": {"qty": 0.5}} -PRICE = {"labor:LB000002#0": {"labor": 200000}} OWNER = "7/42" @@ -42,33 +40,11 @@ def _json(value): return json.loads(json.dumps(value, ensure_ascii=False, default=str)) -def _sc(world, lines): - with store.at(world["personal"]): - doc = {"이름": "속 일위대가", "단위": "㎡", "담은로직": lines} - return refs.create("precombo", doc)["이름"] - - -def _mine(world, full=False): - """SK = 품 덮개 · 인력 더한줄 · 로직 더한줄(하위 산근) · full = 단가 덮개 + SC 더한줄.""" - added = [ - {"종류": "인력", "요소": "LB000002", "수량": 0.1}, - {"종류": "로직", "로직": PCT, "입력값": {}, "수량": 0.5}, - ] - cover = COVER - if full: - sc = _sc(world, [{"로직": PCT, "수량": {"손": 1}}]) - added.append({"참조": {**MINE, "키": sc}, "수량": 2}) # 단가산출 속 일위대가 - cover = {**COVER, **PRICE} - return _sk(world["personal"], 바탕={"로직": PCT}, 덮개=cover, 더한줄=added) - - -def _engine_ready(world): - """엔진 입력 덧칸(715-1b `단가` · `값묶음`)이 붙었나 — 아니면 M02 도 못 셈.""" - key = _sk( - world["personal"], 이름="엔진", 바탕={"로직": PCT}, 덮개={"labor:LB000002#0": {"labor": 1}} - ) - got = _calc(world["personal"], key) - return not got.get("까닭") and got["줄"][1]["단가"] == 1 +def _mine(world): + """SK = 바탕 로직 + M02 에서 고친 문서(따로 · 첫 줄 수량 × 2).""" + key = _sk(world["personal"], 바탕={"로직": PCT}) + edit(world["personal"], key) + return key def _b09(root, cover=None): @@ -88,62 +64,29 @@ def _lib(world, tmp_path, key, kind="sangeun"): return root, made["폴더"] -def _set_cover(world, key, cover): - with store.at(world["personal"]): - now = store.read("sangeun", key) - store.write("sangeun", key, now["판"], {**now["문서"], "덮개": cover}) - - def _same_money(block, live): assert block["sum"] == pytest.approx(float(live["1단위"]["계"]), abs=5) # 끝수(내림)만 다름 for part, name in (("labor", "노무비"), ("material", "재료비"), ("expense", "경비")): assert block[part] == pytest.approx(float(live["1단위"][name]), abs=3) -def test_SK_대가_블록_금액_M02_같음_하위_산근(world, tmp_path): +def test_SK_대가_블록_금액_M02_같음(world, tmp_path): key = _mine(world) live = _calc(world["personal"], key) assert not live.get("까닭") and live["1단위"]["계"] > 0 root, folder = _lib(world, tmp_path, key) - daega, done, sg_rows = _b09(root) + daega, done, _ = _b09(root) block = done[daega["libs"][folder]] assert block["cover"].startswith("P:") and block["kind"] == "품셈" lines = block["lines"] assert all(ln.get("sk") for ln in lines) - assert lines[0]["kind"] == "labor" and lines[0]["qty"] == 0.5 - assert lines[0]["poom"] == {"qty": 0.018, "단가": 233250} # M02 에서 고친 줄 = 품셈 값 곁 - assert "poom" not in lines[1] - sub = next(ln for ln in lines if ln["kind"] == "sangeun") - assert sub["key"] in sg_rows and sub["key"].startswith(f"SG:{PCT}") and sub["qty"] == 0.5 + assert lines[0]["kind"] == "labor" and lines[0]["key"] == "LB000036" + assert lines[0]["qty"] == pytest.approx(0.036) # M02 에서 고친 문서 = 품셈 0.018 × 2 + assert lines[-1]["kind"] == "pct" and lines[-1]["base"] == "part:labor" _same_money(block, live) -def test_SK_단가_덮개_속_일위대가_펼침(world, tmp_path): - # 715-1b 엔진 입력 덧칸(단가 · 값묶음) — 못 세면 건너뛰지 않고 실패 - assert _engine_ready(world), "M02 SK 셈이 단가 덮개를 못 셈(715-1b 엔진 입력 덧칸)" - key = _mine(world, full=True) - # 740-1 — 속 일위대가 = 넣을 때 펼쳐 담음(SC 로직 줄 = 로직 더한줄 · 본뜬) → 빠진 줄 없음 - live = _calc(world["personal"], key) - added = _added(world, key) - assert live["빠진줄"] == [] and not any("참조" in x for x in added) - assert added[-1]["로직"] == PCT and added[-1]["본뜬"]["키"].startswith("SC-") - root, folder = _lib(world, tmp_path, key) - daega, done, _ = _b09(root) - block = done[daega["libs"][folder]] - lines = block["lines"] - assert lines[1]["kind"] == "fixed" and lines[1]["prices"]["labor"] == pytest.approx(200000) - assert block["blank"] == 0 - _same_money(block, live) - - -def _added(world, key): - with store.at(world["personal"]): - return store.read("sangeun", key)["문서"]["더한줄"] - - -def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳힌키_그대로( - world, tmp_path, monkeypatch -): +def test_구조물_사본_SK_줄_재생성_덮개_입력값_고른자재_그대로(world, tmp_path, monkeypatch): key = _mine(world) ref = {**MINE, "키": key} with store.at(world["personal"]): @@ -184,18 +127,17 @@ def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳 }.items(): (folder / name).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") rid = refs.ref_id(ref) - frozen_key = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] - frozen_key = frozen_key["바탕"]["로직"] + was = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] daega, _, _ = _b09(root) combo = next(b for b in daega["blocks"] if b["id"] == daega["owners"]["pipe@100.0"]) sk_block = next(b for b in daega["blocks"] if b["id"] == combo["lines"][0]["key"]) cid = sk_block["lines"][0]["cid"] cover = {sk_block["cover"]: {cid: {"qty": 0.9}}} - # SK 고침(품 0.5 → 0.7) → [재적용](업데이트) = 다시 풀어 굳힘 - _set_cover(world, key, {**COVER, "labor:LB000036#0": {"qty": 0.7}}) + # SK 고침(품 × 2 → × 2 × 3) → [재적용](재생성) = 수식 사본 다시 굳힘 + edit(world["personal"], key, 3) item_copy.reapply(root, folder.name) after = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] - assert after["바탕"]["로직"] == frozen_key # 굳힌 키 그대로 + assert after["수식"]["문서"] != was["수식"]["문서"] and after["수식"]["따로"] assert ( json.loads((folder / snapshots.VALUES_FILE).read_text("utf-8"))["GF000219"] == (values["GF000219"]) @@ -205,7 +147,7 @@ def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳 block = next(b for b in done.values() if b["cover"] == sk_block["cover"]) line = block["lines"][0] assert line["cid"] == cid and line["covered"] == ["qty"] and line["qty"] == 0.9 - assert line["base"]["qty"] == 0.7 # 덮개 밑 = 새 단가산출 값(「단가산출 값으로」 되돌림 값) + assert line["base"]["qty"] == pytest.approx(0.108) # 덮개 밑 = 새 단가산출 값(0.018 × 6) assert daega2["owners"]["pipe@100.0"] in done @@ -215,7 +157,7 @@ def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): assert library.changed(root) == [] before = daega_inputs(root) cover_key = next(b for b in before["blocks"] if b["id"] == before["libs"][folder])["cover"] - _set_cover(world, key, {**COVER, "labor:LB000036#0": {"qty": 0.7}}) + edit(world["personal"], key, 3) got = refresh.preview(root, None, [], None) assert [(x["키"], x["판"]) for x in got["단가산출"]] == [(key, "바뀜")] assert [c["폴더"] for c in got["사본"]] == [folder] @@ -223,53 +165,4 @@ def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): assert library.changed(root) == [] and [f.name for f, _ in library.copies(root)] == [folder] after = daega_inputs(root) block = next(b for b in after["blocks"] if b["id"] == after["libs"][folder]) - assert block["cover"] == cover_key and block["lines"][0]["qty"] == 0.7 - - -def test_내_자료집_SK_왕복_같은_금액(world, tmp_path): - key = _mine(world) - root, folder = _lib(world, tmp_path, key) - daega, _, _ = _b09(root) - block = next(b for b in daega["blocks"] if b["id"] == daega["libs"][folder]) - first, second = block["lines"][0]["cid"], block["lines"][1]["cid"] - priced = {block["cover"]: {first: {"qty": 0.9}, second: {"labor": 210000}}} - made = personal.build(root, block["cover"], priced, "내 SK 2") - doc = made["문서"] - assert doc["종류"] == "단가산출" and doc["바탕"] == {"로직": PCT} - assert doc["덮개"]["labor:LB000036#0"] == {"qty": 0.9} - assert "labor:LB000002#0" not in doc["덮개"] # 841-1 단가 칸 = 안 읽음 · 안 담음 - assert doc["더한줄"][0]["요소"] == "LB000002" - assert made["담음"]["품"] == 1 and made["담음"]["단가"] == 0 - third = block["lines"][2]["cid"] # 더한줄 인력 = 그 더한줄 수량 - cover = {block["cover"]: {first: {"qty": 0.9}, third: {"qty": 0.3}}} - doc = personal.build(root, block["cover"], cover, "내 SK 2")["문서"] - assert doc["더한줄"][0]["수량"] == 0.3 and doc["덮개"] == {"labor:LB000036#0": {"qty": 0.9}} - _, done, _ = _b09(root, cover) - want = done[daega["libs"][folder]]["sum"] - with store.at(world["personal"]): - new = personal.write(doc)["이름"] - with pytest.raises(store.StoreError) as same: - personal.write(doc) - assert same.value.status == 409 and same.value.detail["같은이름"] == new - assert new.startswith("SK-") and new != key - root2, folder2 = _lib(world, tmp_path / "b", new) - daega2, done2, _ = _b09(root2) - assert done2[daega2["libs"][folder2]]["sum"] == pytest.approx(want, abs=2) - - -def test_내_자료집_품셈_블록_SK(world, tmp_path): - root = _project(tmp_path / "proj", [(100, "SS000901")]) - _snap(root, "pipe@100.0", "SS000901", [{"로직": PCT, "승격": True, "수량": {"손": 1}}], {}) - daega = daega_inputs(root) - top = next(b for b in daega["blocks"] if b["id"] == daega["owners"]["pipe@100.0"]) - block = next(b for b in daega["blocks"] if b["id"] == top["lines"][0]["key"]) - assert block["kind"] == "품셈" and block["origin"]["로직"] == PCT - cover = {block["cover"]: {block["lines"][0]["cid"]: {"qty": 0.5}}} - doc = personal.build(root, block["cover"], cover, "내 해체")["문서"] - assert doc["바탕"] == {"로직": PCT} and doc["단위"] == "㎡" - assert doc["덮개"] == {"labor:LB000036#0": {"qty": 0.5}} - with store.at(world["personal"]): - new = personal.write(doc)["이름"] - plain = _sk(world["personal"], 이름="견줌", 바탕={"로직": PCT}, 덮개=doc["덮개"]) - a, b = _calc(world["personal"], new), _calc(world["personal"], plain) - assert a["1단위"]["계"] == b["1단위"]["계"] > 0 + assert block["cover"] == cover_key and block["lines"][0]["qty"] == pytest.approx(0.108) diff --git a/resources/tester/test_778_4_rate_line.py b/resources/tester/test_778_4_rate_line.py index 0d8345aa3..6aa681008 100644 --- a/resources/tester/test_778_4_rate_line.py +++ b/resources/tester/test_778_4_rate_line.py @@ -185,20 +185,6 @@ def test_B09_율_기준_밑수_꼴(): assert source.fixed_line(rate, 2, {"y": 4, "x": 1})["base"] == "rows:1,4@labor" -def test_B09_SK_블록_율_줄_pct(): - whole = _whole() - adds = [{"종류": "인력", "요소": "LB000003", "수량": 0.1}, _rate("인력")] - adds.append(_rate(["labor:LB000002#0", "add:#1"], 5, "재료비", "목록")) - doc = sd.clean({**_doc(adds), "바탕": {"로직": SUB}, "단위": "주"}, None, whole) - build = source.Builder() - bid = build.sangeun(whole, {"층": "project", "키": "SK-000001"}, {**doc, "굳힌줄": {}}, {}) - lines = build.blocks[bid]["lines"] - pct = {ln["name"]: ln for ln in lines if ln["kind"] == "pct"} - assert pct["공구손료"]["base"] == "bundle:labor" and pct["공구손료"]["qty"] == 2 - assert pct["목록"]["base"] == "rows:1,4" and pct["목록"]["part"] == "material" - assert [ln["kind"] for ln in lines[:5]] == ["labor", "labor", "machine", "labor", "pct"] - - BLOCK = { "id": "DGR", "cover": "S:r", "kind": "조합", "name": "율 블록", "spec": "", "unit": "㎥", "cite": "", "origin": {}, diff --git a/resources/tester/test_792_3_engine_paths.py b/resources/tester/test_792_3_engine_paths.py index c06e7ac3b..7afbbd7f7 100644 --- a/resources/tester/test_792_3_engine_paths.py +++ b/resources/tester/test_792_3_engine_paths.py @@ -3,7 +3,7 @@ ① 엔진 직접(`master_cut.engine`) · ② M02 단가산출 SK 셈(`M02_Sangeun_Calc.run`) · ③ 일위대가 SC 한 줄(수량 1 · `M02_Labor_Doc.calc`) · ④ B09 산근 풀이(`B09_Estimation_Sangeun.Solver` · 841-1 단가 = M02 엔진) · -⑤ B09 일위대가 대가 블록(SC → 굳힌 SK 참조 수량 1 · `Labor_Source.Builder` → `Calc_Labor` 파이썬 · +⑤ B09 일위대가 대가 블록(SC → 사본 SK 참조 수량 1 · `Labor_Source.Builder` → `Calc_Labor` 파이썬 · TS 짝 · 내역 단가 `daega_price`)에서 같은 금액. 실무 견본(봉화 D00102 · 북부청임도 18)은 793-2 길(가져온 식 SK · 임시 층)로 만들어 ⑤ = 엑셀. @@ -115,7 +115,7 @@ OWNER = "pipe@100.0" # `test_145_2._ts` 가 내역 단가를 읽는 구조물 i def _daega(whole, sk: dict, sheets: dict) -> dict: - """⑤ SC(굳힌 SK 참조 수량 1) → 대가 블록 → 파이썬 셈 = TS 짝 → 내역 단가.""" + """⑤ SC(사본 SK 참조 수량 1) → 대가 블록 → 파이썬 셈 = TS 짝 → 내역 단가.""" from resources.tester.test_145_2_b09_labor_calc import _same, _ts sk_ref, sc_ref = {"층": "project", "키": "SK-990001"}, {"층": "project", "키": "SC-990001"} @@ -132,11 +132,27 @@ def _daega(whole, sk: dict, sheets: dict) -> dict: return {PART[p]: D(str(price[p])) for p in PART} +def _copy(doc: dict, master) -> dict: + """사본 SK(855-F B9-5 · `Item_Sangeun.freeze` 꼴) = SK 문서 + 수식 따로 사본 — 견본 로직은 + M01 문서 밖이라 문서 = 견본 줄 변환 · 값 사본 = 견본 줄 전부.""" + from M02_MasterTemplete import M02_Doc_Copy as dc + from M02_MasterTemplete import M02_Doc_Sk as dsk + from M02_MasterTemplete import M02_Item_Prices as prices + + rows = [r for part in master.index.values() for r in part.values()] + logic = prices.to_json([r for r in rows if "호표" in r]) + res = prices.to_json([r for r in rows if "호표" not in r]) + values = {"판": sc.skc._fp(logic), "로직": logic, "단가판": sc.skc._fp(res), "단가": res} + key = doc["바탕"]["로직"] + docs = dc.closure(master, [key]) + root = {**docs[key], "키": doc["키"]} + return {**doc, dsk.KEY: dsk.norm({**values, "따로": True, "문서": root, "부름": docs})} + + def _b09_daega(build) -> dict: master, row, _ = build() - sk = {"종류": sd.TITLE, "키": "SK-990001", "이름": "시험", "단위": "식", - "바탕": {"로직": _key(row)}, "입력값": {}, "덮개": {}, "더한줄": [], "뺀줄": [], - item_sk.ROW: row, "정체": []} # fmt: skip + doc = {"키": "SK-990001", "이름": "시험", "단위": "식", "바탕": {"로직": _key(row)}} + sk = _copy(sd.clean(doc, None, master), master) files = master.index sheets = { "labor": [{"key": k, "price": float(r["값"])} for k, r in files.get("LB", {}).items()], @@ -167,7 +183,7 @@ REAL = [("봉화", "D00102"), ("북부청임도", 18)] @pytest.mark.parametrize(("tag", "code"), REAL) def test_실무_가져온_식_SK_대가_내역_엑셀(tag, code, world): - """793-2 길 — 경쟁사 블록 → 가져온 식 SK(임시 층) → 굳힘 → SC 줄 → B09 대가 → + """793-2 길 — 경쟁사 블록 → 가져온 식 SK(임시 층) → 사본(수식 따로) → SC 줄 → B09 대가 → 내역 단가 = 엑셀.""" from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_MasterTemplete_Store as store @@ -181,10 +197,9 @@ def test_실무_가져온_식_SK_대가_내역_엑셀(tag, code, world): whole = m01.loaded()[1] rid = "project||SK-990001" frozen = item_sk.freeze({rid: sd.clean(doc, None, whole)})[rid] - key, row = frozen["바탕"]["로직"], json.loads(json.dumps(frozen[item_sk.ROW])) - assert ms_uses(row) # 새 의미 로직(줄 자리 · 번지 · 단계) + assert frozen["수식"]["따로"] and ms_uses(frozen["가져온"]["로직"]) # 새 의미(줄 자리 · 번지) books = {"labor": [], "material": [], "machine": [], "gaps": []} # 엑셀 단가 = 고정 줄 - got = _daega(sc._Over(whole, key, row), frozen, books) + got = _daega(whole, frozen, books) excel = {k: D(str(round(v))) for k, v in out["원본"]["엑셀금액"].items()} assert got == excel diff --git a/resources/tester/test_793_2_sangeun_imported.py b/resources/tester/test_793_2_sangeun_imported.py index d4efcf548..088cce60b 100644 --- a/resources/tester/test_793_2_sangeun_imported.py +++ b/resources/tester/test_793_2_sangeun_imported.py @@ -12,7 +12,6 @@ from __future__ import annotations import copy -import json from decimal import Decimal import pytest @@ -302,14 +301,12 @@ class _Priced: def _frozen_total(doc, whole): rid = "personal|7/42|SK-000001" - frozen = sk.freeze({rid: sd.clean(doc, None, _whole())})[rid] - key, row = frozen["바탕"]["로직"], json.loads(json.dumps(frozen[sk.ROW])) - assert key.startswith("GX9") and frozen["원본"][imp.KEY]["로직"] - over = calc._Over(whole, key, row) - return float(calc.run(sd.clean(frozen, None, over), over)["1단위"]["계"]) + frozen = sk.freeze({rid: sd.clean(doc, None, _whole())})[rid] # 사본 = 수식 따로(855-F B9-5) + assert frozen["수식"]["따로"] and frozen[imp.KEY]["로직"] + return float(calc.run(frozen, whole)["1단위"]["계"]) -def test_B09_굳힘_단가_전파(): +def test_B09_사본_엑셀_값_우리_값_굳힘(): whole = _whole() excel, ours = _doc(), imp.to_price(_doc(), "우리")["문서"] assert _frozen_total(excel, whole) == 45652 @@ -317,7 +314,7 @@ def test_B09_굳힘_단가_전파(): assert _frozen_total(ours, whole) == live up = _Priced(whole, MAN, float(whole.get(MAN)["값"]) + 50000) assert _frozen_total(excel, up) == 45652 # 엑셀 단가 그대로 = 안 바뀜 - assert _frozen_total(ours, up) == pytest.approx(live + 50000 * 2 / 50 * 1.01, abs=2) + assert _frozen_total(ours, up) == live # 사본 = 굳힌 값(855-F B9-5 · 새 값 = [재생성]) covered = _doc(덮개={"labor:형틀목공#0": {"qty": 0.2}}) assert _frozen_total(covered, whole) == _total(covered)