From 56739989713c6cbc2a1938159092c19794458ed1 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Mon, 16 Nov 2026 21:05:28 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat(848-2):=20Doc=5FSk=20=EC=84=B8=20?= =?UTF-8?q?=EC=A4=84=20=E2=80=94=20=EC=9B=90=EB=B3=B8=20=ED=8C=90=20=3D=20?= =?UTF-8?q?=EA=B3=84=EC=82=B0=20=EB=82=B4=EC=9A=A9=20=EC=A7=80=EB=AC=B8=20?= =?UTF-8?q?=C2=B7=20=ED=8C=8C=EC=83=9D=20=EC=A0=80=EC=9E=A5=EC=97=90=20?= =?UTF-8?q?=EB=A7=A1=EA=B8=B4=20=EC=B9=B8=20=EC=8B=A4=EC=9D=8C=20=C2=B7=20?= =?UTF-8?q?=EC=95=8C=EB=A6=BC=20[=ED=99=95=EC=9D=B8]=20=EB=95=8C=20?= =?UTF-8?q?=EB=B0=94=ED=83=95=20=EA=B1=B7=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - copy_of 원본 판 = dc.doc_fp(기초 덮음 · 글만 바뀜 = 따로 문서 그대로) - settle 파생 갈래 = renew.KEEP(기계덮음 · 맡긴값 · 덮음바탕) 이어 실음(재생성 빼고) — 다시 복사 뒤 저장해도 기계 고침 · 옵션 값 남음 - settle 의 renew.form 에 confirm = 할일 갱신확인 - 시험 test_848_2: 「붙인 뒤」 xfail 셋 걷음 · 기초 기계덮음만 바뀜 = 따로 SK 문서 고침 그대로(sub2 남긴 경우) · ① 안 고친 칸 따라옴 금액 확인 더함 - 시험 test_848_1: M01 문서 파일 전후 바이트 비교를 줄 끝 무시로 — autocrlf 워크트리(CRLF 로 풀림)에서 저장이 LF 로 써 줄 끝만 달라 실패하던 것 Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Doc_Sk.py | 6 +++-- resources/tester/test_848_1_cover_layers.py | 4 ++- resources/tester/test_848_2_cover_renew.py | 29 ++++++++++++++------- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/M02_MasterTemplete/M02_Doc_Sk.py b/M02_MasterTemplete/M02_Doc_Sk.py index 295590e3c..628874cac 100644 --- a/M02_MasterTemplete/M02_Doc_Sk.py +++ b/M02_MasterTemplete/M02_Doc_Sk.py @@ -170,7 +170,7 @@ def copy_of(sk: dict, ctx: tuple | None) -> dict | None: calls = dc.closure(whole, [*dc.calls(root), *dc.upper_calls(got)], got.get("부름")) base = str((sk.get("바탕") or {}).get("로직") or "") seen = dc.doc_of(whole, base) if base else None # 바탕 M01 문서 판(「M01 새 판」 표지) - origin = {"원본": {"키": base, "판": dc.fp(seen)}} if seen else {} + origin = {"원본": {"키": base, "판": dc.doc_fp(seen)}} if seen else {} return {**got, **values, "문서": root, "부름": calls, **origin} @@ -225,7 +225,7 @@ def settle(out: dict, whole: Any, job: Any, raw: Any) -> dict: file = stored(out.get("키")) or {} have = file.get(KEY) if dc.has(file) else (raw.get(KEY) if dc.has(raw) else None) have = ( - upper(out, renew.form(out, have)) if have else have + upper(out, renew.form(out, have, confirm=job == renew.CONFIRM)) if have else have ) # 836-2 · ① 위 층 덮음(848-1) — 저장 때 굳음 if have and have.get("따로") and job != skc.REGEN: if file and old_fp(file) != old_fp(out): @@ -248,6 +248,8 @@ def settle(out: dict, whole: Any, job: Any, raw: Any) -> dict: first = {**(dc.values_of(out[skc.KEY]) if skc.has(out) else {}), "부름": calls} if job != skc.REGEN and (have or {}).get("끊음"): # 안 바뀐 항목 고침 = 그대로(836-2) first["끊음"] = have["끊음"] + if job != skc.REGEN: # 맡긴 기계 고침 · 옵션 값 · 지킨 칸 바탕(848-2) + first |= {k: have[k] for k in renew.KEEP if (have or {}).get(k)} if (have or {}).get( UPPER ): # ① = 저장본(프로젝트 층) · 밖은 `copy_of` 가 지금 기초 것으로(848-1) diff --git a/resources/tester/test_848_1_cover_layers.py b/resources/tester/test_848_1_cover_layers.py index 6d900a91f..dde16ddd5 100644 --- a/resources/tester/test_848_1_cover_layers.py +++ b/resources/tester/test_848_1_cover_layers.py @@ -262,7 +262,9 @@ def test_M01_기초_고침_빌더_이어받기_되돌림(docs_tmp): back = {NO: {"값": {"가격": float(d["값"]["가격"])}, "조종원": d["조종원"]}, SYM: {"작업량": {"방식": "일당"}}} # fmt: skip got = _save_m01(back) - assert COVER not in got["문서"] and file.read_bytes() == orig + assert COVER not in got["문서"] and file.read_bytes().replace(b"\r", b"") == orig.replace( + b"\r", b"" + ) # 줄 끝(autocrlf) 무시 assert got["셈"]["계"] == before diff --git a/resources/tester/test_848_2_cover_renew.py b/resources/tester/test_848_2_cover_renew.py index 03fcf783c..453926451 100644 --- a/resources/tester/test_848_2_cover_renew.py +++ b/resources/tester/test_848_2_cover_renew.py @@ -15,8 +15,6 @@ from __future__ import annotations import copy import shutil -import pytest - from M01_MasterData import M01_MasterData_Store as m01 from M02_MasterTemplete import M02_Doc_Sk_Path as path from M02_MasterTemplete import M02_Labor_Ref as refs @@ -31,7 +29,6 @@ CUT = ( "GC000085" # 흙깎기(기계) 보통토사 — 굴착기 1.0㎥(0201-0100) 부름 · 옵션 규모 · 지역 · 보정작업 ) PRICE = 142069 # 굴착기 1.0㎥ M01 가격 -WAIT = pytest.mark.xfail(reason="M02_Doc_Sk 세 줄(848-2 a · b · c) 붙인 뒤", strict=True) def _eq_move(monkeypatch, key: str, fn) -> None: @@ -127,7 +124,7 @@ def test_label_only(world, monkeypatch): def test_crew_list_kept(world, monkeypatch): - """㉡ 목록 칸 — 기계 인력 줄 바뀜 + 인력 고침 = 지킴 알림(목록 글) · 가격 고침 칸은 알림 없음.""" + """㉡ 목록 칸 — 인력 줄 바뀜 + 인력 고침 = 지킴 알림(목록 글) · 가격 칸 알림 없음.""" me = world["personal"] mine = [{"키": "LB:1048", "인": 2}] key = _machine_sk(me, {"값": {"가격": 150000}, "조종원": mine}) @@ -137,9 +134,8 @@ def test_crew_list_kept(world, monkeypatch): assert note["M01"] == ["인력 LB:1048 1인 → LB:1048 1.5인"] -@WAIT def test_upper_only(world, monkeypatch): - """㉣ 기초 고침(①)만 바뀜(+ 이름 글) = 따로 문서 그대로 · 내 고침 칸을 ① 이 바꾸면 지킴 알림(층 기초) · + """㉣ 기초 고침(①)만 바뀜(+ 이름) = 따로 문서 그대로 · ① 이 내 고침 칸을 바꿈 = 지킴(층 기초) · ② 없는 칸(주연료)은 알림 없음.""" me = world["personal"] key = _cut_sk(me, cover={"값": {"가격": 150000}}) @@ -156,6 +152,7 @@ def test_upper_only(world, monkeypatch): assert got["문서"]["기계덮음"] == {DIG_NO: {"값": {"가격": 150000}}} [note] = got["사본"]["갱신"] assert (note["경로"], note["층"], note["전"], note["후"]) == ("값.가격", "기초", PRICE, 200000) + assert got["셈"]["계"] > was["셈"]["계"] # 안 고친 칸(주연료 ①) = 따라옴 · 가격 = 내 값 assert not got["사본"]["문서새판"] @@ -189,7 +186,7 @@ def _grow(d: dict) -> None: def test_structure_recopy(world, monkeypatch): - """㉤ 기초에 줄이 더해짐 = 다시 복사(따로 아님) · 기계 고침 · 옵션 값 다시 얹음 · 알림 다시복사.""" + """㉤ 기초에 줄 더함 = 다시 복사(따로 아님) · 기계 고침 · 옵션 값 다시 얹음 · 알림 다시복사.""" me = world["personal"] cover = {"값": {"가격": 150000}} key = _cut_sk(me, cover=cover) @@ -203,7 +200,6 @@ def test_structure_recopy(world, monkeypatch): assert note["다시얹음"] == ["규모 소규모"] -@WAIT def test_structure_recopy_saved(world, monkeypatch): """㉤ 다시 복사한 뒤 알림 [확인](저장) = 기계 고침 · 옵션 값 남음 · 알림 없음.""" me = world["personal"] @@ -229,7 +225,6 @@ def test_save_keeps_base(world, monkeypatch): assert (note["전"], note["후"]) == (PRICE, PRICE * 2) -@WAIT def test_confirm_clears(world, monkeypatch): """㉥ 알림 [확인] 뒤 = 안 뜸 · 내 값 그대로 · 금액 같음.""" me = world["personal"] @@ -288,3 +283,19 @@ def test_imported_same_rule(world, monkeypatch): with store.at(me): [note] = renew.notes(sk) assert (note["처리"], note["경로"], note["후"]) == ("지킴", "값.가격", PRICE * 2) + + +def test_upper_cover_keeps_edited_doc(world, monkeypatch): + """㉣ 기초 문서의 `기계덮음`(①)만 바뀜 = 그 기초로 만든 따로 SK 문서 고침 그대로 · 알림 없음 + (문서 지문에서 덮음 뺌 — 848-1 이 남긴 경우).""" + from resources.tester.test_836_2_sk_auto_renew import TOOL, _base, _edit + + me = world["personal"] + key = _base(me) + _edit(me, key, "노무비 × 5%") + was = _read(me, key) + _doc_move(monkeypatch, "GC001109", lambda d: d.update(기계덮음={DIG_NO: {"값": {"가격": 1}}})) + got = _read(me, key) + assert got["사본"]["따로"] is True and got["사본"]["갱신"] == [] + assert got["문서"]["금액"][TOOL]["단가"] == "노무비 × 5%" + assert got["셈"]["계"] == was["셈"]["계"] and not got["사본"]["문서새판"] From 6f0f9be9e6ae4fdfbb269771295751d76e6609df Mon Sep 17 00:00:00 2001 From: umsangdon Date: Mon, 16 Nov 2026 21:06:37 +0900 Subject: [PATCH 2/2] =?UTF-8?q?feat(848-6):=20=EB=B6=88=EB=9F=AC=EC=98=A4?= =?UTF-8?q?=EA=B8=B0=20=EC=9B=90=EB=AC=B8=20=EB=8B=A8=EC=9C=84=20=C2=B7=20?= =?UTF-8?q?Q=20=EA=B0=92=20=EA=B8=80=EC=9E=90=20Q=20=EB=B6=80=EB=A6=84=20?= =?UTF-8?q?=C2=B7=20STmate=20=EA=B8=B0=EA=B3=84=20=EB=8B=A8=EC=9C=84=20X?= =?UTF-8?q?=20=E2=86=92=20=EC=8B=9C=EA=B0=84=20=C2=B7=20=EB=8B=A8=EC=9C=84?= =?UTF-8?q?=20=EC=A0=95=EA=B7=9C=ED=99=94=20=EB=8C=80=EB=AC=B8=EC=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 가져온 식 문서 derive 끝 `M02_Doc_Import_Q.tidy` (새 파일) — 원문 글줄(mid:) 단위 글 → 빈 변수 단위 (짐작 없음 · 낱말 목록 밖 안 닮) · 기계 밖 줄 나눔 자리 수 = Q 값이고 뜻 분명할 때만 Q 부름 · 아니면 「참고 · Q 값 글자」 표지 - STmate 원파일 기계 단위 기호 「X」 → 「시간」 (엑셀 내보내기와 같음 · 호표 · 자원 단위) - `norm_unit` ↔ `normUnit` 대문자 M3 · M2 · M · HR · TON (기존 입력 결과 그대로) - 전수 3,241 블록 — 엑셀 단가 그대로 · 우리 단가로 계 · 비목 · 검산 전후 다름 0 · 작업량 줄 블록 715 → 1,634 · Q 단위 2,324 / 2,362 · Q 글자 바꾼 블록 32 · 단위 X 667 → 0 · 그리기 규칙 지킴 전후 같음 - 세 줄 합침 · 겹분수는 안 고침 (848-7 · 화면 몫 — 보고) - 시험 test_848_6_import_q 30 Co-Authored-By: Claude Opus 5.5 --- M02_MasterTemplete/M02_Doc_Import.py | 2 + M02_MasterTemplete/M02_Doc_Import_Q.py | 220 ++++++++++++++++++ M02_MasterTemplete/M02_San_Emit.py | 6 +- common_util/common_util_formula_doc_work.ts | 5 +- .../master_data/scripts/master_doc_work.py | 3 +- resources/tester/test_848_6_import_q.py | 206 ++++++++++++++++ 6 files changed, 437 insertions(+), 5 deletions(-) create mode 100644 M02_MasterTemplete/M02_Doc_Import_Q.py create mode 100644 resources/tester/test_848_6_import_q.py diff --git a/M02_MasterTemplete/M02_Doc_Import.py b/M02_MasterTemplete/M02_Doc_Import.py index 0db7ddac7..af79cebb4 100644 --- a/M02_MasterTemplete/M02_Doc_Import.py +++ b/M02_MasterTemplete/M02_Doc_Import.py @@ -20,6 +20,7 @@ from decimal import Decimal from typing import Any from M02_MasterTemplete import M02_Doc_Copy as dc +from M02_MasterTemplete import M02_Doc_Import_Q as qt from M02_MasterTemplete import M02_Doc_Import_Shape as shape from M02_MasterTemplete import M02_Labor_Ref as refs from M02_MasterTemplete import M02_San_MatPick as mp @@ -452,6 +453,7 @@ def derive(sk: dict, ctx: tuple | None = None, whole: Any = None) -> dict: if mats: # 827-3 재료 찾기 판정(줄 쌓기 풍선말 · 이미 만든 SK 고름 얹기) alive = {dc.md.var_id(v) for v in doc.get("변수") or []} doc["가져온"]["재료"] = [x for x in mats if x["기호"] in alive] + qt.tidy(doc, meta) # 848-6 원문 단위 · Q 값 글자 return {**doc, "키": str(sk.get("키") or key), "이름": str(sk.get("이름") or doc.get("이름"))} diff --git a/M02_MasterTemplete/M02_Doc_Import_Q.py b/M02_MasterTemplete/M02_Doc_Import_Q.py new file mode 100644 index 000000000..a5208f202 --- /dev/null +++ b/M02_MasterTemplete/M02_Doc_Import_Q.py @@ -0,0 +1,220 @@ +"""M02 가져온 식 문서 — 원문 단위 · Q 값 글자(PLAN 848-6 · 요구 889) — 금액 그대로. + +`M02_Doc_Import.derive` 끝에 부름(서버 단독). +① 변수 단위 = 원문 글줄(자리 `mid:이름` · `자리들`)의 단위 글 — + EST 「= 23.39 ㎥/hr」 「20sec (135˚)」 · STmate 「='m3/hr'」 「20 'sec(135)'」 · 괄호 덧말 뗌 · + 단위 글 없음 · 못 읽음 = 안 닮(짐작 없음) · 이미 단위 있는 변수는 그대로 · + 표기 = `master_doc_work.norm_unit`(엔진이 「…/hr」 로 작업량 자리를 읽음) +② 기계 밖 줄 수량의 Q 값 글자(「1 ÷ 8 ÷ 23.39」) → Q 부름(「1 ÷ 8 ÷ Q」) — + 나눔 자리 수(괄호 속 사슬 포함 「3 ÷ (63 ÷ 2)」) = 기계 줄 수량이 나누는 변수(Q) 값과 꼭 같음 · + 같은 값 변수가 그 Q 하나 · 8(시간) 아님 · 그 글자가 줄에 하나 · + 그 줄이 Q 나 Q 사슬 변수를 안 부름 · 아니면 그대로 두고 「참고 · …」 표지(판정 칠 밖) +경쟁사 식 · 변수 이름 · 글 줄 · 로직 층(검산)은 안 고침. +""" + +from __future__ import annotations + +import re +from decimal import Decimal +from typing import Any + +from M02_MasterTemplete import M02_Doc_Copy as dc + +md, mw = dc.md, dc.mw +_ATOM = ( + r"\d*(?:㎥|㎡|㎞|㎝|㎜|㎏|ℓ|m3|m2|km|cm|mm|m|hr|h|min|sec|ton|kg|ea|set|a|l|t|" + r"시간|일|분|초|회|대|인|개소|개|본|톤|주|매|공|조|기|장|쌍|그루)" +) +_UNIT = re.compile(rf"^{_ATOM}(?:/{_ATOM})*$", re.I) +_HEAD = re.compile(r"(? str: + """단위 글 후보 → 단위 | 빈 글 — 괄호 · {} 덧말 · <> 뗌 · 「:」 「,」 뒤 설명 뗌 · + 낱말 목록(`_ATOM`) 밖 = 빈 글.""" + s = re.sub(r"\([^)]*\)?|\{[^}]*\}?|[<>\[\]]", "", raw) + s = re.split(r"[:,]", s)[0].replace(" ", "") + return mw.norm_unit(s) if s and _UNIT.match(s) else "" + + +def _outside(text: str) -> list[tuple[bool, str]]: + """글 → [(따옴표 안?, 조각)].""" + return [(i % 2 == 1, x) for i, x in enumerate(text.split("'"))] + + +def _tail(seg: str) -> str: + """대입 한 조각 → 맨 끝 「=」 뒤 단위 글(STmate = 따옴표 글 · EST = 값 뒤 글).""" + bits = _outside(seg) + last = max((i for i, (q, x) in enumerate(bits) if not q and "=" in x), default=None) + if last is None: + return "" + after = [bits[last][1].rsplit("=", 1)[1], *(x for _, x in bits[last + 1 :])] + quoted = [x for i, x in enumerate(after) if i % 2 == 1] + if quoted: # 「=3.5'㎥/hr''연암'」 — 단위로 읽히는 첫 글 + return next((u for u in map(_unit, quoted) if u), "") + return _unit(_LEAD.sub("", after[0])) + + +def _segments(text: str, n: int) -> list[str] | None: + """한 글줄의 대입 n 개 조각 — STmate(따옴표) = 바깥 「,」 로 · EST = 「이름 =」 자리로 · + 안 맞음 = None.""" + if n == 1: + return [text] + if "'" in text: + parts, cur, depth = [], "", 0 + for quoted, bit in _outside(text): + if quoted: + cur += f"'{bit}'" + continue + for ch in bit: + depth += (ch == "(") - (ch == ")") + if ch == "," and depth == 0: + parts.append(cur) + cur = "" + else: + cur += ch + parts = [p for p in [*parts, cur] if _HEAD.search(p)] + return parts if len(parts) == n else None + at = [m.start() for m in _HEAD.finditer(text)] + return [text[a:b] for a, b in zip(at, [*at[1:], len(text)])] if len(at) == n else None + + +def units(doc: dict, lines: list[dict]) -> int: + """① 원문 글줄 단위 → 빈 단위 변수 · 단 수.""" + by = {md.var_id(v): v for v in doc.get("변수") or []} + n = 0 + for one in lines: + spots = one.get("자리들") or [one.get("자리")] + names = [str(s)[4:] for s in spots if str(s or "").startswith("mid:")] + segs = _segments(str(one.get("글") or ""), len(names)) if names else None + for name, seg in zip(names, segs or []): + var = by.get(name) + got = _tail(seg) if var is not None and not var.get("단위") else "" + if got: + var["단위"] = got + n += 1 + return n + + +# ── ② Q 값 글자 ──────────────────────────────────────────────────────── +def _parse(text: Any): + try: + return md.parse(str(text)) + except Exception: # noqa: BLE001 — 못 읽는 식 = 건너뜀 + return None + + +def _dividers(node, kind: str = "var", sign: int = 1, out: list | None = None) -> list: + """곱 · 나눔 사슬(괄호 속 사슬까지)에서 나누는 변수 이름 | 수(kind = var | num).""" + out = [] if out is None else out + if node and node[0] == "bin" and node[1] in ("*", "/"): + _dividers(node[2], kind, sign, out) + _dividers(node[3], kind, -sign if node[1] == "/" else sign, out) + elif node and node[0] == kind and sign < 0: + out.append(node[1]) + return out + + +def _chain(doc: dict, name: str, seen: set) -> set: + """Q 정의 식이 부르는 변수(거슬러 올라감).""" + line = next((x for x in doc.get("식") or [] if x.get("기호") == name), None) + node = _parse(line.get("식")) if line else None + for n in md.names(node) if node else []: + if n not in seen: + seen.add(n) + _chain(doc, n, seen) + return seen + + +def _values(doc: dict) -> dict: + """수 · 식 변수만 셈(연결 없이) — Q 값.""" + bare = {k: doc.get(k) for k in ("키", "이름", "결과단위", "식", "끝수")} + bare["변수"] = [ + v for v in doc.get("변수") or [] if (v.get("연결") or {}).get("갈래") in ("숫자", "식") + ] + bare["금액"] = [] + try: + return dc.mc.calc(bare, None).get("값") or {} + except Exception: # noqa: BLE001 — 못 셈 = Q 값 모름(안 바꿈) + return {} + + +def _dec(v: Any) -> Decimal | None: + """셈 값 → 수(수 글 = 저장본 꼴 · 묶음 · 글 = None).""" + if isinstance(v, bool) or not isinstance(v, (Decimal, int, float, str)): + return None + try: + return Decimal(str(v)) + except ArithmeticError: + return None + + +def _two(v: Decimal) -> str: + return f"{v:.2f}".rstrip("0").rstrip(".") + + +def literals(doc: dict) -> list[str]: + """② 기계 밖 줄 Q 값 글자 → Q 부름 · 못 가름 = 표지 글 목록.""" + by = {md.var_id(v): v for v in doc.get("변수") or []} + found = {x.get("기호") for x in (doc.get("가져온") or {}).get("기계") or []} + money = doc.get("금액") or [] + + def machine(line: dict) -> bool: + price = str(line.get("단가") or "").removesuffix(".계") + link = (by.get(price) or {}).get("연결") or {} + return price in found or ( + link.get("갈래") == "단가산출" and "기계" in (link.get("입력") or {}) + ) + + qs = list( + dict.fromkeys( + q for x in money if machine(x) for q in _dividers(_parse(x.get("수량") or "1")) + ) + ) + if not qs: + return [] + vals = {k: d for k, v in _values(doc).items() if (d := _dec(v)) is not None} + qv = {q: vals[q] for q in qs if q in vals} + notes = [] + for line in money: + text = line.get("수량") + if machine(line) or not isinstance(text, str): + continue + node = _parse(text) + if node is None: + continue + used, spots = set(md.names(node)), {} + for lit in dict.fromkeys(_dividers(node, "num")): + lit = Decimal(lit) + same = [q for q, v in qv.items() if v == lit] + near = [q for q, v in qv.items() if _two(v) == _two(lit)] + if not same and not near: + continue + at = [m for m in _NUM.finditer(text) if Decimal(m.group(0)) == lit] + others = [n for n, v in vals.items() if v == lit and n not in qv] # 같은 값 다른 변수 + ok = len(same) == 1 and not others and lit != mw.EIGHT and len(at) == 1 + ok = ok and not (used & _chain(doc, same[0], {same[0]})) + if ok: + spots[at[0].span()] = same[0] + continue + why = "Q 여럿" if len(same) > 1 else "끝수 다름" if not same else "뜻 불분명" + why = f"같은 값 변수 {others[0]}" if others and same else why + why = "같은 글자 여럿" if len(at) > 1 and why == "뜻 불분명" else why + who = f"{at[0].group(0) if at else lit} = {(same or near)[0]} 값" + notes.append(f"{NOTE}「{line.get('이름')}」 수량 {text} 의 {who} · {why}") + for (a, b), q in sorted(spots.items(), reverse=True): + text = text[:a] + q + text[b:] + line["수량"] = text + return notes + + +def tidy(doc: dict, meta: dict) -> None: + """derive 끝 — ① 단위 ② Q 글자(표지 = `가져온.표지` 뒤).""" + units(doc, list((meta.get("원본") or {}).get("글줄") or [])) + notes = literals(doc) + if notes: + head = doc.setdefault("가져온", {}) + head["표지"] = [*(head.get("표지") or []), *notes] diff --git a/M02_MasterTemplete/M02_San_Emit.py b/M02_MasterTemplete/M02_San_Emit.py index e1e2d002d..c218fee94 100644 --- a/M02_MasterTemplete/M02_San_Emit.py +++ b/M02_MasterTemplete/M02_San_Emit.py @@ -40,6 +40,7 @@ RESERVED |= {"또는", "만약", "올림", "버림", "반올림", "최소", "최 _KEY = re.compile(r"[A-Z]{2}\d{6}") _LABEL = re.compile(r"'([^']*)'") NOTE = "참고 · " # 사람 확인 표지 머리(못 옮김 표지와 가름) +HOUR = "시간" # 848-6 STmate 원파일 기계 단위 기호 「X」 = 엑셀 내보내기 「시간」 class EmitError(Exception): @@ -409,7 +410,8 @@ class _Stm: self.fix.append((one, len(self.order))) return self.line(one, node, False, src) res = {"꼴": "STmate", "갈래": KIND.get(code[0], "고정"), "코드": code} - res |= {k: pr.get(k) for k in ("이름", "규격", "단위")} + unit = HOUR if code[0] == "X" and pr.get("단위") == "X" else pr.get("단위") + res |= {k: pr.get(k) for k in ("이름", "규격")} | {"단위": unit} res |= {"단가": {c: pr.get(c) or 0 for c in COMP}} sole = [c for c in COMP if res["단가"][c]] if not one_ and len(sole) == 1: # 비목 꼬리 없어도 값 든 비목 하나면 단가 줄(셈 같음) @@ -423,7 +425,7 @@ class _Stm: res |= {"조합첫": True} if len(parts) > 1 else {} else: link, many = _m01(res["갈래"], res, _label(node)) if self.keys else (None, None) - one = first_spec(resource(o.names.item(name), pr.get("단위"), cf, res, link), parts) + one = first_spec(resource(o.names.item(name), unit, cf, res, link), parts) if parts and one["종류"] == "로직": one["이음"] = combo_link(one, parts) or hourly_text(link) self.line(one, node, True, src) diff --git a/common_util/common_util_formula_doc_work.ts b/common_util/common_util_formula_doc_work.ts index 1d01567d9..6590d60bc 100644 --- a/common_util/common_util_formula_doc_work.ts +++ b/common_util/common_util_formula_doc_work.ts @@ -84,8 +84,9 @@ type Fac = [number, Node]; export const normUnit = (u: unknown): string => String(u ?? "") .trim() - .replace(/m3/g, "㎥") - .replace(/m2/g, "㎡") + .replace(/[mM]3/g, "㎥") // 848-6 대문자 꼴 + .replace(/[mM]2/g, "㎡") + .replace(/(? s.toLowerCase()) .replace(/\/(시간|h|Hr|HR)$/, "/hr"); const varOf = (doc: FormulaDoc, name: string): DocVar | undefined => diff --git a/resources/master_data/scripts/master_doc_work.py b/resources/master_data/scripts/master_doc_work.py index d58119ba7..043377f86 100644 --- a/resources/master_data/scripts/master_doc_work.py +++ b/resources/master_data/scripts/master_doc_work.py @@ -33,7 +33,8 @@ EIGHT = Decimal(8) def norm_unit(u) -> str: - t = str(u or "").strip().replace("m3", "㎥").replace("m2", "㎡") + t = re.sub(r"[mM]3", "㎥", re.sub(r"[mM]2", "㎡", str(u or "").strip())) # 848-6 대문자 꼴 + t = re.sub(r"(? (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 work = load(path.join(process.argv[1], "common_util", "common_util_formula_doc_work.ts")); +const xs = JSON.parse(fs.readFileSync(0, "utf8")); +process.stdout.write(JSON.stringify(xs.map(work.normUnit))); +""" + + +def test_정규화_대문자_파이썬_TS_같음(): + want = [qt.mw.norm_unit(x) for x in NORM] + assert want == ["㎥/hr", "㎥/hr", "㎡/hr", "m/hr", "ton/hr", "ton", "㎥/hr", "m/hr", "100㎡", "MIN", "EA/hr"] # fmt: skip + proc = subprocess.run(["node", "-e", _JS, str(ROOT)], input=json.dumps(NORM), capture_output=True, + text=True, encoding="utf-8", check=True) # fmt: skip + assert json.loads(proc.stdout) == want + + +# ── ③ Q 값 글자 ───────────────────────────────────────────────────────── +def _doc(vars_, crew, defs=()): + return { + "키": "SK-999999", "이름": "시험", "결과단위": "원/㎥", + "변수": [*vars_, _var("P_굴", {"갈래": "숫자", "값": {"노무비": D(1), "재료비": D(1), "경비": D(1)}}), + _var("P_인", {"갈래": "숫자", "값": D(100)})], + "식": [{"기호": k, "식": v} for k, v in defs], + "금액": [{"이름": "굴삭기", "비목": "묶음", "수량": "1 ÷ Q", "단가": "P_굴"}, + {"이름": "보통인부", "비목": "노무비", "수량": crew, "단가": "P_인"}], + "가져온": {"기계": [{"기호": "P_굴"}]}, + } # fmt: skip + + +NUM = {"갈래": "숫자", "값": D("23.39")} + + +@pytest.mark.parametrize( + "crew, want", + [("1 ÷ 8 ÷ 23.39 × 0.1", "1 ÷ 8 ÷ Q × 0.1"), ("3 ÷ (23.39 ÷ 2)", "3 ÷ (Q ÷ 2)")], +) +def test_Q_글자_값_같으면_Q_부름(crew, want): + doc = _doc([_var("Q", NUM)], crew) + assert qt.literals(doc) == [] + assert doc["금액"][1]["수량"] == want + + +@pytest.mark.parametrize( + "vars_, crew, defs, why", + [ + ([_var("Q", NUM), _var("t", NUM)], "1 ÷ 8 ÷ 23.39", (), "같은 값 변수 t"), + ([_var("Qd", {"갈래": "숫자", "값": D(20)}), _var("Q", {"갈래": "식"})], "1 ÷ Qd ÷ 2.5", + (("Q", "Qd ÷ 8"),), "뜻 불분명"), # 줄이 Q 사슬(Qd)을 부름 · 2.5 = 길이 + ([_var("Q", {"갈래": "숫자", "값": D(8)})], "1 ÷ 8", (), "뜻 불분명"), # 8 = 시간 + ([_var("Q", {"갈래": "숫자", "값": D("23.389")})], "1 ÷ 8 ÷ 23.39", (), "끝수 다름"), + ([_var("Q", NUM)], "23.39 ÷ 23.39", (), "같은 글자 여럿"), + ], +) # fmt: skip +def test_Q_글자_못_가르면_그대로_표지(vars_, crew, defs, why): + doc = _doc(vars_, crew, defs) + notes = qt.literals(doc) + assert doc["금액"][1]["수량"] == crew + assert len(notes) == 1 and notes[0].startswith("참고 · ") and why in notes[0] + + +def test_Q_글자_금액_같음(): + a = _doc([_var("Q", NUM)], "1 ÷ 8 ÷ 23.39") + b = _doc([_var("Q", NUM)], "1 ÷ 8 ÷ 23.39") + qt.literals(b) + assert b["금액"][1]["수량"] == "1 ÷ 8 ÷ Q" + x, y = qt.dc.mc.calc(a, None), qt.dc.mc.calc(b, None) + assert x["셈됨"] and [z["금액"] for z in x["줄"]] == [z["금액"] for z in y["줄"]] + assert x["계"] == y["계"] + + +# ── ④ 실제 원파일 견본 ─────────────────────────────────────────────────── +def _block(kind, tag, no): + out = fn.emit(nd.native(kind, tag), no) + sk = nd.sk_of(out) + doc = dim.derive(sk, None, nd.whole()) + ours = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": "우리"}} + return out, sk, doc, dim.run(doc, sk, nd.whole()), dim.run(doc, ours, nd.whole()) + + +def _unit(doc, name): + return next(v["단위"] for v in doc["변수"] if v["열쇠"] == name) + + +def test_EST_굴착기형_Q_단위_보조인부_Q_부름(): + out, sk, doc, xl, ours = _block("EST", "거창", 1) + assert _unit(doc, "Q") == "㎥/hr" and _unit(doc, "Cm") == "sec" + assert doc["금액"][1]["수량"] == "1 ÷ 8 ÷ Q" + assert xl["계"] == D(str(out["원본"]["엑셀금액"]["계"])) == 5323 + assert ours["줄"][0]["작업량"]["값"] == D("23.39") and ours["줄"][0]["작업량"]["식들"] + assert imp.check(sk, nd.whole())["같음"] + + +def test_EST_일당_꼴_단위만_달아_문서_식(): + out, sk, doc, xl, ours = _block("EST", "main", 96) + assert doc["식"] == [{"기호": "Q", "식": "560 ÷ 8"}] and _unit(doc, "Q") == "㎥/hr" + assert xl["계"] == 1884 and ours["줄"][0]["작업량"]["값"] == 70 + + +def test_STmate_덤프_60형_작업량_줄_기계_단위_시간(): + out, sk, doc, xl, ours = _block("STC", "봉화", 109) + assert {x["단위"] for x in out["로직"]["호표"]} == {"시간"} # 원파일 기호 「X」 → 시간 + assert _unit(doc, "q1_2") == "㎥/hr" and _unit(doc, "t1") == "분" + assert xl["계"] == 3796 and imp.check(sk, nd.whole())["같음"] + assert all(z.get("작업량") for z in ours["줄"])