"""프로젝트 사본 단가 묶음(`단가.json`) — 수식 문서 묶음이 잇는 자원 · 표 줄만(PLAN 855-F B9-6). 사본 = `수식.json`(셈 정본 · 닫힌 문서 묶음) + `단가.json`(자원 · 표 줄 — [단가 갱신] 이 바꾸는 자리) · M01 로직 줄은 사본에 안 실음. 모으기 = 문서 변수 연결을 훑음(옛 로직 줄 식 글 훑기 대신): 표 = 그 표 · 요소 키 = 그 줄(`{변수}` 틀 구멍 = 그 변수 고르기 목록으로 끼움 · 못 끼우면 그 테이블 전부 · 자재품목 뺌) · 재료 조건 = 후보 줄(구멍 = 목록 · 못 끼우면 구멍 칸 뺀 조건 · 지역 · 계약종별 「입력」 = 넓게) · 준용 · 연결 줄도(`M02_Item_Prices._Collector.add`). 셈 색인(`load`) = 묶음 색인 + 문서 이름표 — `logic(키)` = 문서의 이름 · 결과단위 · 입력 이름(SK 배 · B09 줄 꼴이 읽음 · 로직 줄 셈 칸 없음) · `docs` = 그 문서 묶음(`M02_Doc_Copy.doc_of` 가 먼저 읽음). """ from __future__ import annotations import re from typing import Any from M02_MasterTemplete import M02_Item_Prices as prices import master_doc as md # noqa: E402 — scripts 길 = prices(m01) 뒤에 import master_machine_crew as crew # noqa: E402 _HOLE = re.compile(r"\{([^{}]+)\}") class _Docs(prices._Collector): """수식 문서가 잇는 자원 · 표 줄 키 모음.""" def options(self, ids: dict, hole: str, depth: int = 0) -> list | None: """구멍 변수의 값 후보 — 고르기 목록 · 요소 칸을 읽는 변수(「EQ:{기계}」 의 조종원직종 등) = 그 틀을 끼운 줄마다 그 칸 값(옛 식 글 훑기 `_expand` 와 같은 뜻) · 모름 = None.""" link = (ids.get(hole) or {}).get("연결") or {} if isinstance(link.get("목록"), list): # 빈 목록 = 끼울 값 없음(옛 `_choices` 와 같음) return [str(x).strip("'") for x in link["목록"]] if link.get("갈래") != "요소" or not link.get("키") or not link.get("칸") or depth > 3: return None keys = self._filled(str(link["키"]), ids, depth + 1) if keys is None: return None out = [] for key in keys: try: row = self.whole.get(key) except prices.mf.FormulaError: continue vals = row.get("값") or {} # 줄 값 — 기계 = 인력 · 잡품 목록을 칸으로(842-3) vals = crew.view(vals) if str(row.get("키"))[:2] == "EQ" else vals value = vals.get(link["칸"]) if isinstance(vals, dict) else None if value not in (None, ""): out.append(str(value)) return list(dict.fromkeys(out)) def _filled(self, text: str, ids: dict, depth: int = 0) -> list[str] | None: """틀 글 → 끼운 글들 · 못 끼움 = None.""" out = [text] for hole in sorted(set(_HOLE.findall(text))): opts = self.options(ids, hole, depth) if opts is None: return None out = [one.replace(f"{{{hole}}}", x) for one in out for x in opts] return out def doc(self, doc: dict) -> None: ids = {md.var_id(v): v for v in doc.get("변수") or []} for v in ids.values(): link = v.get("연결") or {} if link.get("갈래") == "표" and link.get("표"): self.add(str(link["표"])) elif link.get("갈래") == "요소" and isinstance(link.get("재료"), dict): self.cond(link["재료"], link.get("단위"), ids) elif link.get("갈래") == "요소" and link.get("키"): for ref in self.fill(str(link["키"]), ids): self.add(ref) def fill(self, text: str, ids: dict) -> list[str]: """틀 글 `{변수}` 구멍 → 값 후보로 끼운 글들(`options`) · 못 끼움 = 그 테이블 전부(빈 목록).""" out = self._filled(text, ids) if out is None: tid = prices.mk.id_of(text) if tid and tid not in prices._TOO_BIG: self.keys.update(self.whole.index.get(tid, {})) return [] return out def cond(self, cond: dict, unit: Any, ids: dict) -> None: if cond.get("지역") == "입력" or cond.get("계약종별") == "입력": self.widely(cond, unit) return variants = [cond] holes = {h for v in cond.values() if isinstance(v, str) for h in _HOLE.findall(v)} for hole in sorted(holes): opts = self.options(ids, hole) if opts is None: variants = [prices.mm.static(cond)] break variants = [ { k: v.replace(f"{{{hole}}}", x) if isinstance(v, str) else v for k, v in one.items() } for one in variants for x in opts ] for one in variants: if one.get("대표"): self.add(str(one["대표"])) if one.get("구분") or one.get("검색어"): for key in prices._candidates(self.whole, one): self.add(key) def collect( docs: dict[str, dict], materials: list[str] | None = None, over: list[dict] | None = None ) -> dict[str, Any]: """문서 묶음 `docs` 가 잇는 자원 · 표 줄 + 자재(MT)의 닫힌 단가 묶음 — 로직 줄 없음 · `over` = M02 값 사본 줄(795-4 · 같은 키는 M01 줄 대신 · M01 에 없는 키 = `COPY_FILE`).""" from M02_MasterTemplete import M02_Material_Own as mat files, whole = prices.master() whole = mat.whole(prices.mym.whole(whole)) # 지금 층 내 기계(821-1) · 내 재료(840-4) own = {str(r.get("키")): r for r in (*prices.mym.added(whole), *mat.added(whole))} mine = {str(r.get("키")): r for r in over or [] if "호표" not in r and "흐름" not in r} if mine: from M02_MasterTemplete import M02_Sangeun_Copy as skc whole = skc.Copy(whole, skc._rows({"로직": list(mine.values())})) got = _Docs(whole) for doc in docs.values(): got.doc(doc) for code in materials or []: got.add(code) out: dict[str, Any] = {} seen: set[str] = set() for name, data in files.items(): slot = prices.m01.items_key(data) rows = [ mine.get(str(row.get("키")), row) for row in data.get(slot) or [] if str(row.get("키")) in got.keys ] seen.update(str(row.get("키")) for row in rows) if rows: out[name] = {**{k: v for k, v in data.items() if k != slot}, slot: rows} left = [r for k, r in {**own, **mine}.items() if k in got.keys and k not in seen] if left: out[prices.COPY_FILE] = {"그룹": "사본", "줄": left} if got.missing: out["_빠진"] = sorted(set(got.missing)) return out class Index: """사본 셈 색인 — 단가 묶음 색인 위 문서 이름표(`logic`) · 문서 묶음(`docs`) · 그 밖 그대로.""" def __init__(self, whole: Any, docs: dict[str, dict]) -> None: self._whole, self.docs = whole, docs def logic(self, key: str) -> dict: doc = self.docs.get(str(key)) if doc is None: # 문서 묶음 밖 = 없는 기초(855-E L3 — 로직 줄 안 읽음) raise prices.mf.FormulaError(f"없는 요소 「{key}」") names = prices.doc_inputs(doc) row = {k: doc.get(k) for k in ("키", "이름", "결과단위", "출처")} return {**row, "입력": [{"이름": n} for n in names], "호표": [], "중간": [], "덧줄": []} def __getattr__(self, name: str) -> Any: return getattr(self._whole, name) def __setattr__(self, name: str, value: Any) -> None: if name in ("_whole", "docs"): object.__setattr__(self, name, value) else: setattr(self._whole, name, value) def load(bundle: dict[str, Any], docs: dict[str, dict] | None) -> Any: """`단가.json` + 문서 묶음 → 사본 셈 색인(문서 없음 = 묶음 색인 그대로).""" whole = prices.load_prices(bundle) return Index(whole, docs) if docs else whole