Files
Aislo/B09_Estimation/B09_Estimation_Router_Edits.py
T
eomsangdonandClaude Opus 5 c3618fe872 feat(b09): 2차 편집 ② 일위대가·단산 구성행 수정 · ③ Q 식 편집 — 프로젝트 단위 · 서버가 다시 계산 · ↺
- 구성행(sheet_rows): 수량 고치기 · 줄 빼기(수량 0, 흐리게) · 줄 더하기(단가표 고르개) — 비율 줄·돌림 참조는 받지 않음
- Q 식(price_basis_q): 식은 명세 13장 식 언어 — B08 구조물도 풀이기(evaluate_sheets, Node 한 벌)를 그대로 부름 ·
  소수 2자리 사사오입 확정 → 새 수량 = 수량 × 옛 Q ÷ 새 Q · 비고에 「Q(사용자) = 식 = 값」
  · PriceDetail.output(시공능력 Q)을 Q 로 선 장비 줄 넷 자리(굴착기·도자·직접 작업량·암 잎)에서 실음 · 저장 모양에도 실음
- 따로 짰던 파이썬 식 셈(B09_Estimation_Expression)은 걷어냄 — 식 풀이 두 벌 금지(브레인 판정)
- 새 문: GET /estimation/edits/sheet/{code}(본표 + 줄마다 고친 값 표시) · GET /estimation/edits/search(줄 더하기 고르개)
- 화면: 본표 [편집] — 수량 칸 · ✕ · Q 식 칸 · 줄 더하기 · 고친 줄 「사용자」 + ↺
- 검증: 시험 1664 통과 · 골든셋 초록 · ORCA — 제 3 호표 보통인부 0.023→0.046 이면 5,652→9,610 · 내역 본체 122,848,989→122,857,198,
  ↺ 뒤 5,652 · 산근 2호표 Q 58.21→116.42 이면 1,695→847, ↺ 뒤 1,695 · 틀린 식 422 「모르는 이름: abc」 · 고친 값 {} 로 복구

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016VBGFXB9AbJBwXP19z75Qq
2026-09-14 03:37:18 +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})