- M02_Item_Bundle · B09_Estimation_Sheet: master_doc · master_basis · master_unit 을 scripts 길을 두는 import(Item_Prices · M01 Store) 뒤로 - 찾은 곳: 화면 검증 중 B08 _folder_units 를 새 프로세스에서 처음 부를 때 ModuleNotFoundError(서버는 다른 모듈이 먼저 길을 둬 안 드러남) - 검증: 두 모듈 새 프로세스 단독 import 통과 · 관련 + 855_b09_golden · 719_4 20 통과 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
|
||
|
||
from B09_Estimation import B09_Estimation_Doc_Run as dr
|
||
from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠
|
||
|
||
import master_basis as mbs # noqa: E402 — scripts 길(_m01) 뒤에
|
||
import master_doc as md # noqa: E402
|
||
import master_unit as mu # noqa: E402
|
||
|
||
_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)}
|