From 8e21ea40375e3ba4a1729aa2b4295c0cbccd7baa Mon Sep 17 00:00:00 2001 From: umsangdon Date: Tue, 17 Nov 2026 23:32:59 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat(857-2):=20=EB=91=98=20=EA=BC=B4?= =?UTF-8?q?=EC=97=90=20=EC=9D=BC=EC=9C=84=EB=8C=80=EA=B0=80=20=EB=B6=88?= =?UTF-8?q?=EB=9F=AC=EC=98=A4=EA=B8=B0=20=EB=AA=AB=20=EC=B9=B8=20=EB=8D=94?= =?UTF-8?q?=ED=95=A8=20=E2=80=94=20EST=20=EC=9D=BC=EC=9C=84=EB=8C=80?= =?UTF-8?q?=EA=B0=80=20=EC=8B=9C=ED=8A=B8=20=C2=B7=20=EB=B8=94=EB=A1=9D=20?= =?UTF-8?q?=EB=A8=B8=EB=A6=AC=20=C2=B7=20=EC=B9=B8=20=EB=82=98=EB=88=94=20?= =?UTF-8?q?=EA=B8=80=20=C2=B7=20STmate=20=EC=B9=B8=EC=A4=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - EST 「일위대가」 · 「일위대가총괄표」 시트 읽기 = `M02_San_Xlsx_Ilwi.est`(칸 그대로 · 갈래 · 검산은 호표 쪽) → 둘 꼴 `일위대가` - EST 산근 블록 `머리`(머리 글) · `머리돈`(머리 줄 수 칸) · 줄 `칸글`(글자 칸 나눔 꼴을 칸마다 빈칸 하나로) · pack 이 `엑셀행` 도 실음 - STmate 산근 블록 `칸줄`(머리 ~ 다음 머리 앞 값 든 칸 A~N · X) · `줄합` 실음 · 둘 꼴 `일위대가` = 일위대가표 공용 읽기 답 통째(숨은 칸 없어도) - 있던 칸의 이름 · 뜻 그대로 — 실무 엑셀 11 둘 꼴 옛 칸 전부 같음 · 호표 읽기 그대로(아직 안 읽음 · 다음 커밋) Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Doc_FromNative.py | 10 ++- M02_MasterTemplete/M02_San_Xlsx_Est.py | 23 +++++- M02_MasterTemplete/M02_San_Xlsx_Ilwi.py | 94 +++++++++++++++++++++++ M02_MasterTemplete/M02_San_Xlsx_Stmate.py | 29 ++++++- 4 files changed, 148 insertions(+), 8 deletions(-) diff --git a/M02_MasterTemplete/M02_Doc_FromNative.py b/M02_MasterTemplete/M02_Doc_FromNative.py index 01deeb61b..648d53b51 100644 --- a/M02_MasterTemplete/M02_Doc_FromNative.py +++ b/M02_MasterTemplete/M02_Doc_FromNative.py @@ -22,7 +22,7 @@ from M02_MasterTemplete import M02_San_Emit as em EXT = (".estx", ".stc") RULE = {"0": "합버림_큰나머지"} # STmate SAN_TYP — 그 밖 = 비목버림 _EST_KEYS = ("행", "글", "보임", "품명", "단", "색인", "연결", "비목", "자원", "연결단가", "변수") -_EST_KEYS += ("줄참조", "결과", "합계", "저장") +_EST_KEYS += ("줄참조", "결과", "합계", "저장", "칸글") _RES_KEYS = ("코드", "종류", "이름", "규격", "단위") @@ -47,7 +47,8 @@ def read(name: str, data: bytes) -> dict[str, Any]: def pack(got: dict, name: str) -> dict[str, Any]: - """파서 답 → 둘 꼴(셈 · 변환에 쓰는 칸만 · JSON).""" + """파서 답 → 둘 꼴(셈 · 변환에 쓰는 칸만 · JSON) · 엑셀 = 일위대가 불러오기(`M02_Hopyo_Excel.read_book`)가 + 읽는 칸도(857-2 — EST 줄 `칸글` · 블록 `엑셀행 머리 머리돈` / STmate 블록 `칸줄 줄합` / `일위대가`).""" out: dict[str, Any] = {"꼴": got["꼴"], "파일": name, "표지": got.get("표지") or []} out |= {"엑셀": True} if got.get("엑셀") else {} # 812-1 엑셀 읽기기(`M02_San_Xlsx`) — 같은 꼴 out |= ( @@ -58,7 +59,12 @@ def pack(got: dict, name: str) -> dict[str, Any]: "엑셀" ): # 엑셀 읽기기 — 줄 행 = 시트 행(원문 카드 · 옛 엑셀 길과 같은 자리) · 블록 표지 head += ("표지", "몸", "꼬리") + head += ("엑셀행", "머리", "머리돈", "칸줄", "줄합") # 857-2 일위대가 불러오기 몫 got = {**got, "산근": [_rows(b) for b in got["산근"]]} + if ( + "일위대가" in got + ): # 857-2 엑셀 「일위대가」 · 「일위대가표」 시트 읽기 답(일위대가 불러오기 몫) + out["일위대가"] = got["일위대가"] if got["꼴"] == "EST": out["산근"] = [ {**{k: b.get(k) for k in head if k in b}, "줄": [_est_line(ln) for ln in b["줄"]]} diff --git a/M02_MasterTemplete/M02_San_Xlsx_Est.py b/M02_MasterTemplete/M02_San_Xlsx_Est.py index d38a64122..44e454f57 100644 --- a/M02_MasterTemplete/M02_San_Xlsx_Est.py +++ b/M02_MasterTemplete/M02_San_Xlsx_Est.py @@ -55,7 +55,9 @@ def _span(text: str, name: str, start: int = 0) -> tuple[int, int] | None: # ── 시트 → 블록 ─────────────────────────────────────────────────────── def blocks(rows: list[list[Any]]) -> list[dict[str, Any]]: - """단가산출 시트 → [{번, 머리, 행, 저장, 줄 [{행, 엑셀행, 보임, 돈}]}](머리 = B 열 「N.이름[단위]」).""" + """단가산출 시트 → [{번, 머리, 행, 저장, 머리돈, 줄 [{행, 엑셀행, 보임, 돈, 칸글?}]}](머리 = B 열 「N.이름[단위]」 · + 머리돈 = 머리 줄 수 칸 그대로 {계 노무비 재료비 경비} · 칸글 = 글자 칸 나눔 줄의 칸 글을 빈칸 하나로 이음 + — 일위대가 불러오기 `M02_Hopyo_ReadEst.from_two` 가 읽음 · 857-2).""" cols = sx.money_cols(rows) or [2, 3, 4, 5] split = cols[0] > 6 # 거창 꼴 — 글자 칸 나눔(열 = 화면 자리 · B 열 = 머리만) out: list[dict[str, Any]] = [] @@ -65,6 +67,11 @@ def blocks(rows: list[list[Any]]) -> list[dict[str, Any]]: if m and i > 2: out.append({"번": int(m.group(1)), "머리": head, "행": i + 1, "줄": []}) out[-1]["저장"] = sx.money_of(r, cols) + out[-1]["머리돈"] = { + k: r[j] + for k, j in zip(("계", "노무비", "재료비", "경비"), cols) + if j < len(r) and isinstance(r[j], (int, float)) and not isinstance(r[j], bool) + } continue if not out: continue @@ -74,6 +81,8 @@ def blocks(rows: list[list[Any]]) -> list[dict[str, Any]]: else: text = sx._cell(head) one = {"행": len(out[-1]["줄"]) + 1, "엑셀행": i + 1, "보임": text, "칸": split} + if split: + one["칸글"] = " ".join(v.strip() for _, v in cells if v.strip()) out[-1]["줄"].append(one | {"돈": sx.money_of(r, cols)}) for b in out: # 끝 빈 줄(시트 꼬리) while b["줄"] and not b["줄"][-1]["보임"].strip() and not b["줄"][-1]["돈"]: @@ -147,6 +156,7 @@ class Lines: "추정": False, "_marks": [], "_칸": src.get("칸"), + **({"칸글": src["칸글"]} if src.get("칸글") else {}), } def resource(self, kind: str, one: dict) -> dict[str, Any]: @@ -622,7 +632,8 @@ def index(res: dict[str, list[dict]]) -> dict[str, Any]: def read(sheets: dict[str, list]) -> dict[str, Any]: - """EST 엑셀 시트 → {꼴, 산근, 일위, 자원, 내역, 표지}(`M02_San_Estx.read` 꼴 · 일위 = 호표 길).""" + """EST 엑셀 시트 → {꼴, 산근, 일위, 자원, 내역, 표지, 일위대가}(`M02_San_Estx.read` 꼴 · 일위 = 호표 길 · + 일위대가 = 「일위대가」 시트 그대로 `M02_San_Xlsx_Ilwi.est` · 857-2).""" res = sx.resources(sheets) look = index(res) total = {one["번"]: one for one in res.get("산근") or []} @@ -653,13 +664,19 @@ def read(sheets: dict[str, list]) -> dict[str, Any]: ln.pop("_칸", None) ln["글"] = _glyph(ln["보임"], marks) lines.append(ln) - out["산근"].append({**head, "번": b["번"], "엑셀행": b["행"], "줄": lines, "표지": tags}) + more = {"머리": b["머리"], "머리돈": b["머리돈"]} # 일위대가 불러오기 몫(857-2) + out["산근"].append( + {**head, "번": b["번"], "엑셀행": b["행"], "줄": lines, "표지": tags} | more + ) out["자원"] = { f"{kind}:{one['번']}": {k: one[k] for k in ("이름", "규격", "단위", "표")} | {"저장": one["값"]} for kind, rows in res.items() for one in rows } + from M02_MasterTemplete import M02_San_Xlsx_Ilwi as ilwi + + out["일위대가"] = ilwi.est(sheets) out["표지"] = [ f"{sx.NOTE}자원 코드 · LinkIndex · 자리(Diget) 없음 — 연결뜻 = 글 · 금액 칸 · 단가표로 정함({sx.GUESS})", f"{sx.NOTE}자원 코드 = 단가표 이름#No(산근 = 단산 번)", diff --git a/M02_MasterTemplete/M02_San_Xlsx_Ilwi.py b/M02_MasterTemplete/M02_San_Xlsx_Ilwi.py index 36c4c19d1..bfc74f586 100644 --- a/M02_MasterTemplete/M02_San_Xlsx_Ilwi.py +++ b/M02_MasterTemplete/M02_San_Xlsx_Ilwi.py @@ -2,6 +2,7 @@ 읽는 곳 하나 — 일위대가 불러오기(`M02_Hopyo_Stmate.read`) · 단가산출 불러오기 (`M02_San_Xlsx_Stmate.read` 「일위」) · 재료 단서(`M02_San_MatFind.from_book`). +EST 「일위대가」 · 「일위대가총괄표」 = `est`(857-2 · 칸 그대로 → 둘 꼴 `일위대가` · 갈래 · 검산 = 일위대가 불러오기). 호표 = A 「제N호표」 줄(숨은 칸 `BDCOD|B…`) → 다음 줄 이름 · 규격 · 단위 → 구성 줄 → 「합계」 · 「계」. 구성 줄 = 숨은 칸 기준(표시대로 · 글 짐작 안 함 · 원파일 구성표 BDQTY 와 같은 칸) — N 열 메타 `COD|M00131 ␅ EXI DVD BMK IPR KWN BLA EQC PRI PRO UNI TPR` · O 열 차수 꼬리 `M00131_1`. @@ -184,3 +185,96 @@ def blocks(sheet: dict[str, Any]) -> list[dict[str, Any]]: | {"엑셀행": h["행"][0], "줄": h["줄"], "줄합": None, "표지": []} for h in sheet["호표"] ] + + +# ── EST 「일위대가」 시트(857-2 · 일위대가 불러오기 `M02_Hopyo_Excel.read_book` 이 이 답을 받음) ── +EST_SHEET, EST_SUMMARY = "일위대가", "일위대가총괄표" +EST_HEADS = ("호표", "품명", "규격", "수량", "단위", "비고") +EST_MONEY = ("합계", "노무비", "재료비", "경비") + + +def _flat(v: Any) -> str: + return re.sub(r"\s+", "", str(v or "")) + + +def _at(row: list[Any], col: int | None) -> Any: + return row[col] if col is not None and col < len(row) else None + + +def _raw(v: Any) -> Any: + """칸 값 그대로(JSON 꼴 · 날짜 등 = 글) — 수 풀이는 받는 쪽.""" + return v if v is None or isinstance(v, (int, float, str, bool)) else str(v) + + +def columns(rows: list[list[Any]], money: tuple[str, ...]) -> tuple[int, dict[str, int]]: + """(자료 첫 줄, {머리: 열}) — 머리 글은 앞 10 줄 안 「호표」 · 「품명」 이 든 줄 · 없음 = BookError.""" + from M02_MasterTemplete.M02_San_Workbook import BookError + + for at, row in enumerate(rows[:10]): + flat = [_flat(v) for v in row] + if "호표" not in flat or "품명" not in flat: + continue + cols = {head: flat.index(head) for head in (*EST_HEADS, *money) if head in flat} + below = [_flat(v) for v in rows[at + 1]] if at + 1 < len(rows) else [] + start = at + 2 if "단가" in below or "금액" in below else at + 1 + return start, cols + raise BookError(f"{EST_SHEET} 시트 머리 글(호표 · 품명)을 못 찾음") + + +def _money_raw(row: list[Any], cols: dict[str, int], offset: int) -> dict[str, Any]: + """비목 넷(합계 = 계) 칸 그대로 — `offset` 0 = 단가 열 · 1 = 금액 열.""" + return { + ("계" if head == "합계" else head): _raw(_at(row, None if c is None else c + offset)) + for head in EST_MONEY + for c in [cols.get(head)] + } + + +def _totals(rows: list[list[Any]] | None) -> list[list[Any]]: + """총괄표 [[호표 번, 합계 칸]] — 머리 글이 없으면 빈 것.""" + from M02_MasterTemplete.M02_San_Workbook import BookError + + if not rows: + return [] + try: + start, cols = columns(rows, ("합계",)) + except BookError: + return [] + out = [] + for row in rows[start:]: + if hit := _HOPYO.fullmatch(_flat(_at(row, cols.get("호표")))): + out.append([int(hit.group(1)), _raw(_at(row, cols.get("합계")))]) + return out + + +def est(sheets: dict[str, list]) -> dict[str, Any] | None: + """EST 「일위대가」 · 「일위대가총괄표」 → {호표 [{번, 이름, 규격, 단위, 금액, 행 [처음, 끝], 줄 [{행, 이름, + 규격, 수량, 단위, 단가, 금액, 비고}]}], 총괄표 [[번, 합계]]}(수 = 칸 그대로 · 갈래 · 이음 · 검산 = + `M02_Hopyo_Excel`) · 시트 없음 = None · 머리 글 없음 = {오류}. + 호표 줄 = 「제N호표」 · 구성 줄 = 호표 칸 빔 · 품명 있음 · 끝 = 다음 호표.""" + from M02_MasterTemplete.M02_San_Workbook import BookError + + rows = sheets.get(EST_SHEET) + if rows is None: + return None + try: + start, cols = columns(rows, EST_MONEY) + except BookError as error: + return {"오류": str(error)} + text = lambda row, head: _s(_at(row, cols.get(head))) # noqa: E731 + hopyos: list[dict[str, Any]] = [] + for at, row in enumerate(rows[start:], start + 1): + head, name = _flat(_at(row, cols.get("호표"))), text(row, "품명") + if hit := _HOPYO.fullmatch(head): + one = {"번": int(hit.group(1)), "이름": name, "규격": text(row, "규격")} + one |= {"단위": text(row, "단위"), "금액": _money_raw(row, cols, 1), "행": [at, at]} + hopyos.append(one | {"줄": []}) + continue + if head or not name or not hopyos: + continue + line = {"행": at, "이름": name, "규격": text(row, "규격")} + line |= {"수량": _raw(_at(row, cols.get("수량"))), "단위": text(row, "단위")} + line |= {"단가": _money_raw(row, cols, 0), "금액": _money_raw(row, cols, 1)} + hopyos[-1]["줄"].append(line | {"비고": text(row, "비고")}) + hopyos[-1]["행"][1] = at + return {"호표": hopyos, "총괄표": _totals(sheets.get(EST_SUMMARY))} diff --git a/M02_MasterTemplete/M02_San_Xlsx_Stmate.py b/M02_MasterTemplete/M02_San_Xlsx_Stmate.py index e27cf8d09..cc4c7b37f 100644 --- a/M02_MasterTemplete/M02_San_Xlsx_Stmate.py +++ b/M02_MasterTemplete/M02_San_Xlsx_Stmate.py @@ -17,6 +17,22 @@ from M02_MasterTemplete import M02_San_Stc as stc from M02_MasterTemplete import M02_San_Xlsx as sx RULE = {"비목버림": "1", "합버림_큰나머지": "0"} # 끝전 갈래 → SAN_TYP +#: 일위대가 불러오기가 읽는 칸(857-2 · `M02_Hopyo_Stmate.from_two`) — A 끝 · B 글 · C~F 금액 · G 식 · H 품 · +#: I~L 단가 · M 자원 · N 셈 밖 · X 「이름 / 규격」 +CELLS = {k: ord(k) - 65 for k in "ABCDEFGHIJKLMNX"} + + +def cells(rows: list[list], start: int, end: int) -> list[dict[str, Any]]: + """블록 머리 줄 ~ 다음 머리 앞 칸(값 든 칸만 · 그대로 · 빈 줄 뺌) → [{행, A.. X}].""" + from M02_MasterTemplete.M02_San_Xlsx_Ilwi import _raw + + out = [] + for rn in range(start, end): + r = rows[rn - 1] + one = {k: _raw(r[i]) for k, i in CELLS.items() if i < len(r) and r[i] not in (None, "")} + if one: + out.append({"행": rn, **one}) + return out def _amt(head: dict) -> dict[str, float]: @@ -41,8 +57,9 @@ def vote(blocks: list[dict], prices: dict) -> tuple[str, dict[str, int]]: def read(sheets: dict[str, list]) -> dict[str, Any]: - """STmate 엑셀 시트 → {꼴, 산근, 일위, 자원, 내역, 단가, 옵션, 표지} · 일위 = 일위대가표 숨은 칸 - 구성 줄(828-2 `M02_San_Xlsx_Ilwi` · 숨은 칸 없으면 빈 목록 + 표지).""" + """STmate 엑셀 시트 → {꼴, 산근, 일위, 자원, 내역, 단가, 옵션, 표지, 일위대가} · 일위 = 일위대가표 숨은 칸 + 구성 줄(828-2 `M02_San_Xlsx_Ilwi` · 숨은 칸 없으면 빈 목록 + 표지) · 일위대가 = 같은 시트 읽기 답 통째 · + 산근 블록 `칸줄` = 머리 ~ 다음 머리 앞 칸(일위대가 불러오기 몫 · 857-2).""" found = book.stmate_prices(sheets) prices = {c: {k: p.get(k) for k in ("T", "L", "M", "S", "meta")} for c, p in found.items()} res = { @@ -51,7 +68,9 @@ def read(sheets: dict[str, list]) -> dict[str, Any]: for c, p in found.items() } out: dict[str, Any] = {"꼴": "STmate", "산근": [], "일위": [], "자원": res, "단가": prices} - for blk in book.stmate_blocks(sheets): + blocks, rows = book.stmate_blocks(sheets), sheets.get("단가산출근거") or [] + ends = [b["행"] for b in blocks[1:]] + [len(rows) + 1] + for blk, end in zip(blocks, ends, strict=True): tags: list[str] = [] lines = [stc.stc_line(i, ln["G"], res, tags) for i, ln in enumerate(blk["몸"], 1)] for one, src in zip(lines, blk["몸"]): @@ -66,6 +85,7 @@ def read(sheets: dict[str, list]) -> dict[str, Any]: | { "몸": body, "꼬리": blk["꼬리"], + "칸줄": cells(rows, blk["행"], end), # 일위대가 불러오기 몫(857-2) } # 엑셀 줄 금액 · 계 꼬리(검산 · `M02_San_Emit.stmate`) ) rule, got = vote(out["산근"], prices) @@ -76,6 +96,9 @@ def read(sheets: dict[str, list]) -> dict[str, Any]: sheet = ilwi.read(sheets.get(ilwi.SHEET)) # 828-2 일위대가표 숨은 칸 → 구성 줄(읽는 곳 하나) out["일위"] = ilwi.blocks(sheet) + out["일위대가"] = ( + sheet # 857-2 일위대가 불러오기(`M02_Hopyo_Stmate.read`) — 숨은 칸 없어도 호표 · 줄 + ) out["단서"] = mf.from_book(sheet) # 827-2 재료 단서 out["표지"] = [ f"{sx.NOTE}일위대가 구성 = 일위대가표 숨은 칸 · 내역은 안 읽음" From b8315dcd42911ec4d066e102bf483dfce6ed7d06 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 00:07:09 +0900 Subject: [PATCH 2/2] =?UTF-8?q?refactor(857-2):=20=EC=9D=BC=EC=9C=84?= =?UTF-8?q?=EB=8C=80=EA=B0=80=20=EB=B6=88=EB=9F=AC=EC=98=A4=EA=B8=B0?= =?UTF-8?q?=EA=B0=80=20=EC=8B=9C=ED=8A=B8=EB=A5=BC=20=EB=8B=A4=EC=8B=9C=20?= =?UTF-8?q?=EA=B0=80=EB=A5=B4=EC=A7=80=20=EC=95=8A=EA=B3=A0=20=EB=91=98=20?= =?UTF-8?q?=EA=BC=B4=20=EC=9C=84=EC=97=90=EC=84=9C=20=EC=9D=BD=EC=9D=8C=20?= =?UTF-8?q?=E2=80=94=20=EA=B0=99=EC=9D=80=20=EC=8B=9C=ED=8A=B8=20=EA=B0=80?= =?UTF-8?q?=EB=A6=84=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]"])