- GET /surface/confirmed 추가: 확정 구성(모델·필터·표현·평활·등고선간격)과 지형 가장자리만 반환(수 KB, 0.02s). 진입 판정·준비화면·B05의 단일 출처. - B05 진입이 받던 포인트클라우드 JSON 23.8MB 제거 — 실제로 쓰던 값은 bounds뿐. - 준비 표식을 프로젝트 ID에서 확정 signature로 변경: B04에서 다시 확정하면 대시보드 복귀·새 브라우저·B그룹 단계 이동 어느 경로로 들어와도 최신본을 담는다. - preloadSurfaceAssets가 평활 여부를 추측하던 부분 제거(확정 저장값 사용) — 추측이 어긋나면 같은 지형을 두 번 내려받았다. - B04 진입 시 필터·표현·평활·등고선간격을 확정본 값으로 초기화(확정 없으면 기존 기본값). - 모델 확정 직후 준비 표식과 B05 세션 캐시를 비워 옛 지형이 남지 않게 함. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
360 lines
12 KiB
TypeScript
360 lines
12 KiB
TypeScript
/* =============================================================================
|
|
* B05_wf2_Route_Api_Fetch.ts
|
|
* 2차 워크플로우(경로 설계) API 클라이언트
|
|
*
|
|
* 백엔드 계약 (B05_wf2_Route_Router.py):
|
|
* POST /api/projects/{project_id}/route/solve → 경로 탐색 + DB 기록
|
|
* POST /api/projects/{project_id}/route/confirm → 최신 경로 확정
|
|
*
|
|
* 규칙:
|
|
* - 모든 제어 상수는 config_frontend에서 참조 (하드코딩 금지).
|
|
* - 오류 응답 형식 {status:"error", message:"..."}을 Error로 변환.
|
|
* ========================================================================== */
|
|
|
|
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;
|
|
}
|
|
|
|
/** 경로 탐색 실행 요청 (RouteSolveRequest) */
|
|
export interface RouteSolveRequest {
|
|
filter_key: string;
|
|
method?: string;
|
|
smooth?: boolean;
|
|
surface_model_id?: number | null;
|
|
algorithm?: string;
|
|
bp: RoutePoint;
|
|
ep: RoutePoint;
|
|
cp?: RoutePoint[];
|
|
ap?: CirclePoint[];
|
|
fp?: CirclePoint[];
|
|
grade_class?: string;
|
|
paved?: boolean;
|
|
min_curve_radius_m?: number | null;
|
|
max_uphill_grade?: number | null;
|
|
max_downhill_grade?: number | null;
|
|
min_uphill_grade?: number | null;
|
|
min_downhill_grade?: number | null;
|
|
allow_avoid_pass_through?: boolean;
|
|
station_interval_m?: number | null;
|
|
cross_half_width_m?: number | null;
|
|
cross_sample_interval_m?: number | null;
|
|
long_sample_interval_m?: number | null;
|
|
terrain_type?: string;
|
|
main_direction?: string;
|
|
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;
|
|
}
|
|
|
|
/** 계획선 산출 요약 (실패 시 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[];
|
|
}
|
|
|
|
/** 경로 탐색 실행 결과 (RouteSolveResponse) */
|
|
export interface RouteSolveResponse {
|
|
status: string;
|
|
project_id: string;
|
|
route_id: number;
|
|
total_length_m: number;
|
|
metrics: Record<string, unknown>;
|
|
required_points_ok: boolean;
|
|
route_data_path: string;
|
|
longitudinal_length_m: number | null;
|
|
cross_section_count: number | null;
|
|
grade_summary: RouteGradeSummary | null;
|
|
}
|
|
|
|
/** 경로 확정 결과 (RouteConfirmResponse) */
|
|
export interface RouteConfirmResponse {
|
|
status: string;
|
|
project_id: string;
|
|
route_id: number;
|
|
confirmed: boolean;
|
|
}
|
|
|
|
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;
|
|
} | 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);
|
|
}
|
|
}
|
|
|
|
/** 경로 탐색을 실행한다 (비용면 생성 → Dijkstra/ridge-valley → GeoJSON 저장). */
|
|
export async function solveRoute(
|
|
projectId: string,
|
|
request: RouteSolveRequest,
|
|
): Promise<RouteSolveResponse> {
|
|
return requestJson<RouteSolveResponse>(`/projects/${projectId}/route/solve`, {
|
|
method: "POST",
|
|
body: JSON.stringify(request),
|
|
});
|
|
}
|
|
|
|
/** 등고선 간격 재적용 값을 서버(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;
|
|
}
|
|
|
|
/**
|
|
* 종단 계획선 사용자 편집을 영속화한다.
|
|
* 화면은 즉시 계산해 보여주고, 여기서 **편집 델타만** 보내면 서버가 저장된 자동
|
|
* 선형에 다시 얹어 정본(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 }),
|
|
},
|
|
);
|
|
}
|
|
|
|
/** 확정 시 비정규 측점 횡단을 생성하기 위한 입력(빈 값이면 확정만 한다). */
|
|
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" }>;
|
|
}
|
|
|
|
/** 프로젝트의 최신 경로를 확정한다. 비정규 측점이 있으면 그 횡단까지 생성한다. */
|
|
export async function confirmRoute(
|
|
projectId: string,
|
|
body: RouteConfirmRequest = {},
|
|
): Promise<RouteConfirmResponse> {
|
|
return requestJson<RouteConfirmResponse>(`/projects/${projectId}/route/confirm`, {
|
|
method: "POST",
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
export async function fetchLatestRoute(projectId: string): Promise<RouteLatestResponse> {
|
|
return requestJson<RouteLatestResponse>(`/projects/${projectId}/route/latest`, {
|
|
method: "GET",
|
|
});
|
|
}
|
|
|
|
/** B05가 최신 경로·확정 설정값을 탭 세션에 담아 둘 때 쓰는 키(유일한 정의처). */
|
|
export const routeLatestCacheKey = (projectId: string): string => `b05:latest:${projectId}`;
|
|
|
|
/** 담아 둔 최신 경로 값을 버린다. B04에서 지표면을 다시 확정하면 옛 확정값이 남아
|
|
* B05가 이전 지형을 그리게 되므로, 확정 직후 이 값을 지운다. */
|
|
export function clearRouteLatestCache(projectId: string): void {
|
|
try {
|
|
window.sessionStorage.removeItem(routeLatestCacheKey(projectId));
|
|
} catch {
|
|
/* 세션 접근 실패 시에는 다음 진입에서 DB를 읽게 되므로 그대로 둔다. */
|
|
}
|
|
}
|
|
|
|
/* ── 배수유역도 (B05_wf2_Route_Router_Drainage.py) ───────────────────────── */
|
|
|
|
/** 관 매설 구조물 측점 후보 1개. reason: stream=세류 교차, spacing=300m 보충. */
|
|
export interface DrainageCandidate {
|
|
chainage_m: number;
|
|
x: number;
|
|
y: number;
|
|
lon: number;
|
|
lat: number;
|
|
reason: "stream" | "spacing" | "confirmed";
|
|
stream_name: string | null;
|
|
}
|
|
|
|
export interface DrainageCandidateResponse {
|
|
status: string;
|
|
project_id: string;
|
|
route_id: number;
|
|
candidates: DrainageCandidate[];
|
|
}
|
|
|
|
/** 관 1개가 받는 세부 배수유역. 관경(pipe_diameter_mm)은 수식 미확정이라 당분간 항상 null이다. */
|
|
export interface DrainageBasin {
|
|
index: number;
|
|
chainage_m: number;
|
|
/** 관(배관) 매설 지점 좌표 — 계획선 위 마커 렌더용. */
|
|
outlet_lonlat: [number, number];
|
|
polygon_lonlat: Array<[number, number]>;
|
|
area_m2: number;
|
|
relief_m: number;
|
|
flow_length_m: number;
|
|
pipe_diameter_mm: number | null;
|
|
}
|
|
|
|
export interface DrainageBasinResponse {
|
|
status: string;
|
|
project_id: string;
|
|
route_id: number;
|
|
/** 산정에 실제 사용된 배관 지점 — 유역이 없는 관도 포함(마커 동기화용). */
|
|
pipes: DrainageCandidate[];
|
|
/** B04가 분석에 쓴 계획 노선 선형(lon/lat). */
|
|
route_lonlat: Array<[number, number]>;
|
|
/** 2차 전체 배수유역 외곽선 = 분수령. 편집 핸들 간격으로 다시 찍고 저장된 편집분이 반영된 값. */
|
|
main_polygon_lonlat: Array<[number, number]>;
|
|
/** 외곽선 편집 핸들 간격(m). */
|
|
boundary_spacing_m: number;
|
|
/** 저장돼 있던 외곽선 편집 포인트(원래 자리 base, 옮긴 자리 moved). */
|
|
boundary_overrides: Array<{ base: [number, number]; moved: [number, number] }>;
|
|
/** 새 유역 안쪽으로 들어가 버려진 편집 포인트 수. */
|
|
boundary_dropped: number;
|
|
/** 유역 안쪽 상류 세류망 — 하이라이트 토글용. */
|
|
upstream_lonlat: Array<Array<[number, number]>>;
|
|
/** B04 해석 격자 한 변(m). */
|
|
grid_cell_m: number;
|
|
/** 평균 흐름 화살표 — [x, y(사업지 CRS m), 방위(도), 도로도달, 셀 수]. */
|
|
flow_arrows: Array<[number, number, number, boolean, number]>;
|
|
/** 화살표 사이 실제 간격(m). */
|
|
arrow_spacing_m: number;
|
|
basins: DrainageBasin[];
|
|
}
|
|
|
|
/** chainages를 주면 그 위치로 확정 산정하고, 비우면 자동 제안분으로 산정한다. */
|
|
export async function fetchDrainageBasins(
|
|
projectId: string,
|
|
chainages?: number[],
|
|
): Promise<DrainageBasinResponse> {
|
|
// 격자 해석이 포함된 요청이라 캐시가 없으면 수십 초가 걸린다.
|
|
return requestJson<DrainageBasinResponse>(
|
|
`/projects/${projectId}/drainage/basins`,
|
|
{ method: "POST", body: JSON.stringify({ chainages: chainages ?? [] }) },
|
|
API_ANALYSIS_TIMEOUT_MS,
|
|
);
|
|
}
|
|
|
|
/** 사용자가 옮긴 유역 외곽선 포인트만 저장한다(종단 경로 확정 시 모달 승인 후 호출). */
|
|
export async function saveDrainageBoundary(
|
|
projectId: string,
|
|
points: Array<{ base: [number, number]; moved: [number, number] }>,
|
|
): Promise<{ status: string; saved: number }> {
|
|
return requestJson<{ status: string; saved: number }>(
|
|
`/projects/${projectId}/drainage/boundary`,
|
|
{ method: "PUT", body: JSON.stringify({ points }) },
|
|
);
|
|
}
|