diff --git a/A00_Common/design/design_pipeline_page.ts b/A00_Common/design/design_pipeline_page.ts index e49271760..d5dbe7cd8 100644 --- a/A00_Common/design/design_pipeline_page.ts +++ b/A00_Common/design/design_pipeline_page.ts @@ -16,6 +16,7 @@ * 출력 — 가게 stations · profile · footprint · generation · 노선 초안이 있으면 종단도가 새 첫 계획선 · * 옮긴 계획고 · 새 노선 상세(`pipelineDetail` — 지반 · 측점 · 횡단 면적 → 유토곡선)를 그림. * 첫 계산 = 열 때 한 번(저장 노선 · 발자국 · 저장 안 한 노선 초안이 있으면 그 노선). + * 노선 초안을 버리면(되돌리기 · [저장 전으로]) 열 때처럼 — 측점 · 종단을 안 내고 초안 전 상세 그대로(349-0k). * [저장](sub5)이 서버 정본 — 노선을 먼저 보내고 `pendingAlignment(DRAFT_ROUTE_ID)` 를 새 노선에 보냄. * ========================================================================== */ @@ -25,6 +26,7 @@ import { createStationsStage } from "./logic/design_pipeline_stations"; import type { FollowPatch, PipelineInputs, + PipelineOutputs, PipelineStation, RouteDraft, StageFn, @@ -120,6 +122,12 @@ export interface PagePipelineOptions { /** 노선 조작 뒤 follow 가 가게 관 · 구조물을 다시 씀(목록 · 알약 다시) — `far` = 새 노선에서 * `STRUCTURE_ROUTE_DRIFT_MAX_M` 넘게 먼 구조물 수(초안을 버려 되돌렸으면 0). */ onFacilitiesFollowed?: (far: number) => void; + /** 노선 초안을 버림(349-0k) — 초안 전 상세(`saved` · 없으면 null)로 되돌림 · `stations` = 저장 노선 측점. */ + onDraftDropped?: ( + routeId: number, + saved: SectionDetailResponse | null, + stations: PipelineStation[], + ) => void; } interface PagePipeline { @@ -212,6 +220,11 @@ function createPagePipeline( let disposed = false; /** 열 때 · 정본이 바뀐 차례(start) 번호 — 측점 · 종단을 가게에 안 냄(상세 = 저장 정본 그대로). */ let openGeneration = -1; + /** 측점 · 종단을 가게에 안 내는 차례 — 열 때 · 노선 초안을 버린 차례(상세 = 초안 전 상세로 되돌림). */ + let quietGeneration = -1; + /** 노선 초안 전 상세(종단도가 그리던 것) — 초안을 버리면 이것으로(다시 셈 없음 · 349-0k). */ + let restoreTo: SectionDetailResponse | null = null; + let restoring = false; /** 노선 초안 전 가게 관 · 구조물 — 초안 동안 follow 가 새 측점을 가게에 씀 · 초안을 버리면 이것으로. */ let beforeDraft: Facilities | null = null; /** 묶음이 가게에 마지막으로 쓴 관 · 구조물 · 쓰는 동안(메아리 — 다시 입력으로 안 받음). */ @@ -295,7 +308,19 @@ function createPagePipeline( const publish = publishToStore(store); pipe.subscribe((event) => { const saved = event.kind === "stage" && (event.stage === "ground" || event.stage === "profile"); - if (!(saved && event.generation === openGeneration)) publish(event); + if (!(saved && event.generation === quietGeneration)) publish(event); + }); + // 노선 초안을 버린 차례 — 저장 노선 측점이 나오면 초안 전 상세로 되돌림(열 때와 같은 길) + pipe.subscribe((event) => { + if (event.kind !== "stage" || event.stage !== "ground") return; + if (!restoring || event.generation !== quietGeneration) return; + restoring = false; + const routeId = canon?.routeId; + const stations = (event.value as PipelineOutputs["ground"] | null)?.stations ?? []; + const saved = restoreTo; + restoreTo = null; + if (typeof routeId === "number" && stations.length) + queueMicrotask(() => options.onDraftDropped?.(routeId, saved, stations)); }); // 사용자 노선 조작 뒤 follow 가 다시 매긴 관 · 구조물 = 가게(목록 · 알약 · 횡단 보기가 바로 새 측점) · // 초안을 버리면 초안 전 값 · 열 때(start 차례)는 안 씀 — 알림 밖(틱 뒤)에서 씀(쓰기 고리 막음과 안 부딪힘) @@ -384,8 +409,10 @@ function createPagePipeline( if (disposed || !ready || !savedSource().base) return; canonChanged(); started = true; + restoreTo = null; + restoring = false; void pipe.start(inputsNow()); - openGeneration = pipe.generation; + openGeneration = quietGeneration = pipe.generation; }; /** 저장 노선(그린 선 · 곡선표 · 기본 반경) · 그 측점 열쇠 — [저장] 뒤 다시 받음(`restart`). */ @@ -440,11 +467,15 @@ function createPagePipeline( draft = { ...edit, rev: (stored?.rev ?? 0) + 1, terrain: analysisTerrain(projectId) }; if (stored && same({ ...stored, rev: 0 }, { ...draft, rev: 0 })) draft = stored; } + if (draft && !stored && !restoring) restoreTo = savedSource().detail ?? null; store.set("routeDraft", draft); if (!started) return start(); const before = pipe.output("route")?.line ?? null; const after = draft ? draftLine(draft, plan?.min_radius_m ?? 0).line : savedLine(); + const generation = pipe.generation; void pipe.update("route", draft, routeRange(before, after)); + restoring = !draft && !!stored && pipe.generation !== generation; + if (restoring) quietGeneration = pipe.generation; }, }; diff --git a/A00_Common/design/design_view_profile.ts b/A00_Common/design/design_view_profile.ts index a28ad3914..27de2179b 100644 --- a/A00_Common/design/design_view_profile.ts +++ b/A00_Common/design/design_view_profile.ts @@ -48,7 +48,11 @@ import { rememberStandardDefaults, } from "../../B06_Section/B06_Section_UI_Standard_Panel"; import { fetchSectionContext } from "../../B06_Section/B06_Section_Api_Fetch"; -import { invalidateSectionDetail } from "../../B06_Section/B06_Section_Section_Store"; +import { + invalidateSectionDetail, + restoreSectionDetail, + swapSectionStations, +} from "../../B06_Section/B06_Section_Section_Store"; import { onStaleStructureTypes, structureAnchorM, @@ -524,6 +528,14 @@ export async function mountProfileView( stationIntervalM: panel.values().stationInterval ?? undefined, onCorridorStale: () => sections.setCorridorPending(true), onFacilitiesFollowed: followFacilities, + // 초안을 버림 — 초안 전 상세 그대로(349-0k) · 그 상세가 없거나(초안 둔 채 새로고침) 측점이 다르면 갈아끼움 + onDraftDropped: (routeId, saved, stations) => + void (async () => { + const back = + saved && (await restoreSectionDetail(activeProjectId, routeId, saved, stations)); + if (!saved || (back && !back.same)) + await swapSectionStations(activeProjectId, routeId, stations); + })(), }), }); diff --git a/B06_Section/B06_Section_Section_Store.ts b/B06_Section/B06_Section_Section_Store.ts index 036b73f39..749b1977c 100644 --- a/B06_Section/B06_Section_Section_Store.ts +++ b/B06_Section/B06_Section_Section_Store.ts @@ -35,6 +35,7 @@ import { carryStationKeys, registeredKeys, stationIntervalOf, + stationKeysOf, useStationKeyList, } from "./B06_Section_Station_Keys"; import { sameStationList, swapCrossSections } from "./logic/B06_Section_Station_Swap"; @@ -160,6 +161,51 @@ export async function swapSectionStations( return { detail: swap.detail, moves: swap.moves }; } +/** + * 노선 초안을 버림(PLAN 349-0k) — 갈아끼운 상세를 초안 전 상세(`saved` · 열 때 받은 저장 정본 객체)로 되돌림 · + * 다시 셈 없음. 측점 열쇠 = 묶음 저장 노선 측점(`stations` · 목록이 같을 때) · 세션 고침 · 조작값 맵은 열쇠로 + * 넘김(갈아끼움 길 그대로). 이미 그 상세면 null · `same` = 묶음 측점 목록이 그 상세와 같음(1 mm). + */ +export async function restoreSectionDetail( + projectId: string, + routeId: number, + saved: SectionDetailResponse, + stations: ReadonlyArray, +): Promise<{ detail: SectionDetailResponse; same: boolean } | null> { + const key = keyOf(projectId, routeId); + const current = cache.get(key); + if (!current || current === saved) return null; + const sections = saved.cross_sections; + const same = + sections.length === stations.length && + stations.every((station, i) => Math.abs(station.chainageM - sections[i].chainage_m) < 1e-3); + const nextKeys = same + ? stations.map((station, i) => ({ key: station.key, chainageM: sections[i].chainage_m })) + : stationKeysOf(projectId, sections, stationIntervalOf(saved)); + const oldKeys = registeredKeys( + projectId, + routeId, + current.cross_sections, + stationIntervalOf(current), + ); + const text = (chainageM: number) => chainageM.toFixed(2); + const moves = new Map(); + current.cross_sections.forEach((section, i) => { + const to = nextKeys.find((entry) => entry.key === oldKeys[i]); + if (to && text(to.chainageM) !== text(section.chainage_m)) + moves.set(text(section.chainage_m), text(to.chainageM)); + }); + carryStationKeys(projectId, routeId, nextKeys); + cache.set(key, saved); + writeState("section-detail", saved, projectId, routeId); + await withDraftShapes(saved, projectId); + withStructureAreas(saved); + if (cache.get(key) !== saved) return null; // 그 사이 다른 갈아끼움 · 새로 받음 + emitSwap(saved, moves); + listeners.get(key)?.forEach((fn) => fn(saved, moves)); + return { detail: saved, same }; +} + /** * 캐시를 비운다. routeId를 생략하면 그 프로젝트 전부 — * 서버 쪽 정본이 바뀌었는데 새 상세를 손에 못 쥔 조작(계획선 편집 저장 등) 뒤에 쓴다. diff --git a/resources/tester/helper_349_0k_undo_saved.cjs b/resources/tester/helper_349_0k_undo_saved.cjs new file mode 100644 index 000000000..132b0786f --- /dev/null +++ b/resources/tester/helper_349_0k_undo_saved.cjs @@ -0,0 +1,272 @@ +/* PLAN 349-0k sub7 헬퍼 — 열기 → 노선 꼭짓점 끌기 → 되돌리기(초안 버림)면 상세 = 열 때 저장 정본 그대로. + * 진짜 TS(`design_pipeline_page` · 단계 파일 · 상세 가게 `B06_Section_Section_Store`)를 트랜스파일해 Node 로 · + * 서버 창구만 가짜. 종단 보기 고리 흉내 = `design_view_profile_sections.followSwap`(가게 stations → 갈아끼움 · + * 새 상세 → render) · `design_view_profile` 의 `onDraftDropped`(되돌림) 그대로. 초안 동안 갈아끼운 횡단은 + * 브라우저 다시 셈 흉내로 면적을 바꿔 둠(옛 길이면 되돌린 뒤 그 값이 남음). + * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0k_undo_saved.py`. */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); +const CATALOG = require("./helper_322_catalog_module.cjs"); + +const ROOT = path.join(__dirname, "..", ".."); +const job = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); + +function memoryStorage() { + const map = new Map(); + return { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => map.set(key, String(value)), + removeItem: (key) => map.delete(key), + key: (index) => [...map.keys()][index] ?? null, + get length() { + return map.size; + }, + }; +} +globalThis.window = { + sessionStorage: memoryStorage(), + localStorage: memoryStorage(), + setTimeout, + clearTimeout, +}; + +// 흙 배분 서버 — 늦게 답함 · 끊기면 버림 +globalThis.fetch = (url, init) => + new Promise((resolve, reject) => { + const timer = setTimeout( + () => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }), + 20, + ); + init.signal.addEventListener("abort", () => { + clearTimeout(timer); + reject(new Error("aborted")); + }); + }); + +const STUBS = {}; +const cache = new Map(); +function loadTs(full) { + 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 (CATALOG.isCatalogRequest(request)) return CATALOG; + const key = Object.keys(STUBS).find((name) => request.endsWith(name)); + if (key) return STUBS[key]; + if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" }; + if (request.startsWith("@ui/")) return { showToast: () => undefined }; + if (request.endsWith(".css")) return {}; + if (request.endsWith(".json")) return require(path.join(path.dirname(full), request)); + if (request.startsWith("@util/")) + return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`)); + if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`)); + return require(request); + }; + new Function("exports", "module", "require", js)(box.exports, box, localRequire); + return box.exports; +} +const load = (...parts) => loadTs(path.join(ROOT, ...parts)); + +const sampler = load("common_util", "common_util_surface_sampler.ts"); +const bytes = fs.readFileSync(process.argv[3]); +const grid = sampler.parseDtmGrid( + bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), +); +const local = { grid, design: "las" }; + +STUBS["B05_Profile_Api_Replan"] = { + analysisTerrain: () => "las", + fetchRoutePlan: async () => ({ + planned: job.line, + curves: job.curves, + min_radius_m: job.minRadius, + station_snap: job.stationSnap, + }), +}; +STUBS["B05_Profile_Api_Structures"] = { + fetchStructures: async () => ({ structures: [] }), + fetchStructureTypes: async () => job.types, + readPendingStructures: () => null, +}; +STUBS["B05_Profile_Api_TerrainGrid"] = { + loadDesignTerrainGrid: async () => local, + groundStageDeps: () => ({ grid: () => local, remote: async () => [] }), +}; +STUBS["B04_PreProcess_Api_Fetch"] = { + fetchDetailPipePoints: async () => ({ + pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })), + }), +}; +STUBS["B06_Section_UI_Standard_Panel"] = { effectiveStandardCross: () => job.standard }; + +// 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음 +STUBS["B06_Section_Section_Drafts"] = { + withDraftStations: async () => undefined, + withDraftShapes: async () => undefined, + forgetDraftStations: () => undefined, +}; +STUBS["B06_Section_Api_Fetch"] = { + fetchSectionDetail: async () => JSON.parse(JSON.stringify(job.detail)), + saveSections: async () => undefined, +}; + +const pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); +const storeMod = load("A00_Common", "design", "design_store.ts"); +const sectionStore = load("B06_Section", "B06_Section_Section_Store.ts"); +const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); +const massHaul = load("common_util", "common_util_mass_haul.ts"); + +const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); +const runs = () => globalThis.__aisloPipeline?.runs ?? []; +/** 묶음 · 상세 가게가 조용해질 때까지 — 마지막 기록이 끝나고 새 기록이 더 안 생김. */ +async function quiet() { + let seen = -1; + for (let i = 0; i < 400; i += 1) { + await tick(15); + const last = runs()[runs().length - 1]; + const count = runs().length; + if (count === seen && (!last || last.outcome !== "running")) return; + seen = count; + } + throw new Error("묶음이 조용해지지 않음"); +} +const n = job.nodes.length; +const draftOf = (nodes) => ({ + nodes, + curveOn: Array(n).fill(true), + curveRadius: Array(n).fill(null), + curveLock: Array(n).fill(null), + curveArc: Array(n).fill(null), + stationSnap: job.stationSnap, +}); +const shift = (index, dx, dy) => + job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node)); +const sliceRuns = (mark) => + runs() + .slice(mark) + .map((r) => ({ sources: r.sources, outcome: r.outcome })); +const finalOf = (detail) => { + const [series] = massHaul.computeMassHaulSeries( + detail.longitudinal, + detail.cross_sections, + job.conversion, + undefined, + ["cross"], + ); + const points = series?.result.points ?? []; + return points.length ? points[points.length - 1].cumulative_volume_m3 : null; +}; +const crossOf = (detail) => + JSON.stringify(detail.cross_sections.map((s) => [s.chainage_m, s.design, s.samples])); +/** 브라우저 다시 셈 흉내 — 면적 칸(`*_m2`)을 두 배로(카드 · 종단도가 갈아끼운 상세 횡단을 다시 셈). */ +const recompute = (detail) => + detail.cross_sections.forEach((section) => { + if (!section.design) return; + const design = { ...section.design }; + for (const [key, value] of Object.entries(design)) + if (key.endsWith("_m2") && typeof value === "number") design[key] = value * 2; + section.design = design; + }); + +async function run() { + const P = "proj-349k"; + const R = 7; + window.localStorage.setItem("frd_current_project_id", P); + const savedAlignment = job.detail.longitudinal.profile_alignment; + const savedBase = alignment.toAlignmentBase(savedAlignment); + let detail = await sectionStore.loadSectionDetail(P, R); + const opened = detail; + const link = { + pipelineSource: () => ({ base: savedBase, edits: savedAlignment.edits, detail, routeId: R }), + adoptPipeline: (base, edits, draft) => + pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits), + redraw: () => undefined, + side: null, + }; + const swaps = []; + const restores = []; + pageMod.routeDraftBridge(P, link, { + stationIntervalM: job.interval, + // `design_view_profile` 의 onDraftDropped 그대로 + onDraftDropped: (routeId, saved, stations) => + void (async () => { + const back = + saved && (await sectionStore.restoreSectionDetail(P, routeId, saved, stations)); + restores.push({ saved: !!saved, back: back ? { same: back.same } : null }); + if (!saved || (back && !back.same)) + await sectionStore.swapSectionStations(P, routeId, stations); + })(), + }); + // followSwap — 새 상세 → 종단도 render(처음부터 다시 · 비정규 측점) · 가게 stations → 갈아끼움 + const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => { + swaps.push(next.cross_sections.length); + detail = next; + pageMod.restartPagePipeline(P); + pageMod.restartPagePipeline(P); + }); + const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => { + if (stations?.length) void sectionStore.swapSectionStations(P, R, stations); + }); + pageMod.pipelineEarthwork(P, { conversion: job.conversion }); + pageMod.restartPagePipeline(P); + await quiet(); + const open = { + runs: sliceRuns(0), + stations: detail.cross_sections.map((s) => s.chainage_m), + final: finalOf(detail), + cross: crossOf(detail), + same: detail === opened, + }; + + // 노선 꼭짓점 한 번 끌기 — 상세가 새 노선 측점으로 갈아끼워짐 · 그 횡단을 다시 셈 + let mark = runs().length; + const bridge = pageMod.routeDraftBridge(P, link); + bridge.edited(draftOf(shift(1, 6, -4))); + await quiet(); + const cached = await sectionStore.loadSectionDetail(P, R); + recompute(cached); + const drag = { + runs: sliceRuns(mark), + swapped: cached !== opened && detail === cached, + stations: cached.cross_sections.map((s) => s.chainage_m), + final: finalOf(cached), + }; + + // 되돌리기 한 번(초안 버림) + mark = runs().length; + const swapMark = swaps.length; + bridge.edited(null); + await quiet(); + const back = await sectionStore.loadSectionDetail(P, R); + const undo = { + runs: sliceRuns(mark), + restores, + swaps: swaps.length - swapMark, + sameObject: back === opened && detail === opened, + stations: back.cross_sections.map((s) => s.chainage_m), + final: finalOf(back), + cross: crossOf(back), + }; + // 되돌린 뒤 조용함 — 더 안 돎 + mark = runs().length; + await quiet(); + const after = { runs: runs().length - mark, blocked: pageMod.pagePipeline(P).blockedWrites }; + stopListen(); + stopStore(); + pageMod.disposePagePipeline(P); + return { open, drag, undo, after }; +} + +run() + .then((out) => { + process.stdout.write(JSON.stringify(out)); + process.exit(0); + }) + .catch((error) => { + process.stderr.write(String(error && error.stack ? error.stack : error)); + process.exit(1); + }); diff --git a/resources/tester/test_349_0k_undo_saved.py b/resources/tester/test_349_0k_undo_saved.py new file mode 100644 index 000000000..f60a71ec6 --- /dev/null +++ b/resources/tester/test_349_0k_undo_saved.py @@ -0,0 +1,131 @@ +"""PLAN 349-0k sub7 — 되돌리기로 저장 노선에 돌아오면 저장 정본 그대로(다시 셈 없음). + +· 열기 → 노선 꼭짓점 끌기(상세가 새 노선 측점으로 갈아끼워지고 다시 셈) → 되돌리기 한 번 +· 되돌린 뒤 상세 = 열 때 받은 저장 정본 객체 · 측점 · 횡단 · 누가토량 = 열기 값 +· 되돌리기 = 묶음 한 번 · 더 안 돎 +짝: `helper_349_0k_undo_saved.cjs`(실제 TS 를 Node 로 · 서버 창구만 가짜 · 종단 보기 고리 흉내). +""" + +from __future__ import annotations + +import csv +import json +import subprocess +import sys +import tempfile +from pathlib import Path + +import pytest + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from B05_Profile.B05_Profile_Structures_Schema import structure_type_map # noqa: E402 +from common_util.common_util_surface_sampler import dtm_grid_bytes # noqa: E402 +from config.config_system_design import STANDARD_CROSS_SECTION # noqa: E402 + +pytestmark = pytest.mark.skipif( + not (ROOT / "config" / "node_modules" / "typescript").is_dir(), + reason="프론트엔드 의존성 미설치", +) + +PROJECT = ROOT / "storage/1/3/6d3b2812-6d5a-4168-a932-40e4ae303d5a" # 검증_sub7 +ROUTE = PROJECT / "B05_Profile/route" +SECTION = PROJECT / "B06_Section" +GRID = PROJECT / "B04_PreProcess/models/dtm_classification_smooth.npz" +ONES = {g: {"loose": 1.0, "compacted": 1.0} for g in ("soil", "ripping_rock", "blasting_rock")} + + +def _csv(path: Path) -> list[list[float]]: + with path.open(encoding="utf-8") as handle: + return [[float(r["x"]), float(r["y"])] for r in csv.DictReader(handle)] + + +def _json(path: Path): + return json.loads(path.read_text(encoding="utf-8")) + + +@pytest.fixture(scope="module") +def r() -> dict: + if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()): + pytest.skip("검증_sub7 없음") + curves = _json(ROUTE / "planned_route_curves.json") + sections = sorted( + (_json(p) for p in (SECTION / "cross_sections").glob("cross_*.json")), + key=lambda s: s["chainage_m"], + ) + pipes = _json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"] + # 저장 횡단 면적 = 서버가 상세를 낼 때 셈(파일엔 없음) — 정본 대신 정한 값 + for i, section in enumerate(sections): + section["design"] = { + "ground_type": "soil", + "design_elevation_m": section["center_z"], + "cut_area_m2": 4.0 + (i % 5), + "fill_area_m2": 1.5 + (i % 3), + } + job = { + "line": _csv(ROUTE / "planned_route.csv"), + "nodes": _csv(ROUTE / "planned_route_nodes.csv"), + "curves": [ + {k: c[k] for k in ("start", "apex", "end", "radius_m")} for c in curves["curves"] + ], + "stationSnap": bool(curves.get("station_snap")), + "minRadius": curves["min_radius_m"], + "interval": 20.0, + "types": [ + {"type_id": t.type_id, "group": t.group, "placement": t.placement} + for t in structure_type_map().values() + ], + "pipes": pipes, + "standard": STANDARD_CROSS_SECTION, + "conversion": ONES, + "detail": { + "longitudinal": _json(SECTION / "longitudinal/longitudinal.json"), + "cross_sections": sections, + }, + } + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "job.json" + path.write_text(json.dumps(job), encoding="utf-8") + grid = Path(folder) / "grid.bin" + grid.write_bytes(dtm_grid_bytes(GRID)) + proc = subprocess.run( # noqa: S603 — 고정 실행 파일 + ["node", str(HERE / "helper_349_0k_undo_saved.cjs"), str(path), str(grid)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=300, + ) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout) + + +def test_열_때_한_번_저장_정본(r): + o = r["open"] + assert [x["outcome"] for x in o["runs"]] == ["done"], o["runs"] + assert o["same"] + assert o["final"] is not None + + +def test_끌기_새_측점으로_갈아끼움(r): + d = r["drag"] + assert [x["sources"] for x in d["runs"]] == [["route"]], d["runs"] + assert d["swapped"] # 이 시험이 갈아끼움 길을 실제로 거침 + assert d["final"] != r["open"]["final"] + + +def test_되돌리기_열기_값(r): + u, o = r["undo"], r["open"] + assert [x["sources"] for x in u["runs"]] == [["route"]], u["runs"] + assert u["restores"] == [{"saved": True, "back": {"same": True}}] + assert u["sameObject"] + assert u["stations"] == o["stations"] + assert u["cross"] == o["cross"] + assert u["final"] == o["final"] + + +def test_되돌린_뒤_조용함(r): + assert r["after"]["runs"] == 0 + assert r["after"]["blocked"] == 0