"""778-4 단가산출(SK) 율 줄 — 고정 비율 더한줄 · 기준 = 비목 · 묶음 · 줄 목록 · 율 위 율 (요구 623 · 분석 621-D 2-4 · 5-2) · M01 읽기만 · 쓰는 일 없음. - 서버 셈(`M02_Sangeun_Calc._rated`) = 손셈 · 묶음 인력 = 인력 줄만(기계 노무 섞인 블록 = 노무비 합과 다름) - 밑 공용 함수 `M02_Labor_Fixed.rate_base` ↔ `Labor_Calc.ts` `rateBase` 거울 · 일위대가 비율 줄 settle 거울(1e-9) - 검사 — 자기 · 뒤 율 줄 · 꼴 틀린 열쇠 · 모르는 기준 막음 · 율 줄 없는 문서 = 엔진 한 번(값 그대로) - B09 — 율 기준 → pct 밑수(`part:` · `bundle:` · `rows:`) · 파이썬 = TS · SK 블록 밑수 꼴 - 굳힘 — 바탕 없는 SK 율 줄 = 한 줄로 안 펼침 · 겹침(`compose`) 열쇠 새 차례 """ from __future__ import annotations import json import os import re import subprocess from decimal import Decimal from pathlib import Path import pytest from B09_Estimation import B09_Estimation_Labor_Source as source 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_Fixed as fixed from M02_MasterTemplete import M02_Library_Flat as flat from M02_MasterTemplete import M02_Sangeun_Calc as calc from M02_MasterTemplete import M02_Sangeun_Doc as sd ROOT = Path(__file__).resolve().parents[2] HERE = os.path.dirname(os.path.abspath(__file__)) IMPORTS = re.compile(r"^import[^;]*;\r?\n", re.MULTILINE) SUB = "GC000999" # 원/주 · 조경공 · 보통인부 + 고소작업차 로직 줄 + 덧줄 공구손료 3 % MACHINE = "GC000268" # 기계경비(손료 보정 없는 기종) — 노무비 몫 있음 def _whole(): return m01.loaded()[1] def _rate(basis, q=2, part="경비", name="공구손료"): fx = {"이름": name, "단가": {}, "이음": {}, "비율": {"기준": basis, "비목": part}} return {"고정": fx, "수량": q} def _doc(adds, **more): return { "키": "SK-000001", "이름": "율 시험", "단위": "㎥", "바탕": None, "더한줄": adds, **more, } def _run(doc): whole = _whole() return labor._json(calc.run(sd.clean(doc, None, whole), whole)) LABOR = [ {"종류": "인력", "요소": "LB000002", "수량": 0.5}, # 보통인부 {"종류": "인력", "요소": "LB000003", "수량": 0.2}, # 특별인부 {"종류": "로직", "로직": MACHINE, "입력값": {}, "수량": 0.29}, ] # ── 서버 셈 ────────────────────────────────────────────────────────────────── @pytest.mark.parametrize( "adds, why", [ ([LABOR[0], _rate(["add:#1"])], "자기"), ([LABOR[0], _rate(["add:#2"]), _rate("인력")], "뒤 율"), ([LABOR[0], _rate(["보통인부"])], "꼴 아님"), ([LABOR[0], _rate("합계")], "비율"), ], ) def test_검사_막음(adds, why): with pytest.raises(sd.DocError, match=why): sd.clean(_doc(adds), None, _whole()) # ── 밑 공용 함수 거울 ─────────────────────────────────────────────────────── def _node(payload: dict): got = subprocess.run( ["node", os.path.join(HERE, "helper_m02_labor_calc.cjs")], input=json.dumps(payload, ensure_ascii=False, default=float), capture_output=True, text=True, encoding="utf-8", check=True, ) # fmt: skip return json.loads(got.stdout) ROWS = [ {"키": "a", "묶음": "인력", "비목": {"노무비": 1000.5, "재료비": 0, "경비": 0}}, {"키": "b", "묶음": "장비", "비목": {"노무비": 300.25, "재료비": 12.5, "경비": 700}}, {"키": "c", "묶음": "재료", "비목": {"노무비": 0, "재료비": 4000, "경비": None}}, {"키": "d", "묶음": None, "비목": {"노무비": 10, "재료비": 20, "경비": 30}}, {"키": "r", "묶음": None, "비목": {"노무비": 0, "재료비": 0, "경비": 55.5}, "율": True}, ] @pytest.mark.parametrize( "basis", [ "노무비", "재료비", "경비", "인력", "재료", "장비", ["a", "c"], ["a", "r"], ["zz"], ["a", "b@노무비"], ["b@경비", "c@재료비", "c@재료비"], ["a@없는칸"], ], # fmt: skip ) def test_밑_파이썬과_TS_같음(basis): py = fixed.rate_base(basis, json.loads(json.dumps(ROWS))) assert _node({"밑": {"기준": basis, "줄": ROWS}}) == pytest.approx(float(py), rel=1e-9) def _fx(name, price, link=None, rate=None): fx = {"이름": name, "단위": "식", "단가": price, "이음": link or {}} return fx | ({"비율": rate} if rate else {}) def test_일위대가_비율_줄_묶음_목록_settle_거울(): plain = _fx("손 노임", {"노무비": 50000}) tool = _fx("공구손료", {}, rate={"기준": "인력", "비목": "경비"}) doc = labor.clean( { "담은로직": [ {"고정": _fx("보통인부", {"노무비": 1}, {"노임": "LB000002"}), "수량": {"손": 0.5}}, {"고정": plain, "수량": {"손": 0.3}}, {"고정": tool, "수량": {"손": 2}}, {"고정": _fx("목록 율", {}, rate={"기준": [fixed.fixed_id(tool)], "비목": "재료비"}), "수량": {"손": 10}}, {"고정": _fx("노무 율", {}, rate={"기준": "노무비", "비목": "경비"}), "수량": {"손": 3}}, ], "자재": [], } ) # fmt: skip answer = labor.calc(doc, {}) py = labor.settle(answer, doc, {}) ts = _node({"답": answer, "문서": doc, "값": {}}) _same(json.loads(json.dumps(labor._json(py), default=float)), ts) lines = py["줄"] people = Decimal(str(lines[0]["반영"]["노무비"])) assert lines[2]["기준"]["경비"] == people # 인력 = 노임 이음 줄만(손 노임 뺌) assert lines[3]["기준"]["재료비"] == lines[2]["반영"]["계"] # 율 위 율 assert lines[4]["기준"]["경비"] == people + Decimal(str(lines[1]["반영"]["노무비"])) def _same(a, b) -> None: if isinstance(a, dict): assert set(a) == set(b), set(a) ^ set(b) for k in a: _same(a[k], b[k]) elif isinstance(a, list): assert len(a) == len(b) for x, y in zip(a, b): _same(x, y) elif isinstance(a, (int, float)) and not isinstance(a, bool): assert b == pytest.approx(a, rel=1e-9, abs=1e-9) else: assert a == b # ── B09 ───────────────────────────────────────────────────────────────────── def test_B09_율_기준_밑수_꼴(): rate = {"이름": "공구손료", "비율": {"기준": "인력", "비목": "경비"}} assert source.fixed_line(rate, 2)["base"] == "bundle:labor" rate["비율"]["기준"] = "노무비" assert source.fixed_line(rate, 2)["base"] == "part:labor" rate["비율"]["기준"] = ["x", "y"] assert source.fixed_line(rate, 2)["kind"] == "blank" # 일위대가 블록 = 열쇠 차례 모름 assert source.fixed_line(rate, 2, {"y": 4, "x": 1})["base"] == "rows:1,4" rate["비율"]["기준"] = ["x", "y@노무비", "z"] assert source.fixed_line(rate, 2, {"y": 4, "x": 1})["base"] == "rows:1,4@labor" BLOCK = { "id": "DGR", "cover": "S:r", "kind": "조합", "name": "율 블록", "spec": "", "unit": "㎥", "cite": "", "origin": {}, "lines": [ # 841-1 줄 단가 = M02 엔진(`own`) · 고정 줄 = M02 고정 줄 셈(이은 노임 100,000 그대로) {"kind": "labor", "key": "L1", "name": "보통인부", "qty": 0.5, "own": {"labor": 172068}}, {"kind": "fixed", "name": "특별인부", "qty": 0.2, "own": {"labor": 100000.0}, "link": {"labor": "L9", "material": None, "machine": None}}, {"kind": "machine", "key": "E1", "name": "굴착기", "qty": 0.29, "own": {"labor": 30000, "material": 5000, "expense": 70000}}, {"kind": "material", "key": "M1", "name": "시멘트", "qty": 3, "own": {"material": 5000}}, {"kind": "pct", "name": "공구손료", "part": "expense", "base": "bundle:labor", "qty": 2}, {"kind": "pct", "name": "율 위 율", "part": "material", "base": "rows:3,4", "qty": 10}, {"kind": "pct", "name": "장비 율", "part": "expense", "base": "bundle:machine", "qty": 1}, {"kind": "pct", "name": "절 노무", "part": "expense", "base": "rows:0,2@labor", "qty": 6}, ], } # fmt: skip BOOKS = { "labor": [{"key": "L1", "price": 172068}], "material": [{"key": "M1", "price": 5000}], "machine": [{"key": "E1", "labor": 30000, "material": 5000, "expense": 70000}], } def _ts_labor(daega, sheets): base = IMPORTS.sub("", (ROOT / "B09_Estimation/B09_Estimation_Calc_Base.ts").read_text("utf-8")) code = IMPORTS.sub( "", (ROOT / "B09_Estimation/B09_Estimation_Calc_Labor.ts").read_text("utf-8") ) body = ( f"\nconst d = {json.dumps(daega, ensure_ascii=False)};" f"\nconst s = {json.dumps(sheets, ensure_ascii=False)};" "\nconsole.log(JSON.stringify(computeLabor(d, s, {}, {})));" ) got = subprocess.run( ["node", "--experimental-strip-types", "--no-warnings", "--input-type=module-typescript", "-e", base + code + body], capture_output=True, text=True, encoding="utf-8", timeout=60, ) # fmt: skip assert got.returncode == 0, got.stderr return json.loads(got.stdout) def test_B09_bundle_rows_파이썬과_TS_같음_손셈(): lines = [{**ln, "cid": f"{ln['kind']}:{ln['name']}#0"} for ln in BLOCK["lines"]] daega = {"blocks": [{**BLOCK, "lines": lines}], "owners": {}} py = json.loads(json.dumps(compute_labor(daega, BOOKS, {}), ensure_ascii=False)) _same(py, _ts_labor(daega, BOOKS)) got = {ln["name"]: ln for ln in py["daega_blocks"][0]["lines"]} people = 86034.0 + 20000.0 # 보통인부 + 노임 이음 고정 줄 assert got["공구손료"]["amounts"]["expense"] == pytest.approx(people * 0.02, abs=0.1) tool = got["공구손료"]["amounts"]["expense"] assert got["율 위 율"]["amounts"]["material"] == pytest.approx((15000 + tool) * 0.1, abs=0.1) mach = got["굴착기"]["amount"] assert got["장비 율"]["amounts"]["expense"] == pytest.approx(mach * 0.01, abs=0.1) labor_part = got["굴착기"]["amounts"]["labor"] assert got["절 노무"]["amounts"]["expense"] == pytest.approx( (86034.0 + labor_part) * 0.06, abs=0.1 ) assert py["gaps"] == [] # ── 굳힘 ──────────────────────────────────────────────────────────────────── def test_바탕_없는_SK_율_줄은_한_줄로_안_펼침(): whole = _whole() y = sd.clean(_doc([LABOR[0], _rate("인력")]), None, whole) with pytest.raises(sd.DocError, match="율 줄"): flat.sk_adds(y, Decimal(2), whole, {}) plain = sd.clean(_doc([LABOR[0]]), None, whole) assert flat.sk_adds(plain, Decimal(2), whole, {})[0]["수량"] == 1 # 율 없으면 그대로 # ── 화면 — 더한줄 지움 · 되살림 때 율 기준 열쇠 옮김(`logic/M02_Sangeun_Undo.ts`) ──────────