refactor(855-F B9-4): B09 산출근거 글이 옛 엔진 · master_text 대신 풀이 블록 + 문서 셈 답으로
- Sangeun_Text 새 render · foot — 풀이 블록 줄 값(B09 수량 · 단가 · 금액) + 문서 셈 답(입력 · 공식 · 표 값 · 단위) · 수 꼴 · 단위 · 금액 줄 꼴 = master_doc_text(화면 줄 쌓기 산출근거 규칙) - Sangeun _env · _captured · _Prices · price_of 지움 · Solver._text = render 한 번(못 지으면 빈 글 · 값 그대로) - Sangeun_Sum 옛 shown · _cut · places · sums · scope · extra · totals 지움(doc_* 만) - helper_855_engine 옛 대조 기준 _old_env · _old_captured(test_855_trace) - test_155_5 · test_157_1 · test_155_b09_sources — 엑셀 꼴 글자 대신 새 규칙 결과(글 금액 = 블록 · 계 · Q 공식 줄 · 값 넣은 수량 식 · ÷ 배 · 원) - 골든 855_b09 글 5 갈래 다시 뜸(전 → 후 견본 tmp 표) · 값 10 갈래 같음 · 옛 글이 블록 값과 어긋나던 자리(옛 키 단가 0) 바로잡힘 - B09 옛 엔진 부름 37 → 0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,7 +10,7 @@
|
||||
로직 줄이 부르는 다른 돈 로직(기계경비 밖) = 하위 산근(그 산근도 목록에 · 산근 → 산근).
|
||||
풀이 = 사본 수식 문서(`수식.json`)를 M02 와 같은 계산기로 셈한 답 + 셈 기록(`B09_Estimation_Doc_Run` ·
|
||||
855-F B9-3)에서 줄마다 수량 · 단가 · 자원 키 · 하위 산근 · % 줄 율 · 끝수를 읽음(옛 엔진 안 부름) ·
|
||||
줄 이름 · 단위 · 종류 = 사본 로직 줄 글(B9-5 에서 문서로) · 산출근거 글 = 옛 길(B9-4 · `_env` · `_captured`) ·
|
||||
줄 이름 · 단위 · 종류 = 사본 로직 줄 글(B9-5 에서 문서로) · 산출근거 글 = 풀이 블록 + 문서 셈 답(B9-4) ·
|
||||
단가 = B09 프로젝트 한 벌 굳힌 단가(144 · `compute_base` 표) — 노무 = 노무비목록표 ·
|
||||
중기 = 중기목록표 노 · 재 · 경 · 재료 = 자재단가대비표 적용 단가 ·
|
||||
% 줄(덧줄) = 엔진 식에 B09 비목 합.
|
||||
@@ -45,6 +45,7 @@ from typing import Any
|
||||
from B08_Quantity.B08_Quantity_Haul_Cycle import fill_given
|
||||
from B09_Estimation import B09_Estimation_Doc_Run as dr
|
||||
from B09_Estimation import B09_Estimation_Sangeun_Sum as ss
|
||||
from B09_Estimation import B09_Estimation_Sangeun_Text as st
|
||||
from B09_Estimation.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total
|
||||
from B09_Estimation.B09_Estimation_Copy_Prices import bundle
|
||||
from B09_Estimation.B09_Estimation_Store import ref_rows
|
||||
@@ -66,7 +67,6 @@ import master_sheet_line as msl # noqa: E402 — 계산서 줄 덧칸(714-1) ·
|
||||
PARTS = ("labor", "material", "expense")
|
||||
COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
|
||||
PART_COST = {v: k for k, v in COST_PART.items()}
|
||||
PART_NAMES = tuple((p, k) for k, p in COST_PART.items()) # 글 계 줄 차례(노 · 재 · 경)
|
||||
PCT_OF = {**COST_PART, "인건비": "people"} # % 덧줄 밑수 → 덮개 다시 셈(719-3)
|
||||
DEPTH = 4 # 하위 산근 깊이 상한
|
||||
NO_SOURCE = "조합 밖 토공 · 운반 · 사토 · 준비공은 산근 없음"
|
||||
@@ -172,17 +172,6 @@ def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[d
|
||||
|
||||
|
||||
# ── 풀이 ──────────────────────────────────────────────────────────────
|
||||
class _Prices:
|
||||
"""엔진 단가(841-1) — M02 엔진이 사본 단가 묶음으로 낸 줄 금액 ÷ 수량 · 텍스트 수식 글이 읽음
|
||||
(노무 · 자재 = 수 · 중기 = 노 · 재 · 경). B09 단가 책 · 바탕 표는 안 읽음."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# ponytail: 키 하나 = 단가 하나(사본마다 기준 시점이 달라도 마지막 본 값) — 글 짓기 전용
|
||||
self.labor: dict[str, float | None] = {}
|
||||
self.material: dict[str, float | None] = {}
|
||||
self.machine: dict[str, dict[str, float | None]] = {}
|
||||
|
||||
|
||||
def _unit(row: dict) -> tuple[str, Decimal]:
|
||||
"""결과단위 1 단위 — (단위, 배)(「원/10㎡」 = ㎡ · 10) · 알약 규칙(`combo_pills`) 그대로 ·
|
||||
줄 = 사본 단가 묶음 것(M01 다시 안 읽음 · 719-2)."""
|
||||
@@ -201,21 +190,6 @@ def unit_of(whole: Any, code: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _env(whole: Any, row: dict, given: dict) -> dict:
|
||||
"""입력(빈 입력 = 자동값) + 중간값 · 작업량 Q = ROUND(식, 2)(엑셀 자리) — 산출근거 글 몫만
|
||||
(`B09_Estimation_Sangeun_Text` · B9-4 에서 걷음 · 풀이 금액은 `Doc_Run`)."""
|
||||
auto = {k: v for k, v in m01.mau.values(whole, row).items() if v is not None}
|
||||
env = mf._inputs(row, {**auto, **m01._dec(given or {})})
|
||||
for step in row.get("중간", []):
|
||||
try:
|
||||
value = mf.evaluate(mf.parse(step["식"]), env, whole, 0)
|
||||
except mf.EmptyInput as e:
|
||||
env[step["이름"]] = mf.Blank(str(e))
|
||||
continue
|
||||
env[step["이름"]] = ss.shown(row, step, value) # 표시 · Q ROUND 2(792-3)
|
||||
return env
|
||||
|
||||
|
||||
def is_money(whole: Any, code: str) -> bool:
|
||||
"""돈 로직(호표 줄 꼴)인지 — 없는 로직 · 흐름 · 결과 로직 = 아님."""
|
||||
try:
|
||||
@@ -286,28 +260,6 @@ def line_calls(
|
||||
}
|
||||
|
||||
|
||||
def _captured(whole: Any, node: Any, env: dict) -> list[str]:
|
||||
"""식을 돌리며 부른 기계 키(EQ) — 기계경비 로직 줄의 기계 · 산출근거 글 몫만(B9-4)."""
|
||||
seen: list[str] = []
|
||||
base = whole.get
|
||||
|
||||
def get(ref: str) -> dict[str, Any]:
|
||||
row = base(ref)
|
||||
key = str(row.get("키") or "")
|
||||
if key.startswith("EQ") and key not in seen:
|
||||
seen.append(key)
|
||||
return row
|
||||
|
||||
whole.get = get
|
||||
try:
|
||||
mf.evaluate(node, env, whole, 1)
|
||||
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
|
||||
pass # 기계 단가를 못 셈 — 키만 있으면 됨(단가는 B09 중기목록표)
|
||||
finally:
|
||||
whole.get = base
|
||||
return seen
|
||||
|
||||
|
||||
def spec_text(whole: Any, given: dict[str, Any]) -> tuple[str, str]:
|
||||
"""규격 글(157-3) → (보일 글, 원문번호 글) — 기계 · 직종 번호 = 「이름 규격」(M02 85-1)."""
|
||||
|
||||
@@ -343,7 +295,6 @@ class Solver:
|
||||
|
||||
def __init__(self, supply: Any = None) -> None:
|
||||
self.supply = supply or (lambda key: None) # 자재 키 → 관급 · 별도 · None(841-1)
|
||||
self.prices = _Prices()
|
||||
self.eng: list[dict[str, Any]] = [] # 지금 푸는 로직의 문서 셈 줄(금액 줄 차례 · 841-1)
|
||||
self.blocks: dict[str, dict[str, Any]] = {}
|
||||
self.shelf = dr.Shelf() # 값 색인 → 사본 수식 문서(`collect` 가 사본마다 둠)
|
||||
@@ -388,19 +339,17 @@ class Solver:
|
||||
lines.append(self._line(whole, item, n, times, rate, depth))
|
||||
ss.doc_places(row, lines) # 줄 자리(792-3)
|
||||
self._extras(row, per or eng, lines)
|
||||
head = self._text(whole, eng, lines, times, src.get("rate"))
|
||||
self._aside(lines)
|
||||
_annotate(whole, row, eng.env, lines)
|
||||
except (ArithmeticError, KeyError, TypeError, ValueError) as e:
|
||||
return self._stop(code, name, str(e) or type(e).__name__)
|
||||
sums = ss.doc_totals(eng, lines) # 끝수 · 끝전 · 조정 = 문서 답 끝수(792-3)
|
||||
why = next((ln["why"] for ln in lines if ln.get("why")), None)
|
||||
head, foot = self._text(whole, src, times, lines)
|
||||
for ln in lines: # 글 = 엔진 단가 셈 그대로 · 별도계상 재료 줄은 끝에 0 원 표시(841-1)
|
||||
foot = st.foot(sums)
|
||||
for ln in lines: # 글 = 풀이 단가 셈 그대로 · 별도계상 재료 줄은 끝에 0 원 표시(841-1)
|
||||
if "aside" in ln and ln.get("text"):
|
||||
ln["text"] = [*ln["text"][:-1], f"{ln['text'][-1]} · 별도계상 = 0.0"]
|
||||
if foot and any("aside" in ln for ln in lines) and sums.get("sum") is not None:
|
||||
parts = " + ".join(f"{st_name} {sums[p]:,.0f}" for p, st_name in PART_NAMES)
|
||||
foot = f"계 : {parts} = {sums['sum']:,.0f}"
|
||||
ln["text"] = [*ln["text"][:-1], f"{ln['text'][-1]} · 별도계상 = 0.0 원"]
|
||||
spec, spec_raw = spec_text(whole, src["given"])
|
||||
return {
|
||||
"logic": code,
|
||||
@@ -423,37 +372,21 @@ class Solver:
|
||||
"lines": [], **dict.fromkeys(PARTS), "sum": None, "why": why,
|
||||
"head": [], "foot": ""} # fmt: skip
|
||||
|
||||
def price_of(self, key: str) -> Any:
|
||||
"""글 짓기 단가(`Sangeun_Text` 꼴) — 노무 · 자재 = 수 · 중기 · 산근 = 비목 단가 묶음."""
|
||||
if key in self.prices.labor:
|
||||
return self.prices.labor[key]
|
||||
if key in self.prices.material:
|
||||
return self.prices.material[key]
|
||||
if key in self.prices.machine:
|
||||
return {p: num(self.prices.machine[key].get(p)) for p in PARTS}
|
||||
block = self.blocks.get(key)
|
||||
return {k: block.get(k) for k in (*PARTS, "sum", "no")} if block else None
|
||||
|
||||
def _text(self, whole, src, times, lines) -> tuple[list[str], str]:
|
||||
"""텍스트 수식(155-5) → (머리 줄들, 계) · 줄마다 `text` 를 얹음(중기 = 세 줄 · 그 밖 한 줄).
|
||||
줄 수가 안 맞으면 모두 머리에(값 칸과 어긋나게 얹지 않음)."""
|
||||
from B09_Estimation.B09_Estimation_Sangeun_Text import render_sangeun_text
|
||||
|
||||
def _text(self, whole, eng, lines, times, rate) -> list[str]:
|
||||
"""산출근거 글(155-5 · B9-4 `Sangeun_Text.render`) — 줄마다 `text` 를 얹고 머리 줄들 · 글을 못 지으면
|
||||
빈 글(값은 그대로)."""
|
||||
try:
|
||||
text = render_sangeun_text(whole, src["code"], src["given"], self.price_of,
|
||||
times=times, rate=src.get("rate"),
|
||||
picks=src.get("picks")) # fmt: skip
|
||||
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
|
||||
return [], ""
|
||||
counts = [3 if ln["kind"] == "machine" and not ln.get("why") else 1 for ln in lines]
|
||||
start = len(text) - 1 - sum(counts)
|
||||
if start < 1:
|
||||
return text, ""
|
||||
at = start
|
||||
for ln, n in zip(lines, counts):
|
||||
ln["text"] = text[at : at + n]
|
||||
at += n
|
||||
return text[:start], text[-1]
|
||||
head, texts = st.render(whole, eng, lines, times=times, rate=rate, no_of=self._no)
|
||||
except Exception: # noqa: BLE001 — 글은 보기 · 못 지어도 풀이 값은 살림
|
||||
return []
|
||||
for ln, text in zip(lines, texts):
|
||||
ln["text"] = text
|
||||
return head
|
||||
|
||||
def _no(self, key: Any) -> int | None:
|
||||
"""하위 산근 호표 번호(글)."""
|
||||
block = self.blocks.get(str(key or ""))
|
||||
return block.get("no") if block else None
|
||||
|
||||
def _aside(self, lines: list[dict[str, Any]]) -> None:
|
||||
"""관급 · 별도계상 재료 = 산근 안 0원(841-1 · % 덧줄 밑수는 엔진 값 그대로 · 자재대 · 관급 단락)."""
|
||||
@@ -492,7 +425,6 @@ class Solver:
|
||||
if kind == "인력":
|
||||
key = str(x.get("키") or "") # 노임 키 = 셈 기록(부른 노임 줄)
|
||||
price = self._each(n, "labor", q)
|
||||
self.prices.labor[key] = price
|
||||
why = None if price is not None else f"노임 단가 없음(M02 엔진) 「{key}」"
|
||||
return {**base, **zero, "kind": "labor", "ref": {"tab": "labor", "key": key},
|
||||
"price": {"labor": price}, "labor": _money(price, q), "why": why} # fmt: skip
|
||||
@@ -500,7 +432,6 @@ class Solver:
|
||||
key = str(x.get("키") or "")
|
||||
part = COST_PART.get(item.get("비목"), "material")
|
||||
price = self._each(n, part, q)
|
||||
self.prices.material[key] = price
|
||||
why = None if price is not None else f"자재 단가 없음(M02 엔진) 「{key}」"
|
||||
spec = goods.get("규격") or ""
|
||||
ref = {"tab": "compare", "key": key}
|
||||
@@ -514,8 +445,6 @@ class Solver:
|
||||
keys = [call["machine"]] if call["machine"] else []
|
||||
price = {p: self._each(n, p, q) for p in PARTS} # 기계 시간당 = M02 엔진 값(841-1)
|
||||
m = None not in price.values()
|
||||
if keys:
|
||||
self.prices.machine[keys[0]] = price
|
||||
why = (
|
||||
None
|
||||
if m
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"""B09 산근 풀이 셈 의미(PLAN 792-3) — 791-1 엔진 새 의미(줄 자리 · 합밖 · 번지 · 단계 · 블록 끝전 ·
|
||||
결과 조정 · 변수 표시)를 쓰는 로직만 엔진 규칙(`master_cut` · `master_formula_sum`) 그대로 ·
|
||||
새 칸 없는 로직 = 옛 B09 규칙(작업량 Q = ROUND 2 · 줄 ROUNDDOWN 1 · 총계 비목마다 ROUNDDOWN 0).
|
||||
쓰는 곳 = 산출근거 글(`B09_Estimation_Sangeun_Text` · B9-4 에서 걷음) · 풀이 금액(`Sangeun.Solver`) =
|
||||
아래 `doc_*`(855-F B9-3 · 문서 셈 답 `끝수` · `합밖` · 새 계산기 `master_doc_calc.cut` · `_settle`) · 지킴 시험 = `test_792_3_engine_paths.py`(엔진 · M02 SK ·
|
||||
"""B09 산근 풀이 셈 의미(PLAN 792-3 · 855-F B9-3) — 줄 자리 · 합밖 · 블록 끝전 · 결과 조정 = 문서 셈 답의
|
||||
`끝수` · `합밖`(새 계산기 `master_doc_calc.cut` · `_settle`) · 기본 = 줄 ROUNDDOWN 1 · 총계 비목마다
|
||||
ROUNDDOWN 0 · 중간값 표시 자리(`표시` · 옛 로직 작업량 Q = ROUND 2 · 엑셀 자리) = 문서 식에 반올림.
|
||||
쓰는 곳 = `B09_Estimation_Sangeun.Solver` · 지킴 시험 = `test_792_3_engine_paths.py`(엔진 · M02 SK ·
|
||||
SC · B09 산근 네 길 같은 금액).
|
||||
"""
|
||||
|
||||
@@ -13,10 +12,9 @@ import re
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from B09_Estimation.B09_Estimation_Calc_Base import round_half, rounddown, total
|
||||
from B09_Estimation.B09_Estimation_Calc_Base import rounddown, total
|
||||
from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠
|
||||
|
||||
mcut = importlib.import_module("master_cut")
|
||||
mc = importlib.import_module("master_doc_calc")
|
||||
ms = importlib.import_module("master_formula_sum")
|
||||
|
||||
@@ -25,73 +23,6 @@ COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
|
||||
_Q = re.compile(r"Q\d*") # 작업량 중간값 이름(산림품셈 09장 토공 · 07장 집재 …)
|
||||
|
||||
|
||||
def shown(row: dict, step: dict, value: Any) -> Any:
|
||||
"""중간값 — `표시` 칸 · 새 의미 로직 = 엔진 그대로(`표시` 자리 반올림) · 옛 = Q ROUND 2."""
|
||||
if step.get("표시") is not None or ms.uses(row):
|
||||
return ms.shown(step, value)
|
||||
if _Q.fullmatch(step["이름"]) and isinstance(value, (Decimal, int, float)):
|
||||
return Decimal(str(round_half(float(value), 2)))
|
||||
return value
|
||||
|
||||
|
||||
def _cut(value: float, rule: dict | None) -> float:
|
||||
return float(mcut._line(value, rule)) if rule else rounddown(value, 1)
|
||||
|
||||
|
||||
def places(row: dict, lines: list[dict]) -> None:
|
||||
"""호표 줄 `자리`(줄 자리) — 그 줄 금액만 단가 × 수량을 그 규칙으로 다시 버림(제자리)."""
|
||||
for item, ln in zip(row.get("호표", []), lines):
|
||||
rule = item.get("자리")
|
||||
if not rule or ln.get("qty") is None:
|
||||
continue
|
||||
for part, price in (ln.get("price") or {}).items():
|
||||
if part in PARTS and price is not None:
|
||||
ln[part] = _cut(price * ln["qty"], rule)
|
||||
|
||||
|
||||
def _engine(lines: list[dict]) -> list[dict]:
|
||||
"""B09 줄 → 엔진 줄 꼴 `{비목}`(번지 · 단계 셈)."""
|
||||
return [
|
||||
{"비목": {k: Decimal(str(ln.get(p) or 0)) for k, p in COST_PART.items()}} for ln in lines
|
||||
]
|
||||
|
||||
|
||||
def sums(row: dict, lines: list[dict]) -> dict[str, float | None]:
|
||||
"""덧줄 밑 비목 합 — 새 의미 로직은 합밖 · 제외 단계 줄을 뺌."""
|
||||
skip = ms.skipped(row) if ms.uses(row) else set()
|
||||
kept = [ln for n, ln in enumerate(lines) if n not in skip]
|
||||
return {name: total([ln[p] for ln in kept]) for name, p in COST_PART.items()}
|
||||
|
||||
|
||||
def scope(row: dict, lines: list[dict], env: dict) -> None:
|
||||
"""덧줄 식 이름 `번지` · `단계`(지금까지 줄) — 새 의미 로직만."""
|
||||
if ms.uses(row):
|
||||
env.update(ms.scope(row, _engine(lines)))
|
||||
|
||||
|
||||
def extra(row: dict, item: dict, value: float, env: dict) -> float:
|
||||
"""덧줄 금액 — 줄 `자리` 면 그 규칙 · 아니면 ROUNDDOWN 1 ·
|
||||
새 의미 로직은 뒤 덧줄이 그 값을 부름."""
|
||||
money = _cut(value, item.get("자리"))
|
||||
if ms.uses(row):
|
||||
env[item["이름"]] = Decimal(str(money))
|
||||
return money
|
||||
|
||||
|
||||
def totals(row: dict, lines: list[dict]) -> dict[str, float | None] | None:
|
||||
"""총계 — 새 의미 로직 = 합밖 · 제외 빼고 블록 끝전 · `끝수` · 조정(`master_cut.settle`) ·
|
||||
옛 로직 · 빈칸 비목 있음 = None(옛 `block_totals`)."""
|
||||
if not ms.uses(row):
|
||||
return None
|
||||
got = sums(row, lines)
|
||||
if any(v is None for v in got.values()):
|
||||
return None
|
||||
costs = mcut.settle(row, {k: Decimal(str(v)) for k, v in got.items()})
|
||||
out = {COST_PART[k]: float(v) for k, v in costs.items()}
|
||||
return {**out, "sum": sum(out.values())}
|
||||
|
||||
|
||||
# ── 문서 셈 답 길(855-F B9-3 · `Sangeun.Solver`) — 위 옛 길 = 산출근거 글 몫 ──────────
|
||||
def doc_cut(value: float, rule: dict | None) -> float:
|
||||
"""줄 끝수 — 줄 `자리` 면 그 규칙(새 계산기 `master_doc_calc.cut`) · 없으면 ROUNDDOWN 1."""
|
||||
return float(mc.cut(Decimal(str(value)), rule)) if rule else rounddown(value, 1)
|
||||
|
||||
@@ -1,419 +1,292 @@
|
||||
"""B09 산근 한 항목 → 엑셀 단가산출근거 꼴 텍스트 수식 줄들(PLAN 155-5) — 서버 단독(③ · 순수 함수).
|
||||
"""B09 산근 한 블록 → 산출근거 글 줄들(PLAN 155-5 · 855-F B9-4) — 서버 단독(③ · 순수 함수 · 셈 안 함).
|
||||
|
||||
꼴 = 엑셀 단가산출근거 탭 산출내역 한 칸 글:
|
||||
머리 「이름 / 단위」 · 출처 「… 적용」 · 입력 「이름 : 설명 = 값 단위」(157-1 · 설명 없으면
|
||||
「이름 : 값 단위」 · 기계 · 직종 번호 = 「이름 규격」 157-3 `M02_Labor_Inputs._labels`) ·
|
||||
함수(M01 흐름도 함수 상자 · 157-1) = 계산 차례대로 「이름 = 이름식 = 값 넣은 식 = 값」 —
|
||||
중간 · 결과(돈 아닌 로직) · 호표 수량(이름식이 값 꼴과 다를 때 「이름 수량 = …」) ·
|
||||
찾기 = 「표 이름(조건 = 값).칸」 · 만약 = 걸린 갈래만 · 하위 로직 = 로직 이름(산근 n호표) ·
|
||||
돈 아닌 하위 로직은 그 풀이를 「└ 」 줄로 이어 씀(작업량 Q = ROUND 2 — `Sangeun._env`) ·
|
||||
함수 줄은 모두 머리(호표 줄 수 그대로) ·
|
||||
줄 「보통인부 : 172,068 * 0.022 = 3,785.4」(단가 * 수량식 값 꼴[ / 배][ * 율 %] = 금액) ·
|
||||
중기 = 노무비 · 재료비 · 경비 세 줄 · 하위 산근 = 「산근 n호표 단가 * 수량」 ·
|
||||
% 덧줄 = 「이름 (노무비의 %) : 밑수 * n % = 금액」(규격 = 149-4 `pct_extras`) ·
|
||||
끝 = 「계 : 노무비 + 재료비 + 경비 = 합」.
|
||||
식 풀이 = 엔진 `master_text` 낮은 부품(render · _names · fmt) · 단가 = 인자 `price_of(key)`(B09 굳힌
|
||||
단가 · 엔진 단가 글은 안 씀) · 단가 없음 = 「단가 없음」 글.
|
||||
끝수 = 엑셀 자리 — 줄 ROUNDDOWN 1 · 계 비목마다 ROUNDDOWN 0(`Sangeun._money` · `block_totals`).
|
||||
`price_of(key)` — 인력 · 자재 키 → 수 | None · 기계(EQ) · 하위 산근(SG:) → {labor, material, expense
|
||||
[, sum, no]} | None.
|
||||
재료 = 산근 풀이 블록 줄(`B09_Estimation_Sangeun.Solver` · B09 수량 · 단가 · 금액) + 그 로직 문서 셈 답
|
||||
(`B09_Estimation_Doc_Run.Answer` · 입력 · 중간 값 · 단위) — 옛 엔진 · `master_text` 안 부름.
|
||||
수 꼴 · 단위 · 금액 줄 꼴 = 화면 줄 쌓기 산출근거 규칙(`master_doc_text` · 짝 `A00_Common/line_stack_out.ts`):
|
||||
머리 = 「이름 / 단위」 · 「출처 적용」 · 입력 「이름 : 설명 = 값 단위」(기계 · 직종 번호 = 「이름 규격」 157-3) ·
|
||||
공식 줄 「이름 = 이름식 = 값식 = 값 단위」(식 변수 · 같은 꼴은 한 번) · 표 · 하위 결과 값 「이름 = 값 단위」
|
||||
줄 = 「이름 : 단가 원/단위 × 수량 단위[ ÷ 배][ × 율 %] = 금액 원」(B09 단가 · 1 단위 수량 = 문서 수량 ÷ 배 × 율) ·
|
||||
중기 = 노무비 · 재료비 · 경비 세 줄 · 하위 산근 = 「산근 n호표 단가 × 수량」 ·
|
||||
% 덧줄 = 「이름 (노무비의 %) : 밑수 × n % = 금액 원」 · 못 셈 = 「이름 : — 까닭」
|
||||
끝 = 「계 : 노무비 + 재료비 + 경비 = 합」(블록 합 · B09 끝수).
|
||||
화면만인 것(옮기지 않음) = 식 조판 · 표 조건 글 · 만약 갈래 글 · 하위 결과 펼침 · 쌓기 묶음.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
import importlib
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from B09_Estimation import B09_Estimation_Sangeun as sg
|
||||
from B09_Estimation import B09_Estimation_Sangeun_Sum as ss
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
from M02_MasterTemplete import M02_Labor_Doc as labor_doc
|
||||
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
|
||||
|
||||
mf = sg.mf
|
||||
mtx = m01.mtx
|
||||
md = importlib.import_module("master_doc")
|
||||
mdt = importlib.import_module("master_doc_text")
|
||||
ml = importlib.import_module("master_doc_link")
|
||||
|
||||
PART_NAME = {"labor": "노무비", "material": "재료비", "expense": "경비"}
|
||||
_ERRORS = (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError)
|
||||
PARTS = tuple(PART_NAME)
|
||||
NO_PRICE = "단가 없음"
|
||||
|
||||
PriceOf = Callable[[str], Any]
|
||||
GAP = "—"
|
||||
INPUTS = ("입력", "선택")
|
||||
VALUES = ("표", "단가산출", "숫자") # 값만 줄(표 찾기 · 하위 결과 · 손 수)
|
||||
PACK = 4 # 값만 줄 = 넷까지 한 줄(화면 공식 묶음)
|
||||
|
||||
|
||||
def _money(value: float | None) -> str:
|
||||
return "빈칸" if value is None else f"{value:,.1f}"
|
||||
def _dec(v: Any) -> Decimal | None:
|
||||
return mdt._dec(v)
|
||||
|
||||
|
||||
def _price(value: Any) -> str:
|
||||
return NO_PRICE if value is None else mtx.fmt_price(Decimal(str(value)))
|
||||
|
||||
|
||||
def _qty_text(item: dict, env: dict, whole: Any, times: Decimal, rate: Decimal | None) -> str:
|
||||
"""수량식 값 꼴 — 덧셈 묶음이면 괄호 · 결과단위 배 「/ 배」 · 켜쌓기율 「* 율 %」."""
|
||||
text = mtx._times(mtx.render(mf.parse(item["수량"]), env, whole), item, env, whole)
|
||||
if times != 1:
|
||||
text += f" / {mtx.fmt(times)}"
|
||||
if rate is not None:
|
||||
text += f" * {mtx.fmt(rate * 100)} %"
|
||||
return text
|
||||
|
||||
|
||||
def _line(name: str, price: Any, qty_text: str, q: float, rule=None) -> tuple[str, float | None]:
|
||||
money = None if price is None else ss._cut(float(price) * q, rule) # 줄 자리(792-3)
|
||||
return f"{name} : {_price(price)} * {qty_text} = {_money(money)}", money
|
||||
|
||||
|
||||
def _head(row: dict, env: dict, whole: Any, times: Decimal, price_of: PriceOf) -> list[str]:
|
||||
unit = str(row.get("결과단위") or "").removeprefix("원/")
|
||||
if times != 1:
|
||||
unit = unit.removeprefix(mtx.fmt(times))
|
||||
out = [f"{row.get('이름') or row.get('키')} / {unit}"]
|
||||
if row.get("출처"):
|
||||
out.append(f"{row['출처']} 적용")
|
||||
return out + _steps(whole, row, env, price_of, 0)
|
||||
def _won(v: Any) -> str:
|
||||
return GAP if v is None else f"{v:,.0f}"
|
||||
|
||||
|
||||
def _word(whole: Any, name: str, value: Any) -> str:
|
||||
"""값 글 — 수 = 보이는 자릿수 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미)."""
|
||||
if isinstance(value, Decimal):
|
||||
return mtx.fmt(value)
|
||||
"""값 글 — 수 = 화면 수 꼴 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미)."""
|
||||
if isinstance(value, str):
|
||||
return labor_inputs._labels(whole, {"이름": name, "고르기": [value]}).get(value, value)
|
||||
return str(value)
|
||||
return mdt.eq_text(value) if _dec(value) is not None else str(value)
|
||||
|
||||
|
||||
def _shown(whole: Any, name: str, value: Any) -> str | None:
|
||||
if value is None or isinstance(value, mf.Blank):
|
||||
return "값 없음"
|
||||
return None if isinstance(value, dict) else _word(whole, name, value)
|
||||
# ── 머리(입력 · 공식) ────────────────────────────────────────────────
|
||||
def _bare(node: tuple) -> tuple:
|
||||
"""표시 자리 감싸개(`반올림(식, n)` · B09 작업량 Q) — 식 글은 속 식으로."""
|
||||
if node and node[0] == "call" and node[1] in ("반올림", "올림", "버림") and len(node[2]) == 2:
|
||||
return node[2][0]
|
||||
return node
|
||||
|
||||
|
||||
def _marks(row: dict, whole: Any) -> list[dict]:
|
||||
"""별칭(찾기 · 로직 부르기 → 짧은 이름 · `master_copy.aliases`) — 못 지으면 빈 목록."""
|
||||
try:
|
||||
return mtx.mc.aliases(row, whole)
|
||||
except _ERRORS:
|
||||
return []
|
||||
def _swap(node: Any, put) -> Any:
|
||||
"""식 나무의 기호 바꿈 — `put(이름)` 이 None 이면 그대로."""
|
||||
if not isinstance(node, tuple):
|
||||
return node
|
||||
if node[0] == "var":
|
||||
got = put(node[1])
|
||||
return node if got is None else got
|
||||
if node[0] == "call":
|
||||
return ("call", node[1], [_swap(x, put) for x in node[2]])
|
||||
return tuple(_swap(x, put) for x in node)
|
||||
|
||||
|
||||
def _call_text(whole: Any, mark: dict, env: dict, price_of: PriceOf) -> str | None:
|
||||
"""별칭 자리 글 — 찾기 = 「표 이름(조건 = 값)」 · 로직 = 「로직 이름(산근 n호표)」."""
|
||||
try:
|
||||
node = mf.parse(mark["원문"])
|
||||
ref = mf.fill(node[1], env)
|
||||
args = [(k, mf.evaluate(v, env, whole, 0)) for k, v in node[2]]
|
||||
except _ERRORS:
|
||||
return None
|
||||
if mark["종류"] == "찾기":
|
||||
conds = ", ".join(f"{k} = {_word(whole, k, v)}" for k, v in args)
|
||||
return f"{mark.get('밑이름') or mark['이름']}{f'({conds})' if conds else ''}"
|
||||
try:
|
||||
name = str(whole.logic(ref).get("이름") or ref)
|
||||
except mf.FormulaError:
|
||||
return None
|
||||
got = (
|
||||
price_of(sg.sangeun_key(ref, sg._clean_given(dict(args))))
|
||||
if sg.is_money(whole, ref)
|
||||
else None
|
||||
)
|
||||
return f"{name}(산근 {got['no']}호표)" if isinstance(got, dict) and got.get("no") else name
|
||||
def _label(i: str, var: dict) -> str:
|
||||
"""기호 화면 이름 — 원래 이름(열쇠) · 지은 기호(열쇠 = 기호 · 표 칸)면 변수 이름(「표 이름.칸」)."""
|
||||
key = str(var.get("열쇠") or "")
|
||||
return key if key and key != i else str(var.get("이름") or i)
|
||||
|
||||
|
||||
def _named(text: str, env: dict, whole: Any, marks: list[dict], price_of: PriceOf) -> str:
|
||||
"""이름 꼴 식 — 별칭은 찾기 표 이름(조건) · 로직 이름으로 바꿔 씀."""
|
||||
named = mtx._names(text, env, whole, mtx.mc.names(marks))
|
||||
for mark in sorted(marks, key=lambda m: -len(m["이름"])):
|
||||
pattern = rf"(?<![\w]){re.escape(mark['이름'])}(?![\w])"
|
||||
shown = re.search(pattern, named) and _call_text(whole, mark, env, price_of)
|
||||
if shown:
|
||||
named = re.sub(pattern, lambda _m, s=shown: s, named)
|
||||
return named
|
||||
class _Head:
|
||||
def __init__(self, whole: Any, answer: Any) -> None:
|
||||
self.whole, self.answer = whole, answer
|
||||
self.doc, self.values = answer.doc, answer.ans.get("값") or {}
|
||||
self.vars = {md.var_id(v): v for v in self.doc.get("변수") or []}
|
||||
self.names = {i: _label(i, v) for i, v in self.vars.items()}
|
||||
|
||||
def unit(self, i: str) -> str:
|
||||
return mdt.unit_text((self.vars.get(i) or {}).get("단위"))
|
||||
|
||||
def _valued(show, real, env: dict, whole: Any, depth: int = 0) -> str:
|
||||
"""값 꼴 식 — 엔진 `render` 와 같되 반올림 · 최소 · 최대 부르기는 값 넣은 인자째 ·
|
||||
만약 = 걸린 갈래."""
|
||||
if show[0] == "call" and show[1] != "만약":
|
||||
args = ", ".join(_valued(s, r, env, whole, depth) for s, r in zip(show[2], real[2]))
|
||||
return f"{show[1]}({args})"
|
||||
if show[0] == "call":
|
||||
at = 1 if mf.evaluate(real[2][0], env, whole, depth) else 2
|
||||
return _valued(show[2][at], real[2][at], env, whole, depth)
|
||||
if show[0] == "bin":
|
||||
return mtx._bin(show, real, env, whole, depth, _valued)
|
||||
if show[0] == "neg":
|
||||
return "-" + _valued(show[1], real[1], env, whole, depth)
|
||||
return mtx._draw(show, real, env, whole, depth)
|
||||
def value(self, i: str) -> str:
|
||||
v = self.values.get(i)
|
||||
if v is None:
|
||||
return "값 없음"
|
||||
if isinstance(v, dict):
|
||||
return " · ".join(f"{c} {mdt.eq_text(v.get(c))}" for c in mdt.COSTS)
|
||||
return " ".join(x for x in (_word(self.whole, self.names.get(i, i), v), self.unit(i)) if x)
|
||||
|
||||
|
||||
def _formula(name, text, value, env, whole, marks, price_of, unit="") -> str:
|
||||
"""함수 한 줄 「이름 = 이름식 = 값 넣은 식 = 값」 — 같은 글이 이어지면 한 번만 ·
|
||||
글 값(기계 원문번호 따위)은 따옴표 글을 빼고 「이름 규격」 만(157-3)."""
|
||||
parts = [name]
|
||||
literal = f"'{value}'" if isinstance(value, str) else None
|
||||
for make in (
|
||||
lambda: _named(text, env, whole, marks, price_of),
|
||||
lambda: _valued(*[mf.parse(text)] * 2, env, whole),
|
||||
lambda: _shown(whole, name, value),
|
||||
):
|
||||
try:
|
||||
got = make()
|
||||
except _ERRORS:
|
||||
got = None
|
||||
if got and got != parts[-1] and got != literal:
|
||||
parts.append(got)
|
||||
tail = f" {unit}" if unit and unit != "-" and isinstance(value, Decimal) else ""
|
||||
return " = ".join(parts) + tail
|
||||
|
||||
|
||||
def _expand(whole, mark: dict, env: dict, price_of: PriceOf, depth: int) -> list[str]:
|
||||
"""돈 아닌 하위 로직 풀이 — 그 로직의 입력 · 중간 · 결과를 「└ 」 줄로(돈 로직 = 산근 호표)."""
|
||||
if mark["종류"] != "로직" or depth > 3:
|
||||
return []
|
||||
try:
|
||||
node = mf.parse(mark["원문"])
|
||||
ref = mf.fill(node[1], env)
|
||||
row = whole.logic(ref)
|
||||
if "결과" not in row or isinstance(row.get("흐름"), dict):
|
||||
return []
|
||||
sub = mf._inputs(row, {k: mf.evaluate(v, env, whole, 0) for k, v in node[2]})
|
||||
for step in row.get("중간", []):
|
||||
try:
|
||||
sub[step["이름"]] = mf.evaluate(mf.parse(step["식"]), sub, whole, depth + 1)
|
||||
except mf.EmptyInput as e:
|
||||
sub[step["이름"]] = mf.Blank(str(e))
|
||||
except _ERRORS:
|
||||
return []
|
||||
lead = " " * depth + "└ "
|
||||
return [lead + line for line in _steps(whole, row, sub, price_of, depth + 1)]
|
||||
|
||||
|
||||
def _steps(whole, row: dict, env: dict, price_of: PriceOf, depth: int) -> list[str]:
|
||||
"""흐름도 함수 상자 차례 — 입력(약어 뜻) · 중간 · 결과 · 호표 수량(맨 위만) · 하위 로직 풀이."""
|
||||
out: list[str] = []
|
||||
for spec in row.get("입력", []):
|
||||
value = env.get(spec["이름"])
|
||||
if value is None:
|
||||
continue
|
||||
tail = f" {spec['단위']}" if spec.get("단위") else ""
|
||||
about = f"{spec['설명']} = " if spec.get("설명") else ""
|
||||
out.append(f"{spec['이름']} : {about}{_word(whole, spec['이름'], value)}{tail}")
|
||||
marks = _marks(row, whole)
|
||||
done: set[str] = set()
|
||||
|
||||
def subs(where: str) -> list[str]:
|
||||
lines = []
|
||||
for mark in marks:
|
||||
if mark["이름"] not in done and where in mark.get("자리", []):
|
||||
done.add(mark["이름"])
|
||||
lines += _expand(whole, mark, env, price_of, depth)
|
||||
return lines
|
||||
|
||||
for n, step in enumerate(row.get("중간", [])):
|
||||
value = env.get(step["이름"])
|
||||
if value is None or isinstance(value, mf.Blank):
|
||||
out.append(f"{step['이름']} = 값 없음")
|
||||
continue
|
||||
unit = step.get("단위") or _find_unit(step["식"], marks)
|
||||
out.append(_formula(step["이름"], step["식"], value, env, whole, marks, price_of, unit))
|
||||
out += subs(f"중간[{n}].식")
|
||||
if "결과" in row:
|
||||
try:
|
||||
value = mf.cut(row, mf.evaluate(mf.parse(row["결과"]["식"]), env, whole, depth), "결과")
|
||||
except _ERRORS:
|
||||
value = None
|
||||
out.append(_formula("결과", row["결과"]["식"], value, env, whole, marks, price_of))
|
||||
out += subs("결과.식")
|
||||
if depth:
|
||||
return out
|
||||
for n, item in enumerate(row.get("호표", [])):
|
||||
try:
|
||||
raw = mf.evaluate(mf.parse(item["수량"]), env, whole, 0)
|
||||
named = _named(item["수량"], env, whole, marks, price_of)
|
||||
valued = _valued(*[mf.parse(item["수량"])] * 2, env, whole)
|
||||
except _ERRORS:
|
||||
continue
|
||||
if named != valued:
|
||||
name = f"{item.get('이름', '')} 수량"
|
||||
out.append(
|
||||
_formula(name, item["수량"], raw, env, whole, marks, price_of, item.get("단위"))
|
||||
def formula(self, i: str, text: str) -> str:
|
||||
"""「이름 = 이름식 = 값식 = 값 단위」 — 같은 글이 이어지면 한 번만."""
|
||||
node = _decide(mdt.node_of(text), self.answer) # 만약 = 걸린 갈래
|
||||
parts = [self.names.get(i, i)]
|
||||
if node is not None:
|
||||
node = _bare(node)
|
||||
named = md.text_of(
|
||||
_swap(node, lambda n: ("var", self.names[n]) if n in self.names else None)
|
||||
)
|
||||
out += subs(f"호표[{n}].수량")
|
||||
return out
|
||||
valued = md.text_of(_swap(node, self._num))
|
||||
parts += [named, valued]
|
||||
v = self.values.get(i)
|
||||
bare = mdt.eq_text(v) if _dec(v) is not None else f"'{v}'" if isinstance(v, str) else None
|
||||
out = [parts[0]]
|
||||
for p in parts[1:]: # 같은 글 · 값 그대로인 식 = 한 번만(화면 공식 줄)
|
||||
if p and p != out[-1] and p != bare:
|
||||
out.append(p)
|
||||
out.append(self.value(i))
|
||||
return " = ".join(out)
|
||||
|
||||
def _num(self, name: str):
|
||||
v = self.values.get(name)
|
||||
d = _dec(v)
|
||||
return ("var", mdt.eq_text(d)) if d is not None else None
|
||||
|
||||
def _find_unit(text: str, marks: list[dict]) -> str:
|
||||
"""식이 표 찾기 한 칸뿐이면 그 칸 단위(별칭 `값칸`) · 그 밖 = 빈 글."""
|
||||
for mark in marks:
|
||||
head = mark["원문"]
|
||||
if mark["종류"] == "찾기" and text.replace(" ", "").startswith(head.replace(" ", "") + "."):
|
||||
unit = (mark.get("값칸") or {}).get(text.rpartition(".")[2], "")
|
||||
return "" if unit in ("글", "구분 따름") else unit
|
||||
return ""
|
||||
def lines(self, times: Decimal) -> list[str]:
|
||||
doc = self.doc
|
||||
out = [f"{doc.get('이름') or doc.get('키')} / {mdt.unit_text(_per_unit(doc, times))}"]
|
||||
if doc.get("출처"):
|
||||
out.append(f"{doc['출처']} 적용")
|
||||
steps = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []}
|
||||
pack: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
if pack:
|
||||
out.append(" · ".join(pack))
|
||||
pack.clear()
|
||||
|
||||
def _material_key(whole: Any, item: dict, ref: Any, env: dict, n: int) -> tuple[str, str]:
|
||||
"""자재 줄 (대비표 키, 규격) — 자리표시 글(「MO:경유:전국평균」)은 그 요소의 실제 키로."""
|
||||
_p, source, _w, extra = mf.mp.priced(whole, item, ref, env, n)
|
||||
goods = (extra or {}).get("품목") or {}
|
||||
key = str(
|
||||
goods.get("키") or (source or "").split(".")[0] or (ref if isinstance(ref, str) else "")
|
||||
)
|
||||
if ":" in key:
|
||||
try:
|
||||
key = str(whole.get(key).get("키") or key)
|
||||
except _ERRORS:
|
||||
pass
|
||||
return key, str(goods.get("규격") or "")
|
||||
|
||||
|
||||
def _logic_lines(whole, item, env, qty_text, q, price_of) -> list[tuple[str, dict]]:
|
||||
"""로직 부르기 줄 — 기계경비 = 중기 노 · 재 · 경 세 줄 · 그 밖 = 하위 산근 한 줄 ·
|
||||
금액 끝수 = 줄 `자리`(792-4 · `Sangeun_Sum.places` 와 같음)."""
|
||||
node = mf.parse(item["요소"])
|
||||
called = node[1] if node and node[0] == "logic" else None
|
||||
try:
|
||||
target = whole.logic(called) if called else None
|
||||
except mf.FormulaError:
|
||||
target = None
|
||||
name = item.get("이름", "")
|
||||
if mf.mb.is_machine(target): # 기계경비 판별 한 곳(712-1)
|
||||
keys = sg._captured(whole, node, env)
|
||||
got = price_of(keys[0]) if keys else None
|
||||
if not got:
|
||||
return [(f"{name} : {NO_PRICE} * {qty_text}", dict.fromkeys(sg.PARTS))]
|
||||
out = []
|
||||
for part in sg.PARTS:
|
||||
text, money = _line(
|
||||
f"{name} {PART_NAME[part]}", got.get(part), qty_text, q, item.get("자리")
|
||||
)
|
||||
out.append((text, {part: money}))
|
||||
for i, v in self.vars.items():
|
||||
kind = (v.get("연결") or {}).get("갈래")
|
||||
if kind in INPUTS and self.values.get(i) is not None:
|
||||
about = f"{v['설명']} = " if v.get("설명") else ""
|
||||
flush()
|
||||
out.append(f"{v.get('열쇠') or self.names[i]} : {about}{self.value(i)}")
|
||||
elif kind == "식" and i in steps:
|
||||
flush()
|
||||
out.append(self.formula(i, steps[i]))
|
||||
elif kind in VALUES and _dec(self.values.get(i)) is not None:
|
||||
pack.append(f"{self.names[i]} = {self.value(i)}")
|
||||
if len(pack) >= PACK:
|
||||
flush()
|
||||
flush()
|
||||
return out
|
||||
if not target:
|
||||
return [(f"{name} : 하위 로직을 못 펼침", dict.fromkeys(sg.PARTS))]
|
||||
given = {k: mf.evaluate(expr, env, whole, 1) for k, expr in node[2]}
|
||||
got = price_of(sg.sangeun_key(called, sg._clean_given(given))) or {}
|
||||
parts = {p: got.get(p) for p in sg.PARTS}
|
||||
if any(v is None for v in parts.values()):
|
||||
return [(f"{name} : {NO_PRICE} * {qty_text}", dict.fromkeys(sg.PARTS))]
|
||||
amounts = {p: ss._cut(float(v) * q, item.get("자리")) for p, v in parts.items()}
|
||||
head = f"산근 {got['no']}호표 " if got.get("no") else ""
|
||||
unit = sum(float(v) for v in parts.values())
|
||||
text = f"{name} : {head}{_price(unit)} * {qty_text} = {_money(sum(amounts.values()))}"
|
||||
return [(text, amounts)]
|
||||
|
||||
|
||||
def _pct_specs(whole, row, env) -> list[str]:
|
||||
"""% 덧줄마다 규격(「노무비의 %」 · 149-4 `M02_Labor_Doc.pct_extras`) · % 아닌 덧줄 = 빈 글."""
|
||||
head = [{} for _ in row.get("호표", [])]
|
||||
tail = [{} for _ in row.get("덧줄", [])]
|
||||
got = labor_doc.pct_extras(whole, row, head + tail, dict(env))[len(head) :]
|
||||
return [str(one.get("규격") or "") for one in got]
|
||||
def _per_unit(doc: dict, times: Decimal) -> str:
|
||||
"""결과단위 1 단위 이름(「원/10㎡」 = ㎡ · 배 1 = 그대로 「원/1기」 = 1기)."""
|
||||
unit = str(doc.get("결과단위") or "").removeprefix("원/")
|
||||
return unit.removeprefix(mdt.eq_text(times)) if times != 1 else unit
|
||||
|
||||
|
||||
def _full(amounts: list[dict]) -> list[dict]:
|
||||
return [{**dict.fromkeys(sg.PARTS, 0.0), **a} for a in amounts]
|
||||
# ── 금액 줄 ───────────────────────────────────────────────────────────
|
||||
class _Docs:
|
||||
"""`master_doc_text.money_units` 의 하위 문서 읽기 — 사본 문서 묶음에서."""
|
||||
|
||||
def __init__(self, docs: dict) -> None:
|
||||
self.docs = docs
|
||||
|
||||
def doc(self, key: str) -> dict | None:
|
||||
return self.docs.get(key)
|
||||
|
||||
|
||||
def _extra_lines(whole, row, env, amounts: list[dict]) -> list[tuple[str, dict]]:
|
||||
"""% 줄(덧줄) — 밑수 = 그때까지 B09 비목 합(`Sangeun._extras` 와 같음) · 금액 ROUNDDOWN 1."""
|
||||
out: list[tuple[str, dict]] = []
|
||||
specs = _pct_specs(whole, row, env)
|
||||
for extra, spec in zip(row.get("덧줄", []), specs):
|
||||
part = sg.COST_PART.get(extra.get("비목"), "material")
|
||||
sums = ss.sums(row, _full(amounts)) # 합밖 · 제외(792-3)
|
||||
head = f"{extra['이름']}{f' ({spec})' if spec else ''} : "
|
||||
if any(v is None for v in sums.values()):
|
||||
out.append((f"{head}밑수 빈칸", {part: None}))
|
||||
amounts.append({part: None})
|
||||
continue
|
||||
env.update({k: Decimal(str(v)) for k, v in sums.items()})
|
||||
ss.scope(row, _full(amounts), env) # 번지 · 단계(792-3)
|
||||
try:
|
||||
node = mf.parse(extra["식"])
|
||||
value = float(mf.evaluate(node, env, whole, 0))
|
||||
shown = mtx.render(node, env, whole)
|
||||
except _ERRORS as e:
|
||||
out.append((f"{head}계산 못 함 — {e}", {part: None}))
|
||||
amounts.append({part: None})
|
||||
continue
|
||||
money = ss.extra(row, extra, value, env) # 줄 자리(792-3)
|
||||
out.append((f"{head}{shown} = {_money(money)}", {part: money}))
|
||||
amounts.append({part: money})
|
||||
return out
|
||||
def _units(answer: Any, n: int) -> dict:
|
||||
doc = answer.doc
|
||||
line = (doc.get("금액") or [])[n]
|
||||
sym = mdt.price_sym(line)
|
||||
var = answer.vars.get(sym) if sym else None
|
||||
link = (var or {}).get("연결") or {}
|
||||
sub = (answer.docs or {}).get(str(link.get("키"))) if link.get("갈래") == "단가산출" else None
|
||||
qty = mdt.node_of(line.get("수량"))
|
||||
return mdt.money_units(line, mdt.node_of(line.get("단가")), qty, var, sub)
|
||||
|
||||
|
||||
def render_sangeun_text(
|
||||
def _qty(answer: Any, n: int, units: dict, times: Decimal, rate: Decimal | None) -> str:
|
||||
"""수량 글 — 값 넣은 수량 식(화면 금액 줄 「× (수량 식) 단위」 · 식이면 괄호) 단위[ ÷ 배][ × 율 %]."""
|
||||
raw = (answer.ans.get("줄") or [{}] * (n + 1))[n].get("수량")
|
||||
node = _decide(mdt.node_of(((answer.doc.get("금액") or [])[n]).get("수량")), answer)
|
||||
values = answer.ans.get("값") or {}
|
||||
shown = mdt.eq_text(raw)
|
||||
if node is not None and not mdt.is_atom(node):
|
||||
put = lambda s: ("var", mdt.eq_text(values[s])) if _dec(values.get(s)) is not None else None # noqa: E731
|
||||
shown = f"({md.text_of(_swap(_bare(node), put))})"
|
||||
text = mdt._u(shown, units["qty"])
|
||||
if times != 1:
|
||||
text += f" ÷ {mdt.eq_text(times)}"
|
||||
if rate is not None:
|
||||
text += f" × {mdt.eq_text(rate * 100)} %"
|
||||
return text
|
||||
|
||||
|
||||
def _decide(node: Any, answer: Any) -> Any:
|
||||
"""만약 = 걸린 갈래만(화면 `decide` · 조건 = 셈 답 값 · `master_doc_text._Look`)."""
|
||||
if node is None:
|
||||
return None
|
||||
look = getattr(answer, "_look", None)
|
||||
if look is None:
|
||||
look = answer._look = mdt._Look(answer.doc, answer.ans, ml.Links(answer.whole, answer.docs))
|
||||
|
||||
def walk(n: Any) -> Any:
|
||||
if not isinstance(n, tuple):
|
||||
return n
|
||||
if (pick := look.taken(n)) and n[0] == "call":
|
||||
return walk(n[2][pick])
|
||||
if n[0] == "call":
|
||||
return ("call", n[1], [walk(x) for x in n[2]])
|
||||
return tuple(walk(x) for x in n)
|
||||
|
||||
return walk(node)
|
||||
|
||||
|
||||
def _price(v: Any, unit: str) -> str:
|
||||
return NO_PRICE if v is None else mdt._u(mdt.eq_text(v), unit)
|
||||
|
||||
|
||||
def _amount(v: Any) -> str:
|
||||
return GAP if v is None else f"{mdt.one(v)} {mdt.AMOUNT_UNIT}"
|
||||
|
||||
|
||||
def _line_texts(
|
||||
ln: dict, answer: Any, n: int, times: Decimal, rate: Decimal | None, no_of
|
||||
) -> list[str]:
|
||||
name, kind = ln.get("name") or "", ln.get("kind")
|
||||
if kind == "blank":
|
||||
return [f"{name} : {GAP} {ln.get('why') or '못 셈'}"]
|
||||
units = _units(answer, n)
|
||||
qty = _qty(answer, n, units, times, rate)
|
||||
price = ln.get("price") or {}
|
||||
if kind == "machine" and ln.get("why"): # 기계 시간당 없음 = 한 줄(풀이 줄 글 수와 같게)
|
||||
return [f"{name} : {NO_PRICE} × {qty} = {GAP}"]
|
||||
if kind == "machine":
|
||||
return [
|
||||
f"{name} {PART_NAME[p]} : {_price(price.get(p), units['price'])} × {qty} = "
|
||||
f"{_amount(ln.get(p))}"
|
||||
for p in PARTS
|
||||
]
|
||||
if kind == "sangeun":
|
||||
no = no_of((ln.get("ref") or {}).get("key"))
|
||||
unit = None if any(price.get(p) is None for p in PARTS) else sum(price[p] for p in PARTS)
|
||||
money = None if unit is None else sum(ln.get(p) or 0 for p in PARTS)
|
||||
head = f"산근 {no}호표 " if no else ""
|
||||
return [f"{name} : {head}{_price(unit, units['price'])} × {qty} = {_amount(money)}"]
|
||||
part = next(iter(price), None) or next((p for p in PARTS if ln.get(p)), "material")
|
||||
shown = ln.get(part)
|
||||
label = f"{name}({ln['spec']})" if kind == "material" and ln.get("spec") else name
|
||||
return [f"{label} : {_price(price.get(part), units['price'])} × {qty} = {_amount(shown)}"]
|
||||
|
||||
|
||||
def _extra_text(ln: dict) -> str:
|
||||
"""% 덧줄 · 고정 덧줄 — 밑수 × 율 % · 값 하나."""
|
||||
spec = f" ({ln.get('spec')})" if ln.get("unit") == "%" and ln.get("spec") else ""
|
||||
head = f"{ln['name']}{spec} : "
|
||||
part = next(iter(ln.get("price") or {}), None)
|
||||
if part is None or ln.get(part) is None:
|
||||
return f"{head}{GAP} {ln.get('why') or '밑수 빈칸'}"
|
||||
value, money = ln["price"][part], ln[part]
|
||||
if ln.get("unit") == "%" and ln.get("qty"):
|
||||
base = Decimal(str(value)) * 100 / Decimal(str(ln["qty"]))
|
||||
return f"{head}{mdt.eq_text(base)} × {mdt.eq_text(ln['qty'])} % = {_amount(money)}"
|
||||
return f"{head}{mdt.eq_text(value)} = {_amount(money)}"
|
||||
|
||||
|
||||
def render(
|
||||
whole: Any,
|
||||
logic_id: str,
|
||||
inputs: dict | None,
|
||||
price_of: PriceOf,
|
||||
answer: Any,
|
||||
lines: list[dict],
|
||||
*,
|
||||
times: Any = 1,
|
||||
rate: Any = None,
|
||||
picks: dict | None = None,
|
||||
) -> list[str]:
|
||||
"""산근 한 항목(로직 + 입력값 + 단가) → 엑셀 꼴 글 줄들.
|
||||
|
||||
whole = 사본 단가 묶음(`item_prices.load_prices`) · inputs = 입력값(빈 칸 = 자동값) ·
|
||||
price_of = B09 단가 조회 · times = 결과단위 배(「원/10㎡」 = 10) ·
|
||||
rate = 켜쌓기율 %(100 · None = 없음) · picks = 고른 자재."""
|
||||
try:
|
||||
row = whole.logic(logic_id)
|
||||
except mf.FormulaError as e:
|
||||
return [f"{logic_id} : 로직 없음 — {e}"]
|
||||
no_of=lambda _key: None,
|
||||
) -> tuple[list[str], list[list[str]]]:
|
||||
"""산근 한 블록 → (머리 줄들, 블록 줄마다 글 줄들 · 중기 = 셋) — `answer` = 그 로직 문서 셈 답
|
||||
(켜쌓기율 없이 · 결과단위 몫) · `lines` = 풀이 블록 줄(관급 0 원 앞) · times = 결과단위 배 ·
|
||||
rate = 켜쌓기율 % · `no_of(산근 키)` = 하위 산근 호표 번호."""
|
||||
times = Decimal(str(times or 1))
|
||||
scale = Decimal(str(rate)) / 100 if rate not in (None, 100) else None
|
||||
try:
|
||||
env = sg._env(whole, row, sg._clean_given(inputs))
|
||||
except _ERRORS as e:
|
||||
return [f"{row.get('이름') or logic_id} : 입력을 못 읽음 — {e}"]
|
||||
out = _head(row, env, whole, times, price_of)
|
||||
amounts: list[dict] = []
|
||||
with mf.mp.choosing(picks):
|
||||
for n, item in enumerate(row.get("호표", [])):
|
||||
name = item.get("이름", "")
|
||||
try:
|
||||
raw = mf.evaluate(mf.parse(item["수량"]), env, whole, 0)
|
||||
qty_text = _qty_text(item, env, whole, times, scale)
|
||||
except mf.EmptyInput as e:
|
||||
out.append(f"{name} : 수량 없음 — {e}")
|
||||
amounts.append({sg.COST_PART.get(item.get("비목"), "material"): None})
|
||||
continue
|
||||
q = float(Decimal(str(raw)) / times * (scale or 1))
|
||||
kind = item.get("종류")
|
||||
if kind == "로직":
|
||||
merged: dict = {} # 줄 하나 = 금액 하나(중기 세 줄 · 792-3 합밖 · 번지 차례)
|
||||
for text, money in _logic_lines(whole, item, env, qty_text, q, price_of):
|
||||
out.append(text)
|
||||
merged.update(money)
|
||||
amounts.append(merged)
|
||||
continue
|
||||
if kind == "인력":
|
||||
key = mf.fill(item["요소"], env) if isinstance(item["요소"], str) else ""
|
||||
text, money = _line(name, price_of(key), qty_text, q, item.get("자리"))
|
||||
out.append(text)
|
||||
amounts.append({"labor": money})
|
||||
continue
|
||||
ref = (
|
||||
{k: mf.fill(v, env) if isinstance(v, str) else v for k, v in item["요소"].items()}
|
||||
if isinstance(item["요소"], dict)
|
||||
else mf.fill(item["요소"], env)
|
||||
)
|
||||
key, spec = _material_key(whole, item, ref, env, n)
|
||||
price = price_of(key)
|
||||
if q == 0 and price is None:
|
||||
price = 0.0 # 안 쓰는 재료 줄 — 금액 0(`Sangeun._line` 과 같음)
|
||||
label = f"{name}({spec})" if spec else name
|
||||
text, money = _line(label, price, qty_text, q, item.get("자리"))
|
||||
out.append(text)
|
||||
amounts.append({sg.COST_PART.get(item.get("비목"), "material"): money})
|
||||
for text, _money_part in _extra_lines(whole, row, env, amounts):
|
||||
out.append(text)
|
||||
sums = ss.totals(row, _full(amounts)) or sg.block_totals(_full(amounts)) # 끝전 · 조정(792-3)
|
||||
parts = " + ".join(
|
||||
f"{PART_NAME[p]} {'빈칸' if sums[p] is None else f'{sums[p]:,.0f}'}" for p in sg.PARTS
|
||||
)
|
||||
out.append(f"계 : {parts} = {'빈칸' if sums['sum'] is None else f'{sums["sum"]:,.0f}'}")
|
||||
return out
|
||||
head = _Head(whole, answer).lines(times)
|
||||
heads = len([x for x in lines if x.get("kind") != "extra"])
|
||||
texts = [
|
||||
_line_texts(ln, answer, n, times, scale, no_of) if n < heads else [_extra_text(ln)]
|
||||
for n, ln in enumerate(lines)
|
||||
]
|
||||
return head, texts
|
||||
|
||||
|
||||
def foot(sums: dict) -> str:
|
||||
"""계 줄 — 블록 비목 합(B09 끝수 · 관급 0 원 뒤)."""
|
||||
parts = " + ".join(f"{PART_NAME[p]} {_won(sums.get(p))}" for p in PARTS)
|
||||
return f"계 : {parts} = {_won(sums.get('sum'))}"
|
||||
|
||||
@@ -6,15 +6,15 @@
|
||||
"daega_inputs": "a06884bce408c602",
|
||||
"수요": "5fdf7c49052e322c",
|
||||
"산근 값": "38455c2edce885ff",
|
||||
"산근 글": "c41b0c2e4ae200fb",
|
||||
"산근 글": "f5b884a2c49c91c6",
|
||||
"산근 관급 값": "d154925ee64c985c",
|
||||
"산근 관급 글": "396194c98b10b525",
|
||||
"산근 관급 글": "9397c1d1a5fe0dcd",
|
||||
"미리보기 hand:rate 값": "091690571b7dc54b",
|
||||
"미리보기 hand:rate 글": "c49b1bc692d59fe5",
|
||||
"미리보기 hand:rate 글": "d17615784f25e4f5",
|
||||
"미리보기 hand:pick 값": "6c7f426d37e31998",
|
||||
"미리보기 hand:pick 글": "96a9de9a02e3d124",
|
||||
"미리보기 hand:pick 글": "7836022de46b3072",
|
||||
"미리보기 hand:net 값": "b1c2c650567a14ae",
|
||||
"미리보기 hand:net 글": "9846e15ac6f0f663",
|
||||
"미리보기 hand:net 글": "0254ea22d7a23e43",
|
||||
"B08 단위수량": "896710398b04b4fd"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,52 @@ def fingerprint(key: str, row: dict, options: bool = True) -> str:
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _old_env(whole, row: dict, given: dict) -> dict:
|
||||
"""옛 B09 `Sangeun._env`(B9-4 에서 B09 는 걷음 · 대조 기준만) — 입력(빈 입력 = 자동값) + 중간값 ·
|
||||
작업량 Q = ROUND 2 · `표시` 자리."""
|
||||
import re
|
||||
|
||||
from B09_Estimation.B09_Estimation_Calc_Base import round_half
|
||||
|
||||
ms = importlib.import_module("master_formula_sum")
|
||||
auto = {k: v for k, v in m01.mau.values(whole, row).items() if v is not None}
|
||||
env = mf._inputs(row, {**auto, **m01._dec(given or {})})
|
||||
for step in row.get("중간", []):
|
||||
try:
|
||||
value = mf.evaluate(mf.parse(step["식"]), env, whole, 0)
|
||||
except mf.EmptyInput as e:
|
||||
env[step["이름"]] = mf.Blank(str(e))
|
||||
continue
|
||||
if step.get("표시") is not None or ms.uses(row):
|
||||
value = ms.shown(step, value)
|
||||
elif re.fullmatch(r"Q\d*", step["이름"]) and isinstance(value, Decimal):
|
||||
value = Decimal(str(round_half(float(value), 2)))
|
||||
env[step["이름"]] = value
|
||||
return env
|
||||
|
||||
|
||||
def _old_captured(whole, node, env: dict) -> list[str]:
|
||||
"""옛 B09 `Sangeun._captured` — 식을 돌리며 부른 기계 키(EQ)."""
|
||||
seen: list[str] = []
|
||||
base = whole.get
|
||||
|
||||
def get(ref):
|
||||
row = base(ref)
|
||||
key = str(row.get("키") or "")
|
||||
if key.startswith("EQ") and key not in seen:
|
||||
seen.append(key)
|
||||
return row
|
||||
|
||||
whole.get = get
|
||||
try:
|
||||
mf.evaluate(node, env, whole, 1)
|
||||
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
whole.get = base
|
||||
return seen
|
||||
|
||||
|
||||
def old_line_calls(whole, code: str, given) -> dict:
|
||||
"""옛 엔진 하위 부름(855-F B9-3 전 `B09 line_calls` · 대조 기준 · 2-E4 에서 은퇴) — 로직 호표 줄
|
||||
차례 → 기계경비 {machine} · 돈 로직 {code, given} · 못 셈 = None."""
|
||||
@@ -171,7 +217,7 @@ def old_line_calls(whole, code: str, given) -> dict:
|
||||
|
||||
try:
|
||||
row = whole.logic(code)
|
||||
env = sg._env(whole, row, sg._clean_given(given))
|
||||
env = _old_env(whole, row, sg._clean_given(given))
|
||||
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
|
||||
return {}
|
||||
out: dict = {}
|
||||
@@ -185,7 +231,7 @@ def old_line_calls(whole, code: str, given) -> dict:
|
||||
if not target:
|
||||
out[n] = None
|
||||
elif mf.mb.is_machine(target):
|
||||
keys = sg._captured(whole, node, env)
|
||||
keys = _old_captured(whole, node, env)
|
||||
out[n] = {"machine": keys[0] if keys else None}
|
||||
else:
|
||||
given_ = {name: mf.evaluate(expr, env, whole, 1) for name, expr in node[2]}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""155-5 산근 텍스트 수식 — 엑셀 단가산출근거 꼴 글 줄(`B09_Estimation_Sangeun_Text`).
|
||||
"""155-5 · 855-F B9-4 산근 산출근거 글(`B09_Estimation_Sangeun_Text.render`) — 풀이 블록 + 문서 셈 답.
|
||||
|
||||
- 엑셀 6호표 뒷채움: 「보통인부 : 165,545 * 0.018 = 2,979.8」 · 중기 노 · 재 · 경 세 줄 ·
|
||||
「계 : 노무비 6,878 + 재료비 538 + 경비 912 = 8,328」(줄 ROUNDDOWN 1 · 계 ROUNDDOWN 0)
|
||||
- 엑셀 7호표 막자갈채집: 작업량 Q = ROUND 2 중간 줄 · 「55,700 * 1 / 21.59 * 2 = 5,159.7」
|
||||
- % 덧줄 = 「공구손료 (노무비의 %) : 6,878.8 * 3 % = 206.3」(규격 = 149-4 `pct_extras`)
|
||||
- 단가 없음 = 「단가 없음」 글 · 계 그 비목 빈칸 · 글 속 금액 = 산근 풀이(`Sangeun.Solver` · 841-1 M02 엔진
|
||||
단가) 줄 값
|
||||
- 머리 = 「이름 / 단위」 · 「출처 적용」 · 입력 「이름 : 값 단위」(801-5 단위)
|
||||
- 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」(화면 줄 쌓기 산출근거 꼴 · `master_doc_text`) ·
|
||||
중기 노 · 재 · 경 세 줄 · 결과단위 배 「÷ 배」 · 켜쌓기율 「× 율 %」 · 글 속 금액 = 풀이 블록 줄 값
|
||||
- 작업량 Q = ROUND 2 공식 줄 「Q = 21.594 = 21.59」 · 수량 식 = 값 넣은 식 「(1 ÷ 21.59 × 2)」
|
||||
- % 덧줄 = 「공구손료 (노무비의 %) : 밑수 × 3 % = 금액 원」 · 계 = 블록 합
|
||||
"""
|
||||
|
||||
import copy
|
||||
@@ -17,12 +16,10 @@ if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from B09_Estimation import B09_Estimation_Sangeun as sg # noqa: E402
|
||||
from B09_Estimation import B09_Estimation_Sangeun_Text as st # noqa: E402
|
||||
from M02_MasterTemplete import M02_Item_Prices as item_prices # noqa: E402
|
||||
|
||||
BASE = "GF000218" # 기초다짐 및 뒷채움(기계) — 보통인부 + 굴착기 0.2㎥ 로직 줄
|
||||
GIVEN = {"규격": 150, "지역": "전국평균", "보정작업": "해당 없음"}
|
||||
EXCEL_EQ = {"labor": 55700, "material": 7695, "expense": 13041} # 중기목록표 굴삭기 0.2㎥
|
||||
|
||||
|
||||
def _whole(edit=None):
|
||||
@@ -46,76 +43,82 @@ def _excel(qty_labor: str, qty_eq: str, mids=(), extras=()):
|
||||
return edit
|
||||
|
||||
|
||||
def _prices(labor):
|
||||
return lambda key: EXCEL_EQ if key.startswith("EQ") else labor.get(key)
|
||||
def _block(edit, code=BASE, given=GIVEN, **src):
|
||||
return sg.Solver().add(
|
||||
_whole(edit) if edit else _whole(), {"code": code, "given": given, **src}, "s1"
|
||||
)
|
||||
|
||||
|
||||
def test_엑셀_6호표_뒷채움_같은_글():
|
||||
whole = _whole(_excel("0.018", "0.07"))
|
||||
got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545}))
|
||||
assert got[:3] == [
|
||||
def _texts(block) -> list[str]:
|
||||
return [t for ln in block["lines"] for t in ln.get("text") or []]
|
||||
|
||||
|
||||
def _foot(block) -> str:
|
||||
parts = " + ".join(
|
||||
f"{n} {block[p]:,.0f}" for p, n in zip(sg.PARTS, ("노무비", "재료비", "경비"))
|
||||
)
|
||||
return f"계 : {parts} = {block['sum']:,.0f}"
|
||||
|
||||
|
||||
def test_머리_줄_중기_세_줄_계():
|
||||
block = _block(_excel("0.018", "0.07"))
|
||||
assert block["head"][:3] == [
|
||||
"기초다짐 및 뒷채움(기계) / ㎥",
|
||||
"산림품셈 13-3-2 적용",
|
||||
"규격 : 150 ㎜",
|
||||
] # 801-5 단위
|
||||
assert got[-5:] == [
|
||||
"보통인부 : 165,545 * 0.018 = 2,979.8",
|
||||
"굴착기(무한궤도) 0.2㎥ 노무비 : 55,700 * 0.07 = 3,899.0",
|
||||
"굴착기(무한궤도) 0.2㎥ 재료비 : 7,695 * 0.07 = 538.6",
|
||||
"굴착기(무한궤도) 0.2㎥ 경비 : 13,041 * 0.07 = 912.8",
|
||||
"계 : 노무비 6,878 + 재료비 538 + 경비 912 = 8,328",
|
||||
]
|
||||
labor, eq = block["lines"]
|
||||
assert labor["text"] == [
|
||||
f"보통인부 : {labor['price']['labor']:,.0f} 원/인 × 0.018 인 = {labor['labor']:,.1f} 원"
|
||||
]
|
||||
assert [t.split(" : ")[0] for t in eq["text"]] == [
|
||||
f"굴착기(무한궤도) 0.2㎥ {n}" for n in ("노무비", "재료비", "경비")
|
||||
]
|
||||
assert [t.endswith(f"= {eq[p]:,.1f} 원") for t, p in zip(eq["text"], sg.PARTS)] == [True] * 3
|
||||
assert block["foot"] == _foot(block)
|
||||
|
||||
|
||||
def test_엑셀_7호표_작업량_Q_중간_줄():
|
||||
whole = _whole(_excel("0", "1 / Q * 2", mids=[("Q", "21.594")]))
|
||||
got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545}))
|
||||
assert "Q = 21.594 = 21.59" in got # ROUND(식, 2) 뒤 쓰임
|
||||
assert "굴착기(무한궤도) 0.2㎥ 노무비 : 55,700 * 1 / 21.59 * 2 = 5,159.7" in got
|
||||
def test_작업량_Q_공식_줄_값_넣은_수량식():
|
||||
block = _block(_excel("0", "1 / Q * 2", mids=[("Q", "21.594")]))
|
||||
assert "Q = 21.594 = 21.59 ㎥/hr" in block["head"] # ROUND(식, 2) 뒤 쓰임
|
||||
assert all("× (1 ÷ 21.59 × 2) 시간 = " in t for t in block["lines"][1]["text"])
|
||||
|
||||
|
||||
def test_퍼센트_덧줄_노무비의_퍼센트():
|
||||
tool = {"이름": "공구손료", "식": "노무비 * 3 / 100", "비목": "경비"}
|
||||
whole = _whole(_excel("0.018", "0.07", extras=[tool]))
|
||||
got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({"LB000002": 165545}))
|
||||
assert got[-2:] == [
|
||||
"공구손료 (노무비의 %) : 6,878.8 * 3 % = 206.3", # 밑수 = 인력 + 중기 노무비
|
||||
"계 : 노무비 6,878 + 재료비 538 + 경비 1,119 = 8,535",
|
||||
]
|
||||
block = _block(_excel("0.018", "0.07", extras=[tool]))
|
||||
pct = block["lines"][-1]
|
||||
base = sum(ln["labor"] for ln in block["lines"][:-1]) # 밑수 = 인력 + 중기 노무비
|
||||
assert pct["text"] == [f"공구손료 (노무비의 %) : {base:,.1f} × 3 % = {pct['expense']:,.1f} 원"]
|
||||
assert block["foot"] == _foot(block)
|
||||
|
||||
|
||||
def test_배_켜쌓기율_꼬리_단가_없음():
|
||||
whole = _whole(_excel("0.018", "0.07"))
|
||||
got = st.render_sangeun_text(whole, BASE, GIVEN, _prices({}), times=10, rate=90)
|
||||
assert "보통인부 : 단가 없음 * 0.018 / 10 * 90 % = 빈칸" in got
|
||||
assert got[-1] == "계 : 노무비 빈칸 + 재료비 48 + 경비 82 = 빈칸"
|
||||
def test_켜쌓기율_꼬리():
|
||||
block = _block(_excel("0.018", "0.07"), rate=90)
|
||||
assert block["lines"][0]["text"][0].startswith("보통인부 : ")
|
||||
assert "× 0.018 인 × 90 % = " in block["lines"][0]["text"][0]
|
||||
assert block["foot"] == _foot(block)
|
||||
|
||||
|
||||
def test_글_속_금액은_산근_풀이_값과_같음():
|
||||
for code, given in ((BASE, GIVEN), ("GF000288", {})): # 중기 · 노무 · % 덧줄 · 배 1,000
|
||||
whole = item_prices.load_prices(item_prices.to_json(item_prices.collect([code])))
|
||||
solver = sg.Solver() # 841-1 단가 = M02 엔진 · 글 단가 = 풀이가 쓴 그 단가
|
||||
block = solver.add(whole, {"code": code, "given": given}, "s1")
|
||||
price_of = solver.price_of
|
||||
# 결과단위 배(「원/1,000㎡」) — 산근 풀이와 같은 1 단위
|
||||
times = sg._unit(whole.logic(code))[1]
|
||||
got = st.render_sangeun_text(whole, code, given, price_of, times=times)
|
||||
parts = " + ".join(f"{st.PART_NAME[p]} {block[p]:,.0f}" for p in sg.PARTS)
|
||||
assert got[-1] == f"계 : {parts} = {block['sum']:,.0f}", code
|
||||
block = sg.Solver().add(whole, {"code": code, "given": given}, "s1")
|
||||
assert block["foot"] == _foot(block), code
|
||||
for ln in block["lines"]:
|
||||
if ln["kind"] in ("labor", "material"):
|
||||
part = next(iter(ln["price"]))
|
||||
assert ln["text"][0].endswith(f"= {ln[part]:,.1f} 원"), (code, ln["text"])
|
||||
if sg._unit(whole.logic(code))[1] != 1:
|
||||
assert all(" ÷ 1,000" in t for t in _texts(block)[:2]), code
|
||||
|
||||
|
||||
def test_자재_자리표시_키는_실제_키로():
|
||||
"""「MO:휘발유:{지역}」 자리표시 = 대비표 키(MO…)로 물음 — 산근 풀이 흠(H4 · 155 데스크탑 보조가
|
||||
고침)과 달리 단가가 나옴 · Q 중간 줄 · 「줄.'이름'」 % 덧줄."""
|
||||
"""「MO:휘발유:{지역}」 자리표시 = 대비표 키(MO…) · 수집량 공식 줄 · 「× (6.5 × 0.125)」 · % 덧줄."""
|
||||
whole = item_prices.load_prices(item_prices.to_json(item_prices.collect(["GF000062"])))
|
||||
asked = []
|
||||
|
||||
def price_of(key):
|
||||
asked.append(key)
|
||||
return 1000.0
|
||||
|
||||
got = st.render_sangeun_text(whole, "GF000062", {}, price_of)
|
||||
assert not [k for k in asked if ":" in k] and any(k.startswith("MO") for k in asked)
|
||||
assert "Q = 아키야윈치(임업용 윈치) 집재(집재거리 = 50m 내외).수집량 = 8 ㎥" in got # 157-1
|
||||
assert "일수 = 1 / Q = 1 / 8 = 0.125" in got
|
||||
assert "휘발유(아키아윈치(휘발유)) : 1,000 * 6.5 * 0.125 = 812.5" in got
|
||||
block = sg.Solver().add(whole, {"code": "GF000062", "given": {}}, "s1")
|
||||
fuel = next(ln for ln in block["lines"] if ln["name"].startswith("휘발유"))
|
||||
assert fuel["ref"]["key"].startswith("MO") and ":" not in fuel["ref"]["key"]
|
||||
assert "일수 = 1 ÷ 수집량 = 1 ÷ 8 = 0.125 일/㎥" in block["head"]
|
||||
assert "× (6.5 × 0.125) ℓ = " in fuel["text"][0]
|
||||
assert block["lines"][3]["text"][0].startswith("잡품 (재료비의 %) : ")
|
||||
|
||||
@@ -124,9 +124,9 @@ def test_155_5_산근_글_줄마다_덧줄_퍼센트_표기(tmp_path):
|
||||
for b in (crane, pile):
|
||||
for ln in b["lines"]:
|
||||
money = sum(ln[p] or 0 for p in sg.PARTS)
|
||||
assert ln["text"][-1].endswith(f"= {money:,.1f}") or ln["kind"] == "machine"
|
||||
assert ln["text"][-1].endswith(f"= {money:,.1f} 원") or ln["kind"] == "machine"
|
||||
assert b["foot"] == (
|
||||
f"계 : 노무비 {b['labor']:,.0f} + 재료비 {b['material']:,.0f}"
|
||||
f" + 경비 {b['expense']:,.0f} = {b['sum']:,.0f}"
|
||||
)
|
||||
assert " / 10 = " in pile["lines"][0]["text"][0] # 배 10 로직 꼬리
|
||||
assert " ÷ 10 = " in pile["lines"][0]["text"][0] # 배 10 로직 꼬리(B9-4 화면 꼴 「÷」)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""157-1 산근 글 = M01 흐름도 함수 상자 빠짐없이 · 157-3 기계 번호 = 「이름 규격」(`Sangeun_Text`).
|
||||
"""157-1 · 855-F B9-4 산근 글 머리 = 문서 공식 줄 · 157-3 기계 번호 = 「이름 규격」(`Sangeun_Text`).
|
||||
|
||||
- 중간 여럿 · 중간이 중간을 부름 = 「이름 = 이름식 = 값 넣은 식 = 값」(GF000064 일수)
|
||||
- 찾기 = 「이름 = 표 이름(조건 = 값).칸 = 값 단위」 · 돈 아닌 하위 로직 = 이름 + 「└ 」 풀이
|
||||
- 돈 하위 로직 = 「로직 이름(산근 n호표)」 · 만약 = 걸린 갈래만 · 입력 = 「이름 : 설명 = 값 단위」
|
||||
- 함수 줄은 머리에만 — 호표 줄 · 계 = 산근 풀이(`Sangeun.Solver`) 줄 글 · 금액 그대로
|
||||
- 공식 줄 = 「이름 = 이름식 = 값 넣은 식 = 값 단위」(GF000064 일수 · 중간이 중간을 부름) · 만약 = 걸린 갈래만
|
||||
- 표 · 하위 결과 값 = 「이름 = 값 단위」(넷까지 한 줄 · 화면 공식 묶음) · 입력 = 「이름 : 설명 = 값 단위」
|
||||
- 수량 식 = 금액 줄 안 값 넣은 식 「× (2 × 0.098302)」(머리 「… 수량 =」 줄 없음)
|
||||
- 호표 줄 · 계 = 산근 풀이(`Sangeun.Solver`) 줄 글 · 금액 그대로
|
||||
"""
|
||||
|
||||
import copy
|
||||
@@ -15,11 +15,8 @@ if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from B09_Estimation import B09_Estimation_Sangeun as sg # noqa: E402
|
||||
from B09_Estimation import B09_Estimation_Sangeun_Text as st # noqa: E402
|
||||
from M02_MasterTemplete import M02_Item_Prices as item_prices # noqa: E402
|
||||
|
||||
EQ = {"labor": 55700, "material": 7695, "expense": 13041}
|
||||
|
||||
|
||||
def _whole(codes, edit=None):
|
||||
files = copy.deepcopy(item_prices.to_json(item_prices.collect(codes)))
|
||||
@@ -31,63 +28,31 @@ def _whole(codes, edit=None):
|
||||
return item_prices.load_prices(files)
|
||||
|
||||
|
||||
def _price_of(key):
|
||||
if key.startswith("SG:"):
|
||||
return {"no": 3, "labor": 1000.0, "material": 0.0, "expense": 0.0, "sum": 1000.0}
|
||||
return EQ if key.startswith("EQ") else 1000.0
|
||||
|
||||
|
||||
def test_중간이_중간을_부름_값_넣은_식까지():
|
||||
got = st.render_sangeun_text(_whole(["GF000064"]), "GF000064", {}, _price_of)
|
||||
assert "일수 = 1 / Q * (1 + 할증 %) = 1 / 11.19 * (1 + 10 %) = 0.0983" in got
|
||||
assert "할증 = 소형가선 집재 숲가꾸기 주 속 수(구분 = 총 소요인력 할증).적용 = 10" in got
|
||||
assert "보통인부 수량 = 2 * 일수 = 2 * 0.0983 = 0.1966 인" in got # 호표 수량 함수
|
||||
|
||||
|
||||
def test_돈_아닌_하위_로직_풀이_찾기_결과식():
|
||||
got = st.render_sangeun_text(_whole(["GF000089"]), "GF000089", {}, _price_of)
|
||||
at = got.index("작업량 = 토사깍기(기계 · 굴착기 0.7㎥) 시간당 작업량 = 39.293")
|
||||
assert got[at + 1 : at + 8] == [
|
||||
"└ E입력 : 0.45",
|
||||
"└ q = 토사깍기 장비(구분 = 무한궤도 굴착기).적용 = 0.7 ㎥",
|
||||
"└ K = 토사깍기 기계(구분 = K).적용 = 0.9",
|
||||
"└ f = 토사깍기 체적환산계수(구분 = f).적용 = 0.77",
|
||||
"└ E = E입력 = 0.45",
|
||||
"└ Cm = 토사깍기 기계(구분 = ㎝(sec)).적용 = 20 sec", # 801-5 M01 단위 표기
|
||||
"└ 결과 = 반올림(3,600 * q * K * f * E / Cm, 3) = "
|
||||
"반올림(3,600 * 0.7 * 0.9 * 0.77 * 0.45 / 20, 3) = 39.293",
|
||||
]
|
||||
assert "굴착기(무한궤도) 0.7㎥ 노무비 : 55,700 * 1 / 39.293 = 1,417.5" in got
|
||||
|
||||
|
||||
def test_결과_로직_맨_위():
|
||||
got = st.render_sangeun_text(_whole(["GF000088"]), "GF000088", {}, _price_of)
|
||||
block = _solver(_whole(["GF000064"]), "GF000064", {})
|
||||
assert (
|
||||
"결과 = 반올림(3,600 * q * K * f * E / Cm, 3) = "
|
||||
"반올림(3,600 * 0.7 * 0.9 * 0.77 * 0.45 / 20, 3) = 39.293"
|
||||
) in got
|
||||
"일수 = 1 ÷ 수집량 × (1 + 할증 ÷ 100) = 1 ÷ 11.19 × (1 + 10 ÷ 100) = 0.098302 일/㎥"
|
||||
) in block["head"]
|
||||
assert "할증 = 소형가선 집재 숲가꾸기 주 속 수 총 소요인력 할증 = 10 %" in block["head"]
|
||||
worker = next(ln for ln in block["lines"] if ln["name"] == "보통인부")
|
||||
assert "× (2 × 0.098302) 인 = " in worker["text"][0] # 수량 식 = 금액 줄 안
|
||||
|
||||
|
||||
def test_돈_하위_로직_산근_호표_번호():
|
||||
def edit(row):
|
||||
row["중간"].append(
|
||||
{"이름": "참고", "식": "로직(GF000123, 지역=지역, 보정작업=보정작업).노무비"}
|
||||
)
|
||||
|
||||
got = st.render_sangeun_text(_whole(["GF000089", "GF000123"], edit), "GF000089", {}, _price_of)
|
||||
line = next(t for t in got if t.startswith("참고 = "))
|
||||
assert line.startswith("참고 = 층따기(산근 3호표).노무비 = ")
|
||||
def test_하위_결과_값_줄():
|
||||
block = _solver(_whole(["GF000089"]), "GF000089", {})
|
||||
assert "작업량 = 39.293 ㎥/hr" in block["head"]
|
||||
assert "E입력 : 0.45" in block["head"]
|
||||
assert all("× (1 ÷ 39.293) 시간 = " in t for t in block["lines"][0]["text"])
|
||||
|
||||
|
||||
def test_만약_걸린_갈래_입력_설명_기계_이름():
|
||||
got = st.render_sangeun_text(_whole(["GF000297"]), "GF000297", {"흉고직경": 20}, _price_of)
|
||||
assert "흉고직경 : 가슴높이(1.2m) 지름(표 구간 안 값) = 20 ㎝" in got
|
||||
assert "굴착기 = 굴착기(무한궤도) 0.6㎥" in got # 157-3 원문번호 '0201-0060' 대신
|
||||
assert "기계 = 1" in got and not [t for t in got if "0201-" in t]
|
||||
assert (
|
||||
"특별인부 수량 = 식재작업 교목식재(흉고직경)(흉고직경(㎝) = 20).특별인부 * (1 - 감 %)"
|
||||
" = 0.56 * (1 - 0 %) = 0.56 인"
|
||||
) in got
|
||||
block = _solver(_whole(["GF000297"]), "GF000297", {"흉고직경": 20})
|
||||
head = block["head"]
|
||||
assert "흉고직경 : 가슴높이(1.2m) 지름(표 구간 안 값) = 20 ㎝" in head
|
||||
assert "굴착기 = 굴착기(무한궤도) 0.6㎥" in head # 157-3 원문번호 '0201-0060' 대신
|
||||
assert "기계 = 1" in head and not [t for t in head if "0201-" in t]
|
||||
labor = next(ln for ln in block["lines"] if ln["name"] == "특별인부")
|
||||
assert "× (0.56 × (1 - 0 ÷ 100)) 인 = " in labor["text"][0]
|
||||
|
||||
|
||||
def _solver(whole, code, given):
|
||||
@@ -100,7 +65,9 @@ def test_호표_줄_계는_산근_풀이와_같음():
|
||||
for code, given in (("GF000089", {}), ("GF000064", {}), ("GF000297", {"흉고직경": 20})):
|
||||
whole = _whole([code])
|
||||
block = _solver(whole, code, given)
|
||||
parts = " + ".join(f"{st.PART_NAME[p]} {block[p]:,.0f}" for p in sg.PARTS)
|
||||
parts = " + ".join(
|
||||
f"{n} {block[p]:,.0f}" for p, n in zip(sg.PARTS, ("노무비", "재료비", "경비"))
|
||||
)
|
||||
assert block["foot"] == f"계 : {parts} = {block['sum']:,.0f}", code
|
||||
assert all(ln.get("text") for ln in block["lines"]), code
|
||||
assert any(" 수량 = " in t or " = " in t for t in block["head"]), code
|
||||
|
||||
@@ -112,7 +112,7 @@ def survey() -> dict:
|
||||
out["하위"][key] = (sorted(a), sorted(b))
|
||||
if not lines:
|
||||
try:
|
||||
sg()._env(whole, row, sg()._clean_given(given))
|
||||
h._old_env(whole, row, sg()._clean_given(given))
|
||||
except Exception:
|
||||
out["옛 빈 답"].add(key)
|
||||
for c in got["부름"]:
|
||||
|
||||
Reference in New Issue
Block a user