Merge branch 'sub_laptop_7' of C:/Aislo_wt/sub_laptop_7 into main_laptop_1
This commit is contained in:
@@ -0,0 +1,327 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""단가산출 수식 문서 셈 답 → 산출근거 글(PLAN 855-C 2-C4 · 서버 풀이 글) — 셈 안 함(답만 읽음).
|
||||
|
||||
쓰는 곳 = M02 기준 목록 계산서(`M02_Logic_Standard.sheet`) · (뒤에) B09 산출근거(855 보충 B9-4).
|
||||
⚠ 짝(글 규칙) — 한쪽을 고치면 다른 쪽도 · 거울 시험 `resources/tester/test_855_c4_doc_text.py`:
|
||||
`A00_Common/line_stack_out.ts`(금액 줄 · 계 줄 꼴 · 수 꼴 `one` · `won` · 비목 이름) ·
|
||||
`ui_template/ui_template_equation.ts`(`eqText`) ·
|
||||
`common_util/common_util_line_stack_unit.ts`(`unitText` · `isAtom` · `moneyUnits`) ·
|
||||
`common_util/common_util_formula_doc_view.ts`(`offLine` — 선택으로 꺼진 줄).
|
||||
금액 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」 · 묶음 줄 = 비목마다 「노무비 : …」 ·
|
||||
계 = 「노무비 : 줄 + 줄 = 금액 원」 · 「합계 : 금액 원」.
|
||||
수 꼴 = 화면과 같음 — 단가 · 수량 = `eqText`(소수 여섯 자리까지 · 셈 값 그대로) ·
|
||||
줄 금액 = 소수 한 자리 · 비목 · 합계 = 원(셈 답의 끝수 그대로 · 여기서 자르지 않음).
|
||||
옮기지 않은 것(화면만) — 식 조판(KaTeX · 수량 식은 값 하나로) · 공식 줄 · 펼침 ·
|
||||
작업량 줄(846-2) · 굳은 기계 이름(847-1) · 비목곱 인수 글(848-7 · 금액은 답 그대로) ·
|
||||
계 덧셈 항 = 줄 금액(화면은 묶음 줄 있는 항목 · 항이 넷 넘으면 항목 소계 — 여기는 금액만).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
|
||||
import master_doc as md
|
||||
import master_doc_calc as mc
|
||||
|
||||
COSTS = md.COSTS # 노무비 · 재료비 · 경비
|
||||
COST_SHOW = {"노무비": "노무비", "재료비": "재료비", "경비": "경 비"}
|
||||
AMOUNT_UNIT = "원"
|
||||
LONG_SUM = 4
|
||||
_HIDE = ("반올림", "올림", "버림")
|
||||
_SAME = (("일", "인"), ("㎏", "kg"), ("ℓ", "L"))
|
||||
|
||||
|
||||
# ── 수 꼴 ─────────────────────────────────────────────────────────────
|
||||
def _dec(v) -> Decimal | None:
|
||||
if isinstance(v, bool) or v is None:
|
||||
return None
|
||||
try:
|
||||
d = Decimal(str(v)) if not isinstance(v, Decimal) else v
|
||||
except InvalidOperation:
|
||||
return None
|
||||
return d if d.is_finite() else None
|
||||
|
||||
|
||||
def _group(d: Decimal, places: int, keep: bool) -> str:
|
||||
q = d.quantize(Decimal(1).scaleb(-places), ROUND_HALF_UP)
|
||||
sign = "-" if q.is_signed() else "" # Intl 과 같음 — 0 으로 반올림된 음수 = 「-0」
|
||||
whole, _, frac = f"{abs(q):f}".partition(".")
|
||||
frac = frac if keep else frac.rstrip("0")
|
||||
head = f"{int(whole):,}"
|
||||
return f"{sign}{head}.{frac}" if frac else f"{sign}{head}"
|
||||
|
||||
|
||||
def eq_text(v) -> str:
|
||||
"""`eqText` — 수 = 천 단위 쉼표 · 소수 여섯 자리까지(반올림 · 끝 0 뗌) · 그 밖 = 글 그대로."""
|
||||
if v is None or v == "":
|
||||
return ""
|
||||
if isinstance(v, bool):
|
||||
return "true" if v else "false"
|
||||
d = _dec(v)
|
||||
if d is None or (isinstance(v, str) and not v.strip()):
|
||||
return str(v)
|
||||
return _group(d, 6, False)
|
||||
|
||||
|
||||
def one(v) -> str:
|
||||
"""줄 금액 — 소수 한 자리 꼭(「26,890.8」 · 「0.0」)."""
|
||||
return _group(_dec(v) or Decimal(0), 1, True)
|
||||
|
||||
|
||||
def won(v) -> str:
|
||||
"""비목 · 합계 — 원(JS `Math.round` = 0.5 올림)."""
|
||||
d = _dec(v) or Decimal(0)
|
||||
r = (d + Decimal("0.5")).to_integral_value(ROUND_FLOOR)
|
||||
return eq_text(Decimal("-0") if r == 0 and d.is_signed() else r) # JS Math.round(-0.4) = -0
|
||||
|
||||
|
||||
# ── 단위 ─────────────────────────────────────────────────────────────
|
||||
def unit_text(u) -> str:
|
||||
"""자료 단위 글 → 화면 단위(메타 단위 = 빈 글)."""
|
||||
s = str(u if u is not None else "").strip()
|
||||
if not s or re.search(r"따름|원문 단위 없음", s) or re.match(r"^수(\(| 또는|$)", s):
|
||||
return ""
|
||||
s = re.sub(r"^%\(.*\)$", "%", s)
|
||||
return s.replace("10^-7", "10⁻⁷").replace("kWh", "㎾h")
|
||||
|
||||
|
||||
def _same(a: str, b: str) -> bool:
|
||||
return a == b or any((a == x and b == y) or (a == y and b == x) for x, y in _SAME)
|
||||
|
||||
|
||||
def is_atom(n) -> bool:
|
||||
"""한 덩이(기호 · 수 · 칸 · 글 — 반올림 · 올림 · 버림 감싸개 안 한 덩이 포함)."""
|
||||
if not n:
|
||||
return False
|
||||
if n[0] == "call" and n[1] in _HIDE and 1 <= len(n[2]) <= 2:
|
||||
return is_atom(n[2][0])
|
||||
return n[0] in ("var", "num", "field", "str")
|
||||
|
||||
|
||||
def node_of(text):
|
||||
if text is None or str(text).strip() == "":
|
||||
return None
|
||||
try:
|
||||
return md.parse(text)
|
||||
except md.DocError:
|
||||
return None
|
||||
|
||||
|
||||
def money_units(
|
||||
line: dict, price, qty, price_var: dict | None = None, sub: dict | None = None
|
||||
) -> dict:
|
||||
"""금액 줄 단위 자리 `{price, qty, wrap}` — 수량이 식이면 괄호 ·
|
||||
단가 분모가 수량 단위와 같은 뜻이면 수량 단위 글."""
|
||||
has = line.get("수량") not in (None, "")
|
||||
q = unit_text(line.get("단위")) if has else ""
|
||||
wrap = bool(q) and bool(qty) and not is_atom(qty)
|
||||
own = next(
|
||||
(
|
||||
u
|
||||
for u in (
|
||||
unit_text((sub or {}).get("결과단위")),
|
||||
unit_text((price_var or {}).get("단위")),
|
||||
)
|
||||
if u.startswith("원")
|
||||
), # fmt: skip
|
||||
None,
|
||||
)
|
||||
mine = f"{AMOUNT_UNIT}/{q}" if own and q and _same(own[2:], q) else own
|
||||
fallback = f"{AMOUNT_UNIT}/{q}" if q else ""
|
||||
price_unit = (mine if mine is not None else fallback) if has and is_atom(price) else ""
|
||||
return {"price": price_unit, "qty": q, "wrap": wrap}
|
||||
|
||||
|
||||
def price_sym(line: dict) -> str | None:
|
||||
n = node_of(line.get("단가"))
|
||||
if not n:
|
||||
return None
|
||||
if n[0] == "var":
|
||||
return n[1]
|
||||
if n[0] == "field" and n[1][0] == "var":
|
||||
return n[1][1]
|
||||
return None
|
||||
|
||||
|
||||
def line_name(line: dict) -> str:
|
||||
"""이름에 규격이 들면 한 번만(814-1)."""
|
||||
name, spec = str(line.get("이름") or ""), line.get("규격")
|
||||
return f"{name} {spec}".strip() if spec and spec not in name else name
|
||||
|
||||
|
||||
# ── 선택으로 꺼진 줄(`offLine`) ───────────────────────────────────────
|
||||
class _Look:
|
||||
"""셈 답 값으로 조건만 읽음 — 계산기 한 벌(`master_doc_calc._Run.ev`) · 값은 답에서 채움."""
|
||||
|
||||
def __init__(self, doc: dict, answer: dict, links):
|
||||
self.run = mc._Run(doc, links, None, (), {})
|
||||
got = answer.get("값") or {}
|
||||
names = {md.var_id(v) for v in doc.get("변수") or []}
|
||||
names |= {str(x.get("기호") or "") for x in doc.get("식") or []}
|
||||
for name in names: # 답에 없는 값 = 모름(다시 셈하지 않음 · 화면 `evalNode` 와 같음)
|
||||
have = got.get(name)
|
||||
self.run.values[name] = mc.Blank("모름") if have is None else have
|
||||
self.lines = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []}
|
||||
|
||||
def value(self, n):
|
||||
try:
|
||||
v = self.run.ev(n, None, "")
|
||||
except Exception: # noqa: BLE001 — 그림용 값 · 모르면 없음
|
||||
return None
|
||||
return None if isinstance(v, (mc.Blank, mc.Stop)) else v
|
||||
|
||||
def taken(self, n) -> int:
|
||||
if not (n and n[0] == "call" and n[1] == "만약" and len(n[2]) == 3):
|
||||
return 0
|
||||
t = self.value(n[2][0])
|
||||
return 0 if t is None else (1 if t else 2)
|
||||
|
||||
def off_zero(self, n, path: frozenset = frozenset()) -> bool:
|
||||
if not n:
|
||||
return False
|
||||
at, hop = n, 0
|
||||
while pick := self.taken(at):
|
||||
at, hop = at[2][pick], hop + 1
|
||||
if hop and at[0] == "num":
|
||||
return at[1] == 0
|
||||
kind = at[0]
|
||||
if kind == "var":
|
||||
name = at[1]
|
||||
if name not in self.lines or name in path:
|
||||
return False
|
||||
return self.off_zero(node_of(self.lines[name]), path | {name})
|
||||
if kind in ("neg", "pct"):
|
||||
return self.off_zero(at[1], path)
|
||||
if kind == "bin":
|
||||
if at[1] == "*":
|
||||
return self.off_zero(at[2], path) or self.off_zero(at[3], path)
|
||||
if at[1] == "/":
|
||||
return self.off_zero(at[2], path)
|
||||
if at[1] in ("+", "-"):
|
||||
return self.off_zero(at[2], path) and self.off_zero(at[3], path)
|
||||
return False
|
||||
|
||||
def off_line(self, line: dict) -> bool:
|
||||
return any(self.off_zero(node_of(line.get(k))) for k in ("수량", "단가"))
|
||||
|
||||
|
||||
# ── 줄 글 ────────────────────────────────────────────────────────────
|
||||
def _num(v) -> Decimal | None:
|
||||
return _dec(v)
|
||||
|
||||
|
||||
def _u(text: str, unit: str) -> str:
|
||||
return f"{text} {unit}" if unit else text
|
||||
|
||||
|
||||
def money_lines(doc: dict, answer: dict, links) -> list[dict]:
|
||||
"""금액 줄마다 산출근거 조각 `{i, 이름, 비목, 단가, 수량, 금액, 단위, 글, 꺼짐, 합밖, 까닭?}` ·
|
||||
묶음 줄 = 비목마다 한 조각(`비목` = 노무비 · 재료비 · 경비 · `묶음줄` 참)."""
|
||||
look = _Look(doc, answer, links)
|
||||
vars_ = {md.var_id(v): v for v in doc.get("변수") or []}
|
||||
rows = answer.get("줄") or []
|
||||
out: list[dict] = []
|
||||
for i, line in enumerate(doc.get("금액") or []):
|
||||
got = rows[i] if i < len(rows) else {}
|
||||
name = line_name(line)
|
||||
ps = price_sym(line)
|
||||
pv = vars_.get(ps) if ps else None
|
||||
link = (pv or {}).get("연결") or {}
|
||||
sub = None
|
||||
if link.get("갈래") == "단가산출" and link.get("키") and "{" not in str(link["키"]):
|
||||
try:
|
||||
sub = links.doc(str(link["키"]))
|
||||
except Exception: # noqa: BLE001 — 못 읽는 부름 = 단위 없이
|
||||
sub = None
|
||||
mu = money_units(line, node_of(line.get("단가")), node_of(line.get("수량")), pv, sub)
|
||||
qty = got.get("수량")
|
||||
base = {
|
||||
"i": i,
|
||||
"이름": name,
|
||||
"수량": _num(qty),
|
||||
"단위": mu,
|
||||
"꺼짐": look.off_line(line),
|
||||
"합밖": bool(got.get("합밖")),
|
||||
"묶음": line.get("묶음") or "",
|
||||
}
|
||||
tail = "" if qty is None else " × " + _u(eq_text(qty), mu["qty"])
|
||||
if got.get("까닭") and got.get("금액") is None:
|
||||
why = got["까닭"]
|
||||
out.append({**base, "비목": line.get("비목"), "단가": None, "금액": None, "까닭": why,
|
||||
"글": f"{name} : — {why}"}) # fmt: skip
|
||||
continue
|
||||
if line.get("비목") == "묶음":
|
||||
bundle = got.get("단가") if isinstance(got.get("단가"), dict) else {}
|
||||
for c in COSTS:
|
||||
part = (got.get("비목") or {}).get(c)
|
||||
if _dec(part) is None or (not part and not bundle.get(c)):
|
||||
continue
|
||||
price = _u(eq_text(bundle.get(c)), mu["price"])
|
||||
text = f"{COST_SHOW[c]} : {price}{tail} = {one(part)} {AMOUNT_UNIT}"
|
||||
out.append({**base, "비목": c, "묶음줄": True, "단가": _num(bundle.get(c)),
|
||||
"금액": _num(part), "글": text}) # fmt: skip
|
||||
continue
|
||||
amt, price = got.get("금액"), got.get("단가")
|
||||
text = f"{name} : {_u(eq_text(price), mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}"
|
||||
out.append({**base, "비목": line.get("비목"), "단가": _num(price), "금액": _num(amt),
|
||||
"글": text}) # fmt: skip
|
||||
return out
|
||||
|
||||
|
||||
def total_lines(answer: dict, lines: list[dict]) -> list[str]:
|
||||
"""계 줄 — 비목마다 「노무비 : 줄 + 줄 = 금액 원」(항이 넷 넘으면 금액만) ·
|
||||
「합계 : 금액 원」."""
|
||||
out = []
|
||||
for c in COSTS:
|
||||
terms = [
|
||||
x["금액"]
|
||||
for x in lines
|
||||
if x.get("비목") == c and not x["합밖"] and not x["꺼짐"] and x.get("금액")
|
||||
]
|
||||
v = answer.get(c)
|
||||
if _dec(v) is None:
|
||||
body = "—"
|
||||
elif 1 < len(terms) <= LONG_SUM:
|
||||
body = f"{' + '.join(one(t) for t in terms)} = {won(v)}"
|
||||
else:
|
||||
body = won(v) if terms or v else ""
|
||||
unit = f" {AMOUNT_UNIT}" if _dec(v) is not None and body else ""
|
||||
out.append(f"{COST_SHOW[c]} : {body}{unit}")
|
||||
total = answer.get("계")
|
||||
out.append(f"합계 : {_u(won(total), AMOUNT_UNIT) if _dec(total) is not None else '—'}")
|
||||
return out
|
||||
|
||||
|
||||
def sheet_groups(doc: dict, answer: dict, links) -> list[dict]:
|
||||
"""공용 계산서(`A00_Common/calc_sheet.ts`) 묶음 — 비목마다 줄
|
||||
`{이름, 글 「단가 * 수량 = 금액」, 금액, 묶음, 장비, 옵션꺼짐}` ·
|
||||
소계 = 셈 답 비목 값(끝수 뒤) ·
|
||||
합 밖 줄 · 비목 없는 줄 = 뺌."""
|
||||
groups: dict[str, list] = {c: [] for c in COSTS}
|
||||
for x in money_lines(doc, answer, links):
|
||||
c = x.get("비목")
|
||||
if c not in groups or x["합밖"]:
|
||||
continue
|
||||
mu = x["단위"]
|
||||
if x.get("까닭"):
|
||||
text = f"— {x['까닭']}"
|
||||
else:
|
||||
price = "—" if x["단가"] is None else _u(eq_text(x["단가"]), mu["price"])
|
||||
qty = "" if x["수량"] is None else " * " + _u(eq_text(x["수량"]), mu["qty"])
|
||||
text = f"{price}{qty} = {one(x['금액'] or 0)}"
|
||||
groups[c].append(
|
||||
{
|
||||
"이름": x["이름"],
|
||||
"글": text,
|
||||
"금액": x["금액"],
|
||||
"묶음": x["묶음"] or None,
|
||||
"장비": bool(x.get("묶음줄")) or None,
|
||||
"옵션꺼짐": x["꺼짐"] or None,
|
||||
}
|
||||
)
|
||||
return [
|
||||
{"비목": c, "소계": _num(answer.get(c)), "끝수": "", "줄": groups[c]}
|
||||
for c in COSTS
|
||||
if groups[c] or _dec(answer.get(c))
|
||||
]
|
||||
Reference in New Issue
Block a user