외부 AI 교차검증 미통과 지적을 전부 수정한다. 1. 마이그레이션: 확정 저장분은 structure 문자열뿐(structureType 없음) — 라벨 파싱 판별 추가(기성막이/대피로 X.Xm/관종 D직경). 명시 필드가 라벨 파싱보다 우선. 2. 서버 검증 강화(_validate_types 확장): 레지스트리 배치형태 대조, 미정의 옵션 거절, number 옵션 유한·0 이상, select 선택지 검사, required 옵션 누락 거절, structure_id 중복 거절, 노선 연장 범위 검증(라우터가 get_latest_route로 총연장 주입, 없으면 생략). 3. 기본값 원칙: 법정 명시값(별표2 측구 30cm·대피소 5/15m 등)·사용자 기확정값(골막이)만 default 유지. 옹벽·돌쌓기 높이, 사토장·토취장 면적/용량, 포장·쇄석 두께 등 미확정 수치는 default 제거 + required (화면 placeholder "필수 입력"+빈 값 추가 차단, 서버도 거절). 4. 404: get_project_storage_relative_path는 없는 프로젝트에서 LookupError를 던짐 — _project_root에서 잡아 None, 라우터 예외 사다리에도 LookupError→404 분기. 5. STALE 정합: _invalidate_downstream이 성공 여부 반환 — invalidated_downstream은 실제 전파 성공 시에만 true. pytest 42건(tmp/tests) 통과 · tsc 0 · ruff 통과. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
172 lines
5.8 KiB
TypeScript
172 lines
5.8 KiB
TypeScript
/* =============================================================================
|
|
* B05_Profile_Api_Structures.ts
|
|
* 구조물 타입 레지스트리·구조물 정본 API 클라이언트.
|
|
*
|
|
* 백엔드 계약 (B05_Profile_Structures_Router.py):
|
|
* GET /api/projects/structure-types → 타입 레지스트리
|
|
* GET /api/projects/{project_id}/route/structures → 목록 + 판번호
|
|
* PUT /api/projects/{project_id}/route/structures → 목록 전체 덮어쓰기
|
|
*
|
|
* 타입 정의를 화면에 박아 두지 않는다 — 레지스트리 파일 하나만 고치면 폼까지 따라오게
|
|
* 하려는 것이라, 목록은 반드시 서버에서 받아 온다.
|
|
* ========================================================================== */
|
|
|
|
import { API_BASE_URL, API_TIMEOUT_MS } from "@config/config_frontend";
|
|
|
|
/** 배치형태 — 점형(측점 1개) / 구간형(시~종점) / 부지형(위치+면적). */
|
|
export type StructurePlacement = "point" | "interval" | "site";
|
|
/** 노선 기준 설치 측. 횡단(B06) 연계에 쓴다. */
|
|
export type StructureSide = "left" | "right" | "center" | "cross";
|
|
|
|
export interface StructureOptionField {
|
|
key: string;
|
|
label: string;
|
|
input: "select" | "number" | "text";
|
|
choices: string[];
|
|
unit: string | null;
|
|
default: string | number | null;
|
|
/** 미확정 항목(기본값 없음) — 사용자가 값을 넣어야 저장된다. */
|
|
required?: boolean;
|
|
}
|
|
|
|
export interface StructureType {
|
|
type_id: string;
|
|
group: string;
|
|
name: string;
|
|
placement: StructurePlacement;
|
|
options: StructureOptionField[];
|
|
style: { color?: string; abbr?: string };
|
|
drawing_views: string[];
|
|
/** 다른 정본이 관리하는 타입(배관 = pipe_points.json) — 구조물 목록에 넣지 않는다. */
|
|
managed_by: string | null;
|
|
reference_only: boolean;
|
|
enabled: boolean;
|
|
}
|
|
|
|
export interface StructureInstance {
|
|
structure_id?: string | null;
|
|
type_id: string;
|
|
placement: StructurePlacement;
|
|
chainage_m?: number | null;
|
|
start_m?: number | null;
|
|
end_m?: number | null;
|
|
side: StructureSide;
|
|
offset_m: number;
|
|
options: Record<string, string | number>;
|
|
memo: string;
|
|
placement_source: "manual" | "suggested" | "automatic";
|
|
status: "draft" | "confirmed";
|
|
revision: number;
|
|
geometry: Record<string, unknown> | null;
|
|
}
|
|
|
|
interface StructureTypesResponse {
|
|
status: string;
|
|
schema_version: number;
|
|
types: StructureType[];
|
|
}
|
|
|
|
export interface StructureListResponse {
|
|
status: string;
|
|
project_id: string;
|
|
revision: number;
|
|
structures: StructureInstance[];
|
|
}
|
|
|
|
export interface StructureSaveResponse {
|
|
status: string;
|
|
project_id: string;
|
|
revision: number;
|
|
count: number;
|
|
invalidated_downstream: boolean;
|
|
}
|
|
|
|
/** 다른 창이 먼저 저장해 판번호가 어긋났다 — 화면이 최신본을 다시 받아야 한다. */
|
|
export class StructureConflictError extends Error {
|
|
constructor(
|
|
message: string,
|
|
readonly currentRevision: number,
|
|
) {
|
|
super(message);
|
|
this.name = "StructureConflictError";
|
|
}
|
|
}
|
|
|
|
async function requestJson<T>(path: string, init: RequestInit = {}): Promise<T> {
|
|
const controller = new AbortController();
|
|
const timer = window.setTimeout(() => controller.abort(), API_TIMEOUT_MS);
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}${path}`, {
|
|
credentials: "include",
|
|
headers: { "Content-Type": "application/json" },
|
|
signal: controller.signal,
|
|
...init,
|
|
});
|
|
const payload = await response.json().catch(() => null);
|
|
if (!response.ok) {
|
|
const message =
|
|
(payload && typeof payload.message === "string" && payload.message) ||
|
|
`요청이 실패했습니다 (${response.status}).`;
|
|
if (response.status === 409) {
|
|
throw new StructureConflictError(message, Number(payload?.revision ?? 0));
|
|
}
|
|
throw new Error(message);
|
|
}
|
|
return payload as T;
|
|
} finally {
|
|
window.clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
/** 타입 레지스트리는 서버 배포 중에 바뀌지 않으므로 탭 수명 동안 한 번만 받는다. */
|
|
let typesCache: Promise<StructureType[]> | null = null;
|
|
|
|
export function fetchStructureTypes(): Promise<StructureType[]> {
|
|
if (!typesCache) {
|
|
typesCache = requestJson<StructureTypesResponse>("/projects/structure-types", {
|
|
method: "GET",
|
|
})
|
|
.then((payload) => payload.types.filter((type) => type.enabled))
|
|
.catch((error) => {
|
|
typesCache = null; // 실패한 약속을 남겨 두면 다시 시도할 수 없다.
|
|
throw error;
|
|
});
|
|
}
|
|
return typesCache;
|
|
}
|
|
|
|
export async function fetchStructures(projectId: string): Promise<StructureListResponse> {
|
|
return requestJson<StructureListResponse>(`/projects/${projectId}/route/structures`, {
|
|
method: "GET",
|
|
});
|
|
}
|
|
|
|
export async function saveStructures(
|
|
projectId: string,
|
|
baseRevision: number,
|
|
structures: StructureInstance[],
|
|
): Promise<StructureSaveResponse> {
|
|
return requestJson<StructureSaveResponse>(`/projects/${projectId}/route/structures`, {
|
|
method: "PUT",
|
|
body: JSON.stringify({ base_revision: baseRevision, structures }),
|
|
});
|
|
}
|
|
|
|
/** 종단도 마크 위치 — 구간형은 기점(시점)에 찍는다(2026-08-16 사용자 확정). */
|
|
export function structureAnchorM(structure: StructureInstance): number {
|
|
return structure.placement === "interval"
|
|
? (structure.start_m ?? 0)
|
|
: (structure.chainage_m ?? 0);
|
|
}
|
|
|
|
/** 타입 정의의 기본값으로 옵션을 채운다(신규 추가·타입 변경 시). */
|
|
export function defaultOptions(type: StructureType): Record<string, string | number> {
|
|
const options: Record<string, string | number> = {};
|
|
type.options.forEach((field) => {
|
|
if (field.default !== null && field.default !== undefined) options[field.key] = field.default;
|
|
else if (field.input === "select" && field.choices.length)
|
|
options[field.key] = field.choices[0];
|
|
});
|
|
return options;
|
|
}
|