Merge commit '395c7072805d49f3974b90d14e03e5c6d92d600f' into main_laptop_1

This commit is contained in:
2026-11-18 11:42:51 +09:00
44 changed files with 465 additions and 1160 deletions
+50 -1
View File
@@ -22,13 +22,62 @@ from typing import Any
from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠
md = importlib.import_module("master_doc") # 식 꼴 읽기 = 새 계산기 파서(855-F B9-3)
ms = importlib.import_module("master_formula_sum")
PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
FLAGS = ("place", "out") # 블록 줄 덧칸 — 단가산출 블록이 줄을 바꿔도 이어 받음
Refs = list[tuple[int, str | None]] # (줄 차례, 비목 | None = 줄 전체)
# ── 블록 줄 꼴 읽기(옛 `master_formula_sum` 의 줄 꼴 함수 · 셈 아님 · 855-E 2-E4 에서 옮김) ──────────
class ms: # noqa: N801 — 부르는 쪽 이름(`ms.items` …) 그대로
"""줄 꼴(`Doc_Run.row` — 호표 · 덧줄 · 단계)만 읽는 작은 함수 — 엔진 셈 몸 없음."""
ROW_KEYS = ("단계", "끝전", "조정") # 블록 칸
LINE_KEYS = ("번지", "합밖", "자리") # 호표 · 덧줄 칸
ADDR, STEP = "번지", "단계" # 덧줄 식 이름 — `번지.A01.재료비` · `단계.'소계'.계`
@staticmethod
def items(row: dict) -> list[dict]:
"""줄 차례 = 호표 하나씩 뒤 덧줄 하나씩."""
return [*row.get("호표", []), *row.get("덧줄", [])]
@staticmethod
def uses(row: dict) -> bool:
"""새 의미(번지 · 단계 · 끝전 · 조정 · 합밖 · 줄 자리)를 쓰는 블록."""
lines = ms.items(row)
return any(k in row for k in ms.ROW_KEYS) or any(
k in x for x in lines for k in ms.LINE_KEYS
)
@staticmethod
def _cover(row: dict) -> list[tuple[dict, set]]:
"""단계마다 (단계, 담은 줄 차례) — 단 1 = 제 `줄` · 단 k = 제 `줄` + 아직 안 담긴 아래 단 단계 ·
제외 단계는 위로 안 올라감."""
where = {x.get("이름"): i for i, x in enumerate(ms.items(row)) if x.get("이름")}
out, open_ = [], []
for st in row.get(ms.STEP) or []:
level = int(st.get("단") or 1)
mine = {where[n] for n in st.get("줄") or [] if n in where}
keep = []
for low, got in open_:
if low < level:
mine |= got
else:
keep.append((low, got))
open_ = keep if st.get("제외") else [*keep, (level, mine)]
out.append((st, mine))
return out
@staticmethod
def skipped(row: dict) -> set:
"""비목 합에서 빼는 줄 차례 — `합밖` 줄(번지엔 쌓음) · 제외 단계가 담은 줄."""
out = {i for i, x in enumerate(ms.items(row)) if x.get("합밖")}
for st, mine in ms._cover(row):
if st.get("제외"):
out |= mine
return out
def _f(value: Any) -> float | None:
try:
return None if value is None else float(value)
-2
View File
@@ -31,8 +31,6 @@ from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
#: 원가 단가 목록에 오르는 자원 표
RESOURCE_TABLES = ("LB", "EQ", "MT", "MO")
mf = item_prices.mf
def used_keys(folder: Path) -> list[str]:
"""사본 하나가 담은 로직을 돌릴 때 부른 자원 키 — 부른 차례 · 겹침 없음."""
-1
View File
@@ -62,7 +62,6 @@ from M02_MasterTemplete.M02_Item_Snapshot import (
)
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json
mf = item_prices.mf
PARTS = ("labor", "material", "expense")
COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
+2 -1
View File
@@ -16,7 +16,6 @@ from B09_Estimation.B09_Estimation_Calc_Base import rounddown, total
from M01_MasterData import M01_MasterData_Store as _m01 # noqa: F401 — scripts 길을 둠
mc = importlib.import_module("master_doc_calc")
ms = importlib.import_module("master_formula_sum")
PARTS = ("labor", "material", "expense")
COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
@@ -61,6 +60,8 @@ def doc_totals(answer: Any, lines: list[dict]) -> dict[str, float | None]:
def doc_shown(row: dict) -> dict[str, int]:
"""중간값 표시 자리 {이름: 자리} — `shown` 과 같은 뜻(`표시` · 옛 로직 작업량 Q = ROUND 2 · 엑셀 자리) ·
문서 셈에 그 식 줄을 반올림으로 씌워 셈(`Doc_Run.solve` `shown`)."""
from B09_Estimation.B09_Estimation_Labor_Rule import ms # 줄 꼴 읽기(855-E 2-E4)
new = ms.uses(row)
out: dict[str, int] = {}
for step in row.get("중간", []):
+40 -11
View File
@@ -65,9 +65,21 @@ LOGIC = ("변수", "식", "금액", "끝수", "결과단위") # fmt: skip
LABEL = ("이름", "규격", "단위", "비고", "출처") # fmt: skip
def doc_fp(doc: Any) -> str:
def _whole_num(v: Any) -> Any:
"""수 꼴 맞춤 — 정수 값 실수(4.0) = 정수(4)(저장본 · M01 문서 읽기 꼴이 달라도 같은 지문 · 855-E 2-E4)."""
if isinstance(v, dict):
return {k: _whole_num(x) for k, x in v.items()}
if isinstance(v, list):
return [_whole_num(x) for x in v]
if isinstance(v, float) and v.is_integer():
return int(v)
return v
def doc_fp(doc: Any, legacy: bool = False) -> str:
"""문서 계산 내용 지문(848-2) — 셈 칸(`LOGIC`)만 · 줄 · 변수의 글 칸 뺌 · 서버 표지 칸 뺌 ·
`기계덮음`(②) · `위덮음`(①) · `손고침` 은 셈 칸 밖 = 바뀌어도 같은 지문."""
`기계덮음`(②) · `위덮음`(①) · `손고침` 은 셈 칸 밖 = 바뀌어도 같은 지문 · 수 꼴(4 · 4.0) 안 가림 ·
`legacy` = 수 꼴 가리던 옛 지문(저장본 `원본.판` 대조만)."""
from M02_MasterTemplete import M02_Doc_Sk as dsk
doc = doc if isinstance(doc, dict) else {}
@@ -75,7 +87,8 @@ def doc_fp(doc: Any) -> str:
got = {k: doc.get(k) for k in LOGIC}
for part in ("변수", "식", "금액"):
got[part] = [bare(x) for x in got[part] or []]
return fp(dsk._strip(got))
got = dsk._strip(got)
return fp(got) if legacy else fp(_whole_num(ml._norm(got)))
# ── M01 문서(정본 폴더) ────────────────────────────────────────────────
@@ -108,18 +121,34 @@ def _carried(whole: Any, key: str) -> dict | None:
return None
def _held(whole: Any, key: str) -> dict | None:
"""값 사본 색인(`skc.Copy`)이 든 그 키 줄(옛 저장본 · 새 값 사본엔 로직 줄 없음) · 없음 = None."""
for _ in range(8):
box = getattr(whole, "_box", None) if isinstance(whole, skc.Copy) else None
if box and key in box:
return whole.index.get(key[:2], {}).get(key)
own = vars(whole) if hasattr(whole, "__dict__") else {}
whole = own.get("_whole")
if whole is None:
return None
return None
def doc_of(whole: Any, key: str) -> dict | None:
"""키 하나의 문서 — 색인이 실어 온 사본 문서 › 값 사본 줄 = 지금 M01 줄이면 M01 문서 · 다르면 그 줄
변환 · 없으면 None."""
"""키 하나의 문서 — 색인이 실어 온 사본 문서 › 값 사본 줄(옛 저장본) = 지금 M01 줄이면 M01 문서 · 다르면
그 줄 변환 › M01 문서 › M01 문서 없는 키 = 색인 줄 변환(견본 · 마스터 밖 줄) · 없으면 None ·
M01 로직 줄은 안 읽음(855-E 2-E4)."""
if (got := _carried(whole, str(key))) is not None:
return cp.deepcopy(got)
try:
row = whole.logic(key)
except _ERR:
row = None
live = folder().get(key)
row = _held(whole, str(key))
if row is None and live is not None:
return cp.deepcopy(live)
if row is None:
return cp.deepcopy(live) if live else None
try:
row = whole.logic(key)
except _ERR:
return None
if live and (_live(key) is None or skc._fp(_live(key)) == skc._fp(prices.to_json(row))):
return cp.deepcopy(live)
try:
@@ -442,4 +471,4 @@ def state(copy: dict) -> dict[str, Any]:
def same_origin(base: dict, live: Any) -> bool:
"""`원본.판` 대 지금 M01 문서 — 계산 내용 지문(`doc_fp`) · 옛 통째 지문(`fp`) 둘 다 받음."""
return base.get("판") in (doc_fp(live), fp(live))
return base.get("판") in (doc_fp(live), doc_fp(live, True), fp(live))
-1
View File
@@ -47,7 +47,6 @@ OLD_FIELDS = (
"수식고침", "고름", "자재표시", "켜쌓기율",
) # fmt: skip
_STAMPED = ("원값", "바탕판", "처음수량", "M01판", "끊음") # 서버가 적는 칸 — 옛 칸 대조에서 뺌
OLD: ContextVar[bool] = ContextVar("옛길", default=False) # 옛 셈 길(옮기기 전 금액 대조)
SAVING: ContextVar[dict | None] = ContextVar("수식길저장", default=None) # {키, 사본} — 수식 길만
+3 -1
View File
@@ -45,7 +45,9 @@ def kind_of(line: dict[str, Any]) -> str:
return kind
mm_plain = m01.cm.mf.mp.mm.plain
import master_base as mb # noqa: E402 — 바탕만(855-E 2-E4)
mm_plain = mb.mp.mm.plain
def _parts(money: Any) -> dict[str, Decimal]:
+2 -1
View File
@@ -22,7 +22,8 @@ from M01_MasterData import M01_MasterData_Store as m01
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M02_MasterTemplete import M02_Mat_Place as place
mf = m01.cm.mf
import master_base as mf # noqa: E402 — 바탕만(855-E 2-E4 · 엔진 몸 안 읽음) · scripts 길은 `m01` 이 둠
mp = mf.mp
mm = mp.mm
SEED_NAME = "일위대가조합.json"
+4 -2
View File
@@ -14,7 +14,7 @@ from decimal import Decimal
from pathlib import Path
from typing import Any
from M01_MasterData import M01_MasterData_Store as m01
from M01_MasterData import M01_MasterData_Store as m01 # noqa: F401 — scripts 길을 둠
from M02_MasterTemplete import M02_Hopyo_Elem as elem
from M02_MasterTemplete import M02_Hopyo_Fixed as hfix
from M02_MasterTemplete import M02_Labor_Doc as labor
@@ -35,7 +35,9 @@ WHY = {
"호표": "하위 호표 단위 다름 · 같은 하위 둘째",
"%": "밑수가 다른 줄 금액 합 아님",
}
mm_unit = m01.cm.mf.mp.mm.plain_unit
import master_base as mb # noqa: E402 — 바탕만(855-E 2-E4)
mm_unit = mb.mp.mm.plain_unit
def mark(key: str, no: int) -> str:
+43 -16
View File
@@ -17,18 +17,48 @@ from typing import Any
from M02_MasterTemplete import M02_Item_Prices as prices
import master_doc as md # noqa: E402 — scripts 길 = prices(m01) 뒤에
import master_machine_crew as crew # noqa: E402
_HOLE = re.compile(r"\{([^{}]+)\}")
def _options(ids: dict, hole: str) -> list | None:
opts = ((ids.get(hole) or {}).get("연결") or {}).get("목록")
return [str(x).strip("'") for x in opts] if opts else None
class _Docs(prices._Collector):
"""수식 문서가 잇는 자원 · 표 줄 키 모음."""
def options(self, ids: dict, hole: str, depth: int = 0) -> list | None:
"""구멍 변수의 값 후보 — 고르기 목록 · 요소 칸을 읽는 변수(「EQ:{기계}」 의 조종원직종 등) = 그 틀을
끼운 줄마다 그 칸 값(옛 식 글 훑기 `_expand` 와 같은 뜻) · 모름 = None."""
link = (ids.get(hole) or {}).get("연결") or {}
if isinstance(link.get("목록"), list): # 빈 목록 = 끼울 값 없음(옛 `_choices` 와 같음)
return [str(x).strip("'") for x in link["목록"]]
if link.get("갈래") != "요소" or not link.get("키") or not link.get("칸") or depth > 3:
return None
keys = self._filled(str(link["키"]), ids, depth + 1)
if keys is None:
return None
out = []
for key in keys:
try:
row = self.whole.get(key)
except prices.mf.FormulaError:
continue
vals = row.get("값") or {} # 줄 값 — 기계 = 인력 · 잡품 목록을 칸으로(842-3)
vals = crew.view(vals) if str(row.get("키"))[:2] == "EQ" else vals
value = vals.get(link["칸"]) if isinstance(vals, dict) else None
if value not in (None, ""):
out.append(str(value))
return list(dict.fromkeys(out))
def _filled(self, text: str, ids: dict, depth: int = 0) -> list[str] | None:
"""틀 글 → 끼운 글들 · 못 끼움 = None."""
out = [text]
for hole in sorted(set(_HOLE.findall(text))):
opts = self.options(ids, hole, depth)
if opts is None:
return None
out = [one.replace(f"{{{hole}}}", x) for one in out for x in opts]
return out
def doc(self, doc: dict) -> None:
ids = {md.var_id(v): v for v in doc.get("변수") or []}
for v in ids.values():
@@ -42,16 +72,13 @@ class _Docs(prices._Collector):
self.add(ref)
def fill(self, text: str, ids: dict) -> list[str]:
"""틀 글 `{변수}` 구멍 → 고르기 목록으로 끼운 글들 · 목록 없는 구멍 = 그 테이블 전부(빈 목록)."""
out = [text]
for hole in sorted(set(_HOLE.findall(text))):
opts = _options(ids, hole)
if opts is None:
tid = prices.mk.id_of(text)
if tid and tid not in prices._TOO_BIG:
self.keys.update(self.whole.index.get(tid, {}))
return []
out = [one.replace(f"{{{hole}}}", x) for one in out for x in opts]
"""틀 글 `{변수}` 구멍 → 값 후보로 끼운 글들(`options`) · 못 끼움 = 그 테이블 전부(빈 목록)."""
out = self._filled(text, ids)
if out is None:
tid = prices.mk.id_of(text)
if tid and tid not in prices._TOO_BIG:
self.keys.update(self.whole.index.get(tid, {}))
return []
return out
def cond(self, cond: dict, unit: Any, ids: dict) -> None:
@@ -61,7 +88,7 @@ class _Docs(prices._Collector):
variants = [cond]
holes = {h for v in cond.values() if isinstance(v, str) for h in _HOLE.findall(v)}
for hole in sorted(holes):
opts = _options(ids, hole)
opts = self.options(ids, hole)
if opts is None:
variants = [prices.mm.static(cond)]
break
+15 -173
View File
@@ -23,9 +23,10 @@ from decimal import Decimal
from typing import Any
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_MyMachine as mym
from M02_MasterTemplete import M02_MyMachine as mym # noqa: F401 — Item_Bundle.collect 가 씀
import master_base as mf # noqa: E402 — 바탕만(855-E 2-E4 · 엔진 몸 안 읽음) · scripts 길은 `m01` 이 둠
mf = m01.cm.mf
mk = m01.mk
mcb = m01.mcb
mm = mf.mp.mm # 품셈재료 · 자재품목 후보(`master_material`)
@@ -39,18 +40,6 @@ def master() -> tuple[dict[str, dict], Any]:
return m01.loaded()
def _texts(row: dict) -> list[str]:
out = [step["식"] for step in row.get("중간", [])]
if "결과" in row:
out.append(row["결과"]["식"])
for item in row.get("호표", []):
out.append(item["수량"])
if isinstance(item.get("요소"), str): # 단가산출 참조 · 고정 더한줄 = 요소 없음(719-1)
out.append(item["요소"])
out += [extra["식"] for extra in row.get("덧줄", [])]
return out
#: 재료 후보 찾기 답 — (마스터 색인, {조건 글: 키}) · 색인이 바뀌면(마스터 저장) 새로 ·
#: 복사본 목록이 복사본마다 단가 묶음을 다시 모아도 같은 조건은 한 번만 찾음(156-2)
_FOUND: tuple[Any, dict[str, list[str]]] = (None, {})
@@ -73,22 +62,8 @@ class _Collector:
def __init__(self, whole: Any):
self.whole = whole
self.keys: set[str] = set()
self.logics: set[str] = set()
self.missing: list[str] = []
def refs(self, row: dict, template: str) -> list[str]:
"""원문번호 틀 → 닿을 수 있는 요소 참조 — 고르기로 끼우고, 못 풀면 그 테이블 전부."""
if "{" not in template:
return [template]
expanded = mf._expand(row, template, self.whole)
if expanded is not None:
return expanded
tid = mk.id_of(template)
if not tid or tid in _TOO_BIG:
self.missing.append(f"{row.get('키')} 「{template}」 틀을 못 풂")
return []
return list(self.whole.index.get(tid, {}))
def add(self, ref: str) -> None:
try:
row = self.whole.get(ref)
@@ -119,113 +94,6 @@ class _Collector:
if root.endswith(want) and u == unit_p and (not spec or s == spec):
self.keys.add(key)
def pick(self, row: dict, cond: dict, unit: Any) -> None:
"""재료 고르기 조건 — 대표 줄 · 후보 줄(`{입력}` 은 고르기 값으로 끼움)."""
if cond.get("지역") == "입력" or cond.get("계약종별") == "입력":
self.widely(cond, unit)
return
holes = sorted(
{h for v in cond.values() if isinstance(v, str) for h in mf._HOLE.findall(v)}
)
variants = [cond]
if holes:
env_sets = mf._expand(row, "|".join(f"{{{h}}}" for h in holes), self.whole)
if env_sets is None:
variants = [mf.static(cond)]
else:
variants = []
for filled in env_sets:
env = dict(zip(holes, filled.split("|")))
variants.append(
{k: mf.fill(v, env) if isinstance(v, str) else v for k, v in cond.items()}
)
for one in variants:
if one.get("대표"):
self.add(str(one["대표"]))
if not one.get("구분") and not one.get("검색어"):
continue
for key in _candidates(self.whole, one):
self.add(key)
def flow(self, row: dict) -> None:
"""흐름 입력 상자 — 요소(고정 · 기본 · 검색어 묶음 · 조건 찾기 후보) · 표 · 다른 로직 ·
기계 시간당 경비 로직."""
from M02_MasterTemplete.DataFlow import M02_DF_Values as dv # 흐름 값 찾기와 같은 뜻
for box in row["흐름"].get("boxes") or []:
inp = (box.get("input") or {}) if box.get("kind") == "input" else {}
if inp.get("mode") == "logic":
self.logic(str((inp.get("logic") or {}).get("key") or ""))
if inp.get("table"):
self.add(str(inp["table"].get("key") or ""))
for el in inp.get("elements") or []:
ref, unit = str(el.get("ref") or ""), el.get("unit")
for one in (ref, str(el.get("default") or "")):
cond = dv._pick(one)
if cond is not None:
self.pick(row, cond, unit)
elif one and not one.startswith("UE-"):
self.element(one)
if el.get("mode") != "rule":
continue
if inp.get("group") in dv.GROUP_RULE: # 인력 · 기계 · 유가전력 찾기 = 그 그룹 전부
self.keys.update(str(r.get("키")) for r in dv._group_rows(inp["group"]))
elif dv._pick(ref) is None: # 재료 범위 찾기 — 범위(구분 · 상세구분) 후보
scope = el.get("scope") or {}
self.pick(
row, {k: scope[k] for k in ("구분", "상세구분") if scope.get(k)}, unit
)
def element(self, ref: str) -> None:
"""요소 키 · 「EQ키#칸」(시간당 경비면 그 기계경비 로직까지) · 「ID:원문번호{…}」 틀."""
from M02_MasterTemplete.DataFlow import M02_DF_Values as dv
base, _, field = ref.partition(dv.MACHINE_SEP)
if "{" in base: # 「EQ:{기계}」 같은 틀 — 그 테이블 전부
self.keys.update(self.whole.index.get(mk.id_of(base) or "", {}))
return
self.add(base)
if field == dv.HOURLY:
from M02_MasterTemplete import M02_Machine_Hourly as mh
row = self.whole.index.get(base[:2], {}).get(base) or {}
if got := mh.pick(row): # 식 고름 한 곳(822-2)
self.logic(str(got.get("키")))
def logic(self, key: str) -> None:
if key in self.logics:
return
try:
row = self.whole.logic(key)
except mf.FormulaError as error:
self.missing.append(f"{key} · {error}")
return
self.logics.add(key)
self.keys.add(key)
self.row(row)
def row(self, row: dict) -> None:
"""로직 줄 하나가 닿는 것 — 마스터 로직 · 굳힌 단가산출 줄(719-1 · 마스터 밖 줄)."""
if isinstance(row.get("흐름"), dict): # 흐름 로직 — 옛 칸 대신 흐름이 쓰는 것을 모음
self.flow(row)
return
for text in _texts(row):
try:
node = mf.parse(text)
except mf.FormulaError:
continue # 못 읽는 식 — 계산도 같은 까닭으로 멈춤
for part in mf.walk(node):
kind = part[0]
if kind == "ref" or kind == "find":
for ref in self.refs(row, part[1]):
self.add(ref)
elif kind == "logic":
for ref in self.refs(row, part[1]):
self.logic(ref)
for item in row.get("호표", []):
if isinstance(item.get("요소"), dict):
self.pick(row, item["요소"], item.get("단위"))
#: M01 에서 지워진 사본 줄(795-4) 자리 — `Master` 가 그룹 아닌 「줄」 로 읽음
COPY_FILE = "사본_남은줄.json"
@@ -238,45 +106,19 @@ def collect(
over: list[dict] | None = None,
) -> dict[str, Any]:
"""담은 로직 + 자재(MT)의 닫힌 단가 묶음 — `{파일 이름: 파일(줄은 모은 것만 · 차례 그대로)}` ·
`extra` = 마스터 밖 로직 줄(굳힌 단가산출 719-1) — 그 줄이 닿는 것만 모음(줄은 안 담음) ·
`over` = M02 로직 사본 줄(795-4) — 같은 키는 M01 줄 대신 · M01 에 없는 키 = `COPY_FILE`."""
files, whole = master()
from M02_MasterTemplete import M02_Material_Own as mat
닫힌 묶음 = 로직 키의 수식 문서 묶음(`M02_Doc_Copy.closure`)이 잇는 자원 · 표 줄(`M02_Item_Bundle.collect`
· 로직 줄 · 옛 식 글 훑기 없음 · 855-E 2-E4) · `over` = M02 값 사본 줄(795-4 · 같은 키는 M01 줄 대신) ·
M01 수식 문서 없는 로직 키 = `_빠진` · `extra`(마스터 밖 로직 줄) = 받지 않음(부르는 곳 0)."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Item_Bundle as item_bundle
whole = mat.whole(
mym.whole(whole)
) # 지금 층 내 기계(821-1) · 내 재료(840-4) — 없으면 M01 그대로
own = {str(r.get("키")): r for r in (*mym.added(whole), *mat.added(whole))}
mine = {str(r.get("키")): r for r in over or []}
if mine:
from M02_MasterTemplete import M02_Sangeun_Copy as skc
whole = skc.Copy(whole, skc._rows({"로직": list(mine.values())}))
collector = _Collector(whole)
for key in logic_keys:
collector.logic(key)
for row in extra or []:
collector.row(row)
for code in materials or []:
collector.add(code)
out: dict[str, Any] = {}
seen: set[str] = set()
for name, data in files.items():
slot = m01.items_key(data)
rows = [
mine.get(str(row.get("키")), row)
for row in data.get(slot) or []
if str(row.get("키")) in collector.keys
]
seen.update(str(row.get("키")) for row in rows)
if rows:
out[name] = {**{k: v for k, v in data.items() if k != slot}, slot: rows}
left = [r for k, r in {**own, **mine}.items() if k in collector.keys and k not in seen]
if left:
out[COPY_FILE] = {"그룹": "사본", "줄": left}
if collector.missing:
out["_빠진"] = sorted(set(collector.missing))
return out
keys = [str(k) for k in logic_keys]
docs = dc.closure(master()[1], keys)
out = item_bundle.collect(docs, materials, over)
lost = sorted(
set(out.pop("_빠진", [])) | {f"{k} · 수식 문서 없음" for k in keys if k not in docs}
)
return out | ({"_빠진": lost} if lost else {})
def to_json(value: Any) -> Any:
+22 -10
View File
@@ -30,6 +30,7 @@ import master_doc_trace as mt # noqa: E402 — scripts 길 = dc(855-F 셈 기
KEY, JOB, PRICE, REGEN = skc.KEY, skc.JOB, skc.PRICE, skc.REGEN
_SC = re.compile(r"^SC-\d{6}$")
_HOLE = re.compile(r"\{([^{}]+)\}") # 틀 구멍 `{S_규격}`
def _project() -> bool:
@@ -136,14 +137,9 @@ def _formula_of(doc: dict) -> dict | None:
def line(whole: Any, doc: dict, one: dict) -> dict[str, Any]:
"""로직 줄 기준 — 층 셈 = 수식 문서 셈 한 길(줄 옵션 = 문서 규칙 · `dc.line_doc` · 줄 = 문서 답 줄 ·
재료 = 셈 기록이 읽은 품목 · 옛 엔진 안 돎 · 855 2-C1 · 2-C5) · 수식 사본 있음 = 사본 · 없음(저장 전 새 문서) =
지금 M01 문서(저장 때 사본 찍음) · 프로젝트 층 · B09(단가 책) · `OLD` 시험 = 옛 길(B9 걸음 몫)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
재료 = 셈 기록이 읽은 품목 · 옛 엔진 안 돎 · 855 2-C1 · 2-C5) · 수식 사본 있음 = 사본 · 없음(저장 전 새 문서 ·
프로젝트 층) = 지금 M01 문서(저장 때 사본 찍음 · 프로젝트 층 옛 엔진 갈래 걷음 · 855-E 2-E4)."""
code, rate, picks = one["로직"], one.get("켜쌓기율"), one.get("고름")
if _project() or dsk.OLD.get():
got = labor.run_line(whole, code, one.get("입력값"), rate, picks)
return labor.drop_apart(got, one.get("자재표시"))
copy = _formula_of(doc)
if copy and getattr(whole, "_tag", None) == (copy.get("판"), copy.get("단가판")):
base, docs = copy["부름"].get(code), dc.docs_of(copy)
@@ -167,7 +163,7 @@ def line(whole: Any, doc: dict, one: dict) -> dict[str, Any]:
for n, x in enumerate(ans.get("줄") or [])
if n not in apart
]
found = _mats(mats, ans, picks)
found = _mats(mats, ans, picks, base)
return {"기준": got, "줄": lines, "재료": found, "까닭": None if got else dc.why(ans)}
@@ -183,9 +179,24 @@ def _traced(doc: dict, whole: Any, docs: dict, given: dict, copy: dict) -> dict:
}
def _mats(mats: list, ans: dict, picks: Any) -> list[dict[str, Any]]:
def _tied(link: dict, doc: dict) -> list[str]:
"""재료 조건 · 요소 키 틀 구멍에 든 입력 이름(화면 `releaseTied` 가 그 입력이 바뀌면 고름을 풂 · 문서 몫 ·
855-E 2-E4 — 옛 `logic_mats` 의 `걸림`)."""
texts = [v for v in (link.get("재료") or {}).values() if isinstance(v, str)]
texts += [str(link.get("키") or "")]
holes = {h for t in texts for h in _HOLE.findall(t)}
ids = {dc.md.var_id(v): v for v in doc.get("변수") or []}
names = {
str(ids[h].get("열쇠"))
for h in holes
if h in ids and (ids[h].get("연결") or {}).get("갈래") in ("입력", "선택")
}
return sorted(names)
def _mats(mats: list, ans: dict, picks: Any, doc: dict) -> list[dict[str, Any]]:
"""로직 자재(103-1) — 재료 금액 줄(`_mat_lines` · 단위 = 연결 단위 = 로직 원문 표기)마다
셈 기록이 읽은 품목 키 · 수량 · 단가 · 금액(별도계상 · 같은 품목 400 · `_inside` 가 읽음)."""
셈 기록이 읽은 품목 키 · 수량 · 단가 · 금액 · 걸린 입력(별도계상 · 같은 품목 400 · `_inside` 가 읽음)."""
calls, lines, out = ans.get("부름") or [], ans.get("줄") or [], []
for n, line, link in mats:
if n >= len(lines):
@@ -204,6 +215,7 @@ def _mats(mats: list, ans: dict, picks: Any) -> list[dict[str, Any]]:
}
| head
| {"품목": {"키": key} if key else None, "고름": str(n) in (picks or {})}
| {"걸림": _tied(link, doc)}
)
return out
+30 -160
View File
@@ -7,38 +7,36 @@
이름은 구조물 열 이름(따로 안 둠).
수량 = `null`(면적산출 알약 칸 값 · 로직 알약 「이름|단위」 · 자재 알약 「자재|MT키」) | `{손: 수}`
(손이 칸보다 앞섬) · 같은 로직 두 번 금지 · 입력값 = 그 로직 입력 이름만(빈 값 = 자동값).
금액: 기준 = 결과단위 그대로(서버 단독 · M01 엔진) · 반영 = 기준 × 수량 ÷ 배 · 돈 아닌 로직은
금액: 기준 = 결과단위 그대로(서버 단독 · 로직 줄 = 수식 문서 셈 `Labor_Copy.line`) · 반영 = 기준 × 수량 ÷ 배 · 돈 아닌 로직은
반영 없음 · 자재 기준 단가 = `master_material.element` 기본값 · 자재 줄에 값 열 다섯(`가격`) ·
기준단가가 된 칸 이름(`기준칸`)도 실음(43-3).
켜쌓기율(85-2) = 표 주문 「골쌓기 기준」 로직만 · % · 없음 = 100 · 그 로직 세부항목 줄 전부 수량 × 율
(`layered` · `run_line` 한 곳 → 문서 · 프로젝트 사본 · 서고 같은 함수).
(문서 규칙 `M02_Doc_Copy.line_doc` · 문서 · 프로젝트 사본 · 서고 같은 함수).
참조 줄(단가승격 · 사전조합 · 50-3) = 기준이 가리킨 문서 1 단위 값(펼침 `M02_Labor_Ref.Expand` · 안 줄
수량 = 같은 given 의 안 줄 알약 · 723-1) · 분모 = 그 문서 단위 · 배 1 · 알약 키 = `ref_id` · 같은 참조 두 번 금지.
짝(CLAUDE.md 5장 ①): 수량 · 반영 · 합 `settle` ↔ `M02_MasterTemplete_Labor_Calc.ts` —
거울 시험 `resources/tester/test_m02_labor_calc_mirror.py`.
규격 열(704-4) = 문서 `규격?` 칸 · 열마다 줄 수량(`M02_Labor_Spec` · settle `col`) · 계산값 `규격합`.
로직 자재(103-1) = 담은 로직 맨 위 층 호표 재료 줄(`logic_mats` · 줄마다 `재료`) ·
로직 자재(103-1) = 담은 로직 문서 재료 금액 줄(`Labor_Copy.line` · 줄마다 `재료`) ·
고름 = `{호표 차례: MT키}`(엔진 `choosing` 그대로) · 금액은 로직 재료비 안이라 합 · 알약에 안 더함(보기만) · 사용자 자재와
같은 품목 두 번은 [저장] 때 400.
승격(134-1) = 로직 줄 「단가승격」 표시(`true` 만 · 없음 = 단가산출) · 금액 무관 · B09 호표 몫.
자재 세 칸(148-4) = `MARKS` 허용 값만(그 밖 · 빈 것 버림 · 별도계상만 금액에 닿음) — 사용자 자재 = 줄 덧칸 ·
로직 자재 = 로직 줄 `자재표시 {호표 차례: {세 칸}}`(차례가 재료 줄인 것만 · 틀리면 버림) ·
빈 칸 = 읽을 때 `MARK_DEFAULT`(`mark_of` · 저장은 비움 · 옛 「일반」 = 버림 → 사급 · 162-1).
별도계상(222-1) = 그 자재 금액은 기준 · 합에서 빠지고 로직 `줄` 에서 지움(`drop_apart` · `settle` ·
별도계상(222-1) = 그 자재 금액은 기준 · 합에서 빠지고 로직 `줄` 에서 지움(문서 `합밖` · `settle` ·
짝 `Labor_Calc.ts`) · `재료` · `자재`(자재목록 · B08 수량)엔 남음.
고정 줄(705-1) = `{고정: {이름 · 규격 · 단위 · 단가 · 이음 · 출처}}` — 숫자 그대로 · 셈 `M02_Labor_Fixed`.
% 덧줄(149-4) = 식 「X * Y / 100」 덧줄에 덧칸 `율`(Y) · `규격`(「노무비의 %」 등 · `pct_extras`) — 표기만 ·
단위 · 수량 · 금액 그대로(「식 · 1」) · 화면이 율 · % 로 그림 · M01 시험계산 표도 이 함수.
옛 엔진 줄 셈(`run_line` · `pct_extras` · `logic_mats` · `layered` · `drop_apart`) = 855-E 2-E4 에서 걷음.
"""
from __future__ import annotations
import json
import re
from decimal import Decimal, InvalidOperation
from typing import Any
from M01_MasterData import M01_MasterData_Store as m01
from M01_MasterData import M01_MasterData_Store as m01 # noqa: F401 — scripts 길을 둠
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M02_MasterTemplete import M02_Labor_Fixed as fixed
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
@@ -48,7 +46,8 @@ from M02_MasterTemplete import M02_Labor_Spec as spec
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Material_Own as own
mf = m01.cm.mf
import master_base as mf # noqa: E402 — 바탕만(855-E 2-E4 · 엔진 몸 안 읽음) · scripts 길은 `m01` 이 둠
mm = mf.mp.mm
import master_cut as mcut # noqa: E402 — 끝수(751-3 · 품셈 1-2-2) · scripts 길은 `m01` 이 둠
@@ -62,7 +61,6 @@ MARKS = {
}
MARK_DEFAULT = {"자재구분": "사급", "별도계상": "별도계상", "운반비": "포함"} # 읽을 때 기본(162-1)
ALIAS_MAX = 40 # 별칭(44-6) 글자 수 상한 — 화면 칸과 같음
_BRACE = re.compile(r"\{([^{}]+)\}") # 품목 조건의 {입력}
def _bad(text: str) -> store.StoreError:
@@ -80,11 +78,26 @@ def _number(raw: Any) -> Decimal | None:
return got if got.is_finite() else None
def _specs(logic: dict) -> list[dict]:
"""로직 입력 꼴 — 흐름 로직은 「설계 때 정할 것」."""
if isinstance(logic.get("흐름"), dict):
return mf.inputs_of(logic)
return list(logic.get("입력") or [])
def _head(whole: Any, code: str) -> dict:
"""담을 로직 머리(855-E 2-E4 · M01 로직 줄 안 읽음) — 입력 이름 = 문서 입력 · 선택 열쇠 · 호표 = 문서
금액 줄(재료 줄 표지 · 차례 = 호표 차례) · 문서 없음 = FormulaError."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Item_Prices as prices
doc = dc.doc_of(whole, code)
if doc is None:
raise mf.FormulaError(f"없는 로직 「{code}」")
mats = {n for n, _, _ in prices._mat_lines(doc)}
return {
"키": code,
"이름": doc.get("이름"),
"결과단위": doc.get("결과단위"),
"입력": [{"이름": n} for n in prices.doc_inputs(doc)],
"호표": [
{"이름": x.get("이름"), "종류": "재료" if n in mats else ""}
for n, x in enumerate(doc.get("금액") or [])
],
}
def _qty(value: Any, where: str) -> dict | None:
@@ -136,13 +149,13 @@ def clean(doc: Any) -> dict[str, Any]:
continue
code = str(one.get("로직") or "")
try:
logic = whole.logic(code)
logic = _head(whole, code)
except mf.FormulaError as e:
raise _bad(f"{where} · {e}") from e
if code in seen:
raise _bad(f"{where} · 같은 로직을 두 번 담음 「{code}」")
seen.add(code)
names = {str(spec.get("이름")) for spec in _specs(logic)}
names = {str(x["이름"]) for x in logic["입력"]}
given = one.get("입력값") or {}
if not isinstance(given, dict):
raise _bad(f"{where} · 입력값이 묶음 아님")
@@ -254,23 +267,6 @@ def apart(one: Any) -> bool:
return mark_of(one, "별도계상") == "별도계상"
def drop_apart(got: dict[str, Any], shown: Any) -> dict[str, Any]:
"""로직 줄 답(`run_line`)에서 별도계상 로직 자재 빼기(222-1) — 그 재료 줄 금액을 기준에서 빼고
`줄`(일위대가 상세)에서 지움 · `재료`(자재목록 · 세 칸 고침)는 그대로.
ponytail: 「재료비의 %」 덧줄은 엔진 값 그대로(뺀 재료 몫 안 고침) — 그런 로직이 별도계상을 쓰면 엔진에 넘김."""
shown = shown if isinstance(shown, dict) else {}
lines = got.get("줄") or []
out = {
n
for m in got.get("재료") or []
if (n := m["차례"]) < len(lines) and apart(shown.get(str(n)))
}
if not out or not got.get("기준"):
return got
got = mcut.plain(got, out) # 기준 = 남은 줄 합(751-3 끝수 · 791-1 셈법)
return {**got, "기준": _json(got["기준"])}
def _mat_marks(value: Any, logic: dict) -> dict[str, dict[str, str]] | None:
"""로직 자재 세 칸(148-4) `{호표 차례: {세 칸}}` — 맨 위 층 재료 줄 차례 · 허용 값만 ·
빈 것 = None."""
@@ -297,28 +293,6 @@ def _rate(value: Any, code: str, where: str) -> int | float | None:
return int(rate) if rate == rate.to_integral_value() else float(rate)
def layered(got: dict[str, Any], rate: Any) -> dict[str, Any]:
"""엔진 답 × 켜쌓기율(85-2) — 세부항목 줄 전부 수량 · 금액 · 비목 · 비목 합 · 계 · 단가는 그대로."""
if rate in (None, 100) or "결과" in got:
return got
times = Decimal(str(rate)) / 100
def mul(value: Any) -> Any:
return value * times if isinstance(value, Decimal) else value
lines = [
{
**x,
"수량": mul(x.get("수량")),
"금액": mul(x.get("금액")),
"비목": {k: mul(v) for k, v in (x.get("비목") or {}).items()},
}
for x in got.get("줄") or []
]
sums = {k: mul(got[k]) for k in COSTS}
return {**got, "줄": lines, **sums, "계": sum(sums.values())}
def from_combo(key: str) -> dict[str, Any]:
"""옛 일위대가 조합(마스터 UA · 회사 UC · 개인 UP) → 일위대가 문서 몸 —
담은로직 · 단위 복사 · 입력값 {} · 수량 null · 자재 [] · `본뜬` = 그 조합(층 · 주인 · 키).
@@ -542,110 +516,6 @@ def calc(
return settle(_json({"줄": lines, "자재": mats}), doc, have)
def run_line(
whole: Any, code: str, given: Any, rate: Any = None, picks: Any = None, raw: bool = False
) -> dict[str, Any]:
"""로직 한 줄 기준(서버 단독 · M01 엔진 · 빈 입력 = 자동값 · × 켜쌓기율 · 고른 재료 = 엔진
`choosing`) — `{기준, 줄, 재료, 까닭}` · 돈 아닌 로직은 `{결과, 기준: None}`(반영 없음) ·
끝수 = 품셈 1-2-2(`master_cut` · 751-3) · `raw` = 엔진 날 값(B09 = 제 단가로 버림)."""
try:
logic = whole.logic(code)
auto = {k: v for k, v in m01.mau.values(whole, logic).items() if v is not None}
with mf.mp.choosing(picks):
got = layered(mf.run(whole, code, {**auto, **m01._dec(given or {})}), rate)
got = got if raw else mcut.engine(whole, code, got) # 율 곱 → 끝수(문서 셈 · 844-1)
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError) as e:
return {"기준": None, "까닭": str(e) or type(e).__name__}
if "결과" in got:
return {"결과": got["결과"], "기준": None, "까닭": None}
# 「줄」 = 그 로직 재료 · 노무 · 경비 줄(줄 누름 상세 · 50-4)
money = {k: got[k] for k in (*COSTS, "계")}
mats = logic_mats(whole, logic, got["줄"], picks)
lines = pct_extras(whole, logic, got["줄"], got.get("중간") or {})
out = {"기준": money, "줄": lines, "재료": mats, "까닭": None, **mcut.kept(got)}
return out
def pct_extras(whole: Any, logic: dict, lines: list[dict], env: dict) -> list[dict]:
"""% 덧줄(149-4) — 덧줄 식이 「X * Y / 100」 이면 그 엔진 줄(호표 수 뒤 같은 차례)에 덧칸
`율` = Y(엔진 마지막 env 로 셈) · `규격` = X 이름(「노무비의 %」 · 인력 줄 합 「인건비의 %」 ·
`줄.'이름'` · 중간값 「이름의 %」 · 그 밖 복합 = 빈 글). 다른 덧줄 · 흐름 로직 · 못 셈 = 그대로."""
if isinstance(logic.get("흐름"), dict):
return lines
out, head = list(lines), len(logic.get("호표") or [])
for n, add in enumerate(logic.get("덧줄") or []):
if head + n >= len(out):
break
try:
node = mf.parse(add.get("식") or "")
except mf.FormulaError:
continue
if not (
node[0] == "bin"
and node[1] == "/"
and node[3] == ("num", Decimal(100))
and node[2][0] == "bin"
and node[2][1] == "*"
):
continue # 금액 식(기계손료 등) · 조건부 % = 「식」 그대로
base, part = node[2][2], node[2][3]
try:
rate = mf.evaluate(part, dict(env), whole)
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
continue
if isinstance(rate, Decimal):
out[head + n] = {**out[head + n], "율": rate, "규격": _pct_base(base)}
return out
def _pct_base(node: tuple) -> str:
"""% 덧줄 밑수 이름 — B09 대가(`B09_Estimation_Labor_Source._base_of`)와 같은 말."""
if node[0] == "name":
return f"{node[1]}의 %" # 노무비 · 재료비 · 경비 · 중간값 이름
if node[0] == "field" and node[1] == ("name", "줄"):
return f"{node[2]}의 %"
parts = list(mf.walk(node))
if any(x[0] == "ref" and str(x[1]).startswith("LB") for x in parts) and not any(
x[0] == "name" and x[1] in COSTS for x in parts
):
return "인건비의 %"
return ""
def logic_mats(whole: Any, logic: dict, lines: list[dict], picks: Any) -> list[dict[str, Any]]:
"""로직 자재(103-1) — 맨 위 층 호표 재료 줄마다 엔진 답 줄(같은 차례) 그대로 · 금액은 로직
재료비 안(합에 안 더함) · `걸림` = 품목 조건에 든 입력 이름(중간값이면 입력 전부 — 그 입력이
바뀌면 화면이 고름을 풂 · 짝 `M02_Labor_LogicMats_Model.ts` `releaseTied`)."""
if isinstance(logic.get("흐름"), dict):
return [] # 흐름 로직 재료 자리는 입력 이름 — 이번엔 안 보임
names = {str(spec.get("이름")) for spec in _specs(logic)}
out = []
for n, item in enumerate(logic.get("호표") or []):
if item.get("종류") != "재료" or n >= len(lines):
continue
line, goods = lines[n], lines[n].get("품목")
try:
row = (whole.get(goods["키"]) if goods else None) or {}
except mf.FormulaError:
row = {}
cond = item.get("요소")
texts = cond.values() if isinstance(cond, dict) else [cond]
tied = {w for t in texts if isinstance(t, str) for w in _BRACE.findall(t)}
out.append(
{
"차례": n,
"이름": item.get("이름") or "",
"단위": item.get("단위") or "",
**{k: line.get(k) for k in ("수량", "단가", "금액", "까닭")},
"품목": goods,
"가격": {slot: row.get(slot) for slot in mm.SLOTS},
"고름": str(n) in (picks or {}),
"걸림": sorted(tied if tied <= names else names) if tied else [],
}
)
return out
def ref_line(ref: dict, got: dict[str, Any]) -> dict[str, Any]:
"""참조 줄 계산 답 — 분모 = 가리킨 문서 단위 · 배 1 · `안` = 사전조합 안 줄(한 층)."""
line = {"참조": ref, "이름": got.get("이름"), "알약": refs.ref_id(ref), "분모": got.get("단위")}
+13 -27
View File
@@ -13,6 +13,7 @@ from collections.abc import Callable
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Labor_Copy as lc
from M02_MasterTemplete import M02_Labor_Fixed as fixed
from M02_MasterTemplete import M02_Labor_Patch as patch
@@ -86,28 +87,18 @@ class Expand:
return {"이름": ref["키"], "단위": None, "기준": None, "까닭": why}
def _promote(self, doc: dict) -> dict[str, Any]:
"""옛 단가승격(SP · 134-2 앞 꼴) — 층 = 로직 줄과 같은 문서 셈(`Labor_Copy.line` · 옛 엔진 안 돎 ·
855 2-C5) · 프로젝트 사본 = 옛 길(B9 걸음 몫)."""
"""옛 단가승격(SP · 134-2 앞 꼴 · 저장소 0) — 로직 줄과 같은 문서 셈(`Labor_Copy.line` · 855 2-C5) ·
로직 재료 = 직접계산(별도계상 안 뺌 · 옛 셈과 같음) · 사본 옛 엔진 갈래 걷음(855-E 2-E4)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
line = (doc.get("담은로직") or [{}])[0]
if lc._project() or self.hands:
got = labor.run_line(
self.whole,
str(line.get("로직") or ""),
line.get("입력값"),
line.get("켜쌓기율"),
line.get("고름"),
)
else: # 옛 승격 = 로직 자재 직접계산(별도계상 안 뺌 · 옛 셈과 같음)
code = str(line.get("로직") or "")
try:
items = self.whole.logic(code).get("호표") or []
except Exception: # noqa: BLE001 — 없는 로직 = 셈이 까닭
items = []
direct = {"별도계상": "직접계산"}
marks = {str(n): direct for n, x in enumerate(items) if x.get("종류") == "재료"}
got = lc.line(self.whole, {}, {**line, "로직": code, "자재표시": marks})
code = str(line.get("로직") or "")
money = (dc.doc_of(self.whole, code) or {}).get(
"금액"
) or [] # 문서 금액 줄 차례 = 호표 차례
direct = {"별도계상": "직접계산"}
marks = {str(n): direct for n, x in enumerate(money) if x.get("비목") == "재료비"}
got = lc.line(self.whole, {}, {**line, "로직": code, "자재표시": marks})
times = labor._number(doc.get("배")) or Decimal(1)
base = got.get("기준")
why = got.get("까닭") or (None if base else "돈 아닌 로직")
@@ -133,16 +124,11 @@ class Expand:
def _logic(self, one: dict, pill: dict | None, doc: dict | None = None) -> dict[str, Any]:
"""사전조합 안 로직 줄 — 일위대가 로직 줄과 같은 `Labor_Copy.line`(문서 셈) · 배는 물량 알약 것 ·
굳힌 덮개 줄(프로젝트 사본) = 옛 길(B9 걸음 몫)."""
사본 굳힌 덮개 줄(`굳힌` · B9-5 뒤 0) 옛 엔진 갈래 걷음(855-E 2-E4)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
pill, fz = pill or {}, one.get("굳힌")
if isinstance(fz, dict) and fz.get("키"): # 사본 굳힌 덮개 줄(740-1 · `Item_Sangeun`)
got = labor.run_line(
self.whole, fz["키"], fz.get("입력값"), fz.get("켜쌓기율"), fz.get("고름") or None
)
got = labor.drop_apart(got, fz.get("자재표시"))
elif one.get(patch.FIELD): # 줄 덮개(715-3) = 이름 없는 단가산출 · 별도계상까지
pill = pill or {}
if one.get(patch.FIELD): # 줄 덮개(715-3) = 이름 없는 단가산출 · 별도계상까지
got = patch.run(self.whole, one, self.read)
else: # 별도계상 로직 자재 뺌(222-1) · 수식 사본 SC = 문서 셈(802-4a)
got = lc.line(self.whole, doc or {}, one)
+2 -2
View File
@@ -21,9 +21,9 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from M01_MasterData import M01_MasterData_Store as m01
from M01_MasterData import M01_MasterData_Store as m01 # noqa: F401 — scripts 길을 둠
mf = m01.cm.mf
import master_base as mf # noqa: E402 — 바탕만(855-E 2-E4 · 엔진 몸 안 읽음) · scripts 길은 `m01` 이 둠
import master_cut as mcut # noqa: E402 — 끝수(751-3) · scripts 길은 `m01` 이 둠
mm = mf.mp.mm
+3 -3
View File
@@ -33,7 +33,7 @@ from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
from M02_MasterTemplete import M02_Template_Layers as layers
mf = m01.cm.mf
import master_base as mf # noqa: E402 — 바탕만(855-E 2-E4 · 엔진 몸 안 읽음) · scripts 길은 `m01` 이 둠
import master_doc as md # noqa: E402 — scripts 길은 `m01` 이 둠
import master_doc_calc as mc # noqa: E402
import master_doc_link as ml # noqa: E402
@@ -113,7 +113,7 @@ def _table_reps(whole: Any, ref: str, cond: str, unit: str) -> list[tuple[Any, s
"""표 `ref` 조건 칸 `cond` 줄마다 (값, 글) — 범위 줄은 위 끝(없으면 아래 끝 · 드는 값)."""
try:
table = whole.get(ref)
except m01.cm.mf.FormulaError:
except mf.FormulaError:
return []
ranged = table.get("조건", {}).get(cond) == "범위"
out: dict[Any, str] = {}
@@ -374,7 +374,7 @@ def sheet(key: str, change: dict) -> dict:
files, whole = m01.loaded()
try:
m01_doc.head(key) # 없는 · 로직 아닌 키 = 옛 `Master.logic` 과 같은 까닭 글
except m01.cm.mf.FormulaError as e:
except mf.FormulaError as e:
raise m01.StoreError(404, str(e)) from e
doc = m01_doc.docs()[key]
given, ax = _given(whole, doc, change)
+7 -6
View File
@@ -20,14 +20,15 @@ from __future__ import annotations
from typing import Any
import master_machine_crew as mcrew
from M01_MasterData import M01_MasterData_Doc as m01doc
from M01_MasterData import M01_MasterData_Store as store
from M02_MasterTemplete import M02_Labor_Inputs as li
from M02_MasterTemplete import M02_MyMachine as mym
cm = store.cm
import master_base as mb # noqa: E402 — 바탕만(855-E 2-E4) · scripts 길은 `store` 가 둠
import master_machine_crew as mcrew # noqa: E402
_PLAIN = {
"기계",
"지역",
@@ -184,7 +185,7 @@ def hourly(key: str) -> dict[str, Any]:
return {"ok": False, "reason": f"「{key}」 는 기계 아님"}
try:
row = (whole := mym.whole()).get(key)
except cm.mf.FormulaError as e:
except mb.FormulaError as e:
return {"ok": False, "reason": str(e)}
if mym.mine(key):
return mym.hourly(row, whole)
@@ -228,7 +229,7 @@ def doc_sums(row: dict, logic: dict, index: Any) -> dict | None:
if not got["셈됨"]:
why = got.get("까닭") or " · ".join(m["글"] for m in got["표지"]) or "셈 못 함"
return {"ok": False, "reason": why, "로직": logic["키"]}
return {"ok": True, "합": {k: float(got[k]) for k in (*cm.mf.COST_ITEMS, "계")}}
return {"ok": True, "합": {k: float(got[k]) for k in (*mb.COST_ITEMS, "계")}}
#: {키: (색인, 줄)} — 색인이 바뀌면 비움 · 꺼낼 때 `is` 확인(옛 색인 주소 재사용 · 옛 값 막음 · 854-1)
@@ -241,7 +242,7 @@ def brief(keys: list[str]) -> list[dict[str, Any]]:
마스터를 다시 읽지 않고 색인 위에서 셈 · 색인마다 메모) · 키 · 원문번호로 찾음 · 없는 키 = 뺌."""
from M02_MasterTemplete.M02_Item_Prices import to_json
index, mf = store.loaded()[1], cm.mf
index, mf = store.loaded()[1], mb
# ponytail: 통째 비움 · 기계 수(655)의 세 배
if _BRIEF_OF[0] is not index or len(_BRIEF) > 2000:
_BRIEF.clear()
@@ -273,7 +274,7 @@ def combo(main: str, part: str) -> tuple[str, str] | None:
(GC000270 · 271) 고르기에 있을 때만 · 부착 기계 줄은 제 시간당(손료만)."""
try:
codes = [str(store.loaded()[1].get(k).get("원문번호") or "") for k in (main, part)]
except cm.mf.FormulaError:
except mb.FormulaError:
return None
rows = _rows()
fits = any(
+9 -76
View File
@@ -1,88 +1,21 @@
"""M02 단가산출(SK) 더한 기초 블록 [연결 끊기] · [다시 잇기](PLAN 796-2e · 요구 659-3 · 656-1).
"""M02 단가산출(SK) 더한 기초 옛 [연결 끊기](PLAN 796-2e) — 받지 않음(855-E 2-E4).
더한 기초 = 더한줄 로직(`종류: 로직`). 기본 = 연결 — 이 SK 의 로직 사본(`M02_Sangeun_Copy`)이 닿는 그 기초
(원본 바뀜은 [재생성]·[다시 잇기]에서 따라옴 · 자동 아님 · 보기만).
끊음 = 더한줄 칸 `끊음` {시점, 로직 [M01 줄]} — 끊는 때 그 기초가 닿는 닫힌 묶음(하위 로직 · 찾기 표 ·
요율 · 사본 줄 그대로 = 금액 그대로)을 이 SK 안 자기 사본으로 굳힘 → 그 줄만 고침:
칸 `수식고침`(796-2b 와 같은 꼴 · 같은 `eqm.apply`)을 그 기초 줄에 얹어 셈(`Calc.sub_run`).
[재생성] = 끊은 기초의 줄은 안 바꿈(자원 단가만 — 단가는 SK 사본 `단가` · [단가 갱신] 한 길).
다시 잇기 = `끊음` · `수식고침` 뗌 + 표지 `다시잇기`(서버만 · 셈·저장 첫머리 `Copy.settle` 이 그 기초가 닿는
닫힌 묶음을 지금 M01 줄로 갈음하고 표지 뗌 — 고친 것 버림).
화면 길(끊기 · 다시 잇기 · 끊은 기초 수식 탭)은 걷음(894) — 남은 것 = 저장 문서의 `끊음` · `수식고침` 꼴 · 셈.
저장 = SK [저장](서버가 다시 얹어 검사 · 셈 · 브라우저 값 안 받음 — 끊음 줄은 사본과 같은 `taken` 꼴 검사).
옛 끊음 = 더한줄 로직 칸 `끊음` {시점, 로직 [M01 줄]} + 그 줄 `수식고침` — 굳힌 로직 줄에 엔진 수식 고침을
얹던 길 · 화면 길은 894 에서 걷음 · 저장본 0 — 받으면 400.
"""
from __future__ import annotations
from typing import Any
from M02_MasterTemplete import M02_Sangeun_Copy as skc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from M02_MasterTemplete import M02_Sangeun_Equation as eqm
CUT, EDIT = "끊음", eqm.KEY
MANY = 400 # 끊은 기초가 닿는 줄 상한
_OWN: dict[int, tuple[Any, Any, Any]] = {}
def is_block(one: Any) -> bool:
"""더한 기초 = 더한줄 로직(참조 · 고정 · 자원 줄 아님)."""
return isinstance(one, dict) and one.get("종류") == "로직" and bool(one.get("로직"))
def clean(raw: dict, where: str) -> dict:
"""`sd._added` 가 부름 — 끊음 · 수식고침 꼴만(뜻 검사는 셈 · 저장 `strict`)."""
cut = raw.get(CUT)
if not cut:
if raw.get(EDIT):
raise sd.DocError(f"{where} · 수식 고침은 연결을 끊은 기초만")
return {}
rows = cut.get("로직") if isinstance(cut, dict) else None
code = str(raw.get("로직"))
if any(raw.get(k) not in (None, {}, []) for k in sd.BODY):
raise sd.DocError(f"{where} · 넣은 SK 몸은 이미 이 SK 안 사본 — 연결 끊기 없음")
if (
not isinstance(rows, list)
or len(rows) > MANY
or not all(isinstance(r, dict) and r.get("키") for r in rows)
):
raise sd.DocError(f"{where} · 끊은 기초 사본 꼴이 틀림")
rows = [r for r in rows if str(r["키"])[:2] not in skc.RES] # 단가 = SK 사본 한 곳
if code not in {str(r["키"]) for r in rows}:
raise sd.DocError(f"{where} · 끊은 기초 사본에 「{code}」 줄 없음")
return {CUT: {"시점": str(cut.get("시점") or ""), "로직": rows}} | eqm.clean(raw, {})
def own(one: dict, whole: Any) -> Any:
"""끊은 기초의 셈 색인 — `whole` 위에 자기 사본 줄(끊음 아님 = `whole` 그대로)."""
cut = one.get(CUT)
if not isinstance(cut, dict):
return whole
hit = _OWN.get(id(cut))
if hit and hit[0] is cut and hit[1] is whole:
return hit[2]
if len(_OWN) > 32: # ponytail: 통째 비움 · 끊은 기초가 많아 느려지면 LRU 로
_OWN.clear()
got = skc.Copy(whole, skc._rows(cut))
_OWN[id(cut)] = (cut, whole, got)
return got
def row_of(whole: Any, one: dict, edits: list | None = None) -> tuple[dict, list[str], Any]:
"""(끊은 기초 줄 + 수식 고침, 못 얹은 까닭, 그 기초 셈 색인) — `edits` None = 그 기초 자기 고침."""
mine = own(one, whole)
row = mine.logic(str(one["로직"]))
use = one.get(EDIT) if edits is None else edits
if not use:
return row, [], mine
new, why = eqm.apply(row, use, mine)
return new, why, mine
def strict(doc: dict, whole: Any) -> None:
"""저장 — 끊은 기초 고침이 못 얹히면 400."""
for at, one in enumerate(doc.get("더한줄") or [], 1):
if is_block(one) and one.get(EDIT):
why = row_of(whole, one)[1]
if why:
raise sd.DocError(f"더한줄 {at}째 수식 고침 못 얹음 — " + " · ".join(why))
"""`sd._added` 가 부름 — 옛 칸 `끊음` · `수식고침` 이 있으면 400."""
if raw.get(CUT) or raw.get(EDIT):
raise sd.DocError(
f"{where} · 연결 끊기 · 수식고침(옛 칸) — 받지 않음 · 단가산출 수식 문서로 고침"
)
return {}
+30 -304
View File
@@ -2,8 +2,8 @@
셈(`run`) = 수식 사본(`M02_Doc_Sk.copy_of` — 따로 = 저장 문서 · 파생 = 기초 문서 + 줄 규칙)을 문서 계산기로 ·
기준 · 1 단위 · 줄 · 비목 · 끝수 = 문서 답 · 옛 엔진 안 돎 · 수식 사본 없음(바탕 참조) · 옛 칸 고침(덮개 ·
뺀줄 · 더한줄 · 수식고침 · 식 칸) = 못 셈 + 까닭 하나 · 굳힌 사본(B09 · 구조물 사본 GX9) = 옛 길(`_frozen` ·
`resolve` 바탕 사슬 · `_bundles` · `_rated` 율 더한줄 — B9 걸음 몫 · `Doc_Import._ctx` 도 고친 줄 도구를 씀).
뺀줄 · 더한줄 · 수식고침 · 식 칸) · 굳힌 옛 사본(수식 사본 없음 · 저장소 0) = 못 셈 + 까닭 하나(옛 엔진 길 ·
`resolve` 바탕 사슬 걷음 · 855-E 2-E4).
계산 자리(CLAUDE.md 5장 ③) = 서버 단독 · 화면은 셈 길(저장 안 함 · 최신 응답만).
저장(`clean_doc`) = 꼴 검사 + 참조 위 층 · 있는 문서 · 순환 422 · 바탕 머리 = 기초 문서(855 L2 ⓑ-3).
SK 단위 환산(728-2) = 배 = 바탕 기준단위(「100본」) → SK 단위(`master_unit.swap` ·
@@ -14,44 +14,18 @@ SK 단위 환산(728-2) = 배 = 바탕 기준단위(「100본」) → SK 단위(
from __future__ import annotations
import hashlib
import json
import re
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_Doc_Sk as dsk # 수식 사본(802-4a)
from M02_MasterTemplete import M02_Labor_Doc as labor, M02_Labor_Fixed as fixed
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Block as blk
from M02_MasterTemplete import M02_Sangeun_Const as const, M02_Sangeun_Copy as skc
from M02_MasterTemplete import M02_Sangeun_Doc as sd, M02_Sangeun_Equation as eqm
from M02_MasterTemplete import M02_Sangeun_Doc as sd
COSTS = labor.COSTS
Ref = dict[str, Any]
_SHARED = ("_market", "_by_class", "_found") # 마스터에만 따르는 자재 색인 · 찾기 답
class _Over:
"""M01 색인 위에 고친 줄 하나 — `logic(키)` 만 가로챔(그 밖 그대로 · 색인 안 고침)."""
def __init__(self, whole: Any, key: str, row: dict) -> None:
self._whole, self._key, self._row = whole, key, row
def logic(self, ref: str) -> dict:
return self._row if ref == self._key else self._whole.logic(ref)
def __getattr__(self, name: str) -> Any:
return getattr(self._whole, name)
def __setattr__(self, name: str, value: Any) -> None:
"""자재 색인(`master_material`)은 속 M01 색인에 둠 — 셈마다 다시 안 지음(792-2) ·
M01 파일 자국이 바뀌면 새 색인 = 새로 지음 · 그 밖은 이 덮개에만."""
if name in _SHARED:
setattr(self._whole, name, value)
else:
super().__setattr__(name, value)
def _fail(e: sd.DocError) -> store.StoreError:
@@ -99,153 +73,6 @@ def ratio_of(doc: dict, row: dict, whole: Any) -> Decimal:
return swap["배"]
def fingerprint(row: dict) -> str:
raw = json.dumps(row, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
# ── 바탕 사슬 → 고친 줄 ─────────────────────────────────────────────────
def _base_of(doc: dict, whole: Any, read: Any, trail: tuple[str, ...]) -> dict[str, Any]:
"""이 SK 가 얹힐 바탕 — {줄, 고름, 자재표시, 입력값, 켜쌓기율, 짝잃음}."""
base = doc.get("바탕")
empty = {"고름": {}, "자재표시": {}, "입력값": {}, "켜쌓기율": None, "짝잃음": []}
if not base or "로직" in base: # 사본(795-1) · 가져온 식 · 그 위 수식 고침(796-2b)
try:
row = skc.over(doc, whole).logic(base["로직"]) if base else sd.empty_row(doc)
except Exception as e: # noqa: BLE001 — 엔진 FormulaError
raise sd.DocError(f"바탕 로직 · {e}") from e
if any(x.get("참조") for x in row.get("호표") or []): # 가져온 식 안쪽 산근(797-1) 값 채움
from M02_MasterTemplete.M02_Labor_Expand import Expand
row = {**row, "호표": [dict(x) for x in row["호표"]]}
_bundles(row, whole, Expand(whole, read), trail)
row, lost = eqm.on(row, doc, skc.over(doc, whole))
return {**empty, "줄": row, "짝잃음": lost}
ref = base["참조"]
rid = refs.ref_id(ref)
if rid in trail:
keys = [t.rsplit("|", 1)[-1] for t in (*trail, rid)]
raise sd.DocError("순환 — " + " → ".join(keys), 422)
if len(trail) >= refs.DEPTH:
raise sd.DocError(f"바탕 사슬이 {refs.DEPTH}단을 넘음", 422)
parent = read(ref)
if not isinstance(parent, dict):
raise sd.DocError(f"없는 바탕 「{ref.get('키')}」")
up = resolve(parent, whole, read, (*trail, rid))
lost = [{**x, "바탕": ref.get("키")} for x in up["짝잃음"]]
return {**up, "짝잃음": lost}
def resolve(
doc: dict,
whole: Any,
read: Any = refs.read_ref,
trail: tuple = (),
given: dict | None = None,
line: bool = False,
) -> dict[str, Any]:
"""SK 문서 → 고친 줄 `{줄, 고름, 자재표시, 정체, 짝잃음, 입력값, 켜쌓기율, 배, 바탕판}` ·
`trail` = 지나온 참조 이름표(순환 · 깊이 422) · `given` = 공통 옵션(더한줄 로직 입력)."""
base = _base_of(doc, whole, read, trail)
common = {**base["입력값"], **(doc.get("입력값") or {}), **(given or {})}
doc, lack = _fill(doc, whole, common)
got = sd.patched(base["줄"], doc, base["고름"], base["자재표시"])
items = got["줄"]["호표"]
if not line:
_direct(got["자재표시"], items)
for at, cid in enumerate(got["정체"][: len(items)]):
hit = re.match(r"^add:#(\d+)$", cid)
if hit and int(hit[1]) in lack:
items[at] = _gap(items[at], lack[int(hit[1])])
elif hit and sd.sub_patched(doc["더한줄"][int(hit[1])]): # 고친 둘째 기초 = 셈한 값묶음
sub = sub_run(doc["더한줄"][int(hit[1])], whole)
got["짝잃음"] += [{**x, "cid": f"{cid}/{x['cid']}"} for x in sub["짝잃음"]]
items[at] = _bundled(items[at], sub)
rate = doc.get("켜쌓기율", base["켜쌓기율"])
return {
**got,
"채운더한줄": doc["더한줄"],
"짝잃음": base["짝잃음"] + got["짝잃음"],
"입력값": {**base["입력값"], **(doc.get("입력값") or {})},
"켜쌓기율": rate,
"배": ratio_of(doc, base["줄"], whole),
"바탕판": fingerprint(base["줄"]),
}
def _direct(marks: dict, items: list) -> None:
"""SK 재료 줄 별도계상 빈 칸 = 직접계산(747-1 · 제자리) — 다른 두 칸은 그대로."""
for n, item in enumerate(items):
if item.get("종류") == "재료":
marks[str(n)] = {"별도계상": "직접계산", **labor.marks(marks.get(str(n)))}
# ── 못 셈 줄 = 그 줄만 빠짐(725-1 · 725-2) ─────────────────────────────────
NO_QTY = "수량 없음" # `M02_Labor_Expand.NO_QTY` 와 같은 글(가져오기 둘레 피함)
NO_QTY_WHY = "수량 없음 — 쓰는 자리에서 연결"
def _defaults(whole: Any, code: str) -> dict:
"""로직 기본값 = M01 견본 입력(`/m01/logic/auto` 와 같은 길)."""
from M01_MasterData import M01_MasterData_Store as m01
try:
got = {"값": m01.mau.values(whole, whole.logic(code))}
except Exception: # noqa: BLE001 — 없는 로직 · 자동값 못 셈 = 기본값 없음
return {}
return got.get("값") or {}
def _fill(doc: dict, whole: Any, common: dict) -> tuple[dict, dict[int, str]]:
"""더한줄 로직 입력 = 줄 값 › 공통 옵션 › 로직 기본값 — (채운 사본, {더한줄 차례: 까닭})."""
adds, lack = [], {}
for k, one in enumerate(doc.get("더한줄") or []):
if one.get("종류") != "로직":
adds.append(one)
continue
try:
names = [str(s.get("이름")) for s in whole.logic(one["로직"]).get("입력") or []]
except Exception: # noqa: BLE001 — 없는 로직 = 검사(`sd.clean`)가 먼저 막음
names = []
mine = dict(one.get("입력값") or {})
blank = [n for n in names if mine.get(n) is None or not str(mine[n]).strip()]
auto = _defaults(whole, one["로직"]) if blank else {}
for n in blank:
mine.pop(n, None)
for v in (common.get(n), auto.get(n)):
if v is not None and str(v).strip():
mine[n] = v
break
miss = [n for n in names if n not in mine]
if miss:
lack[k] = f"입력 「{miss[0]}」 없음"
adds.append({**one, "입력값": mine})
return {**doc, "더한줄": adds}, lack
def _gap(item: dict, why: str) -> dict:
"""못 셈 줄 → 0 값묶음 줄(차례 그대로 · 계에 안 듦) + `빠짐` 까닭."""
zero = dict.fromkeys(COSTS, Decimal(0))
head = {k: item.get(k) or "" for k in ("이름", "단위")}
return {**head, "종류": "로직", "요소": None, "수량": item["수량"], "값묶음": zero, "빠짐": why}
# ── 둘째 기초 세부(727-2) ─────────────────────────────────────────────────
def sub_run(one: dict, whole: Any, patched: bool = True) -> dict[str, Any]:
"""더한줄 로직 하나(둘째 기초 · 옛 칸) — 수식 사본 없음 = 못 셈 + 까닭(855 2-C1 · 옛 엔진 안 돎)."""
return {"기준": None, "까닭": dsk.OLD_WHY, "정체": [], "짝잃음": [], "바탕판": ""}
def _bundled(item: dict, sub: dict) -> dict:
"""고친 둘째 기초 줄 → 셈한 1 기준단위 노 · 재 · 경 `값묶음` 줄(수량 그대로) ·
못 셈 = `_gap`."""
if not sub.get("기준"):
return _gap(item, str(sub.get("까닭") or "돈 아닌 로직"))
head = {k: item.get(k) or "" for k in ("이름", "단위")}
bundle = {k: Decimal(str(sub["기준"][k])) for k in COSTS}
return {**head, "종류": "로직", "요소": None, "수량": item["수량"], "값묶음": bundle}
def tag_of(whole: Any, code: str) -> str:
"""꼬리표 = 기초 원문번호(「9-12-1」 · 문서 이름표 855 L2 ⓑ-3) · 없으면 키."""
try:
@@ -254,30 +81,6 @@ def tag_of(whole: Any, code: str) -> str:
return code
def _bundles(row: dict, whole: Any, expand: Any, trail: tuple) -> None:
"""더한줄 참조 · 고정 줄 `값묶음` = 1 단위 노 · 재 · 경 — 못 셈 줄 = `_gap`(나머지 셈 계속)."""
for at, item in enumerate(row["호표"]):
if item.get("값묶음") is not None or not ("참조" in item or "고정" in item):
continue
if "참조" in item and item.get(
"기준"
): # 가져온 식 산근 속 산근(797-1) — 부르는 쪽 단가기준
sub = expand(item["참조"], trail, item["기준"])
else:
sub = expand(item["참조"], trail) if "참조" in item else fixed.line(whole, item["고정"])
item["이름"] = item.get("이름") or sub.get("이름") or ""
item["단위"] = item.get("단위") or sub.get("단위") or ""
if sub.get("기준") is None:
why = str(sub.get("까닭") or "")
row["호표"][at] = _gap(item, NO_QTY_WHY if NO_QTY in why else why)
continue
item["값묶음"] = {k: Decimal(str(sub["기준"][k])) for k in COSTS}
if item.get("참조비목") in COSTS: # 안쪽 산근의 그 비목만(엑셀이 비목마다 한 줄로 부른 때)
item["값묶음"] = {
k: v if k == item["참조비목"] else Decimal(0) for k, v in item["값묶음"].items()
}
def _row_of(doc: dict, whole: Any) -> dict:
"""배가 읽는 바탕 머리(셈 아님) — 바탕 로직 = 기초 문서 머리(`sd.doc_row` · 855 L2 ⓑ-3) ·
없음 = 빈 줄(가져온 식 = 그 줄)."""
@@ -288,6 +91,10 @@ def _row_of(doc: dict, whole: Any) -> dict:
raise sd.DocError(f"바탕 로직 · {e}") from e
#: 굳힌 옛 사본 SK(수식 사본 없음 · 바탕 로직이 M01 문서에 없음 · 저장소 0) — 옛 엔진 셈 걷음(855-E 2-E4)
FROZEN_WHY = "굳힌 옛 사본 — 수식 사본 없음 · [재생성] 으로 새로 가져와야 셈"
def run(
doc: dict,
whole: Any,
@@ -300,18 +107,15 @@ def run(
"""SK 셈(저장 안 함 · 855 2-C1) = 수식 사본 문서 셈 한 길 — 기준 · 1 단위 · 줄 · 비목 · 끝수 모두
문서 답(`M02_Doc_Sk.run`) · 줄 `cid` = 「금액#n」(문서 금액 줄 차례) · 줄 `단위` = 문서 금액 줄 단위 ·
수식 사본 없음(바탕 참조 · 옛 칸 덮개 · 더한줄 …) = 못 셈 + 까닭 하나(옛 엔진 안 돎 · 올림 없음) ·
굳힌 사본(`M02_Doc_Sk.frozen` — B09 · 구조물 사본) = 옛 길(`_frozen` · B9 걸음 몫).
`given` · `_opts`(detail · line · seen) = 옛 길 손님 꼴 — 문서 셈은 안 씀(옛 길도 금액은 문서 답 ·
2-E2 에서 부르는 쪽과 같이 걷음). 틀린 단위 환산 = `sd.DocError`."""
if dsk.frozen(doc):
return _frozen(doc, whole, given, read, expand, trail)
굳힌 옛 사본(`M02_Doc_Sk.frozen`) = 못 셈 + `FROZEN_WHY`(옛 엔진 길 걷음 · 855-E 2-E4).
`given` · `read` · `expand` · `trail` · `_opts` = 부르는 쪽 꼴 — 문서 셈은 안 씀. 틀린 단위 환산 = `sd.DocError`."""
whole = skc.over(doc, whole)
base = doc.get("바탕") or {}
tag = tag_of(whole, base["로직"]) if "로직" in base else (base.get("참조") or {}).get("키")
head = {"짝잃음": [], "빠진줄": [], "꼬리표": tag}
copy = dsk.copy_of(doc, whole)
copy = None if dsk.frozen(doc) else dsk.copy_of(doc, whole)
if copy is None:
why = dsk.OLD_WHY if dsk.own(doc) else dsk.REF_WHY
why = FROZEN_WHY if dsk.frozen(doc) else dsk.OLD_WHY if dsk.own(doc) else dsk.REF_WHY
none = {"기준": None, "1단위": None, "배": Decimal(1), "줄": [], "정체": []}
return {**head, **none, "까닭": why, "수식셈": {"셈됨": False, "따로": False, "까닭": why}}
row = _row_of(doc, whole)
@@ -341,91 +145,6 @@ def run(
return out | ({"결과": got["결과"]} if "결과" in got else {})
def _frozen(doc: dict, whole: Any, given: Any, read: Any, expand: Any, trail: tuple) -> dict:
"""굳힌 사본 SK(수식 없음) 옛 엔진 셈 — 2-C1 전 `run` 그대로(굳힌 줄 = 덮개 · 더한줄 없음) · B9 몫."""
from M02_MasterTemplete.M02_Labor_Expand import Expand
got = resolve(doc, whole := skc.over(doc, whole), read, trail, given)
row = {**got["줄"], "호표": [dict(x) for x in got["줄"]["호표"]]}
_bundles(row, whole, expand or Expand(whole, read), trail)
gaps = {at: x for at, x in enumerate(row["호표"]) if x.get("빠짐")}
key = str(doc.get("키") or "SK-000000")
names = {str(i.get("이름")) for i in row.get("입력") or []}
values = {k: v for k, v in {**got["입력값"], **(given or {})}.items() if k in names}
args = (
_Over(whole, key, {**row, "키": key}),
key,
values,
got["켜쌓기율"],
got["고름"] or None,
)
out = labor.run_line(*args)
lost = _rated(row, out.get("줄") or [], got["정체"], got["자재표시"], got["켜쌓기율"])
if lost is not None: # 율 더한줄(778-4) — 밑을 넣고 다시
out = labor.run_line(*args)
gap = {"단가": None, "금액": None, "비목": {}}
lines = [
{**line, "cid": cid, **({**gap, "까닭": gaps[at]["빠짐"]} if at in gaps else {})}
for at, (cid, line) in enumerate(zip(got["정체"], out.get("줄") or []))
]
out = labor.drop_apart({**out, "줄": lines}, got["자재표시"])
base = out.get("기준")
gone = [
{"cid": got["정체"][at], "이름": x.get("이름") or "", "까닭": x["빠짐"]}
for at, x in gaps.items()
]
head = {k: got[k] for k in ("정체", "바탕판", "배")} | {"짝잃음": got["짝잃음"] + (lost or [])}
unit = {k: Decimal(str(v)) / got["배"] for k, v in base.items()} if base else None
tag = tag_of(whole, str((doc.get("바탕") or {}).get("로직") or ""))
return {**out, **head, "1단위": unit, "빠진줄": gone, "꼬리표": tag}
def _group(item: dict, line: dict) -> str | None:
"""율 밑 묶음(778-4) — 인력 · 재료 · 장비(기계경비 로직 · 기계 이음 고정 · 기계 줄) · 그 밖 None."""
if isinstance(item.get("고정"), dict):
return fixed.group_of(item["고정"])
if line.get("장비"):
return "장비"
return {"인력": "인력", "재료": "재료", "기계": "장비"}.get(str(item.get("종류")))
def _rated(row: dict, eng: list, ids: list, marks: dict, stack: Any = None) -> list[dict] | None:
"""율 더한줄(778-4) `값묶음` = {비목: 밑 ÷ 100} — 한 번 돈 엔진 줄(`eng` · 정체 `ids`)로
`fixed.rate_base`(별도계상 재료 뺌 · 앞 율 줄 차례로 · 켜쌓기율 몫 뗌) · 제자리 · 율 줄 없음 = None ·
돌려줌 = 짝잃음(없는 기준 줄)."""
items = row["호표"]
at = [i for i, x in enumerate(items) if (x.get("고정") or {}).get("비율")]
if not at:
return None
rows = [
{"키": cid, "묶음": _group(items[i] if i < len(items) else {}, x), "비목": x.get("비목")}
for i, (cid, x) in enumerate(zip(ids, eng))
if i not in at
and not (
i < len(items) and items[i].get("종류") == "재료" and labor.apart(marks.get(str(i)))
)
]
times = Decimal(str(stack)) / 100 if stack not in (None, 100) else Decimal(1)
lost = []
for i in at:
rate, qty = items[i]["고정"]["비율"], Decimal(str(items[i]["수량"]))
if isinstance(rate["기준"], list):
lost += [
{"cid": ids[i], "까닭": f"율 기준 줄 없음 「{k}」"}
for k in rate["기준"] or [""]
if fixed.split_key(k)[0] not in ids
]
base = fixed.rate_base(rate["기준"], rows) / times
items[i] = {
**items[i],
"값묶음": {**dict.fromkeys(COSTS, Decimal(0)), rate["비목"]: base / 100},
}
rows.append(
{"키": ids[i], "묶음": None, "비목": {rate["비목"]: base * qty / 100}, "율": True}
)
return lost
def unit(doc: dict, whole: Any, expand: Any, trail: tuple) -> dict[str, Any]:
"""펼침(`Expand`) 한 칸 — `{이름, 단위, 기준(1 단위), 까닭, 줄, 짝잃음}` · 못 셈 = 까닭."""
head = {"이름": doc.get("이름"), "단위": doc.get("단위")}
@@ -496,15 +215,23 @@ def _check_refs(doc: dict, here_: refs.Here) -> None:
refs._no_loop(ref, [me, ref])
def _head_of(doc: dict, whole: Any) -> dict[str, Any]:
"""저장 검사가 읽는 바탕 — 로직 바탕 · 옛 칸 고침 없음 = 기초 문서 머리(입력 이름 · 결과단위 ·
855 L2 ⓑ-3 로직 줄 안 읽음) · 그 밖(가져온 식 · 참조 · 옛 칸) = 바탕 사슬(`_base_of`)."""
if "로직" in (doc.get("바탕") or {}) and not dsk.patched(doc):
try:
return {"줄": sd.doc_row(whole, doc["바탕"]["로직"]), "짝잃음": []}
except Exception as e: # noqa: BLE001 — 엔진 FormulaError(없는 기초)
raise sd.DocError(f"바탕 로직 · {e}") from e
return _base_of(doc, whole, refs.read_ref, ())
def _head_of(doc: dict, whole: Any, trail: tuple = ()) -> dict[str, Any]:
"""저장 검사가 읽는 바탕 머리(855 L2 ⓑ-3 · 로직 줄 안 읽음) — 로직 바탕 = 기초 문서 머리 · 가져온 식 ·
바탕 없음 = 그 줄(`_row_of`) · 바탕 참조 = 그 SK 의 바탕 머리(순환 · 깊이 422) · 옛 칸 고침을 바탕
줄에 얹던 사슬(`resolve`) 걷음(855-E 2-E4)."""
ref = (doc.get("바탕") or {}).get("참조")
if not isinstance(ref, dict):
return {"줄": _row_of(doc, whole), "짝잃음": []}
rid = refs.ref_id(ref)
if rid in trail:
keys = [x.rsplit("|", 1)[-1] for x in (*trail, rid)]
raise sd.DocError("순환 — " + " → ".join(keys), 422)
if len(trail) >= refs.DEPTH:
raise sd.DocError(f"바탕 사슬이 {refs.DEPTH}단을 넘음", 422)
parent = refs.read_ref(ref)
if not isinstance(parent, dict):
raise sd.DocError(f"없는 바탕 「{ref.get('키')}」")
return _head_of(parent, whole, (*trail, rid))
def clean_doc(doc: Any, here_: refs.Here) -> dict[str, Any]:
@@ -515,8 +242,7 @@ def clean_doc(doc: Any, here_: refs.Here) -> dict[str, Any]:
try:
rough = sd.clean(doc, None, whole)
_check_refs(rough, here_)
eqm.strict(base := _head_of(rough, whole)) # 수식 고침(796-2b)
blk.strict(rough, whole) # 끊은 기초 수식 고침(796-2e)
base = _head_of(rough, whole)
out = sd.clean(doc, base["줄"], whole)
out["바탕"], out["더한줄"] = rough["바탕"], rough["더한줄"]
for one in out["더한줄"]: # 처음수량(744-1) = 넣을 때 수량 · 없으면 지금 수량
+1 -3
View File
@@ -356,9 +356,7 @@ def clean(doc: Any, base_row: dict | None = None, whole: Any = None) -> dict[str
given = _given(doc.get("입력값"), "입력값")
opened = [str(x) for x in doc.get("열린입력") or []]
if base_row is not None:
from M02_MasterTemplete import M02_Sangeun_Equation as eqm # 수식 고침 더한 입력(796-2b)
keep = names | _added_names(whole, doc.get("더한줄")) | eqm.added_inputs(doc)
keep = names | _added_names(whole, doc.get("더한줄"))
given = {k: v for k, v in given.items() if k in keep}
bad = [x for x in opened if x not in names or x in given]
if bad:
+7 -88
View File
@@ -1,102 +1,21 @@
"""M02 단가산출(SK) 수식 탭 서버 몫(PLAN 796-2b · 요구 655 · 656 · 657 · 요구서_655 0 · 2 장 1).
"""M02 단가산출(SK) 옛 칸 `수식고침`(PLAN 796-2b) — 받지 않음(855-E 2-E4).
수식 = 그 SK 바탕 줄(로직 사본 줄 `M02_Sangeun_Copy` · 가져온 식 줄 `M02_Sangeun_Imported.row_of`) +
문서 덧칸 `수식고침` = 사본 위 고침 기록 — M01 수식 탭 고침 꼴(`master_equation_edit` 머리 ·
차례대로 · 식 · 더함 · 지움 · 변수 · 표시) + 줄마다 `까닭`?(예정가격작성기준 제2조 ②) ·
사본은 찍은 그대로(= 원래 대비 · 고친 칸 = 고침 목록).
셈 = `M02_Sangeun_Calc._base_of` 가 바탕 줄에 `on` 으로 얹음(엔진 · 검사 = M01 `edit_row` 한 벌) →
모든 셈 길(화면 · 저장 원값 · B09 · 펼침) 같은 줄 · 못 얹은 고침(재생성 뒤 자리 없음 등) =
고침 없는 바탕 + 짝잃음 cid `수식` · 저장(`strict`) = 400 · [재생성] = 새 사본에 같은 고침
다시 얹음(못 얹음 = 795-1 `못얹은`).
수식 탭 화면 길(읽기 · 미리 셈 · 합계 소계)은 걷음(894) — 남은 것 = 저장 문서 `수식고침` 꼴 · 셈 · 저장 검사.
저장 = SK [저장](`clean_doc` 이 다시 얹어 검사 · 셈 · 브라우저 값 안 받음).
바탕 참조 SK(`바탕.참조`) = 수식 없음(바탕 SK 의 고침은 그 SK 가 얹음).
옛 수식 탭 고침 = 바탕 로직 줄에 엔진 수식 고침(`master_equation_edit`)을 얹던 칸 · 화면 길은 894 에서 걷음 ·
저장본 0 · 고침은 단가산출 수식 문서(줄 쌓기 · 수식 길 저장)로 — 받으면 400.
"""
from __future__ import annotations
import hashlib
import json
from typing import Any
from M02_MasterTemplete import M02_Sangeun_Doc as sd
KEY = "수식고침"
MANY = 200
LONG = 500 # 까닭 길이
LOST = "수식" # 짝잃음 cid
STAND = "GX999997" # 가져온 식(SK 키) 줄을 엔진에 얹을 잠깐 키(GX999998 = 견본 · 999999 = 초안)
_MEMO: dict[tuple[str, str], tuple[dict, list[str]]] = {}
def _eqn() -> Any:
from M01_MasterData import M01_MasterData_Equation as eqn # M02 가 M01 을 부름 — 늦게
return eqn
def _hash(v: Any) -> str:
raw = json.dumps(v, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
WHY = "수식고침(옛 칸) — 받지 않음 · 단가산출 수식 문서(줄 쌓기)로 고침"
def clean(raw: Any, out: dict) -> dict:
"""`sd.clean` 끝 — 꼴만(목록 · 묶음 · 까닭 길이) · 뜻 검사는 셈 · 저장 때 `on`."""
edits = raw.get(KEY) if isinstance(raw, dict) else None
if not edits:
return out
if not isinstance(edits, list) or len(edits) > MANY:
raise sd.DocError(f"수식고침 · {MANY} 개까지 목록")
for at, one in enumerate(edits, 1):
why = one.get("까닭") if isinstance(one, dict) else None
if not isinstance(one, dict) or (why is not None and len(str(why)) > LONG):
raise sd.DocError(f"수식고침 {at}째 · 묶음 · 까닭 {LONG} 자까지")
out[KEY] = json.loads(json.dumps(edits, ensure_ascii=False, default=str))
"""`sd.clean` 끝 — 옛 칸 `수식고침` 이 있으면 400."""
if isinstance(raw, dict) and raw.get(KEY):
raise sd.DocError(WHY)
return out
def added_inputs(doc: Any) -> set[str]:
"""고침으로 더한 입력 이름 — `sd.clean` 입력값 거름에서 남김."""
edits = (doc.get(KEY) if isinstance(doc, dict) else None) or []
return {
str(e.get("열쇠"))
for e in edits
if isinstance(e, dict) and e.get("할일") == "더함" and e.get("갈래") == "입력"
}
def _stand(row: dict) -> tuple[dict, str]:
"""(엔진이 로직으로 부를 줄, 본 키) — M01 로직 키 아님(가져온 식 SK) = 잠깐 키."""
key = str(row.get("키"))
return (row, key) if key[:2] in ("GC", "GF", "GX") else ({**row, "키": STAND}, key)
def apply(row: dict, edits: list, whole: Any) -> tuple[dict, list[str]]:
"""바탕 줄 + 고침 → (새 줄, 까닭) — 같은 줄 · 같은 고침 = 메모(셈 길마다 다시 검사 안 함)."""
tag = (_hash(row), _hash(edits))
got = _MEMO.get(tag)
if got is None:
if len(_MEMO) > 64: # ponytail: 통째 비움 · 쓰는 SK 가 많아 느려지면 LRU 로
_MEMO.clear()
stand, key = _stand(row)
new, why = _eqn().edit_row(whole, stand, edits)
got = _MEMO[tag] = ({**new, "키": key}, why)
return got
def on(row: dict, doc: Any, whole: Any) -> tuple[dict, list[dict]]:
"""셈 길 — 고침 얹은 줄 · 못 얹음 = 바탕 그대로 + 짝잃음 `수식`."""
edits = (doc.get(KEY) if isinstance(doc, dict) else None) or []
if not edits:
return row, []
new, why = apply(row, edits, whole)
if why:
return row, [{"cid": LOST, "까닭": "수식 고침 못 얹음 — " + " · ".join(why)}]
return new, []
def strict(base: dict) -> None:
"""저장 — 이 SK 고침이 못 얹히면 400(바탕 SK 사슬 것 = 알림만)."""
for x in base.get("짝잃음") or []:
if x.get("cid") == LOST and "바탕" not in x:
raise sd.DocError(x["까닭"])
+24
View File
@@ -0,0 +1,24 @@
"""옛 `M02_Labor_Doc.run_line` 자리(855-E 2-E4) — 로직 줄 하나 = 층 문서 셈(`M02_Labor_Copy.line`).
재료 줄 전부 직접계산(옛 날 답 = 별도계상 안 뺌) · 켜쌓기율 · 고름 = 줄 옵션 · 답 `{기준, 줄, 재료, 까닭}`.
"""
from __future__ import annotations
from typing import Any
DIRECT = {"별도계상": "직접계산"}
def run_line(
whole: Any, code: str, given: dict | None = None, rate: Any = None, picks: dict | None = None
) -> dict[str, Any]:
from M02_MasterTemplete import M02_Labor_Copy as lc
one: dict[str, Any] = {"로직": code, "입력값": dict(given or {})}
one["자재표시"] = {str(n): DIRECT for n in range(64)}
if rate is not None:
one["켜쌓기율"] = rate
if picks:
one["고름"] = picks
return lc.line(whole, {}, one)
@@ -7,6 +7,7 @@
from __future__ import annotations
from decimal import Decimal
from typing import Any
from fastapi import APIRouter
@@ -112,14 +113,12 @@ def post_calc(body: CalcBody) -> dict:
got = m01._call(calc, body.key, body.inputs, body.row, body.file)
if not got.get("lines"):
return got
from M02_MasterTemplete import M02_Labor_Doc as labor_doc # % 덧줄 표기(149-4)
whole = store.loaded()[1]
try:
logic = body.row or whole.logic(body.key)
except mf.FormulaError:
return got
lines = labor_doc.pct_extras(whole, logic, got["lines"], got.get("middle") or {})
lines = _pct_extras(whole, logic, got["lines"], got.get("middle") or {})
return {**got, "lines": m01._num(lines)}
@@ -127,3 +126,53 @@ def post_calc(body: CalcBody) -> dict:
def post_text(body: CalcBody) -> dict:
with mf.mp.choosing(body.고름):
return m01._call(text, body.key, body.inputs, body.row, body.file)
COSTS = ("노무비", "재료비", "경비")
# ── 옛 % 덧줄 표기(옛 `M02_Labor_Doc.pct_extras` · 855-E 2-E4 에서 제품에서 걷어 옛 길 도우미로 옮김) ──
def _pct_extras(whole: Any, logic: dict, lines: list[dict], env: dict) -> list[dict]:
"""% 덧줄(149-4) — 덧줄 식이 「X * Y / 100」 이면 그 엔진 줄(호표 수 뒤 같은 차례)에 덧칸
`율` = Y(엔진 마지막 env 로 셈) · `규격` = X 이름(「노무비의 %」 · 인력 줄 합 「인건비의 %」 ·
`줄.'이름'` · 중간값 「이름의 %」 · 그 밖 복합 = 빈 글). 다른 덧줄 · 흐름 로직 · 못 셈 = 그대로."""
if isinstance(logic.get("흐름"), dict):
return lines
out, head = list(lines), len(logic.get("호표") or [])
for n, add in enumerate(logic.get("덧줄") or []):
if head + n >= len(out):
break
try:
node = mf.parse(add.get("식") or "")
except mf.FormulaError:
continue
if not (
node[0] == "bin"
and node[1] == "/"
and node[3] == ("num", Decimal(100))
and node[2][0] == "bin"
and node[2][1] == "*"
):
continue # 금액 식(기계손료 등) · 조건부 % = 「식」 그대로
base, part = node[2][2], node[2][3]
try:
rate = mf.evaluate(part, dict(env), whole)
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
continue
if isinstance(rate, Decimal):
out[head + n] = {**out[head + n], "율": rate, "규격": _pct_base_name(base)}
return out
def _pct_base_name(node: tuple) -> str:
"""% 덧줄 밑수 이름 — B09 대가(`B09_Estimation_Labor_Source._base_of`)와 같은 말."""
if node[0] == "name":
return f"{node[1]}의 %" # 노무비 · 재료비 · 경비 · 중간값 이름
if node[0] == "field" and node[1] == ("name", "줄"):
return f"{node[2]}의 %"
parts = list(mf.walk(node))
if any(x[0] == "ref" and str(x[1]).startswith("LB") for x in parts) and not any(
x[0] == "name" and x[1] in COSTS for x in parts
):
return "인건비의 %"
return ""
-43
View File
@@ -1,43 +0,0 @@
"""% 덧줄 표기(PLAN 149-4) — 식 「X * Y / 100」 덧줄 = 덧칸 율 · 규격 · 금액 · 단위 · 수량 그대로.
- M02 `run_line` → 큰돌쌓기 찰쌓기 제잡비 설치 9 · 안 함 3 · 「노무비의 %」
- 인력 줄 합 밑수 = 「인건비의 %」 · 호표 줄 밑수 = 「그 줄 이름의 %」 · 금액 식(기계손료) = 덧칸 없음
- M01 시험계산 길(`post_calc`)은 855 2-E1 에 걷음 · 화면은 `pctView` 한 벌
"""
from decimal import Decimal
from pathlib import Path
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
ROOT = Path(__file__).resolve().parents[2]
def _extra(code: str, given: dict | None = None, name: str | None = None) -> dict:
got = labor.run_line(m01.loaded()[1], code, given or {})
assert got["까닭"] is None
lines = [x for x in got["줄"] if x.get("단위") == "식" and (name is None or x["이름"] == name)]
assert lines, code
return {**lines[-1], "_기준": got["기준"]}
def test_큰돌쌓기_찰쌓기_제잡비_율_설치_9_안함_3_금액_그대로():
for pipe, rate in (("설치", 9), ("설치 안 함", 3)):
x = _extra("GF000227", {"물빼기파이프": pipe}, "제잡비")
assert x["율"] == Decimal(rate) and x["규격"] == "노무비의 %"
assert x["단위"] == "식" and x["수량"] == 1 # 엔진 줄은 그대로 · 표기는 화면
labor_sum = x["_기준"]["노무비"]
# 751-3 — % 밑 = 버린 줄 합(소계 1 원 버림 전) · 금액 0.1 원 버림
assert abs(x["금액"] - labor_sum * rate / 100) <= Decimal(rate) / 100 + Decimal("0.1")
def test_인건비_호표줄_밑수_금액식은_덧칸_없음():
x = _extra("GC000198")
assert x["율"] == 2 and x["규격"] == "인건비의 %"
x = _extra("GF000002", name="잡품")
assert x["규격"] == "휘발유(체인톱)의 %" and x["율"] > 0
mach = _extra("GC000267", name="기계손료")
assert "율" not in mach and "규격" not in mach
mat = _extra("GC000267", name="잡재료비")
assert mat["규격"] == "재료비의 %"
+22 -10
View File
@@ -22,15 +22,27 @@ BASE = "GF000218" # 기초다짐 및 뒷채움(기계) — 보통인부 + 굴
GIVEN = {"규격": 150, "지역": "전국평균", "보정작업": "해당 없음"}
def _copy(codes, over=None):
"""사본 셈 색인(855-E 2-E4) = 수식 문서 묶음 + 그 문서가 잇는 자원 · 표 줄(`Item_Bundle.load`) ·
`over` = 견본 값 사본 색인(고친 로직 줄 → 그 줄 문서)."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Item_Bundle as item_bundle
docs = dc.closure(over or item_prices.master()[1], codes)
return item_bundle.load(item_prices.to_json(item_bundle.collect(docs)), docs)
def _whole(edit=None):
"""사본 단가 묶음 — `edit(로직 줄)` 로 GF000218 을 엑셀 견본 꼴로 바꿈(수량 · 중간 · 덧줄)."""
files = copy.deepcopy(item_prices.to_json(item_prices.collect([BASE])))
if edit:
for data in files.values():
for row in data.get("줄") or []:
if isinstance(row, dict) and row.get("키") == BASE:
edit(row)
return item_prices.load_prices(files)
"""사본 셈 색인 — `edit(로직 줄)` 로 GF000218 을 엑셀 견본 꼴로 바꿈(수량 · 중간 · 덧줄 · 고친 줄 =
값 사본 줄 → 그 줄 문서)."""
from M02_MasterTemplete import M02_Sangeun_Copy as skc
if not edit:
return _copy([BASE])
master = item_prices.master()[1]
row = copy.deepcopy(item_prices.to_json(master.logic(BASE)))
edit(row)
return _copy([BASE], skc.Copy(master, skc._rows({"로직": [row]})))
def _excel(qty_labor: str, qty_eq: str, mids=(), extras=()):
@@ -102,7 +114,7 @@ def test_켜쌓기율_꼬리():
def test_글_속_금액은_산근_풀이_값과_같음():
for code, given in ((BASE, GIVEN), ("GF000288", {})): # 중기 · 노무 · % 덧줄 · 배 1,000
whole = item_prices.load_prices(item_prices.to_json(item_prices.collect([code])))
whole = _copy([code])
block = sg.Solver().add(whole, {"code": code, "given": given}, "s1")
assert block["foot"] == _foot(block), code
for ln in block["lines"]:
@@ -115,7 +127,7 @@ def test_글_속_금액은_산근_풀이_값과_같음():
def test_자재_자리표시_키는_실제_키로():
"""「MO:휘발유:{지역}」 자리표시 = 대비표 키(MO…) · 수집량 공식 줄 · 「× (6.5 × 0.125)」 · % 덧줄."""
whole = item_prices.load_prices(item_prices.to_json(item_prices.collect(["GF000062"])))
whole = _copy(["GF000062"])
block = sg.Solver().add(whole, {"code": "GF000062", "given": {}}, "s1")
fuel = next(ln for ln in block["lines"] if ln["name"].startswith("휘발유"))
assert fuel["ref"]["key"].startswith("MO") and ":" not in fuel["ref"]["key"]
+2 -1
View File
@@ -16,6 +16,7 @@ from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.test_222_1_m02_apart import raw_line
from resources.tester.test_m02_labor_ref import _area, world # noqa: F401 — 임시 층 fixture
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -95,7 +96,7 @@ def _world_combo(world): # noqa: F811
key = refs.create(
"precombo", {"이름": "자재 조합", "단위": "㎡", "담은로직": lines, "자재": mats}
)["이름"]
stone = Decimal(str(labor.run_line(m01.loaded()[1], STONE, {})["기준"]["계"]))
stone = Decimal(str(raw_line(STONE)["기준"]["계"])) # 로직 줄 값(문서 셈 · 855-E 2-E4)
return key, stone + _price(MAT) * 2
+15 -6
View File
@@ -34,6 +34,15 @@ def _whole():
return m01.loaded()[1]
def raw_line(code: str, given: dict | None = None) -> dict:
"""별도계상 없는 로직 줄 답(옛 `run_line` 자리 · 층 문서 셈 `Labor_Copy.line` · 855-E 2-E4) — 재료 줄 전부
직접계산 → 줄 · 재료 · 기준 통째."""
from M02_MasterTemplete import M02_Labor_Copy as lc
marks = {str(n): DIRECT for n in range(64)}
return lc.line(_whole(), {}, {"로직": code, "입력값": given or {}, "자재표시": marks})
def _rows(got):
return {x["이름"]: {**x, "수량": float(x["수량"])} for x in got["줄"]}
@@ -49,13 +58,13 @@ def _kept(raw, names=None):
# ── ① 단위 ──────────────────────────────────────────────────────────
def test_단위중량_칸에_t_값이면_1000배_0이면_표_위끝():
wrong = labor.run_line(_whole(), MIX, {**GIVEN, "모래단위중량": 2, "자갈단위중량": 2.1})
wrong = raw_line(MIX, {**GIVEN, "모래단위중량": 2, "자갈단위중량": 2.1})
rows = _rows(wrong)
assert rows["시멘트"]["단위"] == "kg" and rows["시멘트"]["수량"] == pytest.approx(335)
assert rows["시멘트"]["단위"] == "㎏" and rows["시멘트"]["수량"] == pytest.approx(335)
assert rows["모래(건조상태)"]["수량"] == pytest.approx(838 / 2) # 419 ㎥
assert rows["자갈 또는 부순돌"]["수량"] == pytest.approx(1032 / 2.1) # 491.4 ㎥
zero = {**GIVEN, "모래단위중량": 0, "자갈단위중량": 0}
right = _rows(labor.run_line(_whole(), MIX, zero))
right = _rows(raw_line(MIX, zero))
assert right["모래(건조상태)"]["수량"] == pytest.approx(838 / 1700)
assert right["자갈 또는 부순돌"]["수량"] == pytest.approx(1032 / 1800)
@@ -70,7 +79,7 @@ def _calc(shown=None, mats=()):
def test_로직_자재_기본_별도계상은_기준_줄에서_빠지고_재료엔_남음():
raw = labor.run_line(_whole(), MIX, GIVEN)
raw = raw_line(MIX, GIVEN)
one = _calc()["줄"][0]
names = {x["이름"] for x in one["줄"]}
assert not names & {"시멘트", "모래(건조상태)", "자갈 또는 부순돌"}
@@ -82,7 +91,7 @@ def test_로직_자재_기본_별도계상은_기준_줄에서_빠지고_재료
def test_직접계산은_그대로_섞이면_그_자재만_빠짐():
raw = labor.run_line(_whole(), MIX, GIVEN)
raw = raw_line(MIX, GIVEN)
full = _calc({str(n): DIRECT for n in (3, 4, 5)})["줄"][0]
assert full["기준"]["계"] == pytest.approx(float(raw["기준"]["계"]))
assert len(full["줄"]) == len(raw["줄"])
@@ -113,7 +122,7 @@ def test_사용자_자재_별도계상_파이썬과_TS_같은_답(mark):
def test_사전조합_안_줄도_별도계상_뺌():
raw = labor.run_line(_whole(), MIX, GIVEN)
raw = raw_line(MIX, GIVEN)
doc = {
"이름": "비빔 조합",
"단위": "㎥",
+3 -4
View File
@@ -12,6 +12,7 @@ from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.test_222_1_m02_apart import raw_line
from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층
PCT = "GC001109" # 원/㎡ · 인력 둘(LB000036 · LB000002) + 「노무비 * 3 / 100」
@@ -55,10 +56,8 @@ def test_refusals(world):
def test_no_patch_same_value(world):
"""덮개 없는 줄 = run_line 값 그대로(옛 셈 길)."""
"""덮개 없는 줄 = 로직 줄 값 그대로(문서 셈 · 855-E 2-E4)."""
sc = _sc(world["personal"], [{"로직": PCT, "패치": {}}])
with store.at(world["personal"]):
assert "패치" not in store.read("precombo", sc)["문서"]["담은로직"][0]
assert _value(world["personal"], sc)["기준"]["계"] == pytest.approx(
labor.run_line(_whole(), PCT, {})["기준"]["계"]
)
assert _value(world["personal"], sc)["기준"]["계"] == pytest.approx(raw_line(PCT)["기준"]["계"])
+2 -2
View File
@@ -39,9 +39,9 @@ def _whole():
def _bare(code):
from M02_MasterTemplete import M02_Labor_Doc as labor
from resources.tester.helper_855_line import run_line
return labor.run_line(_whole(), code, {})
return run_line(_whole(), code, {})
def test_refusals(world):
+2 -2
View File
@@ -17,11 +17,11 @@ import pytest
from M01_MasterData import M01_MasterData_Doc as m01_doc
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_Logic_Standard as standard
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Calc as calc
from resources.tester.helper_855_line import run_line
from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층
ROOT = Path(__file__).resolve().parents[2]
@@ -100,7 +100,7 @@ def _line(got, cid):
def _m01(code, values=None):
return float(labor.run_line(m01.loaded()[1], code, values or {}, None, None)["기준"]["계"])
return float(run_line(m01.loaded()[1], code, values or {}, None, None)["기준"]["계"])
def test_727_3_옵션_저장_일위대가_그_옵션(world): # noqa: F811
+2 -2
View File
@@ -15,9 +15,9 @@ import pytest
from B09_Estimation.B09_Estimation_Calc_Labor import compute_labor
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.helper_855_line import run_line
from resources.tester.test_723_4_b09_sc_qty import MAT, RID, SHEETS, _build, _doc
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 임시 층 fixture
@@ -28,7 +28,7 @@ RATE = {"이름": "공구손료", "단위": "%", "단가": {"노무비": 0, "재
def _stone() -> float:
return labor.run_line(m01.loaded()[1], STONE, {})["기준"]["계"]
return run_line(m01.loaded()[1], STONE, {})["기준"]["계"]
def _sc(world, lines): # noqa: F811
+2 -1
View File
@@ -7,6 +7,7 @@ from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Sangeun_Calc as calc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from resources.tester.helper_855_line import run_line
FORM = "GC000211" # 6-3-1 합판거푸집 — 합판 1.03 · 각재 0.038 · 폼타이 0 · 소모자재 = 재료비 %
PLY = "금액#2" # 합판 = 기초 문서 금액 줄 2째(855 L2 ⓑ-3 줄 규칙 열쇠)
@@ -23,7 +24,7 @@ def _run(**doc):
def test_base_materials_count_like_m01():
m01_ = labor._json(labor.run_line(_whole(), FORM, None))
m01_ = labor._json(run_line(_whole(), FORM, None))
got = _run(바탕={"로직": FORM})
assert got["기준"]["재료비"] == pytest.approx(m01_["기준"]["재료비"])
assert got["기준"]["계"] == pytest.approx(m01_["기준"]["계"])
-74
View File
@@ -6,7 +6,6 @@ M01 시험 계산 · 읽는 식 · M02 단가산출(SK) · 일위대가 반영
from decimal import Decimal
from B09_Estimation import B09_Estimation_Sangeun as sg
from M01_MasterData import M01_MasterData_Store as m01
import helper_855_old_engine_routes as old_engine # noqa: E402 — 옛 셈 몸(855 2-E1 · 시험 전용)
from M02_MasterTemplete import M02_Labor_Doc as labor
@@ -35,38 +34,6 @@ def _sums_of_lines(lines) -> dict:
return {k: mcut.down(v, 0) for k, v in total.items()}
def test_줄은_0점1원_소계는_1원_버림_줄합이_소계():
got = labor.run_line(_whole(), KEY, {})
base = got["기준"]
assert all(_tenth(x.get("금액")) for x in got["줄"])
assert all(Decimal(str(base[k])) == int(base[k]) for k in COSTS)
assert {k: Decimal(str(base[k])) for k in COSTS} == _sums_of_lines(got["줄"])
assert base["계"] == sum(base[k] for k in COSTS)
def test_B09_산근_끝수와_같음():
"""엔진 날 줄을 B09 규칙(줄 ROUNDDOWN 1 · % = 버린 밑 × 율 · 비목 ROUNDDOWN 0)으로 = 끝수 답."""
whole = _whole()
raw = labor.run_line(whole, KEY, {}, raw=True)
cut = labor.run_line(whole, KEY, {})
lines = []
for x in raw["줄"][: len(whole.logic(KEY)["호표"])]:
lines.append(
{k: sg._money(float(x["단가"] or 0), float(x["수량"] or 0)) for k in x["비목"]}
)
under = {k: sum(ln.get(k, 0) for ln in lines) for k in COSTS}
for x in raw["줄"][len(lines) :]: # % 덧줄 = 버린 밑 × 율 / 100 → ROUNDDOWN 1
(part,) = x["비목"]
base = under["재료비"] if "재료" in x["이름"] or "소모" in x["이름"] else under["노무비"]
lines.append({part: sg.rounddown(base * float(x["율"]) / 100, 1)})
b09 = sg.block_totals([{"labor": ln.get("노무비", 0), "material": ln.get("재료비", 0),
"expense": ln.get("경비", 0)} for ln in lines]) # fmt: skip
assert (b09["labor"], b09["material"], b09["expense"], b09["sum"]) == tuple(
float(cut["기준"][k]) for k in (*COSTS, "계")
)
assert raw["기준"]["계"] != cut["기준"]["계"] # 날 값은 버리기 전(B09 몫)
def test_화면_넷_같은_값_SK_시험계산_읽는식():
whole = _whole()
doc = sd.clean(
@@ -88,37 +55,6 @@ def _line_text(v) -> str:
return fmt_line_money(Decimal(str(v)))
def test_하위_로직_줄은_하위_계를_버려_단가로():
"""기계 · 하위 로직 줄 단가 = 하위 로직 끝수 계(1 원) ·
비목마다 하위 비목 × 수량 0.1 원 버림."""
whole = _whole()
key = next(
str(r["키"])
for _, d in m01._logic_files(m01.cm.load(folder=m01.FOLDER))
for r in d.get("줄") or []
if any(i.get("종류") == "로직" for i in r.get("호표") or [])
and "결과" not in r
and not isinstance(r.get("흐름"), dict)
and labor.run_line(whole, str(r["키"]), {}).get("기준")
)
got = labor.run_line(whole, key, {})
for item, x in zip(whole.logic(key)["호표"], got["줄"]):
if item.get("종류") == "로직" and x.get("단가") is not None and x.get("수량") is not None:
assert Decimal(str(x["단가"])) == int(x["단가"])
parts = [
Decimal(str(v)) for v in x["비목"].values()
] # 비목마다 0.1 원 버림 · 금액 = 합
assert all(_tenth(v) for v in parts) and Decimal(str(x["금액"])) == sum(parts)
assert abs(Decimal(str(x["단가"])) * x["수량"] - sum(parts)) < Decimal("0.3")
def test_날_값은_엔진_그대로():
whole = _whole()
eng = mf.run(whole, KEY, {**m01.mau.values(whole, whole.logic(KEY))})
raw = labor.run_line(whole, KEY, {}, raw=True)
assert raw["기준"]["계"] == eng["계"]
def test_일위대가_반영_줄_0점1원_합_1원():
doc = labor.clean({"담은로직": [{"로직": KEY, "수량": {"손": 3.3}}]})
out = labor.calc(doc, {})
@@ -129,13 +65,3 @@ def test_일위대가_반영_줄_0점1원_합_1원():
assert {k: Decimal(str(total[k])) for k in COSTS} == {
k: mcut.down(Decimal(str(line[k])), 0) for k in COSTS
}
def test_별도계상_뺀_기준은_남은_줄_합_버림():
whole = _whole()
got = labor.run_line(whole, KEY, {})
marks = {str(m["차례"]): {"별도계상": "직접계산"} for m in got["재료"]}
marks[str(got["재료"][0]["차례"])] = {"별도계상": "별도계상"} # 첫 재료만 뺌
out = labor.drop_apart(got, marks)
assert len(out["줄"]) == len(got["줄"]) - 1
assert {k: Decimal(str(out["기준"][k])) for k in COSTS} == _sums_of_lines(out["줄"])
@@ -53,10 +53,6 @@ def test_색인은_M01_색인에_한_번_두번째_셈은_안_지음(monkeypatch
assert again["기준"] == first["기준"] and first["기준"]["계"] == 51419
assert all(vars(whole)[n] is v for n, v in held.items())
assert found == [] # 같은 조건 찾기 = 기억한 답(자재품목 3만 줄을 안 훑음)
over = calc._Over(whole, "SK-000001", {})
assert over._market is whole._market and "_market" not in vars(over)
over.mine = 1 # 그 밖 칸은 덮개에만
assert "mine" not in vars(whole)
def test_M01_파일이_바뀌면_새_색인_새로_지음(tmp_path):
+1 -25
View File
@@ -1,7 +1,7 @@
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
"""792-3 · 792-4 엔진 새 의미 다섯 길 지킴 시험 — 같은 로직 JSON 이
① 엔진 직접(`master_cut.engine`) ·
② M02 단가산출 SK 셈(`M02_Sangeun_Calc.run`) · ③ 일위대가 SC 한 줄(수량 1 · `M02_Labor_Doc.calc`) ·
② M02 단가산출 SK 셈(견본 로직 줄 = M01 문서 밖 → 굳힌 옛 사본 = 못 셈 · 855-E 2-E4 에서 뺌) · ③ 일위대가 SC 한 줄(수량 1 · `M02_Labor_Doc.calc`) ·
④ B09 산근 풀이(`B09_Estimation_Sangeun.Solver` · 841-1 단가 = M02 엔진) ·
⑤ B09 일위대가 대가 블록(SC → 사본 SK 참조 수량 1 · `Labor_Source.Builder` → `Calc_Labor` 파이썬 ·
TS 짝 · 내역 단가 `daega_price`)에서 같은 금액.
@@ -74,12 +74,6 @@ def _engine(master, row) -> dict:
return {k: got[k] for k in COSTS}
def _sk(master, row) -> dict:
doc = {"키": "SK-990001", "이름": "시험", "단위": "식", "바탕": {"로직": _key(row)}}
got = sc.run(sd.clean(doc, None, master), master)
return {k: got["기준"][k] for k in COSTS}
def _sc(master, row) -> dict:
mats = {
str(n): {"별도계상": "직접계산"} for n, x in enumerate(row["호표"]) if x["종류"] == "재료"
@@ -172,7 +166,6 @@ def test_다섯_길_같은_금액(name):
one = _engine(master, row)
if want is not None:
assert one == want # 엑셀 금액
assert _sk(*build()[:2]) == one
assert _sc(*build()[:2]) == one
assert _b09(build, row) == one
assert _b09_daega(build) == one # ⑤ B09 일위대가 대가 블록(792-4)
@@ -217,20 +210,3 @@ def test_단위_로직_새_의미가_금액을_바꿈():
for k in ("합밖", "자리", "번지"):
x.pop(k, None)
assert got != _engine(t._master([plain], t.LAB, t.MAT), plain) # 시험이 새 길을 거침
@pytest.mark.parametrize("name", ["영월", "단위"])
def test_다시_버림도_셈법_지킴(name):
"""켜쌓기율 · 별도계상 뒤 다시 버림(`plain`) — 셈법이 있으면
줄 자리 · 합밖 · 끝전 · 조정 그대로."""
master, row, _ = CASES[name]()
out = labor.run_line(master, _key(row), {})
assert "셈법" in out and out["단계"]
again = mcut.plain(out)
assert again["기준"] == out["기준"]
assert [x["계"] for x in again["단계"]] == [x["계"] for x in out["단계"]]
old = mcut.plain({k: v for k, v in out.items() if k != "셈법"})
if name == "영월":
assert (
old["기준"]["계"] == 5470 and again["기준"]["계"] == 5471
) # 옛 다시 버림 = 1 원 모자람
+4 -4
View File
@@ -15,13 +15,13 @@ import pytest
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Doc_Sk_Path as path
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_Library_Same as same
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Calc as calc
from M02_MasterTemplete import M02_Sangeun_Copy as skc
from M02_MasterTemplete import M02_Sangeun_Imported as imp
from resources.tester.helper_855_line import run_line
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
@@ -108,9 +108,9 @@ def test_copy_stamped_and_logic_change_kept(world, monkeypatch):
first = _calc(me, _doc(me, key))
assert first["사본"]["M01새판"] is False and first["사본"]["지운키"] == []
was = first["기준"]["계"]
plain = labor.run_line(_live(), PCT, {})["기준"]["계"]
plain = run_line(_live(), PCT, {})["기준"]["계"]
_fake(monkeypatch, [_changed(_live().logic(PCT))])
assert labor.run_line(m01.loaded()[1], PCT, {})["기준"]["계"] != plain # M01 셈은 바뀜
assert run_line(m01.loaded()[1], PCT, {})["기준"]["계"] != plain # M01 셈은 바뀜
now = _calc(me, _doc(me, key))
assert now["기준"]["계"] == was
assert now["사본"]["M01새판"] is True
@@ -168,7 +168,7 @@ def test_old_sk_without_copy_old_path(world, monkeypatch):
with store.at(me):
assert same.Same().finger("sangeun", old) == same.Same().finger("sangeun", _doc(me, fresh))
_fake(monkeypatch, [_changed(_live().logic(PCT))])
moved = labor.run_line(m01.loaded()[1], PCT, {})["기준"]["계"]
moved = run_line(m01.loaded()[1], PCT, {})["기준"]["계"]
assert _sum(me, key) == pytest.approx(moved, abs=1) # 옛 길 = 따라감
assert _sum(me, fresh) != _sum(me, key) # 사본 SK = 그대로
with store.at(me): # 판 다른 두 SK = 지문 다름(오판 막음)
+8 -6
View File
@@ -19,6 +19,7 @@ from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Copy as skc
from resources.tester.helper_855_line import run_line
from resources.tester.test_795_1_sk_copy import _changed, _fake, _live
from resources.tester.test_m02_labor_calc_mirror import _same, _ts
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
@@ -82,12 +83,12 @@ def test_copy_stamped_logic_change_kept(world, monkeypatch):
sc = _sc(me, [{"로직": PCT, "수량": {"손": 1}}])
doc = _labor(me, [{"로직": PCT, "수량": {"손": 2}}])
for got in (doc, _read(me, "precombo", sc)):
assert PCT in {r["키"] for r in skc.held(got)["로직"]}
assert PCT in got["수식"]["부름"] # 로직 몫 = 수식 부름 문서(값 사본 로직 줄 없음 · 855-E 2-E4)
assert LB in {r["키"] for r in skc.held(got)["단가"]}
was = (_calc(me, COL)["반영합"]["계"], _calc(me, sc)["기준합"]["계"], _unit(me, sc))
assert _calc(me, COL)["사본"]["M01새판"] is False
_fake(monkeypatch, [_changed(_live().logic(PCT))])
assert labor.run_line(m01.loaded()[1], PCT, {})["기준"]["계"] != was[2] # M01 셈은 바뀜
assert run_line(m01.loaded()[1], PCT, {})["기준"]["계"] != was[2] # M01 셈은 바뀜
now = (_calc(me, COL)["반영합"]["계"], _calc(me, sc)["기준합"]["계"], _unit(me, sc))
assert now == was
assert _calc(me, COL)["사본"]["M01새판"] is True
@@ -114,7 +115,7 @@ def test_layer_and_column_copy_keep_copy(world, monkeypatch):
co, me = world["company"], world["personal"]
src = _sc(co, [{"로직": PCT, "수량": {"손": 1}, "패치": COVER}])
first = skc.held(_read(co, "precombo", src))
old = skc.held(_labor(me, [{"로직": PCT, "수량": {"손": 2}}])) # 받는 열 = 옛 M01 사본
old_doc = _labor(me, [{"로직": PCT, "수량": {"손": 2}}]) # 받는 열 = 옛 M01 사본
_fake(monkeypatch, [_double(LB), _changed(_live().logic(PCT))])
ref = {"층": "company", "주인": "7", "키": src}
with store.at(me):
@@ -124,8 +125,9 @@ def test_layer_and_column_copy_keep_copy(world, monkeypatch):
mine = skc.held(_read(me, "precombo", got["이름"]))
assert (mine["판"], mine["단가판"]) == (first["판"], first["단가판"])
_write(me, "labor", "sub2임시2", {"열": "sub2임시2", "담은로직": [{"로직": PCT}], "자재": []})
other = skc.held(_read(me, "labor", "sub2임시2")) # 원본 열 = 바뀐 M01 사본
assert other["판"] != old["판"]
other_doc = _read(me, "labor", "sub2임시2") # 원본 열 = 바뀐 M01 사본
other = skc.held(other_doc)
assert other_doc["수식"]["부름"][PCT] != old_doc["수식"]["부름"][PCT] # 바뀐 M01 문서
with store.at(me): # 열 복사(copy_from) = 받은 사본 먼저
store.copy_from("labor", COL, "sub2임시2")
assert skc.held(_read(me, "labor", COL))["판"] == other["판"]
@@ -157,7 +159,7 @@ def test_old_doc_without_copy_old_path(world, monkeypatch):
path.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
assert "사본" not in _calc(me, COL)
_fake(monkeypatch, [_double(LB)])
moved = labor.run_line(m01.loaded()[1], PCT, {})["기준"]["계"]
moved = run_line(m01.loaded()[1], PCT, {})["기준"]["계"]
assert _calc(me, COL)["기준합"]["계"] == pytest.approx(moved, abs=1)
with store.at(me):
assert skc.has(labor.server(raw))
+1 -13
View File
@@ -42,17 +42,5 @@ def test_imported_old_equation_edit_refused(world):
doc = _doc(me, key)
assert "로직" not in doc["가져온"] and doc["가져온"]["문서"]["금액"]
edit = [{"할일": "식", "자리": "호표:0", "식": "0.5 × 2"}]
with pytest.raises(Exception, match="수식 고침 못 얹음"):
with pytest.raises(Exception, match="수식고침"): # 옛 칸 = 받지 않음(855-E 2-E4)
_save(me, key, {**doc, eqm.KEY: edit})
def test_screen_same_part_first_tab():
"""화면 — M02 수식 = 공용 수식 문서 화면(802-4b-2 · 옛 수식 나무 화면 걷음) · 첫 탭 · 옛 탭 걷음(799-2)."""
import re
from pathlib import Path
root = Path(__file__).resolve().parents[2] / "M02_MasterTemplete"
assert not (root / "M02_MasterTemplete_Sangeun_Equation.ts").exists()
tabs = (root / "M02_MasterTemplete_Sangeun_Tabs.ts").read_text(encoding="utf-8")
# 799-2 · 836-3 — 시트 · 인력·재료·경비 · 시험 계산 · 텍스트 수식 · 보기 고르기(단가산출 상세 탭) 걷음
assert not re.findall(r'\{ value: "(\w+)", label: ', tabs) and "createSegment" not in tabs
-36
View File
@@ -17,12 +17,10 @@ from fastapi import HTTPException
from M02_MasterTemplete import M02_Doc_B09 as doc_b09
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Doc_Router as router
from M02_MasterTemplete import M02_Doc_Sk as dsk
from M02_MasterTemplete import M02_Doc_Sk_Path as path
from M02_MasterTemplete import M02_Item_Snapshot as snap
from M02_MasterTemplete import M02_Item_Source as source
from M02_MasterTemplete import M02_Labor_Copy as lc
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.test_795_1_sk_copy import _calc, _changed, _doc, _fake, _live, _save, _sk
from resources.tester.test_795_2_sc_copy import LB, PCT, _double, _labor, _sc
@@ -71,11 +69,6 @@ def test_stamp_is_m01_doc_copy(world):
assert not got.get("따로") and got["로직"] and got["단가"]
m01_calc = dc.mc.calc(root, dc.ml.Links(_live(), dc.folder()))
assert _sum(me, key) == m01_calc["계"]
token = dsk.OLD.set(True)
try:
assert _sum(me, key) == m01_calc["계"] # 옛 엔진 금액과 같음
finally:
dsk.OLD.reset(token)
read = _at(me, path.read, key)
assert read["셈"]["계"] == m01_calc["계"] and read["사본"]["따로"] is False
@@ -181,39 +174,10 @@ def test_sc_and_labor_use_doc(world, monkeypatch):
monkeypatch.setattr(lc, "_traced", lambda *a, **k: runs.append(1) or real(*a, **k))
new = (_sc_calc(me, sc)["기준합"], _sc_calc(me, "sub2임시")["반영합"])
assert runs
token = dsk.OLD.set(True)
try:
assert (_sc_calc(me, sc)["기준합"], _sc_calc(me, "sub2임시")["반영합"]) == new
finally:
dsk.OLD.reset(token)
_fake(monkeypatch, [_changed(_live().logic(PCT))])
assert _sc_calc(me, sc)["기준합"] == new[0]
@pytest.mark.parametrize(
"code, rate, picks, marks",
[
("GC000261", 90, None, None), # 켜쌓기율 = 변수 r · 수량 × r ÷ 100
("GF000156", None, {"3": "MT004176", "4": "MT003834"}, None), # 고른 자재 = 요소 키
("GC000665", None, None, None), # 별도계상(기본) = 합밖 · 「재료비의 %」 밑엔 듦
],
)
def test_line_rules_in_doc(code, rate, picks, marks):
"""⑥ 일위대가 줄 옵션 = 문서 규칙(브레인 ④) — 옛 `run_line` · `drop_apart` 와 같은 금액."""
whole = _live()
old = labor.drop_apart(labor.run_line(whole, code, {}, rate, picks), marks)
assert old["기준"]
apart = dc.apart_of(marks, old.get("재료"))
doc = dc.line_doc(dc.folder()[code], rate, picks, apart)
if rate:
assert dc.RATE_ID in str(doc["금액"][0]["수량"])
if apart:
assert all(doc["금액"][n].get("합밖") for n in apart)
got = dc.mc.calc(doc, dc.ml.Links(whole, dc.folder()), dc.given_of(whole, code, {}))
assert {k: got[k] for k in dc.COSTS} == {k: old["기준"][k] for k in dc.COSTS}
assert dc.line_doc(dc.folder()[code]) is dc.folder()[code] # 옵션 없음 = 그 문서
def test_b09_copy_has_doc_file(world, monkeypatch):
"""⑦ B09 사본 = 단가 묶음 옆 `수식.json`(만든 때 부름) · 원본판에 듦(로직 몫 · 855-F B9-6) ·
M01 바뀌어도 그대로."""
+7 -3
View File
@@ -86,12 +86,16 @@ def test_층_SK_한_길_줄_합_기준(world, body):
def test_옛_엔진_안_돎(world, monkeypatch):
"""한 번 셈에 옛 엔진(`run_line`) 부름 0."""
"""한 번 셈에 옛 엔진(`master_formula.run`) 부름 0 · 옛 줄 셈 함수 없음(855-E 2-E4)."""
import importlib
me = world["personal"]
key = _sk(me, 바탕={"로직": FORM})
hits = []
real = labor.run_line
monkeypatch.setattr(labor, "run_line", lambda *a, **k: hits.append(1) or real(*a, **k))
eng = importlib.import_module("master_formula")
real = eng.run
monkeypatch.setattr(eng, "run", lambda *a, **k: hits.append(1) or real(*a, **k))
assert not hasattr(labor, "run_line")
_one_path(_run(me, _doc(me, key)))
assert hits == []
+19 -19
View File
@@ -148,37 +148,37 @@ def test_지정하면_새_파일까지_복사(world):
def test_단가_묶음은_닫혀_있음(world):
"""조합마다 복사본 단가 묶음만으로 돌린 값 = 마스터로 돌린 값(자동값 · 고르기 끝값)."""
"""조합마다 복사본 단가 묶음 + 수식 문서만으로 셈한 값 = 마스터로 셈한 값(자동값 · 고르기 첫 · 끝값 ·
문서 셈 · 855-E 2-E4 — 옛 엔진 대조 걷음)."""
from M02_MasterTemplete import M02_Doc_Copy as dc
from M02_MasterTemplete import M02_Item_Bundle as item_bundle
files, whole = prices.master()
combos = [r for d in files.values() if d.get("그룹") == "일위대가조합" for r in d["줄"]]
runs = 0
for ua in combos:
keys = prices.mcb.logic_keys(ua)
snapshot = prices.load_prices(prices.to_json(prices.collect(keys)))
docs = dc.closure(whole, keys)
snapshot = item_bundle.load(prices.to_json(prices.collect(keys)), docs)
for key in keys:
try:
row = whole.logic(key)
except prices.mf.FormulaError:
doc = docs.get(key)
if doc is None:
continue
picks = [
v for v in doc.get("변수") or [] if (v.get("연결") or {}).get("갈래") == "선택"
]
for pick in (0, -1):
values = m01.mau.values(whole, row)
for spec in row.get("입력", []):
if spec.get("고르기"):
values[spec["이름"]] = spec["고르기"][pick]
assert _run(whole, key, values) == _run(snapshot, key, values), (ua["키"], key)
given = {v["열쇠"]: v["연결"]["목록"][pick] for v in picks if v["연결"].get("목록")}
one = {"로직": key, "입력값": given}
want = prices.line(whole, dict(docs), one)
got = prices.line(snapshot, dict(docs), one)
assert _money(got) == _money(want), (ua["키"], key)
runs += 1
assert len(combos) >= 30 and runs >= 300
def _run(master: Any, key: str, values: dict) -> str:
try:
got = prices.mf.run(master, key, dict(values))
except Exception as error: # 까닭도 같아야 함
return f"멈춤 {error}"
return str(got.get("계", got.get("결과")))
# ── 계산 · 마스터 바뀜 · 새로 가져오기 ───────────────────
def _money(got: dict) -> str:
return str(got.get("기준") or got.get("결과") or got.get("까닭"))
def test_입력이_없으면_빠진_입력_목록_셈은_자동값(world):
+5 -4
View File
@@ -20,6 +20,7 @@ from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.helper_855_line import run_line
CODE = "GC000260"
@@ -36,8 +37,8 @@ def test_대상은_골쌓기_기준_주문_로직() -> None:
def test_90퍼센트는_100퍼센트_곱하기_0점9() -> None:
whole = m01.loaded()[1]
full = labor.run_line(whole, CODE, {})
part = labor.run_line(whole, CODE, {}, 90)
full = run_line(whole, CODE, {})
part = run_line(whole, CODE, {}, 90)
for k in (*labor.COSTS, "계"):
# 751-3 — 곱한 뒤 줄 0.1 원 · 비목 합 1 원 다시 버림
assert part["기준"][k] == pytest.approx(full["기준"][k] * Decimal("0.9"), abs=5)
@@ -47,7 +48,7 @@ def test_90퍼센트는_100퍼센트_곱하기_0점9() -> None:
assert b["금액"] == pytest.approx(a["금액"] * Decimal("0.9"), abs=Decimal("0.3"))
for k, v in a["비목"].items():
assert b["비목"][k] == pytest.approx(v * Decimal("0.9"), abs=Decimal("0.1"))
assert labor.run_line(whole, CODE, {}, 100) == full
assert run_line(whole, CODE, {}, 100) == full
@pytest.mark.parametrize("bad", [0, -5, 200.1, 90.55, "abc"])
@@ -91,7 +92,7 @@ def test_옛_단가승격도_율() -> None:
whole = m01.loaded()[1]
expand = refs.Expand(whole, lambda ref: doc)
got = expand({"층": "system", "주인": None, "키": "SP-900001"})
full = labor.run_line(whole, CODE, {})
full = run_line(whole, CODE, {})
times = _d(doc["배"])
assert got["기준"]["계"] == pytest.approx(full["기준"]["계"] * Decimal("0.9") / times, abs=5)
@@ -19,6 +19,7 @@ from M02_MasterTemplete import M02_Item_Snapshot as snap
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.helper_855_line import run_line
from resources.tester.test_m02_structure import write_sample_table
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -38,27 +39,27 @@ def _doc(**extra):
def test_로직_자재는_맨_위_층_재료_줄_재료_없는_로직은_빈_목록():
got = labor.run_line(_whole(), NET, {})
got = run_line(_whole(), NET, {})
assert [(m["차례"], m["품목"]["키"]) for m in got["재료"]] == [
(3, NET_ITEM),
(4, WIRE),
(5, "MT007705"),
]
assert all(m["고름"] is False and m["걸림"] == [] for m in got["재료"])
assert labor.run_line(_whole(), BARE, {})["재료"] == []
assert run_line(_whole(), BARE, {})["재료"] == []
def test_조건에_든_입력은_걸림():
mats = {m["차례"]: m for m in labor.run_line(_whole(), BORING, {})["재료"]}
mats = {m["차례"]: m for m in run_line(_whole(), BORING, {})["재료"]}
assert all(mats[n]["걸림"] == ["규격"] for n in range(4, 9))
assert mats[9]["걸림"] == []
def test_고름이_단가와_로직_재료비를_바꿈_고름_없으면_지금_값():
plain = labor.run_line(_whole(), NET, {})
again = labor.run_line(_whole(), NET, {}, None, None)
plain = run_line(_whole(), NET, {})
again = run_line(_whole(), NET, {}, None, None)
assert again["기준"] == plain["기준"] # 고름 없음 = 지금 길 그대로(회귀)
picked = labor.run_line(_whole(), NET, {}, None, {"3": WIRE})
picked = run_line(_whole(), NET, {}, None, {"3": WIRE})
row = picked["재료"][0]
assert (row["품목"]["키"], row["고름"]) == (WIRE, True)
assert row["단가"] == picked["재료"][1]["단가"] != plain["재료"][0]["단가"]
@@ -99,7 +100,7 @@ def test_단가승격도_고름을_따름_없으면_지금_값():
expand = refs.Expand(_whole())
plain = expand._promote({"담은로직": [{"로직": NET}], "배": 1})
picked = expand._promote({"담은로직": [{"로직": NET, "고름": {"3": WIRE}}], "배": 1})
assert plain["기준"] == labor.run_line(_whole(), NET, {})["기준"]
assert plain["기준"] == run_line(_whole(), NET, {})["기준"]
assert picked["기준"]["재료비"] < plain["기준"]["재료비"]
@@ -130,7 +131,7 @@ def _release(row: dict, before: dict, mats: list) -> dict:
def test_입력이_바뀌면_걸린_고름만_풂_화면_짝():
mats = labor._json(labor.run_line(_whole(), BORING, {})["재료"])
mats = labor._json(run_line(_whole(), BORING, {})["재료"])
picks = {"4": "MT007895", "9": WIRE}
row = {"로직": BORING, "입력값": {"규격": "NX"}, "고름": picks}
assert _release(row, {"규격": "NX"}, mats)["고름"] == picks # 그대로
+2 -1
View File
@@ -16,6 +16,7 @@ from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_Library_Uses as library_uses
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Template_Layers as layers
from resources.tester.helper_855_line import run_line
from resources.tester.test_m02_labor_calc_mirror import _same, _ts
from resources.tester.test_m02_structure import write_sample_table
@@ -88,7 +89,7 @@ def _read(folder, kind, key):
def _base(code):
import M01_MasterData.M01_MasterData_Store as m01
return labor.run_line(m01.loaded()[1], code, {})["기준"]
return run_line(m01.loaded()[1], code, {})["기준"]
# ── 자료 틀 ────────────────────────────────────────────────────────────