"""848-7 불러오기 — 엑셀 판 기계 정체 · 가져온 값 층 · 비목곱(세 줄 → 기계 한 줄) 지킴 시험. ① 비목곱 — 한 줄(수량 × 곱 × 단가[비목]) 금액 = 세 줄 금액 · 틀린 곱 = 그 줄 멈춤 · 파이썬 = TS 거울 ② 엑셀 판 보기(`view` ↔ `importView`) — 기계 줄 = 숫자 + 입력 · 잠금 · 다른 줄 = 숫자만 · 거울 · 그 꼴에서도 작업량 엔진이 기계를 찾음(셈 답 `작업량` 우리 판과 같음 · 금액 = 엑셀 값) ③ 「톤/hr」 = 「ton/hr」(파이썬 = TS) ④ 세 줄 합침 — 재료비 수량 = 노무비 수량 × 곱이면 한 줄 + 비목곱(금액 그대로) · 꼴이 다르면 세 줄 그대로 ⑤ 실제 원파일 견본(없으면 skip) — 가져온 값 층(굴착기 · 덤프) · 켜기 전 금액 그대로 · 켜면 Q = 경쟁사 Q · 읽기 답 `위덮음` · 미리 셈에 시간당을 켜면 그 값으로 셈 """ from __future__ import annotations import copy as cp import importlib import json import os import subprocess import sys from decimal import Decimal as D from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[2] HERE = Path(__file__).resolve().parent for p in (ROOT, HERE): if str(p) not in sys.path: sys.path.insert(0, str(p)) from M01_MasterData import M01_MasterData_Store as m01 # noqa: E402 — scripts 길 from M02_MasterTemplete import M02_Doc_Import as dim # noqa: E402 from M02_MasterTemplete import M02_Doc_Import_Carry as car # noqa: E402 from M02_MasterTemplete import M02_Doc_Import_Shape as shape # noqa: E402 mc = importlib.import_module("master_doc_calc") ml = importlib.import_module("master_doc_link") mw = importlib.import_module("master_doc_work") COSTS = ("노무비", "재료비", "경비") NO = "0201-0100" # 굴착기(무한궤도) 1.0㎥ @pytest.fixture(scope="module") def links(): return ml.Links(m01.loaded()[1]) def _var(name, link, unit=""): return {"열쇠": name, "기호": name.split("_")[0], "아래": "_".join(name.split("_")[1:]), "위": "", "이름": name, "단위": unit, "연결": link} # fmt: skip def _num(name, v): return _var(name, {"갈래": "숫자", "값": D(str(v))}) def _machine(name, col, excel): link = {"갈래": "단가산출", "키": "GC000267", "입력": {"기계": f"'{NO}'", "지역": "'전국평균'"}} return _var(name, {**link, **({"칸": col} if col else {}), "엑셀": excel}) def _three(material_qty): """노 · 재 · 경 세 줄(같은 기계 · 재료비 수량만 다름) 문서.""" vars_ = [_num("q", "26.21"), _num("c", "18.16"), _num("a", "14.11"), _num("b", "1.5"), _machine("P_노무", "노무비", D(55700)), _machine("P_재료", "재료비", D(27932)), _machine("P_경비", "경비", D(19631))] # fmt: skip lines = [{"이름": "노 무 비", "단위": "시간", "비목": "노무비", "수량": "1 ÷ q", "단가": "P_노무"}, {"이름": "재 료 비", "단위": "시간", "비목": "재료비", "수량": material_qty, "단가": "P_재료"}, {"이름": "경 비", "단위": "시간", "비목": "경비", "수량": "1 ÷ q", "단가": "P_경비"}] # fmt: skip return { "키": "SK-999998", "이름": "덤프", "결과단위": "원/㎥", "변수": vars_, "식": [], "금액": lines, } def _money(ans): return [ans.get(k) for k in (*COSTS, "계")] # ── ① · ④ 비목곱 · 세 줄 합침 ───────────────────────────────────────────── def test_세_줄_합침_비목곱_금액_같음(links): doc = _three("1 ÷ q × ((c - a - b) ÷ c)") before = mc.calc(dim.view(doc, "엑셀"), links) merged = cp.deepcopy(doc) shape.machines(merged, {}, {}) assert len(merged["금액"]) == 1 line = merged["금액"][0] assert line["비목"] == "묶음" and line["수량"] == "1 ÷ q" and line["비목곱"] == {"재료비": "(c - a - b) ÷ c"} # fmt: skip after = mc.calc(dim.view(merged, "엑셀"), links) assert after["셈됨"] and _money(after) == _money(before) == [D(2125), D(149), D(748), D(3022)] assert after["줄"][0]["비목"] == { "노무비": D("2125.1"), "재료비": D("149.6"), "경비": D("748.9"), } def test_세_줄_꼴_다르면_그대로(): doc = _three("1 ÷ c") # 노무비 수량의 인수를 다 담지 않음 shape.machines(doc, {}, {}) assert len(doc["금액"]) == 3 and not any("비목곱" in x for x in doc["금액"]) def test_비목곱_틀리면_그_줄_멈춤(links): doc = _three("1 ÷ q") shape.machines(doc, {}, {}) doc["금액"][0]["비목곱"] = {"재료비": "없는기호 × 2"} ans = mc.calc(dim.view(doc, "엑셀"), links) assert not ans["셈됨"] and "없는기호" in ans["줄"][0]["까닭"] # ── ② 엑셀 판 기계 정체 ─────────────────────────────────────────────── def _excel_doc(links): """터파기(GC000088) 기계 줄 단가를 엑셀 값 기억 연결로(가져온 식 꼴).""" doc = cp.deepcopy(links.doc("GC000088")) for v in doc["변수"]: link = v.get("연결") or {} if link.get("갈래") == "단가산출" and "기계" in (link.get("입력") or {}): link["엑셀"] = {"노무비": D(59020), "재료비": D(43274), "경비": D(29621)} return doc def test_엑셀_판_기계_줄_숫자_입력_잠금_없음(links): doc = _excel_doc(links) xv = dim.view(doc, "엑셀") got = [v["연결"] for v in xv["변수"] if "엑셀" in (next(x for x in doc["변수"] if x["열쇠"] == v["열쇠"])["연결"])] # fmt: skip assert got and all(x["갈래"] == "숫자" and "기계" in x["입력"] and "잠금" not in x for x in got) # fmt: skip ours = mc.calc(dim.view(doc, "우리"), links) xl = mc.calc(xv, links) wx = [z.get(mw.WORK) for z in xl["줄"] if z.get(mw.WORK)] wu = [z.get(mw.WORK) for z in ours["줄"] if z.get(mw.WORK)] assert wx and [{k: w[k] for k in ("기계", "꼴", "율", "값", "단위")} for w in wx] == [ {k: w[k] for k in ("기계", "꼴", "율", "값", "단위")} for w in wu ] machine = next(z for z in xl["줄"] if z.get(mw.WORK)) assert {k: machine["단가"][k] for k in COSTS} == { "노무비": D(59020), "재료비": D(43274), "경비": D(29621), } def test_엑셀_판_시간당_켜면_엑셀_값_나누기_우리_Q(links): doc = _excel_doc(links) key = next(z[mw.WORK]["기호"] for z in mc.calc(dim.view(doc, "엑셀"), links)["줄"] if z.get(mw.WORK)) # fmt: skip on = { **dim.view(doc, "엑셀"), "기계덮음": {key: {mw.WORK: {"방식": "시간당", "식": "GC001147"}}}, } ans = mc.calc(on, links) line = next(z for z in ans["줄"] if z.get(mw.WORK)) assert ans["셈됨"] and line[mw.WORK]["꼴"] == "시간당" and line["단가"]["노무비"] == D(59020) assert float(line["수량"]) == pytest.approx(1 / float(line[mw.WORK]["값"]), rel=1e-9) # ── ① ② ③ 거울 ───────────────────────────────────────────────────────── _JS = r""" const fs = require("fs"), path = require("path"); const ts = require(path.join(process.argv[1], "config", "node_modules", "typescript")); const cache = new Map(); function load(at) { if (cache.has(at)) return cache.get(at); const js = ts.transpileModule(fs.readFileSync(at, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, }).outputText; const box = { exports: {} }; cache.set(at, box.exports); const need = (p) => (p.startsWith(".") ? load(path.resolve(path.dirname(at), `${p}.ts`)) : require(p)); new Function("exports", "module", "require", js)(box.exports, box, need); return box.exports; } const cu = (n) => load(path.join(process.argv[1], "common_util", n)); const imp = cu("common_util_formula_doc_import.ts"), work = cu("common_util_formula_doc_work.ts"); const x = JSON.parse(fs.readFileSync(0, "utf8")); process.stdout.write(JSON.stringify({ 보기: x.보기.map((d) => imp.importView(d, "엑셀")), 단위: x.단위.map(work.normUnit) })); """ def test_거울_보기_단위(links): docs = [_excel_doc(links), _three("1 ÷ q × ((c - a - b) ÷ c)")] units = ["톤/hr", "TON/HR", "톤", "인/톤"] want = {"보기": [dim.view(d, "엑셀") for d in docs], "단위": [mw.norm_unit(u) for u in units]} assert want["단위"] == ["ton/hr", "ton/hr", "톤", "인/톤"] proc = subprocess.run(["node", "-e", _JS, str(ROOT)], input=json.dumps(ml._norm({"보기": docs, "단위": units}), ensure_ascii=False), # fmt: skip capture_output=True, text=True, encoding="utf-8", check=True) # fmt: skip assert json.loads(proc.stdout) == json.loads(json.dumps(ml._norm(want), ensure_ascii=False)) def test_거울_비목곱_엑셀_판_셈(links): from test_846_1_machine_work import Rec, _lines, _same rec = Rec(links) merged = _three("1 ÷ q × ((c - a - b) ÷ c)") shape.machines(merged, {}, {}) cases = [{"문서": dim.view(merged, "엑셀"), "덮음": None}, {"문서": dim.view(_excel_doc(links), "엑셀"), "덮음": None}] # fmt: skip key = next(z[mw.WORK]["기호"] for z in mc.calc(cases[1]["문서"], links)["줄"] if z.get(mw.WORK)) # fmt: skip cases.append({"문서": cases[1]["문서"], "덮음": {key: {mw.WORK: {"방식": "시간당", "식": "GC001147", "변수": {"K입력": 0.8}}}}}) # fmt: skip want = [ mc.calc({**c["문서"], **({"기계덮음": c["덮음"]} if c["덮음"] else {})}, rec) for c in cases ] proc = subprocess.run(["node", os.path.join(HERE, "helper_846_1_machine_work.cjs")], input=json.dumps(ml._norm({"문서들": rec.docs, "대상": cases, "기록": rec.log}), ensure_ascii=False), # fmt: skip capture_output=True, text=True, encoding="utf-8", check=True) # fmt: skip got = json.loads(proc.stdout)["답"] for i, (a, b) in enumerate(zip(want, got)): _same(ml._norm({k: a.get(k) for k in (*COSTS, "계", "셈됨")}), {k: b.get(k) for k in (*COSTS, "계", "셈됨")}, f"답{i}") # fmt: skip _same(ml._norm(_lines(a)), _lines(b), f"줄{i}") assert want[0]["계"] == 3022 and want[2]["줄"][0][mw.WORK]["꼴"] == "시간당" # ── ⑤ 실제 원파일 견본 ─────────────────────────────────────────────────── def _block(kind, tag, no): import test_810_2_native_doc as nd from M02_MasterTemplete import M02_Doc_FromNative as fn from M02_MasterTemplete import M02_Sangeun_Imported as imp try: saved = nd.native(kind, tag) except Exception: # noqa: BLE001 — 원파일 없는 PC pytest.skip("원파일 없음") sk = nd.sk_of(fn.emit(saved, no)) return ( sk, dim.derive(sk, None, nd.whole()), {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": "우리"}}, ) @pytest.mark.parametrize( "kind, tag, no, want", [ ( "EST", "거창", 1, { "P_굴삭기": ( "GC001147", {"버킷용량": 0.7, "K입력": 0.55, "f": 0.75, "E입력": 0.45, "싸이클입력": 20.0}, ) }, ), # fmt: skip ( "STC", "봉화", 109, { "P_노무": ("GC001155", {"적재용량": 15.0, "운반거리": 0.185, "적하조건": "불량"}), "P_노무2": ("GC001155", {"적재용량": 24.0}), "P_굴삭기": ("GC001147", {"싸이클입력": 18.0}), }, ), # fmt: skip ], ) def test_가져온_값_층_켜기_전_그대로_켜면_Q_같음(kind, tag, no, want): sk, doc, ours = _block(kind, tag, no) got, why = car.carried(doc) assert not why and set(got) == set(want) for sym, (form, vals) in want.items(): assert "방식" not in got[sym][mw.WORK] and got[sym][mw.WORK]["식"] == form assert {k: got[sym][mw.WORK]["변수"][k] for k in vals} == vals for s in (sk, ours): assert _money(dim.run(doc, s, upper=got)) == _money(dim.run(doc, s)) comp = {z[mw.WORK]["기호"]: z[mw.WORK]["값"] for z in dim.run(doc, sk)["줄"] if z.get(mw.WORK)} on = {**doc, "기계덮음": {k: {mw.WORK: {"방식": "시간당"}} for k in got}} for z in dim.run(on, sk, upper=got)["줄"]: w = z.get(mw.WORK) or {} if w.get("기호") in got: assert w["꼴"] == "시간당" and abs(w["값"] - comp[w["기호"]]) <= D("0.01"), w def test_봉화_세_줄_한_줄_금액_그대로(): sk, doc, _ = _block("STC", "봉화", 109) assert [x["이름"] for x in doc["금액"]] == [ "덤프트럭 15톤", "덤프트럭 24톤", "굴삭기(무한궤도)", ] assert doc["금액"][0]["비목곱"] == {"재료비": "(cm_2 - t1 - t3) ÷ cm_2"} assert _money(dim.run(doc, sk)) == [D(2570), D(293), D(933), D(3796)] def test_읽기_답_위덮음_미리_셈_시간당(): from M02_MasterTemplete import M02_Doc_Sk_Path as path sk, doc, _ = _block("EST", "거창", 1) got = path.read_memory(sk) assert got["위덮음"]["P_굴삭기"]["작업량"]["식"] == "GC001147" and got["셈"]["계"] == 5323 mine = { **got["문서"], "기계덮음": {"P_굴삭기": {"작업량": {"방식": "시간당", "식": "GC001147"}}}, } # 화면이 고른 꼴 pre = path.preview("", {"본": sk, "문서": mine}) line = pre["셈"]["줄"][0]["작업량"] assert ( line["꼴"] == "시간당" and line["값"] == pytest.approx(23.389) and pre["전"]["계"] == 5323 ) # ── ⑥ 프로젝트 사본(굳히기) — B09 = M02(임시 storage) ────────────────────── @pytest.fixture def world(tmp_path, monkeypatch): from resources.tester.test_m02_labor_ref import world as make return make.__wrapped__(tmp_path, monkeypatch) def _b09(me, key): from B09_Estimation import B09_Estimation_Supply as supply from B09_Estimation.B09_Estimation_Labor_Source import _Loose from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Item_Source as source from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_MasterTemplete_Store as store with store.at(me): here = refs.here() ref = {"층": here[0], "주인": here[1], "키": key} rows = source.labor_doc_rows({"이름": "t", "단위": "m", "담은로직": [{"참조": ref, "수량": {"손": 1}}]}) # fmt: skip bundle = source.price_bundle(rows, me) got = item_prices.calc(rows, bundle, {}, {}) copies, whole = rows["참조사본"], item_prices.load_prices(bundle) rid = refs.ref_id(ref) b09 = supply.sk_money(copies[rid], whole, _Loose(whole, lambda r: copies.get(refs.ref_id(r))), rid) # fmt: skip return float(got["반영합"]["계"]), sum(b09.values()) @pytest.mark.parametrize("basis", ["엑셀", "우리"]) def test_시간당_고침_저장_사본_B09_같음(world, basis): from M02_MasterTemplete import M02_Doc_Sk_Path as path from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_MasterTemplete_Store as store sk, _, _ = _block("EST", "거창", 1) sk["가져온"]["단가기준"] = basis me = world["personal"] with store.at(me): key = refs.create("sangeun", {**sk, "이름": f"848-7 sub1임시 {basis}"})["이름"] got = path.read(key) first = float(got["셈"]["계"]) assert _b09(me, key) == (first, first) with store.at(me): doc = cp.deepcopy(got["문서"]) doc["기계덮음"] = {"P_굴삭기": {"작업량": {"방식": "시간당", "식": "GC001147", "변수": {"싸이클입력": 15}}}} # fmt: skip after = float(path.save(key, {"문서": doc, "판": got["판"]})["셈"]["계"]) again = path.read(key) assert after < first and float(again["셈"]["계"]) == after assert again["셈"]["줄"][0]["작업량"]["변수"]["버킷용량"] == 0.7 # 가져온 값 위에 내 고침 assert _b09(me, key) == (after, after) def test_세_줄_OH_나누기_꼴도_한_줄_금액_같음(links): doc = _three("0.5 ÷ q") # EST 「OH ÷ Q」 = 노무비 수량 인수 + 0.5 before = mc.calc(dim.view(doc, "엑셀"), links) shape.machines(doc, {}, {}) assert len(doc["금액"]) == 1 and doc["금액"][0]["비목곱"] == {"재료비": "0.5"} assert _money(mc.calc(dim.view(doc, "엑셀"), links)) == _money(before) # ── ⑦ 방식 없는 위 층(가져온 값) — 내 고침엔 바꾼 칸만 남음(파이썬 = TS) ───────────── _JS_PRUNE = r""" const fs = require("fs"), path = require("path"); const ts = require(path.join(process.argv[1], "config", "node_modules", "typescript")); const cache = new Map(); function load(at) { if (cache.has(at)) return cache.get(at); const js = ts.transpileModule(fs.readFileSync(at, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, }).outputText; const box = { exports: {} }; cache.set(at, box.exports); const need = (p) => (p.startsWith(".") ? load(path.resolve(path.dirname(at), `${p}.ts`)) : require(p)); new Function("exports", "module", "require", js)(box.exports, box, need); return box.exports; } const cov = load(path.join(process.argv[1], "common_util", "common_util_formula_doc_cover.ts")); const xs = JSON.parse(fs.readFileSync(0, "utf8")); process.stdout.write(JSON.stringify(xs.map((x) => cov.pruneWorkLayer(x[0], x[1], x[2]) ?? null))); """ def test_방식_없는_위_층_변수_물려받음_거울(): mcv = importlib.import_module("master_doc_cover") up = {"식": "GC001155", "변수": {"운반거리": 0.185, "f": 0.85}} cases = [ [{"방식": "시간당", "식": "GC001155", "변수": {"운반거리": 0.3, "f": 0.85}}, {}, up], [{"방식": "시간당", "식": "GC001155", "변수": {"운반거리": 0.185, "f": 0.85}}, {}, up], [{"방식": "시간당", "식": "GC001173", "변수": {"f": 0.85}}, {}, up], ] want = [mcv.prune_work_layer(*c) for c in cases] assert want == [ {"방식": "시간당", "식": "GC001155", "변수": {"운반거리": 0.3}}, {"방식": "시간당", "식": "GC001155"}, # 시간당만 켬 = 경쟁사 값 그대로 {"방식": "시간당", "식": "GC001173", "변수": {"f": 0.85}}, # 다른 식 = 안 물려받음 ] proc = subprocess.run(["node", "-e", _JS_PRUNE, str(ROOT)], input=json.dumps(cases), capture_output=True, text=True, encoding="utf-8", check=True) # fmt: skip assert json.loads(proc.stdout) == want # ── ⑧ 가져온 식 [초기화] = 불러온 그대로(임시 storage) ─────────────────────── @pytest.mark.parametrize( "kind, tag, no, sym, basis", [("EST", "거창", 1, "P_굴삭기", "엑셀"), ("STC", "봉화", 109, "P_노무", "엑셀")], ) def test_초기화_불러온_그대로(world, kind, tag, no, sym, basis): from M02_MasterTemplete import M02_Doc_Sk_Path as path from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_Library_Flat as flat from M02_MasterTemplete import M02_MasterTemplete_Store as store sk, _, _ = _block(kind, tag, no) sk["가져온"]["단가기준"] = basis with store.at(world["personal"]): key = refs.create("sangeun", {**sk, "이름": "848-7 sub1임시 초기화"})["이름"] got = path.read(key) first = _money(got["셈"]) assert flat.reset_doc("sangeun", key, None, True, None)["걷힘"] == 0 # 고침 없음 doc = cp.deepcopy(got["문서"]) doc["기계덮음"] = { sym: {"작업량": {"방식": "시간당", "식": got["위덮음"][sym]["작업량"]["식"]}} } var = next(v for v in doc["변수"] if (v.get("연결") or {}).get("갈래") == "숫자" and not isinstance(v["연결"]["값"], dict)) # fmt: skip var["연결"]["값"] = float(var["연결"]["값"]) * 1.5 # 줄 · 값 고침 edited = _money(path.save(key, {"문서": doc, "판": got["판"]})["셈"]) assert edited != first look = flat.reset_doc("sangeun", key, None, True, None) assert look["걷힘"] == 2 and look["목록"] == [ "수식 문서 고침(줄 · 식)", f"기계 고침 — {sym}", ] flat.reset_doc("sangeun", key, None, False, None) again = path.read(key) assert _money(again["셈"]) == first and again["사본"]["단가기준"] == basis assert ( not again["사본"]["따로"] and not again["문서"].get("기계덮음") and again["위덮음"] == got["위덮음"] ) def test_초기화_우리_단가로_넘어간_판도_엑셀_판으로(world): """850-2 — 엑셀 판 기계 값을 고쳐 우리 단가로 넘어간 SK 도 [초기화] = 불러온 직후(엑셀 판 · 금액 같음).""" from M02_MasterTemplete import M02_Doc_Sk_Path as path from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_Library_Flat as flat from M02_MasterTemplete import M02_MasterTemplete_Store as store sk, _, _ = _block("STC", "봉화", 109) with store.at(world["personal"]): key = refs.create("sangeun", {**sk, "이름": "850-2 sub3임시 초기화"})["이름"] got = path.read(key) first = _money(got["셈"]) assert ( flat.reset_doc("sangeun", key, None, True, None)["걷힘"] == 0 ) # 엑셀 판 그대로 = 걷을 것 없음 ours = path.save(key, {"문서": got["문서"], "판": got["판"], "단가기준": "우리"}) assert ours["사본"]["단가기준"] == "우리" and _money(ours["셈"]) != first look = flat.reset_doc("sangeun", key, None, True, None) assert look["걷힘"] == 1 and look["목록"] == ["단가 기준 — 우리 단가로"] flat.reset_doc("sangeun", key, None, False, None) again = path.read(key) assert _money(again["셈"]) == first and again["사본"]["단가기준"] == "엑셀"