feat(855-C): 2-C4 기준 목록 · 계산서를 수식 문서 셈으로 · 서버 산출근거 글 모듈 새로

- 새 `master_doc_text.py` — 문서 셈 답 → 산출근거 글(금액 줄 · 묶음 줄 · 계 줄 · 계산서 묶음) · 화면 짝(line_stack_out · eqText · unitText · moneyUnits · offLine) 규칙을 옮김 · 거울 시험 `test_855_c4_doc_text`(+ helper .cjs)
- `M02_Logic_Standard` — 기준 목록 축 = 문서 선택 변수 · 표 조건 입력 변수 · 바탕 = 문서 기본값 · 금액 = 문서 셈 · 계산서 = 문서 셈 + 새 글 · 파생 저장본 열쇠에 수식 문서 지문(SHAPE 4) · 답 꼴 그대로(화면 안 고침) · `M02_Logic_Settle` 은 B09 짝이라 남김
- 전수(1,521 기초 · 옛 줄 11,267): 같은 입력이면 금액 같음 11,165 · 다름 101 = 옛 목록만의 B09 산근 끝수(settle) — 새 값 = 옛 엔진 값 = M02 단가산출 값 · 옛 엔진 멈춤 1(새 0 원 줄은 목록에서 빠짐)
- 바탕 = 문서 기본값(옛 = master_auto 자동값) — 114 기초의 바탕 줄 규격이 바뀜(시험입력 · 기본 칸을 담은 문서 기본값)
- 시험 고침: test_704_logic_standard(옛 엔진 끝수 차 3 원 허용 → 수식 탭 셈과 같음) · test_704_settle(축 · 금액 인자가 문서) · test_714_1 의 「M01 /text 와 M02 계산서가 같은 줄 꼴」 시험 지움(M02 계산서가 옛 덧칸 길을 안 탐 — 까닭: 855-C 새 길)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 17:59:31 +09:00
co-authored by Claude Opus 5.5
parent c2ea206f6a
commit c42d66ad68
7 changed files with 672 additions and 87 deletions
@@ -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))
]
@@ -0,0 +1,71 @@
/* 855-C 2-C4 거울 헬퍼 — 산출근거 글 규칙(TS)을 Node 로 돌림(`master_doc_text.py` 짝).
* stdin = {수: [값], 단위: [글], 금액줄: [{줄, 단가변수, 부름}], 꺼짐: [{문서, 값}], 원: [수]}
* stdout = {eq: [eqText], one: [one], won: [won], 단위: [unitText], 금액줄: [moneyUnits],
* 꺼짐: [[offLine …] …], 비목: COST_SHOW, 항: LONG_SUM}
* `one` · `won` · `COST_SHOW` · `LONG_SUM` = `line_stack_out.ts` 안 정의를 그대로 읽어 돌림(내보내지 않는 값). */
const fs = require("fs");
const path = require("path");
const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript"));
const cache = new Map();
function load(at) {
if (cache.has(at)) return cache.get(at);
const js = ts.transpileModule(fs.readFileSync(at, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
cache.set(at, box.exports);
const need = (p) => {
if (p.endsWith(".css")) return {};
return p.startsWith(".") ? load(path.resolve(path.dirname(at), `${p}.ts`)) : require(p);
};
new Function("exports", "module", "require", js)(box.exports, box, need);
return box.exports;
}
const ROOT = path.join(__dirname, "..", "..");
const eq = load(path.join(ROOT, "ui_template", "ui_template_equation.ts"));
const unit = load(path.join(ROOT, "common_util", "common_util_line_stack_unit.ts"));
const view = load(path.join(ROOT, "common_util", "common_util_formula_doc_view.ts"));
const stack = load(path.join(ROOT, "common_util", "common_util_line_stack.ts"));
// line_stack_out.ts 안 정의(내보내지 않음) — 그 줄 글을 그대로 떼어 돌림
const out = fs.readFileSync(path.join(ROOT, "A00_Common", "line_stack_out.ts"), "utf8");
const grab = (re) => {
const m = out.match(re);
if (!m) throw new Error(`line_stack_out.ts 에서 못 찾음: ${re}`);
return m[0];
};
const defs = [
grab(/const COST_SHOW: Record<string, string> = \{[^}]*\};/),
grab(/const won = \(n: number\): string => [^;]*;/),
grab(/const one = \(n: number\): string =>\s*n\.toLocaleString\([^;]*;/),
grab(/const LONG_SUM = \d+;/),
].join("\n");
const js = ts.transpileModule(`${defs}\nreturn { COST_SHOW, won, one, LONG_SUM };`, {
compilerOptions: { target: ts.ScriptTarget.ES2020 },
}).outputText;
const local = new Function("eqText", js)(eq.eqText);
const input = JSON.parse(fs.readFileSync(0, "utf8"));
const res = {
eq: (input.수 || []).map((v) => eq.eqText(v)),
one: (input.원 || []).map((v) => local.one(v)),
won: (input.원 || []).map((v) => local.won(v)),
단위: (input.단위 || []).map((u) => unit.unitText(u)),
금액줄: (input.금액줄 || []).map((x) =>
unit.moneyUnits(
x.줄,
view.tryParse(x.줄.단가),
view.tryParse(x.줄.수량),
x.단가변수 || undefined,
x.부름 || null,
),
),
기호: (input.금액줄 || []).map((x) => stack.priceSym(x.줄)),
꺼짐: (input.꺼짐 || []).map((x) =>
(x.문서.금액 || []).map((line) => view.offLine(line, x.값, view.lineMap(x.문서))),
),
비목: local.COST_SHOW,
항: local.LONG_SUM,
};
process.stdout.write(JSON.stringify(res));
+10 -6
View File
@@ -11,10 +11,12 @@
from __future__ import annotations
import json
from pathlib import Path
import pytest
from M01_MasterData import M01_MasterData_Doc as m01_doc
from M01_MasterData import M01_MasterData_Store as m01
from M01_MasterData.M01_MasterData_Store_Find import hit
from M02_MasterTemplete import M02_Logic_Standard as st
@@ -30,18 +32,20 @@ def _rows(key: str) -> list[dict]:
def _given(key: str, change: dict) -> dict:
whole = m01.loaded()[1]
return st._given(whole, whole.logic(key), change)[0]
return st._given(whole, m01_doc.docs()[key], change)[0]
@pytest.mark.parametrize("key", THREE)
def test_줄_금액은_M01_시험_계산에_끝수만_버림(key: str) -> None:
def test_줄_금액은_M01_수식_탭_셈과_같음(key: str) -> None:
"""855-C — 기준 목록 금액 = 수식 문서 셈(M01 수식 탭 미리 셈 · M02 단가산출과 같은 계산기)."""
rows = _rows(key)
assert rows
doc = json.loads(json.dumps(m01_doc.docs()[key], default=float)) # 화면 JSON 꼴 문서
for row in rows:
got = m01.calc(key, _given(key, row["바꿈"]))
assert got["ok"], got
gap = float(got["sums"]["계"]) - row["금액"] # 줄 · 비목 버림(B09 산근 규칙) — 최대 3 원
assert -0.01 <= gap < 3.2, row["규격"]
given = st.labor_inputs._num(_given(key, row["바꿈"]))
got = m01_doc.preview(doc, given)["셈"]
assert got["셈됨"], row["규격"]
assert float(got["계"]) == row["금액"], row["규격"]
def test_대표_규격_펼침() -> None:
+4 -4
View File
@@ -13,6 +13,7 @@ if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from B09_Estimation import B09_Estimation_Sangeun as sg # noqa: E402
from M01_MasterData import M01_MasterData_Doc as m01_doc # noqa: E402
from M01_MasterData import M01_MasterData_Store as m01 # noqa: E402
from M02_MasterTemplete import M02_Logic_Settle as st # noqa: E402
from M02_MasterTemplete import M02_Logic_Standard as ls # noqa: E402
@@ -39,7 +40,7 @@ def test_줄마다_버림_비목마다_버림_B09와_같음():
for row in data.get("줄") or []:
if not _plain(row) or checked >= 60:
continue
base, _ = ls.axes(whole, row)
base, _ = ls.axes(whole, m01_doc.docs()[row["키"]])
given = mf.fill_empty(row, base)
got = mf.run(whole, row["키"], given)
lines = []
@@ -70,6 +71,5 @@ def test_계산서_줄_소계_계가_맞물림():
assert group["소계"] == int(group["소계"])
assert group["소계"] <= sum(lines) < group["소계"] + 1 + Decimal("0.05"), group["비목"]
assert got["계"] == sum(g["소계"] for g in got["묶음"])
assert got["계"] == ls._money(
whole, whole.logic(key), ls._given(whole, whole.logic(key), {})[0]
)
doc = m01_doc.docs()[key] # 855-C 계산서 = 문서 셈(목록 금액과 같은 값)
assert got["계"] == ls._money(doc, ls._links(whole), ls._given(whole, doc, {})[0])
+2 -16
View File
@@ -1,5 +1,5 @@
"""714-1 지킴 — 계산서 줄 덧칸(쓰는 입력 · 묶음 · 기준단위 · 환산 근거) · M01 `/text` 와
M02 `/logic-lib/sheet` 가 같은 줄 꼴(`master_sheet_line`)."""
"""714-1 지킴 — 계산서 줄 덧칸(쓰는 입력 · 묶음 · 기준단위 · 환산 근거) — M01 `/text`.
(M02 `/logic-lib/sheet` 는 855-C 부터 문서 셈 · `master_doc_text` 글 — `test_855_c4_doc_text`.)"""
from __future__ import annotations
@@ -11,10 +11,8 @@ sys.path.insert(0, str(ROOT))
from M01_MasterData import M01_MasterData_Store as store # noqa: E402
from M01_MasterData import M01_MasterData_Store_Sheet as sheet # noqa: E402
from M02_MasterTemplete import M02_Logic_Standard as standard # noqa: E402
msl = sheet.msl
num = standard.labor_inputs._num # Decimal → JSON 수(두 길 같은 규칙)
def _text(key: str) -> dict:
@@ -61,15 +59,3 @@ def test_basis_note_tenfold():
assert one[0]["기준단위"] == "10㎡" and one[0]["환산근거"] == "10㎡당 → 1㎡당 ÷10"
ten = _text("GF000124")
assert ten["기준단위"] == "10㎡" and all(not x["환산근거"] for x in _lines(ten))
def test_two_routes_same_shape():
"""M01 `/text` 와 M02 계산서 — 줄 차례 · 덧칸 값이 같음(금액 끝수만 다를 수 있음)."""
for key in ("GF000169", "GF000103", "GF000219"):
m01 = _lines(_text(key))
m02 = _lines(standard.sheet(key, {}), "묶음")
assert len(m01) == len(m02)
for a, b in zip(m01, m02):
assert set(b) == {"이름", "글", "금액", *msl.KEYS}
assert a["이름"] == b["이름"]
assert num([a.get(k) for k in msl.KEYS]) == [b.get(k) for k in msl.KEYS]
+155
View File
@@ -0,0 +1,155 @@
"""855-C 2-C4 지킴 — 서버 산출근거 글(`master_doc_text`) · 기준 목록 · 계산서가 문서 셈.
① 거울 — 글 규칙이 화면 TS 와 같음(헬퍼 `helper_855_c4_doc_text.cjs`):
수 꼴(`eqText` · 줄 금액 · 원) · 단위 글(`unitText`) · 금액 줄 단위 자리 · 단가 기호
(`moneyUnits` · `priceSym`) · 선택으로 꺼진 줄(`offLine`) · 비목 이름 — 실제 M01 수식 문서 전부
(기본 입력 셈 답)로.
② 계산서 — 줄 금액 · 소계 · 계 = 문서 셈 답 그대로 · 소계 합 = 계 ·
줄 글 「단가 원/단위 * 수량 단위 = 금액」.
③ 기준 목록 줄 금액 = 같은 입력의 문서 셈 계.
"""
from __future__ import annotations
import importlib
import json
import os
import subprocess
from decimal import Decimal
from functools import lru_cache
import pytest
from M01_MasterData import M01_MasterData_Doc as m01_doc
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Logic_Standard as st
mc = importlib.import_module("master_doc_calc")
md = importlib.import_module("master_doc")
mdt = importlib.import_module("master_doc_text")
HERE = os.path.dirname(os.path.abspath(__file__))
NUMS = [0, 1, -1, 0.5, 1.5, 2.5, -2.5, 0.05, 0.15, 0.25, 0.35, 1.05, 1.15, 1.25, 2.675, 99.95,
-0.05, 0.1 + 0.2, 1e-7, 1234567.891234567, 59018.0857142857, 284.42142857142,
123456789012.345, 26890.75, 1502.04999] # fmt: skip
def _js(v):
if isinstance(v, Decimal):
return float(v)
if isinstance(v, dict):
return {k: _js(x) for k, x in v.items()}
if isinstance(v, (list, tuple)):
return [_js(x) for x in v]
if isinstance(v, (mc.Blank, mc.Stop)):
return None
return v
@lru_cache(maxsize=1)
def world():
"""(문서들, 연결, {키: 기본 셈 답})."""
whole = m01.loaded()[1]
docs = m01_doc.docs()
links = st._links(whole)
answers = {k: mc.calc(d, links, None) for k, d in docs.items() if d.get("금액")}
return docs, links, answers
def _helper(payload: dict) -> dict:
run = subprocess.run(
["node", os.path.join(HERE, "helper_855_c4_doc_text.cjs")],
input=json.dumps(payload, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
check=True,
)
return json.loads(run.stdout)
@lru_cache(maxsize=1)
def mirror():
docs, links, answers = world()
nums, units, lines, offs, py = list(NUMS), set(), [], [], {"단위": [], "줄": [], "꺼짐": []}
for key, a in answers.items():
doc = docs[key]
vars_ = {md.var_id(v): v for v in doc.get("변수") or []}
units |= {str(v.get("단위") or "") for v in doc.get("변수") or []}
units.add(str(doc.get("결과단위") or ""))
for row in a.get("줄") or []:
nums += [_js(row.get(k)) for k in ("단가", "수량", "금액")]
for line in doc["금액"]:
units.add(str(line.get("단위") or ""))
sym = mdt.price_sym(line)
pv = vars_.get(sym) if sym else None
link = (pv or {}).get("연결") or {}
sub = None
if link.get("갈래") == "단가산출" and link.get("키") and "{" not in str(link["키"]):
got = links.doc(str(link["키"]))
sub = {"결과단위": got.get("결과단위")} if got else None
lines.append({"줄": _js(line), "단가변수": _js(pv), "부름": sub})
nodes = (mdt.node_of(line.get("단가")), mdt.node_of(line.get("수량")))
py["줄"].append((mdt.money_units(line, *nodes, pv, sub), sym))
look = mdt._Look(doc, a, links)
vals = {k: v for k, v in (a.get("값") or {}).items() if v is not None}
part = {"식": _js(doc.get("식") or []), "금액": _js(doc["금액"])}
offs.append({"문서": part, "값": _js(vals)})
py["꺼짐"].append([look.off_line(line) for line in doc["금액"]])
nums = [x for x in nums if isinstance(x, (int, float))]
units |= {"%(인력품 대비)", "10^-7/시간", "kWh/hr", "줄 따름", "수(개)", "원문 단위 없음"}
units = sorted(units)
ts = _helper({"수": nums, "원": nums, "단위": units, "금액줄": lines, "꺼짐": offs})
return nums, units, py, ts
def test_수_꼴_eqText_한자리_원():
nums, _, _, ts = mirror()
assert len(nums) > 5000
assert [mdt.eq_text(v) for v in nums] == ts["eq"]
assert [mdt.one(v) for v in nums] == ts["one"]
assert [mdt.won(v) for v in nums] == ts["won"]
texts = ("5401-0017", "", " ", "1048")
assert [mdt.eq_text(v) for v in texts] == ["5401-0017", "", " ", "1,048"]
def test_단위_글_금액줄_단위_자리_단가_기호():
_, units, py, ts = mirror()
assert [mdt.unit_text(u) for u in units] == ts["단위"]
assert len(py["줄"]) > 5000
assert [u for u, _ in py["줄"]] == ts["금액줄"]
assert [s for _, s in py["줄"]] == ts["기호"]
assert any(u["wrap"] for u, _ in py["줄"]) and any(u["price"] for u, _ in py["줄"])
def test_선택으로_꺼진_줄_비목_이름():
_, _, py, ts = mirror()
assert py["꺼짐"] == ts["꺼짐"]
assert sum(map(sum, py["꺼짐"])) > 0 # 꺼진 줄이 실제로 있음(판정이 일을 함)
assert mdt.COST_SHOW == ts["비목"] and mdt.LONG_SUM == ts["항"]
@pytest.mark.parametrize("key", ("GF000220", "GF000089", "GC000404", "GF000101"))
def test_계산서_문서_셈_답_그대로(key):
got = st.sheet(key, {})
docs, links, _ = world()
answer = mc.calc(docs[key], links, st._given(m01.loaded()[1], docs[key], {})[0])
assert got["계"] == float(answer["계"]) and got["계"] == sum(g["소계"] for g in got["묶음"])
for g in got["묶음"]:
assert g["소계"] == float(answer[g["비목"]])
for line in g["줄"]:
assert line["글"].endswith(f"= {mdt.one(line['금액'] or 0)}")
assert " * " in line["글"] or line["글"].startswith("—")
first = got["묶음"][0]["줄"][0]
if key == "GF000220": # 석공 노임 — 「268,908 원/인 * 0.1 인 = 26,890.8」
assert first["이름"] == "석공" and first["글"].startswith("268,908 원/인 * 0.1 인 = ")
def test_기준_목록_금액_문서_셈():
whole = m01.loaded()[1]
docs, links, _ = world()
for key in ("GF000220", "GC000404", "GX000004"):
for row in st._rows_of(whole, whole.logic(key), False, links):
given = st._given(whole, docs[key], row["바꿈"])[0]
want = mc.calc(docs[key], links, given)
assert row["금액"] == round(float(want["계"]), 2), (key, row["규격"])