From b8315dcd42911ec4d066e102bf483dfce6ed7d06 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 00:07:09 +0900 Subject: [PATCH] =?UTF-8?q?refactor(857-2):=20=EC=9D=BC=EC=9C=84=EB=8C=80?= =?UTF-8?q?=EA=B0=80=20=EB=B6=88=EB=9F=AC=EC=98=A4=EA=B8=B0=EA=B0=80=20?= =?UTF-8?q?=EC=8B=9C=ED=8A=B8=EB=A5=BC=20=EB=8B=A4=EC=8B=9C=20=EA=B0=80?= =?UTF-8?q?=EB=A5=B4=EC=A7=80=20=EC=95=8A=EA=B3=A0=20=EB=91=98=20=EA=BC=B4?= =?UTF-8?q?=20=EC=9C=84=EC=97=90=EC=84=9C=20=EC=9D=BD=EC=9D=8C=20=E2=80=94?= =?UTF-8?q?=20=EA=B0=99=EC=9D=80=20=EC=8B=9C=ED=8A=B8=20=EA=B0=80=EB=A6=84?= =?UTF-8?q?=202=20=E2=86=92=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `M02_Hopyo_Excel.read_book` = 둘 꼴(`two_of` · 올림 길은 한 번 지어 산근 보관과 같이 씀) 위 — EST 「일위대가」 = 둘 꼴 `일위대가` · 단산 = `M02_Hopyo_ReadEst.from_two`(블록 머리 · 머리돈 · 칸글/보임) - STmate = 일위대가표 공용 읽기 답(`일위대가`) · 단산 = `M02_Hopyo_Stmate.from_two`(블록 `칸줄`) · 줄 규칙(`_take`) · 마무리(`_finish`)는 옛 가름과 한 벌 - 몸 · 갈래 · 칠 · 고정 줄 규칙 그대로 — 실무 엑셀 11 호표 읽기 답 통째 같음(호표 · 단산 · 검산) · 산근 못 읽는 엑셀 = 단산 빈 목록(호표는 됨 · 사유는 산근 보관) - 같은 시트 가름(올림 한 번) 단가산출 · 단가산출근거 · 일위대가표 2 → 1 · 옛 가름 본체(`ReadEst.read` · `Stmate._blocks` · `Excel._columns · _summary`)는 857-5 에서 지움 - 시험 고침 2 — `test_828_2` 호표 길 대조가 시트 줄 대신 공용 읽기 답을 넘김(`_hopyos` 입력 꼴) · `test_m02_hopyo_excel` 지은 엑셀 단가산출 시트에 제목 · 빈 줄(산근 읽기는 넷째 줄부터 블록 머리 — 실무 꼴) Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Hopyo_Excel.py | 107 ++++--- M02_MasterTemplete/M02_Hopyo_ReadEst.py | 52 +++- M02_MasterTemplete/M02_Hopyo_Router.py | 5 +- M02_MasterTemplete/M02_Hopyo_Stmate.py | 273 +++++++++++------- M02_MasterTemplete/M02_Sangeun_FromHopyo.py | 9 +- resources/tester/test_828_2_xlsx_ilwi_meta.py | 4 +- resources/tester/test_m02_hopyo_excel.py | 2 + 7 files changed, 278 insertions(+), 174 deletions(-) diff --git a/M02_MasterTemplete/M02_Hopyo_Excel.py b/M02_MasterTemplete/M02_Hopyo_Excel.py index c5ab6ecce..a2a7ba5b0 100644 --- a/M02_MasterTemplete/M02_Hopyo_Excel.py +++ b/M02_MasterTemplete/M02_Hopyo_Excel.py @@ -34,6 +34,7 @@ from M02_MasterTemplete import M02_Hopyo_ReadEst as hopyo_est # EST 단가산 from M02_MasterTemplete import M02_Hopyo_Stmate as hopyo_stmate from M02_MasterTemplete import M02_Hopyo_UnitLine as unit_line from M02_MasterTemplete import M02_San_Workbook as workbook # 책 한 벌(857-1) +from M02_MasterTemplete import M02_San_Xlsx_Ilwi as xilwi # 「일위대가」 시트 읽기(857-2) SHEET = "일위대가" SUMMARY = "일위대가총괄표" @@ -233,69 +234,85 @@ def _by_name(raw: list[list[dict[str, Any]]], blocks: dict[int, dict[str, Any]]) # ── 읽기 ────────────────────────────────────────────────────────────── +def two_of(name: str, book: workbook.Book) -> dict[str, Any] | None: + """한 번 연 책 → 둘 꼴(`M02_San_Xlsx` → `M02_Doc_FromNative.pack` · 857-2) — 산근 시트 없음 · 못 읽음 = None + (단산 빈 목록 · 못 읽은 사유는 산근 보관 `M02_Sangeun_FromHopyo.keep` 이 다시 냄).""" + if not book.kind: + return None + from M02_MasterTemplete import M02_Doc_FromNative as from_native + from M02_MasterTemplete import M02_San_Xlsx as san_xlsx + + try: + return from_native.pack(san_xlsx.read_sheets(book.sheets), name) + except Exception: # noqa: BLE001 — 산근은 덤(호표 읽기는 됨) + return None + + +def _line(one: dict[str, Any], at: int) -> dict[str, Any]: + """「일위대가」 시트 구성 줄(칸 그대로 · `M02_San_Xlsx_Ilwi.est`) → HP 줄(수 = Decimal · 이음 · 갈래).""" + note = one["비고"] + ref = _REF.match(_flat(note)) + line = { + "차례": at, + "이름": one["이름"], + "규격": one["규격"], + "수량": _num(one["수량"]), + "단위": one["단위"], + "단가": {k: _num(v) for k, v in one["단가"].items()}, + "금액": {k: _num(v) for k, v in one["금액"].items()}, + "비고": note, + "참조": {"종류": "단산" if ref.group(1) else "일위", "번": int(ref.group(3))} + if ref + else None, + } + line["갈래"] = kind_of(line) + line["행"] = one["행"] + return line + + def read_book( - name: str, data: bytes, book: workbook.Book | None = None, blocks_only: bool = False + name: str, + data: bytes, + book: workbook.Book | None = None, + blocks_only: bool = False, + two: dict[str, Any] | None = None, ) -> dict[str, Any]: """엑셀 → `{시트, 호표: [...], 검산: {어긋남: [글 …], 총괄표: 맞춘 수}}` — 값은 JSON 수 · `book` = 올림 길이 한 번 연 책(857-1) · `blocks_only`(올림 길) = 단가산출 시트가 있으면 일위대가 - 시트 · 호표 없음도 받음(호표 빈 목록 · 단산만).""" + 시트 · 호표 없음도 받음(호표 빈 목록 · 단산만) · `two` = 같은 책 둘 꼴(857-2 · 없으면 `two_of`) — + 시트를 다시 가르지 않고 둘 꼴의 `일위대가` · 산근 블록 위에서 셈.""" book = book or workbook.read(name, data) + two = two if two is not None else two_of(name, book) sheets, loose = book.sheets, blocks_only and book.kind is not None if book.kind == "STmate": - return unit_line.settle(hopyo_clause.settle(hopyo_stmate.read(sheets, loose))) - rows = sheets.get(SHEET) - if rows is None and not loose: + return unit_line.settle(hopyo_clause.settle(hopyo_stmate.read(sheets, loose, two))) + got = two["일위대가"] if two and "일위대가" in two else xilwi.est(sheets) + if got is None and not loose: raise ExcelError(NO_SHEET) - start, cols = _columns(rows, ("합계", *COSTS)) if rows is not None else (0, {}) + if got and "오류" in got: + raise ExcelError(got["오류"]) hopyos: list[dict[str, Any]] = [] raw: list[list[dict[str, Any]]] = [] - for at, row in enumerate((rows or [])[start:], start + 1): - head = _flat(_cell(row, cols.get("호표"))) - name_ = _text(_cell(row, cols.get("품명"))) - hit = _HOPYO.fullmatch(head) - if hit: - hopyos.append( - { - "번": int(hit.group(1)), - "이름": name_, - "규격": _text(_cell(row, cols.get("규격"))), - "단위": _text(_cell(row, cols.get("단위"))), - "금액": _money(row, cols, 1), - "행": [at, at], - } - ) - raw.append([]) - continue - if head or not name_ or not hopyos: - continue - note = _text(_cell(row, cols.get("비고"))) - ref = _REF.match(_flat(note)) - line = { - "차례": len(raw[-1]), - "이름": name_, - "규격": _text(_cell(row, cols.get("규격"))), - "수량": _num(_cell(row, cols.get("수량"))), - "단위": _text(_cell(row, cols.get("단위"))), - "단가": _money(row, cols, 0), - "금액": _money(row, cols, 1), - "비고": note, - "참조": {"종류": "단산" if ref.group(1) else "일위", "번": int(ref.group(3))} - if ref - else None, - } - line["갈래"] = kind_of(line) - line["행"] = hopyos[-1]["행"][1] = at - raw[-1].append(line) + for one in (got or {}).get("호표") or []: + hopyos.append( + {k: one[k] for k in ("번", "이름", "규격", "단위")} + | {"금액": {k: _num(v) for k, v in one["금액"].items()}, "행": list(one["행"])} + ) + raw.append([_line(x, at) for at, x in enumerate(one["줄"])]) if not hopyos and not loose: raise ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음") - blocks = hopyo_est.read(sheets.get(hopyo_est.SHEET)) + blocks = hopyo_est.from_two((two or {}).get("산근") or []) _by_name(raw, blocks) for line in (one for lines in raw for one in lines): ref = line["참조"] or {} if ref.get("종류") == "단산" and (block := blocks.get(ref["번"])): line["근거"] = {k: block[k] for k in ("출처", "직종", "행")} wrong: list[str] = [] - totals = _summary(sheets.get(SUMMARY)) + totals = { + no: total + for no, cell in (got or {}).get("총괄표") or [] + if (total := _num(cell)) is not None + } for hopyo, lines in zip(hopyos, raw, strict=True): wrong += _check_hopyo(hopyo, lines) total = hopyo["금액"].get("계") diff --git a/M02_MasterTemplete/M02_Hopyo_ReadEst.py b/M02_MasterTemplete/M02_Hopyo_ReadEst.py index b9f2ad842..0c54c00ec 100644 --- a/M02_MasterTemplete/M02_Hopyo_ReadEst.py +++ b/M02_MasterTemplete/M02_Hopyo_ReadEst.py @@ -211,17 +211,25 @@ def read(rows: list[list[Any]] | None) -> dict[int, dict[str, Any]]: }, ) continue - if block is None: - continue - block["행"][1] = at - if len(block["글"]) < GLINES: - block["글"].append(text.rstrip()[:GCHARS]) - block["_글행"].append(at) - block["출처"] += [one for one in sources(text) if one not in block["출처"]] - trade_ = _TRADE.match(text) - name = names.get(_flat(trade_.group(1))) if trade_ else None - if name and name not in block["직종"]: - block["직종"].append(name) + if block is not None: + _take(block, at, text, names) + return _finish(blocks) + + +def _take(block: dict[str, Any], at: int, text: str, names: dict[str, str]) -> None: + """몸 줄 하나 → 블록 끝 행 · 글(`GLINES` 줄 · 줄마다 `GCHARS` 자) · 출처 · 직종.""" + block["행"][1] = at + if len(block["글"]) < GLINES: + block["글"].append(text.rstrip()[:GCHARS]) + block["_글행"].append(at) + block["출처"] += [one for one in sources(text) if one not in block["출처"]] + trade_ = _TRADE.match(text) + name = names.get(_flat(trade_.group(1))) if trade_ else None + if name and name not in block["직종"]: + block["직종"].append(name) + + +def _finish(blocks: dict[int, dict[str, Any]]) -> dict[int, dict[str, Any]]: for block in blocks.values(): block["글행"] = block.pop("_글행") block["항목"] = items(block["글"], block["글행"]) @@ -229,6 +237,28 @@ def read(rows: list[list[Any]] | None) -> dict[int, dict[str, Any]]: return blocks +def from_two(blocks: list[dict[str, Any]]) -> dict[int, dict[str, Any]]: + """둘 꼴 EST 산근 블록(`M02_Doc_FromNative.pack` · 857-2) → `read` 와 같은 블록 — 시트를 다시 가르지 않음 · + 머리 = 블록 `머리` 글 · 금액 = `머리돈` · 글 = 줄 `칸글`(글자 칸 나눔 꼴) 아니면 `보임` · 빈 글 줄 뺌.""" + names = trade_names() + out: dict[int, dict[str, Any]] = {} + for b in blocks: + head = _HEAD.match(str(b.get("머리") or "")) + if not head: + continue + no, at = int(head.group(1)), b["엑셀행"] + block = out.setdefault( + no, + {"번": no, "이름": head.group(2), "단위": head.group(3).strip(), "행": [at, at]} + | {"출처": [], "직종": [], "글": [], "금액": dict(b.get("머리돈") or {}), "_글행": []}, + ) + for ln in b.get("줄") or []: + text = str(ln.get("칸글") or ln.get("보임") or "") + if text.strip(): + _take(block, ln["행"], text, names) + return _finish(out) + + # ── 글 → 단위 줄 ─────────────────────────────────────────────────────── def _ratio(rhs: str) -> float | None: """식을 못 풀 때만 — 금액 ÷ 단가(품 되찾기용).""" diff --git a/M02_MasterTemplete/M02_Hopyo_Router.py b/M02_MasterTemplete/M02_Hopyo_Router.py index c345c0cd1..d715e90d9 100644 --- a/M02_MasterTemplete/M02_Hopyo_Router.py +++ b/M02_MasterTemplete/M02_Hopyo_Router.py @@ -82,7 +82,8 @@ def _upload(name: str, data: bytes, who: dict[str, Any]) -> dict[str, Any]: return {**same, "이어서": True, **({"읽기불가": cannot} if cannot else {})} try: # 책 한 번(857-1) · 단가산출만 있는 엑셀(일위대가 시트 없음)도 받음 = 호표 빈 목록 book = workbook.read(name, data) - parsed = hopyo_excel.read_book(name, data, book, blocks_only=True) + two = hopyo_excel.two_of(name, book) # 둘 꼴 한 번(857-2) — 호표 읽기 · 산근 보관이 같이 씀 + parsed = hopyo_excel.read_book(name, data, book, blocks_only=True, two=two) except hopyo_excel.ExcelError as error: raise store.StoreError(400, str(error)) from error try: @@ -90,7 +91,7 @@ def _upload(name: str, data: bytes, who: dict[str, Any]) -> dict[str, Any]: except Exception: # 격자는 보기용 덤 — 못 만들어도 올리기는 됨(보기 창 404) grid = None # 산근 시트(793-3b 가져온 식 열기) = HP 를 목록에 보이기 전에 보관(814-1) · 못 씀 사유 → 화면 토스트(797-1) - keep = lambda key: from_hopyo.keep(store.root(), key, name, data, book) # noqa: E731 + keep = lambda key: from_hopyo.keep(store.root(), key, name, data, book, two) # noqa: E731 return hopyo_store.save(store.root(), name, parsed, who, grid, mark, keep) diff --git a/M02_MasterTemplete/M02_Hopyo_Stmate.py b/M02_MasterTemplete/M02_Hopyo_Stmate.py index 46487ec69..fd898ff23 100644 --- a/M02_MasterTemplete/M02_Hopyo_Stmate.py +++ b/M02_MasterTemplete/M02_Hopyo_Stmate.py @@ -62,6 +62,7 @@ _LOSS = re.compile(r"\*\s*([\d.]+)\s*'%'") # 자재 손료율 「* 0.443'%'」 _BASE_WORD = re.compile(r"([가-힣]+)의\s*[\d.]+\s*%") # 율 기준글 「(인건비의 3%)」 _NUMBERED = re.compile(r"^\s*(?:\d+|[가-하])\s*[.)]\s*") _TAG = re.compile(r"&([A-Z][A-Z0-9_]*?)(?::[A-Z])?&") # 율 기준 표지 「&PA01M:M&」 → PA01M +_D_CODE = re.compile(r"D\d{5}") # 단가산출근거 블록 코드(857-2 둘 꼴) def is_stmate(names: Any) -> bool: @@ -186,104 +187,97 @@ def _rate_row(row: list[Any], code: str, text: str, label: str) -> dict[str, Any } -def _blocks(rows: list[list[Any]], table: dict[str, dict[str, str]]) -> dict[str, dict[str, Any]]: - """{D 코드: {번, 코드, 이름, 규격, 단위, 행, 출처, 직종, 글, 자원, 금액, 항목}}.""" - names = hopyo_est.trade_names() - out: dict[str, dict[str, Any]] = {} - block: dict[str, Any] | None = None - title = label = "" # 절 제목 · 율 행 위 라벨 줄(코드 · 금액 없는 글) - for at, row in enumerate(rows, 1): - head = next( - (hit for v in row[:8] if (hit := _HEAD_D.search(_s(v)))), None - ) # 머리 = G 열(판마다 B 열 글이 다름) - if head: - code = head.group(1) - info = table.get(code) or {} - block = out.setdefault( - code, - { - "번": int(code[1:]), - "코드": code, - "이름": info.get("이름", ""), - "규격": info.get("규격", ""), - "단위": info.get("단위", ""), - "행": [at, at], - "글": [], - "금액": _calc_money(row, _CALC_AMOUNT), - "항목": [], - }, - ) - title = label = "" - continue - if block is None: - continue - first = _flat(_cell(row, 0)) - if first.startswith("총계"): - block["행"][1] = at - block = None - continue - text, cell = _s(_cell(row, 1)), _s(_cell(row, RES_COL)) - res = _RES.match(cell) - code = res.group(1) + res.group(2) if res else None - if not code: - alt = _RES_A.match(first) or _RES_G.search(_s(_cell(row, FORMULA_COL))) - code = alt.group(1) if alt else None - rate = None if code else _RATE.match(cell) - sub = None if code or rate else _SUB_D.match(cell) - if not text and not code: - continue +def _new(code: str, at: int, row: list[Any], table: dict[str, dict[str, str]]) -> dict[str, Any]: + info = table.get(code) or {} + return { + "번": int(code[1:]), + "코드": code, + "이름": info.get("이름", ""), + "규격": info.get("규격", ""), + "단위": info.get("단위", ""), + "행": [at, at], + "글": [], + "금액": _calc_money(row, _CALC_AMOUNT), + "항목": [], + } + + +def _take( + block: dict[str, Any], at: int, row: list[Any], table: dict, state: dict[str, str] +) -> bool: + """몸 줄 하나 → 글 · 항목(`state` = 절 제목 · 율 행 위 라벨 줄) · 거짓 = 「총계」(블록 끝).""" + first = _flat(_cell(row, 0)) + if first.startswith("총계"): block["행"][1] = at - if cell == block["코드"]: # 머리 이름 줄 「이름 규격 / 단위」 - if not block["이름"]: - name, _, unit = text.rpartition("/") - block["이름"], block["단위"] = name.strip() or text, unit.strip() - continue - if text and _flat(text) not in ("소계", "계"): - if len(block["글"]) < hopyo_est.GLINES: - block["글"].append(text[: hopyo_est.GCHARS]) - if (sec := _SECTION.match(text)) and not re.match(r"^\s*\d+\.\d", text): - title = sec.group(1).strip() - money = _calc_money(row, _CALC_AMOUNT) - place = { - "단가": _calc_money(row, _CALC_PRICE), - "금액": money.get("계"), - "행": at, - "절": title, - "윗절": title, - **({"밖": True} if _s(_cell(row, OUT_COL)).startswith("C") else {}), - } - if rate: - block["항목"].append({**_rate_row(row, cell, text, label), **place, "어떻게": "율"}) - continue - if code or sub or money.get("계") is not None: - label = "" # 라벨은 바로 위 글 줄만 - elif text: - label = text.strip() - if sub and sub.group(1) != block["코드"] and money.get("계"): - qty = hopyo_excel._num(_cell(row, QTY_COL)) - one = {"묶음": "S", "코드": sub.group(1), "이름": text[:40], "규격": ""} - more = {"품": float(qty) if qty is not None else None, "어떻게": "QTY"} - block["항목"].append( - {**one, **more, **place, "하위": {"종류": "단산", "번": int(sub.group(1)[1:])}} - ) - continue - if not code: - continue - last, part = block["항목"][-1] if block["항목"] else None, _part(row) - if code[0] == "X" and _same_machine(last, code, title, part): - _add(last["단가"], place["단가"]) # 기계 노무비 · 재료비 · 경비 셋 줄 = 하나 - last["금액"] = hopyo_excel._out( - hopyo_excel._num(last["금액"] or 0) + hopyo_excel._num(place["금액"] or 0) - ) - last["_q"][part] = hopyo_excel._num(_cell(row, QTY_COL)) - continue - one = _unit(row, code, title, table.get(code) or {}) - who = hopyo_est.trade(one["이름"]) if one["묶음"] == "L" else None - one = {**one, **({"직종": who} if one["묶음"] == "L" else {}), "밑품": one["품"]} - one.update(율=[], 인자=[], 어떻게="율" if one["묶음"] == "R" else "QTY", **place) - if one["묶음"] == "X": - one["_q"] = {part: hopyo_excel._num(_cell(row, QTY_COL))} if part else {} - block["항목"].append(one) + return False + text, cell = _s(_cell(row, 1)), _s(_cell(row, RES_COL)) + res = _RES.match(cell) + code = res.group(1) + res.group(2) if res else None + if not code: + alt = _RES_A.match(first) or _RES_G.search(_s(_cell(row, FORMULA_COL))) + code = alt.group(1) if alt else None + rate = None if code else _RATE.match(cell) + sub = None if code or rate else _SUB_D.match(cell) + if not text and not code: + return True + block["행"][1] = at + if cell == block["코드"]: # 머리 이름 줄 「이름 규격 / 단위」 + if not block["이름"]: + name, _, unit = text.rpartition("/") + block["이름"], block["단위"] = name.strip() or text, unit.strip() + return True + if text and _flat(text) not in ("소계", "계"): + if len(block["글"]) < hopyo_est.GLINES: + block["글"].append(text[: hopyo_est.GCHARS]) + if (sec := _SECTION.match(text)) and not re.match(r"^\s*\d+\.\d", text): + state["절"] = sec.group(1).strip() + title = state["절"] + money = _calc_money(row, _CALC_AMOUNT) + place = { + "단가": _calc_money(row, _CALC_PRICE), + "금액": money.get("계"), + "행": at, + "절": title, + "윗절": title, + **({"밖": True} if _s(_cell(row, OUT_COL)).startswith("C") else {}), + } + if rate: + block["항목"].append({**_rate_row(row, cell, text, state["라벨"]), **place, "어떻게": "율"}) + return True + if code or sub or money.get("계") is not None: + state["라벨"] = "" # 라벨은 바로 위 글 줄만 + elif text: + state["라벨"] = text.strip() + if sub and sub.group(1) != block["코드"] and money.get("계"): + qty = hopyo_excel._num(_cell(row, QTY_COL)) + one = {"묶음": "S", "코드": sub.group(1), "이름": text[:40], "규격": ""} + more = {"품": float(qty) if qty is not None else None, "어떻게": "QTY"} + block["항목"].append( + {**one, **more, **place, "하위": {"종류": "단산", "번": int(sub.group(1)[1:])}} + ) + return True + if not code: + return True + last, part = block["항목"][-1] if block["항목"] else None, _part(row) + if code[0] == "X" and _same_machine(last, code, title, part): + _add(last["단가"], place["단가"]) # 기계 노무비 · 재료비 · 경비 셋 줄 = 하나 + last["금액"] = hopyo_excel._out( + hopyo_excel._num(last["금액"] or 0) + hopyo_excel._num(place["금액"] or 0) + ) + last["_q"][part] = hopyo_excel._num(_cell(row, QTY_COL)) + return True + one = _unit(row, code, title, table.get(code) or {}) + who = hopyo_est.trade(one["이름"]) if one["묶음"] == "L" else None + one = {**one, **({"직종": who} if one["묶음"] == "L" else {}), "밑품": one["품"]} + one.update(율=[], 인자=[], 어떻게="율" if one["묶음"] == "R" else "QTY", **place) + if one["묶음"] == "X": + one["_q"] = {part: hopyo_excel._num(_cell(row, QTY_COL))} if part else {} + block["항목"].append(one) + return True + + +def _finish(out: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: + names = hopyo_est.trade_names() for block in out.values(): for one in block["항목"]: if "_q" in one: @@ -299,18 +293,70 @@ def _blocks(rows: list[list[Any]], table: dict[str, dict[str, str]]) -> dict[str return out +def _blocks(rows: list[list[Any]], table: dict[str, dict[str, str]]) -> dict[str, dict[str, Any]]: + """{D 코드: {번, 코드, 이름, 규격, 단위, 행, 출처, 직종, 글, 자원, 금액, 항목}}.""" + out: dict[str, dict[str, Any]] = {} + block: dict[str, Any] | None = None + state = {"절": "", "라벨": ""} # 절 제목 · 율 행 위 라벨 줄(코드 · 금액 없는 글) + for at, row in enumerate(rows, 1): + head = next( + (hit for v in row[:8] if (hit := _HEAD_D.search(_s(v)))), None + ) # 머리 = G 열(판마다 B 열 글이 다름) + if head: + block = out.setdefault(head.group(1), _new(head.group(1), at, row, table)) + state = {"절": "", "라벨": ""} + continue + if block is not None and not _take(block, at, row, table, state): + block = None + return _finish(out) + + +def from_two(blocks: list[dict[str, Any]], table: dict[str, dict[str, str]]) -> dict[str, Any]: + """둘 꼴 STmate 산근 블록 `칸줄`(머리 ~ 다음 머리 앞 칸 · `M02_San_Xlsx_Stmate.cells` · 857-2) → + `_blocks` 와 같은 블록 — 시트를 다시 가르지 않음 · D 코드 블록만.""" + out: dict[str, dict[str, Any]] = {} + for b in blocks: + code = str(b.get("코드") or "") + rows = [(c["행"], _row_of(c)) for c in b.get("칸줄") or []] + if not rows or not _D_CODE.fullmatch(code): + continue + (at, head), *body = rows + block = out.setdefault(code, _new(code, at, head, table)) + state = {"절": "", "라벨": ""} + for at, row in body: + if not _take(block, at, row, table, state): + break + return _finish(out) + + +def _row_of(cells: dict[str, Any]) -> list[Any]: + """`칸줄` 한 줄 {행, A .. X} → 시트 줄 꼴(열 = 글자 차례).""" + row: list[Any] = [None] * (NAME_COL + 1) + for k, v in cells.items(): + if k != "행": + row[ord(k) - 65] = v + return row + + # ── 일위대가표 ──────────────────────────────────────────────────────── -def _hopyos(rows: list[list[Any]]) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]: - """호표 · 구성 줄 = 공용 읽기(`M02_San_Xlsx_Ilwi.read` · 828-2) → HP 줄 꼴 · 설명 줄 = 근거글 · - 닫기 · 구분 줄 뺌 · 율 줄 코드 = PR + 율 코드(「PRA01」) · 숨은 칸 율 = `율` {밑, 대상}(비목 이름).""" +def _cost(money: dict[str, Any] | None) -> dict[str, Any]: + """공용 읽기 비목 {T L M S}(수) → HP 비목 {계 노무비 재료비 경비}(Decimal).""" + money = money or {} + return {k: hopyo_excel._num(money.get(c)) for k, c in zip(("계", *COSTS), "TLMS")} + + +def _hopyos(sheet: dict[str, Any]) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]: + """호표 · 구성 줄 = 공용 읽기 답(`M02_San_Xlsx_Ilwi.read` · 828-2 · 둘 꼴 `일위대가` · 857-2) → HP 줄 꼴 · + 설명 줄 = 근거글 · 닫기 · 구분 줄 뺌 · 율 줄 코드 = PR + 율 코드(「PRA01」) · 숨은 칸 율 = `율` {밑, 대상} + (비목 이름).""" hopyos: list[dict[str, Any]] = [] raw: list[list[dict[str, Any]]] = [] - for got in ilwi.read(rows)["호표"]: + for got in sheet["호표"]: hopyo = {k: got[k] for k in ("번", "코드", "행")} | {"근거글": []} if "머리행" in got: hopyo |= {k: got[k] for k in ("이름", "규격", "단위")} | {"금액": {}} if "끝행" in got: - hopyo["금액"] = hopyo_excel._money(rows[got["끝행"] - 1], _COLS, 1) + hopyo["금액"] = _cost(got.get("저장")) hopyos.append(hopyo) raw.append([]) for one in got["줄"]: @@ -320,21 +366,21 @@ def _hopyos(rows: list[list[Any]]) -> tuple[list[dict[str, Any]], list[list[dict continue if one["갈래"] in ("닫기", "구분"): continue # 계 · 소계 · 계약단가 - raw[-1].append(_hopyo_line(rows[one["행"] - 1], one, len(raw[-1]))) + raw[-1].append(_hopyo_line(one, len(raw[-1]))) return hopyos, raw -def _hopyo_line(row: list[Any], one: dict[str, Any], at: int) -> dict[str, Any]: +def _hopyo_line(one: dict[str, Any], at: int) -> dict[str, Any]: rate = one.get("율") or {} code = one["코드"] + rate.get("코드", "") if rate else one["코드"] line = { "차례": at, "이름": one["이름"], "규격": one["규격"], - "수량": hopyo_excel._num(_cell(row, 2)), + "수량": hopyo_excel._num(one.get("수량")), "단위": one["단위"], - "단가": hopyo_excel._money(row, _COLS, 0), - "금액": hopyo_excel._money(row, _COLS, 1), + "단가": _cost(one.get("단가")), + "금액": _cost(one.get("금액")), "비고": one["비고"], "코드": code, "행": one["행"], @@ -354,14 +400,19 @@ def _hopyo_line(row: list[Any], one: dict[str, Any], at: int) -> dict[str, Any]: return line -def read(sheets: dict[str, list[list[Any]]], loose: bool = False) -> dict[str, Any]: +def read( + sheets: dict[str, list[list[Any]]], loose: bool = False, two: dict[str, Any] | None = None +) -> dict[str, Any]: """STmate 시트 → HP 꼴 `{꼴, 시트, 호표, 단산, 검산}`(값은 JSON 수) · - `loose` = 호표 없음도 받음(857-1).""" - hopyos, raw = _hopyos(sheets.get(SHEET) or []) + `loose` = 호표 없음도 받음(857-1) · `two` = 같은 책 둘 꼴(857-2 — 일위대가표 = `일위대가` · + 단가산출근거 = 산근 블록 `칸줄` · 없으면(산근 못 읽음) 일위대가표만 공용 읽기 · 단산 빈 것) · + 목록표(이름 · 규격 · 단위)는 시트에서.""" + sheet = (two or {}).get("일위대가") or ilwi.read(sheets.get(SHEET) or []) + hopyos, raw = _hopyos(sheet) if not hopyos and not loose: raise hopyo_excel.ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음") table = _lists(sheets) - blocks = _blocks(sheets.get(CALC) or [], table) + blocks = from_two((two or {}).get("산근") or [], table) by_code = {h["코드"]: h["번"] for h in hopyos if h["코드"]} for line in (one for lines in raw for one in lines): ref = line["참조"] or {} diff --git a/M02_MasterTemplete/M02_Sangeun_FromHopyo.py b/M02_MasterTemplete/M02_Sangeun_FromHopyo.py index d7577fccc..e208f48df 100644 --- a/M02_MasterTemplete/M02_Sangeun_FromHopyo.py +++ b/M02_MasterTemplete/M02_Sangeun_FromHopyo.py @@ -47,9 +47,12 @@ def unreadable(data: bytes) -> str | None: return None -def keep(folder: str | Path, key: str, name: str, data: bytes, opened: Any = None) -> str | None: +def keep( + folder: str | Path, key: str, name: str, data: bytes, opened: Any = None, excel: Any = None +) -> str | None: """올린 엑셀 → 산근 시트 둠(STmate · EST 꼴만 · 못 읽으면 안 둠 — 올리기는 됨). - 돌려줌 = 못 읽은 사유(빈 파일 · DRM 암호 · 형식 오류) · 둠 · 산근 꼴 아님 = None.""" + 돌려줌 = 못 읽은 사유(빈 파일 · DRM 암호 · 형식 오류) · 둠 · 산근 꼴 아님 = None · + `excel` = 올림 길이 지은 둘 꼴(857-2 · 없으면 여기서 지음).""" from M02_MasterTemplete import M02_San_Book as book if why := unreadable(data): @@ -61,7 +64,7 @@ def keep(folder: str | Path, key: str, name: str, data: bytes, opened: Any = Non if not book.kind_of(sheets): return None try: - excel = _excel(name, sheets) + excel = excel or _excel(name, sheets) except Exception as e: # noqa: BLE001 — 산근 읽기 실패 = 사유(올리기는 됨) return f"산근 시트 읽기 오류 — {type(e).__name__}: {str(e)[:80]}" path = _path(folder, key) diff --git a/resources/tester/test_828_2_xlsx_ilwi_meta.py b/resources/tester/test_828_2_xlsx_ilwi_meta.py index eef8dad3a..7624072ca 100644 --- a/resources/tester/test_828_2_xlsx_ilwi_meta.py +++ b/resources/tester/test_828_2_xlsx_ilwi_meta.py @@ -91,8 +91,8 @@ def test_bare_sheet_falls_back(): # 호표 길 = 옛 코드 찾기(O 열) — 숨은 칸 율 · 호표 코드만 빠지고 줄은 같음 from M02_MasterTemplete import M02_Hopyo_Stmate as st - a = st._hopyos(_sheets("봉화")[il.SHEET]) - b = st._hopyos(rows) + a = st._hopyos(il.read(_sheets("봉화")[il.SHEET])) # 857-2 공용 읽기 답을 받음 + b = st._hopyos(got) strip = [[{k: v for k, v in x.items() if k != "율"} for x in h] for h in a[1]] heads = [[{k: v for k, v in h.items() if k != "코드"} for h in x[0]] for x in (a, b)] assert heads[0] == heads[1] and strip == b[1] # 호표 코드(BDCOD)도 숨은 칸이라 빠짐 diff --git a/resources/tester/test_m02_hopyo_excel.py b/resources/tester/test_m02_hopyo_excel.py index 258d24fa9..0e116a296 100644 --- a/resources/tester/test_m02_hopyo_excel.py +++ b/resources/tester/test_m02_hopyo_excel.py @@ -241,6 +241,8 @@ def _linked_xlsx() -> bytes: ws.append([None, None, "보통인부", "", 1, "인", 100, 100, 100, 100, None]) ws.append([None, None, "호표 줄", "", 1, "개소", 100, 100, 100, 100, "대가1"]) calc = book.create_sheet("단가산출") + calc.append([None, "단 가 산 출 서"]) # 실무 꼴 — 제목 · 빈 줄 뒤 머리(블록은 넷째 줄부터 · 857-2) + calc.append([]) calc.append([None, "산출근거", "합계", "노무비"]) calc.append([None, "2.터파기[㎥]"]) calc.append([None, " [건설공사표준품셈 3-2-1]"])