feat(b06): 횡단도 바로 반영 — 새로 놓거나 옮긴 관 · 구조물의 횡단 카드를 [저장] 전에 보임 (273-2)

- 서버: 읽기 전용 미리 뜨기 POST /section/preview-stations — 로그인 · 회사 · 프로젝트 권한 그대로 · 한 번에 60곳 · 파일 · DB 안 씀 · 저장과 같은 길(sample_structure_sections · compute_default_designs crosses)
- 화면: 초안이 심는 자리 중 횡단 없는 곳만 묻고 한 번 뜬 자리는 기억(B06_Section_Section_Drafts) · 카드 이름 · 관 그림 얹음 · 늦은 옛 응답 무시 · 배수 재계산이 관경을 정하면 카드 다시 얹음 · B06 관 옮김도 카드 다시
- [저장]은 지금처럼 서버가 같은 계산으로 정본에 씀 — 미리 본 카드와 같은 값
- 알림 글: 횡단도는 바로 보이고 세부 배수유역만 저장 뒤 다시 셈
- 시험: test_273_2 새로 · 177-3 헬퍼에 revealPick 자리 채움

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LLCk2y5xE8YGVgjbTntWsY
This commit is contained in:
2026-10-11 20:48:32 +09:00
co-authored by Claude Opus 5.5
parent 887c89bbf8
commit dfd7427c46
14 changed files with 642 additions and 105 deletions
@@ -22,6 +22,7 @@ let selectedStructureId = null;
const structureIdAtStation = (stationId) => (stationId === "irr-80" ? "pipe-80.17" : null);
const stationIdAtStructure = (structureId) => (structureId === "pipe-80.17" ? "irr-80" : null);
const draw = () => {};
const revealPick = () => {}; // 화면 밖이면 가운데로(273-1) — 이 시험 몫 아님
module.exports = {
line: () => selectedStationId,
${method("setSelectedStation")}
@@ -0,0 +1,113 @@
/* 273-2 초안 측점 — 진짜 `B06_Section_Section_Drafts.ts` + 진짜 측점 규칙(`common_util_structure_station`)을
* 가짜 서버 · 초안으로 돌림. 표준출력 JSON 한 벌.
*/
const fs = require("fs");
const path = require("path");
const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript"));
const ROOT = path.join(__dirname, "..", "..");
function loadTs(file, stubs = {}) {
const js = ts.transpileModule(fs.readFileSync(path.join(ROOT, file), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
new Function("exports", "module", "require", js)(box.exports, box, (name) => {
if (!stubs[name]) throw new Error(`stub 없음: ${name} (${file})`);
return stubs[name];
});
return box.exports;
}
const station = loadTs("common_util/common_util_structure_station.ts");
let draftPipes = null;
const asked = [];
let slow = false;
const types = [
{
type_id: "pipe",
group: "A",
placement: "point",
managed_by: "pipe_points",
name: "배관",
options: [],
},
];
const drafts = loadTs("B06_Section/B06_Section_Section_Drafts.ts", {
"../B04_PreProcess/B04_PreProcess_Api_Fetch": {
fetchDetailPipePoints: async () => ({ pipe_points: [{ chainage_m: 95.38, facility: "pipe" }] }),
},
"../B05_Profile/B05_Profile_Api_Structures": {
fetchStructures: async () => ({ structures: [] }),
fetchStructureTypes: async () => types,
readPendingStructures: () => null,
},
"../B05_Profile/B05_Profile_Api_Pipes_Draft": { readPendingPipes: () => draftPipes },
"@util/common_util_culvert_sets": {
registryDefaults: () => ({ pipe: { pipe_kind: "파형강관", pipe_diameter_mm: 800 } }),
buildCulvertSets: (points) => new Map(points.map((p) => [p.chainage_m, { kind: "pipe" }])),
attachCulvertSets: (sections, sets) => {
for (const [at] of sets) {
const hit = sections.find((s) => Math.abs(s.chainage_m - at) < 0.005);
if (hit) hit.culvert = true;
}
},
},
"../common_util/common_util_structure_station": station,
"./B06_Section_Api_Fetch": {
previewStructureSections: async (_projectId, chainages) => {
asked.push(chainages);
if (slow) await new Promise((resolve) => setTimeout(resolve, 50));
return chainages.map((c) => ({
chainage_m: c,
kind: "irregular",
station_id: `s${c}`,
samples: [],
}));
},
},
});
/** 서버 상세 — 격자 0 · 20 · 40 · 100 + 옛 관 측점 95.38. */
const detailOf = () => ({
cross_sections: [0, 20, 40, 95.38, 100].map((c) => ({
chainage_m: c,
kind: c === 95.38 ? "irregular" : c === 0 ? "bp" : "regular",
station_id: `s${c}`,
samples: [],
})),
});
const chainages = (detail) => detail.cross_sections.map((s) => s.chainage_m);
(async () => {
const out = {};
const detail = detailOf();
draftPipes = [{ chainage_m: 95, facility: "pipe", source: "user" }]; // 95.38 → 95
await drafts.withDraftStations(detail, "P", 1);
const preview = detail.cross_sections.find((s) => s.chainage_m === 95);
out.moved = {
chainages: chainages(detail),
asked: asked.splice(0),
preview: { preview: preview.preview, structure: preview.structure, culvert: preview.culvert },
};
await drafts.withDraftStations(detail, "P", 1);
out.again = { chainages: chainages(detail), asked: asked.splice(0) };
draftPipes = null;
await drafts.withDraftStations(detail, "P", 1);
out.cleared = { chainages: chainages(detail) };
const race = detailOf();
slow = true;
draftPipes = [{ chainage_m: 96, facility: "pipe", source: "user" }];
const first = drafts.withDraftStations(race, "P", 1); // 늦게 끝남
await new Promise((resolve) => setTimeout(resolve, 5));
slow = false;
draftPipes = [{ chainage_m: 120, facility: "pipe", source: "user" }];
await drafts.withDraftStations(race, "P", 1);
await first;
out.race = { chainages: chainages(race) };
process.stdout.write(JSON.stringify(out));
})().catch((error) => {
process.stderr.write(String(error && error.stack ? error.stack : error));
process.exit(1);
});
@@ -0,0 +1,132 @@
"""273-2 B06 횡단도 바로 반영 — 초안 자리 횡단 미리 뜨기(요구 168).
- 미리 뜨기(`sample_structure_sections`)는 파일을 안 쓰고, [저장] 때 정본 쓰기
(`generate_irregular_sections`)와 같은 횡단을 낸다(같은 길 · 화면이 본 값 = 저장 값).
- 기본 설계(`compute_default_designs`)는 파일 대신 받은 횡단으로도 셈.
- 화면 쪽: 옛 자리 숨김 · 새 자리 얹음 · 이름 · 관 그림 · 늦게 끝난 옛 맞춤이 새 것을 안 덮음
(`helper_273_2_preview_stations.cjs`).
"""
from __future__ import annotations
import json
import subprocess
from pathlib import Path
import numpy as np
import pytest
import B05_Profile.B05_Profile_Engine_Sections as sections
from B06_Section.B06_Section_Router_Design import compute_default_designs
from common_util.common_util_drainage_pipes import route_signature
from common_util.common_util_route_geometry import RouteVertex
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
LINE = [[0.0, 0.0, 100.0], [350.0, 0.0, 100.0]]
ROUTE = "B05_Profile/route/route.geojson"
class _Slope:
"""옆으로 기운 지표 — 왼쪽이 높음(상단측 = left)."""
def sample_xy(self, xy):
points = np.asarray(xy, dtype=np.float64).reshape(-1, 2)
return 100.0 + 0.2 * points[:, 1], np.ones(len(points), dtype=bool)
def _write(root: Path, rel: str, data) -> None:
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
def _project(root: Path) -> None:
_write(root, ROUTE, {"geometry": {"type": "LineString", "coordinates": LINE}})
vertices = [RouteVertex(x=p[0], y=p[1], z=p[2], chainage_m=0.0) for p in LINE]
_write(
root,
"B04_PreProcess/drainage/edits/pipe_points.json",
{"route_signature": route_signature(vertices), "points": []},
)
def _files(root: Path) -> list[str]:
return sorted(str(p.relative_to(root)) for p in root.rglob("*") if p.is_file())
def test_미리_뜨기는_안_쓰고_저장과_같은_횡단(tmp_path: Path, monkeypatch) -> None:
_project(tmp_path)
monkeypatch.setattr(sections, "build_surface_sampler", lambda *_a, **_k: _Slope())
before = _files(tmp_path)
stations, crosses = sections.sample_structure_sections(
tmp_path, ROUTE, "csf", "tin", False, extra_stations=((130.0, ""),)
)
assert _files(tmp_path) == before # 파일 · 폴더 하나도 안 생김
assert [c["chainage_m"] for c in crosses] == [130.0] and len(stations) == 1
sections.generate_irregular_sections(
tmp_path, ROUTE, "csf", "tin", False, extra_stations=((130.0, "파형강관 D800"),)
)
written = json.loads(
(tmp_path / "B06_Section/cross_sections/cross_00130m.json").read_text(encoding="utf-8")
)
assert written["samples"] == crosses[0]["samples"]
assert written["frame"] == crosses[0]["frame"]
def test_기본_설계는_받은_횡단으로도_셈(tmp_path: Path) -> None:
rel = "B06_Section/longitudinal/longitudinal.json"
plan = [{"chainage_m": c, "elevation_m": 851.0} for c in (0.0, 1000.0)]
_write(tmp_path, rel, {"stations": [], "design_profiles": [{"samples": plan}]})
offsets = np.arange(-20.0, 20.5, 0.5)
cross = {
"chainage_m": 610.0,
"uphill_side": "right",
"samples": [
{"offset_m": float(o), "elevation_m": 852.0 - 0.1 * float(o), "valid": True}
for o in offsets
],
}
designs = compute_default_designs(tmp_path, rel, [610.0], crosses={610.0: cross})
assert [chainage for chainage, _ in designs] == [610.0]
design = designs[0][1]
assert design["status"] == "provisional" and design.get("section_mode")
# 파일에도 없고 받은 횡단에도 없는 자리는 건너뜀
assert compute_default_designs(tmp_path, rel, [611.0], crosses={610.0: cross}) == []
@pytest.fixture(scope="module")
def ts() -> dict:
if not (ROOT / "config" / "node_modules" / "typescript").is_dir():
pytest.skip("프론트엔드 의존성 미설치")
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_273_2_preview_stations.cjs")],
capture_output=True,
text=True,
encoding="utf-8",
cwd=str(ROOT),
check=False,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_화면_옛_자리_숨기고_새_자리_얹음(ts) -> None:
assert ts["moved"]["chainages"] == [0, 20, 40, 95, 100] # 옛 95.38 숨김 · 새 95 미리 뜬 것
assert ts["moved"]["asked"] == [[95]]
card = ts["moved"]["preview"]
assert card["preview"] is True and card["structure"] == "파형강관 D800"
assert card["culvert"] is True # 관 그림(세트)도 얹힘
def test_한_번_뜬_자리는_다시_안_물음(ts) -> None:
assert ts["again"]["asked"] == []
assert ts["again"]["chainages"] == [0, 20, 40, 95, 100]
def test_초안이_없으면_서버_목록_그대로(ts) -> None:
assert ts["cleared"]["chainages"] == [0, 20, 40, 95.38, 100]
def test_늦게_끝난_옛_맞춤이_새_것을_안_덮음(ts) -> None:
assert ts["race"]["chainages"] == [0, 20, 40, 100, 120]