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>
This commit is contained in:
2026-11-18 03:24:52 +09:00
co-authored by Claude Opus 5.5
parent a1ecc1df3f
commit 11d348492e
14 changed files with 310 additions and 487 deletions
+98 -98
View File
@@ -40,10 +40,12 @@ 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,
@@ -184,64 +186,79 @@ class Builder:
"_items": items,
}
# ── 단가산출(SK · 719-2) ────────────────────────────────────────────
# ── 단가산출(SK · 719-2 · 855-F B9-5) ──────────────────────────────────
def sangeun(self, whole: Any, ref: dict, doc: dict, copies: dict, depth: int = 0) -> str | None:
"""굳힌 SK(사본 `단가.json` 로직 줄 · 719-1) = 품셈 블록 꼴 대가 — 셈 = 굳힌 줄 그대로 ·
단가산출 속 일위대가 · SK 줄(참조) = 그 대가 블록을 부르는 줄(펼침 · B09 차례 그대로) ·
고정 줄 = `fixed` · 단가 고친 줄(덮개 · 더한줄 단가 · 값묶음) = `fixed`(줄 단가 = M02 셈) ·
cover = `P:` + SK 이름표(SK 를 고쳐 [업데이트] 해도 B09 덮개 그대로) ·
속 일위대가 안 줄 수량 없음(723-4) = 엔진엔 0 값묶음 · 그 줄 = 사전조합 블록(이 공사 입력) ·
줄 `sk` · `poom`(M02 에서 고친 줄의 품셈 값 = 원본 덮개 `원값`)."""
from M02_MasterTemplete import M02_Item_Sangeun as item_sk
from M02_MasterTemplete import M02_Sangeun_Calc as calc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
"""사본 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)
key = str((doc.get("바탕") or {}).get("로직") or "")
if item_sk.ROW not in doc or not key:
return None # 못 푼 SK(없는 바탕 · 순환) — 부르는 줄이 까닭
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 read(r: dict) -> dict | None:
return copies.get(refs.ref_id(r))
try:
got = calc.resolve(doc, whole, read, (rid,))
row = {**got["줄"], "키": key, "호표": [dict(x) for x in got["줄"]["호표"]]}
if calc._bundles(row, whole, _Loose(whole, read), (rid,)):
return None
except (sd.DocError, mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
return None
one = {"로직": key, "입력값": got["입력값"], "켜쌓기율": got["켜쌓기율"],
"자재표시": got.get("자재표시")} # fmt: skip
where = {c: n for n, c in enumerate(got["정체"])} # 율 기준 줄 목록(778-4) → 블록 차례
block = self._poomsem(calc._Over(whole, key, row), {**one, "고름": got["고름"]})
if block is None:
return None
ids = list(doc.get("정체") or [])
was = {c: v.get("원값") for c, v in ((doc.get("원본") or {}).get("덮개") or {}).items()}
lines = []
for n, (line, x) in enumerate(zip(block["lines"], block.pop("_engine"))):
item = block["_items"][n] if n < len(block["_items"]) else {}
qty, keep = _f(x.get("수량")), {k: line[k] for k in rule.FLAGS if k in line}
head = {"name": line.get("name") or "", "spec": "", "unit": line.get("unit") or ""}
if isinstance(item.get("참조"), dict) and depth < refs.DEPTH:
line = {**self.line_of(whole, item, qty, 1, head["name"], copies, depth), **head}
elif isinstance(item.get("고정"), dict):
line = {**fixed_line(item["고정"], qty, where, whole), **head}
elif qty and ("단가" in item or item.get("값묶음")):
own = {PART[k]: _f(v) / qty for k, v in (x.get("비목") or {}).items() if k in PART}
line = {**head, "kind": "fixed", "qty": qty, "own": own, "link": {}}
poom = was.get(ids[n]) if n < len(ids) else None
lines.append({**line, **keep, "sk": True, **({"poom": poom} if poom else {})})
block.pop("_items")
name = doc.get("이름") or block["name"]
m02 = sk_money(doc, whole, _Loose(whole, read), rid) # 841-1 블록 합 = M02 SK 셈
block = {**block, **({"m02": m02} if m02 else {})}
origin = {**block["origin"], "단가산출": rid}
cover = f"P:{_digest({'단가산출': rid})}"
return self.put({**block, "name": name,
"cite": f"단가산출 {ref.get('키')}", "origin": origin,
"lines": lines}, cover) # fmt: skip
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
@@ -295,6 +312,8 @@ class Builder:
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))
@@ -305,16 +324,16 @@ class Builder:
"qty": each,
"why": f"없는 참조 「{ref.get('키')}」",
}
if refs.kind_of(ref.get("키")) == "sangeun": # 단가산출(719-2) = 굳힌 줄 대가
if refs.kind_of(ref.get("키")) == "sangeun": # 단가산출(719-2) = 수식 사본 대가
bid = self.sangeun(whole, ref, doc, copies, depth + 1)
if bid is None:
why = "단가산출을 못 셈(바탕 없음 · 순환)"
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, whole.logic(doc["바탕"]["로직"]), whole))
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"],
@@ -329,16 +348,6 @@ class Builder:
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
fz = one.get("굳힌")
if isinstance(fz, dict) and fz.get("키"): # 덮개 줄(740-1) = 굳힌 줄 단가산출 대가
bid = self.sangeun(
whole, {"층": "project", "키": fz["키"]}, _sk_of(one), copies, depth + 1
)
if bid is None:
return {"kind": "blank", "name": name, "qty": each, "why": "덮개 줄을 못 셈"}
block = self.blocks[bid] # 블록 = 결과단위(배) 몫 · 수량 = 수량 ÷ 배
return {"kind": "daega", "key": bid, "name": block["name"], "unit": block["unit"],
"qty": each} # fmt: skip
code = str(one.get("로직") or "")
if one.get("승격") is not True: # 단가산출 줄 = 산근
if not sg.is_money(whole, code):
@@ -490,36 +499,6 @@ class Builder:
return self.precombo(whole, ref, doc, copies, 1)
def _sk_of(one: dict) -> dict[str, Any]:
"""굳힌 덮개 줄(740-1) → 굳힌 SK 꼴(`Builder.sangeun` 이 읽음) — 고름 · 자재표시 = 굳힌 줄 cid ·
`원본.덮개` = 그 줄 패치 덮개(원값 = M02 에서 고친 줄의 품셈 값)."""
from M02_MasterTemplete import M02_Item_Sangeun as item_sk
from M02_MasterTemplete import M02_Sangeun_Doc as sd
fz = one["굳힌"]
ids = sd.line_ids(fz["줄"])
keyed = {
k: {ids[int(n)]: v for n, v in (fz.get(k) or {}).items() if int(n) < len(ids)}
for k in ("고름", "자재표시")
}
return {
"종류": "단가산출",
"키": fz["키"],
"이름": one.get("별칭") or fz["줄"].get("이름") or "",
"단위": "",
"바탕": {"로직": fz["키"]},
"입력값": fz.get("입력값") or {},
**({"켜쌓기율": fz["켜쌓기율"]} if fz.get("켜쌓기율") is not None else {}),
**keyed,
"덮개": {},
"더한줄": [],
"뺀줄": [],
item_sk.ROW: fz["줄"],
"원본": {"덮개": (one.get("패치") or {}).get("덮개") or {}},
"정체": list(fz.get("정체") or []),
}
def _Loose(whole: Any, read: Any) -> Any:
"""B09 SK 속 펼침(723-4) — 사전조합 안 줄 수량 없음 = 0 값묶음(엔진 차례 · 수량만 씀 ·
그 줄 값 = B09 사전조합 블록 · 이 공사에서 입력) · 그 밖 까닭은 그대로."""
@@ -535,6 +514,27 @@ def _Loose(whole: Any, read: Any) -> Any:
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) · 없으면(붙인 줄) 줄 단가 ·