Files
Aislo/B09_Estimation/B09_Estimation_Doc_Run.py
T
eomsangdonandClaude Opus 5.5 d254b4b555 refactor(855-F B9-3): B09 산근 · 대가 · 수요 키가 옛 엔진 대신 문서 셈 답 + 셈 기록을 읽음
- 새 B09_Estimation_Doc_Run — 사본 수식 문서를 M02 와 같은 계산기로 셈 → 줄마다 수량 · 단가 · 비목 · 자원 키 · 품목 · 하위 부름 · % 율 · 끝수
- Sangeun 풀이(_solve · _line · _logic_line · _extras · call_of · line_calls · hand_resource_keys) · Labor_Source._poomsem · Linked.used_keys = 문서 셈 답 · 기록
- Sangeun_Sum doc_* = 답 끝수 · 합밖(새 계산기 cut · _settle) · 옛 함수와 _env · _captured 는 산출근거 글 몫(B9-4)
- Labor_Rule 식 꼴 읽기 = 새 계산기 파서 · 작업량 Q ROUND 2 · 빈 입력 멈춤 · 굳은 기계 단가 기계 키 살림
- master_doc_trace 감싼 색인 메서드 찾기 한 줄(굳힌 단가산출 대가 블록)
- test_855_trace 옛 하위 부름 기준 = helper_855_engine.old_line_calls(옛 함수 옮김)
- 골든 855_b09 다시 뜸 7 갈래 — 기계 시간당 단가 = M02 문서 셈 값(옛 = 엔진 날 값 · 줄 0.1 원 · 합 1 원 다를 수 있음) · 수요 키에서 재료 고르기 후보 빠짐 · 글 · 나머지 8 갈래 같음
- 옛 엔진 부름 B09(글 뺌) 19 → 6 · 719-1 · 719-2 실패 5 는 옛 칸 SK 견본(B9-5 몫 · 고치기 전에도 같음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:01:29 +09:00

268 lines
12 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.
"""B09 산근 · 대가 풀이의 셈 한 벌 — 수식 문서 셈 답 + 셈 기록(PLAN 855-F B9-3) · 서버 단독(짝 없음).
M02 와 같은 계산기(`master_doc_calc` · 기록 `master_doc_trace`)로 사본 문서(`수식.json` · 없는 키 =
그 자리 닫힌 묶음 · `M02_Item_Prices.line` 같은 길 · 줄 규칙 `line_doc`)를 셈 → B09 가 읽는 꼴:
줄 = 금액 줄마다 {이름, 단위, 수량, 단가, 비목(날 값 = 수량 × 단가 · 끝수 전), 금액(날 합), 까닭,
합밖, 키(노임 · 자재 · 기계 자원 키), 품목(고른 재료 줄), 부름(하위 산근 {code, given} |
기계경비 {machine})}
`pct(n)` = % 줄 (율, 밑 이름) · `rules` = 답 `끝수` · `settle` = 블록 비목 합 끝수(새 계산기 것)
B09 고유 셈 = 비목 합 · 끝수 · 관급 0 원 · % 밑수(옛 엔진 · 옛 식 풀이 안 부름).
"""
from __future__ import annotations
import importlib
from decimal import Decimal
from pathlib import Path
from typing import Any
from M02_MasterTemplete import M02_Doc_Copy as dc # scripts 길을 둠
from M02_MasterTemplete.M02_Item_Source import read_json
md = importlib.import_module("master_doc")
mc = importlib.import_module("master_doc_calc")
ml = importlib.import_module("master_doc_link")
mt = importlib.import_module("master_doc_trace")
FILE = "수식.json"
COSTS = ("노무비", "재료비", "경비")
INPUTS = ("입력", "선택", "숫자") # 입력 갈래 연결
def docs_of(folder: Path) -> dict[str, dict]:
"""사본 `수식.json` 문서 {키: 문서} — 없으면 빈 것(셈 때 그 자리 닫힌 묶음)."""
got = read_json(Path(folder) / FILE)
return dict((got or {}).get("문서") or {}) if isinstance(got, dict) else {}
def _num(value: Any) -> Decimal | None:
return value if isinstance(value, Decimal) else None
class Answer:
"""문서 셈 답 한 벌 — 옛 엔진 줄 꼴(`줄`)로 갈라 읽음."""
def __init__(self, whole: Any, doc: dict, ans: dict, docs: dict, given: dict) -> None:
self.whole, self.doc, self.ans, self.docs, self.given = whole, doc, ans, docs, given
self.vars = {md.var_id(v): v for v in doc.get("변수") or []}
self.rules = ans.get("끝수") or {}
self.lines = [
self._line(n, dl, out)
for n, (dl, out) in enumerate(zip(doc.get("금액") or [], ans.get("줄") or []))
]
@property
def stopped(self) -> str | None:
"""블록 통째로 못 셈 까닭 — 셈 멈춤(없는 요소 · 순환 …) · 빈 입력(옛 엔진도 입력에서 멈춤)."""
if not self.ans.get("셈됨") and "결과" not in self.ans:
marks = self.ans.get("표지") or []
if marks:
return str(marks[0].get("글") or marks[0].get("갈래"))
empty = self.ans.get("빈값") or {}
for i, v in self.vars.items():
if i in empty and (v.get("연결") or {}).get("갈래") in INPUTS:
return str(empty[i])
return None
@property
def resources(self) -> list[str]:
"""문서 전체(하위 포함)가 부른 자원 키 — 부른 차례 · 겹침 없음(표 뺌)."""
return list(self.ans.get("자원") or [])
@property
def env(self) -> dict[str, Any]:
"""입력 · 중간 값 {원래 이름: 값} — 표 틀(`{구분}`) 채우기 · 계산서 줄 덧칸이 읽음."""
values = self.ans.get("값") or {}
out = {
str(v.get("열쇠")): values[i]
for i, v in self.vars.items()
if v.get("열쇠") and values.get(i) is not None
}
for x in self.doc.get("식") or []:
if x.get("이름") and values.get(str(x.get("기호"))) is not None:
out.setdefault(str(x["이름"]), values[str(x["기호"])])
return out
def _call(self, n: int, dl: dict, out: dict) -> dict | None:
"""줄 단가 기호를 부른 기록(맨 위 깊이) — 단가가 기호 하나가 아니면 None."""
sym = str(dl.get("단가") or "")
calls = self.ans.get("부름") or []
return next((calls[i] for i in out.get("부름") or [] if calls[i]["이름"] == sym), None)
def _line(self, n: int, dl: dict, out: dict) -> dict[str, Any]:
qty, price = _num(out.get("수량")), out.get("단가")
kind = str(dl.get("비목") or "")
raw: dict[str, Decimal] = {}
if qty is not None and isinstance(price, dict):
raw = {k: qty * price[k] for k in COSTS if isinstance(price.get(k), Decimal)}
elif qty is not None and isinstance(price, Decimal) and kind in COSTS:
raw = {kind: qty * price}
call = self._call(n, dl, out)
line = {
"이름": dl.get("이름") or "",
"단위": dl.get("단위") or "",
"수량": qty,
"단가": price,
"비목": raw,
"금액": sum(raw.values()) if raw else None,
"까닭": out.get("까닭"),
"합밖": bool(out.get("합밖")),
"부름": None,
}
if call is None:
return line
if call["갈래"] == "단가산출":
p = call["부름"]
line["부름"] = (
{"machine": call.get("기계")}
if "기계" in call
else {"code": str(p.get("키") or ""), "given": dict(p.get("입력") or {})}
)
return line
keys = [x["키"] for x in call.get("자원") or [] if x["갈래"] != "표"]
asked = call["부름"].get("키") # 노임 「LB:직종」 꼴 = 부른 글 그대로(옛 키 · 글 단가 짝)
if isinstance(asked, str) and asked[:3] == "LB:" and "{" not in asked:
line["키"] = asked
return line
if price is None and (self.vars.get(str(dl.get("단가"))) or {}).get("연결", {}).get("재료"):
return line # 값 없는 재료 찾기 = 품목 없음(옛 `mp.priced` 와 같게 · 키 빈 글)
goods = call.get("품목") or (keys[0] if keys and keys[0][:2] == "MT" else None)
line["키"] = goods or (keys[0] if keys else "")
if goods:
try:
row = self.whole.get(goods) or {}
except Exception: # noqa: BLE001 — 없는 품목 = 키만
row = {}
line["품목"] = {"키": goods, **{k: row.get(k) for k in ("이름", "규격", "단위")}}
return line
def engine(self, items: list[dict]) -> list[dict[str, Any]]:
"""옛 엔진 줄 꼴(대가 품셈 블록) — 호표 줄 단위 = 로직 원문 표기(B9-5 에서 문서로) · % 줄 = 율."""
out = []
for n, x in enumerate(self.lines):
if n < len(items):
out.append({**x, "단위": items[n].get("단위") or x["단위"]})
else:
pct = self.pct(n)
out.append({**x, "율": pct[0]} if pct else x)
return out
def pct(self, n: int) -> tuple[Decimal, str] | None:
"""% 줄(149-4) — 단가 식이 「X × Y%」 · 「X × Y ÷ 100」 이면 (율 Y, 밑 이름 「노무비의 %」 …)."""
try:
node = md.parse(str((self.doc.get("금액") or [])[n].get("단가") or ""))
except (md.DocError, IndexError):
return None
if node[0] == "bin" and node[1] == "*" and node[3][0] == "pct":
base, part = node[2], node[3][1]
elif (
node[0] == "bin"
and node[1] == "/"
and node[3] == ("num", Decimal(100))
and node[2][0] == "bin"
and node[2][1] == "*"
):
base, part = node[2][2], node[2][3]
else:
return None
rate = part[1] if part[0] == "num" else self._value(part)
return (rate, self._label(base)) if isinstance(rate, Decimal) else None
def _value(self, node: tuple) -> Any:
"""식 조각 값 — 같은 계산기(`master_doc_calc`)로 이 문서 · 입력 그대로."""
if node[0] == "var":
return (self.ans.get("값") or {}).get(str(node[1]))
try:
run = mc._Run(self.doc, ml.Links(self.whole, self.docs), self.given, (), {})
return run.ev(node, None, "율")
except Exception: # noqa: BLE001 — 못 셈 = % 줄 아님(식 그대로)
return None
def _label(self, node: tuple) -> str:
"""% 밑 이름 — `M02_Labor_Doc._pct_base` 같은 말(문서 기호 → 원래 이름)."""
if node[0] == "var":
name = str(node[1])
if name in COSTS:
return f"{name}의 %"
line = next((x for x in self.doc.get("금액") or [] if x.get("기호") == name), None)
if line is not None: # 앞 금액 줄 기호(옛 줄 이름)
return f"{line.get('이름') or name}의 %"
step = next((x for x in self.doc.get("식") or [] if x.get("기호") == name), None)
var = self.vars.get(name) or {}
if step is None and (var.get("연결") or {}).get("갈래") not in (*INPUTS, "식"):
return (
"인건비의 %" if str((var.get("연결") or {}).get("키", ""))[:2] == "LB" else ""
)
return f"{var.get('열쇠') or (step or {}).get('이름') or name}의 %"
if node[0] == "field" and node[1] == ("var", "줄"):
return f"{node[2]}의 %"
names = md.names(node)
labor = [
n
for n in names
if str(((self.vars.get(n) or {}).get("연결") or {}).get("키", ""))[:2] == "LB"
]
return "인건비의 %" if labor and not set(names) & set(COSTS) else ""
def settle(self, sums: dict[str, Decimal]) -> dict[str, Decimal]:
"""블록 비목 합 끝수(끝전 · 계 · 조정) — 새 계산기 `_settle` 그대로 · 규칙 = 답 `끝수`."""
return mc._settle(self.doc, self.rules, sums)
def solve(
whole: Any,
docs: dict[str, dict],
code: str,
given: Any = None,
picks: Any = None,
rate: Any = None,
shown: dict[str, int] | None = None,
) -> Answer | None:
"""로직 하나 문서 셈 — `docs` 에 없는 키 = 그 자리 닫힌 묶음(받은 묶음에 더함) · 입력 = 자동값 ›
받은 값 · `rate` = 금액 줄 수량 × 율 ÷ 100(켜쌓기율 · 1 단위 몫) · `shown` = 중간값 표시 자리
{원래 이름: 자리}(그 식 줄 = 반올림(식, 자리) · B09 엑셀 자리) · 문서 없음 = None."""
code = str(code)
if code not in docs:
docs.update(dc.closure(whole, [code], docs))
base = docs.get(code)
if base is None:
return None
doc = _shown(dc.line_doc(base, rate, picks or None), shown or {})
copy, given = {"부름": docs}, dc.given_of(whole, code, given)
try:
ans = mt.calc(doc, mt.Trace(whole, docs), given, dc.cover_of(copy, doc))
except Exception: # noqa: BLE001 — 계산기는 예외 없음이 원칙 · 남은 틈 = 못 셈
return None
return Answer(whole, doc, ans, docs, given)
def _shown(doc: dict, shown: dict[str, int]) -> dict:
"""중간값 표시 자리 — 열쇠가 `shown` 인 식 변수의 식 줄을 반올림(식, 자리)으로(새 문서)."""
syms = {
md.var_id(v): shown[str(v.get("열쇠"))]
for v in doc.get("변수") or []
if (v.get("연결") or {}).get("갈래") == "식" and str(v.get("열쇠")) in shown
}
if not syms:
return doc
doc = {**doc, "식": [dict(x) for x in doc.get("식") or []]}
for x in doc["식"]:
if str(x.get("기호")) in syms:
x["식"] = f"반올림({x.get('식')}, {syms[str(x['기호'])]})"
return doc
class Shelf:
"""값 색인(`whole`) → 문서 묶음 — 같은 색인 = 같은 묶음(사본 `수식.json` · 없으면 셈 때 그 자리)."""
def __init__(self) -> None:
self._got: list[tuple[Any, dict[str, dict]]] = [] # 색인을 붙들어 둠(id 다시 쓰기 막음)
def put(self, whole: Any, docs: dict[str, dict]) -> dict[str, dict]:
self._got.append((whole, docs))
return docs
def of(self, whole: Any) -> dict[str, dict]:
got = next((d for w, d in self._got if w is whole), None)
return self.put(whole, {}) if got is None else got