From d254b4b555325a5b5c329709d37f127b1e9db2fd Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 02:01:29 +0900 Subject: [PATCH] =?UTF-8?q?refactor(855-F=20B9-3):=20B09=20=EC=82=B0?= =?UTF-8?q?=EA=B7=BC=20=C2=B7=20=EB=8C=80=EA=B0=80=20=C2=B7=20=EC=88=98?= =?UTF-8?q?=EC=9A=94=20=ED=82=A4=EA=B0=80=20=EC=98=9B=20=EC=97=94=EC=A7=84?= =?UTF-8?q?=20=EB=8C=80=EC=8B=A0=20=EB=AC=B8=EC=84=9C=20=EC=85=88=20?= =?UTF-8?q?=EB=8B=B5=20+=20=EC=85=88=20=EA=B8=B0=EB=A1=9D=EC=9D=84=20?= =?UTF-8?q?=EC=9D=BD=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 새 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 --- B09_Estimation/B09_Estimation_Doc_Run.py | 267 ++++++++++++++++++ B09_Estimation/B09_Estimation_Labor_Rule.py | 18 +- B09_Estimation/B09_Estimation_Labor_Source.py | 25 +- B09_Estimation/B09_Estimation_Linked.py | 25 +- B09_Estimation/B09_Estimation_Sangeun.py | 238 ++++++++-------- B09_Estimation/B09_Estimation_Sangeun_Sum.py | 53 +++- .../master_data/scripts/master_doc_trace.py | 10 +- resources/tester/golden_855_b09.json | 14 +- resources/tester/helper_855_engine.py | 31 ++ resources/tester/test_855_trace.py | 4 +- 10 files changed, 529 insertions(+), 156 deletions(-) create mode 100644 B09_Estimation/B09_Estimation_Doc_Run.py diff --git a/B09_Estimation/B09_Estimation_Doc_Run.py b/B09_Estimation/B09_Estimation_Doc_Run.py new file mode 100644 index 000000000..c18511b22 --- /dev/null +++ b/B09_Estimation/B09_Estimation_Doc_Run.py @@ -0,0 +1,267 @@ +"""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 diff --git a/B09_Estimation/B09_Estimation_Labor_Rule.py b/B09_Estimation/B09_Estimation_Labor_Rule.py index 0d92c2089..023e9e5af 100644 --- a/B09_Estimation/B09_Estimation_Labor_Rule.py +++ b/B09_Estimation/B09_Estimation_Labor_Rule.py @@ -21,7 +21,7 @@ from typing import Any from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠 -mf = importlib.import_module("master_formula") +md = importlib.import_module("master_doc") # 식 꼴 읽기 = 새 계산기 파서(855-F B9-3) ms = importlib.import_module("master_formula_sum") PART = {"노무비": "labor", "재료비": "material", "경비": "expense"} @@ -46,7 +46,7 @@ def _ref(row: dict, node: tuple, n: int) -> Refs | None: """밑 이름 하나 → 줄 차례(n 앞만) · 모름 = None.""" lines = ms.items(row) names = {x.get("이름"): i for i, x in reversed(list(enumerate(lines[:n]))) if x.get("이름")} - if node[0] == "name": + if node[0] == "var": if node[1] in PART: # 비목 합 = 앞 줄 중 합에 드는 줄 skip = ms.skipped(row) return [(i, PART[node[1]]) for i in range(n) if i not in skip] @@ -54,9 +54,9 @@ def _ref(row: dict, node: tuple, n: int) -> Refs | None: if node[0] != "field": return None head, name = node[1], node[2] - if head == ("name", "줄"): + if head == ("var", "줄"): return [(names[name], None)] if name in names else None - if head[0] != "field" or head[1][0] != "name": + if head[0] != "field" or head[1][0] != "var": return None group, key = head[1][1], head[2] if group == ms.ADDR: @@ -69,7 +69,7 @@ def _ref(row: dict, node: tuple, n: int) -> Refs | None: def _linear(row: dict, node: tuple, n: int) -> tuple[Refs, Decimal] | None: """식 = 수 하나 × 밑 합 → (밑, 수) · 다른 꼴 = None.""" - if node[0] in ("name", "field"): + if node[0] in ("var", "field"): got = _ref(row, node, n) return None if got is None else (got, Decimal(1)) if node[0] != "bin": @@ -87,8 +87,8 @@ def _linear(row: dict, node: tuple, n: int) -> tuple[Refs, Decimal] | None: def _pct(row: dict, formula: str, n: int) -> tuple[str, float] | None: """덧줄 식 → (`rows:` 밑, %) · 못 바꿈 = None(밑 없음 · 겹친 밑 포함).""" try: - got = _linear(row, mf.parse(formula), n) - except mf.FormulaError: + got = _linear(row, md.parse(formula), n) + except md.DocError: return None if not got or not got[0] or len(set(got[0])) != len(got[0]): return None @@ -112,8 +112,8 @@ def mark(row: dict, lines: list[dict], engine: list[dict]) -> dict | None: formula = str(item.get("식") or "") part = PART.get(str(item.get("비목")), "expense") try: - plain = _plain(mf.parse(formula)) - except mf.FormulaError: + plain = _plain(md.parse(formula)) + except md.DocError: continue value = _f(engine[n].get("금액")) if n < len(engine) else None if plain and value is not None: # 이름 없는 수 식 = 고정 줄(수량 1) diff --git a/B09_Estimation/B09_Estimation_Labor_Source.py b/B09_Estimation/B09_Estimation_Labor_Source.py index 953efb10e..99d4c6205 100644 --- a/B09_Estimation/B09_Estimation_Labor_Source.py +++ b/B09_Estimation/B09_Estimation_Labor_Source.py @@ -34,6 +34,7 @@ from pathlib import Path from typing import Any from B09_Estimation import B09_Estimation_Bill_Library as library +from B09_Estimation import B09_Estimation_Doc_Run as dr from B09_Estimation import B09_Estimation_Labor_Rule as rule from B09_Estimation import B09_Estimation_Sangeun as sg from B09_Estimation import B09_Estimation_Sangeun_Text as st @@ -91,6 +92,9 @@ class Builder: def __init__(self) -> None: self.blocks: dict[str, dict[str, Any]] = {} self.gaps: list[dict[str, str]] = [] + self.shelf = ( + dr.Shelf() + ) # 값 색인 → 사본 수식 문서(855-F B9-3 · 사본마다 `combo` · `library`) def put(self, block: dict[str, Any], cover: str | None = None) -> str: bid = f"DG:{_digest([block['kind'], block['origin'], block['lines']])}" @@ -130,24 +134,27 @@ class Builder: return self.put(got) def _poomsem(self, whole: Any, one: dict[str, Any], title: str = "") -> dict | None: - """품셈 블록 꼴(넣기 전) — 엔진 줄 · 줄마다 `_n`(엔진 차례 · 단가산출 블록이 씀).""" + """품셈 블록 꼴(넣기 전) — 문서 셈 줄(`Doc_Run` · 옛 엔진 줄 꼴 · 855-F B9-3) · 줄마다 `_n` + (금액 줄 차례 · 단가산출 블록이 씀).""" code = str(one.get("로직") or "") given, rate, picks = one.get("입력값") or {}, one.get("켜쌓기율"), one.get("고름") try: logic = whole.logic(code) except mf.FormulaError: return None - got = labor_doc.run_line(whole, code, given, rate, picks, raw=True) # B09 끝수는 제 단가로 - if got.get("기준") is None: + got = dr.solve( + whole, self.shelf.of(whole), code, given, picks, rate + ) # B09 끝수는 제 단가로 + if got is None or got.stopped or "결과" in got.ans: return None # 돈 아닌 로직 · 못 돈 로직 — 조합 줄이 까닭을 냄 items = logic.get("호표") or [] lines = [] - engine = got.get("줄") or [] + engine = got.engine(items) # 옛 엔진 줄 꼴(단위 = 원문 · % 줄 율) bases = _engine_bases(engine[: len(items)], items) - calls = sg.line_calls(whole, code, given, picks) for n, x in enumerate(engine): item = items[n] if n < len(items) else None - lines.append(self._engine_line(item, x, logic, n - len(items), bases, calls.get(n))) + call = sg.logic_call(whole, self.shelf.of(whole), item, x) + lines.append(self._engine_line(item, x, logic, n - len(items), bases, call)) eq = {str(r.get("키")): r for r in (whole.numbers.get("EQ") or {}).values()} for line in lines: if line["kind"] == "machine": @@ -251,7 +258,7 @@ class Builder: return {**head, "kind": "blank", "qty": qty, "why": "덧줄 — 대가 단가로 못 셈"} part = PART.get(str(add.get("비목")), "expense") return {**head, "kind": "pct", "part": part, "base": base, "spec": f"{label}의 %", - "unit": "%", "qty": round(value / under * 100, 6)} # fmt: skip + "unit": "%", "qty": round(float(x["율"]) if "율" in x else value / under * 100, 6)} # fmt: skip kind, own = item.get("종류"), _own(x, qty) if kind == "인력": key = goods.get("키") or str(item.get("요소") or "") @@ -421,8 +428,9 @@ class Builder: values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} whole = item_prices.load_prices(prices) + docs = self.shelf.put(whole, dr.docs_of(folder)) # 사본 수식 문서(855-F B9-3) area = read_json(folder / AREA_FILE) - result = item_prices.calc(labor, prices, values, picks, area) + result = item_prices.calc(labor, prices, values, picks, area, {"문서": docs}) use = (labor_doc.area_values(area), cover or f"S:{folder.name}") # SC 안 줄 알약(723-4) doc = item_prices.with_values(labor.get("줄") or {}, values, picks) copies = labor.get("참조사본") or {} @@ -476,6 +484,7 @@ class Builder: if not isinstance(doc, dict): return None whole = item_prices.load_prices(bundle(folder)) + self.shelf.put(whole, dr.docs_of(folder)) # 사본 수식 문서(855-F B9-3) if manifest["종류"] == "sangeun": # 내 자료집 단가산출(719-2) return self.sangeun(whole, ref, doc, copies, 1) return self.precombo(whole, ref, doc, copies, 1) diff --git a/B09_Estimation/B09_Estimation_Linked.py b/B09_Estimation/B09_Estimation_Linked.py index 13549a6e7..d813e6e21 100644 --- a/B09_Estimation/B09_Estimation_Linked.py +++ b/B09_Estimation/B09_Estimation_Linked.py @@ -2,7 +2,8 @@ 연결된 사본 = `M02_Item_Snapshot.linked_snapshots`(지정 ∩ 같은 항목 사본 · B08 · B09 공용). 사본마다 `일위대가.json` 담은 로직을 그 사본 단가 묶음(`단가.json`) · 입력값 · 고른자재로 돌리며 -실제로 부른 자원 줄(인력 LB · 기계 EQ · 자재 MT · 유가 MO)만 모음 — 단가 묶음 통째 +실제로 부른 자원 줄(인력 LB · 기계 EQ · 자재 MT · 유가 MO · 문서 셈 기록 `Doc_Run.resources` · +855-F B9-3)만 모음 — 단가 묶음 통째 (고르기 후보 전부)는 안 씀 · 값은 쓰지 않음(단가는 원가 한 벌 `price_book.json` 이 맡음) · 사본 일위대가 자재 · 굳힌 사전조합 자재 코드 · 고정 줄 이음 키도(183-1 · 705-1 · 로직을 안 돌아 `get` 에 안 걸림). 굳힌 SK(719-2) = 굳힌 키 로직 줄로 돌림(사본 `단가.json` · M01 안 읽음). @@ -15,9 +16,9 @@ from __future__ import annotations from pathlib import Path from typing import Any +from B09_Estimation import B09_Estimation_Doc_Run as dr from B09_Estimation.B09_Estimation_Copy_Prices import bundle from M02_MasterTemplete import M02_Item_Prices as item_prices -from M02_MasterTemplete import M02_Labor_Doc as labor_doc from M02_MasterTemplete import M02_Labor_Fixed as fixed from M02_MasterTemplete.M02_Item_Snapshot import ( PICKS_FILE, @@ -42,16 +43,7 @@ def used_keys(folder: Path) -> list[str]: values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} seen: list[str] = [] - base_get = snapshot.get - - def get(ref: str) -> dict[str, Any]: - row = base_get(ref) - key = str(row.get("키") or "") - if key[:2] in RESOURCE_TABLES and key not in seen: - seen.append(key) - return row - - snapshot.get = get # 이 사본 묶음 한 벌에만 — 마스터 캐시는 안 건드림 + docs = dr.docs_of(folder) # 사본 수식 문서 — 셈 기록의 자원 키(855-F B9-3) # 사본 셈 한 벌(142-1)과 같은 길 — 빈 입력 = 자동값 · 켜쌓기율 · 고름 · # 굳힌 참조사본 안 로직까지 doc = item_prices.with_values(labor.get("줄") or {}, values, picks) @@ -61,9 +53,14 @@ def used_keys(folder: Path) -> list[str]: for one in [*lines, *sks]: # 못 돈 로직 — 부른 데까지만(까닭은 안 봄) if isinstance(one, dict) and one.get("로직"): - labor_doc.run_line( - snapshot, one["로직"], one.get("입력값"), one.get("켜쌓기율"), one.get("고름") + got = dr.solve( + snapshot, docs, one["로직"], one.get("입력값"), one.get("고름"), one.get("켜쌓기율") ) + seen += [ + k + for k in (got.resources if got else []) + if k[:2] in RESOURCE_TABLES and k not in seen + ] mats = [*(doc.get("자재") or []), *(m for d in inner for m in d.get("자재") or [])] codes = [str(mat.get("코드") or "") if isinstance(mat, dict) else "" for mat in mats] codes += [k for d in [doc, *inner] for k in fixed.link_keys(d)] # 705-1 고정 줄 이음 diff --git a/B09_Estimation/B09_Estimation_Sangeun.py b/B09_Estimation/B09_Estimation_Sangeun.py index ee6ef1017..2f0bbc4fa 100644 --- a/B09_Estimation/B09_Estimation_Sangeun.py +++ b/B09_Estimation/B09_Estimation_Sangeun.py @@ -8,8 +8,9 @@ 같은 로직 + 같은 입력값(+ 켜쌓기율 · 고른 자재) = 산근 하나(`sangeun_key`) · 번호 = 첫 등장 차례 · 로직 줄이 부르는 다른 돈 로직(기계경비 밖) = 하위 산근(그 산근도 목록에 · 산근 → 산근). -풀이 = 로직 호표 줄을 사본 단가 묶음(`단가.json`)으로 펼쳐 수량 · 자원 키만 얻고 - (M01 엔진 식 그대로) · +풀이 = 사본 수식 문서(`수식.json`)를 M02 와 같은 계산기로 셈한 답 + 셈 기록(`B09_Estimation_Doc_Run` · + 855-F B9-3)에서 줄마다 수량 · 단가 · 자원 키 · 하위 산근 · % 줄 율 · 끝수를 읽음(옛 엔진 안 부름) · + 줄 이름 · 단위 · 종류 = 사본 로직 줄 글(B9-5 에서 문서로) · 산출근거 글 = 옛 길(B9-4 · `_env` · `_captured`) · 단가 = B09 프로젝트 한 벌 굳힌 단가(144 · `compute_base` 표) — 노무 = 노무비목록표 · 중기 = 중기목록표 노 · 재 · 경 · 재료 = 자재단가대비표 적용 단가 · % 줄(덧줄) = 엔진 식에 B09 비목 합. @@ -36,11 +37,13 @@ from __future__ import annotations import copy import hashlib import json +import re from decimal import Decimal from pathlib import Path 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.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total from B09_Estimation.B09_Estimation_Copy_Prices import bundle @@ -48,7 +51,6 @@ from B09_Estimation.B09_Estimation_Store import ref_rows from M01_MasterData import M01_MasterData_Store as m01 from M01_MasterData import M01_MasterData_Store_Combo as combo_store from M02_MasterTemplete import M02_Item_Prices as item_prices -from M02_MasterTemplete import M02_Labor_Doc as labor_doc from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs from M02_MasterTemplete.M02_Item_Snapshot import ( PICKS_FILE, @@ -102,9 +104,10 @@ def _values(values: dict[str, Any], code: str) -> dict[str, Any]: return {name: (one or {}).get("값") for name, one in (values.get(code) or {}).items()} -def rows_of(folder: Path, whole: Any = None) -> list[dict[str, Any]]: +def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[dict[str, Any]]: """사본 하나의 산근 원천 줄(차례대로) — 단가산출 줄 · 사전조합 안 단가산출 줄 · - 일위대가화 줄(승격 · 옛 SP)의 하위 로직 줄. 키 = 대가 블록 산근 줄 키(`Labor_Source`)와 같음.""" + 일위대가화 줄(승격 · 옛 SP)의 하위 로직 줄. 키 = 대가 블록 산근 줄 키(`Labor_Source`)와 같음 · + `docs` = 사본 수식 문서(없으면 `수식.json`).""" from M02_MasterTemplete import M02_Labor_Ref as refs labor = read_json(folder / LABOR_FILE) @@ -112,6 +115,7 @@ def rows_of(folder: Path, whole: Any = None) -> list[dict[str, Any]]: return [] if whole is None: whole = item_prices.load_prices(bundle(folder)) + docs = dr.docs_of(folder) if docs is None else docs values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} copies = labor.get("참조사본") or {} @@ -123,7 +127,7 @@ def rows_of(folder: Path, whole: Any = None) -> list[dict[str, Any]]: if not promoted: out.append({"code": code, "given": _clean_given(given), "rate": rate, "picks": chosen}) return - for call in line_calls(whole, code, given, chosen).values(): + for call in line_calls(whole, code, given, chosen, docs).values(): if call and call.get("code"): out.append({"code": call["code"], "given": call["given"], "rate": None, "picks": None}) # fmt: skip @@ -198,7 +202,8 @@ def unit_of(whole: Any, code: str) -> str: def _env(whole: Any, row: dict, given: dict) -> dict: - """입력(빈 입력 = 자동값) + 중간값 · 작업량 Q = ROUND(식, 2)(엑셀 자리).""" + """입력(빈 입력 = 자동값) + 중간값 · 작업량 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("중간", []): @@ -220,46 +225,69 @@ def is_money(whole: Any, code: str) -> bool: return not (isinstance(row.get("흐름"), dict) or "결과" in row) -def call_of(whole: Any, item: dict, env: dict) -> dict[str, Any] | None: - """로직 호표 줄(종류 로직) → 부른 것 — 기계경비 로직 `{machine: EQ 키 | None}` · - 다른 돈 로직 `{code, given}`(하위 산근) · 못 펼치면 None. +def call_of(line: dict) -> dict[str, Any] | None: + """문서 셈 줄(`Doc_Run` 줄) → 부른 것 — 기계경비 `{machine: EQ 키 | None}` · 다른 돈 문서 + `{code, given}`(하위 산근) · 단가가 단가산출 부름 아님 = None. 대가 품셈 줄(`B09_Estimation_Labor_Source`)과 산근 풀이가 같은 판정을 씀.""" - 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 - if not target: + call = line.get("부름") + if not call: return None - if mf.mb.is_machine(target): # 기계경비 판별 한 곳(712-1) - keys = _captured(whole, node, env) - return {"machine": keys[0] if keys else None} - given = {name: mf.evaluate(expr, env, whole, 1) for name, expr in node[2]} - return {"code": called, "given": _clean_given(given)} + if "machine" in call: + return {"machine": call["machine"]} + return {"code": call["code"], "given": _clean_given(call["given"])} -def line_calls(whole: Any, code: str, given: Any, picks: Any = None) -> dict[int, dict | None]: - """로직 하나의 로직 호표 줄마다 `call_of`(호표 차례 n → 부른 것) — 못 셈 줄 = None.""" +_LOGIC = re.compile(r"\s*로직\(\s*([A-Z]{2}\d+)") # 호표 요소 「로직(키, …)」 의 키 + + +def frozen_machine(whole: Any, docs: dict, item: dict, line: dict) -> dict[str, Any] | None: + """굳은 기계 단가 줄(847-1 · 문서 = 숫자 묶음 · 셈 기록에 하위 부름 없음) → `{machine}` — 기계 키 = + 로직 원문 요소 「로직(키 …)」 문서의 셈 기록 첫 기계 · 묶음 단가 아님 = None.""" + if not isinstance(line.get("단가"), dict): + return None + hit = _LOGIC.match(str(item.get("요소") or "")) + got = dr.solve(whole, docs, hit.group(1)) if hit else None + keys = [k for k in (got.resources if got else []) if k[:2] == "EQ"] + return {"machine": keys[0] if keys else None} + + +def logic_call(whole: Any, docs: dict, item: dict | None, line: dict) -> dict[str, Any] | None: + """로직 호표 줄의 부른 것 — 하위 부름(`call_of`) · 굳은 기계 단가(`frozen_machine`) · 로직 줄 아님 = None.""" + if not item or item.get("종류") != "로직": + return None + return call_of(line) or frozen_machine(whole, docs, item, line) + + +def line_calls( + whole: Any, code: str, given: Any, picks: Any = None, docs: dict | None = None +) -> dict[int, dict | None]: + """로직 하나의 로직 호표 줄마다 `call_of`(호표 차례 n → 부른 것) — 못 셈 줄 = None · + 셈 = 문서 셈 답(`Doc_Run` · `docs` = 사본 수식 문서 · 없으면 그 자리 닫힌 묶음).""" try: row = whole.logic(code) - env = _env(whole, row, _clean_given(given)) - except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): + except mf.FormulaError: return {} - out: dict[int, dict | None] = {} - with mf.mp.choosing(picks): - for n, item in enumerate(row.get("호표", [])): - if item.get("종류") != "로직": - continue - try: - out[n] = call_of(whole, item, env) - except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): - out[n] = None - return out + docs = {} if docs is None else docs + got = dr.solve( + whole, + docs, + code, + _clean_given(given), + picks, + None, + ss.doc_shown(row), + ) + if got is None: + return {} + return { + n: logic_call(whole, docs, item, got.lines[n]) if n < len(got.lines) else None + for n, item in enumerate(row.get("호표", [])) + if item.get("종류") == "로직" + } def _captured(whole: Any, node: Any, env: dict) -> list[str]: - """식을 돌리며 부른 기계 키(EQ) — 기계경비 로직 줄의 기계.""" + """식을 돌리며 부른 기계 키(EQ) — 기계경비 로직 줄의 기계 · 산출근거 글 몫만(B9-4).""" seen: list[str] = [] base = whole.get @@ -316,8 +344,9 @@ 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.eng: list[dict[str, Any]] = [] # 지금 푸는 로직의 문서 셈 줄(금액 줄 차례 · 841-1) self.blocks: dict[str, dict[str, Any]] = {} + self.shelf = dr.Shelf() # 값 색인 → 사본 수식 문서(`collect` 가 사본마다 둠) def add( self, whole: Any, src: dict[str, Any], owner: str | None, depth: int = 0 @@ -342,21 +371,28 @@ class Solver: unit, times = _unit(row) rate = Decimal(str(src["rate"])) / 100 if src.get("rate") not in (None, 100) else None lines: list[dict[str, Any]] = [] - # 841-1 단가 = M02 엔진 줄 금액 ÷ 수량(켜쌓기율 없이 · 날 값 · B09 단가 책 안 읽음) - eng = labor_doc.run_line(whole, code, src["given"], None, src.get("picks"), raw=True) + # 841-1 단가 = M02 셈(문서 셈) 줄 금액 ÷ 수량(켜쌓기율 없이 · 날 값 · B09 단가 책 안 읽음) + docs = self.shelf.of(whole) + shown = ss.doc_shown(row) # 작업량 Q = ROUND 2(엑셀 자리) + eng = dr.solve(whole, docs, code, src["given"], src.get("picks"), None, shown) + if eng is None: + return self._stop(code, name, f"수식 문서 없음 「{code}」") + if why := eng.stopped: # 빈 입력 · 셈 멈춤 = 블록 통째 빈칸(옛 엔진과 같게) + return self._stop(code, name, why) + scale = (rate or 1) * 100 / times # % 줄 밑 = 1 단위 몫 줄 합(켜쌓기율 · 배 반영) + per = eng if scale == 100 else dr.solve(whole, docs, code, src["given"], + src.get("picks"), scale, shown) # fmt: skip try: - env = _env(whole, row, src["given"]) - with mf.mp.choosing(src.get("picks")): - for n, item in enumerate(row.get("호표", [])): - self.eng = eng.get("줄") or [] # 하위 산근 풀이가 바꿔 놓아도 되돌림 - lines.append(self._line(whole, item, n, env, times, rate, depth)) - ss.places(row, lines) # 줄 자리(792-3) - self._extras(whole, row, env, lines) - self._aside(lines) - _annotate(whole, row, env, lines) - except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError) as e: + for n, item in enumerate(row.get("호표", [])): + self.eng = eng.lines # 하위 산근 풀이가 바꿔 놓아도 되돌림 + lines.append(self._line(whole, item, n, times, rate, depth)) + ss.doc_places(row, lines) # 줄 자리(792-3) + self._extras(row, per or eng, lines) + 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.totals(row, lines) or block_totals(lines) # 끝전 · 조정(792-3) + 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) @@ -442,39 +478,26 @@ class Solver: "unit": item.get("단위", ""), "ref": None, "price": {}, **{p: (None if p == part else 0.0) for p in PARTS}, "why": why} # fmt: skip - def _line(self, whole, item, n, env, times, rate, depth) -> dict[str, Any]: - try: - raw = mf.evaluate(mf.parse(item["수량"]), env, whole, 0) - except mf.EmptyInput as e: - return self._blank(item, str(e)) - qty = Decimal(str(raw)) / times * (rate or 1) + def _line(self, whole, item, n, times, rate, depth) -> dict[str, Any]: + x = self.eng[n] if n < len(self.eng) else {} + if x.get("수량") is None: # 빈 입력 · 못 셈 수량 = 빈 줄(문서 셈 까닭) + return self._blank(item, x.get("까닭") or "수량을 못 셈") + qty = x["수량"] / times * (rate or 1) q = float(qty) base = {"name": item.get("이름", ""), "spec": "", "qty": q, "unit": item.get("단위", "")} zero = dict.fromkeys(PARTS, 0.0) kind = item.get("종류") if kind == "로직": - return self._logic_line(whole, item, n, env, q, base, zero, depth) + return self._logic_line(whole, item, n, x, q, base, zero, depth) if kind == "인력": - key = mf.fill(item["요소"], env) if isinstance(item["요소"], str) else "" + 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 - 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) - ) - _price, source, _why, 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 "") - ) - try: # 자리표시 글(「MO:경유:전국평균」) = 그 줄 키로 - key = str((whole.get(key) or {}).get("키") or key) - except (mf.FormulaError, KeyError, TypeError, ValueError): - pass + goods = x.get("품목") or {} # 고른 품목 = 셈 기록 · 자원 키(유가 MO 등) + key = str(x.get("키") or "") part = COST_PART.get(item.get("비목"), "material") price = self._each(n, part, q) self.prices.material[key] = price @@ -485,8 +508,8 @@ class Solver: "price": {part: price}, part: _money(price, q), "why": why, "_goods": goods} # fmt: skip - def _logic_line(self, whole, item, n, env, q, base, zero, depth) -> dict[str, Any]: - call = call_of(whole, item, env) + def _logic_line(self, whole, item, n, x, q, base, zero, depth) -> dict[str, Any]: + call = logic_call(whole, self.shelf.of(whole), item, x) if call and "machine" in call: keys = [call["machine"]] if call["machine"] else [] price = {p: self._each(n, p, q) for p in PARTS} # 기계 시간당 = M02 엔진 값(841-1) @@ -510,38 +533,30 @@ class Solver: return {**base, "kind": "sangeun", "ref": {"tab": "sg", "key": sub["key"]}, "price": price, **{p: _money(price[p], q) for p in PARTS}, "why": why} # fmt: skip - def _extras(self, whole, row, env, lines) -> None: - """% 줄(덧줄) — 엔진 식 그대로 · 밑수 = 그때까지 B09 비목 합 · 줄 금액 = 이름별 · - 「X * Y / 100」 덧줄 = 규격 「노무비의 %」 · 수량 = 율 · 단위 %(149-4 `pct_extras`).""" - heads = [{} for _ in row.get("호표", [])] - pcts = labor_doc.pct_extras( - whole, row, heads + [{} for _ in row.get("덧줄", [])], dict(env) - ) - for extra, pct in zip(row.get("덧줄", []), pcts[len(heads) :]): - sums = ss.sums(row, lines) # 합밖 · 제외(792-3) + def _extras(self, row, per, lines) -> None: + """% 줄(덧줄) — 값 = 문서 셈 답(`per` = 1 단위 몫 셈 · 밑수 = 그때까지 줄 합) · 줄 금액 = 줄 자리 · + 「X × Y%」 덧줄 = 규격 「노무비의 %」 · 수량 = 율 · 단위 %(149-4) · 앞 줄 빈칸 = 「밑수 빈칸」.""" + heads = len(row.get("호표", [])) + skip = {n for n, x in enumerate(per.lines) if x.get("합밖")} + for i, extra in enumerate(row.get("덧줄", [])): + n = heads + i + sums = ss.doc_sums(skip, lines) # 합밖 · 제외(792-3) part = COST_PART.get(extra.get("비목"), "material") line = {"kind": "extra", "name": extra["이름"], "spec": extra["식"], "qty": 1.0, "unit": "식", "ref": None, **dict.fromkeys(PARTS, 0.0)} # fmt: skip - if "율" in pct: - line.update(spec=pct.get("규격") or extra["식"], qty=float(pct["율"]), unit="%") - if of := PCT_OF.get(str(pct.get("규격") or "").removesuffix("의 %")): + if pct := per.pct(n): + line.update(spec=pct[1] or extra["식"], qty=float(pct[0]), unit="%") + if of := PCT_OF.get(pct[1].removesuffix("의 %")): line["of"] = of # 719-3 덮개 다시 셈 밑수(`Sangeun_Cover`) if any(v is None for v in sums.values()): lines.append({**line, part: None, "price": {}, "why": "밑수 빈칸"}) continue - env.update({k: Decimal(str(v)) for k, v in sums.items()}) - ss.scope(row, lines, env) # 번지 · 단계(792-3) - env["줄"] = { - ln["name"]: Decimal(str(sum(ln[p] or 0 for p in PARTS))) - for ln in lines - if ln["name"] - } - try: - value = float(mf.evaluate(mf.parse(extra["식"]), env, whole, 0)) - except (mf.FormulaError, ArithmeticError, TypeError, ValueError) as e: - lines.append({**line, part: None, "price": {}, "why": str(e)}) + x = per.lines[n] if n < len(per.lines) else {} + if x.get("금액") is None: + lines.append({**line, part: None, "price": {}, "why": x.get("까닭") or "못 셈"}) continue - money = ss.extra(row, extra, value, env) # 줄 자리(792-3) + value = float(x["금액"]) + money = ss.doc_cut(value, extra.get("자리")) # 줄 자리(792-3) lines.append({**line, "price": {part: value}, part: money, "why": None}) @@ -600,26 +615,20 @@ def hand_whole(hands: list[tuple[str, str, dict[str, Any]]]) -> Any: def hand_resource_keys(user: dict[str, Any] | None) -> list[str]: - """손 줄 로직이 부르는 자원 키(단가 책 수요 · `Linked.used_keys` 꼴) — 부른 차례 · 겹침 없음.""" + """손 줄 로직이 부르는 자원 키(단가 책 수요 · `Linked.used_keys` 꼴) — 부른 차례 · 겹침 없음 · + 셈 기록(`Doc_Run.resources`).""" hands = hand_sources(user) if not hands: return [] from B09_Estimation.B09_Estimation_Linked import RESOURCE_TABLES - whole = hand_whole(hands) + whole, docs = hand_whole(hands), {} seen: list[str] = [] - base = whole.get - - def get(ref: str) -> dict[str, Any]: - row = base(ref) - key = str(row.get("키") or "") - if key[:2] in RESOURCE_TABLES and key not in seen: - seen.append(key) - return row - - whole.get = get # 이 묶음 한 벌에만 - for _key, _use, src in hands: - labor_doc.run_line(whole, src["code"], src["given"], src["rate"], src["picks"]) + for _key, _use, src in hands: # 자원 키 = 문서 셈 기록(하위 포함 · 고른 품목만) + got = dr.solve(whole, docs, src["code"], src["given"], src["picks"], src["rate"]) + for key in got.resources if got else []: + if key[:2] in RESOURCE_TABLES and key not in seen: + seen.append(key) return seen @@ -638,7 +647,8 @@ def collect( solver = Solver(supply) for owner, folder in entries: whole = item_prices.load_prices(bundle(folder)) - for src in rows_of(folder, whole): + docs = solver.shelf.put(whole, dr.docs_of(folder)) # 사본 수식 문서(855-F B9-3) + for src in rows_of(folder, whole, docs): solver.add(whole, src, owner) hand_keys: dict[str, str] = {} if hands: diff --git a/B09_Estimation/B09_Estimation_Sangeun_Sum.py b/B09_Estimation/B09_Estimation_Sangeun_Sum.py index 7d8eb85d5..64d8528d1 100644 --- a/B09_Estimation/B09_Estimation_Sangeun_Sum.py +++ b/B09_Estimation/B09_Estimation_Sangeun_Sum.py @@ -1,7 +1,8 @@ """B09 산근 풀이 셈 의미(PLAN 792-3) — 791-1 엔진 새 의미(줄 자리 · 합밖 · 번지 · 단계 · 블록 끝전 · 결과 조정 · 변수 표시)를 쓰는 로직만 엔진 규칙(`master_cut` · `master_formula_sum`) 그대로 · 새 칸 없는 로직 = 옛 B09 규칙(작업량 Q = ROUND 2 · 줄 ROUNDDOWN 1 · 총계 비목마다 ROUNDDOWN 0). -쓰는 곳 = `B09_Estimation_Sangeun.Solver` · 지킴 시험 = `test_792_3_engine_paths.py`(엔진 · M02 SK · +쓰는 곳 = 산출근거 글(`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 · SC · B09 산근 네 길 같은 금액). """ @@ -16,6 +17,7 @@ from B09_Estimation.B09_Estimation_Calc_Base import round_half, 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") PARTS = ("labor", "material", "expense") @@ -87,3 +89,52 @@ def totals(row: dict, lines: list[dict]) -> dict[str, float | None] | 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) + + +def doc_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] = doc_cut(price * ln["qty"], rule) + + +def doc_sums(skip: set[int], lines: list[dict]) -> dict[str, float | None]: + """덧줄 밑 비목 합 — 합밖 · 제외 단계 줄(문서 셈 답 `합밖`)을 뺌.""" + 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 doc_totals(answer: Any, lines: list[dict]) -> dict[str, float | None]: + """총계 — 합밖 · 제외 줄 빼고 B09 줄 금액 비목 합 → 문서 답 `끝수`(끝전 · 계 · 조정 · 새 계산기 + `settle`) · 빈칸 비목 있으면 그 비목 · 합계 빈칸(옛 `block_totals`).""" + skip = {n for n, x in enumerate(answer.lines) if x.get("합밖")} + got = doc_sums(skip, lines) + if any(v is None for v in got.values()): + out = {COST_PART[k]: None if v is None else rounddown(v, 0) for k, v in got.items()} + return {**out, "sum": total(list(out.values()))} + costs = answer.settle({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())} + + +def doc_shown(row: dict) -> dict[str, int]: + """중간값 표시 자리 {이름: 자리} — `shown` 과 같은 뜻(`표시` · 옛 로직 작업량 Q = ROUND 2 · 엑셀 자리) · + 문서 셈에 그 식 줄을 반올림으로 씌워 셈(`Doc_Run.solve` `shown`).""" + new = ms.uses(row) + out: dict[str, int] = {} + for step in row.get("중간", []): + if step.get("표시") is not None: + out[step["이름"]] = int(step["표시"]) + elif not new and _Q.fullmatch(step["이름"]): + out[step["이름"]] = 2 + return out diff --git a/resources/master_data/scripts/master_doc_trace.py b/resources/master_data/scripts/master_doc_trace.py index 07e0278b1..7045c1942 100644 --- a/resources/master_data/scripts/master_doc_trace.py +++ b/resources/master_data/scripts/master_doc_trace.py @@ -50,7 +50,15 @@ class _Seen: setattr(self._m, name, value) def __getattr__(self, name): - raw = inspect.getattr_static(self._m, name) + target = self._m + while True: # 감싼 색인(`_Over` · 사본 색인)은 속 색인 메서드를 이 감쌈에 묶음 + try: + raw = inspect.getattr_static(target, name) + break + except AttributeError: + target = getattr(target, "_whole", None) + if target is None: + return getattr(self._m, name) if isinstance(raw, types.FunctionType): return raw.__get__(self) return getattr(self._m, name) diff --git a/resources/tester/golden_855_b09.json b/resources/tester/golden_855_b09.json index bf39536aa..36d1c81f4 100644 --- a/resources/tester/golden_855_b09.json +++ b/resources/tester/golden_855_b09.json @@ -3,18 +3,18 @@ "지문": { "키": "e68369418202e5ee", "calc_user": "6d74551273d6735f", - "daega_inputs": "d26099b92d7d0a1b", - "수요": "f793204cf95c45c4", - "산근 값": "c486d041a3246ffb", - "산근 글": "a21b34ec13661f0c", - "산근 관급 값": "c5c3daf85d9bd01b", - "산근 관급 글": "a65b945fc8582ca3", + "daega_inputs": "a06884bce408c602", + "수요": "5fdf7c49052e322c", + "산근 값": "38455c2edce885ff", + "산근 글": "c41b0c2e4ae200fb", + "산근 관급 값": "d154925ee64c985c", + "산근 관급 글": "396194c98b10b525", "미리보기 hand:rate 값": "091690571b7dc54b", "미리보기 hand:rate 글": "c49b1bc692d59fe5", "미리보기 hand:pick 값": "6c7f426d37e31998", "미리보기 hand:pick 글": "96a9de9a02e3d124", "미리보기 hand:net 값": "b1c2c650567a14ae", - "미리보기 hand:net 글": "be7884bdbeb29ed3", + "미리보기 hand:net 글": "9846e15ac6f0f663", "B08 단위수량": "896710398b04b4fd" } } diff --git a/resources/tester/helper_855_engine.py b/resources/tester/helper_855_engine.py index 224cead19..8eeb49b12 100644 --- a/resources/tester/helper_855_engine.py +++ b/resources/tester/helper_855_engine.py @@ -162,3 +162,34 @@ def fingerprint(key: str, row: dict, options: bool = True) -> str: got = [[label, answer(new_run(doc, changed))] for label, _, changed in cases(row, options)] raw = json.dumps(got, ensure_ascii=False, sort_keys=True) return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] + + +def old_line_calls(whole, code: str, given) -> dict: + """옛 엔진 하위 부름(855-F B9-3 전 `B09 line_calls` · 대조 기준 · 2-E4 에서 은퇴) — 로직 호표 줄 + 차례 → 기계경비 {machine} · 돈 로직 {code, given} · 못 셈 = None.""" + from B09_Estimation import B09_Estimation_Sangeun as sg + + try: + row = whole.logic(code) + env = sg._env(whole, row, sg._clean_given(given)) + except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): + return {} + out: dict = {} + for n, item in enumerate(row.get("호표", [])): + if item.get("종류") != "로직": + continue + try: + node = mf.parse(item["요소"]) + called = node[1] if node and node[0] == "logic" else None + target = whole.logic(called) if called else None + if not target: + out[n] = None + elif mf.mb.is_machine(target): + keys = sg._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]} + out[n] = {"code": called, "given": sg._clean_given(given_)} + except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError): + out[n] = None + return out diff --git a/resources/tester/test_855_trace.py b/resources/tester/test_855_trace.py index 1be8cbb9e..b6e711607 100644 --- a/resources/tester/test_855_trace.py +++ b/resources/tester/test_855_trace.py @@ -4,7 +4,7 @@ - 자원 키 = 옛 엔진 셈 중 `whole.get` 가로채기 키(B09 `hand_resource_keys` 방식 · 찾기 색인 데운 뒤) — 다름 = `MORE` 뿐(새 계산기는 이름마다 셈 — 옛은 안 고른 「만약」 갈래 · 빈 수량 줄 · 앞서 멈춘 줄을 안 읽음 · 새 쪽에만 더 있음). -- 하위 부름 = 옛 `B09 line_calls`(돈 문서 {code, given} · 기계경비 {machine}) — 다름 = 옛이 입력 +- 하위 부름 = 옛 `B09 line_calls`(`helper_855_engine.old_line_calls` · 돈 문서 {code, given} · 기계경비 {machine}) — 다름 = 옛이 입력 기본값을 못 세 빈 답인 문서뿐 · 새 쪽 결과 문서 부름(작업량 등 중간 값)은 하위 산근 아님. - 고른 품목 = `master_pick.priced` 의 품목 키 · 줄 `부름` = 그 줄 자원. - 옛 엔진을 지우는 걸음(2-E4)에서 옛 대조(자원 · 하위)는 은퇴. @@ -106,7 +106,7 @@ def survey() -> dict: new = set(got["자원"]) if old != new: out["자원"][key] = (sorted(old - new), sorted(new - old)) - lines = sg().line_calls(whole, key, given) + lines = h.old_line_calls(whole, key, given) # 옛 엔진 기준(B9-3 뒤 B09 는 문서 셈) a, b = _calls(lines, got, docs) if a != b: out["하위"][key] = (sorted(a), sorted(b))