- B09_Estimation_Doc_Run: doc · row · row_of 더함 — 수식 문서 → B09 풀이 줄 꼴(이름 · 결과단위 · 출처 · 입력 · 중간 = 변수 열쇠 · 호표 = 수량 있는 금액 줄(종류 = 단가 연결: 단가산출 · 굳은 기계 묶음 → 로직 · 노임 요소 → 인력 · 그 밖 → 재료 · 요소 = 연결 키) · 덧줄 = 수량 없는 금액 줄(1,456 돈 문서 전부 끝) · 단계) · engine 덧줄에 % 밑 이름 - B09_Estimation_Sangeun: unit_of · is_money · line_calls · Solver._solve 가 whole.logic 대신 문서 · 계산서 줄 덧칸 = 새 B09_Estimation_Sheet(문서에서 쓰는입력 · 기준단위 · 환산근거 · master_sheet_line 안 부름) · _input_names = 지금 수식 문서 - B09_Estimation_Labor_Source._poomsem: 문서 줄 꼴 · % 밑 = 문서 셈 밑 이름(옛 덧줄 식 글 정규식 걷음) · 키 모르는 굳은 기계 묶음 줄 = M02 값 고정 줄 - B09_Estimation_Bill_Library._logic(운반 값 입력) = 지금 수식 문서(Item_Prices.doc_specs) - 골든 test_855_b09_golden 다시 뜸 — 산근 값 · 산근 관급 값 · 미리보기 hand:net 값 세 갈래 = 재료 줄 단위 글 kg → ㎏(문서 단위)뿐 - 실제 B09 프로젝트(손 줄 6): 산근 답 = 옛 코드 답과 같음(계산서 덧칸 쓰는입력까지) · 해시 같음 - 검증: 관련 + 핵심 + 855_golden · 855_trace · 795_4 549 통과 · typecheck 0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
331 lines
15 KiB
Python
331 lines
15 KiB
Python
"""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], "밑": pct[1]} 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 doc(whole: Any, docs: dict[str, dict], code: str) -> dict | None:
|
||
"""키 하나의 수식 문서 — `docs`(사본 수식 문서) › 그 자리 닫힌 묶음(받은 묶음에 더함) ·
|
||
없음 = None."""
|
||
code = str(code)
|
||
if code not in docs:
|
||
docs.update(dc.closure(whole, [code], docs))
|
||
return docs.get(code)
|
||
|
||
|
||
def row_of(doc: dict) -> dict[str, Any]:
|
||
"""수식 문서 → B09 풀이가 읽는 줄 꼴(855-F B9-6 · 옛 로직 줄 대신 문서에서) — 이름 ·
|
||
결과단위 · 출처 · 입력(변수 열쇠) · 중간(식 변수 열쇠) · 호표 = 수량 있는 금액 줄(종류 = 단가
|
||
연결: 단가산출 → 로직 「로직(키)」 · 노임 요소 → 인력 · 그 밖 → 재료) · 덧줄 = 수량 없는 금액 줄
|
||
(식 = 단가 글 · 늘 끝) · 단계."""
|
||
ids = {md.var_id(v): v for v in doc.get("변수") or []}
|
||
heads: list[dict] = []
|
||
extras: list[dict] = []
|
||
for line in doc.get("금액") or []:
|
||
keep = {k: line[k] for k in ("이름", "단위", "비목", "자리", "번지", "합밖") if k in line}
|
||
if "수량" not in line:
|
||
extras.append({**keep, "식": str(line.get("단가") or "")})
|
||
continue
|
||
link = (ids.get(str(line.get("단가"))) or {}).get("연결") or {}
|
||
key = str(link.get("키") or "")
|
||
frozen = link.get("갈래") == "숫자" and isinstance(
|
||
link.get("값"), dict
|
||
) # 굳은 기계 묶음(847-1)
|
||
kind = (
|
||
"로직"
|
||
if link.get("갈래") == "단가산출" or frozen
|
||
else "인력"
|
||
if key[:2] == "LB"
|
||
else "재료"
|
||
)
|
||
elem = (
|
||
f"로직({key})" if kind == "로직" and key else key
|
||
) # 노임 · 요소 키(줄 정체 · 덮개 cid)
|
||
heads.append({**keep, "종류": kind, **({"요소": elem} if elem else {})})
|
||
out = {
|
||
**{k: doc.get(k) for k in ("키", "이름", "결과단위", "출처")},
|
||
"입력": [
|
||
{"이름": str(v["열쇠"])} for v in ids.values() if _kind(v) in INPUTS and v.get("열쇠")
|
||
],
|
||
"중간": [
|
||
{"이름": str(v["열쇠"])} for v in ids.values() if _kind(v) == "식" and v.get("열쇠")
|
||
],
|
||
"호표": heads,
|
||
"덧줄": extras,
|
||
**({"단계": doc["단계"]} if doc.get("단계") else {}),
|
||
}
|
||
return {**out, "결과": doc["결과"]} if "결과" in doc else out
|
||
|
||
|
||
def _kind(var: dict) -> str:
|
||
return str((var.get("연결") or {}).get("갈래") or "")
|
||
|
||
|
||
def row(whole: Any, docs: dict[str, dict], code: str) -> dict[str, Any] | None:
|
||
"""키 하나의 B09 풀이 줄 꼴(`row_of`) — 문서 없음 = None."""
|
||
got = doc(whole, docs, code)
|
||
return None if got is None else row_of(got)
|
||
|
||
|
||
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, docs)
|
||
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
|