Files
Aislo/B06_Section/B06_Section_Section_Store.ts
T
eomsangdonandClaude Opus 5.5 1e02ecc196 fix(structure): 관 지점 시설 종류 바꾸기 뒤 B06 횡단도 · 알약 · 목록 바로 새 종류(54-4)
- 좌측 패널 종류 바꿈 = 고른 관 지점 실시간 반영
- B06 관 고침이 시설 종류를 받음 · 옛 종류 칸 안 이음 · 알약 · 횡단 다시 그림
- 횡단 상세 읽기에 초안 종류 얹기(짝 산식 common_util_culvert_sets) · 카드 제목 라벨 포함
- 상세 조회가 측점 라벨을 지금 관 지점 종류로(저장 뒤 다시 열기)
- 구조물 다시 그림 최신 요청만 채택
- 시험: test_b05_pipe_station_relabel · ui_checks 54-4_종류바꾸기_횡단

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rJwJMVL4EE31y77TB11AP
2026-10-06 10:26:34 +09:00

267 lines
13 KiB
TypeScript

/* =============================================================================
* B06_Section_Section_Store.ts
* 종횡단 상세(SectionDetailResponse)의 **프론트 공유 캐시** — B05·B06이 같은 객체를 본다.
*
* ── 왜 필요한가 (2026-08-03 사용자 확정) ─────────────────────────────
* B05(노선·계획선)와 B06(종횡단 설계)은 같은 영구저장소 데이터의 두 창이다. 페이지마다
* 따로 fetch해 제각각 들고 있으면, B06에서 지반유형·암 경계를 고친 뒤 B05로 넘어갔을 때
* 횡단 기준 유토곡선이 옛 값으로 그려진다(사용자가 실제로 겪은 문제). 여기서 한 번 받아
* **같은 객체 참조**를 두 페이지에 주면, B06이 측점 설계를 제자리 갱신하는 순간 B05가
* 다음 그리기에서 그대로 본다 — 별도 동기화 코드가 필요 없다.
*
* ── 수명 규칙 ─────────────────────────────────────────────────────
* 키는 `projectId:routeId`. SPA 모듈 싱글턴이라 페이지를 오가도 살아 있다. 새로고침이면
* 메모리가 비므로 **세션에도 한 벌 얹어 둔다**(④ 계산 결과, 2026-09-06 캐시·세션 일원화)
* — 새로고침 뒤 첫 화면이 서버를 기다리지 않는다. 세션 용량을 넘으면 조용히 건너뛰고
* 예전처럼 영구저장소에서 다시 받는다(영구저장소가 항상 정본). 서버가 파일을 통째로 다시
* 쓰는 조작(재생성·계획선 편집 저장·확정)은 그 응답/재조회로 `replace`·`invalidate`한다.
* ========================================================================== */
import { clearState, readState, writeState } from "../A00_Common/b_page_state";
import {
fetchStructureTypes,
readPendingStructures,
} from "../B05_Profile/B05_Profile_Api_Structures";
import { readPendingPipes } from "../B05_Profile/B05_Profile_Api_Pipes_Draft";
import { PIPE_MATCH_M } from "../A00_Common/design/design_selection";
import {
attachCulvertSets,
buildCulvertSets,
registryDefaults,
} from "@util/common_util_culvert_sets";
import {
attachWallSpecs,
wallSpecsFrom,
type WallStructureInput,
} from "@util/common_util_structure_walls";
import { applyStructureAreaRows, structureAreaRows } from "./B06_Section_Structure_Layouts";
import type { CrossSectionPatch, SectionDetailResponse } from "./B06_Section_Api_Fetch";
import { fetchSectionDetail, saveSections } from "./B06_Section_Api_Fetch";
import { USER_TOUCHED_KEYS } from "./B06_Section_Cross_Refresh";
const cache = new Map<string, SectionDetailResponse>();
const pending = new Map<string, Promise<SectionDetailResponse>>();
function keyOf(projectId: string, routeId: number): string {
return `${projectId}:${routeId}`;
}
/**
* 아직 저장하지 않은 구조물(C군 벽)을 상세에 얹는다 — **여기가 유일한 자리**다.
*
* 서버는 저장분만 얹어 준다(`attach_wall_structures`). 초안이 있으면 그것이 화면의
* 정본이므로, 캐시·세션·새 요청 어느 길로 들어오든 이 함수를 지나 같은 상태가 된다.
* 페이지마다 따로 얹으면 새로고침 뒤 세션 스냅샷이 저장분 기준으로 되돌아간다
* (2026-09-06 실측). 산식은 서버와 짝(`common_util_structure_walls`).
*/
async function withDraftWalls(
detail: SectionDetailResponse,
projectId: string,
): Promise<SectionDetailResponse> {
const drafts = readPendingStructures(projectId);
// ⚠ **빈 목록도 「초안 없음」이다**(2026-09-09). 예전에는 `[]` 가 「초안이 있는데 벽이
// 하나도 없다」로 읽혀 **아래에서 서버 저장분을 통째로 지웠다** — 구조물을 놓아도
// 횡단도에 아무것도 안 보이던 결함의 원인이다(창 둘에서 같은 증상, 실측 확인).
await withDraftPipeKinds(detail, projectId);
if (!drafts || !drafts.length) return withStructureAreas(detail);
const types = await fetchStructureTypes().catch(() => []);
const names = new Map(
types
// 소단은 C군 구간형이지만 **벽이 아니다** — 사면을 계단으로 끊는 시설이라
// 기슭막이 제원 자리에 얹으면 안 된다(계획서 3-9).
.filter(
(type) => type.group === "C" && type.placement === "interval" && type.type_id !== "berm",
)
.map((type) => [type.type_id, type.name] as const),
);
if (!names.size) return detail;
for (const section of detail.cross_sections) {
if (section.revetment) delete (section as { revetment?: unknown }).revetment;
}
attachWallSpecs(
detail.cross_sections as unknown as Array<Record<string, unknown>>,
wallSpecsFrom(drafts as unknown as WallStructureInput[], names),
);
return withStructureAreas(detail);
}
/** 관 지점 시설 → 횡단 자리 키(파이썬 `_SECTION_KEYS` · 배관 · 독립 기슭막이 = culvert). */
const FACILITY_KEYS = ["culvert", "ford", "box", "ford_pavement"] as const;
const facilityKey = (facility: string): (typeof FACILITY_KEYS)[number] =>
facility === "ford_bridge"
? "ford"
: facility === "box_culvert"
? "box"
: facility === "ford_pavement"
? "ford_pavement"
: "culvert";
/**
* 저장 전에 **종류를 바꾼 관**(배관 ↔ BOX암거 ↔ 세월교 ↔ 물넘이포장 · 54-4)을 상세에 얹는다.
* 서버는 저장분 종류로만 얹어 준다 — 초안 종류와 다른 관만 옛 자리를 걷고 짝 산식
* (`common_util_culvert_sets`)으로 새 종류 제원을 얹는다. 옛 종류 칸 값은 섞지 않는다.
*/
async function withDraftPipeKinds(detail: SectionDetailResponse, projectId: string): Promise<void> {
const pipes = readPendingPipes(projectId);
if (!pipes?.length) return;
const sections = detail.cross_sections as unknown as Array<Record<string, unknown>>;
const near = (spec: Record<string, unknown>, section: Record<string, unknown>, at: number) =>
Math.abs(Number(spec.chainage_m ?? section.chainage_m) - at) < PIPE_MATCH_M;
/** 그 관 자리에 얹힌 시설 키가 이 종류와 맞는가 — 얹힌 것이 없으면(새 관 · 옮긴 관) 대상 밖. */
const fits = (pipe: (typeof pipes)[number], key: string, spec: Record<string, unknown>) =>
key === facilityKey(pipe.facility ?? "pipe") &&
(key !== "culvert" || (spec.hidden_pipe === true) === (pipe.facility === "revetment"));
const stale = pipes.filter((pipe) => {
const here = sections.flatMap((section) =>
FACILITY_KEYS.flatMap((key) => {
const spec = section[key] as Record<string, unknown> | undefined;
return spec && near(spec, section, pipe.chainage_m) ? [[key, spec] as const] : [];
}),
);
return here.length > 0 && !here.some(([key, spec]) => fits(pipe, key, spec));
});
if (!stale.length) return;
const types = await fetchStructureTypes().catch(() => []);
const registry = registryDefaults(types);
for (const section of sections) {
for (const key of FACILITY_KEYS) {
const spec = section[key] as Record<string, unknown> | undefined;
if (spec && stale.some((pipe) => near(spec, section, pipe.chainage_m))) delete section[key];
}
// 카드 제목 구조물 이름 — 서버 `resolve_extra_stations` 라벨 규칙(배관 = 관종 D관경 · 물넘이 = 없음)
// 라벨 자리 = 이름 있는 측점 · 관 자리 그 측점(물넘이로 지웠다 되돌린 때)
const pipe = stale.find((entry) => {
const gap = Math.abs(entry.chainage_m - Number(section.chainage_m));
return section.structure ? gap < PIPE_MATCH_M : gap < 0.01;
});
if (!pipe) continue;
const facility = pipe.facility ?? "pipe";
const values = { ...registry.pipe, ...pipe.options };
if (facility === "ford_pavement") delete section.structure;
else if (facility === "pipe")
section.structure = `${values.pipe_kind} D${Math.trunc(Number(values.pipe_diameter_mm))}`;
else section.structure = types.find((type) => type.type_id === facility)?.name ?? facility;
}
attachCulvertSets(sections, buildCulvertSets(stale, registry));
}
/**
* 구조물이 선 측점의 절·성토 면적을 **읽어 오는 자리에서 한 번** 다시 얹는다.
*
* 카드는 자기 그림에서 면적을 고쳐 들지만 유토곡선은 카드보다 먼저 계산된다 — 여기서
* 얹지 않으면 새로고침 직후 곡선만 옛 면적으로 남는다(2026-09-06 실측 553.4 vs 546.4).
* 순수 계산(6ms/67측점)이라 읽기 경로에 두어도 규칙에 어긋나지 않는다.
*/
function withStructureAreas(detail: SectionDetailResponse): SectionDetailResponse {
applyStructureAreaRows(detail.cross_sections, structureAreaRows(detail.cross_sections));
return detail;
}
/**
* 상세를 가져온다 — 캐시가 있으면 **같은 객체**를 즉시 돌려주고, 없으면 한 번만 fetch한다
* (동시 호출은 같은 Promise를 공유). `force`면 캐시를 버리고 다시 받는다.
*/
export async function loadSectionDetail(
projectId: string,
routeId: number,
options?: { force?: boolean },
): Promise<SectionDetailResponse> {
const key = keyOf(projectId, routeId);
if (!options?.force) {
const cached = cache.get(key);
if (cached) return withDraftWalls(cached, projectId);
const inFlight = pending.get(key);
if (inFlight) return inFlight;
// 새로고침으로 메모리가 빈 경우 — 세션에 얹어 둔 한 벌로 바로 선다.
const stored = readState<SectionDetailResponse>("section-detail", projectId, routeId);
if (stored) {
cache.set(key, stored);
return withDraftWalls(stored, projectId);
}
}
const request = fetchSectionDetail(projectId, routeId)
.then(async (detail) => {
cache.set(key, detail);
writeState("section-detail", detail, projectId, routeId);
return withDraftWalls(detail, projectId);
})
.finally(() => {
pending.delete(key);
});
pending.set(key, request);
return request;
}
/** 서버가 새 상세를 통째로 돌려준 조작(재생성 등) 뒤 캐시를 그 값으로 바꾼다. */
export function replaceSectionDetail(
projectId: string,
routeId: number,
detail: SectionDetailResponse,
): void {
cache.set(keyOf(projectId, routeId), detail);
writeState("section-detail", detail, projectId, routeId);
}
/**
* 캐시를 비운다. routeId를 생략하면 그 프로젝트 전부 —
* 서버 쪽 정본이 바뀌었는데 새 상세를 손에 못 쥔 조작(계획선 편집 저장 등) 뒤에 쓴다.
*/
export function invalidateSectionDetail(projectId: string, routeId?: number): void {
if (routeId !== undefined) {
cache.delete(keyOf(projectId, routeId));
clearState("section-detail", projectId, routeId);
return;
}
const prefix = `${projectId}:`;
for (const key of [...cache.keys()]) {
if (!key.startsWith(prefix)) continue;
cache.delete(key);
clearState("section-detail", projectId, Number(key.slice(prefix.length)));
}
}
/**
* 캐시에 얹힌 **사용자 수정분**을 저장 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;
// 필드를 손으로 나열하지 않는다(2026-09-07) — 목록은 `USER_TOUCHED_KEYS` 한 벌뿐이고
// 서버 목록과 짝이다. 나열이 흩어져 있던 탓에 새 값을 더할 때 한 곳이 빠져 그 값이
// 조용히 사라졌다(`extra_spans` 실사고 `b6941bd2`).
const source = design as unknown as Record<string, unknown>;
const target = patch as unknown as Record<string, unknown>;
for (const key of USER_TOUCHED_KEYS) {
const value = source[key];
if (value === undefined || value === null) continue;
target[key] = value;
touched = true;
}
if (touched) patches.push(patch);
}
return patches;
}
/**
* 캐시에 얹힌 사용자 수정분을 영구저장소에 남긴다(임시저장용). 캐시가 없거나 수정분이
* 없으면 아무것도 보내지 않는다. 저장 실패는 호출자가 처리한다.
*/
export async function saveCachedCrossPatches(projectId: string, routeId: number): Promise<number> {
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;
}