- 화면: 「내역 점검」 카드 [단가 갱신] 단추 · 점 배지 · 호버 · 미리 보기 창([재생성] · [적용]) 걷음 · 연결 점검 목록 그대로 - 서버: POST …/estimation/prices · …/prices/preview 걷음(openapi 469 → 467) · GET 답 `book` · `stale` 칸(매 GET 단가 책 견줌) 걷음 - B09_Estimation_Refresh · B09_Estimation_Copy_Prices 지움(사본 단가 읽기 = 단가.json 바로) · Bill_Library 서고 다시 굳힘(changed · refresh_copy) 걷음 - 단가 책: 첫 굳힘 `make_book`(옛 refresh_book 의 단가 갱신 몫 · book_stale · book_diff · labor_editions 걷음) - 시험: 죽은 길만 보던 test_296 · test_703_3 지움 · 203_1 배지 · 795_4 ⑤ ⑥ · 719_2 서고 업데이트 지움 · 144 길 = 없음 확인 - test_253_3: B9-4 화면 꼴 뒤 낡은 단언(엑셀 꼴 식 글)을 작업량 값 줄로 고침 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
607 lines
31 KiB
Python
607 lines
31 KiB
Python
"""B09 단가산출근거 · 단가산출근거목록표(PLAN 145-1) — 서버 단독(③ · 화면 짝 없음 · 저장 안 함).
|
||
|
||
산근 호표(155-4 · 엑셀 꼴 · 145 정함 뒤집음) = 연결된 사본(`linked_snapshots` · 143-1)의
|
||
단가산출 줄(일위대가화 아닌 돈 로직 줄 · 입력값 = 사본 `입력값.json` · 빈 입력 = 자동값) +
|
||
사전조합(SC 참조 · 굳힌 `참조사본`) 안 단가산출 줄(입력값 = 그 문서 값) +
|
||
일위대가화 줄(승격 · 옛 SP)의 하위 로직 줄(기계경비 밖 · 입력 = 부르는 식 값)
|
||
— 노무 · 자재 · 중기 줄은 각 목록표(산근 아님) · 일위대가화 줄 자체 = 대가(145-2 블록)
|
||
같은 로직 + 같은 입력값(+ 켜쌓기율 · 고른 자재) = 산근 하나(`sangeun_key`) ·
|
||
번호 = 첫 등장 차례 ·
|
||
로직 줄이 부르는 다른 돈 로직(기계경비 밖) = 하위 산근(그 산근도 목록에 · 산근 → 산근).
|
||
풀이 = 사본 수식 문서(`수식.json`)를 M02 와 같은 계산기로 셈한 답 + 셈 기록(`B09_Estimation_Doc_Run` ·
|
||
855-F B9-3)에서 줄마다 수량 · 단가 · 자원 키 · 하위 산근 · % 줄 율 · 끝수를 읽음(옛 엔진 안 부름) ·
|
||
줄 이름 · 단위 · 종류 = 수식 문서(`Doc_Run.row_of` · B9-6) · 산출근거 글 = 풀이 블록 + 문서
|
||
셈 답(B9-4) ·
|
||
단가 = B09 프로젝트 한 벌 굳힌 단가(144 · `compute_base` 표) — 노무 = 노무비목록표 ·
|
||
중기 = 중기목록표 노 · 재 · 경 · 재료 = 자재단가대비표 적용 단가 ·
|
||
% 줄(덧줄) = 엔진 식에 B09 비목 합.
|
||
끝수 = 엑셀 자리 — 수량 = 결과단위 1 단위(÷ 배) ·
|
||
작업량 Q(중간 이름 Q · Q1 …) = ROUND(식, 2) 뒤 쓰임 ·
|
||
줄 금액 = ROUNDDOWN(단가 × 수량, 1) 비목마다 · 총계 = 비목마다 ROUNDDOWN(Σ, 0) · 합계 = 셋 합.
|
||
빈칸 규칙 = 단가 · 수량을 낸 원천이 없으면 그 칸 · 그 비목 총계 None(0 을 채우지 않음)
|
||
+ 「연결 없음」.
|
||
조합 밖 토공 · 운반 · 사토 산근 · 준비공 = 원천 없음(만들지 않음 · 목록 안내 한 줄).
|
||
대가(145-2) · 내역서(145-3)가 읽는 길 = `sangeun_key` + `price_of`.
|
||
손 줄 산근(166-2) = 설계내역서 손 줄이 고른 M01 로직(`ref` tab logic) — 마스터 로직을 같은 풀이로 ·
|
||
번호 = 사본 산근 뒤 · 쓰는 곳 = 「손 줄 명칭」 ·
|
||
`sg_hand{줄 키: 산근 키}` 로 내역서가 단가를 읽음.
|
||
텍스트 수식(155-5) = `B09_Estimation_Sangeun_Text`(같은 B09 단가) — `head`(머리 · 입력 · 중간) ·
|
||
줄 `text`(줄마다 · 중기 = 노 · 재 · 경 세 줄) · `foot`(계) · % 덧줄 = 규격 「노무비의 %」 ·
|
||
수량 = 율 · 단위 %(149-4 `pct_extras`).
|
||
계산서 줄 덧칸(719-4) = 줄 `sheet`{쓰는입력 · 기준단위 · 환산근거} · 블록 `기준단위` —
|
||
화면 공용 계산서(`B09_Estimation_UI_Tabs_Sangeun_Sheet`) ·
|
||
덮개(719-3) = `B09_Estimation_Sangeun_Cover`(풀이 뒤 덧씌움).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
import hashlib
|
||
import json
|
||
import re
|
||
from decimal import Decimal
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from B08_Quantity.B08_Quantity_Haul_Cycle import fill_given
|
||
from B09_Estimation import B09_Estimation_Doc_Run as dr
|
||
from B09_Estimation import B09_Estimation_Sangeun_Sum as ss
|
||
from B09_Estimation import B09_Estimation_Sangeun_Text as st
|
||
from B09_Estimation import B09_Estimation_Sheet as sheet
|
||
from B09_Estimation.B09_Estimation_Calc_Base import SUPPLY, gap, num, rounddown, total
|
||
from B09_Estimation.B09_Estimation_Store import ref_rows
|
||
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
|
||
from M02_MasterTemplete import M02_Item_Prices as item_prices
|
||
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
|
||
from M02_MasterTemplete.M02_Item_Snapshot import (
|
||
PICKS_FILE,
|
||
VALUES_FILE,
|
||
linked_snapshots,
|
||
structures_dir,
|
||
)
|
||
from M02_MasterTemplete.M02_Item_Source import LABOR_FILE, PRICE_FILE, read_json
|
||
|
||
|
||
PARTS = ("labor", "material", "expense")
|
||
COST_PART = {"노무비": "labor", "재료비": "material", "경비": "expense"}
|
||
PART_COST = {v: k for k, v in COST_PART.items()}
|
||
PCT_OF = {**COST_PART, "인건비": "people"} # % 덧줄 밑수 → 덮개 다시 셈(719-3)
|
||
DEPTH = 4 # 하위 산근 깊이 상한
|
||
NO_SOURCE = "조합 밖 토공 · 운반 · 사토 · 준비공은 산근 없음"
|
||
EMPTY = "연결된 구조물 조합 사본에 단가산출 줄 없음 — 연결 없음"
|
||
|
||
|
||
# ── 산근 정체 ─────────────────────────────────────────────────────────
|
||
def _clean_given(given: Any) -> dict[str, Any]:
|
||
return {
|
||
str(k): v for k, v in sorted((given or {}).items()) if v not in (None, "") and k != "줄"
|
||
}
|
||
|
||
|
||
def sangeun_key(code: str, given: Any = None, rate: Any = None, picks: Any = None) -> str:
|
||
"""산근 이름표 — 같은 로직 + 같은 입력값(+ 켜쌓기율 · 고른 자재)이면 같은 글.
|
||
145-2 대가 · 145-3 내역서가 승격 줄에서 이 글을 만들어 `price_of` 로 단가를 읽음."""
|
||
body = {
|
||
"입력값": _clean_given(given),
|
||
"율": None if rate in (None, 100) else float(rate),
|
||
"고름": {str(k): v for k, v in sorted((picks or {}).items())},
|
||
}
|
||
text = json.dumps(body, ensure_ascii=False, sort_keys=True, default=str)
|
||
return f"SG:{code}:{hashlib.sha1(text.encode('utf-8')).hexdigest()[:10]}"
|
||
|
||
|
||
def price_of(sheets: dict[str, Any], key: str) -> dict[str, Any] | None:
|
||
"""산근 한 줄 단가 `{no, labor, material, expense, sum}`(1 단위 · 빈칸 = None) — 없으면 None."""
|
||
for row in sheets.get("sg_list") or []:
|
||
if row["key"] == key:
|
||
return {k: row[k] for k in ("no", *PARTS, "sum")}
|
||
return None
|
||
|
||
|
||
def _values(values: dict[str, Any], code: str) -> dict[str, Any]:
|
||
return {name: (one or {}).get("값") for name, one in (values.get(code) or {}).items()}
|
||
|
||
|
||
def rows_of(folder: Path, whole: Any = None, docs: dict | None = None) -> list[dict[str, Any]]:
|
||
"""사본 하나의 산근 원천 줄(차례대로) — 단가산출 줄 · 사전조합 안 단가산출 줄 ·
|
||
일위대가화 줄(승격 · 옛 SP)의 하위 로직 줄. 키 = 대가 블록 산근 줄 키(`Labor_Source`)와 같음 ·
|
||
`docs` = 사본 수식 문서(없으면 `수식.json`)."""
|
||
from M02_MasterTemplete import M02_Labor_Ref as refs
|
||
|
||
labor = read_json(folder / LABOR_FILE)
|
||
if not isinstance(labor, dict):
|
||
return []
|
||
docs = dr.docs_of(folder) if docs is None else docs
|
||
if whole is None:
|
||
whole = dr.load((read_json(folder / PRICE_FILE) or {}), docs)
|
||
values = read_json(folder / VALUES_FILE) or {}
|
||
picks = read_json(folder / PICKS_FILE) or {}
|
||
copies = labor.get("참조사본") or {}
|
||
out: list[dict[str, Any]] = []
|
||
|
||
def logic_line(code: str, given: Any, rate: Any, chosen: Any, promoted: bool) -> None:
|
||
if not is_money(whole, code, docs):
|
||
return
|
||
if not promoted:
|
||
out.append({"code": code, "given": _clean_given(given), "rate": rate, "picks": chosen})
|
||
return
|
||
for call in line_calls(whole, code, given, chosen, docs).values():
|
||
if call and call.get("code"):
|
||
out.append({"code": call["code"], "given": call["given"], "rate": None,
|
||
"picks": None}) # fmt: skip
|
||
|
||
def walk(lines: list, inner: bool, depth: int) -> None:
|
||
for one in lines:
|
||
if not isinstance(one, dict):
|
||
continue
|
||
ref = one.get("참조")
|
||
if isinstance(ref, dict):
|
||
doc = copies.get(refs.ref_id(ref))
|
||
if not isinstance(doc, dict) or depth >= refs.DEPTH:
|
||
continue
|
||
if refs.kind_of(ref.get("키")) == "sangeun": # 사본 SK(719-2) = 대가 · 하위 = 산근
|
||
from B09_Estimation.B09_Estimation_Linked import sk_answer
|
||
|
||
got = sk_answer(doc) # 수식 사본 문서 셈(855-F B9-5) — 줄이 부른 하위 단가산출
|
||
for x in got.lines if got else []:
|
||
call = x.get("부름") or {}
|
||
if call.get("code"):
|
||
out.append({"code": call["code"], "given": call.get("given") or {},
|
||
"rate": None, "picks": None}) # fmt: skip
|
||
continue
|
||
if refs.kind_of(ref.get("키")) == "promote": # 옛 SP = 일위대가화
|
||
first = (doc.get("담은로직") or [None])[0]
|
||
if isinstance(first, dict) and first.get("로직"):
|
||
logic_line(str(first["로직"]), first.get("입력값"),
|
||
first.get("켜쌓기율"), first.get("고름"), True) # fmt: skip
|
||
continue
|
||
walk(doc.get("담은로직") or [], True, depth + 1) # 사전조합 = 굳힌 값
|
||
continue
|
||
if not one.get("로직"):
|
||
continue
|
||
code = str(one["로직"])
|
||
given = one.get("입력값") if inner else _values(values, code)
|
||
chosen = one.get("고름") if inner else (picks.get(code) or one.get("고름"))
|
||
logic_line(code, given, one.get("켜쌓기율"), chosen, one.get("승격") is True)
|
||
|
||
walk((labor.get("줄") or {}).get("담은로직") or [], False, 0)
|
||
return out
|
||
|
||
|
||
# ── 풀이 ──────────────────────────────────────────────────────────────
|
||
def _unit(row: dict) -> tuple[str, Decimal]:
|
||
"""결과단위 1 단위 — (단위, 배)(「원/10㎡」 = ㎡ · 10) · 알약 규칙(`combo_pills`) 그대로 ·
|
||
줄 = 사본 단가 묶음 것(M01 다시 안 읽음 · 719-2)."""
|
||
per = combo_store.mu.per(row.get("결과단위")) # 712-2 단위 한 벌
|
||
if not per:
|
||
return "", Decimal(1)
|
||
unit = " · ".join(dict.fromkeys(u for _, u in per))
|
||
return unit, Decimal(per[0][0]) if len(per) == 1 else Decimal(1)
|
||
|
||
|
||
def unit_of(whole: Any, code: str, docs: dict | None = None) -> str:
|
||
"""산근 1 단위 이름(「원/10㎡」 = ㎡) — 수식 문서 결과단위(`docs` = 사본 수식 문서)."""
|
||
row = dr.row(whole, {} if docs is None else docs, code)
|
||
return _unit(row)[0] if row else ""
|
||
|
||
|
||
def is_money(whole: Any, code: str, docs: dict | None = None) -> bool:
|
||
"""돈 문서(금액 줄 꼴)인지 — 없는 문서 · 결과 문서 = 아님(수식 문서 · 855-F B9-6)."""
|
||
row = dr.row(whole, {} if docs is None else docs, code)
|
||
return row is not None and "결과" not in row
|
||
|
||
|
||
def call_of(line: dict) -> dict[str, Any] | None:
|
||
"""문서 셈 줄(`Doc_Run` 줄) → 부른 것 — 기계경비 `{machine: EQ 키 | None}` · 다른 돈 문서
|
||
`{code, given}`(하위 산근) · 단가가 단가산출 부름 아님 = None.
|
||
대가 품셈 줄(`B09_Estimation_Labor_Source`)과 산근 풀이가 같은 판정을 씀."""
|
||
call = line.get("부름")
|
||
if not call:
|
||
return None
|
||
if "machine" in call:
|
||
return {"machine": call["machine"]}
|
||
return {"code": call["code"], "given": _clean_given(call["given"])}
|
||
|
||
|
||
_LOGIC = re.compile(r"\s*로직\(\s*([A-Z]{2}\d+)") # 호표 요소 「로직(키, …)」 의 키
|
||
|
||
|
||
def frozen_machine(whole: Any, docs: dict, item: dict, line: dict) -> dict[str, Any] | None:
|
||
"""굳은 기계 단가 줄(847-1 · 문서 = 숫자 묶음 · 셈 기록에 하위 부름 없음) → `{machine}` — 기계 키 =
|
||
로직 원문 요소 「로직(키 …)」 문서의 셈 기록 첫 기계 · 묶음 단가 아님 = None."""
|
||
if not isinstance(line.get("단가"), dict):
|
||
return None
|
||
hit = _LOGIC.match(str(item.get("요소") or ""))
|
||
got = dr.solve(whole, docs, hit.group(1)) if hit else None
|
||
keys = [k for k in (got.resources if got else []) if k[:2] == "EQ"]
|
||
return {"machine": keys[0] if keys else None}
|
||
|
||
|
||
def logic_call(whole: Any, docs: dict, item: dict | None, line: dict) -> dict[str, Any] | None:
|
||
"""로직 호표 줄의 부른 것 — 하위 부름(`call_of`) · 굳은 기계 단가(`frozen_machine`) · 로직 줄 아님 = None."""
|
||
if not item or item.get("종류") != "로직":
|
||
return None
|
||
return call_of(line) or frozen_machine(whole, docs, item, line)
|
||
|
||
|
||
def line_calls(
|
||
whole: Any, code: str, given: Any, picks: Any = None, docs: dict | None = None
|
||
) -> dict[int, dict | None]:
|
||
"""로직 하나의 로직 호표 줄마다 `call_of`(호표 차례 n → 부른 것) — 못 셈 줄 = None ·
|
||
셈 = 문서 셈 답(`Doc_Run` · `docs` = 사본 수식 문서 · 없으면 그 자리 닫힌 묶음)."""
|
||
docs = {} if docs is None else docs
|
||
row = dr.row(whole, docs, code)
|
||
if row is None:
|
||
return {}
|
||
got = dr.solve(
|
||
whole,
|
||
docs,
|
||
code,
|
||
_clean_given(given),
|
||
picks,
|
||
None,
|
||
ss.doc_shown(row),
|
||
)
|
||
if got is None:
|
||
return {}
|
||
return {
|
||
n: logic_call(whole, docs, item, got.lines[n]) if n < len(got.lines) else None
|
||
for n, item in enumerate(row.get("호표", []))
|
||
if item.get("종류") == "로직"
|
||
}
|
||
|
||
|
||
def spec_text(whole: Any, given: dict[str, Any]) -> tuple[str, str]:
|
||
"""규격 글(157-3) → (보일 글, 원문번호 글) — 기계 · 직종 번호 = 「이름 규격」(M02 85-1)."""
|
||
|
||
def shown(name: str, value: Any) -> Any:
|
||
if not isinstance(value, str):
|
||
return value
|
||
return labor_inputs._labels(whole, {"이름": name, "고르기": [value]}).get(value, value)
|
||
|
||
raw = ", ".join(f"{k}={v}" for k, v in given.items())
|
||
return ", ".join(f"{k}={shown(k, v)}" for k, v in given.items()), raw
|
||
|
||
|
||
def _float(value: Any) -> Any:
|
||
return float(value) if isinstance(value, Decimal) else value
|
||
|
||
|
||
def _money(price: float | None, qty: float | None) -> float | None:
|
||
"""줄 금액 = ROUNDDOWN(단가 × 수량, 1)(엑셀 자리)."""
|
||
return None if price is None or qty is None else rounddown(price * qty, 1)
|
||
|
||
|
||
def block_totals(lines: list[dict[str, Any]]) -> dict[str, float | None]:
|
||
"""총계 — 비목마다 ROUNDDOWN(Σ 줄 금액, 0) · 합계 = 셋 합 · 빈칸 하나면 그 비목 · 합계 빈칸."""
|
||
out: dict[str, float | None] = {}
|
||
for part in PARTS:
|
||
s = total([ln[part] for ln in lines])
|
||
out[part] = None if s is None else rounddown(s, 0)
|
||
return {**out, "sum": total([out[p] for p in PARTS])}
|
||
|
||
|
||
class Solver:
|
||
"""한 번 셈 — 산근 블록을 첫 등장 차례로 모음(하위 산근 포함)."""
|
||
|
||
def __init__(self, supply: Any = None) -> None:
|
||
self.supply = supply or (lambda key: None) # 자재 키 → 관급 · 별도 · None(841-1)
|
||
self.eng: list[dict[str, Any]] = [] # 지금 푸는 로직의 문서 셈 줄(금액 줄 차례 · 841-1)
|
||
self.blocks: dict[str, dict[str, Any]] = {}
|
||
self.shelf = dr.Shelf() # 값 색인 → 사본 수식 문서(`collect` 가 사본마다 둠)
|
||
|
||
def add(
|
||
self, whole: Any, src: dict[str, Any], owner: str | None, depth: int = 0
|
||
) -> dict[str, Any]:
|
||
key = sangeun_key(src["code"], src["given"], src.get("rate"), src.get("picks"))
|
||
if key not in self.blocks:
|
||
self.blocks[key] = {"key": key, "no": len(self.blocks) + 1, "uses": []} # 자리 먼저
|
||
self.blocks[key].update(self._solve(whole, src, depth))
|
||
if owner and owner not in self.blocks[key]["uses"]:
|
||
self.blocks[key]["uses"].append(owner)
|
||
return self.blocks[key]
|
||
|
||
def _solve(self, whole: Any, src: dict[str, Any], depth: int) -> dict[str, Any]:
|
||
code = src["code"]
|
||
docs = self.shelf.of(whole)
|
||
doc = dr.doc(whole, docs, code) # 수식 문서(855-F B9-6 · 옛 로직 줄 안 읽음)
|
||
if doc is None:
|
||
return self._stop(code, code, f"수식 문서 없음 「{code}」")
|
||
row = dr.row_of(doc)
|
||
name = str(row.get("이름") or code)
|
||
if "결과" in row:
|
||
return self._stop(code, name, "돈 로직 아님(흐름 · 결과 로직) — 산근 풀이 꼴 없음")
|
||
unit, times = _unit(row)
|
||
rate = Decimal(str(src["rate"])) / 100 if src.get("rate") not in (None, 100) else None
|
||
lines: list[dict[str, Any]] = []
|
||
# 841-1 단가 = M02 셈(문서 셈) 줄 금액 ÷ 수량(켜쌓기율 없이 · 날 값 · B09 단가 책 안 읽음)
|
||
shown = ss.doc_shown(row) # 작업량 Q = ROUND 2(엑셀 자리)
|
||
eng = dr.solve(whole, docs, code, src["given"], src.get("picks"), None, shown)
|
||
if eng is None:
|
||
return self._stop(code, name, f"수식 문서 없음 「{code}」")
|
||
if why := eng.stopped: # 빈 입력 · 셈 멈춤 = 블록 통째 빈칸(옛 엔진과 같게)
|
||
return self._stop(code, name, why)
|
||
scale = (rate or 1) * 100 / times # % 줄 밑 = 1 단위 몫 줄 합(켜쌓기율 · 배 반영)
|
||
per = eng if scale == 100 else dr.solve(whole, docs, code, src["given"],
|
||
src.get("picks"), scale, shown) # fmt: skip
|
||
try:
|
||
for n, item in enumerate(row.get("호표", [])):
|
||
self.eng = eng.lines # 하위 산근 풀이가 바꿔 놓아도 되돌림
|
||
lines.append(self._line(whole, item, n, times, rate, depth))
|
||
ss.doc_places(row, lines) # 줄 자리(792-3)
|
||
self._extras(row, per or eng, lines)
|
||
head = self._text(whole, eng, lines, times, src.get("rate"))
|
||
self._aside(lines)
|
||
sheet.annotate(whole, doc, lines) # 계산서 줄 덧칸(719-4) = 문서
|
||
except (ArithmeticError, KeyError, TypeError, ValueError) as e:
|
||
return self._stop(code, name, str(e) or type(e).__name__)
|
||
sums = ss.doc_totals(eng, lines) # 끝수 · 끝전 · 조정 = 문서 답 끝수(792-3)
|
||
why = next((ln["why"] for ln in lines if ln.get("why")), None)
|
||
foot = st.foot(sums)
|
||
for ln in lines: # 글 = 풀이 단가 셈 그대로 · 별도계상 재료 줄은 끝에 0 원 표시(841-1)
|
||
if "aside" in ln and ln.get("text"):
|
||
ln["text"] = [*ln["text"][:-1], f"{ln['text'][-1]} · 별도계상 = 0.0 원"]
|
||
spec, spec_raw = spec_text(whole, src["given"])
|
||
return {
|
||
"logic": code,
|
||
"name": name,
|
||
"spec": spec,
|
||
"spec_raw": spec_raw,
|
||
"unit": unit,
|
||
"source": row.get("출처") or "",
|
||
"lines": lines,
|
||
**sums,
|
||
"why": why,
|
||
"head": head,
|
||
"foot": foot,
|
||
"기준단위": sheet.base_unit(doc),
|
||
}
|
||
|
||
@staticmethod
|
||
def _stop(code: str, name: str, why: str) -> dict[str, Any]:
|
||
return {"logic": code, "name": name, "spec": "", "spec_raw": "", "unit": "", "source": "",
|
||
"lines": [], **dict.fromkeys(PARTS), "sum": None, "why": why,
|
||
"head": [], "foot": ""} # fmt: skip
|
||
|
||
def _text(self, whole, eng, lines, times, rate) -> list[str]:
|
||
"""산출근거 글(155-5 · B9-4 `Sangeun_Text.render`) — 줄마다 `text` 를 얹고 머리 줄들 · 글을 못 지으면
|
||
빈 글(값은 그대로)."""
|
||
try:
|
||
head, texts = st.render(whole, eng, lines, times=times, rate=rate, no_of=self._no)
|
||
except Exception: # noqa: BLE001 — 글은 보기 · 못 지어도 풀이 값은 살림
|
||
return []
|
||
for ln, text in zip(lines, texts):
|
||
ln["text"] = text
|
||
return head
|
||
|
||
def _no(self, key: Any) -> int | None:
|
||
"""하위 산근 호표 번호(글)."""
|
||
block = self.blocks.get(str(key or ""))
|
||
return block.get("no") if block else None
|
||
|
||
def _aside(self, lines: list[dict[str, Any]]) -> None:
|
||
"""관급 · 별도계상 재료 = 산근 안 0원(841-1 · % 덧줄 밑수는 엔진 값 그대로 · 자재대 · 관급 단락)."""
|
||
for ln in lines:
|
||
key = (ln.get("ref") or {}).get("key")
|
||
if ln["kind"] != "material" or self.supply(key) not in SUPPLY:
|
||
continue
|
||
part = next(iter(ln["price"]), "material")
|
||
ln["aside"], ln[part], ln["price"] = ln[part], 0.0, {part: 0.0}
|
||
|
||
def _each(self, n: int, part: str, q: float) -> float | None:
|
||
"""엔진 줄 n 비목 단가 = 엔진 금액 ÷ 엔진 수량 · 안 쓰는 줄(수량 0) = 0 · 못 셈 = None."""
|
||
x = self.eng[n] if n < len(self.eng) else {}
|
||
qty, money = num(_float(x.get("수량"))), (x.get("비목") or {}).get(PART_COST[part])
|
||
if not qty:
|
||
return 0.0 if q == 0 else None
|
||
return None if money is None else float(money) / qty
|
||
|
||
def _blank(self, item: dict, why: str) -> dict[str, Any]:
|
||
part = COST_PART.get(item.get("비목"), "material")
|
||
return {"kind": "blank", "name": item.get("이름", ""), "spec": "", "qty": None,
|
||
"unit": item.get("단위", ""), "ref": None, "price": {},
|
||
**{p: (None if p == part else 0.0) for p in PARTS}, "why": why} # fmt: skip
|
||
|
||
def _line(self, whole, item, n, times, rate, depth) -> dict[str, Any]:
|
||
x = self.eng[n] if n < len(self.eng) else {}
|
||
if x.get("수량") is None: # 빈 입력 · 못 셈 수량 = 빈 줄(문서 셈 까닭)
|
||
return self._blank(item, x.get("까닭") or "수량을 못 셈")
|
||
qty = x["수량"] / times * (rate or 1)
|
||
q = float(qty)
|
||
base = {"name": item.get("이름", ""), "spec": "", "qty": q, "unit": item.get("단위", "")}
|
||
zero = dict.fromkeys(PARTS, 0.0)
|
||
kind = item.get("종류")
|
||
if kind == "로직":
|
||
return self._logic_line(whole, item, n, x, q, base, zero, depth)
|
||
if kind == "인력":
|
||
key = str(x.get("키") or "") # 노임 키 = 셈 기록(부른 노임 줄)
|
||
price = self._each(n, "labor", q)
|
||
why = None if price is not None else f"노임 단가 없음(M02 엔진) 「{key}」"
|
||
return {**base, **zero, "kind": "labor", "ref": {"tab": "labor", "key": key},
|
||
"price": {"labor": price}, "labor": _money(price, q), "why": why} # fmt: skip
|
||
goods = x.get("품목") or {} # 고른 품목 = 셈 기록 · 자원 키(유가 MO 등)
|
||
key = str(x.get("키") or "")
|
||
part = COST_PART.get(item.get("비목"), "material")
|
||
price = self._each(n, part, q)
|
||
why = None if price is not None else f"자재 단가 없음(M02 엔진) 「{key}」"
|
||
spec = goods.get("규격") or ""
|
||
ref = {"tab": "compare", "key": key}
|
||
return {**base, **zero, "spec": spec, "kind": "material", "ref": ref,
|
||
"price": {part: price}, part: _money(price, q), "why": why,
|
||
"_goods": goods} # fmt: skip
|
||
|
||
def _logic_line(self, whole, item, n, x, q, base, zero, depth) -> dict[str, Any]:
|
||
call = logic_call(whole, self.shelf.of(whole), item, x)
|
||
if call and "machine" in call:
|
||
keys = [call["machine"]] if call["machine"] else []
|
||
price = {p: self._each(n, p, q) for p in PARTS} # 기계 시간당 = M02 엔진 값(841-1)
|
||
m = None not in price.values()
|
||
why = (
|
||
None
|
||
if m
|
||
else f"기계 시간당 없음(M02 엔진) 「{keys[0] if keys else item.get('이름')}」"
|
||
)
|
||
amounts = {p: _money(price[p], q) if m else None for p in PARTS}
|
||
ref = {"tab": "machine", "key": keys[0] if keys else ""}
|
||
return {**base, "kind": "machine", "ref": ref,
|
||
"price": price, **amounts, "why": why} # fmt: skip
|
||
if not call or depth >= DEPTH:
|
||
return {**self._blank(item, "하위 로직을 못 펼침"), **base}
|
||
sub = self.add(whole, {"code": call["code"], "given": call["given"]}, None, depth + 1)
|
||
price = {p: sub.get(p) for p in PARTS}
|
||
why = None if sub.get("sum") is not None else f"하위 산근 {sub['no']} 빈칸"
|
||
return {**base, "kind": "sangeun", "ref": {"tab": "sg", "key": sub["key"]},
|
||
"price": price, **{p: _money(price[p], q) for p in PARTS}, "why": why} # fmt: skip
|
||
|
||
def _extras(self, row, per, lines) -> None:
|
||
"""% 줄(덧줄) — 값 = 문서 셈 답(`per` = 1 단위 몫 셈 · 밑수 = 그때까지 줄 합) · 줄 금액 = 줄 자리 ·
|
||
「X × Y%」 덧줄 = 규격 「노무비의 %」 · 수량 = 율 · 단위 %(149-4) · 앞 줄 빈칸 = 「밑수 빈칸」."""
|
||
heads = len(row.get("호표", []))
|
||
skip = {n for n, x in enumerate(per.lines) if x.get("합밖")}
|
||
for i, extra in enumerate(row.get("덧줄", [])):
|
||
n = heads + i
|
||
sums = ss.doc_sums(skip, lines) # 합밖 · 제외(792-3)
|
||
part = COST_PART.get(extra.get("비목"), "material")
|
||
line = {"kind": "extra", "name": extra["이름"], "spec": extra["식"], "qty": 1.0,
|
||
"unit": "식", "ref": None, **dict.fromkeys(PARTS, 0.0)} # fmt: skip
|
||
if pct := per.pct(n):
|
||
line.update(spec=pct[1] or extra["식"], qty=float(pct[0]), unit="%")
|
||
if of := PCT_OF.get(pct[1].removesuffix("의 %")):
|
||
line["of"] = of # 719-3 덮개 다시 셈 밑수(`Sangeun_Cover`)
|
||
if any(v is None for v in sums.values()):
|
||
lines.append({**line, part: None, "price": {}, "why": "밑수 빈칸"})
|
||
continue
|
||
x = per.lines[n] if n < len(per.lines) else {}
|
||
if x.get("금액") is None:
|
||
lines.append({**line, part: None, "price": {}, "why": x.get("까닭") or "못 셈"})
|
||
continue
|
||
value = float(x["금액"])
|
||
money = ss.doc_cut(value, extra.get("자리")) # 줄 자리(792-3)
|
||
lines.append({**line, "price": {part: value}, part: money, "why": None})
|
||
|
||
|
||
# ── 모음 ──────────────────────────────────────────────────────────────
|
||
LISTED = ("no", "key", "logic", "name", "spec", "spec_raw", "unit", "sum", *PARTS, "uses")
|
||
|
||
|
||
def _input_names(code: str) -> list[str]:
|
||
"""M01 기초 입력 이름 — 지금 수식 문서(855-F B9-6)."""
|
||
from M02_MasterTemplete import M02_Doc_Copy as dc
|
||
|
||
return item_prices.doc_inputs(dc.folder().get(str(code)))
|
||
|
||
|
||
def hand_sources(user: dict[str, Any] | None) -> list[tuple[str, str, dict[str, Any]]]:
|
||
"""설계내역서 손 줄 중 M01 로직 연결 → [(줄 키, 쓰는 곳 글, 산근 원천)] ·
|
||
운반공 줄(253-2 · `haul_dist{줄 키: {L1, L2}}`) = 거리이정표 거리로 로직 입력 다시 채움(정본)."""
|
||
out = []
|
||
dist = (user or {}).get("haul_dist") or {}
|
||
for row in ref_rows(user): # 251-5 거리이정표 운반 연결 포함
|
||
ref = row.get("ref") or {}
|
||
if ref.get("tab") != "logic" or not ref.get("code"):
|
||
continue
|
||
if row["key"] in dist:
|
||
ref = {
|
||
**ref,
|
||
"given": fill_given(ref, _input_names(str(ref["code"])), dist[row["key"]]),
|
||
}
|
||
src = {"code": str(ref["code"]), "given": _clean_given(ref.get("given")),
|
||
"rate": ref.get("rate"), "picks": ref.get("picks")} # fmt: skip
|
||
where = "수기 줄" if row["key"].startswith("hand:") else "내역 줄" # 184 자동 줄 연결 덮개
|
||
out.append((row["key"], f"{where} {row.get('name') or ref.get('name') or row['key']}", src))
|
||
return out
|
||
|
||
|
||
def hand_whole(hands: list[tuple[str, str, dict[str, Any]]]) -> Any:
|
||
"""손 줄 로직의 닫힌 묶음 — 지금 M01 수식 문서 + 그 문서가 잇는 자원 · 표 줄(사본 꼴 · 855-F B9-6 ·
|
||
마스터 캐시는 안 건드림)."""
|
||
from M02_MasterTemplete import M02_Doc_Copy as dc
|
||
from M02_MasterTemplete import M02_Item_Bundle as item_bundle
|
||
|
||
codes = list(dict.fromkeys(src["code"] for _k, _u, src in hands))
|
||
docs = dc.closure(item_prices.master()[1], codes)
|
||
return dr.load(item_prices.to_json(item_bundle.collect(docs)), docs)
|
||
|
||
|
||
def hand_resource_keys(user: dict[str, Any] | None) -> list[str]:
|
||
"""손 줄 로직이 부르는 자원 키(단가 책 수요 · `Linked.used_keys` 꼴) — 부른 차례 · 겹침 없음 ·
|
||
셈 기록(`Doc_Run.resources`)."""
|
||
hands = hand_sources(user)
|
||
if not hands:
|
||
return []
|
||
from B09_Estimation.B09_Estimation_Linked import RESOURCE_TABLES
|
||
|
||
whole, docs = hand_whole(hands), {}
|
||
seen: list[str] = []
|
||
for _key, _use, src in hands: # 자원 키 = 문서 셈 기록(하위 포함 · 고른 품목만)
|
||
got = dr.solve(whole, docs, src["code"], src["given"], src["picks"], src["rate"])
|
||
for key in got.resources if got else []:
|
||
if key[:2] in RESOURCE_TABLES and key not in seen:
|
||
seen.append(key)
|
||
return seen
|
||
|
||
|
||
def collect(
|
||
entries: list[tuple[str, Path]],
|
||
hands: list[tuple[str, str, dict[str, Any]]] | None = None,
|
||
memo: dict[str, Any] | None = None,
|
||
supply: Any = None,
|
||
) -> dict[str, Any]:
|
||
"""`entries` = [(구조물 id, 사본 폴더)] → 블록 · 목록 · 「연결 없음」 ·
|
||
supply = 자재 키 → 관급 · 별도(841-1 · 대비표 표시) ·
|
||
`hands` = 손 줄 로직(166-2 · 사본 뒤 번호 · 마스터 로직) ·
|
||
memo = 같은 사본 · 손 줄의 앞 풀이(두 번 셈) — 앞 풀이가 본 단가가 같으면 그 풀이 사본."""
|
||
if memo and "sg" in memo: # 841-1 풀이 = 사본 · 엔진만(바탕 표 안 읽음) → 앞 풀이 그대로
|
||
return copy.deepcopy(memo["sg"])
|
||
solver = Solver(supply)
|
||
for owner, folder in entries:
|
||
docs = dr.docs_of(folder) # 사본 수식 문서(855-F B9-3)
|
||
whole = solver.shelf.put_whole((read_json(folder / PRICE_FILE) or {}), docs)
|
||
for src in rows_of(folder, whole, docs):
|
||
solver.add(whole, src, owner)
|
||
hand_keys: dict[str, str] = {}
|
||
if hands:
|
||
whole = hand_whole(hands)
|
||
for row_key, use, src in hands:
|
||
hand_keys[row_key] = solver.add(whole, src, use)["key"]
|
||
blocks = sorted(solver.blocks.values(), key=lambda b: b["no"])
|
||
listing = [{k: b[k] for k in LISTED} for b in blocks]
|
||
gaps = [
|
||
gap("sg", b["key"], f"산근 {b['no']} {b['name']}", b["why"] or "단가 빈칸")
|
||
for b in blocks
|
||
if b["sum"] is None
|
||
]
|
||
out = {
|
||
"sg": blocks,
|
||
"sg_list": listing,
|
||
"sg_gaps": gaps,
|
||
"sg_notes": [NO_SOURCE] + ([] if blocks else [EMPTY]),
|
||
"sg_hand": hand_keys,
|
||
}
|
||
if memo is not None:
|
||
memo.update(sg=copy.deepcopy(out))
|
||
return out
|
||
|
||
|
||
def build(
|
||
project_root: str | Path,
|
||
user: dict[str, Any] | None = None,
|
||
memo: dict[str, Any] | None = None,
|
||
supply: Any = None,
|
||
) -> dict[str, Any]:
|
||
"""연결된 사본 전부(구조물 id 차례 → 설계내역서 서고 사본 · 702-3)의 산근 +
|
||
설계내역서 손 줄 로직(166-2 · 뒤 번호) — 차례 = `Labor_Source.daega_inputs` ·
|
||
memo = 같은 root · user 두 번 셈의 앞 풀이(`collect`)."""
|
||
from B09_Estimation.B09_Estimation_Bill_Library import copies
|
||
|
||
base = structures_dir(project_root)
|
||
entries = [
|
||
(owner, base / linked["폴더"])
|
||
for owner, linked in sorted(linked_snapshots(project_root).items())
|
||
if "일위대가" in linked.get("부분", [])
|
||
]
|
||
entries += [
|
||
(f"서고 {(m.get('원본') or {}).get('name') or f.name}", f) for f, m in copies(project_root)
|
||
]
|
||
return collect(entries, hand_sources(user), memo, supply)
|