Files
Aislo/resources/tester/test_719_3_sangeun_cover.py
T
eomsangdonandClaude Opus 5.5 5d8d9a4fd3 test(841-1): B09 = M02 값 — 산근 · 대가 · 고정 줄 셈 다듬기 · 낡은 시험 정리 — C 걸음
코드
- 고정 줄 단가 = M02_Labor_Fixed.line(사본 묶음 · 이은 노임 · 자재 = 묶음 값) — B09 단가 책으로 다시 안 덮음
- 대가 · 산근 고친 칸 = 품만 실제로(단가 칸 덮기 줄 남던 흠 · 품 고친 뒤 줄 금액 다시 셈 흠 py · ts 짝)
- 산근 글 = 엔진 단가 셈 그대로 · 별도계상 재료 줄 끝 「· 별도계상 = 0.0」 · 계 줄 = 블록 합
- 노무비 · 중기목록 이름에서 규격 겹침 뗌 · TS 바탕 셈 이름 PARTS → MACHINE_PARTS(짝 시험이 TS 를 이어 붙일 때 겹침)

시험(고친 까닭 = 단가 원천이 B09 책 → M02 엔진 · 노임 · 기계 덮개 · 단가 고친 칸 · 중기사용료 걷음)
- 144 바탕 · 뼈대: 운전사 · 중기사용료 · 경비 · 덮개 시험 걷음 → 노무 · 중기 나열 · 사급 표시 · 자재만 책
- 145-1 · 145-2 · 155 · 157-1 · 166-2 · 166-6 · 719-3 · 719-4 · 723-4 · 778-4 · 792-3: 줄 단가 = own(엔진) · 산근 = Solver() · collect 새 부름 꼴
- 702 · 705-1 · 719-2: 단가 칸 덮개 = 안 읽음 · 고정 줄 = M02 셈(노임 새 판 따라가기 시험 걷음)
- 203-1 · 296 · 703-3 · 795-4: 단가 책 = 자재 줄로
- 707 · 707-6 · 707-7: 단가표 불러오기 = 자재만 · 거창 이은 안내판 줄 = M02 사본 셈(엑셀 −50,000)
- 201-1: 환율 · 중기사용료 표 걷음 · b09 저장 속도: 산근 앞 풀이 그대로(단가 표 같음 견줌 걷음)
- 대상 113 파일 764 통과 · 25 실패 = 원래 실패(formatMoney · formatPrice 없음 · 단위 글 ㎜ · sec · 719-1 · 796-2e · 717-4 · 721 · 311 · 243 · 246)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:57:01 +09:00

224 lines
10 KiB
Python

"""719-3 B09 산근 덮개 — 이 공사 단가산출근거 고친 칸(품 · 단가) · 거울(`Sangeun_Cover.py` ↔ `.ts`).
- 고침 없음 = 서버 풀이 그대로(금액 전후 같음)
- 품 · 단가 고침 = 줄 금액 ROUNDDOWN(단가 × 품, 1) · 총계 · 목록표 · 고친 줄 base · covered
- 하위 산근 고침 = 부르는 블록 산근 줄 단가 · 총계로 이어짐 · % 덧줄(인건비의 %) = 밑수 비례
- 줄 이름 다름 · 없는 블록 = 짝 잃음(알림만) · 저장 다듬기에 남음
- 덮개 → 설계내역서 손 줄 단가 · 원가계산서 직접비 · [업데이트](새 단가 판) 뒤 덮개 지킴
"""
import copy
import json
import re
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402
from B09_Estimation import B09_Estimation_Router as router_mod # noqa: E402
from B09_Estimation import B09_Estimation_Sangeun as sangeun # noqa: E402
from B09_Estimation import B09_Estimation_Store as store # noqa: E402
from B09_Estimation.B09_Estimation_Calc_Base import rounddown # noqa: E402
from B09_Estimation.B09_Estimation_Sangeun_Cover import cover_sangeun, line_id # noqa: E402
IMPORTS = re.compile(r"^import[^;]*;\n", re.MULTILINE)
CODES = ["GF000169", "GC001018", "GC000337", "GF000103"] # 하위 산근 · 인건비 % · 중기 · 중기
GIVEN = {"GF000169": {"콘크리트량": 0.2, "거푸집면적": 1.5, "연결철근량": 0.01, "비닐면적": 0.5}}
def _user(cover=None):
rows = [
{"key": f"hand:t{i}", "name": f"시험 {c}", "spec": "", "unit": "식", "qty": 10,
"ref": {"tab": "logic", "code": c, "given": GIVEN.get(c, {})}}
for i, c in enumerate(CODES)
] # fmt: skip
return {"bill": {"v": 2, "rows": rows}, **({"sg_cover": cover} if cover else {})}
def _inputs():
return prices.build_inputs(None, sangeun.hand_resource_keys(_user()))
@pytest.fixture(scope="module")
def sg():
return sangeun.collect([], sangeun.hand_sources(_user())) # 841-1 단가 = M02 엔진
def _block(got, code):
return next(b for b in got["sg"] if b["logic"] == code)
def _at(block, kind):
return next((n, ln) for n, ln in enumerate(block["lines"]) if ln["kind"] == kind)
def _ts(sg, cover):
base = IMPORTS.sub("", (ROOT / "B09_Estimation/B09_Estimation_Calc_Base.ts").read_text("utf-8"))
calc = IMPORTS.sub(
"", (ROOT / "B09_Estimation/B09_Estimation_Sangeun_Cover.ts").read_text("utf-8")
)
body = (
f"\nconst sg = {json.dumps(sg, ensure_ascii=False)};"
f"\nconst c = {json.dumps(cover, ensure_ascii=False)};"
"\nconsole.log(JSON.stringify(coverSangeun(sg, c)));"
)
result = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-"],
input=base + calc + body, capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
def _same(a, b):
if isinstance(a, dict) and isinstance(b, dict):
return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
if isinstance(a, list) and isinstance(b, list):
return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return abs(a - b) < 1e-9
return a == b
def _cover(sg):
"""품 · 하위 산근 · 율 고침 한 벌(841-1 단가 칸은 안 읽음 — 함께 넣어 버려짐을 봄) + 짝 잃은 칸 둘."""
sub = _block(sg, "GF000155")
n_l, labor = _at(sub, "labor")
people = _block(sg, "GC001018")
n_p, first = _at(people, "labor")
n_x, _extra = _at(people, "extra")
net = _block(sg, "GC000337")
n_m, machine = _at(net, "machine")
n_t, mat = _at(net, "material")
return {
sub["key"]: {line_id(n_l, labor): {"qty": labor["qty"] * 2}},
people["key"]: {line_id(n_p, first): {"labor": 300000}, line_id(n_x, _extra): {"qty": 5}},
net["key"]: {
line_id(n_m, machine): {"qty": machine["qty"] * 1.5, "expense": 20000},
line_id(n_t, mat): {"qty": mat["qty"] + 1, "material": 4500},
},
"SG:없는블록": {"0:x": {"qty": 1}},
net["key"] + "x": {"0:다른이름": {"qty": 1}},
}
def test_고침_없음_그대로(sg):
got = cover_sangeun(sg, {})
assert got["sg"] is sg["sg"] and got["sg_list"] is sg["sg_list"] and got["sg_orphans"] == []
only_orphans = cover_sangeun(sg, {"SG:없는블록": {"0:x": {"qty": 1}}})
assert only_orphans["sg"] == sg["sg"] and only_orphans["sg_orphans"] == [
{"key": "SG:없는블록", "line": "0:x"}
]
def test_품_고침_줄_금액_총계_단가_칸_안_읽음(sg):
before = copy.deepcopy(sg)
got = cover_sangeun(sg, _cover(sg))
assert sg == before # 받은 답 안 고침
net0, net = _block(sg, "GC000337"), _block(got, "GC000337")
n, m = _at(net, "machine")
m0 = _at(net0, "machine")[1]
assert m["covered"] == ["qty"] and m["base"] == {"qty": m0["qty"]}
assert m["price"] == m0["price"] # 단가 칸(경비 20,000) = 안 읽음
assert m["expense"] == rounddown(m0["price"]["expense"] * m["qty"], 1)
for part in ("labor", "material", "expense"):
assert net[part] == rounddown(sum(ln[part] for ln in net["lines"]), 0)
assert net["sum"] == net["labor"] + net["material"] + net["expense"] != net0["sum"]
row = next(r for r in got["sg_list"] if r["key"] == net["key"])
assert row["sum"] == net["sum"] and row["covered"] == 2
people = _block(got, "GC001018")
assert "covered" not in _at(people, "labor")[1] # 단가만 든 칸 = 고침 없음
untouched = _block(got, "GF000103")
assert untouched == _block(sg, "GF000103") # 덮개 안 닿은 블록 = 서버 값
def test_하위_산근_이어짐_덧줄_비례(sg):
got = cover_sangeun(sg, _cover(sg))
sub, parent = _block(got, "GF000155"), _block(got, "GF000169")
line = next(ln for ln in parent["lines"] if ln["ref"] and ln["ref"]["key"] == sub["key"])
assert line["price"]["labor"] == sub["labor"] != _block(sg, "GF000155")["labor"]
assert line["labor"] == rounddown(sub["labor"] * line["qty"], 1)
assert parent["labor"] > _block(sg, "GF000169")["labor"]
people0, people = _block(sg, "GC001018"), _block(got, "GC001018")
n, extra = _at(people, "extra")
assert extra["of"] == "people" and extra["qty"] == 5
base0 = sum(ln["labor"] for ln in people0["lines"][:n] if ln["kind"] == "labor")
base1 = sum(ln["labor"] for ln in people["lines"][:n] if ln["kind"] == "labor")
value0 = _at(people0, "extra")[1]["price"]["expense"]
assert extra["price"]["expense"] == pytest.approx(
value0 * base1 / base0 * 5 / extra["base"]["qty"]
)
def test_짝_잃음(sg):
got = cover_sangeun(sg, _cover(sg))
assert {o["key"] for o in got["sg_orphans"]} == {
"SG:없는블록",
_block(sg, "GC000337")["key"] + "x",
}
def test_거울_파이썬_TS(sg):
cover = _cover(sg)
assert _same(cover_sangeun(sg, cover), _ts(sg, cover))
assert _same(cover_sangeun(sg, {}), _ts(sg, {}))
def test_저장_다듬기_남음(sg):
cover = _cover(sg)
clean = store.clean_user({"sg_cover": cover})["sg_cover"]
want = {
k: {line: {"qty": c["qty"]} for line, c in lines.items() if "qty" in c}
for k, lines in cover.items()
}
assert clean == {k: v for k, v in want.items() if v} # 841-1 품만 남음
def test_덮개_대가_원가계산서_업데이트_뒤_지킴(sg, tmp_path):
inputs = _inputs()
net = _block(sg, "GC000337")
n, mat = _at(net, "material")
mine = {"materials": {mat["ref"]["key"]: {"supply": "사급"}}} # 841-1 기본 별도계상 끔
plain = router_mod.compute_sheets(tmp_path, copy.deepcopy(inputs), {**_user(), **mine})
cover = {net["key"]: {line_id(n, mat): {"qty": mat["qty"] + 1}}}
covered = router_mod.compute_sheets(tmp_path, copy.deepcopy(inputs), {**_user(cover), **mine})
gap = rounddown(rounddown(mat["price"]["material"] * (mat["qty"] + 1), 1) - mat["material"], 0)
row0 = next(r for r in plain["sg_list"] if r["key"] == net["key"])
row1 = next(r for r in covered["sg_list"] if r["key"] == net["key"])
assert row1["material"] - row0["material"] in (gap, gap + 1, gap - 1)
hand = next(r for r in covered["bill"]["rows"] if r["key"] == "hand:t2")
hand0 = next(r for r in plain["bill"]["rows"] if r["key"] == "hand:t2")
assert hand["material"] - hand0["material"] == (row1["material"] - row0["material"]) * 10
m0, m1 = plain["total"]["sums"]["material"], covered["total"]["sums"]["material"]
assert m1 - m0 == hand["material"] - hand0["material"]
# [업데이트] = 새 단가 판 — 산근 키 같음 · 덮개 칸 그대로 · 밑 값 = 새 단가
newer = copy.deepcopy(inputs)
for row in newer.get("materials") or []:
if row.get("key") == mat["ref"]["key"]:
for k in ("price", "applied", "lowest"):
if isinstance(row.get(k), (int, float)):
row[k] = row[k] * 2
again = router_mod.compute_sheets(tmp_path, newer, {**_user(cover), **mine})
line = _block(again, "GC000337")["lines"][n]
assert line["covered"] == ["qty"] and line["qty"] == mat["qty"] + 1
assert line["base"]["qty"] == mat["qty"] and again["sg_orphans"] == []
def test_덮인_답_다시_덮음_되돌림(sg):
"""서버 답이 덮인 채 옴([저장] · 셈 답) — 화면 짝이 벗기고 다시 덮음 · 덮개 지우면 처음 값."""
cover = _cover(sg)
once = cover_sangeun(sg, cover)
assert cover_sangeun(once, cover) == once # 두 번 덮어도 같음(원래 값 = 처음 값)
back = cover_sangeun(once, {})
assert back["sg"] == sg["sg"] and back["sg_list"] == sg["sg_list"]
assert back["sg_gaps"] == sg["sg_gaps"]
assert _same(cover_sangeun(once, cover), _ts(once, cover))
assert _same(back, _ts(once, {}))