Merge branch 'sub_laptop_8' of C:/Aislo_wt/sub_laptop_8 into main_laptop_1
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""M02 일위대가 실무자료 읽기(PLAN 324-1) — 설계내역서 엑셀 「일위대가」 시트 →
|
||||
호표 · 줄 · 갈래 · 검산.
|
||||
|
||||
읽기 = .xls `xlrd`(경고가 stdout 으로 안 나가게 logfile) · .xlsx `openpyxl`(빈 칸 None) ·
|
||||
읽기 = 책 한 벌 `M02_San_Workbook.read`(857-1 · .xls xlrd · .xlsx openpyxl · 빈 칸 None) ·
|
||||
시트 · 열은 머리 글(빈칸 뺌)로 찾음 — 호표 · 품명 · 규격 · 수량 · 단위 · 합계 · 노무비 ·
|
||||
재료비 · 경비 · 비고(돈 머리 = 단가 열 · 다음 열 = 금액).
|
||||
호표 줄 = 「제N호표」 · 호표 1 단위 값 = 금액 열 · 구성 줄 = 호표 칸 빔 · 품명 있음 ·
|
||||
@@ -25,7 +25,6 @@ STmate 꼴(「일위대가표」 · 「단가산출근거」 시트) = `M02_Hopy
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from decimal import ROUND_FLOOR, Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
@@ -34,6 +33,7 @@ from M02_MasterTemplete import M02_Hopyo_Clause as hopyo_clause # 출처 풀이
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hopyo_est # EST 단가산출 어댑터(776-2)
|
||||
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)
|
||||
|
||||
SHEET = "일위대가"
|
||||
SUMMARY = "일위대가총괄표"
|
||||
@@ -43,8 +43,7 @@ HEADS = ("호표", "품명", "규격", "수량", "단위", "비고")
|
||||
NO_SHEET = "일위대가 시트 없음"
|
||||
_HOPYO = re.compile(r"제\s*(\d+)\s*호표")
|
||||
_REF = re.compile(r"^(?:(단산|산근|단가산출)|(일위대가|일위|대가))(\d+)(?:참조|호표)?$")
|
||||
DRM = "문서 보안(DRM)으로 잠긴 파일 — 보안을 푼 사본으로 저장해 올림"
|
||||
_OLE = b"\xd0\xcf\x11\xe0"
|
||||
DRM = workbook.DRM
|
||||
_MACHINE_UNITS = ("hr", "시간", "h")
|
||||
_CODE_KIND = {
|
||||
"D": "단가산출",
|
||||
@@ -54,12 +53,7 @@ _CODE_KIND = {
|
||||
"S": "별도계상",
|
||||
"W": "별도계상",
|
||||
}
|
||||
# ponytail: 마지막 연 책 하나(올림 길 read_book → Grid.read 가 같은 바이트) — 여럿 동시면 다시 엶
|
||||
_OPENED: tuple[bytes, dict[str, list[list[Any]]], Any] | None = None
|
||||
|
||||
|
||||
class ExcelError(ValueError):
|
||||
"""엉터리 파일 · 시트 없음 — 길이 400 으로 답함."""
|
||||
ExcelError = workbook.BookError # 엉터리 파일 · 시트 없음 — 길이 400 으로 답함
|
||||
|
||||
|
||||
def _flat(value: Any) -> str:
|
||||
@@ -93,64 +87,6 @@ def _out(value: Decimal | None) -> int | float | None:
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
|
||||
|
||||
# ── 파일 → 시트 표(줄마다 값 목록) ────────────────────────────────────────
|
||||
def _sheets(name: str, data: bytes, wanted: tuple[str, ...] = ()) -> dict[str, list[list[Any]]]:
|
||||
"""시트 이름 → 줄 목록 — 일위대가 · 총괄표 · 단가산출만 읽음(`wanted` = 더 읽을 시트)."""
|
||||
return _open(name, data, wanted)[0]
|
||||
|
||||
|
||||
def opened(name: str, data: bytes, wanted: tuple[str, ...] = ()) -> tuple[dict[str, Any], Any]:
|
||||
"""(시트 줄, xls 책 | None) — 방금 `read_book` 이 연 같은 바이트면 그 책(한 번 열기 · 776-2) ·
|
||||
아니면 엶. xls 책 = xlrd `formatting_info`(격자 서식)."""
|
||||
global _OPENED
|
||||
got, _OPENED = _OPENED, None
|
||||
if got is not None and got[0] is data: # read_book 은 목록 시트(LISTS)까지 읽어 둠
|
||||
return got[1], got[2]
|
||||
return _open(name, data, wanted)
|
||||
|
||||
|
||||
def _open(
|
||||
name: str, data: bytes, wanted: tuple[str, ...] = ()
|
||||
) -> tuple[dict[str, list[list[Any]]], Any]:
|
||||
keep = (SHEET, SUMMARY, hopyo_est.SHEET, *wanted)
|
||||
if not data:
|
||||
raise ExcelError("빈 파일")
|
||||
if b"DRMONE" in data[:256] and data[:4] not in (b"PK\x03\x04", _OLE):
|
||||
raise ExcelError(DRM)
|
||||
try:
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
if hopyo_stmate.is_stmate([t.strip() for t in book.sheetnames]):
|
||||
keep = (*hopyo_stmate.SHEETS, *wanted)
|
||||
out = {
|
||||
ws.title.strip(): [list(row) for row in ws.iter_rows(values_only=True)]
|
||||
for ws in book.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
book.close()
|
||||
return out, None
|
||||
import xlrd
|
||||
|
||||
try:
|
||||
book = xlrd.open_workbook(
|
||||
file_contents=data, formatting_info=True, logfile=io.StringIO()
|
||||
)
|
||||
except Exception: # 서식 표가 깨진 파일 — 값만(격자는 그때 서식 없이 다시 엶)
|
||||
book = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
rows = {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in book.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return rows, book
|
||||
except ExcelError:
|
||||
raise
|
||||
except Exception as error: # 라이브러리마다 다른 예외 — 깨진 파일 · 엑셀 아님
|
||||
raise ExcelError("엑셀 파일을 읽지 못함 — xls · xlsx 가 아니거나 깨진 파일") from error
|
||||
|
||||
|
||||
def _columns(rows: list[list[Any]], money: tuple[str, ...]) -> tuple[int, dict[str, int]]:
|
||||
"""(자료 첫 줄, {머리: 열}) — 머리 글은 앞 10 줄 안 「호표」 · 「품명」 이 든 줄."""
|
||||
for at, row in enumerate(rows[:10]):
|
||||
@@ -297,20 +233,23 @@ def _by_name(raw: list[list[dict[str, Any]]], blocks: dict[int, dict[str, Any]])
|
||||
|
||||
|
||||
# ── 읽기 ──────────────────────────────────────────────────────────────
|
||||
def read_book(name: str, data: bytes) -> dict[str, Any]:
|
||||
"""엑셀 → `{시트, 호표: [...], 검산: {어긋남: [글 …], 총괄표: 맞춘 수}}` — 값은 JSON 수."""
|
||||
global _OPENED
|
||||
sheets, xls = _open(name, data, LISTS)
|
||||
_OPENED = (data, sheets, xls) # 격자(`Grid.read`)가 이어 씀 — 한 번 열기
|
||||
if hopyo_stmate.is_stmate(sheets):
|
||||
return unit_line.settle(hopyo_clause.settle(hopyo_stmate.read(sheets)))
|
||||
def read_book(
|
||||
name: str, data: bytes, book: workbook.Book | None = None, blocks_only: bool = False
|
||||
) -> dict[str, Any]:
|
||||
"""엑셀 → `{시트, 호표: [...], 검산: {어긋남: [글 …], 총괄표: 맞춘 수}}` — 값은 JSON 수 ·
|
||||
`book` = 올림 길이 한 번 연 책(857-1) · `blocks_only`(올림 길) = 단가산출 시트가 있으면 일위대가
|
||||
시트 · 호표 없음도 받음(호표 빈 목록 · 단산만)."""
|
||||
book = book or workbook.read(name, data)
|
||||
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:
|
||||
if rows is None and not loose:
|
||||
raise ExcelError(NO_SHEET)
|
||||
start, cols = _columns(rows, ("합계", *COSTS))
|
||||
start, cols = _columns(rows, ("합계", *COSTS)) if rows is not None else (0, {})
|
||||
hopyos: list[dict[str, Any]] = []
|
||||
raw: list[list[dict[str, Any]]] = []
|
||||
for at, row in enumerate(rows[start:], start + 1):
|
||||
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)
|
||||
@@ -347,7 +286,7 @@ def read_book(name: str, data: bytes) -> dict[str, Any]:
|
||||
line["갈래"] = kind_of(line)
|
||||
line["행"] = hopyos[-1]["행"][1] = at
|
||||
raw[-1].append(line)
|
||||
if not hopyos:
|
||||
if not hopyos and not loose:
|
||||
raise ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음")
|
||||
blocks = hopyo_est.read(sheets.get(hopyo_est.SHEET))
|
||||
_by_name(raw, blocks)
|
||||
|
||||
@@ -29,6 +29,7 @@ from openpyxl.xml.functions import fromstring, iterparse
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hopyo_excel
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hopyo_basis # EST 단가산출 시트 이름
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hopyo_stmate
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
LIST_E, HOPYO_S = hopyo_excel.LISTS
|
||||
LIST_S = hopyo_stmate.LISTS[0]
|
||||
@@ -241,11 +242,8 @@ def _xlsx_widths(
|
||||
return out
|
||||
|
||||
|
||||
def _xlsx(
|
||||
name: str, data: bytes, found: dict[str, list[list[Any]]] | None = None
|
||||
) -> dict[str, Any]:
|
||||
def _xlsx(name: str, data: bytes, found: dict[str, list[list[Any]]]) -> dict[str, Any]:
|
||||
# ponytail: xlsx 는 값 · 열 폭만(병합 · 서식은 openpyxl 비 read_only 로 무거움) — 필요하면 그때
|
||||
found = found or hopyo_excel._sheets(name, data, EXTRA)
|
||||
widths = _xlsx_widths(data, SHEETS)
|
||||
sheets = []
|
||||
for at, title in enumerate((n for n in SHEETS if n in found), 1):
|
||||
@@ -322,10 +320,13 @@ def _lists(rows: dict[str, Any], parsed: dict[str, Any]) -> dict[str, list[dict[
|
||||
return {"호표": pair(hopyo), "단산": pair(calc)}
|
||||
|
||||
|
||||
def read(name: str, data: bytes, parsed: dict[str, Any]) -> dict[str, Any]:
|
||||
def read(
|
||||
name: str, data: bytes, parsed: dict[str, Any], opened: workbook.Book | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""엑셀 → `{책: Workbook, 호표, 단산, 보기, 원본, 목록, 줄}` — `parsed` =
|
||||
`M02_Hopyo_Excel.read_book` 결과(행 범위)."""
|
||||
rows, xls = hopyo_excel.opened(name, data, EXTRA) # 읽기가 연 책 그대로(한 번 열기 · 776-2)
|
||||
`M02_Hopyo_Excel.read_book` 결과(행 범위) · `opened` = 올림 길이 한 번 연 책(857-1)."""
|
||||
opened = opened or workbook.read(name, data)
|
||||
rows, xls = opened.sheets, opened.xls
|
||||
book = _xlsx(name, data, rows) if xls is None else _xls(xls)
|
||||
keep = ("번", "이름", "행")
|
||||
ids = {s["이름"]: s["id"] for s in book["시트"]}
|
||||
|
||||
@@ -32,6 +32,7 @@ from M02_MasterTemplete import M02_Hopyo_Store as hopyo_store
|
||||
from M02_MasterTemplete import M02_Hopyo_View as hopyo_view_
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mat_pick
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as from_hopyo
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Items import Layer, Session, _call
|
||||
from M02_MasterTemplete.M02_MasterTemplete_Router_Items import _root as _layer_root
|
||||
@@ -79,16 +80,17 @@ def _upload(name: str, data: bytes, who: dict[str, Any]) -> dict[str, Any]:
|
||||
if not from_hopyo.has(store.root(), same["키"]): # 793-3b 전에 올린 HP
|
||||
cannot = from_hopyo.keep(store.root(), same["키"], name, data)
|
||||
return {**same, "이어서": True, **({"읽기불가": cannot} if cannot else {})}
|
||||
try:
|
||||
parsed = hopyo_excel.read_book(name, data)
|
||||
try: # 책 한 번(857-1) · 단가산출만 있는 엑셀(일위대가 시트 없음)도 받음 = 호표 빈 목록
|
||||
book = workbook.read(name, data)
|
||||
parsed = hopyo_excel.read_book(name, data, book, blocks_only=True)
|
||||
except hopyo_excel.ExcelError as error:
|
||||
raise store.StoreError(400, str(error)) from error
|
||||
try:
|
||||
grid = hopyo_grid.read(name, data, parsed)
|
||||
grid = hopyo_grid.read(name, data, parsed, book)
|
||||
except Exception: # 격자는 보기용 덤 — 못 만들어도 올리기는 됨(보기 창 404)
|
||||
grid = None
|
||||
# 산근 시트(793-3b 가져온 식 열기) = HP 를 목록에 보이기 전에 보관(814-1) · 못 씀 사유 → 화면 토스트(797-1)
|
||||
keep = lambda key: from_hopyo.keep(store.root(), key, name, data) # noqa: E731
|
||||
keep = lambda key: from_hopyo.keep(store.root(), key, name, data, book) # noqa: E731
|
||||
return hopyo_store.save(store.root(), name, parsed, who, grid, mark, keep)
|
||||
|
||||
|
||||
|
||||
@@ -65,7 +65,10 @@ _TAG = re.compile(r"&([A-Z][A-Z0-9_]*?)(?::[A-Z])?&") # 율 기준 표지 「&P
|
||||
|
||||
|
||||
def is_stmate(names: Any) -> bool:
|
||||
return SHEET in names and CALC in names
|
||||
"""STmate 꼴 — 종류 가름 한 말(`M02_San_Workbook.kind_of` · 857-1)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
return workbook.kind_of(names) == "STmate"
|
||||
|
||||
|
||||
def _cell(row: list[Any], col: int) -> Any:
|
||||
@@ -351,10 +354,11 @@ 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]]]) -> dict[str, Any]:
|
||||
"""STmate 시트 → HP 꼴 `{꼴, 시트, 호표, 단산, 검산}`(값은 JSON 수)."""
|
||||
def read(sheets: dict[str, list[list[Any]]], loose: bool = False) -> dict[str, Any]:
|
||||
"""STmate 시트 → HP 꼴 `{꼴, 시트, 호표, 단산, 검산}`(값은 JSON 수) ·
|
||||
`loose` = 호표 없음도 받음(857-1)."""
|
||||
hopyos, raw = _hopyos(sheets.get(SHEET) or [])
|
||||
if not hopyos:
|
||||
if not hopyos and not loose:
|
||||
raise hopyo_excel.ExcelError(f"{SHEET} 시트에 호표(제N호표)가 없음")
|
||||
table = _lists(sheets)
|
||||
blocks = _blocks(sheets.get(CALC) or [], table)
|
||||
|
||||
@@ -9,9 +9,7 @@ EST(.xls · .xlsx) = 단가산출 시트 블록 글(`M02_Hopyo_ReadEst.read`) +
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import warnings
|
||||
from typing import Any
|
||||
|
||||
STM_SHEETS = (
|
||||
@@ -37,37 +35,21 @@ _X7, _X5 = "_x0007_", "_x0005_"
|
||||
_HEAD = re.compile(r"BDCOD\|([A-Z]\d+).*?POSS\|(\d+).*?POSE\|(\d+)")
|
||||
|
||||
|
||||
def sheets(name: str, data: bytes) -> dict[str, list[list[Any]]]:
|
||||
"""책 바이트 → {시트: 줄} (두 꼴 시트만)."""
|
||||
def sheets(name: str, data: bytes, book: Any = None) -> dict[str, list[list[Any]]]:
|
||||
"""책 바이트 → {시트: 줄} (두 꼴 시트만) · `book` = 올림 길이 한 번 연 책
|
||||
(857-1 `M02_San_Workbook`)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
book = book or workbook.read(name, data)
|
||||
keep = STM_SHEETS + EST_SHEETS
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
with warnings.catch_warnings(): # 인쇄 영역 이름 경고
|
||||
warnings.simplefilter("ignore")
|
||||
wb = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
try:
|
||||
return {
|
||||
ws.title.strip(): [list(r) for r in ws.iter_rows(values_only=True)]
|
||||
for ws in wb.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
finally:
|
||||
wb.close()
|
||||
import xlrd
|
||||
|
||||
wb = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
return {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in wb.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return {k: v for k, v in book.sheets.items() if k in keep}
|
||||
|
||||
|
||||
def kind_of(book: dict[str, list]) -> str | None:
|
||||
if "단가산출근거" in book:
|
||||
return "STmate"
|
||||
return "EST" if "단가산출" in book else None
|
||||
"""종류 가름 한 말(`M02_San_Workbook.kind_of`)."""
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
return workbook.kind_of(book)
|
||||
|
||||
|
||||
# ── STmate ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
자리 = 개인 층 `실무자료/재료고름/<파일 지문>.json` {파일, 고름 {종: {키, 이름, 규격, 단위}}} — [끝내기] 뒤에도 남음 ·
|
||||
같은 파일(지문)을 다시 올리면 그대로 보임.
|
||||
판(`census`) = 그 HP 블록마다 재료 줄 판정(`자원["재료찾기"]` · 827-2)을 종으로 묶음 —
|
||||
첫 판 열 때 한 번 셈 → 산근 저장본 칸 `재료판`(HP 지울 때 같이 지움).
|
||||
첫 판 열 때 한 번 셈 → 산근 저장본 칸 `재료판` + `재료판지문`(M01 지문 · 다르면 다시 셈 ·
|
||||
857-1) · HP 지울 때 같이 지움.
|
||||
만들기(`using` → `M02_Sangeun_FromHopyo._emit` 이 `apply`) = 고른 종 줄: 이음 = 고른 키 · `재료찾기.고름`
|
||||
(문서 셈 = 우리 값 · 엑셀 값 기억 없음 · `M02_Doc_Import._attach`) · 별도계상 줄 = `고름` 만(줄 이음 · 단가 0 그대로).
|
||||
문서 머리 `가져온.재료` = [{기호, 종, 원래, 판정, 방법, 키, 후보, 단서, 별도계상?, 고름?, 처음}](`entry` ·
|
||||
@@ -29,6 +30,7 @@ from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
|
||||
DIRNAME = "재료고름"
|
||||
CENSUS = "재료판"
|
||||
MARK = "재료판지문" # 판을 셀 때 M01 지문(857-1 · 별칭 · 자재가 바뀌면 다시 셈)
|
||||
KINDS = (
|
||||
"규격 없음 — 고르기",
|
||||
"단위 다름 — 고르기", # 840-3
|
||||
@@ -179,9 +181,24 @@ def entry(item: dict, sym: str, excel: Any) -> dict | None:
|
||||
|
||||
|
||||
# ── 판(그 파일 재료 종) ──────────────────────────────────────────────────
|
||||
def _mark() -> str:
|
||||
"""판 무효 지문 = M01 지문(첫 층 파일 내용 · 기계 폴더 — 별칭 · 자재 칸 포함 ·
|
||||
`San_Basis_Index.stamp`)."""
|
||||
from M02_MasterTemplete import M02_San_Basis_Index as basis
|
||||
|
||||
return basis.stamp()
|
||||
|
||||
|
||||
def census(folder: str | Path, key: str) -> list[dict]:
|
||||
"""HP 블록마다 재료 줄 판정 → 종 [{종, 이름, 규격, 단위, 판정, 방법, 키, 후보, 단서, 별도계상, 블록, 줄,
|
||||
호표?(828-1 일위 구성 줄 · 코드 숫자)}]."""
|
||||
호표?(828-1 일위 구성 줄 · 코드 숫자)}] — 셈 동안 M01 한 벌(857-1 · 파일 자국 한 번)."""
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
|
||||
with m01.cache.steady():
|
||||
return _census(folder, key)
|
||||
|
||||
|
||||
def _census(folder: str | Path, key: str) -> list[dict]:
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
@@ -191,12 +208,13 @@ def census(folder: str | Path, key: str) -> list[dict]:
|
||||
saved = json.loads(path.read_bytes())
|
||||
except (OSError, ValueError) as e:
|
||||
raise store.StoreError(409, fh.RELOAD) from e
|
||||
if isinstance(saved.get(CENSUS), list):
|
||||
mark = _mark()
|
||||
if isinstance(saved.get(CENSUS), list) and saved.get(MARK) == mark:
|
||||
return saved[CENSUS]
|
||||
native = saved.get("원파일")
|
||||
src = native if isinstance(native, dict) else fh._excel_of(path, saved) if saved.get("시트") else {} # fmt: skip
|
||||
groups: dict[str, dict] = {}
|
||||
# ponytail: 블록마다 셈 전부(기계 찾기 포함 · 70 블록 10~20 초) — 첫 판 한 번 · 느리면 재료 줄만 도는 길
|
||||
# ponytail: 블록마다 셈 전부(기계 찾기 포함) — 첫 판 한 번 · 더 느리면 재료 줄만 도는 길
|
||||
for no in sorted(fn.numbers(src)) if src else []:
|
||||
with using(None):
|
||||
try:
|
||||
@@ -235,7 +253,7 @@ def census(folder: str | Path, key: str) -> list[dict]:
|
||||
if (n := int(str(b["코드"])[1:])) not in hp:
|
||||
hp.append(n)
|
||||
out_ = sorted(groups.values(), key=lambda g: (KINDS.index(g["판정"]) if g["판정"] in KINDS else 9, -len(g["블록"]), g["이름"])) # fmt: skip
|
||||
atomic_write_json(path, {**saved, CENSUS: out_})
|
||||
atomic_write_json(path, {**saved, CENSUS: out_, MARK: mark})
|
||||
return out_
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""M02 불러오기 책 한 벌(PLAN 857-1) — 올린 엑셀을 한 번만 열어 시트 줄 · xls 서식 책 · 종류를
|
||||
같이 넘김.
|
||||
|
||||
읽는 시트 = 호표 쪽(`M02_Hopyo_Excel` 일위대가 · 총괄표 · 단가산출 · 목록 ·
|
||||
`M02_Hopyo_Stmate.SHEETS`) + 산근 쪽(`M02_San_Book.STM_SHEETS` · `EST_SHEETS`) 합집합 ·
|
||||
호표 읽기 · 격자 · 산근 보관이 같은 책을 받음.
|
||||
종류 가름 한 말 = `kind_of` — 「단가산출근거」 = STmate · 「단가산출」 = EST · 그 밖 None.
|
||||
xls = xlrd `formatting_info`(격자 서식 · 깨진 서식 표 = 값만) · xlsx = openpyxl read_only · 값만.
|
||||
엉터리 · 빈 파일 · 문서 보안(DRM) = `BookError`(올림 길 400).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
DRM = "문서 보안(DRM)으로 잠긴 파일 — 보안을 푼 사본으로 저장해 올림"
|
||||
_OLE = b"\xd0\xcf\x11\xe0"
|
||||
|
||||
|
||||
class BookError(ValueError):
|
||||
"""엉터리 파일 · 시트 없음 — 길이 400 으로 답함."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Book:
|
||||
"""한 번 연 책 — `sheets` = {시트: 줄 목록}(합집합 시트만) · `xls` = xlrd 책 | None."""
|
||||
|
||||
name: str
|
||||
sheets: dict[str, list[list[Any]]]
|
||||
xls: Any
|
||||
kind: str | None
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def wanted() -> frozenset[str]:
|
||||
"""읽을 시트 이름 합집합(호표 쪽 + 산근 쪽)."""
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as hr
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hs
|
||||
from M02_MasterTemplete import M02_San_Book as sb
|
||||
|
||||
return frozenset(
|
||||
(hx.SHEET, hx.SUMMARY, hr.SHEET, *hx.LISTS, *hs.SHEETS, *sb.STM_SHEETS, *sb.EST_SHEETS)
|
||||
)
|
||||
|
||||
|
||||
def kind_of(names: Any) -> str | None:
|
||||
"""시트 이름들 → STmate · EST · None(종류 가름 한 곳)."""
|
||||
if "단가산출근거" in names:
|
||||
return "STmate"
|
||||
return "EST" if "단가산출" in names else None
|
||||
|
||||
|
||||
def read(name: str, data: bytes) -> Book:
|
||||
"""책 바이트 → `Book`(한 번 열기)."""
|
||||
if not data:
|
||||
raise BookError("빈 파일")
|
||||
if b"DRMONE" in data[:256] and data[:4] not in (b"PK\x03\x04", _OLE):
|
||||
raise BookError(DRM)
|
||||
keep = wanted()
|
||||
try:
|
||||
if data[:4] == b"PK\x03\x04" or name.lower().endswith(".xlsx"):
|
||||
import openpyxl
|
||||
|
||||
with warnings.catch_warnings(): # 인쇄 영역 이름 경고
|
||||
warnings.simplefilter("ignore")
|
||||
book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
try:
|
||||
sheets = {
|
||||
ws.title.strip(): [list(row) for row in ws.iter_rows(values_only=True)]
|
||||
for ws in book.worksheets
|
||||
if ws.title.strip() in keep
|
||||
}
|
||||
finally:
|
||||
book.close()
|
||||
return Book(name, sheets, None, kind_of(sheets))
|
||||
import xlrd
|
||||
|
||||
try:
|
||||
xls = xlrd.open_workbook(
|
||||
file_contents=data, formatting_info=True, logfile=io.StringIO()
|
||||
)
|
||||
except Exception: # 서식 표가 깨진 파일 — 값만(격자는 서식 없이)
|
||||
xls = xlrd.open_workbook(file_contents=data, logfile=io.StringIO())
|
||||
sheets = {
|
||||
sh.name.strip(): [sh.row_values(r) for r in range(sh.nrows)]
|
||||
for sh in xls.sheets()
|
||||
if sh.name.strip() in keep
|
||||
}
|
||||
return Book(name, sheets, xls, kind_of(sheets))
|
||||
except BookError:
|
||||
raise
|
||||
except Exception as error: # 라이브러리마다 다른 예외 — 깨진 파일 · 엑셀 아님
|
||||
raise BookError("엑셀 파일을 읽지 못함 — xls · xlsx 가 아니거나 깨진 파일") from error
|
||||
@@ -47,7 +47,7 @@ def unreadable(data: bytes) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def keep(folder: str | Path, key: str, name: str, data: bytes) -> str | None:
|
||||
def keep(folder: str | Path, key: str, name: str, data: bytes, opened: Any = None) -> str | None:
|
||||
"""올린 엑셀 → 산근 시트 둠(STmate · EST 꼴만 · 못 읽으면 안 둠 — 올리기는 됨).
|
||||
돌려줌 = 못 읽은 사유(빈 파일 · DRM 암호 · 형식 오류) · 둠 · 산근 꼴 아님 = None."""
|
||||
from M02_MasterTemplete import M02_San_Book as book
|
||||
@@ -55,7 +55,7 @@ def keep(folder: str | Path, key: str, name: str, data: bytes) -> str | None:
|
||||
if why := unreadable(data):
|
||||
return why
|
||||
try:
|
||||
sheets = book.sheets(name, data)
|
||||
sheets = book.sheets(name, data, opened) # 올림 길이 한 번 연 책(857-1)
|
||||
except Exception as e: # noqa: BLE001 — 산근은 덤(가져온 식 열기만 막힘) · 사유는 돌려줌
|
||||
return f"엑셀 형식 오류 — {type(e).__name__}: {str(e)[:80]}"
|
||||
if not book.kind_of(sheets):
|
||||
|
||||
@@ -3243,8 +3243,16 @@
|
||||
"블록 엑셀:울진소광#918": "494eacf70e3fb96f"
|
||||
},
|
||||
"올림": {
|
||||
"올림 2016사방 올림": "591a8b4dfbe67819",
|
||||
"올림 2026수목 올림": "591a8b4dfbe67819",
|
||||
"올림 2016사방 고정": "4f53cda18c2baa0c",
|
||||
"올림 2016사방 목록": "128c3c95d0fb34e1",
|
||||
"올림 2016사방 올림": "bd033d8606e78695",
|
||||
"올림 2016사방 재료": "4f53cda18c2baa0c",
|
||||
"올림 2016사방 칠": "0246368daa0544d7",
|
||||
"올림 2026수목 고정": "4f53cda18c2baa0c",
|
||||
"올림 2026수목 목록": "128c3c95d0fb34e1",
|
||||
"올림 2026수목 올림": "bd033d8606e78695",
|
||||
"올림 2026수목 재료": "4f53cda18c2baa0c",
|
||||
"올림 2026수목 칠": "c9e90bcbd1a88642",
|
||||
"올림 거창 고정": "301f9d50d2aa6e01",
|
||||
"올림 거창 목록": "1b2914680b1c29fc",
|
||||
"올림 거창 올림": "5f32212ea5f045b1",
|
||||
|
||||
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
import openpyxl
|
||||
|
||||
from M02_MasterTemplete import M02_Hopyo_Grid as grid
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
SS = ROOT / "A00_Common/spreadsheet"
|
||||
@@ -38,7 +39,7 @@ def test_xlsx_without_widths_is_empty_and_garbage_is_safe():
|
||||
|
||||
def test_xlsx_sheet_carries_widths():
|
||||
data = _xlsx({"A": 30})
|
||||
sheets = grid._xlsx("a.xlsx", data)["시트"]
|
||||
sheets = grid._xlsx("a.xlsx", data, workbook.read("a.xlsx", data).sheets)["시트"]
|
||||
assert sheets and sheets[0]["열"]["A"]["폭"] == 30.0
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""857-1 지킴 — 불러오기 책 한 번 · 종류 한 말 · 일위대가 시트 없는 엑셀 올림 ·
|
||||
「고를 재료」 판 무효 지문 · 판 셈 동안 M01 한 벌(`M01_MasterData_Store_Cache.steady`).
|
||||
|
||||
임시 storage 개인 층 · 실무 엑셀 견본(없는 PC = 건너뜀).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import helper_857_import as h # noqa: E402
|
||||
|
||||
|
||||
def _path(name: str) -> Path:
|
||||
p = h.sources().get(f"엑셀:{name}")
|
||||
if not p or not p.exists():
|
||||
pytest.skip(f"견본 없음 — {name}")
|
||||
return p
|
||||
|
||||
|
||||
def _opens(monkeypatch) -> list[str]:
|
||||
import openpyxl
|
||||
import xlrd
|
||||
|
||||
seen: list[str] = []
|
||||
for mod, attr in ((openpyxl, "load_workbook"), (xlrd, "open_workbook")):
|
||||
real = getattr(mod, attr)
|
||||
|
||||
def wrap(*a, _real=real, _tag=attr, **k):
|
||||
seen.append(_tag)
|
||||
return _real(*a, **k)
|
||||
|
||||
monkeypatch.setattr(mod, attr, wrap)
|
||||
return seen
|
||||
|
||||
|
||||
def test_종류_한_말():
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as hs
|
||||
from M02_MasterTemplete import M02_San_Book as sb
|
||||
from M02_MasterTemplete import M02_San_Workbook as wb
|
||||
|
||||
for names, kind in (
|
||||
(["일위대가표", "단가산출근거"], "STmate"),
|
||||
(["단가산출근거"], "STmate"),
|
||||
(["일위대가", "단가산출"], "EST"),
|
||||
(["일위대가"], None),
|
||||
):
|
||||
assert wb.kind_of(names) == kind
|
||||
assert sb.kind_of(dict.fromkeys(names)) == kind
|
||||
assert hs.is_stmate(names) == (kind == "STmate")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["봉화", "북부청사방"])
|
||||
def test_올림_한_번에_책_한_번(monkeypatch, name):
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
|
||||
path = _path(name)
|
||||
seen = _opens(monkeypatch)
|
||||
with h.personal():
|
||||
row = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})
|
||||
assert row["호표수"] > 0 and not row.get("읽기불가")
|
||||
assert len(seen) == 1, seen
|
||||
|
||||
|
||||
def test_일위대가_시트_없는_엑셀도_올라감_호표_빈_목록_단산은_보임():
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_Hopyo_Store as hstore
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("2026수목")
|
||||
data = path.read_bytes()
|
||||
with pytest.raises(hx.ExcelError): # B09 내역서 길(그대로) — 일위대가 시트 없음 = 거절
|
||||
hx.read_book(path.name, data)
|
||||
with h.personal():
|
||||
row = router._upload(path.name, data, {"id": 42, "이름": "시험"})
|
||||
hp = hstore.read(store.root(), row["키"])
|
||||
assert row["호표수"] == 0 and hp["호표"] == []
|
||||
assert len(hp["단산"]) == 142 # 단가산출 시트 블록(둘 꼴 산근 수와 같음)
|
||||
assert fh.has(store.root(), row["키"]) # 가져온 식 열기 자료 보관
|
||||
|
||||
|
||||
def test_재료판_무효_지문_M01_이_바뀌면_다시_셈(monkeypatch):
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mp
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("영덕계류")
|
||||
with h.personal():
|
||||
key = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})["키"]
|
||||
first = mp.census(store.root(), key)
|
||||
saved = json.loads(fh._path(store.root(), key).read_bytes())
|
||||
assert saved[mp.MARK] == mp._mark() and saved[mp.CENSUS] == first
|
||||
runs: list[int] = []
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
|
||||
emit = fn.emit
|
||||
monkeypatch.setattr(fn, "emit", lambda *a, **k: runs.append(1) or emit(*a, **k))
|
||||
assert mp.census(store.root(), key) == first and not runs # 같은 M01 = 저장본
|
||||
monkeypatch.setattr(mp, "_mark", lambda: "다른 M01")
|
||||
assert mp.census(store.root(), key) == first and runs # 지문 다름 = 다시 셈 · 답 같음
|
||||
|
||||
|
||||
def test_판_셈_동안_M01_파일_자국_한_번(monkeypatch):
|
||||
from M01_MasterData import M01_MasterData_Store_Cache as cache
|
||||
from M02_MasterTemplete import M02_Doc_FromNative as fn
|
||||
from M02_MasterTemplete import M02_Hopyo_Router as router
|
||||
from M02_MasterTemplete import M02_MasterTemplete_Store as store
|
||||
from M02_MasterTemplete import M02_San_MatPick as mp
|
||||
from M02_MasterTemplete import M02_Sangeun_FromHopyo as fh
|
||||
|
||||
path = _path("영덕계류")
|
||||
counts: list[int] = []
|
||||
real = cache._stamps
|
||||
monkeypatch.setattr(cache, "_stamps", lambda folder: counts.append(1) or real(folder))
|
||||
with h.personal():
|
||||
key = router._upload(path.name, path.read_bytes(), {"id": 42, "이름": "시험"})["키"]
|
||||
counts.clear()
|
||||
held = mp.census(store.root(), key)
|
||||
with_hold = len(counts)
|
||||
at = fh._path(store.root(), key)
|
||||
src = fh._excel_of(at, json.loads(at.read_bytes()))
|
||||
counts.clear()
|
||||
for no in sorted(fn.numbers(src)): # 안 쥔 셈(지금 길) — 블록마다 자국을 다시 잼
|
||||
with mp.using(None):
|
||||
fn.emit(src, no)
|
||||
bare = len(counts)
|
||||
assert held and with_hold <= 3 < bare
|
||||
@@ -7,6 +7,7 @@
|
||||
- 기본 = 빠른 표본(`QUICK_*`) · 전수 = 환경 `S857_ALL=1` · 견본 없는 PC = 그 갈래 건너뜀(수를 글로).
|
||||
- 다르면 실패 + 갈래 이름 — 뜻대로 바꾼 걸음만 다시 뜸(바뀐 갈래를 커밋 글에):
|
||||
`S857_ALL=1 ./venv/Scripts/python.exe resources/tester/test_857_import_golden.py --write`
|
||||
(뒤에 「블록」 · 「올림」 = 그 갈래만)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -61,9 +62,11 @@ def test_엑셀_올림_호표_목록_칠_고정_재료_지문_같음():
|
||||
if __name__ == "__main__":
|
||||
if "--write" not in sys.argv or not ALL:
|
||||
sys.exit(f"다시 뜨기 = {REDO}")
|
||||
blocks, skip_b = h.blocks(True)
|
||||
ups, table, skip_u = h.uploads(True)
|
||||
body = {"판": 1, "블록": blocks, "올림": ups, "재료표": h.mat_counts(table)}
|
||||
only = sys.argv[sys.argv.index("--write") + 1 :] # 갈래 하나만(블록 | 올림) · 없으면 둘 다
|
||||
blocks, skip_b = (_want()["블록"], 0) if only == ["올림"] else h.blocks(True)
|
||||
ups, table, skip_u = h.uploads(True) if only != ["블록"] else (_want()["올림"], None, 0)
|
||||
mats = h.mat_counts(table) if table is not None else _want()["재료표"]
|
||||
body = {"판": 1, "블록": blocks, "올림": ups, "재료표": mats}
|
||||
FILE.write_text(
|
||||
json.dumps(body, ensure_ascii=False, indent=1, sort_keys=True) + "\n", "utf-8", newline="\n"
|
||||
)
|
||||
|
||||
@@ -182,8 +182,15 @@ def test_올리기_목록_읽기_지우기(client):
|
||||
def test_엉터리_시트없음_큰_파일_400(client, monkeypatch):
|
||||
bad = _post(client, data=b"garbage", name="a.xls")
|
||||
assert bad.status_code == 400 and "읽지 못함" in bad.json()["detail"]
|
||||
none = _post(client, data=NO_SHEET.read_bytes(), name=NO_SHEET.name)
|
||||
book = io.BytesIO()
|
||||
import openpyxl
|
||||
|
||||
openpyxl.Workbook().save(book) # 일위대가 · 단가산출 시트 둘 다 없음
|
||||
none = _post(client, data=book.getvalue(), name="빈책.xlsx")
|
||||
assert none.status_code == 400 and none.json()["detail"] == "일위대가 시트 없음"
|
||||
only = _post(client, data=NO_SHEET.read_bytes(), name=NO_SHEET.name) # 857-1 단가산출만 = 올라감
|
||||
assert only.status_code == 200 and only.json()["호표수"] == 0
|
||||
assert client.delete(URL.format("personal") + "/" + only.json()["키"]).status_code == 200
|
||||
monkeypatch.setattr(hopyo_router, "HOPYO_MAX_BYTES", 1000)
|
||||
big = _post(client)
|
||||
assert big.status_code == 400 and "20 MB" in big.json()["detail"]
|
||||
|
||||
@@ -16,6 +16,7 @@ from M02_MasterTemplete import M02_Hopyo_ReadEst as hb
|
||||
from M02_MasterTemplete import M02_Hopyo_Excel as hx
|
||||
from M02_MasterTemplete import M02_Hopyo_Stmate as st
|
||||
from M02_MasterTemplete import M02_Hopyo_Store as hs
|
||||
from M02_MasterTemplete import M02_San_Workbook as workbook
|
||||
from M02_MasterTemplete import M02_Template_Layers as layers
|
||||
from resources.tester import test_m02_hopyo_excel as base
|
||||
from resources.tester.test_m02_hopyo_excel import ROOT, _post, master_hash
|
||||
@@ -129,7 +130,7 @@ def test_기계_자원_하나로(books):
|
||||
def test_노임_이름_어긋남_0(books):
|
||||
names = hb.trade_names()
|
||||
for tag in FILES:
|
||||
sheets = hx._sheets(_path(tag).name, _path(tag).read_bytes())
|
||||
sheets = workbook.read(_path(tag).name, _path(tag).read_bytes()).sheets
|
||||
table = st._lists(sheets)
|
||||
res = [r for b in books[tag]["단산"] for r in b["자원"] if r["갈래"] == "L" and r["이름"]]
|
||||
assert res
|
||||
|
||||
Reference in New Issue
Block a user