fix(M02): 흐름 셈 = 옛 셈 — 표 「·범위규칙」 줄 경계 말 · 검색어 조건 찾기 · 재료가 로직 입력 읽음 · 빈 단가 알림 · 고르기 글 값 그대로(PLAN 36-2 대조 49 → 8)

- main(sub7 a774b4e97 Model 덧) 받아 합침 · Compute 재료 조건 찾기는 sub7 의 틀 채우기 + 빈 단가 알림
- 남은 8: 표에 여럿 맞음 5(옛 find 의 값 칸 있는 줄만 거름 — lookup) · 빈 값이 든 식 3(옛 = 그 줄 비움 · 흐름 = 빈 칸 0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KmELpdXFDRZHhfbGuRhSmL
This commit is contained in:
2026-10-02 01:04:03 +09:00
co-authored by Claude Opus 5.5
16 changed files with 345 additions and 42 deletions
+4 -1
View File
@@ -28,7 +28,10 @@ export interface CfQuery {
unit?: string;
field?: string;
inputs?: Record<string, unknown>;
slot?: Partial<CfElementRef> & { field?: "규격" | "이름" | "키"; op?: "포함" | "같음" };
slot?: Partial<CfElementRef> & {
field?: "규격" | "이름" | "키" | "검색어";
op?: "포함" | "같음";
};
value?: unknown;
pick?: string;
}
+35 -4
View File
@@ -131,7 +131,10 @@ def _element_value(
"unit": el.get("unit"),
"inputs": env,
}
got = dv.slot_price(slot, ports.get(src.get("box"), {}).get(src.get("name")))
value = ports.get(src.get("box"), {}).get(src.get("name"))
if rule.get("field") == "검색어": # 틀의 자리마다 알약 값 → 채운 검색어 글(빈 자리면 None)
value, slot["unit"] = _fill_template(rule, ports), el.get("unit")
got = dv.slot_price(slot, value)
if not got["ok"] and not got.get("blank") and el.get("default"):
errors.append(
f"「{box.get('name')} · {el.get('name')}」 {got['reason']} — 기본 품목으로 셈"
@@ -160,6 +163,20 @@ def _element_value(
return got.get("value")
def _fill_template(rule: dict, ports: dict) -> str | None:
"""재료 검색어 틀의 자리에 slots 알약 값 — 옛 엔진 fill 그대로(빈 자리 = None)."""
env = {}
for x in rule.get("slots") or []:
src = x.get("from") or {}
env[x.get("name")] = ports.get(src.get("box"), {}).get(src.get("name"))
if any(v is None for v in env.values()):
return None
try:
return store.cm.mf.fill(str(rule.get("template") or ""), env)
except store.cm.mf.FormulaError:
return None
def _port(el: dict) -> str:
"""요소 알약 이름 — Model `elementPort`(고정 아니면 자리 이름 slot · 없으면 name)."""
slot = str(el.get("slot") or "").strip()
@@ -349,6 +366,7 @@ def _lookup(rule: dict, block: Any, conds: dict) -> tuple[Any, str | None]:
if out not in head and not two:
return None, "오류"
tests, ups = [], []
rk = head.index(RANGE_RULE) if RANGE_RULE in head else None
for c in rule.get("conds") or []:
col, want = str(c.get("col")), _cond_of(conds, c.get("from") or {})
if col in head:
@@ -366,10 +384,17 @@ def _lookup(rule: dict, block: Any, conds: dict) -> tuple[Any, str | None]:
low, high = _num_of(row[lo]), _num_of(row[hi])
if low is not None and low == high: # 숫자 하나(아래 = 위) = 같음(브레인 정함)
return x is not None and x == low
word = str(row[rk] or "") if rk is not None else "" # 경계 — 이상 · 미만(Rule 같음)
return (
x is not None
and (row[lo] is None or (low is not None and low < x))
and (row[hi] is None or (high is not None and x <= high))
and (
row[lo] is None
or (low is not None and (low <= x if word[:2] == "이상" else low < x))
)
and (
row[hi] is None
or (high is not None and (x < high if word[-2:] == "미만" else x <= high))
)
)
tests.append(fits)
@@ -451,7 +476,12 @@ def _depends(lg: dict) -> list[tuple[str, str]]:
for b in lg.get("boxes") or []:
for el in (b.get("input") or {}).get("elements") or []:
if el.get("mode") == "rule" and el.get("rule"):
out.append(((el["rule"].get("from") or {}).get("box"), b["id"]))
rule = el["rule"]
srcs = [
rule.get("from") or {},
*[x.get("from") or {} for x in rule.get("slots") or []],
]
out += [(p.get("box"), b["id"]) for p in srcs]
return out
@@ -489,6 +519,7 @@ def _sheet_of(box: dict, arrived: dict, given: dict) -> dict:
REST = "앞 조건이 안 맞아 쉬는 갈래"
RANGE_RULE = "·범위규칙" # 표 블록 줄마다 범위 경계 규칙 칸(Values._table · Rule RANGE_RULE)
NA_VALUE = "#N/A" # 함수 칸으로 가는 표 찾기 실패 — 칸에 NA() · 결과 오류일 때만 끊긴 곳(Eval 같음)
+16 -6
View File
@@ -103,10 +103,10 @@ class _Flow:
# ── 바깥 값 알약 ──────────────────────────────────────────────────
def element(
self, group: str, ref: str, unit: str, label: str, rule: dict | None = None
self, group: str, ref: str, unit: str, label: str, rule: dict | None = None, **more: Any
) -> dict:
"""그룹 입력 상자의 요소 알약 — 그룹마다 상자 하나 · 같은 ref · 단위 · 조건이면 알약 하나
· rule = 조건 찾기(field 「키」 — ref 의 {…} 에 알약 값을 끼운 요소 · CfMaterialRule)."""
· rule = 조건 찾기(CfMaterialRule · 알약 값은 Model depends 로 · 선 없음) · more = scope."""
key = f"el|{group}|{ref}|{unit}|{json.dumps(rule, ensure_ascii=False, sort_keys=True)}"
if key in self.cache:
return self.cache[key]
@@ -120,8 +120,7 @@ class _Flow:
name += "·"
one = {"ref": ref, "name": name, "spec": "", "unit": unit or "-", "mode": "fixed"}
if rule:
one |= {"mode": "rule", "rule": rule, "slot": name}
self.link(rule["from"], {"box": self.cache[gkey]["id"], "name": name})
one |= {"mode": "rule", "rule": rule, "slot": name, **more}
els.append(one)
self.cache[key] = {"box": self.cache[gkey]["id"], "name": name}
return self.cache[key]
@@ -139,14 +138,20 @@ class _Flow:
if len(texts) > 1:
raise Unsupported(f"자리 표시가 여러 칸에 낀 요소 「{ref}」")
((at, text),) = texts.items()
if at == "검색어": # 재료 검색어 틀 — 자리마다 알약 · 서버는 옛 검색어 찾기(정함 · sub4)
names = list(dict.fromkeys(_HOLE.findall(text)))
slots = [{"name": n, "from": self.hole(n)} for n in names]
rule = {"field": "검색어", "op": "같음", "from": slots[0]["from"]}
rule |= {"template": text, "slots": slots}
scope = {k: str(v) for k, v in ref.items() if k in ("구분", "상세구분") and v}
tpl = json.dumps(plain(ref), ensure_ascii=False)
return ("@port", self.element(group, tpl, unit, f"{label} 자리", rule, scope=scope))
# 찾는 값 = 원문번호(「EQ:{기계}」 → 기계 · 「MO:경유:{지역}」 → "경유:"&지역)
want = text.partition(":")[2] if at is None and ":" in text else text
if _HOLE.fullmatch(want):
src = self.hole(want[1:-1])
else:
src = self.func(f"{label} 찾는 말", ("@text", want))
if at is not None:
self.notes.append(f"재료 검색어에 입력이 낌 「{text}」 — 조건 찾기(키 같음)로 옮김")
tpl = text if at is None else json.dumps(plain(ref), ensure_ascii=False)
tpl += f"#{field}" if field else ""
rule = {"field": "키", "op": "같음", "from": src}
@@ -383,6 +388,11 @@ def _layout(f: _Flow) -> None:
for ln in f.links:
srcs = [ln["from"], *[c["from"] for c in (ln.get("rule") or {}).get("conds", [])]]
feeds.setdefault(ln["to"]["box"], set()).update(s["box"] for s in srcs)
for bid, b in f.boxes.items(): # 조건 찾기 요소 — 값을 주는 알약 상자 뒤
for e in (b.get("input") or {}).get("elements") or []:
rule = e.get("rule") or {}
srcs = [rule.get("from"), *[x["from"] for x in rule.get("slots") or []]]
feeds.setdefault(bid, set()).update(p["box"] for p in srcs if p)
depth: dict[str, int] = {}
def level(bid: str, path: frozenset = frozenset()) -> int:
+20 -4
View File
@@ -27,9 +27,19 @@ export interface CfScope {
* field 「키」 = 요소 ref 의 자리 표시 {…} 에 알약 값을 끼운 요소(op 같음) — ref 꼴 「EQ:{기계}」 · 「EQ:{기계}#가격」 ·
* 「MO:경유:{지역}」 · 「LB:{직종}」 · 재료 검색어 묶음 JSON(검색어 안 {…}) · 옛 엔진 `fill` → `Master.get` 과 같은 뜻 */
export interface CfMaterialRule {
field: "규격" | "이름" | "키";
field: "규격" | "이름" | "키" | "검색어";
op: "포함" | "같음";
from: CfPort;
/** field 「검색어」 — 옛 재료 검색어 찾기(master_pick.search) 의 틀(「레미콘 {a}-{b}-{c}」) · scope 구분 · 상세구분 안 */
template?: string;
/** 틀의 자리 {이름} 마다 값을 줄 알약 — from = 첫 자리 */
slots?: { name: string; from: CfPort }[];
}
/** 재료 조건 찾기가 값을 받는 알약 — from + 틀 자리들(겹침 없이) */
export function materialSources(rule: CfMaterialRule): CfPort[] {
const all = [rule.from, ...(rule.slots ?? []).map((x) => x.from)];
return all.filter((p, i) => all.findIndex((q) => q.box === p.box && q.name === p.name) === i);
}
/** 입력 상자가 고른 요소 — ref = 마스터 키 또는 사용자 요소 id
@@ -446,7 +456,8 @@ export function depends(lg: CfLogic): { from: string; to: string }[] {
}
for (const b of lg.boxes)
for (const e of b.input?.elements ?? [])
if (e.mode === "rule" && e.rule) out.push({ from: e.rule.from.box, to: b.id });
if (e.mode === "rule" && e.rule)
for (const p of materialSources(e.rule)) out.push({ from: p.box, to: b.id });
return out;
}
@@ -584,7 +595,8 @@ export function traceBack(lg: CfLogic, port: CfPort): CfStep[] {
lg.links.find((l) => l.to.box === box.id && l.to.name === q.name),
);
for (const e of box.input?.elements ?? [])
if (e.mode === "rule" && e.rule && elementPort(e) === p.name) visit(e.rule.from, "out");
if (e.mode === "rule" && e.rule && elementPort(e) === p.name)
for (const q of materialSources(e.rule)) visit(q, "out");
};
const box = boxOf(lg, port.box);
if (!box) return [];
@@ -630,7 +642,11 @@ export function traceForward(lg: CfLogic, port: CfPort): CfStep[] {
visit(l.to, "in", l);
for (const b of lg.boxes)
for (const e of b.input?.elements ?? [])
if (e.mode === "rule" && e.rule?.from.box === p.box && e.rule.from.name === p.name)
if (
e.mode === "rule" &&
e.rule &&
materialSources(e.rule).some((q) => q.box === p.box && q.name === p.name)
)
visit({ box: b.id, name: elementPort(e) }, "out");
};
const box = boxOf(lg, port.box);
@@ -107,3 +107,15 @@ export function showRounded(v: number, r?: CfRound): string {
let totalNow: CfRound = { places: 0, method: "버림" };
void defaultTotalRound().then((r) => (totalNow = r));
export const totalRoundNow = (): CfRound => totalNow;
/** 그 로직의 합계 끝수 — 비용 출력 상자에 끝수가 실려 있으면 그것(옛 로직을 옮긴 흐름은 자신의 끝수) ·
* 없으면 기본(새 로직 = 일위대가표 계금 1원 미만 버림) */
export function totalRoundOf(
lg: { boxes: { kind: string; output?: { cost: string; round?: CfRound } }[] },
fallback: CfRound,
): CfRound {
const hit = lg.boxes.find(
(b) => b.kind === "output" && b.output?.cost !== "값" && b.output?.round,
);
return hit?.output?.round ?? fallback;
}
+10 -1
View File
@@ -159,6 +159,9 @@ export function applyRule(
return { value: got, why: null, formula };
}
/** 표 블록 범위 경계 규칙 칸(줄마다 「초과·이하」 「이상·이하」 「이상·미만」 「이하」 · Values._table) */
export const RANGE_RULE = "·범위규칙";
/** 표에서 찾기 — 줄마다 맞음 칸 · 맞은 줄 수 · INDEX/MATCH(범위 칸 「이름·아래」 「이름·위」 · 초과 · 이하)
* 빈 조건 칸 = 무엇이든 · 꺼낼 칸이 빈 줄은 뺌(옛 엔진 find · 서버 Compute `_lookup` 과 같음) */
function lookup(
@@ -187,6 +190,12 @@ function lookup(
// 조건 값 = 1행 · 블록 오른쪽 한 칸 띄고
const tests: ((r: number) => string)[] = out ? [(r) => `NOT(ISBLANK(${out}${r}))`] : [];
const ups: string[] = [];
// 범위 경계 — 줄마다 「·범위규칙」 칸(이상 … = 아래 끝 포함 · … 미만 = 위 끝 뺌) · 없으면 초과 · 이하
const rc = at(RANGE_RULE);
const lowCmp = (c: string, r: number, x: string): string =>
rc ? `IF(LEFT(${rc}${r},2)="이상",${c}${r}<=${x},${c}${r}<${x})` : `${c}${r}<${x}`;
const highCmp = (c: string, r: number, x: string): string =>
rc ? `IF(RIGHT(${rc}${r},2)="미만",${x}<${c}${r},${x}<=${c}${r})` : `${x}<=${c}${r}`;
let bad = !out || rows < 1;
rule.conds.forEach((c, i) => {
const ref = `$${colName(W + 1 + i)}$1`;
@@ -201,7 +210,7 @@ function lookup(
tests.push(
(r) =>
`IF(AND(NOT(ISBLANK(${low}${r})),${low}${r}=${high}${r}),${ref}=${low}${r},` +
`AND(OR(ISBLANK(${low}${r}),${low}${r}<${ref}),OR(ISBLANK(${high}${r}),${ref}<=${high}${r})))`,
`AND(OR(ISBLANK(${low}${r}),${lowCmp(low, r, ref)}),OR(ISBLANK(${high}${r}),${highCmp(high, r, ref)})))`,
);
} else bad = true;
});
+13 -4
View File
@@ -12,7 +12,14 @@ import { formatMoney } from "../../M01_MasterData/M01_MasterData_UI_Logic_Money"
import type { CfEvalOptions, CfEvalResult, CfValues } from "./M02_DF_Eval";
import type { CfBox, CfLogic, CfRound } from "./M02_DF_Model";
import { showValue } from "./M02_DF_OutputPanel";
import { defaultTotalRound, itemRoundNow, roundBy, roundText, showRounded } from "./M02_DF_Round";
import {
defaultTotalRound,
itemRoundNow,
roundBy,
roundText,
showRounded,
totalRoundOf,
} from "./M02_DF_Round";
import { renderVerify, type CfSel } from "./M02_DF_Verify";
import "./M02_DF_Summary.css";
@@ -69,18 +76,20 @@ export function renderSummary(
? ts("Total")
: ts("Per", { per: /^\d/.test(perUnit) ? perUnit : `1${perUnit}` });
const { cost } = result;
/** 합계 끝수 — 비용 출력 상자에 실린 끝수(옮긴 로직의 자신 끝수) · 없으면 기본 1원 미만 버림 */
const sumRound = totalRoundOf(lg, totalRound);
const big = el("p", {
className: "m02-dfsum__big",
children: [
el("span", { text: money ? perText : ts("Total") }),
el("strong", { text: `${formatMoney(roundBy(totalRound, cost.계))} ${ts("Won")}` }),
el("strong", { text: `${formatMoney(roundBy(sumRound, cost.계))} ${ts("Won")}` }),
],
});
const costs = el("dl", {
className: "m02-dfsum__costs",
children: COSTS.flatMap((c) => [
el("dt", { text: ts(COST_KEY[c]) }),
el("dd", { text: formatMoney(roundBy(totalRound, cost[c])) }),
el("dd", { text: formatMoney(roundBy(sumRound, cost[c])) }),
]),
});
@@ -161,7 +170,7 @@ export function renderSummary(
: []),
el("p", {
className: "m02-dfsum__muted",
text: `${ts("RoundTotal")}: ${roundText(totalRound)}`,
text: `${ts("RoundTotal")}: ${roundText(sumRound)}`,
}),
verifyHost,
);
+26 -10
View File
@@ -19,7 +19,7 @@ from M01_MasterData import M01_MasterData_Store as store
cm = store.cm
_UKEY = re.compile(r"^UE-(\d{4,})$")
RANGE_LOW, RANGE_HIGH = "·아래", "·위"
RANGE_RULE = "범위규칙" # 표 블록 끝 칸 — 범위 경계(옛 find 와 같음 · 없으면 초과·이하)
RANGE_RULE = "·범위규칙" # 표 블록 끝 칸 — 줄마다 경계 말(옛 find 와 같음 · 없으면 초과·이하)
FIELDS = (*cm.mf.COST_ITEMS, "계")
@@ -214,14 +214,28 @@ def _table_of(table: dict | None, key: str, at: Any) -> dict:
else:
line.append(None if v == "" else v if not isinstance(v, dict) else str(v))
rows.append(line)
if (
"범위" in conds.values()
): # 범위 경계 규칙 — 끝 칸 「범위규칙」 줄마다 같은 글(lookup 이 읽음)
rule = str(table.get(RANGE_RULE) or "초과·이하")
head, rows = [*head, RANGE_RULE], [[*r, rule] for r in rows]
if "범위" in conds.values(): # 끝 칸 「·범위규칙」 = 줄마다 그 줄 경계 말(lookup 이 읽음)
head, rows = [*head, RANGE_RULE], [[*r, _bound(table, x)] for r, x in zip(rows, lines)]
return {"ok": True, "rows": [head, *rows], "name": table.get("이름"), "unit": table.get("기준")}
def _bound(table: dict, row: dict) -> str:
"""줄 경계 말 — 옛 `_match` 와 같음 · 첫 낱말 · 「이하 포함」 이면 맨 윗줄만 이상·이하."""
rule, *more = str(table.get("범위규칙") or "초과·이하").split(" · ")
rule = rule.split(" (")[0]
if rule != "이상·미만" or not any("이하 포함" in x for x in more):
return rule
for c, kind in (table.get("조건") or {}).items(): # 옛 _match — 그 범위 칸 위 끝이 가장 큰 줄
ups = [
r[c][1]
for r in table.get("줄") or []
if isinstance(r.get(c), list) and r[c][1] is not None
]
if kind == "범위" and ups and isinstance(row.get(c), list) and row[c][1] == max(ups):
return "이상·이하"
return rule
def _arith(v: Any) -> Any:
"""값 칸 수 식 글(「(0.05)」 「1/1.30」) — 옛 셈처럼 수로(사칙연산 · 괄호만 · 옛 엔진 파서)."""
if not isinstance(v, str) or not cm.mf._ARITH.fullmatch(v):
@@ -412,13 +426,15 @@ def _filled(template: str, value: Any) -> str:
def _search(slot: dict, value: Any) -> dict:
"""조건 찾기 field 검색어 — 틀(요소 ref 묶음)의 {자리} 를 알약 값으로 채워 옛 찾기 그대로."""
cond = _pick(slot.get("ref"))
if cond is None:
return {"ok": False, "reason": "검색어 틀이 없음 — 요소에 검색어 묶음을 넣어 주세요"}
if value in (None, ""):
return {"ok": False, "reason": "찾을 값이 비어 있음 — 이어진 알약을 확인해 주세요"}
cond = _pick(slot.get("ref")) # 요소 ref = 옛 검색어 묶음(규격 · 지역 칸도 그대로)
if cond is None: # 묶음이 없으면 범위(구분 · 상세구분) + 채운 검색어
scope = slot.get("scope") or {}
cond = {k: scope[k] for k in ("구분", "상세구분") if scope.get(k)} | {"검색어": ""}
fill = {k: _filled(v, value) for k, v in cond.items() if isinstance(v, str) and _HOLE.search(v)}
return _material({**cond, **fill}, str(slot.get("unit") or ""), slot.get("inputs"))
cond = {**cond, **fill} if fill else {**cond, "검색어": str(value)}
return _material(cond, str(slot.get("unit") or ""), slot.get("inputs"))
def slot_price(slot: dict, value: Any = None, pick: str | None = None) -> dict: