diff --git a/A00_Common/design/design_pipeline_page.ts b/A00_Common/design/design_pipeline_page.ts index b341c573f..360673ff9 100644 --- a/A00_Common/design/design_pipeline_page.ts +++ b/A00_Common/design/design_pipeline_page.ts @@ -16,7 +16,8 @@ * 출력 — 가게 stations · profile · footprint · generation · 노선 초안이 있으면 종단도가 새 첫 계획선 · * 옮긴 계획고 · 새 노선 상세(`pipelineDetail` — 지반 · 측점 · 횡단 면적 → 유토곡선)를 그림. * 첫 계산 = 열 때 한 번(저장 노선 · 발자국 · 저장 안 한 노선 초안이 있으면 그 노선). - * 노선 초안을 버리면(되돌리기 · [저장 전으로]) 열 때처럼 — 측점 · 종단을 안 내고 초안 전 상세 그대로(349-0k). + * 노선 초안을 버리면(되돌리기 · [저장 전으로]) 열 때처럼 — 측점 · 종단을 안 내고 초안 시작 때 뜬 상세 사본 · + * 횡단 초안 칸 그대로(349-0k · 349-0o). * [저장](sub5)이 서버 정본 — 노선을 먼저 보내고 `pendingAlignment(DRAFT_ROUTE_ID)` 를 새 노선에 보냄. * ========================================================================== */ @@ -125,13 +126,13 @@ export interface PagePipelineOptions { /** 새 노선 상세에 관 · 구조물 측점 폐회로 면적을 얹음(상세 가게 · 서버와 같은 얹기 · 349-0j) — 화면 * 부품 계산이라 페이지가 넘김(묶음은 안 끌어옴). */ structureAreas?: (detail: SectionDetailResponse) => void; - /** 노선 초안을 버림(349-0k) — 초안 전 상세(`saved` · 없으면 null)로 되돌림 · `stations` = 저장 노선 측점 · - * 돌려주는 값 = 되돌림 길 한 단어(묶음 기록 `restoreWhy`). 끝난 뒤 종단도가 저장 기준으로 돌아옴. */ - onDraftDropped?: ( + /** 노선 초안 시작(349-0o) — 초안 전 상세 사본(`saved` · 없으면 null · 초안 둔 채 새로고침)을 맡김 · 돌려준 + * 함수 = 초안을 버린 차례 끝에 부름(`stations` = 묶음 저장 노선 측점) · 그 값 = 되돌림 길 한 단어(묶음 기록 + * `restoreWhy`). 끝난 뒤 종단도가 저장 기준으로 돌아옴. */ + holdDraft?: ( routeId: number, saved: SectionDetailResponse | null, - stations: PipelineStation[], - ) => Promise; + ) => (stations: PipelineStation[]) => Promise; } interface PagePipeline { @@ -150,6 +151,22 @@ type Facilities = Pick; const pages = new Map(); const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); +/** 상세 측점 대 묶음 측점(1 mm) — 같으면 null · 다르면 첫 다른 자리 · 개수(묶음 기록 `restoreDiff`). */ +function stationDiff( + detail: SectionDetailResponse, + stations: ReadonlyArray, +): NonNullable | null { + const saved = detail.cross_sections.map((section) => section.chainage_m); + const n = Math.max(saved.length, stations.length); + for (let i = 0; i < n; i += 1) { + const pipelineM = stations[i]?.chainageM ?? null; + if (saved[i] !== undefined && pipelineM !== null && Math.abs(saved[i] - pipelineM) < 1e-3) + continue; + return { savedM: saved[i] ?? null, pipelineM, saved: saved.length, pipeline: stations.length }; + } + return null; +} + /** 편집기에 넘길 다리 — 그 프로젝트 묶음을 처음 부를 때 세움. */ export function routeDraftBridge( projectId: string, @@ -226,8 +243,12 @@ function createPagePipeline( let openGeneration = -1; /** 측점 · 종단을 가게에 안 내는 차례 — 열 때 · 노선 초안을 버린 차례(상세 = 초안 전 상세로 되돌림). */ let quietGeneration = -1; - /** 노선 초안 전 상세(종단도가 그리던 것) — 초안을 버리면 이것으로(다시 셈 없음 · 349-0k). */ - let restoreTo: SectionDetailResponse | null = null; + /** 노선 초안 전 상세 사본(종단도가 그리던 것 · 초안 동안 제자리 고침이 안 닿음) · 되돌리는 함수 — 초안을 + * 버리면 이것으로(다시 셈 없음 · 349-0k · 349-0o). */ + let held: { + copy: SectionDetailResponse | null; + restore: ((stations: PipelineStation[]) => Promise) | null; + } | null = null; /** 초안을 버린 차례가 끝나 되돌림까지 마치는 약속(종단도는 그 뒤 저장 기준으로 — 349-0l). */ let dropping: Promise | null = null; /** 노선 초안 전 가게 관 · 구조물 — 초안 동안 follow 가 새 측점을 가게에 씀 · 초안을 버리면 이것으로. */ @@ -316,23 +337,41 @@ function createPagePipeline( const saved = event.kind === "stage" && (event.stage === "ground" || event.stage === "profile"); if (!(saved && event.generation === quietGeneration)) publish(event); }); - /** 노선 초안을 버린 차례 끝 — 저장 노선 측점으로 초안 전 상세에 되돌림(열 때와 같은 길) · 기록에 길 남김. - * 차례 끝에서 판정 — ground 를 건너뛰어도 · 사진첩 되돌리기가 가게 초안을 먼저 비워도(349-0m). */ + /** 노선 초안을 버린 차례 끝 — 초안 전 상세 사본으로 되돌림(열 때와 같은 상태 · 측점이 달라도 · 다른 자리는 + * 기록에) · 그 사본이 저장 정본(다시 하기도 같은 기준). 차례 끝에서 판정 — ground 를 건너뛰어도 · 사진첩 + * 되돌리기가 가게 초안을 먼저 비워도(349-0m). */ const finishDrop = async (record: PipelineRunRecord): Promise => { const routeId = canon?.routeId; const stations = pipe.output("ground")?.stations ?? []; let why: string = record.outcome; // 새 조작에 밀림 · 단계 실패 — 초안 전 상세는 그대로 둠 if (record.outcome === "done") { why = "none"; - if (typeof routeId === "number" && stations.length && options.onDraftDropped) { - const saved = restoreTo; - restoreTo = null; - why = await options.onDraftDropped(routeId, saved, stations).catch(() => "error"); + const hold = held; + const restore = + typeof routeId === "number" && stations.length + ? (hold?.restore ?? options.holdDraft?.(routeId, null)) + : null; + if (restore) { + held = null; + const copy = hold?.copy; + if (copy) { + canon = { routeId, samples: copy.longitudinal.samples, detail: copy }; + const diff = stationDiff(copy, stations); + if (diff) record.restoreDiff = diff; + } + why = await restore(stations).catch(() => "error"); } } - Object.assign(record, { restored: why === "saved" || why === "unchanged", restoreWhy: why }); + Object.assign(record, { restored: why.startsWith("saved"), restoreWhy: why }); return why; }; + /** 노선 초안 시작 — 지금 저장 상세 사본(초안 동안 다시 셈 · 면적 얹기가 안 닿음) · 되돌리는 함수를 맡김. */ + const holdNow = (): typeof held => { + const { detail = null, routeId } = savedSource(); + if (typeof routeId !== "number") return null; + const copy = detail && structuredClone(detail); + return { copy, restore: options.holdDraft?.(routeId, copy) ?? null }; + }; // 사용자 노선 조작 뒤 follow 가 다시 매긴 관 · 구조물 = 가게(목록 · 알약 · 횡단 보기가 바로 새 측점) · // 초안을 버리면 초안 전 값 · 열 때(start 차례)는 안 씀 — 알림 밖(틱 뒤)에서 씀(쓰기 고리 막음과 안 부딪힘) pipe.subscribe((event) => { @@ -429,7 +468,7 @@ function createPagePipeline( if (disposed || !ready || !savedSource().base) return; canonChanged(); started = true; - restoreTo = null; + held = null; dropping = null; void pipe.start(inputsNow()); openGeneration = quietGeneration = pipe.generation; @@ -489,7 +528,7 @@ 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 && !wasDraft) restoreTo ??= savedSource().detail ?? null; + if (draft && !wasDraft && !held) held = holdNow(); store.set("routeDraft", draft); if (!started) return start(); const before = pipe.output("route")?.line ?? null; diff --git a/A00_Common/design/design_view_profile.ts b/A00_Common/design/design_view_profile.ts index debe4fbce..8ce3f71ca 100644 --- a/A00_Common/design/design_view_profile.ts +++ b/A00_Common/design/design_view_profile.ts @@ -53,6 +53,7 @@ import { structureAreaRows, } from "../../B06_Section/B06_Section_Structure_Layouts"; import { + holdSectionDetail, invalidateSectionDetail, restoreSectionDetail, swapSectionStations, @@ -534,14 +535,18 @@ export async function mountProfileView( onFacilitiesFollowed: followFacilities, structureAreas: ({ cross_sections: rows }) => applyStructureAreaRows(rows, structureAreaRows(rows)), - // 초안을 버림 — 초안 전 상세 그대로(349-0k) · 그 상세가 없거나(초안 둔 채 새로고침) 측점이 다르면 갈아끼움 - onDraftDropped: async (routeId, saved, stations) => { - const back = - saved && (await restoreSectionDetail(activeProjectId, routeId, saved, stations)); - if (saved && !back) return "unchanged"; - if (back?.same) return "saved"; - await swapSectionStations(activeProjectId, routeId, stations); - return saved ? "stations" : "no-saved"; + // 초안 시작 — 초안 전 상태를 떠 둠 · 버리면 그대로(측점이 달라도 · 349-0o) · 사본이 없으면(초안 둔 채 + // 새로고침) 묶음 측점으로 갈아끼움 + holdDraft: (routeId, saved) => { + const hold = saved && holdSectionDetail(activeProjectId, routeId, saved); + return async (stations) => { + if (!hold) { + await swapSectionStations(activeProjectId, routeId, stations); + return "no-saved"; + } + const back = await restoreSectionDetail(activeProjectId, routeId, hold, stations); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; }, }), }); diff --git a/A00_Common/design/logic/design_pipeline_types.ts b/A00_Common/design/logic/design_pipeline_types.ts index 49557f657..53abc1a96 100644 --- a/A00_Common/design/logic/design_pipeline_types.ts +++ b/A00_Common/design/logic/design_pipeline_types.ts @@ -278,8 +278,15 @@ export interface PipelineRunRecord { totalMs: number; /** done = 브라우저 단계 끝 · dropped = 새 조작에 밀려 버림 · error = 단계가 던짐. */ outcome: "running" | "done" | "dropped" | "error"; - /** 노선 초안을 버린 차례(349-0l) — 초안 전 상세로 되돌렸나 · 까닭 한 단어(saved · unchanged · stations · - * no-saved · none). */ + /** 노선 초안을 버린 차례(349-0l) — 초안 전 상세로 되돌렸나 · 까닭 한 단어(saved · saved-diff · no-cache · + * no-saved · none · error · dropped). */ restored?: boolean; restoreWhy?: string; + /** 되돌린 상세 측점 ≠ 묶음 저장 노선 측점(349-0o) — 첫 다른 자리(없으면 null) · 개수. 상세는 초안 전 그대로. */ + restoreDiff?: { + savedM: number | null; + pipelineM: number | null; + saved: number; + pipeline: number; + }; } diff --git a/B06_Section/B06_Section_Cross_Refresh.ts b/B06_Section/B06_Section_Cross_Refresh.ts index f1496380d..32a8ad3b5 100644 --- a/B06_Section/B06_Section_Cross_Refresh.ts +++ b/B06_Section/B06_Section_Cross_Refresh.ts @@ -216,6 +216,9 @@ export async function refreshStaleDesigns( * 계획선 ▲ 한 번에 값이 바뀌는 측점은 몇 개뿐 — 전부 돌려주면 카드를 다 갈아 끼워 멈춤(54-22). */ export async function refreshCrossDesigns(input: CrossRefreshInput): Promise { + // 노선 초안 동안 묶음 새 노선 상세(`preview` 측점) = 묶음 cross 결과 그대로 — 브라우저 다시 셈이 다른 값을 + // 안 냄(넓힌 표본 · 화면 선이 다름 · 349-0o) + if (input.detail.cross_sections.some((section) => section.preview)) return []; useStationKeys(input.projectId, input.routeId, input.detail); // 세션 고침을 이 측점 목록으로 읽음(344-3) const sections = input.detail.cross_sections; const before = new Map(sections.map((section) => [section, JSON.stringify(section.design)])); diff --git a/B06_Section/B06_Section_Section_Store.ts b/B06_Section/B06_Section_Section_Store.ts index 749b1977c..dc38b537e 100644 --- a/B06_Section/B06_Section_Section_Store.ts +++ b/B06_Section/B06_Section_Section_Store.ts @@ -33,10 +33,12 @@ import { kindChangedChainages, STRUCTURE_ADJUST_KEYS } from "./B06_Section_Api_C import type { PipelineStation } from "../A00_Common/design/logic/design_pipeline_types"; import { carryStationKeys, + KEYED_STATES, registeredKeys, stationIntervalOf, - stationKeysOf, useStationKeyList, + type Keyed, + type KeyedState, } from "./B06_Section_Station_Keys"; import { sameStationList, swapCrossSections } from "./logic/B06_Section_Station_Swap"; import { emitSwap, type DetailListener } from "./B06_Section_Swap_Bus"; @@ -147,6 +149,9 @@ export async function swapSectionStations( const oldKeys = registeredKeys(projectId, routeId, current.cross_sections, interval); if (sameStationList(current.cross_sections, oldKeys, stations)) return null; const swap = swapCrossSections(current, stations, oldKeys, interval); + // 설계는 사본 — 면적 얹기 · 다시 셈이 앞 상세(초안 전 상세 등)의 설계를 제자리로 안 고침(349-0o) + for (const section of swap.detail.cross_sections) + if (section.design) section.design = { ...section.design }; // 새 목록 열쇠 = 묶음 측점이 정한 것 그대로(규칙 한 벌 · 다시 셈하지 않음) const nextKeys = stations.map((station) => ({ key: station.key, chainageM: station.chainageM })); if (swap.moved) carryStationKeys(projectId, routeId, nextKeys); @@ -161,27 +166,48 @@ export async function swapSectionStations( return { detail: swap.detail, moves: swap.moves }; } +/** 노선 초안 전 상태(349-0o) — 상세(사본 · 되돌리면 그대로 캐시) · 측점 열쇠 · 측점 열쇠 칸 다섯(횡단 초안). */ +export interface SectionHold { + detail: SectionDetailResponse; + keys: Keyed[]; + cells: Array<[KeyedState, unknown]>; +} + +/** 노선 초안 시작 — 초안 전 상세(`detail` = 부르는 쪽이 뜬 사본) · 지금 측점 열쇠 · 횡단 초안 칸을 떠 둠. */ +export function holdSectionDetail( + projectId: string, + routeId: number, + detail: SectionDetailResponse, +): SectionHold { + const sections = detail.cross_sections; + const keys = registeredKeys(projectId, routeId, sections, stationIntervalOf(detail)); + return { + detail, + keys: sections.map((section, i) => ({ key: keys[i], chainageM: section.chainage_m })), + cells: KEYED_STATES.map((name) => [name, readState(name, projectId, routeId)]), + }; +} + /** - * 노선 초안을 버림(PLAN 349-0k) — 갈아끼운 상세를 초안 전 상세(`saved` · 열 때 받은 저장 정본 객체)로 되돌림 · - * 다시 셈 없음. 측점 열쇠 = 묶음 저장 노선 측점(`stations` · 목록이 같을 때) · 세션 고침 · 조작값 맵은 열쇠로 - * 넘김(갈아끼움 길 그대로). 이미 그 상세면 null · `same` = 묶음 측점 목록이 그 상세와 같음(1 mm). + * 노선 초안을 버림(PLAN 349-0k · 349-0o) — 갈아끼운 상세를 초안 전 상태(`hold`)로 되돌림 · 다시 셈 없음. + * 상세 = 초안 시작 때 뜬 사본 · 측점 열쇠 · 횡단 초안 칸 = 그때 값(초안 동안 넘김이 버린 고침도) · 누가거리 + * 열쇠 조작값 맵은 열쇠로 옮김. 묶음 측점(`stations`)이 달라도 초안 전 상세 — `same` = 측점 목록이 같음(1 mm). + * 캐시가 없으면 null. */ export async function restoreSectionDetail( projectId: string, routeId: number, - saved: SectionDetailResponse, + hold: SectionHold, stations: ReadonlyArray, ): Promise<{ detail: SectionDetailResponse; same: boolean } | null> { const key = keyOf(projectId, routeId); const current = cache.get(key); - if (!current || current === saved) return null; + if (!current) return null; + const saved = hold.detail; 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, @@ -191,11 +217,12 @@ export async function restoreSectionDetail( 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]); + const to = hold.keys.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); + for (const [name, value] of hold.cells) writeState(name, value ?? null, projectId, routeId); + useStationKeyList(projectId, routeId, hold.keys); cache.set(key, saved); writeState("section-detail", saved, projectId, routeId); await withDraftShapes(saved, projectId); diff --git a/resources/tester/helper_349_0k_undo_saved.cjs b/resources/tester/helper_349_0k_undo_saved.cjs index 5394f9385..9ab428160 100644 --- a/resources/tester/helper_349_0k_undo_saved.cjs +++ b/resources/tester/helper_349_0k_undo_saved.cjs @@ -1,7 +1,7 @@ /* PLAN 349-0k sub7 헬퍼 — 열기 → 노선 꼭짓점 끌기 → 되돌리기(초안 버림)면 상세 = 열 때 저장 정본 그대로. * 진짜 TS(`design_pipeline_page` · 단계 파일 · 상세 가게 `B06_Section_Section_Store`)를 트랜스파일해 Node 로 · * 서버 창구만 가짜. 종단 보기 고리 흉내 = `design_view_profile_sections.followSwap`(가게 stations → 갈아끼움 · - * 새 상세 → render) · `design_view_profile` 의 `onDraftDropped`(되돌림) 그대로. 초안 동안 갈아끼운 횡단은 + * 새 상세 → render) · `design_view_profile` 의 `holdDraft`(초안 전 상태 · 되돌림) 그대로. 초안 동안 갈아끼운 횡단은 * 브라우저 다시 셈 흉내로 면적을 바꿔 둠(옛 길이면 되돌린 뒤 그 값이 남음). * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0k_undo_saved.py`. */ const fs = require("fs"); @@ -191,14 +191,19 @@ async function run() { const restores = []; pageMod.routeDraftBridge(P, link, { stationIntervalM: job.interval, - // `design_view_profile` 의 onDraftDropped 그대로 - onDraftDropped: async (routeId, saved, stations) => { - const back = saved && (await sectionStore.restoreSectionDetail(P, routeId, saved, stations)); - restores.push({ saved: !!saved, back: back ? { same: back.same } : null }); - if (saved && !back) return "unchanged"; - if (back?.same) return "saved"; - await sectionStore.swapSectionStations(P, routeId, stations); - return saved ? "stations" : "no-saved"; + // `design_view_profile` 의 holdDraft 그대로(349-0o) + holdDraft: (routeId, saved) => { + const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); + return async (stations) => { + if (!hold) { + restores.push({ saved: false, back: null }); + await sectionStore.swapSectionStations(P, routeId, stations); + return "no-saved"; + } + const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); + restores.push({ saved: true, back: back ? { same: back.same } : null }); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; }, }); // followSwap — 새 상세 → 종단도 render(처음부터 다시 · 비정규 측점) · 가게 stations → 갈아끼움 @@ -246,7 +251,8 @@ async function run() { runs: sliceRuns(mark), restores, swaps: swaps.length - swapMark, - sameObject: back === opened && detail === opened, + // 되돌린 상세 = 초안 시작 때 뜬 사본(349-0o) — 열 때 객체가 아님 · 종단도가 쥔 것 = 가게 것 + sameObject: back === detail && back !== opened, stations: back.cross_sections.map((s) => s.chainage_m), final: finalOf(back), cross: crossOf(back), diff --git a/resources/tester/helper_349_0l_undo_draw.cjs b/resources/tester/helper_349_0l_undo_draw.cjs index b16e95478..d8b3ba90e 100644 --- a/resources/tester/helper_349_0l_undo_draw.cjs +++ b/resources/tester/helper_349_0l_undo_draw.cjs @@ -181,7 +181,8 @@ STUBS["B05_Profile_UI_Profile_Render"] = { longitudinal: { design_profiles: designProfiles }, cross_sections: detail.cross_sections, }); - draws.push({ key, saved: detail === opened }); + // 저장 상세를 그림 = 묶음 새 노선 상세(preview)가 아님 · 그린 객체(가게 것인지 견줌) + draws.push({ key, saved: !detail.cross_sections.some((s) => s.preview), ref: detail }); ctx.onStaleDesigns?.(key); }, }; @@ -295,13 +296,17 @@ async function run() { stationIntervalM: job.interval, structureAreas: ({ cross_sections: rows }) => layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)), - // `design_view_profile` 의 onDraftDropped 그대로 - onDraftDropped: async (routeId, saved, stations) => { - const back = saved && (await sectionStore.restoreSectionDetail(P, routeId, saved, stations)); - if (saved && !back) return "unchanged"; - if (back?.same) return "saved"; - await sectionStore.swapSectionStations(P, routeId, stations); - return saved ? "stations" : "no-saved"; + // `design_view_profile` 의 holdDraft 그대로(349-0o) + holdDraft: (routeId, saved) => { + const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); + return async (stations) => { + if (!hold) { + await sectionStore.swapSectionStations(P, routeId, stations); + return "no-saved"; + } + const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; }, }); // 종단 보기 `renderSections` · followSwap 그대로 — 새 상세 → render · 비정규 측점 · 가게 stations → 갈아끼움 @@ -323,6 +328,7 @@ async function run() { refresh: refreshCalls - refreshMark, lastKey: draws[draws.length - 1]?.key ?? null, drawnSaved: draws[draws.length - 1]?.saved ?? null, + drawnLive: draws[draws.length - 1]?.ref === detail, sameObject: detail === opened, stations: detail.cross_sections.map((s) => s.chainage_m), final: finalOf(detail), diff --git a/resources/tester/helper_349_0o_redo_same.cjs b/resources/tester/helper_349_0o_redo_same.cjs new file mode 100644 index 000000000..8c5ae5c85 --- /dev/null +++ b/resources/tester/helper_349_0o_redo_same.cjs @@ -0,0 +1,456 @@ +/* PLAN 349-0o sub7 헬퍼 — 열기 → 끌기 → 되돌리기 → 다시 하기 → 되돌리기 → 횡단 보기 → 종단 보기 = + * 열기 · 끌기 · 열기 · 끌기 · 열기 · 열기 · 열기 값. 저장 상세 측점 ≠ 묶음 측점(세월교 측점이 상세에 없음)이어도 + * 되돌림 = 초안 전 상세 · 횡단 초안 칸 그대로 · 다시 하기 = 첫 끌기 값. 진짜 TS — 종단도 · 계산 묶음 · 상세 가게 · + * 횡단 보기 진입 다시 셈 판정(`B06_Section_UI_Page_Design_Sync`). 화면 부품 · 서버 창구만 가짜 · 다시 셈 창구는 + * 부른 수를 세고 면적을 두 배로(서버와 다른 값 흉내) · 낡음 판정은 진짜 화면 선 기준 그대로. + * 되돌리기 · 다시 하기 = 화면 꼴(사진첩이 세션 노선 초안 칸을 먼저 씀 · 알림 두 번 · 349-0m). + * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0o_redo_same.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; + }, + }; +} +const windowBase = { + sessionStorage: memoryStorage(), + localStorage: memoryStorage(), + setTimeout, + clearTimeout, + addEventListener: () => undefined, + removeEventListener: () => undefined, +}; +globalThis.window = new Proxy(windowBase, { + get: (t, key) => (key in t ? t[key] : undefined), + set: (t, key, value) => ((t[key] = value), true), +}); + +// 흙 배분 서버 — 늦게 답함 · 끊기면 버림 +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 anyModule(); + 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" }; + +/** 아무 화면 부품 — 무엇을 읽든 · 부르든 또 그것(DOM · 오버레이 · 도구줄 흉내). */ +function anyNode() { + const box = { dataset: {}, style: {}, classList: { add() {}, remove() {}, toggle() {} } }; + return new Proxy(function node() {}, { + get: (_t, key) => { + if (key in box) return box[key]; + if (key === "then" || typeof key === "symbol") return undefined; + return (box[key] = anyNode()); + }, + set: (_t, key, value) => ((box[key] = value), true), + apply: () => anyNode(), + }); +} +const anyModule = (own = {}) => + new Proxy(own, { + get: (t, key) => + key in t + ? t[key] + : key === "__esModule" + ? true + : typeof key === "symbol" + ? undefined + : anyNode(), + }); +globalThis.document = anyNode(); +globalThis.HTMLElement = function HTMLElement() {}; + +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"] = anyModule({ + fetchStructures: async () => ({ structures: job.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, +}; +// 횡단 다시 셈(브라우저 · B05 crossPreview · B06 카드 같은 창구) — 부른 횟수 · 면적은 서버와 달라짐(두 배) +let refreshCalls = 0; +const doubled = (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; + }); +STUBS["B06_Section_Cross_Refresh"] = { + refreshCrossDesigns: async ({ detail }) => { + refreshCalls += 1; + doubled(detail); + return detail.cross_sections.map((s) => s.chainage_m); + }, + // 화면 선 맡김 · 낡음 판정 = 진짜 `staleAgainstScreen` 그대로(화면 선 → 없으면 상세 자기 선) + holdScreenAlignment: (line) => { + screenLine = line; + return () => undefined; + }, + staleAgainstScreen: (detail, routeId) => { + const screen = screenLine?.(routeId); + if (!screen) return common.hasStaleDesigns(detail); + return common.hasStaleDesigns({ + longitudinal: { + design_profiles: [ + profileData.toDesignProfile(screen, detail.longitudinal.design_profiles?.[0]), + ], + }, + cross_sections: detail.cross_sections, + }); + }, + USER_TOUCHED_KEYS: [], +}; +let screenLine = null; +STUBS["B06_Section_UI_Cross_Detail"] = anyModule(); +STUBS["B06_Section_UI_Page_Common"] = anyModule({ L: (key) => key }); +// 그리기 — 진짜 `renderProfile` 의 낡음 판정 줄만(같은 함수 · 같은 인자) · SVG 는 안 그림 +const draws = []; +let opened = null; +STUBS["B05_Profile_UI_Profile_Render"] = { + renderProfile: (ctx) => { + const detail = ctx.detail(); + if (!detail) return; + const alignment = ctx.alignment(); + const longitudinal = detail.longitudinal; + const designProfiles = alignment + ? [profileData.toDesignProfile(alignment, longitudinal.design_profiles?.[0])] + : (longitudinal.design_profiles ?? []); + const key = common.staleKey({ + longitudinal: { design_profiles: designProfiles }, + cross_sections: detail.cross_sections, + }); + // 저장 상세를 그림 = 묶음 새 노선 상세(preview)가 아님 · 그린 객체(가게 것인지 견줌) + draws.push({ key, saved: !detail.cross_sections.some((s) => s.preview), ref: detail }); + ctx.onStaleDesigns?.(key); + }, +}; +STUBS["common_util_view_window"] = { frameOf: (_root, fn) => fn() }; +for (const name of [ + "B05_Profile_UI_Profile_Balance", + "B05_Profile_UI_Profile_Heights", + "B05_Profile_UI_Profile_Panel_Tools", + "B05_Profile_UI_Profile_Zoom", + "B05_Profile_UI_Profile_Drag", + "B05_Profile_UI_Profile_MassHaul", + "design_profile_overlays", + "design_profile_viewport", + "design_save", + "B05_Profile_Api_Fetch", + "common_util_mass_haul_balance_view", +]) + STUBS[name] = anyModule(); + +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 common = load("B06_Section", "B06_Section_UI_Section_Common.ts"); +const layouts = load("B06_Section", "B06_Section_Structure_Layouts.ts"); +const profileData = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Data.ts"); +const alignmentMod = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); +const baseMod = load("A00_Common", "design", "design_profile_base.ts"); +const pageState = load("A00_Common", "b_page_state.ts"); +const massHaul = load("common_util", "common_util_mass_haul.ts"); +const profileMod = load("A00_Common", "design", "design_profile.ts"); +const designSync = load("B06_Section", "B06_Section_UI_Page_Design_Sync.ts"); +const designSession = load("B06_Section", "B06_Section_Cross_Design_Session.ts"); +const stationKeys = load("B06_Section", "B06_Section_Station_Keys.ts"); +// 진짜 다시 셈 창구(묶음 새 노선 상세를 안 고치는지만 봄 · 다른 곳은 위 가짜를 부름) +const realRefresh = loadTs(path.join(ROOT, "B06_Section", "B06_Section_Cross_Refresh.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(30); + const last = runs()[runs().length - 1]; + const count = runs().length + refreshCalls * 1000 + draws.length * 1e6; + 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, + restored: r.restored ?? null, + why: r.restoreWhy ?? null, + })); +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])); +/** 서버 정본 흉내 — 저장 횡단 계획고 = 열 때 종단도 계획선(낡음 0 · 서버가 낸 상세와 같음). */ +function settleDesigns(detail) { + const pa = detail.longitudinal.profile_alignment; + const base = baseMod.listedBase(alignmentMod.toAlignmentBase(pa), detail, []); + const samples = alignmentMod.buildAlignment(base, pa.edits).samples; + const at = (c) => { + const i = samples.findIndex((s) => s.chainage_m >= c); + if (i < 0) return samples[samples.length - 1].elevation_m; + if (i === 0) return samples[0].elevation_m; + const a = samples[i - 1]; + const b = samples[i]; + return ( + a.elevation_m + + ((b.elevation_m - a.elevation_m) * (c - a.chainage_m)) / (b.chainage_m - a.chainage_m) + ); + }; + detail.cross_sections.forEach((s) => (s.design.design_elevation_m = at(s.chainage_m))); +} + +async function run() { + const P = "proj-349o"; + const R = 7; + window.localStorage.setItem("frd_current_project_id", P); + opened = await sectionStore.loadSectionDetail(P, R); + settleDesigns(opened); + stationKeys.useStationKeys(P, R, opened); // 상세가 측점을 얹은 뒤(Section_Drafts 몫 · 여기선 가짜) + // 횡단 초안 칸 — 열기 전에 고친 카드 선택(단면 유형은 노선이 바뀌면 안 넘김 · 349-0o) + for (const [chainage, value] of Object.entries(job.touched)) + designSession.writeCrossDesignChoice(P, R, Number(chainage), value); + const profile = profileMod.createDesignProfile({ + projectId: P, + view: "profile", + onSelectStation: () => undefined, + }); + const live = () => sectionStore.loadSectionDetail(P, R); + pageMod.routeDraftBridge(P, profile, { + stationIntervalM: job.interval, + structureAreas: ({ cross_sections: rows }) => + layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)), + // `design_view_profile` 의 holdDraft 그대로 + holdDraft: (routeId, saved) => { + const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); + return async (stations) => { + if (!hold) { + await sectionStore.swapSectionStations(P, routeId, stations); + return "no-saved"; + } + const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; + }, + }); + // 종단 보기 `renderSections` · followSwap 그대로 — 새 상세 → render · 비정규 측점 · 가게 stations → 갈아끼움 + const show = (detail) => { + profile.render(detail, job.interval, R); + profile.setIrregularStations([]); + }; + const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => show(next)); + const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => { + if (stations?.length) void sectionStore.swapSectionStations(P, R, stations); + }); + // 횡단 보기 다시 셈 — 진짜 `B06_Section_UI_Page_Design_Sync`(낡음 · 계획고 초안이면 다시 셈) · 카드 = 그 상세 + const cards = () => pageMod.pipelineDetail(P) ?? cached; + let cached = opened; + const sync = designSync.createDesignSync({ + projectId: P, + routeId: () => R, + detail: () => cards(), + view: () => ({ refreshCards: () => undefined }), + }); + show(opened); + profile.setEarthworkContext({ conversion: job.conversion }); + await quiet(); + + const measure = async (mark, refreshMark) => { + const detail = await live(); + const drawn = pageMod.pipelineDetail(P) ?? detail; // 종단도가 그리는 상세(초안 동안 묶음 새 상세) + return { + runs: sliceRuns(mark), + refresh: refreshCalls - refreshMark, + lastKey: draws[draws.length - 1]?.key ?? null, + drawnSaved: draws[draws.length - 1]?.saved ?? null, + drawnLive: draws[draws.length - 1]?.ref === detail, + stations: detail.cross_sections.map((s) => s.chainage_m), + final: finalOf(drawn), + cross: crossOf(drawn), + edits: JSON.stringify(profile.pipelineSource().edits), + cells: JSON.stringify( + ["crossdesign", "rockb"].map((name) => pageState.readState(name, P, R) ?? null), + ), + }; + }; + const open = await measure(0, 0); + + const drag = async () => { + const mark = runs().length; + const refreshMark = refreshCalls; + const bridge = pageMod.routeDraftBridge(P, profile); + pageState.writeState("route-draft", null, P); // 사진첩 다시 하기 — 세션 칸을 먼저 씀(지난 값) + bridge.edited(draftOf(shift(1, 6, -4))); + bridge.edited(draftOf(shift(1, 6, -4))); + await quiet(); + // 초안 동안 횡단 카드가 갈아끼운 상세를 다시 셈(흉내 · 저장 상세 사본엔 안 닿아야) + doubled(await live()); + // 횡단 보기 다시 셈 창구(진짜 `refreshCrossDesigns`)가 묶음 새 노선 상세를 부르면 — 안 고침(묶음 결과 그대로) + const shown = pageMod.pipelineDetail(P); + const before = crossOf(shown); + const updated = await realRefresh.refreshCrossDesigns({ + projectId: P, + routeId: R, + detail: shown, + edits: { station_offsets: {}, curve_radii: {} }, + }); + return { + ...(await measure(mark, refreshMark)), + draftRefresh: { updated, same: crossOf(shown) === before }, + }; + }; + const undo = async () => { + const mark = runs().length; + const refreshMark = refreshCalls; + const bridge = pageMod.routeDraftBridge(P, profile); + pageState.writeState("route-draft", null, P); + bridge.edited(null); + bridge.edited(null); + await quiet(); + return measure(mark, refreshMark); + }; + const first = await drag(); + const back1 = await undo(); + const redo = await drag(); + const back2 = await undo(); + + // 횡단 보기(B06) — 카드 상세 다시 받음 · 진입 다시 셈 판정 · 종단도는 횡단 보기 자리 + let mark = runs().length; + let refreshMark = refreshCalls; + cached = await live(); + profile.setView("cross"); + show(cards()); + profile.setEarthworkContext({ conversion: job.conversion }); + await sync.reconcileStaleDesigns(); + await quiet(); + const cross = await measure(mark, refreshMark); + // 종단 보기(B05)로 + mark = runs().length; + refreshMark = refreshCalls; + profile.setView("profile"); + profile.setActive(true); + await quiet(); + const back = await measure(mark, refreshMark); + const blocked = pageMod.pagePipeline(P).blockedWrites; + const restoreDiffs = runs() + .filter((r) => r.restoreDiff) + .map((r) => r.restoreDiff); + stopListen(); + stopStore(); + pageMod.disposePagePipeline(P); + return { open, first, back1, redo, back2, cross, back, blocked, restoreDiffs }; +} + +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 index f60a71ec6..c8b686e35 100644 --- a/resources/tester/test_349_0k_undo_saved.py +++ b/resources/tester/test_349_0k_undo_saved.py @@ -120,7 +120,7 @@ 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["sameObject"] # 가게 = 종단도 · 열 때 객체의 사본(349-0o) assert u["stations"] == o["stations"] assert u["cross"] == o["cross"] assert u["final"] == o["final"] diff --git a/resources/tester/test_349_0l_undo_draw.py b/resources/tester/test_349_0l_undo_draw.py index 88ded36ee..55264f3c7 100644 --- a/resources/tester/test_349_0l_undo_draw.py +++ b/resources/tester/test_349_0l_undo_draw.py @@ -134,8 +134,8 @@ def test_되돌리기_열기_값_다시_셈_0(r): (["route"], True, "saved") ], u["runs"] assert u["refresh"] == 0 - assert u["lastKey"] == "" and u["drawnSaved"] - assert u["sameObject"] + assert u["lastKey"] == "" and u["drawnSaved"] and u["drawnLive"] + assert not u["sameObject"] # 초안 시작 때 뜬 사본(349-0o) assert u["stations"] == o["stations"] assert u["cross"] == o["cross"] assert u["final"] == o["final"] diff --git a/resources/tester/test_349_0o_redo_same.py b/resources/tester/test_349_0o_redo_same.py new file mode 100644 index 000000000..910e654fb --- /dev/null +++ b/resources/tester/test_349_0o_redo_same.py @@ -0,0 +1,196 @@ +"""PLAN 349-0o sub7 — 값 한 벌: 되돌림 · 다시 하기 · 횡단 보기가 같은 값. + +· 열기 → 끌기 → 되돌리기 → 다시 하기 → 되돌리기 → 횡단 보기 → 종단 보기 = + 열기 · 끌기 · 열기 · 끌기 · 열기 · 열기 · 열기 값(누가토량 · 횡단 · 측점) +· 저장 상세에 없는 세월교 측점(묶음 측점 ≠ 상세 측점) — 되돌림 = 초안 전 상세 · 묶음 기록에 첫 다른 측점 · 개수 +· 횡단 초안 칸(카드 선택 · 단면 유형) = 열기 값 — 초안 동안 넘김이 버린 칸도 +· 횡단 보기 진입 다시 셈 판정은 진짜(`Design_Sync`) — 되돌린 뒤 다시 셈 0 +· 되돌리기 · 다시 하기 = 화면 꼴(세션 노선 초안 칸 먼저 · 알림 두 번) +짝: `helper_349_0o_redo_same.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")) + + +def _between(sections: list[dict], index: int) -> dict: + """두 측점 사이 한 점(0.37) — 누가거리 · 좌표.""" + a, b = sections[index], sections[index + 1] + k = 0.37 + return { + "chainage_m": round(a["chainage_m"] + k * (b["chainage_m"] - a["chainage_m"]), 2), + "x": a["center_x"] + k * (b["center_x"] - a["center_x"]), + "y": a["center_y"] + k * (b["center_y"] - a["center_y"]), + } + + +@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"] + # 세월교 하나 더(측점 사이) — 저장 상세엔 그 측점이 없음 = 묶음 저장 노선 측점과 다름(검증_sub7 세월교 2 + 1) + pipes = [*pipes, {"source": "manual", "facility": "ford_bridge", **_between(sections, -6)}] + # 저장 횡단 면적 = 서버가 상세를 낼 때 셈(파일엔 없음) — 정본 대신 정한 값 + 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, + # 구조물 하나 — 첫 관 자리 횡단배수(같은 측점을 덮음) + "structures": [ + { + "structure_id": "s-349o", + "type_id": "cross_drain_exposed", + "chainage_m": pipes[0]["chainage_m"], + "x": pipes[0]["x"], + "y": pipes[0]["y"], + } + ], + # 열기 전에 고친 카드 선택 — 끌면 밀리는 측점(뒤쪽) · 단면 유형은 노선이 바뀌면 안 넘기는 칸 + "touched": { + str(sections[-3]["chainage_m"]): { + "ground_type": "blasting_rock", + "section_mode": "right_cut", + } + }, + "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_0o_redo_same.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 _same(a: dict, b: dict) -> None: + assert a["final"] == b["final"] + assert a["cross"] == b["cross"] + + +def test_열기(r): + o = r["open"] + assert [x["outcome"] for x in o["runs"]] == ["done"], o["runs"] + assert o["lastKey"] == "" and o["drawnSaved"] and o["refresh"] == 0 + assert o["final"] is not None + + +def test_끌기_새_노선(r): + d = r["first"] + assert [x["sources"] for x in d["runs"]] == [["route"]], d["runs"] + assert not d["drawnSaved"] # 묶음 새 노선 상세를 그림 + assert d["final"] != r["open"]["final"] + + +def test_되돌리기_열기_값_측점_다름은_기록(r): + o = r["open"] + for u in (r["back1"], r["back2"]): + assert [(x["sources"], x["restored"], x["why"]) for x in u["runs"]] == [ + (["route"], True, "saved-diff") + ], u["runs"] + assert u["refresh"] == 0 + assert u["lastKey"] == "" and u["drawnSaved"] and u["drawnLive"] + assert u["stations"] == o["stations"] + _same(u, o) + assert u["edits"] == o["edits"] + assert u["cells"] == o["cells"] # 횡단 초안 칸 = 열기 값 + diffs = r["restoreDiffs"] + assert len(diffs) == 2 and diffs[0] == diffs[1] + d = diffs[0] + assert d["pipeline"] == d["saved"] + 1 # 세월교 측점 하나 더 + assert d["pipelineM"] is not None and d["savedM"] is not None + + +def test_초안_상세는_다시_셈이_안_고침(r): + for step in (r["first"], r["redo"]): + assert step["draftRefresh"] == {"updated": [], "same": True} + + +def test_다시_하기_첫_끌기_값(r): + d, f = r["redo"], r["first"] + assert [x["sources"] for x in d["runs"]] == [["route"]], d["runs"] + _same(d, f) + assert d["stations"] == f["stations"] + + +def test_횡단_보기_다녀와도_열기_값(r): + o = r["open"] + for step in (r["cross"], r["back"]): + assert step["runs"] == [], step["runs"] + assert step["refresh"] == 0 # 진입 다시 셈 판정 · crossPreview 모두 안 돎 + assert step["lastKey"] == "" and step["drawnSaved"] + _same(step, o) + assert step["cells"] == o["cells"] + assert r["blocked"] == 0