diff --git a/B05_Profile/B05_Profile_Structures_Repository.py b/B05_Profile/B05_Profile_Structures_Repository.py index aeb8c833..e337c46d 100644 --- a/B05_Profile/B05_Profile_Structures_Repository.py +++ b/B05_Profile/B05_Profile_Structures_Repository.py @@ -64,6 +64,24 @@ def load_structures(project_root: str) -> tuple[int, list[StructureInstance]]: return revision, structures +def load_migrated_legacy(project_root: str) -> set[str]: + """이미 구조물 정본으로 옮긴 구 비정규 측점의 표식 집합. + + 원천(종단 정본의 비정규 측점)은 **원복용으로 그대로 둔다**. 대신 "옮겼다"는 이력을 + 여기 남겨, 사용자가 그 구조물을 지운 뒤 화면에 다시 들어와도 되살아나지 않게 한다 + (2026-08-24 사용자 확정: 초기 계산값은 원복용, 사용자 수정 1세트가 최종본). + """ + path = structures_file_path(project_root) + if not os.path.exists(path): + return set() + try: + with open(path, encoding="utf-8") as handle: + payload = json.load(handle) + return {str(key) for key in payload.get("migrated_legacy", [])} + except (OSError, ValueError, TypeError): + return set() + + def _without_dropped_keys(item: Any) -> Any: """폐지된 필드가 남아 있는 저장분을 지금 스키마로 읽을 수 있게 손질한다.""" if not isinstance(item, dict): @@ -79,10 +97,13 @@ def save_structures( *, base_revision: int, max_chainage_m: float | None = None, + migrated_legacy: Iterable[str] | None = None, ) -> int: """구조물 목록을 정본에 덮어쓰고 새 판번호를 돌려준다. `max_chainage_m`는 노선 총연장(m) — 주어지면 범위 밖 배치를 거절한다. + `migrated_legacy`는 이번에 옮긴 구 측점 표식 — 기존 이력에 **더해서** 남긴다. + 이력은 어느 저장 경로로 덮어써도 사라지면 안 된다(사라지면 지운 구조물이 되살아난다). """ items = list(structures) _validate_types(items) @@ -98,9 +119,11 @@ def save_structures( item.structure_id = uuid.uuid4().hex revision = current_revision + 1 + history = load_migrated_legacy(project_root) | set(migrated_legacy or ()) payload = { "revision": revision, "structures": [item.model_dump(mode="json") for item in items], + "migrated_legacy": sorted(history), } atomic_write_json(structures_file_path(project_root), payload) return revision diff --git a/B05_Profile/B05_Profile_Structures_Router.py b/B05_Profile/B05_Profile_Structures_Router.py index fa644a37..78d17607 100644 --- a/B05_Profile/B05_Profile_Structures_Router.py +++ b/B05_Profile/B05_Profile_Structures_Router.py @@ -22,11 +22,13 @@ from B05_Profile.B05_Profile_Repository import get_latest_route from B05_Profile.B05_Profile_Structures_Migration import migrate_irregular_stations from B05_Profile.B05_Profile_Structures_Repository import ( StructureRevisionConflict, + load_migrated_legacy, load_structures, requires_downstream_invalidation, save_structures, ) from B05_Profile.B05_Profile_Structures_Schema import ( + StructureInstance, StructureListResponse, StructureSaveRequest, StructureSaveResponse, @@ -153,19 +155,42 @@ async def migrate_structures(project_id: UUID, payload: StructureMigrateRequest) if root is None: return JSONResponse(status_code=404, content=_PROJECT_PATH_MISSING) revision, existing = load_structures(root) - occupied = {(item.type_id, round(item.anchor_m(), 3)) for item in existing} + migrated_before = load_migrated_legacy(root) + candidates = migrate_irregular_stations(payload.stations) + # 표식 = "타입@위치". 원천(종단 정본의 비정규 측점)은 원복용으로 그대로 두고, + # 옮긴 이력만 남긴다 — 그래야 사용자가 지운 구조물이 재진입 때 되살아나지 않는다 + # (2026-08-24 사용자: 초기 계산값은 원복용, 사용자 수정 1세트가 최종본). + + def key_of(item: StructureInstance) -> str: + return f"{item.type_id}@{round(item.anchor_m(), 3)}" + + occupied = {key_of(item) for item in existing} fresh = [ item - for item in migrate_irregular_stations(payload.stations) - if (item.type_id, round(item.anchor_m(), 3)) not in occupied + for item in candidates + if key_of(item) not in occupied and key_of(item) not in migrated_before ] + # 이번에 건너뛴 것(이미 있던 자리)도 이력에 남긴다 — 그 자리는 이관이 끝난 자리다. + history = {key_of(item) for item in candidates} if not fresh: + # 새로 옮길 건 없어도 아직 이력에 없는 자리가 있으면 이력만 남긴다 — 그래야 + # 다음 진입에서 그 자리가 다시 후보로 잡히지 않는다. 이력이 이미 다 있으면 + # 저장하지 않는다(판번호를 괜히 올리면 다른 창의 저장이 충돌한다). + if history - migrated_before: + revision = save_structures( + root, + existing, + base_revision=revision, + max_chainage_m=await _route_length(project_id), + migrated_legacy=history, + ) return JSONResponse(content={"status": "success", "migrated": 0, "revision": revision}) new_revision = save_structures( root, [*existing, *fresh], base_revision=revision, max_chainage_m=await _route_length(project_id), + migrated_legacy=history, ) logger.info("B05 구 비정규 측점 이관: project_id=%s, %d건", project_id, len(fresh)) return JSONResponse( diff --git a/B05_Profile/B05_Profile_UI_Page.ts b/B05_Profile/B05_Profile_UI_Page.ts index 10f727d2..a23ebad6 100644 --- a/B05_Profile/B05_Profile_UI_Page.ts +++ b/B05_Profile/B05_Profile_UI_Page.ts @@ -46,6 +46,7 @@ import { import { invalidateSectionDetail, loadSectionDetail, + saveCachedCrossPatches, } from "../B06_Section/B06_Section_Section_Store"; import { migrateLegacyStations } from "./B05_Profile_Api_Structures"; import { refreshCorridor, saveCorridorIfDirty } from "./B05_Profile_UI_Corridor"; @@ -628,8 +629,6 @@ export async function renderB05Route(root: HTMLElement): Promise { try { // 종단 계획선 편집은 화면에서만 계산해 두었으므로 저장 시점에 영속화한다. await profilePanel.save(); - // 서버가 종단 정본의 계획선을 다시 썼다 — 공유 캐시를 비워 B06이 옛 계획선을 못 보게 한다. - invalidateSectionDetail(activeProjectId); // 비정규 측점·상단측 변경분까지 데이터로는 확정 저장하되, 단계 완료 전이는 하지 않는다. await confirmRoute( activeProjectId, @@ -650,6 +649,14 @@ export async function renderB05Route(root: HTMLElement): Promise { }, false, ); + // B06에서 만져 **캐시에 얹힌** 횡단 수정분을 함께 남긴다 — 안 보내면 바로 아래 + // 캐시 비우기에서 사라진다. 계획선 저장 **뒤에** 보내야 사용자 수정 1세트가 + // 최종본으로 얹힌다(2026-08-24 사용자 지적). + if (latest?.route?.id != null) { + await saveCachedCrossPatches(activeProjectId, latest.route.id); + } + // 서버가 종단 정본의 계획선을 다시 썼다 — 공유 캐시를 비워 B06이 옛 계획선을 못 보게 한다. + invalidateSectionDetail(activeProjectId); renderLatest(await loadLatest(true)); // 임시저장 = 코리도 영구저장 시점(2026-08-23) — 실패해도 임시저장은 성공 처리. if (latest?.route?.id) void saveCorridorIfDirty(activeProjectId, latest.route.id); diff --git a/B06_Section/B06_Section_Section_Store.ts b/B06_Section/B06_Section_Section_Store.ts index 86c5e2bf..52e30914 100644 --- a/B06_Section/B06_Section_Section_Store.ts +++ b/B06_Section/B06_Section_Section_Store.ts @@ -15,8 +15,8 @@ * 쓰는 조작(재생성·계획선 편집 저장·확정)은 그 응답/재조회로 `replace`·`invalidate`한다. * ========================================================================== */ -import type { SectionDetailResponse } from "./B06_Section_Api_Fetch"; -import { fetchSectionDetail } from "./B06_Section_Api_Fetch"; +import type { CrossSectionPatch, SectionDetailResponse } from "./B06_Section_Api_Fetch"; +import { fetchSectionDetail, saveSections } from "./B06_Section_Api_Fetch"; const cache = new Map(); const pending = new Map>(); @@ -76,3 +76,49 @@ export function invalidateSectionDetail(projectId: string, routeId?: number): vo if (key.startsWith(prefix)) cache.delete(key); } } + +/** + * 캐시에 얹힌 **사용자 수정분**을 저장 payload로 뽑는다(2026-08-24 사용자 확정 흐름). + * + * 초기 계산값은 원복용으로 서버에 그대로 있고, 사용자가 만진 값은 이 캐시 한 세트가 + * 최종본이다. B05 [임시저장]도 이 세트를 함께 보내야 B06에서 만진 구조물 조정이 + * 영구저장소에 남는다 — 안 보내면 캐시만 비워져 편집이 사라진다. + * + * 초기 계산값에는 없는 키(사용자가 만져야 생기는 키)만 싣는다. + */ +export function crossPatchesFromCache(detail: SectionDetailResponse): CrossSectionPatch[] { + const patches: CrossSectionPatch[] = []; + for (const section of detail.cross_sections) { + const design = section.design; + if (!design) continue; + const patch: CrossSectionPatch = { chainage_m: section.chainage_m }; + let touched = false; + const put = (key: K, value: CrossSectionPatch[K]): void => { + if (value === undefined || value === null) return; + patch[key] = value; + touched = true; + }; + put("display_half_width_m", design.display_half_width_m); + put("inlet_structure", design.inlet_structure); + put("basin_adjust", design.basin_adjust); + put("revet_adjust", design.revet_adjust); + put("extra_wall_counts", design.extra_wall_counts); + put("revet_link_detached", design.revet_link_detached); + put("revet_follow_grade", design.revet_follow_grade); + if (touched) patches.push(patch); + } + return patches; +} + +/** + * 캐시에 얹힌 사용자 수정분을 영구저장소에 남긴다(임시저장용). 캐시가 없거나 수정분이 + * 없으면 아무것도 보내지 않는다. 저장 실패는 호출자가 처리한다. + */ +export async function saveCachedCrossPatches(projectId: string, routeId: number): Promise { + const detail = cache.get(keyOf(projectId, routeId)); + if (!detail) return 0; + const patches = crossPatchesFromCache(detail); + if (!patches.length) return 0; + await saveSections(projectId, routeId, undefined, patches); + return patches.length; +}