Files
Aislo/M02_MasterTemplete/M02_Item_Bundle.py
T

154 lines
6.6 KiB
Python

"""프로젝트 사본 단가 묶음(`단가.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
import master_doc as md # noqa: E402 — scripts 길 = prices(m01)
from M02_MasterTemplete import M02_Item_Prices as prices
_HOLE = re.compile(r"\{([^{}]+)\}")
def _options(ids: dict, hole: str) -> list | None:
opts = ((ids.get(hole) or {}).get("연결") or {}).get("목록")
return [str(x).strip("'") for x in opts] if opts else None
class _Docs(prices._Collector):
"""수식 문서가 잇는 자원 · 표 줄 키 모음."""
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]:
"""틀 글 `{변수}` 구멍 → 고르기 목록으로 끼운 글들 · 목록 없는 구멍 = 그 테이블 전부(빈 목록)."""
out = [text]
for hole in sorted(set(_HOLE.findall(text))):
opts = _options(ids, hole)
if opts 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 []
out = [one.replace(f"{{{hole}}}", x) for one in out for x in opts]
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 = _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():
if data.get("그룹") == "로직":
continue
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:
return self._whole.logic(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