"""855-A 지킴 도우미 — 로직마다 셈 경우(기본 + 옵션 표본) · 옛 엔진 대 새 계산기 층 가름 · 새 답 지문. - 경우 = 빌더 대조와 같은 표본(`build_수식문서_802_2.build`) — 기본 입력(수식 탭 기본값) + 고르기 입력의 다른 갈래 하나씩(나머지 기본). - 옛 = `master_formula.run` → `master_cut.engine` · 새 = 저장된 수식 문서(`master_doc_link.load_all`) · `master_doc_calc.calc`. - 층(앞 층이 다르면 뒤 층 안 봄): L0 합계 · L1 줄 이름별 비목 금액 · L2 줄 꼴(차례 · 이름 · 금액 · 비목) · L3 수량 · 단가. 「보임」 = 금액은 같고 보이는 단가만 다름(옛 = 줄 끝수 자리로 자른 단가 · 새 = 날 값 / 수량 0 줄 단가 0 ↔ 빈 값 / 값 없는 줄 단가 빈 값 ↔ 채움 / 묶음 단가 = 계로 맞댐). """ from __future__ import annotations import hashlib import importlib import json from collections import defaultdict from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal from functools import lru_cache from M01_MasterData import M01_MasterData_Store as m01 # scripts 길을 둠 mf = importlib.import_module("master_formula") mcut = importlib.import_module("master_cut") mc = importlib.import_module("master_doc_calc") ml = importlib.import_module("master_doc_link") meq = importlib.import_module("master_equation") build = importlib.import_module("build_수식문서_802_2") KEYS = ("노무비", "재료비", "경비", "계") SEEN = "보임" @lru_cache(maxsize=1) def world(): """(로직 줄 목록, M01 색인, 수식 문서 {키: 문서}, 연결).""" files, whole = m01.loaded() docs = ml.load_all() rows = [r for d in files.values() if d.get("그룹") == "로직" for r in d.get("줄") or []] return rows, whole, docs, ml.Links(whole, docs) def cases(row: dict, options: bool) -> list[tuple[str, dict, dict | None]]: """(옵션 글, 옛 엔진 입력, 새 문서에 넘길 바뀐 입력).""" whole = world()[1] base = meq.given_of(whole, row) out = [("", base, None)] if options: for spec in row.get("입력") or []: for opt in spec.get("고르기") or []: if str(opt) != str(base.get(spec["이름"])): one = {spec["이름"]: opt} out.append((f"{spec['이름']}={opt}", {**base, **one}, one)) return out def old_run(row: dict, given: dict): whole = world()[1] try: return mcut.engine(whole, row["키"], mf.run(whole, row["키"], mf.fill_empty(row, given))) except Exception: # 옛 엔진 멈춤도 대조 값 return None def new_run(doc: dict, changed: dict | None): try: got = mc.calc(doc, world()[3], changed) except Exception: return None return got if got.get("셈됨") else None def _d(v): try: return Decimal(str(v)) except Exception: return None def _unit(v): return _d(v.get("계")) if isinstance(v, dict) else _d(v) def _per_name(lines) -> dict: acc: dict = defaultdict(lambda: defaultdict(Decimal)) for ln in lines or []: for k, v in (ln.get("비목") or {}).items(): if _d(v) is not None: acc[str(ln.get("이름"))][k] += _d(v) return {n: {k: v for k, v in b.items() if v} for n, b in acc.items()} def _shape(lines) -> list: return [ ( str(ln.get("이름")), _d(ln.get("금액")), tuple(sorted((k, _d(v)) for k, v in (ln.get("비목") or {}).items() if v is not None)), ) for ln in lines or [] ] def _cut_only(a, b) -> bool: """옛 단가 = 새 날 값을 옛 자리로 자른 값(버림 · 반올림 · 올림 어느 하나).""" ua, ub = _unit(a.get("단가")), _unit(b.get("단가")) if ua is None and _d(a.get("금액")) is None and _d(b.get("금액")) is None: return True # 값 없는 줄 — 금액 둘 다 빈 값 if ub is None and ua == 0 and _d(a.get("수량")) == 0: return True # 수량 0 줄 — 금액 0 if ua is None or ub is None: return False return ua in (ub.quantize(ua, m) for m in (ROUND_DOWN, ROUND_HALF_UP, ROUND_UP)) def level(old, new, money: bool) -> str | None: """다름 층 — None = 같음(둘 다 못 셈 포함) · 「보임」 = 보이는 단가만 다름.""" if old is None or new is None: return None if old is None and new is None else "L0" keys = KEYS if money else ("결과",) if any(_d(old.get(k)) != _d(new.get(k)) for k in keys): return "L0" if not money: return None if _per_name(old["줄"]) != _per_name(new["줄"]): return "L1" if _shape(old["줄"]) != _shape(new["줄"]): return "L2" seen = False for a, b in zip(old["줄"], new["줄"]): if _d(a.get("수량")) != _d(b.get("수량")): return "L3" if _unit(a.get("단가")) != _unit(b.get("단가")): if not _cut_only(a, b): return "L3" seen = True return SEEN if seen else None def adopted(key: str, label: str, lv: str) -> bool: """채택된 차이(요구 714-3 · 빌더 `ADOPTED`) — 합계는 그 목록만 · 줄 비목은 같은 까닭 (식 속 단가산출 부름 = 끝수 뒤 값)이 있는 문서만.""" if lv == "L0": return (key, label) in build.ADOPTED return lv == "L1" and build._uses_raw_sub(world()[2][key]) def answer(got) -> object: """새 답의 지문 꼴 — 노 · 재 · 경 · 계(돈 아닌 = 결과) · 줄(이름 · 금액 · 비목).""" if got is None: return "못 셈" if "결과" in got and got.get("계") is None: return {"결과": str(got.get("결과"))} return { "합": [str(got.get(k)) for k in KEYS], "줄": [[n, str(m), [[k, str(v)] for k, v in b]] for n, m, b in _shape(got.get("줄"))], } def fingerprint(key: str, row: dict, options: bool = True) -> str: doc = world()[2][key] 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]