Merge remote-tracking branch 'origin/dev' into sub_desktop_1

This commit is contained in:
2026-10-10 11:57:59 +09:00
89 changed files with 2859 additions and 334 deletions
@@ -3333,6 +3333,8 @@
"inlet.before": "기준측점 전 (m)",
"inlet.after": "기준측점 후 (m)",
"inlet.animal": "동물이동형",
"inlet.animal=true": "유",
"inlet.animal=false": "무",
"outlet.structure": "구조",
"outlet.structure=기슭막이": "흙막이",
"outlet.form": "형태",
@@ -57,6 +57,7 @@ const { taubin } = loadTs(B05("B05_Profile_UI_Corridor_Loft_Grid"));
const { TerrainBandSplit } = loadTs(B05("B05_Profile_UI_Corridor_Split"));
const { TerrainHeightIndex } = loadTs(B05("B05_Profile_UI_Corridor_Terrain"));
const PSLG = loadTs(B05("B05_Profile_UI_Corridor_Tin_Pslg"));
const { SEAM_M } = loadTs(B05("B05_Profile_UI_Corridor_Tin"));
const HALF = 3;
const ROAD_Z = 100;
@@ -257,7 +258,7 @@ function gapEdges(tris, out, original) {
return { gaps, maxGapLen };
}
/** 공사 밖(설계 구역 · 구멍 밖 · 둘레에서 1 mm 넘게 떨어진) 원래 정점 중 결과 망에서 사라진 수. */
/** 공사 밖(설계 구역 · 구멍 밖 · 둘레에서 SEAM_M 넘게 떨어진) 원래 정점 중 결과 망에서 사라진 수. */
function lostVertices(tris, before, out) {
const region = new PSLG.LoopIndex([out.design.outer, ...out.design.holes]);
const border = new PSLG.SegGrid(2);
@@ -274,7 +275,7 @@ function lostVertices(tris, before, out) {
for (let v = 0; v < before.length / 3; v += 1) {
const x = before[v * 3];
const z = before[v * 3 + 2];
if (region.contains(x, z) || border.passesNear(x, z, 1e-3)) continue;
if (region.contains(x, z) || border.passesNear(x, z, SEAM_M)) continue;
if (!present.has(key(x, before[v * 3 + 1], z))) lost += 1;
}
return lost;
@@ -450,6 +451,8 @@ function daylightPoints(out, bounds) {
let sectionErr = 0;
for (const side of [1, -1]) {
for (let s = 0.05; s <= 12; s += 0.05) {
// 비탈 끝(s 9) 바깥 이음 띠(SEAM_M + 격자 0.5 m)는 지형 굴곡을 긴 삼각형으로 펴므로 뺀다(176-1).
if (s > 9 && s < 9 + SEAM_M + 0.5) continue;
const z = tin(0, -side * (HALF + s)); // 씬 x = 20 − 20
if (z === null) continue;
sectionErr = Math.max(sectionErr, Math.abs(z + 100 - Math.max(ROAD_Z - s / 1.5, 94)));
@@ -162,4 +162,30 @@ out.notSheet = {
values: inputs().map((n) => n.value),
};
// 180-2 표 배율 칸 — 배치 칸 줄 뒤 · 0.5~2.0 · step 0.1 · [배율 적용]
const scales = [];
const toastStart = toasts.length;
slot.replaceChildren(
buildCrossLayoutControls([4, 4], null, () => {}, {
scale: { value: 1, onApply: (value) => scales.push(value) },
}),
);
const scaleInput = inputs()[2];
out.scale = {
labels: byClass(slot, "ui-field__label").map((n) => n.textContent),
input: {
value: scaleInput.value,
min: scaleInput.attrs.min,
max: scaleInput.attrs.max,
step: scaleInput.attrs.step,
},
buttons: buttons().map((n) => n.textContent),
};
scaleInput.value = "1.5";
buttons()[2].click();
scaleInput.value = "2.5";
buttons()[2].click();
out.scale.applied = scales;
out.scale.toasts = toasts.slice(toastStart).map((t) => t[0]);
process.stdout.write(JSON.stringify(out));
+20 -5
View File
@@ -202,6 +202,13 @@ const view = {
profile.showCard(CARDS.find((card) => card.station_id === this.selected) ?? null);
if (this.selected !== previous) this.listener(this.selected);
},
revealed: null,
revealStation(id) {
// 노면공 목록 고름 = 카드 하나 안 고름 · 리스너 없이 풂 · 스크롤만(177-4 · Section_View `revealStation`)
this.selected = null;
profile.showCard(null);
this.revealed = id;
},
focusStation(id) {
if (id === null) this.selected = null;
else if (this.selected !== id) this.selectStation(id);
@@ -214,11 +221,12 @@ const view = {
};
let wallSelecting = false;
const focusStationAt = (at) => {
const focusStationAt = (at, revealOnly = false) => {
const nearest = CARDS.reduce((best, card) =>
Math.abs(card.chainage_m - at) < Math.abs(best.chainage_m - at) ? card : best,
);
view.focusStation(nearest.station_id);
if (revealOnly) view.revealStation(nearest.station_id);
else view.focusStation(nearest.station_id);
};
const current = { structures: [PAVE] };
@@ -248,6 +256,7 @@ async function build(list) {
form.id = null;
form.pipe = null;
view.selected = null;
view.revealed = null;
view.spanMarkId = null;
profile.markedId = null;
profile.pill = null;
@@ -256,8 +265,8 @@ async function build(list) {
shared: { view: () => "cross" },
detail: () => ({ cross_sections: CARDS }),
stationInterval: () => 20,
focusChainage: (at) => {
if (!wallSelecting) focusStationAt(at);
focusChainage: (at, revealOnly) => {
if (!wallSelecting) focusStationAt(at, revealOnly);
},
markStructure: (id) => view.selectMark(id),
onMarks: (next, types) => {
@@ -308,7 +317,11 @@ const wallPick = (cardAtM, ownerM) => {
await build([PAVE, { structure_id: "sign", type_id: "hazard_sign", chainage_m: 127.86 }]);
listPick("pave");
out.step1 = snap();
cardPick(40); // 고름이 이미 연 범위 첫 카드 재누름(브레인 ORCA ②)
out.reveal1 = view.revealed; // 고르지 않고 스크롤만 한 카드(177-4)
out.pick1 = selection.readSelection(PID);
cardPick(40); // 스크롤만 한 범위 첫 카드 누름
out.step2first = snap();
cardPick(40); // 고른 범위 카드 재누름(167-3 · 브레인 ORCA ②)
out.step2re = snap();
cardPick(140);
out.step2 = snap();
@@ -318,6 +331,7 @@ const wallPick = (cardAtM, ownerM) => {
out.step3 = snap();
pillPick("pave");
out.step4 = snap();
out.reveal4 = view.revealed;
cardPick(80); // 관 자리 카드 = 관(지금처럼)
out.pipeCard = snap();
pillPick("pave");
@@ -339,6 +353,7 @@ const wallPick = (cardAtM, ownerM) => {
await build([PAVE, PAVE2]);
listPick("pave2");
out.step6 = snap();
out.reveal6 = view.revealed;
cardPick(160);
out.step6b = snap();
process.stdout.write(JSON.stringify(out));
+25 -13
View File
@@ -1,5 +1,5 @@
/* 집수정 「동물이동형」 체크 칸(PLAN 173-7) 단위검증 헬퍼 — 공용 명세 폼을 그 자리에서 트랜스파일해 Node 로 돌린다.
* 빈 값 = 체크 · 끄면 "false" · 다시 켜면 "true" · 흙막이 갈래엔 칸 없음. 결과는 표준출력에 JSON 한 벌.
/* 집수정 「동물이동형」 칸(PLAN 173-7 · 177-2 고르기 유 / 무) 단위검증 헬퍼 — 공용 명세 폼을 그 자리에서 트랜스파일해 Node 로 돌린다.
* 빈 값 = 유("true" 적힘) · 무 = "false" · 다시 유 = "true" · 흙막이 갈래엔 칸 없음. 결과는 표준출력에 JSON 한 벌.
* 짝 = `test_173_7_inlet_animal.py` · 화면 그릇 흉내는 `helper_54_10_soil_tiers.cjs` 꼴(+ 듣개).
*/
const fs = require("fs");
@@ -121,32 +121,44 @@ const { createSpecForm } = loadTs(
const { PIPE_SPEC } = loadTs(path.join(ROOT, "A00_Common", "design", "design_structure_pipe.ts"));
const form = createSpecForm(null, {});
// 177-2 — 체크박스 → 고르기(유 / 무) · 저장 글 "true" / "false" 그대로
const box = () =>
form.root
.querySelectorAll("label")
.find((l) => l.dataset.specItem === "inlet.animal")
?.querySelector("input") ?? null;
?.querySelector("select") ?? null;
const animal = () => form.read().inlet_basin_animal ?? null;
const toggle = (on) => {
const input = box();
input.checked = on;
input.fire("change");
const pick = (v) => {
const select = box();
select.value = v;
select.fire("change");
};
const shown = () => {
const select = box();
return select
? {
value: select.value,
options: select.children.map((o) => [o.value, o.textContent]),
saved: animal(),
}
: null;
};
const out = {};
form.write(PIPE_SPEC, { pipe_diameter_mm: 1000, inlet_type: "집수정" });
out.blank = { checked: box()?.checked ?? null, saved: animal() };
toggle(false);
out.off = { checked: box().checked, saved: animal() };
toggle(true);
out.on = { checked: box().checked, saved: animal() };
out.blank = shown();
pick("false");
out.off = shown();
pick("true");
out.on = shown();
form.write(PIPE_SPEC, {
pipe_diameter_mm: 1000,
inlet_type: "집수정",
inlet_basin_animal: "false",
});
out.storedOff = { checked: box().checked, saved: animal() };
out.storedOff = shown();
form.write(PIPE_SPEC, { pipe_diameter_mm: 1000, inlet_type: "기슭막이" });
out.soil = { shown: box() !== null, saved: animal() };
out.checkbox = form.root.querySelectorAll("input").some((i) => i.type === "checkbox");
process.stdout.write(JSON.stringify(out));
+263
View File
@@ -0,0 +1,263 @@
/* PLAN 176-1 단위검증 헬퍼 — B05 3D 성토 비탈 끝 이음 띠(SEAM_M) · 성토 덩이 끝 뜸 줄이기.
* 직선 노선 80 m · 측점 0 · 20 · 40 성토(노면 100 · 지반 94 · 1:1.5) · 60 · 80 절토(지반 104 · 1:1).
* 지반에 노선 방향 사인 물결(진폭 1 m · 파장 10 m · 측점 자리 0) → 성토 비탈 끝이 한도까지 뜸.
* 트랜스파일 틀 · 격자 지형 · 틈 셈은 helper_172_1_loft_wrinkle.cjs 와 같다. 결과는 표준출력 JSON.
*/
const fs = require("fs");
const path = require("path");
const ROOT = path.join(__dirname, "..", "..");
const NM = path.join(ROOT, "config", "node_modules");
const ts = require(path.join(NM, "typescript"));
const THREE = require(path.join(NM, "three"));
const LIBS = {
three: THREE,
delaunator: require(path.join(NM, "delaunator", "index.js")),
"three/examples/jsm/utils/BufferGeometryUtils.js": require(path.join(NM, "three", "examples", "jsm", "utils", "BufferGeometryUtils.js")),
"@kninnug/constrainautor": {
__esModule: true,
default: require(path.join(NM, "@kninnug", "constrainautor", "lib", "Constrainautor.cjs")),
},
};
const cache = new Map();
function loadTs(file) {
const full = path.resolve(file);
if (cache.has(full)) return cache.get(full);
const js = ts.transpileModule(fs.readFileSync(full, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
cache.set(full, box.exports);
const localRequire = (request) => {
if (LIBS[request]) return LIBS[request];
if (request.startsWith("@ui/") || request.startsWith("@config/")) {
return new Proxy({}, { get: () => () => undefined });
}
const target = request.startsWith("@util/")
? path.join(ROOT, "common_util", request.slice(6))
: path.join(path.dirname(full), request);
if (request.endsWith(".json")) return JSON.parse(fs.readFileSync(target, "utf8"));
return loadTs(fs.existsSync(`${target}.ts`) ? `${target}.ts` : path.join(target, "index.ts"));
};
new Function("exports", "module", "require", js)(box.exports, box, localRequire);
return box.exports;
}
const B05 = (name) => path.join(ROOT, "B05_Profile", `${name}.ts`);
const { buildCorridor } = loadTs(B05("B05_Profile_UI_Corridor_Build"));
const { loftTerrain } = loadTs(B05("B05_Profile_UI_Corridor_Loft"));
const { TerrainBandSplit } = loadTs(B05("B05_Profile_UI_Corridor_Split"));
const { TerrainHeightIndex } = loadTs(B05("B05_Profile_UI_Corridor_Terrain"));
const PSLG = loadTs(B05("B05_Profile_UI_Corridor_Tin_Pslg"));
const { SEAM_M } = loadTs(B05("B05_Profile_UI_Corridor_Tin"));
const HALF = 3;
const ROAD_Z = 100;
const LENGTH = 80;
const STATIONS = [0, 20, 40, 60, 80];
const AMP = 1;
const WAVE_M = 10;
const r6 = (v) => Math.round(v * 1e6) / 1e6;
/** 측점 단면 — 성토(지반 94 · 1:1.5) 또는 절토(지반 104 · 1:1). */
function station(chainage) {
const fill = chainage <= 40;
const ground = fill ? 94 : 104;
const toe = HALF + Math.abs(ROAD_Z - ground) * (fill ? 1.5 : 1);
const pts = [
[-40, ground],
[-toe, ground],
[-HALF, ROAD_Z],
[-2.5, ROAD_Z],
[2.5, ROAD_Z],
[HALF, ROAD_Z],
[toe, ground],
[40, ground],
];
const samples = [];
for (let o = -40; o <= 40; o += 1) samples.push({ offset_m: o, elevation_m: ground });
return {
station_id: `S${chainage}`,
chainage_m: chainage,
label: "",
kind: "regular",
center_x: chainage,
center_y: 0,
center_z: ground,
frame: { left_xy: [0, 1] },
samples,
design: {
section_mode: fill ? "both_fill" : "both_cut",
road_edges: {
left: { offset_m: HALF, elevation_m: ROAD_Z },
right: { offset_m: -HALF, elevation_m: ROAD_Z },
},
carriageway_edges: {
left: { offset_m: 2.5, elevation_m: ROAD_Z },
right: { offset_m: -2.5, elevation_m: ROAD_Z },
},
design_line: pts.map(([offset_m, elevation_m]) => ({ offset_m, elevation_m })),
ditch: { type: "none" },
ditch_enabled: false,
ditch_side: "left",
},
};
}
const BOUNDS = { x: [-10, 90], y: [-30, 30], z: [85, 115] };
const OX = (BOUNDS.x[0] + BOUNDS.x[1]) / 2;
const OY = (BOUNDS.y[0] + BOUNDS.y[1]) / 2;
const OZ = (BOUNDS.z[0] + BOUNDS.z[1]) / 2;
const X0 = -10;
const X1 = 90;
const Y0 = -30;
const Y1 = 30;
const STEP = 0.5;
function gridTerrain(heightAt) {
const nx = Math.round((X1 - X0) / STEP) + 1;
const ny = Math.round((Y1 - Y0) / STEP) + 1;
const positions = new Float32Array(nx * ny * 3);
for (let j = 0; j < ny; j += 1) {
for (let i = 0; i < nx; i += 1) {
const v = j * nx + i;
const x = X0 + i * STEP;
const y = Y0 + j * STEP;
positions[v * 3] = x - OX;
positions[v * 3 + 1] = heightAt(x, y) - OZ;
positions[v * 3 + 2] = -(y - OY);
}
}
const index = [];
for (let j = 0; j < ny - 1; j += 1) {
for (let i = 0; i < nx - 1; i += 1) {
const a = j * nx + i;
if ((i + j) % 2) index.push(a, a + 1, a + nx, a + 1, a + nx + 1, a + nx);
else index.push(a, a + nx + 1, a + nx, a, a + 1, a + nx + 1);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.BufferAttribute(new Uint8Array(nx * ny * 4).fill(200), 4, true));
geometry.setIndex(index);
return new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ vertexColors: true }));
}
const key = (x, y, z) => `${Math.round(x * 1e4)},${Math.round(y * 1e4)},${Math.round(z * 1e4)}`;
const pkey = (x, z) => `${Math.round(x * 1e4)},${Math.round(z * 1e4)}`;
const fkey = (x, z) => pkey(Math.fround(x), Math.fround(z));
/** 한 번만 쓰인 변 중 지형 바깥 테두리 · 노면 끝 · 구멍 둘레가 아닌 것(틈). */
function gapCount(root, out) {
const pslg = out.design.pslg;
const tagAt = new Map();
for (let i = 0; i < pslg.count; i += 1) tagAt.set(fkey(pslg.x[i], pslg.z[i]), pslg.tag[i]);
const onFrame = (p) => {
const x = p[0] + OX;
const y = -p[2] + OY;
return Math.abs(x - X0) < 1e-3 || Math.abs(x - X1) < 1e-3 || Math.abs(y - Y0) < 1e-3 || Math.abs(y - Y1) < 1e-3;
};
const uses = new Map();
root.traverse((child) => {
if (!(child instanceof THREE.Mesh)) return;
const p = child.geometry.getAttribute("position");
const idx = child.geometry.getIndex();
const count = idx ? idx.count : p.count;
for (let t = 0; t < count; t += 3) {
const tri = [0, 1, 2].map((k) => {
const v = idx ? idx.getX(t + k) : t + k;
return [p.getX(v), p.getY(v), p.getZ(v)];
});
const [a, b, c] = tri;
if (Math.abs((b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2])) < 1e-9) continue;
for (let k = 0; k < 3; k += 1) {
const ka = key(...tri[k]);
const kb = key(...tri[(k + 1) % 3]);
const e = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
const entry = uses.get(e) ?? { n: 0, a: tri[k], b: tri[(k + 1) % 3] };
entry.n += 1;
uses.set(e, entry);
}
}
});
let gaps = 0;
for (const { n, a, b } of uses.values()) {
if (n !== 1) continue;
const ta = tagAt.get(pkey(a[0], a[2]));
const tb = tagAt.get(pkey(b[0], b[2]));
if (ta === PSLG.TAG_ANCHOR && tb === PSLG.TAG_ANCHOR) continue;
if (ta === PSLG.TAG_HOLE && tb === PSLG.TAG_HOLE) continue;
if (onFrame(a) && onFrame(b)) continue;
gaps += 1;
}
return gaps;
}
/** 성토 비탈 끝 둘레 점 · 이음 띠 경사 · 덩이 끝 뜸 · 틈. */
function run() {
const base = (x) => (x <= 40 ? 94 : x >= 60 ? 104 : 94 + (x - 40) / 2);
const terrain = gridTerrain((x) => base(x) + AMP * Math.sin((2 * Math.PI * x) / WAVE_M));
const sections = STATIONS.map(station);
const build = buildCorridor(sections, [
{ x: 0, y: 0 },
{ x: LENGTH, y: 0 },
]);
build.sections = sections;
build.structures = [];
const split = new TerrainBandSplit(terrain, { minX: -1e4, maxX: 1e4, minZ: -1e4, maxZ: 1e4 });
const heightIndex = new TerrainHeightIndex(terrain);
const out = loftTerrain(split, build, BOUNDS, heightIndex);
const pslg = out.design.pslg;
const groundAt = (x, y) => heightIndex.heightAt(x - OX, -(y - OY)) + OZ;
// 성토 비탈 끝(설계 둘레 · 성토 꼬리표) — 측마다 높이 − 지형 · 덩이 끝(가장 큰 x) 점.
const outer = new Set(out.design.outer.map(([x, z]) => pkey(x, z)));
const rim = new Set();
const ends = { 1: { x: -Infinity, off: 0 }, [-1]: { x: -Infinity, off: 0 } };
let midOff = 0;
for (let i = 0; i < pslg.count; i += 1) {
if (pslg.tag[i] !== PSLG.TAG_FILL || !outer.has(pkey(pslg.x[i], pslg.z[i]))) continue;
rim.add(pkey(pslg.x[i], pslg.z[i]));
const x = pslg.x[i] + OX;
const y = -pslg.z[i] + OY;
const off = Math.abs(pslg.y[i] + OZ - groundAt(x, y));
if (x > 5 && x < 35) midOff = Math.max(midOff, off);
const end = ends[y > 0 ? 1 : -1];
if (x > end.x) Object.assign(end, { x, off });
}
// 이음 띠 — 성토 비탈 끝 점을 쓰는 원지반 색 삼각형의 경사(°).
const mesh = out.root.getObjectByName("terrain-tin-mesh");
const p = mesh.geometry.getAttribute("position");
const keep = mesh.userData.keepColor;
const slopes = [];
for (let t = 0; t < p.count / 3; t += 1) {
if (keep[t * 3]) continue;
const v = [0, 1, 2].map((k) => [p.getX(t * 3 + k), p.getY(t * 3 + k), p.getZ(t * 3 + k)]);
if (!v.some(([x, , z]) => rim.has(pkey(x, z)))) continue;
// 지반 바탕이 평탄한 성토 구간만(지형 자체 경사 ≤ 32°) — 40~60 m 오르막은 지형이 45° 넘음.
const cx = (v[0][0] + v[1][0] + v[2][0]) / 3 + OX;
if (cx < 2 || cx > 38) continue;
const u = [0, 1, 2].map((k) => v[1][k] - v[0][k]);
const w = [0, 1, 2].map((k) => v[2][k] - v[0][k]);
const n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
const len = Math.hypot(...n);
if (len < 1e-9) continue;
slopes.push((Math.acos(Math.abs(n[1]) / len) * 180) / Math.PI);
}
slopes.sort((a, b) => a - b);
return {
seam: SEAM_M,
stats: out.stats,
gaps: gapCount(out.root, out),
rimPoints: rim.size,
seamTris: slopes.length,
seamP99: r6(slopes[Math.floor(0.99 * (slopes.length - 1))] ?? 0),
midOff: r6(midOff),
endX: [r6(ends[1].x), r6(ends[-1].x)],
endOff: r6(Math.max(ends[1].off, ends[-1].off)),
};
}
process.stdout.write(JSON.stringify(run()));
@@ -0,0 +1,64 @@
/* 177-3 횡단 카드 ↔ 종단 측점선 헬퍼 — 진짜 design_profile.ts 의 `setSelectedStation` · `setSelectedStructure`
* 본문을 떼어(TS 는 그 자리 트랜스파일) 측점 · 구조물 짝 흉내에 붙이고, B06 카드 고름 차례
* (showCard → setSelectedStation · 리스너 → selectMark → setSelectedStructure(mark, true))와 B05 기본 길을 돌려
* 남은 측점선 id 를 표준출력 JSON 한 벌로.
*/
const fs = require("fs");
const path = require("path");
const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript"));
const ROOT = path.join(__dirname, "..", "..");
const src = fs.readFileSync(path.join(ROOT, "A00_Common", "design", "design_profile.ts"), "utf8");
const method = (name) => {
const pattern = String.raw`\r?\n ${name}\([^\r\n]*\) \{\r?\n[\s\S]*?\r?\n \},`;
const match = src.match(new RegExp(pattern));
if (!match) throw new Error(`본문 없음: ${name}`);
return match[0];
};
const body = `
let selectedStationId = null;
let selectedStructureId = null;
// 관(pipe-80.17)만 측점선(irr-80)이 있음 — 벽 · 노면공은 선 없음(PST stationIdAtStructure)
const structureIdAtStation = (stationId) => (stationId === "irr-80" ? "pipe-80.17" : null);
const stationIdAtStructure = (structureId) => (structureId === "pipe-80.17" ? "irr-80" : null);
const draw = () => {};
module.exports = {
line: () => selectedStationId,
${method("setSelectedStation")}
${method("setSelectedStructure")}
};`;
const js = ts.transpileModule(body, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
new Function("exports", "module", js)(box.exports, box);
const dp = box.exports;
/** B06 카드 고름 — showCard(카드 · 관 측점이면 관 선) 뒤 리스너가 selectMark(mark) = keepStation true. */
const b06Card = (lineId, mark) => {
dp.setSelectedStation(lineId);
dp.setSelectedStructure(mark, true);
return dp.line();
};
/** B05 목록 고름 — 기본값(keepStation 없음). */
const b05Pick = (lineId, structureId) => {
dp.setSelectedStation(lineId);
dp.setSelectedStructure(structureId);
return dp.line();
};
const out = {
plainCard: b06Card("s40", null), // 일반 카드 — 덮는 것 없음
wallCard: b06Card("s100", "wall"), // 벽(선 없는 구조물) 카드
paveCard: b06Card("s140", "pave"), // 노면공 범위 안 카드
pipeCard: b06Card("irr-80", "pipe-80.17"), // 관 카드 = 관 선
pipeFromPlain: b06Card("s60", "pipe-80.17"), // 관 알약 = 관 선으로 옮김
// 반대 길 — 종단 측점선 누름 → 카드 고름 → 같은 리스너(selectMark null)
profileClick: b06Card("s200", null),
// 카드 풂 = showCard(null) → 선 끔
release: (dp.setSelectedStation(null), dp.line()),
b05Wall: b05Pick("s100", "wall"), // B05 = 지금 그대로(선 없는 구조물 → 선 끔)
b05Pipe: b05Pick("s40", "pipe-80.17"),
b05Keep: b05Pick("irr-80", "pipe-80.17"),
};
process.stdout.write(JSON.stringify(out));
@@ -58,6 +58,7 @@ class E {
get className() { return [...this.cls].join(" "); }
set className(v) { this.cls = new Set(String(v).split(/\s+/).filter(Boolean)); }
append(...xs) { for (const x of xs) { x.parent = this; this.children.push(x); } }
replaceChildren(...xs) { this.children = []; this.append(...xs); }
prepend(...xs) { for (const x of xs.reverse()) { x.parent = this; this.children.unshift(x); } }
addEventListener(t, f) { (this.on[t] ??= []).push(f); }
setAttribute(k, v) { this.attrs[k] = String(v); }
@@ -32,8 +32,8 @@ def test_범위_강조_클래스는_고름_목록갱신_카드재생성_세_길
r"spanMarks = structures;\s+spanTypes = types;\s+syncSpanHighlights\(\);", VIEW
)
assert VIEW.count("applySpan(card, section);") == 2
# 152-5 노면공(G군)은 테두리 대신 포장층
assert 'card.classList.toggle("b06-cross-card--span", span && !pave);' in VIEW
# 152-5 노면공(G군) 포장층 · 177-4 범위 카드 테두리도 함께
assert 'card.classList.toggle("b06-cross-card--span", span);' in VIEW
def test_측점_고름은_카드_하나_목록_고름은_여럿():
+4 -5
View File
@@ -106,14 +106,13 @@ def test_카드_배선_하나만() -> None:
assert ".b06-chart__design-hit.is-active {" in css
def test_치수_두_줄_좁은_카드는_표_아래로() -> None:
"""151-1 — 줄바꿈 글자를 살리고 오른쪽 맞춤 · 좁은 카드(3열 등)는 표 높이 아래로 내려 표를 안 덮음."""
def test_치수_두_줄_늘_단추_왼쪽() -> None:
"""151-1 — 줄바꿈 글자를 살리고 오른쪽 맞춤 · 179-1 — 좁은 카드도 표 아래로 안 내림(늘 [+ − ⤢] 왼쪽)."""
css = _src("B06_Section/B06_Section_UI_Style_Cross_Controls.css")
dims = css.split(".b06-cross-card__line-dims {", 1)[1].split("}", 1)[0]
assert "white-space: pre-line;" in dims and "text-align: right;" in dims
assert "container-type: inline-size;" in css
narrow = css.split("@container (max-width: 620px) {", 1)[1]
assert "top: calc(var(--spacing-8) + var(--b06-areas-height, 3.6rem));" in narrow
assert "position:" not in dims
assert "@container" not in css
def test_폴리곤_자르기는_공용_한_벌() -> None:
+5 -1
View File
@@ -119,7 +119,11 @@ def _project(tmp_path: Path, count: int) -> tuple[Path, Path]:
def test_layout_store_and_release_changed_confirmed(tmp_path: Path) -> None:
root, longitudinal_path = _project(tmp_path, 20)
assert read_cross_layout(root) == {"default": [4, 4], "sheets": {}} # 파일 없으면 기본
assert read_cross_layout(root) == {
"default": [4, 4],
"sheets": {},
"table_scale": 1.0,
} # 파일 없으면 기본
ids = [s["id"] for s in _cross_sheet_plan(root, longitudinal_path)]
assert ids == ["cross_s00000m", "cross_s00320m"] # 16 + 4
manifest = _read_manifest(root)
@@ -61,3 +61,12 @@ def test_장_아니면_이_장_꺼짐(out):
assert not_sheet["disabled"] == [True, False]
assert not_sheet["defaults"] == [[4, 4]]
assert not_sheet["values"] == ["4", "4"]
def test_표_배율_칸(out):
scale = out["scale"]
assert scale["labels"] == ["배치 열", "행", "표 배율"]
assert scale["input"] == {"value": "1", "min": "0.5", "max": "2", "step": "0.1"}
assert scale["buttons"] == ["이 장", "모든 장", "배율 적용"]
assert scale["applied"] == [1.5]
assert scale["toasts"] == ["error"] # 2.5 = 범위 밖
@@ -1,7 +1,7 @@
"""157-2 B09 단가산출근거 탭 보기 둘 · 157-3 산근 규격 칸 「이름 규격」.
- 157-2 보기 B(호표별 카드) = 보기 A(표) 줄 그대로 호표마다 묶음 — 같은 값 · 같은 차례(171-3 공용 묶음 카드로 갈음)
- 단추 = 보기 바꿈(글 「호표별 보기」 ↔ 「표로 보기」) · 기억 못 읽음 · 모르는 값 = 카드(171-3 컨테이너 기본)
- 단추 = 보기 바꿈(글 「박스보기」 ↔ 「표로 보기」 · 181-2) · 기억 못 읽음 · 모르는 값 = 카드(171-3 컨테이너 기본)
- 157-3 규격 = 기계 · 직종 원문번호 → 「이름 규격」(M02 85-1 도우미) · 번호는 풍선(tip)
"""
@@ -66,7 +66,7 @@ def test_157_2_단추_바꿈():
"\nconsole.log(JSON.stringify([viewLabel('table'), viewLabel('cards'),"
" flipView('table'), flipView(flipView('table'))]));"
)
assert out == ["호표별 보기", "표로 보기", "cards", "table"]
assert out == ["박스보기", "표로 보기", "cards", "table"]
def test_157_2_기억_실패_때_카드():
+8 -6
View File
@@ -2,7 +2,7 @@
"""165 B06 노면공 고름 일관성 — 조사 K 재현 차례 6단계.
못박는 것(단계마다 폼 · 알약 · 포장층 · 고른 카드 · 세션 sid 가 같은 것을 가리킴)
1. 목록 노면공 = 범위 안 카드 · 포장층 · 알약 · 폼 · sid 모두 노면공(기준점이 범위 경계여도 범위 밖 카드로 안 감).
1. 목록 노면공 = 포장층 · 알약 · 폼 · sid 모두 노면공 · 카드는 안 고름(스크롤만 · 177-4 · 기준점이 범위 경계여도 범위 밖 카드로 안 감).
2. 범위 안 빈 카드(관 · 덮는 구조물 없음) = 노면공 그대로 · 카드만 옮김(165-1).
3. 고른 카드의 벽 = 관 폼 + 관 알약(알약이 꺼진 채 폼만 남지 않음 · 165-2) · 포장층 풂.
4. 알약 다시 = 1 과 같음. 관 자리 카드 = 관 · 범위 밖 카드 = 모두 풂(지금처럼).
@@ -55,10 +55,12 @@ PIPE = {"form": "pipe-80.17", "pill": "pipe-80.17", "paveLayer": None, "paveCard
def test_1_목록_노면공(out):
assert out["step1"] == _pave(40) # 기준점 30 = 범위 경계 → 범위 안 첫 카드(20 아님)
assert out["step1"] == _pave(None) # 카드 하나 안 고름(177-4)
assert out["reveal1"] == "s40" # 기준점 30 = 범위 경계 → 범위 안 첫 카드(20 아님)
def test_2_범위_안_빈_카드는_노면공_그대로(out):
assert out["step2first"] == _pave(40)
assert out["step2re"] == _pave(40) # 이미 고른 카드 재누름도 그대로(167-3)
assert out["step2"] == _pave(140)
assert out["step2b"] == _pave(100)
@@ -69,7 +71,7 @@ def test_3_벽은_관_폼과_관_알약_함께(out):
def test_4_알약_다시_관_카드_범위_밖(out):
assert out["step4"] == _pave(40)
assert out["step4"] == _pave(None)
assert out["pipeCard"] == {**PIPE, "card": 80, "sid": None}
assert out["outside"] == {
"form": None,
@@ -83,17 +85,17 @@ def test_4_알약_다시_관_카드_범위_밖(out):
def test_5_B05_복귀(out):
assert out["step5"] == _pave(40)
assert out["step5"] == _pave(None)
def test_6_겹친_노면공(out):
assert out["step6"] == _pave(100, "pave2", 6)
assert out["step6"] == _pave(None, "pave2", 6)
assert out["step6b"] == _pave(160, "pave2", 6)
def test_배선():
panel = _read("B06_Section", "B06_Section_UI_Page_Structures_Panel.ts")
assert "deps.focusChainage(focusOf(structure));" in panel
assert "deps.focusChainage(focusOf(structure), pave);" in panel
assert "return { chainageM, structureId: openId };" in panel
# 관 알약은 폼 뒤(폼이 연 구조물을 닫으며 알약을 끔)
at = panel.index("section.selectPipeByChainage(hit.pipeChainageM);")
+25 -19
View File
@@ -2,7 +2,7 @@
- 머리 = 호표 · 명칭 · 규격 · 단위 · 합계 / 몸 = 이름 · 규격 · 수량 · 단위 · 합계 · 비고 / 합계 줄 = 노무 · 재료 · 경비 · 계
- 줄 금액 = 합계만 · 비목 셋 = 풍선 · 숫자 오른쪽 · 글자 14px 한 벌 · 줄 간격 좁게(공용 카드 16px 끼움 없음)
- 가로 열 수 1~4(기본 2 · 고르면 알림) · 묶음 12 넘으면 요약 보기(머리 · 합계만 · 머리 누름 = 펼침 · 모두 펼침 · 접기)
- 가로 열 수 1~4(기본 2 · 고르면 알림) · 접기 없음(181-2) · 이동해 온 박스 = `is-pick`(붉은 외곽선) · 머리 누름 = 이동
- 157-2 산근 카드 파일 = 이 양식으로 갈음(지움)
"""
@@ -43,11 +43,9 @@ def test_도우미_열수_요약_풍선():
out = _run(
"\nconsole.log(JSON.stringify({"
" cols: [0, 1, 2, 3, 4, 5, '3', null, undefined].map(clampColumns),"
" summary: [12, 13].map(isSummary),"
" tip: [partsTip([1000, 0, null]), partsTip([null, null, null]), partsTip(null)] }));"
)
assert out["cols"] == [2, 1, 2, 3, 4, 2, 2, 2, 2]
assert out["summary"] == [False, True]
assert out["tip"] == ["노무 1,000 · 재료 0 · 경비 -", None, None]
@@ -91,7 +89,7 @@ def test_카드_머리_몸_합계_줄():
assert out["foot"] == ["노무 100", "재료 20", "경비 3", "계 123", "빈 줄 1"]
assert out["link"] == [True, False]
assert out["cols"] == "2" # 기본 2
assert out["summary"] == ["1", "2", "3", "4"] # 12 이하 = 요약 단추 없음
assert out["summary"] == ["1", "2", "3", "4"] # 가로 열 수 단추뿐(요약 · 접기 단추 없음)
def test_가로_열수_고름_알림_누름_이동():
@@ -111,29 +109,35 @@ def test_가로_열수_고름_알림_누름_이동():
assert out["picks"] == [21, 20] # 줄 · 머리 누름 = 표 줄 번호 그대로(갈 곳은 부르는 쪽 link)
def test_묶음_12_넘으면_요약_보기():
def test_묶음_많아도_접힘_없음_고른_박스_붉은_외곽선():
out = _run(
"\nconst root = make(13, { focus: 52 });"
"\nconst cards = root.all('.ui-group-card');"
"\nconst closed = () => cards.map((c) => c.classList.contains('is-closed'));"
"\nconst first = closed();"
"\nconst focused = root.querySelector('[data-at=\"52\"]');"
"\nconst first = cards.map((c) => c.classList.contains('is-pick'));"
"\ncards[0].querySelector('.ui-group-card__head').click();"
"\nconst opened = closed()[0];"
"\nconst btn = (label) => root.all('.ui-btn').find((b) => b.textContent === label);"
"\nbtn('모두 펼침').click(); const all = closed();"
"\nbtn('모두 접기').click(); const none = closed();"
"\nconsole.log(JSON.stringify({ first, opened, all, none, picks,"
"\nconsole.log(JSON.stringify({ first, picks,"
" closed: cards.map((c) => c.classList.contains('is-closed')),"
" buttons: root.all('.ui-btn').map((b) => b.textContent),"
" foot: cards.every((c) => c.querySelector('.ui-group-card__foot')),"
" focus: [focused.classList.contains('is-focus'), !!focused.scrolled] }));"
" focus: [focused.classList.contains('is-focus'), cards[4].scrolled === true] }));"
)
# 이동해 온 줄(5번째 묶음 줄) = 그 묶음만 펼침 · 강조 · 스크롤
assert out["first"] == [True] * 4 + [False] + [True] * 8
# 이동해 온 줄(5번째 묶음 줄) = 그 박스만 붉은 외곽선 · 그 줄 강조 · 박스 스크롤
assert out["first"] == [False] * 4 + [True] + [False] * 8
assert out["focus"] == [True, True]
assert out["opened"] is False # 머리 누름 = 펼침
assert out["picks"] == [] # 요약 보기 머리 누름은 이동 아님
assert out["all"] == [False] * 13 and out["none"] == [True] * 13
assert out["foot"] is True # 접어도 합계 줄은 보임(몸만 숨김)
assert out["closed"] == [False] * 13 # 13 묶음도 접힘 없음
assert out["picks"] == [10] # 머리 누름 = 이동(표 줄 번호 그대로)
assert out["buttons"] == ["1", "2", "3", "4"] # 모두 펼침 · 접기 단추 없음
assert out["foot"] is True
def test_고른_박스_없으면_외곽선_없음():
out = _run(
"\nconst root = make(3);"
"\nconsole.log(JSON.stringify(root.all('.ui-group-card').map("
"(c) => c.classList.contains('is-pick'))));"
)
assert out == [False, False, False]
def test_양식_글자_간격_숫자():
@@ -146,6 +150,8 @@ def test_양식_글자_간격_숫자():
"font-size: inherit;",
]
assert "padding: 1px var(--spacing-4);" in css # 줄 간격 좁게
assert "is-closed" not in css and "is-closed" not in (ROOT / COMMON).read_text("utf-8")
assert "border-color: var(--color-danger);" in css # 고른 박스 = B06 고름 꼴(181-2)
assert "spacing-16" not in css and "card-padding" not in css # 공용 카드 16px 끼움 없음
assert "grid-template-columns: repeat(var(--group-cols, 2), minmax(0, 1fr));" in css
assert "text-align: right;" in css
@@ -151,9 +151,10 @@ def test_화면_보기_바꿈_누름_이동():
"\nview.querySelector('[data-at=\"2\"]').click();"
"\nview.querySelector('[data-at=\"0\"]').click();"
"\nconst lit = view.querySelector('[data-at=\"3\"]').classList.contains('is-focus');"
"\nconst box = view.querySelector('.ui-group-card').classList.contains('is-pick');"
"\nbar.children[0].click();"
"\nconst [bar2, view2] = renderGroupPanel(o);"
"\nconsole.log(JSON.stringify({ label, table: view.dataset.b09Table, gone, lit, redraws,"
"\nconsole.log(JSON.stringify({ label, table: view.dataset.b09Table, gone, lit, box, redraws,"
" label2: bar2.children[0].textContent, tag2: view2.tagName, focused,"
" kept: Object.fromEntries(kept) }));",
RAW,
@@ -161,8 +162,9 @@ def test_화면_보기_바꿈_누름_이동():
assert out["label"] == "표로 보기" and out["table"] == "dg" # 기본 = 카드
assert out["gone"] == [{"tab": "labor", "key": "L00005"}, None] # 줄 누름 = 표와 같은 이동
assert out["lit"] is True # 이동해 온 줄(키 DG1|1 = 표 3번째 줄) 강조
assert out["box"] is True # 그 호표 박스 = 붉은 외곽선(181-2)
assert out["redraws"] == 1
assert out["label2"] == "호표별 보기" and out["tag2"] == "TABLE" and out["focused"] == [3]
assert out["label2"] == "박스보기" and out["tag2"] == "TABLE" and out["focused"] == [3]
assert json.loads(out["kept"]["b09-group-view"]) == {"dg": "table"}
+11 -7
View File
@@ -1,4 +1,4 @@
"""173-7 집수정 「동물이동형」 체크 칸 — 공용 체크박스 · 저장 키 inlet_basin_animal · 빈 값 = 참.
"""173-7 · 177-2 집수정 「동물이동형」 칸 — 고르기 유 / 무 · 저장 키 inlet_basin_animal("true"/"false") · 빈 값 = 유.
공용 명세 폼(`design_structure_form.ts`)을 그 자리에서 돌린 값(`helper_173_7_inlet_animal.cjs`)
+ 배관 폼 키 목록(`B05_Profile_UI_Drainage_Facility_Merge.ts`).
@@ -28,14 +28,18 @@ def out() -> dict:
return json.loads(done.stdout)
def test_빈_값은_체크_저장_안_함(out: dict) -> None:
assert out["blank"] == {"checked": True, "saved": None}
YU_MU = [["true", "유"], ["false", "무"]]
def test_끄면_false_다시_켜면_true(out: dict) -> None:
assert out["off"] == {"checked": False, "saved": "false"}
assert out["on"] == {"checked": True, "saved": "true"}
assert out["storedOff"] == {"checked": False, "saved": "false"}
def test_빈_값은_유_실제_값으로_적힘(out: dict) -> None:
# 177-2 — 필수 상자 빈 고르기 칸 = 기본값을 실제 값으로(54-43) · 옛 「저장 안 함」 뒤집음
assert out["blank"] == {"value": "true", "options": YU_MU, "saved": "true"}
def test_무면_false_다시_유면_true(out: dict) -> None:
assert out["off"] == {"value": "false", "options": YU_MU, "saved": "false"}
assert out["on"] == {"value": "true", "options": YU_MU, "saved": "true"}
assert out["storedOff"] == {"value": "false", "options": YU_MU, "saved": "false"}
def test_흙막이엔_칸_없음(out: dict) -> None:
+149
View File
@@ -0,0 +1,149 @@
"""M02 일위대가 사전조합 자재목록(PLAN 175) — 구조물 일위대가와 같은 자재목록.
175-1 화면 · 저장 — 서고 모드 자재목록 · 로직 자재 세 칸 막힘 풂 · 저장 `_combo_lines` 가
고름 · 자재표시 남김 · 문서 `자재`(일위대가 자재 검사 · 로직 자재와 같은 품목 400).
175-2 셈 — 담은 자재(손 · 빈칸 = 안 셈)가 사전조합 1 단위 값(`Expand._combo` · 안 줄) · B08 참조 줄
재료(`_ref_mats`) · B09 겹 대가 자재 줄 · 프로젝트 사본 단가 묶음(`frozen_materials`)에 들어감.
"""
import json
import os
from decimal import Decimal
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_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.test_m02_labor_ref import world # noqa: F401 — 임시 층 fixture
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "..", "..", "M02_MasterTemplete")
NET = "GC000337" # 낙석방지망 — 재료 줄 3 · 4 · 5(철망 · 결속선 · 에폭시)
NET_ITEM = "MT006697"
WIRE = "MT000194"
MAT = "MT000008" # 자재품목 · 물가정보 83000
STONE = "GF000219" # 원/㎡
SYS = {"층": "system", "주인": None}
def _save(folder, doc):
with store.at(folder):
key = refs.create("precombo", {"이름": "자재 조합", **doc})["이름"]
return key, json.loads((folder / "precombo" / f"{key}.json").read_bytes())
def test_화면_서고_모드도_자재목록_세_칸_자재_저장(world): # noqa: F811
detail = open(os.path.join(SRC, "M02_MasterTemplete_Labor_Detail.ts"), encoding="utf-8").read()
assert 'section(tc("Labor_Mats"), opt.card ? null : addMat, matHost),' in detail
assert 'lib ? [] : [section(tc("Labor_Mats")' not in detail
assert "mark: markLogicMat," in detail and "lib ? undefined" not in detail
assert "delete out.자재" not in detail and "delete out.열" in detail
def test_저장_왕복_고름_자재표시_자재_남음(world): # noqa: F811
line = {"로직": NET, "고름": {"4": NET_ITEM}, "자재표시": {"3": {"자재구분": "관급"}}}
mats = [
{"코드": MAT, "수량": {"손": 2}, "운반비": "미포함", "이름": "틀린 이름"},
{"코드": WIRE, "수량": None},
]
_, got = _save(world["system"], {"담은로직": [line], "자재": mats})
one = got["담은로직"][0]
assert one["고름"] == {"4": NET_ITEM} and one["자재표시"] == {"3": {"자재구분": "관급"}}
assert [(m["코드"], m["수량"]) for m in got["자재"]] == [(MAT, {"손": 2}), (WIRE, None)]
assert got["자재"][0]["운반비"] == "미포함" and got["자재"][0]["이름"] != "틀린 이름"
# 자재 없음 = 빈 목록(옛 문서 꼴 그대로 읽힘)
_, empty = _save(world["system"], {"담은로직": [{"로직": NET}]})
assert empty["자재"] == []
def test_로직_자재와_같은_품목_400_없는_자재_400(world): # noqa: F811
with pytest.raises(store.StoreError) as e:
_save(world["system"], {"담은로직": [{"로직": NET}], "자재": [{"코드": WIRE}]})
assert e.value.status == 400 and WIRE in str(e.value.detail)
with pytest.raises(store.StoreError) as e:
_save(world["system"], {"담은로직": [], "자재": [{"코드": "MT999999"}]})
assert e.value.status == 400
# ── 175-2 셈 ──────────────────────────────────────────────────────────
def _price(code):
whole = m01.loaded()[1]
return Decimal(str(labor.material_price(whole, code, None)["기준단가"]))
def _world_combo(world): # noqa: F811
"""STONE 1 + MAT 손 2 + WIRE 빈칸(안 셈) · NET 고름 4 = NET_ITEM — (키, 손셈 1 단위 값)."""
lines = [
{"로직": STONE, "수량": {"손": 1}},
{"로직": NET, "수량": {"손": 0}, "고름": {"4": NET_ITEM}},
]
mats = [{"코드": MAT, "수량": {"손": 2}}, {"코드": WIRE, "수량": None}]
with store.at(world["system"]):
key = refs.create("precombo", {"이름": "자재 조합", "담은로직": lines, "자재": mats})[
"이름"
]
stone = Decimal(str(labor.run_line(m01.loaded()[1], STONE, {})["기준"]["계"]))
return key, stone + _price(MAT) * 2
def test_사전조합_값에_자재_금액_빈칸은_안_셈_안_줄에_자재(world): # noqa: F811
key, want = _world_combo(world)
with store.at(world["system"]):
doc = labor.clean(
{"열": "rv", "담은로직": [{"참조": {**SYS, "키": key}, "수량": {"손": 3}}]}
)
one = labor.calc(doc, {})["줄"][0]
assert one["기준"]["계"] == pytest.approx(float(want))
assert one["반영"]["계"] == pytest.approx(float(want * 3))
mats = [x for x in one["안"] if x.get("자재")]
assert [(x["자재"], x["수량"]) for x in mats] == [(MAT, 2)] # WIRE 빈칸 = 안 셈
assert mats[0]["기준"]["재료비"] == pytest.approx(float(_price(MAT)))
# 목록 기준금액(51-4)도 같은 펼침
rows = [{"종류": "precombo", "이름": key}]
refs.summaries(world["system"], rows)
assert rows[0]["기준금액"] == pytest.approx(float(want))
def test_B08_참조_줄_재료에_사전조합_자재_손_곱(world): # noqa: F811
from B08_Quantity.B08_Quantity_Router_Material import _ref_mats
key, _ = _world_combo(world)
with store.at(world["system"]):
outer = refs.create(
"precombo",
{"이름": "겹", "담은로직": [{"참조": {**SYS, "키": key}, "수량": {"손": 3}}]},
)["이름"]
got = _ref_mats(m01.loaded()[1], refs.read_ref, {**SYS, "키": outer})
mats = [(m["품목"]["키"], q) for m, q in got if m.get("자재")]
assert mats == [(MAT, pytest.approx(6.0))] # 2 × 겹 손 3 · WIRE 빈칸 없음
def test_B09_겹_대가에_자재_줄(world): # noqa: F811
from B09_Estimation.B09_Estimation_Labor_Source import Builder
key, _ = _world_combo(world)
ref = {**SYS, "키": key}
build = Builder()
bid = build.precombo(m01.loaded()[1], ref, refs.read_ref(ref), {})
mats = [x for x in build.blocks[bid]["lines"] if x["kind"] == "material"]
assert [(x["key"], x["qty"]) for x in mats] == [(MAT, 2.0), (WIRE, None)]
assert mats[0]["name"] and mats[0]["unit"]
def test_사본_단가_묶음에_사전조합_자재_고름_사본_값_같음(world): # noqa: F811
from M02_MasterTemplete import M02_Item_Prices as prices
from M02_MasterTemplete import M02_Item_Source as source
key, want = _world_combo(world)
doc = {"열": "rv", "담은로직": [{"참조": {**SYS, "키": key}, "수량": {"손": 1}}], "자재": []}
with store.at(world["system"]):
rows = source.labor_doc_rows(labor.clean(doc))
mats = refs.frozen_materials(rows["참조사본"])
assert {MAT, WIRE, NET_ITEM} <= set(mats)
assert "refs.frozen_materials(" in open(source.__file__, encoding="utf-8").read()
bundle = prices.to_json(prices.collect(refs.frozen_logics(rows["참조사본"]), mats))
(world["system"] / "precombo" / f"{key}.json").unlink() # 원본이 사라져도 굳힌 사본
got = prices.calc(rows, bundle, {}, {}, None)["줄"][0]
assert got["기준"]["계"] == pytest.approx(float(want), rel=1e-9)
+45
View File
@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
"""PLAN 176-1 — B05 3D 성토 비탈 끝 깨짐(172 뒤) 고침 검사.
도우미(helper_176_1_seam.cjs) — 직선 80 m · 성토(0~40 m) → 절토(60~80 m) · 지반 사인 물결(진폭 1 m).
비탈 끝 바깥 SEAM_M(1.5 m) 안 지형 점 빼서 잇는 띠 완만 · 성토 덩이 끝 3 m 안 뜸 0 까지 줄임.
"""
import json
import os
import subprocess
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture(scope="module")
def r():
proc = subprocess.run(
["node", os.path.join(HERE, "helper_176_1_seam.cjs")],
capture_output=True,
text=True,
timeout=240,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_seam_band_gentle(r):
# 성토 비탈 끝을 쓰는 원지반 삼각형 경사 p99 < 45°(1 mm 띠 = 54.7°)
assert r["seam"] == 1.5
assert r["seamTris"] > 100, r
assert r["seamP99"] < 45, r
def test_run_end_lift_tapered(r):
# 성토 덩이 가운데는 한도까지 뜸(물결이 실제로 재어짐) · 절토로 바뀌는 끝은 0 근처
assert r["midOff"] > 0.4, r
assert r["endX"][0] > 45 and r["endX"][1] > 45, r
assert r["endOff"] < 0.02, r
def test_no_gap_no_failed_constraint(r):
assert r["gaps"] == 0, r
assert r["stats"]["failed"] == 0, r
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""PLAN 176-2 — B05 3D 흑백 지형 · 등고선 처음 값 false(단추 · 뷰어 두 곳 다)."""
import os
import re
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
def _read(name):
with open(os.path.join(ROOT, "B05_Profile", name), encoding="utf-8") as f:
return f.read()
def test_panel_buttons_start_off():
src = _read("B05_Profile_UI_Panel_View.ts")
assert re.search(r'toggleButton\("등고선", false,', src)
assert re.search(r'toggleButton\("흑백 지형", false,', src)
def test_viewer_starts_off():
src = _read("B05_Profile_UI_Viewer.ts")
assert "let surfaceGrayscale = false;" in src
# 등고선 그룹은 만들자마자 숨김(적재 때 선은 그대로 만들고 단추로 켬)
assert re.search(
r"const contours = new THREE\.Group\(\);\s*\n\s*contours\.visible = false;", src
)
@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
"""PLAN 176-3 — B05 3D 측점 노란 띠 끝 주황 구슬(측구 방향 고르기) · 클릭 · 처리기 지움.
저장 길(세션 uphill → uphill_overrides)과 B06 이 쓰는 종단 병합 함수는 남김.
"""
import os
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
def _read(*parts):
with open(os.path.join(ROOT, *parts), encoding="utf-8") as f:
return f.read()
def test_markers_have_no_lamp():
src = _read("B05_Profile", "B05_Profile_UI_Markers.ts")
for gone in ("uphillStationId", "onUphillPick", "0xf97316", "UPHILL_LAMP", "lampHit"):
assert gone not in src, gone
def test_page_has_no_lamp_handler():
src = _read("A00_Common", "design", "design_view_profile.ts")
assert "onUphillPick" not in src
assert "uphillOverrides" not in _read("B05_Profile", "B05_Profile_UI_Page_Stations.ts")
def test_save_path_and_merge_kept():
# 저장 길(세션 → 저장 몸통)과 B06 이 부르는 종단 병합 함수는 그대로
page = _read("A00_Common", "design", "design_view_profile.ts")
assert "persistUphillOverrides" in page
assert "uphill_overrides" in _read("B05_Profile", "B05_Profile_UI_Page_Actions.ts")
assert "def _merge_uphill_overrides_into_longitudinal" in _read(
"B05_Profile", "B05_Profile_Router_Confirm.py"
)
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""PLAN 177-1 — 구조물 조합 미연결 라벨 = 연한 노랑(경고) 배경 + 테두리(소스 시험)."""
import os
import re
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
CSS = os.path.join(ROOT, "B05_Profile", "B05_Profile_UI_Style_Structures.css")
def _rule(sel: str) -> str:
src = open(CSS, encoding="utf-8").read()
m = re.search(re.escape(sel) + r"\s*\{([^}]*)\}", src)
assert m, sel
return m.group(1)
def test_미연결_배경_테두리_경고색_글자색_없음():
body = _rule(".b05-structure__summary-name:not(.is-assigned)")
assert re.search(r"border-color:\s*var\(--color-warning\)", body)
assert re.search(r"background:\s*color-mix\([^;]*--color-warning[^;]*--color-surface", body)
assert not re.search(r"(^|[;\s])color:", body)
def test_테마_토큰_밝음_어두움_둘다():
th = open(os.path.join(ROOT, "ui_template", "ui_template_theme.css"), encoding="utf-8").read()
assert len(re.findall(r"--color-warning:\s*#", th)) >= 2
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""PLAN 177-2 — 동물이동형 = 고르기(유 / 무) · 체크박스 꼴(bool) 지움 · 화면 값은 helper_173_7."""
import json
import subprocess
from pathlib import Path
import pytest
HERE = Path(__file__).parent
ROOT = HERE.parents[1]
DESIGN = ROOT / "A00_Common" / "design"
@pytest.fixture(scope="module")
def out() -> dict:
if not (ROOT / "config" / "node_modules").is_dir():
pytest.skip("의존성 미설치")
done = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_173_7_inlet_animal.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
)
assert done.returncode == 0, done.stderr
return json.loads(done.stdout)
def test_체크박스_없음(out: dict) -> None:
assert out["checkbox"] is False
def test_bool_꼴_지움() -> None:
spec = (DESIGN / "design_structure_spec.ts").read_text("utf-8")
form = (DESIGN / "design_structure_form.ts").read_text("utf-8")
pipe = (DESIGN / "design_structure_pipe.ts").read_text("utf-8")
assert '"bool"' not in spec and '"bool"' not in form and '"bool"' not in pipe
assert "createCheckbox" not in form
@@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
"""177-3 B06 횡단 카드 고름 → 종단 측점 세로선 유지(반대 방향도).
못박는 것
- 카드 고름 뒤 리스너의 selectMark(mark) 가 측점선을 끄지 않음 — 일반 · 벽 · 노면공 카드 = 그 카드 선.
- 관 카드 · 관 알약 = 관 측점선 · 카드 풂 = 선 끔.
- 종단 측점선 누름(반대 길)도 같은 리스너 — 누른 선 그대로.
- B05(keepStation 기본값) = 지금 그대로(선 없는 구조물 → 선 끔).
Node 헬퍼 `helper_177_3_station_line_keep.cjs` 가 진짜 design_profile.ts 본문을 돌림. 화면은 사용자 확인.
"""
import json
import os
import subprocess
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
def _read(*parts: str) -> str:
with open(os.path.join(ROOT, *parts), encoding="utf-8") as handle:
return handle.read()
@pytest.fixture(scope="module")
def out():
proc = subprocess.run(
["node", os.path.join(HERE, "helper_177_3_station_line_keep.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_카드_고름은_그_카드_측점선_유지(out):
assert out["plainCard"] == "s40"
assert out["wallCard"] == "s100"
assert out["paveCard"] == "s140"
def test_관은_관_측점선(out):
assert out["pipeCard"] == "irr-80"
assert out["pipeFromPlain"] == "irr-80"
def test_반대_길_종단_측점선_누름도_유지(out):
assert out["profileClick"] == "s200"
assert out["release"] is None
def test_B05_기본_길은_그대로(out):
assert out["b05Wall"] is None
assert out["b05Pipe"] == "irr-80"
assert out["b05Keep"] == "irr-80"
def test_배선():
svp = _read("B06_Section", "B06_Section_UI_Section_View_Profile.ts")
assert "profile?.setSelectedStructure(structureId, true);" in svp
assert "profile.setSelectedStructure(markedId, true);" in svp
cross = _read("A00_Common", "design", "design_view_cross.ts")
assert "sectionView.selectMark(mark, false);" in cross
b05 = _read("A00_Common", "design", "design_view_profile.ts")
assert ", true)" not in "".join(
line for line in b05.splitlines() if "setSelectedStructure(" in line
)
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
"""177-4 B06 노면공 목록 · 알약 고름 = 범위 카드 전부 테두리(박스) · 카드 하나 안 고름.
못박는 것
- 노면공 고름 = 범위 안 카드 전부 `b06-cross-card--span`(다른 구간형과 같음) + 포장층 강조 그대로.
- 카드 하나 고르기(`--selected`) 없음 · 범위 첫 카드로 스크롤만 · 옛 고른 카드는 리스너 없이 풂(폼 · 알약 유지).
- 세션 고름은 노면공 + 스크롤한 카드 측점(B05 로 가도 그 노면공).
Node 헬퍼 `helper_165_pavement_flow.cjs`(진짜 SPN) 결과를 같이 씀. 화면은 사용자 확인.
"""
import json
import os
import re
import subprocess
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
def _read(*parts: str) -> str:
with open(os.path.join(ROOT, *parts), encoding="utf-8") as handle:
return handle.read()
@pytest.fixture(scope="module")
def out():
proc = subprocess.run(
["node", os.path.join(HERE, "helper_165_pavement_flow.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_노면공_고름은_카드_안_고르고_스크롤만(out):
for step, reveal, layer, cards in (
("step1", "reveal1", "pave", 12),
("step4", "reveal4", "pave", 12),
("step6", "reveal6", "pave2", 6),
):
snap = out[step]
assert snap["card"] is None # --selected 0
assert snap["form"] == layer and snap["pill"] == layer # 폼 · 알약 유지
assert snap["paveCards"] == cards # 범위 카드 전부
assert out[reveal] in ("s40", "s100")
assert out["pick1"] == {"chainageM": 40, "structureId": "pave"}
def test_범위_카드_테두리는_노면공도():
view = _read("B06_Section", "B06_Section_UI_Section_View.ts")
assert 'card.classList.toggle("b06-cross-card--span", span);' in view
assert "highlightPavement(card, pave ? mark : undefined);" in view
def test_스크롤만_길은_리스너를_안_거침():
view = _read("B06_Section", "B06_Section_UI_Section_View.ts")
body = re.search(r"revealStation\(stationId\) \{(.*?)\n \},", view, re.S)
assert body, "revealStation 없음"
text = body.group(1)
assert "selectedStationId = null;" in text
assert "profile.showCard(null);" in text
assert 'revealCard(stationId, "smooth");' in text
assert "stationSelectListener" not in text # 폼을 닫지 않음
cross = _read("A00_Common", "design", "design_view_cross.ts")
assert "if (revealOnly) sectionView.revealStation(nearest.station_id);" in cross
panel = _read("B06_Section", "B06_Section_UI_Page_Structures_Panel.ts")
assert "const pave = !coverable(structure);" in panel
assert 'if (pave) selectDesign(deps.projectId, at, { from: "b06" });' in panel
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
"""177-5 좌측 폼 「측점 범위」 줄 — 사면안정군(C군)만 숨김.
못박는 것
- PNL5 `syncRangeDisplay` 가 C군이면 `rangeWrap.hidden` · 다른 구간형(B 소단배수로 · E 대피소 등)은 그대로.
- `hasComputedRange` 자체는 그대로(시작 · 종료 칸 숨김에도 씀).
- C군 = 사면안정 6종(정의 기준) · 그 밖 범위 종류는 C 가 아님.
화면은 사용자 확인.
"""
import os
from B05_Profile.B05_Profile_Structures_Schema import load_structure_types
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
def _read(*parts: str) -> str:
with open(os.path.join(ROOT, *parts), encoding="utf-8") as handle:
return handle.read()
def test_범위_줄은_C군만_숨김():
panel = _read("B05_Profile", "B05_Profile_UI_Structures_Panel.ts")
at = panel.index("function syncRangeDisplay(): void {")
body = panel[at : panel.index("\n }", at)]
assert (
'const computed = hasComputedRange(currentType()) && currentType()?.group !== "C";' in body
)
assert "rangeWrap.hidden = !computed;" in body
def test_hasComputedRange_는_그대로():
types = _read("B05_Profile", "B05_Profile_UI_Structures_Panel_Types.ts")
assert "export function hasComputedRange(" in types
assert '"C"' not in types[types.index("export function hasComputedRange(") :][:600]
def test_C군은_사면안정_6종_다른_범위_종류는_C_아님():
groups = {t.type_id: t.group for t in load_structure_types()}
slope = {
"retaining_wall",
"masonry_wet",
"masonry_dry",
"soil_guard",
"boulder_masonry",
"berm",
}
assert {k for k, g in groups.items() if g == "C"} == slope
for kept in ("ditch_berm", "refuge", "work_yard", "guardrail"):
assert groups.get(kept) not in (None, "C"), kept
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
"""PLAN 179-1 — 선 길이 정보창 = 열 수 무관 늘 줌 [+ − ⤢] 왼쪽(좁은 카드 내림 규칙 지움 · 소스 시험)."""
import os
import re
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def _src(rel: str) -> str:
return open(os.path.join(ROOT, rel), encoding="utf-8").read()
def test_좁은_카드_내림_규칙_없음():
css = _src("B06_Section/B06_Section_UI_Style_Cross_Controls.css")
assert "@container" not in css
# 치수 칸 규칙은 기본 꼴 · 숨김(+ 옆 단추) 뿐 — 절대 자리 · 왼선 지움 규칙 없음
assert re.findall(r"\.b06-cross-card__line-dims[^{,;]*\{", css) == [
".b06-cross-card__line-dims {",
".b06-cross-card__line-dims[hidden] {",
".b06-cross-card__line-dims[hidden] + .b06-cross-card__zoom-btn {",
]
def test_치수_칸은_줌_막대_맨_앞():
view = _src("B06_Section/B06_Section_UI_Cross_View.ts")
assert "zoomBar.prepend(linePick.label);" in view
zoom = (
_src("B06_Section/B06_Section_UI_Style_Cross_Controls.css")
.split(".b06-cross-card__zoom {", 1)[1]
.split("}", 1)[0]
)
assert "display: flex;" in zoom and "position: absolute;" in zoom
@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
"""PLAN 179-2 — 측구 줄 컴팩트(W16 (가)): 막힌 단추 숨김 · 「측구형식」 글 지움(툴팁) · 알약에 편측 쪽(소스 시험)."""
import os
import re
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def _src(rel: str) -> str:
return open(os.path.join(ROOT, rel), encoding="utf-8").read()
def test_막힌_묶음은_숨김():
css = _src("B06_Section/B06_Section_UI_Style_Cross.css")
body = re.search(r"\.b06-design__seg--disabled\s*\{([^}]*)\}", css).group(1)
assert "display: none;" in body
assert "opacity" not in body
def test_측구형식_글_없이_툴팁():
cd = _src("B06_Section/B06_Section_UI_Cross_Design.ts")
seg = cd.split("const ditchTypeSeg = segment(", 1)[1].split(");", 1)[0]
assert seg.lstrip().startswith('"",')
assert 'ditchTypeSeg.title = L("B06_Design_DitchType_Legend");' in cd
def test_넘침_셈은_숨긴_칸_폭_간격_뺌():
cd = _src("B06_Section/B06_Section_UI_Cross_Design.ts")
assert "overflow -= width ? width + barGapPx : 0;" in cd
def test_알약에_편측_쪽():
lb = _src("ui_template/ui_template_locale_b2.ts")
assert 'B06_Design_Mode_LeftCut: ["편측 성토(좌 절토)"' in lb
assert 'B06_Design_Mode_RightCut: ["편측 성토(우 절토)"' in lb
@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
"""180-2 B07 횡단 장 — 표 · 표 위 글 배율(모든 장 한 값 · 0.5~2.0 · 기본 1).
못박는 것
- 배율 1.5 = 표 폭 162 · 높이 60 · 글 줄 높이 × 1.5 · 표 아래선은 칸 아래 + 여백 그대로.
- 그림 아래 끝 = 글(없으면 표) 위 8 mm(간격은 배율 안 탐) · 넓은 표가 칸을 넘으면 overflow_cells.
- 배율 1 = 배율 칸 없는 배치와 같은 엔티티.
- cross_layout.json 이 배율을 지킴 · 범위 밖 = 거절 · 배율만 바꾸면 확정 장 안 풂.
- 지금과 다른 배율로 확정된 장 = 그대로 + stale_scale 안내.
"""
import json
from pathlib import Path
import pytest
from B07_DesignDetail.B07_DesignDetail_Engine_Cad import DRAWING_FORMAT, GROUND_LAYER_ID
from B07_DesignDetail.B07_DesignDetail_Engine_Cad_Sheet import (
CELL_TABLE_PAD_MM,
build_cross_sheet,
plan_cross_sheets,
)
from B07_DesignDetail.B07_DesignDetail_Engine_Template import (
entities_bbox,
usable_area,
use_project_templates,
)
from B07_DesignDetail.B07_DesignDetail_Router_Support import (
CROSS_SHEET_LAYOUT,
_cross_sheet_plan,
_read_drawing,
_read_manifest,
_write_manifest,
read_cross_layout,
write_cross_layout,
)
NOTE = {"structure_note": "L형 측구\n집수정 보강"}
def _source(chainage: float, lo: int = -5, hi: int = 5) -> dict:
return {
"chainage_m": chainage,
"samples": [
{"valid": True, "offset_m": float(x), "elevation_m": 100.0 + 0.05 * x}
for x in range(lo, hi + 1)
],
}
def _drawing(layout: dict, designs: list[dict | None]) -> tuple[dict, dict]:
use_project_templates(None)
sources = [_source(i * 20.0) for i in range(len(designs))]
sheet = plan_cross_sheets([s["chainage_m"] for s in sources], layout)[0]
sections = [
{
"chainage": s["chainage_m"],
"source": s,
"design": design,
"quantity_table": {"ground": 1.0, "planned": 0.5},
"title": "No.0",
}
for s, design in zip(sources, designs, strict=True)
]
return sheet, build_cross_sheet(sheet, sections)
def _tables(drawing: dict) -> list[dict]:
return [e for e in drawing["entities"] if e["type"] == "Table"]
def test_배율_15_표_크기와_쌓기() -> None:
sheet, drawing = _drawing({"default": [2, 2], "table_scale": 1.5}, [NOTE, None])
assert sheet["table_scale"] == 1.5
_w, h = usable_area()
tables = _tables(drawing)
for table, slot in zip(tables, sheet["slots"], strict=True):
shape = table["shapeData"]
assert sum(shape["columnWidths"]) == pytest.approx(162.0)
assert sum(shape["rowHeights"]) == pytest.approx(60.0)
bottom = shape["origin"]["y"] - sum(shape["rowHeights"])
assert bottom == pytest.approx(slot[1] - h / 4 + CELL_TABLE_PAD_MM) # 표 아래선 그대로
grounds = [
entities_bbox([e]) for e in drawing["entities"] if e.get("layerId") == GROUND_LAYER_ID
]
# 글 2 줄 × 3.0 × 1.5 = 9 mm · 간격 8 mm 는 배율 안 탐
tops = [t["shapeData"]["origin"]["y"] for t in tables]
assert grounds[0][1] == pytest.approx(tops[0] + 9.0 + 8.0)
assert grounds[1][1] == pytest.approx(tops[1] + 8.0)
def test_배율_1_은_지금과_같음() -> None:
_s, plain = _drawing({"default": [2, 2]}, [NOTE, None])
_s, one = _drawing({"default": [2, 2], "table_scale": 1.0}, [NOTE, None])
assert one["entities"] == plain["entities"]
assert sum(_tables(one)[0]["shapeData"]["columnWidths"]) == pytest.approx(108.0)
def test_넓은_표_넘침() -> None:
w, _h = usable_area()
# 4 × 4 칸 폭 192.5 — 표 108 × 2.0 = 216 이 칸을 넘음
_s, drawing = _drawing({"default": [4, 4], "table_scale": 2.0}, [None])
assert w / 4 < 216.0
assert len(drawing["overflow_cells"]) == 1
_s, drawing = _drawing({"default": [4, 4], "table_scale": 1.0}, [None])
assert drawing["overflow_cells"] == []
def _project(tmp_path: Path, count: int) -> tuple[Path, Path]:
root = tmp_path / "project"
cross_dir = root / "B06_Section" / "cross_sections"
cross_dir.mkdir(parents=True)
longitudinal_path = root / "B06_Section" / "longitudinal" / "longitudinal.json"
longitudinal_path.parent.mkdir(parents=True)
stations = []
for i in range(count):
chainage = i * 20
stations.append({"chainage_m": float(chainage), "center_x": 0.0, "center_y": 0.0})
(cross_dir / f"cross_{chainage:05d}m.json").write_text(
json.dumps(_source(float(chainage))), "utf-8"
)
longitudinal_path.write_text(json.dumps({"stations": stations}), "utf-8")
return root, longitudinal_path
def test_배치_파일_배율_저장_범위(tmp_path: Path) -> None:
root, longitudinal_path = _project(tmp_path, 5)
ids = [s["id"] for s in _cross_sheet_plan(root, longitudinal_path)]
manifest = _read_manifest(root)
manifest["drawings"] = {i: {"confirmed": True} for i in ids}
_write_manifest(root, manifest)
# 배율만 바꿈 — 담긴 측점 그대로라 확정 장 안 풂
assert (
write_cross_layout(root, longitudinal_path, {"default": [4, 4], "table_scale": 1.3}) == []
)
assert read_cross_layout(root)["table_scale"] == 1.3
assert _read_manifest(root)["drawings"][ids[0]]["confirmed"] is True
assert _cross_sheet_plan(root, longitudinal_path)[0]["table_scale"] == 1.3
for bad in (0.4, 2.1, "1.2", True):
with pytest.raises(ValueError):
write_cross_layout(root, longitudinal_path, {"default": [4, 4], "table_scale": bad})
assert read_cross_layout(root)["table_scale"] == 1.3
def test_옛_배율_확정_장_안내(tmp_path: Path) -> None:
stage = tmp_path / "B07_DesignDetail"
(stage / "drawings").mkdir(parents=True)
saved = {"format": DRAWING_FORMAT, "entities": [], "layers": []}
(stage / "drawings" / "cross_s00000m.json").write_text(json.dumps(saved), encoding="utf-8")
entry = {"kind": "cross", "label": "1장", "confirmed": True, "layout": CROSS_SHEET_LAYOUT}
manifest = {"drawings": {"cross_s00000m": entry}}
(stage / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
def read() -> dict:
_k, _l, drawing, confirmed, _t = _read_drawing(
tmp_path, tmp_path / "x.json", "cross_s00000m"
)
assert confirmed
return drawing
assert "stale_scale" not in read() # 배율 적힘 없음 = 1 · 지금도 1
(stage / "cross_layout.json").write_text(
json.dumps({"default": [4, 4], "sheets": {}, "table_scale": 1.5}), encoding="utf-8"
)
assert read().get("stale_scale") is True
entry["table_scale"] = 1.5
(stage / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
assert "stale_scale" not in read()
@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
"""180-1 B07 횡단 장 — 원지반선 고르기 · 측점 한 벌 groupId.
못박는 것
- 횡단 장 · 측점 한 장의 원지반 층은 안 잠김(종단은 그대로 잠김).
- 측점마다 groupId 하나(원지반 · 계획선 · 표 · 글 전부) · 측점끼리 다름.
- 칸 격자선 · 도각엔 groupId 없음.
- cross_placements 의 group_id = 그 측점 엔티티 값(화면 덧그림이 같은 묶음).
"""
from B07_DesignDetail.B07_DesignDetail_Engine_Cad import (
FRAME_LAYER_ID,
GROUND_LAYER_ID,
build_cross_drawing,
)
from B07_DesignDetail.B07_DesignDetail_Engine_Cad_Sheet import (
build_cross_sheet,
plan_cross_sheets,
)
from B07_DesignDetail.B07_DesignDetail_Engine_Template import use_project_templates
def _source(chainage: float) -> dict:
return {
"chainage_m": chainage,
"samples": [
{"valid": True, "offset_m": float(x), "elevation_m": 100.0 + 0.1 * x}
for x in range(-5, 6)
],
}
def _design_line() -> list[dict]:
return [{"offset_m": x, "elevation_m": 100.0} for x in (-3.0, 0.0, 3.0)]
def _drawing() -> dict:
use_project_templates(None)
chainages = [0.0, 20.0, 40.0, 60.0]
sheet = plan_cross_sheets(chainages, {"default": [2, 2]})[0]
sections = [
{
"chainage": c,
"source": _source(c),
"design_line": _design_line(),
"design": {"structure_note": "L형 측구"},
"quantity_table": {"ground": 1.0, "planned": 0.5},
"title": f"No.{int(c // 20)}",
}
for c in chainages
]
return build_cross_sheet(sheet, sections)
def _ground_locked(drawing: dict) -> bool:
return next(layer for layer in drawing["layers"] if layer["id"] == GROUND_LAYER_ID)["isLocked"]
def test_원지반_층_안_잠김() -> None:
assert _ground_locked(_drawing()) is False
single = build_cross_drawing(_source(0.0), "cross_00000m", _design_line(), None, None, "")
assert _ground_locked(single) is False
def test_측점마다_groupId_하나() -> None:
drawing = _drawing()
placements = drawing["cross_placements"]
assert len(placements) == 4
group_ids = [p["group_id"] for p in placements]
assert len(set(group_ids)) == 4 # 측점끼리 다름
grouped = [e for e in drawing["entities"] if "groupId" in e]
assert {e["groupId"] for e in grouped} == set(group_ids)
for group_id in group_ids:
members = [e for e in grouped if e["groupId"] == group_id]
layers = {e["layerId"] for e in members}
types = {e["type"] for e in members}
assert GROUND_LAYER_ID in layers and "Table" in types and "Text" in types
# 격자선 · 도각은 묶지 않음
assert all("groupId" not in e for e in drawing["entities"] if e["layerId"] == FRAME_LAYER_ID)
assert all(e["layerId"] != FRAME_LAYER_ID for e in grouped)
def test_groupId_결정적() -> None:
first = [p["group_id"] for p in _drawing()["cross_placements"]]
assert first == [p["group_id"] for p in _drawing()["cross_placements"]]
@@ -0,0 +1,104 @@
"""181-1 B09 탭 두 층 — 위 탭 10 · 아래 탭 묶음(사용자 30번) · 줄 그리기 · 마지막 본 아래 탭.
- 위 탭 = `TAB_GROUPS`(`TABS` 19 키를 빠짐 · 겹침 없이 묶음) · `TABS`(엑셀 차례)는 그대로
- 줄 = 위 md · 아래 sm · 아래 탭 없는 위 탭 = 빈 보조 줄(B08 꼴)
"""
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from resources.tester.helper_b09_group_cards import TABS, run # noqa: E402
BAR = "B09_Estimation/B09_Estimation_UI_TabBar.ts"
# 사용자 30번 — 위 탭 차례 = 지금 탭 차례(묶음 첫 자리) · 아래 = 글에 적힌 차례
EXPECTED = [
["연결 점검", ["check"]],
["공사원가계산서", ["cost"]],
["총괄설계내역서", ["total"]],
["설계내역서", ["bill"]],
["일위대가", ["dg_list", "dg"]],
["단가산출", ["sg_list", "sg"]],
["환율및기초자료", ["basis"]],
["중기", ["machine", "machine_blocks", "sum_machine", "expense", "sum_expense"]],
["재료", ["material", "compare", "sum_material"]],
["노무", ["labor", "sum_labor"]],
]
def test_묶음_표_사용자_30번과_같고_19_탭이_한_번씩():
out = run(
[TABS],
"\nconsole.log(JSON.stringify({ groups: TAB_GROUPS, ids: TABS.map(([t]) => t),"
" of: TABS.map(([t]) => groupOf(t)[0]) }));",
)
assert out["groups"] == EXPECTED
flat = [t for _, tabs in out["groups"] for t in tabs]
assert sorted(flat) == sorted(out["ids"]) and len(flat) == len(set(flat)) == 19
# 위 탭 차례 = 엑셀 차례에서 묶음이 처음 나오는 자리
firsts = list(dict.fromkeys(out["of"]))
assert firsts == [g[0] for g in EXPECTED]
assert len(firsts) == 10
def test_줄_그리기_두_층_빈_줄_마지막_본_아래_탭():
out = run(
[TABS, BAR],
"""
const picks = [];
const bars = createTabBars((t) => picks.push(t));
const view = () => ({
top: bars.top.children.map((b) => [b.textContent, b.className, b.attrs['aria-selected'],
b.dataset.b09Group, b.dataset.b09Tab ?? null]),
sub: bars.sub.children.map((b) => [b.textContent, b.attrs['aria-selected'], b.dataset.b09Tab ?? null]),
blank: bars.sub.classList.contains('b09-estimation__tabs--blank'),
role: bars.sub.attrs.role,
});
bars.draw('dg');
const a = view();
bars.top.children[4].click(); // 켜진 위 탭 다시 누름 = 아무 일 없음
bars.sub.children[0].click(); // 일위대가목록표
bars.draw('compare'); // 묶음을 넘는 이동 = 위 탭 따라 켜짐
const b = view();
bars.draw('sum_material');
bars.draw('dg');
bars.top.children[8].click(); // 재료 = 마지막 본 아래 탭(재료비수량금액집계표)
bars.top.children[7].click(); // 중기 = 본 적 없음 → 첫 아래 탭
bars.draw('cost');
const c = view();
bars.top.children[0].click(); // 연결 점검 = 단독 위 탭
bars.sub.children[0].click(); // 빈 줄 단추(숨김) = 누름 없음
console.log(JSON.stringify({ a, b, c, picks }));
""",
)
a, b, c = out["a"], out["b"], out["c"]
assert len(a["top"]) == 10 and [t[0] for t in a["top"]][:5] == [
"연결 점검", "공사원가계산서", "총괄설계내역서", "설계내역서", "일위대가"
] # fmt: skip
assert [t[2] for t in a["top"]] == ["false"] * 4 + ["true"] + ["false"] * 5
assert all("ui-btn--ghost" in t[1] for t in a["top"] if t[2] == "false")
assert a["sub"] == [["일위대가목록표", "false", "dg_list"], ["일위대가표", "true", "dg"]]
assert not a["blank"] and a["role"] == "tablist"
assert b["sub"] == [
["재료비목록표", "false", "material"],
["자재단가대비표", "true", "compare"],
["재료비수량금액집계표", "false", "sum_material"],
] # fmt: skip
assert b["top"][8][2] == "true" and b["top"][4][2] == "false"
# 단독 위 탭 — 위 단추가 탭 키도 가짐 · 아래 줄 = 숨긴 단추 한 개
assert c["blank"] and c["role"] == "presentation" and len(c["sub"]) == 1
assert c["top"][1][3] == "cost" and c["top"][1][4] == "cost" and c["top"][4][4] is None
assert out["picks"] == ["dg_list", "sum_material", "machine", "check"]
def test_잇기_쉘이_두_줄을_쓰고_CSS_빈_줄_규칙():
shell = (ROOT / "B09_Estimation" / "B09_Estimation_UI_Shell.ts").read_text("utf-8")
assert "createTabBars((tab) => show(tab))" in shell and "bars.draw(tab);" in shell
assert "body.append(bars.top, bars.sub, panel);" in shell
css = (ROOT / "B09_Estimation" / "B09_Estimation_UI_Page.css").read_text("utf-8")
assert ".b09-estimation__tabs--blank > .ui-btn" in css and "visibility: hidden" in css
@@ -0,0 +1,76 @@
"""181-2 박스보기 — 이름 · 접기 없음 · 목록표에서 고른 호표 = 박스 붉은 외곽선 · 표 보기 = 줄 구간 전체.
- 단추 글 「박스보기」 ↔ 「표로 보기」 · 요약(접기) 보기 지움
- 표 보기 = 고른 호표 줄 구간(키 `|` 앞머리 같은 줄) 모두 `is-pick` · 첫 줄 `is-pick-top` · 끝 줄 `is-pick-end`
- 붉은 색 = `--color-danger`(B06 횡단 카드 고름 꼴)
"""
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from resources.tester.helper_b09_group_cards import COMMON, GROUPS, TABS, run # noqa: E402
ROWS = [ # 호표 A(3줄) · 호표 B(4줄) · 호표 C(1줄)
{"key": "A"}, {"key": "A|1"}, {"key": "A|합계"},
{"key": "B"}, {"key": "B|1"}, {"key": "B|2"}, {"key": "B|총계"},
{"key": "C"},
] # fmt: skip
def test_구간_첫_끝_줄():
out = run(
[COMMON, TABS, GROUPS],
f"\nconst rows = {json.dumps(ROWS)};"
"\nconst show = (focus) => { const r = pickRange(rows, focus);"
" return [r, rows.map((_, i) => pickClass(r, i))]; };"
"\nconsole.log(JSON.stringify({ a: show('A|1'), b: show('B'), c: show('C'),"
" none: show(undefined), unknown: show('Z|1') }));",
)
assert out["a"][0] == [0, 2]
assert out["a"][1] == [
"is-pick is-pick-top", "is-pick", "is-pick is-pick-end", None, None, None, None, None,
] # fmt: skip
assert out["b"][0] == [3, 6]
assert out["b"][1][3:7] == [
"is-pick is-pick-top", "is-pick", "is-pick", "is-pick is-pick-end",
] # fmt: skip
assert out["b"][1][:3] == [None] * 3 # 다른 호표 없음
assert out["c"][0] == [7, 7] and out["c"][1][7] == "is-pick is-pick-top is-pick-end"
assert out["none"] == [None, [None] * 8] and out["unknown"] == [None, [None] * 8]
def test_표_보기_줄_class_넘김():
out = run(
[COMMON, TABS, GROUPS],
f"\nconst spec = {{ columns: [{{ key: 'key' }}], rows: {json.dumps(ROWS)} }};"
"\nlet extra = null;"
"\nconst o = { tab: 'dg', spec, hint: null, focus: 'B|1', goto: () => {}, redraw: () => {},"
" makeTable: (e) => { extra = e; return { root: document.createElement('table'),"
" focusRow: () => {} }; } };"
"\nchosen.set('dg', 'table');"
"\nrenderGroupPanel(o);"
"\nconsole.log(JSON.stringify(spec.rows.map((_, i) => extra(i))));",
)
assert out == (
[None] * 3 + ["is-pick is-pick-top", "is-pick", "is-pick", "is-pick is-pick-end"] + [None]
)
def test_글_접기_없음_CSS_잇기():
groups = (ROOT / GROUPS).read_text("utf-8")
assert '"표로 보기" : "박스보기"' in groups and "호표별 보기" not in groups
common = (ROOT / COMMON).read_text("utf-8")
for gone in ("isSummary", "GROUP_SUMMARY_OVER", "is-closed", "모두 펼침", "모두 접기"):
assert gone not in common
assert 'box?.classList.add("is-pick")' in common
page = (ROOT / "B09_Estimation" / "B09_Estimation_UI_Page.css").read_text("utf-8")
for sel in ("tr.is-pick td", "tr.is-pick.is-pick-top td", "tr.is-pick.is-pick-end td"):
assert sel in page
assert page.count("var(--color-danger)") == 4 # 위 · 아래 · 왼 · 오른 2px
shell = (ROOT / "B09_Estimation" / "B09_Estimation_UI_Shell.ts").read_text("utf-8")
assert "extra?: (index: number) => string | null" in shell
+1 -1
View File
@@ -125,7 +125,7 @@ def test_화면_칸_부품_사용자_줄_로직_줄_같은_칸():
assert "...markCells(mat, on?.mark" in rows and "...markHeads()," in rows
assert "...markCells(" in _src("M02_MasterTemplete_Labor_LogicMats.ts")
detail = _src("M02_MasterTemplete_Labor_Detail.ts")
assert "mark: lib ? undefined : markLogicMat" in detail
assert "mark: markLogicMat," in detail and "lib ? undefined" not in detail # 사전조합도(175-1)
assert "mark: markMat" in detail
# 서버 허용 값 = 화면 허용 값
api = _src("M02_MasterTemplete_Labor_Api.ts")