Files
Aislo/M02_MasterTemplete/M02_Sangeun_QtyLinks.py
T
eomsangdonandClaude Opus 5.5 c76822f9b0 refactor(860-12): 용어 「고르-」 → 「선택」 — 화면 · 서버 안내 글 323 곳(면고르기 · 자료 열쇠는 그대로)
- 바꿈: 고르기 → 선택 · 다시 고르기 · 다시 고름 → 재선택 · 고름 풀기 → 선택 해제 · 고른 → 선택한 · 고를 → 선택할 · 고르세요 → 선택하세요 · 골라 → 선택해 · 안 고르면 → 선택하지 않으면 등(TS 280 · Python 43 · CAD 앱 글 포함)
- 남김: 「면고르기 · 노면고르기및다짐」 = 공종 이름(사용자 확정) · 수식 문서 칸 · 파일 · 판정 · 상태 값을 겸하는 글(「고름」 · 「고르기」 · 「고른자재」 · 「고른」 · 「고를 것」 · 「규격 없음 — 고르기」 · 「단위 다름 — 고르기」 · 그 칸 이름을 가리키는 검사 글) · 「고르게」(가지런 뜻) · 주석 · 이름 · 자료 파일
- 파이썬 짝: `master_unit_swap.ts` ↔ `resources/master_data/scripts/master_unit.py` 같은 글(「선택해야 셈」) — 자료 값 아님
- 시험: 바뀐 글을 기대하던 15 개를 새 글로(소스 글 대조 포함)
- 목록 · 남긴 자리 = sub1 tmp/s894/표_용어_선택.md · typecheck 0 · CAD 앱 다시 지음 · 관련 + 관문 3,250 중 바뀐 글 시험 고친 뒤 통과(남은 1 = test_442_2 · 다른 창 860-6 의 station_display 자리 · 이번 일 무관)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:19:48 +09:00

498 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""M02 가져온 식 소요량 · 계수 이음(PLAN 797-2 · 요구 655-3 · 요구서_655) — 서버 단독.
가져온 식 줄(엑셀 그대로)에 쓰인 수가 M01 소요량(QC/QF) · 계수(CC/CF) 표 칸의 값인지 **값 역색인**
(`M02_San_Basis_Index.lookup` 한 벌)으로 후보를 냄 — 같은 값 + 같은 단위 성격 + 이름 · 공종 문맥이
맞는 칸만 후보 · 유일해도 자동 확정 없음(사람이 고름) · 값을 지어 넣지 않음.
- 자리(slot) = `호표:i:n` | `덧줄:i:n` — 로직 줄 i 의 식(수량 | 식)의 n 번째 수(중간 변수는 단위 ·
이름 문맥이 없어 자리 아님). 일반 수(1 · 10 · 60 · 100 · 1000 · 8) · 비교 글자 · 찾기 · 로직 부름
인자는 안 셈.
- 고름 = 엑셀 수와 표 칸 값이 같을 때만(같은 값 · 율 ↔ 소수 · t ↔ kg) — 다르면 못 고름 + 까닭.
기록(`가져온.연결` = {고름 [..], 버림 [..]}) + 문서 고침(857-3b) — 그 금액 줄 식의 그 수 자리 = 표 연결
변수(`소요량k` · 엑셀 칸 값 기억 · 금액 그대로) · 풂 = 수로 되돌림 · 자리 = 불러올 때 문서 머리
`가져온.자리`(가져온 줄 수 차례 · 앞 수 `앞` → 문서 식 수 차례로 맞춤).
- 고름 = {자리, 수, 층 「M01」, 표, 줄, 칸, 값, 꼴 eq|pct|kgt} · 로직이 바뀌어 자리의 수가 달라지면
그 기록은 버려진 것으로 보고 화면에 안 내놓음.
길(`M02_Sangeun_Router` `imported/{qty|qty-pick|qty-drop}`) · 표지(`flags` · 가져온 식 만들 때).
"""
from __future__ import annotations
import copy as cp
import re
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_San_Basis_Index as bi
from M02_MasterTemplete import M02_San_Emit as em
from M02_MasterTemplete import M02_San_ToDoc as todoc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from M02_MasterTemplete import M02_Sangeun_Imported as imp
KEY = "연결"
LAYER = "M01"
GENERAL = (0, 1, 8, 10, 60, 100, 1000) # 일반 수(793-3a N9)
SHOWN = 12 # 자리마다 화면에 내는 후보 상한(후보 수는 전부 셈)
FORMS = ("eq", "pct", "kgt")
FIELDS = (("호표", "수량"), ("덧줄", "식")) # 중간 변수 = 단위 · 이름 문맥 없음 → 자리 아님
_ctx: dict[int, dict[str, set[str]]] = {}
def _flat(s: Any) -> str:
return re.sub(r"[^가-힣A-Za-z0-9]", "", str(s or ""))
CMP = ("<=", ">=", "==", "!=", "<", ">") # 비교 글자
def _literals(node: Any, out: list[Decimal]) -> None:
"""식 나무(문서 파서) → 수 글자(차례대로) — 비교 글자는 뺌."""
if not isinstance(node, tuple):
return
kind = node[0]
if kind == "num":
out.append(node[1])
elif kind == "bin":
cmp_ = node[1] in CMP
for side in node[2:]:
if not (cmp_ and isinstance(side, tuple) and side[0] == "num"):
_literals(side, out)
elif kind in ("neg", "pct", "field"):
_literals(node[1], out)
elif kind == "call":
for arg in node[2]:
_literals(arg, out)
def literals(text: Any) -> list[Decimal]:
out: list[Decimal] = []
try:
_literals(todoc.md.parse(str(text)), out)
except todoc.md.DocError:
pass
return out
def slots(row: dict) -> list[dict]:
"""가져온 로직 줄 → 소요량 · 계수 자리 `[{자리, 갈래, 줄, 이름, 단위, 수, d, 직종?}]`."""
out = []
for kind, field in FIELDS:
for i, one in enumerate(row.get(kind) or []):
if not isinstance(one, dict):
continue
labor = kind == "호표" and one.get("종류") == "인력"
nums = literals(one.get(field))
for n, x in enumerate(nums):
if float(x) in GENERAL:
continue
out.append(
{
"자리": f"{kind}:{i}:{n}",
"앞": [str(v) for v in nums[:n]],
"갈래": kind,
"종류": str(one.get("종류") or ""),
"줄": str(one.get("이름") or ""),
"단위": "인" if labor else str(one.get("단위") or ""),
"보임": len(nums) == 1, # 식이 이 수 하나 = 줄 단위가 이 수의 단위(860-3)
"수": float(x),
"d": max(0, -x.as_tuple().exponent),
"직종": str(one.get("이름") or "") if labor else None,
}
)
return out
def _context(idx: bi.Index) -> dict[str, set[str]]:
"""표 → 이름 · 공종 · 구분 글(한글만) — 역색인 한 판마다 한 번."""
got = _ctx.get(id(idx))
if got is None:
_ctx.clear()
got = _ctx[id(idx)] = {
k: _tokens(
" ".join(
str(x or "")
for x in (t.get("이름"), (t.get("용도") or {}).get("공종"), t.get("상세구분"))
)
)
for k, t in idx.tables.items()
}
return got
STOP = re.compile(
"및|설치|해체|운반|조립|가공|제작|시공|공사|현장|작업|기계|인력|보통|일반|사용|적용|기준|표준|구간|공통"
)
def _tokens(s: str) -> set[str]:
return {t for t in re.split(r"[^가-힣]+", STOP.sub(" ", _hangul_keep(s))) if len(t) >= 2}
def _hangul_keep(s: Any) -> str:
"""한글 · 공백만 남김(낱말 가름 유지)."""
return re.sub(r"[^가-힣]+", " ", str(s or ""))
def _on_topic(title: set[str], table: set[str]) -> bool:
"""공종 맞음 — 블록 이름 낱말과 표 이름 · 공종 낱말이 같거나 한쪽이 다른 쪽에 들어 있음."""
return any(
a == b or min(len(a), len(b)) >= 3 and (a in b or b in a) for a in title for b in table
)
def _near(a: str, b: str) -> bool:
x, y = _flat(a), _flat(b)
return len(x) >= 2 and len(y) >= 2 and (x in y or y in x)
def _same(how: str, cell: float, v: float) -> bool:
"""엑셀 수와 칸 값이 같은 꼴(eq 같음 · pct 율 ↔ 소수 · kgt t ↔ kg)."""
scale = {"eq": (1,), "pct": (100, 0.01), "kgt": (1000, 0.001)}[how]
return any(abs(cell - v * m) <= 1e-9 * max(1.0, abs(cell)) for m in scale)
def _named(slot: dict, cell: dict, table: dict) -> bool:
"""줄 이름이 칸 이름(칸 · 같은 줄 글 칸)과 맞는가 — 인력 = 직종 맞음."""
name = slot["직종"] or slot["줄"]
if _near(name, str(cell["칸"]).split("/")[0]):
return True
row = (table.get("줄") or [{}])[cell["줄"]] if cell["줄"] < len(table.get("줄") or []) else {}
return any(isinstance(v, str) and _near(name, v) for v in row.values())
def find(idx: bi.Index, slot: dict, title: str) -> list[dict]:
"""자리 하나 → 후보 칸 `[{표, 줄, 칸, 값, 단위, 꼴, 맥락, 이름, 번호, 갈래}]`(이름 맥락 먼저)"""
k = {"v": slot["수"], "d": slot["d"], "단위": slot["단위"], "직종": slot["직종"]}
ctx, want = _context(idx), _tokens(title.split("(")[0]) # 이름 앞부분(규격 괄호 앞)
out, seen = [], set()
for cid, how in idx.lookup(k):
c = idx.cells[cid]
t = idx.tables.get(c["표"])
if t is None or c["종류"] in ("eq", "cond") or how not in FORMS:
continue
if not _same(how, c["v"], slot["수"]) or (c["표"], c["줄"], c["칸"]) in seen:
continue
if not _on_topic(want, ctx.get(c["표"], set())):
continue # 공종 문맥이 맞아야 후보
named = slot["직종"] is not None or _named(slot, c, t) # 인력 = lookup 이 직종 맞춤
if not named and slot["종류"] == "재료":
continue # 재료는 칸 이름도 맞아야
why = "이름 · 공종" if named else "공종"
seen.add((c["표"], c["줄"], c["칸"]))
out.append(
{
"표": c["표"],
"줄": c["줄"],
"칸": c["칸"],
"값": c["v"],
"단위": c["단위"],
"꼴": how,
"맥락": why,
"이름": t.get("이름"),
"번호": t.get("원문번호"),
"갈래": "소요량" if c["표"].startswith("Q") else "계수",
}
)
return sorted(out, key=lambda x: (x["맥락"] == "공종", x["표"], x["줄"]))
def scan(row: dict, idx: bi.Index | None = None) -> list[dict]:
"""로직 줄 → 자리마다 `후보`(전부) · 수 — 순수(저장 안 함)."""
idx = idx or bi.get()
title = str(row.get("이름") or "")
return [{**s, "후보": find(idx, s, title)} for s in slots(row)]
def flags(row: dict, idx: bi.Index | None = None) -> list[str]:
"""만들 때 표지(「참고 · …」) — 자리마다 한 줄 · 사람 확인 · 후보 0 = 표 칸 없음."""
out = []
for s in scan(row, idx):
n = len(s["후보"])
what = f"소요량 후보 {n} · 사람 확인" if n else "표 칸 없음"
out.append(f"{em.NOTE}{what} — {s['줄']} {s['수']:g}")
return out
def tally(scanned: list[dict]) -> dict[str, int]:
"""자리 수 · 줄 수 · 후보 유일 | 여럿 | 없음 자리 수."""
return {
"자리": len(scanned),
"줄": len({s["자리"].rsplit(":", 1)[0] for s in scanned}),
"유일": sum(len(s["후보"]) == 1 for s in scanned),
"여럿": sum(len(s["후보"]) > 1 for s in scanned),
"없음": sum(not s["후보"] for s in scanned),
}
# ── 고름 · 버림(문서 기록) ─────────────────────────────────────────────
def _need(doc: Any) -> dict:
if not imp.is_imported(doc) or imp.old_form(doc):
raise sd.DocError("가져온 식 단가산출만(옛 꼴 = 다시 불러오기)")
return doc
def _slots(doc: dict) -> list[dict]:
"""불러올 때 적은 자리(문서 머리 `가져온.자리`)."""
return list(((doc[imp.KEY][imp.FIRST].get(imp.KEY) or {}).get("자리")) or [])
def _state(doc: dict) -> dict[str, list]:
meta = doc[imp.KEY].get(KEY) or {}
return {"고름": list(meta.get("고름") or []), "버림": list(meta.get("버림") or [])}
def _with(doc: dict, state: dict) -> dict:
meta = {k: v for k, v in state.items() if v}
rest = {k: v for k, v in doc[imp.KEY].items() if k != KEY}
return {**doc, imp.KEY: rest | ({KEY: meta} if meta else {})}
def view(doc: Any, idx: bi.Index | None = None) -> dict[str, Any]:
"""화면 답 — 자리마다 {자리, 줄, 수, 단위(식이 그 수 하나일 때만), 후보수, 후보, 상태 후보|없음|고름|버림, 고른}."""
doc = _need(doc)
state, rows = _state(doc), []
idx = idx or bi.get()
title = str(doc[imp.KEY][imp.FIRST].get("이름") or "")
scanned = [{**s, "후보": find(idx, s, title)} for s in _slots(doc)]
picked = {x["자리"]: x for x in state["고름"] if x.get("수") is not None}
dropped = set(state["버림"])
for s in scanned:
mine = picked.get(s["자리"])
if mine: # M01 칸 값이 그새 바뀌었으면 알림(기록은 그대로)
now = next(
(
c["v"]
for c in idx.cells_of_table.get(mine["표"], [])
if c["줄"] == mine["줄"] and c["칸"] == mine["칸"]
),
None,
)
mine = {
**mine,
"지금": now,
"같음": now is not None and _same(mine["꼴"], now, s["수"]),
}
rows.append(
{
**{k: s[k] for k in ("자리", "갈래", "줄", "수")},
# 식 속 수(시공량 · 나눔 수) = 단위 모름 → 수만
"단위": s["단위"] if s.get("보임") else "",
"후보수": len(s["후보"]),
"후보": s["후보"][:SHOWN],
"고른": mine,
"상태": (
"고름"
if mine
else "버림"
if s["자리"] in dropped
else "후보"
if s["후보"]
else "없음"
),
}
)
count = tally(scanned) | {
"고름": sum(r["상태"] == "고름" for r in rows),
"버림": sum(r["상태"] == "버림" for r in rows),
}
return {"줄": rows, "집계": count}
def pick(doc: Any, spot: str, cell: dict, idx: bi.Index | None = None) -> dict[str, Any]:
"""후보 칸 고름 — 엑셀 수 = 칸 값일 때만(다르면 400 까닭) · 기록 + 문서 그 수 자리 = 표 연결 변수
(엑셀 칸 값 기억 · 금액 그대로)."""
doc = cp.deepcopy(_need(doc))
idx = idx or bi.get()
slot = next((s for s in _slots(doc) if s["자리"] == spot), None)
if slot is None:
raise sd.DocError(f"없는 자리 「{spot}」")
table = idx.tables.get(str((cell or {}).get("표")))
rows = (table or {}).get("줄") or []
at, col = (cell or {}).get("줄"), (cell or {}).get("칸")
found = next(
(
c
for c in idx.cells_of_table.get(str((cell or {}).get("표")), [])
if c["줄"] == at and c["칸"] == col and c["종류"] not in ("eq", "cond")
),
None,
)
if table is None or found is None or not isinstance(at, int) or at >= len(rows):
raise sd.DocError("없는 표 칸")
how = next((h for h in FORMS if _same(h, found["v"], slot["수"])), None)
if how is None:
raise sd.DocError(
f"엑셀 수 {slot['수']:g} ≠ 표 칸 값 {found['v']:g} — 같은 값인 칸만 선택할 수 있음"
)
one = {
"자리": spot,
"수": slot["수"],
"층": LAYER,
"표": found["표"],
"줄": at,
"칸": col,
"값": found["v"],
"꼴": how,
}
conds = _conds(table, at)
for target in imp.docs_of(doc):
_unpick(target, spot)
if conds is not None:
_apply(target, slot, one, conds)
state = _state(doc)
state["고름"] = [x for x in state["고름"] if x.get("자리") != spot] + [one]
state["버림"] = [x for x in state["버림"] if x != spot]
return {"문서": _with(doc, state)}
def drop(doc: Any, spot: str, undo: bool = False) -> dict[str, Any]:
"""자리 후보 버림(또는 [되돌리기]) — 고른 것이 있으면 같이 풂(문서 수 되돌림)."""
doc = cp.deepcopy(_need(doc))
if not any(s["자리"] == spot for s in _slots(doc)):
raise sd.DocError(f"없는 자리 「{spot}」")
for target in imp.docs_of(doc):
_unpick(target, spot)
state = _state(doc)
state["고름"] = [x for x in state["고름"] if x.get("자리") != spot]
state["버림"] = [x for x in state["버림"] if x != spot] + ([] if undo else [spot])
return {"문서": _with(doc, state)}
# ── 문서 고침(857-3b) — 그 수 자리 ↔ 표 연결 변수 ─────────────────────────
SPOT = "가져온자리" # 고른 칸 변수 — 자리 · 되돌릴 수 글
SCALE = {"eq": (1,), "pct": (100, 0.01), "kgt": (1000, 0.001)}
def _field(spot: str) -> str:
return "수량" if spot.startswith("호표:") else "단가"
def _line_of(doc: dict, spot: str) -> dict | None:
head = spot.rsplit(":", 1)[0]
return next((x for x in doc.get("금액") or [] if x.get(todoc.FROM) == head), None)
def _doc_nth(node: Any, before: list[str]) -> int | None:
"""가져온 줄 n 번째 수(앞 수 `before`) → 문서 식 수 차례 — 문서 = 가져온 줄 수에서 군더더기
(0 · 1 · 100)만 빠진 차례."""
doc_nums: list[Decimal] = []
_literals(node, doc_nums)
j = 0
for v in (Decimal(x) for x in before):
if j < len(doc_nums) and doc_nums[j] == v:
j += 1
return j if j < len(doc_nums) else None
def _swap(node: Any, n: int, new: tuple, seen: list) -> Any:
"""`_literals` 차례의 n 번째 수 → `new` 마디."""
if not isinstance(node, tuple):
return node
kind = node[0]
if kind == "num":
seen[0] += 1
return new if seen[0] - 1 == n else node
if kind == "bin":
cmp_ = node[1] in CMP
sides = [
side if cmp_ and side[0] == "num" else _swap(side, n, new, seen) for side in node[2:]
]
return (kind, node[1], *sides)
if kind in ("neg", "pct", "field"):
return (kind, _swap(node[1], n, new, seen), *node[2:])
if kind == "call":
return ("call", node[1], [_swap(a, n, new, seen) for a in node[2]])
return node
def _conds(table: dict, at: int) -> dict | None:
"""표 줄 차례 → 그 줄 하나만 맞는 조건 {조건: 값}(범위 = 위 끝 › 아래 끝) · 못 가림 = None."""
from M02_MasterTemplete import M02_Doc_Copy as dc
rows = table.get("줄") or []
if not (0 <= at < len(rows)):
return None
row, out = rows[at], {}
for cond, how in (table.get("조건") or {}).items():
if cond not in row:
continue
have = row[cond]
if how == "범위":
low, high = have
have = high if high is not None else low
if have is None:
return None
out[cond] = have
try:
hit = dc.ml.find(table, out)
except Exception: # noqa: BLE001 — 못 가림 = 수 그대로
return None
return out if hit is row else None
def _times(one: dict, m: float) -> bool:
"""칸 값 = 엑셀 수 × 배 m."""
cell, v = float(one.get("값") or 0), float(one.get("수") or 0)
return abs(cell - v * m) <= 1e-9 * max(1.0, abs(cell))
def _apply(doc: dict, slot: dict, one: dict, conds: dict) -> None:
"""문서 그 금액 줄 식의 그 수 → 표 연결 변수(÷ 배) · 줄 · 수가 안 맞으면 그대로(기록만)."""
from M02_MasterTemplete import M02_Doc_Import as dim
spot = slot["자리"]
line, field = _line_of(doc, spot), _field(spot)
if line is None:
return
try:
node = todoc.md.parse(str(line.get(field)))
except todoc.md.DocError:
return
n = _doc_nth(node, list(slot.get("앞") or []))
nums: list[Decimal] = []
_literals(node, nums)
scale = next((m for m in SCALE.get(str(one["꼴"]), (1,)) if _times(one, m)), None)
if n is None or float(nums[n]) != float(slot["수"]) or scale is None:
return
taken = {str(v.get("열쇠")) for v in doc.get("변수") or []}
taken |= {todoc.md.var_id(v) for v in doc.get("변수") or []}
name = next(f"{dim.PICK}{k}" for k in range(1, 999) if f"{dim.PICK}{k}" not in taken)
ref = ("var", name) if scale == 1 else ("bin", "/", ("var", name), ("num", Decimal(str(scale))))
line[field] = todoc.md.text_of(_swap(node, n, ref, [0]))
link = {"갈래": "표", "표": str(one["표"]), "조건": {k: dim._lit(v) for k, v in conds.items()}}
link |= {"칸": str(one["칸"]), dim.XL: Decimal(str(one["값"]))}
var = {"열쇠": name, "기호": name, "아래": "", "위": "", "이름": name, "단위": "", "연결": link}
doc.setdefault("변수", []).append(var | {SPOT: {"자리": spot, "수": str(nums[n])}})
def _unpick(doc: dict, spot: str) -> None:
"""그 자리 고른 칸 변수 → 원래 수로 되돌림 · 변수 지움."""
mine = [v for v in doc.get("변수") or [] if (v.get(SPOT) or {}).get("자리") == spot]
if not mine:
return
line, field = _line_of(doc, spot), _field(spot)
for var in mine:
name, num = todoc.md.var_id(var), ("num", Decimal(var[SPOT]["수"]))
if line is not None:
try:
node = todoc.md.parse(str(line.get(field)))
line[field] = todoc.md.text_of(_back(node, name, num))
except todoc.md.DocError:
pass
doc["변수"] = [v for v in doc["변수"] if v is not var]
def _back(node: Any, name: str, num: tuple) -> Any:
if not isinstance(node, tuple):
return node
if node == ("var", name) or (node[0] == "bin" and node[1] == "/" and node[2] == ("var", name)):
return num
if node[0] == "bin":
return ("bin", node[1], _back(node[2], name, num), _back(node[3], name, num))
if node[0] in ("neg", "pct", "field"):
return (node[0], _back(node[1], name, num), *node[2:])
if node[0] == "call":
return ("call", node[1], [_back(a, name, num) for a in node[2]])
return node