Files
Aislo/M02_MasterTemplete/M02_Hopyo_Forget.py
T
eomsangdonandClaude Opus 5.5 aa30e68256 fix(859-4): 불러온 일위대가 판 [끝내기] 뒤에도 남음 · [수정] 후보 창 이름 규격
- 화면 판 고르기(Labor_Basis · 일위대가표 머리 [엑셀 단가 그대로 | 우리 단가로])는 앞 auto 커밋 09160485d 에 들어감(autopush 가 쓸어 올림 · 이 묶음 몫)
- Hopyo_Forget.strip_sc KEEP 에 단가기준 — [끝내기] · 화면 떠남 뒤에도 판 그대로(전에는 걷혀 우리 값으로 셈)
- Hopyo_View 자재 줄 후보 = 단가산출 길 후보 이름 · 규격(전에는 MT 이름 빈칸)
- 화면 한 바퀴(5183 · 검증 계정 개인 층): EST 북부청임도 제38호표 엑셀 판 60,759 = 엑셀 · 우리 판 미리 보기 60,504 · [내 일위대가로] 뒤 일위대가 화면 엑셀 60,759 → 우리 61,099(단산 SK 도 우리 값) · 저장 · 다시 열기 같음 / STmate 봉화 제1호표 58,889 = 엑셀 → 우리 59,948 저장 · 다시 열기 같음 · 만든 SC 3 · SK 8 지움 · 콘솔 0 · 서버 오류 0
- 시험 test_859_4 하나 더함(끝내도 판 남음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:44:07 +09:00

147 lines
6.8 KiB
Python

"""M02 일위대가 불러오기 끝냄(PLAN 743-1 · 요구 582-3 · 584-2) — 올린 엑셀은 그 불러오기 동안만.
끝냄 한 길 `finish` = [끝내기] · 화면 떠남 · 하루 지남(`Store.EXPIRE`) · 붙여넣기 만듦 뒤 ·
엑셀 보기 [삭제]:
HP · 격자 지움(블록 풀이 저장본 = Router 가 `Judge.forget`) · 그 HP 로 만든 이 층 일위대가(SC) · 단가산출(SK) 엑셀 사본 걷음
(`본뜬` → 출처 `{층 「실무자료」, 파일, 때, 누가}` + 전국자재 · 복사원본 · 판 `단가기준`(859-4) ·
SC 줄 메모 「실무 …」 걷음 · `본뜬.실무수량` = 모든 값이 그 줄 저장 `수량.손` 과 같을 때만
걷음(742-1 · 다르면 남김 = 금액 그대로)) · SK · SC `본뜬.또` = 그 HP 몫만 뺌 ·
문서 몸(줄 · 덮개 · 더한줄 · 별칭 · 구분)과 별칭 장부는 그대로 ·
끝낸 기록 없음(같은 엑셀 다시 올림 됨 · 키 번은 `불러옴.json` 번으로 다시 안 씀).
"""
from __future__ import annotations
import json
import re
from collections.abc import Callable
from datetime import datetime
from pathlib import Path
from typing import Any
from common_util.common_util_json import atomic_write_json
from M02_MasterTemplete import M02_Hopyo_Store as hopyo_store
from M02_MasterTemplete import M02_Labor_Ref as refs
ORIGIN = "실무자료"
KEEP = ("층", "파일", "전국자재", "복사원본", "단가기준")
_MEMO = re.compile(r"^실무 ")
# ── 사본 걷음(순수) ───────────────────────────────────────────────────
def _slim(got: dict[str, Any]) -> dict[str, Any]:
"""출처만 — 파일 · 때 · 누가(+ 전국자재 · 복사원본)."""
sure = got.get("확인") if isinstance(got.get("확인"), dict) else {}
out = {k: got[k] for k in KEEP if got.get(k) is not None}
return {**out, "층": ORIGIN, "때": sure.get("때"), "누가": sure.get("누가")}
def _hand(one: Any) -> Any:
qty = one.get("수량") if isinstance(one, dict) else None
return qty.get("손") if isinstance(qty, dict) else None
def _carried(doc: dict[str, Any], hands: dict[str, Any]) -> bool:
"""실무수량 값이 모두 그 줄 · 자재 저장 수량과 같음(742-1 저장 뒤)."""
lines = doc.get("담은로직") or []
mats = {m.get("코드"): m for m in doc.get("자재") or [] if isinstance(m, dict)}
for at, value in (hands.get("줄") or {}).items():
i = int(at) if str(at).isdigit() else -1
if not 0 <= i < len(lines) or _hand(lines[i]) != value:
return False
return all(_hand(mats.get(code)) == value for code, value in (hands.get("자재") or {}).items())
def strip_sc(doc: dict[str, Any]) -> dict[str, Any]:
"""일위대가(SC) 엑셀 사본 걷음 — 본뜬 출처만 · 줄 메모 「실무 …」 뺌."""
got = doc.get("본뜬") or {}
lines = [
{k: v for k, v in one.items() if k != "메모"}
if isinstance(one, dict) and _MEMO.match(str(one.get("메모") or ""))
else one
for one in doc.get("담은로직") or []
]
out = {**doc, "담은로직": lines, "본뜬": _slim(got)}
hands = got.get("실무수량")
if isinstance(hands, dict) and hands and not _carried(out, hands):
out["본뜬"]["실무수량"] = hands # 742 전 저장본 — 셈이 기대므로 남김
return out
def strip_sk(doc: dict[str, Any], gone: Callable[[dict], bool]) -> dict[str, Any]:
"""단가산출(SK) — 끝낸 출처(`gone(본뜬 · 또 한 칸)`) 몫만 걷음 · 다른 불러오기 몫은 그대로."""
got = doc.get("본뜬") or {}
also = [x for x in got.get("또") or [] if isinstance(x, dict) and not gone(x)]
own = _slim(got) if gone(got) else {k: v for k, v in got.items() if k != "또"}
return {**doc, "본뜬": {**own, "또": also} if also else own}
# ── 끝냄 ─────────────────────────────────────────────────────────────
def _docs(folder: Path, kind: str):
prefix = "SC" if kind == "precombo" else "SK"
for path in sorted((folder / kind).glob(f"{prefix}-*.json")):
try:
doc = json.loads(path.read_bytes())
except (OSError, ValueError):
continue
got = doc.get("본뜬") if isinstance(doc, dict) else None
if isinstance(got, dict) and got.get("층") == ORIGIN:
yield path, doc
def _here(got: dict[str, Any], here: refs.Here) -> bool:
"""출처 원본이 이 층(원본 없는 옛 것 = 이 층)."""
return not got.get("원본") or tuple(got["원본"]) == tuple(here)
def forget(folder: str | Path, gone: Callable[[str], bool]) -> list[str]:
"""`gone(본뜬 키)` 인 이 층 SC · SK 엑셀 사본 걷음 → 걷은 문서 키."""
folder, out = Path(folder), []
here = refs.where(folder)
def hit(one: dict[str, Any]) -> bool:
mark = str(one.get("키") or "")
return bool(mark) and _here(one, here) and gone(mark)
for kind in ("precombo", "sangeun"):
for path, doc in _docs(folder, kind):
got = doc["본뜬"]
if not any(hit(x) for x in [got, *(got.get("또") or [])] if isinstance(x, dict)):
continue
new = strip_sk(doc, hit) if kind == "sangeun" or not hit(got) else strip_sc(doc)
if kind == "precombo" and (
also := [x for x in got.get("또") or [] if isinstance(x, dict) and not hit(x)]
):
new["본뜬"]["또"] = also # 777-1 같은 내용 SC 를 나눠 쓴 다른 불러오기 몫은 그대로
if new != doc:
out.append(path.stem)
atomic_write_json(path, new)
return out
def finish(folder: str | Path, key: str) -> dict[str, Any]:
"""불러오기 끝냄 — 만든 문서 사본 걷음 · HP · 격자 지움 → `{지움, 만든}`."""
folder = Path(folder)
hopyo_store.read(folder, key, old=True) # 없으면 404 · 옛 판도 끝냄(776-2)
head = f"{key} "
made = forget(folder, lambda mark: mark.startswith(head))
hopyo_store.delete(folder, key)
return {"지움": key, "만든": len(made)}
def expired(folder: str | Path, now: datetime | None = None) -> list[str]:
"""하루 지난 작업 중 HP 키(`M02_Hopyo_Store.stale`)."""
out = []
for path in sorted((Path(folder) / hopyo_store.DIRNAME).glob("HP-*.json")):
doc = hopyo_store._load(path)
if isinstance(doc, dict) and doc.get("지문") and hopyo_store.stale(doc, now):
out.append(path.stem)
return out
def sweep(folder: str | Path, now: datetime | None = None) -> list[str]:
"""하루 지난 HP 끝냄 → 끝낸 키."""
for key in (got := expired(folder, now)):
finish(folder, key)
return got