972 lines
32 KiB
TypeScript
972 lines
32 KiB
TypeScript
"use client";
|
|
|
|
import type { ChangeEvent } from "react";
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import {
|
|
StandardPopupLayout,
|
|
type UiHeadProps,
|
|
} from "@common/business_components";
|
|
import {
|
|
Button,
|
|
Input,
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow,
|
|
} from "@common/components";
|
|
|
|
import {
|
|
getBlobDataWithHeaders,
|
|
getData,
|
|
postMutiPart,
|
|
postRawJson,
|
|
} from "@/components/lib/api";
|
|
import LoadingOverlay from "@/components/ui/LoadingBar";
|
|
import { windowPopupDefinitions } from "@/features/windowPopup/model/popupDefinitions";
|
|
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
|
import MapPopupDataTable from "@/features/windowPopup/ui/MapPopupDataTable";
|
|
import { useAlertStore } from "@/shared/lib";
|
|
import { useUserStore } from "@/shared/lib/use-user-store";
|
|
import GisUploadPreviewMap from "./GisUploadPreviewMap";
|
|
import PopupSearchPanel from "@/features/windowPopup/ui/PopupSearchPanel";
|
|
|
|
type UploadFacilityType = {
|
|
facilityTypeCode: string;
|
|
facilityTypeName: string;
|
|
layerId: string;
|
|
allowedExtensions: string[];
|
|
maxFileSizeMb: number;
|
|
requiredDownloadFormat: string;
|
|
};
|
|
|
|
type MngInstOption = {
|
|
mngInstCd: string;
|
|
lwrInstNm: string;
|
|
};
|
|
|
|
type UploadHistoryItem = {
|
|
uploadId: string;
|
|
downloadId?: string;
|
|
mngInstCd?: string | null;
|
|
mngInstNm?: string | null;
|
|
fileName: string;
|
|
status?: string;
|
|
totalCount?: number | null;
|
|
changedCount?: number | null;
|
|
invalidCount?: number | null;
|
|
registeredAt: string;
|
|
registeredBy: string;
|
|
registeredByName?: string | null;
|
|
message?: string | null;
|
|
};
|
|
|
|
type UploadHistoryRow = UploadHistoryItem &
|
|
Record<string, unknown> & {
|
|
rowNo: number;
|
|
managementLabel: string;
|
|
changeSummary: string;
|
|
registeredAtLabel: string;
|
|
registeredByLabel: string;
|
|
};
|
|
|
|
const GIS_UPLOAD_HISTORY_HEADLIST: UiHeadProps[] = [
|
|
{ id: "rowNo", title: "순번", widthPercent: 7 },
|
|
{ id: "managementLabel", title: "관리기관", widthPercent: 13 },
|
|
{ id: "fileName", title: "파일명", align: "left", widthPercent: 34 },
|
|
{ id: "changeSummary", title: "변경/오류", widthPercent: 13 },
|
|
{ id: "registeredAtLabel", title: "등록일자", widthPercent: 22 },
|
|
{ id: "registeredByLabel", title: "등록자", widthPercent: 11 },
|
|
];
|
|
|
|
type GisUploadResponse = {
|
|
uploadId: string;
|
|
status: "COMPLETED" | "VALIDATION_FAILED" | string;
|
|
mapRefreshRequired?: boolean;
|
|
refreshLayerTypeNames?: string[];
|
|
validationErrors?: ValidationErrorItem[];
|
|
message?: string;
|
|
};
|
|
|
|
type ValidationErrorItem = {
|
|
rowNo?: number | null;
|
|
fid?: string | null;
|
|
errorCode?: string | null;
|
|
errorMessage?: string | null;
|
|
};
|
|
|
|
type ViewMode = "history" | "validationErrors" | "preview";
|
|
|
|
type DownloadJob = {
|
|
jobId: string;
|
|
status: "QUEUED" | "RUNNING" | "READY" | "FAILED" | string;
|
|
message?: string | null;
|
|
errorCode?: string | null;
|
|
downloadId?: string | null;
|
|
fileName?: string | null;
|
|
retryAfterMillis?: number | null;
|
|
};
|
|
|
|
const SCREEN_ID = "SN_MN010302";
|
|
const FACILITY_TYPE_CODE = "PPL";
|
|
const LAYER_ID = "tb_ms_swage_ppl";
|
|
const GIS_UPLOAD_PAGE_SIZE = 10;
|
|
const SELECT_MNG_INST_VALUE = "";
|
|
// A current/history download is an idempotent GET, so one retry is safe after a transient connection drop.
|
|
const DOWNLOAD_NETWORK_RETRY_DELAY_MS = 500;
|
|
const DOWNLOAD_JOB_POLL_INTERVAL_MS = 1_000;
|
|
const DOWNLOAD_JOB_MAX_WAIT_MS = 30 * 60 * 1_000;
|
|
const DEFAULT_FACILITY: UploadFacilityType = {
|
|
facilityTypeCode: FACILITY_TYPE_CODE,
|
|
facilityTypeName: "하수관로",
|
|
layerId: LAYER_ID,
|
|
allowedExtensions: [".gpkg"],
|
|
maxFileSizeMb: 2048,
|
|
requiredDownloadFormat: "GPKG",
|
|
};
|
|
|
|
/** 백엔드 검증 코드를 사용자가 이해할 수 있는 한글 오류내용으로 변환한다. */
|
|
const GIS_VALIDATION_ERROR_MESSAGES: Record<string, string> = {
|
|
GIS_UPLOAD_MNG_INST_MISMATCH:
|
|
"선택한 관리기관과 다른 관로가 포함되어 있습니다.",
|
|
GIS_UPLOAD_FID_DUPLICATED: "업로드 파일에 중복된 시설물 식별번호가 있습니다.",
|
|
GIS_UPLOAD_DELETE_LIMIT_EXCEEDED:
|
|
"삭제 대상 건수가 허용 범위를 초과했습니다.",
|
|
};
|
|
|
|
/** 형상 오류는 같은 오류코드 안에서도 누락과 형식 오류를 구분해 안내한다. */
|
|
const getLocalizedValidationErrorMessage = (error: ValidationErrorItem) => {
|
|
const errorCode = String(error.errorCode ?? "").trim();
|
|
const errorMessage = String(error.errorMessage ?? "").trim();
|
|
|
|
if (errorCode === "GIS_UPLOAD_INVALID_GEOMETRY") {
|
|
return errorMessage.toLowerCase().includes("없는 feature")
|
|
? "공간정보가 없는 시설물입니다."
|
|
: "하수관로는 선 또는 다중선 형식의 공간정보만 업로드할 수 있습니다.";
|
|
}
|
|
|
|
const localizedMessage = GIS_VALIDATION_ERROR_MESSAGES[errorCode];
|
|
if (localizedMessage) {
|
|
const count = errorMessage.match(/count\s*=\s*(\d+)/i)?.[1];
|
|
return count ? `${localizedMessage} (대상: ${count}건)` : localizedMessage;
|
|
}
|
|
|
|
// 서버가 완전한 한글 문구를 제공한 신규 오류만 보존하고 영문이 섞인 문구는 일반 안내로 대체한다.
|
|
return /[가-힣]/.test(errorMessage) && !/[A-Za-z]/.test(errorMessage)
|
|
? errorMessage
|
|
: "업로드 파일 검증 중 오류가 발생했습니다.";
|
|
};
|
|
|
|
const getFileExtension = (fileName: string) => {
|
|
const lastDotIndex = fileName.lastIndexOf(".");
|
|
if (lastDotIndex < 0) return "";
|
|
return fileName.slice(lastDotIndex).toLowerCase();
|
|
};
|
|
|
|
const formatDateTime = (value?: string | null) => {
|
|
if (!value) return "-";
|
|
return value.replace("T", " ").slice(0, 19);
|
|
};
|
|
|
|
const toScopeKey = (mngInstCd: string) => mngInstCd || "__UNSELECTED__";
|
|
|
|
const buildManagementLabel = (
|
|
mngInstCd?: string | null,
|
|
mngInstNm?: string | null,
|
|
) => {
|
|
if (!mngInstCd) return "-";
|
|
return mngInstNm || mngInstCd;
|
|
};
|
|
|
|
// Chrome reports an interrupted fetch as TypeError without an HTTP response.
|
|
const isDownloadNetworkError = (error: unknown) => {
|
|
if (!(error instanceof TypeError)) return false;
|
|
const message = error.message.toLowerCase();
|
|
return (
|
|
message.includes("failed to fetch") || message.includes("networkerror")
|
|
);
|
|
};
|
|
|
|
// Retry only transport failures; HTTP validation and server errors must be shown immediately.
|
|
const downloadGeoPackage = async (url: string) => {
|
|
try {
|
|
return await getBlobDataWithHeaders(url);
|
|
} catch (error) {
|
|
if (!isDownloadNetworkError(error)) throw error;
|
|
console.warn("GIS 다운로드 연결이 중단되어 1회 재시도합니다.", error);
|
|
await new Promise((resolve) =>
|
|
window.setTimeout(resolve, DOWNLOAD_NETWORK_RETRY_DELAY_MS),
|
|
);
|
|
return getBlobDataWithHeaders(url);
|
|
}
|
|
};
|
|
|
|
// 파일 생성 요청과 상태 조회를 짧은 HTTP 요청으로 분리해 서버의 10초 요청 제한을 넘지 않는다.
|
|
const startDownloadJob = async (url: string): Promise<DownloadJob> => {
|
|
const response = await postRawJson(url, {});
|
|
const job = (response?.data ?? response) as DownloadJob | null;
|
|
if (!job?.jobId) {
|
|
throw new Error("다운로드 작업 접수 정보를 확인하지 못했습니다.");
|
|
}
|
|
return job;
|
|
};
|
|
|
|
const waitForDownloadJob = async (jobId: string): Promise<DownloadJob> => {
|
|
const startedAt = Date.now();
|
|
while (Date.now() - startedAt < DOWNLOAD_JOB_MAX_WAIT_MS) {
|
|
const job = (await getData(
|
|
`v1/map/gisDownloadJobs/${encodeURIComponent(jobId)}`,
|
|
)) as DownloadJob;
|
|
if (job?.status === "READY") return job;
|
|
if (job?.status === "FAILED") {
|
|
throw new Error(
|
|
job.message || "GeoPackage 다운로드 파일 생성에 실패했습니다.",
|
|
);
|
|
}
|
|
const retryAfter = Math.max(
|
|
Number(job?.retryAfterMillis) || DOWNLOAD_JOB_POLL_INTERVAL_MS,
|
|
DOWNLOAD_JOB_POLL_INTERVAL_MS,
|
|
);
|
|
await new Promise((resolve) => window.setTimeout(resolve, retryAfter));
|
|
}
|
|
throw new Error(
|
|
"GeoPackage 파일 생성 대기 시간이 초과되었습니다. 다시 시도하세요.",
|
|
);
|
|
};
|
|
|
|
// Keep the object URL alive until Chrome has accepted the synthetic download click.
|
|
const saveBlob = (blob: Blob, fileName: string) => {
|
|
const url = window.URL.createObjectURL(blob);
|
|
const anchor = document.createElement("a");
|
|
anchor.href = url;
|
|
anchor.download = fileName;
|
|
document.body.appendChild(anchor);
|
|
anchor.click();
|
|
anchor.remove();
|
|
window.setTimeout(() => window.URL.revokeObjectURL(url), 1_000);
|
|
};
|
|
|
|
const getErrorMessage = (error: unknown, fallback: string) => {
|
|
const apiError = error as any;
|
|
return (
|
|
apiError?.response?.data?.message ??
|
|
apiError?.response?.data?.data?.message ??
|
|
apiError?.body?.message ??
|
|
apiError?.message ??
|
|
fallback
|
|
);
|
|
};
|
|
|
|
const postRefreshMessageToOpener = (response: GisUploadResponse) => {
|
|
if (
|
|
!response.mapRefreshRequired ||
|
|
typeof window === "undefined" ||
|
|
!window.opener
|
|
) {
|
|
return;
|
|
}
|
|
|
|
window.opener.postMessage(
|
|
{
|
|
type: WINDOW_POPUP_MESSAGE_TYPE.GIS_UPLOAD_COMPLETED,
|
|
payload: {
|
|
refreshLayerTypeNames: JSON.stringify(
|
|
response.refreshLayerTypeNames ?? [LAYER_ID],
|
|
),
|
|
},
|
|
},
|
|
window.location.origin,
|
|
);
|
|
};
|
|
|
|
export default function GisManagementPopupPage() {
|
|
const alert = useAlertStore((state) => state.setMessage);
|
|
const userInfo = useUserStore((state) => state.userInfo);
|
|
// 파일 input은 브라우저 보안 정책상 value 직접 제어가 제한돼 ref로 선택/초기화한다.
|
|
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
|
|
|
const [facility, setFacility] =
|
|
useState<UploadFacilityType>(DEFAULT_FACILITY);
|
|
const [mngInstOptions, setMngInstOptions] = useState<MngInstOption[]>([]);
|
|
const [selectedMngInstCd, setSelectedMngInstCd] = useState(
|
|
SELECT_MNG_INST_VALUE,
|
|
);
|
|
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
|
const [downloadIdsByScope, setDownloadIdsByScope] = useState<
|
|
Record<string, string>
|
|
>({});
|
|
const [uploadHistory, setUploadHistory] = useState<UploadHistoryItem[]>([]);
|
|
const [validationErrors, setValidationErrors] = useState<
|
|
ValidationErrorItem[]
|
|
>([]);
|
|
const [viewMode, setViewMode] = useState<ViewMode>("history");
|
|
const [selectedUploadId, setSelectedUploadId] = useState("");
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [total, setTotal] = useState(0);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [notice, setNotice] = useState("");
|
|
|
|
const selectedHistory = useMemo(
|
|
() =>
|
|
uploadHistory.find((history) => history.uploadId === selectedUploadId) ??
|
|
null,
|
|
[selectedUploadId, uploadHistory],
|
|
);
|
|
const uploadHistoryRows = useMemo<UploadHistoryRow[]>(
|
|
() =>
|
|
uploadHistory.map((history) => ({
|
|
...history,
|
|
rowNo: 0,
|
|
managementLabel: buildManagementLabel(
|
|
history.mngInstCd,
|
|
history.mngInstNm,
|
|
),
|
|
changeSummary: `${(history.changedCount ?? 0).toLocaleString("ko-KR")} / ${(history.invalidCount ?? 0).toLocaleString("ko-KR")}`,
|
|
registeredAtLabel: formatDateTime(history.registeredAt),
|
|
registeredByLabel:
|
|
history.registeredByName ||
|
|
(history.registeredBy === userInfo?.userUnqId
|
|
? userInfo.userName
|
|
: history.registeredBy) ||
|
|
"-",
|
|
})),
|
|
[uploadHistory, userInfo?.userName, userInfo?.userUnqId],
|
|
);
|
|
|
|
const selectedScopeKey = toScopeKey(selectedMngInstCd);
|
|
const selectedScopeLabel = useMemo(() => {
|
|
if (!selectedMngInstCd) return "선택";
|
|
const matched = mngInstOptions.find(
|
|
(option) => option.mngInstCd === selectedMngInstCd,
|
|
);
|
|
return matched?.lwrInstNm || selectedMngInstCd;
|
|
}, [mngInstOptions, selectedMngInstCd]);
|
|
|
|
const allowedExtensionText = facility.allowedExtensions.join(", ");
|
|
const latestDownloadId = downloadIdsByScope[selectedScopeKey] ?? "";
|
|
const isManagementSelected = Boolean(selectedMngInstCd);
|
|
|
|
const resetSelectedFile = () => {
|
|
setSelectedFile(null);
|
|
if (fileInputRef.current) {
|
|
fileInputRef.current.value = "";
|
|
}
|
|
};
|
|
|
|
const fetchHistories = useCallback(
|
|
async (page = currentPage, mngInstCd = selectedMngInstCd) => {
|
|
if (!mngInstCd) {
|
|
setUploadHistory([]);
|
|
setSelectedUploadId("");
|
|
setTotal(0);
|
|
setCurrentPage(1);
|
|
return;
|
|
}
|
|
|
|
const params = new URLSearchParams({
|
|
screenId: SCREEN_ID,
|
|
facilityTypeCode: FACILITY_TYPE_CODE,
|
|
page: String(page - 1),
|
|
size: String(GIS_UPLOAD_PAGE_SIZE),
|
|
});
|
|
params.set("mngInstCd", mngInstCd);
|
|
|
|
try {
|
|
const response = await getData(
|
|
`v1/map/gisUploads?${params.toString()}`,
|
|
);
|
|
const items = Array.isArray(response?.items) ? response.items : [];
|
|
setUploadHistory(items);
|
|
setTotal(Number(response?.total ?? 0));
|
|
setCurrentPage(page);
|
|
setSelectedUploadId(items[0]?.uploadId ?? "");
|
|
setNotice("");
|
|
} catch (error) {
|
|
console.error("GIS 업로드 이력 조회 실패:", error);
|
|
setUploadHistory([]);
|
|
setSelectedUploadId("");
|
|
setTotal(0);
|
|
setCurrentPage(1);
|
|
setNotice("GIS 업로드 이력을 불러오지 못했습니다.");
|
|
}
|
|
},
|
|
[currentPage, selectedMngInstCd],
|
|
);
|
|
|
|
useEffect(() => {
|
|
let mounted = true;
|
|
|
|
const initialize = async () => {
|
|
setIsLoading(true);
|
|
// 시설유형과 관리기관은 서로 독립 계약이므로 한쪽 실패가 다른 콤보박스까지 비우지 않게 분리한다.
|
|
const loadFacilityType = async () => {
|
|
try {
|
|
const facilityTypes = await getData(
|
|
`v1/map/gisUploadFacilityTypes?screenId=${SCREEN_ID}`,
|
|
);
|
|
if (!mounted) return;
|
|
|
|
const pplFacility = Array.isArray(facilityTypes)
|
|
? facilityTypes.find(
|
|
(item) => item?.facilityTypeCode === FACILITY_TYPE_CODE,
|
|
)
|
|
: null;
|
|
if (pplFacility) {
|
|
setFacility({
|
|
...DEFAULT_FACILITY,
|
|
...pplFacility,
|
|
allowedExtensions: Array.isArray(pplFacility.allowedExtensions)
|
|
? pplFacility.allowedExtensions
|
|
: DEFAULT_FACILITY.allowedExtensions,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.error("GIS 관리 시설유형 조회 실패:", error);
|
|
if (mounted) {
|
|
setNotice(
|
|
"GIS 시설정보를 불러오지 못했습니다. 기본 하수관로 설정으로 표시합니다.",
|
|
);
|
|
}
|
|
}
|
|
};
|
|
|
|
// 관리기관 목록은 시설유형 조회 결과와 무관하게 즉시 화면 상태에 반영한다.
|
|
const loadManagementOptions = async () => {
|
|
try {
|
|
const managementOptions = await getData("v1/fcltppl/mngInsts");
|
|
if (!mounted) return;
|
|
|
|
const sortedOptions = Array.isArray(managementOptions)
|
|
? [...managementOptions].sort((a, b) =>
|
|
String(a?.lwrInstNm ?? a?.mngInstCd ?? "").localeCompare(
|
|
String(b?.lwrInstNm ?? b?.mngInstCd ?? ""),
|
|
"ko",
|
|
),
|
|
)
|
|
: [];
|
|
setMngInstOptions(sortedOptions);
|
|
if (sortedOptions.length === 0) {
|
|
setNotice("조회 가능한 관리기관이 없습니다.");
|
|
}
|
|
} catch (error) {
|
|
console.error("GIS 관리 관리기관 조회 실패:", error);
|
|
if (mounted) {
|
|
setMngInstOptions([]);
|
|
setNotice("관리기관 목록을 불러오지 못했습니다.");
|
|
}
|
|
}
|
|
};
|
|
|
|
try {
|
|
await Promise.all([loadFacilityType(), loadManagementOptions()]);
|
|
} finally {
|
|
if (mounted) setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
void initialize();
|
|
return () => {
|
|
mounted = false;
|
|
};
|
|
// 최초 로딩은 고정 화면 ID와 전체 관리기관 기준으로 한 번만 수행한다.
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, []);
|
|
|
|
const handleMngInstChange = (event: ChangeEvent<HTMLSelectElement>) => {
|
|
if (isLoading) return;
|
|
const nextMngInstCd = event.target.value;
|
|
setSelectedMngInstCd(nextMngInstCd);
|
|
setUploadHistory([]);
|
|
setSelectedUploadId("");
|
|
setTotal(0);
|
|
setCurrentPage(1);
|
|
resetSelectedFile();
|
|
setValidationErrors([]);
|
|
setViewMode("history");
|
|
setNotice("");
|
|
void fetchHistories(1, nextMngInstCd);
|
|
};
|
|
|
|
const handleOpenFilePicker = () => {
|
|
if (!isManagementSelected) {
|
|
alert("관리기관을 선택하세요.");
|
|
return;
|
|
}
|
|
fileInputRef.current?.click();
|
|
};
|
|
|
|
const handleFileSelected = (event: ChangeEvent<HTMLInputElement>) => {
|
|
const nextFile = event.target.files?.[0] ?? null;
|
|
if (!nextFile) {
|
|
resetSelectedFile();
|
|
return;
|
|
}
|
|
|
|
const fileExtension = getFileExtension(nextFile.name);
|
|
if (!facility.allowedExtensions.includes(fileExtension)) {
|
|
resetSelectedFile();
|
|
alert(
|
|
`업로드 가능한 파일 형식이 아닙니다. 허용 형식: ${allowedExtensionText}`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const maxFileSizeInBytes = facility.maxFileSizeMb * 1024 * 1024;
|
|
if (nextFile.size > maxFileSizeInBytes) {
|
|
resetSelectedFile();
|
|
alert(
|
|
`파일 크기가 제한을 초과했습니다. 최대 ${facility.maxFileSizeMb}MB까지 업로드할 수 있습니다.`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
setSelectedFile(nextFile);
|
|
};
|
|
|
|
const handleDownloadCurrent = async () => {
|
|
if (!isManagementSelected) {
|
|
alert("관리기관을 선택하세요.");
|
|
return;
|
|
}
|
|
|
|
const params = new URLSearchParams({
|
|
screenId: SCREEN_ID,
|
|
facilityTypeCode: FACILITY_TYPE_CODE,
|
|
format: facility.requiredDownloadFormat || "GPKG",
|
|
});
|
|
params.set("mngInstCd", selectedMngInstCd);
|
|
|
|
setIsLoading(true);
|
|
setNotice("");
|
|
try {
|
|
const job = await startDownloadJob(
|
|
`v1/map/gisUploads/swagePpl/downloadJobs?${params.toString()}`,
|
|
);
|
|
setNotice(`${selectedScopeLabel} GeoPackage 파일을 생성하고 있습니다.`);
|
|
const readyJob = await waitForDownloadJob(job.jobId);
|
|
const response = await downloadGeoPackage(
|
|
`v1/map/gisDownloadJobs/${encodeURIComponent(job.jobId)}/file`,
|
|
);
|
|
const downloadId =
|
|
response.headers.get("X-Gis-Download-Id") ?? readyJob.downloadId ?? "";
|
|
if (!downloadId) {
|
|
setNotice(
|
|
"다운로드 기준 정보를 확인하지 못했습니다. 다시 다운로드한 뒤 업로드하세요.",
|
|
);
|
|
} else {
|
|
setDownloadIdsByScope((current) => ({
|
|
...current,
|
|
[selectedScopeKey]: downloadId,
|
|
}));
|
|
}
|
|
saveBlob(
|
|
response.blob,
|
|
response.fileName ??
|
|
readyJob.fileName ??
|
|
`swage_ppl_${selectedScopeKey}.gpkg`,
|
|
);
|
|
if (downloadId) {
|
|
setNotice(`${selectedScopeLabel} 기준 GeoPackage를 다운로드했습니다.`);
|
|
}
|
|
} catch (error) {
|
|
console.error("GIS 다운로드 실패:", error);
|
|
alert(
|
|
getErrorMessage(error, "GeoPackage 다운로드 중 오류가 발생했습니다."),
|
|
);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleUpload = async () => {
|
|
if (!isManagementSelected) {
|
|
alert("관리기관을 선택하세요.");
|
|
return;
|
|
}
|
|
|
|
if (!selectedFile) {
|
|
alert("업로드할 파일을 선택하세요.");
|
|
return;
|
|
}
|
|
|
|
const formData = new FormData();
|
|
formData.append("screenId", SCREEN_ID);
|
|
formData.append("facilityTypeCode", FACILITY_TYPE_CODE);
|
|
formData.append("layerId", facility.layerId || LAYER_ID);
|
|
if (latestDownloadId) {
|
|
formData.append("downloadId", latestDownloadId);
|
|
}
|
|
formData.append("mngInstCd", selectedMngInstCd);
|
|
formData.append("file", selectedFile);
|
|
|
|
setIsLoading(true);
|
|
setNotice("");
|
|
try {
|
|
const response = (await postMutiPart(
|
|
"/api/gis-upload",
|
|
formData,
|
|
)) as GisUploadResponse;
|
|
if (response.status === "VALIDATION_FAILED") {
|
|
setValidationErrors(
|
|
Array.isArray(response.validationErrors)
|
|
? response.validationErrors
|
|
: [],
|
|
);
|
|
setViewMode("validationErrors");
|
|
setNotice(response.message ?? "GeoPackage 검증 오류가 있습니다.");
|
|
return;
|
|
}
|
|
|
|
postRefreshMessageToOpener(response);
|
|
await fetchHistories(1, selectedMngInstCd);
|
|
resetSelectedFile();
|
|
setValidationErrors([]);
|
|
setViewMode("history");
|
|
setNotice(response.message ?? "GIS 업로드가 완료되었습니다.");
|
|
} catch (error) {
|
|
console.error("GIS 업로드 실패:", error);
|
|
alert(
|
|
getErrorMessage(error, "GeoPackage 업로드 중 오류가 발생했습니다."),
|
|
);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleDownloadSelectedHistory = async () => {
|
|
if (viewMode !== "history") return;
|
|
if (!selectedHistory) {
|
|
alert("다운로드할 업로드 현황 행을 선택하세요.");
|
|
return;
|
|
}
|
|
|
|
setIsLoading(true);
|
|
setNotice("");
|
|
try {
|
|
const job = await startDownloadJob(
|
|
`v1/map/gisUploads/${encodeURIComponent(selectedHistory.uploadId)}/downloadJobs`,
|
|
);
|
|
setNotice("선택한 현황의 GeoPackage 파일을 생성하고 있습니다.");
|
|
const readyJob = await waitForDownloadJob(job.jobId);
|
|
const response = await downloadGeoPackage(
|
|
`v1/map/gisDownloadJobs/${encodeURIComponent(job.jobId)}/file`,
|
|
);
|
|
saveBlob(
|
|
response.blob,
|
|
response.fileName ??
|
|
readyJob.fileName ??
|
|
`${selectedHistory.uploadId}.gpkg`,
|
|
);
|
|
setNotice(
|
|
`${buildManagementLabel(selectedHistory.mngInstCd, selectedHistory.mngInstNm)} 기준 GeoPackage를 다운로드했습니다.`,
|
|
);
|
|
} catch (error) {
|
|
console.error("GIS 이력 다운로드 실패:", error);
|
|
alert(
|
|
getErrorMessage(
|
|
error,
|
|
"선택한 현황 기준 GeoPackage 다운로드 중 오류가 발생했습니다.",
|
|
),
|
|
);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const fetchValidationErrors = async (uploadId = selectedUploadId) => {
|
|
if (!uploadId) {
|
|
alert("오류를 확인할 업로드 현황 행을 선택하세요.");
|
|
return;
|
|
}
|
|
|
|
setIsLoading(true);
|
|
setNotice("");
|
|
try {
|
|
const response = await getData(
|
|
`v1/map/gisUploads/${encodeURIComponent(uploadId)}/validationErrors?page=0&size=500`,
|
|
);
|
|
setValidationErrors(
|
|
Array.isArray(response?.errors) ? response.errors : [],
|
|
);
|
|
setViewMode("validationErrors");
|
|
} catch (error) {
|
|
console.error("GIS 업로드 오류 조회 실패:", error);
|
|
alert("업로드 오류 목록을 불러오지 못했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleRefreshHistories = async () => {
|
|
setValidationErrors([]);
|
|
setViewMode("history");
|
|
await fetchHistories(1, selectedMngInstCd);
|
|
};
|
|
|
|
const handleOpenPreview = () => {
|
|
if (!selectedHistory) {
|
|
alert("미리보기할 업로드 현황 행을 선택하세요.");
|
|
return;
|
|
}
|
|
setViewMode("preview");
|
|
};
|
|
|
|
return (
|
|
<StandardPopupLayout
|
|
title={windowPopupDefinitions.gisManagementPopup.title}
|
|
>
|
|
<LoadingOverlay isLoading={isLoading} />
|
|
|
|
{notice ? (
|
|
<div className="border-b border-border bg-secondary px-5 py-2 text-[1rem] text-label">
|
|
{notice}
|
|
</div>
|
|
) : null}
|
|
|
|
<section
|
|
className={
|
|
viewMode === "preview"
|
|
? "flex min-h-0 flex-1 flex-col gap-[1.2rem] overflow-hidden p-4 pb-2"
|
|
: "flex min-h-0 flex-1 flex-col gap-[1.2rem] p-4"
|
|
}
|
|
>
|
|
<PopupSearchPanel
|
|
className="shrink-0"
|
|
contentClassName="flex flex-wrap items-center gap-x-5 gap-y-3"
|
|
>
|
|
<label className="flex shrink-0 items-center gap-2">
|
|
<div className="whitespace-nowrap text-xl font-medium text-label">
|
|
관리기관
|
|
</div>
|
|
<select
|
|
className="h-[3.2rem] w-[20rem] rounded-md border border-input bg-field px-3 text-xl text-foreground"
|
|
value={selectedMngInstCd}
|
|
onChange={handleMngInstChange}
|
|
disabled={isLoading}
|
|
>
|
|
<option value={SELECT_MNG_INST_VALUE}>선택</option>
|
|
{mngInstOptions.map((option) => {
|
|
const value = String(option.mngInstCd ?? "").trim();
|
|
if (!value) return null;
|
|
return (
|
|
<option key={value} value={value}>
|
|
{option.lwrInstNm || value}
|
|
</option>
|
|
);
|
|
})}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="flex min-w-[30rem] flex-1 items-center gap-2">
|
|
<div className="shrink-0 whitespace-nowrap text-xl font-medium text-label">
|
|
업로드 파일 ({facility.facilityTypeName}, {allowedExtensionText})
|
|
</div>
|
|
<Input
|
|
value={selectedFile?.name ?? ""}
|
|
placeholder="선택된 파일 없음"
|
|
readOnly
|
|
aria-label="선택 파일명"
|
|
className="!h-[3.2rem] min-w-0 flex-1 !text-xl"
|
|
/>
|
|
</label>
|
|
|
|
<div className="flex min-w-fit flex-wrap justify-end gap-2">
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled={!isManagementSelected || isLoading}
|
|
onClick={() => void handleDownloadCurrent()}
|
|
>
|
|
GeoPackage 다운로드
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="white"
|
|
disabled={!isManagementSelected || isLoading}
|
|
onClick={handleOpenFilePicker}
|
|
>
|
|
파일찾기
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled={!isManagementSelected || !selectedFile || isLoading}
|
|
onClick={() => void handleUpload()}
|
|
>
|
|
업로드
|
|
</Button>
|
|
</div>
|
|
</PopupSearchPanel>
|
|
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
className="hidden"
|
|
accept={facility.allowedExtensions.join(",")}
|
|
onChange={handleFileSelected}
|
|
/>
|
|
|
|
{viewMode !== "history" ? (
|
|
<div className="card-header flex shrink-0 items-center justify-between">
|
|
<h3 className="text-2xl font-medium text-label">
|
|
{viewMode === "preview"
|
|
? "GIS 업로드 미리보기"
|
|
: "GIS 업로드 오류 목록"}
|
|
</h3>
|
|
<div className="flex flex-wrap justify-end gap-2">
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled={!isManagementSelected || isLoading}
|
|
onClick={() => void handleRefreshHistories()}
|
|
>
|
|
목록
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled
|
|
onClick={() => void handleDownloadSelectedHistory()}
|
|
>
|
|
GeoPackage 다운로드
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="white"
|
|
disabled={!selectedHistory || isLoading}
|
|
onClick={handleOpenPreview}
|
|
>
|
|
미리보기
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="white"
|
|
disabled={!selectedHistory || isLoading}
|
|
onClick={() => void fetchValidationErrors()}
|
|
>
|
|
오류 확인
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{viewMode === "preview" && selectedHistory ? (
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<GisUploadPreviewMap
|
|
uploadId={selectedHistory.uploadId}
|
|
mngInstCd={selectedMngInstCd}
|
|
/>
|
|
</div>
|
|
) : viewMode === "validationErrors" ? (
|
|
<div className="card !m-0 overflow-x-auto !p-0">
|
|
<Table
|
|
variant="secondary"
|
|
className="w-full min-w-[640px] caption-bottom text-sm"
|
|
>
|
|
<TableHeader className="font-bold">
|
|
<TableRow>
|
|
{["순번", "행번호", "FID", "오류내용"].map((head) => (
|
|
<TableHead
|
|
key={head}
|
|
className="border border-border !bg-primary px-4 py-[1.1rem] text-center text-[1.2rem] font-medium !text-primary-foreground"
|
|
>
|
|
{head}
|
|
</TableHead>
|
|
))}
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody className="text-center">
|
|
{validationErrors.length > 0 ? (
|
|
validationErrors.map((error, index) => (
|
|
<TableRow
|
|
key={`${error.rowNo ?? index}-${error.fid ?? ""}-${error.errorCode ?? ""}`}
|
|
>
|
|
<TableCell className="border border-border px-3 py-[1rem] text-[1.15rem]">
|
|
{validationErrors.length - index}
|
|
</TableCell>
|
|
<TableCell className="border border-border px-3 py-[1rem] text-[1.15rem]">
|
|
{error.rowNo ?? "-"}
|
|
</TableCell>
|
|
<TableCell className="border border-border px-3 py-[1rem] text-[1.15rem]">
|
|
{error.fid || "-"}
|
|
</TableCell>
|
|
<TableCell className="border border-border px-3 py-[1rem] text-left text-[1.15rem]">
|
|
{getLocalizedValidationErrorMessage(error)}
|
|
</TableCell>
|
|
</TableRow>
|
|
))
|
|
) : (
|
|
<TableRow>
|
|
<TableCell
|
|
colSpan={4}
|
|
className="h-[calc(100dvh-28rem)] min-h-96 border border-border text-center text-[1.2rem] text-muted-foreground"
|
|
>
|
|
표시할 오류가 없습니다.
|
|
</TableCell>
|
|
</TableRow>
|
|
)}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
) : (
|
|
<MapPopupDataTable
|
|
rows={uploadHistoryRows}
|
|
headlist={GIS_UPLOAD_HISTORY_HEADLIST}
|
|
title="GIS 업로드 목록"
|
|
total={total}
|
|
page={currentPage}
|
|
pageSize={GIS_UPLOAD_PAGE_SIZE}
|
|
onPageChange={(page) =>
|
|
void fetchHistories(page, selectedMngInstCd)
|
|
}
|
|
actions={
|
|
<>
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled={!isManagementSelected || isLoading}
|
|
onClick={() => void handleRefreshHistories()}
|
|
>
|
|
목록
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="primary"
|
|
disabled={!selectedHistory || isLoading}
|
|
onClick={() => void handleDownloadSelectedHistory()}
|
|
>
|
|
GeoPackage 다운로드
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="white"
|
|
disabled={!selectedHistory || isLoading}
|
|
onClick={handleOpenPreview}
|
|
>
|
|
미리보기
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
color="white"
|
|
disabled={!selectedHistory || isLoading}
|
|
onClick={() => void fetchValidationErrors()}
|
|
>
|
|
오류 확인
|
|
</Button>
|
|
</>
|
|
}
|
|
scrollMode="horizontal"
|
|
minTableWidth="72rem"
|
|
emptyMessage="조회 결과가 없습니다."
|
|
fillAvailableHeight
|
|
rowId={(row) => row.uploadId}
|
|
selectedRowId={selectedUploadId}
|
|
onRowClick={(row) => setSelectedUploadId(row.uploadId)}
|
|
/>
|
|
)}
|
|
</section>
|
|
</StandardPopupLayout>
|
|
);
|
|
}
|