refactor(855-E 2-E4): M02 로직 줄 옛 엔진 셈 걷음 — Labor_Doc.run_line · pct_extras · logic_mats · layered · drop_apart

- M02_Labor_Copy.line: 프로젝트 층 · `dsk.OLD` 옛 엔진 갈래 걷음(층 셈과 같은 문서 셈) · 재료 줄 `걸림`(재료 조건 ·
  요소 키 틀 구멍의 입력 이름 = 문서 몫 · 화면 `releaseTied` 가 읽음 — 옛 logic_mats 와 같은 뜻)
- M02_Labor_Doc: `run_line` · `pct_extras` · `_pct_base` · `logic_mats` · `layered` · `drop_apart` · `_specs`(mf.inputs_of) 지움
  (제품 부르는 곳 0) · 담기 검사 = 새 `_head`(문서 입력 이름 · 재료 금액 줄 차례 — M01 로직 줄 안 읽음)
- M02_Doc_Sk: 아무도 안 켜는 `OLD` ContextVar 지움
- 시험: 옛 날 답 자리 = 새 `helper_855_line.run_line`(층 문서 셈 · 재료 직접계산) — 175 · 222_1 · 715_3 ·
  715_sangeun_store · 727 · 742_1 · 747_1 · 795_1 · 795_2 · m02_labor_layer · m02_labor_logic_mats · m02_labor_ref ·
  옛 엔진만 붙든 것 걷음: test_149_4 통째(옛 % 덧줄 표기) · 751_3 다섯(run_line 끝수) · 792_3 다시 버림 ·
  802_4a 옛 길 대조(OLD · run_line) · 855_sk_layers 옛 엔진 안 돎 = master_formula.run 부름 0 으로 ·
  helper_855_old_engine_routes 의 % 덧줄 표기 = 그 도우미 안으로(옛 길 도우미 · 엔진 몸과 같이 지움)
- 222_1 시멘트 단위 글 kg → ㎏(문서 단위)
- 검증: 관련 82 파일 + 지킴 + 관문 776 통과 · 빌더 --check 같음 · typecheck 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 10:33:46 +09:00
co-authored by Claude Opus 5.5
parent 7dfc402685
commit 35d3242711
22 changed files with 183 additions and 382 deletions
-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) # {키, 사본} — 수식 길만
+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
+27 -158
View File
@@ -7,34 +7,32 @@
이름은 구조물 열 이름(따로 안 둠).
수량 = `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
@@ -62,7 +60,6 @@ MARKS = {
}
MARK_DEFAULT = {"자재구분": "사급", "별도계상": "별도계상", "운반비": "포함"} # 읽을 때 기본(162-1)
ALIAS_MAX = 40 # 별칭(44-6) 글자 수 상한 — 화면 칸과 같음
_BRACE = re.compile(r"\{([^{}]+)\}") # 품목 조건의 {입력}
def _bad(text: str) -> store.StoreError:
@@ -80,11 +77,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 +148,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 +266,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 +292,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 +515,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("단위")}
+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["규격"] == "재료비의 %"
+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["줄"])
@@ -210,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 = 지문 다름(오판 막음)
+3 -2
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 — 같은 임시 층
@@ -87,7 +88,7 @@ def test_copy_stamped_logic_change_kept(world, monkeypatch):
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
@@ -157,7 +158,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))
-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 == []
+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, {})["기준"]
# ── 자료 틀 ────────────────────────────────────────────────────────────