Merge branch 'sub_laptop_5' of C:/Aislo_wt/sub_laptop_5 into main_laptop_1
This commit is contained in:
@@ -533,7 +533,10 @@ export function createStackScreen(opt: StackScreenOptions) {
|
||||
const save = async (job?: Record<string, unknown>, done = ft("Saved")): Promise<boolean> => {
|
||||
await loading; // 새 로직 저장 뒤 여는 중이면 다 읽고(캐시 이어 받음)
|
||||
if (!doc || (!job && !dirty())) return true;
|
||||
const send = job ?? (cp ? { 문서: doc, 끊음: cut, 판: version, ...pending() } : { 문서: doc });
|
||||
// M01 = 읽을 때 받은 판도(그 사이 다른 곳에서 바뀌면 409 · 덮지 않음)
|
||||
const send =
|
||||
job ??
|
||||
(cp ? { 문서: doc, 끊음: cut, 판: version, ...pending() } : { 문서: doc, 판: version });
|
||||
const was = saved;
|
||||
showLoadingOverlay();
|
||||
try {
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
@@ -30,12 +32,33 @@ import master_equation_link as link # noqa: E402
|
||||
|
||||
OWN_FILE = "수식_자체.json"
|
||||
_memo: dict = {}
|
||||
# 수식 문서 쓰기 한 번에 하나 — 저장 · 지움 · 기계 고르기 목록 등록(`Machine._register_docs`)
|
||||
# ponytail: 프로세스 안 잠금(`Store._LOCK` 과 같은 한계) · 서버를 여럿 띄우면 파일 잠금으로
|
||||
_LOCK = threading.Lock()
|
||||
_HOME = Path(ml.__file__).resolve().parents[1] # 저장소 정본 마스터 폴더
|
||||
STALE = "그 사이 파일이 바뀜 — 고친 것을 버리고 다시 여세요: {v}" # 화면 `Save_Stale` 과 같은 글
|
||||
|
||||
|
||||
def folder() -> Path:
|
||||
return ml.FOLDER
|
||||
|
||||
|
||||
def version_of(doc: dict | None) -> str:
|
||||
"""문서 한 장의 판(저장 글 기준) — 저장본 없음 = 빈 글."""
|
||||
return "" if doc is None else store.version_of(ml.dump(doc).encode("utf-8"))
|
||||
|
||||
|
||||
def put(path: Path, data: dict) -> None:
|
||||
"""수식 문서 파일 한 벌 — 임시 파일 → 교체(원자적) · `_LOCK` 안에서 부름.
|
||||
마스터만 사본으로 바꾼 시험(`Store.FOLDER` ≠ 정본)이 정본 수식 문서를 쓰지 않게 건너뜀."""
|
||||
if path.resolve().parent.parent == _HOME and Path(store.FOLDER).resolve() != _HOME:
|
||||
return
|
||||
tmp = path.with_name(f".{path.name}.tmp")
|
||||
tmp.write_text(ml.dump(data), encoding="utf-8", newline="\n")
|
||||
os.replace(tmp, path)
|
||||
_memo.clear()
|
||||
|
||||
|
||||
def _stamp() -> tuple:
|
||||
return tuple((p.name, p.stat().st_mtime_ns) for p in sorted(folder().glob("수식_*.json")))
|
||||
|
||||
@@ -95,7 +118,8 @@ def read(key: str) -> dict:
|
||||
out = _run(found)
|
||||
up = None if fresh else built(key)
|
||||
more = {"층바탕": {"위": up}} if up is not None else {}
|
||||
return {"문서": found, **out, "파일": _where(key) or "", "새": fresh, **more}
|
||||
판 = version_of(None if fresh else found) # 저장 때 대조(다른 곳에서 바뀌면 409)
|
||||
return {"문서": found, **out, "파일": _where(key) or "", "새": fresh, "판": 판, **more}
|
||||
|
||||
|
||||
def preview(doc: dict, given: dict | None = None) -> dict:
|
||||
@@ -130,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 — 기계덮음 검사 · 정본과 같은 칸 지움 · 셈 칸이 빌더 결과와 같음 = 빌더 문서 + 덮음 ·
|
||||
다름 = 받은 문서 + `손고침` · 빌더가 모르는 키 = 받은 문서 그대로."""
|
||||
@@ -150,22 +216,27 @@ def layered(doc: dict, key: str) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
def save(doc: dict) -> dict:
|
||||
def save(doc: dict, 판: str | None = None) -> dict:
|
||||
"""`판` = 읽을 때 받은 판(없음 = 대조 안 함 · 빈 글 = 저장본 없던 문서) · 다르면 409."""
|
||||
doc = _check(doc)
|
||||
key = str(doc["키"]).strip()
|
||||
doc = layered(doc, key)
|
||||
name = _file_for(key)
|
||||
path = folder() / name
|
||||
data = ml.load_file(path) if path.exists() else {"그룹": "수식문서", "로직파일": "", "줄": []}
|
||||
rows = data.setdefault("줄", [])
|
||||
at = next((i for i, d in enumerate(rows) if str(d.get("키")) == key), None)
|
||||
if at is None:
|
||||
rows.append(doc)
|
||||
else:
|
||||
rows[at] = doc
|
||||
path.write_text(ml.dump(data), encoding="utf-8", newline="\n")
|
||||
_memo.clear()
|
||||
return {"문서": doc, **_run(doc), "파일": name}
|
||||
with _LOCK:
|
||||
doc = layered(doc, key)
|
||||
name = _file_for(key)
|
||||
path = folder() / name
|
||||
data = (
|
||||
ml.load_file(path) if path.exists() else {"그룹": "수식문서", "로직파일": "", "줄": []}
|
||||
)
|
||||
rows = data.setdefault("줄", [])
|
||||
at = next((i for i, d in enumerate(rows) if str(d.get("키")) == key), None)
|
||||
if 판 is not None and version_of(None if at is None else rows[at]) != 판:
|
||||
raise store.StoreError(409, STALE.format(v=f"{name} {key}"))
|
||||
if at is None:
|
||||
rows.append(doc)
|
||||
else:
|
||||
rows[at] = doc
|
||||
put(path, data)
|
||||
return {"문서": doc, **_run(doc), "파일": name, "판": version_of(doc)}
|
||||
|
||||
|
||||
def candidates(ask: dict) -> dict:
|
||||
@@ -222,14 +293,14 @@ def users(key: str) -> list[str]:
|
||||
|
||||
def drop(key: str) -> None:
|
||||
"""수식 문서 줄 하나 지움(없으면 그냥)."""
|
||||
name = _where(key)
|
||||
if not name:
|
||||
return
|
||||
path = folder() / name
|
||||
data = ml.load_file(path)
|
||||
data["줄"] = [d for d in data.get("줄") or [] if str(d.get("키")) != key]
|
||||
path.write_text(ml.dump(data), encoding="utf-8", newline="\n")
|
||||
_memo.clear()
|
||||
with _LOCK:
|
||||
name = _where(key)
|
||||
if not name:
|
||||
return
|
||||
path = folder() / name
|
||||
data = ml.load_file(path)
|
||||
data["줄"] = [d for d in data.get("줄") or [] if str(d.get("키")) != key]
|
||||
put(path, data)
|
||||
|
||||
|
||||
def remove(key: str, file: str, version: str, confirmed: bool) -> dict:
|
||||
|
||||
@@ -182,22 +182,26 @@ def register(batch: list[dict]) -> Callable[[], None]:
|
||||
|
||||
|
||||
def _register_docs(add: dict[str, list[str]], drop: set[str]) -> None:
|
||||
"""수식 문서의 「기계」 고르기 목록에 로직 목록과 같은 더함 · 뺌 — 바뀐 파일만 다시 씀."""
|
||||
"""수식 문서의 「기계」 고르기 목록에 로직 목록과 같은 더함 · 뺌 — 바뀐 파일만 다시 씀
|
||||
(수식 문서 쓰기 길 `Doc.put` · 잠금 안 — 화면 저장과 겹쳐도 한쪽이 덮지 않음)."""
|
||||
import master_doc_link as ml # noqa: E402
|
||||
|
||||
for path in sorted(ml.FOLDER.glob("수식_*.json")):
|
||||
data, hit = ml.load_file(path), False
|
||||
for doc in data.get("줄") or []:
|
||||
for v in doc.get("변수") or []:
|
||||
link = v.get("연결") or {}
|
||||
if link.get("갈래") != "선택" or v.get("이름") != "기계":
|
||||
continue
|
||||
codes = [c for c in link.get("목록") or [] if str(c) not in drop]
|
||||
codes += [c for c in add.get(str(doc.get("키")), []) if c not in codes]
|
||||
if codes != link.get("목록"):
|
||||
link["목록"], hit = codes, True
|
||||
if hit:
|
||||
path.write_text(ml.dump(data), encoding="utf-8", newline="\n")
|
||||
from M01_MasterData import M01_MasterData_Doc as docs
|
||||
|
||||
with docs._LOCK:
|
||||
for path in sorted(docs.folder().glob("수식_*.json")):
|
||||
data, hit = ml.load_file(path), False
|
||||
for doc in data.get("줄") or []:
|
||||
for v in doc.get("변수") or []:
|
||||
link = v.get("연결") or {}
|
||||
if link.get("갈래") != "선택" or v.get("이름") != "기계":
|
||||
continue
|
||||
codes = [c for c in link.get("목록") or [] if str(c) not in drop]
|
||||
codes += [c for c in add.get(str(doc.get("키")), []) if c not in codes]
|
||||
if codes != link.get("목록"):
|
||||
link["목록"], hit = codes, True
|
||||
if hit:
|
||||
docs.put(path, data)
|
||||
|
||||
|
||||
# ── 쓰는 곳 = `M01_MasterData_Machine_Uses`(수식 문서 기준 · 848-5) ──────────────
|
||||
|
||||
@@ -318,6 +318,7 @@ def post_logic_formula_preview(body: FormulaPreview) -> dict:
|
||||
class DocBody(BaseModel):
|
||||
문서: dict[str, Any]
|
||||
입력: dict[str, Any] = {}
|
||||
판: str | None = None # 저장 — 읽을 때 받은 판(다르면 409 · 없으면 대조 안 함)
|
||||
|
||||
|
||||
@router.get("/logic/doc")
|
||||
@@ -335,7 +336,7 @@ def post_logic_doc_preview(body: DocBody) -> dict:
|
||||
@router.post("/logic/doc/save")
|
||||
def post_logic_doc_save(body: DocBody) -> dict:
|
||||
"""저장 — 서버가 정본으로 다시 셈 · 문서 파일에 씀 → {문서, 셈, 연결, 파일}."""
|
||||
return _call(doc_screen.save, body.문서)
|
||||
return _call(doc_screen.save, body.문서, body.판)
|
||||
|
||||
|
||||
class RemoveBody(BaseModel):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -116,16 +116,50 @@ def save(batch: list[dict]) -> list[dict]:
|
||||
new = [x for x in new + cache.labor_errors(fresh, gone) if x not in old]
|
||||
if new:
|
||||
raise store.StoreError(422, {"errors": new})
|
||||
if book["다음"] != issued:
|
||||
mk.save_book(book, book_path)
|
||||
out = [{"file": name, "version": _write(name, before[name], after[name])} for name in names]
|
||||
# 대장(원자적) → 파일 · 중간에 끊기면 쓴 것 모두 저장 전으로(대장만 · 파일만 앞서가지 않게)
|
||||
raw = {n: (store.FOLDER / n).read_bytes() for n in names if not _machine(n)}
|
||||
book_raw = book_path.read_bytes() if book["다음"] != issued else None
|
||||
tried: list[str] = []
|
||||
try:
|
||||
if book_raw is not None:
|
||||
mk.save_book(book, book_path)
|
||||
out = []
|
||||
for name in names:
|
||||
tried.append(name)
|
||||
out.append({"file": name, "version": _write(name, before[name], after[name])})
|
||||
except BaseException:
|
||||
_undo(tried, before, after, raw, book_path, book_raw)
|
||||
raise
|
||||
# 저장 뒤 — 쓴 파일만 기억에 갈아 끼우고 흔들린 자리를 알려 줘 그 줄만 다시 세게
|
||||
cache.adopt(store.FOLDER, after, fresh, names, narrowed[2])
|
||||
return out
|
||||
|
||||
|
||||
def _machine(name: str) -> bool:
|
||||
return name == mmf.NAME and mmf.here(store.FOLDER) # 기계 = 폴더(826-2)
|
||||
|
||||
|
||||
def _put(path, raw: bytes) -> None:
|
||||
tmp = path.with_name(f".{path.name}.tmp")
|
||||
tmp.write_bytes(raw)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _undo(names, before, after, raw, book_path, book_raw) -> None:
|
||||
"""쓰기 중간 실패 — 쓴(쓰려던) 파일 · 대장을 저장 전 글로 되돌림."""
|
||||
for name in names:
|
||||
if _machine(name):
|
||||
mmf.write(
|
||||
store.FOLDER, before[name], after[name]
|
||||
) # 바뀐 · 더한 · 지운 대를 저장 전으로
|
||||
else:
|
||||
_put(store.FOLDER / name, raw[name])
|
||||
if book_raw is not None:
|
||||
_put(book_path, book_raw)
|
||||
|
||||
|
||||
def _write(name: str, before: dict, after: dict) -> str:
|
||||
if name == mmf.NAME and mmf.here(store.FOLDER): # 기계 = 바뀐 대 파일만(826-2)
|
||||
if _machine(name): # 기계 = 바뀐 대 파일만(826-2)
|
||||
mmf.write(store.FOLDER, after, before)
|
||||
return store.version(name)
|
||||
path = store.FOLDER / name
|
||||
|
||||
@@ -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(
|
||||
{
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
@@ -24,7 +25,9 @@ import master_machine_crew as mcrew
|
||||
import master_material as mm
|
||||
import master_pick as mp
|
||||
|
||||
FOLDER = Path(__file__).resolve().parents[1] / "수식문서"
|
||||
# 화면 저장 시험 사본(`AISLO_MASTER_DIR` — `M01_MasterData_Store.FOLDER` 와 같이) · 없으면 정본
|
||||
_HOME = os.environ.get("AISLO_MASTER_DIR") or Path(__file__).resolve().parents[1]
|
||||
FOLDER = Path(_HOME).resolve() / "수식문서"
|
||||
_ARITH_OK = ("num", "bin", "neg")
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
@@ -77,7 +78,9 @@ def save_book(book: dict, path: Path = BOOK) -> None:
|
||||
comma = "," if i < len(items) - 1 else ""
|
||||
lines.append(f" {json.dumps(key)}: {json.dumps(v, ensure_ascii=False)}{comma}")
|
||||
lines += [" }", "}"]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
|
||||
tmp = path.with_name(f".{path.name}.tmp") # 임시 파일 → 교체(원자적 · 끊겨도 반쪽 대장 없음)
|
||||
tmp.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def lookup(book: dict) -> dict:
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,141 @@
|
||||
"""M01 수식 문서 쓰기 안전(PLAN 854-2 · 요구 894 걸음 1) — 잠금 · 판 대조(409) · 임시 파일 → 교체.
|
||||
|
||||
마스터 · 수식 문서 사본 폴더에서만 씀.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from M01_MasterData import M01_MasterData_Store as store
|
||||
|
||||
REAL = store.FOLDER
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def master(tmp_path: Path, monkeypatch) -> Path:
|
||||
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 / "기계")
|
||||
monkeypatch.setattr(store, "FOLDER", tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
DOC_KEY = "GF000219" # 산림 13-4-1 메쌓기(인력)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def docs(master: Path, monkeypatch) -> Path:
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_screen
|
||||
|
||||
folder = master / "수식문서"
|
||||
shutil.copytree(REAL / "수식문서", folder)
|
||||
monkeypatch.setattr(doc_screen.ml, "FOLDER", folder)
|
||||
doc_screen._memo.clear()
|
||||
return folder
|
||||
|
||||
|
||||
def _client():
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from M01_MasterData import M01_MasterData_Router as router_module
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router_module.router)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _renamed(doc: dict, tail: str) -> dict:
|
||||
return {**doc, "이름": f"{doc['이름']} {tail}"}
|
||||
|
||||
|
||||
def test_옛_판으로_저장하면_409_이고_앞_저장을_덮지_않는다(docs: Path) -> None:
|
||||
client = _client()
|
||||
got = client.get("/api/m01/logic/doc", params={"key": DOC_KEY}).json()
|
||||
assert got["판"] and not got["새"]
|
||||
first = client.post(
|
||||
"/api/m01/logic/doc/save",
|
||||
json={"문서": _renamed(got["문서"], "sub5임시A"), "판": got["판"]},
|
||||
)
|
||||
assert first.status_code == 200, first.text
|
||||
again = client.get("/api/m01/logic/doc", params={"key": DOC_KEY}).json()
|
||||
assert again["판"] == first.json()["판"] != got["판"] # 저장 뒤 판 = 다시 읽은 판
|
||||
late = client.post(
|
||||
"/api/m01/logic/doc/save",
|
||||
json={"문서": _renamed(got["문서"], "sub5임시B"), "판": got["판"]},
|
||||
)
|
||||
assert late.status_code == 409 and "그 사이 파일이 바뀜" in late.json()["detail"]
|
||||
assert again["문서"]["이름"].endswith("sub5임시A")
|
||||
now = client.get("/api/m01/logic/doc", params={"key": DOC_KEY}).json()
|
||||
assert now["문서"]["이름"].endswith("sub5임시A") # 늦은 저장이 소리 없이 덮지 않음
|
||||
assert not list(docs.glob(".*.tmp"))
|
||||
|
||||
|
||||
def test_동시에_두_저장이면_하나만_되고_하나는_409(docs: Path, monkeypatch) -> None:
|
||||
import threading
|
||||
import time
|
||||
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_screen
|
||||
|
||||
got = _client().get("/api/m01/logic/doc", params={"key": DOC_KEY}).json() # 화면 꼴(수 = JSON)
|
||||
real = doc_screen.layered
|
||||
|
||||
def slow(doc, key): # 두 저장이 겹치게 — 판 확인 · 쓰기 사이를 넓힘
|
||||
time.sleep(0.3)
|
||||
return real(doc, key)
|
||||
|
||||
monkeypatch.setattr(doc_screen, "layered", slow)
|
||||
plain = got["문서"]
|
||||
out: list[str] = []
|
||||
|
||||
def one(tail: str) -> None:
|
||||
try:
|
||||
doc_screen.save(_renamed(plain, tail), got["판"])
|
||||
out.append("ok")
|
||||
except doc_screen.store.StoreError as e:
|
||||
out.append(str(e.status))
|
||||
|
||||
runs = [threading.Thread(target=one, args=(t,)) for t in ("sub5임시A", "sub5임시B")]
|
||||
for t in runs:
|
||||
t.start()
|
||||
for t in runs:
|
||||
t.join()
|
||||
assert sorted(out) == ["409", "ok"]
|
||||
|
||||
|
||||
def test_기계_목록_등록이_바꾼_문서를_옛_판_저장이_덮지_않는다(docs: Path) -> None:
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_screen
|
||||
from M01_MasterData import M01_MasterData_Machine as machine
|
||||
|
||||
key = next(
|
||||
k
|
||||
for k, d in doc_screen.docs().items()
|
||||
if any(
|
||||
v.get("이름") == "기계" and (v.get("연결") or {}).get("갈래") == "선택"
|
||||
for v in d.get("변수") or []
|
||||
)
|
||||
)
|
||||
got = _client().get("/api/m01/logic/doc", params={"key": key}).json()
|
||||
machine._register_docs({key: ["sub5임시EQ"]}, set())
|
||||
after = doc_screen.read(key)
|
||||
assert after["판"] != got["판"]
|
||||
plain = got["문서"]
|
||||
with pytest.raises(doc_screen.store.StoreError) as e:
|
||||
doc_screen.save(_renamed(plain, "sub5임시"), got["판"])
|
||||
assert e.value.status == 409
|
||||
picks = next(v for v in doc_screen.read(key)["문서"]["변수"] if v.get("이름") == "기계")
|
||||
assert "sub5임시EQ" in picks["연결"]["목록"]
|
||||
|
||||
|
||||
def test_마스터만_사본인_시험은_정본_수식_문서를_안_쓴다(master: Path) -> None:
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_screen
|
||||
|
||||
path = doc_screen.folder() / "수식_자체.json" # 정본 폴더(사본으로 안 바꿈)
|
||||
raw = path.read_bytes()
|
||||
doc_screen.put(path, {"그룹": "수식문서", "로직파일": "", "줄": []})
|
||||
assert path.read_bytes() == raw
|
||||
@@ -0,0 +1,113 @@
|
||||
"""M01 저장 안전(PLAN 854-2 · 요구 894 걸음 1) — 마스터 사본 폴더에서만 씀.
|
||||
|
||||
- 키 대장 · 파일 쓰기: 중간에 끊겨도 대장 · 파일이 저장 전 그대로(대장만 앞서가지 않음).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from M01_MasterData import M01_MasterData_Store as store
|
||||
from M01_MasterData import M01_MasterData_Store_Save as save_mod
|
||||
|
||||
REAL = store.FOLDER
|
||||
OWN = "로직_자체.json"
|
||||
MACHINE = "EQ000002"
|
||||
LABOR = "LB000002" # 보통인부
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def master(tmp_path: Path, monkeypatch) -> Path:
|
||||
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 / "기계")
|
||||
monkeypatch.setattr(store, "FOLDER", tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _bytes(folder: Path) -> dict[str, bytes]:
|
||||
out = {p.name: p.read_bytes() for p in folder.glob("*.json")}
|
||||
out |= {f"기계/{p.name}": p.read_bytes() for p in (folder / "기계").glob("*.json")}
|
||||
return out
|
||||
|
||||
|
||||
def _new_logic() -> dict:
|
||||
return {
|
||||
"op": "add",
|
||||
"row": {
|
||||
"원문번호": "",
|
||||
"구분": "자체",
|
||||
"상세구분": "",
|
||||
"소유": "현장",
|
||||
"이름": "sub5임시 대장 시험",
|
||||
"결과단위": "원/㎡",
|
||||
"출처": "자체",
|
||||
"입력": [],
|
||||
"중간": [],
|
||||
"호표": [
|
||||
{
|
||||
"종류": "인력",
|
||||
"요소": LABOR,
|
||||
"이름": "보통인부",
|
||||
"단위": "인",
|
||||
"수량": "1 / 7",
|
||||
"비목": "노무비",
|
||||
}
|
||||
],
|
||||
"덧줄": [],
|
||||
"끝수": None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _batch() -> list[dict]:
|
||||
"""기계 한 대 고침(기계 폴더) + 자체 로직 새 줄(GX 키 발급 = 대장 바뀜)."""
|
||||
machine = json.loads((store.FOLDER / "기계" / f"{MACHINE}.json").read_text(encoding="utf-8"))
|
||||
machine["비고"] = "sub5임시"
|
||||
return [
|
||||
{
|
||||
"file": "기계.json",
|
||||
"version": store.version("기계.json"),
|
||||
"changes": [{"op": "edit", "key": MACHINE, "row": machine}],
|
||||
},
|
||||
{"file": OWN, "version": store.version(OWN), "changes": [_new_logic()]},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fail_at", [0, 1])
|
||||
def test_파일_쓰기가_끊기면_대장과_파일이_저장_전_그대로(
|
||||
master: Path, monkeypatch, fail_at
|
||||
) -> None:
|
||||
before = _bytes(master)
|
||||
real = save_mod._write
|
||||
calls = []
|
||||
|
||||
def broken(name, was, now):
|
||||
calls.append(name)
|
||||
if len(calls) - 1 == fail_at:
|
||||
if fail_at: # 둘째 파일은 쓴 뒤에 끊김(반쯤 쓴 꼴)
|
||||
real(name, was, now)
|
||||
raise OSError("디스크 흉내 실패")
|
||||
return real(name, was, now)
|
||||
|
||||
monkeypatch.setattr(save_mod, "_write", broken)
|
||||
with pytest.raises(OSError):
|
||||
store.save(_batch())
|
||||
after = _bytes(master)
|
||||
assert after == before # 대장 · 기계 · 로직 파일 모두 저장 전 글 그대로
|
||||
assert not list(master.glob(".*.tmp")) and not list((master / "기계").glob(".*.tmp"))
|
||||
|
||||
|
||||
def test_끊김_없으면_대장과_파일이_같이_간다(master: Path) -> None:
|
||||
book_before = store.mk.load_book(master / store.mk.BOOK.name)["다음"].get("GX", 1)
|
||||
store.save(_batch())
|
||||
book = store.mk.load_book(master / store.mk.BOOK.name)
|
||||
keys = [r["키"] for r in json.loads((master / OWN).read_text(encoding="utf-8"))["줄"]]
|
||||
assert f"GX{book_before:06d}" in keys and book["다음"]["GX"] == book_before + 1
|
||||
machine = json.loads((master / "기계" / f"{MACHINE}.json").read_text(encoding="utf-8"))
|
||||
assert machine["비고"] == "sub5임시"
|
||||
Reference in New Issue
Block a user