From aa36c4fb6b6675cbe9ac75ac180b5a2eba271129 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Wed, 18 Nov 2026 21:55:48 +0900 Subject: [PATCH] =?UTF-8?q?feat(859-3):=20=EB=B3=B4=EC=9D=B4=EB=8A=94=20?= =?UTF-8?q?=EC=88=98=20=EC=9E=90=EB=A6=BF=EC=88=98=20=EA=B7=9C=EC=B9=99=20?= =?UTF-8?q?=ED=95=9C=20=EC=8C=8D=20=E2=80=94=20=EC=A4=84=20=EC=8C=93?= =?UTF-8?q?=EA=B8=B0=20=ED=99=94=EB=A9=B4=20=C2=B7=20=EC=84=9C=EB=B2=84=20?= =?UTF-8?q?=EA=B3=84=EC=82=B0=EC=84=9C=20=EA=B8=80(=EC=85=88=20=C2=B7=20?= =?UTF-8?q?=EA=B8=88=EC=95=A1=20=EA=B7=B8=EB=8C=80=EB=A1=9C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 규칙 한 벌 = common_util_show_digits.ts ↔ master_doc_digits.py(짝 · 거울 시험 test_859_3) 표 값 = 고른 줄의 원문 글자 자리(끝 0 살림 · 서버 표 캐시에 줄마다 `자리` 실음) · 식 값 = Q 3 · n 2 · cm 3(8-1 주①) › 원 단위 · 비목 이름 = 소수 한 자리 › 그 밖 유효숫자 3(소수 2~6) · 입력 · 요소 = 자료 그대로 · 만약으로 고른 기호 하나인 식은 그 값의 갈래를 따름 - 줄 쌓기 오른쪽(공식 줄 · 값 묶음 · 금액 줄 수량 · 단가 식 · 결과) · 왼쪽 값 · 작업량 줄 · M02 계산서 글 - test_845_2 기대 글 고침(노무비 계수 0.208333 → 0.208 — 뜻한 바뀜 · 금액 59,020.2 그대로) - 관련 시험 + 관문 256 통과 · typecheck 0 Co-Authored-By: Claude Opus 5.5 --- A00_Common/line_stack_edit.ts | 3 + A00_Common/line_stack_out.ts | 32 +-- A00_Common/line_stack_rows.ts | 7 +- A00_Common/line_stack_screen.ts | 1 + A00_Common/line_stack_tex.ts | 8 +- A00_Common/line_stack_work.ts | 33 ++-- common_util/common_util_formula_doc_cache.ts | 5 + common_util/common_util_show_digits.ts | 154 +++++++++++++++ .../master_data/scripts/master_doc_digits.py | 185 ++++++++++++++++++ .../master_data/scripts/master_doc_record.py | 10 +- .../master_data/scripts/master_doc_text.py | 38 +++- resources/tester/helper_859_3_show_digits.cjs | 35 ++++ resources/tester/test_845_2_unit_show.py | 5 +- resources/tester/test_859_3_show_digits.py | 161 +++++++++++++++ 14 files changed, 639 insertions(+), 38 deletions(-) create mode 100644 common_util/common_util_show_digits.ts create mode 100644 resources/master_data/scripts/master_doc_digits.py create mode 100644 resources/tester/helper_859_3_show_digits.cjs create mode 100644 resources/tester/test_859_3_show_digits.py diff --git a/A00_Common/line_stack_edit.ts b/A00_Common/line_stack_edit.ts index b68e5e8d6..61f53f667 100644 --- a/A00_Common/line_stack_edit.ts +++ b/A00_Common/line_stack_edit.ts @@ -10,6 +10,7 @@ * 고르면 줄이 생김(닫으면 안 생김) · 있는 줄 = 자원 이름 단추 * ========================================================================== */ +import type { PlacedTable } from "../common_util/common_util_show_digits"; import { createBadge } from "@ui/ui_template_badge"; import { createButton, createIconButton, setUiDiff } from "@ui/ui_template_button"; import { createRowMenu } from "@ui/ui_template_context_menu"; @@ -93,6 +94,8 @@ export interface EditHooks { lists?: (given: Record) => Record | null; /** 845-2 표 한 칸 읽기(캐시) — 「줄 따름」 값의 고른 줄 단위 */ look?: TableLook; + /** 859-3 캐시 표 통째 — 표 값의 원문 글자 자리(보이는 자리) */ + tableCache?: (ref: string) => PlacedTable | undefined; /** 846-2 그 기계 작업량 줄 */ work?: (machine: string) => WorkSpec[]; /** 848-3 ① 위 층 고침(SK 읽기 답 `위덮음` · M01 = 없음) */ diff --git a/A00_Common/line_stack_out.ts b/A00_Common/line_stack_out.ts index 12e322924..3873a1e92 100644 --- a/A00_Common/line_stack_out.ts +++ b/A00_Common/line_stack_out.ts @@ -59,8 +59,9 @@ import { } from "../common_util/common_util_line_stack_unit"; import { workAt } from "../common_util/common_util_line_stack_work"; import { workKey } from "../common_util/common_util_formula_doc_work"; +import { showValue } from "../common_util/common_util_show_digits"; import { partName, partUnit } from "../common_util/common_util_machine_symbol_name"; -import { katexNode, symTex, tex, txt, valTex, type TexCtx } from "./line_stack_tex"; +import { katexNode, symTex, tex, txt, type TexCtx } from "./line_stack_tex"; import { lt } from "./line_stack_text"; import { workQty, workRows } from "./line_stack_work"; @@ -143,9 +144,14 @@ function rows( const alias = tableAlias(doc); // 표 값 기호 화면 이름(요구 683) const machine = doc.부품?.갈래 === "기계경비식"; // 845-2 한 줄 분수 한 층(중간 줄로 나눔) const taken = new Set([...vars.keys(), ...lines.keys(), ...Object.values(alias)]); - /** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 */ + /** 수 글 — 고르기 · 코드 값(S_ · 직종 1048 등)은 쉼표 없이 · 그 밖 = 보이는 자리 규칙(859-3) */ const code = (id: string): boolean => /^S(_|$)/.test(id); - const numText = (id: string, v: number): string => (code(id) ? String(v) : eqText(v)); + const numText = (id: string, v: unknown, u?: string): string => { + if (code(id)) return String(v); + return showValue(doc, id, v, vals, h.cache.tableOf, u); + }; + /** 조판 값 글(천 자리 쉼표 = TeX 「{,}」) */ + const show = (id: string, v: unknown): string => numText(id, v).replace(/,/g, "{,}"); /** 식 줄 「기호 = 기호식 = 값식 = 결과 단위」 — 같은 꼴이 이어지면 한 번만(만약이 수 하나를 탄 줄) */ const formula = ( id: string, @@ -156,13 +162,13 @@ function rows( more: Partial, ): (string | HTMLElement)[] => { const res = isNum(v) - ? katexNode(`${code(id) ? String(v) : valTex(v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음) + ? katexNode(`${show(id, v)}\\ ${u ? txt(u) : ""}`) // 단위 글 = TeX 안전(「%」 주석 · 「^」 첨자 막음) : typeof v === "string" // 글 값(기계 원문번호 등 · 838-3) = 그 글 · 기계면 이름 ? el("span", { text: machineText(v, () => h.redraw?.()) ?? v }) : missing(a, id); const sym = tex(n, { side: "sym", vals: vs, alias, ...more }); - const val = tex(n, { side: "val", vals: vs, alias, ...more }); - const same = isNum(v) && val === valTex(v); + const val = tex(n, { side: "val", vals: vs, alias, show, ...more }); + const same = isNum(v) && val === show(id, v); return [ katexNode(symTex(alias[id] ?? id)), ...(sym === val ? [] : [" = ", katexNode(sym)]), @@ -342,7 +348,7 @@ function rows( const glue = (...xs: (string | HTMLElement)[]): HTMLElement => el("span", { className: "lstk-pack", children: xs.filter((x) => x !== "") }); // 846-2 작업량 — 「시간당 작업량」 줄 먼저 · 수량 = 「÷ 시간당 작업량」 - const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias); // 줄마다 새 요소 + const wq = (): HTMLElement[] | null => workQty(doc, qty, w, scope, alias, show); // 줄마다 새 요소 const byWork = wq() !== null; const workHead = (): void => { if (!w) return; @@ -359,8 +365,8 @@ function rows( glue( " × ", mu.wrap && qn - ? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias })}\\right)`) // prettier-ignore - : exprNode(qty, "val", scope, true, cost, { alias }), + ? katexNode(`\\left(${tex(qn, { side: "val", vals: scope, inline: true, cost, alias, show })}\\right)`) // prettier-ignore + : exprNode(qty, "val", scope, true, cost, { alias, show }), mu.qty ? ` ${mu.qty}` : "", ), ]; @@ -383,7 +389,7 @@ function rows( const by = (line as { 비목곱?: Record }).비목곱?.[c]; // 848-7 그 비목만 더 곱함 const byNode = by ? nodeOf(by) : null; const times = byNode - ? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias })}\\right)`))] // prettier-ignore + ? [glue(" × ", katexNode(`\\left(${tex(byNode, { side: "val", vals: scope, inline: true, cost: c, alias, show })}\\right)`))] // prettier-ignore : []; push({ h: [`${COST_SHOW[c]} : `, glue(`${eqText(bundle[c])}${priceUnit}`), ...qtyNode(c), ...times, ` = ${one(part)} ${AMOUNT_UNIT}`], // prettier-ignore @@ -399,9 +405,9 @@ function rows( ? [ exprNode(line.단가, "sym", scope, true, undefined, { place, alias }), " = ", - exprNode(line.단가, "val", scope, true, undefined, { alias }), + exprNode(line.단가, "val", scope, true, undefined, { alias, show }), ] - : [glue(exprNode(line.단가, "val", scope, true, undefined, { alias }), priceUnit)]; + : [glue(exprNode(line.단가, "val", scope, true, undefined, { alias, show }), priceUnit)]; const c = String(line.비목); const bare = !!line.합밖 && !line.비목; // 합 밖 소계(810-2) = 글에만 금액 · 비목 칸 빈칸 workHead(); @@ -462,7 +468,7 @@ function rows( push({ h: [ katexNode(symTex(doc.결과)), - ` = ${isNum(r) ? `${eqText(r)} ${doc.결과단위 ?? ""}` : "—"}`, + ` = ${isNum(r) ? `${numText(doc.결과, r, String(doc.결과단위 ?? ""))} ${doc.결과단위 ?? ""}` : "—"}`, ], cls: "total", }); diff --git a/A00_Common/line_stack_rows.ts b/A00_Common/line_stack_rows.ts index d7a1d1548..024a8d5eb 100644 --- a/A00_Common/line_stack_rows.ts +++ b/A00_Common/line_stack_rows.ts @@ -10,6 +10,7 @@ * 표 값(804-3) = [표 · 칸] 단추 → 표 고르기 창(`line_stack_pick.ts`) · 값 칸 누름 = 그 줄 · 칸(`pickCell`) * ========================================================================== */ +import { showValue } from "../common_util/common_util_show_digits"; import { createButton, createIconButton } from "@ui/ui_template_button"; import { eqText } from "@ui/ui_template_equation"; import { el, showToast } from "@ui/ui_template_elements"; @@ -162,7 +163,11 @@ export function buildBlock( const v = vals[id]; const mach = machineText(v, () => h.change(() => undefined)); // 838-3 기계 원문번호 = 이름 if (mach) return mach; - if (isNum(v) || typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim(); + if (isNum(v)) { + const t = showValue(d, id, v, vals, h.tableCache); // 859-3 보이는 자리 규칙(표 = 원문 글자 자리) + return `${t} ${unitOf(id)}`.trim(); + } + if (typeof v === "string") return `${eqText(v)} ${unitOf(id)}`.trim(); if (v && typeof v === "object") { const key = vars.get(id)?.연결?.키; // 845-2 묶음 값 = 그 문서 결과 단위(원/시간 등) const u = unitOf(id) || unitText(key ? h.subDoc(key)?.결과단위 : ""); diff --git a/A00_Common/line_stack_screen.ts b/A00_Common/line_stack_screen.ts index 89abd4681..a55dc54f7 100644 --- a/A00_Common/line_stack_screen.ts +++ b/A00_Common/line_stack_screen.ts @@ -444,6 +444,7 @@ export function createStackScreen(opt: StackScreenOptions) { calc: calcSub, lists: (g) => listsOf((q) => cache.links.element(q), g), look: (p) => cache.links.table(p), + tableCache: (k) => cache.tableOf(k), work: (m) => machineWork((q) => cache.links.element(q), m), upper, ctlEdit: !cp && edit(), // 848-3 M01 기초 = 시스템 관리자 diff --git a/A00_Common/line_stack_tex.ts b/A00_Common/line_stack_tex.ts index 78d01d1a3..cffccd88b 100644 --- a/A00_Common/line_stack_tex.ts +++ b/A00_Common/line_stack_tex.ts @@ -27,6 +27,8 @@ export interface TexCtx { decided?: boolean; /** 남은 분수 층(845-2 — 0 이면 안쪽 ÷ 는 한 줄 · 없음 = 끝없음) */ frac?: number; + /** 859-3 값 식의 기호 값 글(보이는 자리 규칙 · TeX 쉼표 「{,}」) — 없으면 `valTex` */ + show?: (id: string, v: unknown) => string; } const HIDE = new Set(["반올림", "올림", "버림"]); @@ -101,8 +103,10 @@ export function tex(n: Node, c: TexCtx): string { const id = c.alias?.[n[1]] ?? n[1]; if (c.side === "sym") return symTex(id); let v = c.vals[n[1]]; - if (v && typeof v === "object" && c.cost) v = (v as Values)[c.cost]; - return v === null || v === undefined || typeof v === "object" ? miss(symTex(id)) : valTex(v); + const part = !!v && typeof v === "object" && !!c.cost; // 묶음 값의 비목(단가 · 자료 그대로) + if (part) v = (v as Values)[c.cost!]; + if (v === null || v === undefined || typeof v === "object") return miss(symTex(id)); + return c.show && isNum(v) && !part ? c.show(n[1], v) : valTex(v); } case "field": { const [, of, key] = n; diff --git a/A00_Common/line_stack_work.ts b/A00_Common/line_stack_work.ts index 179fd06c3..73a69390a 100644 --- a/A00_Common/line_stack_work.ts +++ b/A00_Common/line_stack_work.ts @@ -11,8 +11,8 @@ import { createBadge } from "@ui/ui_template_badge"; import { el } from "@ui/ui_template_elements"; -import { eqText } from "@ui/ui_template_equation"; import { varId, type FormulaDoc, type Node } from "../common_util/common_util_formula_doc"; +import { showDigits, showValue } from "../common_util/common_util_show_digits"; import { calcDoc, isNum, @@ -30,7 +30,7 @@ import { restOfQty, workUnit, } from "../common_util/common_util_line_stack_work"; -import { katexNode, symTex, tex, txt, valTex } from "./line_stack_tex"; +import { katexNode, symTex, tex, txt } from "./line_stack_tex"; import { lt, type LsKey } from "./line_stack_text"; export interface WorkRow { @@ -51,7 +51,15 @@ export function workTag(kind: string, title = ""): HTMLElement { const chain = (...xs: string[]): (string | HTMLElement)[] => xs.flatMap((x, i) => (i ? [" = ", katexNode(x)] : [katexNode(x)])); const unitTex = (u: string): string => (u ? `\\ ${txt(u)}` : ""); -const amount = (v: unknown, u: string): string => `${valTex(v)}${unitTex(u)}`; +/** 859-3 시간당 작업량 Q = 소수 3 자리(건설 8-1 [주]① 계산값의 맺음) */ +const workText = (v: unknown): string => showDigits(v, "식", "Q"); +const workAmount = (v: unknown, u: string): string => + `${workText(v).replace(/,/g, "{,}")}${unitTex(u)}`; +/** 859-3 문서 값 글(보이는 자리 규칙 · TeX 쉼표) */ +const docShow = + (doc: FormulaDoc, vals: Values) => + (id: string, v: unknown): string => + showValue(doc, id, v, vals).replace(/,/g, "{,}"); /** 작업량 틀 풀이 — 값 줄 + 결과 식 줄(없으면 빈 목록) */ export function hourlyRows( @@ -64,13 +72,15 @@ export function hourlyRows( const vals = (a.값 ?? {}) as Values; const vars = new Map((tpl.변수 ?? []).map((v) => [varId(v), v])); const unit = (id: string): string => workUnit(shownUnitOf(vars.get(id), vals, look)); - const pack = parts.uses.map((id) => - katexNode(`${symTex(id)} = ${isNum(vals[id]) ? amount(vals[id], unit(id)) : txt("—")}`), + const show = docShow(tpl, vals); + const pack = parts.uses.map( + (id) => + katexNode(`${symTex(id)} = ${isNum(vals[id]) ? `${show(id, vals[id])}${unitTex(unit(id))}` : txt("—")}`), // prettier-ignore ); const res = vals[parts.id]; const sym = tex(parts.node, { side: "sym", vals, frac: 1 }); - const val = tex(parts.node, { side: "val", vals, frac: 1 }); - const end = isNum(res) ? amount(res, workUnit(tpl.결과단위)) : txt("—"); + const val = tex(parts.node, { side: "val", vals, frac: 1, show }); + const end = isNum(res) ? workAmount(res, workUnit(tpl.결과단위)) : txt("—"); return [ ...(pack.length ? [{ h: pack, cls: "packs" }] : []), { h: chain(symTex(parts.id), sym, val, end), cls: "work" }, @@ -99,14 +109,14 @@ export function workRows(w: WorkInfo, c: WorkCtx): WorkRow[] { c.miss(); } const tag = workTag(w.꼴, tpl?.이름 ?? w.율); - if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${eqText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore + if (!tpl) return [{ h: [tag, `${head} = `, isNum(w.값) ? `${workText(w.값)} ${u}`.trim() : lt("Work_Wait")] }]; // prettier-ignore const a = calcDoc(tpl, c.links!, w.변수 ?? {}, [], new Map(), {}); const name = el("span", { className: "lstk-hint", text: tpl.이름 ?? w.율 }); return [{ h: [tag, name] }, ...hourlyRows(tpl, a, c.look)]; } if (!isNum(w.값)) return []; const tag = workTag(w.꼴 || "일당"); - const res = amount(w.값, u); + const res = workAmount(w.값, u); const parts = w.꼴 === "일당" ? dailyParts(w.율) : null; if (parts) { const val = (n: Node): string => tex(n, { side: "val", vals: c.vals, inline: true }); @@ -130,13 +140,14 @@ export function workQty( w: WorkInfo | null, scope: Values, alias?: Record, + show?: (id: string, v: unknown) => string, ): HTMLElement[] | null { if (!w || !isNum(w.값) || w.값 <= 0) return null; const got = restOfQty(doc, qty); if (!got) return null; - const by = katexNode(`{}\\div ${amount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격 + const by = katexNode(`{}\\div ${workAmount(w.값, workUnit(w.단위))}`); // {} = 두 항 사이 ÷ 간격 if (!got.rest) return [by]; - return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias })}`)]; // prettier-ignore + return [by, katexNode(`\\times ${tex(got.rest, { side: "val", vals: scope, inline: true, alias, show: show ?? docShow(doc, scope) })}`)]; // prettier-ignore } const nameOf = (doc: FormulaDoc, id: string): string => diff --git a/common_util/common_util_formula_doc_cache.ts b/common_util/common_util_formula_doc_cache.ts index 792438dea..88c0a9d21 100644 --- a/common_util/common_util_formula_doc_cache.ts +++ b/common_util/common_util_formula_doc_cache.ts @@ -44,6 +44,8 @@ export interface DocCache { takeMissing: () => boolean; /** 표 하나 넣음(고르기에서 받은 것) */ putTable: (ref: string, table: DocTable) => void; + /** 표 통째(859-3 보이는 자리 — 줄마다 원문 글자 자리 `자리`) · 없으면 undefined */ + tableOf: (ref: string) => (DocTable & { 끊김?: string }) | undefined; } export function createDocCache(): DocCache { @@ -99,5 +101,8 @@ export function createDocCache(): DocCache { putTable(ref, table) { tables.set(ref, table); }, + tableOf(ref) { + return tables.get(ref) ?? undefined; + }, }; } diff --git a/common_util/common_util_show_digits.ts b/common_util/common_util_show_digits.ts new file mode 100644 index 000000000..56b0e6c89 --- /dev/null +++ b/common_util/common_util_show_digits.ts @@ -0,0 +1,154 @@ +/* ============================================================================= + * common_util_show_digits.ts + * 보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) — 셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만 + * ⚠ 짝 = resources/master_data/scripts/master_doc_digits.py(같은 규칙 · 한쪽을 고치면 다른 쪽도) · + * 거울 시험 resources/tester/test_859_3_show_digits.py + * 갈래(`digitKind`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 · 그 밖(요소 · 단가산출) → 「요소」 + * 규칙(자리 값은 `RULE` 한 곳): + * 표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 — 건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」 · + * 서버가 표 캐시에 줄마다 `자리` 를 실음) · 글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로 + * 식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) › + * 단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리(1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) › + * 그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수) + * 입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`) + * 수 꼴 = 천 단위 쉼표 · 반올림(Intl — 짧은 10 진 글 기준 0.5 올림) · 화면 · fetch 없음 + * ========================================================================== */ + +import { varId, type DocVar, type FormulaDoc } from "./common_util_formula_doc"; +import { findRow, type DocTable } from "./common_util_formula_doc_table"; +import { evalNode, tryParse, type Values } from "./common_util_formula_doc_view"; + +/** 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 PY `RULE`) */ +export const RULE = { + /** 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌) */ + plain: 6, + /** 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로 */ + symbol: { Q: 3, n: 2, cm: 3 } as Record, + /** 원 단위 중간 값(율 줄 단가 · 원/… 식 값) */ + money: 1, + /** 단위 없는 비목 값(기계 시간당 식) = 원 */ + moneyNames: ["노무비", "재료비", "경비"], + /** 그 밖 식 값 — 유효숫자 · 소수 최소(정수는 정수) · 최대 */ + sig: 3, + min: 2, + max: 6, +}; + +export type DigitKind = "식" | "표" | "입력" | "요소"; + +/** 서버 표 캐시 줄마다 원문 글자 자리(끝 0 있는 칸만) — `master_doc_record` 가 실음 */ +export type PlacedTable = DocTable & { 자리?: (Record | null)[] | null }; + +const formats = new Map(); +/** 소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표 */ +export function fmt(n: number, lo: number, hi: number): string { + const k = `${lo}:${hi}`; + let f = formats.get(k); + if (!f) { + f = new Intl.NumberFormat("ko-KR", { minimumFractionDigits: lo, maximumFractionDigits: hi }); + formats.set(k, f); + } + return f.format(n); +} + +/** 짧은 10 진 글의 [소수 자리, 맨 앞 자리 지수] — 0.0278 → [4, -2] */ +function digits(n: number): [number, number] { + const [m, e] = Math.abs(n).toExponential().split("e"); + const exp = Number(e); + const frac = (m.split(".")[1] ?? "").length; + return [Math.max(0, frac - exp), exp]; +} + +/** 표 값의 원문 글자 자리 — 지금 조건으로 고른 줄의 그 칸 · 값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = undefined) */ +export function tablePlaces( + v: DocVar | undefined, + value: unknown, + vals: Values, + tableOf?: (ref: string) => PlacedTable | null | undefined, +): number | undefined { + const k = v?.연결; + const ref = String(k?.표 ?? ""); + const col = k?.칸; + if (!tableOf || !ref || !col || ref.includes("{")) return undefined; + const 조건: Record = {}; + for (const [c, t] of Object.entries(k?.조건 ?? {})) { + const n = tryParse(t); + if (n) 조건[c] = evalNode(n, vals); + } + try { + const t = tableOf(ref); + if (!t?.줄) return undefined; + const row = findRow(t, 조건, col); + if (typeof row[col] !== "number" || row[col] !== value) return undefined; + return t.자리?.[t.줄.indexOf(row)]?.[col] ?? undefined; + } catch { + return undefined; + } +} + +/** 값 갈래 — 식 · 표 · 입력 · 요소 */ +export function digitKind(doc: Pick, name: string, v?: DocVar): DigitKind { + if ((doc.식 ?? []).some((x) => String(x.기호 ?? "") === name)) return "식"; + const kind = v?.연결?.갈래; + if (kind === "표") return "표"; + if (kind === "입력" || kind === "선택") return "입력"; + return v ? "요소" : "식"; +} + +/** 보이는 수 글 — `places` = 표 원문 글자 자리(모르면 없음) · 수가 아니면 글 그대로 */ +export function showDigits( + value: unknown, + kind: DigitKind = "요소", + name = "", + unit = "", + places?: number, +): string { + if (value === null || value === undefined || value === "") return ""; + if (typeof value !== "number" || !Number.isFinite(value)) return String(value); + const [own, exp] = digits(value); + if (kind === "표") { + const p = Math.max(places ?? 0, own); + return p <= RULE.plain ? fmt(value, p, p) : fmt(value, 0, RULE.plain); + } + if (kind !== "식") return fmt(value, 0, RULE.plain); + if (Object.prototype.hasOwnProperty.call(RULE.symbol, name)) + return fmt(value, 0, RULE.symbol[name]); + if (unit.trim().startsWith("원") || RULE.moneyNames.includes(name)) + return fmt(value, 0, RULE.money); + if (Number.isInteger(value)) return fmt(value, 0, 0); + const hi = Math.max(RULE.min, Math.min(RULE.max, RULE.sig - 1 - exp)); + return fmt(value, RULE.min, hi); +} + +/** 값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감(K = 만약(K_입력 > 0, K_입력, K_2) → K_2) */ +export function digitSource(doc: Pick, name: string, vals: Values): string { + const lines = new Map((doc.식 ?? []).map((x) => [String(x.기호 ?? ""), x.식])); + let at = name; + for (let hop = 0; hop < 8 && lines.has(at); hop++) { + let n = tryParse(lines.get(at)); + while (n && n[0] === "call" && n[1] === "만약" && n[2].length === 3) { + const t = evalNode(n[2][0], vals); + if (t === undefined) return at; + n = n[2][t ? 1 : 2]; + } + if (!n || n[0] !== "var" || n[1] === at) return at; + at = n[1]; + } + return at; +} + +/** 문서 기호 값 글 한 벌 — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위(`unit` = 부르는 쪽이 정한 단위) */ +export function showValue( + doc: Pick, + name: string, + value: unknown, + vals: Values, + tableOf?: (ref: string) => PlacedTable | null | undefined, + unit?: string, +): string { + const src = digitSource(doc, name, vals); + const v = (doc.변수 ?? []).find((x) => varId(x) === src); + const kind = digitKind(doc, src, v); + const places = kind === "표" ? tablePlaces(v, value, vals, tableOf) : undefined; + return showDigits(value, kind, src, unit ?? String(v?.단위 ?? ""), places); +} diff --git a/resources/master_data/scripts/master_doc_digits.py b/resources/master_data/scripts/master_doc_digits.py new file mode 100644 index 000000000..a848cab76 --- /dev/null +++ b/resources/master_data/scripts/master_doc_digits.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +"""보이는 수의 자릿수 규칙 한 벌(PLAN 859-3 · 856-5 · 요구 898 · 902) — +셈 값 · 저장 값 · 금액은 그대로 · 그리는 글자만. + +⚠ 짝 = `common_util/common_util_show_digits.ts`(같은 규칙 · 한쪽을 고치면 다른 쪽도) · + 거울 시험 `resources/tester/test_859_3_show_digits.py`. +갈래(`kind_of`) = 문서 식 줄 → 「식」 · 변수 연결 표 → 「표」 · 입력 · 선택 → 「입력」 · + 그 밖(요소 · 단가산출) → 「요소」. +규칙(자리 값은 `RULE` 한 곳): + 표 = 고른 표 줄의 원문 글자 자리(끝 0 살림 — + 건설 · 산림 1-2-2 1 [주]② 「항목에서 제시한 소수자리 우선」) · + 글자 자리를 모르면(끝 0 빠진 자료 · 사용자가 바꾼 값) 자료 수 그대로 + 식 = 기호 Q 3 · n 2 · cm 3 자리(건설 8-1 [주]① 계산값의 맺음) › + 단위가 원(원/…) · 비목 이름(노무비 · 재료비 · 경비)이면 소수 한 자리 + (1-2-2 2 「일위대가표의 금액란 0.1 원」 준용) › + 그 밖 = 유효숫자 3 · 소수 최소 2 · 최대 6(1-2-2 3 시공단위 품 표 근사 · 정수는 정수) + 입력 · 요소 = 자료 수 그대로(소수 여섯 자리까지 · 끝 0 뗌 — `eqText`) +수 꼴 = 천 단위 쉼표 · 반올림(0.5 올림 · 짧은 10 진 글 기준 — 화면 `Intl` 과 같음). +""" + +from __future__ import annotations + +from decimal import ROUND_HALF_UP, Decimal, InvalidOperation + +#: 자리 값 표 — 사용자 확정 값이 바뀌면 여기만 고침(짝 TS `RULE`) +RULE = { + "plain": 6, # 입력 · 요소 · 자리 모르는 표 값 = 최대 자리(끝 0 뗌) + "symbol": {"Q": 3, "n": 2, "cm": 3}, # 건설 8-1 [주]① — 식이 낸 값 · 기호 그대로 + "money": 1, # 원 단위 중간 값(율 줄 단가 · 원/… 식 값) + "money_names": ("노무비", "재료비", "경비"), # 단위 없는 비목 값(기계 시간당 식) = 원 + "sig": 3, # 그 밖 식 값 — 유효숫자 + "min": 2, # 〃 소수 최소(정수는 정수) + "max": 6, # 〃 소수 최대 +} + + +def dec(v) -> Decimal | None: + """수 → Decimal(화면 double 의 짧은 10 진 글 · 글 · 참거짓 · 빈 값 = None).""" + if isinstance(v, bool) or v is None or isinstance(v, str): + return None + try: + d = Decimal(repr(float(v))) # 화면 수(double)와 같은 짧은 10 진 글 + except (InvalidOperation, ValueError, TypeError, OverflowError): + return None + return d if d.is_finite() else None + + +def fmt(d: Decimal, lo: int, hi: int) -> str: + """소수 `hi` 자리 반올림 · 끝 0 은 `lo` 자리까지 뗌 · 천 단위 쉼표 + (Intl 과 같음 — 0 으로 반올림된 음수 = 「-0」).""" + q = d.quantize(Decimal(1).scaleb(-hi), ROUND_HALF_UP) + sign = "-" if q.is_signed() else "" + whole, _, frac = f"{abs(q):f}".partition(".") + frac = frac.rstrip("0") + frac += "0" * (lo - len(frac)) + head = f"{int(whole):,}" + return f"{sign}{head}.{frac}" if frac else f"{sign}{head}" + + +def places_of(d: Decimal) -> int: + """짧은 10 진 글의 소수 자리(0.10 → 1 · 3.0 → 0).""" + exp = d.normalize().as_tuple().exponent + return -exp if isinstance(exp, int) and exp < 0 else 0 + + +def text_places(d: Decimal) -> int: + """글자 그대로의 소수 자리(Decimal('0.10') → 2 · 표 파일 원문 글자).""" + exp = d.as_tuple().exponent + return -exp if isinstance(exp, int) and exp < 0 else 0 + + +def row_places(row: dict) -> dict: + """표 줄의 칸마다 원문 글자 자리 — 짧은 글보다 길 때만(끝 0 · 화면 캐시 `자리`).""" + out = {} + for col, v in row.items(): + if isinstance(v, Decimal) and v.is_finite() and text_places(v) > places_of(v): + out[col] = text_places(v) + return out + + +def table_places(table: dict) -> list | None: + """표 줄마다 `row_places`(끝 0 없는 줄 = None) · 표 통째 끝 0 없음 = None.""" + got = [row_places(r) if isinstance(r, dict) else {} for r in table.get("줄") or []] + return [x or None for x in got] if any(got) else None + + +def table_value_places(link: dict, value, evaluate, get_table) -> int | None: + """표 값의 원문 글자 자리 — 지금 조건으로 고른 줄(`find`)의 그 칸 글자 · + 값이 그 줄 값과 같을 때만(사용자가 바꾼 값 = None) · + `evaluate(식 나무)` = 조건 값 · `get_table(키)` = 표(못 읽으면 None).""" + import master_doc as md + import master_doc_link as ml + + ref, col = str(link.get("표") or ""), link.get("칸") + if not ref or not col or "{" in ref: + return None + conds = {} + for c, t in (link.get("조건") or {}).items(): + try: + n = md.parse(t) + except md.DocError: + continue + conds[c] = evaluate(n) + try: + table = get_table(ref) + row = ml.find(table, conds, col) if table else None + except Exception: # noqa: BLE001 — 그림용 · 못 찾으면 자료 수 그대로 + return None + if not row or dec(row.get(col)) is None or dec(row.get(col)) != dec(value): + return None + return row_places(row).get(col) + + +def kind_of(doc: dict, name: str, var: dict | None = None) -> str: + """값 갈래 — 식 · 표 · 입력 · 요소.""" + if any(str(x.get("기호") or "") == name for x in doc.get("식") or []): + return "식" + kind = ((var or {}).get("연결") or {}).get("갈래") + if kind == "표": + return "표" + if kind in ("입력", "선택"): + return "입력" + return "요소" if var is not None else "식" + + +def show(v, kind: str = "요소", name: str = "", unit: str = "", places: int | None = None) -> str: + """보이는 수 글 — `places` = 표 원문 글자 자리(모르면 None) · 수가 아니면 글 그대로.""" + if v is None or v == "": + return "" + if isinstance(v, bool): + return "true" if v else "false" + d = dec(v) + if d is None: + return str(v) + if kind == "표": + p = max(places or 0, places_of(d)) + return fmt(d, p, p) if p <= RULE["plain"] else fmt(d, 0, RULE["plain"]) + if kind != "식": + return fmt(d, 0, RULE["plain"]) + if name in RULE["symbol"]: + return fmt(d, 0, RULE["symbol"][name]) + if str(unit or "").strip().startswith("원") or name in RULE["money_names"]: + return fmt(d, 0, RULE["money"]) + if d == d.to_integral_value(): + return fmt(d, 0, 0) + hi = max(RULE["min"], min(RULE["max"], RULE["sig"] - 1 - d.adjusted())) + return fmt(d, RULE["min"], hi) + + +def source(doc: dict, name: str, evaluate) -> str: + """값이 온 기호 — 식 줄이 기호 하나(만약 = 지금 탄 갈래)면 그 기호로 따라감 · + `evaluate(식 나무)` = 그림용 값(모르면 None).""" + import master_doc as md + + lines = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []} + at = name + for _ in range(8): + if at not in lines: + break + try: + n = md.parse(lines[at]) + except md.DocError: + return at + while n and n[0] == "call" and n[1] == "만약" and len(n[2]) == 3: + t = evaluate(n[2][0]) + if t is None: + return at + n = n[2][1 if t else 2] + if not n or n[0] != "var" or n[1] == at: + return at + at = n[1] + return at + + +def show_value(doc: dict, name: str, v, evaluate, get_table, unit: str | None = None) -> str: + """문서 기호 값 글 한 벌(짝 TS `showValue`) — 값이 온 기호의 갈래 · 표 원문 글자 자리 · 단위.""" + import master_doc as md + + src = source(doc, name, evaluate) + var = next((x for x in doc.get("변수") or [] if md.var_id(x) == src), None) + kind = kind_of(doc, src, var) + places = None + if kind == "표" and var is not None: + places = table_value_places(var.get("연결") or {}, v, evaluate, get_table) + return show(v, kind, src, str((var or {}).get("단위") or "") if unit is None else unit, places) diff --git a/resources/master_data/scripts/master_doc_record.py b/resources/master_data/scripts/master_doc_record.py index ee7b647b3..6ad4247ca 100644 --- a/resources/master_data/scripts/master_doc_record.py +++ b/resources/master_data/scripts/master_doc_record.py @@ -5,15 +5,17 @@ 브라우저가 같은 계산기(`common_util_formula_doc_calc.ts`)로 네트워크 없이 다시 셈. 화면 짝 = `common_util/common_util_formula_doc_cache.ts`(기록 → `DocLinks`). - 요소 = 부른 꼴(payload) 그대로 + {값 | 빈 | 끊김} -- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김} +- 표 = 표 통째(조건 · 값칸 · 줄) — 옵션 · 입력이 바뀌어도 화면이 줄을 찾음 · 표 아님 = {끊김} · + 줄마다 원문 글자 자리 `자리`(859-3) - 단가산출 = 문서 통째(없으면 null) `prefetch` = 식 · 옵션과 무관하게 글로 적힌 표 · 단가산출 키를 미리 담음(구멍 `{…}` 든 키는 셈 때만). """ from __future__ import annotations -import master_doc_calc as mc import master_base as mf # 바탕 기반(색인 · 오류) +import master_doc_calc as mc +import master_doc_digits as mdd class Rec: @@ -52,6 +54,10 @@ class Rec: return keep = ("키", "원문번호", "이름", "조건", "범위규칙", "값칸", "줄") self.표[ref] = {k: table[k] for k in keep if k in table} + if places := mdd.table_places( + table + ): # 859-3 줄마다 원문 글자 자리(끝 0 · 화면이 수로 받으면 잃음) + self.표[ref]["자리"] = places def table(self, p: dict): self.see_table(str(p.get("표"))) diff --git a/resources/master_data/scripts/master_doc_text.py b/resources/master_data/scripts/master_doc_text.py index 9e1696287..26be79eb5 100644 --- a/resources/master_data/scripts/master_doc_text.py +++ b/resources/master_data/scripts/master_doc_text.py @@ -9,7 +9,8 @@ `common_util/common_util_formula_doc_view.ts`(`offLine` — 선택으로 꺼진 줄). 금액 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」 · 묶음 줄 = 비목마다 「노무비 : …」 · 계 = 「노무비 : 줄 + 줄 = 금액 원」 · 「합계 : 금액 원」. -수 꼴 = 화면과 같음 — 단가 · 수량 = `eqText`(소수 여섯 자리까지 · 셈 값 그대로) · +수 꼴 = 화면과 같음 — 단가 · 수량 = 보이는 자리 규칙(859-3 · `master_doc_digits` · + 짝 `common_util_show_digits.ts`) · 줄 금액 = 소수 한 자리 · 비목 · 합계 = 원(셈 답의 끝수 그대로 · 여기서 자르지 않음). 옮기지 않은 것(화면만) — 식 조판(KaTeX · 수량 식은 값 하나로) · 공식 줄 · 펼침 · 작업량 줄(846-2) · 굳은 기계 이름(847-1) · 비목곱 인수 글(848-7 · 금액은 답 그대로) · @@ -23,6 +24,7 @@ from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation import master_doc as md import master_doc_calc as mc +import master_doc_digits as mdd COSTS = md.COSTS # 노무비 · 재료비 · 경비 COST_SHOW = {"노무비": "노무비", "재료비": "재료비", "경비": "경 비"} @@ -211,6 +213,24 @@ def _num(v) -> Decimal | None: return _dec(v) +def _table_of(links): + """연결의 마스터 표 읽기(`Links.master` · 기록 `Rec.links.master`) — 없으면 None.""" + master = getattr(links, "master", None) or getattr( + getattr(links, "links", None), "master", None + ) + return master.get if master is not None else (lambda ref: None) + + +def shown(doc: dict, node, v, look: "_Look", links, money: bool = False) -> str: + """금액 줄 단가 · 수량 값 글(859-3) — 기호 하나 = 그 변수 갈래 규칙(표 = 원문 글자 자리) · + 상수 = 자료 그대로 · 식 = 식 규칙(`money` = 단가 = 원 단위).""" + if node and node[0] == "var": + return mdd.show_value(doc, node[1], v, look.value, _table_of(links)) + if node and node[0] == "num": + return mdd.show(v) + return mdd.show(v, "식", "", "원" if money else "") + + def _u(text: str, unit: str) -> str: return f"{text} {unit}" if unit else text @@ -236,6 +256,7 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: sub = None mu = money_units(line, node_of(line.get("단가")), node_of(line.get("수량")), pv, sub) qty = got.get("수량") + qty_text = shown(doc, node_of(line.get("수량")), qty, look, links) base = { "i": i, "이름": name, @@ -244,8 +265,9 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: "꺼짐": look.off_line(line), "합밖": bool(got.get("합밖")), "묶음": line.get("묶음") or "", + "수량글": qty_text, } - tail = "" if qty is None else " × " + _u(eq_text(qty), mu["qty"]) + tail = "" if qty is None else " × " + _u(qty_text, mu["qty"]) if got.get("까닭") and got.get("금액") is None: why = got["까닭"] out.append({**base, "비목": line.get("비목"), "단가": None, "금액": None, "까닭": why, @@ -260,12 +282,14 @@ def money_lines(doc: dict, answer: dict, links) -> list[dict]: 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)), + "단가글": eq_text(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 + price_text = shown(doc, node_of(line.get("단가")), price, look, links, money=True) + text = f"{name} : {_u(price_text, mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}" + out.append({**base, "비목": line.get("비목"), "단가": _num(price), "단가글": price_text, + "금액": _num(amt), "글": text}) # fmt: skip return out @@ -307,8 +331,8 @@ def sheet_groups(doc: dict, answer: dict, links) -> list[dict]: 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"]) + price = "—" if x["단가"] is None else _u(x["단가글"], mu["price"]) + qty = "" if x["수량"] is None else " * " + _u(x["수량글"], mu["qty"]) text = f"{price}{qty} = {one(x['금액'] or 0)}" groups[c].append( { diff --git a/resources/tester/helper_859_3_show_digits.cjs b/resources/tester/helper_859_3_show_digits.cjs new file mode 100644 index 000000000..f57f6f134 --- /dev/null +++ b/resources/tester/helper_859_3_show_digits.cjs @@ -0,0 +1,35 @@ +/* 859-3 거울 헬퍼 — 보이는 자리 규칙(TS `common_util_show_digits.ts`)을 Node 로 돌림(`master_doc_digits.py` 짝). + * stdin = {수: [[값, 갈래, 이름, 단위, 자리|null]], 갈래: [{문서: {식}, 이름, 변수}], 표: {키: 표}, 자리: [{변수, 값, 값들}], + * 문서값: [{문서: {식, 변수}, 값들, 기호: [[이름, 값]]}]} + * stdout = {수: [showDigits], 갈래: [digitKind], 자리: [tablePlaces | null], 문서값: [[showValue]]} */ +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) => (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 dig = load(path.join(__dirname, "..", "..", "common_util", "common_util_show_digits.ts")); + +const input = JSON.parse(fs.readFileSync(0, "utf8")); +const tables = input.표 || {}; +const res = { + 수: (input.수 || []).map(([v, k, n, u, p]) => dig.showDigits(v, k, n, u, p ?? undefined)), + 갈래: (input.갈래 || []).map((x) => dig.digitKind(x.문서, x.이름, x.변수 ?? undefined)), + 문서값: (input.문서값 || []).map((x) => + x.기호.map(([n, v]) => dig.showValue(x.문서, n, v, x.값들, (k) => tables[k])), + ), + 자리: (input.자리 || []).map( + (x) => dig.tablePlaces(x.변수, x.값, x.값들, (k) => tables[k]) ?? null, + ), +}; +process.stdout.write(JSON.stringify(res)); diff --git a/resources/tester/test_845_2_unit_show.py b/resources/tester/test_845_2_unit_show.py index 67c0ca008..f6dbf5d4c 100644 --- a/resources/tester/test_845_2_unit_show.py +++ b/resources/tester/test_845_2_unit_show.py @@ -86,7 +86,8 @@ def test_GC000088_비목_줄_단위_자리(world): "⟦\\text{휴지율}⟧ = ⟦\\dfrac{\\text{월간급여지급일}}{\\text{월간가동일수}}⟧ = ⟦\\dfrac{25}{20}⟧" in sub ) - assert "\\dfrac{1}{8} \\times 1.333333 \\times 1.25⟧ = ⟦0.208333" in sub + # 859-3 식이 낸 값 = 유효숫자 3(그림만 · 금액 59,020.2 그대로) + assert "\\dfrac{1}{8} \\times 1.33 \\times 1.25⟧ = ⟦0.208\\ " in sub assert ( "\\text{노무비 계수}⟧ = ⟦\\dfrac{\\text{일}}{\\text{일일근무시간}} \\times \\text{상여율} \\times \\text{휴지율}⟧" in sub @@ -97,7 +98,7 @@ def test_GC000088_비목_줄_단위_자리(world): assert "⟦\\text{가격}⟧ = 142,069 천원" in sub assert "⟦\\text{직종}⟧ = 1048" in sub # 코드 값 = 쉼표 없음 assert ( - "조종원 : ⟦283{,}297⟧ 원/인 × ⟦\\left(1 \\times 0.208333\\right)⟧ 인 = 59,020.2 원" in sub + "조종원 : ⟦283{,}297⟧ 원/인 × ⟦\\left(1 \\times 0.208\\right)⟧ 인 = 59,020.2 원" in sub ) assert "⟦\\text{가산}⟧ = ⟦0\\ \\text{\\%}⟧" in sub # % = TeX 글(주석으로 안 먹힘) diff --git a/resources/tester/test_859_3_show_digits.py b/resources/tester/test_859_3_show_digits.py new file mode 100644 index 000000000..849169537 --- /dev/null +++ b/resources/tester/test_859_3_show_digits.py @@ -0,0 +1,161 @@ +"""859-3 지킴 — 보이는 수 자릿수 규칙 한 쌍 +(TS `common_util_show_digits.ts` ↔ PY `master_doc_digits.py`). + +① 거울 — 같은 값 · 갈래 · 기호 · 단위 · 표 자리 → 같은 글(헬퍼 `helper_859_3_show_digits.cjs`) · + 갈래 판정 · 표 값 원문 글자 자리(서버 표 캐시 `자리` → 화면 `tablePlaces`) · 문서 기호 값 글 — + M01 수식 문서 전부(기본 입력 셈 답). +② 규칙 결과 — 표 값 끝 0 살림 · 식 품 유효숫자 3 · 원 단위 소수 한 자리 · 8-1 Q 3 자리 · + 입력 · 요소 그대로. +③ 그림만 — 서버 산출근거 글의 금액은 셈 답 그대로(글 끝 「= 금액」 = 줄 금액 소수 한 자리). +""" + +from __future__ import annotations + +import importlib +import json +import os +import subprocess +from decimal import Decimal +from functools import lru_cache + +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") +mdd = importlib.import_module("master_doc_digits") +mdt = importlib.import_module("master_doc_text") +rec = importlib.import_module("master_doc_record") + +HERE = os.path.dirname(os.path.abspath(__file__)) +NUMS = [0, 1, -1, 8, 250, 0.5, 1.5, 2.5, -2.5, 0.05, 0.15, 0.25, 0.35, 1.05, 1.005, 2.675, 99.95, + -0.05, 0.1 + 0.2, 1e-7, 0.0004, 0.000417, 0.027778, 0.0285, 0.0995, 0.99999, 1.4552, + 0.606061, 33971.813333, 535.396667, 12987.917773, 2446.08, 1234567.891234567, + 59018.0857142857, 284.42142857142, 123456789012.345, 26890.75, 1502.04999, + 0.1, 3.0] # fmt: skip +KINDS = [("식", "", ""), ("식", "Q", ""), ("식", "n", ""), ("식", "cm", ""), ("식", "", "원/시간"), + ("식", "", "인"), ("표", "", ""), ("입력", "", ""), ("요소", "", "원/인")] # 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_859_3_show_digits.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 = [[v, k, n, u, p] for v in NUMS for k, n, u in KINDS for p in (None, 2, 3)] + kinds, places, tables, py = [], [], {}, {"수": [], "갈래": [], "자리": [], "문서값": []} + whole = [] + keep = rec.Rec(links) + for key, a in answers.items(): + doc = docs[key] + vals = a.get("값") or {} + look = mdt._Look(doc, a, links) + shown = {k: _js(v) for k, v in vals.items() if v is not None} + names = [md.var_id(x) for x in doc.get("변수") or []] + names += [str(x.get("기호") or "") for x in doc.get("식") or []] + pairs = [[n, float(vals[n])] for n in names if isinstance(vals.get(n), Decimal)] + get = links.master.get + py["문서값"].append([mdd.show_value(doc, n, vals[n], look.value, get) for n, _ in pairs]) + part = {"식": doc.get("식") or [], "변수": _js(doc.get("변수") or [])} + whole.append({"문서": part, "값들": shown, "기호": pairs}) + for var in doc.get("변수") or []: + name = md.var_id(var) + kinds.append({"문서": {"식": doc.get("식") or []}, "이름": name, "변수": _js(var)}) + py["갈래"].append(mdd.kind_of(doc, name, var)) + v = vals.get(name) + link = var.get("연결") or {} + if link.get("갈래") != "표" or not isinstance(v, Decimal): + continue + ref = str(link.get("표") or "") + keep.see_table(ref) + tables[ref] = _js(keep.표[ref]) + places.append({"변수": _js(var), "값": float(v), "값들": shown}) + py["자리"].append(mdd.table_value_places(link, v, look.value, links.master.get)) + nums.append([float(v), "표", name, "", py["자리"][-1]]) + for v, k, n, u, p in nums: + py["수"].append(mdd.show(v, k, n, u, p)) + every = [v for d in docs.values() for v in d.get("변수") or []] + refs = {str((v.get("연결") or {}).get("표") or "") for v in every} + for ref in refs: + if ref and "{" not in ref and ref not in tables: + keep.see_table(ref) + tables[ref] = _js(keep.표[ref]) + ts = _helper({"수": nums, "갈래": kinds, "표": tables, "자리": places, "문서값": whole}) + return nums, py, ts + + +def test_수_꼴_거울(): + nums, py, ts = mirror() + assert len(nums) > 7000 + bad = [(n, a, b) for n, a, b in zip(nums, py["수"], ts["수"]) if a != b] + assert not bad, bad[:10] + + +def test_갈래_표_자리_거울(): + _, py, ts = mirror() + assert len(py["갈래"]) > 10000 and py["갈래"] == ts["갈래"] + assert len(py["자리"]) > 7000 and py["자리"] == ts["자리"] + assert sum(1 for p in py["자리"] if p) > 500 # 끝 0 글자 자리가 실제로 실려 감 + + +def test_문서_기호_값_글_거울(): + _, py, ts = mirror() + assert sum(map(len, py["문서값"])) > 15000 + bad = [(a, b) for x, y in zip(py["문서값"], ts["문서값"]) for a, b in zip(x, y) if a != b] + assert not bad and py["문서값"] == ts["문서값"], bad[:10] + + +def test_규칙_결과(): + show = mdd.show + assert show(0.1, "표", "Q_수량^표", "인", 2) == "0.10" # 원문 글자 끝 0 + assert show(0.1, "표") == "0.1" and show(3.0, "표", "", "", 1) == "3.0" + assert show(0.027778, "식", "Q_보링공", "인") == "0.0278" # 유효숫자 3 + assert show(1.4552, "식") == "1.46" and show(8, "식") == "8" + assert show(33971.813333, "식", "", "원") == "33,971.8" # 원 단위 한 자리 + assert show(70.12345, "식", "Q") == "70.123" and show(2.456, "식", "n") == "2.46" + assert show(0.027778, "입력") == "0.027778" and show(1846.39, "요소") == "1,846.39" + assert show("5401-0017") == "5401-0017" and show(None) == "" and show(1048, "입력") == "1,048" + + +def test_서버_글_금액_그대로(): + docs, links, answers = world() + for key in ("GF000220", "GC000994", "GC000996"): + for line in mdt.money_lines(docs[key], answers[key], links): + if line.get("금액") is not None: + assert line["글"].endswith(f"= {mdt.one(line['금액'])} 원") + got = {x["이름"]: x for x in mdt.money_lines(docs["GC000994"], answers["GC000994"], links)} + assert got["보링공"]["수량글"] == "0.0278" + rate = [x for x in mdt.money_lines(docs["GC000996"], answers["GC000996"], links)] + assert any(x.get("단가글") == "33,971.8" for x in rate)