- 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>
116 lines
5.0 KiB
Python
116 lines
5.0 KiB
Python
"""B09 산근 계산서 줄 덧칸 `sheet`{쓰는입력 · 기준단위 · 환산근거}(719-4) — 수식 문서에서
|
||
(855-F B9-6) · 서버 단독(짝 없음).
|
||
|
||
옛 `master_sheet_line._fields`(옛 로직 줄 식 풀이)와 같은 뜻:
|
||
- `쓰는입력` = 그 줄 값(수량 · 단가 식)이 쓰는 문서 입력 변수 열쇠 — 식 변수 · 표 조건 ·
|
||
단가산출 넘긴 입력 · 요소 키 틀 · 재료 조건 글 구멍을 거슬러 감 · 문서 변수 차례.
|
||
- `기준단위` = 그 줄이 찾는 표의 기준(「10㎡」 · `master_basis.basis`) · 없으면 None.
|
||
- `환산근거` = 표 기준배 ↔ 결과단위 배 · 재료 품목 단위 ↔ 줄 단위(`master_unit.note`) · 없으면 「」.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from decimal import Decimal
|
||
from typing import Any
|
||
|
||
import master_basis as mbs # noqa: E402
|
||
import master_doc as md # noqa: E402
|
||
import master_unit as mu # noqa: E402
|
||
|
||
from B09_Estimation import B09_Estimation_Doc_Run as dr
|
||
from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠
|
||
|
||
_HOLE = re.compile(r"\{([^{}]+)\}")
|
||
|
||
|
||
def _times(x: Decimal) -> str:
|
||
return format(x.normalize(), "f")
|
||
|
||
|
||
def per_text(per: list[tuple[Decimal, str]]) -> str:
|
||
"""결과단위 분모 글(「10㎡」 · 여럿 = 「㎡ · ㎥」)."""
|
||
return " · ".join(dict.fromkeys(f"{_times(n) if n != 1 else ''}{u}" for n, u in per))
|
||
|
||
|
||
def base_unit(doc: dict) -> str | None:
|
||
"""답 머리 `기준단위` = 결과단위 분모."""
|
||
return per_text(mbs.result_per(doc.get("결과단위"))) or None
|
||
|
||
|
||
def _reach(doc: dict, texts: list) -> tuple[list[str], list[str]]:
|
||
"""식들이 쓰는 (입력 열쇠 · 표 키) — 식 변수 · 표 조건 · 단가산출 넘긴 입력을 거슬러 감."""
|
||
ids = {md.var_id(v): v for v in doc.get("변수") or []}
|
||
steps = {md.var_id(x): x.get("식") for x in doc.get("식") or []}
|
||
seen: set[str] = set()
|
||
tables: list[str] = []
|
||
todo = [t for t in texts if t not in (None, "")]
|
||
while todo:
|
||
try:
|
||
names = set(md.names(md.parse(todo.pop())))
|
||
except md.DocError:
|
||
continue
|
||
for name in names - seen:
|
||
seen.add(name)
|
||
link = (ids.get(name) or {}).get("연결") or {}
|
||
if name in steps:
|
||
todo.append(steps[name])
|
||
if link.get("갈래") == "표":
|
||
tables += [str(link["표"])] if link.get("표") and link["표"] not in tables else []
|
||
todo += [str(x) for x in (link.get("조건") or {}).values()]
|
||
elif link.get("갈래") == "단가산출":
|
||
todo += [str(x) for x in (link.get("입력") or {}).values()]
|
||
elif (
|
||
link.get("갈래") == "요소"
|
||
): # 키 틀 · 재료 조건 글 구멍(「LB:{S_직종}」 · 「{D_관}」)
|
||
cond = link.get("재료") if isinstance(link.get("재료"), dict) else {}
|
||
for text in [str(link.get("키") or ""), *(str(x) for x in cond.values())]:
|
||
todo += _HOLE.findall(text)
|
||
inputs = [
|
||
str(v["열쇠"])
|
||
for vid, v in ids.items()
|
||
if vid in seen and dr._kind(v) in dr.INPUTS and v.get("열쇠")
|
||
]
|
||
return inputs, tables
|
||
|
||
|
||
def _basis(whole: Any, tables: list[str]) -> dict | None:
|
||
for ref in tables:
|
||
try:
|
||
got = mbs.basis(whole.get(ref))
|
||
except Exception: # noqa: BLE001 — 없는 표 · 기준 없음 = 다음
|
||
continue
|
||
if got["갈래"] == "단위":
|
||
return got
|
||
return None
|
||
|
||
|
||
def _note(basis: dict | None, per: list, line: dict) -> str:
|
||
notes = []
|
||
if basis and len(per) == 1:
|
||
times, one = per[0]
|
||
if mu.plain(basis["기준단위"]) == mu.plain(mbs.unit(one)) and basis["기준배"] != times:
|
||
ratio = basis["기준배"] / times
|
||
how = f"÷{_times(ratio)}" if ratio > 1 else f"×{_times(1 / ratio)}"
|
||
notes.append(
|
||
f"{_times(basis['기준배'])}{basis['기준단위']}당 → {_times(times)}{one}당 {how}"
|
||
)
|
||
goods = line.get("품목") or {}
|
||
if goods.get("단위") and line.get("단위"):
|
||
notes.append(mu.note(goods["단위"], line["단위"]))
|
||
return " · ".join(n for n in notes if n)
|
||
|
||
|
||
def annotate(whole: Any, doc: dict, lines: list[dict[str, Any]]) -> None:
|
||
"""블록 줄마다 `sheet` — 줄 차례 = 문서 금액 줄 차례(호표 · 뒤 덧줄) · 제자리."""
|
||
per = mbs.result_per(doc.get("결과단위"))
|
||
for dl, ln in zip(doc.get("금액") or [], lines):
|
||
goods = ln.pop("_goods", None) or {}
|
||
inputs, tables = _reach(doc, [dl.get("수량"), dl.get("단가")])
|
||
basis = _basis(whole, tables)
|
||
unit = None
|
||
if basis:
|
||
unit = f"{_times(basis['기준배']) if basis['기준배'] != 1 else ''}{basis['기준단위']}"
|
||
seen = {"품목": goods, "단위": dl.get("단위")}
|
||
ln["sheet"] = {"쓰는입력": inputs, "기준단위": unit, "환산근거": _note(basis, per, seen)}
|