"""857-0 지킴 도우미 — 불러오기 지문(블록 × 두 판 · 검산 · 이음 / 엑셀 올림 · 호표 목록 · 칠 · 고정 줄 / 재료 이음 표). - 블록 = 견본(원파일 EST · STC · 실무 엑셀)마다 `Doc_FromNative.emit` → 가져온 식 SK(`new_doc` · 저장 없음) → 엑셀 판 · 우리 판 문서 셈(`Doc_Import.derive` + `run`) 노 · 재 · 경 · 계 + 검산(`Sangeun_Imported.check` 같음 · 줄 같음 수) + 줄마다 이음(종류 · 이음 · 기계 찾기 · 재료 찾기 판정 · 키). - 올림 = 엑셀을 임시 개인 층에 올림(`Hopyo_Router._upload`) → 거절 글 | 목록(`Hopyo_View.listing`) · 칠(`Hopyo_Marks.blocks`) · 고정 줄(`Hopyo_Fixed.line_of` 이름 · 규격 · 단위 · 단가 · 이음 · 비율). - 재료 이음 표 = 일위대가 호표 자재 · 별도계상 줄 — 호표 길 키(`line_of`) · 단가산출 길 키(`San_Link.m01`). - 지문 = 갈래 열쇠(「블록 EST:거창#3」 등)마다 sha256 앞 16 자 · 견본 내용은 안 남김. - M01 한 벌 쥠(셈 동안 M01 파일이 안 바뀜 — 빠르게만 · 답 같음). """ from __future__ import annotations import contextlib import hashlib import json import sys import tempfile import warnings from pathlib import Path from typing import Any HERE = Path(__file__).resolve().parent ROOT = HERE.parents[1] for p in (str(ROOT), str(HERE)): if p not in sys.path: sys.path.insert(0, p) warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl") KEYS = ("노무비", "재료비", "경비", "계") #: 기본(빠른) 표본 — 견본마다 블록 몇 개 · 올림 파일 몇 개(전수 = `S857_ALL=1`) QUICK_BLOCKS = { "EST:거창": 8, "STC:봉화": 8, "엑셀:북부청임도": 8, "엑셀:봉화": 8, "엑셀:2026수목": 8, } QUICK_UPLOAD = ("북부청임도", "봉화", "2026수목") def sources() -> dict[str, Path]: """「갈래:이름」 → 견본 경로(없는 PC = 경로가 없음).""" import test_797_1a_import_flags as practice from test_810_1_estx import FILES as EST from test_810_1_stc import FILES as STC out = {f"EST:{k}": v for k, v in EST.items()} out |= {f"STC:{k}": v for k, v in STC.items()} return out | {f"엑셀:{k}": v for k, v in practice.FILES.items()} def digest(value: Any) -> str: raw = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str) return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] @contextlib.contextmanager def hold_m01(): """M01 한 벌을 셈 동안 쥠(줄마다 파일 날짜 다시 재기 뺌).""" from M01_MasterData import M01_MasterData_Store as m01 real, memo = m01.loaded, [] def once(): if not memo: memo.append(real()) return memo[0] m01.loaded = once try: yield finally: m01.loaded = real @contextlib.contextmanager def personal(): """임시 storage 개인 층(원본 storage · 마스터 안 씀).""" from config import config_system old = config_system.STORAGE_BASE_DIR tmp = Path(tempfile.mkdtemp(prefix="t857_")) config_system.STORAGE_BASE_DIR = str(tmp / "storage") (tmp / "storage").mkdir() from M02_MasterTemplete import M02_MasterTemplete_Store as store from M02_MasterTemplete import M02_Template_Layers as layers folder = layers.personal_dir(7, 42) folder.mkdir(parents=True, exist_ok=True) try: with store.at(folder): yield folder finally: config_system.STORAGE_BASE_DIR = old # ── 블록 ────────────────────────────────────────────────────────────── def saved_of(tag: str, path: Path) -> dict: from M02_MasterTemplete import M02_Doc_FromNative as fn from M02_MasterTemplete import M02_San_Xlsx as sx raw = path.read_bytes() if tag.startswith("엑셀:"): return fn.pack(sx.read(path.name, raw), path.name) return fn.read(path.name, raw) def _money(got: dict) -> Any: return {k: str(got.get(k)) for k in KEYS} if got.get("셈됨") else "못 셈" def _links(row: dict) -> list: out = [] for it in row.get("호표") or []: res = it.get("자원") or {} find, mat = res.get("찾기") or {}, res.get("재료찾기") or {} out.append( [ it.get("종류"), it.get("이음"), find.get("판정"), find.get("키"), mat.get("판정"), mat.get("키"), ] ) return out def block(saved: dict, no: int) -> dict: """블록 하나 → 지문 몸 {엑셀, 우리, 검산, 이음}.""" from M02_MasterTemplete import M02_Doc_FromNative as fn from M02_MasterTemplete import M02_Doc_Import as dim from M02_MasterTemplete import M02_Sangeun_Doc as sd from M02_MasterTemplete import M02_Sangeun_Imported as imp whole = imp._whole() out = fn.emit(saved, no) row = out["로직"] sk = { **imp.new_doc(row, out["원본"], row["이름"]), "키": "SK-999999", } # 857-3b 불러온 그대로 문서 sk = sd.clean(sk, None, whole) got: dict[str, Any] = {"이음": _links(row)} for basis in ("엑셀", "우리"): one = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": basis}} try: got[basis] = _money(dim.run(dim.derive(one, None, whole), one, whole)) except Exception as e: # noqa: BLE001 — 예외도 지문 got[basis] = f"예외 {type(e).__name__}" try: c = imp.check(sk, whole) got["검산"] = [c["같음"], sum(1 for x in c["줄"] if x.get("같음")), len(c["줄"])] except Exception as e: # noqa: BLE001 got["검산"] = f"예외 {type(e).__name__}" return got def blocks(full: bool) -> tuple[dict[str, str], int]: """{「블록 갈래:이름#번」: 지문} · 건너뛴 견본 수.""" from M02_MasterTemplete import M02_Doc_FromNative as fn out, skipped = {}, 0 with hold_m01(), personal(): for tag, path in sources().items(): if not full and tag not in QUICK_BLOCKS: continue if not path or not path.exists(): skipped += 1 continue saved = saved_of(tag, path) nos = sorted(fn.numbers(saved)) if not full: step = max(1, len(nos) // QUICK_BLOCKS[tag]) nos = nos[::step][: QUICK_BLOCKS[tag]] for no in nos: out[f"블록 {tag}#{no}"] = digest(block(saved, no)) return out, skipped # ── 엑셀 올림 · 호표 쪽 ───────────────────────────────────────────────── def _fixed(book: dict) -> list: from M02_MasterTemplete import M02_Hopyo_Fixed as hf linker, out = hf.Linker(True), [] for h in book.get("호표") or []: for ln in h.get("줄") or []: fx = hf.line_of(ln, h["줄"], {}, set(), linker)["고정"] out.append( [ h["번"], ln.get("차례"), {k: fx.get(k) for k in ("이름", "규격", "단위", "단가", "이음", "비율")}, ] ) return out def mats(book: dict, clues: list) -> list: """재료 이음 표 [호표, 차례, 갈래, 호표 길 키, 단가산출 길 키, 산근 판정 · 방법].""" from M02_MasterTemplete import M02_Hopyo_Fixed as hf from M02_MasterTemplete import M02_Hopyo_Match as hm from M02_MasterTemplete import M02_San_Link as sl from M02_MasterTemplete import M02_San_MatFind as smf linker, out = hf.Linker(True), [] for h in book.get("호표") or []: for ln in h.get("줄") or []: if hf.kind_of(ln) not in hm.MATERIAL_KINDS: continue a = (hf.line_of(ln, h["줄"], {}, set(), linker)["고정"]["이음"] or {}).get("자재") src = {k: ln.get(k) or "" for k in ("이름", "규격", "단위")} src |= {"종류": "자재", "코드": ln.get("코드") or ""} with smf.clues_on(clues): b, _ = sl.m01("재료", src, "") found = src.get("재료찾기") or {} out.append( [ h["번"], ln.get("차례"), ln.get("갈래"), a, b, found.get("판정"), found.get("방법"), ] ) return out def upload(tag: str, path: Path) -> dict[str, Any]: """엑셀 하나 올림(임시 층) → {올림, 목록, 칠, 고정, 재료} 지문 몸.""" from M02_MasterTemplete import M02_Doc_FromNative as fn from M02_MasterTemplete import M02_Hopyo_Marks as marks from M02_MasterTemplete import M02_Hopyo_Router as router from M02_MasterTemplete import M02_Hopyo_Store as hstore from M02_MasterTemplete import M02_Hopyo_View as view from M02_MasterTemplete import M02_MasterTemplete_Store as store from M02_MasterTemplete import M02_San_Book as sb from M02_MasterTemplete import M02_San_Xlsx as sx data = path.read_bytes() try: row = router._upload(path.name, data, {"id": 42, "이름": "시험"}) except store.StoreError as e: return {"올림": f"거절 {e.status} {e}"} folder, key = store.root(), row["키"] book = hstore.read(folder, key) listing = view.listing(folder, key, folder) sheets = sb.sheets(path.name, data) clues = (fn.pack(sx.read_sheets(sheets), path.name) if sb.kind_of(sheets) else {}).get("단서") return { "올림": {k: row.get(k) for k in ("시트", "호표수", "읽기불가")}, "목록": {k: listing.get(k) for k in ("호표", "단산", "검산")}, "칠": marks.blocks(folder, key), "고정": _fixed(book), "재료": mats(book, clues or []), } def uploads(full: bool) -> tuple[dict[str, str], dict[str, list], int]: """({「올림 이름 갈래」: 지문}, {이름: 재료 이음 표}, 건너뛴 수).""" out, table, skipped = {}, {}, 0 with hold_m01(), personal(): for tag, path in sources().items(): name = tag.split(":", 1)[1] if not tag.startswith("엑셀:") or (not full and name not in QUICK_UPLOAD): continue if not path or not path.exists(): skipped += 1 continue got = upload(tag, path) for part, body in got.items(): out[f"올림 {name} {part}"] = digest(body) table[name] = got.get("재료") or [] return out, table, skipped def mat_counts(table: dict[str, list]) -> dict[str, dict[str, int]]: """재료 이음 전후 표(`m857_mat` 꼴) — 같음(이음) · 같음(못 이음) · 생김 · 풂 · 다른 품목.""" out = {} for name, rows in table.items(): c: dict[str, int] = {} for r in rows: a, b = r[3], r[4] if a == b: k = "같음(이음)" if a else "같음(못 이음)" else: k = "풀림" if a and not b else "생김" if b and not a else "다른 품목" c[k] = c.get(k, 0) + 1 out[name] = c return out