From 11d348492ee58d8467b8739daeed71fe79309187 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 03:24:52 +0900 Subject: [PATCH] =?UTF-8?q?refactor(855-F=20B9-5):=20=EC=82=AC=EB=B3=B8=20?= =?UTF-8?q?=EB=8B=A8=EA=B0=80=EC=82=B0=EC=B6=9C=20=EA=B5=B3=ED=9E=98=20?= =?UTF-8?q?=EA=B1=B7=EC=9D=8C=20=E2=80=94=20=EA=B5=B3=ED=9E=8C=20=EB=A1=9C?= =?UTF-8?q?=EC=A7=81=20=EC=A4=84(GX9)=20=EB=8C=80=EC=8B=A0=20M02=20?= =?UTF-8?q?=EB=AC=B8=EC=84=9C=20+=20=EC=88=98=EC=8B=9D=20=EB=94=B0?= =?UTF-8?q?=EB=A1=9C=20=EC=82=AC=EB=B3=B8=20=C2=B7=20B09=20=EB=8C=80?= =?UTF-8?q?=EA=B0=80=EA=B0=80=20=EB=AC=B8=EC=84=9C=20=EC=85=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- B09_Estimation/B09_Estimation_Bill_Library.py | 6 +- B09_Estimation/B09_Estimation_Labor_Source.py | 196 +++++++++--------- B09_Estimation/B09_Estimation_Linked.py | 43 ++-- B09_Estimation/B09_Estimation_Refresh.py | 9 +- B09_Estimation/B09_Estimation_Supply.py | 2 +- M02_MasterTemplete/M02_Doc_B09.py | 4 +- M02_MasterTemplete/M02_Item_Sangeun.py | 183 ++++------------ M02_MasterTemplete/M02_Item_Source.py | 16 +- resources/tester/golden_855_b09.json | 4 +- resources/tester/test_719_1_sk_freeze.py | 111 ++++++---- resources/tester/test_719_2_sk_project.py | 163 +++------------ resources/tester/test_778_4_rate_line.py | 14 -- resources/tester/test_792_3_engine_paths.py | 33 ++- .../tester/test_793_2_sangeun_imported.py | 13 +- 14 files changed, 310 insertions(+), 487 deletions(-) diff --git a/B09_Estimation/B09_Estimation_Bill_Library.py b/B09_Estimation/B09_Estimation_Bill_Library.py index b9895c5a2..a37e44a3f 100644 --- a/B09_Estimation/B09_Estimation_Bill_Library.py +++ b/B09_Estimation/B09_Estimation_Bill_Library.py @@ -6,7 +6,7 @@ 도면 · 면적 · 일위대가 · 단가 · 입력값 · 고른자재 첫 값) precombo 사전조합 = `일위대가.json` {줄: {담은로직: [{참조, 수량: {손: 1}}]}, 참조사본} · `단가.json`(`M02_Item_Source.price_bundle` — 사본 단가 묶음 한 벌) - sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(참조사본 = 풀어 굳힌 SK) + sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(SK = 수식 사본 · B9-5) [업데이트](719-2) = 원본판이 다른 사본만 같은 폴더에 다시 굳힘(`changed` · `refresh_copy` · 값 그대로 · 원본판 없는 옛 사본 = 그대로). 사본 = 원본이 바뀌거나 지워져도 그대로(굳힘) · @@ -106,8 +106,8 @@ def _precombo_files(layer: str, owner: str | None, key: str, kind: str = "precom def source_version(files: dict[str, Any]) -> str: - """서고 사본 원본판(719-1) = 일위대가.json 지문 — 굳힌 SC · SK 문서 + 풀어 굳힌 SK 줄(바탕 - M01 줄 · 바탕판) · 단가는 뺌(단가 바뀜은 [업데이트] 단가 굳힘 몫) · 값 덮기 전에 셈.""" + """서고 사본 원본판(719-1) = 일위대가.json 지문 — 굳힌 SC · SK 문서(SK = 수식 사본) · + 단가는 뺌(단가 바뀜은 [업데이트] 단가 굳힘 몫) · 값 덮기 전에 셈.""" return version_of(files.get(LABOR_FILE)) diff --git a/B09_Estimation/B09_Estimation_Labor_Source.py b/B09_Estimation/B09_Estimation_Labor_Source.py index 99d4c6205..a1dfa349e 100644 --- a/B09_Estimation/B09_Estimation_Labor_Source.py +++ b/B09_Estimation/B09_Estimation_Labor_Source.py @@ -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) · 없으면(붙인 줄) 줄 단가 · diff --git a/B09_Estimation/B09_Estimation_Linked.py b/B09_Estimation/B09_Estimation_Linked.py index d813e6e21..755df9188 100644 --- a/B09_Estimation/B09_Estimation_Linked.py +++ b/B09_Estimation/B09_Estimation_Linked.py @@ -6,7 +6,7 @@ 855-F B9-3)만 모음 — 단가 묶음 통째 (고르기 후보 전부)는 안 씀 · 값은 쓰지 않음(단가는 원가 한 벌 `price_book.json` 이 맡음) · 사본 일위대가 자재 · 굳힌 사전조합 자재 코드 · 고정 줄 이음 키도(183-1 · 705-1 · 로직을 안 돌아 `get` 에 안 걸림). -굳힌 SK(719-2) = 굳힌 키 로직 줄로 돌림(사본 `단가.json` · M01 안 읽음). +사본 SK(719-2) = 그 수식 사본 문서 셈 기록의 자원 키(`sk_answer` · 855-F B9-5). 고르기가 훑은 후보 줄도 걸림 → 원가 길이 두 번 셈해 쓰는 줄만 남김(`Summary.used_materials`). 구조물 조합 사본 없으면 그 구조물은 없음 · 일위대가 없는 사본은 자원 없음. """ @@ -48,9 +48,8 @@ def used_keys(folder: Path) -> list[str]: # 굳힌 참조사본 안 로직까지 doc = item_prices.with_values(labor.get("줄") or {}, values, picks) inner = [d for d in (labor.get("참조사본") or {}).values() if isinstance(d, dict)] - sks = [_sk_line(d) for d in inner if d.get("종류") == "단가산출" and "굳힌줄" in d] lines = [*(doc.get("담은로직") or []), *(x for d in inner for x in d.get("담은로직") or [])] - for one in [*lines, *sks]: + for one in lines: # 못 돈 로직 — 부른 데까지만(까닭은 안 봄) if isinstance(one, dict) and one.get("로직"): got = dr.solve( @@ -64,28 +63,36 @@ def used_keys(folder: Path) -> list[str]: 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 고정 줄 이음 - codes += [ # 굳힌 SK 고정 더한줄 이음(719-2) - k - for d in inner - for x in (d.get("굳힌줄") or {}).get("호표") or [] - if isinstance(x.get("고정"), dict) - for k in fixed.link_keys({"담은로직": [{"고정": x["고정"]}]}) - ] + for d in inner: # 사본 SK = 수식 사본 셈 기록(855-F B9-5) + got = sk_answer(d) + codes += got.resources if got else [] for code in codes: if code[:2] in RESOURCE_TABLES and code not in seen: seen.append(code) return seen -def _sk_line(doc: dict[str, Any]) -> dict[str, Any]: - """굳힌 SK(719-1) → 로직 줄 꼴 — 굳힌 키(사본 `단가.json` 로직) · 고름 cid → 차례.""" - from M02_MasterTemplete.M02_Sangeun_Doc import line_ids +def sk_answer(doc: Any) -> Any: + """사본 단가산출(SK · 855-F B9-5) 문서 셈 답(`Doc_Run.Answer` · 셈 기록) — 그 수식 사본(따로 · + M02 SK 셈과 같은 길 `M02_Doc_Sk.run` · 값 사본 · 덮음) · 수식 사본 없음(형제 · 옛 칸) · + 못 셈 = None.""" + from M02_MasterTemplete import M02_Doc_Copy as dc + from M02_MasterTemplete import M02_Doc_Sk as dsk - chosen = doc.get("고름") or {} - ids = line_ids(doc["굳힌줄"]) - picks = {str(n): chosen[cid] for n, cid in enumerate(ids) if cid in chosen} - one = {"로직": (doc.get("바탕") or {}).get("로직"), "입력값": doc.get("입력값")} - return {**one, "켜쌓기율": doc.get("켜쌓기율"), "고름": picks or None} + if not isinstance(doc, dict) or doc.get("종류") != "단가산출": + return None + try: + copy = dsk.copy_of(doc) + if copy is None or not isinstance(copy.get("문서"), dict): + return None + docs, whole = dc.docs_of(copy), dc.over(copy) + if dsk.dim.is_imported(doc): # 가져온 식 = 단가기준 셈(엑셀 값 · 기록 없음 = 줄 단가) + ans = dsk.run(doc, copy, whole) + else: + ans = dr.mt.calc(copy["문서"], dr.mt.Trace(whole, docs), {}, dc.cover_of(copy)) + except Exception: # noqa: BLE001 — 계산기 틈 · 못 짓는 사본 = 못 셈 + return None + return dr.Answer(whole, copy["문서"], ans, docs, {}) def _folders(project_root: str | Path, keep: set[str] | None = None) -> list[Path]: diff --git a/B09_Estimation/B09_Estimation_Refresh.py b/B09_Estimation/B09_Estimation_Refresh.py index dae1f2b4d..85904206c 100644 --- a/B09_Estimation/B09_Estimation_Refresh.py +++ b/B09_Estimation/B09_Estimation_Refresh.py @@ -8,8 +8,9 @@ 재적용 · 새 판 뒤에도 남음) · 노임 판(굳힌 판 → 지금 M01 판 · 옛 책 = 굳힌 날) 적용(`reapply_changed` → 부르는 쪽이 수요 다시 → `prices.refresh_book`) — 사본 먼저(수요가 바뀜) · 덮개(사용자 값)는 안 건드림 · 사본 하나가 막혀도 나머지는 함(막힌 것 = 알림). -M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 굳힌 SK 를 원본 층에서 다시 풀어 굳힘(같은 굳힌 키 · - 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로) · 서고 사본도 원본판이 다르면 다시 굳힘 · +M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 SK 수식 사본을 원본 층에서 다시 굳힘(같은 이름표 · + 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로 · 855-F B9-5) · + 서고 사본도 원본판이 다르면 다시 · 미리 보기 `단가산출` = 바뀌는 SK 줄 [{사본, 이름, 키, 판(새 · 바뀜 · 빠짐)}]. """ @@ -90,12 +91,12 @@ def _sks(labor: Any) -> dict[str, dict]: def sk_lines(old: Any, new: Any, where: str) -> list[dict[str, str]]: - """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(굳힌 줄 · 원본 SK 문서가 다름).""" + """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(SK 문서 · 수식 사본이 다름).""" was, now = _sks(old), _sks(new) out = [] for rid in sorted(set(was) | set(now)): a, b = was.get(rid) or {}, now.get(rid) or {} - if all(a.get(k) == b.get(k) for k in (item_sk.ROW, "원본")): + if a == b: continue mark = "새" if not a else "빠짐" if not b else "바뀜" out.append({"사본": where, "이름": (b or a).get("이름") or "", "키": rid.rsplit("|")[-1], diff --git a/B09_Estimation/B09_Estimation_Supply.py b/B09_Estimation/B09_Estimation_Supply.py index 63f727217..0f6a305a3 100644 --- a/B09_Estimation/B09_Estimation_Supply.py +++ b/B09_Estimation/B09_Estimation_Supply.py @@ -83,7 +83,7 @@ def sk_money(doc: dict, whole: Any, expand: Any, rid: str) -> dict[str, float] | try: got = calc.unit(doc, whole, expand, (rid,)).get("기준") - per = float(calc.ratio_of(doc, whole.logic(doc["바탕"]["로직"]), whole)) + per = float(calc.ratio_of(doc, calc._row_of(doc, whole), whole)) # 바탕 없음 = 1 except Exception: # noqa: BLE001 — M02 셈이 못 돌면 줄 합(옛 길) 그대로 return None if not got: diff --git a/M02_MasterTemplete/M02_Doc_B09.py b/M02_MasterTemplete/M02_Doc_B09.py index 8ac08fc40..3143da594 100644 --- a/M02_MasterTemplete/M02_Doc_B09.py +++ b/M02_MasterTemplete/M02_Doc_B09.py @@ -1,11 +1,11 @@ """B09 사본(구조물 · 서고)의 수식 문서 사본 `수식.json`(PLAN 802-4a 2 · 브레인 802-4a ①) — 서버 단독. 사본을 만들 때(`M02_Item_Source.build_source`) 단가 묶음 `단가.json` 옆에 함께 굳힘 — - {그룹: 수식문서, 문서: {키: 문서}} = 그 묶음의 로직 줄(담은 로직 · 하위 로직 · 굳힌 단가산출 GX9)이 + {그룹: 수식문서, 문서: {키: 문서}} = 그 묶음의 로직 줄(담은 로직 · 하위 로직 · SK 바탕 로직)이 닿는 닫힌 묶음 · 원본 일위대가 문서의 수식 사본 부름이 먼저(만든 때 것) · 없으면 묶음 줄 = 지금 M01 줄이면 M01 문서 · 다르면 그 줄 변환(`M02_Doc_Copy.doc_of`). [단가 갱신](값만) = 이 파일 안 고침 · [재생성](재적용) = 새로 찍음. -B09 셈은 지금 풀이(`단가.json` · 단가 책) 그대로 — 산근을 문서 셈으로 바꾸는 것은 802-6. +단가산출(SK) 셈 문서 = 참조사본 SK `수식`(따로 사본 · 855-F B9-5) — 이 파일엔 없음. 원본판(`version_of`)에는 안 듦(로직 줄은 `단가.json` 이 이미 잼 · 옛 사본이 거짓 「원본 바뀜」 안 뜸). """ diff --git a/M02_MasterTemplete/M02_Item_Sangeun.py b/M02_MasterTemplete/M02_Item_Sangeun.py index 8b0ad87b2..10d8acd82 100644 --- a/M02_MasterTemplete/M02_Item_Sangeun.py +++ b/M02_MasterTemplete/M02_Item_Sangeun.py @@ -1,42 +1,21 @@ -"""프로젝트 사본 — M02 단가산출(SK) 풀어 굳힘(PLAN 719-1 · 요구서 내역12 원칙 3 · 4장 14). +"""프로젝트 사본 — M02 단가산출(SK) 수식 문서 사본(PLAN 855-F B9-5 · 719-1). -사본을 만들 때(구조물 사본 `M02_Item_Source.build_source` · B09 서고 사본 `Bill_Library`) 굳힌 -참조사본 안 SK 문서마다 고친 줄(`M02_Sangeun_Calc.resolve` = 바탕 사슬 + 덮개 · 더한줄 · 뺀줄)을 -풀어 사본 `단가.json` 로직 줄 하나로 굳힘 — 사본 SK 문서는 그 줄만 바탕으로 가리킴(덮개 0 · -연결 끊김). 셈은 그대로 `M02_Sangeun_Calc` 한 벌(사본 색인 = 사본 `단가.json`). - -굳힌 키 = SK 참조 이름표(`ref_id` = 층 · 주인 · 키)에서 정해지는 `GX9#####`(해시 · 겹치면 -이름표 차례로 다음 번호) — 같은 SK = 같은 굳힌 키([업데이트] 때 B09 덮개 cover · cid · 입력값 · -고른자재가 짝을 안 잃음). 원본 층 문서는 읽기만. -사본 SK 문서 = {종류 · 키 · 이름 · 단위 · 구분 · 상세구분, 바탕 {로직: 굳힌 키}, 입력값(사슬 합), -열린입력, 켜쌓기율, 고름 · 자재표시(굳힌 줄 cid), 덮개 {}, 더한줄 [], 뺀줄 [], -굳힌줄(= 단가.json 줄), 원본(원래 SK 문서 · 「M02 에서 고침」 근거), 정체(굳힌 줄 차례 → 원본 -cid · 더한줄 = `add:#k`), 바탕판, 짝잃음}. -단가산출 속 일위대가(SC) · SK 더한줄 = 참조 줄 그대로 → 사본 셈이 굳힌 참조사본으로 펼침. +사본을 만들 때(구조물 사본 `M02_Item_Source.build_source` · B09 서고 사본 `Bill_Library`) +참조사본 안 SK 문서마다 지금 M02 셈 사본(`M02_Doc_Sk.copy_of` — 파생 · 따로 · 가져온 식 · +위 층 덮음 반영)을 `수식` 칸에 「따로」 로 굳힘 — 사본 셈 = M02 SK 셈 한 벌(따로 = 굳힌 문서 +그대로 · 기초 M01 문서를 다시 안 지음) · 수식 사본을 못 짓는 SK(바탕 참조 형제 · 옛 칸 고침) = +그대로(M02 처럼 못 셈 + 까닭). 원본 층 문서는 읽기만 · 굳힌 로직 줄(옛 `GX9…`) 없음. """ from __future__ import annotations -import hashlib from typing import Any -from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_Sangeun_Doc as sd -#: 사본 `단가.json` 안 굳힌 SK 줄 파일(`master_formula.Master` 가 그룹 「로직」 으로 읽음) -FILE = "로직_단가산출.json" -ROW = "굳힌줄" -_IMPORTED = "가져온" # 가져온 식 머리(`M02_Sangeun_Imported.KEY`) -_HEAD, _LOW, _SPAN = "GX", 900000, 99999 # GX900000 ~ GX999998(999999 = M01 저장 전 초안) - - -def frozen_key(rid: str, taken: set[str]) -> str: - """SK 이름표 → 굳힌 로직 키 — 해시 자리 · 이미 쓴 키면 다음 번호(제자리 `taken` 에 더함).""" - at = int(hashlib.sha256(rid.encode("utf-8")).hexdigest(), 16) % _SPAN - while (key := f"{_HEAD}{_LOW + at:06d}") in taken: - at = (at + 1) % _SPAN - taken.add(key) - return key +#: 사본 표지 — 셈이 위덮음 · M01 따라옴을 안 바꿈(`Doc_Sk.upper` · `Sk_AutoRenew.form` 이 읽음) +LOCK = "굳힘" +_FOLLOW = ("원본", "처음", "덮음바탕") # M02 자동 따라옴 기록(`M02_Sk_AutoRenew` FIRST · BASE) def is_sangeun(doc: Any) -> bool: @@ -44,133 +23,41 @@ def is_sangeun(doc: Any) -> bool: def freeze(copies: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: - """참조사본 `{ref_id: 문서}` → SK 를 풀어 굳힌 참조사본(새 묶음 · 받은 것 안 고침) · - 못 푼 SK(없는 바탕 · 순환) = 그대로(사본 셈이 까닭을 냄).""" - from M01_MasterData import M01_MasterData_Store as m01 - from M02_MasterTemplete import M02_Item_Prices as prices - from M02_MasterTemplete import M02_Sangeun_Calc as calc + """참조사본 `{ref_id: 문서}` → SK 마다 `수식` = 굳힌 따로 사본(새 묶음 · 받은 것 안 고침) · + SK 없음 = 받은 묶음 그대로.""" + from M02_MasterTemplete import M02_Doc_Sk as dsk sks = sorted(rid for rid, doc in copies.items() if is_sangeun(doc)) - if not sks and not any(_patched(doc) for doc in copies.values()): + if not sks: return copies - whole = m01.loaded()[1] - - def read(ref: dict) -> dict | None: - return copies.get(refs.ref_id(ref)) - - out, taken = dict(copies), set() + out = dict(copies) for rid in sks: doc = copies[rid] try: - got = calc.resolve(doc, whole, read, (rid,)) - except sd.DocError: - continue - key = frozen_key(rid, taken) - row = prices.to_json({**got["줄"], "키": key}) - ids = sd.line_ids(row) - frozen = {k: doc.get(k) for k in ("종류", "키", "이름", "단위", "구분", "상세구분")} - frozen |= { - "바탕": {"로직": key}, - "입력값": prices.to_json(got["입력값"]), - "열린입력": list(doc.get("열린입력") or []), - "고름": {ids[int(n)]: mt for n, mt in got["고름"].items()}, - "자재표시": {ids[int(n)]: one for n, one in got["자재표시"].items()}, - "덮개": {}, - "더한줄": [], - "뺀줄": [], - ROW: row, - "원본": doc, - "정체": list(got["정체"]), # 굳힌 줄 차례 → 원본 cid(B09 덮개 · 내 자료집 · 719-2) - "바탕판": got["바탕판"], - "짝잃음": got["짝잃음"], - } - if got["켜쌓기율"] is not None: - frozen["켜쌓기율"] = prices.to_json(got["켜쌓기율"]) - if isinstance(doc.get("수식"), dict): # 841-1 수식 문서(기계덮음) — 사본 셈 = M02 - frozen["수식"] = _upper(doc) # 848-1 ① 위덮음 = 굳힐 때 기초 것 - # 848-7 가져온 식 수식 고침(저장 문서) = 사본도 가져온 식 셈(단가기준 · 가져온 값 층) - if doc.get(_IMPORTED) and doc["수식"].get("따로"): - frozen[_IMPORTED] = doc[_IMPORTED] - out[rid] = frozen - for rid in sorted(rid for rid, doc in copies.items() if _patched(doc)): - out[rid] = _freeze_lines(rid, copies[rid], whole, read, taken) + got = dsk.copy_of(doc) + except Exception: # noqa: BLE001 — 못 짓는 사본 = 그대로(사본 셈이 M02 처럼 까닭을 냄) + got = None + if got is not None: # 따로 · M01 원본 표지 · 따라옴 기록 뺌(사본 = 굳힘 · 새 값 = [재생성]) + got = {k: v for k, v in got.items() if k not in _FOLLOW} + out[rid] = {**doc, dsk.KEY: dsk.norm({**got, "따로": True, LOCK: True})} return out -def _upper(doc: dict) -> dict: - """SK `수식` — ① 위 층 덮음을 굳힐 때 기초 것으로(848-1 · 가져온 식 · 기초 문서 없음 = 저장본).""" +def bundle_keys(copies: dict[str, Any]) -> tuple[list[str], list[str], list[dict]]: + """SK 사본 셈이 사본 단가 묶음(`단가.json`)에서 읽는 것 `(로직 키, 자원 키, 줄)` — + 바탕 로직(배 · 728-2) · 수식 사본 부름 문서 키(기계 덮음 작업량 식 포함) · 값 사본 자원 줄 키 · + 가져온 식 줄(셈 = 단가기준 · 사본 묶음 색인).""" + from M02_MasterTemplete import M02_Doc_Import as dim - from M02_MasterTemplete import M02_Doc_Sk as dsk - return doc["수식"] if dim.is_imported(doc) else dsk.with_upper(doc, doc["수식"], keep=True) - - -def _patched(doc: Any) -> list[int]: - """일위대가(SC) 사본의 덮개 줄(로직 줄 + `패치` · 740-1 SK 넣기 꼴) 차례.""" - if not isinstance(doc, dict) or doc.get("종류") != refs.TITLE["precombo"]: - return [] - lines = doc.get("담은로직") or [] - return [ - n for n, x in enumerate(lines) if isinstance(x, dict) and x.get("로직") and x.get("패치") - ] - - -def _freeze_lines(rid: str, doc: dict, whole: Any, read: Any, taken: set[str]) -> dict: - """SC 사본 덮개 줄마다 고친 줄을 풀어 굳힘(740-1 · B09 대가 · 사본 셈이 덮개를 읽게) — - 줄은 그대로 두고 덧칸 `굳힌 {키, 줄, 입력값, 켜쌓기율, 고름, 자재표시, 정체}`(고름 · - 자재표시 = 굳힌 줄 차례) · 못 푼 줄 = 그대로(사본 셈이 옛 길).""" - from M02_MasterTemplete import M02_Item_Prices as prices - from M02_MasterTemplete import M02_Labor_Patch as patch - from M02_MasterTemplete import M02_Sangeun_Calc as calc - from M02_MasterTemplete.M02_Labor_Expand import Expand - - lines = list(doc.get("담은로직") or []) - for n in _patched(doc): - one = lines[n] - try: - doc_ = sd.clean(patch.as_doc(one, whole), None, whole) - got = calc.resolve(doc_, whole, read, (rid,), line=True) # 일위대가 기본 별도계상 - row = {**got["줄"], "호표": [dict(x) for x in got["줄"]["호표"]]} - calc._bundles(row, whole, Expand(whole, read), (rid,)) # 고정 더한줄 = 값묶음 - except sd.DocError: - continue - key = frozen_key(f"{rid}#{n}", taken) - fz = {"키": key, "줄": prices.to_json({**row, "키": key}), "정체": list(got["정체"])} - fz |= { - "입력값": prices.to_json(got["입력값"]), - "고름": got["고름"], - "자재표시": got["자재표시"], - } - if got["켜쌓기율"] is not None: - fz["켜쌓기율"] = prices.to_json(got["켜쌓기율"]) - lines[n] = {**one, FROZEN: fz} - return {**doc, "담은로직": lines} - - -FROZEN = "굳힌" - - -def rows(copies: dict[str, Any]) -> list[dict[str, Any]]: - """굳힌 SK 줄 + SC 덮개 줄 굳힌 줄(740-1) — 사본 `단가.json` `FILE` 에 넣음(이름표 차례).""" - out = [doc[ROW] for _, doc in sorted(copies.items()) if is_sangeun(doc) and ROW in doc] - for _, doc in sorted(copies.items()): - out += [ - x[FROZEN]["줄"] - for x in doc.get("담은로직") or [] - if isinstance(x, dict) and x.get(FROZEN) - ] - return out - - -def materials(copies: dict[str, Any]) -> list[str]: - """굳힌 SK 고른 자재 키 — 단가 묶음에 담음.""" - out = [ - str(mt) - for doc in copies.values() - if is_sangeun(doc) - for mt in (doc.get("고름") or {}).values() - ] + logic, res, rows = [], [], [] for doc in copies.values(): - lines = [x for x in doc.get("담은로직") or [] if isinstance(x, dict) and x.get(FROZEN)] - out += [str(mt) for x in lines for mt in (x[FROZEN].get("고름") or {}).values()] - return out + if not is_sangeun(doc): + continue + copy = doc.get("수식") if isinstance(doc.get("수식"), dict) else {} + logic += [str((doc.get("바탕") or {}).get("로직") or "")] + logic += [str(k) for k in (copy.get("부름") or {})] + res += [str(r.get("키")) for r in copy.get("단가") or [] if isinstance(r, dict)] + if dim.is_imported(doc) and isinstance((doc.get("가져온") or {}).get("로직"), dict): + rows.append(doc["가져온"]["로직"]) + return [k for k in dict.fromkeys(logic) if k], list(dict.fromkeys(res)), rows diff --git a/M02_MasterTemplete/M02_Item_Source.py b/M02_MasterTemplete/M02_Item_Source.py index 6ac0aa147..3e4dcf009 100644 --- a/M02_MasterTemplete/M02_Item_Source.py +++ b/M02_MasterTemplete/M02_Item_Source.py @@ -5,7 +5,7 @@ `일위대가.json` = 층 `labor/<열id>.json` 문서(39-1c · 없으면 옛 UA 조합 줄 · 규격 열 = summary_item `spec` 열 수량을 손으로 굳힘 · 704-4) + 담은 로직 줄(M01 시스템) + 알약(가져온 때 그대로) + - 참조사본(단가승격 · 사전조합을 값으로 굳힘 · 단가산출 SK = 풀어 굳힌 로직 줄 719-1) · + 참조사본(단가승격 · 사전조합을 값으로 굳힘 · 단가산출 SK = 수식 문서 사본 따로 · 855-F B9-5) · `단가.json` 계산에 닿는 마스터 줄 전부(담은 로직 + 일위대가 자재 MT) `원본판` = 모은 내용의 해시 — 지금 층 · 마스터에서 다시 모은 판과 대어 「마스터가 바뀜」 을 앎. 프로젝트가 고치는 값(`입력값.json` · `고른자재.json`)은 원본이 아니라 여기서 안 모음. @@ -98,7 +98,7 @@ def labor_doc_rows(doc: dict[str, Any]) -> dict[str, Any]: from M02_MasterTemplete import M02_Labor_Ref as refs rows = {**logic_rows(doc), "알약": labor_doc.pills(doc)} - copies = sk.freeze(refs.frozen(doc)) # 단가산출(SK) = 풀어 굳힌 로직 줄(719-1) + copies = sk.freeze(refs.frozen(doc)) # 단가산출(SK) = 수식 문서 사본(855-F B9-5) return {**rows, "참조사본": copies} if copies else rows @@ -160,17 +160,19 @@ def build_source(item: dict[str, Any]) -> dict[str, Any]: def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: - """사본 단가 묶음(`단가.json`) — 담은 로직 · 굳힌 참조 로직 · 자재 · 고른 자재 · 사전조합 자재 · - 개인 자재(`root` = 원본 층 · B09 설계내역서 서고 사본도 이 길 · 204-2).""" + """사본 단가 묶음(`단가.json`) — 담은 로직 · 굳힌 참조 로직 · SK 바탕 로직 · 자재 · 고른 자재 · + 사전조합 자재 · 개인 자재(`root` = 원본 층 · B09 설계내역서 서고 사본도 이 길 · 204-2) · + SK 셈 = 그 수식 사본(굳힌 SK 로직 줄 없음 · 855-F B9-5).""" from M02_MasterTemplete import M02_Item_Prices as prices from M02_MasterTemplete import M02_Item_Sangeun as sk from M02_MasterTemplete import M02_Labor_Fixed as fixed from M02_MasterTemplete import M02_Labor_Ref as refs copies = (labor or {}).get("참조사본") or {} - sk_rows = sk.rows(copies) # 굳힌 단가산출 줄(719-1) — 그 줄이 닿는 마스터 줄도 모음 logic_keys = [str(one.get("키")) for one in (labor or {}).get("로직", [])] logic_keys += refs.frozen_logics(copies) # 굳힌 단가승격 로직 + sk_logic, sk_res, sk_rows = sk.bundle_keys(copies) # SK 수식 사본 셈이 읽는 줄(855-F B9-5) + logic_keys += sk_logic doc = (labor or {}).get("줄") or {} materials = [str(m.get("코드")) for m in doc.get("자재") or []] materials += [ # 고른 로직 자재(103-1) 품목 줄도 — 복사본 계산이 그 단가를 씀 @@ -178,7 +180,7 @@ def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: ] materials += refs.frozen_materials((labor or {}).get("참조사본") or {}) # 175-2 사전조합 자재 materials += fixed.link_keys(doc) # 705-1 고정 줄이 잇는 노임 · 자재 · 기계 - materials += sk.materials(copies) + materials += sk_res wanted = logic_keys + [code for code in materials if code] over = copy_rows([doc, *copies.values()]) # M02 로직 사본(795-4) = 만든 때 줄 먼저 bundle = ( @@ -186,8 +188,6 @@ def price_bundle(labor: dict[str, Any] | None, root: Path) -> dict[str, Any]: if wanted or sk_rows else {} ) - if sk_rows: - bundle[sk.FILE] = {"그룹": "로직", "원문": "자체", "줄": sk_rows} if mine := own.bundle( [c for c in materials if own.is_own(c)], root ): # 개인 자재(148-3 · 사전조합 것도 175-2) — 원본 목록이 바뀌어도 사본 그대로 diff --git a/resources/tester/golden_855_b09.json b/resources/tester/golden_855_b09.json index 36d1c81f4..41a824a0b 100644 --- a/resources/tester/golden_855_b09.json +++ b/resources/tester/golden_855_b09.json @@ -3,8 +3,8 @@ "지문": { "키": "e68369418202e5ee", "calc_user": "6d74551273d6735f", - "daega_inputs": "a06884bce408c602", - "수요": "5fdf7c49052e322c", + "daega_inputs": "f9269299e609306d", + "수요": "23b0132a8a7f46f7", "산근 값": "38455c2edce885ff", "산근 글": "c41b0c2e4ae200fb", "산근 관급 값": "d154925ee64c985c", diff --git a/resources/tester/test_719_1_sk_freeze.py b/resources/tester/test_719_1_sk_freeze.py index fd82867e7..913efac26 100644 --- a/resources/tester/test_719_1_sk_freeze.py +++ b/resources/tester/test_719_1_sk_freeze.py @@ -1,18 +1,22 @@ -"""719-1 프로젝트 사본 — M02 단가산출(SK) 풀어 굳힘(`M02_Item_Sangeun` · `M02_Item_Source` · -`M02_Item_Prices` · `B09_Estimation_Bill_Library`) — 임시 storage(견본 층 · 실제 M01 읽기만). +"""719-1 · 855-F B9-5 프로젝트 사본 — M02 단가산출(SK) 수식 문서 사본(`M02_Item_Sangeun` · +`M02_Item_Source` · `M02_Item_Prices` · `B09_Estimation_Bill_Library`) — 임시 storage(견본 층 · +실제 M01 읽기만). -구조물 사본 · B09 서고 사본 셈 = M02 층 SK 셈 · 굳힌 줄은 사본 `단가.json` 로직 줄 · 원본 SK 를 -지워도 같은 값 · 같은 SK = 같은 굳힌 키(다시 복사 · SK 고친 뒤도) · 원본 층 지문 그대로 · -서고 manifest 원본판 = SK 바뀌면 다름. +사본 SK = 원래 SK 문서 + `수식` 따로 사본(덮음 · 고친 문서 반영) · 굳힌 로직 줄(옛 GX9 · +`로직_단가산출.json`) 없음 · 구조물 사본 · B09 서고 사본 셈 = M02 층 SK 셈 · 원본 SK 를 지우거나 +M02 에서 고쳐도 사본 값 그대로([재생성] = 새 값) · 원본 층 지문 그대로 · 서고 원본판 = 다시 모아도 +같음 · SK 고치면 다름 · 수식 사본을 못 짓는 SK(옛 칸) = 그대로(M02 처럼 못 셈). """ # ruff: noqa: F811 — 임시 층 fixture `world` 를 들여 씀 +import copy import hashlib import json import pytest from B09_Estimation import B09_Estimation_Bill_Library as library +from M02_MasterTemplete import M02_Doc_Sk_Path as sk_path from M02_MasterTemplete import M02_Item_Prices as prices from M02_MasterTemplete import M02_Item_Sangeun as sk from M02_MasterTemplete import M02_Item_Source as source @@ -22,9 +26,6 @@ from M02_MasterTemplete import M02_MasterTemplete_Store as store from resources.tester.test_715_sangeun_store import PCT, _sk from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층 -COVER = {"labor:LB000036#0": {"qty": 0.5}} -ADD = [{"종류": "인력", "요소": "LB000002", "수량": 0.1}] - def _print(folder): """층 폴더 지문 — 파일 이름 · 바이트.""" @@ -40,12 +41,33 @@ def _top(ref, qty=2): return doc, labor.calc(doc, {})["줄"][0] +def edit(folder, key, times=2): + """M02 수식 길에서 SK 문서를 고침(따로) — 첫 금액 줄 수량 × times.""" + with store.at(folder): + read = sk_path.read(key) + doc = copy.deepcopy(read["문서"]) + doc["금액"][0]["수량"] = f"({doc['금액'][0].get('수량') or 1}) × {times}" + sk_path.save(key, {"문서": doc, "판": read["판"]}) + + def _mine(world): - key = _sk(world["personal"], 바탕={"로직": PCT}, 덮개=COVER, 더한줄=ADD) + """SK = 바탕 로직 + M02 에서 고친 문서(따로).""" + key = _sk(world["personal"], 바탕={"로직": PCT}) + edit(world["personal"], key) return key, {"folder": world["personal"], "ref": {**MINE, "키": key}} -def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): +def _rows(bundle): + return [ + row + for part in bundle.values() + if isinstance(part, dict) + for row in part.get("줄") or part.get("표") or [] + if isinstance(row, dict) + ] + + +def test_구조물_사본_수식_사본_값_같음_원본_지우고_고쳐도(world): key, ref = _mine(world) doc, live = _top(ref) assert not live["까닭"] and live["기준"]["계"] > 0 @@ -53,16 +75,20 @@ def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): rows = source.labor_doc_rows(doc) bundle = source.price_bundle(rows, world["personal"]) assert _print(world["personal"]) == before # 원본 층 안 건드림 - rid = refs.ref_id(ref["ref"]) - frozen = rows["참조사본"][rid] - fk = frozen["바탕"]["로직"] - assert fk == sk.frozen_key(rid, set()) and fk.startswith("GX9") - assert frozen["덮개"] == {} and frozen["더한줄"] == [] and frozen["뺀줄"] == [] - assert frozen["원본"]["덮개"]["labor:LB000036#0"]["qty"] == 0.5 # 고친 근거 - assert [r["키"] for r in bundle[sk.FILE]["줄"]] == [fk] + frozen = rows["참조사본"][refs.ref_id(ref["ref"])] + assert ( + frozen["바탕"] == {"로직": PCT} + and frozen["수식"]["따로"] is True + and frozen["수식"][sk.LOCK] + ) + assert "굳힌줄" not in frozen and "원본" not in frozen + assert "로직_단가산출.json" not in bundle + assert not [r for r in _rows(bundle) if str(r.get("키")).startswith("GX9")] json.dumps(rows["참조사본"], ensure_ascii=False) # 사본 파일로 쓸 수 있는 꼴(Decimal 없음) + saved = json.loads(json.dumps(bundle, ensure_ascii=False)) + edit(world["personal"], key, 3) # M02 에서 다시 고침 → 사본 그대로 (world["personal"] / "sangeun" / f"{key}.json").unlink() # 원본이 사라져도 사본만 봄 - got = prices.calc(rows, json.loads(json.dumps(bundle, ensure_ascii=False)), {}, {}, None) + got = prices.calc(rows, saved, {}, {}, None) line = got["줄"][0] assert not line["까닭"] for part in ("노무비", "재료비", "경비", "계"): @@ -70,30 +96,28 @@ def test_구조물_사본_굳힌_줄_값_같음_원본_지워도(world): assert line["반영"]["계"] == pytest.approx(live["반영"]["계"], rel=1e-9) -def test_같은_SK_같은_굳힌_키_다른_SK_다른_키(world): +def test_재생성은_M02_새_값(world): key, ref = _mine(world) doc, _ = _top(ref) + first = source.labor_doc_rows(doc) + edit(world["personal"], key, 3) + _, live = _top(ref) + again = source.labor_doc_rows(doc) + bundle = source.price_bundle(again, world["personal"]) + got = prices.calc(again, json.loads(json.dumps(bundle, ensure_ascii=False)), {}, {}, None) + assert got["줄"][0]["기준"]["계"] == pytest.approx(live["기준"]["계"], rel=1e-9) rid = refs.ref_id(ref["ref"]) - first = source.labor_doc_rows(doc)["참조사본"][rid]["바탕"]["로직"] - with store.at(world["personal"]): # SK 를 고쳐도 굳힌 키 그대로(B09 덮개 짝 지킴) - now = store.read("sangeun", key) - store.write("sangeun", key, now["판"], {**now["문서"], "덮개": {}}) - again = source.labor_doc_rows(doc)["참조사본"][rid] - assert again["바탕"]["로직"] == first and again["원본"]["덮개"] == {} - other = refs.ref_id({"층": "company", "주인": "7", "키": key}) # 같은 번호 다른 층 - assert sk.frozen_key(other, set()) != first - taken = {first} - assert sk.frozen_key(rid, taken) != first and len(taken) == 2 # 겹치면 다음 번호 + assert first["참조사본"][rid]["수식"]["문서"] != again["참조사본"][rid]["수식"]["문서"] def test_B09_서고_사본_값_같음_원본판(world, tmp_path): - _, ref = _mine(world) + key, ref = _mine(world) with store.at(world["personal"]): sc = refs.create( "precombo", {"이름": "조합", "단위": "㎡", "담은로직": [{"참조": ref["ref"], "수량": {"손": 2}}]}, )["이름"] - # 742-1 = SC 안 줄 수량(손 2) 저장 → 굳힌 사본 = 저장 2 · 쓰는 쪽 알약 값(2)이 앞섬(층 · 사본 같은 값) + # 742-1 = SC 안 줄 수량(손 2) 저장 → 사본 = 저장 2 · 쓰는 쪽 알약 값(2)이 앞섬(층 · 사본 같은 값) pill = f"{refs.ref_id({**MINE, '키': sc})}#0" with store.at(world["personal"]): top = labor.clean( @@ -119,15 +143,28 @@ def test_B09_서고_사본_값_같음_원본판(world, tmp_path): assert library.source_version(built) == mark # 다시 모아도 같은 판 again = library.import_copy(root, "precombo", "personal", "7/42", sc) assert again == {"폴더": made["폴더"], "만듦": False} - with store.at( - world["personal"] - ): # 811-1 — SC 안 SK = 참조 한 행(안 펼침) → SK 고치면 원본판 바뀜 = 사본 [업데이트] 대상 - now = store.read("sangeun", ref["ref"]["키"]) - store.write("sangeun", ref["ref"]["키"], now["판"], {**now["문서"], "덮개": {}}) + edit( + world["personal"], key, 3 + ) # 811-1 SC 안 SK = 참조 한 행 → SK 고치면 원본판 바뀜 = [재생성] 대상 assert library.source_version(library._build("precombo", "personal", "7/42", sc)[0]) != mark def test_SK_없는_사본_그대로(): """SK 없는 참조사본 = 받은 묶음 그대로(기존 사본 · 공사 금액 전후 같음).""" copies = {"x": {"종류": "사전조합", "담은로직": []}} - assert sk.freeze(copies) is copies and sk.rows(copies) == [] and sk.materials(copies) == [] + assert sk.freeze(copies) is copies and sk.bundle_keys(copies) == ([], [], []) + + +def test_옛_칸_SK_는_그대로_못_셈(world): + """수식 사본을 못 짓는 SK(옛 칸 덮개 · 855 2-C1) = 그대로 · 사본 셈 = M02 처럼 까닭.""" + key = _sk(world["personal"], 바탕={"로직": PCT}, 덮개={"labor:LB000036#0": {"qty": 0.5}}) + ref = {"folder": world["personal"], "ref": {**MINE, "키": key}} + doc, live = _top(ref) + rows = source.labor_doc_rows(doc) + frozen = rows["참조사본"][refs.ref_id(ref["ref"])] + assert not (frozen.get("수식") or {}).get("따로") + bundle = json.loads( + json.dumps(source.price_bundle(rows, world["personal"]), ensure_ascii=False) + ) + got = prices.calc(rows, bundle, {}, {}, None)["줄"][0] + assert live["까닭"] and got["까닭"] and got["기준"] is None diff --git a/resources/tester/test_719_2_sk_project.py b/resources/tester/test_719_2_sk_project.py index 5593213fb..4d304fe6d 100644 --- a/resources/tester/test_719_2_sk_project.py +++ b/resources/tester/test_719_2_sk_project.py @@ -1,12 +1,12 @@ -"""719-2 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · 산근 · [업데이트] · 내 자료집 SK(임시 storage · -실제 M01 읽기만). +"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · [재생성](업데이트) · 서고(임시 +storage · 실제 M01 읽기만). -- 굳힌 SK = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 금액 = M02 SK 셈 · 단가산출 속 일위대가 줄 = - 사전조합 블록을 부르는 줄 · 로직 더한줄의 하위 로직 = 산근 목록(`Sangeun.rows_of`) -- [업데이트] = SK 고친 뒤 다시 굳힘 — 굳힌 키 · cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · - 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 · - 미리 보기 SK 줄 -- 내 자료집 = SK 블록 · 품셈 블록 → 개인 층 SK(B09 덮개 = SK 덮개) → 서고로 다시 불러와 같은 금액 +- 사본 SK(수식 따로 사본) = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 줄 = 문서 답 금액 줄 + (M02 에서 고친 문서 그대로) · 금액 = M02 SK 셈 +- [재생성] = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · + 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 + · 미리 보기 SK 줄 +(옛 칸 덮개 · 더한줄 SK · 내 자료집 = 옛 칸 SK 만들기는 855 2-C1 셈 은퇴 — 시험 없음) """ # ruff: noqa: F811 — 임시 층 fixture `world` 를 들여 씀 @@ -15,7 +15,6 @@ import json import pytest from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Daega_Personal as personal from B09_Estimation import B09_Estimation_Prices as prices from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun @@ -28,13 +27,12 @@ from M02_MasterTemplete import M02_Item_Snapshot as snapshots from M02_MasterTemplete import M02_Item_Source as source from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_MasterTemplete_Store as store -from resources.tester.test_145_2_b09_labor_calc import STONE, _item, _project, _snap +from resources.tester.test_145_2_b09_labor_calc import STONE, _item, _project from resources.tester.test_715_sangeun_store import PCT, _calc, _sk +from resources.tester.test_719_1_sk_freeze import edit from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층 TWO_MATS = "GC000565" # 재료 줄 둘(고른자재 열쇠) -COVER = {"labor:LB000036#0": {"qty": 0.5}} -PRICE = {"labor:LB000002#0": {"labor": 200000}} OWNER = "7/42" @@ -42,33 +40,11 @@ def _json(value): return json.loads(json.dumps(value, ensure_ascii=False, default=str)) -def _sc(world, lines): - with store.at(world["personal"]): - doc = {"이름": "속 일위대가", "단위": "㎡", "담은로직": lines} - return refs.create("precombo", doc)["이름"] - - -def _mine(world, full=False): - """SK = 품 덮개 · 인력 더한줄 · 로직 더한줄(하위 산근) · full = 단가 덮개 + SC 더한줄.""" - added = [ - {"종류": "인력", "요소": "LB000002", "수량": 0.1}, - {"종류": "로직", "로직": PCT, "입력값": {}, "수량": 0.5}, - ] - cover = COVER - if full: - sc = _sc(world, [{"로직": PCT, "수량": {"손": 1}}]) - added.append({"참조": {**MINE, "키": sc}, "수량": 2}) # 단가산출 속 일위대가 - cover = {**COVER, **PRICE} - return _sk(world["personal"], 바탕={"로직": PCT}, 덮개=cover, 더한줄=added) - - -def _engine_ready(world): - """엔진 입력 덧칸(715-1b `단가` · `값묶음`)이 붙었나 — 아니면 M02 도 못 셈.""" - key = _sk( - world["personal"], 이름="엔진", 바탕={"로직": PCT}, 덮개={"labor:LB000002#0": {"labor": 1}} - ) - got = _calc(world["personal"], key) - return not got.get("까닭") and got["줄"][1]["단가"] == 1 +def _mine(world): + """SK = 바탕 로직 + M02 에서 고친 문서(따로 · 첫 줄 수량 × 2).""" + key = _sk(world["personal"], 바탕={"로직": PCT}) + edit(world["personal"], key) + return key def _b09(root, cover=None): @@ -88,62 +64,29 @@ def _lib(world, tmp_path, key, kind="sangeun"): return root, made["폴더"] -def _set_cover(world, key, cover): - with store.at(world["personal"]): - now = store.read("sangeun", key) - store.write("sangeun", key, now["판"], {**now["문서"], "덮개": cover}) - - def _same_money(block, live): assert block["sum"] == pytest.approx(float(live["1단위"]["계"]), abs=5) # 끝수(내림)만 다름 for part, name in (("labor", "노무비"), ("material", "재료비"), ("expense", "경비")): assert block[part] == pytest.approx(float(live["1단위"][name]), abs=3) -def test_SK_대가_블록_금액_M02_같음_하위_산근(world, tmp_path): +def test_SK_대가_블록_금액_M02_같음(world, tmp_path): key = _mine(world) live = _calc(world["personal"], key) assert not live.get("까닭") and live["1단위"]["계"] > 0 root, folder = _lib(world, tmp_path, key) - daega, done, sg_rows = _b09(root) + daega, done, _ = _b09(root) block = done[daega["libs"][folder]] assert block["cover"].startswith("P:") and block["kind"] == "품셈" lines = block["lines"] assert all(ln.get("sk") for ln in lines) - assert lines[0]["kind"] == "labor" and lines[0]["qty"] == 0.5 - assert lines[0]["poom"] == {"qty": 0.018, "단가": 233250} # M02 에서 고친 줄 = 품셈 값 곁 - assert "poom" not in lines[1] - sub = next(ln for ln in lines if ln["kind"] == "sangeun") - assert sub["key"] in sg_rows and sub["key"].startswith(f"SG:{PCT}") and sub["qty"] == 0.5 + assert lines[0]["kind"] == "labor" and lines[0]["key"] == "LB000036" + assert lines[0]["qty"] == pytest.approx(0.036) # M02 에서 고친 문서 = 품셈 0.018 × 2 + assert lines[-1]["kind"] == "pct" and lines[-1]["base"] == "part:labor" _same_money(block, live) -def test_SK_단가_덮개_속_일위대가_펼침(world, tmp_path): - # 715-1b 엔진 입력 덧칸(단가 · 값묶음) — 못 세면 건너뛰지 않고 실패 - assert _engine_ready(world), "M02 SK 셈이 단가 덮개를 못 셈(715-1b 엔진 입력 덧칸)" - key = _mine(world, full=True) - # 740-1 — 속 일위대가 = 넣을 때 펼쳐 담음(SC 로직 줄 = 로직 더한줄 · 본뜬) → 빠진 줄 없음 - live = _calc(world["personal"], key) - added = _added(world, key) - assert live["빠진줄"] == [] and not any("참조" in x for x in added) - assert added[-1]["로직"] == PCT and added[-1]["본뜬"]["키"].startswith("SC-") - root, folder = _lib(world, tmp_path, key) - daega, done, _ = _b09(root) - block = done[daega["libs"][folder]] - lines = block["lines"] - assert lines[1]["kind"] == "fixed" and lines[1]["prices"]["labor"] == pytest.approx(200000) - assert block["blank"] == 0 - _same_money(block, live) - - -def _added(world, key): - with store.at(world["personal"]): - return store.read("sangeun", key)["문서"]["더한줄"] - - -def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳힌키_그대로( - world, tmp_path, monkeypatch -): +def test_구조물_사본_SK_줄_재생성_덮개_입력값_고른자재_그대로(world, tmp_path, monkeypatch): key = _mine(world) ref = {**MINE, "키": key} with store.at(world["personal"]): @@ -184,18 +127,17 @@ def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳 }.items(): (folder / name).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") rid = refs.ref_id(ref) - frozen_key = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] - frozen_key = frozen_key["바탕"]["로직"] + was = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] daega, _, _ = _b09(root) combo = next(b for b in daega["blocks"] if b["id"] == daega["owners"]["pipe@100.0"]) sk_block = next(b for b in daega["blocks"] if b["id"] == combo["lines"][0]["key"]) cid = sk_block["lines"][0]["cid"] cover = {sk_block["cover"]: {cid: {"qty": 0.9}}} - # SK 고침(품 0.5 → 0.7) → [재적용](업데이트) = 다시 풀어 굳힘 - _set_cover(world, key, {**COVER, "labor:LB000036#0": {"qty": 0.7}}) + # SK 고침(품 × 2 → × 2 × 3) → [재적용](재생성) = 수식 사본 다시 굳힘 + edit(world["personal"], key, 3) item_copy.reapply(root, folder.name) after = json.loads((folder / source.LABOR_FILE).read_text("utf-8"))["참조사본"][rid] - assert after["바탕"]["로직"] == frozen_key # 굳힌 키 그대로 + assert after["수식"]["문서"] != was["수식"]["문서"] and after["수식"]["따로"] assert ( json.loads((folder / snapshots.VALUES_FILE).read_text("utf-8"))["GF000219"] == (values["GF000219"]) @@ -205,7 +147,7 @@ def test_구조물_사본_SK_줄_업데이트_덮개_입력값_고른자재_굳 block = next(b for b in done.values() if b["cover"] == sk_block["cover"]) line = block["lines"][0] assert line["cid"] == cid and line["covered"] == ["qty"] and line["qty"] == 0.9 - assert line["base"]["qty"] == 0.7 # 덮개 밑 = 새 단가산출 값(「단가산출 값으로」 되돌림 값) + assert line["base"]["qty"] == pytest.approx(0.108) # 덮개 밑 = 새 단가산출 값(0.018 × 6) assert daega2["owners"]["pipe@100.0"] in done @@ -215,7 +157,7 @@ def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): assert library.changed(root) == [] before = daega_inputs(root) cover_key = next(b for b in before["blocks"] if b["id"] == before["libs"][folder])["cover"] - _set_cover(world, key, {**COVER, "labor:LB000036#0": {"qty": 0.7}}) + edit(world["personal"], key, 3) got = refresh.preview(root, None, [], None) assert [(x["키"], x["판"]) for x in got["단가산출"]] == [(key, "바뀜")] assert [c["폴더"] for c in got["사본"]] == [folder] @@ -223,53 +165,4 @@ def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): assert library.changed(root) == [] and [f.name for f, _ in library.copies(root)] == [folder] after = daega_inputs(root) block = next(b for b in after["blocks"] if b["id"] == after["libs"][folder]) - assert block["cover"] == cover_key and block["lines"][0]["qty"] == 0.7 - - -def test_내_자료집_SK_왕복_같은_금액(world, tmp_path): - key = _mine(world) - root, folder = _lib(world, tmp_path, key) - daega, _, _ = _b09(root) - block = next(b for b in daega["blocks"] if b["id"] == daega["libs"][folder]) - first, second = block["lines"][0]["cid"], block["lines"][1]["cid"] - priced = {block["cover"]: {first: {"qty": 0.9}, second: {"labor": 210000}}} - made = personal.build(root, block["cover"], priced, "내 SK 2") - doc = made["문서"] - assert doc["종류"] == "단가산출" and doc["바탕"] == {"로직": PCT} - assert doc["덮개"]["labor:LB000036#0"] == {"qty": 0.9} - assert "labor:LB000002#0" not in doc["덮개"] # 841-1 단가 칸 = 안 읽음 · 안 담음 - assert doc["더한줄"][0]["요소"] == "LB000002" - assert made["담음"]["품"] == 1 and made["담음"]["단가"] == 0 - third = block["lines"][2]["cid"] # 더한줄 인력 = 그 더한줄 수량 - cover = {block["cover"]: {first: {"qty": 0.9}, third: {"qty": 0.3}}} - doc = personal.build(root, block["cover"], cover, "내 SK 2")["문서"] - assert doc["더한줄"][0]["수량"] == 0.3 and doc["덮개"] == {"labor:LB000036#0": {"qty": 0.9}} - _, done, _ = _b09(root, cover) - want = done[daega["libs"][folder]]["sum"] - with store.at(world["personal"]): - new = personal.write(doc)["이름"] - with pytest.raises(store.StoreError) as same: - personal.write(doc) - assert same.value.status == 409 and same.value.detail["같은이름"] == new - assert new.startswith("SK-") and new != key - root2, folder2 = _lib(world, tmp_path / "b", new) - daega2, done2, _ = _b09(root2) - assert done2[daega2["libs"][folder2]]["sum"] == pytest.approx(want, abs=2) - - -def test_내_자료집_품셈_블록_SK(world, tmp_path): - root = _project(tmp_path / "proj", [(100, "SS000901")]) - _snap(root, "pipe@100.0", "SS000901", [{"로직": PCT, "승격": True, "수량": {"손": 1}}], {}) - daega = daega_inputs(root) - top = next(b for b in daega["blocks"] if b["id"] == daega["owners"]["pipe@100.0"]) - block = next(b for b in daega["blocks"] if b["id"] == top["lines"][0]["key"]) - assert block["kind"] == "품셈" and block["origin"]["로직"] == PCT - cover = {block["cover"]: {block["lines"][0]["cid"]: {"qty": 0.5}}} - doc = personal.build(root, block["cover"], cover, "내 해체")["문서"] - assert doc["바탕"] == {"로직": PCT} and doc["단위"] == "㎡" - assert doc["덮개"] == {"labor:LB000036#0": {"qty": 0.5}} - with store.at(world["personal"]): - new = personal.write(doc)["이름"] - plain = _sk(world["personal"], 이름="견줌", 바탕={"로직": PCT}, 덮개=doc["덮개"]) - a, b = _calc(world["personal"], new), _calc(world["personal"], plain) - assert a["1단위"]["계"] == b["1단위"]["계"] > 0 + assert block["cover"] == cover_key and block["lines"][0]["qty"] == pytest.approx(0.108) diff --git a/resources/tester/test_778_4_rate_line.py b/resources/tester/test_778_4_rate_line.py index 0d8345aa3..6aa681008 100644 --- a/resources/tester/test_778_4_rate_line.py +++ b/resources/tester/test_778_4_rate_line.py @@ -185,20 +185,6 @@ def test_B09_율_기준_밑수_꼴(): assert source.fixed_line(rate, 2, {"y": 4, "x": 1})["base"] == "rows:1,4@labor" -def test_B09_SK_블록_율_줄_pct(): - whole = _whole() - adds = [{"종류": "인력", "요소": "LB000003", "수량": 0.1}, _rate("인력")] - adds.append(_rate(["labor:LB000002#0", "add:#1"], 5, "재료비", "목록")) - doc = sd.clean({**_doc(adds), "바탕": {"로직": SUB}, "단위": "주"}, None, whole) - build = source.Builder() - bid = build.sangeun(whole, {"층": "project", "키": "SK-000001"}, {**doc, "굳힌줄": {}}, {}) - lines = build.blocks[bid]["lines"] - pct = {ln["name"]: ln for ln in lines if ln["kind"] == "pct"} - assert pct["공구손료"]["base"] == "bundle:labor" and pct["공구손료"]["qty"] == 2 - assert pct["목록"]["base"] == "rows:1,4" and pct["목록"]["part"] == "material" - assert [ln["kind"] for ln in lines[:5]] == ["labor", "labor", "machine", "labor", "pct"] - - BLOCK = { "id": "DGR", "cover": "S:r", "kind": "조합", "name": "율 블록", "spec": "", "unit": "㎥", "cite": "", "origin": {}, diff --git a/resources/tester/test_792_3_engine_paths.py b/resources/tester/test_792_3_engine_paths.py index c06e7ac3b..7afbbd7f7 100644 --- a/resources/tester/test_792_3_engine_paths.py +++ b/resources/tester/test_792_3_engine_paths.py @@ -3,7 +3,7 @@ ① 엔진 직접(`master_cut.engine`) · ② M02 단가산출 SK 셈(`M02_Sangeun_Calc.run`) · ③ 일위대가 SC 한 줄(수량 1 · `M02_Labor_Doc.calc`) · ④ B09 산근 풀이(`B09_Estimation_Sangeun.Solver` · 841-1 단가 = M02 엔진) · -⑤ B09 일위대가 대가 블록(SC → 굳힌 SK 참조 수량 1 · `Labor_Source.Builder` → `Calc_Labor` 파이썬 · +⑤ B09 일위대가 대가 블록(SC → 사본 SK 참조 수량 1 · `Labor_Source.Builder` → `Calc_Labor` 파이썬 · TS 짝 · 내역 단가 `daega_price`)에서 같은 금액. 실무 견본(봉화 D00102 · 북부청임도 18)은 793-2 길(가져온 식 SK · 임시 층)로 만들어 ⑤ = 엑셀. @@ -115,7 +115,7 @@ OWNER = "pipe@100.0" # `test_145_2._ts` 가 내역 단가를 읽는 구조물 i def _daega(whole, sk: dict, sheets: dict) -> dict: - """⑤ SC(굳힌 SK 참조 수량 1) → 대가 블록 → 파이썬 셈 = TS 짝 → 내역 단가.""" + """⑤ SC(사본 SK 참조 수량 1) → 대가 블록 → 파이썬 셈 = TS 짝 → 내역 단가.""" from resources.tester.test_145_2_b09_labor_calc import _same, _ts sk_ref, sc_ref = {"층": "project", "키": "SK-990001"}, {"층": "project", "키": "SC-990001"} @@ -132,11 +132,27 @@ def _daega(whole, sk: dict, sheets: dict) -> dict: return {PART[p]: D(str(price[p])) for p in PART} +def _copy(doc: dict, master) -> dict: + """사본 SK(855-F B9-5 · `Item_Sangeun.freeze` 꼴) = SK 문서 + 수식 따로 사본 — 견본 로직은 + M01 문서 밖이라 문서 = 견본 줄 변환 · 값 사본 = 견본 줄 전부.""" + from M02_MasterTemplete import M02_Doc_Copy as dc + from M02_MasterTemplete import M02_Doc_Sk as dsk + from M02_MasterTemplete import M02_Item_Prices as prices + + rows = [r for part in master.index.values() for r in part.values()] + logic = prices.to_json([r for r in rows if "호표" in r]) + res = prices.to_json([r for r in rows if "호표" not in r]) + values = {"판": sc.skc._fp(logic), "로직": logic, "단가판": sc.skc._fp(res), "단가": res} + key = doc["바탕"]["로직"] + docs = dc.closure(master, [key]) + root = {**docs[key], "키": doc["키"]} + return {**doc, dsk.KEY: dsk.norm({**values, "따로": True, "문서": root, "부름": docs})} + + def _b09_daega(build) -> dict: master, row, _ = build() - sk = {"종류": sd.TITLE, "키": "SK-990001", "이름": "시험", "단위": "식", - "바탕": {"로직": _key(row)}, "입력값": {}, "덮개": {}, "더한줄": [], "뺀줄": [], - item_sk.ROW: row, "정체": []} # fmt: skip + doc = {"키": "SK-990001", "이름": "시험", "단위": "식", "바탕": {"로직": _key(row)}} + sk = _copy(sd.clean(doc, None, master), master) files = master.index sheets = { "labor": [{"key": k, "price": float(r["값"])} for k, r in files.get("LB", {}).items()], @@ -167,7 +183,7 @@ REAL = [("봉화", "D00102"), ("북부청임도", 18)] @pytest.mark.parametrize(("tag", "code"), REAL) def test_실무_가져온_식_SK_대가_내역_엑셀(tag, code, world): - """793-2 길 — 경쟁사 블록 → 가져온 식 SK(임시 층) → 굳힘 → SC 줄 → B09 대가 → + """793-2 길 — 경쟁사 블록 → 가져온 식 SK(임시 층) → 사본(수식 따로) → SC 줄 → B09 대가 → 내역 단가 = 엑셀.""" from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_MasterTemplete_Store as store @@ -181,10 +197,9 @@ def test_실무_가져온_식_SK_대가_내역_엑셀(tag, code, world): whole = m01.loaded()[1] rid = "project||SK-990001" frozen = item_sk.freeze({rid: sd.clean(doc, None, whole)})[rid] - key, row = frozen["바탕"]["로직"], json.loads(json.dumps(frozen[item_sk.ROW])) - assert ms_uses(row) # 새 의미 로직(줄 자리 · 번지 · 단계) + assert frozen["수식"]["따로"] and ms_uses(frozen["가져온"]["로직"]) # 새 의미(줄 자리 · 번지) books = {"labor": [], "material": [], "machine": [], "gaps": []} # 엑셀 단가 = 고정 줄 - got = _daega(sc._Over(whole, key, row), frozen, books) + got = _daega(whole, frozen, books) excel = {k: D(str(round(v))) for k, v in out["원본"]["엑셀금액"].items()} assert got == excel diff --git a/resources/tester/test_793_2_sangeun_imported.py b/resources/tester/test_793_2_sangeun_imported.py index d4efcf548..088cce60b 100644 --- a/resources/tester/test_793_2_sangeun_imported.py +++ b/resources/tester/test_793_2_sangeun_imported.py @@ -12,7 +12,6 @@ from __future__ import annotations import copy -import json from decimal import Decimal import pytest @@ -302,14 +301,12 @@ class _Priced: def _frozen_total(doc, whole): rid = "personal|7/42|SK-000001" - frozen = sk.freeze({rid: sd.clean(doc, None, _whole())})[rid] - key, row = frozen["바탕"]["로직"], json.loads(json.dumps(frozen[sk.ROW])) - assert key.startswith("GX9") and frozen["원본"][imp.KEY]["로직"] - over = calc._Over(whole, key, row) - return float(calc.run(sd.clean(frozen, None, over), over)["1단위"]["계"]) + frozen = sk.freeze({rid: sd.clean(doc, None, _whole())})[rid] # 사본 = 수식 따로(855-F B9-5) + assert frozen["수식"]["따로"] and frozen[imp.KEY]["로직"] + return float(calc.run(frozen, whole)["1단위"]["계"]) -def test_B09_굳힘_단가_전파(): +def test_B09_사본_엑셀_값_우리_값_굳힘(): whole = _whole() excel, ours = _doc(), imp.to_price(_doc(), "우리")["문서"] assert _frozen_total(excel, whole) == 45652 @@ -317,7 +314,7 @@ def test_B09_굳힘_단가_전파(): assert _frozen_total(ours, whole) == live up = _Priced(whole, MAN, float(whole.get(MAN)["값"]) + 50000) assert _frozen_total(excel, up) == 45652 # 엑셀 단가 그대로 = 안 바뀜 - assert _frozen_total(ours, up) == pytest.approx(live + 50000 * 2 / 50 * 1.01, abs=2) + assert _frozen_total(ours, up) == live # 사본 = 굳힌 값(855-F B9-5 · 새 값 = [재생성]) covered = _doc(덮개={"labor:형틀목공#0": {"qty": 0.2}}) assert _frozen_total(covered, whole) == _total(covered)