diff --git a/M01_MasterData/M01_MasterData_Doc.py b/M01_MasterData/M01_MasterData_Doc.py index 3627779db..767827b1f 100644 --- a/M01_MasterData/M01_MasterData_Doc.py +++ b/M01_MasterData/M01_MasterData_Doc.py @@ -154,6 +154,48 @@ def built(key: str) -> dict | None: return None +def make(key: str) -> bool: + """[로직 복사/생성](`Store_Make.logic_new`) 뒤 수식 문서를 지어 씀 — 빌더(`build_수식문서_802_2`)와 + 같은 변환 · 같은 대조(옛 엔진 = 새 계산기 · 기본 + 옵션 표본 · 부르는 단가산출이 저장본)를 지난 것만 + (빌더도 그것만 넣음 · 못 지나면 안 씀 = 열면 빈 문서) · 이미 있으면 그대로 · 썼거나 있음 = True.""" + import importlib + + builder = importlib.import_module("build_수식문서_802_2") + files, whole = store.loaded() + row = next( + ( + r + for data in files.values() + if data.get("그룹") == "로직" + for r in data.get("줄") or [] + if str(r.get("키")) == key + ), + None, + ) + doc = built(key) if row is not None else None + if doc is None: + return False + with _LOCK: + have = docs() + if key in have: + return True + links = ml.Links(whole, {**have, key: doc}) + if not builder._calls(doc) <= set(have) or not all( + builder.agree( + builder.old_answer(whole, row, given), builder.new_answer(links, doc, one) + ) + for _, given, one in builder.cases_of(whole, row) + ): + return False + path = folder() / _file_for(key) + data = ( + ml.load_file(path) if path.exists() else {"그룹": "수식문서", "로직파일": "", "줄": []} + ) + data.setdefault("줄", []).append(doc) + put(path, data) + return True + + def layered(doc: dict, key: str) -> dict: """848-1 — 기계덮음 검사 · 정본과 같은 칸 지움 · 셈 칸이 빌더 결과와 같음 = 빌더 문서 + 덮음 · 다름 = 받은 문서 + `손고침` · 빌더가 모르는 키 = 받은 문서 그대로.""" diff --git a/M01_MasterData/M01_MasterData_Store_Make.py b/M01_MasterData/M01_MasterData_Store_Make.py index 40c84f4b9..e60e3f328 100644 --- a/M01_MasterData/M01_MasterData_Store_Make.py +++ b/M01_MasterData/M01_MasterData_Store_Make.py @@ -257,12 +257,26 @@ def save(batch: list[dict], confirmed: bool = False) -> dict: _own_path().unlink(missing_ok=True) raise docs_too() # 수식 문서 기계 고르기 목록도 같게(848-5) + _drop_docs(batch) added = [ {"file": f, "key": k} for f, old in before.items() for k in _file_keys(f) if k not in old ] return {"files": files, "added": added, "warnings": []} +def _drop_docs(batch: list[dict]) -> None: + """지운 로직 줄의 수식 문서도 지움(문서만 남지 않게 · `/logic/remove` 와 같은 끝).""" + from M01_MasterData import M01_MasterData_Doc as doc_store # Doc 이 이 파일을 늦게 부름 — 늦게 + + files = store.loaded()[0] + for part in batch: + if (files.get(str(part.get("file"))) or {}).get("그룹") != "로직": + continue + for ch in part.get("changes") or []: + if ch.get("op") == "delete" and ch.get("key"): + doc_store.drop(str(ch["key"])) + + def _keep_same(part: dict) -> None: """고친 줄의 값이 같은 칸 = 파일 값 그대로(화면 왕복 「9.0」 → 「9」 막음 · 그 칸만 바뀜).""" data = store.loaded()[0].get(str(part.get("file") or "")) # 읽기만 — 기억(826-2) @@ -340,11 +354,14 @@ def _keys() -> list[str]: def logic_new(logic: dict, owner: str = OWNERS[0]) -> dict: - """새 자체 로직 — 키는 서버가 `GX` 다음 번호로 줌.""" + """새 자체 로직 — 키 = 서버가 `GX` 다음 번호 · 수식 문서도 같이(`Doc.make` · 요구 896).""" + from M01_MasterData import M01_MasterData_Doc as doc_store # Doc 이 이 파일을 늦게 부름 — 늦게 + before = set(_keys()) done = _write([{"op": "add", "row": _clean(logic, owner)}]) key = next((k for k in reversed(_keys()) if k not in before), "") - return {**done, "key": key, "logic": store.logic(key)["logic"] if key else {}} + made = doc_store.make(key) if key else False + return {**done, "key": key, "logic": store.logic(key)["logic"] if key else {}, "수식문서": made} def logic_copy(key: str, 이름: str = "", owner: str = OWNERS[0]) -> dict: diff --git a/resources/master_data/scripts/build_수식문서_802_2.py b/resources/master_data/scripts/build_수식문서_802_2.py index 2eaa2fa84..bbe15a9ff 100644 --- a/resources/master_data/scripts/build_수식문서_802_2.py +++ b/resources/master_data/scripts/build_수식문서_802_2.py @@ -81,6 +81,23 @@ def new_answer(links, doc: dict, given: dict | None = None): return {"결과": got["결과"]} if doc.get("결과") else {k: got.get(k) for k in KEYS} +def cases_of(whole, row: dict) -> list[tuple]: + """(옵션 글, 옛 엔진 입력, 새 문서에 넘길 바뀐 입력) — 기본 + 고르기 입력의 다른 갈래 하나씩.""" + base = meq.given_of(whole, row) + cases = [("", base, None)] + for spec in row.get("입력") or []: + for opt in spec.get("고르기") or []: + if str(opt) != str(base.get(spec["이름"])): + one = {spec["이름"]: opt} + cases.append((f"{spec['이름']}={opt}", {**base, **one}, one)) + return cases + + +def agree(old, new) -> bool: + """대조 같음 — 같은 값 · 둘 다 못 셈.""" + return old == new or (isinstance(old, str) and isinstance(new, str)) + + def _text(v) -> str: if isinstance(v, str): return v @@ -137,17 +154,11 @@ def build(log=print) -> dict: links = ml.Links(whole, docs) runs, both_out = [], 0 for _, row in items: - key, base = str(row["키"]), meq.given_of(whole, row) - cases = [("", base, None)] # (옵션 글, 옛 엔진 입력, 새 문서에 넘길 바뀐 입력) - for spec in row.get("입력") or []: - for opt in spec.get("고르기") or []: - if str(opt) != str(base.get(spec["이름"])): - one = {spec["이름"]: opt} - cases.append((f"{spec['이름']}={opt}", {**base, **one}, one)) - for label, given, changed in cases: + key = str(row["키"]) + for label, given, changed in cases_of(whole, row): old = old_answer(whole, row, given) new = new_answer(links, docs[key], changed) - same = old == new or (isinstance(old, str) and isinstance(new, str)) + same = agree(old, new) both_out += isinstance(old, str) and isinstance(new, str) runs.append( { diff --git a/resources/tester/test_854_2_m01_copy_doc.py b/resources/tester/test_854_2_m01_copy_doc.py new file mode 100644 index 000000000..a53e1a438 --- /dev/null +++ b/resources/tester/test_854_2_m01_copy_doc.py @@ -0,0 +1,108 @@ +"""M01 [로직 복사/생성] 이 수식 문서도 같이 지음(PLAN 854-2 · 요구 896) — 사본 폴더에서만. + +- 만들면 문서 있음 · 새 계산기 금액 = 옛 엔진 = 본뜬 로직 · 빌더가 다시 지어도 같은 글. +- 지우면(`/logic/remove` · `/save` 지움) 문서도 없음. +""" + +from __future__ import annotations + +import importlib +import shutil +from decimal import Decimal +from pathlib import Path + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from M01_MasterData import M01_MasterData_Doc as doc_screen +from M01_MasterData import M01_MasterData_Router as router_module +from M01_MasterData import M01_MasterData_Store as store +from M01_MasterData import M01_MasterData_Store_Make as make + +REAL = store.FOLDER +SAMPLE = "GF000219" # 산림 13-4-1 메쌓기(인력) +COSTS = ("노무비", "재료비", "경비", "계") + + +@pytest.fixture +def client(tmp_path: Path, monkeypatch) -> TestClient: + for path in REAL.glob("*.json"): + if not path.name.startswith("_") or path.name == store.mk.BOOK.name: + shutil.copy(path, tmp_path / path.name) + shutil.copytree(REAL / "기계", tmp_path / "기계") + shutil.copytree(REAL / "수식문서", tmp_path / "수식문서") + monkeypatch.setattr(store, "FOLDER", tmp_path) + monkeypatch.setattr(doc_screen.ml, "FOLDER", tmp_path / "수식문서") + doc_screen._memo.clear() + app = FastAPI() + app.include_router(router_module.router) + return TestClient(app) + + +def _get(client: TestClient, url: str, **params) -> dict: + res = client.get(url, params=params) + assert res.status_code == 200, res.text + return res.json() + + +def _post(client: TestClient, url: str, body: dict) -> dict: + res = client.post(url, json=body) + assert res.status_code == 200, res.text + return res.json() + + +def _money(answer: dict) -> dict: + return {k: Decimal(str(answer[k])) for k in COSTS} + + +def _old(key: str) -> dict: + """옛 엔진 금액(빌더 대조와 같은 길 · 기본 입력).""" + builder = importlib.import_module("build_수식문서_802_2") + whole = store.loaded()[1] + row = store.logic(key)["logic"] + return _money(builder.old_answer(whole, row, builder.cases_of(whole, row)[0][1])) + + +def test_복사로_만든_로직은_수식_문서가_있고_금액이_옛_엔진과_같다(client: TestClient) -> None: + made = _post(client, "/api/m01/logic/copy", {"key": SAMPLE, "이름": "sub5임시 본뜸"}) + key = made["key"] + assert key.startswith("GX") and made["수식문서"] is True + got = _get(client, "/api/m01/logic/doc", key=key) + assert got["새"] is False and got["파일"] == "수식_자체.json" and got["문서"]["식"] + assert got["셈"]["셈됨"] is True + source = _get(client, "/api/m01/logic/doc", key=SAMPLE) + assert _money(got["셈"]) == _old(key) == _money(source["셈"]) and _old(key)["계"] > 0 + + # 빌더가 다음에 다시 지어도 같은 파일 글(옛 로직 줄이 있는 키 = 빌더 몫) + builder = importlib.import_module("build_수식문서_802_2") + result = builder.build(log=lambda *_: None) + assert key in result["저장"] + want = builder.files_of(result)["수식_자체.json"] + assert (doc_screen.folder() / "수식_자체.json").read_text(encoding="utf-8") == want + + # 지우면 문서도 같이 + info = _get(client, "/api/m01/logic", key=key) + _post( + client, + "/api/m01/logic/remove", + {"key": key, "file": info["file"], "version": info["version"]}, + ) + assert _get(client, "/api/m01/logic/doc", key=SAMPLE)["새"] is False + assert key not in doc_screen.docs() + + +def test_식_복사로_만든_로직도_문서가_있고_save_지움이면_문서도_없다(client: TestClient) -> None: + view = _get(client, "/api/m01/logic/formula", key=SAMPLE) + made = _post( + client, + "/api/m01/logic/formula/save", + {"로직": view["로직"], "별칭": view["별칭"], "본뜬키": SAMPLE, "이름": "sub5임시 식복사"}, + ) + key = made["key"] + assert made["수식문서"] is True and key in doc_screen.docs() + assert _money(_get(client, "/api/m01/logic/doc", key=key)["셈"]) == _old(key) + + body = {"file": make.OWN, "version": made["version"], "changes": [{"op": "delete", "key": key}]} + _post(client, "/api/m01/save", {"files": [body]}) + assert key not in doc_screen.docs()