Files
Aislo/B09_Estimation/B09_Estimation_Router_Contract.py
eomsangdonandClaude Opus 5 1edde503fe feat(b09): 기성 단계 1벌 — 금회직접공사비 × 계약잡비율 · 계약/전회/금회/누계와 각 율 · 부가세 넷
- 계약내역·계약 원가계산서(같은 엔진에 계약 직접비)를 읽기만 해 파생 — 계약 불변
- 제잡비 줄마다 계약잡비율 = 도급액 ÷ 계약 직접공사비 (구조로 읽음, 확인 대기)
- 회차 목록 저장 · 기성(%) · 잔량 · 계약 수량 넘으면 알림
- 부가세: 직접입력 / 공급가액 / 재료비 / 재료비+산출경비 (설계 vat_base 같이 씀)
- 원가계산서 조립·계약본 받기 조각을 떼어 기성이 같은 길로 받음
- 기성 탭 파일 · 사전 키(등록은 서브) · 시험 6건 · 전체 1717 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BW6Jdsh18WPtYUR6THZJqn
2026-09-14 06:03:22 +09:00

111 lines
4.3 KiB
Python

"""B09 계약 단계 탭 API — 당초설계 → 계약내역 (PLAN 12장 · 랩탑 메인).
⚠ 설계 내역을 **읽기만** 한다(`/estimation/bill` 결과를 복사해 적용률을 얹음). 저장은
`estimation.contract` 한 칸 — 설계 내역·원가계산서 저장본은 안 건드린다.
"""
from __future__ import annotations
import json
import logging
from typing import Any
from uuid import UUID
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from B09_Estimation.B09_Estimation_Contract import (
OPTIONS,
RATE_FIELDS,
SETTINGS_KEY,
clean_settings,
contract_bill,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=["B09 Estimation — Contract"])
async def _root(project_id: UUID) -> str | None:
from B09_Estimation.B09_Estimation_Router import _project_root_of
return await _project_root_of(project_id)
async def contract_for(
project_id: UUID,
) -> tuple[str, dict[str, Any], dict[str, Any], dict[str, Any]] | JSONResponse:
"""(저장 폴더, 설계 내역, 계약 조건, 계약내역) — 못 서면 그 까닭 응답.
기성도 이 길로 계약본을 받음(계약 값을 따로 셈하지 않음).
"""
from B09_Estimation.B09_Estimation_Router import _build_for, get_bill
from common_util.common_util_project_settings import estimation_settings
root = await _root(project_id)
if root is None:
return JSONResponse(
status_code=404,
content={"status": "error", "message": "프로젝트 저장 폴더를 찾지 못했습니다."},
)
response = await get_bill(project_id)
bill = json.loads(bytes(response.body).decode("utf-8"))
if response.status_code != 200 or "rows" not in bill:
return JSONResponse(status_code=response.status_code or 502, content=bill)
stored, _ = clean_settings(dict(estimation_settings(root).get(SETTINGS_KEY) or {}))
# 조립본은 캐시 공유본 — `contract_bill` 이 단가표 복사본에만 적용률을 얹음(설계 불변).
build = await _build_for(project_id) if stored.get("apply_to_base_prices") else None
return root, bill, stored, contract_bill(bill["rows"], stored, build=build)
@router.get("/{project_id}/estimation/contract")
async def get_contract(project_id: UUID) -> JSONResponse:
"""계약내역 한 장 — 설계 줄 옆에 계약단가·계약금액 · 설계↔계약 합계 · 옵션."""
found = await contract_for(project_id)
if isinstance(found, JSONResponse):
return found
_, bill, stored, result = found
return JSONResponse(
content={
"status": "success",
**result,
"settings": stored,
"fields": {
"rates": [{"key": k, "label": label} for k, label in RATE_FIELDS],
"options": [{"key": k, "label": label} for k, label in OPTIONS],
},
"bill_missing_count": len((bill.get("summary") or {}).get("missing") or []),
"limit_note": (
"계약 표본 0건 — 구조가 서는지까지만 확인됨 · 원 단위 값은 표본이 생기면 대조"
),
}
)
@router.put("/{project_id}/estimation/contract")
async def put_contract(project_id: UUID, body: dict[str, Any]) -> JSONResponse:
"""적용률·옵션·적용 제외 줄 저장 — 틀린 칸이 있으면 아무것도 안 저장."""
from common_util.common_util_project_settings import save_section
root = await _root(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})