Files
Aislo/B05_Profile/B05_Profile_Api_Fetch.ts
T
eomsangdonandClaude Opus 5.5 4b6800e387 feat(472-6 6-B 노선 바뀐 [저장] 한 본문): 노선 저장 · 관 · 구조물 다시 얹기 · 횡단 고침 넘김을 서버 한 창구로 — 전부 아니면 없음
- POST /design/save 에 route(노선 초안) · carry(옛 노선 세션 칸) 칸 · 서버 = 노선 저장 → Node facility.rebase(rebasePipeDraft · rebaseStructureDraft) → 6-A 차례(새 노선) → Node stations.carry(routeCarryPatches) → 횡단 저장
- 되돌림 범위 = 노선 행 · 자식 표 · 단계 · 배수 폴더 · 노선 파일 · 지표면 확정(설계 지형 바꿈)
- 손 상단측은 안 넘김(요구 274) · 노선 바뀐 [확정] = [저장](새 노선 본 뒤 다시)
- 브라우저 = 노선 초안 + 사용자 칸만 한 본문 · 옛 차례 길(saveRouteDraft 뒤 flush · carryAfterRouteSave · keepDraftsOnNewRoute) · 부름 0 된 flush 창구 여섯 · saveCachedCrossPatches 걷음
- 등록부 R9 stations.carry · F10 facility.rebase · 옛 차례 단언 시험 한 본문 꼴로 · test_472_6_route_save(옛 길 = 새 길 · 실패 되돌림)

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

308 lines
12 KiB
TypeScript

/* =============================================================================
* B05_Profile_Api_Fetch.ts
* 2차 워크플로우(경로 설계) API 클라이언트
*
* 백엔드 계약 (B05_Profile_Router.py):
* POST /api/projects/{project_id}/route/confirm → 최신 경로 확정
*
* 규칙:
* - 모든 제어 상수는 config_frontend에서 참조 (하드코딩 금지).
* - 오류 응답 형식 {status:"error", message:"..."}을 Error로 변환.
* ========================================================================== */
import { clearState, readState, writeState } from "../A00_Common/b_page_state";
import { fetchConfirmedSurface } from "../B04_PreProcess/B04_PreProcess_Api_Fetch";
import { API_ANALYSIS_TIMEOUT_MS, API_BASE_URL, API_TIMEOUT_MS } from "@config/config_frontend";
/** 경로 제어점 (BP/EP/CP) */
export interface RoutePoint {
x: number;
y: number;
z?: number;
order?: number;
}
export interface CirclePoint extends RoutePoint {
radius_m: number;
}
/** 계획선 산출 요약 (실패 시 null) */
export interface RouteGradeSummary {
id: string;
cut_area_m2: number;
fill_area_m2: number;
balance_error_m2: number;
max_grade_pct: number;
vertical_curve_count: number;
pvi_count: number;
balance_segment_count: number;
balanced: boolean;
main_direction: string;
suggested_elevation_offset_m: number | null;
warnings: string[];
}
/** 경로 확정 결과 (RouteConfirmResponse) */
export interface RouteConfirmResponse {
status: string;
project_id: string;
route_id: number;
confirmed: boolean;
/** 실패한 하위 차례(비정규 측점 횡단 · 상단측 병합) — 확정은 됨(443). */
failed_parts?: string[];
}
export interface RouteLatestResponse {
status: string;
project_id: string;
route: {
id: number;
status: string;
surface_model_id: number | null;
total_length_m: number | null;
min_slope: number | null;
max_slope: number | null;
mean_slope: number | null;
cost_score: number | null;
algorithm_params?: Record<string, unknown> | null;
} | null;
route_points: Array<RoutePoint & { chainage_m?: number; slope_percent?: number }>;
surface_params: {
source_filter: string;
method: string;
smooth: boolean;
contour_interval_m: number;
};
route_params: {
points?: {
bp?: RoutePoint | null;
ep?: RoutePoint | null;
cp?: RoutePoint[];
ap?: CirclePoint[];
fp?: CirclePoint[];
};
options?: Record<string, unknown>;
algorithm?: string;
station_interval_m?: number | null;
cross_half_width_m?: number | null;
cross_sample_interval_m?: number | null;
long_sample_interval_m?: number | null;
max_grade_pct?: number | null;
min_vertical_radius_m?: number | null;
min_tangent_length_m?: number | null;
balance_segment_length_m?: number | null;
start_elevation_offset_m?: number | null;
end_elevation_offset_m?: number | null;
enforce_pipe_clearance?: boolean | null;
/** 시작 측점 · 누가거리 표시(448) — B05 라벨만. */
station_display?: { station: number; cumulative: number } | null;
} | null;
}
/** 공통 fetch 헬퍼: 타임아웃 + 인증 헤더 + 오류 응답 변환.
*
* `timeoutMs`를 주면 그 값으로 끊는다. 격자 해석처럼 오래 걸리는 요청은
* `API_ANALYSIS_TIMEOUT_MS`를 넘긴다 — 기본값으로 두면 계산 도중 abort 된다. */
async function requestJson<T>(
path: string,
init: RequestInit,
timeoutMs: number = API_TIMEOUT_MS,
): Promise<T> {
const controller = new AbortController();
const timeoutId = window.setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(`${API_BASE_URL}${path}`, {
...init,
credentials: "include",
headers: {
"Content-Type": "application/json",
...(init.headers ?? {}),
},
signal: controller.signal,
});
const payload = (await response.json()) as T & { message?: string };
if (!response.ok) {
throw new Error(payload.message ?? `HTTP ${response.status}`);
}
return payload;
} catch (error) {
// AbortError 원문("signal is aborted without reason")은 원인을 알 수 없으니 바꿔 준다.
if (error instanceof DOMException && error.name === "AbortError") {
throw new Error(`요청이 ${Math.round(timeoutMs / 1000)}초 안에 끝나지 않았습니다.`);
}
throw error;
} finally {
window.clearTimeout(timeoutId);
}
}
/** 등고선 간격 재적용 값을 서버(stage 1 params)에 영속화한다. */
export async function updateContourInterval(
projectId: string,
contourIntervalM: number,
): Promise<{ status: string; contour_interval_m: number }> {
return requestJson<{ status: string; contour_interval_m: number }>(
`/projects/${projectId}/route/contour-interval`,
{ method: "PUT", body: JSON.stringify({ contour_interval_m: contourIntervalM }) },
);
}
/** 종단 계획선 편집 델타 (자동 선형 대비 측점 계획고 델타 + 종단곡선 반경). */
export interface ProfileAlignmentEdits {
station_offsets: Record<string, number>;
curve_radii: Record<string, number>;
}
export interface ProfileAlignmentSaveResponse {
status: string;
project_id: string;
route_id: number;
profile_alignment: unknown;
grade_summary: RouteGradeSummary | null;
/** 측점 · 관 · 구조물 자리가 없어 서버가 버린 계획고 편집 자리(m · 213-2). */
dropped_edit_chainages?: number[];
}
/**
* 종단 계획선 사용자 편집을 영속화한다.
* 화면은 즉시 계산해 보여주고, 여기서 **편집 델타만** 보내면 서버가 저장된 자동
* 선형에 다시 얹어 정본(longitudinal.json)을 만든다.
*/
export async function saveProfileAlignment(
projectId: string,
routeId: number,
edits: ProfileAlignmentEdits,
): Promise<ProfileAlignmentSaveResponse> {
return requestJson<ProfileAlignmentSaveResponse>(
`/projects/${projectId}/route/profile-alignment`,
{
method: "PUT",
body: JSON.stringify({ route_id: routeId, ...edits }),
},
);
}
/** B05 페이지 설정(448) — 사용자가 넣은 값 그대로(빈 칸 = null = 법정값). */
export interface PageSettingsBody {
design_speed_kph: 20 | 30 | 40;
terrain_type: "normal" | "special";
max_grade_pct: number | null;
min_vertical_radius_m: number | null;
min_tangent_length_m: number | null;
enforce_pipe_clearance: boolean;
station_display: { station: number; cumulative: number };
}
/** 페이지 설정을 stage 2 params 에 얹고 종단 경고 기준을 갈아 끼운다(기하 그대로). */
export async function savePageSettings(
projectId: string,
body: PageSettingsBody,
): Promise<{ warnings: string[]; profile_updated: boolean }> {
return requestJson(`/projects/${projectId}/route/page-settings`, {
method: "PUT",
body: JSON.stringify(body),
});
}
/** 확정 시 비정규 측점 횡단을 생성하기 위한 입력(빈 값이면 확정만 한다). */
export interface RouteConfirmRequest {
filter_key?: string;
method?: string;
smooth?: boolean;
surface_model_id?: number;
irregular_stations?: Array<{ chainage_m: number; structure: string }>;
/** 측점 상단측(=측구 방향) 사용자 변경분 — 3D 램프 클릭으로 지정. */
uphill_overrides?: Array<{ chainage_m: number; side: "left" | "right" }>;
}
/** 프로젝트의 최신 경로를 확정한다. 비정규 측점이 있으면 그 횡단까지 생성한다.
* `markStageComplete=false`는 [임시저장]용 — 데이터(경로 CONFIRMED·비정규 횡단·상단측
* 병합)는 그대로 저장하되 워크플로 stage 2 완료 전이를 하지 않는다(2026-08-08 재정의). */
export async function confirmRoute(
projectId: string,
body: RouteConfirmRequest = {},
markStageComplete = true,
): Promise<RouteConfirmResponse> {
const query = markStageComplete ? "" : "?mark_stage_complete=false";
return requestJson<RouteConfirmResponse>(`/projects/${projectId}/route/confirm${query}`, {
method: "POST",
body: JSON.stringify(body),
});
}
/** 세션 상단측(측구 방향) 변경분 — 요청 본문 모양. */
function uphillOverridesOf(
projectId: string,
): NonNullable<RouteConfirmRequest["uphill_overrides"]> {
const stored = readState<Record<string, "left" | "right">>("uphill", projectId);
return Object.entries(stored ?? {})
.filter(([, side]) => side === "left" || side === "right")
.map(([chainage, side]) => ({ chainage_m: Number(chainage), side }));
}
/** [저장] 상단측 차례 본문 한 벌(463 · 요구 271-5 · 472-6 한 본문 `uphill` 칸) — 노선 캐시 지표 조건 + 확정 지표면
* id(서버가 비정규 측점 횡단을 맞춤) · 비정규 목록 = 빈 목록(서버가 정본 관 · 구조물에서 셈) · 상단측 = 세션.
* B06 에서 [저장]해도 세션 상단측이 나감(B05 · B06 은 한 페이지 · 2026-09-06). */
export async function routePartsBody(projectId: string): Promise<RouteConfirmRequest> {
const latest =
readRouteLatestCache(projectId) ?? (await fetchLatestRoute(projectId).catch(() => null));
const surface = await fetchConfirmedSurface(projectId).catch(() => null);
return {
filter_key: latest?.surface_params?.source_filter,
method: latest?.surface_params?.method,
smooth: latest?.surface_params?.smooth,
surface_model_id: surface?.model_id ?? undefined,
irregular_stations: [],
uphill_overrides: uphillOverridesOf(projectId),
};
}
/** [초기화] 응답 — 초기 자동 계산 상태로 재구성된 경로. */
export interface RouteResetResponse {
status: string;
project_id: string;
route_id: number;
deleted_routes: number;
/** 초기값 스냅샷을 되돌렸으면 true. false면 스냅샷이 없어 재계산으로 폴백한 것이다. */
restored?: boolean;
}
/** [초기화] — 사용자 편집을 전부 버리고 초기값으로 되돌린다. 초기값 스냅샷이 있으면
* 복원이라 빠르지만, 없는 옛 프로젝트는 재계산으로 폴백하므로 분석용 타임아웃을 쓴다.
* 초기 설계가 실패로 끝난 프로젝트는 서버가 409로 거부한다 — 되돌릴 기준이 없어
* 재계산으로 얼버무리지 않는다(2026-09-02). 그 안내 문구가 그대로 오류 토스트에 뜬다. */
export async function resetRouteDesign(projectId: string): Promise<RouteResetResponse> {
return requestJson<RouteResetResponse>(
`/projects/${projectId}/route/reset`,
{ method: "POST" },
API_ANALYSIS_TIMEOUT_MS,
);
}
export async function fetchLatestRoute(projectId: string): Promise<RouteLatestResponse> {
return requestJson<RouteLatestResponse>(`/projects/${projectId}/route/latest`, {
method: "GET",
});
}
/* 최신 경로 응답은 ④ 계산 결과다 — 키·이관은 등록표(`b_page_state`)가 맡는다.
B04에서 지표면을 다시 확정하면 옛 확정값이 남아 B05가 이전 지형을 그리므로, 확정
직후 `clearRouteLatestCache`로 버린다. */
/** 세션 캐시에서 최신 경로 응답을 읽는다. 없거나 깨졌으면 null(다음 진입은 DB 조회). */
export function readRouteLatestCache(projectId: string): RouteLatestResponse | null {
return readState<RouteLatestResponse>("latest", projectId);
}
/** 최신 경로 응답을 세션 캐시에 넣는다. 용량 초과 등으로 실패해도 화면은 그대로 돈다. */
export function writeRouteLatestCache(projectId: string, value: RouteLatestResponse): void {
writeState("latest", value, projectId);
}
export function clearRouteLatestCache(projectId: string): void {
clearState("latest", projectId);
// 설정값에 노선 id 가 실려 있어 함께 버려야 옛 노선을 가리키지 않는다(2026-09-06).
clearState("section-context", projectId);
}