오늘 같은 계통이 두 번 났음 — 키는 등록표에서 받는데 **저장소는 제 맘대로** 고르는 자리. · `rockb` — 키를 날문자열로 만들어 읽는 쪽이 늘 빈 값(`f8fafd23`) · 화면 취향 — 키는 맞았는데 저장소를 직접 골라 **절반만** 옮겨짐(`9db84d9d`) 남은 두 자리(암 경계선 저장·표시 반폭)도 `storageOf` 를 거치게 함. 지금은 둘 다 초안이라 세션이 맞지만, 통이 바뀌면 조용히 갈릴 자리였음. 그물도 넓힘(`test_session_keys_registered.py`) — 등록표 키를 쓰는 파일이 저장소를 이름으로 직접 고르면 깨짐. 고르는 곳은 `b_page_state` 하나. 앱 전역 값(`CURRENT_PROJECT_ID_KEY`)은 등록표 밖이라 제외하고 이유를 적어 둠. **훑어 보니 남은 위반 0곳.** Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
302 lines
14 KiB
TypeScript
302 lines
14 KiB
TypeScript
/* =============================================================================
|
|
* B06_Section_UI_Page_Persist.ts
|
|
* B06 페이지의 **저장 흐름** — 암 경계선 세션 저장소, 편집분 수집, [저장]·[확정].
|
|
*
|
|
* `B06_Section_UI_Page` 에서 떼어낸 몫이다(700줄 제한, 2026-09-02). 화면 조립·조정창
|
|
* 배선은 페이지에 남고, 여기에는 "세션에 쌓인 조작을 정본으로 내보내는" 경로만 둔다
|
|
* (CLAUDE.md 5장 데이터 3층: 영구저장은 [저장]·[확정]에서만).
|
|
* ========================================================================== */
|
|
|
|
import { hideLoadingOverlay, showLoadingOverlay, showToast } from "@ui/ui_template_elements";
|
|
import { goToWorkflowStage, WORKFLOW_STEP_ROUTES } from "../A00_Common/b_workflow_nav";
|
|
import {
|
|
confirmSections,
|
|
saveSections,
|
|
type CrossSectionPatch,
|
|
type SectionContextResponse,
|
|
type SectionDetailResponse,
|
|
} from "./B06_Section_Api_Fetch";
|
|
import { invalidateSectionDetail } from "./B06_Section_Section_Store";
|
|
import { flushPendingPipes } from "../B05_Profile/B05_Profile_Api_Pipes_Draft";
|
|
import { flushPendingStructures } from "../B05_Profile/B05_Profile_Api_Structures";
|
|
import { flushUphillOverrides } from "../B05_Profile/B05_Profile_Api_Fetch";
|
|
import { buildCrossPatches, type CrossPatchSources } from "./B06_Section_UI_Page_Patches";
|
|
import { readState, storageOf } from "../A00_Common/b_page_state";
|
|
import {
|
|
applyStructureAreaRows,
|
|
STRUCTURE_AREA_KEYS,
|
|
structureAreaRows,
|
|
} from "./B06_Section_Structure_Layouts";
|
|
import { crossDesignChoices } from "./B06_Section_Cross_Design_Session";
|
|
import type { StandardCrossSection } from "./B06_Section_Api_Fetch";
|
|
import type { RockBoundaryControl } from "./B06_Section_UI_Section_View";
|
|
import { balloonOffsetsPayload } from "@util/common_util_mass_haul_balance_view";
|
|
import { L } from "./B06_Section_UI_Page_Common";
|
|
|
|
/**
|
|
* 세션에 쌓인 암 경계선 오프셋(측점키 → m). 없거나 손상되면 빈 객체.
|
|
*
|
|
* **등록표를 거쳐 읽는다**(2026-09-07 고침). 예전에는 옛 키 `b06:rockb:{p}:{r}` 를 날문자열로
|
|
* 읽었는데, 쓰는 쪽(`B06_Section_UI_Page.ts` 의 `stateKey("rockb", …)`)은 새 키
|
|
* `aislo:draft:rockb:{p}:{r}` 에 쓰고 있어 **읽는 쪽이 늘 빈 값**을 받았다. 그래서
|
|
* 계획선을 고쳐 횡단을 다시 계산할 때(`B06_Section_Cross_Refresh`) 사용자가 옮긴 암 경계선이
|
|
* 안 실려 나가 토사/암 나눔이 기본값으로 돌아갔다 — 수량이 갈리는 자리다.
|
|
* 실측(용화 5601e828, route 169): 경계선을 -0.5 → -0.8m 로 옮기니 새 키에만 `{"0.00":-0.8}`
|
|
* 가 쌓이고 옛 키는 아예 없었다.
|
|
*/
|
|
export function readRockBoundarySession(
|
|
projectId: string,
|
|
routeId: number,
|
|
): Record<string, number> {
|
|
const stored = readState<Record<string, number>>("rockb", projectId, routeId);
|
|
return stored && typeof stored === "object" ? stored : {};
|
|
}
|
|
|
|
/** 암 경계선 오프셋 저장소 — 값(Map)과 조정창 제어기를 함께 낸다. */
|
|
export interface RockBoundaryStore {
|
|
/** 측점키(누가거리 2자리) → 오프셋(m). `buildCrossPatches` 가 그대로 읽는다. */
|
|
offsets: Map<string, number>;
|
|
control: RockBoundaryControl;
|
|
/** 세션값 읽기 — 프로젝트·노선이 정해진 뒤에 부른다. */
|
|
load: () => void;
|
|
/** context(config) 기본값·스텝 반영. */
|
|
setDefaults: (defaultOffsetM: number, stepM: number) => void;
|
|
}
|
|
|
|
/**
|
|
* 암 경계선 오프셋(측점별) 세션 저장소.
|
|
*
|
|
* 서버 재계산 없이 프론트 세션(sessionStorage)에 보관하고, 종횡단 확정 시
|
|
* cross_patches로 DB(data.design.rock_boundary_offset_m)에 병합한다.
|
|
*/
|
|
export function createRockBoundaryStore(options: {
|
|
sessionKey: () => string | null;
|
|
detail: () => SectionDetailResponse | null;
|
|
refreshCard: (chainageM: number) => void;
|
|
/** 경계 이동 → 2단계 무릎·단면적 재계산. */
|
|
recompute: (chainageM: number) => void;
|
|
}): RockBoundaryStore {
|
|
const { sessionKey, detail, refreshCard, recompute } = options;
|
|
let rockBoundaryDefault = -0.5;
|
|
let rockBoundaryStep = 0.1;
|
|
/**
|
|
* 암 경계선 오프셋은 **0을 넘을 수 없다**(2026-08-02 사용자 지시). 오프셋은 지면선에서
|
|
* 아래로 파고든 깊이라, 양수가 되면 경계선이 지표면 위로 떠올라 토사층이 음수가 된다.
|
|
* DB에 옛 양수값이 남아 있어도 읽는 즉시 0으로 눌러 계산이 뒤집히지 않게 한다.
|
|
*/
|
|
const clamp = (value: number): number => Math.min(value, 0);
|
|
const offsets = new Map<string, number>();
|
|
const key = (chainageM: number): string => chainageM.toFixed(2);
|
|
|
|
function persist(): void {
|
|
const storageKey = sessionKey();
|
|
if (!storageKey) return;
|
|
try {
|
|
storageOf(storageKey).setItem(storageKey, JSON.stringify(Object.fromEntries(offsets)));
|
|
} catch {
|
|
/* 세션 저장 실패는 무시(용량 초과 등) — 값은 메모리에 유지된다. */
|
|
}
|
|
}
|
|
|
|
return {
|
|
offsets,
|
|
load(): void {
|
|
offsets.clear();
|
|
const storageKey = sessionKey();
|
|
if (!storageKey) return;
|
|
try {
|
|
const raw = storageOf(storageKey).getItem(storageKey);
|
|
if (!raw) return;
|
|
const parsed = JSON.parse(raw) as Record<string, number>;
|
|
Object.entries(parsed).forEach(([chainage, offset]) => {
|
|
if (Number.isFinite(offset)) offsets.set(chainage, offset);
|
|
});
|
|
} catch {
|
|
/* 손상된 세션 값은 무시 — 기본값으로 재시작. */
|
|
}
|
|
},
|
|
setDefaults(defaultOffsetM: number, stepM: number): void {
|
|
rockBoundaryDefault = defaultOffsetM;
|
|
rockBoundaryStep = stepM;
|
|
},
|
|
control: {
|
|
get stepM() {
|
|
return rockBoundaryStep;
|
|
},
|
|
get defaultOffsetM() {
|
|
return rockBoundaryDefault;
|
|
},
|
|
offsetFor: (section) =>
|
|
clamp(
|
|
offsets.get(key(section.chainage_m)) ??
|
|
section.design?.rock_boundary_offset_m ??
|
|
rockBoundaryDefault,
|
|
),
|
|
adjust: (chainageM, deltaM) => {
|
|
const stored = detail()?.cross_sections.find(
|
|
(section) => Math.abs(section.chainage_m - chainageM) < 0.01,
|
|
)?.design?.rock_boundary_offset_m;
|
|
const current = clamp(offsets.get(key(chainageM)) ?? stored ?? rockBoundaryDefault);
|
|
offsets.set(key(chainageM), clamp(Math.round((current + deltaM) * 100) / 100));
|
|
persist();
|
|
refreshCard(chainageM);
|
|
recompute(chainageM);
|
|
},
|
|
reset: (chainageM) => {
|
|
offsets.set(key(chainageM), rockBoundaryDefault);
|
|
persist();
|
|
refreshCard(chainageM);
|
|
recompute(chainageM);
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
/** [저장]·[확정]이 함께 쓰는 페이지 상태 창구. */
|
|
export interface SectionPersistContext {
|
|
projectId: string | null;
|
|
routeId: () => number | null;
|
|
detail: () => SectionDetailResponse | null;
|
|
context: () => SectionContextResponse | null;
|
|
standardValues: () => StandardCrossSection | undefined;
|
|
/** 조정창 구간값을 정본으로 내보낸다(세션 → 서버). */
|
|
flushCulvertOptions: () => Promise<void>;
|
|
/** 측점별 편집분의 출처 묶음 — 세션·제어기에 흩어진 값을 페이지가 모아 준다. */
|
|
patchSources: () => CrossPatchSources;
|
|
}
|
|
|
|
/** 확정과 임시 저장이 함께 보내는 편집분(암 경계선 오프셋 + 유토곡선 + balloon 위치). */
|
|
export function collectSectionEdits(ctx: SectionPersistContext): {
|
|
crossPatches: CrossSectionPatch[];
|
|
massHaul: Record<string, unknown> | undefined;
|
|
} {
|
|
const crossPatches = buildCrossPatches(ctx.patchSources());
|
|
const detail = ctx.detail();
|
|
// 구조물 폐회로 면적 — **카드를 그리지 않은 측점까지** 여기서 다 계산해 싣는다
|
|
// (2026-09-06 사용자 확정: 「일단은 브라우저 계산으로」). 카드 그리기가 고쳐 둔 값에
|
|
// 기대면 화면에 안 뜬 측점이 표준값으로 남는다.
|
|
const byChainage = new Map(crossPatches.map((patch) => [patch.chainage_m, patch]));
|
|
const patchFor = (chainageM: number): CrossSectionPatch => {
|
|
const existing = byChainage.get(chainageM);
|
|
if (existing) return existing;
|
|
const created: CrossSectionPatch = { chainage_m: chainageM };
|
|
byChainage.set(chainageM, created);
|
|
crossPatches.push(created);
|
|
return created;
|
|
};
|
|
// 카드 버튼 선택(지반유형·단면유형·측구·포장·2단 비탈) — 세션 초안이 정본으로 나가는
|
|
// 유일한 길이다(2026-09-06 사용자 확정: 버튼을 누를 때 서버가 저장하지 않는다).
|
|
crossDesignChoices(ctx.projectId, ctx.routeId()).forEach((choice, chainage) => {
|
|
const patch = patchFor(chainage);
|
|
patch.ground_type = choice.ground_type;
|
|
patch.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 (detail) {
|
|
// 구조물 폐회로 면적 — **카드를 그리지 않은 측점까지** 여기서 다 계산한다
|
|
// (2026-09-06 사용자 확정: 「일단은 브라우저 계산으로」).
|
|
applyStructureAreaRows(detail.cross_sections, structureAreaRows(detail.cross_sections));
|
|
// 면적은 **전 측점**을 싣는다 — 브라우저가 만든 값이 곧 작업본이다. 카드 버튼을
|
|
// 바꾸면 구조물이 없는 측점의 면적도 달라지므로 구조물 측점만 보내면 수량이 어긋난다.
|
|
for (const section of detail.cross_sections) {
|
|
const design = section.design as Record<string, unknown> | undefined;
|
|
if (!design) continue;
|
|
let patch: CrossSectionPatch | null = null;
|
|
for (const key of STRUCTURE_AREA_KEYS) {
|
|
if (typeof design[key] !== "number") continue;
|
|
patch = patch ?? patchFor(section.chainage_m);
|
|
patch[key] = design[key] as number;
|
|
}
|
|
}
|
|
}
|
|
// 유토곡선 **정본은 서버가 낸다**(2026-09-06 사용자 확정) — 저장 뒤 `recompute_server_side`
|
|
// 가 Node 로 다시 계산해 덮어쓴다. 그래서 여기서는 곡선도 배분도 만들지 않는다.
|
|
// 서버가 만들 수 없는 것 하나만 보낸다: 사용자가 끌어 옮긴 balloon 위치(화면값).
|
|
const offsets = balloonOffsetsPayload();
|
|
return {
|
|
crossPatches,
|
|
massHaul: offsets ? { balloon_offsets: offsets } : undefined,
|
|
};
|
|
}
|
|
|
|
/** 세션에 쌓인 조정창·구조물 조작을 정본으로 내보낸다 — [저장]·[확정] 공통 앞단. */
|
|
async function flushPendingEdits(ctx: SectionPersistContext, projectId: string): Promise<void> {
|
|
// 조정창 구간값은 세션에만 있다 — 정본 payload를 모으기 전에 내보낸다
|
|
// (CLAUDE.md 5장: 영구저장은 [저장]·[확정]에서만).
|
|
await ctx.flushCulvertOptions();
|
|
// B05 3D에서 바꾼 상단측(측구 방향)도 여기서 내보낸다 — 예전에는 B05 [임시저장]에만
|
|
// 실려, B06에서 저장·확정하면 세션에만 남아 옛 방향이 정본에 그대로 있었다
|
|
// (2026-09-06). 서버가 종단 정본과 저장된 횡단 설계를 함께 갱신하므로 아래
|
|
// 횡단 patch 저장보다 **먼저** 나가야 사용자 수정이 위에 얹힌다.
|
|
await flushUphillOverrides(projectId).catch(() => undefined);
|
|
// B05에서 만지고 넘어온 구조물 조작분도 여기서 정본에 남긴다. 실패해도 횡단
|
|
// 저장까지 막지는 않는다 — 미저장분은 세션에 남으므로 다시 시도할 수 있다
|
|
// (2026-08-29 실측: 타입이 거절되자 sections/save가 아예 나가지 않았다).
|
|
// B05 배수유역도에서 고친 관 목록(추가·이동·삭제)도 여기서 정본에 남긴다 — 예전에는
|
|
// B05 [임시저장]에만 실려, B06 에서 저장하면 그 편집이 사라졌다(2026-09-06 대응표).
|
|
await flushPendingPipes(projectId).catch((error) => {
|
|
const detail = error instanceof Error ? ` ${error.message}` : "";
|
|
showToast(`배수관 저장에 실패했습니다.${detail}`, "error");
|
|
});
|
|
await flushPendingStructures(projectId).catch((error) => {
|
|
const detail = error instanceof Error ? ` ${error.message}` : "";
|
|
showToast(`구조물 저장에 실패했습니다.${detail}`, "error");
|
|
});
|
|
}
|
|
|
|
/** 임시 저장 — 저장만 하고 페이지는 그대로 둔다. */
|
|
export async function saveCurrentSections(ctx: SectionPersistContext): Promise<void> {
|
|
const routeId = ctx.routeId();
|
|
if (!ctx.projectId || routeId === null) return;
|
|
showLoadingOverlay();
|
|
try {
|
|
await flushPendingEdits(ctx, ctx.projectId);
|
|
const edits = collectSectionEdits(ctx);
|
|
await saveSections(
|
|
ctx.projectId,
|
|
routeId,
|
|
ctx.standardValues(),
|
|
edits.crossPatches.length ? edits.crossPatches : undefined,
|
|
edits.massHaul,
|
|
);
|
|
// 저장으로 구조물 초안이 정본이 됐다 — 화면이 들고 있던 상세는 초안 기준으로 벽을
|
|
// 얹은 사본이라, 그대로 두면 새로 저장된 구조물의 벽이 다음 조회까지 안 붙는다
|
|
// (2026-09-06 실측: 8+0.0 흙막이가 저장 뒤 화면 사본에만 빠져 있었음).
|
|
invalidateSectionDetail(ctx.projectId, routeId);
|
|
showToast(L("B06_Profile_Save_Success"), "success");
|
|
} catch (error) {
|
|
const detail = error instanceof Error ? ` ${error.message}` : "";
|
|
showToast(`${L("B06_Profile_Save_Failed")}${detail}`, "error");
|
|
} finally {
|
|
hideLoadingOverlay();
|
|
}
|
|
}
|
|
|
|
/** 확정 — 저장 뒤 다음 단계(상세설계)로 넘어간다. */
|
|
export async function confirmCurrentSections(ctx: SectionPersistContext): Promise<void> {
|
|
const routeId = ctx.routeId();
|
|
if (!ctx.projectId || routeId === null) return;
|
|
showLoadingOverlay();
|
|
try {
|
|
await flushPendingEdits(ctx, ctx.projectId);
|
|
const edits = collectSectionEdits(ctx);
|
|
await confirmSections(
|
|
ctx.projectId,
|
|
routeId,
|
|
ctx.standardValues(),
|
|
edits.crossPatches.length ? edits.crossPatches : undefined,
|
|
edits.massHaul,
|
|
);
|
|
showToast(L("B06_Profile_Confirm_Success"), "success");
|
|
goToWorkflowStage(ctx.projectId, WORKFLOW_STEP_ROUTES[4]);
|
|
} catch (error) {
|
|
const detail = error instanceof Error ? error.message : L("B06_Profile_Confirm_Failed");
|
|
showToast(`${L("B06_Profile_Confirm_Failed")} ${detail}`, "error");
|
|
} finally {
|
|
hideLoadingOverlay();
|
|
}
|
|
}
|