Files
Aislo/old_code/B09_Estimation/B09_Estimation_Router_Edits.py
T
eomsangdonandClaude Opus 5 8472fc9f40 refactor(B08,B09): 폴더째 old_code 로 옮기고 빈 화면 둘만 남김 (PLAN 7-3)
B08_Quantity 86 · B09_Estimation 111 파일을 old_code/ 로 옮김(지우지 않음).
화면은 메뉴·주소·단계 막대만 남은 빈 틀 둘 — main.py 라우터 13 개는 끊음.
B07 이 빌려 쓰던 비탈 길이·면적은 필요한 함수만 B07_DesignDetail_Engine_SlopeGeometry
로 옮겨 적음(면적 적분·노면 면적·측점 묶음은 안 옮김) · 시험 하나를 새로 둠.
B07 구조물도 조립(Cad_StandardSheet)은 2026-09-13 에 이미 도면 목록에서 빠져
부르는 곳이 없어 old_code 로 같이 보냄 — 구조물 그림은 되살리지 않음.
B06 구조물 몫 조회는 빈 값으로 두어 화면이 그대로 서게 함.
B08·B09 를 부르던 시험 25 개도 old_code/resources/tester 로 옮김.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAdA5ThqmtVSsbzjusk1cJ
2026-09-22 12:27:45 +09:00

150 lines
6.1 KiB
Python

"""B09 원가계산 라우터 — **사용자가 고친 값** 읽기·저장 (PLAN 12장 2차 · `B09_Estimation_Edits`).
⚠ `B09_Estimation_Router.py` 는 쪼개기 차례를 기다리는 중이라(브레인 판정) 새 문을 여기 둠.
⚠ 저장은 고친 값만 — 금액은 다음 조회 때 서버가 조립 뒤 고친 값을 얹어 **다시 계산**함.
"""
from __future__ import annotations
import logging
from typing import Any
from uuid import UUID
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from B09_Estimation.B09_Estimation_Edits import (
EDITS_KEY,
EditError,
merge_changes,
normalize,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=["B09 Estimation Edits"])
class EditChange(BaseModel):
"""고칠 칸 하나 — `value` 가 `null` 이면 그 칸을 지움(↺ 계산값으로 돌아감)."""
section: str
key: str
value: Any = None
class EditRequest(BaseModel):
changes: list[EditChange] = Field(default_factory=list)
@router.get("/{project_id}/estimation/edits")
async def get_edits(project_id: UUID) -> JSONResponse:
"""고친 값 한 벌 — 화면이 「사용자」 표시·↺ 를 붙이는 데 씀."""
from B09_Estimation.B09_Estimation_Router import _build_for, _project_root_of
from common_util.common_util_project_settings import estimation_settings
root = await _project_root_of(project_id)
settings = estimation_settings(root) if root else {}
build = await _build_for(project_id)
return JSONResponse(
content={
"status": "success",
EDITS_KEY: normalize(settings.get(EDITS_KEY)),
"skipped": list(getattr(build, "edit_skipped", [])),
}
)
@router.get("/{project_id}/estimation/edits/sheet/{code}")
async def get_edit_sheet(project_id: UUID, code: str) -> JSONResponse:
"""호표 본표 + 줄마다 고친 값 표시(`edit`) — 일위대가·단산 구성행 수정·Q 식 편집 화면이 씀.
본표 모양은 `/unit-prices/{code}` 와 같음(`detail_of`) — 줄 차례가 상세 줄 차례와 같아 칸이 맞음.
"""
from B09_Estimation.B09_Estimation_Edits import EDITABLE_KINDS, row_edits
from B09_Estimation.B09_Estimation_PriceBook import PriceBookError
from B09_Estimation.B09_Estimation_Router import _build_for, _with_provenance
from B09_Estimation.B09_Estimation_UnitPrice import detail_of
try:
build = await _build_for(project_id)
body = detail_of(build, code)
except PriceBookError as error:
return JSONResponse(status_code=404, content={"status": "error", "message": str(error)})
except Exception:
logger.exception("B09 편집 본표 실패: project_id=%s, code=%s", project_id, code)
return JSONResponse(
status_code=500,
content={"status": "error", "message": "본표를 못 만들었습니다."},
)
for row, edit in zip(body["rows"], row_edits(build, code)):
row["edit"] = edit
added = [
int(mark["key"].rsplit("|+", 1)[1])
for mark in getattr(build, "edit_rows", {}).get(code, {}).values()
if "|+" in str(mark.get("key", ""))
]
body["editable"] = build.book.title(code).kind in EDITABLE_KINDS
body["next_add_key"] = f"{code}|+{max(added, default=0) + 1}"
return JSONResponse(content=_with_provenance({"status": "success", **body}))
@router.get("/{project_id}/estimation/edits/search")
async def search_titles(project_id: UUID, q: str = "", parent: str = "") -> JSONResponse:
"""줄 더하기 고르개 — 단가표 제목을 이름·규격으로 찾음(노임·자재·중기·일위대가·단산·일식)."""
from B09_Estimation.B09_Estimation_Edits import ADDABLE_KINDS
from B09_Estimation.B09_Estimation_Router import _build_for
from B09_Estimation.B09_Estimation_UnitPrice import HOURLY_WAGE_SUFFIX, SOURCE_LABEL
words = [word for word in q.lower().split() if word]
build = await _build_for(project_id)
rows = []
for code, title in build.book.titles.items():
if title.kind not in ADDABLE_KINDS or code == parent or code.endswith(HOURLY_WAGE_SUFFIX):
continue
text = f"{title.name} {title.spec} {code}".lower()
if words and all(word in text for word in words):
rows.append(
{
"code": code,
"name": title.name,
"spec": title.spec,
"unit": title.unit,
"kind_label": SOURCE_LABEL.get(title.kind, ""),
}
)
if len(rows) >= 40:
break
return JSONResponse(content={"status": "success", "rows": rows})
@router.put("/{project_id}/estimation/edits")
async def put_edits(project_id: UUID, payload: EditRequest) -> JSONResponse:
"""고친 값 저장 — 칸마다 검사하고(값 없는 슬롯 등은 받지 않음) 구획째 갈아 끼움."""
from B09_Estimation.B09_Estimation_Router import _build_for, _project_root_of
from common_util.common_util_project_settings import estimation_settings, save_section
root = await _project_root_of(project_id)
if root is None:
return JSONResponse(
status_code=404,
content={"status": "error", "message": "프로젝트 저장 폴더를 찾지 못했습니다."},
)
settings = estimation_settings(root)
try:
build = await _build_for(project_id)
edits = merge_changes(
settings.get(EDITS_KEY), build, [change.model_dump() for change in payload.changes]
)
except EditError as error:
return JSONResponse(status_code=422, content={"status": "error", "message": str(error)})
try:
save_section(root, "estimation", {EDITS_KEY: edits}, replace_keys=(EDITS_KEY,))
except Exception:
logger.exception("B09 고친 값 저장 실패: project_id=%s", project_id)
return JSONResponse(
status_code=500,
content={"status": "error", "message": "고친 값을 저장하지 못했습니다."},
)
return JSONResponse(content={"status": "success", EDITS_KEY: edits})