Files
frontend/apps/sn/app/(with-base-layout)/oper/dredging/_lib/client.ts
T
2026-08-05 16:05:07 +09:00

292 lines
9.2 KiB
TypeScript

import { getRawJson, postRawJson } from "@/components/lib/api";
import { handleUpload } from "@/components/lib/utils";
import type { HttpResponse } from "tus-js-client";
import type {
DredgingSaveGroup,
DredgingRecord,
GeoPoint,
MatchConfidence,
PipeMatch,
} from "./types";
type LocationRequest = GeoPoint & {
locationKey: string;
};
export type AttachmentReference = {
atflCd: string;
atflId: string;
};
type NearestPipeResponseItem = {
locationKey: string;
failureCode?:
| "PIPE_NOT_FOUND"
| "PIPE_ASSET_NOT_MAPPED"
| "PIPE_ASSET_AMBIGUOUS"
| string
| null;
failureMessage?: string | null;
selected?: {
fid: string;
mngInstCd: string;
fcltMngNo: string;
pipeDiameterMm?: number;
pipeLengthM?: number;
pipeMaterial?: string;
installationYear?: number | null;
distanceMeters: number;
snappedLongitude: number;
snappedLatitude: number;
confidence: MatchConfidence;
} | null;
};
const nearestPipeFailureMessage = (item: NearestPipeResponseItem) => {
switch (item.failureCode) {
case "PIPE_NOT_FOUND":
return "50m 이내에 관로가 없습니다. 지도에서 준설위치를 다시 확인해주세요.";
case "PIPE_ASSET_NOT_MAPPED":
return "가장 가까운 관로는 찾았지만 자산 매핑 정보가 없습니다. 관로 자산 매핑 데이터를 확인해주세요.";
case "PIPE_ASSET_AMBIGUOUS":
return "가장 가까운 관로의 자산 매핑이 둘 이상입니다. 관로 자산 매핑 데이터를 확인해주세요.";
default:
return (
item.failureMessage?.trim() ??
"최근접 관로를 자동으로 연결하지 못했습니다."
);
}
};
export const isDredgingBackendEnabled =
process.env.NEXT_PUBLIC_DREDGING_BACKEND_ENABLED !== "false";
const toDredgingApiError = (error: unknown, fallbackMessage: string) => {
if (!(error instanceof Error)) return new Error(fallbackMessage);
// 프록시/서버 오류가 HTML 또는 plain text로 반환되면 공통 JSON 파서의
// SyntaxError를 그대로 노출하지 않고 사용자가 이해할 수 있는 문구로 바꾼다.
if (
error instanceof SyntaxError ||
/Unexpected token|Internal Server Error|Failed to (fetch|post) data/i.test(
error.message,
)
) {
return new Error(fallbackMessage);
}
return error;
};
type DredgingRecordListResponse = {
items: DredgingRecord[];
total: number;
page: number;
size: number;
};
/** 실제 준설관리 API에서 기간 내 등록 기록을 조회한다. */
export const fetchDredgingRecords = async (params: {
fromDate: string;
toDate: string;
page?: number;
size?: number;
}): Promise<DredgingRecordListResponse> => {
if (!isDredgingBackendEnabled) {
return { items: [], total: 0, page: 0, size: params.size ?? 2000 };
}
const search = new URLSearchParams({
fromDate: params.fromDate,
toDate: params.toDate,
page: String(params.page ?? 0),
size: String(params.size ?? 2000),
});
const body = await getRawJson(`v1/dredging/records?${search.toString()}`);
return (body?.data ?? body) as DredgingRecordListResponse;
};
const mockPipeForLocations = (locations: LocationRequest[]): PipeMatch => {
const first = locations[0];
const longitude = first?.longitude ?? 127.5;
const latitude = first?.latitude ?? 36.5;
const seed = Math.abs(
Math.round(longitude * 100_000) + Math.round(latitude * 100_000),
);
const distanceMeters = Number(((seed % 850) / 100 + 1.2).toFixed(2));
return {
fid: `MOCK-${String(seed % 1_000_000).padStart(6, "0")}`,
mngInstCd: "4173000",
fcltMngNo: `PPL-${String(seed % 1_000_000).padStart(6, "0")}`,
pipeDiameterMm: [450, 600, 700, 900][seed % 4] ?? 450,
pipeLengthM: Number((((seed % 8_000) + 2_000) / 100).toFixed(2)),
pipeMaterial: ["콘크리트", "PVC", "PE"][seed % 3] ?? "콘크리트",
installationYear: 1995 + (seed % 25),
distanceMeters,
snappedLongitude: longitude + 0.00001,
snappedLatitude: latitude - 0.00001,
confidence: distanceMeters <= 10 ? "HIGH" : "MEDIUM",
isMock: true,
};
};
/**
* 위치 목록을 한 번에 보내고 사진별 최근접 관로를 받는다.
* FE 선행 모드에서는 같은 그룹의 상태 전이를 검증할 수 있는 명시적 모의 관로를 반환한다.
*/
export const findNearestPipeMatches = async (
locations: LocationRequest[],
): Promise<Map<string, PipeMatch>> => {
if (locations.length === 0) return new Map();
if (!isDredgingBackendEnabled) {
const mockPipe = mockPipeForLocations(locations);
return new Map(
locations.map((location) => [location.locationKey, mockPipe]),
);
}
let body: any;
try {
body = await postRawJson("v1/dredging/nearestPipes", { locations });
} catch (error) {
throw toDredgingApiError(
error,
"최근접 관로를 조회하지 못했습니다. 잠시 후 다시 시도해주세요.",
);
}
const items = (body?.data ?? body) as NearestPipeResponseItem[];
const matches = new Map<string, PipeMatch>();
const failureMessages: string[] = [];
for (const item of items ?? []) {
if (!item.selected) {
failureMessages.push(nearestPipeFailureMessage(item));
continue;
}
matches.set(item.locationKey, {
fid: item.selected.fid,
mngInstCd: item.selected.mngInstCd,
fcltMngNo: item.selected.fcltMngNo,
pipeDiameterMm: item.selected.pipeDiameterMm ?? 0,
pipeLengthM: item.selected.pipeLengthM ?? 0,
pipeMaterial: item.selected.pipeMaterial ?? "",
installationYear: item.selected.installationYear ?? null,
distanceMeters: item.selected.distanceMeters,
snappedLongitude: item.selected.snappedLongitude,
snappedLatitude: item.selected.snappedLatitude,
confidence: item.selected.confidence,
isMock: false,
});
}
if (failureMessages.length > 0) {
throw new Error(Array.from(new Set(failureMessages)).join(" "));
}
return matches;
};
const uploadOnePhoto = (file: File): Promise<AttachmentReference> =>
new Promise((resolve, reject) => {
const transfer = new DataTransfer();
transfer.items.add(file);
const timeoutId = window.setTimeout(() => {
reject(new Error(`${file.name} 첨부 업로드 응답 시간이 초과되었습니다.`));
}, 90_000);
const handleResponse = (response: HttpResponse) => {
const fileInfo = response.getHeader("X-File-Info");
if (!fileInfo) return;
try {
const parsed = JSON.parse(fileInfo) as Partial<AttachmentReference>;
if (!parsed.atflCd || !parsed.atflId) {
throw new Error("첨부 식별자가 응답에 없습니다.");
}
window.clearTimeout(timeoutId);
resolve({ atflCd: parsed.atflCd, atflId: parsed.atflId });
} catch (error) {
window.clearTimeout(timeoutId);
reject(error);
}
};
try {
handleUpload(transfer.files, { handleResponse });
} catch (error) {
window.clearTimeout(timeoutId);
reject(error);
}
});
/**
* 공통 attach-service TUS 업로드를 순차 실행한다.
* 등록 API가 아직 없는 FE 선행 모드에서는 고아 첨부 생성을 막기 위해 전송하지 않는다.
*/
export const uploadDredgingPhotos = async (
groups: DredgingSaveGroup[],
existingReferences: Map<string, AttachmentReference> = new Map(),
) => {
const references = new Map(existingReferences);
if (!isDredgingBackendEnabled) return references;
for (const group of groups) {
for (const photo of group.photos) {
// DB 저장만 실패한 재시도에서는 이미 성공한 공통 첨부 업로드를 재사용한다.
if (references.has(photo.key)) continue;
references.set(photo.key, await uploadOnePhoto(photo.file));
}
}
return references;
};
export const saveDredgingRegistrations = async (
groups: DredgingSaveGroup[],
attachments: Map<string, AttachmentReference>,
) => {
if (!isDredgingBackendEnabled) {
return {
mock: true,
registeredCount: groups.length,
clientRequestId: crypto.randomUUID(),
};
}
const clientRequestId = crypto.randomUUID();
return postRawJson("v1/dredging/registrations", {
clientRequestId,
groups: groups.map((group, groupIndex) => ({
groupSn: groupIndex + 1,
registrationMode: group.registrationMode,
dredgingDate: group.dredgingDate,
location: {
source: group.locationSource,
longitude: group.location.longitude,
latitude: group.location.latitude,
},
expectedPipe: {
fid: group.pipe.fid,
mngInstCd: group.pipe.mngInstCd,
fcltMngNo: group.pipe.fcltMngNo,
},
lowConfidenceConfirmed: group.lowConfidenceConfirmed,
photos: group.photos.map((photo) => {
const attachment = attachments.get(photo.key);
if (!attachment) {
throw new Error(`${photo.file.name}의 첨부 식별자가 없습니다.`);
}
return {
...attachment,
originalFileName: photo.file.name,
clientCapturedAt: photo.metadata.capturedAt,
clientLongitude: photo.metadata.location?.longitude ?? null,
clientLatitude: photo.metadata.location?.latitude ?? null,
};
}),
})),
});
};