Files
Aislo/M02_MasterTemplete/M02_Labor_Expand.py
T
eomsangdonandClaude Opus 5.5 d9e6ec9ca1 feat(859-4): 일위대가 두 판 셈 — 문서 본뜬.단가기준 엑셀 = 고정 줄 줄 단가 그대로 · 우리 = 이은 비목 단가 책 값
- Labor_Fixed.line 판 받음 · basis_of(본뜬.단가기준 엑셀 | 우리 · 없음 = 지금 셈)
- Labor_Doc.calc · Labor_Expand = 판을 고정 줄 · 하위 SC · 가져온 식 SK 참조에 넘김(부르는 쪽 › SC 자기 판)
- 판 없는 문서 = 그대로(아직 판을 다는 길 없음 · 다음 묶음)
- 새 지킴 test_859_4_hopyo_basis(엑셀 판 = 줄 단가 · 우리 판 = 단가 책 · 펼침 판 차례)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:38:56 +09:00

275 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""M02 서고 참조 펼침(계산) — `M02_Labor_Ref.Expand` 를 떼어 둠(PLAN 715-2 · 700 줄).
참조 → `{이름, 단위, 기준(1 단위), 까닭, 안?}` — 단가승격(옛 SP) · 사전조합(SC) · 단가산출(SK ·
`M02_Sangeun_Calc.unit`). 이름은 `M02_Labor_Ref.Expand` 로 그대로 부름.
사전조합 안 줄 수량(742-1) 차례 — 층 문서 = 알약 값(쓰는 쪽 `given` 「참조|층|주인|키#차례」 · 자재 =
「…#자재|코드」 · `inner_pills`) → 저장 손 · 굳힌 사본(`hands` · 프로젝트) = 굳힌 손(옛 사본 · 707-7) →
알약 값 → 저장(`refs.SAVED`) · 비율 줄 = 율 · 모두 없으면 「수량 없음」(1 아님 · 그 사전조합 기준 없음).
"""
from __future__ import annotations
from collections.abc import Callable
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Labor_Copy as lc
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 import M02_Sangeun_Calc as calc
Ref = dict[str, Any]
NO_QTY = "수량 없음"
MAT = "자재|"
class Expand:
"""참조 → `{이름, 단위, 기준(1 단위), 까닭, 안?}` — 한 번 셈 안에서 키별 캐시 ·
깊이 상한 · 순환은 까닭(통째로 멈추지 않음). `read` = 참조 → 문서(프로젝트는 굳힌 사본)."""
def __init__(
self,
whole: Any,
read: Callable[[Ref], dict | None] = refs.read_ref,
given: dict[str, Any] | None = None,
hands: bool | None = None,
) -> None:
self.whole, self.read, self.memo = whole, read, {}
self.basis: str | None = None # 판(859-4) — 부르는 쪽 · 없으면 SC 자기 `본뜬.단가기준`
self.given = given or {}
self.hands = (
read is not refs.read_ref if hands is None else hands
) # 층 원본 손 = 옛 값(안 씀)
def _qty(self, one: dict, key: str) -> Decimal | None:
"""안 줄 수량 — 굳힌 손(사본) · 비율 줄 율 → 알약 값(given) → 저장 수량(층 손 · 사본 `저장`)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
qty = one.get("수량") if isinstance(one.get("수량"), dict) else {}
hand = labor._number(qty.get("손"))
if hand is not None and (self.hands or refs.is_rate(one)):
return hand
got = labor._number(self.given.get(key))
if got is not None:
return got
return labor._number(qty.get(refs.SAVED)) if self.hands else hand
def __call__(
self, ref: Ref, trail: tuple[str, ...] = (), basis: str | None = None
) -> dict[str, Any]:
"""`basis` = 가져온 식 SK(797-1 산근 속 산근) · SC 고정 줄(859-4)을 부르는 쪽 단가기준(엑셀 | 우리)으로 셈."""
basis = basis or self.basis
rid = refs.ref_id(ref)
if rid in trail:
keys = [t.rsplit("|", 1)[-1] for t in (*trail, rid)]
return self._stop(ref, "순환 — " + " → ".join(keys))
if len(trail) >= refs.DEPTH:
return self._stop(ref, f"참조가 {refs.DEPTH}단을 넘음")
memo = f"{rid}|{basis}" if basis else rid
if memo not in self.memo:
doc = self.read(ref)
if not isinstance(doc, dict):
return self._stop(ref, f"없는 참조 「{ref['키']}」")
if refs.kind_of(ref["키"]) == "promote":
self.memo[memo] = self._promote(doc)
elif refs.kind_of(ref["키"]) == "sangeun": # 단가산출(715-2) = 고친 줄 셈 1 단위
from M02_MasterTemplete import M02_Sangeun_Imported as imp
if basis and imp.is_imported(doc):
doc = {**doc, "가져온": {**doc["가져온"], "단가기준": basis}}
self.memo[memo] = calc.unit(doc, self.whole, self, (*trail, rid))
else: # 사전조합 = 그 SC 로직 사본(795-2) · 판 = 부르는 쪽 › 자기 것(859-4)
was, self.basis = self.basis, basis or fixed.basis_of(doc)
try:
self.memo[memo] = lc.combo(self, doc, (*trail, rid))
finally:
self.basis = was
return self.memo[memo]
@staticmethod
def _stop(ref: Ref, why: str) -> dict[str, Any]:
return {"이름": ref["키"], "단위": None, "기준": None, "까닭": why}
def _promote(self, doc: dict) -> dict[str, Any]:
"""옛 단가승격(SP · 134-2 앞 꼴 · 저장소 0) — 로직 줄과 같은 문서 셈(`Labor_Copy.line` · 855 2-C5) ·
로직 재료 = 직접계산(별도계상 안 뺌 · 옛 셈과 같음) · 사본 옛 엔진 갈래 걷음(855-E 2-E4)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
line = (doc.get("담은로직") or [{}])[0]
code = str(line.get("로직") or "")
money = (dc.doc_of(self.whole, code) or {}).get(
"금액"
) or [] # 문서 금액 줄 차례 = 호표 차례
direct = {"별도계상": "직접계산"}
marks = {str(n): direct for n, x in enumerate(money) if x.get("비목") == "재료비"}
got = lc.line(self.whole, {}, {**line, "로직": code, "자재표시": marks})
times = labor._number(doc.get("배")) or Decimal(1)
base = got.get("기준")
why = got.get("까닭") or (None if base else "돈 아닌 로직")
return {
"이름": doc.get("이름"),
"단위": doc.get("단위"),
"로직": line.get("로직"),
"기준": {k: Decimal(str(v)) / times for k, v in base.items()} if base else None,
"까닭": why,
# 원 로직 줄(줄 누름 하위 행 · 51-2) — 1 단위로 나눔(하위 합 = 기준)
"줄": [
{
**x,
**{
k: None if x.get(k) is None else Decimal(str(x[k])) / times
for k in ("수량", "금액")
}, # 문서 줄 = 빈 값 있음
"비목": {k: Decimal(str(v)) / times for k, v in (x.get("비목") or {}).items()},
}
for x in got.get("줄") or []
],
}
def _logic(self, one: dict, pill: dict | None, doc: dict | None = None) -> dict[str, Any]:
"""사전조합 안 로직 줄 — 일위대가 로직 줄과 같은 `Labor_Copy.line`(문서 셈) · 배는 물량 알약 것 ·
사본 굳힌 덮개 줄(`굳힌` · B9-5 뒤 0) 옛 엔진 갈래 걷음(855-E 2-E4)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
pill = pill or {}
if one.get(patch.FIELD): # 줄 덮개(715-3) = 이름 없는 단가산출 · 별도계상까지
got = patch.run(self.whole, one, self.read)
else: # 별도계상 로직 자재 뺌(222-1) · 수식 사본 SC = 문서 셈(802-4a)
got = lc.line(self.whole, doc or {}, one)
times = labor._number(pill.get("배")) or Decimal(1)
base = got.get("기준")
return {
"이름": pill.get("이름") or one["로직"],
"단위": pill.get("단위"),
"기준": {k: Decimal(str(v)) / times for k, v in base.items()} if base else None,
"까닭": got.get("까닭") or (None if base else "돈 아닌 로직"),
}
def _combo(self, doc: dict, trail: tuple[str, ...]) -> dict[str, Any]:
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M02_MasterTemplete import M02_Labor_Doc as labor
lines = [one for one in doc.get("담은로직") or [] if isinstance(one, dict)]
kept = doc.get("알약") # 프로젝트 참조사본 = 가져온 때 굳힌 알약(142-2) · 층 = 지금 M01
pills = kept if isinstance(kept, list) else None
by_logic = {
code: pill
for pill in pills or combo_store.combo_pills({"담은로직": lines})["물량"]
for code in pill["로직"]
}
inner, rows, why, rid = [], [], None, trail[-1] if trail else ""
keyed: list[dict] = [] # 율 밑 줄(778-4 · `fixed.rate_base`)
for at, one in enumerate(lines):
ref = one.get("참조")
if isinstance(ref, dict): # 줄 덮개(715-3) 있는 SK 참조 = 그 줄만 다시 셈
head = {"참조": ref}
sub = self(ref, trail) if not one.get(patch.FIELD) else patch.ref(one, self)
elif one.get("로직"): # 로직 줄(51-11) = 1 단위 값(기준 ÷ 배 · 승격과 같음) · 덮개 있음
head, sub = {"로직": one["로직"]}, self._logic(one, by_logic.get(one["로직"]), doc)
elif fixed.is_fixed(one): # 고정 줄(705-3) = 줄 단가 · 비율 줄 = 끝에(`ratio_row`)
head, sub = {"고정": one["고정"]}, fixed.line(self.whole, one["고정"], self.basis)
else:
continue
qty = self._qty(one, f"{rid}#{at}")
keep = ("이름", "단위", "기준", "까닭")
inner.append({**head, "수량": qty, **{k: sub.get(k) for k in keep}})
if sub.get("기준") is None:
why = why or f"「{sub.get('이름')}」 {sub.get('까닭')}"
continue
if qty is None: # 742-1 — 저장 · 이은 값 없음 = 금액 빠짐(1 로 안 셈)
inner[-1]["까닭"] = NO_QTY
why = why or f"「{sub.get('이름')}」 {NO_QTY}"
continue
rows.append(labor.mcut.row({k: v * qty for k, v in sub["기준"].items()}))
if not refs.is_rate(head):
keyed.append(fixed.rate_row(head, labor.line_id(head), rows[-1]))
for mat in doc.get("자재") or []: # 사용자 자재(175-2) = 기준단가 × 수량(이은 값)
if labor.apart(mat): # 별도계상 = 안 셈 · 안 줄에도 없음(222-1)
continue
qty = self._qty(mat, f"{rid}#{MAT}{mat['코드']}")
got = labor.material_price(self.whole, mat["코드"], mat.get("단위"))
price = labor._number(got["기준단가"])
zero = dict.fromkeys(labor.COSTS, Decimal(0))
base = None if price is None else {**zero, "재료비": price, "계": price}
name = mat.get("이름") or mat["코드"]
inner.append(
{
"자재": mat["코드"],
"수량": qty,
"이름": name,
"단위": mat.get("단위"),
"기준": base,
"까닭": got["까닭"],
}
)
if qty is None or base is None:
inner[-1]["까닭"] = got["까닭"] or NO_QTY # 단가 까닭 먼저
why = why or f"「{name}」 {inner[-1]['까닭']}"
continue
rows.append(labor.mcut.row({k: v * qty for k, v in base.items()}))
keyed.append({"키": None, "묶음": "재료", "비목": rows[-1]})
for one in inner: # 비율 고정 줄(705-3) — 밑 = `rate_base`(778-4)
if rate := (one.get("고정") or {}).get("비율"):
under = fixed.rate_base(rate["기준"], keyed)
one["기준"], row = fixed.ratio_row(rate, one["수량"], under)
rows.append(row)
if row:
keyed.append(fixed.rate_row(one, labor.line_id(one), row, True))
return {
"이름": doc.get("이름"),
"단위": doc.get("단위"),
"머리": head_of(doc),
"기준": None if why else labor.mcut.sums(rows), # 줄 0.1 원 · 합 1 원 버림(751-3)
"까닭": why,
"안": inner,
}
def head_of(doc: dict) -> str | None:
"""상세 머리 「1 ㎡ 당」(715-3 · 일위대가 = 기준단위 1 당) — 단위 빈 옛 문서는 None."""
unit = str(doc.get("단위") or "").strip()
return f"1 {unit} 당" if unit else None
def inner_pills(
ref: Ref, read: Callable[[Ref], dict | None] = refs.read_ref, depth: int = 1
) -> list[dict[str, Any]]:
"""사전조합 안 줄 알약(723-1) — 키 「참조|…#차례」 · 「참조|…#자재|코드」 · 이름 = 「일위대가 · 줄」 ·
단위 = 그 줄 분모 · 비율 줄 뺌 · 안의 사전조합도 한 번씩(깊이 상한) · 사전조합 아니면 빈 것."""
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
doc = read(ref) if refs.kind_of(ref["키"]) == "precombo" and depth <= refs.DEPTH else None
if not isinstance(doc, dict):
return []
rid, top = refs.ref_id(ref), doc.get("이름") or ref["키"]
lines = [one for one in doc.get("담은로직") or [] if isinstance(one, dict)]
by_logic = {
code: pill
for pill in combo_store.combo_pills({"담은로직": lines})["물량"]
for code in pill["로직"]
}
out: list[dict[str, Any]] = []
for at, one in enumerate(lines):
if refs.is_rate(one):
continue
sub = one.get("참조")
if isinstance(sub, dict):
got = read(sub) or {}
name, unit = got.get("이름") or sub["키"], got.get("단위")
out += inner_pills(sub, read, depth + 1)
elif fixed.is_fixed(one):
name, unit = one["고정"].get("이름"), one["고정"].get("단위")
else:
pill = by_logic.get(one.get("로직")) or {}
name, unit = pill.get("이름") or one.get("로직"), pill.get("단위")
name = one.get("별칭") or name
out.append({"키": f"{rid}#{at}", "이름": f"{top} · {name}", "단위": unit or "", "로직": [], "참조": ref}) # fmt: skip
for mat in doc.get("자재") or []:
name = mat.get("이름") or mat.get("코드")
key = f"{rid}#{MAT}{mat.get('코드')}"
out.append({"키": key, "이름": f"{top} · {name}", "단위": mat.get("단위") or "", "로직": [], "참조": ref}) # fmt: skip
seen: set[str] = set()
return [p for p in out if not (p["키"] in seen or seen.add(p["키"]))]