"""M02 일위대가 짝 검사 · 불러오기 열쇠(PLAN 338-3 · 739-1 · 815-2) — `M02_Hopyo_Build` 가 부름. 남은 것 = 짝 재검사(`check_pair` · 고른 것 꼴 · 돈 로직 · 그 로직 입력 이름 · M01 자재품목 · 배 0 넘음 · 몫 (0, 1]) · `times_of` · `KINDS` · 불러오기 하나 열쇠 `doc_id`. 옛 별칭 장부(층 `실무자료/맞춤.json` 읽기 · 쓰기 · 찾기)는 815-2 에 화면 · 길을 걷고 853-3 에서 지움 (별칭 = M01 요소 「별칭」 칸). """ from __future__ import annotations from decimal import Decimal from pathlib import Path from typing import Any from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_MasterTemplete_Store as store KINDS = ("짝", "우리에 없음", "안 씀") def doc_id(folder: str | Path, doc: str) -> str: """불러오기 하나 열쇠 — 「층/주인/HP 키」(장부 줄 `불러오기` · 같은 불러오기 안 자동).""" layer, owner = refs.where(folder) return f"{layer}/{owner or ''}/{doc}" # ── 검사 · 쓰기 ─────────────────────────────────────────────────────── def _bad(text: str) -> store.StoreError: return store.StoreError(400, text) def _number(raw: Any) -> Decimal | None: if isinstance(raw, bool): return None try: got = Decimal(str(raw).replace(",", "").strip()) except ArithmeticError: return None return got if got.is_finite() else None def _json(value: Decimal) -> int | float: value = value.normalize() return int(value) if value == value.to_integral_value() else float(value) def _known() -> tuple[set[str], set[str]]: """(돈 로직 키, M01 자재품목 키) — 맞춤 목록 한 벌(`M02_Hopyo_Match.targets`).""" from M02_MasterTemplete import M02_Hopyo_Match as match # 맞춤이 장부를 부름 — 늦게 읽음 got = match.targets() return {x["로직"] for x in got["로직"]}, {x["자재"] for x in got["자재"]} def input_names(code: str) -> set[str]: got = labor_inputs.logic_inputs([code])["로직"] return {str(x.get("이름")) for x in (got[0]["입력"] if got else [])} # 고른 것 꼴(785-3 · `M02_Hopyo_Row.pick`) — 갈래 → 키 머리(None = 키 없음 · 기초 = 돈 로직 목록) PICK_HEADS: dict[str, tuple[str, ...] | None] = { "기초": ("GC", "GF"), "단가산출": ("SK-",), "일위대가": ("SC-",), "인력": ("LB",), "재료": ("MT", "PM"), "유가": ("MO",), "기계": ("EQ",), "율": None, "고정": None, } PICK_KEYS = {"갈래", "키", "입력값", "배", "몫", "이름", "단위", "비목", "기준", "별도계상"} def _check_pick(raw: dict, where: str, known: tuple[set[str], set[str]]) -> dict[str, Any]: """고른 것 꼴 짝 재검사 — 갈래 · 키 머리 · M01 에 있음 · 입력값(기초만) · 율 비목 · 기준.""" from M02_MasterTemplete import M02_Labor_Fixed as fixed # 고정 줄 규칙(율 기준) — 늦게 읽음 kind = raw.get("갈래") if kind not in PICK_HEADS or set(raw) - PICK_KEYS: raise _bad(f"짝 갈래 · 칸이 틀림 「{where}」") code, heads = str(raw.get("키") or ""), PICK_HEADS[kind] if heads is None and code or heads is not None and not code.startswith(heads): raise _bad(f"「{kind}」 키가 틀림 「{code}」 「{where}」") if ( kind == "기초" and code not in known[0] or kind == "재료" and code[:2] == "MT" and code not in known[1] ): raise _bad(f"없는 {kind} 「{code}」 「{where}」") if kind in ("인력", "유가", "기계") and not fixed._has(m01.loaded()[1], code): raise _bad(f"M01 에 없는 {kind} 「{code}」 「{where}」") values = raw.get("입력값") or {} if not isinstance(values, dict) or (values and kind != "기초"): raise _bad(f"입력값이 틀림 「{where}」") if unknown := set(values) - input_names(code) if values else set(): raise _bad(f"모르는 입력 {sorted(unknown)} 「{where}」") if kind == "율" and not (raw.get("비목") in fixed.COSTS and fixed._basis(raw.get("기준"))): raise _bad(f"율 짝은 비목 · 기준 「{where}」") times, part = times_of(raw, where) out = { "갈래": kind, **({"키": code} if code else {}), "입력값": values, "배": times, "몫": part, } out.update({k: str(raw[k]) for k in ("이름", "단위", "비목") if raw.get(k)}) if kind == "율": out["기준"] = raw["기준"] return {**out, **({"별도계상": True} if raw.get("별도계상") is True else {})} def check_pair(raw: Any, where: str, known: tuple[set[str], set[str]]) -> dict[str, Any]: """짝 하나 재검사 → `{로직|자재, 입력값, 배, 몫}` · 고른 것 꼴(`갈래`) — 틀리면 400.""" if not isinstance(raw, dict): raise _bad(f"짝 꼴이 틀림 「{where}」") if "갈래" in raw: return _check_pick(raw, where, known) extra = set(raw) - {"로직", "자재", "입력값", "배", "몫", "이름", "단위"} if extra: raise _bad(f"모르는 칸 {sorted(extra)} 「{where}」") code, mat = str(raw.get("로직") or ""), str(raw.get("자재") or "") if bool(code) == bool(mat): raise _bad(f"돈 로직 · 우리 자재 하나만 「{where}」") if (code and code not in known[0]) or (mat and mat not in known[1]): raise _bad(f"없는 {'로직' if code else '자재'} 「{code or mat}」 「{where}」") values = raw.get("입력값") or {} if not isinstance(values, dict) or (mat and values): raise _bad(f"입력값이 틀림 「{where}」") unknown = set(values) - input_names(code) if code and values else set() if unknown: raise _bad(f"모르는 입력 {sorted(unknown)} 「{where}」") times, part = times_of(raw, where) head = {"로직": code} if code else {"자재": mat} return { **head, "입력값": values, "배": times, "몫": part, } def times_of(raw: dict[str, Any], where: str) -> tuple[int | float, int | float | None]: """(배, 몫) 재검사 — 배 0 넘는 수 · 몫 없음 또는 (0, 1].""" times = _number(raw.get("배", 1)) if times is None or times <= 0: raise _bad(f"배는 0 넘는 수 「{where}」") share = raw.get("몫") part = None if share is None else _number(share) if share is not None and (part is None or not 0 < part <= 1): raise _bad(f"몫은 0 넘고 1 이하 「{where}」") return _json(times), None if part is None else _json(part)