Merge branch 'sub_laptop_5' of C:/Aislo_wt/sub_laptop_5 into main_laptop_1

This commit is contained in:
2026-11-17 21:31:22 +09:00
11 changed files with 369 additions and 51 deletions
+21 -9
View File
@@ -178,7 +178,26 @@ def register(batch: list[dict]) -> Callable[[], None]:
changes.append({"op": "edit", "key": logic["키"], "row": new})
if changes:
batch.append({"file": name, "version": store.read(name)[1], "changes": changes})
return lambda: _register_docs(add, drop)
after = lambda: _register_docs(add, drop) # noqa: E731
after.lists = (
add,
drop,
) # 저장 검사가 문서 목록을 미리 같게 봄(`Store_Cache.picks` · 855 2-B3)
return after
def relist(doc: dict, add: dict[str, list[str]], drop: set[str]) -> bool:
"""문서 하나의 「기계」 고르기 목록에 더함 · 뺌(제자리 고침) — 바뀌었으면 True."""
hit = False
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
return hit
def _register_docs(add: dict[str, list[str]], drop: set[str]) -> None:
@@ -192,14 +211,7 @@ def _register_docs(add: dict[str, list[str]], drop: set[str]) -> None:
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
hit = relist(doc, add, drop) or hit
if hit:
docs.put(path, data)
+1 -1
View File
@@ -387,7 +387,7 @@ def logic(key: str) -> dict:
for name, data in _logic_files(files):
for row in data.get("줄") or []:
if str(row.get("키")) == key:
reasons = cm.mf.check_logic(whole, row)[0]
reasons = cache.reasons(key, whole) # 수식 문서 기준(855 2-B3)
_, version = read(name)
return {
"file": name,
+68 -26
View File
@@ -12,6 +12,7 @@ from __future__ import annotations
import contextlib
import contextvars
import copy
import json
import sys
import threading
@@ -22,7 +23,7 @@ SCRIPTS = Path(__file__).resolve().parents[1] / "resources/master_data/scripts"
sys.path.insert(0, str(SCRIPTS))
import check_master as cm # noqa: E402
import master_material as mm # noqa: E402 (자재품목 테이블ID — 재료 고르기는 그 묶음을 훑음)
import master_doc_block as mb # noqa: E402 (막힘 · 저장 검사 = 수식 문서 기준 · 855 2-B3)
_FRESH = threading.RLock()
_READ: dict[str, tuple[tuple, dict]] = {} # 파일 이름 → (자국, 읽은 내용)
@@ -72,34 +73,27 @@ def _logic_files(files: dict[str, dict]):
yield name, data
class _Watch:
"""`Master.get` 을 감싸 그 로직 줄이 본 요소·표를 적어 둠 — 저장 때 검사를 좁히는 지도."""
def docs() -> dict[str, dict]:
"""저장 수식 문서 전부 {키: 문서}(`M01_MasterData_Doc.docs` · 파일 시각이 같으면 같은 묶음)."""
from M01_MasterData import M01_MasterData_Doc as doc_store # Doc 이 Store 를 부름 — 늦게
def __init__(self, whole):
self._whole, self.seen = whole, set()
return doc_store.docs()
def get(self, ref):
self.seen.add(str(ref))
return self._whole.get(ref)
def __getattr__(self, name):
return getattr(self._whole, name)
def __setattr__(self, name, value): # 속에 적어 둠 — 미리 갈라 둔 것을 줄마다 다시 안 짜게
if name in ("_whole", "seen"):
super().__setattr__(name, value)
else:
setattr(self._whole, name, value)
def reasons(key: str, whole) -> list[str]:
"""로직 하나의 막힘 까닭 — 수식 문서 기준(`master_doc_block` · 요소 닫힘은 `whole` 색인)."""
have = docs()
return mb.reasons(key, have.get(key), have, whole)
def _check(whole, row: dict) -> tuple[list[str], set, set]:
"""(막힘 까닭, 부르는 로직, 본 요소·표) — 본 것은 키 · 「ID:원문번호」 ·
재료 고르기가 있으면 자재품목 묶음 통째(「#MT」 · 후보를 그 안에서 고름)."""
watch = _Watch(whole)
why, calls = cm.mf.check_logic(watch, row)
if any(isinstance(h.get("요소"), dict) for h in row.get("호표") or []):
watch.seen.add("#" + mm.MARKET)
return why, calls, watch.seen
"""(막힘 까닭, 부르는 로직, 본 요소·표) — 그 로직의 수식 문서 기준(855 2-B3) ·
본 것 = 연결 요소 · 표 키 · 재료 고르기면 자재품목 묶음 통째(「#MT」)."""
have, key = docs(), str(row.get("키"))
doc = have.get(key)
if doc is None:
return mb.reasons(key, None, have, whole), set(), set()
return mb.reasons(key, doc, have, whole), mb.calls(doc), mb.seen(doc)
def forget() -> None:
@@ -180,6 +174,9 @@ def blocks(folder: Path) -> dict[str, list[str]]:
with _FRESH:
files, whole = loaded(folder)
stamps = _INDEX["자국"]
if _INDEX.get("문서") is not (now := docs()): # 수식 문서가 바뀌면 통째로 다시
_BLOCK.clear()
_INDEX["문서"] = now
base = {n: s for n, s in stamps.items() if files[n].get("그룹") != "로직"}
marks = None # 요소·표에서 흔들린 자리 — None 이면 무엇이 바뀐지 모름(통째로 다시)
if _BASE != base: # 인력 · 재료 · 표가 바뀌면 바탕이 달라짐
@@ -236,7 +233,7 @@ def narrow(folder: Path, batch: list[dict], before: dict, after: dict):
"""(검사할 로직 키, 안 보는 줄이 부르는 키, 요소도 고쳤는지) — 저장이 흔드는 줄만.
로직 줄은 고친 줄과 **그 줄을 부르던 줄** · 요소·표 줄은 그 줄을 **보던 로직**
(키 · 「ID:원문번호」 · 자재품목은 묶음 통째 — `_Watch` 가 적어 둔 지도).
(키 · 「ID:원문번호」 · 자재품목은 묶음 통째 — `_check` 가 적어 둔 지도 · 855 2-B3 부터 수식 문서 연결).
"""
counts = counted(folder)
calls = {key: got[1] for key, got in counts.items()}
@@ -270,10 +267,55 @@ def check_saved(files: dict, changed: list[str], book: dict, narrowed=None) -> l
"""
whole = cm.mf.Master(files)
out = [x for name in changed for x in cm.check_form(name, files[name])]
out += cm.check_logics(files, whole, book, narrowed and narrowed[:2])
out += logic_errors(files, whole, book, narrowed and narrowed[:2])
if narrowed and narrowed[2]: # 요소·표를 고쳤으면 연결 · 준용도 봄(로직 좁힘과 따로)
out += cm.check_links(whole)
return out + cm.mcb.check_all(files, whole) + labor_errors(whole)
return out + combo_errors(files) + labor_errors(whole)
_PICKS: contextvars.ContextVar[tuple | None] = contextvars.ContextVar("m01_picks", default=None)
@contextlib.contextmanager
def picks(add: dict, drop: set):
"""저장 중 — 저장 뒤 수식 문서 기계 고르기 목록에 할 더함 · 뺌(`Machine.register`)을 검사가 미리 봄."""
token = _PICKS.set((add, drop))
try:
yield
finally:
_PICKS.reset(token)
def _docs_of(files: dict) -> dict[str, dict]:
"""`files` 에 로직 줄이 있는 키의 수식 문서만 — 지운 로직은 문서가 아직 있어도 없는 것으로 ·
저장 중 기계 목록 고침(`picks`)은 사본에 얹음."""
keys = {str(r.get("키")) for _, data in _logic_files(files) for r in data.get("줄") or []}
out = {k: d for k, d in docs().items() if k in keys}
if pending := _PICKS.get():
from M01_MasterData import (
M01_MasterData_Machine as machine,
) # Machine 이 Store 를 부름 — 늦게
for k, d in out.items():
one = copy.deepcopy(d)
if machine.relist(one, *pending):
out[k] = one
return out
def logic_errors(files: dict, whole, book: dict | None, narrow=None) -> list[str]:
"""저장 검사의 로직 몫 — 옛 로직 줄 검사(`check_master.check_logics` · 좁힌 줄 · 키 겹침 · 대장 ·
연결)가 먼저 · 그것이 깨끗하면 수식 문서 막힘(`narrow` 를 주면 그 키만 · 문서 없는 새 줄은 안 봄 ·
요소 닫힘 · 문서 사이 순환) — 같은 흠을 두 번 안 적음.
ponytail: 로직 줄 몫 = 옛 `check_logic` 남음(로직 JSON 이 아직 옛 엔진 길에 쓰임) · L3 에서 걷음."""
out = cm.check_logics(files, whole, book, narrow)
return out or mb.check_docs(_docs_of(files), narrow[0] if narrow else None, whole)
def combo_errors(files: dict) -> list[str]:
"""일위대가 조합 전부(옛 `master_combo.check_all` 대신) — 로직이 있는지는 수식 문서로."""
have = _docs_of(files)
return [f"{name} · {x}" for name, row in cm.mcb.rows(files) for x in mb.combo_row(row, have)]
def _labor_files() -> list[tuple[str, Path]]:
+8 -2
View File
@@ -17,6 +17,7 @@ from config import config_system
from M01_MasterData import M01_MasterData_Store as store
cm, mk, mcb = store.cm, store.mk, store.mcb
import master_doc_block as mcb_doc # noqa: E402
import master_unit as mu # noqa: E402 — `store` 가 scripts 를 길에 둔 뒤(712-2)
FILE = mcb.FILE
@@ -86,6 +87,11 @@ def _write(changes: list[dict], version: str | None = None) -> dict:
return out[0]
def problems_of(row: dict) -> list[str]:
"""조합 한 줄 막힘 까닭 — 로직이 있는지는 수식 문서로(855 2-B3 · M02 조합 층도 씀)."""
return mcb_doc.combo_row(row, store.cache.docs())
# ── 읽기 ──────────────────────────────────────────────────────────────
def _brief(whole, row: dict) -> list[dict]:
"""담은 로직 줄에 그 로직의 이름·단위를 붙여 보임 — 없는 키는 `ok` false."""
@@ -122,7 +128,7 @@ def combos(sub: str = "", detail: str = "", q: str = "", owner: str = "") -> lis
continue
if not store._hit(row, q):
continue
problems = mcb.check_row(whole, row)
problems = problems_of(row)
out.append(
{
"file": FILE,
@@ -140,7 +146,7 @@ def combo(key: str) -> dict:
data, version = _read()
row = _find(data, key)
whole = store.loaded()[1]
problems = mcb.check_row(whole, row)
problems = problems_of(row)
return {
"file": FILE,
"version": version,
+2 -1
View File
@@ -251,7 +251,8 @@ def save(batch: list[dict], confirmed: bool = False) -> dict:
part["version"] = part.get("version") or store.read(OWN)[1]
before = {p["file"]: set(_file_keys(p["file"])) for p in batch} # 자재 3만 키 — 목록 찾기 금지
try:
files = store.save(batch)
with store.cache.picks(*getattr(docs_too, "lists", ({}, set()))):
files = store.save(batch)
except store.StoreError:
if fresh:
_own_path().unlink(missing_ok=True)
+2 -2
View File
@@ -67,11 +67,11 @@ def _index(files: dict, whole, moved: list[dict]):
def _errors(files, whole, names, book, narrowed, keys, gone) -> list[str]:
out = [x for name in names for x in cm.check_form(name, _only(name, files[name], keys[name]))]
out += cm.check_logics(files, whole, book, narrowed[:2])
out += cache.logic_errors(files, whole, book, narrowed[:2]) # 수식 문서 기준(855 2-B3)
if narrowed[2]: # 요소·표를 고쳤으면 연결 · 준용도 봄(로직 좁힘과 따로)
out += cm.check_links(whole)
if cm.mcb.FILE in names or gone:
out += cm.mcb.check_all(files, whole)
out += cache.combo_errors(files)
return out