Files
Aislo/B09_Estimation/B09_Estimation_Labor_Source.py
T
eomsangdonandClaude Opus 5.5 11d348492e refactor(855-F B9-5): 사본 단가산출 굳힘 걷음 — 굳힌 로직 줄(GX9) 대신 M02 문서 + 수식 따로 사본 · B09 대가가 문서 셈
- M02_Item_Sangeun: freeze = SK 마다 지금 M02 셈 사본(Doc_Sk.copy_of · 덮음 반영)을 수식에 따로 · 굳힘 표지로 굳힘 ·
  원본 · 처음 · 덮음바탕(M01 따라옴 기록) 뺌 · 옛 GX9 키 · 굳힌줄 · 정체 · 원본 · SC 굳힌 덮개 줄 지움
  · bundle_keys = SK 셈이 읽는 바탕 로직 · 부름 문서 키 · 값 사본 자원 키 · 가져온 식 줄
- M02_Item_Source: 단가.json 에 로직_단가산출.json(GX9) 없음 · SK 줄은 bundle_keys 로 모음
- B09 Labor_Source.sangeun: SK 대가 블록 = 수식 사본 문서 답(줄 이름 · 단위 · 종류 · 자원 키 · 하위 부름) ·
  셈법(792-4)은 줄이 기초 줄과 맞을 때만 · cid 열쇠 = SK 이름표 · 줄 덮개(패치) = M02 처럼 못 셈
- B09 Linked: sk_answer(사본 SK 문서 셈 · 가져온 식 = 단가기준) · 수요 키 = 셈 기록
- B09 Refresh: 바뀐 SK = SK 문서 · 수식 사본 대조 · Supply.sk_money: 배 = 바탕 줄(바탕 없음 = 1)
- 골든 test_855_b09_golden 다시 뜸 — daega_inputs · 수요 두 갈래만(calc_user · 산근 · 미리보기 · B08 같음):
  SK 블록 origin · cid 열쇠(GX9 → SK 이름표) · 재료 단위 = 문서 표기(kg → ㎏) ·
  따로 고친 SK 줄 수량 = M02 문서(0.018 → 0.036 · 옛 굳힘은 고친 문서를 못 봄) ·
  옛 칸(율 더한줄) SK = M02 처럼 못 셈 → 그 SK 자원 키 둘(LB000038 · EQ000153) 빠짐
- 시험: test_719_1 · 719_2 견본을 수식 사본 있는 SK(M02 에서 고친 문서)로 · 단언을 새 사본 꼴로 ·
  719_2 옛 칸 견본 셋 지움(단가 덮개 · SC 더한줄 펼침 · 내 자료집 둘 — 옛 칸 SK 만들기 = 2-C1 셈 은퇴) ·
  test_778_4 옛 칸 율 더한줄 SK 블록 하나 지움 · test_792_3 ⑤ · test_793_2 = 새 사본 꼴(793_2 우리 단가 = 사본 굳힘)
- 검증: 관련 + 핵심 672 — 통과 671 · test_848_1 ㉦ 하나 = sub4 2-D 굳힘 표지 읽기 두 줄 뒤 통과(브레인 정함) ·
  사본 칸(골든 견본) SK 굳힌줄 · GX9 10 → 0 · 수식 따로 2 → 9 · typecheck 0 · 빌더 --check 같음 · 서버 뜸 로그 오류 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:24:52 +09:00

696 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""B09 일위대가(대가) 블록 입력(PLAN 145-2) — 서버 단독 · 읽기만 · 값(단가)은 안 씀.
연결된 사본(`M02_Item_Snapshot.linked_snapshots`)마다 `일위대가.json` 을 사본 셈 한 벌
(`M02_Item_Prices.calc` = 142-1 층 셈 꼴)로 돌려 줄 수량을 받고, 블록 꼴로 펼침:
조합 구조물 조합 사본 하나 = 블록(엑셀 「조합」 꼴) · 줄 = 담은 로직 줄 · 자재 줄
사전조합 참조 SC = 겹 대가(굳힌 `참조사본`) · 줄 = 그 안 로직 · 참조 줄 · 자재 줄(175-2) ·
안 줄 수량(723-4) = 굳힌 옛 손 → 쓰는 구조물 사본 면적 알약 값(723-1
「참조 id#차례」 · 「참조 id#자재|코드」) → 없음 = 빈 줄(`ask` · 이 공사에서 입력 =
702 덮개 qty) · 알약 값 쓴 블록 덮개 = `C:참조|S:사본`(사본마다 값 다름) ·
그 밖 = `C:참조`(공사 안 한 덮개)
품셈 일위대가화(승격) 줄 · 옛 참조 SP = 로직마다 따로(노무 · 재료 · 중기 · 산근 · % 줄)
— 조합이 수량만큼 부름 · 기계 = 기계경비 로직 줄 · 다른 돈 로직 줄 = 하위 산근
산근 단가산출 줄(일위대가화 아닌 로직 줄) = 산근 호표 참조(키 = 145-1 `sangeun_key`)
(155-3 · 사용자 뜻 = 일위대가화 줄 = 대가 · 단가산출 줄 = 산근 · 145 정함 뒤집음)
고정 고정 줄(705-1) = `fixed` 줄 하나 · `own` = 줄 단가 · `link` = 이음 키(셈 짝이 단가 책 값)
같은 블록 = 같은 꼴 → 한 호표(id = 내용 해시 · 같은 원본 + 같은 셈 단가 = 하나) ·
덮개 열쇠(702-2 · 내용 해시 밖 · 수량 · 단가가 바뀌어도 그대로) = 블록 `cover` + 줄 `cid` —
cover = 조합 `S:사본 폴더` · 서고 `L:폴더` · 사전조합 `C:참조` · 품셈 `P:로직 + 입력 해시`
cid = 줄 정체(비목 : 노임 · 자재 · 중기 코드 · 산근 · 부른 대가 로직 · 참조) + `#n번째`
줄 수량 = 사본 셈 수량(손 · 면적 알약 칸) — 대가 줄만 ÷ 배(부르는 호표 1 단위 몫 ·
산근 단가는 이미 1 단위).
단가 · 금액 · 끝수는 셈 짝(`B09_Estimation_Calc_Labor`)이 B09 프로젝트 한 벌 단가로 냄.
"""
from __future__ import annotations
import hashlib
import json
import re
from decimal import Decimal
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
from B09_Estimation.B09_Estimation_Bill_Items import LAYER_WORD
from B09_Estimation.B09_Estimation_Copy_Prices import bundle
from B09_Estimation.B09_Estimation_Linked import sk_answer
from B09_Estimation.B09_Estimation_Supply import sk_money, supply_mark
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 import M02_Labor_Patch as patch
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete.M02_Item_Snapshot import (
MANIFEST_NAME,
PICKS_FILE,
VALUES_FILE,
linked_snapshots,
structures_dir,
)
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
mf = item_prices.mf
#: 엔진 비목 → 블록 비목
PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
GROUP = {"인력": "labor", "재료": "material", "장비": "machine"} # 율 기준 묶음(778-4)
#: % 덧줄 밑수 — `노무비 * …` · `줄.'이름' * …` · `(석공 * LB… + …) * …`(인력 줄)
BASE_PART = re.compile(r"^\s*(노무비|재료비|경비)\s*\*")
BASE_LINE = re.compile(r"^\s*줄\.'([^']+)'\s*\*")
BASE_LABOR = re.compile(r"^\s*\(.*\*\s*LB\d+")
AREA_FILE = "면적.json"
ASK = "수량 없음 — 이 공사에서 입력" # 723-4 SC 안 줄 수량 빈칸(펼침 품 · 수량 칸)
def _f(value: Any) -> float | None:
if isinstance(value, bool) or value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _digest(value: Any) -> str:
text = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
def sangeun_ref(code: str, given: Any, rate: Any, picks: Any) -> str:
"""산근 호표 키 — 145-1 `B09_Estimation_Sangeun.sangeun_key`."""
return sg.sangeun_key(code, given or {}, rate, picks or {})
class Builder:
"""한 프로젝트 블록 모음 — 같은 id 는 한 번만(처음 본 차례)."""
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']])}"
if bid not in self.blocks:
mark = {"품셈": "P", "사전조합": "C"}.get(block["kind"], "S")
if cover is None:
origin = block["origin"]
cover = f"C:{origin['참조']}" if mark == "C" else f"{mark}:{_digest(origin)}"
lines = [{**ln, "cid": cid} for ln, cid in zip(block["lines"], self._cids(block))]
self.blocks[bid] = {"id": bid, "cover": cover, **block, "lines": lines}
return bid
def _cids(self, block: dict[str, Any]) -> list[str]:
"""줄 정체(702-2) — 같은 정체 n번째 = `#n` · 재적용으로 줄이 늘거나 바뀌어도 맞는 줄에."""
seen: dict[str, int] = {}
out = []
for line in block["lines"]:
kind, key = line["kind"], str(line.get("key") or "")
if kind == "daega" and key in self.blocks:
origin = self.blocks[key]["origin"]
key = str(origin.get("로직") or origin.get("참조") or key)
elif kind == "sangeun":
key = key.rsplit(":", 1)[0] # SG:로직:입력 해시 → 로직만
elif kind == "pct":
key = str(line.get("base") or "")
head = f"{kind}:{key or line.get('name') or ''}"
seen[head] = seen.get(head, -1) + 1
out.append(f"{head}#{seen[head]}")
return out
# ── 품셈(로직 하나) ─────────────────────────────────────────────────
def poomsem(self, whole: Any, one: dict[str, Any], title: str = "") -> str | None:
got = self._poomsem(whole, one, title)
if got is None:
return None
got.pop("_engine"), got.pop("_items")
return self.put(got)
def _poomsem(self, whole: Any, one: dict[str, Any], title: str = "") -> dict | None:
"""품셈 블록 꼴(넣기 전) — 문서 셈 줄(`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 = 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.engine(items) # 옛 엔진 줄 꼴(단위 = 원문 · % 줄 율)
bases = _engine_bases(engine[: len(items)], items)
for n, x in enumerate(engine):
item = items[n] if n < len(items) else None
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":
line["spec"] = (eq.get(line["key"]) or {}).get("규격") or ""
marks = one.get("자재표시") or {} # 841-1 M02 자재표시(호표 차례) → 대비표 기본 표시
for n, line in enumerate(lines):
if line["kind"] == "material":
line["mark"] = supply_mark(marks.get(str(n)))
law = rule.mark(logic, lines, engine) # 새 의미 로직 = 줄 자리 · 합밖 · 번지 · 끝전(792-4)
unit = str(logic.get("결과단위") or "").replace("원/", "")
spec = " · ".join(f"{k} {v}" for k, v in sorted(given.items()))
shown = " · ".join( # 157-4 기계 · 직종 원문번호 = 「이름 규격」(번호 = 화면 풍선 spec_raw)
f"{k} {st._word(whole, k, v) if isinstance(v, str) else v}"
for k, v in sorted(given.items())
)
return {
"kind": "품셈",
"name": title or logic.get("이름") or code,
"spec": shown,
"spec_raw": spec,
"unit": unit,
"cite": logic.get("출처") or "",
"origin": {"로직": code, "입력값": given, "켜쌓기율": rate, "고름": picks},
"lines": lines,
**({"rule": law} if law else {}),
"_engine": engine,
"_items": items,
}
# ── 단가산출(SK · 719-2 · 855-F B9-5) ──────────────────────────────────
def sangeun(self, whole: Any, ref: dict, doc: dict, copies: dict, depth: int = 0) -> str | None:
"""사본 SK = 품셈 꼴 대가 — 셈 = 그 수식 사본 문서 셈(`Linked.sk_answer` ·
M02 SK 셈과 같은 문서) · 줄 = 문서 답 금액 줄(이름 · 단위 · 수량 · 종류 = 답 ·
자원 키 · 하위 부름 = 셈 기록) — 노임 · 자재 · 기계경비(중기) · 하위 단가산출(산근) ·
% 줄 · 그 밖 = 줄 단가 `fixed` · 합밖 = `out` · cover = `P:` + SK 이름표(SK 를 고쳐
[재생성] 해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) ·
수식 사본 없는 SK(형제 · 옛 칸) = None(부르는 줄이 까닭 · M02 처럼 못 셈)."""
got = sk_answer(doc)
if got is None or got.stopped or "결과" in got.ans:
return None
rid = refs.ref_id(ref)
lines = [{**self._doc_line(got, n, x), "sk": True} for n, x in enumerate(got.lines)]
base = str((doc.get("바탕") or {}).get("로직") or "")
law = _law(doc, base, whole, lines, got.lines) # 새 의미 로직 줄 자리 · 합밖 · % 밑(792-4)
expand = _Loose(whole, lambda r: copies.get(refs.ref_id(r)))
m02 = sk_money(doc, whole, expand, rid)
given = doc.get("입력값") or {}
block = {
"kind": "품셈",
"name": doc.get("이름") or got.doc.get("이름") or "",
"spec": " · ".join(
f"{k} {st._word(got.whole, k, v) if isinstance(v, str) else v}"
for k, v in sorted(given.items())
),
"spec_raw": " · ".join(f"{k} {v}" for k, v in sorted(given.items())),
"unit": str(got.doc.get("결과단위") or "").replace("원/", "") or doc.get("단위") or "",
"cite": f"단가산출 {ref.get('키')}",
"origin": {"참조": rid, "단가산출": rid, "바탕": base}, # cid 열쇠 = SK 이름표
"lines": lines,
**({"rule": law} if law else {}),
**({"m02": m02} if m02 else {}),
}
return self.put(block, f"P:{_digest({'단가산출': rid})}")
def _doc_line(self, got: Any, n: int, x: dict) -> dict[str, Any]:
"""문서 답 금액 줄 하나 → 블록 줄(855-F B9-5)."""
head = {"name": x.get("이름") or "", "spec": "", "unit": x.get("단위") or ""}
qty, key, call = _f(x.get("수량")), str(x.get("키") or ""), x.get("부름") or {}
out = {"out": True} if x.get("합밖") else {}
if pct := got.pct(n):
word = pct[1].removesuffix("의 %")
base = {"노무비": "part:labor", "재료비": "part:material", "경비": "part:expense",
"인건비": "lines:labor"}.get(word, f"line:{word}") # fmt: skip
if not word: # 밑을 모르는 덧줄 — 옛 길과 같게 빈 줄
return {
**head,
**out,
"kind": "blank",
"qty": qty,
"why": "덧줄 — 대가 단가로 못 셈",
}
part = PART.get(str((got.doc.get("금액") or [])[n].get("비목")), "expense")
return {**head, **out, "kind": "pct", "part": part, "base": base,
"spec": pct[1], "unit": "%", "qty": float(pct[0])} # fmt: skip
own = _own(x, qty)
if call.get("machine") or key[:2] == "EQ":
key = call.get("machine") or key
spec = (_row(got.whole, key)).get("규격") or ""
return {**head, **out, "kind": "machine", "key": key, "spec": spec, "qty": qty,
"own": own} # fmt: skip
if call.get("code"):
return {**head, **out, "kind": "sangeun", "qty": qty,
"key": sg.sangeun_key(call["code"], call.get("given") or {})} # fmt: skip
if key[:2] == "LB":
return {**head, **out, "kind": "labor", "key": key, "qty": qty, "own": own}
if (x.get("품목") or {}).get("키") or key[:2] in ("MT", "MO", "PM"):
goods = x.get("품목") or {}
return {**head, **out, "kind": "material", "key": goods.get("키") or key,
"spec": goods.get("규격") or "", "qty": qty, "own": own} # fmt: skip
if own is None or (not key and x.get("단가") is None): # 값 없는 재료 찾기 · 못 셈
return {**head, **out, "kind": "blank", "qty": qty, "why": x.get("까닭") or "품목 없음"}
return {**head, **out, "kind": "fixed", "qty": qty, "own": own, "link": {}}
def _engine_line(
self, item: dict | None, x: dict, logic: dict, extra: int, bases: dict, call: dict | None
) -> dict[str, Any]:
head = {"name": x.get("이름") or "", "spec": "", "unit": x.get("단위") or ""}
qty = _f(x.get("수량"))
goods = x.get("품목") or {}
if item is None: # 덧줄 — 밑수 × % / 100(% = 엔진 값 ÷ 엔진 밑수)
add = (logic.get("덧줄") or [])[extra]
base, label = _base_of(str(add.get("식") or ""))
value, under = _f(x.get("금액")), bases.get(base) if base else None
if value is None or not under:
# ponytail: 밑수 없는 덧줄(손료 식 등)은 B09 단가로 못 셈 — 줄만 두고 빈칸
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(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 "")
return {**head, "kind": "labor", "key": key, "qty": qty, "own": own}
if kind == "재료":
if not goods.get("키"):
return {**head, "kind": "blank", "qty": qty, "why": x.get("까닭") or "품목 없음"}
return {**head, "kind": "material", "key": goods["키"], "spec": goods.get("규격") or "",
"qty": qty, "own": own} # fmt: skip
# 로직 줄 — `Sangeun.call_of` 판정: 기계경비 로직 = 중기 · 그 밖 = 하위 산근
if call and call.get("machine"): # 기계 시간당 = M02 엔진 값(841-1)
return {**head, "kind": "machine", "key": call["machine"], "qty": qty, "own": own}
if call and call.get("code"):
key = sg.sangeun_key(call["code"], call["given"])
return {**head, "kind": "sangeun", "key": key, "qty": qty}
return {**head, "kind": "blank", "qty": qty, "why": "하위 로직 줄 — 못 펼침"}
# ── 조합 · 사전조합 줄 ──────────────────────────────────────────────
def line_of(
self,
whole: Any,
one: dict,
qty: Any,
times: Any,
name: str,
copies: dict,
depth: int = 0,
use: tuple[dict, str] = ({}, ""),
) -> dict[str, Any]:
"""담은 로직 줄 하나 → 블록 줄 — 대가 줄 수량 = 수량 ÷ 배(부르는 호표 1 단위 몫) ·
산근 줄 수량 = 수량 그대로(산근 단가 = 결과단위 1 단위) · use = 쓰는 곳(알약 값 · 자리)."""
q = _f(qty)
t = _f(times) or 1.0
each = None if q is None else q / t
if fixed.is_fixed(one):
return fixed_line(one[fixed.FIXED], q, None, whole)
if one.get(patch.FIELD): # 줄 덮개(715-3) = M02 처럼 못 셈(855 2-C5)
return {"kind": "blank", "name": name, "qty": each, "why": patch.WHY}
ref = one.get("참조")
if isinstance(ref, dict):
doc = copies.get(refs.ref_id(ref))
if not isinstance(doc, dict):
return {
"kind": "blank",
"name": name,
"qty": each,
"why": f"없는 참조 「{ref.get('키')}」",
}
if refs.kind_of(ref.get("키")) == "sangeun": # 단가산출(719-2) = 수식 사본 대가
bid = self.sangeun(whole, ref, doc, copies, depth + 1)
if bid is None:
why = "단가산출을 못 셈(수식 사본 없음 · 못 돈 문서)"
return {"kind": "blank", "name": name, "qty": each, "why": why}
from M02_MasterTemplete import M02_Sangeun_Calc as sc
block = self.blocks[bid] # 블록 = 굳힌 줄 결과단위(배) 몫 · M02 참조 줄 = 1 단위
try: # 배 = 바탕 기준단위 → SK 단위(728-2)
per = float(sc.ratio_of(doc, sc._row_of(doc, whole), whole))
except sc.sd.DocError as e:
return {"kind": "blank", "name": name, "qty": each, "why": str(e)}
return {"kind": "daega", "key": bid, "name": block["name"], "unit": block["unit"],
"qty": None if each is None else each / per} # fmt: skip
if refs.kind_of(ref.get("키")) == "promote": # 옛 단가승격 참조 = 일위대가화 = 대가
first = (doc.get("담은로직") or [{}])[0]
bid = self.poomsem(whole, first, doc.get("이름") or name)
if bid is None:
return {"kind": "blank", "name": name, "qty": each, "why": "돈 아닌 로직"}
return {"kind": "daega", "key": bid, "name": self.blocks[bid]["name"],
"unit": doc.get("단위") or "", "qty": each} # fmt: skip
bid = self.precombo(whole, ref, doc, copies, depth + 1, use)
return {"kind": "daega", "key": bid, "name": doc.get("이름") or name,
"unit": doc.get("단위") or "", "qty": each} # fmt: skip
code = str(one.get("로직") or "")
if one.get("승격") is not True: # 단가산출 줄 = 산근
if not sg.is_money(whole, code):
return {"kind": "blank", "name": name or code, "qty": q, "why": "돈 아닌 로직"}
key = sangeun_ref(code, one.get("입력값"), one.get("켜쌓기율"), one.get("고름"))
return {"kind": "sangeun", "key": key, "name": name or code,
"unit": sg.unit_of(whole, code), "qty": q} # fmt: skip
bid = self.poomsem(whole, one, str(one.get("별칭") or "") or name)
if bid is None:
return {
"kind": "blank",
"name": name or code,
"qty": each,
"why": "돈 아닌 로직 · 못 돈 로직",
}
block = self.blocks[bid]
return {"kind": "daega", "key": bid, "name": block["name"], "spec": block["spec"],
"spec_raw": block.get("spec_raw"), "unit": block["unit"], "qty": each} # fmt: skip
def precombo(
self,
whole: Any,
ref: dict,
doc: dict,
copies: dict,
depth: int = 0,
use: tuple[dict, str] = ({}, ""),
) -> str:
"""사전조합(SC) = 겹 대가 — 로직 줄 = 품셈 호표 · 자재 줄(175-2) · 줄 수량(723-4 · 742-1) =
굳힌 손 → use 알약 값 → 저장 수량(`refs.SAVED`) → 없음(`ask`) · use = (쓰는 구조물 사본 면적
알약 값, 덮개 자리)."""
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
rid, (given, where) = refs.ref_id(ref), use
pilled: list[bool] = [] # 줄마다 알약 값을 썼나
def qty_of(key: str, qty: Any) -> float | None: # 짝 = `M02_Labor_Expand._qty` 차례
qty = qty if isinstance(qty, dict) else {}
got = _f(qty.get("손"))
pill = None if got is not None else _f(given.get(key))
pilled.append(got is None and key in given)
return got if got is not None else pill if pill is not None else _f(qty.get(refs.SAVED))
inner = [one for one in doc.get("담은로직") or [] if isinstance(one, dict)]
kept = doc.get("알약") # 굳힌 알약(142-2 · 지금 M01 안 읽음 · 719-2) · 없으면 셈
pills = {
code: pill
for pill in (kept if isinstance(kept, list) else None)
or combo_store.combo_pills({"담은로직": inner})["물량"]
for code in pill["로직"]
}
lines = []
for n, one in enumerate(inner):
qty = qty_of(f"{rid}#{n}", one.get("수량"))
pill = pills.get(one.get("로직")) or {}
times = pill.get("배") if "로직" in one else 1
name = pill.get("이름") or str(one.get("로직") or "")
if depth >= refs.DEPTH and isinstance(one.get("참조"), dict):
lines.append({"kind": "blank", "name": name, "qty": qty, "why": "참조 깊이 넘음"})
continue
lines.append(self.line_of(whole, one, qty, times, name, copies, depth, use))
for mat in doc.get("자재") or []:
key = f"{rid}#{labor_doc.material_key(mat.get('코드'))}"
lines.append(_material(whole, mat, qty_of(key, mat.get("수량"))))
lines = [ln if ln["kind"] == "blank" or ln.get("qty") is not None else {**ln, "ask": ASK}
for ln in lines] # fmt: skip
return self.put(
{
"kind": "사전조합",
"name": doc.get("이름") or ref.get("키"),
"spec": LAYER_WORD.get(str(ref.get("층")), ""), # 번호(키)는 풍선 글로만
"spec_raw": str(ref.get("키") or ""),
"unit": doc.get("단위") or "",
"cite": "",
"origin": {"참조": rid},
"lines": lines,
},
f"C:{rid}|{where}" if where and any(pilled) else None,
)
# ── 조합(구조물 사본) ───────────────────────────────────────────────
def combo(self, folder: Path, cover: str | None = None) -> str | None:
labor = read_json(folder / LABOR_FILE)
if not isinstance(labor, dict):
return None
prices = bundle(folder) # 841-1 미리 보기 덮개
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, {"문서": 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 {}
lines = []
for one, done in zip(doc.get("담은로직") or [], result.get("줄") or []):
name = done.get("이름") or str(one.get("로직") or "")
pill = next(
(p for p in result.get("알약") or [] if p.get("키") == done.get("알약")), {}
)
line = self.line_of(
whole,
one,
done.get("수량"),
done.get("배"),
pill.get("이름") or name,
copies,
0,
use,
)
if line.get("qty") is None and line["kind"] != "blank":
line = {**line, "why": "수량 없음 — 면적산출 알약 칸 · 손 수량을 넣음"}
lines.append(line)
marks = {m.get("코드"): m for m in doc.get("자재") or [] if isinstance(m, dict)}
lines += [
_material(whole, {**(marks.get(mat.get("코드")) or {}), **mat}, mat.get("수량"))
for mat in result.get("자재") or []
]
manifest = read_json(folder / MANIFEST_NAME) or {}
origin = manifest.get("원본") or {}
return self.put(
{
"kind": "조합",
"name": origin.get("name") or " ".join(origin.get("경로") or []) or folder.name,
"spec": " › ".join(origin.get("경로") or []),
"unit": (labor.get("줄") or {}).get("단위") or "",
"cite": "",
"origin": {k: origin.get(k) for k in ("layer", "owner", "key")},
"lines": lines,
},
cover or f"S:{folder.name}",
)
def library(self, folder: Path, manifest: dict[str, Any]) -> str | None:
"""설계내역서 서고 사본(204-2) — 구조물조합 = 조합 블록 · 사전조합 = 겹 대가 블록 그대로."""
if manifest.get("종류") not in ("precombo", "sangeun"):
return self.combo(folder, f"L:{folder.name}")
labor = read_json(folder / LABOR_FILE)
ref = (manifest.get("원본") or {}).get("참조")
copies = (labor or {}).get("참조사본") or {}
doc = copies.get(refs.ref_id(ref)) if isinstance(ref, dict) else None
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)
def _Loose(whole: Any, read: Any) -> Any:
"""B09 SK 속 펼침(723-4) — 사전조합 안 줄 수량 없음 = 0 값묶음(엔진 차례 · 수량만 씀 ·
그 줄 값 = B09 사전조합 블록 · 이 공사에서 입력) · 그 밖 까닭은 그대로."""
from M02_MasterTemplete.M02_Labor_Expand import NO_QTY, Expand
class Loose(Expand):
def __call__(self, ref: dict, trail: tuple[str, ...] = ()) -> dict[str, Any]:
got = super().__call__(ref, trail)
if got.get("기준") is None and str(got.get("까닭") or "").endswith(NO_QTY):
return {**got, "기준": dict.fromkeys(labor_doc.COSTS, Decimal(0))}
return got
return Loose(whole, read)
def _row(whole: Any, key: str) -> dict[str, Any]:
try:
return whole.get(key) or {}
except Exception: # noqa: BLE001 — 없는 키 = 빈 줄
return {}
def _law(doc: dict, base: str, whole: Any, lines: list, engine: list) -> dict | None:
"""SK 블록 셈법(792-4) — 줄이 기초 줄(가져온 식 = 가져온 줄 · 그 밖 = 바탕 로직)과 하나하나
맞을 때만 `rule.mark`(새 의미 로직 = 줄 자리 · 합밖 · % 밑) · 안 맞음(따로 고친 문서) = None."""
from M02_MasterTemplete import M02_Doc_Import as dim
try:
row = (doc.get("가져온") or {}).get("로직") if dim.is_imported(doc) else whole.logic(base)
except Exception: # noqa: BLE001 — 바탕 없음 · 없는 로직
return None
if not isinstance(row, dict) or len(rule.ms.items(row)) != len(lines):
return None
return rule.mark(row, lines, engine)
def fixed_line(fx: dict, qty: Any, where: dict | None = None, whole: Any = None) -> dict[str, Any]:
"""고정 줄(705-1) → 블록 줄 `fixed` — 수량 그대로(배 1) · 단가 = M02 엔진 고정 줄 셈(`whole` =
사본 단가 묶음 · 이은 노임 · 자재 = 묶음 값 · 841-1) · 없으면(붙인 줄) 줄 단가 ·
비율 줄(705-3) = `pct`(밑 = 블록 그 비목 합 · 수량 = 율) · 율 기준(778-4) 묶음 = `bundle:` ·
줄 목록 = `rows:` 블록 차례(`where` {열쇠: 차례} · 단가산출 블록만 · 없으면 빈 줄)."""
if rate := fx.get("비율"):
name = {"name": fx.get("이름") or "", "spec": fx.get("규격") or "", "unit": "%"}
basis = rate["기준"]
if isinstance(basis, list) and where is None:
return {
**name,
"kind": "blank",
"qty": _f(qty),
"why": "율 기준 줄 목록 — 대가로 못 셈",
}
base = (
"rows:" + ",".join(_row_of(k, where) for k in basis if _row_of(k, where))
if isinstance(basis, list)
else f"part:{PART[basis]}"
if basis in PART
else f"bundle:{GROUP[basis]}"
)
return {**name, "kind": "pct", "part": PART[rate["비목"]], "base": base, "qty": _f(qty)}
link = fx.get("이음") or {}
money = fixed.line(whole, fx)["기준"] if whole is not None else fx.get("단가") or {}
return {
"kind": "fixed",
**{k: fx.get(v) or "" for k, v in (("name", "이름"), ("spec", "규격"), ("unit", "단위"))},
"qty": _f(qty),
"own": {PART[k]: _f(v) for k, v in money.items() if k in PART},
"link": {
"labor": link.get("노임"),
"material": link.get("자재"),
"machine": link.get("기계"),
},
}
def _row_of(key: str, where: dict) -> str:
"""율 기준 열쇠 → 블록 차례 글(`열쇠@비목` = `n@labor`) · 없는 열쇠 = ""."""
from M02_MasterTemplete.M02_Labor_Fixed import split_key
line, cost = split_key(key)
if line not in where:
return ""
return f"{where[line]}@{PART[cost]}" if cost else str(where[line])
def _own(x: dict, qty: float | None) -> dict[str, float] | None:
"""엔진 줄 비목 단가(841-1) = 엔진 금액 ÷ 엔진 수량 · 수량 0 = 0 · 못 셈 = None(빈칸)."""
money = x.get("비목") or {}
if not qty:
return dict.fromkeys(PART.values(), 0.0) if qty == 0 else None
return {PART[k]: (_f(v) or 0.0) / qty for k, v in money.items() if k in PART}
def _material(whole: Any, mat: dict, qty: Any) -> dict[str, Any]:
"""자재 줄 — 조합 사용자 자재 · 사전조합 자재(175-2) 한 꼴 · 이름 · 규격 · 단위 = 사본 단가 ·
단가 = M02 엔진 자재 기준단가(841-1 · 조합 셈 답 `기준단가` · 없으면 사본 단가 묶음으로)."""
row = (whole.get(mat.get("코드")) if mat.get("코드") else None) or {}
names = {k: row.get(v) or "" for k, v in (("name", "이름"), ("spec", "규격"), ("unit", "단위"))}
price = mat["기준단가"] if "기준단가" in mat else None
if price is None and mat.get("코드"):
price = labor_doc.material_price(whole, mat["코드"], mat.get("단위"))["기준단가"]
own = None if _f(price) is None else {"material": _f(price)}
return {"kind": "material", "key": mat.get("코드"), **names, "qty": _f(qty), "own": own,
"mark": supply_mark(mat)} # fmt: skip
def _engine_bases(engine: list[dict], items: list[dict]) -> dict[str, float]:
"""엔진 호표 줄 → 덧줄 밑수 후보 — `part:비목` 합 · `lines:labor` 인력 줄 합 · `line:이름`."""
out: dict[str, float] = {f"part:{p}": 0.0 for p in PART.values()}
out["lines:labor"] = 0.0
for x, item in zip(engine, items):
for name, value in (x.get("비목") or {}).items():
if name in PART:
out[f"part:{PART[name]}"] += _f(value) or 0
if item.get("종류") == "인력":
out["lines:labor"] += _f(x.get("금액")) or 0
if x.get("이름"):
out[f"line:{x['이름']}"] = _f(x.get("금액")) or 0
return out
def _base_of(formula: str) -> tuple[str | None, str]:
"""덧줄 식 → (밑수 갈래, 이름) — 모르는 꼴이면 (None, "")."""
if hit := BASE_PART.match(formula):
return f"part:{PART[hit.group(1)]}", hit.group(1)
if hit := BASE_LINE.match(formula):
return f"line:{hit.group(1)}", hit.group(1)
if BASE_LABOR.match(formula):
return "lines:labor", "인건비"
return None, ""
def _plain(value: Any) -> Any:
if isinstance(value, Decimal):
return float(value)
if isinstance(value, dict):
return {k: _plain(v) for k, v in value.items()}
if isinstance(value, list):
return [_plain(v) for v in value]
return value
def cover_count(project_root: str | Path, folder: str) -> int:
"""702-4 B08 구조물도 카드 — 그 사본 블록 + 부른 블록에 붙은 B09 고친 칸 수(카드 = 사본 셈)."""
from B09_Estimation.B09_Estimation_Store import read_user
cover = read_user(project_root).get("daega_cover") or {}
if not cover:
return 0
got = daega_inputs(
project_root
) # ponytail: 프로젝트 한 벌 셈 — 카드 열 때만 · 느리면 사본 하나로
by_id = {b["id"]: b for b in got["blocks"]}
owners = {linked["폴더"]: o for o, linked in linked_snapshots(project_root).items()}
todo, seen = [got["owners"].get(owners.get(folder, ""))], set()
while todo:
block = by_id.get(todo.pop())
if block is None or block["id"] in seen:
continue
seen.add(block["id"])
todo += [ln.get("key") for ln in block["lines"] if ln["kind"] == "daega"]
return sum(len(cover.get(by_id[bid]["cover"]) or {}) for bid in seen)
def daega_inputs(project_root: str | Path) -> dict[str, Any]:
"""대가 셈 입력 — `{blocks: [...], owners: {구조물 id: 블록 id}}` · 사본 없으면 빈 것 ·
설계내역서 서고 사본(204-2)이 있으면 `libs` {폴더: 블록 id}.
차례 = 조합(구조물 id 차례 → 서고 사본) → 사전조합 → 일위대가화(품셈 · 처음 본 차례) —
호표 번호 = 이 차례.
"""
base = structures_dir(project_root)
build = Builder()
owners: dict[str, str] = {}
for owner, linked in sorted(linked_snapshots(project_root).items()):
if "일위대가" not in linked.get("부분", []):
continue
try:
bid = build.combo(base / linked["폴더"])
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
bid = None # 한 사본이 막혀도 나머지 블록은 셈 — 그 구조물은 없음
if bid:
owners[owner] = bid
libs: dict[str, str] = {}
for folder, manifest in library.copies(project_root):
try:
bid = build.library(folder, manifest)
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
bid = None
if bid:
libs[folder.name] = bid
order = {"조합": 0, "사전조합": 1, "품셈": 2}
blocks = sorted(build.blocks.values(), key=lambda b: order[b["kind"]])
out = {"blocks": blocks, "owners": owners}
return _plain({**out, "libs": libs} if libs else out)