refactor(856-1): 단가산출 상세 몸 걷기 — 줄 쌓기 한 벌 · 열 때 서버 셈 한 번

- 지움: M01 LogicLab_Ho · LogicLab_Cover · M02 Sangeun_Cover_Model · Sangeun_Undo · Sangeun_BaseHead · Labor_RowSk
- Sangeun_Detail: 숨긴 몸 · 바탕 원값(bare) 셈 · 덮개 고침 · 재료 고름 · 키 글자 약속(SK-000000) 걷음 → 모드 옵션(page · ref · memory)
- Sangeun_Tabs: 몸 그릇 · 숨김 걷음 · Sangeun_Cover: 뺀 줄 띠 걷음 · 셈 보기 덧칸 끔(머리 띠는 안 씀) · 머리 띠 타입만 둠(856-2 에서 파일째)
- 일위대가 줄 모달: 로직 줄 · 셈 주입 줄 = 안내 한 줄(856-3 까지) · 상세 · [적용] 걷음 · 줄 패치 칸 · 타입 걷음(저장본 0)
- M01 LogicLab_Detail: M02 몸 칸 걷음(M01 보기 그대로) · 지운 파일만 쓰던 글 키 16 · CSS 규칙 걷음
- 시험: 지운 몸만 붙든 시험 지움(717_3 · 722 · 748_0 · helper 728_2 · 748_0) · 섞인 파일은 몸 꼴 · 글 대조 함수 · 줄만 지움(서버 셈 시험 남김) · 856-0 단언 뒤집음
- 수치: 열 때 /sangeun/calc 2 → 1 · 숨은 몸 DOM 2 → 0 · 화면 파일 줄 −1.9 천 안팎

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 19:36:59 +09:00
co-authored by Claude Opus 5.5
parent 13c1bd961a
commit d6715dcec5
44 changed files with 129 additions and 3279 deletions
@@ -1,44 +0,0 @@
/* PLAN 728-2 헬퍼 — SK 고침 꼴(`logic/M02_Sangeun_Cover_Model.ts`)이 화면배(SK 1 단위 몫)를 문서 몫으로 되돌리는지.
* 짝 = `test_728_2_sk_unit.py`. 결과 = 표준출력 JSON.
*/
const path = require("path");
const { makeLoader } = require("./helper_ts_stub_loader.cjs");
const ROOT = path.join(__dirname, "..", "..");
const { load } = makeLoader({ root: ROOT });
const m = load("M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
// GF000287 단목베기 SK 단위 본 — 서버 화면 답 = 100본 몫 ÷100(화면배 100)
const line = (cid, 이름, 수량, 금액) => ({
cid,
이름,
단위: "인",
수량,
단가: 금액 / 수량,
금액,
비목: { 노무비: 금액 },
});
const ans = {
기준: { 계: 1538.894 },
줄: [line("labor:LB000101#0", "벌목부", 0.002, 506.486), line("add:#0", "보통인부", 0.5, 86034)],
정체: ["labor:LB000101#0", "add:#0"],
짝잃음: [],
바탕판: "",
배: 100,
화면배: 100,
};
const bare = { ...ans, 줄: [ans.줄[0]], 정체: ["labor:LB000101#0"] };
const doc = {
단위: "본",
바탕: { 로직: "GF000287" },
더한줄: [{ 종류: "인력", 요소: "LB000002", 수량: 50 }],
};
const rows = m.rowsOf(ans, bare, doc);
const out = { was: rows[0].was, t: rows.map((r) => r.t) };
m.setLineCover(doc, rows[0], { qty: 0.003 }, false); // 화면 0.003 = 문서 0.3(100본 몫)
m.setLineCover(doc, rows[1], { qty: 0.6 }, false); // 더한 인력 화면 0.6 = 문서 60
out.cover = doc.덮개;
out.added = doc.더한줄[0].수량;
const view = m.hoView(ans, bare, null, doc);
out.shown = view.covers;
process.stdout.write(JSON.stringify(out));
-102
View File
@@ -1,102 +0,0 @@
/* PLAN 748-0 헬퍼 — SK 고침 꼴(`logic/M02_Sangeun_Cover_Model.ts` · `M02_Sangeun_Undo.ts`):
* 둘째 기초 세부 품 = M01 원문 · 고침 = 원문 몫 그대로 · 빼기 기억(뺀더한줄) · 되살림 · 수량 처음값 되돌림.
* 짝 = `test_748_0_sk_undo.py`. 결과 = 표준출력 JSON.
*/
const path = require("path");
const { makeLoader } = require("./helper_ts_stub_loader.cjs");
const { load } = makeLoader({ root: path.join(__dirname, "..", "..") });
const m = load("M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
// 둘째 기초 GF 한 줄 — 원문 0.871 · 머리 수량 0.01 이면 상자 몫 0.00871
const detail = {
cid: "add:#1/labor:LB000101#0",
이름: "벌목부",
단위: "인",
수량: 0.00871,
단가: 100000,
금액: 871,
비목: { 노무비: 871 },
원문: { 수량: 0.871, 금액: 87100, 비목: { 노무비: 87100 } },
바탕값: { qty: 0.871, 단가: 100000 },
};
const ans = {
기준: { 계: 871 },
줄: [
{
cid: "labor:LB000002#0",
이름: "보통인부",
단위: "인",
수량: 1,
단가: 100,
금액: 100,
비목: { 노무비: 100 },
},
{
cid: "add:#0",
이름: "추가 인력",
단위: "인",
수량: 2,
단가: 100,
금액: 200,
비목: { 노무비: 200 },
},
{
cid: "add:#1",
이름: "둘째 기초",
단위: "100㎥",
수량: 0.01,
단가: null,
금액: 871,
비목: { 노무비: 871 },
펼침: [detail],
},
],
정체: ["labor:LB000002#0", "add:#0", "add:#1"],
짝잃음: [],
바탕판: "",
};
const doc = {
단위: "㎥",
바탕: { 로직: "GF000099" },
더한줄: [
{ 종류: "인력", 요소: "LB000002", 수량: 2, 처음수량: 2 },
{ 종류: "로직", 로직: "GF000316", 수량: 0.01, 처음수량: 0.01 },
],
고름: { "add:#1": "MT1" },
};
const out = {};
const rows = m.rowsOf(ans, null, doc);
const sub = rows.find((r) => r.cid === detail.cid);
const view = m.hoView(ans, null, null, doc);
const at = view.cids.indexOf(detail.cid);
out.shownQty = view.호표[at].수량; // 원문 그대로
out.lineQty = view.lines[at].수량;
out.lineAmount = view.lines[at].금액; // 상자 몫 그대로
out.t = sub.t;
// 세부 품 고침 — 화면 0.9 = 문서 덮개 0.9(머리 수량 안 나눔)
m.setLineCover(doc, sub, { qty: 0.9 }, false);
out.cover = doc.더한줄[1].덮개;
out.coverShown = m.hoView(ans, null, null, doc).covers[at].qty;
// 더한 항목 수량 고침 → 처음값 되돌림
const man = m.rowsOf(ans, null, doc).find((r) => r.cid === "add:#0");
m.setLineCover(doc, man, { qty: 5 }, false);
out.manQty = doc.더한줄[0].수량;
m.setLineCover(doc, man, null, false);
out.manBack = doc.더한줄[0].수량;
// 더한 항목 빼기 → 기억 + 열쇠 당김 → 되살림
m.dropLine(doc, man);
out.afterDrop = { adds: doc.더한줄.length, gone: doc.뺀더한줄, pick: doc.고름 };
out.goneRows = m.goneRows(doc);
m.restoreLine(doc, "gone:0");
out.afterBack = {
adds: doc.더한줄.map((x) => x.요소 ?? x.로직),
gone: doc.뺀더한줄 ?? null,
pick: doc.고름,
};
// 둘째 기초 통째 빼기 → 되살림
m.dropBase(doc, 1, "둘째 기초");
out.baseGone = { adds: doc.더한줄.length, name: m.goneRows(doc)[0].이름, pick: doc.고름 };
m.restoreLine(doc, "gone:0");
out.baseBack = doc.더한줄.map((x) => x.요소 ?? x.로직);
process.stdout.write(JSON.stringify(out));
@@ -98,7 +98,7 @@ for (let i = 0; i < 5; i++) {
const { createSangeunTabs } = load("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts");
const b2 = listeners;
for (let i = 0; i < 5; i++) {
const t = createSangeunTabs(new Fake("div"), { edit: false, scope: { layer: "system", owner: null } });
const t = createSangeunTabs({ edit: false, scope: { layer: "system", owner: null } });
out.tabs.push(listeners - b2);
t.destroy();
out.tabs.push(listeners - b2);
+5 -5
View File
@@ -311,11 +311,11 @@ async function openSk(doc, opt = {}) {
// ① 단가산출 화면(페이지) — 바탕 있음 · 없음
out.page_base = await openSk(
{ 키: "SK-000001", 이름: "견본", 단위: "㎡", 바탕: { 로직: "GC001109" } },
{ source: true },
{ mode: "page" },
);
out.page_nobase = await openSk({ 키: "SK-000002", 이름: "견본", 단위: "㎡" }, { source: true });
out.page_nobase = await openSk({ 키: "SK-000002", 이름: "견본", 단위: "㎡" }, { mode: "page" });
// 불러오기 미리 보기(저장 전 가져온 식)
out.memory = await openSk({ 이름: "가져온", 단위: "식", 가져온: { 파일: "x" } });
out.memory = await openSk({ 이름: "가져온", 단위: "식", 가져온: { 파일: "x" } }, { mode: "memory" });
// ③ 머리 띠 넷(견본 답) — 까닭 · M01 개정 · 빠진 줄 · 짝 잃음 + 머리 배지
skAnswer = () =>
@@ -328,12 +328,12 @@ async function openSk(doc, opt = {}) {
});
out.bands = await openSk(
{ 키: "SK-000003", 이름: "띠", 단위: "㎡", 바탕: { 로직: "GC001109" }, 바탕판: "v1" },
{ source: true },
{ mode: "page" },
);
skAnswer = () => {
throw new Error("서버 못 닿음");
};
out.bands_fail = await openSk({ 키: "SK-000004", 이름: "띠", 단위: "㎡" }, { source: true });
out.bands_fail = await openSk({ 키: "SK-000004", 이름: "띠", 단위: "㎡" }, { mode: "page" });
skAnswer = () => plainAns();
// ② 일위대가 표 줄 누름 — SK 참조 줄 · M01 로직 줄 · 셈 주입(프로젝트 사본) SK 줄
@@ -8,10 +8,6 @@
- 상세 = M01 상세 부품(M02 길) · 부품 상자만 · 마스터 이동 단추 = 등록 없으면 숨김
"""
import json
import re
import shutil
import subprocess
from decimal import Decimal
from pathlib import Path
@@ -24,7 +20,6 @@ from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은
ROOT = Path(__file__).resolve().parents[2]
M02 = ROOT / "M02_MasterTemplete"
MODEL = M02 / "logic" / "M02_Sangeun_Cover_Model.ts"
BASE = "GC000278"
@@ -32,163 +27,6 @@ def _text(p: Path) -> str:
return p.read_text(encoding="utf-8")
def _node(body: str) -> object:
born = _text(M02 / "logic" / "M02_Born_Tag.ts") # 740-2 — 모델이 쓰는 꼬리표 글(import 줄은 뺌)
model = re.sub(r"^import .*$", "", _text(MODEL), flags=re.M)
undo = re.sub(r"^import .*$", "", _text(M02 / "logic" / "M02_Sangeun_Undo.ts"), flags=re.M)
# 751-3 모델이 가져오는 B09 `rounddown`(import 줄을 빼므로 같은 식을 둠)
cut = "const rounddown = (v, p = 0) => { const s = 10 ** p; " + (
"const a = Math.floor(Math.abs(v) * s + 1e-7) / s; return v < 0 ? -a : a; };"
)
src = "\n".join((born, undo, cut, model, body))
out = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-e", src],
capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert out.returncode == 0, out.stderr
return json.loads(out.stdout)
SAMPLE = """
const line = (cid, 이름, 수량, 단가, 비목, 묶음) => ({ cid, 이름, 단위: "인", 수량, 단가,
금액: Object.values(비목).reduce((a, b) => a + b, 0), 비목, 묶음 });
const bare = { 기준: null, 짝잃음: [], 바탕판: "x",
정체: ["labor:A#0", "logic:G#0", "material:M#0", "pct:공구#0"],
줄: [line("labor:A#0", "석공", 0.1, 1000, { 노무비: 100 }, "인력"),
line("logic:G#0", "굴착기", 2, 50, { 노무비: 60, 재료비: 30, 경비: 10 }, "경비")],
재료: [{ 차례: 2, 이름: "모르타르", 수량: 0.5, 단가: 200, 금액: 100 }] };
"""
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
def test_고침_꼴():
body = (
SAMPLE
+ """
const doc = { 덮개: {}, 뺀줄: [],
더한줄: [{ 종류: "재료", 요소: "MT1", 비목: "재료비", 수량: 1 }] };
const ans = { ...bare, 정체: [...bare.정체, "add:#0"],
줄: [...bare.줄, line("add:#0", "더한 재료", 1, 300, { 재료비: 300 }, "재료")] };
const rows = rowsOf(ans, bare, doc);
const by = (cid) => rowsOf(ans, bare, doc).find((r) => r.cid === cid);
const out = {};
out.rows = rows.map((r) => [r.cid, r.묶음, r.apart, r.added, r.priceEdit]);
setLineCover(doc, by("labor:A#0"), { qty: 0.2 }, false);
out.qty = doc.덮개["labor:A#0"];
setLineCover(doc, by("labor:A#0"), { qty: 0.1 }, false); // 바탕 값과 같음 = 덮개 지움
out.qtyBack = doc.덮개["labor:A#0"] ?? null;
setLineCover(doc, by("labor:A#0"), { labor: 1200 }, false);
out.price = doc.덮개["labor:A#0"];
setLineCover(doc, by("labor:A#0"), null, false); // 고침 풂
out.unset = doc.덮개["labor:A#0"] ?? null;
setLineCover(doc, by("logic:G#0"), { labor: 60, material: 30, expense: 10 }, false);
out.split = doc.덮개["logic:G#0"];
setLineCover(doc, by("add:#0"), { qty: 3, material: 350 }, false);
out.added = doc.더한줄[0];
out.pick = [by("add:#0").apartPick, by("labor:A#0").apartPick];
setApart(doc, by("add:#0"), true);
out.apartOn = doc.더한줄[0].별도계상 ?? null;
setApart(doc, by("add:#0"), false);
out.apartOff = doc.더한줄[0].별도계상 ?? null;
const opened = { 덮개: {} };
setLineCover(opened, by("labor:A#0"), { qty: 0.15 }, true); // 바탕 품 0.1 → 배율 1.5
out.scale = opened.덮개["labor:A#0"];
setLineCover(opened, by("labor:A#0"), { qty: 0.1 }, true);
out.scaleBack = opened.덮개["labor:A#0"] ?? null;
dropLine(doc, by("labor:A#0"));
out.drop = [doc.뺀줄, doc.덮개["labor:A#0"] ?? null];
restoreLine(doc, "labor:A#0");
out.restore = doc.뺀줄;
dropLine(doc, by("add:#0"));
out.dropAdded = doc.더한줄.length;
const covered = { 덮개: { "labor:A#0": { qty: 0.3, 원값: { qty: 0.09, 단가: 1000 } } } };
out.revised = rowsOf(bare, bare, covered).find((r) => r.cid === "labor:A#0").revised;
// 공용 상세 줄 — 바탕 줄 그대로 · 뺀 줄 없음 · 더한줄 · 별도계상 빠진 줄 = 빈 칸 · 덧줄
const base = { 호표: [{ 종류: "인력", 요소: "A", 이름: "석공", 수량: "0.1*x" },
{ 종류: "로직", 요소: "로직(G)", 수량: "2" }, { 종류: "재료", 요소: "M", 수량: "0.5" }],
덧줄: [{ 이름: "공구손료", 식: "노무비 * 3 / 100" }] };
const doc2 = { 덮개: { "labor:A#0": { qty: 0.3, 원값: { qty: 0.1 } } }, 뺀줄: ["logic:G#0"],
더한줄: [{ 종류: "인력", 요소: "LB2", 이름: "보통인부", 비목: "노무비",
수량: 0.01, 단가: 500 }] };
const ans2 = { ...bare, 정체: ["labor:A#0", "material:M#0", "add:#0", "pct:공구#0"],
줄: [line("labor:A#0", "석공", 0.3, 1000, { 노무비: 300 }, "인력"),
line("add:#0", "보통인부", 0.01, 500, { 노무비: 5 }, "인력"),
{ ...line("pct:공구#0", "공구손료", 9.15, 1, { 경비: 9.15 }, "경비"), 율: 3 }] };
const v = hoView(ans2, bare, base, doc2);
out.view = [v.호표.map((x) => [x.종류, x.요소, x.수량, x.비목 ?? null]), v.덧줄, v.cids,
v.lines.map((l) => l?.cid ?? null), v.covers];
out.viewRef = hoView(ans2, bare, null, doc2).호표[0];
console.log(JSON.stringify(out));
"""
)
got = _node(body)
assert got["rows"] == [
["labor:A#0", "인력", False, None, True],
["logic:G#0", "경비", False, None, True],
["add:#0", "재료", False, 0, True],
["material:M#0", "재료", True, None, True],
]
assert got["qty"] == {"qty": 0.2, "원값": {"qty": 0.1, "단가": 1000}}
assert got["qtyBack"] is None
assert got["price"] == {"labor": 1200, "원값": {"qty": 0.1, "단가": 1000}}
assert got["unset"] is None
assert got["split"]["labor"] == 60 and got["split"]["material"] == 30
assert got["split"]["expense"] == 10
assert got["added"]["수량"] == 3 and got["added"]["단가"] == 350
# 더한 재료 줄만 별도계상 고름 · 켬 = 칸 true · 끔 = 칸 지움(기본 계 안)
assert got["pick"] == [True, False]
assert got["apartOn"] is True and got["apartOff"] is None
assert got["scale"]["배율"] == pytest.approx(1.5) and "qty" not in got["scale"]
assert got["scaleBack"] is None
assert got["drop"] == [["labor:A#0"], None]
assert got["restore"] == [] and got["dropAdded"] == 0
assert got["revised"] is True
ho, extra, cids, lines, covers = got["view"]
assert ho == [
["인력", "A", "0.1*x", None], # 바탕 줄 그대로(식)
["재료", "M", "0.5", None],
["인력", "LB2", "0.01", "노무비"], # 더한줄
]
assert extra == [{"이름": "공구손료", "식": "노무비 * 3 / 100"}]
assert cids == ["labor:A#0", "material:M#0", "add:#0", "pct:공구#0"]
assert lines == ["labor:A#0", None, "add:#0", "pct:공구#0"] # 별도계상 빠진 재료 = 빈 칸
assert covers == {"0": {"qty": 0.3}, "2": {"qty": 0.01, "labor": 500}}
assert got["viewRef"] == { # 참조 바탕 = 셈 줄로 지음
"종류": "인력", "요소": "", "이름": "석공", "단위": "인", "수량": "0.3", "비목": "노무비",
} # fmt: skip
def test_상세_부품_길_부품상자():
view = _text(M02 / "M02_MasterTemplete_Sangeun_View.ts")
detail = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
cover = _text(M02 / "M02_MasterTemplete_Sangeun_Cover.ts")
assert "mountSangeunDetail(host, doc," in view and "createEmpty" not in view
assert 'read: "/m02/logic-lib"' in detail and "setLogicApiPaths(LIB)" in detail
assert "buildLabDetail(editor" in detail and "cover: { ho }," in detail
assert "buildCalc" not in detail # 799-2 시험 계산 보기 걷음
assert (
"openSangeunLinePicker" not in detail and "openRateLine" not in detail
) # 840-1 [항목 추가] · [율 줄 추가] 걷음
assert "if (mine !== seq || !alive) return" in detail # 최신 응답만
# 724-1 — 단가산출 상세 = 공용 상세(Ho) · 고침 고리 = SK 덮개 · 옛 고침 표 걷음
assert "...buildHo(hoCtx)" in detail and 'scope: "m02",' in detail
assert "setLineCover(doc, r, c, opened());" in detail and "skCoverTable" not in detail
ho = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts")
assert "edit.more?.(e.idx, close)" in ho and '"EditedM02"' in ho
for s in (detail, cover, _text(MODEL)):
assert "<button" not in s and "<input" not in s and "<table" not in s
assert "document.createElement" not in s and "sessionStorage." not in s
lab = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Detail.ts")
assert "ctx.cover.ho" in lab and "cover?.est" not in lab
side = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_Side.ts")
modal = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Modal.ts")
assert "export const hasMasterJump" in side and "go.hidden = !hasMasterJump()" in modal
assert (
len(_text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab.ts").splitlines()) <= 637
) # 794-1 시트 이음 10 줄
def test_화면_문서_꼴_서버_저장_셈(world): # noqa: F811 — 가져온 fixture
"""화면 꼴(덮개 + 원값 곁 글 · 로직 줄 나눈 단가 · 더한줄 · 뺀줄) → 저장 · 셈 = 손셈."""
mine = world["personal"]
@@ -235,15 +73,3 @@ def test_화면_문서_꼴_서버_저장_셈(world): # noqa: F811 — 가져온
assert added["단가"] == pytest.approx(lines["labor:LB000002#0"]["단가"])
gap = sum(x["금액"] for x in got["줄"]) - got["기준"]["계"] # 751-3 비목마다 1 원 버림
assert -1e-6 <= gap < 3
def test_725_바탕_없으면_개정_안_뜸_새_SK_나무_다시_읽음_더한줄_단가_찾음():
"""725-3 바탕 없는 SK 는 이름 · 단위 따라 지문이 바뀌어도 M01 개정 아님 · 725-4 새 SK 뒤 나무 알림 ·
`prices` 에 없는 요소 = 키로 찾아 옴."""
detail = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
assert "!!(doc.바탕 && doc.바탕판 && ans?.바탕판 && doc.바탕판 !== ans.바탕판)" in detail
assert detail.count("const revised = revisedBase();") == 2
modal = _text(M02 / "M02_MasterTemplete_Labor_RowModal.ts")
assert "saveAsSk" not in modal # 808-1 옛 [단가산출로도 저장] 걷음 — 일위대가 줄은 저장 때 펼침
lab = _text(ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Modal.ts")
assert "lookup(element, element)" in lab and "Pill_NoValue" in lab
@@ -1,151 +0,0 @@
# ruff: noqa: F811 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀
"""일위대가 줄 [단가산출 보기] 모달(PLAN 717-3 · 724-1) — 임시 storage · 순수 함수는 Node 로.
화면 문서(`logic/M02_Sangeun_Cover_Model.lineDoc`) = 서버 `M02_Labor_Patch.as_doc` 꼴
(같은 고름 · 자재표시 cid) ·
모달 셈 길(`/sangeun/calc` = `calc_doc`) 값 = 일위대가 셈의 그 줄 값 · 고친 칸 = 덮개 칸 이름 ·
패치 정리 순수 함수 · `normalizeLabor` 가 줄 `패치` 를 지킴 ·
화면 이음(모달 = 줄 모드 SK 상세 · 공용 상세).
"""
import json
import shutil
import subprocess
from pathlib import Path
import pytest
from M01_MasterData import M01_MasterData_Store as m01
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Patch as patch
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Calc as calc
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
ROOT = Path(__file__).resolve().parents[2]
PCT = "GC001109" # 원/㎡ · 인력 둘 + 「노무비 * 3 / 100」
TWO_MATS = "GC000565" # 원/m · 재료 줄 둘
COVER = {"덮개": {"labor:LB000036#0": {"qty": 0.5}}}
MODEL = r"""
const fs = require("fs");
const path = require("path");
const root = process.argv[1];
const ts = require(path.join(root, "config", "node_modules", "typescript"));
const f = path.join(root, "M02_MasterTemplete", "logic", "M02_Sangeun_Cover_Model.ts");
const js = ts.transpileModule(fs.readFileSync(f, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
new Function("exports", "module", "require", js)(box.exports, box, () => ({}));
const m = box.exports;
const job = JSON.parse(fs.readFileSync(0, "utf8"));
const out = {};
for (const [k, [fn, ...args]] of Object.entries(job)) out[k] = m[fn](...args);
process.stdout.write(JSON.stringify(out));
"""
def _node(job: dict) -> dict:
node = shutil.which("node")
if not node:
pytest.skip("node 없음")
got = subprocess.run(
[node, "-e", MODEL, str(ROOT)],
input=json.dumps(job, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
)
assert got.returncode == 0, got.stderr
return json.loads(got.stdout)
def _whole():
return m01.loaded()[1]
def test_화면_문서_서버_as_doc_꼴():
"""고름 · 자재표시(호표 차례) → cid · 패치 · 참조 줄 = 서버 `as_doc` 와 같은 몸."""
import master_pick as mp
whole = _whole()
row = whole.logic(TWO_MATS)
item = row["호표"][2]
want = mp.search(whole, item["요소"], {}, item.get("단위"))[1]
drop = {"뺀줄": ["material:" + row["호표"][1]["이름"] + "#0"]}
one = {
"로직": TWO_MATS,
"입력값": {},
"고름": {"2": want},
"자재표시": {"2": {"별도계상": "직접계산"}},
}
ref = {"참조": {"층": "personal", "주인": None, "키": "SK-000001"}, "입력값": {}}
ids = sd.line_ids(row)
got = _node(
{
"logic": ["lineDoc", one, ids, drop],
"ref": ["lineDoc", ref, None, COVER],
"bare": ["lineDoc", one, None, None],
"needs": ["needsIds", one],
"needsRef": ["needsIds", ref],
}
)
assert got["logic"].pop("줄모드") is True and got["ref"].pop("줄모드") is True # 750-1
assert got["logic"] == patch.as_doc({**one, "패치": drop}, whole)
assert got["ref"] == patch.as_doc({**ref, "패치": COVER}, whole)
assert got["bare"]["고름"] == {} and got["bare"]["덮개"] == {}
assert got["needs"] is True and got["needsRef"] is False
def test_모달_셈_길_값_일위대가_줄_값(world):
"""모달 셈(`calc_doc` · 저장 안 함) 기준 = 일위대가 셈 그 줄 기준 · 고친 줄 덮개 칸 = qty · 정체 = 바탕 줄."""
whole = _whole()
line = {"로직": PCT, "입력값": {}, "수량": {"손": 1}}
doc = _node({"d": ["lineDoc", line, None, COVER]})["d"]
bare = _node({"d": ["lineDoc", line, None, None]})["d"]
with store.at(world["personal"]):
got = calc.calc_doc(doc)
was = calc.calc_doc(bare)
mine = labor.calc(labor.clean({"담은로직": [{**line, "패치": COVER}]}), {})["줄"][0]
plain = labor.calc(labor.clean({"담은로직": [line]}), {})["줄"][0]
assert got["기준"] == pytest.approx(mine["기준"])
assert was["기준"] == pytest.approx(plain["기준"])
assert got["기준"]["계"] != was["기준"]["계"] # 품 0.5 로 바뀜
assert was["정체"] == sd.line_ids(whole.logic(PCT))
cover = [x for x in got["줄"] if x["cid"] == "labor:LB000036#0"][0]
assert cover["덮개"] == ["qty"] and cover["수량"] == pytest.approx(0.5)
def test_패치_정리_순수_함수():
"""원값 뺌 · 빈 칸 뺌 · 다 비면 null(줄 칸 안 둠) — 덮개 고침 자체는 717-2b `setLineCover`."""
one = {"덮개": {"labor:LB1#0": {"qty": 0.5, "원값": {"qty": 0.2}}, "x:a#0": {"원값": {}}}}
got = _node(
{
"clean": ["cleanPatch", one],
"empty": ["cleanPatch", {"덮개": {}, "뺀줄": [], "더한줄": []}],
"none": ["cleanPatch", None],
"keep": ["cleanPatch", {"뺀줄": ["a:b#0"]}],
}
)
assert got["clean"] == {"덮개": {"labor:LB1#0": {"qty": 0.5}}} # 원값 = 서버 몫
assert got["empty"] is None and got["none"] is None
assert got["keep"] == {"뺀줄": ["a:b#0"]}
def test_normalizeLabor_줄_패치_지킴():
node = shutil.which("node")
if not node:
pytest.skip("node 없음")
doc = {"담은로직": [{"로직": PCT, "패치": COVER}, {"로직": TWO_MATS}]}
got = subprocess.run(
[node, str(ROOT / "resources/tester/helper_m02_labor_normalize.cjs")],
input=json.dumps({"doc": doc, "column": "c"}, ensure_ascii=False),
capture_output=True,
text=True,
encoding="utf-8",
)
assert got.returncode == 0, got.stderr
rows = json.loads(got.stdout)["담은로직"]
assert rows[0]["패치"] == COVER and "패치" not in rows[1]
-98
View File
@@ -1,98 +0,0 @@
"""722 M01 단가산출 상세 개편 지킴 시험 — 글 · 순수 함수(화면 · 서버 없음).
- 722-1 공용 단가산출 상세(`M01_MasterData_UI_LogicLab_Ho.ts`) — 하위 박스(서버 묶음) · 장비 한 줄 + 펼침 · 계산식 열 · 박스 옵션
- 722-2 그 자리 고침(`M01_MasterData_UI_LogicLab_Cover.ts`) — M01 = 시험 값(줄 사본) · 정본 · 캐시 안 바뀜
"""
import json
import shutil
import subprocess
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
M01 = ROOT / "M01_MasterData"
HO = M01 / "M01_MasterData_UI_LogicLab_Ho.ts"
COVER = M01 / "M01_MasterData_UI_LogicLab_Cover.ts"
def _text(p: Path) -> str:
return p.read_text(encoding="utf-8")
def _pure(p: Path) -> str:
s = _text(p)
return s[s.index("/* ── 순수 셈 ── */") : s.index("/* ── 순수 셈 끝 ── */")]
def _node(code: str):
out = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-e", code],
capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert out.returncode == 0, out.stderr
return json.loads(out.stdout)
def test_상세가_공용_부품을_씀():
detail = _text(M01 / "M01_MasterData_UI_LogicLab_Detail.ts")
assert (
"buildHo" not in detail and "trialEdit" not in detail
) # 840-1 M01 상세 보기 걷음 — M02 줄 모달만 씀
assert "...buildHo(hoCtx)" in _text(
ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts"
)
ho = _text(HO)
# 부품 상자만 — 표 · 카드 · 계산 줄 · 변수 칸(calc_sheet) · 입력 칩(텍스트 수식)
for part in (
"tableShell(",
"tableRow(",
"createCard(",
"varRow(",
"sheetFormula(",
):
assert part in ho, part
assert "inputChip(" not in ho # 748-3 줄마다 붙던 옵션 값 칩 걷음(위 옵션 칸이 대신)
for s in (ho, _text(COVER)):
assert 'el("table"' not in s and 'el("button"' not in s and 'el("input"' not in s
assert "document.createElement" not in s and "sessionStorage" not in s
assert "export function varRow(" in _text(ROOT / "A00_Common" / "calc_sheet.ts")
for p in (HO, COVER, M01 / "M01_MasterData_UI_LogicLab.ts"):
assert len(_text(p).splitlines()) <= (
637 if p.name == "M01_MasterData_UI_LogicLab.ts" else 700 # 794-1 시트 이음 10 줄
)
def test_시험_고침은_M01_에서_걷음():
lab = _text(M01 / "M01_MasterData_UI_LogicLab.ts")
assert (
"trial" not in lab and "drive" not in lab
) # 840-1 — 시험 값 · 구동 걷음(수식에서 값을 바꾸고 [되돌림])
cover = _text(COVER)
assert "export const trial" not in cover and "applyCovers" not in cover
assert "drafts" not in cover and "touch" not in cover and "/save" not in cover
modal = _text(M01 / "M01_MasterData_UI_LogicLab_Modal.ts")
assert "...(target.edit ? [target.edit(close, head)] : [])" in modal
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
def test_박스_묶기():
body = """
const e = (idx, bundle, merge, amount) => ({ idx, bundle, merge, amount });
const got = boxesOf([
e(0, "인력", false, 10), e(1, "경비", true, 100), e(1, "경비", true, 20), e(1, "경비", true, 30),
e(2, "하위", true, 5), e(2, "하위", true, null), e(3, "재료", false, null),
], ["인력", "재료", "경비"]).map((b) => ({ 묶음: b.묶음, 소계: b.소계,
줄: b.줄.map((r) => "몫" in r ? [r.idx, r.금액, r.몫.length] : r.idx) }));
console.log(JSON.stringify(got));
"""
got = _node(_pure(HO) + "\n" + body)
assert [b["묶음"] for b in got] == ["인력", "재료", "경비", "하위"]
assert got[0] == {"묶음": "인력", "소계": 10, "줄": [0]}
assert got[1] == {"묶음": "재료", "소계": 0, "줄": [3]}
assert got[2] == {"묶음": "경비", "소계": 150, "줄": [[1, 150, 3]]} # 장비 한 줄 = 몫 셋 합
assert got[3]["줄"] == [[2, 5, 2]]
empty = _node(_pure(HO) + '\nconsole.log(JSON.stringify(boxesOf([], ["인력"])))')
assert empty == [{"묶음": "인력", "줄": [], "소계": 0}]
-12
View File
@@ -47,15 +47,3 @@ def test_화면_서고_상세는_일위대가표만():
for label in ('tc("Up")', 'tc("Down")', 't("Alias")', 'tc("Remove")'):
assert label in table # 우클릭 메뉴
assert "fixed: (fx: LaborFixed, name: string)" in table # 721-2 고정 줄 이음
def test_화면_줄_모달은_SK_상세_줄_모드_적용은_덮개와_옵션():
modal, sk = (
_src("M02_MasterTemplete_Labor_RowModal.ts"),
_src("M02_MasterTemplete_Labor_RowSk.ts"),
)
detail = _src("M02_MasterTemplete_Sangeun_Detail.ts")
assert "mountSangeunDetail(box, doc," in sk and "getValues: () => ({ ...values })" in detail
assert "if (got.patch) row.패치 = got.patch;" in modal and "setValues(got.values);" in modal
assert "AlsoSk" not in modal # 808-1 [단가산출로도 저장] 걷음 · 811-1 M01 기초 = SK 사본 참조
assert "openRowSangeun" not in modal # 717-3 두 보기 갈음
@@ -105,11 +105,3 @@ def test_no_base_common_option_seoul(world): # noqa: F811
assert got["기준"], {k: v for k, v in got.items() if k != "줄"}
assert got["기준"]["계"] == pytest.approx(_m01(GF, {"지역": "서울", "보정작업": "해당 없음"}))
assert float(got["기준"]["계"]) == 5660 # 751-3 끝수 · 840-5 굴착기 조종원 35,412 → 59,020/시간
def test_screen_no_base_inputs_and_gap_dash():
"""725-6 화면 — 바탕 없음 = 더한줄 로직 입력 모음 칸 · 못 셈 줄 금액 「—」 + 까닭 풍선."""
ts = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts").read_text("utf-8")
assert "입력: extra" in ts and "syncExtra" in ts and "void recalc(); // 750-2" in ts
ho = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text("utf-8")
assert "e.line?.까닭 ? gapCell" in ho and "title: why" in ho
-51
View File
@@ -202,54 +202,3 @@ def test_727_3_옵션_저장_일위대가_그_옵션(world): # noqa: F811
assert two["입력값"] == rock
got = _run(world["personal"], two)
assert _line(got, "add:#0")["금액"] == pytest.approx(_m01(GF, rock), rel=1e-9)
def _model(ans, doc, script):
body = (
f"\nconst ans = {json.dumps(ans, ensure_ascii=False)};"
f"\nconst doc = {json.dumps(doc, ensure_ascii=False)};\n{script}"
)
return _node(
[
"M02_MasterTemplete/logic/M02_Born_Tag.ts",
"M02_MasterTemplete/logic/M02_Sangeun_Undo.ts",
"M02_MasterTemplete/logic/M02_Sangeun_Cover_Model.ts",
],
body,
)
def test_727_2_화면_꼴_세부_줄_고침(world): # noqa: F811
doc = _sk(world["personal"], 바탕={"로직": GF}, 더한줄=[{**SECOND, "수량": 2}])
ans = _run(world["personal"], doc)
got = _model(
ans,
doc,
"""
const rows = rowsOf(ans, null, doc);
const view = hoView(ans, null, null, doc);
const sub = rows.find((r) => r.cid === "add:#0/labor:LB000036#0");
setLineCover(doc, sub, { qty: 0.072 }, false);
const covered = JSON.parse(JSON.stringify(doc.더한줄[0]));
dropLine(doc, rows.find((r) => r.cid === "add:#0/pct:공구손료 및 경장비#0"));
const dropped = [...doc.더한줄[0].뺀줄];
restoreLine(doc, "add:#0/pct:공구손료 및 경장비#0");
const one = { ...doc, 더한줄: [] };
console.log(JSON.stringify({
cids: rows.map((r) => r.cid), boxes: rows.map((r) => r.묶음), sub, covered, dropped,
back: doc.더한줄[0].뺀줄 ?? null, tags: view.호표.map((x) => x.꼬리표 ?? ""),
extraTags: view.덧줄.map((x) => x.꼬리표 ?? ""), viewCids: view.cids,
single: [...tagsOf(ans, one).values()],
}));
""",
)
assert "add:#0" not in got["cids"] and "add:#0/labor:LB000036#0" in got["cids"]
assert got["sub"]["sub"] == {"k": 0, "cid": "labor:LB000036#0", "scale": 2}
assert got["sub"]["수량"] == pytest.approx(0.036) and got["sub"]["묶음"] == "인력"
assert got["covered"]["덮개"]["labor:LB000036#0"]["qty"] == pytest.approx(
0.072
) # 화면 품 그대로(M01 원문 몫 · 748-0 — 수량 2 로 안 나눔)
assert got["covered"]["덮개"]["labor:LB000036#0"]["원값"] == {"qty": 0.018, "단가": 233250}
assert got["dropped"] == DROP and got["back"] is None
assert got["tags"] == ["9-12-1", "9-12-1", "3-2-1", "3-2-1"] # 바탕 둘 · 둘째 기초 인력 둘
assert got["extraTags"] == ["3-2-1"] and got["single"] == [] # 기초 하나면 꼬리표 없음
+1 -20
View File
@@ -4,8 +4,6 @@
from __future__ import annotations
import json
import subprocess
import sys
from decimal import Decimal
from pathlib import Path
@@ -91,7 +89,7 @@ def test_둘째_기초_수량_처음값_배(whole):
src = (ROOT / "M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts").read_text(
encoding="utf-8"
)
assert "addBase(" not in src and "baseUnitOf(" in src # 840-1 [항목 추가] 걷음
assert "addBase(" not in src # 840-1 [항목 추가] 걷음
def test_돈_아닌_기초_고르기_창에서_뺌(whole):
@@ -107,20 +105,3 @@ def test_돈_아닌_기초_고르기_창에서_뺌(whole):
assert len(money) == 65 # 지금 M01(785-7 · 옛 21 = M01 기초 늘기 전)
src = (ROOT / "M02_MasterTemplete/M02_MasterTemplete_Find_Pick.ts").read_text(encoding="utf-8")
assert '!logic.결과단위.trim().startsWith("원")' in src
def test_고침_꼴_화면배_되돌림():
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_728_2_cover_unit.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert proc.returncode == 0, proc.stderr
out = json.loads(proc.stdout)
assert out["was"]["qty"] == pytest.approx(0.2) # 바탕 값 = 문서 몫(100본)
assert out["cover"]["labor:LB000101#0"]["qty"] == pytest.approx(0.3)
assert out["added"] == pytest.approx(60)
assert out["shown"]["0"]["qty"] == pytest.approx(0.003) # 다시 그리면 화면 몫
assert out["shown"]["1"]["qty"] == pytest.approx(0.6)
@@ -7,7 +7,6 @@ ROOT = Path(__file__).resolve().parents[2]
M01 = ROOT / "M01_MasterData"
SHEET_CSS = (ROOT / "A00_Common" / "calc_sheet.css").read_text(encoding="utf-8")
STYLE = (M01 / "M01_MasterData_UI_LogicLab_Style.css").read_text(encoding="utf-8")
HO = (M01 / "M01_MasterData_UI_LogicLab_Ho.ts").read_text(encoding="utf-8")
def test_옵션_격자_폭_따라_6_4_3_2_1():
@@ -27,10 +26,4 @@ def test_합계_한_줄_바닥_고정():
assert "overflow: clip" in STYLE # 메인 칸이 굴림 칸이면 바닥에 안 붙음
foot_ts = (M01 / "M01_MasterData_UI_LogicLab_Foot.ts").read_text(encoding="utf-8")
assert 'className: "m01lab__foot"' in foot_ts # 748-3 두 보기가 같은 바닥 줄 부품
assert "buildFoot(sums, calculated, total)" in HO
assert 'data-cols="3"' in STYLE and ".m01lab__ho-box + .m01lab__ho-box" in STYLE
def test_공통_옵션은_모든_박스에_같이():
assert "optionRows([...usesOf(b), ...common], ctx)" in HO
assert "commonCard(" in HO and "boxes.length ||" in HO # 박스 없을 때만 따로 카드
assert 'data-cols="3"' in STYLE
@@ -9,17 +9,12 @@ ROOT = Path(__file__).resolve().parents[2]
M02 = ROOT / "M02_MasterTemplete"
MAIN = (M02 / "M02_MasterTemplete_UI_Main.ts").read_text(encoding="utf-8")
ACTIONS = (M02 / "M02_MasterTemplete_Main_Actions.ts").read_text(encoding="utf-8")
HO = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text(encoding="utf-8")
COVER = (M02 / "logic" / "M02_Sangeun_Cover_Model.ts").read_text(encoding="utf-8")
def _born(expr: str):
"""순수 TS(`logic/M02_Born_Tag.ts`)를 Node 로 돌려 JSON 답을 받음."""
uri = (M02 / "logic" / "M02_Born_Tag.ts").as_uri()
code = (
f"import {{ bornText, bornOfCid, bornNote }} from '{uri}';"
f"console.log(JSON.stringify({expr}));"
)
code = f"import {{ bornText, bornNote }} from '{uri}';console.log(JSON.stringify({expr}));"
out = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", "--experimental-strip-types", "--no-warnings", "--input-type=module", "-e", code],
capture_output=True,
@@ -53,14 +48,6 @@ def test_꼬리표_없으면_빈칸_기초번호_뒤에_붙음():
assert got.split("\n")[0] == "A1 · 본뜬 SK-000012"
def test_줄_열쇠에서_그_더한줄_출처를_찾음():
adds = json.dumps([{}, {"본뜬": BORN}], ensure_ascii=False)
assert _born(f"bornOfCid('add:#1', {adds})").startswith("본뜬 SK-000012")
assert _born(f"bornOfCid('add:#1/add:#0', {adds})").startswith("본뜬 SK-000012") # 펼침 세부
assert _born(f"bornOfCid('add:#0', {adds})") == ""
assert _born(f"bornOfCid('hopyo:X#3', {adds})") == ""
def test_머리_단추_차례_초기화_삭제_저장():
kids = MAIN[MAIN.index('className: "m02-main__head"') :]
kids = kids[: kids.index("]")]
@@ -83,11 +70,6 @@ def test_초기화는_미리보기_뒤_물음_뒤_씀():
assert "옵션 · 기본정보는 그대로" in ACTIONS
def test_공용_꼬리표_칸은_첫줄만_보이고_풍선에_나머지():
assert 'text.split("\\n")' in HO
assert "bornOfCid(" in COVER
def test_격자_비고_칸은_첫줄만():
assert _born(f"bornNote({json.dumps(BORN, ensure_ascii=False)})") == "본뜬 SK-000012"
assert _born("bornNote(null)") == ""
-40
View File
@@ -1,40 +0,0 @@
"""748-0 지킴 — SK 둘째 기초 세부 품 = M01 원문(머리 수량 안 곱함) · 고침 꼴 · 빼기 기억 · 되살림 · 수량 처음값.
(서버 짝 = `test_744_1_sk_detail_undo.py`)"""
from __future__ import annotations
import json
import subprocess
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
def test_세부_원문_품_고침_빼기_되살림_처음값():
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_748_0_sk_undo.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert proc.returncode == 0, proc.stderr
out = json.loads(proc.stdout)
assert float(out["shownQty"]) == pytest.approx(0.871) # 곱하지 않은 M01 원문
assert out["lineQty"] == pytest.approx(0.871)
assert out["lineAmount"] == pytest.approx(871) # 상자 몫은 그대로
assert out["t"] == 1
assert out["cover"]["labor:LB000101#0"]["qty"] == pytest.approx(0.9) # 머리 수량 안 나눔
assert out["coverShown"] == pytest.approx(0.9) # 다시 그려도 같음
assert out["manQty"] == 5 and out["manBack"] == 2 # [되돌림] = 넣을 때 수량
drop = out["afterDrop"]
assert drop["adds"] == 1 and drop["gone"][0]["차례"] == 0
assert drop["pick"] == {"add:#0": "MT1"} # 뒤 더한줄 열쇠 당김
assert out["goneRows"][0]["cid"] == "gone:0"
back = out["afterBack"]
assert back["adds"] == ["LB000002", "GF000316"] and back["gone"] is None
assert back["pick"] == {"add:#1": "MT1"} # 되살림 = 밂
assert out["baseGone"] == {"adds": 1, "name": "둘째 기초", "pick": {}}
assert out["baseBack"] == ["LB000002", "GF000316"]
@@ -10,84 +10,8 @@ def _ts(rel: str) -> str:
return (ROOT / rel).read_text("utf-8")
def test_detail_uses_only_sk_answer():
ts = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
assert "text = got.글" in ts and "answer: async" not in ts and "buildCalc" not in ts
assert "onText" not in ts and "onLines" not in ts # 바탕 `/calc` · `/text` 부름 걷음
assert "dropText" not in ts and "baseCovers" not in ts and "applyCovers" not in ts
assert "calcSangeun(scope, plain, values, false)" in ts # 바탕 원값 셈 = 보기 덧칸 없이
assert "doc.고름 = " in ts and "pickMat" in ts # 재료 고름 = SK 문서 고름
def test_text_lines_joined_by_cid():
ho = _ts("M01_MasterData/M01_MasterData_UI_LogicLab_Ho.ts")
assert "ctx.cids && line.cid" in ho and "pickMat" in ho
api = _ts("M01_MasterData/M01_MasterData_UI_Logic_Api.ts")
assert "cid?: string" in api and "나눔?: number" in api
def test_calc_drive_is_screenless_and_m02_has_no_calc_hook():
ts = _ts("M01_MasterData/M01_MasterData_UI_Logic_Calc.ts")
assert "ctx.answer" not in ts and "CalcShown" not in ts # 799-2 M02 시험 계산 길 걷음
drive = _ts("M01_MasterData/M01_MasterData_UI_Logic_Drive.ts")
assert "runCalc(body)" in drive and "document." not in drive # 셈 구동 = 화면 없이
def test_752_1_source_panel_only_on_sangeun_screen():
"""752-1 원문 패널 — 단가산출 화면만 켬 · 일위대가 줄 모달 안 상세는 끔 · 기초마다 탭 · 좁은 폭 접힘."""
side = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Side.ts")
assert "/m02/logic-lib/source" in side and "createSidePanels" in side
assert "OPEN_FROM" in side and "createSegment" in side
assert "source: true" in _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_View.ts")
assert "source" not in _ts("M02_MasterTemplete/M02_MasterTemplete_Labor_RowSk.ts")
detail = _ts("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
assert "opt.source ? createSangeunSide()" in detail and "side?.set(" in detail
def test_753_2_option_off_flag_reaches_sheet_and_views():
"""753-2 옵션으로 빠진 줄 — SK 줄 `옵션꺼짐` → 표 줄 `off` → 계산서 줄 `옵션꺼짐`(공용 계산서 · 상세 ·
텍스트 수식 · 시험 계산이 안 그림) · 소계 · 금액은 그대로."""
import json
import re
import shutil
import subprocess
import pytest
if shutil.which("node") is None:
pytest.skip("node 가 없음")
m02 = ROOT / "M02_MasterTemplete"
strip = lambda p: re.sub(r"^import .*$", "", p.read_text("utf-8"), flags=re.M) # noqa: E731
src = "\n".join(
[
strip(m02 / "logic" / "M02_Born_Tag.ts"),
strip(m02 / "logic" / "M02_Sangeun_Undo.ts"),
# 751-3 모델이 가져오는 B09 `rounddown`(import 줄을 빼므로 같은 식을 둠)
"const rounddown = (v, p = 0) => { const s = 10 ** p; "
"const a = Math.floor(Math.abs(v) * s + 1e-7) / s; return v < 0 ? -a : a; };",
strip(m02 / "logic" / "M02_Sangeun_Cover_Model.ts"),
"""
const line = (cid, 이름, 수량, 금액, 꺼짐) => ({ cid, 이름, 단위: "개", 수량, 단가: 100, 금액,
비목: { 재료비: 금액 }, 묶음: "재료", ...(꺼짐 ? { 옵션꺼짐: true } : {}) });
const ans = { 기준: null, 짝잃음: [], 바탕판: "x", 정체: ["material:A#0", "material:B#0"],
줄: [line("material:A#0", "폼타이 12.7", 0, 0, true), line("material:B#0", "합판", 1, 100, false)] };
const rows = rowsOf(ans, null, {});
console.log(JSON.stringify({ off: rows.map((r) => r.off) }));
""",
]
)
out = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-e", src],
capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert out.returncode == 0, out.stderr
got = json.loads(out.stdout)
assert got["off"] == [True, False]
sheet = (ROOT / "A00_Common" / "calc_sheet.ts").read_text("utf-8")
assert "b.줄.filter(shown)" in sheet and "g.줄.filter(shown)" in sheet
ho = (ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts").read_text("utf-8")
assert "옵션꺼짐" in ho
assert "옵션꺼짐" in (ROOT / "M01_MasterData" / "M01_MasterData_UI_Logic_Calc.ts").read_text(
"utf-8"
)
-21
View File
@@ -350,24 +350,3 @@ def test_겹침_율_열쇠_새_차례():
# ── 화면 — 더한줄 지움 · 되살림 때 율 기준 열쇠 옮김(`logic/M02_Sangeun_Undo.ts`) ──────────
def test_화면_더한줄_지움_되살림_율_열쇠():
code = IMPORTS.sub(
"", (ROOT / "M02_MasterTemplete/logic/M02_Sangeun_Undo.ts").read_text("utf-8")
)
doc = _doc([LABOR[0], LABOR[1], _rate(["add:#1@노무비", "add:#0", "labor:LB000038#0"])])
body = (
f"\nconst doc = {json.dumps(doc, ensure_ascii=False)};"
"\nconst key = () => doc.더한줄.at(-1).고정.비율.기준;"
"\nforgetAdd(doc, 0, ''); const a = key(); reviveAdd(doc, 0);"
"\nconsole.log(JSON.stringify([a, key()]));"
)
got = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-e", code + body],
capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert got.returncode == 0, got.stderr
assert json.loads(got.stdout) == [
["add:#0@노무비", "labor:LB000038#0"], # 지운 줄 열쇠 버림 · 뒤 줄 당김(비목 꼬리 그대로)
["add:#1@노무비", "labor:LB000038#0"], # 되살림 = 뒤 줄 밂
]
@@ -129,4 +129,3 @@ def test_screen_same_part_first_tab():
tabs = (root / "M02_MasterTemplete_Sangeun_Tabs.ts").read_text(encoding="utf-8")
# 799-2 · 836-3 — 시트 · 인력·재료·경비 · 시험 계산 · 텍스트 수식 · 보기 고르기(단가산출 상세 탭) 걷음
assert not re.findall(r'\{ value: "(\w+)", label: ', tabs) and "createSegment" not in tabs
assert "show(true);" in tabs
@@ -8,13 +8,9 @@
from __future__ import annotations
import json
import shutil
import subprocess
from decimal import Decimal as D
from pathlib import Path
import pytest
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Sangeun_Imported as imp
@@ -22,7 +18,6 @@ from resources.tester.test_795_1_sk_copy import _calc, _doc, _imported_row
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 같은 임시 층
ROOT = Path(__file__).resolve().parents[2]
HO = ROOT / "M01_MasterData" / "M01_MasterData_UI_LogicLab_Ho.ts"
COSTS = ("노무비", "재료비", "경비")
@@ -65,31 +60,3 @@ def test_plain_sample_has_no_tag(world):
assert not any("합밖" in x for x in ans["줄"])
kept = _sum(ans["줄"], True)
assert all(int(kept[k]) == int(D(str(ans["기준"][k]))) for k in COSTS)
@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음")
def test_box_subtotal_skips_outside():
src = HO.read_text(encoding="utf-8")
pure = src[src.index("/* ── 순수 셈 ── */") : src.index("/* ── 순수 셈 끝 ── */")]
body = """
const e = (idx, bundle, amount, out) => ({ idx, bundle, merge: false, amount, out });
const got = boxesOf([e(0, "인력", 10, false), e(1, "인력", 7, true), e(2, "재료", 5)], ["경비"]);
console.log(JSON.stringify(got.map((b) => [b.묶음, b.소계, b.줄.length])));
"""
run = subprocess.run(
["node", "--experimental-strip-types", "--no-warnings",
"--input-type=module-typescript", "-e", pure + body],
capture_output=True, text=True, encoding="utf-8", timeout=60,
) # fmt: skip
assert run.returncode == 0, run.stderr
assert json.loads(run.stdout) == [["인력", 10, 2], ["재료", 5, 1], ["경비", 0, 0]] # 줄은 보임
def test_screen_wiring():
src = HO.read_text(encoding="utf-8")
assert src.count("out: !!line?.합밖,") == 2 # 호표 줄 · 덧줄
assert "e.group === g && !e.out" in src # 맨 아래 합계
assert 'createBadge(th("Out")' in src and len(src.splitlines()) <= 700
assert "합밖?: boolean" in (
ROOT / "M01_MasterData" / "M01_MasterData_UI_Logic_Api.ts"
).read_text(encoding="utf-8")
+1 -1
View File
@@ -78,7 +78,7 @@ def test_셈_구동은_화면_없이_상세는_구동만():
) # 로직 복사 화면이 쓰는 시험 계산 칸 — 구동은 공용
assert "driveRun(ctx)" in calc and "runCalc" not in calc
m02 = _text(M02 / "M02_MasterTemplete_Sangeun_Detail.ts")
assert "buildCalc" not in m02 and "calcHost" not in m02 and "createSangeunTabs(editor" in m02
assert "buildCalc" not in m02 and "calcHost" not in m02
def test_파일_700줄_안():
@@ -218,7 +218,6 @@ def test_M02_수식탭_M01과_같은_단추_저장_한_번() -> None:
tabs = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts")
assert "page: opt.page," in tabs and "save: () => stack.save()," in tabs
detail = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts")
assert "page: opt.source ? () => report() : undefined," in detail
assert "JSON.stringify(doc) !== saved || tabs.dirty()" in detail # 고침 알림 = 기본 + 수식
assert (
"addButton" not in detail and "rateButton" not in detail
@@ -343,5 +342,3 @@ def test_808_1_수량_칸_식_글_꼬리표_글꼴_머리():
screen = _src("A00_Common/line_stack_screen.ts")
assert "opt.tools?.replaceChildren(...tools);" in screen
assert "children: opt.tools ? [] : tools" in screen
tabs = _src("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts")
assert "stack.root.hidden = tools.hidden = !doc;" in tabs
+2 -8
View File
@@ -56,7 +56,7 @@ def test_단가산출_줄은_SK_문서_모달_저장은_그_SK():
r'saveTemplate\(\s*layer,\s*"sangeun",\s*opt\.ref\.키', modal
) # 저장 = 그 SK 문서
assert (
"mountSangeunDetail(host, doc," in modal and "source: true" in modal
"mountSangeunDetail(host, doc," in modal and 'mode: "page"' in modal
) # 수식 탭 부품 그대로
assert "await handle.flush();" in modal # 수식 저장 먼저 → 문서 저장
assert "if (!opt.readOnly) head.append(ok);" in modal # 읽기만 = [저장] 없음
@@ -130,13 +130,7 @@ def test_808_1_모달_머리_일원화():
row = _src("M02_MasterTemplete_Labor_RowModal.ts")
for gone in ("AlsoSk", "createCheckbox", "openLaborInput", "saveAsSk", "Labor_Option"):
assert gone not in row, gone
assert "actions: row.참조 ? [slot, ...tools] : tools," in row and 't("FromSk")' in row
assert "slot: o.slot," in _src("M02_MasterTemplete_Labor_RowSk.ts")
assert 't("FromSk")' in row
detail = _src("M02_MasterTemplete_Sangeun_Detail.ts")
assert "...(opt.slot ? [] : [" in detail # 머리 칸 있으면 머리 줄 없음
assert "children: [tabs.tools]" in detail and "tabs.picker" not in detail
assert r"/^SK-(?!0{6})\d{6}$/" in detail
tabs = _src("M02_MasterTemplete_Sangeun_Tabs.ts")
assert (
"const doc = !!k || !!opt.page || !!opt.memory?.();" in tabs
) # 836-3 · 836-5 문서 없는 줄 = 상세 몸만
+1 -8
View File
@@ -61,13 +61,6 @@ def test_screen_memory_doc_stack_view() -> None:
tabs = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Tabs.ts").read_text(
encoding="utf-8"
)
assert (
"const doc = !!k || !!opt.page || !!opt.memory?.();" in tabs
and "memory: opt.memory," in tabs
)
detail = (ROOT / "M02_MasterTemplete" / "M02_MasterTemplete_Sangeun_Detail.ts").read_text(
encoding="utf-8"
)
assert "doc.가져온 &&" in detail and "memory: () =>" in detail
assert "memory: opt.memory," in tabs
router = (ROOT / "M02_MasterTemplete" / "M02_Doc_Router.py").read_text(encoding="utf-8")
assert '"/layers/{layer}/sangeun/-/doc/read"' in router and "write=body.본 is None" in router
+12 -15
View File
@@ -31,35 +31,32 @@ def _run() -> dict:
def test_sk_page_open_calls_and_hidden_body() -> None:
got = _run()
# 바탕 있는 SK = 셈 두 번(바탕 원값 bare) · 바탕 없음 = 한 번 · 상세 몸 DOM 둘(덮개 그릇 · 호표) 숨김
assert got["page_base"]["calc"] == 2
assert got["page_nobase"]["calc"] == 1
# 856-1 — 셈 한 번(머리 띠용 · 바탕 원값 bare 셈 걷음) · 숨은 상세 몸 DOM 0 · 줄 쌓기 한 번 그림
for k in ("page_base", "page_nobase", "memory"):
assert got[k]["body"] == 2, k
assert got[k]["bodyShown"] == 0, k
assert got[k]["calc"] == 1, k
assert got[k]["body"] == 0, k
assert got[k]["stack"]["shown"] is True, k
assert {d["key"] for d in got["page_base"]["stack"]["draws"]} == {"SK-000001"}
assert got["page_base"]["stack"]["draws"] == [{"key": "SK-000001", "memory": False}]
# 불러오기 미리 보기(저장 전 가져온 식) = 빈 키 + 문서째
assert all(d == {"key": "", "memory": True} for d in got["memory"]["stack"]["draws"])
assert got["memory"]["calc"] == 1
assert got["memory"]["stack"]["draws"] == [{"key": "", "memory": True}]
def test_labor_row_click() -> None:
sk, logic = _run()["labor"]
# 단가산출 참조 줄 = 그 SK 문서 모달 · 줄 쌓기가 그 키로 보임 · 몸 안 보임
# 단가산출 참조 줄 = 그 SK 문서 모달 · 줄 쌓기가 그 키로 보임
assert sk["skModal"] == 1 and sk["stack"]["shown"] is True
assert set(sk["stack"]["draws"]) == {"SK-000010"} and sk["body"] == 0
# M01 로직 줄 = 옛 줄 모달 — 줄 쌓기 숨김 · 상세 몸 보임 · 안내 띠 하나 · 셈 둘(정체 + 상세)
assert logic["skModal"] == 0 and logic["stack"]["shown"] is False
assert logic["body"] == 1 and logic["banners"] == ["info"] and logic["calc"] == 2
assert sk["stack"]["draws"] == ["SK-000010"] and sk["calc"] == 1
# M01 로직 줄 = 줄 모달(안내 한 줄) · 상세 몸 · 줄 쌓기 · 셈 없음(856-1)
assert logic["skModal"] == 0 and logic["stack"] is None
assert logic["body"] == 0 and logic["banners"] == ["info"] and logic["calc"] == 0
def test_labor_row_click_inject() -> None:
sk, logic = _run()["labor_inject"]
# 셈 주입(프로젝트 사본) = 옛 줄 모달 · 상세 없음 · 안내 띠 없음 · 셈 없음
# 셈 주입(프로젝트 사본) = 줄 모달 · 안내 한 줄(856-3 까지) · 셈 없음
for row in (sk, logic):
assert row["modal"] and row["stack"] is None
assert row["body"] == 0 and row["banners"] == [] and row["calc"] == 0
assert row["body"] == 0 and row["banners"] == ["info"] and row["calc"] == 0
def test_head_bands_four() -> None: