feat(855-E L1): 수식 문서 이름표 싣기 — 빌더 · M01 저장 길이 로직 줄과 두 곳에 같게 씀

- master_doc.TAGS(원문번호 · 구분 · 상세구분 · 소유 · 비고 · 개정 · 별칭) · FILE_TAGS(원문 · 부문 · 차례) · tag() · tags_of() — 셈 · 지문(doc_fp) 밖 · `키` 바로 뒤
- 빌더 files_of = 문서 줄 머리 이름표 · 파일 머리 이름표를 로직 줄 · 로직 파일 머리에서(손고침 · 기계덮음 문서도) · --check 새 기준
- M01 Doc: of_row(빌더와 같은 꼴) · save 가 이름표를 로직 줄 것으로 실음(화면 왕복에 안 지워짐 · 손고침 판정 그대로) · sync_tags
- Store_Make.save 뒤 고친 · 더한 로직 줄 이름표를 문서에도(비고 · 별칭 · 자체 이름 · 개정 확인 · 신규 · 별칭 모아 보기 · 기계 등록 — 모두 이 길)
- build_로직_개정 이 문서 줄 머리 「개정」 도 씀
- _수식문서_틀.md 이름표 두 줄 · 새 시험 test_855_l1_tags(1,521 이름표 = 로직 줄 · 파일 머리 같음 · 비고 · 별칭 넣고 뺌 · 문서 저장 왕복 · 복사 · 자체 비고 · 삭제 뒤도 같음 · doc_fp 같음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 22:47:58 +09:00
co-authored by Claude Opus 5.5
parent a25ef0ddeb
commit 09b5b414b7
7 changed files with 270 additions and 11 deletions
+35 -1
View File
@@ -137,6 +137,37 @@ def _file_for(key: str) -> str:
return OWN_FILE
def _row(key: str) -> dict | None:
"""그 키의 로직 줄(기억 · 읽기만) — 없음 = None."""
for data in store.loaded()[0].values():
if data.get("그룹") == "로직":
for row in data.get("줄") or []:
if str(row.get("키")) == key:
return row
return None
def sync_tags(keys) -> int:
"""로직 줄 이름표를 수식 문서 줄 머리에 같게(855 L1 · 읽는 쪽이 문서로 옮길 때까지 두 곳) —
로직 줄 · 문서가 둘 다 있는 키만 · 바뀐 문서 파일만 씀(`put`) · 바꾼 문서 수."""
want = {k: r for k in set(map(str, keys)) if (r := _row(k)) is not None}
if not want:
return 0
n = 0
with _LOCK:
for path in sorted(folder().glob("수식_*.json")):
data, hit = ml.load_file(path), False
rows = data.get("줄") or []
for at, doc in enumerate(rows):
row = want.get(str(doc.get("키")))
if row is not None and md.tags_of(doc) != md.tags_of(row):
rows[at], hit = md.tag(doc, row), True
n += 1
if hit:
put(path, data)
return n
def built(key: str) -> dict | None:
"""빌더가 지을 그 키 문서(옛 로직 줄 변환 · `build_수식문서_802_2`) · 로직 줄 없음 · 변환 틀림 = None."""
for data in store.loaded()[0].values():
@@ -154,9 +185,10 @@ def of_row(row: dict) -> dict | None:
import master_doc_convert as cv
try:
return cv.convert(store.loaded()[1], row)[0]
doc = cv.convert(store.loaded()[1], row)[0]
except Exception: # noqa: BLE001 — 변환 틀림 = 빌더 문서 없음(표지 안 담)
return None
return md.tag(doc, row) # 855 L1 이름표 = 빌더와 같게
def make(key: str) -> bool:
@@ -226,6 +258,8 @@ def save(doc: dict, 판: str | None = None) -> dict:
doc = _check(doc)
key = str(doc["키"]).strip()
with _LOCK:
if (row := _row(key)) is not None: # 이름표 = 로직 줄 것(화면 왕복에 안 지워짐 · 855 L1)
doc = md.tag(doc, row)
doc = layered(doc, key)
name = _file_for(key)
path = folder() / name
@@ -262,9 +262,23 @@ def save(batch: list[dict], confirmed: bool = False) -> dict:
added = [
{"file": f, "key": k} for f, old in before.items() for k in _file_keys(f) if k not in old
]
_sync_tags(batch, added)
return {"files": files, "added": added, "warnings": []}
def _sync_tags(batch: list[dict], added: list[dict]) -> None:
"""고친 · 더한 로직 줄 이름표(비고 · 별칭 · 이름 · 개정 …)를 수식 문서에도(855 L1 · 두 곳 같게)."""
from M01_MasterData import M01_MasterData_Doc as doc_store # Doc 이 이 파일을 늦게 부름 — 늦게
keys = {a["key"] for a in added} | {
str(c.get("key"))
for p in batch
for c in p.get("changes") or []
if c.get("op") == "edit" and c.get("key")
}
doc_store.sync_tags(keys)
def _drop_docs(batch: list[dict]) -> None:
"""지운 로직 줄의 수식 문서도 지움(문서만 남지 않게 · `/logic/remove` 와 같은 끝)."""
from M01_MasterData import M01_MasterData_Doc as doc_store # Doc 이 이 파일을 늦게 부름 — 늦게
@@ -13,6 +13,7 @@
- 자리 = `수식문서/수식_<옛 로직 파일 꼬리>.json` — 옛 로직 파일마다 한 벌(`로직_건설품셈_08장_건설기계.json` → `수식_건설품셈_08장_건설기계.json`).
- 머리 = `그룹`(「수식문서」) · `로직파일`(옛 로직 파일 이름) · `줄`(문서 목록 · 옛 로직 차례).
- 머리 이름표 = `원문` · `부문` · `차례` — 옛 로직 파일 머리와 같은 값(빌더가 실음 · M01 분류).
- UTF-8 · LF · 들여쓰기 2칸 · 변수 · 식 · 금액 줄 하나 = 한 줄.
- 옛 로직 JSON 과 따로 — 빌더가 씀(옛 로직 JSON 은 안 씀) · M01 화면 저장은 10 절(기계덮음 · 손고침).
@@ -43,6 +44,7 @@
```
- 돈 문서 = `금액` 줄 · 돈 아닌 문서(시간당 작업량 등) = `결과`(결과 기호) · `금액` 비움.
- 이름표 = `원문번호` · `구분` · `상세구분` · `소유` · `비고` · `개정` · `별칭` — `키` 바로 뒤 · 옛 로직 줄과 같은 값(빌더 · M01 저장이 두 곳에 씀 · `master_doc.tag`) · 셈 · 지문(`doc_fp`) 밖.
- `변수` = 변수표 — `열쇠`(다른 문서가 입력을 넘길 때 부르는 이름 · 안 바뀜) · `기호` · `아래` · `위`(첨자) · `이름`(국문) · `단위` · `연결` · `설명` · `출처`(있을 때).
- `식` = 식 줄 `기호 = 식` · 차례는 보이는 차례(셈은 차례 무관 — 기호를 필요할 때 셈).
- 식 줄 머리 기호의 변수 = 연결 갈래 「식」. 연결 갈래가 「식」 인데 식 줄이 없으면 「정의 필요」.
@@ -3,7 +3,7 @@
건설 = 본문 md 절 머리 괄호 「('08, '20, 25년 보완)」 · 「('19년 신설, '24년 보완)」 의 연도 전부.
산림 = [2026](2026-01-01 제정 · 절 머리에 연도 없음). 절 머리에 연도가 없으면 윗절로 올라감.
못 찾음 = 칸 없음(빈칸). 글 꼴 그대로 — 줄 「출처」 바로 뒤에 끼우거나 옛 값만 갈음.
사람 입력 없음 · 셈 값 바뀜 0.
사람 입력 없음 · 셈 값 바뀜 0. 수식 문서 줄 머리 「개정」 도 같은 값(855 L1 이름표).
./venv/Scripts/python.exe resources/master_data/scripts/build_로직_개정.py [--check]
"""
@@ -94,7 +94,7 @@ def put(row_text: str, value: list[int] | None) -> str:
def build(check: bool = False) -> Counter:
h, why = heads(), Counter()
h, why, revs = heads(), Counter(), {}
for path in sorted(MASTER.glob("로직_*.json")):
raw = path.read_bytes().decode("utf-8")
data = json.loads(raw)
@@ -112,6 +112,7 @@ def build(check: bool = False) -> Counter:
row["개정"] = value
else:
row.pop("개정", None)
revs[str(row["키"])] = value
last = e
out = "".join(parts + [raw[last:]])
assert json.loads(out) == data, path.name # 끼운 칸 말고 같음
@@ -119,9 +120,34 @@ def build(check: bool = False) -> Counter:
why["바뀐 파일"] += 1
if not check:
path.write_bytes(out.encode("utf-8"))
_docs(revs, why, check)
return why
def _docs(revs: dict, why: Counter, check: bool) -> None:
"""수식 문서 줄 머리 「개정」 도 같게(855 L1 이름표 · 로직 줄과 두 곳)."""
sys.path.insert(0, str(Path(__file__).resolve().parent))
import master_doc as md
import master_doc_link as ml
for path in sorted(ml.FOLDER.glob("수식_*.json")):
data, hit = ml.load_file(path), False
rows = data.get("줄") or []
for at, doc in enumerate(rows):
key = str(doc.get("키"))
if key not in revs:
continue
want = {**md.tags_of(doc), "개정": revs[key]} if revs[key] else md.tags_of(doc)
if not revs[key]:
want.pop("개정", None)
if want != md.tags_of(doc):
rows[at], hit = md.tag(doc, want), True
if hit:
why["바뀐 문서 파일"] += 1
if not check:
path.write_bytes(ml.dump(data).encode("utf-8")) # LF 그대로
if __name__ == "__main__":
got = build("--check" in sys.argv)
for k, v in sorted(got.items()):
@@ -21,6 +21,8 @@
- 이미 저장된 문서가 이번에 저장 밖(다름 · 부르는 문서 빠짐)이면 멈춤 — 안 씀 · 그 문서와 까닭을 알림(`lost`).
- 화면 고침 이어받기(848-1) — 저장본 `기계덮음`(그 기초의 ① 위 층 고침) = 키별로 새 문서에 얹음 ·
`손고침` 문서(M01 화면이 셈 칸을 고쳐 저장) = 저장본 그대로 · 실행 · `--check` 때 목록으로 알림.
- 이름표(855 L1) = 로직 줄 `원문번호 · 구분 · 상세구분 · 소유 · 비고 · 개정 · 별칭` → 문서 줄 머리 ·
로직 파일 머리 `원문 · 부문 · 차례` → 문서 파일 머리(`master_doc.tag` · 셈 · 지문 밖 · `--check` 기준).
- 빌더가 짓지 않는 저장본 문서(848-4 · 옛 로직 줄 없는 키 — 화면에서 만든 자체 로직 등) = 지우거나 덮지 않음 ·
제 파일 끝에 그대로(`foreign`) · 실행 · `--check` 때 목록 · `--check` 는 그대로면 같음.
"""
@@ -217,14 +219,30 @@ def hand_kept(result: dict) -> list[str]:
return sorted(k for k, d in have.items() if d.get(mcv.HAND) and k in result["저장"])
def _out_doc(result: dict, key: str) -> dict:
"""쓸 문서 — `손고침` = 저장본 · 저장본 `기계덮음` = 새 문서에 얹음 · 그 밖 = 새 문서."""
def _labels() -> tuple[dict[str, dict], dict[str, dict]]:
"""855 L1 이름표 — ({키: 로직 줄}, {로직 파일: 머리 이름표}) · 셈 · 지문 밖."""
from M01_MasterData import M01_MasterData_Store as m01
rows, heads = {}, {}
for name, data in m01.loaded()[0].items():
if data.get("그룹") == "로직":
heads[name] = {k: data[k] for k in md.FILE_TAGS if k in data}
rows.update({str(r["키"]): r for r in data.get("줄") or []})
return rows, heads
def _out_doc(result: dict, key: str, rows: dict | None = None) -> dict:
"""쓸 문서 — `손고침` = 저장본 · 저장본 `기계덮음` = 새 문서에 얹음 · 그 밖 = 새 문서 ·
이름표(855 L1) = 로직 줄 것(`rows` · 없으면 그대로)."""
have = (result.get("저장본") or {}).get(key)
if have and have.get(mcv.HAND):
return have
if have and have.get(mcv.COVER):
return {**result["문서"][key], mcv.COVER: have[mcv.COVER]}
return result["문서"][key]
out = have
elif have and have.get(mcv.COVER):
out = {**result["문서"][key], mcv.COVER: have[mcv.COVER]}
else:
out = result["문서"][key]
row = (rows or {}).get(key)
return md.tag(out, row) if row is not None else out
def _calls(doc: dict) -> set[str]:
@@ -285,9 +303,11 @@ def lost(result: dict) -> list[str]:
def files_of(result: dict) -> dict[str, str]:
"""저장 파일 이름 → 글 · 빌더가 짓지 않는 저장본 문서 = 제 파일 끝에 그대로."""
bodies = {}
rows, heads = _labels()
for name, keys in result["파일"].items():
kept = [_out_doc(result, k) for k in keys if k in result["저장"]]
bodies[ml.file_of(name)] = {"그룹": "수식문서", "로직파일": name, "줄": kept}
kept = [_out_doc(result, k, rows) for k in keys if k in result["저장"]]
head = heads.get(name) or {} # 855 L1 파일 머리 이름표
bodies[ml.file_of(name)] = {"그룹": "수식문서", "로직파일": name, **head, "줄": kept}
for file, data in foreign(result).items():
if file in bodies:
bodies[file]["줄"] += data["줄"]
@@ -532,6 +532,29 @@ def loops(uses: dict[str, list[str]]) -> list[list[str]]:
return out
#: 이름표(855 L1) — 옛 로직 줄에서 옮겨 실음 · 셈 · 지문 밖(`doc_fp` 는 셈 칸만 봄)
TAGS = ("원문번호", "구분", "상세구분", "소유", "비고", "개정", "별칭")
#: 문서 파일 머리 이름표 — 옛 로직 파일 머리(분류 · 장 차례)
FILE_TAGS = ("원문", "부문", "차례")
def tags_of(doc: dict) -> dict:
"""문서(또는 로직 줄)의 이름표 칸만."""
return {t: doc[t] for t in TAGS if t in doc}
def tag(doc: dict, row: dict) -> dict:
"""이름표를 `row`(로직 줄 · 이름표 묶음) 것과 같게 — `키` 바로 뒤 · 없는 칸은 뺌 · 새 묶음."""
out: dict = {}
for k, v in doc.items():
if k in TAGS:
continue
out[k] = v
if k == "키":
out.update(tags_of(row))
return out
def blank(key: str = "", name: str = "", unit: str = "원") -> dict:
"""빈 문서 — 빈 화면에서 시작(변수 · 식 · 금액 없음 · 기본 끝수만 적어 둠)."""
return {
+140
View File
@@ -0,0 +1,140 @@
"""855 L1 지킴 — 수식 문서 이름표(줄 머리 `원문번호 구분 상세구분 소유 비고 개정 별칭` · 파일 머리
`원문 부문 차례`) = 옛 로직 줄 · 파일 머리(다름 0) · 화면 저장 길(비고 · 별칭 · 신규 · 복사 · 문서 저장 ·
삭제)을 지나도 같음 · 이름표는 셈 지문(`doc_fp`) 밖. 저장 길 시험은 마스터 · 문서 사본 폴더에서만."""
from __future__ import annotations
import copy
import json
import shutil
from pathlib import Path
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from M01_MasterData import M01_MasterData_Alias as alias_module
from M01_MasterData import M01_MasterData_Doc as doc_store
from M01_MasterData import M01_MasterData_Router as router_module
from M01_MasterData import M01_MasterData_Store as store
md = doc_store.md
ml = doc_store.ml
REAL = store.FOLDER
SAMPLE = "GF000219" # 산림 13-4-1 메쌓기(인력)
def _logic_files(folder: Path) -> dict[str, dict]:
return {p.name: json.loads(p.read_text(encoding="utf-8")) for p in folder.glob("로직_*.json")}
def _gaps(folder: Path, docs_folder: Path) -> list[str]:
"""로직 줄 · 파일 머리 이름표 대 수식 문서 — 다른 자리 목록."""
out = []
docs = {}
for path in docs_folder.glob("수식_*.json"):
data = ml.load_file(path)
docs.update({str(d["키"]): d for d in data.get("줄") or []})
logic = folder / str(data.get("로직파일") or "")
if logic.is_file():
head = json.loads(logic.read_text(encoding="utf-8"))
want = {k: head[k] for k in md.FILE_TAGS if k in head}
if {k: data[k] for k in md.FILE_TAGS if k in data} != want:
out.append(f"머리 {path.name}")
for name, data in _logic_files(folder).items():
for row in data.get("줄") or []:
doc = docs.get(str(row["키"]))
if doc is None:
out.append(f"문서 없음 {row['키']}")
elif ml._norm(md.tags_of(doc)) != ml._norm(md.tags_of(row)):
out.append(f"이름표 {row['키']}")
return out
def test_문서_이름표가_로직_줄과_같다() -> None:
assert _gaps(REAL, ml.FOLDER) == []
rows = sum(len(d.get("줄") or []) for d in _logic_files(REAL).values())
assert rows == 1521
def test_이름표는_셈_지문_밖() -> None:
from M02_MasterTemplete import M02_Doc_Copy as dc
doc = doc_store.docs()[SAMPLE]
bare = {k: v for k, v in doc.items() if k not in md.TAGS}
assert md.tags_of(doc) and dc.doc_fp(doc) == dc.doc_fp(bare)
@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(ml, "FOLDER", tmp_path / "수식문서")
doc_store._memo.clear()
app = FastAPI()
app.include_router(router_module.router)
app.include_router(alias_module.router)
return TestClient(app)
def _ok(res) -> dict:
assert res.status_code == 200, res.text
return res.json()
def _doc(key: str) -> dict:
return doc_store.docs()[key]
def test_화면_저장_길을_지나도_이름표가_같다(client: TestClient, tmp_path: Path) -> None:
# 비고 고침([저장] · 정본 개정 확인)
one = _ok(client.get("/api/m01/logic", params={"key": SAMPLE}))
row = {**one["logic"], "비고": "sub5임시 비고"}
part = {"file": one["file"], "version": one["version"],
"changes": [{"op": "edit", "key": SAMPLE, "row": row}]} # fmt: skip
_ok(client.post("/api/m01/save", json={"files": [part], "개정확인": True}))
assert _doc(SAMPLE)["비고"] == "sub5임시 비고"
# 별칭 넣고 뺌(별칭 모아 보기 길)
_ok(client.post("/api/m01/alias/save", json={"키": SAMPLE, "별칭": "sub5임시"}))
assert _doc(SAMPLE)["별칭"] == "sub5임시"
_ok(client.post("/api/m01/alias/save", json={"키": SAMPLE, "별칭": ""}))
assert "별칭" not in _doc(SAMPLE)
# 문서 저장 왕복 — 화면이 이름표 칸을 빼고 보내도 로직 줄 것으로 실림
got = _ok(client.get("/api/m01/logic/doc", params={"key": SAMPLE}))
sent = {k: v for k, v in got["문서"].items() if k not in md.TAGS}
_ok(client.post("/api/m01/logic/doc/save", json={"문서": sent, "판": got["판"]}))
assert md.tags_of(_doc(SAMPLE))["비고"] == "sub5임시 비고"
assert "손고침" not in _doc(SAMPLE)
# 복사/생성 · 자체 이름 고침 · 삭제
made = _ok(client.post("/api/m01/logic/copy", json={"key": SAMPLE, "이름": "sub5임시 복사"}))
key = made["key"]
assert _doc(key)["소유"] == "현장" and _doc(key)["구분"] == "자체"
info = _ok(client.get("/api/m01/logic", params={"key": key}))
fixed = {**info["logic"], "비고": "sub5임시 자체 비고"}
part = {"file": info["file"], "version": info["version"],
"changes": [{"op": "edit", "key": key, "row": fixed}]} # fmt: skip
_ok(client.post("/api/m01/save", json={"files": [part]}))
assert _doc(key)["비고"] == "sub5임시 자체 비고"
assert _gaps(tmp_path, tmp_path / "수식문서") == []
info = _ok(client.get("/api/m01/logic", params={"key": key}))
body = {"key": key, "file": info["file"], "version": info["version"]}
_ok(client.post("/api/m01/logic/remove", json=body))
assert key not in doc_store.docs()
assert _gaps(tmp_path, tmp_path / "수식문서") == []
def test_tag_는_셈_칸을_안_건드림() -> None:
doc = copy.deepcopy(_doc(SAMPLE))
out = md.tag(doc, {"비고": "x", "별칭": "y"})
assert {k: v for k, v in out.items() if k not in md.TAGS} == {
k: v for k, v in doc.items() if k not in md.TAGS
}
assert md.tags_of(out) == {"비고": "x", "별칭": "y"}
assert list(out)[: list(out).index("키") + 3][-2:] == ["비고", "별칭"]