Files
Aislo/B06_Section/B06_Section_Section_Store.ts
T
eomsangdonandClaude Opus 5.5 d28f1e8584 fix(467 값 안 변함 ②): 갈아끼움 정본 표본 유지 · 소단 원천 한 벌
- (B1) 노선 초안 없는 차례 = 같은 열쇠 · 누가거리 0.01 m 안 앞 횡단 기하 · 표본 그대로(축 허용 1e-3) · 노선 초안 차례는 옛 규칙 · 가게 routeDraft 로 가름(Section_Store 한 줄)
- (B2) 소단 사본(세션 berm) = 페이지 시설 줄이 씀(같으면 안 씀 · 쓰면 cross 한 번 · 늦은 import) · 횡단 보기 syncBermSpans 쓰기 뺌 · 다시 셈 = 사본 없으면 저장분 design.berm(파이썬 berm_from 짝 storedBermSpec)
- 새 시험 test_272_swap_keeps_canon · test_272_berm_source(TS ↔ 파이썬 거울) · helper_271 에 Persist 덧대기(import.meta 로더 밖)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 07:09:44 +09:00

526 lines
27 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, readStateRaw, writeState } from "../A00_Common/b_page_state";
import { PIPE_MATCH_M } from "../A00_Common/design/design_selection";
import { setGeneralStations, setPlusStations } from "../common_util/common_util_structure_station";
import { loadSavedPlusStations, plusStationsOf } from "../B05_Profile/B05_Profile_Api_PlusStations";
import {
forgetDraftStations,
supersedeDraftStations,
withDraftShapes,
withDraftStations,
} from "./B06_Section_Section_Drafts";
import { applyStructureAreaRows, structureAreaRows } from "./B06_Section_Structure_Layouts";
import { withDraftAdjusts, withPipeOptions } from "./B06_Section_Section_Adjusts";
import type {
CrossSection,
CrossSectionPatch,
SectionDetailResponse,
StandardCrossSection,
} from "./B06_Section_Api_Fetch";
import { forgetCanon, keepCanon, savedDesigns, sessionDetail } from "./B06_Section_Section_Canon";
import { fetchSectionDetail, saveSections } from "./B06_Section_Api_Fetch";
import { staleKeyAgainstScreen, USER_TOUCHED_KEYS } from "./B06_Section_Cross_Refresh";
import { kindChangedChainages, STRUCTURE_ADJUST_KEYS } from "./B06_Section_Api_Culvert_Options";
import type { PipelineStation } from "../A00_Common/design/logic/design_pipeline_types";
import type { DesignStoreValues } from "../A00_Common/design/design_store";
import { useDesignStore } from "../A00_Common/design/design_store";
import {
carryStationKeys,
KEYED_STATES,
registeredKeys,
stationIntervalOf,
useStationKeyList,
type Keyed,
type KeyedState,
} from "./B06_Section_Station_Keys";
import {
ROW_CARRY_KEYS,
sameStationList,
swapCrossSections,
} from "./logic/B06_Section_Station_Swap";
import { mergeCrossPatches } from "./logic/B06_Section_UI_Page_Patches";
import { crossDesignChoices } from "./B06_Section_Cross_Design_Session";
import { readCutSlopeSession, readRockBoundarySession } from "./B06_Section_UI_Page_Persist";
import { readStandardCrossSession } from "./B06_Section_UI_Standard_Panel";
import { balloonOffsetsPayload } from "@util/common_util_mass_haul_balance_view";
import { emitSwap, type DetailListener } from "./B06_Section_Swap_Bus";
export { onAnySwap } from "./B06_Section_Swap_Bus";
const cache = new Map<string, SectionDetailResponse>();
const pending = new Map<string, Promise<SectionDetailResponse>>();
function keyOf(projectId: string, routeId: number): string {
return `${projectId}:${routeId}`;
}
/**
* 초안(관 · 구조물)을 상세에 얹는다 — **여기가 유일한 자리**다.
*
* 서버는 저장분만 얹어 준다. 초안이 있으면 그것이 화면의 정본이므로, 캐시·세션·새 요청 어느 길로
* 들어오든 이 함수를 지나 같은 상태가 된다(2026-09-06 실측). 측점 = 측점 계획 한 벌(`withDraftStations`) ·
* 그림 자료 = 형상 얹기 한 벌(`withDraftShapes` · 서버 `attach_shapes` 짝 · 323-4).
*/
async function withDraftWalls(
detail: SectionDetailResponse,
projectId: string,
routeId: number,
): Promise<SectionDetailResponse> {
setGeneralStations(detail.longitudinal?.stations); // 구조물 기준 측점이 붙을 일반 측점(234-1)
setPlusStations(() => plusStationsOf(projectId)); // 측점 계획이 읽을 추가 측점(368-2)
await loadSavedPlusStations(projectId);
await withDraftStations(detail, projectId, routeId); // 옛 자리 숨김 · 새 자리 미리 뜬 횡단(273-2)
await withDraftShapes(detail, projectId);
withDraftAdjusts(detail, projectId, routeId); // 저장 안 한 조정창 4축 · 구간 · 형식(387-4 · B05 만 열어도)
await withPipeOptions(detail, projectId); // 관 옵션 벽 높이 · 형태 · 흙막이 단(387-4b)
withStructureAreas(detail);
// 초안 자리 미리 뜬 횡단 = 서버가 저장 계획선으로 셈 · 묶음 cross 뒤에 얹힐 수 있음 — 다 돈 뒤 지금 계획선과
// 갈리면 cross 한 번 더(387-8 · 낡음 판정 = 가게 몫 · 종단 판이 접혀 그리기가 안 돌아도)
recrossSaved(projectId, keyOf(projectId, routeId), detail, routeId);
return detail;
}
/**
* 구조물이 선 측점의 절·성토 면적을 **읽어 오는 자리에서 한 번** 다시 얹는다.
*
* 카드는 자기 그림에서 면적을 고쳐 들지만 유토곡선은 카드보다 먼저 계산된다 — 여기서
* 얹지 않으면 새로고침 직후 곡선만 옛 면적으로 남는다(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, routeId);
const inFlight = pending.get(key);
if (inFlight) return inFlight;
// 새로고침으로 메모리가 빈 경우 — 세션에 얹어 둔 한 벌로 바로 선다.
const stored = sessionDetail(projectId, routeId); // 세션 글 = 한 번만 풂(387-7)
if (stored) {
cache.set(key, stored);
void checkSessionCanon(projectId, routeId, stored).catch(() => undefined);
return withDraftWalls(stored, projectId, routeId);
}
}
const request = fetchSectionDetail(projectId, routeId)
.then(async (detail) => {
cache.set(key, detail);
writeState("section-detail", detail, projectId, routeId);
keepCanon(projectId, routeId, detail);
const ready = await withDraftWalls(detail, projectId, routeId);
// 강제로 받음(넓힘 재생성 · 측점 만들기) = 갈아끼움 — 옛 객체를 쥔 보기(숨은 종단 보기 등)가 새것으로(463)
if (options?.force && cache.get(key) === detail)
listeners.get(key)?.forEach((fn) => fn(ready, new Map()));
return ready;
})
.finally(() => {
pending.delete(key);
});
pending.set(key, request);
return request;
}
/**
* 세션 상세 판 확인(433-16) — 새로고침 · 새 탭 첫 화면은 세션 한 벌로 서고, 뒤에서 서버에 한 번 물음(ETag ·
* 같으면 304). 다른 탭 · 다른 PC 가 저장해 판이 다르면 서버 값 위에 **이 탭에서 고친 사용자 칸만**(세션 정본
* 사본과 다른 칸) 얹음 — 낡은 캐시가 [저장] patch 바탕(445)으로 서버 값을 되쓰지 않게. 새 상세로 갈아끼워 듣는
* 쪽이 다시 그림 · 노선 초안이 옛 상세를 쥐고 있으면(hold) 버릴 때 새 판으로(`renewed`).
*/
async function checkSessionCanon(
projectId: string,
routeId: number,
stored: SectionDetailResponse,
): Promise<void> {
const fresh = await fetchSectionDetail(projectId, routeId);
if (!Array.isArray(fresh?.cross_sections)) return;
const raw = readStateRaw("section-detail", projectId, routeId);
if (raw === null || raw === JSON.stringify(fresh)) return; // 같은 판 · 그 사이 버림
const key = keyOf(projectId, routeId);
const current = cache.get(key);
const edits = userEdits(current ?? stored, savedDesigns(projectId, routeId) ?? []);
writeState("section-detail", fresh, projectId, routeId);
keepCanon(projectId, routeId, fresh);
for (const section of fresh.cross_sections) {
const edit = edits.find((entry) => Math.abs(entry.chainage_m - section.chainage_m) < 0.01);
if (edit && section.design) section.design = { ...section.design, ...edit.cells };
}
renewed.set(stored, fresh);
if (current !== stored) return; // 노선 초안 갈아끼움 중 · 그 사이 새로 받음 — 초안을 버리면 새 판
cache.set(key, fresh);
await withDraftWalls(fresh, projectId, routeId);
if (cache.get(key) !== fresh) return;
emitSwap(fresh, new Map());
listeners.get(key)?.forEach((fn) => fn(fresh, new Map()));
}
/** 판이 바뀐 세션 상세 → 새 판 상세(433-16) — 노선 초안 hold 가 쥔 옛 객체를 되돌릴 때. */
const renewed = new WeakMap<SectionDetailResponse, SectionDetailResponse>();
/** 측점마다 정본 사본과 다른 사용자 칸(`USER_TOUCHED_KEYS`) — 이 탭에서 고친 것. */
function userEdits(
detail: SectionDetailResponse,
canonRows: ReadonlyArray<{ chainage_m: number; design: CrossSection["design"] }>,
): Array<{ chainage_m: number; cells: Record<string, unknown> }> {
const out: Array<{ chainage_m: number; cells: Record<string, unknown> }> = [];
for (const section of detail.cross_sections) {
if (!section.design) continue;
const now = section.design as unknown as Record<string, unknown>;
const row = canonRows.find((r) => Math.abs(r.chainage_m - section.chainage_m) < 0.01);
const was = (row?.design ?? {}) as unknown as Record<string, unknown>;
const cells: Record<string, unknown> = {};
for (const name of USER_TOUCHED_KEYS)
if (now[name] !== undefined && JSON.stringify(now[name]) !== JSON.stringify(was[name]))
cells[name] = now[name];
if (Object.keys(cells).length) out.push({ chainage_m: section.chainage_m, cells });
}
return out;
}
const listeners = new Map<string, Set<DetailListener>>();
/** 상세 객체가 갈아끼워짐(측점 수가 바뀜 · 346-2 4파) — 쥔 옛 객체를 버리고 새것으로 다시 그릴 것. */
export function subscribeSectionDetail(
projectId: string,
routeId: number,
fn: DetailListener,
): () => void {
const key = keyOf(projectId, routeId);
const set = listeners.get(key) ?? new Set<DetailListener>();
set.add(fn);
listeners.set(key, set);
return () => set.delete(fn);
}
/**
* 계산 묶음 측점(가게 `stations`)이 측점 목록을 바꿨으면 상세를 **갈아끼움** — 같은 목록이면 그대로(제자리
* 갱신 길이 맡음 · null). 앞 횡단은 측점 열쇠로 이어 받고, 노선 모양이 바뀐 차례면 세션 고침도 열쇠로 넘김
* (사라진 측점 = 「노선 밖 고침 N 건」). 새 상세 = 캐시 · 세션 · 듣는 쪽(횡단 · 종단 보기 · 3D).
*/
export async function swapSectionStations(
projectId: string,
routeId: number,
stations: ReadonlyArray<PipelineStation>,
): Promise<{ detail: SectionDetailResponse; moves: Map<string, string> } | null> {
const key = keyOf(projectId, routeId);
const current = cache.get(key);
if (!current || !stations.length) return null;
const interval = stationIntervalOf(current);
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,
useDesignStore(projectId, null).get("routeDraft") !== null,
); // 초안 없으면 정본 표본(467)
// 설계는 사본 — 면적 얹기 · 다시 셈이 앞 상세(초안 전 상세 등)의 설계를 제자리로 안 고침(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);
else useStationKeyList(projectId, routeId, nextKeys);
// 메모리만 — 세션 상세 = 저장 정본만(387-7 · 새로고침 · B06 바로 열기 = 묶음이 다시 갈아끼움 · 365-1)
cache.set(key, swap.detail);
supersedeDraftStations(current); // 옛 상세에 돌던 맞춤이 새 열쇠 목록을 덮지 않게(415 H1)
await withDraftShapes(swap.detail, projectId, true); // 늘 지금 현황으로 다시 얹음 · 이름 = 계획(323-4 · 458)
withStructureAreas(swap.detail);
if (cache.get(key) !== swap.detail) return null; // 그 사이 다른 갈아끼움 · 새로 받음
emitSwap(swap.detail, swap.moves); // 세션 값 옮김 · 다시 그림(어느 보기든)
listeners.get(key)?.forEach((fn) => fn(swap.detail, swap.moves));
recrossSaved(projectId, key, swap.detail);
return { detail: swap.detail, moves: swap.moves };
}
/** 상세마다 마지막으로 cross 를 부탁한 낡음 지문 — 다시 셈이 못 고친 낡음에 되풀이하지 않음(387-8). */
const askedStale = new WeakMap<SectionDetailResponse, string>();
/** 저장 노선 측점을 갈아끼움 — 그 차례 cross 는 옛 상세를 봐서 새 상세 설계 · 면적이 안 셈 → 묶음이 다 돈 뒤(새 측점
* 종단 · 화면 선이 선 뒤 · 그 전에 세면 계획고 0.5 mm 갈림) cross 한 번 더(387-4b · B05 만 연 면적 = B06). 노선 초안
* 동안은 묶음 새 노선 상세가 맡음. 묶음은 늦게 불러옴(가게 ↔ 묶음 순환 없음).
* `staleOf`(노선 번호)를 주면 화면 선 대비 낡을 때만 · 같은 낡음은 한 번만(387-8 · 묶음이 아직 안 섰으면 그 첫 차례 몫). */
function recrossSaved(
projectId: string,
key: string,
detail: SectionDetailResponse,
staleOf?: number,
): void {
void Promise.all([
import("../A00_Common/design/design_pipeline_cross"),
import("../A00_Common/design/design_pipeline_page"),
])
.then(async ([cross, page]) => {
// 낡음 확인 = 지금 차례만 기다림(맞춤은 묶음 몫 · 읽을 때마다 맞추면 되돌리기 차례가 갈림)
if (staleOf === undefined) await page.reconcilePagePipeline(projectId);
else await page.pagePipeline(projectId)?.settled();
// 그 사이 다른 상세 · 다시 셈 창구 없음(묶음만 · 시험) · 노선 초안 = 안 부탁
if (cache.get(key) !== detail) return;
const pipe = page.pagePipeline(projectId);
if (!page.pipelineOwnsCross(projectId) || pipe?.input("route")) return;
if (staleOf !== undefined) {
const stale = pipe?.generation ? staleKeyAgainstScreen(detail, staleOf) : "";
if (!stale || askedStale.get(detail) === stale) return;
askedStale.set(detail, stale);
}
cross.forceCross();
page.pipelineCross(projectId);
})
.catch(() => undefined);
}
/** 노선 초안 전 상태(349-0o) — 상세(초안 전 객체 그대로 · 되돌리면 캐시) · 측점 열쇠 · 측점 열쇠 칸 다섯(횡단 초안) ·
* 가게 관 · 구조물(440-4 · 묶음이 버릴 때 되씀). */
export interface SectionHold {
detail: SectionDetailResponse;
keys: Keyed[];
cells: Array<[KeyedState, unknown]>;
facilities: Pick<DesignStoreValues, "pipes" | "structures">;
}
type HeldDraft = Omit<SectionHold, "detail"> & { routeId: number };
/**
* 노선 초안 시작 — 초안 전 상세(`detail` · 객체 그대로 — 갈아끼움은 설계를 사본으로 씀) · 지금 측점 열쇠 · 횡단 초안 칸 ·
* 관 · 구조물을 떠 둠 · 세션에도 한 벌(440-4). 초안 둔 채 새로고침이면 그 한 벌 — 세션 칸 · 열쇠 · 관은 이미 초안
* 자리로 옮겨 쓴 값이라 처음 값으로 안 뜸.
*/
export function holdSectionDetail(
projectId: string,
routeId: number,
detail: SectionDetailResponse,
): SectionHold {
const kept = readState<HeldDraft>("route-draft-hold", projectId);
if (kept?.routeId === routeId && readState("route-draft", projectId)) {
const { keys, cells, facilities } = kept;
return { detail, keys, cells, facilities };
}
const sections = detail.cross_sections;
const keys = registeredKeys(projectId, routeId, sections, stationIntervalOf(detail));
const held: HeldDraft = {
routeId,
keys: sections.map((section, i) => ({ key: keys[i], chainageM: section.chainage_m })),
cells: KEYED_STATES.map((name) => [name, readState(name, projectId, routeId)]),
facilities: {
pipes: readState<DesignStoreValues["pipes"]>("pipes", projectId),
structures: readState<DesignStoreValues["structures"]>("structures", projectId),
},
};
writeState("route-draft-hold", held, projectId);
return { detail, keys: held.keys, cells: held.cells, facilities: held.facilities };
}
/**
* 노선 초안을 버림(PLAN 349-0k · 349-0o) — 갈아끼운 상세를 초안 전 상태(`hold`)로 되돌림 · 다시 셈 없음.
* 상세 = 초안 전 객체 · 측점 열쇠 · 횡단 초안 칸 = 그때 값(초안 동안 넘김이 버린 고침도) · 누가거리
* 열쇠 조작값 맵은 열쇠로 옮김. 묶음 측점(`stations`)이 달라도 초안 전 상세 — `same` = 측점 목록이 같음(1 mm).
* 캐시가 없으면 null.
*/
export async function restoreSectionDetail(
projectId: string,
routeId: number,
hold: SectionHold,
stations: ReadonlyArray<PipelineStation>,
): Promise<{ detail: SectionDetailResponse; same: boolean } | null> {
const key = keyOf(projectId, routeId);
const current = cache.get(key);
if (!current) return null;
const saved = renewed.get(hold.detail) ?? hold.detail; // 그 사이 서버 판이 바뀌었으면 새 판(433-16)
const oldKeys = registeredKeys(
projectId,
routeId,
current.cross_sections,
stationIntervalOf(current),
);
const text = (chainageM: number) => chainageM.toFixed(2);
const moves = new Map<string, string>();
current.cross_sections.forEach((section, 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));
});
for (const [name, value] of hold.cells) writeState(name, value ?? null, projectId, routeId);
clearState("route-draft-hold", projectId);
cache.set(key, saved); // 세션 상세는 정본 그대로(387-7)
// 초안 둔 채 새로고침 = 초안 전 상세에 초안 자리 관이 얹혀 있었음 — 되쓴 관 · 구조물로 다시 얹음(440-4)
await withDraftStations(saved, projectId, routeId);
useStationKeyList(projectId, routeId, hold.keys);
await withDraftShapes(saved, projectId);
withStructureAreas(saved);
if (cache.get(key) !== saved) return null; // 그 사이 다른 갈아끼움 · 새로 받음
const sections = saved.cross_sections; // 다시 얹은 뒤 측점(440-4)
const same =
sections.length === stations.length &&
stations.every((station, i) => Math.abs(station.chainageM - sections[i].chainage_m) < 1e-3);
emitSwap(saved, moves);
listeners.get(key)?.forEach((fn) => fn(saved, moves));
return { detail: saved, same };
}
/**
* 캐시를 비운다. routeId를 생략하면 그 프로젝트 전부 —
* 서버 쪽 정본이 바뀌었는데 새 상세를 손에 못 쥔 조작(계획선 편집 저장 등) 뒤에 쓴다.
*/
export function invalidateSectionDetail(projectId: string, routeId?: number): void {
forgetDraftStations(projectId);
if (routeId !== undefined) {
cache.delete(keyOf(projectId, routeId));
forgetCanon(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);
forgetCanon(projectId, Number(key.slice(prefix.length)));
clearState("section-detail", projectId, Number(key.slice(prefix.length)));
}
}
/** 받아 둔 그 노선 상세(받지 않고 · 없으면 null) — 노선 = 페이지 노선 id(B05 평면 횡단 판 · 관 길이 · 416). */
export function peekSectionDetail(
projectId: string,
routeId: number | null,
): SectionDetailResponse | null {
return routeId === null ? null : (cache.get(keyOf(projectId, routeId)) ?? null);
}
/**
* 캐시에 얹힌 **사용자 수정분**을 저장 payload로 뽑는다(2026-08-24 사용자 확정 흐름).
*
* 초기 계산값은 원복용으로 서버에 그대로 있고, 사용자가 만진 값은 이 캐시 한 세트가
* 최종본이다. B05 [임시저장]도 이 세트를 함께 보내야 B06에서 만진 구조물 조정이
* 영구저장소에 남는다 — 안 보내면 캐시만 비워져 편집이 사라진다.
*
* 초기 계산값에는 없는 키(사용자가 만져야 생기는 키)를 측점마다 **통째로** 싣는다 — [저장] patch 의 바탕
* (445 H3 · 세션 고침은 그 위에 `mergeCrossPatches`). `savedAt`(서버 행 누가거리)을 주면 그 자리 행이 없는
* 측점(옮긴 관 · 구조물 · 새 측점 = 서버가 기본 설계로 새로 세움)은 지반 등 입력(`ROW_CARRY_KEYS`)도 실음(445 H2).
*/
export function crossPatchesFromCache(
detail: SectionDetailResponse,
kindChanged: readonly number[] = [],
savedAt?: readonly number[],
): CrossSectionPatch[] {
const patches: CrossSectionPatch[] = [];
// 관 종류를 바꾼 측점(318-4) — 옛 종류 조정값은 서버가 비움 · 캐시에 남은 옛 값을 다시 안 실음
const structureKeys: readonly string[] = STRUCTURE_ADJUST_KEYS;
const reset = (at: number) => kindChanged.some((c) => Math.abs(c - at) < PIPE_MATCH_M);
const rowless = (at: number) => !!savedAt && savedAt.every((c) => Math.abs(c - at) >= 0.01);
for (const at of kindChanged) patches.push({ chainage_m: at, structure_reset: true });
for (const section of detail.cross_sections) {
const design = section.design;
if (!design) continue;
const patch: CrossSectionPatch = { chainage_m: section.chainage_m };
const skip = reset(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>;
const keys = rowless(section.chainage_m)
? [...USER_TOUCHED_KEYS, ...ROW_CARRY_KEYS]
: USER_TOUCHED_KEYS;
for (const key of keys) {
const value = source[key];
if (value === undefined || value === null || (skip && structureKeys.includes(key))) continue;
target[key] = value;
touched = true;
}
if (touched) patches.push(patch);
}
return patches;
}
/**
* [저장] · [확정] 횡단 patch(445) — 바탕 = 캐시 설계의 사용자 칸(측점마다 통째 · 서버 행이 없는 측점은 지반 등
* 입력까지) 위에 세션 고침(`overlay` · 벽 · 단 dict 는 열쇠마다 합침 · 안쪽 null = 되돌림). 캐시가 없으면 세션 고침만.
*/
export function cachedCrossPatches(
projectId: string,
routeId: number,
overlay: readonly CrossSectionPatch[] = [],
): CrossSectionPatch[] {
const detail = cache.get(keyOf(projectId, routeId));
const savedAt = savedDesigns(projectId, routeId)?.map((row) => row.chainage_m);
const base = detail
? crossPatchesFromCache(detail, kindChangedChainages(projectId), savedAt)
: [];
return mergeCrossPatches(base, overlay);
}
/** 노선 저장 뒤 세션에만 있는 고침(카드 선택 · 암선 · 암 경사) — 횡단 보기 [저장] 본문과 같은 칸(445 H5). */
function sessionOverlay(projectId: string, routeId: number): CrossSectionPatch[] {
const out: CrossSectionPatch[] = [];
crossDesignChoices(projectId, routeId).forEach((choice, chainage) => {
const patch: CrossSectionPatch = {
chainage_m: chainage,
ground_type: choice.ground_type,
section_mode: choice.section_mode,
};
if (choice.ditch_side !== undefined) patch.ditch_side = choice.ditch_side;
if (choice.ditch_type !== undefined) patch.ditch_type = choice.ditch_type;
if (choice.paved !== undefined) patch.paved = choice.paved;
if (choice.two_stage_slope !== undefined) patch.two_stage_slope = choice.two_stage_slope;
if (typeof choice.ditch_choice === "boolean") patch.ditch_choice = choice.ditch_choice;
out.push(patch);
});
const rock = readRockBoundarySession(projectId, routeId) ?? {};
for (const [chainage, offset] of Object.entries(rock))
if (typeof offset === "number")
out.push({ chainage_m: Number(chainage), rock_boundary_offset_m: offset });
for (const [chainage, ratio] of Object.entries(readCutSlopeSession(projectId, routeId)))
out.push({ chainage_m: Number(chainage), cut_slope_ratio_user: ratio });
return out.filter((patch) => Number.isFinite(patch.chainage_m));
}
/**
* 노선 저장 뒤 고침을 영구저장소에 남긴다 — 횡단 보기 [저장]과 같은 본문(캐시 사용자 칸 · 카드 선택 · 암선 ·
* 암 경사 · 표준 횡단면 · 풍선 자리 · 445 H5). 수정분이 없어도 한 번 보냄 — 서버가 지금 종단으로 횡단을 다시 셈
* (429 ④ · 노선 뒤에 나간 계획고 초안). 저장 실패는 호출자가 처리한다.
*/
export async function saveCachedCrossPatches(projectId: string, routeId: number): Promise<number> {
const patches = cachedCrossPatches(projectId, routeId, sessionOverlay(projectId, routeId));
const standard = readStandardCrossSession(projectId) as StandardCrossSection | null;
await saveSections(
projectId,
routeId,
standard ?? undefined,
patches.length ? patches : undefined,
{ balloon_offsets: balloonOffsetsPayload() },
);
clearState("kindreset", projectId); // 비울 자리를 보냈음(318-4)
return patches.length;
}