- M02_Labor_Copy.line: 프로젝트 층 · `dsk.OLD` 옛 엔진 갈래 걷음(층 셈과 같은 문서 셈) · 재료 줄 `걸림`(재료 조건 · 요소 키 틀 구멍의 입력 이름 = 문서 몫 · 화면 `releaseTied` 가 읽음 — 옛 logic_mats 와 같은 뜻) - M02_Labor_Doc: `run_line` · `pct_extras` · `_pct_base` · `logic_mats` · `layered` · `drop_apart` · `_specs`(mf.inputs_of) 지움 (제품 부르는 곳 0) · 담기 검사 = 새 `_head`(문서 입력 이름 · 재료 금액 줄 차례 — M01 로직 줄 안 읽음) - M02_Doc_Sk: 아무도 안 켜는 `OLD` ContextVar 지움 - 시험: 옛 날 답 자리 = 새 `helper_855_line.run_line`(층 문서 셈 · 재료 직접계산) — 175 · 222_1 · 715_3 · 715_sangeun_store · 727 · 742_1 · 747_1 · 795_1 · 795_2 · m02_labor_layer · m02_labor_logic_mats · m02_labor_ref · 옛 엔진만 붙든 것 걷음: test_149_4 통째(옛 % 덧줄 표기) · 751_3 다섯(run_line 끝수) · 792_3 다시 버림 · 802_4a 옛 길 대조(OLD · run_line) · 855_sk_layers 옛 엔진 안 돎 = master_formula.run 부름 0 으로 · helper_855_old_engine_routes 의 % 덧줄 표기 = 그 도우미 안으로(옛 길 도우미 · 엔진 몸과 같이 지움) - 222_1 시멘트 단위 글 kg → ㎏(문서 단위) - 검증: 관련 82 파일 + 지킴 + 관문 776 통과 · 빌더 --check 같음 · typecheck 0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
6.8 KiB
Python
179 lines
6.8 KiB
Python
"""855 2-E1 — 서버에서 걷은 M01 옛 셈 길(`POST /api/m01/calc` · `/text` · `GET /logic/auto`)의 몸 — 시험 전용.
|
|
|
|
옛 엔진(`master_formula` · `master_text` · `master_sheet_line`)은 B09 · M02 가 아직 씀 →
|
|
그 엔진을 이 길 꼴로 보던 시험(test_m01_text · test_m01_api · test_m01_copy · test_794_1 · test_714_1)이
|
|
앱에 `router` 를 붙여 그대로 셈. 2-E4(엔진 지움)에서 같이 지움.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from decimal import Decimal
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter
|
|
from pydantic import BaseModel
|
|
|
|
from M01_MasterData import M01_MasterData_Router as m01
|
|
from M01_MasterData import M01_MasterData_Store as store
|
|
|
|
import master_sheet_line as msl # noqa: E402 — `store` 가 scripts 를 길에 둔 뒤
|
|
|
|
cm, mf = store.cm, store.cm.mf
|
|
DRAFT = "_초안.json"
|
|
router = APIRouter(prefix="/api/m01")
|
|
|
|
|
|
class CalcBody(BaseModel):
|
|
key: str
|
|
inputs: dict[str, Any] = {}
|
|
row: dict[str, Any] | None = None
|
|
file: str | None = None
|
|
고름: dict[str, str] = {}
|
|
|
|
|
|
def _swap(files: dict, key: str, row: dict, file: str | None) -> str:
|
|
"""저장 전 시험 — 메모리 사본에서 그 로직을 고친 줄로 바꿈(없으면 `file` 에 더함)."""
|
|
row = store._dec(row)
|
|
for data in files.values():
|
|
if data.get("그룹") != "로직":
|
|
continue
|
|
items = data.get("줄") or []
|
|
for i, old in enumerate(items):
|
|
if str(old.get("키")) == key:
|
|
items[i] = {**row, "키": key}
|
|
return key
|
|
if file is None:
|
|
file = DRAFT
|
|
files[file] = {"그룹": "로직", "원문": "자체", "줄": []}
|
|
if file not in files or files[file].get("그룹") != "로직":
|
|
raise store.StoreError(404, f"없는 로직 파일 「{file}」")
|
|
new = store.mk.table_id("로직", files[file].get("원문")) + "999999"
|
|
files[file].setdefault("줄", []).append({**row, "키": new})
|
|
return new
|
|
|
|
|
|
def _files(key: str, row: dict | None, file: str | None) -> tuple[dict, str]:
|
|
files = cm.load(folder=store.FOLDER)
|
|
if row is not None:
|
|
key = _swap(files, str(row.get("키") or key), row, file)
|
|
return files, key
|
|
|
|
|
|
_FAIL = (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError)
|
|
|
|
|
|
def calc(key: str, inputs: dict, row: dict | None = None, file: str | None = None) -> dict:
|
|
given = {k: store._dec(v) for k, v in inputs.items()}
|
|
files, key = _files(key, row, file)
|
|
try:
|
|
given = mf.fill_empty(mf.Master(files).logic(key), given)
|
|
result = cm.calc(files, key, given)
|
|
except _FAIL as e:
|
|
return {"ok": False, "reason": str(e) or type(e).__name__}
|
|
if "결과" in result:
|
|
return {"ok": True, "result": result["결과"], "middle": result["중간"]}
|
|
sums = {k: result[k] for k in mf.BUNDLE}
|
|
return {"ok": True, "lines": result["줄"], "sums": sums, "middle": result["중간"]}
|
|
|
|
|
|
def text(key: str, inputs: dict, row: dict | None = None, file: str | None = None) -> dict:
|
|
"""읽는 식 줄(`master_text`) + 계산서 줄 덧칸(`master_sheet_line.annotate` · 714-1)."""
|
|
given = {k: store._dec(v) for k, v in inputs.items()}
|
|
files, key = _files(key, row, file)
|
|
try:
|
|
given = mf.fill_empty(mf.Master(files).logic(key), given)
|
|
got = store.mtx.lines(files, key, given)
|
|
except _FAIL as e:
|
|
return {"ok": False, "reason": str(e) or type(e).__name__}
|
|
if not isinstance(got, dict) or not got.get("ok"):
|
|
return got
|
|
try:
|
|
return msl.annotate(files, key, given, got)
|
|
except _FAIL:
|
|
return got
|
|
|
|
|
|
def auto(key: str) -> dict:
|
|
"""견본 입력 — 옛 자동값(`master_auto`) · 없는 로직 = 404."""
|
|
whole = store.loaded()[1]
|
|
try:
|
|
return {"값": store.mau.values(whole, whole.logic(key))}
|
|
except mf.FormulaError as e:
|
|
raise store.StoreError(404, str(e)) from e
|
|
|
|
|
|
@router.get("/logic/auto")
|
|
def get_logic_auto(key: str) -> dict:
|
|
return m01._call(auto, key)
|
|
|
|
|
|
@router.post("/calc")
|
|
def post_calc(body: CalcBody) -> dict:
|
|
with mf.mp.choosing(body.고름):
|
|
got = m01._call(calc, body.key, body.inputs, body.row, body.file)
|
|
if not got.get("lines"):
|
|
return got
|
|
whole = store.loaded()[1]
|
|
try:
|
|
logic = body.row or whole.logic(body.key)
|
|
except mf.FormulaError:
|
|
return got
|
|
lines = _pct_extras(whole, logic, got["lines"], got.get("middle") or {})
|
|
return {**got, "lines": m01._num(lines)}
|
|
|
|
|
|
@router.post("/text")
|
|
def post_text(body: CalcBody) -> dict:
|
|
with mf.mp.choosing(body.고름):
|
|
return m01._call(text, body.key, body.inputs, body.row, body.file)
|
|
|
|
|
|
COSTS = ("노무비", "재료비", "경비")
|
|
|
|
|
|
# ── 옛 % 덧줄 표기(옛 `M02_Labor_Doc.pct_extras` · 855-E 2-E4 에서 제품에서 걷어 옛 길 도우미로 옮김) ──
|
|
def _pct_extras(whole: Any, logic: dict, lines: list[dict], env: dict) -> list[dict]:
|
|
"""% 덧줄(149-4) — 덧줄 식이 「X * Y / 100」 이면 그 엔진 줄(호표 수 뒤 같은 차례)에 덧칸
|
|
`율` = Y(엔진 마지막 env 로 셈) · `규격` = X 이름(「노무비의 %」 · 인력 줄 합 「인건비의 %」 ·
|
|
`줄.'이름'` · 중간값 「이름의 %」 · 그 밖 복합 = 빈 글). 다른 덧줄 · 흐름 로직 · 못 셈 = 그대로."""
|
|
if isinstance(logic.get("흐름"), dict):
|
|
return lines
|
|
out, head = list(lines), len(logic.get("호표") or [])
|
|
for n, add in enumerate(logic.get("덧줄") or []):
|
|
if head + n >= len(out):
|
|
break
|
|
try:
|
|
node = mf.parse(add.get("식") or "")
|
|
except mf.FormulaError:
|
|
continue
|
|
if not (
|
|
node[0] == "bin"
|
|
and node[1] == "/"
|
|
and node[3] == ("num", Decimal(100))
|
|
and node[2][0] == "bin"
|
|
and node[2][1] == "*"
|
|
):
|
|
continue # 금액 식(기계손료 등) · 조건부 % = 「식」 그대로
|
|
base, part = node[2][2], node[2][3]
|
|
try:
|
|
rate = mf.evaluate(part, dict(env), whole)
|
|
except (mf.FormulaError, ArithmeticError, KeyError, TypeError, ValueError):
|
|
continue
|
|
if isinstance(rate, Decimal):
|
|
out[head + n] = {**out[head + n], "율": rate, "규격": _pct_base_name(base)}
|
|
return out
|
|
|
|
|
|
def _pct_base_name(node: tuple) -> str:
|
|
"""% 덧줄 밑수 이름 — B09 대가(`B09_Estimation_Labor_Source._base_of`)와 같은 말."""
|
|
if node[0] == "name":
|
|
return f"{node[1]}의 %" # 노무비 · 재료비 · 경비 · 중간값 이름
|
|
if node[0] == "field" and node[1] == ("name", "줄"):
|
|
return f"{node[2]}의 %"
|
|
parts = list(mf.walk(node))
|
|
if any(x[0] == "ref" and str(x[1]).startswith("LB") for x in parts) and not any(
|
|
x[0] == "name" and x[1] in COSTS for x in parts
|
|
):
|
|
return "인건비의 %"
|
|
return ""
|