From dddef2131cfd9fba16460851293a6644416c8986 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 21:54:15 +0900 Subject: [PATCH] =?UTF-8?q?refactor(859-2=20=E3=89=AE-1):=20B09=20?= =?UTF-8?q?=EB=82=B4=EC=97=AD=20=EC=A0=90=EA=B2=80=20[=EB=8B=A8=EA=B0=80?= =?UTF-8?q?=20=EA=B0=B1=EC=8B=A0]=20=C2=B7=20=EB=AF=B8=EB=A6=AC=20?= =?UTF-8?q?=EB=B3=B4=EA=B8=B0=20=EC=B0=BD=20=C2=B7=20[=EC=9E=AC=EC=83=9D?= =?UTF-8?q?=EC=84=B1]=20=EA=B1=B7=EC=9D=8C=20=E2=80=94=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=EC=A0=9D=ED=8A=B8=20=EB=8B=A8=EA=B0=80=EB=8A=94=20?= =?UTF-8?q?=EC=A7=80=EC=A0=95=ED=95=9C=20=EB=95=8C=20=EA=B7=B8=EB=8C=80?= =?UTF-8?q?=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 화면: 「내역 점검」 카드 [단가 갱신] 단추 · 점 배지 · 호버 · 미리 보기 창([재생성] · [적용]) 걷음 · 연결 점검 목록 그대로 - 서버: POST …/estimation/prices · …/prices/preview 걷음(openapi 469 → 467) · GET 답 `book` · `stale` 칸(매 GET 단가 책 견줌) 걷음 - B09_Estimation_Refresh · B09_Estimation_Copy_Prices 지움(사본 단가 읽기 = 단가.json 바로) · Bill_Library 서고 다시 굳힘(changed · refresh_copy) 걷음 - 단가 책: 첫 굳힘 `make_book`(옛 refresh_book 의 단가 갱신 몫 · book_stale · book_diff · labor_editions 걷음) - 시험: 죽은 길만 보던 test_296 · test_703_3 지움 · 203_1 배지 · 795_4 ⑤ ⑥ · 719_2 서고 업데이트 지움 · 144 길 = 없음 확인 - test_253_3: B9-4 화면 꼴 뒤 낡은 단언(엑셀 꼴 식 글)을 작업량 값 줄로 고침 Co-Authored-By: Claude Opus 5.5 --- B09_Estimation/B09_Estimation_Bill_Library.py | 39 +--- B09_Estimation/B09_Estimation_Copy_Prices.py | 92 ---------- B09_Estimation/B09_Estimation_Labor_Source.py | 9 +- B09_Estimation/B09_Estimation_Linked.py | 7 +- B09_Estimation/B09_Estimation_Prices.py | 61 +----- B09_Estimation/B09_Estimation_Refresh.py | 173 ------------------ B09_Estimation/B09_Estimation_Router.py | 83 +-------- B09_Estimation/B09_Estimation_Sangeun.py | 7 +- B09_Estimation/B09_Estimation_Store.py | 2 +- B09_Estimation/B09_Estimation_UI_Check.ts | 135 +------------- B09_Estimation/B09_Estimation_UI_Page.css | 22 --- B09_Estimation/B09_Estimation_UI_Shell.ts | 34 +--- B09_Estimation/B09_Estimation_UI_Tabs_Base.ts | 4 +- .../B09_Estimation_UI_Tabs_Sangeun_Sheet.ts | 2 +- resources/tester/test_144_b09_skeleton.py | 5 +- resources/tester/test_203_1_b09_data_check.py | 54 +----- resources/tester/test_253_3_haul_preview.py | 2 +- .../test_296_b09_update_skip_deleted.py | 90 --------- resources/tester/test_703_3_b09_refresh.py | 75 -------- resources/tester/test_719_2_sk_project.py | 25 +-- resources/tester/test_795_4_b09_copy.py | 60 +----- 21 files changed, 49 insertions(+), 932 deletions(-) delete mode 100644 B09_Estimation/B09_Estimation_Copy_Prices.py delete mode 100644 B09_Estimation/B09_Estimation_Refresh.py delete mode 100644 resources/tester/test_296_b09_update_skip_deleted.py delete mode 100644 resources/tester/test_703_3_b09_refresh.py diff --git a/B09_Estimation/B09_Estimation_Bill_Library.py b/B09_Estimation/B09_Estimation_Bill_Library.py index 2a14b4436..3d9d42e27 100644 --- a/B09_Estimation/B09_Estimation_Bill_Library.py +++ b/B09_Estimation/B09_Estimation_Bill_Library.py @@ -7,9 +7,7 @@ precombo 사전조합 = `일위대가.json` {줄: {담은로직: [{참조, 수량: {손: 1}}]}, 참조사본} · `단가.json`(`M02_Item_Source.price_bundle` — 사본 단가 묶음 한 벌) sangeun 단가산출(SK · 내 자료집 · 719-2) = precombo 와 한 꼴(SK = 수식 사본 · B9-5) -[업데이트](719-2) = 원본판이 다른 사본만 같은 폴더에 다시 굳힘(`changed` · `refresh_copy` · -값 그대로 · 원본판 없는 옛 사본 = 그대로). -사본 = 원본이 바뀌거나 지워져도 그대로(굳힘) · +사본 = 원본이 바뀌거나 지워져도 그대로(굳힘 · 859-2 프로젝트 안 다시 굳힘 없음) · 대가 블록 = `Labor_Source.daega_inputs`(`libs` {폴더: 블록 id}) · 단가 수요 = `Linked.linked_resource_keys` · 줄 연결 = {tab: dg, key: 블록 id, lib: 폴더} · [저장] 때 줄이 안 쓰는 사본은 지움(`prune`) · 층 읽기 권한 = 부르는 쪽(`M02_Layer_Access.grant`). @@ -104,7 +102,7 @@ def _precombo_files(layer: str, owner: str | None, key: str, kind: str = "precom def source_version(files: dict[str, Any]) -> str: """서고 사본 원본판(719-1) = 일위대가.json + 수식 문서(로직 몫 · 855-F B9-6) 지문 — 굳힌 SC · SK - 문서(SK = 수식 사본) · 단가는 뺌(단가 바뀜은 [단가 갱신] 몫) · 값 덮기 전에 셈.""" + 문서(SK = 수식 사본) · 단가는 뺌 · 값 덮기 전에 셈.""" return version_of([files.get(LABOR_FILE), (files.get(doc_b09.FILE) or {}).get("문서")]) @@ -121,39 +119,6 @@ def _build(kind: str, layer: str, owner: str | None, key: str) -> tuple[dict, di return files, files.pop("_원본") -def _source_of(manifest: dict[str, Any]) -> tuple[str, str, str | None, str]: - """manifest → (종류, 층, 주인, 키).""" - kind, origin = str(manifest.get("종류")), manifest.get("원본") or {} - if kind == "combo": - return kind, origin.get("layer"), origin.get("owner"), origin.get("key") - ref = origin.get("참조") or {} - return kind, ref.get("층"), ref.get("주인"), ref.get("키") - - -def changed(project_root: str | Path) -> list[tuple[Path, dict[str, Any], dict, dict]]: - """원본판이 지금 원본과 다른 사본 `(폴더, manifest, 새 파일들, 새 원본 표지)` — 원본판 없는 옛 - 사본 · 원본 없음 = 뺌(그대로).""" - out = [] - for folder, manifest in copies(project_root): - if not manifest.get("원본판"): - continue - try: - files, origin = _build(*_source_of(manifest)) - except (LookupError, ValueError, KeyError): - continue - if source_version(files) != manifest["원본판"]: - out.append((folder, manifest, files, origin)) - return out - - -def refresh_copy(project_root: str | Path, one: tuple) -> None: - """`changed` 한 줄 → 같은 폴더에 다시 굳힘(값 · 가져온이 그대로 · 원본판 새로).""" - folder, manifest, files, origin = one - keep = {k: v for k, v in manifest.items() if k not in ("값", "원값")} - fresh = {**keep, "원본": origin, "원본판": source_version(files), "가져온날": now_text()} - _write(project_root, folder.name, files, fresh, manifest.get("값") or {}) - - # ── 운반 값 사본(263-2) ──────────────────────────────────────────────── def _logic(code: str) -> dict[str, Any]: """M01 기초 이름 · 입력 꼴 — 지금 수식 문서(855-F B9-6) · 없는 기초 = 입력 없음.""" diff --git a/B09_Estimation/B09_Estimation_Copy_Prices.py b/B09_Estimation/B09_Estimation_Copy_Prices.py deleted file mode 100644 index 725490cb4..000000000 --- a/B09_Estimation/B09_Estimation_Copy_Prices.py +++ /dev/null @@ -1,92 +0,0 @@ -"""B09 [단가 갱신] = 프로젝트 사본 자원 단가 줄 갱신(PLAN 841-1 · 요구 854 · 866) — 서버 단독. - -B09 금액 = 프로젝트 사본(구조물 사본 · 서고 사본)을 M02 엔진으로 셈한 값(B09 단가 책으로 다시 안 셈). -그래서 사본 값을 지금 M01 로 올리는 일 = 사본 `단가.json` 자원 줄(LB · MT · EQ · MO · FX)만 지금 M01 줄로 -(로직 줄 · 일위대가 · 입력값 · 고른 자재 · 덮개 그대로 · M01 에서 지워진 키 = 마지막 값 그대로) — -M02 [단가 갱신](`M02_Sangeun_Copy.refresh`)과 같은 뜻 · 사용자가 누를 때만(프로젝트 안은 자동 아님). -미리 보기 = `OVER` 덮개(파일 안 씀 · 사본 읽는 곳이 `bundle` 로 읽음)로 같은 셈. -""" - -from __future__ import annotations - -from contextvars import ContextVar -from pathlib import Path -from typing import Any - -from B09_Estimation import B09_Estimation_Bill_Library as library -from common_util.common_util_json import atomic_write_json -from M01_MasterData import M01_MasterData_Store as m01 -from M02_MasterTemplete import M02_Item_Prices as item_prices -from M02_MasterTemplete import M02_Sangeun_Copy as skc -from M02_MasterTemplete.M02_Item_Snapshot import linked_snapshots, structures_dir -from M02_MasterTemplete.M02_Item_Source import PRICE_FILE, read_json - -#: 미리 보기 덮개 {사본 폴더 글: 새 `단가.json`} — 없으면 파일 -OVER: ContextVar[dict[str, dict] | None] = ContextVar("b09_copy_prices", default=None) - - -def bundle(folder: Path) -> dict[str, Any]: - """사본 `단가.json` — 미리 보기 덮개가 있으면 그것.""" - over = OVER.get() - if over and str(folder) in over: - return over[str(folder)] - return read_json(folder / PRICE_FILE) or {} - - -def folders(root: str | Path) -> list[Path]: - """연결된 구조물 사본 + 서고 사본 폴더.""" - base = structures_dir(root) - out = [base / one["폴더"] for one in linked_snapshots(root).values()] - out += [folder for folder, _manifest in library.copies(root)] - return list(dict.fromkeys(out)) - - -def _shown(row: dict[str, Any]) -> Any: - """미리 보기 값 — 노임 · 유가 = 값 · 기계 = 가격(천원) · 자재 = 출처 값 묶음.""" - value = row.get("값") - if isinstance(value, dict): - return value.get("가격") - if value is not None: - return value - return {k: row.get(k) for k in ("조달청", "물가자료", "유통물가", "물가정보", "거래가격")} - - -def refreshed(root: str | Path) -> tuple[dict[str, dict], list[dict[str, Any]]]: - """({바뀐 사본 폴더 글: 새 `단가.json`}, 바뀐 자원 [{키, 이름, 전, 후}]) — 파일 안 씀.""" - whole = skc.whole_() - news: dict[str, dict] = {} - changed: dict[str, dict[str, Any]] = {} - for folder in folders(root): - data = read_json(folder / PRICE_FILE) - if not isinstance(data, dict): - continue - out, hit = {}, False - for name, part in data.items(): - slot = m01.items_key(part) if isinstance(part, dict) else "" - rows = part.get(slot) if slot else None - if not isinstance(rows, list): - out[name] = part - continue - fresh = [] - for row in rows: - key = str((row or {}).get("키") or "") - live = whole.index.get(key[:2], {}).get(key) if key[:2] in skc.RES else None - new = item_prices.to_json(live) if live is not None else row - if new != row: - hit = True - changed.setdefault( - key, - {"키": key, "이름": new.get("이름"), "전": _shown(row), "후": _shown(new)}, - ) - fresh.append(new) - out[name] = {**part, slot: fresh} - if hit: - news[str(folder)] = out - return news, list(changed.values()) - - -def write(news: dict[str, dict]) -> int: - """새 `단가.json` 을 사본 폴더에 씀 — 쓴 사본 수.""" - for folder, data in news.items(): - atomic_write_json(Path(folder) / PRICE_FILE, data) - return len(news) diff --git a/B09_Estimation/B09_Estimation_Labor_Source.py b/B09_Estimation/B09_Estimation_Labor_Source.py index 09fbbc388..3a2336a8c 100644 --- a/B09_Estimation/B09_Estimation_Labor_Source.py +++ b/B09_Estimation/B09_Estimation_Labor_Source.py @@ -38,7 +38,6 @@ from B09_Estimation import B09_Estimation_Labor_Rule as rule from B09_Estimation import B09_Estimation_Sangeun as sg from B09_Estimation import B09_Estimation_Sangeun_Text as st from B09_Estimation.B09_Estimation_Bill_Items import LAYER_WORD -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from B09_Estimation.B09_Estimation_Linked import sk_answer from B09_Estimation.B09_Estimation_Supply import sk_money, supply_mark from M02_MasterTemplete import M02_Item_Prices as item_prices @@ -53,7 +52,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json mf = item_prices.mf @@ -186,7 +185,7 @@ class Builder: M02 SK 셈과 같은 문서) · 줄 = 문서 답 금액 줄(이름 · 단위 · 수량 · 종류 = 답 · 자원 키 · 하위 부름 = 셈 기록) — 노임 · 자재 · 기계경비(중기) · 하위 단가산출(산근) · % 줄 · 그 밖 = 줄 단가 `fixed` · 합밖 = `out` · cover = `P:` + SK 이름표(SK 를 고쳐 - [재생성] 해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) · + 다시 지정해도 B09 덮개 그대로) · 블록 합 = M02 SK 셈(`sk_money` · 841-1) · 수식 사본 없는 SK(형제 · 옛 칸) = None(부르는 줄이 까닭 · M02 처럼 못 셈).""" got = sk_answer(doc) if got is None or got.stopped or "결과" in got.ans: @@ -429,7 +428,7 @@ class Builder: labor = read_json(folder / LABOR_FILE) if not isinstance(labor, dict): return None - prices = bundle(folder) # 841-1 미리 보기 덮개 + prices = read_json(folder / PRICE_FILE) or {} values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3) @@ -489,7 +488,7 @@ class Builder: if not isinstance(doc, dict): return None whole = self.shelf.put_whole( - bundle(folder), dr.docs_of(folder) + (read_json(folder / PRICE_FILE) or {}), dr.docs_of(folder) ) # 사본 수식 문서(B9-3 · B9-6) if manifest["종류"] == "sangeun": # 내 자료집 단가산출(719-2) return self.sangeun(whole, ref, doc, copies, 1) diff --git a/B09_Estimation/B09_Estimation_Linked.py b/B09_Estimation/B09_Estimation_Linked.py index ab5c98588..81268fdab 100644 --- a/B09_Estimation/B09_Estimation_Linked.py +++ b/B09_Estimation/B09_Estimation_Linked.py @@ -17,7 +17,6 @@ from pathlib import Path from typing import Any from B09_Estimation import B09_Estimation_Doc_Run as dr -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Labor_Fixed as fixed from M02_MasterTemplete.M02_Item_Snapshot import ( @@ -26,7 +25,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json #: 원가 단가 목록에 오르는 자원 표 RESOURCE_TABLES = ("LB", "EQ", "MT", "MO") @@ -38,7 +37,7 @@ def used_keys(folder: Path) -> list[str]: if not isinstance(labor, dict): return [] docs = dr.docs_of(folder) # 사본 수식 문서 — 셈 기록의 자원 키(855-F B9-3) - snapshot = dr.load(bundle(folder), docs) + snapshot = dr.load((read_json(folder / PRICE_FILE) or {}), docs) values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} seen: list[str] = [] @@ -113,7 +112,7 @@ def frozen_rows(project_root: str | Path) -> dict[str, dict[str, Any]]: out: dict[str, dict[str, Any]] = {} for folder in _folders(project_root): - got = bundle(folder) # 841-1 미리 보기 덮개 + got = read_json(folder / PRICE_FILE) or {} for name, data in got.items(): if name.startswith("_") or not isinstance(data, dict): continue diff --git a/B09_Estimation/B09_Estimation_Prices.py b/B09_Estimation/B09_Estimation_Prices.py index ada70ecd6..b2be12480 100644 --- a/B09_Estimation/B09_Estimation_Prices.py +++ b/B09_Estimation/B09_Estimation_Prices.py @@ -1,12 +1,11 @@ """B09 자재 단가 책 · 수요 모음(PLAN 144 · 841-1) — 서버 단독(M01 을 읽는 곳은 여기 하나). -841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값 · -`B09_Estimation_Copy_Prices`). +841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책에서 걷음(B09 금액 = 사본을 M02 엔진으로 셈한 값). 책에 남는 것 = 자재단가대비표(4 자재대 · 관급자재대 단가 고르기) 자재 줄. 자재 단가 = 프로젝트 한 벌 — 원가산출에서 한 번 굳힘(`price_book.json`) · 값 = 사본 단가 기준 시점(795-4 · 구조물 지정 때 `단가.json` 자원 줄 · 없는 자원만 지금 M01 + - `now_keys`) · [단가 갱신] 때만 새로. + `now_keys`) · 다시 굳히지 않음(859-2 프로젝트 안 단가 갱신 없음). 줄 = 수요 따라(사용자 승인 ① · 10-9) — 엑셀 목록을 기본으로 깔지 않음: 연결된 사본이 부른 자재 키(`B09_Estimation_Linked` — 143-1 「연결된 사본」 원천 · 없으면 빈 표) + B08 총괄자재수량집계표 자재(M01 짝 없음 → 출처 빈칸 · 적용 단가는 사용자 입력) @@ -16,7 +15,6 @@ from __future__ import annotations -import json from decimal import Decimal from typing import Any @@ -103,58 +101,13 @@ def _convert(master, key: str) -> dict[str, Any]: return material_input(_row(master, key)) -def refresh_book( - keys: list[str], book: dict[str, Any] | None = None, frozen: dict[str, dict] | None = None -) -> dict[str, Any]: - """[단가 갱신] — 수요 키 전부를 지금 M01 값으로 새로 굳힘 · - M01 원본이 지워진 키(296) = 옛 책 줄 그대로(지우지도 바꾸지도 않음) · - `frozen` = 첫 굳힘(795-4) — 사본 단가 기준 시점 값 · 없는 자원 = 지금 값(`now_keys`).""" +def make_book(keys: list[str], frozen: dict[str, dict] | None = None) -> dict[str, Any]: + """첫 굳힘 — 수요 키 전부 · `frozen` = 사본 단가 기준 시점 값(795-4) · 없는 자원 = 지금 값 + (`now_keys`) · None = 지금 M01.""" master = basis(frozen) want = demand(master, keys) rows = {key: _convert(master, key) for key in want["materials"]} - old = (book or {}).get("rows") or {} - rows.update({key: old[key] for key in want["missing"] if key in old}) - return { - "made": utc_now_text(), - "rows": rows, - "labor_edition": labor_editions(keys), # 703-3 미리 보기 「노임 판 전 → 후」 - "now_keys": now_keys(frozen, list(rows)), - } - - -def labor_editions(keys: list[str]) -> dict[str, str]: - """노임 판(703-3) — 수요 노무 줄 구분(건설업 · 산림 …)마다 M01 `인력.json` 그 구분 `판`.""" - files, master = m01.loaded() - groups = (files.get("인력.json") or {}).get("구분") or {} - out: dict[str, str] = {} - for key in [k for k in keys if k.startswith("LB") and _row(master, k)]: - kind = str((_row(master, key) or {}).get("구분") or "") - if (groups.get(kind) or {}).get("판"): - out[kind] = str(groups[kind]["판"]) - return out - - -def book_diff(old: dict[str, Any] | None, new: dict[str, Any]) -> dict[str, int | bool]: - """두 책 견줌(저장 꼴 JSON) — 새 줄 · 바뀐 줄 수(203-1 · 703-3 · 자재 줄만).""" - new = json.loads(json.dumps(new, ensure_ascii=False)) - rows = (old or {}).get("rows") or {} - return { - "new": sum(key not in rows for key in new["rows"]), - "changed": sum(key in rows and rows[key] != row for key, row in new["rows"].items()), - } - - -def book_stale(book: dict[str, Any] | None, keys: list[str]) -> str | None: - """203-1 [업데이트] 배지 — 지금 M01 로 새로 굳힌 책(`refresh_book`)과 견줌 · 다른 것 한 줄(같으면 None).""" - if book is None: - return "단가 아직 안 굳힘" - # 저장 꼴(JSON)로 견줌 · M01 원본이 지워진 줄 = 옛 줄 그대로(낡음 까닭에서 빠짐 · 296) - diff = book_diff(book, refresh_book(keys, book)) - parts = [ - f"새 단가 줄 {diff['new']}" if diff["new"] else "", - f"M01 에서 바뀐 단가 {diff['changed']}" if diff["changed"] else "", - ] - return " · ".join(p for p in parts if p) or None + return {"made": utc_now_text(), "rows": rows, "now_keys": now_keys(frozen, list(rows))} def extend_book( @@ -163,7 +116,7 @@ def extend_book( """[저장] — 책에 없는 새 줄만 더함(있는 줄 · 계수 · 환율은 안 바꿈) · 책이 없으면 새로 굳힘 · 새 줄 값 = 사본 단가 기준 시점(795-4 · `frozen`) · 없는 자원만 지금 M01(`now_keys`).""" if book is None: - return refresh_book(keys, None, frozen or {}) + return make_book(keys, frozen or {}) master = basis(frozen) want = demand(master, keys) rows = dict(book["rows"]) diff --git a/B09_Estimation/B09_Estimation_Refresh.py b/B09_Estimation/B09_Estimation_Refresh.py deleted file mode 100644 index 85904206c..000000000 --- a/B09_Estimation/B09_Estimation_Refresh.py +++ /dev/null @@ -1,173 +0,0 @@ -"""B09 [단가 갱신] · [재생성](PLAN 795-4 · 옛 [업데이트] 703-3) — 사본 로직은 만든 때 그대로 · -[단가 갱신](기본 · 841-1) = 프로젝트 사본 자원 단가 줄(`B09_Estimation_Copy_Prices`) + 자재 단가 책만 - 지금 M01 값 · 미리 보기 `price_preview` = 바뀐 자원 · 총괄 전 → 후 · -[재생성](사용자가 따로) = 아래 옛 [업데이트] — 단가 책 다시 굳힘 + 원본이 바뀐 구조물 사본 [재적용]. - -미리 보기(`preview`) = 바뀌는 단가 줄(새 줄 + 바뀐 줄 · 지금 수요) · 다시 가져올 구조물 사본 - (연결된 것 중 원본이 바뀐 것만 · 원본 없음 = 그대로) · 지킬 고친 칸(덮개 칸 수 · 702-4 — - 재적용 · 새 판 뒤에도 남음) · 노임 판(굳힌 판 → 지금 M01 판 · 옛 책 = 굳힌 날) -적용(`reapply_changed` → 부르는 쪽이 수요 다시 → `prices.refresh_book`) — 사본 먼저(수요가 바뀜) · - 덮개(사용자 값)는 안 건드림 · 사본 하나가 막혀도 나머지는 함(막힌 것 = 알림). -M02 단가산출(SK · 719-2) — 구조물 · 서고 사본의 SK 수식 사본을 원본 층에서 다시 굳힘(같은 이름표 · - 같은 cover → B09 덮개 · 입력값 · 고른 자재 그대로 · 855-F B9-5) · - 서고 사본도 원본판이 다르면 다시 · - 미리 보기 `단가산출` = 바뀌는 SK 줄 [{사본, 이름, 키, 판(새 · 바뀜 · 빠짐)}]. -""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any - -from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation.B09_Estimation_Calc_Labor import COPY -from M02_MasterTemplete import M02_Item_Copy as item_copy -from M02_MasterTemplete import M02_Item_Sangeun as item_sk -from M02_MasterTemplete.M02_Item_Snapshot import MANIFEST_NAME, linked_snapshots, structures_dir -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, build_source, read_json - -REGEN = "재생성" # POST …/estimation/prices · preview 몸 `job`(795-4) - - -def _value(row: dict[str, Any] | None) -> Any: - return None if row is None else row.get("price", row.get("prices")) - - -def price_preview( - old: dict[str, Any] | None, - new: dict[str, Any], - before: dict, - after: dict, - cells: int, - copies: list[dict[str, Any]] | None = None, -) -> dict[str, Any]: - """[단가 갱신] 미리 보기(795-4 · 841-1) — {할일, 바뀐자원 [{키, 이름, 전, 후}](사본 자원 줄 + - 자재 단가 책), 전, 후(총괄 grand · 빈 줄 있으면 None), 대가 {전, 후}(일위대가 블록 합), 고친칸, - 노임판} · 사본(로직)은 안 바뀜.""" - was = json.loads(json.dumps((old or {}).get("rows") or {}, ensure_ascii=False)) - now = json.loads(json.dumps(new["rows"], ensure_ascii=False)) - rows = [ - {"키": key, "이름": row.get("name") or "", "전": _value(was.get(key)), "후": _value(row)} - for key, row in now.items() - if was.get(key) != row - ] - - def grand(sheets: dict) -> Any: - return (((sheets.get("total") or {}).get("subtotals")) or {}).get("grand") - - def daega(sheets: dict) -> float: - return sum(float(b.get("sum") or 0) for b in sheets.get("daega_blocks") or []) - - seen = {r["키"] for r in copies or []} - return { - "할일": "단가갱신", - "바뀐자원": [*(copies or []), *(r for r in rows if r["키"] not in seen)], - "전": grand(before), - "후": grand(after), - "대가": {"전": daega(before), "후": daega(after)}, - "고친칸": cells, - "노임판": { - "전": edition_text((old or {}).get("labor_edition")), - "후": edition_text(new.get("labor_edition")), - }, - } - - -def changed_copies(root: str | Path) -> list[dict[str, Any]]: - """연결된 구조물 사본 중 원본(층 · 마스터)이 바뀐 것 `[{폴더, 이름}]`.""" - linked = {one["폴더"] for one in linked_snapshots(root).values()} - return [ - {"폴더": it["폴더"], "이름": it["이름"] or it["폴더"]} - for it in item_copy.list_items(root) - if it["폴더"] in linked and it["마스터바뀜"] - ] - - -def _sks(labor: Any) -> dict[str, dict]: - copies = (labor or {}).get("참조사본") or {} - return {rid: doc for rid, doc in copies.items() if item_sk.is_sangeun(doc)} - - -def sk_lines(old: Any, new: Any, where: str) -> list[dict[str, str]]: - """사본 하나 전후 일위대가.json → 바뀌는 SK 줄(SK 문서 · 수식 사본이 다름).""" - was, now = _sks(old), _sks(new) - out = [] - for rid in sorted(set(was) | set(now)): - a, b = was.get(rid) or {}, now.get(rid) or {} - if a == b: - continue - mark = "새" if not a else "빠짐" if not b else "바뀜" - out.append({"사본": where, "이름": (b or a).get("이름") or "", "키": rid.rsplit("|")[-1], - "판": mark}) # fmt: skip - return out - - -def sk_changes(root: str | Path, copies: list[dict], libs: list[tuple]) -> list[dict[str, str]]: - """다시 가져올 구조물 사본(`changed_copies`) · 서고 사본(`library.changed`)의 바뀌는 SK 줄.""" - out = [] - for one in copies: - folder = structures_dir(root) / one["폴더"] - try: - fresh = build_source((read_json(folder / MANIFEST_NAME) or {})["원본"]) - except (LookupError, ValueError, KeyError): - continue - out += sk_lines(read_json(folder / LABOR_FILE), fresh.get(LABOR_FILE), one["이름"]) - for folder, manifest, files, origin in libs: - name = str(origin.get("name") or folder.name) - out += sk_lines(read_json(folder / LABOR_FILE), files.get(LABOR_FILE), name) - return out - - -def cover_cells(cover: dict[str, Any] | None) -> int: - """고친 칸 수 — 덮개 칸(품 · 수량 · 단가) · 복사본 표지 뺌.""" - return sum( - len(cell) for lines in (cover or {}).values() for cid, cell in lines.items() if cid != COPY - ) - - -def edition_text(editions: dict[str, str] | None) -> str: - return " · ".join(f"{kind} {day[:7]}" for kind, day in sorted((editions or {}).items())) - - -def preview( - root: str | Path, book: dict[str, Any] | None, keys: list[str], cover: dict | None -) -> dict[str, Any]: - diff = prices.book_diff(book, prices.refresh_book(keys, book)) - copies, libs = changed_copies(root), library.changed(root) - lib_names = [{"폴더": f.name, "이름": str(o.get("name") or f.name)} for f, _m, _f, o in libs] - before = (book or {}).get("labor_edition") - made = str((book or {}).get("made") or "")[:10] - return { - "단가줄": diff["new"] + diff["changed"], - "새줄": diff["new"], - "바뀐줄": diff["changed"], - "사본": copies + lib_names, - "단가산출": sk_changes(root, copies, libs), - "고친칸": cover_cells(cover), - "노임판": { - "전": edition_text(before) if before else (f"굳힌 날 {made}" if made else "안 굳힘"), - "후": edition_text(prices.labor_editions(keys)), - }, - } - - -def reapply_changed(root: str | Path, who: dict[str, Any] | None = None) -> dict[str, list]: - """원본이 바뀐 연결 사본 재적용 · 서고 사본 다시 굳힘 — - `{다시: [이름], 막힘: [이름 — 까닭]}`.""" - done, stuck = [], [] - for one in library.changed(root): - name = str(one[3].get("name") or one[0].name) - try: - library.refresh_copy(root, one) - done.append(name) - except (LookupError, ValueError, KeyError, OSError) as error: - stuck.append(f"{name} — {error}") - for one in changed_copies(root): - try: - item_copy.reapply(root, one["폴더"], who) - done.append(one["이름"]) - except (LookupError, ValueError, KeyError, OSError) as error: - stuck.append(f"{one['이름']} — {error}") - return {"다시": done, "막힘": stuck} diff --git a/B09_Estimation/B09_Estimation_Router.py b/B09_Estimation/B09_Estimation_Router.py index eeb7b3c45..24a8acab5 100644 --- a/B09_Estimation/B09_Estimation_Router.py +++ b/B09_Estimation/B09_Estimation_Router.py @@ -10,14 +10,6 @@ [초기화](요구 298-2 C1 · C3 · C4 · C5 · 301 · 본문 없음) — 사용자 값 전부(내역 · 자재 · 원가 · 공기) · 단가 책 · `estimation` 설정 구획 지움 · 서고 사본 정리 · 견적서 파일 남김 → 답 = GET 꼴(기준 = 지금 B08 저장본 + 지금 M01 단가) · 단계 = [저장]과 같음 - POST /api/projects/{id}/estimation/prices {user?, job?} - [단가 갱신](795-4 · 기본) — 수요 단가 전부를 지금 M01 값으로 새로 굳힘 · 사본(로직) 그대로 · - job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3 · `B09_Estimation_Refresh`) 먼저 · - user = 화면 캐시(296 · 지운 줄 · 그 사본은 수요에서 뺌 · 저장은 안 함) · - M01 원본이 지워진 줄 = 굳힌 값 그대로 · 덮개 그대로 · 답 notes 첫 줄 = 바뀐 수 - POST /api/projects/{id}/estimation/prices/preview {user?, job?} - 미리 보기(쓰지 않음) — 단가 갱신 = 바뀐 자원 · 총괄 금액 전 → 후(795-4) · - 재생성 = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판(703-3) POST /api/projects/{id}/estimation/calc {user} 조작 중 서버 셈(702-3 · 단가연결 즉시 금액) — 화면 캐시로 GET 꼴 셈 · 저장 안 함 POST /api/projects/{id}/estimation/logic-preview {code, given, rate, picks} @@ -73,13 +65,11 @@ from B08_Quantity.B08_Quantity_Router_Material import once as material_once from B08_Quantity.B08_Quantity_Router_Milestone import read_data as read_milestone from B08_Quantity.B08_Quantity_Router_Milestone import site_info from B09_Estimation import B09_Estimation_Bill_Library as library -from B09_Estimation import B09_Estimation_Copy_Prices as copy_prices from B09_Estimation import B09_Estimation_Daega_Paste as daega_paste from B09_Estimation import B09_Estimation_Daega_Personal as personal from B09_Estimation import B09_Estimation_Linked as linked from B09_Estimation import B09_Estimation_Past as past from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun from B09_Estimation import B09_Estimation_Sangeun_Cover as sg_cover from B09_Estimation import B09_Estimation_Store as store @@ -246,12 +236,10 @@ async def payload( draft: dict[str, Any] | None = None, reuse_b08: bool = False, keys: list[str] | None = None, - book: dict[str, Any] | None = None, ) -> dict[str, Any]: - """셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만 · - book = 안 쓴 단가 책(795-4 미리 보기 · 없으면 저장본).""" + """셈 답 한 벌 — keys = 방금 센 단가 수요(같은 저장 값 · [저장]) · 마스터 자국은 한 번만.""" with m01_cache.steady(): - return await _payload(project_id, root, draft, reuse_b08, keys, book) + return await _payload(project_id, root, draft, reuse_b08, keys) async def _payload( @@ -260,7 +248,6 @@ async def _payload( draft: dict[str, Any] | None, reuse_b08: bool, keys: list[str] | None, - book: dict[str, Any] | None = None, ) -> dict[str, Any]: notes: list[str] = [] b08 = await _b08_for(project_id, notes, reuse_b08) @@ -269,7 +256,7 @@ async def _payload( notes.append( "연결된 구조물 조합 사본 없음 — 노무 · 경비 · 중기 단가 줄은 사본이 연결되면 생김" ) - book = book or await asyncio.to_thread(store.read_book, root) + book = await asyncio.to_thread(store.read_book, root) frozen = await asyncio.to_thread(linked.frozen_rows, root) # 795-4 사본 단가 기준 시점 inputs = await asyncio.to_thread(prices.build_inputs, book, keys, b08["materials"], frozen) if late := inputs["now"]: @@ -292,9 +279,6 @@ async def _payload( return { "inputs": inputs, "user": user, - "book": {"made": book.get("made")} if book else None, - # 203-1 [업데이트] 배지 까닭(지금 M01 과 다른 것 한 줄 · 같으면 None) - "stale": await asyncio.to_thread(prices.book_stale, book, keys), "sheets": sheets, "rate_candidates": rate_candidates(), "rate_table": rate_table(), @@ -365,67 +349,6 @@ async def estimation_reset(project_id: UUID) -> dict[str, Any]: return await payload(project_id, root) -@router.post("/{project_id}/estimation/prices") -async def refresh_prices( - project_id: UUID, - body: dict[str, Any] | None = Body(None), - session: dict[str, Any] = Depends(verify_session), -) -> dict[str, Any]: - """[단가 갱신](795-4 · 841-1) — 프로젝트 사본 자원 단가 줄 + 자재 단가 책을 지금 M01 값으로 · - 사본 로직 · 덮개 그대로 · job 「재생성」 = 원본이 바뀐 구조물 사본 재적용(703-3) 먼저.""" - root = await _project_root(project_id) - raw = (body or {}).get("user") - draft = store.clean_user(raw) if isinstance(raw, dict) else None # 296 화면 캐시(저장 안 함) - regen = (body or {}).get("job") == refresh.REGEN - again = {"다시": [], "막힘": []} - if regen: - again = await asyncio.to_thread(refresh.reapply_changed, root, importer(session)) - news, changed = await asyncio.to_thread(copy_prices.refreshed, root) - await asyncio.to_thread(copy_prices.write, news) - keys = await _demand(root, draft) - old = await asyncio.to_thread(store.read_book, root) - book = await asyncio.to_thread(prices.refresh_book, keys, old) - await asyncio.to_thread(store.write_book, root, book) - out = await payload(project_id, root, draft) - diff = prices.book_diff(old, book) - kept = draft or out.get("user") or {} - cells = refresh.cover_cells(kept.get("daega_cover")) + refresh.cover_cells(kept.get("sg_cover")) - head = f"재생성 — 구조물 사본 {len(again['다시'])} 다시 가져옴 · " if regen else "단가 갱신 — " - out["notes"] = [ - f"{head}사본 {len(news)} · 자원 {len(changed)} · 자재 단가 줄 " - f"{diff['new'] + diff['changed']} 바뀜 · 고친 칸 {cells} 그대로", - *(f"재적용 못 함 {why}" for why in again["막힘"]), - *(out.get("notes") or []), - ] - return out - - -@router.post("/{project_id}/estimation/prices/preview") -async def refresh_preview( - project_id: UUID, body: dict[str, Any] | None = Body(None) -) -> dict[str, Any]: - """미리 보기 — 단가 갱신(795-4) = 바뀐 자원 · 총괄 금액 전 → 후 · - 재생성(703-3) = 바뀌는 단가 줄 · 다시 가져올 사본 · 지킬 고친 칸 · 노임 판.""" - root = await _project_root(project_id) - raw = (body or {}).get("user") - draft = store.clean_user(raw) if isinstance(raw, dict) else None - keys = await _demand(root, draft) - book = await asyncio.to_thread(store.read_book, root) - user = draft if draft is not None else await asyncio.to_thread(store.read_user, root) - if (body or {}).get("job") == refresh.REGEN: - return await asyncio.to_thread(refresh.preview, root, book, keys, user.get("daega_cover")) - new = await asyncio.to_thread(prices.refresh_book, keys, book) - news, changed = await asyncio.to_thread(copy_prices.refreshed, root) - before = await payload(project_id, root, draft, True, keys) - token = copy_prices.OVER.set(news) # 841-1 사본 새 단가 = 덮개로만(파일 안 씀) - try: - after = await payload(project_id, root, draft, True, keys, new) - finally: - copy_prices.OVER.reset(token) - cells = refresh.cover_cells(user.get("daega_cover")) + refresh.cover_cells(user.get("sg_cover")) - return refresh.price_preview(book, new, before["sheets"], after["sheets"], cells, changed) - - @router.post("/{project_id}/estimation/calc") async def calc_estimation(project_id: UUID, body: dict[str, Any] = Body(...)) -> dict[str, Any]: """702-3 조작 중 서버 셈 — 화면 캐시(user)로 GET 꼴 셈 · 저장 안 함 · 단가 = 굳힌 책 diff --git a/B09_Estimation/B09_Estimation_Sangeun.py b/B09_Estimation/B09_Estimation_Sangeun.py index 8c3b26d16..c4c9515f7 100644 --- a/B09_Estimation/B09_Estimation_Sangeun.py +++ b/B09_Estimation/B09_Estimation_Sangeun.py @@ -49,7 +49,6 @@ from B09_Estimation import B09_Estimation_Sangeun_Sum as ss from B09_Estimation import B09_Estimation_Sangeun_Text as st from B09_Estimation import B09_Estimation_Sheet as sheet from B09_Estimation.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total -from B09_Estimation.B09_Estimation_Copy_Prices import bundle from B09_Estimation.B09_Estimation_Store import ref_rows from M01_MasterData import M01_MasterData_Store_Combo as combo_store from M02_MasterTemplete import M02_Item_Prices as item_prices @@ -60,7 +59,7 @@ from M02_MasterTemplete.M02_Item_Snapshot import ( linked_snapshots, structures_dir, ) -from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, read_json +from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json PARTS = ("labor", "material", "expense") @@ -114,7 +113,7 @@ def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[d return [] docs = dr.docs_of(folder) if docs is None else docs if whole is None: - whole = dr.load(bundle(folder), docs) + whole = dr.load((read_json(folder / PRICE_FILE) or {}), docs) values = read_json(folder / VALUES_FILE) or {} picks = read_json(folder / PICKS_FILE) or {} copies = labor.get("참조사본") or {} @@ -557,7 +556,7 @@ def collect( solver = Solver(supply) for owner, folder in entries: docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3) - whole = solver.shelf.put_whole(bundle(folder), docs) + whole = solver.shelf.put_whole((read_json(folder / PRICE_FILE) or {}), docs) for src in rows_of(folder, whole, docs): solver.add(whole, src, owner) hand_keys: dict[str, str] = {} diff --git a/B09_Estimation/B09_Estimation_Store.py b/B09_Estimation/B09_Estimation_Store.py index 0247f15c3..c4c5e5fbc 100644 --- a/B09_Estimation/B09_Estimation_Store.py +++ b/B09_Estimation/B09_Estimation_Store.py @@ -2,7 +2,7 @@ price_book.json 굳힌 자재 단가 한 벌 {"made": 시각, "rows": {키: 입력 줄}}(841-1 자재만 · 옛 책의 노무 · 기계 줄 · 계수 · 환율은 안 읽음) - — [단가 갱신] 때만 M01 로 새로 · + — 처음 굳힌 뒤 다시 안 굳힘(859-2) · [저장] 때 책에 없는 새 줄만 더함(있는 줄 안 바꿈) user_values.json 사용자 값 {"materials": {자재 키: {applied?, supply?, quote?, quote_page?, pick?}}, "estimate": {…}, diff --git a/B09_Estimation/B09_Estimation_UI_Check.ts b/B09_Estimation/B09_Estimation_UI_Check.ts index eecf9d837..8ff561297 100644 --- a/B09_Estimation/B09_Estimation_UI_Check.ts +++ b/B09_Estimation/B09_Estimation_UI_Check.ts @@ -1,27 +1,15 @@ /* ============================================================================= * B09_Estimation_UI_Check.ts - * B09 좌측 「데이터 점검」 묶음(PLAN 203-1) — [단가 갱신] · 연결 점검(옛 「연결 점검」 탭 내용). + * B09 좌측 「내역 점검」 묶음(PLAN 203-1) — 연결 점검(옛 「연결 점검」 탭 내용 · 859-2 [단가 갱신] 걷음). * - * [단가 갱신](795-4 · 옛 [업데이트] · 841-1) = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 서버가 낡았다고 보면(`payload.stale` 까닭 한 줄) - * 단추에 점 배지(`is-pending`) · 굳힌 시각 · 까닭 = 공용 호버 - * 미리 보기 고리 = 누름을 먼저 잡아 POST …/estimation/prices/preview(화면 캐시) → - * 「총괄 금액 전 → 후 · 바뀐 자원」 창 → [적용] = 원래 단추 일(단가만 · 사본 · 덮개 그대로) · - * 창의 [재생성] = 재생성 미리 보기(703-3 · 다시 가져올 사본 · 고친 칸 · 노임 판) → [적용] = - * `job: 재생성`(사본 재적용 + 단가) · 닫기 = 안 함 * 연결 점검 = 「빈 줄 n」(설계내역서 금액 모르는 줄 · 안내 · 집계표와 같은 수 · 701-2) 목록 + * 그 밖 확인 목록(일위대가 · 단가산출 · 재료 등 · 탭 · 키마다 하나)(누르면 그 탭 그 줄로 · 까닭 = 공용 호버) + 서버 알림 · M01 에 없는 키 * ========================================================================== */ -import { API_BASE_URL } from "@config/config_frontend"; -import { createButton, showToast } from "@ui/ui_template_elements"; import { attachHoverInfo } from "@ui/ui_template_hover_info"; -import { openModal } from "@ui/ui_template_modal"; import { createBadge } from "@ui/ui_template_badge"; import { createText } from "@ui/ui_template_text"; import type { Row } from "./B09_Estimation_Calc_Base"; -import { dateTimeText } from "../common_util/common_util_time"; -import { readState } from "../A00_Common/b_page_state"; -import { currentProjectId } from "../A00_Common/b_project_switch"; import { blankRows, tabName, type Link, type TabId } from "./B09_Estimation_UI_Tabs"; export interface CheckItem { @@ -63,131 +51,14 @@ export function checkItems( return { items, others, notes }; } -/** [단가 갱신] 호버 글 — 굳힌 시각 + 낡은 까닭 */ -export function refreshTip(payload: Row | null): string { - const made = payload?.book?.made; - const when = made ? `단가 굳힘 ${dateTimeText(String(made))}` : "단가 아직 안 굳힘"; - const stale = payload?.stale; - return `${when} · 누르면 미리 보기 → [적용] = 프로젝트 사본 자원 단가 · 자재 단가만 지금 M01 값 · 사본(로직) · 고친 칸 그대로 · 로직까지 새로 = 미리 보기의 [재생성]${stale ? ` · 단가 갱신 가능 — ${stale}` : ""}`; -} - -/** [재생성] 미리 보기 글 줄(703-3 옛 [업데이트]) */ -export function previewLines(got: Row): string[] { - const copies: Row[] = got.사본 || []; - const sks: Row[] = got.단가산출 || []; - const edition = got.노임판 || {}; - return [ - `바뀌는 자재 단가 줄 ${got.단가줄 ?? 0}(새 줄 ${got.새줄 ?? 0} · 값 바뀜 ${got.바뀐줄 ?? 0})`, - `다시 가져올 사본 ${copies.length}${copies.length ? ` — ${copies.map((c) => c.이름).join(" · ")}` : ""}`, - ...(sks.length - ? [`M02 단가산출 바뀜 ${sks.length} — ${sks.map((s) => `${s.이름}(${s.판})`).join(" · ")}`] - : []), - `고친 칸 ${got.고친칸 ?? 0} 지킴(일위대가 덮개 · 새 판 · 재적용 뒤에도 그대로)`, - `노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`, - ]; -} - -const won = (v: unknown): string => (v == null ? "—" : Number(v).toLocaleString("ko-KR")); - -/** 자원 단가 값 — 노임 · 기계 = 수 · 자재 = 출처별 값 */ -function priceText(v: unknown): string { - if (v == null) return "새 줄"; - if (typeof v !== "object") return won(v); - const got = Object.entries(v as Row).filter(([, x]) => x != null); - return got.length ? got.map(([k, x]) => `${k} ${won(x)}`).join(" / ") : "—"; -} - -/** [단가 갱신] 미리 보기 글 줄(795-4) — 총괄 금액 전 → 후 · 바뀐 자원 */ -export function priceLines(got: Row): string[] { - const rows: Row[] = got.바뀐자원 || []; - const edition = got.노임판 || {}; - const shown = 30; - return [ - `총괄 금액 ${won(got.전)} → ${won(got.후)} 원 · 대가 합 ${won(got.대가?.전)} → ${won(got.대가?.후)} 원`, - `바뀐 자원 ${rows.length}(사본 자원 단가 · 자재 단가)`, - ...rows - .slice(0, shown) - .map((r) => `· ${r.이름 || r.키} ${priceText(r.전)} → ${priceText(r.후)}`), - ...(rows.length > shown ? [`… 외 ${rows.length - shown}`] : []), - `고친 칸 ${got.고친칸 ?? 0} · 구조물 사본(로직) 그대로 — 로직까지 새로는 [재생성]`, - `노임 판 ${edition.전 || "—"} → ${edition.후 || "—"}`, - ]; -} - -const REGEN = "재생성"; - -/** [단가 갱신] 누름 앞 미리 보기 — [적용] 이면 원래 단추 일(`data-b09-job` = 할일) · 닫기 = 안 함 · - * [재생성] = 재생성 미리 보기 → [적용] = 사본 재적용 + 단가(795-4 · 사용자가 따로 누를 때만) */ -function attachPreview(refresh: HTMLElement, payload: () => Row | null): void { - let pass = false; - const open = (job?: string): void => { - const projectId = currentProjectId(); - const user = readState("b09-estimation", projectId) ?? payload()?.user ?? {}; - void fetch(`${API_BASE_URL}/projects/${projectId}/estimation/prices/preview`, { - method: "POST", - credentials: "include", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(job ? { user, job } : { user }), - }) - .then(async (response) => { - const got = (await response.json()) as Row; - if (!response.ok) throw new Error(String(got?.detail ?? response.status)); - openModal({ - title: job ? "재생성 미리 보기" : "단가 갱신 미리 보기", - closeLabel: "닫기", - width: "40rem", - mount: (body, close, head) => { - const apply = createButton({ - label: "적용", - variant: "filled", - onClick: () => { - close(); - pass = true; - if (job) refresh.dataset.b09Job = job; - refresh.click(); - delete refresh.dataset.b09Job; - }, - }); - apply.dataset.b09RefreshApply = ""; - if (!job) { - const regen = createButton({ - label: REGEN, - variant: "ghost", - onClick: () => (close(), open(REGEN)), - }); - regen.dataset.b09Regen = ""; - head.append(regen); - } - head.append(apply); - const lines = job ? previewLines(got) : priceLines(got); - body.append(...lines.map((line) => createText(line))); - }, - }); - }) - .catch((error) => showToast(`미리 보기 못 함 — ${String(error)}`, "error")); - }; - refresh.addEventListener( - "click", - (event) => { - if (pass) return void (pass = false); - event.stopImmediatePropagation(); - open(); - }, - true, - ); -} - export interface CheckPanel { /** 묶음 안 연결 점검 자리 */ list: HTMLElement; draw: (payload: Row, sheets: Row) => void; } -export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => void): CheckPanel { - let payload: Row | null = null; +export function createCheckPanel(goto: (link: Link) => void): CheckPanel { let items: CheckItem[] = []; - attachHoverInfo(refresh, () => refreshTip(payload)); - attachPreview(refresh, () => payload); const box = document.createElement("div"); box.className = "b09-check"; attachHoverInfo(box, (row) => items[Number(row.dataset.i)]?.why, "[data-i]"); @@ -219,8 +90,6 @@ export function createCheckPanel(refresh: HTMLElement, goto: (link: Link) => voi }; const draw = (next: Row, sheets: Row): void => { - payload = next; - refresh.classList.toggle("is-pending", Boolean(next.stale)); const made = checkItems(sheets, next); items = [...made.items, ...made.others]; const blank = [ diff --git a/B09_Estimation/B09_Estimation_UI_Page.css b/B09_Estimation/B09_Estimation_UI_Page.css index d008489e1..4f9011439 100644 --- a/B09_Estimation/B09_Estimation_UI_Page.css +++ b/B09_Estimation/B09_Estimation_UI_Page.css @@ -143,28 +143,6 @@ html.is-bm-route .b09-estimation > .b09-estimation__tabs:first-child { background: color-mix(in srgb, var(--color-warning) 22%, var(--color-canvas)); } -/* 203-1 좌측 「데이터 점검」 — [업데이트] 필요 = 단추 위 점 배지(B05 [3D 업데이트] 꼴) */ -.b09-options .ui-btn.is-pending { - position: relative; - border-color: var(--color-warning); -} - -.b09-options .ui-btn.is-pending::after { - content: ""; - position: absolute; - top: 4px; - right: 4px; - width: 6px; - height: 6px; - border-radius: 50%; - background: var(--color-warning); -} - -/* 122 데이터 점검 [업데이트] — 제목 아래 틈 = 카드 왼쪽 여유와 같게(공용 카드 틈 8 + 4) */ -.b09-options [data-b09-refresh] { - margin-top: var(--spacing-4); -} - /* 연결 점검 목록 — 이름 · 탭(작게) · 알림 글 */ .b09-check__head, .b09-check__note { diff --git a/B09_Estimation/B09_Estimation_UI_Shell.ts b/B09_Estimation/B09_Estimation_UI_Shell.ts index 3321656c3..76ff16436 100644 --- a/B09_Estimation/B09_Estimation_UI_Shell.ts +++ b/B09_Estimation/B09_Estimation_UI_Shell.ts @@ -7,7 +7,7 @@ * 짝 계산(`…_Calc_*.ts`)으로 바로 다시 셈 · 새 산근(로직 연결) = 뒤에서 서버 셈(702-3 · `…_UI_Live`) · * [저장](702-3 · 왼쪽 아래 [초기화] 옆) = PUT → 서버 정본으로 다시 셈 · 저장 안 하고 단계 옮김 · [>] = 물음(저장 · 버림 · 머묾) * [>] = 물음 → POST …/estimation/complete(단계 6 완료) → `DRAFT.next`(인쇄 미리보기 · 초안) · 실패면 머묾 - * [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값 · [단가 갱신] = POST …/prices(795-4) + * [초기화](요구 298-2) = 확인 창 → POST …/estimation/reset(사용자 값 · 단가 책 지움 · 견적서 남김) → 셈 값 * 호표 칸 누름 = 그 탭 그 줄로 이동 · 자동 저장 없음 * ========================================================================== */ @@ -338,14 +338,8 @@ export function renderB09Estimation(root: HTMLElement): void { show(current); }; - // keep = 화면 캐시 그대로(296 [업데이트] — 지운 줄 · 고친 칸을 안 되살림) · 참 = 성공 - const run = async ( - path: string, - method: string, - done: string, - init?: Row, - keep = false, - ): Promise => { + // 참 = 성공 + const run = async (path: string, method: string, done: string, init?: Row): Promise => { if (!projectId) return false; showLoadingOverlay(); try { @@ -353,8 +347,8 @@ export function renderB09Estimation(root: HTMLElement): void { method, ...(init ? { body: JSON.stringify(init) } : {}), }); - if (!keep) clearState("b09-estimation", projectId); - apply(next, !keep); + clearState("b09-estimation", projectId); + apply(next, true); showToast(done, "success"); return true; } catch (error) { @@ -372,21 +366,7 @@ export function renderB09Estimation(root: HTMLElement): void { : Promise.resolve(true); DRAFT.save = saveChanged; // 초안 [인쇄 미리보기] = 저장 뒤 이동(506-3) DRAFT.blocked = () => (payload ? unfinished(sheets) : null); // 701-3 인쇄 · 확정 = 빈 줄 0 - // 795-4 [단가 갱신] = 값만 · 미리 보기 창 [재생성] = `data-b09-job`(B09_Estimation_UI_Check) - const refresh = createButton({ - label: "단가 갱신", - variant: "ghost", - onClick: () => - void run( - "/estimation/prices", - "POST", - "단가를 지금 M01 값으로 새로 굳혔습니다.", - { user, ...(refresh.dataset.b09Job ? { job: refresh.dataset.b09Job } : {}) }, - true, - ), - }); - refresh.dataset.b09Refresh = ""; - const check = createCheckPanel(refresh, (link) => show(link.tab, link.key)); + const check = createCheckPanel((link) => show(link.tab, link.key)); // 298-2 [초기화] — 내역 · 단가 · 공기 · 요율 등 사용자 값 · 설정 모두 지움 → B08 수량 셈 값(견적서 파일 남김) const reset = createButton({ label: L("Common_Btn_Reset"), @@ -413,7 +393,7 @@ export function renderB09Estimation(root: HTMLElement): void { save.dataset.b09Save = ""; // 카드 = 좌측 패널 공용 카드(269 · 「구조물 배치」 양식) const section = createPanelCard("내역 점검", true); // 311 기본 접힘 - section.append(refresh, check.list); + section.append(check.list); // 303-1 · 304-1 하단 고정 줄 — [박스보기|호표보기] · [하이퍼링크|팝업] · 초안 단추 · [?][<][>][초기화] const actions = createDock([save, reset], () => isGroupTab(current) && show(current)); const left = document.createElement("div"); diff --git a/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts b/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts index d10a67f4f..7b8d22aee 100644 --- a/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts +++ b/B09_Estimation/B09_Estimation_UI_Tabs_Base.ts @@ -63,7 +63,7 @@ export const buildLabor: TabBuild = ({ sheets }) => priceList( sheets.labor || [], "단가(원/인)", - "대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 [단가 갱신]", + "대가 · 산근이 쓰는 노임 = 프로젝트 사본(M02) 값 나열 · 새 값은 구조물 다시 지정", ); export const buildExpense: TabBuild = () => gone(priceList([], "기준가(천원)", "").columns); @@ -290,7 +290,7 @@ export const buildMachine: TabBuild = ({ sheets }): TabTable => { ], rows, frozen: 2, - hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 [단가 갱신]", + hint: "대가 · 산근이 쓰는 기계 시간당 = 프로젝트 사본(M02 단가산출) 값 나열 · 새 값은 구조물 다시 지정", }; }; diff --git a/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts b/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts index 35096f463..27ac1eb34 100644 --- a/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts +++ b/B09_Estimation/B09_Estimation_UI_Tabs_Sangeun_Sheet.ts @@ -287,7 +287,7 @@ function blockCard(ctx: TabContext, block: Row, noOf: Record): H ? [ edit, createText( - `품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · [단가 갱신] · [재생성] 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`, + `품 · 단가 칸을 두 번 눌러 고침 · 색 칸 = ${TAG}(이 공사만 · 구조물 다시 지정 뒤에도 남음) · 우클릭 [${BACK}으로] · [저장] 때 서버가 다시 셈`, "muted", ), ] diff --git a/resources/tester/test_144_b09_skeleton.py b/resources/tester/test_144_b09_skeleton.py index 5e5bb8f76..f3234c19a 100644 --- a/resources/tester/test_144_b09_skeleton.py +++ b/resources/tester/test_144_b09_skeleton.py @@ -52,7 +52,7 @@ def test_길_셋(): routes = {(r.path, tuple(sorted(r.methods))) for r in router_mod.router.routes} assert ("/api/projects/{project_id}/estimation", ("GET",)) in routes assert ("/api/projects/{project_id}/estimation", ("PUT",)) in routes - assert ("/api/projects/{project_id}/estimation/prices", ("POST",)) in routes + assert ("/api/projects/{project_id}/estimation/prices", ("POST",)) not in routes # 859-2 main = (ROOT / "main.py").read_text(encoding="utf-8") assert "app.include_router(b09_estimation_router" in main @@ -79,7 +79,7 @@ def test_사용자_값_다듬기_저장_자리(tmp_path): def test_841_1_단가_책_자재만(): """841-1 — 노무 · 기계 · 운전사 · 연료 · 환율은 책 밖(B09 금액 = 사본 M02 엔진 값) · 자재만 굳힘.""" - book = prices.refresh_book(["EQ000004", "LB000048", "MT000401", "MO000002"]) + book = prices.make_book(["EQ000004", "LB000048", "MT000401", "MO000002"]) rows = book["rows"] assert set(rows) == {"MT000401", "MO000002"} and "driver_factor" not in book assert rows["MO000002"]["prices"]["유가"] > 0 @@ -109,7 +109,6 @@ def test_연결_없으면_빈_표와_연결_없음(tmp_path, monkeypatch): ("compare", "b08:cement"), ] assert any("연결된 구조물 조합 사본 없음" in n for n in body["notes"]) - assert body["book"] is None # GET 은 아무것도 쓰지 않음 assert not (tmp_path / "B09_Estimation").exists() diff --git a/resources/tester/test_203_1_b09_data_check.py b/resources/tester/test_203_1_b09_data_check.py index 5e09a2605..68b609e98 100644 --- a/resources/tester/test_203_1_b09_data_check.py +++ b/resources/tester/test_203_1_b09_data_check.py @@ -1,13 +1,11 @@ """203-1 B09 좌측 「데이터 점검」 묶음(사용자 60번). -- 묶음 이름 = 데이터 점검 · 안 설명 글 없음(굳힌 시각 · 까닭 = [업데이트] 공용 호버) -- [단가 갱신] → [업데이트] · 낡으면(서버 `book_stale` = 지금 M01 로 굳힌 책과 다름) 점 배지(is-pending) +- 묶음 이름 = 내역 점검 · [단가 갱신] · 낡음 점 배지 없음(859-2) - 「연결 점검」 탭 내용 = 묶음 안 목록(누르면 그 탭 그 줄) · 위 탭 줄에서 뺌 - 701-2 첫 화면 = 설계내역서 · 목록 머리 「빈 줄 n」 = 설계내역서 금액 모르는 줄(줄마다 하나 · 까닭 모음) · 그 밖(호표 · 재료) = 「그 밖 확인 n곳」(탭 · 키마다 하나) """ -import json import sys from pathlib import Path @@ -15,24 +13,12 @@ ROOT = Path(__file__).resolve().parents[2] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 from resources.tester.helper_b09_group_cards import TABS, run # noqa: E402 CHECK = "B09_Estimation/B09_Estimation_UI_Check.ts" SHELL = (ROOT / "B09_Estimation/B09_Estimation_UI_Shell.ts").read_text("utf-8") -def test_묶음_이름_단추_글_설명_없음(): - assert ( - 'createPanelCard("내역 점검", true)' in SHELL and "원가 단가" not in SHELL - ) # 269 공용 카드 - assert 'label: "단가 갱신",' in SHELL and 'label: "업데이트"' not in SHELL # 795-4 이름 - # 옛 굳힌 시각 안내 글(made) 없음 · 묶음 = 제목 · [단가 갱신] · 연결 점검 - assert "made.textContent" not in SHELL and "b09-estimation__hint" not in SHELL - assert "section.append(refresh, check.list);" in SHELL # 제목 = 공용 카드(269) - assert "check.draw(payload, sheets);" in SHELL - - def test_연결_점검_탭_없음_첫_화면_설계내역서(): out = run( [TABS], @@ -50,8 +36,7 @@ def test_좌측_목록_이동_호버_배지(): [TABS, CHECK], """ const moves = []; -const refresh = document.createElement("button"); -const panel = createCheckPanel(refresh, (link) => moves.push(link)); +const panel = createCheckPanel((link) => moves.push(link)); const sheets = { bill: { rows: [ { kind: "title", cost: "direct", key: "sec:1", name: "토공사", sum: null }, @@ -68,11 +53,10 @@ const sheets = { { tab: "material", key: "MT9", name: "모래", why: "단가 없음" }, ], }; -const payload = { book: { made: "2026-10-01T09:00:00" }, stale: "M01 에서 바뀐 단가 2", +const payload = { notes: ["B08 자재 집계표 못 읽음"], inputs: { missing: ["EQ1", "LB2"] } }; panel.draw(payload, sheets); const view = () => ({ - pending: refresh.classList.contains("is-pending"), texts: panel.list.children.map((c) => c.text), rows: [1, 3].flatMap((n) => (panel.list.children[n]?.children ?? []).map((r) => [r.dataset.i, r.className, r.text])), @@ -81,19 +65,15 @@ const a = view(); const blankBox = panel.list.children[1]; const rowsBox = panel.list.children[3]; rowsBox.children[1].click(); -const tipRefresh = hoverCalls.find((h) => h.root === refresh).text(); const rowHover = hoverCalls.find((h) => h.root === panel.list); const tipRow = rowHover.text(rowsBox.children[0]); const tipBlank = [0, 1].map((n) => rowHover.text(blankBox.children[n])); -panel.draw({ book: null, stale: null }, { gaps: [] }); +panel.draw({}, { gaps: [] }); const b = view(); -const tipEmpty = refreshTip({ book: null, stale: "단가 아직 안 굳힘" }); -console.log(JSON.stringify({ a, b, moves, tipRefresh, tipRow, tipBlank, selector: rowHover.selector, - tipEmpty })); +console.log(JSON.stringify({ a, b, moves, tipRow, tipBlank, selector: rowHover.selector })); """, ) a, b = out["a"], out["b"] - assert a["pending"] and not b["pending"] # 빈 줄 = 직접공사 항목 중 금액 모름(관급 · 제목 · 아는 줄 빼고) · 같은 줄 까닭은 하나로 assert a["texts"][0] == "금액 빈 줄 2" and a["texts"][2] == "그 밖 확인 2곳" assert a["rows"] == [ @@ -107,28 +87,4 @@ console.log(JSON.stringify({ a, b, moves, tipRefresh, tipRow, tipBlank, selector assert a["texts"][4:] == ["B08 자재 집계표 못 읽음", "M01 에 없는 키 2 — EQ1 · LB2"] assert out["moves"] == [{"tab": "material", "key": "MT9"}] assert out["tipRow"] == "대가 원천 없음" and out["selector"] == "[data-i]" - assert "단가 굳힘 2026-10-01 09:00:00" in out["tipRefresh"] - assert "단가 갱신 가능 — M01 에서 바뀐 단가 2" in out["tipRefresh"] assert b["texts"] == ["금액 빈 줄 0"] and b["rows"] == [] - assert out["tipEmpty"].startswith("단가 아직 안 굳힘") and "단가 갱신 가능" in out["tipEmpty"] - - -def test_배지_조건_서버_book_stale(): - keys = ["MT000401", "MT000338", "LB000002"] # 841-1 책 = 자재만(노임 키는 안 셈) - book = json.loads(json.dumps(prices.refresh_book(keys), ensure_ascii=False)) - assert prices.book_stale(book, keys) is None # 방금 굳힌 책 = 업데이트 필요 없음 - assert prices.book_stale(None, keys) == "단가 아직 안 굳힘" - first, *rest = list(book["rows"]) - old = {**book, "rows": {k: book["rows"][k] for k in rest}} - old["rows"][rest[0]] = {**old["rows"][rest[0]], "prices": {}} - assert prices.book_stale(old, keys) == "새 단가 줄 1 · M01 에서 바뀐 단가 1" - router = (ROOT / "B09_Estimation/B09_Estimation_Router.py").read_text("utf-8") - assert '"stale": await asyncio.to_thread(prices.book_stale, book, keys),' in router - - -def test_배지_꼴_경고_색_토큰(): - css = (ROOT / "B09_Estimation/B09_Estimation_UI_Page.css").read_text("utf-8") - block = css[css.index(".b09-options .ui-btn.is-pending::after") :] - block = block[: block.index("}")] - assert "position: absolute" in block and "border-radius: 50%" in block - assert "background: var(--color-warning)" in block diff --git a/resources/tester/test_253_3_haul_preview.py b/resources/tester/test_253_3_haul_preview.py index 159563ee9..3902b32f6 100644 --- a/resources/tester/test_253_3_haul_preview.py +++ b/resources/tester/test_253_3_haul_preview.py @@ -22,7 +22,7 @@ def test_미리보기_계산_절차(tmp_path): got = logic_preview(tmp_path, PreviewBody(code="GF000134", given=given)) assert got["unit"] == "㎥" and got["price"] and got["price"] > 0 assert "Cm : 109.78 분" in got["lines"] - assert any("60 * 15 * 1 * 0.9 / 109.78" in line for line in got["lines"]) + assert "작업량 = 7.378 ㎥/hr" in got["lines"] # 60 × 15 × 1 × 0.9 ÷ 109.78(B9-4 화면 꼴) assert got["lines"][-1].startswith("계 :") # 거리 늘면 단가도 늘음 far = logic_preview(tmp_path, PreviewBody(code="GF000134", given={**given, "Cm": 200})) diff --git a/resources/tester/test_296_b09_update_skip_deleted.py b/resources/tester/test_296_b09_update_skip_deleted.py deleted file mode 100644 index 2e4ca4563..000000000 --- a/resources/tester/test_296_b09_update_skip_deleted.py +++ /dev/null @@ -1,90 +0,0 @@ -"""296 B09 [업데이트] — 지워진 복사 정보는 업데이트에서 뺌(요구 190-4). - -- ① B09 에서 지운 복사 항목 = 화면 캐시(user)를 같이 보냄 → 그 줄이 안 잇는 서고 사본 = - 수요에서 뺌 · 책에 안 살아남 · 캐시 그대로(지운 줄 안 되살림) · 저장은 안 함 -- ② M01 원본이 지워진 키 = 옛 책 줄 그대로(지우지도 바꾸지도 않음) · 낡음 까닭에서 빠짐 -- 나머지 = 지금처럼 M01 값으로 새로 굳힘 · user 안 보내면 옛 길 그대로 -임시 층(견본 마스터 · 임시 storage) · 실제 마스터 · 프로젝트는 안 씀. -""" - -import asyncio -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from B09_Estimation import B09_Estimation_Bill_Library as library # noqa: E402 -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 -from B09_Estimation import B09_Estimation_Router as router # noqa: E402 -from B09_Estimation import B09_Estimation_Store as store_b09 # noqa: E402 -from B09_Estimation.B09_Estimation_Linked import linked_resource_keys # noqa: E402 -from resources.tester.test_204_2_b09_bill_library import COMBO, world # noqa: E402, F401 - - -def _json(book): - return json.loads(json.dumps(book, ensure_ascii=False)) - - -def _refresh(monkeypatch, root, body): - seen = {} - - async def fake_root(_): - return root - - async def fake_payload(_, at, draft=None): - seen["draft"] = draft - return {} - - monkeypatch.setattr(router, "_project_root", fake_root) - monkeypatch.setattr(router, "payload", fake_payload) - asyncio.run(router.refresh_prices("00000000-0000-0000-0000-000000000001", body)) - return store_b09.read_book(root), seen["draft"] - - -def test_지운_복사_항목_업데이트_뒤_안_살아남(world, monkeypatch): # noqa: F811 - root = world["root"] - a = library.import_copy(root, "precombo", "system", None, world["key"])["폴더"] - b = library.import_copy(root, "combo", "system", None, COMBO)["폴더"] - keep_a = set(prices.refresh_book(linked_resource_keys(root, {a}))["rows"]) - every = set(prices.refresh_book(linked_resource_keys(root))["rows"]) - assert keep_a < every # b 사본만 부르는 줄이 있음 - # 화면 캐시 = b 줄을 지움(아직 [저장] 안 함 · 사본 폴더는 남음) - ref = {"tab": "dg", "key": "DG:x", "lib": a} - user = {"bill": {"v": 2, "rows": [{"key": "hand:1", "name": "줄", "qty": 1, "ref": ref}]}} - book, draft = _refresh(monkeypatch, root, {"user": user}) - assert set(book["rows"]) == keep_a # 지운 사본 단가 줄 안 살아남 - assert draft["bill"]["rows"][0]["ref"]["lib"] == a # 응답 셈도 캐시로 - assert not (store_b09.folder(root) / store_b09.USER).exists() # 저장 안 함 - assert {f.name for f, _ in library.copies(root)} == {a, b} # 사본 정리는 [저장] 몫 - assert prices.book_stale(_json(book), linked_resource_keys(root, {a})) is None - # user 안 보냄 = 옛 길(다 쓴 사본 전부) - book, draft = _refresh(monkeypatch, root, None) - assert set(book["rows"]) == every and draft is None - - -def test_M01_원본_없는_항목_값_그대로_낡음_까닭_빠짐(): - gone = "MT999999" # 841-1 책 = 자재만 — 원본 없는 자재 키 - keys = ["MT000401", "MT000338", gone] - old = _json(prices.refresh_book(["MT000401", "MT000338"])) - kept = {"key": gone, "name": "지워진 자재", "origin": "M01", "prices": {"물가자료": 123.0}} - old["rows"][gone] = kept - old["rows"]["MT000401"] = {**old["rows"]["MT000401"], "prices": {}} # M01 에서 바뀐 단가 - assert prices.book_stale(old, keys) == "M01 에서 바뀐 단가 1" # 원본 없는 줄 = 까닭에 없음 - new = _json(prices.refresh_book(keys, old)) - assert new["rows"][gone] == kept # 지우지도 바꾸지도 않음 - assert new["rows"]["MT000401"]["prices"] != {} # 나머지 = 새로 굳힘 - assert set(new["rows"]) == set(old["rows"]) - assert prices.book_stale(new, keys) is None - assert gone not in prices.refresh_book(keys)["rows"] # 옛 책 없으면 줄 없음(옛 길) - - -def test_화면_업데이트_캐시_보냄_그대로_둠(): - shell = (ROOT / "B09_Estimation/B09_Estimation_UI_Shell.ts").read_text("utf-8") - at = shell.index('"/estimation/prices",') - assert "{ user, ...(refresh.dataset.b09Job" in shell[at : at + 200] # 795-4 할일 덧칸 - assert "\n true," in shell[at : at + 200] - assert 'if (!keep) clearState("b09-estimation", projectId);' in shell - assert "apply(next, !keep);" in shell diff --git a/resources/tester/test_703_3_b09_refresh.py b/resources/tester/test_703_3_b09_refresh.py deleted file mode 100644 index 0f4e59c05..000000000 --- a/resources/tester/test_703_3_b09_refresh.py +++ /dev/null @@ -1,75 +0,0 @@ -"""703-3 B09 [업데이트] 한 곳 — 단가 책 다시 굳힘 + 원본이 바뀐 구조물 사본 재적용. - -- 미리 보기 수(`Refresh.preview`) = 적용 뒤 책 견줌(`Prices.book_diff`) 수 · 노임 판 전 → 후 · 고친 칸 수 -- 재적용 = 연결된 사본 중 원본이 바뀐 것만 · 하나가 막혀도 나머지 · 덮개(사용자 값) 안 건드림 -""" - -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from B09_Estimation import B09_Estimation_Prices as prices # noqa: E402 -from B09_Estimation import B09_Estimation_Refresh as refresh # noqa: E402 -from B09_Estimation import B09_Estimation_Store as store # noqa: E402 - -#: 841-1 책 = 자재만(노임 키 = 노임 판만 셈) — 원목 · 미송각재 + 작업반장(건설업) -KEYS = ["MT000401", "MT000338", "LB000001"] - - -def test_책_견줌_미리보기_수_적용_수_같음(tmp_path, monkeypatch): - monkeypatch.setattr(refresh, "changed_copies", lambda root: []) - new = prices.refresh_book(KEYS) - assert new["labor_edition"] == prices.labor_editions(KEYS) and new["labor_edition"] - old = json.loads(json.dumps(new)) - old["rows"]["MT000401"] = {**old["rows"]["MT000401"], "prices": {}} # 옛 값 - del old["rows"]["MT000338"] # 새 줄 - old["labor_edition"] = {"건설업": "2025-09-01"} - cover = { - "S:a": {"x#0": {"qty": 1, "labor": 2}}, - "K:b": {"@copy": {"from": "S:a"}, "y#0": {"qty": 3}}, - } - got = refresh.preview(tmp_path, old, KEYS, cover) - after = prices.refresh_book(KEYS, old) - diff = prices.book_diff(old, after) - assert (got["새줄"], got["바뀐줄"]) == (diff["new"], diff["changed"]) == (1, 1) - assert got["단가줄"] == 2 and got["고친칸"] == 3 and got["사본"] == [] - assert got["노임판"]["전"] == "건설업 2025-09" - assert got["노임판"]["후"].startswith("건설업 2026") - old.pop("labor_edition") - assert refresh.preview(tmp_path, old, KEYS, None)["노임판"]["전"].startswith("굳힌 날 ") - assert prices.book_diff(after, prices.refresh_book(KEYS, after)) == {"new": 0, "changed": 0} - assert prices.book_stale(after, KEYS) is None - - -def test_재적용_원본_바뀐_사본만_막혀도_나머지_덮개_그대로(tmp_path, monkeypatch): - cover = {"S:a": {"x#0": {"qty": 0.3}}} - store.write_user(tmp_path, {"daega_cover": cover}) - monkeypatch.setattr( - refresh, - "linked_snapshots", - lambda root: {"p1": {"폴더": "a"}, "p2": {"폴더": "b"}, "p3": {"폴더": "c"}}, - ) - items = [ - {"폴더": "a", "이름": "가", "마스터바뀜": True}, - {"폴더": "b", "이름": "나", "마스터바뀜": False}, # 원본 그대로 = 안 함 - {"폴더": "c", "이름": "다", "마스터바뀜": True}, - {"폴더": "z", "이름": "끊김", "마스터바뀜": True}, # 연결 안 됨 = 안 함 - ] - monkeypatch.setattr(refresh.item_copy, "list_items", lambda root: items) - calls = [] - - def fake(root, folder, who=None): - calls.append(folder) - if folder == "c": - raise LookupError("원본 층 없음") - - monkeypatch.setattr(refresh.item_copy, "reapply", fake) - assert [c["이름"] for c in refresh.changed_copies(tmp_path)] == ["가", "다"] - got = refresh.reapply_changed(tmp_path) - assert calls == ["a", "c"] - assert got == {"다시": ["가"], "막힘": ["다 — 원본 층 없음"]} - assert store.read_user(tmp_path)["daega_cover"] == cover diff --git a/resources/tester/test_719_2_sk_project.py b/resources/tester/test_719_2_sk_project.py index c32d51746..e6a6b2684 100644 --- a/resources/tester/test_719_2_sk_project.py +++ b/resources/tester/test_719_2_sk_project.py @@ -1,11 +1,10 @@ -"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · [재생성](업데이트) · 서고(임시 +"""719-2 · 855-F B9-5 공사 쪽 M02 단가산출(SK) — B09 대가 블록 · 구조물 [재적용] · 서고(임시 storage · 실제 M01 읽기만). - 사본 SK(수식 따로 사본) = 품셈 꼴 대가 블록(`Labor_Source.sangeun`) · 줄 = 문서 답 금액 줄 (M02 에서 고친 문서 그대로) · 금액 = M02 SK 셈 -- [재생성] = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 그대로 · - 덮개 밑 값(base) = 새 단가산출 값 · 서고 사본(`sangeun`)도 원본판 다르면 다시 굳힘 - · 미리 보기 SK 줄 +- 구조물 [재적용](다시 지정) = SK 고친 뒤 다시 굳힘 — cover · cid · 입력값 · 고른자재 · B09 덮개 + 그대로 · 덮개 밑 값(base) = 새 단가산출 값(859-2 프로젝트 안 [재생성] 걷음) (옛 칸 덮개 · 더한줄 SK · 내 자료집 = 옛 칸 SK 만들기는 855 2-C1 셈 은퇴 — 시험 없음) """ @@ -16,7 +15,6 @@ import pytest from B09_Estimation import B09_Estimation_Bill_Library as library from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh from B09_Estimation import B09_Estimation_Sangeun as sangeun from B09_Estimation.B09_Estimation_Calc_Base import compute_base from B09_Estimation.B09_Estimation_Calc_Labor import compute_labor @@ -154,23 +152,6 @@ def test_구조물_사본_SK_줄_재생성_덮개_입력값_고른자재_그대 assert daega2["owners"]["pipe@100.0"] in done -def test_서고_SK_업데이트_미리보기_다시_굳힘(world, tmp_path): - key = _mine(world) - root, folder = _lib(world, tmp_path, key) - assert library.changed(root) == [] - before = daega_inputs(root) - cover_key = next(b for b in before["blocks"] if b["id"] == before["libs"][folder])["cover"] - edit(world["personal"], key, 3) - got = refresh.preview(root, None, [], None) - assert [(x["키"], x["판"]) for x in got["단가산출"]] == [(key, "바뀜")] - assert [c["폴더"] for c in got["사본"]] == [folder] - assert refresh.reapply_changed(root)["다시"] == ["내 단가산출"] - assert library.changed(root) == [] and [f.name for f, _ in library.copies(root)] == [folder] - after = daega_inputs(root) - block = next(b for b in after["blocks"] if b["id"] == after["libs"][folder]) - assert block["cover"] == cover_key and block["lines"][0]["qty"] == pytest.approx(0.108) - - def test_SK_하위_단가산출_줄_산근(world, tmp_path): """사본 SK 문서 줄이 부른 하위 단가산출 = 대가 블록 산근 줄 · B09 산근 목록에 그 키(855-F B9-5).""" key = _sk(world["personal"], 바탕={"로직": "GF000206"}) # 합판거푸집 → GF000160 부름 diff --git a/resources/tester/test_795_4_b09_copy.py b/resources/tester/test_795_4_b09_copy.py index c25ced794..09f3b780a 100644 --- a/resources/tester/test_795_4_b09_copy.py +++ b/resources/tester/test_795_4_b09_copy.py @@ -1,25 +1,20 @@ # ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀 -"""795-4 프로젝트(B09) 사본 규칙 — 만든 때 그대로 · [단가 갱신] 값만 · [재생성] 따로 · +"""795-4 프로젝트(B09) 사본 규칙 — 만든 때 그대로 · 시점 섞임 고침(임시 storage · M01 은 메모리 덮개 · 정본 안 고침). ① 구조물 사본 단가 묶음 = M02 일위대가 사본 줄(만든 때) · 뒤에 M01 로직 · 노임이 바뀌어도 사본 금액 그대로 · M01 에서 지워진 키 = 사본 줄 그대로 ② 사본 없는 옛 문서 = 옛 길(지금 M01) ③ [저장] 새 단가 줄 = 사본 기준 시점 값 · 없는 자원만 지금 값 + 표지 · 옛 책 줄 그대로 -④ 연결 사본 `단가.json` 자원 줄 = 기준 시점 원천 ⑤ [단가 갱신] = 값만(사본 재적용 없음) · - [재생성] = 따로 누를 때만 ⑥ 미리 보기 꼴. +④ 연결 사본 `단가.json` 자원 줄 = 기준 시점 원천(859-2 [단가 갱신] · [재생성] 걷음). """ from __future__ import annotations -import asyncio import copy import json -from uuid import uuid4 from B09_Estimation import B09_Estimation_Linked as linked from B09_Estimation import B09_Estimation_Prices as prices -from B09_Estimation import B09_Estimation_Refresh as refresh -from B09_Estimation import B09_Estimation_Router as router from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_Item_Prices as item_prices from M02_MasterTemplete import M02_Item_Source as source @@ -125,11 +120,9 @@ def test_book_new_rows_use_copy_basis(): inputs = prices.build_inputs(None, [WOOD, BAR], None, frozen) assert [_price(r) for r in inputs["materials"]] == [111, _price(both["rows"][BAR])] assert inputs["now"] == [BAR] and prices.build_inputs(both, [WOOD, BAR])["now"] == [BAR] - old = _json(prices.refresh_book([WOOD, BAR])) # 옛 책(사본 규칙 전) = 줄 · 값 그대로 + old = _json(prices.make_book([WOOD, BAR])) # 옛 책(사본 규칙 전) = 줄 · 값 그대로 again = _json(prices.extend_book(old, [WOOD, BAR], frozen)) assert again["rows"] == old["rows"] and again["now_keys"] == [] - fresh = _json(prices.refresh_book([WOOD, BAR], both)) # [단가 갱신] = 지금 값 · 표지 없음 - assert _price(fresh["rows"][WOOD]) != 111 and fresh["now_keys"] == [] def test_frozen_rows_from_linked_copy(tmp_path): @@ -143,50 +136,3 @@ def test_frozen_rows_from_linked_copy(tmp_path): ) inside = {r["키"]: r for d in bundle.values() if isinstance(d, dict) for r in d.get("줄") or []} assert all(inside[k] == row for k, row in got.items()) - - -def _router(monkeypatch, tmp_path, calls): - async def root(_): - return tmp_path - - async def demand(*_): - return [LB] - - async def payload(*_a, **_k): - return {"user": {}, "notes": [], "sheets": {}} - - monkeypatch.setattr(router, "_project_root", root) - monkeypatch.setattr(router, "_demand", demand) - monkeypatch.setattr(router, "payload", payload) - monkeypatch.setattr(router.store, "read_book", lambda _r: None) - monkeypatch.setattr(router.store, "write_book", lambda _r, b: calls.append(("book", b))) - monkeypatch.setattr( - router.refresh, - "reapply_changed", - lambda *_a: calls.append("regen") or {"다시": ["A"], "막힘": []}, - ) - - -def test_price_refresh_default_regen_separate(monkeypatch, tmp_path): - """⑤ [단가 갱신] = 값만(사본 재적용 없음) · [재생성] = job 줄 때만.""" - calls = [] - _router(monkeypatch, tmp_path, calls) - out = asyncio.run(router.refresh_prices(uuid4(), {"user": {}}, {})) - assert "regen" not in calls and calls[-1][0] == "book" - assert out["notes"][0].startswith("단가 갱신 — ") - out = asyncio.run(router.refresh_prices(uuid4(), {"user": {}, "job": refresh.REGEN}, {})) - assert calls.count("regen") == 1 - assert out["notes"][0].startswith("재생성 — 구조물 사본 1 다시 가져옴") - - -def test_price_preview_shape(): - """⑥ 미리 보기 — 바뀐 자원(사본 자원 줄 먼저 · 자재 단가 책) · 총괄 전 → 후.""" - old = _json(prices.refresh_book([WOOD, BAR])) - old["rows"][WOOD] = {**old["rows"][WOOD], "prices": {"물가자료": 1}} - new = _json(prices.refresh_book([WOOD, BAR], old)) - sheets = lambda g: {"total": {"subtotals": {"grand": g}}} # noqa: E731 - copies = [{"키": LB, "이름": "사본 노임", "전": 1, "후": 2}] - got = refresh.price_preview(old, new, sheets(10), sheets(20), 3, copies) - assert got["할일"] == "단가갱신" and (got["전"], got["후"], got["고친칸"]) == (10, 20, 3) - assert [(r["키"], r["전"]) for r in got["바뀐자원"]] == [(LB, 1), (WOOD, {"물가자료": 1})] - assert got["바뀐자원"][1]["후"] == new["rows"][WOOD]["prices"]