Files
Aislo/old_code/B09_Estimation/B09_Estimation_Router_Progress.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

130 lines
5.2 KiB
Python

"""B09 기성 단계 탭 API — 계약내역 → 기성내역 · 기성 제잡비 계산서 (PLAN 12장 · 랩탑 메인).
⚠ 계약내역(`contract_for`)과 계약 원가계산서(`cost_from_bill` 에 계약 직접비)를 **읽기만** 한다.
저장은 `estimation.progress` 한 칸(회차 목록) — 설계·계약·원가계산서 저장본은 안 건드린다.
"""
from __future__ import annotations
import logging
from decimal import Decimal
from typing import Any
from uuid import UUID
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from B09_Estimation.B09_Estimation_Progress import (
CUT_CHOICES,
SETTINGS_KEY,
VAT_CHOICES,
clean_settings,
completion_sheet,
progress_sheet,
)
from B09_Estimation.B09_Estimation_Rates import RateLookupError
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=["B09 Estimation — Progress"])
def _cut_options(first: str) -> list[dict[str, str]]:
"""절사 9택 — 첫 칸은 화면 표기 그대로(빈 값)."""
return [
{"key": unit, "label": f"{int(unit):,}원 미만" if unit else first} for unit in CUT_CHOICES
]
async def progress_for(
project_id: UUID, round: int | None
) -> tuple[dict[str, Any], dict[str, Any]] | JSONResponse:
"""(기성 저장값, 기성 한 장) — 못 서면 그 까닭 응답. 준공도 이 길로 기성본을 받음."""
from B09_Estimation.B09_Estimation_Router_Contract import contract_for
from B09_Estimation.B09_Estimation_Router_CostSheet import cost_from_bill
from common_util.common_util_project_settings import estimation_settings
found = await contract_for(project_id)
if isinstance(found, JSONResponse):
return found
root, bill, _, contract = found
totals = contract["totals"]["contract"]
direct = {part: Decimal(totals[f"{part}_krw"]) for part in ("material", "labor", "expense")}
try:
cost_data, cost_result, _ = cost_from_bill(root, bill, direct)
except RateLookupError as error:
return JSONResponse(status_code=422, content={"status": "error", "message": str(error)})
stored, _ = clean_settings(dict(estimation_settings(root).get(SETTINGS_KEY) or {}))
return stored, progress_sheet(contract["rows"], cost_data, cost_result, stored, round)
@router.get("/{project_id}/estimation/completion")
async def get_completion(project_id: UUID) -> JSONResponse:
"""준공 한 장 — 계약금액 | 준공금액(기성 마지막 회차 누계를 옮김)."""
found = await progress_for(project_id, None)
if isinstance(found, JSONResponse):
return found
return JSONResponse(
content={
"status": "success",
**completion_sheet(found[1]),
"limit_note": (
"준공 별도 계산 규칙 미확인(35번 §3) — 기성 마지막 회차 누계를 옮기기만 함 · "
"준공 표본 0건"
),
}
)
@router.get("/{project_id}/estimation/progress")
async def get_progress(project_id: UUID, round: int | None = None) -> JSONResponse:
"""기성 한 장 — `round` 회차(1부터)를 금회로 · 없으면 마지막 회차."""
found = await progress_for(project_id, round)
if isinstance(found, JSONResponse):
return found
stored, sheet = found
return JSONResponse(
content={
"status": "success",
**sheet,
"settings": stored,
"fields": {
"vat": [{"key": k, "label": label} for k, label in VAT_CHOICES],
"supply_cut": _cut_options("총공사비에서 조정"),
"total_cut": _cut_options("이윤금액 직접입력"),
},
"limit_note": (
"기성 표본 0건 — 구조가 서는지까지만 확인됨 · 계약잡비율 역산(도급액 ÷ 계약 "
"직접공사비)·회차별 절사는 구조로 읽음 · 사정은 뜻 미확인이라 칸만"
),
}
)
@router.put("/{project_id}/estimation/progress")
async def put_progress(project_id: UUID, body: dict[str, Any]) -> JSONResponse:
"""회차 목록 저장 — 틀린 칸이 있으면 아무것도 안 저장."""
from B09_Estimation.B09_Estimation_Router import _project_root_of
from common_util.common_util_project_settings import save_section
root = await _project_root_of(project_id)
if root is None:
return JSONResponse(
status_code=404,
content={"status": "error", "message": "프로젝트 저장 폴더를 찾지 못했습니다."},
)
cleaned, errors = clean_settings(body)
if errors:
return JSONResponse(
status_code=400,
content={"status": "error", "message": " · ".join(errors), "errors": errors},
)
try:
save_section(root, "estimation", {SETTINGS_KEY: cleaned}, replace_keys=(SETTINGS_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", "settings": cleaned})