앞 세션 auto 커밋 cce57c298(Store_Logic 새 길 · /logic 답 머리만 · 판 = 문서 파일 지문 · 개정 = 문서 머리 대조 · 별칭 · 기계 등록 · [신규] · [삭제])에 이어 - Store_Cache: 막힘 세기(blocks · counted)를 문서 파일마다 · 저장 검사 logic_errors = 키 겹침 · 대장(요소 + 문서 키) · 연결 · 문서 막힘(check_logics 로직 줄 검사 걷음) · _docs_of = 문서 전부 · narrow 로직 갈래 걷음 · check_saved(부름 0) 지움 - Store_Save: 기초(로직 파일) 받지 않음(400) · gone · labor_errors(whole) 갈래 걷음 - Store_Logic: 정본 파일에도 새 기초(그 파일 표 키 — 옛 /save 와 같음) · 지움 검사에 조합 · 지운 기초를 부르던 문서 더함(옛 422 그대로) · 쓰는 곳 409 는 Doc.remove 로(옛 자리) - 시험(옛 /save 로 로직 줄 셈 칸 고침 · /logic 답 셈 칸을 붙든 것 = 죽은 길): 새 test_855_l3_doc_only(로직 파일 없음 + 같이 쓰기 끔 = 켬과 답 같음 · 목록 · 상세 · 저장 · 개정 409 · 판 409 · 별칭 · 신규 · 복사 · 삭제 · 기계 등록) · test_m01_cache 셈 칸 /save 검사 셋 · test_794_1 식 고침 /save 422 걷음(셈 칸 고침 = 문서 저장 몫 · /save 는 머리만 씀) · test_m01_make 「시험 계산에 돈다」 → 빈 문서로 열림 · test_m01_api · test_m01_text 옛 셈 길 시험은 로직 줄 사본에서 읽음 · test_854_2_m01_key_book 대장 끊김 = 인력 줄 + 기초 문서 쓰기 · test_794_1b · test_804_7 판 = 문서 파일 · test_802_3 문서 없는 키 = 404(빈 문서 안 지음) · test_826_2 좁힌 검사 = 판정만 견줌(기초 흠 글이 문서 꼴) · 로직 갈래 셋 뺌 · test_m01_copy 옛 시트 길 걷고 master_copy 왕복만 · test_854_2_m01_copy_doc 식 복사 → 기본정보 고친 복사 · test_713_1 · test_796_1 row_print 줄 뺌(row_print 지움) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
332 lines
15 KiB
Python
332 lines
15 KiB
Python
"""M01 「만들기」 저장소 — 원문 절 목록 · 표 조건 값 · 자체 로직 만들기 · 본뜨기(= [복사/생성]) · 고치기 · 지우기.
|
|
|
|
계약: `resources/master_data/_화면_계약.md` 2장·5장 · 파일 모양: `_틀.md` 7장.
|
|
기초(로직) 저장 = 수식 문서 먼저(`Store_Logic` · 855 L3 ⓐ) · 자체 기초는 `수식_자체.json` 한 파일 ·
|
|
키는 `_키대장.json` 의 `GX` 다음 번호(서버가 줌).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from M01_MasterData import M01_MasterData_Doc as doc_store
|
|
from M01_MasterData import M01_MasterData_Machine as machine
|
|
from M01_MasterData import M01_MasterData_Store as store
|
|
from M01_MasterData import M01_MasterData_Store_Logic as logic_store
|
|
from M01_MasterData import M01_MasterData_Store_Revise as revise
|
|
|
|
cm, mk = store.cm, store.mk
|
|
|
|
OWN = "로직_자체.json" # 자체 로직 한 자리 — 이 파일 줄만 고치고 지울 수 있음
|
|
OWNERS = ("현장", "공용")
|
|
BODY = mk._BODY # resources/knowledge/original/원가계산
|
|
BOOKS = {"산림품셈": "산림_표준품셈", "건설품셈": "건설공사_표준품셈"}
|
|
_HEAD = re.compile(r"^#{2,6}\s*(\d+(?:-\d+)*)\.?\s+(\S.*?)\s*$")
|
|
_CHAPTER_DIR = re.compile(r"^제(\d\d)장_(.+)$")
|
|
|
|
|
|
# ── 원문 절 목록 ───────────────────────────────────────────────────────
|
|
def _chapters(book: str):
|
|
"""(부문, 장 번호, 장 제목, 폴더) — 건설품셈은 부문 폴더 아래."""
|
|
root = BODY / BOOKS[book] / "본문"
|
|
tops = sorted(root.glob("*부문")) if book == "건설품셈" else [root]
|
|
for top in tops:
|
|
division = top.name.split("_", 1)[1].removesuffix("부문") if book == "건설품셈" else ""
|
|
for folder in sorted(top.glob("제*장_*")):
|
|
m = _CHAPTER_DIR.match(folder.name)
|
|
if m:
|
|
yield division, m.group(1), m.group(2).replace("_", " "), folder
|
|
|
|
|
|
_CACHE: dict[str, list[dict]] = {}
|
|
|
|
|
|
def _all_sections(book: str) -> list[dict]:
|
|
"""원문 본문 제목 줄에서 모은 절 — 한 번 세워 두고 다시 씀(원문은 안 바뀜)."""
|
|
if book in _CACHE:
|
|
return _CACHE[book]
|
|
out, seen = [], set()
|
|
for division, number, title, folder in _chapters(book):
|
|
for md in sorted(folder.glob("*.md")):
|
|
for line in md.read_text(encoding="utf-8").split("\n"):
|
|
m = _HEAD.match(line)
|
|
if not m or m.group(1).split("-")[0] != str(int(number)):
|
|
continue
|
|
if (division, m.group(1)) in seen:
|
|
continue
|
|
seen.add((division, m.group(1)))
|
|
out.append(
|
|
{
|
|
"book": book,
|
|
"division": division,
|
|
"chapter": f"{division} {number}장 {title}".strip(),
|
|
"chapterNo": number,
|
|
"section": m.group(1),
|
|
"title": m.group(2),
|
|
}
|
|
)
|
|
_CACHE[book] = out
|
|
return out
|
|
|
|
|
|
# ── 로직 원문(출처 글 → 품셈 본문 절) ──────────────────────────────────
|
|
_NUMBER = re.compile(r"(?<![\d-])(\d+(?:-\d+)+)(?![\d-])(?:\s+(주[①-⑳]?|\d{1,2})(?![\d-]))?")
|
|
_ESCAPE = re.compile(r"\\([.\-*_()#\[\]>~`])") # 마크다운 이스케이프 `\.` `\-` …
|
|
_COMMENT = re.compile(r"<!--.*?-->") # 글 안 주석(글자층 표시) — 글자만 남김
|
|
_CIRCLED = "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳"
|
|
|
|
|
|
def _plain(text: str) -> str:
|
|
"""원문 md 기호 벗김 — 주석 · 이스케이프 · 인용 머리 `> `."""
|
|
text = _ESCAPE.sub(r"\1", _COMMENT.sub("", text)).strip()
|
|
return text[1:].strip() if text.startswith(">") else text
|
|
|
|
|
|
def _blocks(lines: list[str]) -> list[dict]:
|
|
"""md 줄 → 화면 조각 — 제목 {h} · 표 {table} · 글 {p} · 주석 줄은 뺌 ·
|
|
빈 줄 · 주석이 표를 끊음(붙은 표 둘을 한 표로 안 합침) · `<br>` = 줄바꿈."""
|
|
out: list[dict] = []
|
|
joinable = False
|
|
for line in lines:
|
|
text = re.sub(r"<br\s*/?>", "\n", line.strip())
|
|
if not text or text.startswith("<!--"):
|
|
joinable = False
|
|
continue
|
|
if not text.startswith(("#", "|")):
|
|
text = _plain(text)
|
|
if not text:
|
|
joinable = False
|
|
continue
|
|
if text.startswith("#"):
|
|
out.append({"h": len(text) - len(text.lstrip("#")), "text": text.lstrip("#").strip()})
|
|
elif text.startswith("|"):
|
|
cells = [_plain(c) for c in text.strip("|").split("|")]
|
|
if all(re.fullmatch(r":?-{3,}:?", c) for c in cells):
|
|
continue # 머리 · 몸 가름 줄
|
|
if not joinable:
|
|
out.append({"table": []})
|
|
out[-1]["table"].append(cells)
|
|
joinable = True
|
|
continue
|
|
else:
|
|
out.append({"p": text})
|
|
joinable = False
|
|
return out
|
|
|
|
|
|
def _mark(blocks: list[dict], item: str) -> bool:
|
|
"""출처 항 · 주 번호(「1」 · 「주③」 · 「주」)에 드는 조각에 hit 표시 — 못 찾으면 False(절 통째만)."""
|
|
texts = [b.get("p") or b.get("text") or "" for b in blocks]
|
|
if item.startswith("주"):
|
|
note = next((i for i, t in enumerate(texts) if t.startswith("[주]")), None)
|
|
if note is None:
|
|
return False
|
|
start, stop = note, len(blocks)
|
|
if len(item) > 1: # 「주③」 — [주] 아래 ③ 줄 하나(다음 ① ~ ⑳ 줄 앞까지)
|
|
start = next(
|
|
(i for i in range(note + 1, len(texts)) if texts[i].startswith(item[1])), None
|
|
)
|
|
if start is None:
|
|
return False
|
|
stop = next(
|
|
(i for i in range(start + 1, len(texts)) if texts[i][:1] in _CIRCLED), len(blocks)
|
|
)
|
|
else: # 「1」 — 「1. …」 제목 · 줄 ~ 다음 제목 · 「2. …」 앞(줄이면 [주] 앞도)
|
|
head = re.compile(rf"{item}[.)]\s")
|
|
start = next((i for i, t in enumerate(texts) if head.match(t)), None)
|
|
if start is None:
|
|
return False
|
|
under = "h" in blocks[start]
|
|
stop = next(
|
|
(
|
|
i
|
|
for i in range(start + 1, len(blocks))
|
|
if "h" in blocks[i]
|
|
or (not under and re.match(r"\d+[.)]\s|\[주\]", texts[i]))
|
|
or (under and re.match(r"\d+[.)]\s", texts[i]) and "p" in blocks[i])
|
|
),
|
|
len(blocks),
|
|
)
|
|
for b in blocks[start:stop]:
|
|
b["hit"] = True
|
|
return True
|
|
|
|
|
|
def _section(book: str, division: str, number: str) -> dict | None:
|
|
"""번호 절을 품셈 본문에서 찾음 — 없으면 끝 마디를 하나씩 떼며 위 절로(두 마디까지)."""
|
|
parts = number.split("-")
|
|
folders = [f for d, no, _t, f in _chapters(book) if d == division and int(no) == int(parts[0])]
|
|
for upto in range(len(parts), 1, -1):
|
|
want = "-".join(parts[:upto])
|
|
for folder in folders:
|
|
for md in sorted(folder.glob("*.md")):
|
|
lines = md.read_text(encoding="utf-8").split("\n")
|
|
for i, line in enumerate(lines):
|
|
m = _HEAD.match(line)
|
|
if not m or m.group(1) != want:
|
|
continue
|
|
level = len(line) - len(line.lstrip("#"))
|
|
end = next(
|
|
(
|
|
j
|
|
for j in range(i + 1, len(lines))
|
|
if _HEAD.match(lines[j])
|
|
and len(lines[j]) - len(lines[j].lstrip("#")) <= level
|
|
),
|
|
len(lines),
|
|
)
|
|
return {
|
|
"number": number,
|
|
"matched": want,
|
|
"file": md.relative_to(BODY.parent).as_posix(),
|
|
"blocks": _blocks(lines[i:end]),
|
|
}
|
|
return None
|
|
|
|
|
|
def source(src: str) -> dict:
|
|
"""로직 출처 글(예 「건설품셈 토목 1-1-2」 · 「산림품셈 3-4-2 1」)로 찾은 품셈 원문 절 —
|
|
번호가 여럿이면(「8-1-5 · 8-1-6」) 절마다 · 못 찾으면 found 빈 목록(화면 「원문 연결 없음」)."""
|
|
words = src.split()
|
|
book = words[0] if words else ""
|
|
if book not in BOOKS:
|
|
return {"source": src, "found": []}
|
|
division = (
|
|
next((d for d in cm.DIVISIONS if src.startswith(f"{book} {d} ")), "")
|
|
if book == "건설품셈"
|
|
else ""
|
|
)
|
|
found = []
|
|
for number, item in dict.fromkeys(_NUMBER.findall(src)):
|
|
one = _section(book, division, number)
|
|
if one:
|
|
if item and _mark(one["blocks"], item):
|
|
one["item"] = item
|
|
found.append(one)
|
|
return {"source": src, "found": found}
|
|
|
|
|
|
# ── 저장 ──────────────────────────────────────────────────────────────
|
|
def _alias(part: dict) -> None:
|
|
"""별칭(815-2) = 앞뒤 빈칸만 뗌 · 빈 글 = 칸 없음."""
|
|
for ch in part.get("changes") or []:
|
|
row = ch.get("row")
|
|
if isinstance(row, dict) and "별칭" in row:
|
|
text = str(row["별칭"] or "").strip()
|
|
row.update(별칭=text) if text else row.pop("별칭")
|
|
|
|
|
|
def save(batch: list[dict], confirmed: bool = False) -> dict:
|
|
"""`/save` — 기초(로직 파일 몫)는 `Store_Logic`(문서 먼저 · 정본 머리 고침은 `confirmed` 없으면 409) ·
|
|
요소 · 표는 `store.save` · 자체 새 줄(키 없음)은 서버가 칸을 잡고 GX 다음 키 — {files, added, warnings}."""
|
|
logic = [p for p in batch if logic_store.is_logic(str(p.get("file") or ""))]
|
|
rest = [p for p in batch if not logic_store.is_logic(str(p.get("file") or ""))]
|
|
revise.guard(logic, confirmed)
|
|
for part in batch:
|
|
_alias(part)
|
|
for part in logic:
|
|
for ch in part.get("changes") or []:
|
|
row = ch.get("row")
|
|
if (
|
|
part.get("file") == OWN
|
|
and isinstance(row, dict)
|
|
and (ch.get("op") == "add" or not ch.get("key"))
|
|
):
|
|
ch.update(op="add", key=None, row=_clean(row, str(row.get("소유") or OWNERS[0])))
|
|
files, added = [], []
|
|
if rest:
|
|
for part in rest:
|
|
machine.fix(part) # 기계 줄 = 계수 서버 재계산 · 단위 · 출처 채움(821-2)
|
|
_keep_same(part)
|
|
docs_too = machine.register(rest) # [새 기계] = 꼴 식 목록 등록(822-2 · 848-5 문서 정본)
|
|
before = {
|
|
p["file"]: set(_file_keys(p["file"])) for p in rest
|
|
} # 자재 3만 키 — 목록 찾기 금지
|
|
with store.cache.picks(*getattr(docs_too, "lists", ({}, set()))):
|
|
files = store.save(rest)
|
|
docs_too()
|
|
added = [
|
|
{"file": f, "key": k}
|
|
for f, old in before.items()
|
|
for k in _file_keys(f)
|
|
if k not in old
|
|
]
|
|
if logic:
|
|
got = logic_store.save(logic, True)
|
|
files, added = files + got["files"], added + got["added"]
|
|
return {"files": files, "added": added, "warnings": []}
|
|
|
|
|
|
def _keep_same(part: dict) -> None:
|
|
"""고친 줄의 값이 같은 칸 = 파일 값 그대로(화면 왕복 「9.0」 → 「9」 막음 · 그 칸만 바뀜)."""
|
|
data = store.loaded()[0].get(str(part.get("file") or "")) # 읽기만 — 기억(826-2)
|
|
if data is None:
|
|
return
|
|
rows = {str(r.get("키")): r for r in data.get(store.items_key(data)) or []}
|
|
for ch in part.get("changes") or []:
|
|
old, row = rows.get(str(ch.get("key"))), ch.get("row")
|
|
if ch.get("op") == "edit" and isinstance(old, dict) and isinstance(row, dict):
|
|
same = {k for k, v in row.items() if k in old and store._dec(v) == old[k]}
|
|
ch["row"] = {k: old[k] if k in same else v for k, v in row.items()}
|
|
|
|
|
|
def _file_keys(file: str) -> list[str]:
|
|
data = store.loaded()[0].get(file) or {} # 읽기만 — 기억(826-2 · 저장 뒤엔 갈아 끼운 것)
|
|
return [str(r.get("키")) for r in data.get(store.items_key(data)) or []]
|
|
|
|
|
|
# ── 자체 로직 ──────────────────────────────────────────────────────────
|
|
def _clean(logic: dict, owner: str, key: str | None = None) -> dict:
|
|
"""서버가 잡는 칸 — 키·소유·구분·상세구분. 화면이 보낸 것은 안 씀."""
|
|
if not isinstance(logic, dict) or not str(logic.get("이름") or "").strip():
|
|
raise store.StoreError(400, "로직 줄에 「이름」 이 없음")
|
|
if owner not in OWNERS:
|
|
raise store.StoreError(400, f"모르는 소유 「{owner}」 — {' · '.join(OWNERS)}")
|
|
number = str(logic.get("원문번호") or "")
|
|
rest = {
|
|
k: v for k, v in logic.items() if k not in ("키", "원문번호", "구분", "상세구분", "소유")
|
|
}
|
|
head = {"키": key, "원문번호": number} if key else {"원문번호": number}
|
|
one = {**head, "구분": "자체", "상세구분": _chapter_of(logic), "소유": owner, **rest}
|
|
order = mk.ROW_ORDER["로직"] # 열 차례는 `_틀.md` 2장
|
|
return {
|
|
**{k: one[k] for k in order if k in one},
|
|
**{k: v for k, v in one.items() if k not in order},
|
|
}
|
|
|
|
|
|
def _chapter_of(logic: dict) -> str:
|
|
"""상세구분 — 원문 절이 속한 장(「13장 구조물」) · 원문 절이 없으면 빈 글."""
|
|
number = str(logic.get("원문번호") or "")
|
|
source = str(logic.get("출처") or "")
|
|
book = next((b for b in BOOKS if source.startswith(b)), "")
|
|
if not number or not book:
|
|
return ""
|
|
at = int(number.split("-")[0])
|
|
division = next((d for d in cm.DIVISIONS if source.startswith(f"{book} {d} ")), "")
|
|
for one_division, chapter, title, _ in _chapters(book):
|
|
if one_division == division and int(chapter) == at:
|
|
return f"{chapter}장 {title}"
|
|
return ""
|
|
|
|
|
|
def logic_new(logic: dict, owner: str = OWNERS[0], source: str = "") -> dict:
|
|
"""새 자체 기초 — 키 = 서버가 `GX` 다음 번호 · 문서 = 빈 문서 / `source` 문서 복제(본뜸) ·
|
|
옛 로직 줄은 같이 쓰기(`Store_Logic.mirror`)."""
|
|
change = {"op": "add", "row": _clean(logic, owner), "from": source}
|
|
part = {"file": OWN, "version": doc_store.file_version(OWN), "changes": [change]}
|
|
got = logic_store.save([part], True)
|
|
key = got["added"][-1]["key"]
|
|
return {**got["files"][0], "key": key, "logic": store.logic(key)["logic"], "수식문서": True}
|
|
|
|
|
|
def logic_copy(key: str, 이름: str = "", owner: str = OWNERS[0], more: dict | None = None) -> dict:
|
|
"""본떠 만들기 = [복사/생성] — 원본 문서를 새 자체 기초로 복제(정본도 본뜸) · 비고 끝에 본뜬 키 ·
|
|
`more` = 기본정보 창에서 고친 원문번호 · 결과단위 · 출처(빈 글은 원본 그대로)."""
|
|
_, doc = doc_store.find(key)
|
|
row = doc_store.head_of(doc)
|
|
note = " · ".join(x for x in (str(row.get("비고") or ""), f"{key} 를 본뜸") if x)
|
|
copy = {**row, "비고": note, **{k: v for k, v in (more or {}).items() if v}}
|
|
if 이름:
|
|
copy["이름"] = 이름
|
|
return logic_new(copy, owner, key)
|