Files
Aislo/M02_MasterTemplete/M02_Sangeun_Copy.py
T
eomsangdonandClaude Opus 5.5 2bb5a53f1e refactor(855-E L2ⓑ-1): 단가산출 값 사본에서 로직 줄(GF · GC · GX) 걷음 — M01 바뀜 = 수식 문서 지문
- 단가산출 값 사본(층 파일 `수식.로직` · 셈 중 `사본.로직`)에 M01 로직 줄을 안 담음 · 옛 저장본의 로직 줄은 읽을 때 뺌(`skc.held` · 다음 [저장] 때 새 꼴 · 호환 없음)
  · 사본 정함 끝(`settle`) · 층 저장 관문(`Copy_Slim.trim` sangeun) · 따라옴(`Sk_AutoRenew.rows`) · 빈틈(`Doc_Gap`) · 사본없음 셈(`Doc_Sk_Path._rows`)
- 부름 로직 줄을 값 사본에 두던 고리 걷음(`Doc_Sk.settle` — 부름 = 문서 사본)
- M01 바뀜 표지 = 수식 사본 문서(부름 · 원본) 지문 대조(`skc.mark` · `same_part` · 자동 따라옴 SK 는 안 봄) · 원본 판 = 셈에 쓴 기초 문서(`base_doc`)
- 프로젝트 층(자동 따라옴 꺼짐) 굳힘 = 저장 때 `바탕문서`(굳히기 전과 같은 문서 · 옛 자동값 길 그대로) · [재생성] 때 새로
- 일위대가 · 사전조합 값 사본 = 로직 줄 그대로(브레인 (나) — 프로젝트 사본 묶음 `Item_Source.copy_rows` 가 읽음 · B9-6 뒤 `Labor_Copy.stamp` 에서 뺌)
- 시험: test_795_1 `_fake` = 가짜 M01 을 M01 꼴 복사로(`skc.Copy` 로 만들면 `dc.base` 가 벗겨 가짜가 사라짐 — 값 사본 로직 줄이 가리던 흠) · ① 값 사본 로직 줄 「없음」 으로 · ⑤ 바탕 로직 지움 갈래 뺌(M01 이 쓰는 로직 지우기 409) · 새 test_855_l2b_copy_plain(저장본 로직 줄 0 · 옛 저장본 로직 줄 안 읽음 · 금액 같음)

검증: 층 서고 SK 14 + SC 6 셈 답 · 표지 다름 0 · m855_sk 14 다름 0 · 다시 저장 파일 로직 줄 6 → 0 · 값 사본 로직 줄 읽힘 14 → 0 · 관련 39 + 지킴 + 핵심 447 통과 · 빌더 같음 · typecheck 0 · 화면 8006 만들기 · M01 고침 따라옴 131,716 · 되돌림 79,279 · 지움 · 콘솔 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:40:16 +09:00

426 lines
20 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.
"""M02 단가산출(SK) 로직 사본(PLAN 795-1 · 요구 655 · 656 · 요구서_655 0 · 1 장) — 서버 단독.
사본 = 저장 때 서버가 찍는 M01 닫힌 묶음(`M02_Item_Prices.collect` 다시 씀) — 셈 중 문서 칸 `사본` ·
층 저장 파일 = `수식` 의 값 몫 한 벌(`held` · 855 2-D — 파일엔 `사본` 안 씀 · 프로젝트 사본 꼴은 그대로):
{판, 시점, 로직 [M01 줄], 단가판, 단가시점, 단가 [M01 줄], 빠진?}
로직 = 바탕 로직 · 더한줄 로직 · 가져온 식 이음 · 하위 로직이 닿는 찾기 표 · 그 밖 요소(요율 등) —
단가산출 = 로직 줄(GF · GC · GX) 자체는 안 담음 · 안 읽음(855 L2 ⓑ · 셈 = 수식 문서 사본 `부름` · M01 바뀜 =
문서 지문) · 일위대가 · 사전조합 = 로직 줄 담음(프로젝트 사본 묶음이 읽음 — B9-6 뒤 `Labor_Copy.stamp` 에서 뺌)
단가 = 자원 단가 줄(`RES` 노임 · 자재 · 기계 · 유가전력 · 환율) = 단가 기준 시점 묶음.
셈 = M01 색인 위에 사본 줄을 얹은 `Copy`(키 · 원문번호 찾기만 사본 먼저 · M01 색인 안 고침) —
`M02_Sangeun_Calc._base_of`(바탕 줄) · `run`(엔진 · 하위 로직 · 표 · 단가)이 `over` 로 부름 ·
M01 에서 지워진 키 = 사본의 마지막 줄로 셈(표지 `지운키`) ·
사본 없는 SK(옛 SK · 바탕 참조) = 옛 길.
사본은 셈 · 저장 첫머리 `settle` 이 정함 — 저장본에 사본이 있으면 그것(화면이 보낸 것 버림) ·
없으면 받은 사본(층 복사 · 새로 · 판 다시 셈) · 그것도 없으면 저장 때 새로 찍음.
할일 칸 `사본할일`(화면 캐시 · [저장] 때 적용):
단가갱신 = 단가 줄만 지금 M01 값(지워진 키 = 그대로) ·
재생성 = 지금 M01 로 새로 찍음 — 덮개 · 식덮개 · 변수줄 · 상수 · 표값 · 까닭은 cid 열쇠라
새 사본에 그대로 얹힘 · 못 얹은 칸 = 짝잃음.
저장 때 = 사본에 없는 새 줄(더한줄 로직 더함 · 기초 바꿈)만 지금 M01 에서 더함.
미리 셈 = `M02_Doc_Sk_Path.preview`(몸 `할일` · 옛 `preview` 는 걷음 · 855 2-E2).
셈 답 덧칸 `사본` = {시점, 단가시점, M01새판, 지운키, 단가새값} · 같은 내용 지문 몫 = `same_part`.
"""
from __future__ import annotations
import hashlib
import json
from contextvars import ContextVar
from datetime import datetime
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_Item_Prices as prices
from M02_MasterTemplete import M02_MyMachine as mym
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from M02_MasterTemplete import M02_Sangeun_Imported as imp
KEY = "사본"
JOB = "사본할일"
PRICE, REGEN = "단가갱신", "재생성"
RES = ("LB", "MT", "EQ", "MO", "FX") # 자원 단가 = 단가 기준 시점 묶음
_MASTER = prices.mf.Master
#: 읽은 줄 적기(826-3 · `M02_Copy_Slim`) — {사본 줄 키 묶음: 그 색인이 내준 줄 키} · 꺼짐 = None
READS: ContextVar[dict | None] = ContextVar("읽은줄", default=None)
def whole_() -> Any:
"""M01 색인 + 지금 층 내 기계 줄(821-1 · `M02_MyMachine.whole`) + 내 재료 줄(840-4 · `M02_Material_Own.whole`)."""
from M02_MasterTemplete import M02_Material_Own as own
from M02_MasterTemplete import M02_MyMachine as mym
return own.whole(mym.whole())
def _fp(rows: Any) -> str:
raw = json.dumps(prices.to_json(rows), ensure_ascii=False, sort_keys=True)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
def _now() -> str:
return datetime.now().isoformat(timespec="seconds")
def has(doc: Any) -> bool:
copy = doc.get(KEY) if isinstance(doc, dict) else None
return isinstance(copy, dict) and isinstance(copy.get("로직"), list)
FORM = "수식" # 수식 사본 칸(`M02_Doc_Copy.KEY`) — 층 저장 파일의 값 사본 자리(855 2-D)
VALUES = ("판", "시점", "로직", "단가판", "단가시점", "단가")
#: M01 로직 줄 키 머리(GF · GC · GX) — 단가산출 값 사본에 안 담음 · 안 읽음(855 L2 ⓑ · 셈 = 수식 문서 사본 `부름`)
LOGIC = frozenset(t for t, g in prices.mf.mk.GROUP_OF.items() if g == "로직")
def plain(rows: Any) -> list:
"""값 사본 줄에서 로직 줄을 뺌(표 · 요율 · 자원 줄만)."""
return [r for r in rows or [] if not (isinstance(r, dict) and str(r.get("키"))[:2] in LOGIC)]
def _plain(copy: dict) -> dict:
"""단가산출 값 사본 — 로직 줄 뺀 꼴 · 판 다시(옛 저장본 = 읽을 때 뺌 · 파일은 다음 [저장] 때 새 꼴)."""
rows = plain(copy["로직"])
return copy if len(rows) == len(copy["로직"]) else {**copy, "로직": rows, "판": _fp(rows)}
def held(doc: Any) -> dict | None:
"""문서의 값 사본 — 셈 · 저장 중 `settle` 이 붙인 `사본` › 층 저장 파일 `수식` 의 값 몫(855 2-D ·
층 파일엔 `사본` 을 안 씀 · 프로젝트 사본은 `사본` 그대로) · 단가산출 = 로직 줄 뺌(855 L2 ⓑ) · 없음 = None."""
sk = isinstance(doc, dict) and doc.get("종류") == sd.TITLE
if has(doc):
return _plain(doc[KEY]) if sk else doc[KEY]
form = doc.get(FORM) if isinstance(doc, dict) else None
if isinstance(form, dict) and isinstance(form.get("로직"), list):
got = {k: form[k] for k in VALUES if k in form}
return _plain(got) if sk else got
return None
# ── 셈 색인 ──────────────────────────────────────────────────────────
class Copy:
"""M01 색인 위 사본 줄 — `get` · `logic` · `value` · `label` = 엔진 `Master` 한 벌
(사본 줄 먼저) · 그 밖 칸(자재 색인 · 찾기 답)은 속 M01 것을 읽음."""
label, value = _MASTER.label, _MASTER.value
def logic(self, key: str) -> dict:
"""사본 줄 › M01 색인 · 둘 다 없으면 속 색인이 따로 내주는 줄(굳힌 사본 `_Over` 등 · 855 2-D)."""
try:
return _MASTER.logic(self, key)
except prices.mf.FormulaError:
if getattr(type(self._whole), "logic", None) is _MASTER.logic:
raise # 속 = 맨 M01 색인 — 없는 키 그대로
return self._whole.logic(key)
def __init__(self, whole: Any, rows: list[dict], tag: Any = None) -> None:
self._whole, self._tag, self.twice = whole, tag, whole.twice
self.index, self.numbers = dict(whole.index), dict(whole.numbers)
mine = isinstance(tag, tuple) and tag[:1] == ("내기계",) # 층 내 기계 바탕 = 안 적음
self._box = None if mine else frozenset(str(r.get("키")) for r in rows)
for row in rows:
key = str(row.get("키"))
tid = key[:2]
self._own(self.index, whole.index, tid)[key] = row
if row.get("원문번호"):
self._own(self.numbers, whole.numbers, tid)[str(row["원문번호"])] = row
def get(self, ref: str) -> dict:
row = _MASTER.get(self, ref)
seen = READS.get()
if seen is not None and self._box is not None:
seen.setdefault(self._box, set()).add(str(row.get("키")))
return row
@staticmethod
def _own(mine: dict, theirs: dict, tid: str) -> dict:
if mine.get(tid) is theirs.get(tid):
mine[tid] = dict(theirs.get(tid) or {})
return mine[tid]
def __getattr__(self, name: str) -> Any:
return getattr(self._whole, name)
def __copy__(self) -> Copy: # 수식 고침(796-2b · `master_equation_edit.swap`) — 얕은 사본
out = object.__new__(Copy)
out.__dict__.update(self.__dict__)
return out
def _rows(copy: dict) -> list[dict]:
raw = json.dumps(prices.to_json([*copy["로직"], *(copy.get("단가") or [])]), ensure_ascii=False)
return json.loads(raw, parse_float=Decimal, parse_int=Decimal)
_CACHE: dict[tuple, Copy] = {}
_SEEN: dict[tuple, dict] = {}
_LIVE: list[Any] = [None] # 지금 M01 색인 — 바뀌면(저장 · 다시 읽음) 메모 비움(옛 색인 안 붙잡음)
def _forget(whole: Any) -> None:
while isinstance(whole, Copy):
whole = whole._whole
if whole is not _LIVE[0]:
_CACHE.clear()
_SEEN.clear()
_LIVE[0] = whole
def _auto(doc: Any, copy: dict) -> dict:
"""SK 사본 = 프로젝트 층 밖이면 지금 M01 줄(836-2 · `M02_Sk_AutoRenew`)."""
from M02_MasterTemplete import M02_Sk_AutoRenew as renew
form = doc.get(FORM) if isinstance(doc, dict) else None
return renew.rows(copy) if renew.is_sk(doc) and not renew.frozen(form) else copy
def over(doc: Any, whole: Any) -> Any:
"""값 사본(`held`) 있는 문서 = 사본 색인 · 없으면 `whole` 그대로."""
copy = held(doc)
if copy is None:
return whole
copy = _auto(doc, copy)
tag = (copy.get("판"), copy.get("단가판"))
if isinstance(whole, Copy) and whole._tag == tag:
return whole
_forget(whole)
got = _CACHE.get((id(whole), *tag))
if got is None or got._whole is not whole:
if len(_CACHE) > 32: # ponytail: 통째 비움 · 쓰는 SK 가 많아 느려지면 LRU 로
_CACHE.clear()
got = _CACHE[(id(whole), *tag)] = Copy(whole, _rows(copy), tag)
return got
# ── 찍기 · 단가 갱신 ──────────────────────────────────────────────────
def _split(rows: list[dict]) -> dict[str, Any]:
logic = [r for r in rows if str(r.get("키"))[:2] not in RES]
cost = [r for r in rows if str(r.get("키"))[:2] in RES]
when = _now()
return {
"판": _fp(logic),
"시점": when,
"로직": logic,
"단가판": _fp(cost),
"단가시점": when,
"단가": cost,
}
def stamp(doc: dict) -> dict | None:
"""지금 M01 로 새 사본 — 바탕 로직 · 더한줄 로직 · 고정 줄 이음 · 가져온 식 줄이 닿는
닫힌 묶음 · 바탕 참조 · 닿을 것 없음 = None."""
base = doc.get("바탕") or {}
if "참조" in base:
return None
keys, links = reach(doc.get("더한줄"))
keys = [str(base["로직"]), *keys] if base.get("로직") else keys
links += mym.keys_in(doc) # 줄 쌓기 기계 입력 「개인 EQP…」(821-1)
more, near = imp.reach_of(doc) # 가져온 식 = 불러온 그대로 문서 연결(857-3b)
return snap([*keys, *more], [*links, *near])
def reach(adds: Any) -> tuple[list[str], list[str]]:
"""더한줄이 닿는 (로직 키, 요소 키) — 로직 줄 · 인력 · 재료 · 기계 요소 · 고정 줄 이음."""
adds = [x for x in adds or [] if isinstance(x, dict)]
keys = [str(x["로직"]) for x in adds if x.get("종류") == "로직" and x.get("로직")]
links = [str(x["요소"]) for x in adds if x.get("종류") in sd.ADD_PART and x.get("요소")]
links += [str(v) for x in adds for v in ((x.get("고정") or {}).get("이음") or {}).values() if v]
return keys, links
def snap(keys: list[str], links: list[str], extra: list[dict] | None = None) -> dict | None:
"""키 · 요소 · 마스터 밖 줄이 닿는 M01 닫힌 묶음 → 사본(닿을 것 없음 = None)."""
if not (keys or links or extra):
return None
got = prices.collect(keys, links, extra)
lost = got.pop("_빠진", None)
keys = [str(r.get("키")) for data in got.values() for r in data[prices.m01.items_key(data)]]
whole = whole_() # 줄 = 셈 색인 것(파일 묶음과 같은 판)
rows = [whole.index[k[:2]][k] for k in keys if k in whole.index.get(k[:2], {})]
out = _split(prices.to_json(rows))
return out | ({"빠진": lost} if lost else {})
def refresh(copy: dict, whole: Any) -> tuple[dict, list[dict]]:
"""[단가 갱신] — 단가 줄만 지금 M01 값 · (새 사본, 바뀐자원) · 지워진 키 = 마지막 값 그대로."""
rows, changed = [], []
for row in copy.get("단가") or []:
key = str(row.get("키"))
live = whole.index.get(key[:2], {}).get(key)
if live is None:
rows.append(row)
changed.append({"키": key, "이름": row.get("이름"), "지워짐": True})
continue
new = prices.to_json(live)
if _fp(new) != _fp(row):
changed.append(
{"키": key, "이름": new.get("이름"), "전": row.get("값"), "후": new.get("값")}
)
rows.append(new)
return {**copy, "단가": rows, "단가판": _fp(rows), "단가시점": _now()}, changed
def grow(copy: dict, fresh: dict | None) -> dict:
"""저장 때 — 사본에 없는 키 줄만 새 사본(`fresh` = 지금 M01)에서 더함(있는 줄 = 그대로)."""
have = {str(r.get("키")) for r in [*copy["로직"], *(copy.get("단가") or [])]}
new = [
r
for r in [*(fresh or {}).get("로직", []), *(fresh or {}).get("단가", [])]
if str(r.get("키")) not in have
]
if not new:
return copy
logic = [*copy["로직"], *(r for r in new if str(r.get("키"))[:2] not in RES)]
cost = [*(copy.get("단가") or []), *(r for r in new if str(r.get("키"))[:2] in RES)]
return {**copy, "로직": logic, "판": _fp(logic), "단가": cost, "단가판": _fp(cost)}
def rejoin(copy: dict, adds: list) -> dict:
"""[다시 잇기](796-2e) — 표지 낀 더한 기초가 닿는 닫힌 묶음을 지금 M01 줄로 갈음(단가 줄은 더하기만)."""
keys = [
str(x["로직"]) for x in adds if isinstance(x, dict) and x.get("다시잇기") and x.get("로직")
]
fresh = snap(keys, [])
if not fresh:
return copy
new = {str(r.get("키")): r for r in fresh["로직"]}
logic = [new.pop(str(r.get("키")), r) for r in copy["로직"]] + list(new.values())
return grow({**copy, "로직": logic, "판": _fp(logic)}, fresh)
def taken(raw: Any) -> dict | None:
"""받은 사본(층 복사 · 새로) — 줄 꼴만 보고 판은 서버가 다시 셈."""
if not has({KEY: raw}):
return None
logic = [r for r in raw["로직"] if isinstance(r, dict) and str(r.get("키"))[:2] not in RES]
cost = [r for r in raw.get("단가") or [] if isinstance(r, dict) and str(r.get("키"))[:2] in RES]
keep = {k: str(raw.get(k) or "") for k in ("시점", "단가시점")}
return {**keep, "로직": logic, "판": _fp(logic), "단가": cost, "단가판": _fp(cost)}
_FILE: list = [(None, None)] # (자국, SK 파일) — 한 저장 안 같은 파일 되풀이 읽기 막음(826-3)
def stored_doc(key: Any) -> dict | None:
"""저장된 SK 파일(읽기만 — 고치지 말 것) · 파일 자국(경로 · 고친 때 · 크기)이 같으면 앞 것."""
from M02_MasterTemplete import M02_MasterTemplete_Store as store
if not sd.KEY.match(str(key or "")):
return None
file = store.root() / sd.KIND / f"{key}.json"
try:
st = file.stat()
mark = (str(file), st.st_mtime_ns, st.st_size)
have = _FILE[0]
if have[0] != mark:
have = _FILE[0] = (mark, json.loads(file.read_bytes()))
except (OSError, ValueError):
return None
return have[1]
def _stored(key: Any) -> dict | None:
return held(stored_doc(key))
def settle(doc: Any, save: bool = False) -> Any:
"""셈 · 저장 첫머리 — 서버가 정한 사본으로 갈음(할일 적용 · 저장 때 새 줄 더함 · 할일 칸 뗌)."""
if not isinstance(doc, dict):
return doc
job = doc.get(JOB) # 모르는 할일 = 없음
out = {k: v for k, v in doc.items() if k not in (KEY, JOB)}
if "참조" in (doc.get("바탕") or {}):
return out
copy = _stored(doc.get("키")) or taken(held(doc))
if job == REGEN or (copy is None and save):
copy = stamp(out)
elif job == PRICE and copy:
copy = refresh(copy, whole_())[0]
if copy and any(isinstance(x, dict) and x.get("다시잇기") for x in out.get("더한줄") or []):
copy = rejoin(copy, out["더한줄"])
if copy:
copy = _auto(doc, copy) # M01 자동 따라옴(836-2) — 저장 때 굳음
if save and copy and READS.get() is None: # 읽은 줄만(826-3) = 저장 관문이 더함
copy = grow(copy, stamp(out))
out = _formula_job(out, job)
return {**out, KEY: _plain(copy)} if copy else out # 로직 줄 안 담음(855 L2 ⓑ)
def _formula_job(out: dict, job: Any) -> dict:
"""수식 사본(802-4a · `M02_Doc_Sk`) 할일 — 재생성 = 파생으로(부름 새로 · 고친 문서 버림) ·
단가갱신 = 따로 문서의 값 줄도 지금 M01."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Sk_AutoRenew as renew
got = out.get(dc.KEY) if dc.has(out) else None
if got is None or job not in (PRICE, REGEN):
return out
if job == REGEN: # 맡긴 기계 고침 · 옵션 값 · 지킨 칸 바탕(848-2)도 버림
drop = (
"문서",
"끊음",
"따로",
"처음",
"바탕문서",
*renew.KEEP,
) # 바탕문서 = 프로젝트 굳힘(855 L2 ⓑ)
got = {k: v for k, v in got.items() if k not in drop} | {"부름": {}}
elif got.get("따로"):
got = dc.refresh(got)[0]
return {**out, dc.KEY: got}
# ── 표지 ──────────────────────────────────────────────────────────────
def state(copy: dict, whole: Any) -> dict[str, Any]:
"""{M01새판, 지운키, 단가새값} — 사본 줄과 지금 M01 줄 대조(같은 M01 · 같은 판 = 메모)."""
_forget(whole)
tag = (id(whole), copy.get("판"), copy.get("단가판"))
if tag in _SEEN and _SEEN[tag]["whole"] is whole:
return _SEEN[tag]["답"]
def live(row: dict) -> Any:
key = str(row.get("키"))
return whole.index.get(key[:2], {}).get(key)
gone = [str(r.get("키")) for r in [*copy["로직"], *(copy.get("단가") or [])] if live(r) is None]
logic = any(live(r) is None or _fp(live(r)) != _fp(r) for r in copy["로직"])
cost = any(live(r) is not None and _fp(live(r)) != _fp(r) for r in copy.get("단가") or [])
got = {"M01새판": logic, "지운키": gone, "단가새값": cost}
_SEEN[tag] = {"whole": whole, "답": got}
return got
def mark(ans: dict, doc: dict) -> dict:
"""셈 답 덧칸 `사본` — 사본 없는 문서 = 칸 없음."""
if not has(doc):
return ans
copy = doc[KEY]
head = {"시점": copy.get("시점"), "단가시점": copy.get("단가시점")}
got = state(copy, whole_())
if not got["M01새판"] and _doc_moved(doc):
got = {**got, "M01새판": True}
return {**ans, KEY: {**head, **got}}
def _doc_moved(doc: dict) -> bool:
"""M01 바뀜 = 수식 사본 문서(부름 · 원본) 지문 ≠ 지금 M01 문서(855 L2 ⓑ · 로직 줄 값 사본 대신) ·
자동 따라옴 SK = 늘 지금 문서라 안 봄."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Sk_AutoRenew as renew
form = doc.get(FORM)
if not dc.has(doc) or (renew.is_sk(doc) and renew.on() and not renew.frozen(form)):
return False
return bool(dc.state(form)["문서새판"])
def same_part(doc: Any) -> str | None:
"""같은 내용 지문 몫 — 지금 M01 과 같은 사본 = None(새로 찍을 문서와 같음) · 다르면 판."""
copy = held(doc)
if copy is None:
return None
seen = state(copy, whole_())
fresh = not (seen["M01새판"] or seen["지운키"] or seen["단가새값"] or _doc_moved(doc))
return None if fresh else f"{copy.get('판')}:{copy.get('단가판')}"