Merge branch 'iipbs/sn/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/sn/dev

This commit is contained in:
2026-09-15 16:28:23 +09:00
217 changed files with 12547 additions and 17723 deletions
@@ -0,0 +1,3 @@
/** 기존 FE 선행 모의 모드 계약을 유지하며 API와 첨부 adapter가 공유한다. */
export const isDredgingBackendEnabled =
process.env.NEXT_PUBLIC_DREDGING_BACKEND_ENABLED !== "false";
@@ -0,0 +1,258 @@
/** 준설 조회·등록·수정·삭제와 최근접 관로 HTTP 계약을 담당한다. */
import {
deleteData,
getBlobData,
getRawJson,
postRawJson,
putData,
} from "@/components/lib/api";
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
import { isDredgingBackendEnabled } from "./backend-mode";
import { toDredgingApiError } from "./dredging-error";
import {
toDredgingRecordPage,
toDredgingPhotos,
toNearestPipeMatches,
type DredgingRecordListResponse,
} from "./response-adapters";
import type {
DredgingRecordUpdate,
DredgingPhoto,
GeoPoint,
PipeMatch,
} from "../model/types";
import type {
AttachmentReference,
DredgingRegistrationRequest,
} from "../model/registration-request";
export type { AttachmentReference } from "../model/registration-request";
type LocationRequest = GeoPoint & {
locationKey: string;
};
/** 실제 준설관리 API에서 기간 내 등록 기록을 조회한다. */
export const fetchDredgingRecords = async (params: {
fromDate: string;
toDate: string;
ctpv?: string;
sgg?: 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),
});
if (params.ctpv?.trim()) search.set("ctpv", params.ctpv.trim());
if (params.sgg?.trim()) search.set("sgg", params.sgg.trim());
try {
const body = await getRawJson(`v1/dredging/records?${search.toString()}`);
return toDredgingRecordPage(body);
} catch (error) {
throw toDredgingApiError(
error,
"준설현황을 불러오지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설현황 조회",
);
}
};
/** 조회조건에 맞는 준설기록 전체 페이지를 순회해 목록·Excel 건수를 일치시킨다. */
export const fetchAllDredgingRecords = async (params: {
fromDate: string;
toDate: string;
ctpv?: string;
sgg?: string;
}) =>
fetchAllPages({
fetchPage: (page, size) => fetchDredgingRecords({ ...params, page, size }),
getItems: (response) => response.items ?? [],
getTotal: (response) => Number(response.total ?? 0),
});
/** 등록된 준설사진의 공통 첨부파일 참조를 조회한다. */
export const fetchDredgingPhotos = async (
dredgingJobSn: string | number,
pipeFid: string,
): Promise<DredgingPhoto[]> => {
if (!isDredgingBackendEnabled) return [];
try {
const body = await getRawJson(
`v1/dredging/records/${encodeURIComponent(dredgingJobSn)}/photos?fid=${encodeURIComponent(pipeFid)}`,
);
return toDredgingPhotos(body);
} catch (error) {
throw toDredgingApiError(
error,
"등록된 준설사진을 불러오지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설사진 목록 조회",
);
}
};
/** 상세 기반 수정 팝업에서 선택 관로의 일자·위치·사진 구성을 함께 수정한다. */
export const updateDredgingRecord = async (
dredgingJobSn: string | number,
update: DredgingRecordUpdate,
attachments: Map<string, AttachmentReference>,
) => {
if (!isDredgingBackendEnabled) return true;
try {
await putData(`v1/dredging/records/${encodeURIComponent(dredgingJobSn)}`, {
dredgingDate: update.dredgingDate,
pipeFid: update.originalPipeFid,
registrationMode: update.registrationMode,
location: {
source: update.locationSource,
longitude: update.location.longitude,
latitude: update.location.latitude,
},
expectedPipe: {
fid: update.pipe.fid,
mngInstCd: update.pipe.mngInstCd,
fcltMngNo: update.pipe.fcltMngNo,
},
retainedPhotoSns: update.retainedPhotoSns,
newPhotos: update.newPhotos.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,
};
}),
});
return true;
} catch (error) {
throw toDredgingApiError(
error,
"준설정보를 수정하지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설작업 수정",
);
}
};
/** 목록에서 선택한 준설작업과 관로·사진 참조를 모두 물리 삭제한다. */
export const deleteDredgingRecord = async (dredgingJobSn: string | number) => {
if (!isDredgingBackendEnabled) return true;
try {
const response = await deleteData(
`v1/dredging/records/${encodeURIComponent(dredgingJobSn)}`,
);
if (response instanceof Response && !response.ok) {
throw new Error(`준설작업 삭제 응답 오류: ${response.status}`);
}
return true;
} catch (error) {
throw toDredgingApiError(
error,
"준설정보를 삭제하지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설작업 삭제",
);
}
};
/** 공통 첨부서비스에서 준설사진 원본을 Blob으로 내려받는다. */
export const fetchDredgingPhotoBlob = async (atflId: string) => {
try {
return await getBlobData(
`/attach-service/api/v1/download/${encodeURIComponent(atflId)}`,
);
} catch (error) {
throw toDredgingApiError(
error,
"사진 원본을 불러오지 못했습니다.",
"준설사진 원본 조회",
);
}
};
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),
swtrmtZoneFid: "MOCK-ZONE",
swtrmtZoneNm: "모의처리구역",
distanceMeters,
snappedLongitude: longitude + 0.00001,
snappedLatitude: latitude - 0.00001,
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,
"최근접 관로를 조회하지 못했습니다. 잠시 후 다시 시도해주세요.",
"최근접 관로 조회",
);
}
return toNearestPipeMatches(body);
};
/** UI 세션이 확정한 요청을 전송하며 transport 내부에서는 ID를 재생성하지 않는다. */
export const saveDredgingRegistrations = async (
request: DredgingRegistrationRequest,
) => {
if (!isDredgingBackendEnabled) {
return {
mock: true,
registeredCount: 1,
clientRequestId: request.clientRequestId,
};
}
try {
return await postRawJson("v1/dredging/registrations", request);
} catch (error) {
throw toDredgingApiError(
error,
"준설결과를 저장하지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설결과 저장",
);
}
};
@@ -0,0 +1,19 @@
/**
* 백엔드·프록시의 상태코드, HTML 오류 본문과 파싱 문구를 화면에 전달하지 않는다.
* 상세 응답은 브라우저 Network에서 확인하고 화면에는 업무별 재시도 안내만 노출한다.
*/
export const toDredgingApiError = (
error: unknown,
fallbackMessage: string,
operation: string,
) => {
const status =
typeof error === "object" && error !== null && "status" in error
? (error as { status?: unknown }).status
: undefined;
console.warn(`[준설관리] ${operation} 실패`, {
status: typeof status === "number" ? status : undefined,
errorType: error instanceof Error ? error.name : typeof error,
});
return new Error(fallbackMessage);
};
@@ -0,0 +1,82 @@
import { handleUpload } from "@/components/lib/utils";
import type { HttpResponse } from "tus-js-client";
import { uploadPhotosWithReferences } from "../lib/photo-upload-queue";
import type { AttachmentReference } from "../model/registration-request";
import type { DredgingPhotoDraft, DredgingSaveGroup } from "../model/types";
import { isDredgingBackendEnabled } from "./backend-mode";
import { toDredgingApiError } from "./dredging-error";
/** 공통 TUS helper의 사진 한 장 업로드와 X-File-Info 응답을 Promise로 연결한다. */
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);
/** 동기 예외·TUS 비동기 실패를 같은 경로에서 처리하고 대기 타이머를 해제한다. */
const handleError = (error: unknown) => {
window.clearTimeout(timeoutId);
reject(error);
};
/** 실제 첨부서비스가 반환한 식별자만 세션에 전달한다. */
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) {
handleError(error);
}
};
try {
handleUpload(transfer.files, { handleResponse, handleError });
} catch (error) {
handleError(error);
}
});
/**
* 공통 attach-service TUS 업로드를 순차 실행한다.
* 등록 API가 아직 없는 FE 선행 모드에서는 고아 첨부 생성을 막기 위해 전송하지 않는다.
*/
export const uploadDredgingPhotos = async (
groups: DredgingSaveGroup[],
existingReferences: Map<string, AttachmentReference> = new Map(),
) =>
uploadDredgingPhotoDrafts(
groups.flatMap((group) => group.photos),
existingReferences,
);
/** 등록·수정 화면의 세션 Map을 직접 갱신해 부분 업로드 성공도 재시도에서 보존한다. */
export const uploadDredgingPhotoDrafts = async (
photos: DredgingPhotoDraft[],
existingReferences: Map<string, AttachmentReference> = new Map(),
) => {
if (!isDredgingBackendEnabled) return existingReferences;
try {
return await uploadPhotosWithReferences(
photos,
existingReferences,
uploadOnePhoto,
);
} catch (error) {
throw toDredgingApiError(
error,
"준설사진을 업로드하지 못했습니다. 잠시 후 다시 시도해주세요.",
"준설사진 업로드",
);
}
};
@@ -0,0 +1,83 @@
import type { DredgingPhoto, DredgingRecord, PipeMatch } from "../model/types";
type NearestPipeResponseItem = {
locationKey: string;
failureCode?: "PIPE_NOT_FOUND" | string | null;
failureMessage?: string | null;
selected?: {
fid: string;
mngInstCd: string;
fcltMngNo: string;
pipeDiameterMm?: number;
pipeLengthM?: number;
pipeMaterial?: string;
installationYear?: number | null;
swtrmtZoneFid?: string | null;
swtrmtZoneNm?: string | null;
distanceMeters: number;
snappedLongitude: number;
snappedLatitude: number;
} | null;
};
const nearestPipeFailureMessage = (item: NearestPipeResponseItem) => {
switch (item.failureCode) {
case "PIPE_NOT_FOUND":
return "50m 이내에 관로가 없습니다. 지도에서 준설위치를 다시 확인해주세요.";
default:
return (
item.failureMessage?.trim() ??
"최근접 관로를 자동으로 연결하지 못했습니다."
);
}
};
export type DredgingRecordListResponse = {
items: DredgingRecord[];
total: number;
page: number;
size: number;
};
/** 목록의 기존 raw/wrapper와 페이지 필드를 그대로 유지하는 응답 경계다. */
export const toDredgingRecordPage = (body: any): DredgingRecordListResponse =>
(body?.data ?? body) as DredgingRecordListResponse;
/** 사진 목록의 기존 null-to-empty fallback만 적용하며 첨부·촬영 원본 필드는 보존한다. */
export const toDredgingPhotos = (body: any): DredgingPhoto[] =>
(body?.data ?? body ?? []) as DredgingPhoto[];
/** 최근접 관로 응답의 wire 필드와 기본값을 화면 PipeMatch 모델로 명시적으로 매핑한다. */
export const toNearestPipeMatches = (body: any): Map<string, PipeMatch> => {
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,
swtrmtZoneFid: item.selected.swtrmtZoneFid ?? null,
swtrmtZoneNm: item.selected.swtrmtZoneNm ?? "",
distanceMeters: item.selected.distanceMeters,
snappedLongitude: item.selected.snappedLongitude,
snappedLatitude: item.selected.snappedLatitude,
isMock: false,
});
}
if (failureMessages.length > 0) {
throw new Error(Array.from(new Set(failureMessages)).join(" "));
}
return matches;
};
+10
View File
@@ -0,0 +1,10 @@
/** 준설 기능의 공개 API. 기존 라우트 UI는 호환 파일을 통해 같은 구현을 사용한다. */
export * from "./model/types";
export * from "./model/registration-request";
export * from "./api/dredging-api";
export * from "./api/photo-upload";
export { isDredgingBackendEnabled } from "./api/backend-mode";
export { formatDredgingCapturedDate } from "./lib/date";
export { readPhotoMetadata } from "./lib/exif";
export { createDredgingClientUuid } from "./lib/uuid";
export { useDredgingCommonCodes } from "./lib/use-dredging-common-codes";
+21
View File
@@ -0,0 +1,21 @@
/** 촬영일시 원본은 유지하고 등록·수정 화면 표출값만 YYYY-MM-DD로 정규화한다. */
export const formatDredgingCapturedDate = (
value: string | null | undefined,
) => {
const normalized = String(value ?? "").trim();
const matched = normalized.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (!matched) return null;
const year = Number(matched[1]);
const month = Number(matched[2]);
const day = Number(matched[3]);
const date = new Date(year, month - 1, day);
if (
date.getFullYear() !== year ||
date.getMonth() !== month - 1 ||
date.getDate() !== day
) {
return null;
}
return matched[0];
};
+334
View File
@@ -0,0 +1,334 @@
import type { ExifStatus, GeoPoint, PhotoMetadata } from "../model/types";
type ByteOrder = "LE" | "BE";
type IfdEntry = {
type: number;
count: number;
valueOffset: number;
entryOffset: number;
};
const JPEG_START = 0xffd8;
const APP1_MARKER = 0xe1;
const EXIF_IFD_POINTER = 0x8769;
const GPS_IFD_POINTER = 0x8825;
const DATE_TIME = 0x0132;
const DATE_TIME_ORIGINAL = 0x9003;
const DATE_TIME_DIGITIZED = 0x9004;
const typeByteLength = (type: number) => {
if (type === 1 || type === 2 || type === 7) return 1;
if (type === 3) return 2;
if (type === 4 || type === 9) return 4;
if (type === 5 || type === 10) return 8;
return 0;
};
/**
* JPEG EXIF TIFF 블록을 읽는 범위 제한 reader이다.
* 손상된 offset이 파일 범위를 벗어나면 예외를 발생시켜 수동 입력 흐름으로 전환한다.
*/
class TiffReader {
private readonly view: DataView;
private readonly tiffStart: number;
private readonly order: ByteOrder;
constructor(buffer: ArrayBuffer, tiffStart: number) {
this.view = new DataView(buffer);
this.tiffStart = tiffStart;
this.ensureRange(tiffStart, 8);
const byteOrder = this.view.getUint16(tiffStart, false);
if (byteOrder === 0x4949) {
this.order = "LE";
} else if (byteOrder === 0x4d4d) {
this.order = "BE";
} else {
throw new Error("지원하지 않는 TIFF 바이트 순서입니다.");
}
if (this.uint16(2) !== 0x002a) {
throw new Error("유효한 TIFF 헤더가 아닙니다.");
}
}
private get littleEndian() {
return this.order === "LE";
}
private absolute(relativeOffset: number) {
return this.tiffStart + relativeOffset;
}
private ensureRange(absoluteOffset: number, byteLength: number) {
if (
absoluteOffset < 0 ||
byteLength < 0 ||
absoluteOffset + byteLength > this.view.byteLength
) {
throw new Error("EXIF offset이 파일 범위를 벗어났습니다.");
}
}
uint16(relativeOffset: number) {
const absoluteOffset = this.absolute(relativeOffset);
this.ensureRange(absoluteOffset, 2);
return this.view.getUint16(absoluteOffset, this.littleEndian);
}
uint32(relativeOffset: number) {
const absoluteOffset = this.absolute(relativeOffset);
this.ensureRange(absoluteOffset, 4);
return this.view.getUint32(absoluteOffset, this.littleEndian);
}
private readIfd(relativeOffset: number) {
const entryCount = this.uint16(relativeOffset);
const entries = new Map<number, IfdEntry>();
for (let index = 0; index < entryCount; index += 1) {
const entryOffset = relativeOffset + 2 + index * 12;
const tag = this.uint16(entryOffset);
const type = this.uint16(entryOffset + 2);
const count = this.uint32(entryOffset + 4);
const valueOffset = this.uint32(entryOffset + 8);
entries.set(tag, { type, count, valueOffset, entryOffset });
}
return entries;
}
private dataRelativeOffset(entry: IfdEntry) {
const byteLength = typeByteLength(entry.type) * entry.count;
if (byteLength <= 4) return entry.entryOffset + 8;
return entry.valueOffset;
}
private ascii(entry: IfdEntry) {
const relativeOffset = this.dataRelativeOffset(entry);
const absoluteOffset = this.absolute(relativeOffset);
const byteLength = typeByteLength(entry.type) * entry.count;
this.ensureRange(absoluteOffset, byteLength);
const bytes = new Uint8Array(this.view.buffer, absoluteOffset, byteLength);
return new TextDecoder("ascii").decode(bytes).replace(/\0+$/g, "").trim();
}
private rational(relativeOffset: number) {
const numerator = this.uint32(relativeOffset);
const denominator = this.uint32(relativeOffset + 4);
if (denominator === 0) return null;
return numerator / denominator;
}
private rationals(entry: IfdEntry) {
const relativeOffset = this.dataRelativeOffset(entry);
const values: number[] = [];
for (let index = 0; index < entry.count; index += 1) {
const value = this.rational(relativeOffset + index * 8);
if (value === null) return null;
values.push(value);
}
return values;
}
private pointer(entry: IfdEntry | undefined) {
if (!entry || entry.type !== 4 || entry.count !== 1) return null;
return entry.valueOffset;
}
private parseDate(value: string | null) {
if (!value) return null;
const match = value.match(
/^(\d{4}):(\d{2}):(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/,
);
if (!match) return null;
const [, year, month, day, hour, minute, second] = match;
if (!year || !month || !day || !hour || !minute || !second) return null;
const monthNumber = Number(month);
const dayNumber = Number(day);
const hourNumber = Number(hour);
const minuteNumber = Number(minute);
const secondNumber = Number(second);
if (
monthNumber < 1 ||
monthNumber > 12 ||
dayNumber < 1 ||
dayNumber > 31 ||
hourNumber > 23 ||
minuteNumber > 59 ||
secondNumber > 59
) {
return null;
}
return {
capturedAt: `${year}-${month}-${day}T${hour}:${minute}:${second}`,
dredgingDate: `${year}-${month}-${day}`,
};
}
private parseGps(entries: Map<number, IfdEntry>): GeoPoint | null {
const latitudeRefEntry = entries.get(0x0001);
const latitudeEntry = entries.get(0x0002);
const longitudeRefEntry = entries.get(0x0003);
const longitudeEntry = entries.get(0x0004);
if (
!latitudeRefEntry ||
!latitudeEntry ||
!longitudeRefEntry ||
!longitudeEntry
) {
return null;
}
const latitudeRef = this.ascii(latitudeRefEntry).toUpperCase();
const longitudeRef = this.ascii(longitudeRefEntry).toUpperCase();
const latitudeDms = this.rationals(latitudeEntry);
const longitudeDms = this.rationals(longitudeEntry);
if (
!latitudeDms ||
latitudeDms.length < 3 ||
!longitudeDms ||
longitudeDms.length < 3
) {
return null;
}
const toDecimal = (values: number[]) =>
(values[0] ?? 0) + (values[1] ?? 0) / 60 + (values[2] ?? 0) / 3600;
let latitude = toDecimal(latitudeDms);
let longitude = toDecimal(longitudeDms);
if (latitudeRef === "S") latitude *= -1;
if (longitudeRef === "W") longitude *= -1;
if (
!Number.isFinite(latitude) ||
!Number.isFinite(longitude) ||
latitude < -90 ||
latitude > 90 ||
longitude < -180 ||
longitude > 180
) {
return null;
}
return { latitude, longitude };
}
parse() {
const ifd0Offset = this.uint32(4);
const ifd0 = this.readIfd(ifd0Offset);
const exifIfdOffset = this.pointer(ifd0.get(EXIF_IFD_POINTER));
const exifIfd = exifIfdOffset === null ? null : this.readIfd(exifIfdOffset);
const gpsIfdOffset = this.pointer(ifd0.get(GPS_IFD_POINTER));
const gpsIfd = gpsIfdOffset === null ? null : this.readIfd(gpsIfdOffset);
const dateValue =
(exifIfd?.get(DATE_TIME_ORIGINAL)
? this.ascii(exifIfd.get(DATE_TIME_ORIGINAL)!)
: null) ??
(exifIfd?.get(DATE_TIME_DIGITIZED)
? this.ascii(exifIfd.get(DATE_TIME_DIGITIZED)!)
: null) ??
(ifd0.get(DATE_TIME) ? this.ascii(ifd0.get(DATE_TIME)!) : null);
return {
date: this.parseDate(dateValue),
location: gpsIfd ? this.parseGps(gpsIfd) : null,
};
}
}
const toMetadata = (
capturedAt: string | null,
dredgingDate: string | null,
location: GeoPoint | null,
unsupported = false,
): PhotoMetadata => {
let status: ExifStatus;
let message: string;
if (unsupported) {
status = "UNSUPPORTED";
message = "JPEG EXIF가 없어 준설일자와 위치를 직접 입력해야 합니다.";
} else if (dredgingDate && location) {
status = "COMPLETE";
message = "촬영일자와 GPS를 확인했습니다.";
} else if (!dredgingDate && !location) {
status = "MISSING_BOTH";
message = "촬영일자와 GPS가 없어 수동 입력이 필요합니다.";
} else if (!dredgingDate) {
status = "MISSING_DATE";
message = "촬영일자가 없어 준설일자를 직접 입력해야 합니다.";
} else {
status = "MISSING_GPS";
message = "GPS가 없어 지도에서 준설위치를 등록해야 합니다.";
}
return { capturedAt, dredgingDate, location, status, message };
};
/**
* 브라우저에서 즉시 보여 줄 JPEG EXIF 미리보기를 만든다.
* 서버는 저장 시 원본 첨부파일을 기준으로 동일 정보를 다시 검증해야 한다.
*/
export const readPhotoMetadata = async (file: File): Promise<PhotoMetadata> => {
if (file.type !== "image/jpeg" && !/\.jpe?g$/i.test(file.name)) {
return toMetadata(null, null, null, true);
}
try {
const buffer = await file.arrayBuffer();
const view = new DataView(buffer);
if (view.byteLength < 4 || view.getUint16(0, false) !== JPEG_START) {
return toMetadata(null, null, null, true);
}
let offset = 2;
while (offset + 4 <= view.byteLength) {
if (view.getUint8(offset) !== 0xff) break;
const marker = view.getUint8(offset + 1);
if (marker === 0xda || marker === 0xd9) break;
const segmentLength = view.getUint16(offset + 2, false);
if (segmentLength < 2 || offset + 2 + segmentLength > view.byteLength) {
break;
}
if (marker === APP1_MARKER) {
const exifStart = offset + 4;
const exifSignature =
exifStart + 6 <= view.byteLength
? String.fromCharCode(
view.getUint8(exifStart),
view.getUint8(exifStart + 1),
view.getUint8(exifStart + 2),
view.getUint8(exifStart + 3),
)
: "";
if (exifSignature === "Exif") {
const parsed = new TiffReader(buffer, exifStart + 6).parse();
return toMetadata(
parsed.date?.capturedAt ?? null,
parsed.date?.dredgingDate ?? null,
parsed.location,
);
}
}
offset += 2 + segmentLength;
}
} catch (error) {
console.warn("준설 사진 EXIF 분석 실패", error);
}
return toMetadata(null, null, null, false);
};
@@ -0,0 +1,20 @@
import type { AttachmentReference } from "../model/registration-request";
import type { DredgingPhotoDraft } from "../model/types";
/**
* 저장 세션이 소유한 Map에 사진 한 장의 업로드 성공 직후 참조를 기록한다.
* 다음 사진이 실패해 전체 Promise가 reject해도 성공 참조는 세션에 남는다.
* 실제 TUS·브라우저 의존성은 uploadOne으로 받아 순서·재시도 정책과 분리한다.
*/
export const uploadPhotosWithReferences = async (
photos: DredgingPhotoDraft[],
references: Map<string, AttachmentReference>,
uploadOne: (file: File) => Promise<AttachmentReference>,
): Promise<Map<string, AttachmentReference>> => {
for (const photo of photos) {
// 전체 업로드 후 DB 실패뿐 아니라 일부 업로드 실패의 재시도에서도 재사용한다.
if (references.has(photo.key)) continue;
references.set(photo.key, await uploadOne(photo.file));
}
return references;
};
@@ -0,0 +1,135 @@
"use client";
import { useEffect, useState } from "react";
import { getCommonCodes } from "@/components/lib/common/apiHelpers";
import type {
DredgingLocationSource,
DredgingRegistrationMode,
ExifStatus,
} from "../model/types";
type CodeLabelMap = Record<string, string>;
const COMMON_CODE_GROUPS = {
registrationMode: "DRDGNREGMODE",
locationSource: "DRDGNLOCSRC",
photoStatus: "DRDGNPHOTOSTTS",
} as const;
const DEFAULT_REGISTRATION_MODE_LABELS: Record<
DredgingRegistrationMode,
string
> = {
PHOTO: "사진 기반 등록",
MANUAL: "사진 없이 직접 등록",
};
const DEFAULT_LOCATION_SOURCE_LABELS: Record<DredgingLocationSource, string> = {
EXIF: "사진 GPS",
MANUAL: "지도 지정",
};
const DEFAULT_PHOTO_STATUS_LABELS: Record<ExifStatus, string> = {
COMPLETE: "정상",
MISSING_DATE: "촬영일 없음",
MISSING_GPS: "GPS 없음",
MISSING_BOTH: "촬영일·GPS 없음",
UNSUPPORTED: "수동 입력 필요",
};
const cachedLabelMaps = new Map<string, CodeLabelMap>();
const pendingLabelMaps = new Map<string, Promise<CodeLabelMap>>();
/** 같은 브라우저 세션에서는 준설 코드그룹별 CMS 요청을 한 번만 수행한다. */
const loadCodeLabelMap = async (
upCd: string,
fallback: CodeLabelMap,
): Promise<CodeLabelMap> => {
const cached = cachedLabelMaps.get(upCd);
if (cached) return cached;
const pending = pendingLabelMaps.get(upCd);
if (pending) return pending;
const request = getCommonCodes(upCd)
.then((codes) => {
const labels = { ...fallback };
codes.forEach((code) => {
if (code.lwpoCd && code.lwpoCdNm) {
labels[code.lwpoCd] = code.lwpoCdNm;
}
});
cachedLabelMaps.set(upCd, labels);
return labels;
})
.finally(() => {
pendingLabelMaps.delete(upCd);
});
pendingLabelMaps.set(upCd, request);
return request;
};
/** 준설 저장 코드값은 유지하고 버튼·상세·사진상태 표시명만 CMS 기준으로 제공한다. */
export const useDredgingCommonCodes = () => {
const [registrationModeLabels, setRegistrationModeLabels] =
useState<CodeLabelMap>(
cachedLabelMaps.get(COMMON_CODE_GROUPS.registrationMode) ??
DEFAULT_REGISTRATION_MODE_LABELS,
);
const [locationSourceLabels, setLocationSourceLabels] =
useState<CodeLabelMap>(
cachedLabelMaps.get(COMMON_CODE_GROUPS.locationSource) ??
DEFAULT_LOCATION_SOURCE_LABELS,
);
const [photoStatusLabels, setPhotoStatusLabels] = useState<CodeLabelMap>(
cachedLabelMaps.get(COMMON_CODE_GROUPS.photoStatus) ??
DEFAULT_PHOTO_STATUS_LABELS,
);
useEffect(() => {
let cancelled = false;
const applyLabels = (
upCd: string,
fallback: CodeLabelMap,
setter: (labels: CodeLabelMap) => void,
) => {
loadCodeLabelMap(upCd, fallback)
.then((labels) => {
if (!cancelled) setter(labels);
})
.catch((error) => {
console.error(`${upCd} 공통코드 조회에 실패했습니다.`, error);
});
};
applyLabels(
COMMON_CODE_GROUPS.registrationMode,
DEFAULT_REGISTRATION_MODE_LABELS,
setRegistrationModeLabels,
);
applyLabels(
COMMON_CODE_GROUPS.locationSource,
DEFAULT_LOCATION_SOURCE_LABELS,
setLocationSourceLabels,
);
applyLabels(
COMMON_CODE_GROUPS.photoStatus,
DEFAULT_PHOTO_STATUS_LABELS,
setPhotoStatusLabels,
);
return () => {
cancelled = true;
};
}, []);
return {
registrationModeLabels,
locationSourceLabels,
photoStatusLabels,
};
};
+31
View File
@@ -0,0 +1,31 @@
/**
* 일반 HTTP에서는 `crypto.randomUUID`가 제공되지 않을 수 있어 Web Crypto 난수로 UUID v4를 생성한다.
* 백엔드 `clientRequestId`가 UUID 타입이므로 fallback도 같은 36자 형식을 유지한다.
*/
export const createDredgingClientUuid = () => {
if (
typeof crypto !== "undefined" &&
typeof crypto.randomUUID === "function"
) {
return crypto.randomUUID();
}
const bytes = new Uint8Array(16);
if (
typeof crypto !== "undefined" &&
typeof crypto.getRandomValues === "function"
) {
crypto.getRandomValues(bytes);
} else {
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Math.floor(Math.random() * 256);
}
}
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = Array.from(bytes, (value) =>
value.toString(16).padStart(2, "0"),
).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
};
@@ -0,0 +1,84 @@
import type { DredgingSaveGroup } from "./types";
import { createDredgingClientUuid } from "../lib/uuid";
/** 공통 첨부 업로드가 완료된 사진의 서버 식별자다. */
export type AttachmentReference = { atflCd: string; atflId: string };
/** 화면 draft에서 기존 등록 DTO에 해당하는 필드만 명시적으로 추출한다. */
const buildRegistrationBody = (
groups: DredgingSaveGroup[],
attachments: Map<string, AttachmentReference>,
requireAttachments: boolean,
) => ({
dredgingDate: groups[0]?.dredgingDate,
groups: groups.map((group, groupIndex) => ({
groupSn: groupIndex + 1,
registrationMode: group.registrationMode,
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,
},
photos: group.photos.map((photo) => {
const attachment = attachments.get(photo.key);
if (!attachment && requireAttachments) {
throw new Error(`${photo.file.name}의 첨부 식별자가 없습니다.`);
}
return {
atflCd: attachment?.atflCd,
atflId: attachment?.atflId,
originalFileName: photo.file.name,
clientCapturedAt: photo.metadata.capturedAt,
clientLongitude: photo.metadata.location?.longitude ?? null,
clientLatitude: photo.metadata.location?.latitude ?? null,
};
}),
})),
});
/** 기존 POST /v1/dredging/registrations의 요청 body를 그대로 표현한다. */
export type DredgingRegistrationRequest = ReturnType<
typeof buildRegistrationBody
> & {
clientRequestId: string;
};
/**
* 모달을 연 한 번의 등록 세션이 전송 payload별 중복방지 ID를 소유한다.
* 응답 유실 후 같은 입력 재시도와 수정 후 원래 입력 복원은 같은 ID를 쓴다.
* 날짜·관로·위치·사진 등 실제 전송값이 바뀌면 새 ID를 발급한다.
* 화면 그룹 ID, 관경 표시값, 선택 탭 등 비전송 상태는 등록 의도를 바꾸지 않는다.
*/
export const createDredgingRegistrationSession = (
createId: () => string = createDredgingClientUuid,
) => {
// 세션 밖으로 공유하지 않으며 모달을 다시 열 때 새 Map으로 교체한다.
const requestIds = new Map<string, string>();
return {
/** 첨부 식별자까지 확정된 동일 payload에 항상 같은 요청 ID를 부여한다. */
prepare: (
groups: DredgingSaveGroup[],
attachments: Map<string, AttachmentReference>,
// FE 선행 모의 모드만 첨부 업로드 없이 payload 구성 검증을 허용한다.
requireAttachments = true,
): DredgingRegistrationRequest => {
const body = buildRegistrationBody(
groups,
attachments,
requireAttachments,
);
const signature = JSON.stringify(body);
let clientRequestId = requestIds.get(signature);
if (!clientRequestId) {
clientRequestId = createId();
requestIds.set(signature, clientRequestId);
}
return { clientRequestId, ...body };
},
};
};
@@ -0,0 +1,122 @@
export type DredgingViewType = "MUNICIPALITY" | "DIAMETER" | "ELAPSED_YEAR";
export type DredgingRegistrationMode = "PHOTO" | "MANUAL";
export type DredgingLocationSource = "EXIF" | "MANUAL";
export type ExifStatus =
| "COMPLETE"
| "MISSING_DATE"
| "MISSING_GPS"
| "MISSING_BOTH"
| "UNSUPPORTED";
export type GeoPoint = {
longitude: number;
latitude: number;
};
export type PhotoMetadata = {
capturedAt: string | null;
dredgingDate: string | null;
location: GeoPoint | null;
status: ExifStatus;
message: string;
};
export type DredgingPhotoDraft = {
key: string;
file: File;
metadata: PhotoMetadata;
};
export type PipeMatch = {
fid: string;
mngInstCd: string;
fcltMngNo: string;
pipeDiameterMm: number;
pipeLengthM: number;
pipeMaterial: string;
installationYear: number | null;
swtrmtZoneFid: string | null;
swtrmtZoneNm: string;
distanceMeters: number;
snappedLongitude: number;
snappedLatitude: number;
isMock: boolean;
};
export type DredgingDraftGroup = {
id: string;
registrationMode: DredgingRegistrationMode;
photos: DredgingPhotoDraft[];
manualLocation: GeoPoint | null;
matchedPipe: PipeMatch | null;
matchError: string | null;
isMatching: boolean;
};
export type DredgingRecord = {
id: string;
dredgingJobSn: number | string;
pipeFid: string;
mngInstCd: string;
ctpv: string;
sgg: string;
treatmentZone: string;
fcltMngNo: string;
pipeDiameterMm: number;
pipeLengthM: number;
pipeMaterial: string;
installationYear: number | null;
dredgingDate: string;
photoCount: number;
registeredDate: string;
longitude: number;
latitude: number;
snappedLongitude: number;
snappedLatitude: number;
registrationMode: DredgingRegistrationMode;
registrationSource: DredgingLocationSource;
matchDistanceMeters: number;
isMock: boolean;
};
export type DredgingPhoto = {
photoSn: number;
pipeFid: string;
atflCd: string;
atflId: string;
originalFileName: string;
capturedAt: string | null;
};
export type DredgingSaveGroup = {
localId: string;
registrationMode: DredgingRegistrationMode;
dredgingDate: string;
location: GeoPoint;
locationSource: DredgingLocationSource;
pipe: PipeMatch;
photos: DredgingPhotoDraft[];
};
/** 상세 기반 수정 팝업에서 선택한 한 관로의 위치·사진을 함께 갱신한다. */
export type DredgingRecordUpdate = {
dredgingDate: string;
originalPipeFid: string;
registrationMode: DredgingRegistrationMode;
location: GeoPoint;
locationSource: DredgingLocationSource;
pipe: PipeMatch;
retainedPhotoSns: number[];
newPhotos: DredgingPhotoDraft[];
};
export const EMPTY_PHOTO_METADATA: PhotoMetadata = {
capturedAt: null,
dredgingDate: null,
location: null,
status: "UNSUPPORTED",
message: "메타정보를 확인하고 있습니다.",
};
@@ -0,0 +1,513 @@
"use client";
import type { ComponentType } from "react";
import { FileUpload } from "@common/business_components/ui/file-upload";
import {
Button,
InputDatePicker,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@common/components";
import type { DredgingDraftGroup, GeoPoint, PipeMatch } from "../model/types";
import { formatDredgingCapturedDate } from "../lib/date";
type LocationMapViewProps = {
value: GeoPoint | null;
onChange?: (point: GeoPoint) => void;
interactive?: boolean;
statusText?: string;
matchedPipe?: PipeMatch | null;
height?: string;
};
type DredgingRegistrationBodyProps = {
presentation: "modal" | "popup";
groups: DredgingDraftGroup[];
activeGroup: DredgingDraftGroup | null;
representativeDredgingDate: string;
setRepresentativeDredgingDate: (date: string) => void;
parseLocalDate: (value: string) => Date;
formatLocalDate: (date: Date) => string;
getResolvedLocation: (group: DredgingDraftGroup) => GeoPoint | null;
addGroup: () => void;
removeGroup: (groupId: string) => void;
selectGroup: (groupId: string) => void;
changeRegistrationMode: (
groupId: string,
mode: "PHOTO" | "MANUAL",
) => void | Promise<void>;
handleFilesChange: (
groupId: string,
files: File[] | null,
) => void | Promise<void>;
removePhoto: (groupId: string, photoKey: string) => void;
registrationModeLabels: Record<string, string>;
photoStatusLabels: Record<string, string>;
locationSourceLabels: Record<string, string>;
isEditingActiveLocation: boolean;
locationDraft: GeoPoint | null;
applyLocationDraft: () => void | Promise<void>;
cancelLocationEditing: () => void;
startLocationEditing: (group: DredgingDraftGroup) => void;
activeResolvedLocation: GeoPoint | null;
hasUnappliedLocationDraft: boolean;
statusMessage: string;
changeLocationDraft: (point: GeoPoint) => void;
LocationMap: ComponentType<LocationMapViewProps>;
};
/** 등록 폼·사진목록·지도 배치를 담당한다. 상태·업로드·저장 수명은 상위 등록 화면이 소유한다. */
export const DredgingRegistrationBody = ({
presentation,
groups,
activeGroup,
representativeDredgingDate,
setRepresentativeDredgingDate,
parseLocalDate,
formatLocalDate,
getResolvedLocation,
addGroup,
removeGroup,
selectGroup,
changeRegistrationMode,
handleFilesChange,
removePhoto,
registrationModeLabels,
photoStatusLabels,
locationSourceLabels,
isEditingActiveLocation,
locationDraft,
applyLocationDraft,
cancelLocationEditing,
startLocationEditing,
activeResolvedLocation,
hasUnappliedLocationDraft,
statusMessage,
changeLocationDraft,
LocationMap,
}: DredgingRegistrationBodyProps) => (
<div
className={
presentation === "popup"
? "sn-dredging-register flex h-full min-h-0 flex-col overflow-hidden"
: "sn-dredging-register flex h-[min(72rem,70dvh)] min-h-0 flex-col overflow-hidden"
}
>
<div className="bg-secondary/40 mb-3 flex shrink-0 flex-wrap items-center gap-x-4 gap-y-1 rounded-sm border border-border px-4 py-2 text-sm text-label">
<strong className="text-foreground">등록 안내</strong>
<span>관로별 사진은 최대 5장까지 등록할 수 있습니다.</span>
<span>
모든 등록 건은 하나의 준설작업이며 동일한 준설일자를 사용합니다.
</span>
</div>
{activeGroup ? (
<div
className="grid min-h-0 flex-1 grid-cols-[minmax(48rem,52rem)_minmax(0,1fr)] gap-3"
data-testid={`dredging-group-${
groups.findIndex((group) => group.id === activeGroup.id) + 1
}`}
>
<aside className="flex min-h-0 min-w-0 flex-col gap-3 overflow-y-auto overscroll-contain pr-1 [scrollbar-gutter:stable]">
<section className="card card-border !m-0 shrink-0 overflow-hidden !p-0">
<div className="card-header !m-0">
<h3 className="text-2xl font-medium text-label">등록 정보</h3>
<Button type="button" size="sm" onClick={addGroup}>
관로 추가
</Button>
</div>
<div className="p-3">
<Table variant="secondary">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead data-required>준설일자</TableHead>
<TableCell className="border px-4">
<div className="flex flex-wrap items-center gap-3">
<div data-testid="representative-dredging-date">
<InputDatePicker
value={
representativeDredgingDate
? parseLocalDate(representativeDredgingDate)
: null
}
onChange={(date) =>
setRepresentativeDredgingDate(
date ? formatLocalDate(date) : "",
)
}
className="w-[15.5rem]"
/>
</div>
<span className="text-sm text-muted-foreground">
첫 사진 촬영일로 자동 입력되며 직접 수정할 수
있습니다.
</span>
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>등록 관로</TableHead>
<TableCell className="border px-4">
<div
className="flex flex-wrap items-center gap-2"
role="tablist"
aria-label="준설 등록 건"
>
{groups.map((group, groupIndex) => {
const active = group.id === activeGroup.id;
return (
<div
key={group.id}
className="inline-flex items-stretch"
>
<Button
type="button"
size="sm"
color={active ? "primary" : "white"}
role="tab"
aria-selected={active}
className={
groupIndex > 0
? "rounded-r-none border-r-0"
: undefined
}
onClick={() => selectGroup(group.id)}
>
등록 건 {groupIndex + 1}
<span
className={`ml-1 inline-block size-2 rounded-full ${
getResolvedLocation(group)
? "bg-emerald-400"
: "bg-amber-400"
}`}
aria-label={
getResolvedLocation(group)
? "위치 등록 완료"
: "위치 등록 필요"
}
/>
</Button>
{groupIndex > 0 ? (
<Button
type="button"
size="icon"
color="red"
variant="destructive"
aria-label={`등록 건 ${groupIndex + 1} 삭제`}
title={`등록 건 ${groupIndex + 1} 삭제`}
className="h-10 min-w-8 rounded-l-none px-2"
onClick={() => removeGroup(group.id)}
>
×
</Button>
) : null}
</div>
);
})}
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</section>
{/* 등록 건별 사진 수가 달라도 목록 카드 높이를 고정해 지도와 하단 정보가 밀리지 않게 한다. */}
<section
className="card card-border !m-0 flex h-[28rem] shrink-0 flex-col overflow-hidden !p-0"
data-testid="dredging-register-photo-panel"
>
<div className="card-header !m-0 flex-wrap gap-2">
<div>
<h3 className="text-2xl font-medium text-label">준설 사진</h3>
<p className="mt-1 text-sm text-muted-foreground">
촬영일과 GPS 정보를 확인합니다.
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
color={
activeGroup.registrationMode === "PHOTO"
? "primary"
: "white"
}
aria-pressed={activeGroup.registrationMode === "PHOTO"}
onClick={() =>
void changeRegistrationMode(activeGroup.id, "PHOTO")
}
>
{registrationModeLabels.PHOTO}
</Button>
<Button
type="button"
size="sm"
color={
activeGroup.registrationMode === "MANUAL"
? "primary"
: "white"
}
aria-pressed={activeGroup.registrationMode === "MANUAL"}
onClick={() =>
void changeRegistrationMode(activeGroup.id, "MANUAL")
}
>
{registrationModeLabels.MANUAL}
</Button>
</div>
</div>
<div className="flex min-h-0 flex-1 flex-col p-3">
{activeGroup.registrationMode === "PHOTO" ? (
<>
<div className="sn-dredging-photo-upload shrink-0">
<FileUpload
files={activeGroup.photos.map((photo) => photo.file)}
setFiles={(files) => {
void handleFilesChange(activeGroup.id, files);
}}
fileTypes=".jpg,.jpeg,.png"
maxFiles={5}
/>
</div>
{activeGroup.photos.length > 0 ? (
<div
className="mt-2 min-h-0 flex-1 overflow-y-auto overscroll-contain rounded-sm border border-border [scrollbar-gutter:stable]"
data-testid="dredging-register-photo-list-viewport"
>
<Table className="table-fixed" variant="default">
<TableHeader>
<TableRow>
<TableHead className="w-[34%]">사진</TableHead>
<TableHead className="w-[25%]">촬영일시</TableHead>
<TableHead className="w-[16%]">위치</TableHead>
<TableHead className="w-[17%]">상태</TableHead>
<TableHead className="w-[8%] whitespace-nowrap px-1">
삭제
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{activeGroup.photos.map((photo) => (
<TableRow key={photo.key}>
<TableCell
className="truncate px-3"
title={photo.file.name}
>
{photo.file.name}
</TableCell>
<TableCell
className="truncate px-3"
title={
formatDredgingCapturedDate(
photo.metadata.capturedAt,
) ?? "-"
}
>
{formatDredgingCapturedDate(
photo.metadata.capturedAt,
) ?? "-"}
</TableCell>
<TableCell className="px-3">
{photo.metadata.location ? "GPS" : "지정 필요"}
</TableCell>
<TableCell className="overflow-hidden px-3">
<span
title={
photoStatusLabels[photo.metadata.status] ||
"수동 입력 필요"
}
className={`inline-block max-w-full truncate rounded-sm px-2 py-1 align-middle text-sm font-medium ${
photo.metadata.status === "COMPLETE"
? "bg-emerald-100 text-emerald-800"
: "bg-amber-100 text-amber-800"
}`}
>
{photoStatusLabels[photo.metadata.status] ||
"수동 입력 필요"}
</span>
</TableCell>
<TableCell className="px-2 text-center">
<Button
type="button"
size="icon"
variant="destructive"
color="red"
aria-label={`${photo.file.name} 삭제`}
title="사진 삭제"
className="size-8 p-0"
onClick={() =>
removePhoto(activeGroup.id, photo.key)
}
>
×
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="bg-secondary/30 mt-2 flex min-h-0 flex-1 items-center justify-center rounded-sm border border-dashed border-border px-3 py-2 text-center text-sm text-muted-foreground">
준설사진을 선택하면 촬영일과 위치정보를 자동으로
확인합니다.
</div>
)}
</>
) : (
<div className="bg-secondary/30 flex min-h-0 flex-1 items-center justify-center rounded-sm border border-dashed border-border px-3 py-3 text-center text-sm text-muted-foreground">
사진 없이 지도에서 준설위치를 직접 지정합니다.
</div>
)}
</div>
</section>
<section className="card card-border !m-0 shrink-0 overflow-hidden !p-0">
<div className="card-header !m-0 flex-wrap gap-2">
<h3 className="text-2xl font-medium text-label">위치 및 관로</h3>
<div className="flex shrink-0 flex-wrap justify-end gap-1">
{isEditingActiveLocation ? (
<>
<Button
type="button"
size="sm"
disabled={!locationDraft || activeGroup.isMatching}
onClick={() => {
void applyLocationDraft();
}}
>
{activeGroup.isMatching
? "관로 찾는 중..."
: "선택 위치 적용"}
</Button>
<Button
type="button"
size="sm"
color="white"
onClick={cancelLocationEditing}
>
취소
</Button>
</>
) : (
<Button
type="button"
size="sm"
onClick={() => startLocationEditing(activeGroup)}
>
{activeResolvedLocation ? "위치 수정" : "위치 지정"}
</Button>
)}
</div>
</div>
<div className="p-3">
<Table variant="secondary">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>위치등록</TableHead>
<TableCell className="border px-4">
<span
className={`inline-flex rounded-sm px-2 py-1 text-sm font-medium ${
hasUnappliedLocationDraft
? "bg-blue-100 text-blue-800"
: activeGroup.manualLocation
? "bg-violet-100 text-violet-800"
: activeResolvedLocation
? "bg-emerald-100 text-emerald-800"
: "bg-amber-100 text-amber-800"
}`}
>
{hasUnappliedLocationDraft
? "새 위치 선택됨"
: activeGroup.manualLocation
? `${locationSourceLabels.MANUAL} 위치`
: activeResolvedLocation
? `${locationSourceLabels.EXIF} 위치`
: "위치 지정 필요"}
</span>
</TableCell>
</TableRow>
<TableRow>
<TableHead>자동 연결 관로</TableHead>
<TableCell className="border px-4">
<strong className="mr-3 text-foreground">
{activeGroup.isMatching
? "탐색 중"
: hasUnappliedLocationDraft
? "재탐색 필요"
: activeGroup.matchedPipe
? activeGroup.matchedPipe.fcltMngNo
: "미연결"}
</strong>
<span
className={
!hasUnappliedLocationDraft && activeGroup.matchError
? "text-rose-700"
: "text-muted-foreground"
}
>
{hasUnappliedLocationDraft
? "선택 위치를 적용하면 최근접 관로를 다시 찾습니다."
: activeGroup.matchedPipe
? `${activeGroup.matchedPipe.distanceMeters.toFixed(2)}m · ${activeGroup.matchedPipe.swtrmtZoneNm || "처리구역 확인불가"}`
: activeGroup.matchError ||
"위치를 지정하면 50m 이내 최근접 관로를 자동으로 연결합니다."}
</span>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</section>
<div
className="bg-secondary/30 shrink-0 rounded-sm border border-border px-3 py-2 text-sm text-muted-foreground"
data-testid="dredging-registration-status"
>
{statusMessage ||
"사진·준설일자·위치와 자동 연결 관로를 확인해주세요."}
</div>
</aside>
<section className="card card-border !m-0 flex min-h-0 min-w-0 flex-col overflow-hidden !p-0">
<div className="card-header !m-0 shrink-0">
<h3 className="text-2xl font-medium text-label">위치 선택 지도</h3>
</div>
<div className="min-h-0 flex-1 p-2">
<LocationMap
value={
isEditingActiveLocation ? locationDraft : activeResolvedLocation
}
interactive={isEditingActiveLocation}
matchedPipe={
hasUnappliedLocationDraft ? null : activeGroup.matchedPipe
}
statusText={
isEditingActiveLocation
? hasUnappliedLocationDraft
? "새 위치를 선택했습니다. 관로 다시 찾기를 눌러 적용해주세요."
: "지도에서 새 준설위치를 클릭해주세요."
: activeResolvedLocation
? "등록된 준설위치를 표시하고 있습니다."
: "위치등록 버튼을 누른 뒤 지도에서 준설위치를 선택해주세요."
}
onChange={changeLocationDraft}
height="h-full min-h-0"
/>
</div>
</section>
</div>
) : null}
</div>
);
@@ -0,0 +1,291 @@
import { downloadExcelWithKoreanHeaders } from "@/shared/lib/download-excel";
import {
EXMN_DETAIL_SEVERITIES,
type ExmnDetailSeverity,
type ExmnDetailDefectColumn,
type ExmnPplUnitDetailRow,
type ExmnSurveyDetailRow,
type ExmnSeverityCounts,
} from "../model/exmn-detail-table";
import { getVisibleAnomalyTotals } from "./exmn-detail-totals";
type ExmnDetailDownloadOptions = {
selectedTrtdstNm: string;
defectGroupTitle: string;
isUnitMode: boolean;
defectTypeLabel: string;
unitRows: ExmnPplUnitDetailRow[];
rows: ExmnSurveyDetailRow[];
recordTypeLabels: Record<string, string>;
pipeItemLabels: Record<string, string>;
severityLabels: Record<ExmnDetailSeverity, string>;
visibleDefectColumns: ExmnDetailDefectColumn[];
totals: {
extensionM: number;
drivingDistanceM: number;
structuralGrade: number;
operationalGrade: number;
};
defectSummary: {
anomalySubtotals: ExmnSeverityCounts;
anomalyTotal: number;
defectSubtotals: Record<string, ExmnSeverityCounts>;
defectTotals: Record<string, number>;
};
summaryLabelColumnCount: number;
fixedColumnCount: number;
setNotice: (notice: { type: "info"; text: string } | null) => void;
};
/** 가변 결함 열 수에 맞춰 엑셀의 마지막 열 이름(A, Z, AA 등)을 계산한다. */
const getExcelColumnName = (columnCount: number) => {
let remaining = columnCount;
let result = "";
while (remaining > 0) {
remaining -= 1;
result = String.fromCharCode(65 + (remaining % 26)) + result;
remaining = Math.floor(remaining / 26);
}
return result || "A";
};
/** 현재 조회·필터·표 순서의 조사 결과로 Excel 열·상세·소계·합계·병합을 구성한다. */
export const downloadExmnSurveyDetails = async ({
selectedTrtdstNm,
defectGroupTitle,
isUnitMode,
defectTypeLabel,
unitRows,
rows,
recordTypeLabels,
pipeItemLabels,
severityLabels,
visibleDefectColumns,
totals,
defectSummary,
summaryLabelColumnCount,
fixedColumnCount,
setNotice,
}: ExmnDetailDownloadOptions) => {
const downloadDate = new Date().toISOString().slice(0, 10);
const safeFilePrefix = `${selectedTrtdstNm}_${defectGroupTitle}조사_${
isUnitMode ? "본단위등급표" : defectTypeLabel
}`.replace(/[\\/:*?"<>|]/g, "_");
try {
if (isUnitMode) {
if (unitRows.length === 0) {
setNotice({
type: "info",
text: "다운로드할 본단위구간 데이터가 없습니다.",
});
return;
}
const unitHeaderMapping: Record<string, string> = {
pipeNo: "관로번호",
unitSeq: "단위구간",
unitLengthM: "단위길이(m)",
defectPositionM: "결함위치(m)",
defectName: "결함 종류",
code: "결함 코드",
severity: "결함 등급",
occurrencePosition: "발생위치",
infiltrationBonus: "침입수 가점",
continuous: "연속결함",
structuralScore: "구조적 등급점수",
operationalScore: "운영적 등급점수",
surveyStopReason: "조사중단사유",
remark: "비고",
};
const unitDownloadRows = unitRows.map((row) => ({
pipeNo: row.pipeNo,
unitSeq: row.unitSeq,
unitLengthM: row.unitLengthM,
defectPositionM: row.defectPositionM,
defectName: row.recordType
? `(${recordTypeLabels[row.recordType] || row.recordType})${pipeItemLabels[row.code] || row.defectName.replace(/^\([^)]*\)/, "")}`
: row.defectName,
code: row.code,
severity: row.severity ? severityLabels[row.severity] : "-",
occurrencePosition: row.occurrencePosition,
infiltrationBonus: row.infiltrationBonus,
continuous: row.continuous == null ? "-" : row.continuous ? "Y" : "N",
structuralScore: row.structuralScore ?? "-",
operationalScore: row.operationalScore ?? "-",
surveyStopReason: row.surveyStopReason ?? "-",
remark: row.remark ?? "-",
}));
await downloadExcelWithKoreanHeaders({
data: unitDownloadRows as unknown as JSON[],
fileName: `${safeFilePrefix}_${downloadDate}.xlsx`,
sheetNameArray: ["본단위등급표"],
headerRange: "A1:N1",
headerMapping: unitHeaderMapping,
});
return;
}
if (rows.length === 0) {
setNotice({
type: "info",
text: "다운로드할 상세현황 데이터가 없습니다.",
});
return;
}
const detailHeaderMapping: Record<string, string> = {
reportNo: "보고서번호",
pipeNo: "관로번호",
upstreamManhole: "상류맨홀",
downstreamManhole: "하류맨홀",
drainageType: "배수방식",
pipeType: "관종",
specification: "규격",
extensionM: "연장(m)",
drivingDistanceM: "주행거리(m)",
};
Object.assign(detailHeaderMapping, {
structuralGrade: "구조적 내부결함",
operationalGrade: "운영적 내부결함",
});
Object.assign(detailHeaderMapping, {
anomalyL: "이상항목 합계-대",
anomalyM: "이상항목 합계-중",
anomalyS: "이상항목 합계-소",
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
detailHeaderMapping[`${column.code}_${severity}`] =
`${column.label} (${column.code})-${severityLabels[severity]}`;
});
});
const detailDownloadRows: Record<string, string | number>[] = rows.map(
(row) => {
const anomalyTotals = getVisibleAnomalyTotals(
row,
visibleDefectColumns,
);
const result: Record<string, string | number> = {
reportNo: row.reportNo,
pipeNo: row.pipeNo,
upstreamManhole: row.upstreamManhole,
downstreamManhole: row.downstreamManhole,
drainageType: row.drainageTypeName?.trim() || row.drainageType,
pipeType: row.pipeTypeName?.trim() || row.pipeType,
specification: row.specification,
extensionM: row.extensionM,
drivingDistanceM: row.drivingDistanceM,
};
Object.assign(result, {
structuralGrade: row.structuralGrade,
operationalGrade: row.operationalGrade,
});
Object.assign(result, {
anomalyL: anomalyTotals.L,
anomalyM: anomalyTotals.M,
anomalyS: anomalyTotals.S,
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
result[`${column.code}_${severity}`] =
row.defectCounts[column.code]?.[severity] ?? 0;
});
});
return result;
},
);
const subtotalRow: Record<string, string | number> = {
reportNo: "소계",
pipeNo: "",
upstreamManhole: "",
downstreamManhole: "",
drainageType: "",
pipeType: "",
specification: "",
extensionM: totals.extensionM,
drivingDistanceM: totals.drivingDistanceM,
};
const totalRow: Record<string, string | number> = {
reportNo: "합계",
pipeNo: "",
upstreamManhole: "",
downstreamManhole: "",
drainageType: "",
pipeType: "",
specification: "",
extensionM: totals.extensionM,
drivingDistanceM: totals.drivingDistanceM,
};
Object.assign(subtotalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(totalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(subtotalRow, {
anomalyL: defectSummary.anomalySubtotals.L,
anomalyM: defectSummary.anomalySubtotals.M,
anomalyS: defectSummary.anomalySubtotals.S,
});
Object.assign(totalRow, {
anomalyL: defectSummary.anomalyTotal,
anomalyM: "",
anomalyS: "",
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
subtotalRow[`${column.code}_${severity}`] =
defectSummary.defectSubtotals[column.code]?.[severity] ?? 0;
});
totalRow[`${column.code}_L`] =
defectSummary.defectTotals[column.code] ?? 0;
totalRow[`${column.code}_M`] = "";
totalRow[`${column.code}_S`] = "";
});
detailDownloadRows.push(subtotalRow, totalRow);
const subtotalExcelRow = rows.length + 2;
const totalExcelRow = rows.length + 3;
const summaryLabelLastColumn = getExcelColumnName(summaryLabelColumnCount);
const mergeRanges = [
`A${subtotalExcelRow}:${summaryLabelLastColumn}${subtotalExcelRow}`,
`A${totalExcelRow}:${summaryLabelLastColumn}${totalExcelRow}`,
];
for (
let groupStartColumn = fixedColumnCount + 1;
groupStartColumn < Object.keys(detailHeaderMapping).length;
groupStartColumn += EXMN_DETAIL_SEVERITIES.length
) {
mergeRanges.push(
`${getExcelColumnName(groupStartColumn)}${totalExcelRow}:${getExcelColumnName(
groupStartColumn + EXMN_DETAIL_SEVERITIES.length - 1,
)}${totalExcelRow}`,
);
}
await downloadExcelWithKoreanHeaders({
data: detailDownloadRows as unknown as JSON[],
fileName: `${safeFilePrefix}_${downloadDate}.xlsx`,
sheetNameArray: [
`${defectGroupTitle}조사 ${defectTypeLabel}`.slice(0, 31),
],
headerRange: `A1:${getExcelColumnName(Object.keys(detailHeaderMapping).length)}1`,
headerMapping: detailHeaderMapping,
mergeRanges,
});
} catch (error) {
console.error("조사 상세현황 엑셀 다운로드 오류:", error);
setNotice({
type: "info",
text:
error instanceof Error
? error.message
: "엑셀 다운로드 중 오류가 발생했습니다.",
});
}
};
@@ -0,0 +1,20 @@
import {
EXMN_DETAIL_SEVERITIES,
type ExmnSurveyDetailRow,
type ExmnDetailDefectColumn,
type ExmnSeverityCounts,
} from "../model/exmn-detail-table";
/** 고정 열의 숫자·한글·번호 혼합 값을 공통 그리드와 같은 방향으로 비교한다. */
/** 현재 화면에 노출하는 결함 열만 합산해 행의 대·중·소 합계를 계산한다. */
export const getVisibleAnomalyTotals = (
row: ExmnSurveyDetailRow,
defectColumns: ExmnDetailDefectColumn[],
): ExmnSeverityCounts => {
const totals: ExmnSeverityCounts = { L: 0, M: 0, S: 0 };
defectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
totals[severity] += row.defectCounts[column.code]?.[severity] ?? 0;
});
});
return totals;
};
@@ -20,7 +20,8 @@ import {
SelectValue,
Table,
} from "@common/components";
import { downloadExcelWithKoreanHeaders } from "@/shared/lib/download-excel";
import { downloadExmnSurveyDetails } from "../lib/download-exmn-details";
import { getVisibleAnomalyTotals } from "../lib/exmn-detail-totals";
import PopupSearchPanel, {
PopupSearchActions,
} from "@/features/windowPopup/ui/PopupSearchPanel";
@@ -38,12 +39,10 @@ import type {
import {
EXMN_DETAIL_SEVERITIES,
EXMN_DETAIL_TABLE_DEFINITIONS,
type ExmnDetailDefectColumn,
type ExmnDetailDefectType,
type ExmnDetailSeverity,
type ExmnPplDetailMode,
type ExmnPplUnitDetailRow,
type ExmnSeverityCounts,
type ExmnSurveyDetailRow,
} from "../model/exmn-detail-table";
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
@@ -108,17 +107,6 @@ const formatNumber = (value: number) =>
const formatCount = (value: number | null | undefined) =>
Number(value ?? 0) === 0 ? "-" : Number(value).toLocaleString("ko-KR");
/** 가변 결함 열 수에 맞춰 엑셀의 마지막 열 이름(A, Z, AA 등)을 계산한다. */
const getExcelColumnName = (columnCount: number) => {
let remaining = columnCount;
let result = "";
while (remaining > 0) {
remaining -= 1;
result = String.fromCharCode(65 + (remaining % 26)) + result;
remaining = Math.floor(remaining / 26);
}
return result || "A";
};
/** 공통 고정 열의 행 값을 화면용 문자열로 변환한다. */
const getFixedCellValue = (
@@ -135,20 +123,6 @@ const getFixedCellValue = (
return typeof value === "number" ? formatNumber(value) : value;
};
/** 고정 열의 숫자·한글·번호 혼합 값을 공통 그리드와 같은 방향으로 비교한다. */
/** 현재 화면에 노출하는 결함 열만 합산해 행의 대·중·소 합계를 계산한다. */
const getVisibleAnomalyTotals = (
row: ExmnSurveyDetailRow,
defectColumns: ExmnDetailDefectColumn[],
): ExmnSeverityCounts => {
const totals: ExmnSeverityCounts = { L: 0, M: 0, S: 0 };
defectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
totals[severity] += row.defectCounts[column.code]?.[severity] ?? 0;
});
});
return totals;
};
/** 엑셀 `01. 덕풍`·`01. 덕풍 (2)` 구조를 관로·맨홀 공통 WindowPopup으로 표시한다. */
export function ExmnSurveyDetailPopupPage({
@@ -512,232 +486,16 @@ export function ExmnSurveyDetailPopupPage({
}, [rows, visibleDefectColumns]);
/** 현재 화면에 표시된 관로·맨홀 상세 결과를 한글 헤더 엑셀로 내려받는다. */
const handleDownload = async () => {
const downloadDate = new Date().toISOString().slice(0, 10);
const safeFilePrefix =
`${selectedTrtdstNm}_${definition.defectGroupTitle}조사_${
isUnitMode ? "본단위등급표" : defectTypeLabel
}`.replace(/[\\/:*?"<>|]/g, "_");
try {
if (isUnitMode) {
if (unitRows.length === 0) {
setNotice({
type: "info",
text: "다운로드할 본단위구간 데이터가 없습니다.",
});
return;
}
const unitHeaderMapping: Record<string, string> = {
pipeNo: "관로번호",
unitSeq: "단위구간",
unitLengthM: "단위길이(m)",
defectPositionM: "결함위치(m)",
defectName: "결함 종류",
code: "결함 코드",
severity: "결함 등급",
occurrencePosition: "발생위치",
infiltrationBonus: "침입수 가점",
continuous: "연속결함",
structuralScore: "구조적 등급점수",
operationalScore: "운영적 등급점수",
surveyStopReason: "조사중단사유",
remark: "비고",
};
const unitDownloadRows = unitRows.map((row) => ({
pipeNo: row.pipeNo,
unitSeq: row.unitSeq,
unitLengthM: row.unitLengthM,
defectPositionM: row.defectPositionM,
defectName: row.recordType
? `(${recordTypeLabels[row.recordType] || row.recordType})${pipeItemLabels[row.code] || row.defectName.replace(/^\([^)]*\)/, "")}`
: row.defectName,
code: row.code,
severity: row.severity ? severityLabels[row.severity] : "-",
occurrencePosition: row.occurrencePosition,
infiltrationBonus: row.infiltrationBonus,
continuous: row.continuous == null ? "-" : row.continuous ? "Y" : "N",
structuralScore: row.structuralScore ?? "-",
operationalScore: row.operationalScore ?? "-",
surveyStopReason: row.surveyStopReason ?? "-",
remark: row.remark ?? "-",
}));
await downloadExcelWithKoreanHeaders({
data: unitDownloadRows as unknown as JSON[],
fileName: `${safeFilePrefix}_${downloadDate}.xlsx`,
sheetNameArray: ["본단위등급표"],
headerRange: "A1:N1",
headerMapping: unitHeaderMapping,
});
return;
}
if (rows.length === 0) {
setNotice({
type: "info",
text: "다운로드할 상세현황 데이터가 없습니다.",
});
return;
}
const detailHeaderMapping: Record<string, string> = {
reportNo: "보고서번호",
pipeNo: "관로번호",
upstreamManhole: "상류맨홀",
downstreamManhole: "하류맨홀",
drainageType: "배수방식",
pipeType: "관종",
specification: "규격",
extensionM: "연장(m)",
drivingDistanceM: "주행거리(m)",
};
Object.assign(detailHeaderMapping, {
structuralGrade: "구조적 내부결함",
operationalGrade: "운영적 내부결함",
});
Object.assign(detailHeaderMapping, {
anomalyL: "이상항목 합계-대",
anomalyM: "이상항목 합계-중",
anomalyS: "이상항목 합계-소",
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
detailHeaderMapping[`${column.code}_${severity}`] =
`${column.label} (${column.code})-${severityLabels[severity]}`;
});
});
const detailDownloadRows: Record<string, string | number>[] = rows.map(
(row) => {
const anomalyTotals = getVisibleAnomalyTotals(
row,
visibleDefectColumns,
);
const result: Record<string, string | number> = {
reportNo: row.reportNo,
pipeNo: row.pipeNo,
upstreamManhole: row.upstreamManhole,
downstreamManhole: row.downstreamManhole,
drainageType: row.drainageTypeName?.trim() || row.drainageType,
pipeType: row.pipeTypeName?.trim() || row.pipeType,
specification: row.specification,
extensionM: row.extensionM,
drivingDistanceM: row.drivingDistanceM,
};
Object.assign(result, {
structuralGrade: row.structuralGrade,
operationalGrade: row.operationalGrade,
});
Object.assign(result, {
anomalyL: anomalyTotals.L,
anomalyM: anomalyTotals.M,
anomalyS: anomalyTotals.S,
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
result[`${column.code}_${severity}`] =
row.defectCounts[column.code]?.[severity] ?? 0;
});
});
return result;
},
);
const subtotalRow: Record<string, string | number> = {
reportNo: "소계",
pipeNo: "",
upstreamManhole: "",
downstreamManhole: "",
drainageType: "",
pipeType: "",
specification: "",
extensionM: totals.extensionM,
drivingDistanceM: totals.drivingDistanceM,
};
const totalRow: Record<string, string | number> = {
reportNo: "합계",
pipeNo: "",
upstreamManhole: "",
downstreamManhole: "",
drainageType: "",
pipeType: "",
specification: "",
extensionM: totals.extensionM,
drivingDistanceM: totals.drivingDistanceM,
};
Object.assign(subtotalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(totalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(subtotalRow, {
anomalyL: defectSummary.anomalySubtotals.L,
anomalyM: defectSummary.anomalySubtotals.M,
anomalyS: defectSummary.anomalySubtotals.S,
});
Object.assign(totalRow, {
anomalyL: defectSummary.anomalyTotal,
anomalyM: "",
anomalyS: "",
});
visibleDefectColumns.forEach((column) => {
EXMN_DETAIL_SEVERITIES.forEach((severity) => {
subtotalRow[`${column.code}_${severity}`] =
defectSummary.defectSubtotals[column.code]?.[severity] ?? 0;
});
totalRow[`${column.code}_L`] =
defectSummary.defectTotals[column.code] ?? 0;
totalRow[`${column.code}_M`] = "";
totalRow[`${column.code}_S`] = "";
});
detailDownloadRows.push(subtotalRow, totalRow);
const subtotalExcelRow = rows.length + 2;
const totalExcelRow = rows.length + 3;
const summaryLabelLastColumn = getExcelColumnName(
summaryLabelColumnCount,
);
const mergeRanges = [
`A${subtotalExcelRow}:${summaryLabelLastColumn}${subtotalExcelRow}`,
`A${totalExcelRow}:${summaryLabelLastColumn}${totalExcelRow}`,
];
for (
let groupStartColumn = fixedColumns.length + 1;
groupStartColumn < Object.keys(detailHeaderMapping).length;
groupStartColumn += EXMN_DETAIL_SEVERITIES.length
) {
mergeRanges.push(
`${getExcelColumnName(groupStartColumn)}${totalExcelRow}:${getExcelColumnName(
groupStartColumn + EXMN_DETAIL_SEVERITIES.length - 1,
)}${totalExcelRow}`,
);
}
await downloadExcelWithKoreanHeaders({
data: detailDownloadRows as unknown as JSON[],
fileName: `${safeFilePrefix}_${downloadDate}.xlsx`,
sheetNameArray: [
`${definition.defectGroupTitle}조사 ${defectTypeLabel}`.slice(0, 31),
],
headerRange: `A1:${getExcelColumnName(Object.keys(detailHeaderMapping).length)}1`,
headerMapping: detailHeaderMapping,
mergeRanges,
});
} catch (error) {
console.error("조사 상세현황 엑셀 다운로드 오류:", error);
setNotice({
type: "info",
text:
error instanceof Error
? error.message
: "엑셀 다운로드 중 오류가 발생했습니다.",
});
}
};
/** 화면은 확정 조회/표 상태만 전달하고 Excel 조립·저장은 기능 모듈이 담당한다. */
const handleDownload = () => downloadExmnSurveyDetails({
selectedTrtdstNm,
defectGroupTitle: definition.defectGroupTitle,
isUnitMode, defectTypeLabel, unitRows, rows,
recordTypeLabels, pipeItemLabels, severityLabels, visibleDefectColumns,
totals, defectSummary, summaryLabelColumnCount,
fixedColumnCount: fixedColumns.length,
setNotice,
});
const tableWidth = useMemo(
() =>
@@ -1,246 +0,0 @@
"use client";
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@common/components/ui";
import { useEffect, useMemo, useState } from "react";
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
import type { PplFacility } from "../model/exmn-business-types";
import { ExmnStandardDataTable } from "./ExmnStandardDataTable";
const UNIT_TABLE_HEAD = [
{ id: "unitSeq", title: "단위", widthPercent: 8 },
{ id: "startPositionM", title: "시작위치(m)", widthPercent: 14 },
{ id: "unitLengthM", title: "단위연장(m)", widthPercent: 14 },
{ id: "structuralScore", title: "구조점수", widthPercent: 13 },
{ id: "structuralGrade", title: "구조등급", widthPercent: 13 },
{ id: "operationalScore", title: "운영점수", widthPercent: 13 },
{ id: "operationalGrade", title: "운영등급", widthPercent: 13 },
{ id: "detailCount", title: "기록수", widthPercent: 12 },
];
const DETAIL_TABLE_HEAD = [
{ id: "detailSeq", title: "순번", widthPercent: 6 },
{ id: "positionM", title: "위치(m)", widthPercent: 9 },
{ id: "code", title: "코드", widthPercent: 8 },
{ id: "recordType", title: "기록유형", widthPercent: 10 },
{ id: "typeText", title: "결함구분", widthPercent: 10 },
{ id: "severityText", title: "심각도", widthPercent: 8 },
{ id: "occurrencePositionText", title: "발생위치", widthPercent: 10 },
{ id: "continuousText", title: "연속결함", widthPercent: 9 },
{ id: "structuralScoreText", title: "구조점수", widthPercent: 10 },
{ id: "operationalScoreText", title: "운영점수", widthPercent: 10 },
{ id: "statusGroupText", title: "상태그룹", widthPercent: 10 },
];
interface PplFacilityDetailModalProps {
open: boolean;
facility: PplFacility | null;
onOpenChange: (open: boolean) => void;
}
/** PPL_UNIT_V1 정규화 응답을 단위 구간과 상태·결함 기록으로 표시한다. */
export function PplFacilityDetailModal({
open,
facility,
onOpenChange,
}: PplFacilityDetailModalProps) {
// 정규화 상세의 코드값은 유지하고 기록유형·분류·심각도·상태그룹 표시명만 변환한다.
const {
defectGradeOptions,
recordTypeLabels,
defectTypeLabels,
severityLabels,
statusGroupLabels,
} = useExmnCommonCodes();
// 선택 단위는 원문 배열 인덱스가 아니라 unitSeq로 보관해 서버 정렬과 무관하게 유지한다.
const [selectedUnitSeq, setSelectedUnitSeq] = useState<number | null>(null);
const defectGradeLabels = useMemo(
() =>
Object.fromEntries(
defectGradeOptions.map((option) => [option.value, option.label]),
),
[defectGradeOptions],
);
/** 시설이 바뀌면 첫 단위 구간을 기본 선택한다. */
useEffect(() => {
if (!open) return;
setSelectedUnitSeq(facility?.unitSections?.[0]?.unitSeq ?? null);
}, [facility, open]);
const unitRows = useMemo(
() =>
(facility?.unitSections ?? []).map((unit) => ({
...unit,
structuralGrade:
defectGradeLabels[String(unit.structuralGrade)] ||
unit.structuralGrade,
operationalGrade:
defectGradeLabels[String(unit.operationalGrade)] ||
unit.operationalGrade,
detailCount: unit.details?.length ?? 0,
})),
[defectGradeLabels, facility],
);
const selectedUnit = useMemo(
() =>
facility?.unitSections?.find(
(unit) => unit.unitSeq === selectedUnitSeq,
) ?? null,
[facility, selectedUnitSeq],
);
const detailRows = useMemo(
() =>
(selectedUnit?.details ?? []).map((detail) => {
const defectType = detail.type ?? "";
const severity = detail.severity ?? "";
const statusGroup = detail.statusGroup ?? "";
return {
...detail,
recordType:
recordTypeLabels[detail.recordType] || detail.recordType || "-",
typeText: defectTypeLabels[defectType] || defectType || "-",
severityText: severityLabels[severity] || severity || "-",
occurrencePositionText: detail.occurrencePosition ?? "-",
continuousText:
detail.continuous == null ? "-" : detail.continuous ? "Y" : "N",
structuralScoreText: detail.structuralScore ?? "-",
operationalScoreText: detail.operationalScore ?? "-",
statusGroupText:
statusGroupLabels[statusGroup] || statusGroup || "-",
};
}),
[
defectTypeLabels,
recordTypeLabels,
selectedUnit,
severityLabels,
statusGroupLabels,
],
);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[94vh] w-[96vw] !max-w-[96vw] flex-col overflow-hidden !p-0">
<DialogHeader className="card-header shrink-0 !space-y-0 px-5">
<DialogTitle className="text-[1.8rem] font-semibold text-label">
PPL 조사시설 상세
</DialogTitle>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto p-4">
<section className="grid grid-cols-1 gap-x-5 gap-y-3 rounded border bg-secondary p-4 text-sm md:grid-cols-3">
<div>
<strong>보고서번호</strong>
<p className="mt-1 text-label">{facility?.rptpNo || "-"}</p>
</div>
<div>
<strong>GIS 관로관리번호</strong>
<p className="mt-1 text-label">
{facility?.exmnFcltyGisMngNo || "-"}
</p>
</div>
<div>
<strong>처리분구</strong>
<p className="mt-1 text-label">{facility?.trtdstNm || "-"}</p>
</div>
<div>
<strong>상류/하류 맨홀</strong>
<p className="mt-1 text-label">
{facility?.upstmMnhlNo || "-"} / {facility?.dnstmMnhlNo || "-"}
</p>
</div>
<div>
<strong>배수방식</strong>
<p className="mt-1 text-label">{facility?.drgptnCd || "-"}</p>
</div>
<div>
<strong>관종/규격</strong>
<p className="mt-1 text-label">
{facility?.pptyCd || "-"} / {facility?.spcfctCd || "-"}
</p>
</div>
<div>
<strong>연장/주행거리</strong>
<p className="mt-1 text-label">
{facility?.prlg ?? "-"} / {facility?.drvngDstnc ?? "-"}
</p>
</div>
<div>
<strong>구조/운영 등급</strong>
<p className="mt-1 text-label">
{facility?.strctDfcGrdCd || "-"} /{" "}
{facility?.operDfcGrdCd || "-"}
</p>
</div>
</section>
<section>
<ExmnStandardDataTable
rows={
unitRows as Array<
(typeof unitRows)[number] & Record<string, unknown>
>
}
title="단위 구간 목록"
headlist={UNIT_TABLE_HEAD}
total={unitRows.length}
pageSize={Math.max(unitRows.length, 1)}
page={1}
onRowClick={(row) => setSelectedUnitSeq(row.unitSeq)}
onPageChange={() => undefined}
/>
</section>
<section className="rounded border bg-secondary p-3 text-sm text-label">
<strong>조사중단사유:</strong>{" "}
{selectedUnit?.surveyStopReason || "없음"}
<span className="mx-4 text-muted-foreground">|</span>
<strong>비고:</strong> {selectedUnit?.remark || "없음"}
</section>
<section>
<ExmnStandardDataTable
rows={
detailRows as Array<
(typeof detailRows)[number] & Record<string, unknown>
>
}
title="상태·결함 상세 기록 목록"
headlist={DETAIL_TABLE_HEAD}
total={detailRows.length}
pageSize={Math.max(detailRows.length, 1)}
page={1}
onPageChange={() => undefined}
scrollMode="horizontal"
minTableWidth="140rem"
/>
</section>
<section className="flex items-center justify-between rounded border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
<span>
시설 보고서 파일 매핑 원천이 확정되기 전까지 보고서 조회는
제공하지 않습니다.
</span>
<Button disabled title="보고서 매핑 모델 확정 필요">
보고서 보기
</Button>
</section>
</div>
<DialogFooter className="card-footer shrink-0">
<Button color="white" onClick={() => onOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,599 +0,0 @@
"use client";
import LoadingOverlay from "@/components/ui/LoadingBar";
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
Input,
} from "@common/components/ui";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
getExmnBusiness,
getPplFacilities,
getPplSummaries,
} from "../api/exmn-business-api";
import type {
ExmnBusiness,
ExmnBusinessDetail,
PplFacility,
PplSummaryRow,
} from "../model/exmn-business-types";
import { PplFacilityDetailModal } from "./PplFacilityDetailModal";
import { ExmnStandardDataTable } from "./ExmnStandardDataTable";
import { downloadExcelWithKoreanHeaders } from "@/shared/lib/download-excel";
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
const SUMMARY_TABLE_HEAD = [
{ id: "trtdstNm", title: "처리분구", widthPercent: 20 },
{
id: "trgtPrlgText",
title: "대상연장(m)",
widthPercent: 13,
},
{
id: "drvngDstncText",
title: "주행거리(m)",
widthPercent: 13,
},
{
id: "pplExmnWholAnmlyArtclCnt",
title: "PPL 전체이상",
widthPercent: 14,
},
{
id: "pplExmnStrctDfcCnt",
title: "구조결함",
widthPercent: 13,
},
{
id: "pplExmnOperDfcCnt",
title: "운영결함",
widthPercent: 13,
},
{ id: "pplExmnEtcCnt", title: "기타", widthPercent: 14 },
];
const FACILITY_TABLE_HEAD = [
{ id: "trtdstNm", title: "처리분구", widthPercent: 13 },
{ id: "rptpNo", title: "보고서번호", widthPercent: 12 },
{
id: "exmnFcltyGisMngNo",
title: "GIS 관로관리번호",
widthPercent: 18,
},
{ id: "upstreamDownstream", title: "상류/하류 맨홀", widthPercent: 17 },
{ id: "pipeSpec", title: "관종/규격", widthPercent: 13 },
{
id: "prlgText",
title: "연장(m)",
widthPercent: 9,
},
{
id: "strctDfcGrdCdText",
title: "구조등급",
widthPercent: 9,
},
{
id: "operDfcGrdCdText",
title: "운영등급",
widthPercent: 9,
},
];
const SUMMARY_CLICKABLE_HEAD_IDS = [
"pplExmnWholAnmlyArtclCnt",
"pplExmnStrctDfcCnt",
"pplExmnOperDfcCnt",
"pplExmnEtcCnt",
];
type Notice = { type: "success" | "error"; text: string } | null;
type PplDefectType = "ALL" | "STRUCTURAL" | "OPERATIONAL" | "ETC";
type PplFacilityFilters = {
trtdstId: string;
sectionType: string;
gisManagementNo: string;
structuralGrade: string;
operationalGrade: string;
defectType: PplDefectType;
};
const DEFAULT_PPL_FACILITY_FILTERS: PplFacilityFilters = {
trtdstId: "",
sectionType: "",
gisManagementNo: "",
structuralGrade: "",
operationalGrade: "",
defectType: "ALL",
};
interface PplSummaryModalProps {
open: boolean;
business: ExmnBusiness | null;
onOpenChange: (open: boolean) => void;
}
/** 숫자 값을 목록에서 단위 없이 천단위 구분 형식으로 표시한다. */
const formatNumber = (value: number | null | undefined) =>
Number(value ?? 0).toLocaleString("ko-KR", { maximumFractionDigits: 3 });
/** 처리분구별 PPL 집계에서 결함 수를 따라 시설 목록과 단위 상세까지 탐색하는 모달이다. */
export function PplSummaryModal({
open,
business,
onOpenChange,
}: PplSummaryModalProps) {
// 조사시설 검색 코드값은 유지하고 등급·결함분류 표시명만 CMS 기준으로 사용한다.
const { defectGradeOptions, defectTypeLabels } = useExmnCommonCodes();
const [businessDetail, setBusinessDetail] =
useState<ExmnBusinessDetail | null>(null);
const [summaryRows, setSummaryRows] = useState<PplSummaryRow[]>([]);
const [summaryTotal, setSummaryTotal] = useState(0);
const [summaryPage, setSummaryPage] = useState(0);
const [facilityRows, setFacilityRows] = useState<PplFacility[]>([]);
const [facilityTotal, setFacilityTotal] = useState(0);
const [facilityPage, setFacilityPage] = useState(0);
// 집계 건수 클릭과 상세 조회조건이 공유하는 처리분구·결함유형 컨텍스트다.
const [trtdstId, setTrtdstId] = useState("");
const [sectionType, setSectionType] = useState("");
const [gisManagementNo, setGisManagementNo] = useState("");
const [structuralGrade, setStructuralGrade] = useState("");
const [operationalGrade, setOperationalGrade] = useState("");
const [defectType, setDefectType] = useState<PplDefectType>("ALL");
const [selectedFacility, setSelectedFacility] = useState<PplFacility | null>(
null,
);
const [isLoading, setIsLoading] = useState(false);
const [notice, setNotice] = useState<Notice>(null);
const displayedSummaryRows = useMemo(
() =>
summaryRows.map((row) => ({
...row,
trgtPrlgText: formatNumber(row.trgtPrlg),
drvngDstncText: formatNumber(row.drvngDstnc),
})),
[summaryRows],
);
const displayedFacilityRows = useMemo(
() =>
facilityRows.map((row) => ({
...row,
upstreamDownstream: `${row.upstmMnhlNo || "-"} / ${row.dnstmMnhlNo || "-"}`,
pipeSpec: `${row.pptyCd || "-"} / ${row.spcfctCd || "-"}`,
prlgText: row.prlg == null ? "-" : formatNumber(row.prlg),
strctDfcGrdCdText: row.strctDfcGrdCd || "-",
operDfcGrdCdText: row.operDfcGrdCd || "-",
})),
[facilityRows],
);
/** 현재 상세 필터로 PPL 시설 페이지를 요청한다. */
const fetchFacilities = useCallback(
async (
nextPage = facilityPage,
filters: PplFacilityFilters = {
trtdstId,
sectionType,
gisManagementNo,
structuralGrade,
operationalGrade,
defectType,
},
) => {
if (!business?.exmnBizId) return;
setIsLoading(true);
setNotice(null);
try {
const page = await getPplFacilities({
exmnBizId: business.exmnBizId,
trtdstId: filters.trtdstId || undefined,
sectionType: filters.sectionType || undefined,
gisManagementNo: filters.gisManagementNo || undefined,
structuralGrade: filters.structuralGrade || undefined,
operationalGrade: filters.operationalGrade || undefined,
defectType: filters.defectType,
page: nextPage,
size: 10,
});
setFacilityRows(page.content);
setFacilityTotal(page.totalElements);
setFacilityPage(page.number);
} catch (error) {
setFacilityRows([]);
setFacilityTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 시설 조회 중 오류가 발생했습니다.",
});
} finally {
setIsLoading(false);
}
},
[
business,
defectType,
facilityPage,
gisManagementNo,
operationalGrade,
sectionType,
structuralGrade,
trtdstId,
],
);
/** 모달 진입과 집계 정렬·페이지 변경 시 사업 상세와 PPL 집계를 읽는다. */
useEffect(() => {
if (!open || !business?.exmnBizId) return;
let active = true;
setIsLoading(true);
setNotice(null);
Promise.all([
getExmnBusiness(business.exmnBizId),
getPplSummaries(business.exmnBizId, {
trtdstId: trtdstId || undefined,
page: summaryPage,
size: 10,
}),
])
.then(([detail, page]) => {
if (!active) return;
setBusinessDetail(detail);
setSummaryRows(page.content);
setSummaryTotal(page.totalElements);
})
.catch((error: unknown) => {
if (!active) return;
setSummaryRows([]);
setSummaryTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 집계 조회 중 오류가 발생했습니다.",
});
})
.finally(() => {
if (active) setIsLoading(false);
});
return () => {
active = false;
};
}, [business, open, summaryPage, trtdstId]);
/** 새 사업을 열 때 상세 필터·페이지·선택 시설을 초기화한다. */
useEffect(() => {
if (!open) return;
setSummaryPage(0);
setFacilityRows([]);
setFacilityTotal(0);
setFacilityPage(0);
setTrtdstId("");
setSectionType("");
setGisManagementNo("");
setStructuralGrade("");
setOperationalGrade("");
setDefectType("ALL");
setSelectedFacility(null);
}, [business, open]);
/** 집계의 전체·구조·운영·기타 건수를 클릭하면 해당 처리분구 시설 조회로 연결한다. */
const handleSummaryCellClick = (
index: number | undefined,
headId: string,
) => {
if (index == null) return;
const row = summaryRows[index];
if (!row) return;
const nextDefectType: PplDefectType =
headId === "pplExmnStrctDfcCnt"
? "STRUCTURAL"
: headId === "pplExmnOperDfcCnt"
? "OPERATIONAL"
: headId === "pplExmnEtcCnt"
? "ETC"
: "ALL";
setTrtdstId(row.trtdstId);
setDefectType(nextDefectType);
setFacilityPage(0);
setNotice(null);
// React 상태 반영 전 값 대신 클릭 컨텍스트로 즉시 요청한다.
setIsLoading(true);
getPplFacilities({
exmnBizId: business?.exmnBizId ?? "",
trtdstId: row.trtdstId,
sectionType: sectionType || undefined,
gisManagementNo: gisManagementNo || undefined,
structuralGrade: structuralGrade || undefined,
operationalGrade: operationalGrade || undefined,
defectType: nextDefectType,
page: 0,
size: 10,
})
.then((page) => {
setFacilityRows(page.content);
setFacilityTotal(page.totalElements);
setFacilityPage(page.number);
})
.catch((error: unknown) => {
setFacilityRows([]);
setFacilityTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 시설 조회 중 오류가 발생했습니다.",
});
})
.finally(() => setIsLoading(false));
};
/** 현재 처리분구 조건의 PPL 집계 엑셀을 다운로드한다. */
const handleExport = async () => {
if (!business) return;
setIsLoading(true);
setNotice(null);
try {
const result = await fetchAllPages({
fetchPage: (page, size) =>
getPplSummaries(business.exmnBizId, {
trtdstId: trtdstId || undefined,
page,
size,
}),
getItems: (page) => page.content ?? [],
getTotal: (page) => Number(page.totalElements ?? 0),
});
const excelRows = result.items.map((row) => ({
trtdstNm: row.trtdstNm,
trgtPrlg: row.trgtPrlg,
drvngDstnc: row.drvngDstnc,
pplExmnWholAnmlyArtclCnt: row.pplExmnWholAnmlyArtclCnt,
pplExmnStrctDfcCnt: row.pplExmnStrctDfcCnt,
pplExmnOperDfcCnt: row.pplExmnOperDfcCnt,
pplExmnEtcCnt: row.pplExmnEtcCnt,
}));
await downloadExcelWithKoreanHeaders({
data: excelRows as unknown as JSON[],
fileName: `${business.bizNm}_PPL집계.xlsx`,
sheetNameArray: ["처리분구별 PPL 집계"],
headerRange: "A1:G1",
headerMapping: {
trtdstNm: "처리분구",
trgtPrlg: "대상연장(m)",
drvngDstnc: "주행거리(m)",
pplExmnWholAnmlyArtclCnt: "PPL 전체이상",
pplExmnStrctDfcCnt: "구조결함",
pplExmnOperDfcCnt: "운영결함",
pplExmnEtcCnt: "기타",
},
});
} catch (error) {
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 엑셀 다운로드 중 오류가 발생했습니다.",
});
} finally {
setIsLoading(false);
}
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[94vh] w-[96vw] !max-w-[96vw] flex-col overflow-hidden !p-0">
<DialogHeader className="card-header shrink-0 !space-y-0 px-5">
<DialogTitle className="text-[1.8rem] font-semibold text-label">
PPL 조사 집계·상세
</DialogTitle>
</DialogHeader>
<div className="relative min-h-0 flex-1 space-y-5 overflow-y-auto p-4">
<LoadingOverlay isLoading={isLoading} />
{notice && (
<div
role="alert"
className={`rounded border px-4 py-3 text-sm ${notice.type === "error" ? "border-red-200 bg-red-50 text-red-700" : "border-emerald-200 bg-emerald-50 text-emerald-700"}`}
>
{notice.text}
</div>
)}
<div className="rounded border bg-secondary px-4 py-3 text-sm text-label">
<strong>{business?.bizNm ?? "선택 사업"}</strong>
<span className="mx-3 text-muted-foreground">|</span>
{business?.bizYr}년 {business?.bizCycl ?? "-"}차
<span className="mx-3 text-muted-foreground">|</span>
{business?.ctpvNm} {business?.sggNm}
</div>
<section>
<ExmnStandardDataTable
rows={
displayedSummaryRows as Array<
(typeof displayedSummaryRows)[number] &
Record<string, unknown>
>
}
title="처리분구별 PPL 집계 목록"
headlist={SUMMARY_TABLE_HEAD}
total={summaryTotal}
pageSize={10}
page={summaryPage + 1}
clickableHeadIds={SUMMARY_CLICKABLE_HEAD_IDS}
onCellClick={(_row, index, headId) =>
handleSummaryCellClick(index, headId)
}
onPageChange={(page) => setSummaryPage(page - 1)}
actions={
<Button
disabled={isLoading}
onClick={() => void handleExport()}
>
엑셀다운로드
</Button>
}
/>
</section>
<section className="rounded border border-border p-4">
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<label className="text-sm font-medium text-label">
처리분구
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={trtdstId}
onChange={(event) => setTrtdstId(event.target.value)}
>
<option value="">전체</option>
{(businessDetail?.districts ?? []).map((district) => (
<option key={district.trtdstId} value={district.trtdstId}>
{district.trtdstNm}
</option>
))}
</select>
</label>
<label className="text-sm font-medium text-label">
구간 구분
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={sectionType}
onChange={(event) => setSectionType(event.target.value)}
>
<option value="">전체</option>
<option value="PIPE">관로</option>
<option value="UNIT">단위구간</option>
</select>
</label>
<label className="col-span-2 text-sm font-medium text-label">
GIS 관로관리번호
<Input
className="mt-1 h-10 text-base"
value={gisManagementNo}
onChange={(event) => setGisManagementNo(event.target.value)}
/>
</label>
<label className="text-sm font-medium text-label">
구조등급
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={structuralGrade}
onChange={(event) => setStructuralGrade(event.target.value)}
>
<option value="">전체</option>
{defectGradeOptions.map((grade) => (
<option key={grade.value} value={grade.value}>
{grade.label}
</option>
))}
</select>
</label>
<label className="text-sm font-medium text-label">
운영등급
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={operationalGrade}
onChange={(event) =>
setOperationalGrade(event.target.value)
}
>
<option value="">전체</option>
{defectGradeOptions.map((grade) => (
<option key={grade.value} value={grade.value}>
{grade.label}
</option>
))}
</select>
</label>
</div>
<div className="mt-3 flex items-center justify-between">
<span className="text-sm text-muted-foreground">
결함 분류: {defectTypeLabels[defectType] || defectType}
</span>
<Button
disabled={isLoading}
onClick={() => void fetchFacilities(0)}
>
조회
</Button>
<Button
color="white"
disabled={isLoading}
onClick={() => {
setTrtdstId(DEFAULT_PPL_FACILITY_FILTERS.trtdstId);
setSectionType(DEFAULT_PPL_FACILITY_FILTERS.sectionType);
setGisManagementNo(
DEFAULT_PPL_FACILITY_FILTERS.gisManagementNo,
);
setStructuralGrade(
DEFAULT_PPL_FACILITY_FILTERS.structuralGrade,
);
setOperationalGrade(
DEFAULT_PPL_FACILITY_FILTERS.operationalGrade,
);
setDefectType(DEFAULT_PPL_FACILITY_FILTERS.defectType);
setFacilityPage(0);
setSelectedFacility(null);
void fetchFacilities(0, DEFAULT_PPL_FACILITY_FILTERS);
}}
>
초기화
</Button>
</div>
</section>
<section>
<ExmnStandardDataTable
rows={
displayedFacilityRows as Array<
(typeof displayedFacilityRows)[number] &
Record<string, unknown>
>
}
title="PPL 시설 목록"
headlist={FACILITY_TABLE_HEAD}
total={facilityTotal}
pageSize={10}
page={facilityPage + 1}
onRowClick={(_row, index) =>
setSelectedFacility(facilityRows[index] ?? null)
}
onPageChange={(page) => void fetchFacilities(page - 1)}
scrollMode="horizontal"
minTableWidth="120rem"
/>
<p className="mt-2 text-right text-sm text-muted-foreground">
시설 행을 선택하면 단위 구간과 상태·결함 상세가 열립니다.
</p>
</section>
</div>
<DialogFooter className="card-footer shrink-0">
<Button color="white" onClick={() => onOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<PplFacilityDetailModal
open={Boolean(selectedFacility)}
facility={selectedFacility}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSelectedFacility(null);
}}
/>
</>
);
}
@@ -349,7 +349,7 @@ export default function FldngPredcPrstPopupContent() {
});
// 백엔드 공통 응답({ data: ... })의 data 영역을 반환하는 API 헬퍼를 사용한다.
const extentData = await getData(
`/sewerage-service/api/v1/fldng/flood-dngr-map/group/extent?${params.toString()}`,
`/sewerage-service/api/v1/fldng/floodDngrMap/group/extent?${params.toString()}`,
);
const extent = [
extentData?.minX,
+4
View File
@@ -0,0 +1,4 @@
/** GIS 편집의 모델·snapshot 규칙을 화면에 제공하는 공개 경계다. */
export * from "./model/types";
export * from "./lib/edit-model";
export * from "./lib/feature-snapshot";
@@ -0,0 +1,343 @@
/** 편집 가능한 레이어·속성·미리보기 규칙을 React 상태 변경과 분리한다. */
/** 편집 가능한 레이어·속성·미리보기 규칙을 React 상태 변경과 분리한다. */
import type {
GisEditChange,
GisEditGeometryType,
GisEditLayerInfo,
GisEditPipeBasicInfo,
GisEditPreviewColors,
} from "../model/types";
export type GisEditInteractionRequest = {
changeId: string;
editType: "MOVE" | "VERTEX_EDIT";
};
export const isActionableChange = (change: GisEditChange) =>
!change.attributeOnly || Boolean(change.basicInfoSavedAt);
export const isGeometryChange = (change: GisEditChange) =>
!change.attributeOnly && change.editType !== "ADD";
export const buildPreviewFocusMessage = (
change: Pick<GisEditChange, "editType" | "layerName" | "objectLabel">,
) => {
if (change.editType === "MOVE") {
return `${change.layerName} ${change.objectLabel} 미리보기 객체를 드래그해 위치를 조정하세요.`;
}
if (change.editType === "VERTEX_EDIT") {
return `${change.layerName} ${change.objectLabel}의 주황색 실꼭지점을 드래그하거나, 선분 위 흰색 midpoint를 끌어 새 꼭지점을 추가하세요.`;
}
if (change.editType === "DELETE") {
return `${change.layerName} ${change.objectLabel} 삭제 미리보기를 유지 중입니다.`;
}
return `${change.layerName} ${change.objectLabel} 신규 객체 미리보기를 확인하세요.`;
};
export const EDITABLE_LAYER_RULES: Record<
string,
Omit<GisEditLayerInfo, "layerId" | "editableYn">
> = {
tb_ms_swage_ppl: {
layerName: "하수관로",
geometryType: "LineString",
allowedTools: ["ADD", "MOVE", "VERTEX_EDIT", "DELETE"],
previewColors: {
pointColor: "rgba(22, 163, 74, 0.92)",
lineColor: "rgba(22, 163, 74, 0.95)",
fillColor: "rgba(22, 163, 74, 0.18)",
},
},
tb_ms_swage_mhl: {
layerName: "하수맨홀",
geometryType: "Point",
allowedTools: ["ADD", "MOVE", "DELETE"],
previewColors: {
pointColor: "rgba(5, 150, 105, 0.92)",
lineColor: "rgba(5, 150, 105, 0.95)",
fillColor: "rgba(5, 150, 105, 0.18)",
},
},
tb_ms_swage_pmstn: {
layerName: "하수펌프장",
geometryType: "Point",
allowedTools: ["ADD", "MOVE", "DELETE"],
previewColors: {
pointColor: "rgba(59, 130, 246, 0.92)",
lineColor: "rgba(59, 130, 246, 0.95)",
fillColor: "rgba(59, 130, 246, 0.18)",
},
},
tb_il_swage_prcs_fclt: {
layerName: "하수처리시설",
geometryType: "Point",
allowedTools: ["ADD", "MOVE", "DELETE"],
previewColors: {
pointColor: "rgba(168, 85, 247, 0.92)",
lineColor: "rgba(168, 85, 247, 0.95)",
fillColor: "rgba(168, 85, 247, 0.18)",
},
},
tb_ms_swage_prcs_zone: {
layerName: "하수처리구역",
geometryType: "Polygon",
allowedTools: ["ADD", "MOVE", "VERTEX_EDIT", "DELETE"],
previewColors: {
pointColor: "rgba(249, 115, 22, 0.92)",
lineColor: "rgba(249, 115, 22, 0.95)",
fillColor: "rgba(249, 115, 22, 0.22)",
},
},
tb_ms_stofcbr: {
layerName: "우수토실",
geometryType: "Point",
allowedTools: ["ADD", "MOVE", "DELETE"],
previewColors: {
pointColor: "rgba(234, 88, 12, 0.92)",
lineColor: "rgba(234, 88, 12, 0.95)",
fillColor: "rgba(234, 88, 12, 0.18)",
},
},
om_dt_untrt_swg_rain: {
layerName: "중점우수토실",
geometryType: "Point",
allowedTools: ["ADD", "MOVE", "DELETE"],
previewColors: {
pointColor: "rgba(220, 38, 38, 0.92)",
lineColor: "rgba(220, 38, 38, 0.95)",
fillColor: "rgba(220, 38, 38, 0.18)",
},
},
};
export const FLOW_DIRECTION_SRS = "EPSG:5179";
export const SCREEN_ID = "SN_MN010301";
export const GIS_EDIT_ALLOWED_LAYER_IDS = new Set(["tb_ms_swage_ppl"]);
export const GIS_EDIT_PIPE_ATTRIBUTE_FIELD_IDS = [
"mngInstCd",
"fcltMngNo",
"instMngNo",
"instlYmd",
"mapshtNo",
"pdmtVl",
"prlgVl",
"usgCd",
"mqltCd",
"avgGrdn",
"drtwMltvArea",
"exclnMltvArea",
"tmptDpth",
"tmptMhlMngNo",
"scendDpth",
"scendMhlMngNo",
"trflnCnt",
"vrtcLen",
"wdthLen",
"instlMbdyCd",
"swtrmtZoneNm",
"mltvZoneNm",
"mltvDtdvNm",
"lineCd",
"floCd",
"layCd",
] as const;
export const buildPipeSaveAttributes = (
basicInfo: GisEditPipeBasicInfo | null | undefined,
) => {
if (!basicInfo) return undefined;
return GIS_EDIT_PIPE_ATTRIBUTE_FIELD_IDS.reduce<GisEditPipeBasicInfo>(
(acc, fieldId) => {
if (!Object.prototype.hasOwnProperty.call(basicInfo, fieldId)) return acc;
const value = basicInfo[fieldId];
const normalizedValue =
fieldId === "instlYmd"
? String(value ?? "").replaceAll("-", "")
: value;
acc[fieldId] =
typeof normalizedValue === "string" && normalizedValue.trim() === ""
? null
: normalizedValue;
return acc;
},
{},
);
};
export const EMPTY_GIS_EDIT_PIPE_BASIC_INFO: GisEditPipeBasicInfo = {
mngInstCd: "",
fcltMngNo: "",
instMngNo: "",
instlYmd: "",
usgCd: "",
instlMbdyCd: "",
swtrmtZoneNm: "",
mltvZoneNm: "",
mltvDtdvNm: "",
lineCd: "",
floCd: "",
layCd: "",
};
export const normalizeLayerIdCandidate = (value: unknown) => {
const raw = String(value ?? "").trim();
if (!raw) return "";
const withoutNamespace = raw.includes(":")
? (raw.split(":").pop() ?? raw)
: raw;
return withoutNamespace.split(".")[0] ?? withoutNamespace;
};
// 현재 레이어 트리 구조 안에서 실제 편집 대상으로 풀 수 있는 레이어만 추출한다.
export const getLayerTypeName = (layerInfo: any) =>
String(
layerInfo?.lyrTyNm ?? layerInfo?.lyrTypeNm ?? layerInfo?.lyr_type_nm ?? "",
).trim();
export const getLayerName = (layerInfo: any) =>
String(layerInfo?.lyrNm ?? layerInfo?.name ?? "").trim();
export const normalizeGeometryType = (value: unknown): GisEditGeometryType => {
const normalized = String(value ?? "").toLowerCase();
if (normalized.includes("polygon")) return "Polygon";
if (normalized.includes("line")) return "LineString";
return "Point";
};
export const getColorString = (value: unknown) => {
const resolved = String(value ?? "").trim();
return resolved || null;
};
export const withAlpha = (color: string | null | undefined, alpha: number) => {
const resolvedColor = String(color ?? "").trim();
if (!resolvedColor) return null;
const rgbaMatch = resolvedColor.match(/^rgba?\(([^)]+)\)$/i);
if (rgbaMatch) {
const [red = "40", green = "90", blue = "180"] = (rgbaMatch[1] ?? "")
.split(",")
.map((part) => part.trim());
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
const hexMatch = resolvedColor.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
if (hexMatch) {
const hex = hexMatch[1] ?? "";
const normalized =
hex.length === 3
? hex
.split("")
.map((char) => char + char)
.join("")
: hex;
const red = parseInt(normalized.slice(0, 2), 16);
const green = parseInt(normalized.slice(2, 4), 16);
const blue = parseInt(normalized.slice(4, 6), 16);
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
return resolvedColor;
};
export const resolvePreviewColors = (
layerInfo: any,
fallback: GisEditPreviewColors,
): GisEditPreviewColors => {
const lineColor =
withAlpha(
getColorString(
layerInfo?.lineColr ??
layerInfo?.line_colr ??
layerInfo?.lineColor ??
layerInfo?.fontInsdColr ??
layerInfo?.font_insd_colr,
),
0.95,
) ?? fallback.lineColor;
const pointColor =
withAlpha(
getColorString(
layerInfo?.lineColr ??
layerInfo?.line_colr ??
layerInfo?.fontInsdColr ??
layerInfo?.font_insd_colr ??
layerInfo?.fontExtnlColr ??
layerInfo?.font_extnl_colr,
),
0.92,
) ?? fallback.pointColor;
const fillColor =
withAlpha(
getColorString(
layerInfo?.spacColr ??
layerInfo?.spac_colr ??
layerInfo?.spaceColor ??
layerInfo?.lineColr ??
layerInfo?.line_colr,
),
0.22,
) ?? fallback.fillColor;
return {
pointColor,
lineColor,
fillColor,
};
};
// 현행 운영 기준상 GIS 편집은 하수관로만 다루므로 treeData에서도 해당 레이어만 추린다.
export const collectEditableLayers = (treeData: any[]): GisEditLayerInfo[] => {
const results = new Map<string, GisEditLayerInfo>();
const visit = (items: any[]) => {
items.forEach((item) => {
const data = item?.data ?? item;
const layerTypeName = getLayerTypeName(data);
const layerRule = EDITABLE_LAYER_RULES[layerTypeName];
if (
layerRule &&
GIS_EDIT_ALLOWED_LAYER_IDS.has(layerTypeName) &&
!results.has(layerTypeName)
) {
results.set(layerTypeName, {
layerId: layerTypeName,
layerName: layerRule.layerName,
geometryType: layerRule.geometryType,
editableYn: "Y",
allowedTools: layerRule.allowedTools,
previewColors: resolvePreviewColors(data, layerRule.previewColors),
});
}
if (Array.isArray(item?.children)) {
visit(item.children);
}
if (Array.isArray(data?.children)) {
visit(data.children);
}
});
};
visit(Array.isArray(treeData) ? treeData : []);
if (results.size === 0) {
Object.entries(EDITABLE_LAYER_RULES).forEach(([layerId, layerRule]) => {
if (!GIS_EDIT_ALLOWED_LAYER_IDS.has(layerId)) return;
results.set(layerId, {
layerId,
layerName: layerRule.layerName,
geometryType: layerRule.geometryType,
editableYn: "Y",
allowedTools: layerRule.allowedTools,
previewColors: layerRule.previewColors,
});
});
}
return Array.from(results.values());
};
@@ -0,0 +1,170 @@
/** 원본 GIS feature와 viewport를 저장 가능한 snapshot으로 변환한다. */
import GeoJSON from "ol/format/GeoJSON.js";
import type { GisEditFeatureRef } from "../model/types";
import { normalizeLayerIdCandidate, FLOW_DIRECTION_SRS } from "./edit-model";
// 지도에서 선택한 OpenLayers Feature의 현재 geometry를 저장 payload 형태로 스냅샷한다.
export const toGeometryObject = (featureData: any) => {
if (!featureData || typeof featureData.getGeometry !== "function")
return null;
try {
return new GeoJSON().writeGeometryObject(featureData.getGeometry(), {
featureProjection: FLOW_DIRECTION_SRS,
dataProjection: FLOW_DIRECTION_SRS,
}) as Record<string, unknown>;
} catch (error) {
console.error("GIS 편집 geometry 변환 실패:", error);
return null;
}
};
// 저장 시점의 지도 범위를 함께 남겨 BE가 편집 세션 컨텍스트를 해석할 수 있게 한다.
export const buildBbox = (map: any) => {
try {
const size = map?.getSize?.();
const view = map?.getView?.();
if (!size || !view?.calculateExtent) return null;
return view
.calculateExtent(size)
.map((value: number) => value.toFixed(3))
.join(",");
} catch (error) {
console.error("GIS 편집 BBOX 계산 실패:", error);
return null;
}
};
export const getFeatureLayerId = (featureData: any) => {
if (typeof featureData?.get === "function") {
const previewLayerId = normalizeLayerIdCandidate(
featureData.get("layerId"),
);
if (previewLayerId) return previewLayerId;
}
if (typeof featureData?.getId === "function") {
return normalizeLayerIdCandidate(featureData.getId());
}
if (typeof featureData?.id_ === "string") {
return normalizeLayerIdCandidate(featureData.id_);
}
return normalizeLayerIdCandidate(
featureData?.lyrTypeNm ?? featureData?.lyrTyNm ?? "",
);
};
export const stripLayerPrefix = (value: unknown) => {
const raw = String(value ?? "").trim();
if (!raw) return "";
const withoutNamespace = raw.includes(":")
? (raw.split(":").pop() ?? raw)
: raw;
if (withoutNamespace.startsWith("tb_ms_swage_ppl.")) {
return withoutNamespace.slice("tb_ms_swage_ppl.".length);
}
return withoutNamespace;
};
export const getFeatureFid = (featureData: any) =>
stripLayerPrefix(
featureData?.get?.("fid") ??
featureData?.values_?.fid ??
featureData?.fid ??
featureData?.getId?.() ??
featureData?.id_ ??
"",
);
export const getFeatureObjectId = (featureData: any) =>
String(
getFeatureFid(featureData) ||
String(
featureData?.get?.("objectId") ??
featureData?.values_?.fclt_mng_no ??
featureData?.values_?.swtrmt_fclt_cd ??
featureData?.fcltMngNo ??
featureData?.fid ??
"",
),
).trim();
export const getFeatureObjectLabel = (featureData: any) => {
const values = featureData?.values_ ?? {};
return String(
featureData?.get?.("fclt_mng_no") ??
values?.fclt_mng_no ??
featureData?.fcltMngNo ??
featureData?.get?.("objectId") ??
values?.swtrmt_fclt_cd ??
getFeatureFid(featureData) ??
"",
).trim();
};
export const getFeatureRef = (
featureData: any,
): GisEditFeatureRef | undefined => {
const mapValues = featureData?.values_ ?? {};
const featureRef: GisEditFeatureRef = {
fcltMngNo:
String(
featureData?.get?.("fclt_mng_no") ??
mapValues?.fclt_mng_no ??
featureData?.fcltMngNo ??
"",
).trim() || undefined,
mngInstCd:
String(
featureData?.get?.("mng_inst_cd") ??
mapValues?.mng_inst_cd ??
featureData?.mngInstCd ??
"",
).trim() || undefined,
fid: getFeatureFid(featureData) || undefined,
};
if (!featureRef.fcltMngNo && !featureRef.mngInstCd && !featureRef.fid) {
return undefined;
}
return featureRef;
};
// 선택한 원본 관로의 속성 snapshot을 보관해 preview 재선택 시 상세정보가 비지 않게 한다.
export const getFeatureProperties = (
featureData: any,
): Record<string, unknown> | null => {
const values =
featureData?.values_ ?? featureData?.getProperties?.() ?? featureData;
if (!values || typeof values !== "object") return null;
const { geometry, ...properties } = values;
return properties;
};
export const normalizePipeGeometry = (
layerId: string,
geometry: Record<string, unknown> | null,
): Record<string, unknown> | null => {
if (layerId !== "tb_ms_swage_ppl" || !geometry) return geometry;
if (geometry.type !== "LineString") return geometry;
const coordinates = geometry.coordinates;
if (!Array.isArray(coordinates)) return geometry;
return {
...geometry,
type: "MultiLineString",
coordinates: [coordinates],
};
};
export const createChangeId = (prefix: string, sequence: number) => {
if (
typeof crypto !== "undefined" &&
typeof crypto.randomUUID === "function"
) {
return `${prefix}-${crypto.randomUUID()}`;
}
return `${prefix}-${Date.now()}-${sequence}`;
};
@@ -0,0 +1,517 @@
/** 편집 geometry의 이동·꼭지점 삭제·스냅 규칙을 담당한다. */
import {
type VertexHandleMeta,
type VertexHandleCandidate,
type VertexDeleteResult,
cloneCoordinates,
buildVertexCoordinateKey,
getSquaredPixelDistance,
} from "../model/vertex-handles";
import { collectVertexHandleCandidates } from "./vertex-handles";
export const updateLineCoordinates = (
coordinates: number[][],
meta: VertexHandleMeta,
nextCoordinate: number[],
) => {
const nextCoordinates = cloneCoordinates(coordinates);
if (meta.kind === "vertex") {
nextCoordinates[meta.coordIndex] = nextCoordinate;
} else {
nextCoordinates.splice(meta.coordIndex + 1, 0, nextCoordinate);
}
return nextCoordinates;
};
export const updatePolygonRingCoordinates = (
coordinates: number[][],
meta: VertexHandleMeta,
nextCoordinate: number[],
) => {
const nextCoordinates = cloneCoordinates(coordinates);
const logicalVertexCount = Math.max(0, nextCoordinates.length - 1);
if (logicalVertexCount === 0) return nextCoordinates;
if (meta.kind === "vertex") {
nextCoordinates[meta.coordIndex] = nextCoordinate;
if (meta.coordIndex === 0) {
nextCoordinates[logicalVertexCount] = nextCoordinate;
}
} else {
const insertIndex =
meta.coordIndex === logicalVertexCount - 1
? logicalVertexCount
: meta.coordIndex + 1;
nextCoordinates.splice(insertIndex, 0, nextCoordinate);
}
return nextCoordinates;
};
export const applyVertexHandleMove = (
geometry: any,
meta: VertexHandleMeta,
nextCoordinate: number[],
) => {
const geometryType = geometry?.getType?.();
if (!geometryType) return;
if (geometryType === "LineString") {
geometry.setCoordinates(
updateLineCoordinates(
geometry.getCoordinates?.() ?? [],
meta,
nextCoordinate,
),
);
return;
}
if (geometryType === "MultiLineString") {
const parts = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const targetPartIndex = meta.partIndex ?? 0;
parts[targetPartIndex] = updateLineCoordinates(
parts[targetPartIndex] ?? [],
meta,
nextCoordinate,
);
geometry.setCoordinates(parts);
return;
}
if (geometryType === "Polygon") {
const rings = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const targetRingIndex = meta.ringIndex ?? 0;
rings[targetRingIndex] = updatePolygonRingCoordinates(
rings[targetRingIndex] ?? [],
meta,
nextCoordinate,
);
geometry.setCoordinates(rings);
return;
}
if (geometryType === "MultiPolygon") {
const polygons = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const targetPolygonIndex = meta.polygonIndex ?? 0;
const targetRingIndex = meta.ringIndex ?? 0;
polygons[targetPolygonIndex][targetRingIndex] =
updatePolygonRingCoordinates(
polygons[targetPolygonIndex][targetRingIndex] ?? [],
meta,
nextCoordinate,
);
geometry.setCoordinates(polygons);
}
};
export const deleteLineVertices = (
coordinates: number[][],
coordIndexes: number[],
) => {
const nextCoordinates = cloneCoordinates(coordinates);
const uniqueIndexes = Array.from(new Set(coordIndexes)).sort(
(left, right) => right - left,
);
if (nextCoordinates.length - uniqueIndexes.length < 2) {
return null;
}
uniqueIndexes.forEach((coordIndex) => {
nextCoordinates.splice(coordIndex, 1);
});
return nextCoordinates;
};
export const deletePolygonVertices = (
coordinates: number[][],
coordIndexes: number[],
) => {
const logicalVertexCount = Math.max(0, coordinates.length - 1);
const uniqueIndexes = Array.from(new Set(coordIndexes)).sort(
(left, right) => right - left,
);
if (logicalVertexCount - uniqueIndexes.length < 3) {
return null;
}
const logicalCoordinates = cloneCoordinates(
coordinates.slice(0, logicalVertexCount),
);
uniqueIndexes.forEach((coordIndex) => {
logicalCoordinates.splice(coordIndex, 1);
});
if (logicalCoordinates.length < 3) return null;
return [...logicalCoordinates, cloneCoordinates(logicalCoordinates[0] ?? [])];
};
export const deleteSelectedVertexHandles = (
geometry: any,
metaList: VertexHandleMeta[],
): VertexDeleteResult => {
if (!geometry || metaList.length === 0) {
return { ok: false, message: "삭제할 꼭지점 정보를 찾지 못했습니다." };
}
if (metaList.some((meta) => meta.kind !== "vertex")) {
return {
ok: false,
message:
"흰색 midpoint는 삭제 대상이 아닙니다. 주황색 실꼭지점을 선택하세요.",
};
}
const geometryType = geometry?.getType?.();
if (!geometryType) {
return {
ok: false,
message: "꼭지점 삭제 대상 geometry를 찾지 못했습니다.",
};
}
if (geometryType === "LineString") {
const nextCoordinates = deleteLineVertices(
geometry.getCoordinates?.() ?? [],
metaList.map((meta) => meta.coordIndex),
);
if (!nextCoordinates) {
return {
ok: false,
message:
"하수관로는 최소 2개의 꼭지점이 필요해 더 이상 삭제할 수 없습니다.",
};
}
geometry.setCoordinates(nextCoordinates);
return { ok: true };
}
if (geometryType === "MultiLineString") {
const nextParts = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const metaGroups = metaList.reduce<Record<number, number[]>>(
(acc, meta) => {
const partIndex = meta.partIndex ?? 0;
if (!acc[partIndex]) acc[partIndex] = [];
acc[partIndex]!.push(meta.coordIndex);
return acc;
},
{},
);
for (const [partIndexRaw, coordIndexes] of Object.entries(metaGroups)) {
const partIndex = Number(partIndexRaw);
const nextCoordinates = deleteLineVertices(
nextParts[partIndex] ?? [],
coordIndexes,
);
if (!nextCoordinates) {
return {
ok: false,
message: "하수관로는 각 선형마다 최소 2개의 꼭지점이 필요합니다.",
};
}
nextParts[partIndex] = nextCoordinates;
}
geometry.setCoordinates(nextParts);
return { ok: true };
}
if (geometryType === "Polygon") {
const nextRings = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const metaGroups = metaList.reduce<Record<number, number[]>>(
(acc, meta) => {
const ringIndex = meta.ringIndex ?? 0;
if (!acc[ringIndex]) acc[ringIndex] = [];
acc[ringIndex]!.push(meta.coordIndex);
return acc;
},
{},
);
for (const [ringIndexRaw, coordIndexes] of Object.entries(metaGroups)) {
const ringIndex = Number(ringIndexRaw);
const nextCoordinates = deletePolygonVertices(
nextRings[ringIndex] ?? [],
coordIndexes,
);
if (!nextCoordinates) {
return {
ok: false,
message:
"폴리곤은 최소 3개의 꼭지점이 필요해 더 이상 삭제할 수 없습니다.",
};
}
nextRings[ringIndex] = nextCoordinates;
}
geometry.setCoordinates(nextRings);
return { ok: true };
}
if (geometryType === "MultiPolygon") {
const nextPolygons = cloneCoordinates(geometry.getCoordinates?.() ?? []);
const metaGroups = metaList.reduce<Record<string, number[]>>(
(acc, meta) => {
const polygonIndex = meta.polygonIndex ?? 0;
const ringIndex = meta.ringIndex ?? 0;
const groupKey = `${polygonIndex}:${ringIndex}`;
if (!acc[groupKey]) acc[groupKey] = [];
acc[groupKey]!.push(meta.coordIndex);
return acc;
},
{},
);
for (const [groupKey, coordIndexes] of Object.entries(metaGroups)) {
const [polygonIndexText, ringIndexText] = groupKey.split(":");
const polygonIndex = Number(polygonIndexText);
const ringIndex = Number(ringIndexText);
const nextCoordinates = deletePolygonVertices(
nextPolygons[polygonIndex]?.[ringIndex] ?? [],
coordIndexes,
);
if (!nextCoordinates) {
return {
ok: false,
message:
"폴리곤은 최소 3개의 꼭지점이 필요해 더 이상 삭제할 수 없습니다.",
};
}
nextPolygons[polygonIndex][ringIndex] = nextCoordinates;
}
geometry.setCoordinates(nextPolygons);
return { ok: true };
}
return {
ok: false,
message: "현재 geometry 유형은 꼭지점 삭제를 지원하지 않습니다.",
};
};
export const getClosestSnapCoordinateFromSource = (
source: VectorSource | null,
map: any,
coordinate: number[],
tolerancePx = 18,
) => {
if (!source || !Array.isArray(coordinate)) return null;
const nearestFeature = source.getClosestFeatureToCoordinate?.(coordinate);
const nearestGeometry = nearestFeature?.getGeometry?.();
if (!nearestGeometry?.getClosestPoint) return null;
const closestCoordinate = nearestGeometry.getClosestPoint(coordinate);
if (!Array.isArray(closestCoordinate)) return null;
const distance = Math.sqrt(
getSquaredPixelDistance(map, coordinate, closestCoordinate),
);
if (!Number.isFinite(distance) || distance > tolerancePx) return null;
return {
coordinate: closestCoordinate as number[],
distance,
};
};
export const applyGeometryVertexSnaps = (
geometry: any,
source: VectorSource | null,
map: any,
tolerancePx = 18,
) => {
if (!geometry || !source || !map) return false;
const vertexCandidates = collectVertexHandleCandidates(geometry).filter(
(candidate: VertexHandleCandidate) => candidate.meta.kind === "vertex",
);
let changed = false;
vertexCandidates.forEach((candidate: VertexHandleCandidate) => {
const snapResult = getClosestSnapCoordinateFromSource(
source,
map,
candidate.coordinate,
tolerancePx,
);
if (!snapResult) return;
const currentKey = buildVertexCoordinateKey(candidate.coordinate);
const nextKey = buildVertexCoordinateKey(snapResult.coordinate);
if (currentKey === nextKey) return;
applyVertexHandleMove(geometry, candidate.meta, snapResult.coordinate);
changed = true;
});
return changed;
};
export const applyGeometryMoveSnap = (
geometry: any,
source: VectorSource | null,
map: any,
anchorCoordinate?: number[] | null,
tolerancePx = 18,
) => {
if (!geometry || !source || !map || typeof geometry.translate !== "function")
return false;
if (Array.isArray(anchorCoordinate)) {
const snapResult = getClosestSnapCoordinateFromSource(
source,
map,
anchorCoordinate,
tolerancePx,
);
if (snapResult) {
const deltaX =
Number(snapResult.coordinate[0] ?? 0) -
Number(anchorCoordinate[0] ?? 0);
const deltaY =
Number(snapResult.coordinate[1] ?? 0) -
Number(anchorCoordinate[1] ?? 0);
if (deltaX !== 0 || deltaY !== 0) {
geometry.translate(deltaX, deltaY);
return true;
}
}
}
const vertexCandidates = collectVertexHandleCandidates(geometry).filter(
(candidate: VertexHandleCandidate) => candidate.meta.kind === "vertex",
);
type GeometryMoveSnapCandidate = {
original: number[];
snapped: number[];
distance: number;
};
let bestCandidate: GeometryMoveSnapCandidate | null = null;
vertexCandidates.forEach((candidate: VertexHandleCandidate) => {
const snapResult = getClosestSnapCoordinateFromSource(
source,
map,
candidate.coordinate,
tolerancePx,
);
if (!snapResult) return;
if (!bestCandidate || snapResult.distance < bestCandidate.distance) {
bestCandidate = {
original: candidate.coordinate,
snapped: snapResult.coordinate,
distance: snapResult.distance,
};
}
});
if (!bestCandidate) return false;
const resolvedBestCandidate = bestCandidate as GeometryMoveSnapCandidate;
const deltaX =
Number(resolvedBestCandidate.snapped[0] ?? 0) -
Number(resolvedBestCandidate.original[0] ?? 0);
const deltaY =
Number(resolvedBestCandidate.snapped[1] ?? 0) -
Number(resolvedBestCandidate.original[1] ?? 0);
if (deltaX === 0 && deltaY === 0) return false;
geometry.translate(deltaX, deltaY);
return true;
};
export const getClosestGeometryVertexCoordinate = (
geometry: any,
map: any,
coordinate: number[] | null,
) => {
if (!geometry || !map || !Array.isArray(coordinate)) return null;
const vertexCandidates = collectVertexHandleCandidates(geometry).filter(
(candidate: VertexHandleCandidate) => candidate.meta.kind === "vertex",
);
let bestCandidate: VertexHandleCandidate | null = null;
let minimumDistance = Number.POSITIVE_INFINITY;
vertexCandidates.forEach((candidate: VertexHandleCandidate) => {
const distance = getSquaredPixelDistance(
map,
coordinate,
candidate.coordinate,
);
if (distance < minimumDistance) {
minimumDistance = distance;
bestCandidate = candidate;
}
});
return (bestCandidate as VertexHandleCandidate | null)?.coordinate ?? null;
};
export const getClosestGeometryVertexMeta = (
geometry: any,
map: any,
coordinate: number[] | null,
) => {
if (!geometry || !map || !Array.isArray(coordinate)) return null;
const vertexCandidates = collectVertexHandleCandidates(geometry).filter(
(candidate: VertexHandleCandidate) => candidate.meta.kind === "vertex",
);
let bestCandidate: VertexHandleCandidate | null = null;
let minimumDistance = Number.POSITIVE_INFINITY;
vertexCandidates.forEach((candidate: VertexHandleCandidate) => {
const distance = getSquaredPixelDistance(
map,
coordinate,
candidate.coordinate,
);
if (distance < minimumDistance) {
minimumDistance = distance;
bestCandidate = candidate;
}
});
return (bestCandidate as VertexHandleCandidate | null)?.meta ?? null;
};
export const getGeometryVertexCoordinateByMeta = (
geometry: any,
meta: VertexHandleMeta | null,
) => {
if (!geometry || !meta) return null;
const geometryType = geometry?.getType?.();
if (!geometryType) return null;
if (geometryType === "LineString") {
return geometry.getCoordinates?.()?.[meta.coordIndex] ?? null;
}
if (geometryType === "MultiLineString") {
return (
geometry.getCoordinates?.()?.[meta.partIndex ?? 0]?.[meta.coordIndex] ??
null
);
}
if (geometryType === "Polygon") {
return (
geometry.getCoordinates?.()?.[meta.ringIndex ?? 0]?.[meta.coordIndex] ??
null
);
}
if (geometryType === "MultiPolygon") {
return (
geometry.getCoordinates?.()?.[meta.polygonIndex ?? 0]?.[
meta.ringIndex ?? 0
]?.[meta.coordIndex] ?? null
);
}
return null;
};
import type VectorSource from "ol/source/Vector.js";
@@ -0,0 +1,255 @@
/** GIS 편집 미리보기와 꼭지점 표시 스타일을 지도 상태에서 분리한다. */
import Fill from "ol/style/Fill.js";
import Point from "ol/geom/Point.js";
import CircleStyle from "ol/style/Circle.js";
import Stroke from "ol/style/Stroke.js";
import Style from "ol/style/Style.js";
import Text from "ol/style/Text.js";
import type { VertexHandleMeta } from "../model/vertex-handles";
export const getGeometryExtentCenterPoint = (geometry: any) => {
const extent = geometry?.getExtent?.();
if (!extent || extent.length < 4) return null;
const [minX = 0, minY = 0, maxX = 0, maxY = 0] = extent;
return new Point([(minX + maxX) / 2, (minY + maxY) / 2]);
};
// MultiPolygon/MultiLineString preview 라벨이 각 조각마다 반복되지 않도록 대표 지점 1곳에만 텍스트를 배치한다.
export const getGisEditPreviewLabelGeometry = (geometry: any) => {
const geometryType = geometry?.getType?.();
if (!geometryType) return null;
if (geometryType === "Point") {
return geometry;
}
if (geometryType === "Polygon") {
return (
geometry.getInteriorPoint?.() ?? getGeometryExtentCenterPoint(geometry)
);
}
if (geometryType === "MultiPolygon") {
const polygons = geometry.getPolygons?.() ?? [];
if (polygons.length > 0) {
const representativePolygon = polygons.reduce(
(largest: any, current: any) =>
(current?.getArea?.() ?? 0) > (largest?.getArea?.() ?? 0)
? current
: largest,
polygons[0],
);
return (
representativePolygon?.getInteriorPoint?.() ??
getGeometryExtentCenterPoint(representativePolygon)
);
}
return getGeometryExtentCenterPoint(geometry);
}
return getGeometryExtentCenterPoint(geometry);
};
export const createGisEditPreviewStyle = (feature: any) => {
const editType = String(feature.get("editType") ?? "");
const geometry = feature.getGeometry?.();
const geometryType = geometry?.getType?.();
const previewLabel = String(feature.get("previewLabel") ?? "").trim();
const isInteractionTarget = Boolean(feature.get("isInteractionTarget"));
const isDragging = Boolean(feature.get("isDragging"));
const layerPointColor = String(feature.get("layerPointColor") ?? "").trim();
const layerLineColor = String(feature.get("layerLineColor") ?? "").trim();
const layerFillColor = String(feature.get("layerFillColor") ?? "").trim();
const pointColor =
editType === "DELETE"
? "rgba(220, 38, 38, 0.85)"
: editType === "VERTEX_EDIT"
? "rgba(245, 158, 11, 0.92)"
: editType === "MOVE"
? layerPointColor || "rgba(37, 99, 235, 0.92)"
: editType === "ADD"
? "rgba(15, 23, 42, 0.96)"
: layerPointColor || "rgba(22, 163, 74, 0.92)";
const lineColor =
editType === "DELETE"
? "rgba(220, 38, 38, 0.9)"
: editType === "VERTEX_EDIT"
? "rgba(245, 158, 11, 0.95)"
: editType === "MOVE"
? layerLineColor || "rgba(37, 99, 235, 0.95)"
: editType === "ADD"
? "rgba(15, 23, 42, 0.96)"
: layerLineColor || "rgba(22, 163, 74, 0.95)";
const fillColor =
editType === "DELETE"
? "rgba(220, 38, 38, 0.18)"
: editType === "VERTEX_EDIT"
? "rgba(245, 158, 11, 0.2)"
: editType === "MOVE"
? layerFillColor || "rgba(37, 99, 235, 0.18)"
: editType === "ADD"
? "rgba(15, 23, 42, 0.2)"
: layerFillColor || "rgba(22, 163, 74, 0.18)";
const highlightColor = isDragging
? "rgba(14, 116, 144, 0.98)"
: isInteractionTarget
? "rgba(15, 23, 42, 0.9)"
: lineColor;
const emphasisWidth = isDragging
? 7
: isInteractionTarget
? 6
: editType === "ADD"
? 6
: 4;
const textStyle = previewLabel
? new Text({
text: previewLabel,
font: "600 12px sans-serif",
fill: new Fill({ color: "#ffffff" }),
backgroundFill: new Fill({ color: highlightColor }),
padding: [3, 6, 3, 6],
offsetY: geometryType === "Point" ? -18 : -12,
overflow: true,
})
: undefined;
const labelGeometry = previewLabel
? getGisEditPreviewLabelGeometry(geometry)
: null;
if (geometryType === "Point") {
return new Style({
image: new CircleStyle({
radius: isInteractionTarget ? 10 : 8,
fill: new Fill({ color: pointColor }),
stroke: new Stroke({
color: isDragging ? "rgba(255,255,255,1)" : "rgba(255,255,255,0.95)",
width: isInteractionTarget ? 3 : 2,
}),
}),
text: textStyle,
zIndex: 10001,
});
}
if (geometryType === "Polygon") {
const polygonStyles: Style[] = [
new Style({
fill: new Fill({
color:
isInteractionTarget && editType !== "DELETE"
? fillColor.replace(/0\.\d+\)$/, "0.28)")
: fillColor,
}),
stroke: new Stroke({
color: highlightColor,
width: emphasisWidth,
lineDash: editType === "DELETE" ? [8, 6] : undefined,
}),
zIndex: 10001,
}),
];
if (textStyle && labelGeometry) {
polygonStyles.push(
new Style({
geometry: labelGeometry,
text: textStyle,
zIndex: 10002,
}),
);
}
return polygonStyles;
}
const lineStyles: Style[] =
editType === "ADD"
? [
new Style({
stroke: new Stroke({
color: "rgba(255, 255, 255, 0.98)",
width: emphasisWidth + 4,
}),
zIndex: 10000,
}),
new Style({
stroke: new Stroke({
color: highlightColor,
width: emphasisWidth,
}),
zIndex: 10003,
}),
]
: [
new Style({
stroke: new Stroke({
color: highlightColor,
width: emphasisWidth,
lineDash: editType === "DELETE" ? [10, 6] : undefined,
}),
zIndex: 10001,
}),
];
if (textStyle && labelGeometry) {
lineStyles.push(
new Style({
geometry: labelGeometry,
text: textStyle,
zIndex: 10002,
}),
);
}
return lineStyles;
};
export const GIS_EDIT_VERTEX_HANDLE_STYLE = new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({ color: "rgba(245, 158, 11, 0.98)" }),
stroke: new Stroke({ color: "rgba(255,255,255,0.98)", width: 3 }),
}),
zIndex: 10005,
});
export const GIS_EDIT_VERTEX_MIDPOINT_STYLE = new Style({
image: new CircleStyle({
radius: 6,
fill: new Fill({ color: "rgba(255, 255, 255, 0.98)" }),
stroke: new Stroke({ color: "rgba(245, 158, 11, 0.98)", width: 2.5 }),
}),
zIndex: 10004,
});
export const GIS_EDIT_VERTEX_DRAGGING_STYLE = new Style({
image: new CircleStyle({
radius: 11,
fill: new Fill({ color: "rgba(59, 130, 246, 0.95)" }),
stroke: new Stroke({ color: "rgba(255,255,255,0.98)", width: 3 }),
}),
zIndex: 10006,
});
export const GIS_EDIT_VERTEX_SELECTED_STYLE = new Style({
image: new CircleStyle({
radius: 11,
fill: new Fill({ color: "rgba(217, 119, 6, 0.98)" }),
stroke: new Stroke({ color: "rgba(15, 23, 42, 0.95)", width: 3 }),
}),
zIndex: 10007,
});
export const getGisEditVertexHandleStyle = (
kind: VertexHandleMeta["kind"],
isSelected = false,
) => {
if (isSelected && kind === "vertex") {
return GIS_EDIT_VERTEX_SELECTED_STYLE;
}
return kind === "midpoint"
? GIS_EDIT_VERTEX_MIDPOINT_STYLE
: GIS_EDIT_VERTEX_HANDLE_STYLE;
};
@@ -0,0 +1,386 @@
/** 꼭지점·중간점 후보와 OpenLayers 핸들 feature 생성을 담당한다. */
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import { getGisEditVertexHandleStyle } from "./preview-styles";
import {
type VertexHandleMeta,
type VertexHandleCandidate,
getMidpoint,
buildVertexCoordinateKey,
buildVertexHandleSelectionKey,
getSquaredPixelDistance,
GIS_EDIT_VERTEX_CLUSTER_PIXEL_THRESHOLD,
getAverageCoordinate,
getPixelDistanceToSegment,
} from "../model/vertex-handles";
export const createVertexHandleFeature = (
coordinate: number[],
meta: VertexHandleMeta,
metaList: VertexHandleMeta[] = [meta],
) => {
const handleFeature = new Feature({
geometry: new Point(coordinate),
});
handleFeature.set("handleKind", meta.kind);
handleFeature.set("handleMeta", meta);
handleFeature.set("handleMetaList", metaList);
handleFeature.set(
"handleSelectionKey",
buildVertexHandleSelectionKey(metaList),
);
handleFeature.setStyle(getGisEditVertexHandleStyle(meta.kind));
return handleFeature;
};
export const collectLineVertexHandleCandidates = (
coordinates: number[][],
geometryType: string,
partIndex?: number,
) => {
const candidates: VertexHandleCandidate[] = [];
coordinates.forEach((coordinate, coordIndex) => {
candidates.push({
coordinate,
meta: {
kind: "vertex",
geometryType,
partIndex,
coordIndex,
},
});
});
return candidates;
};
export const collectPolygonRingVertexHandleCandidates = (
coordinates: number[][],
geometryType: string,
polygonIndex?: number,
ringIndex?: number,
) => {
const candidates: VertexHandleCandidate[] = [];
const logicalVertexCount = Math.max(0, coordinates.length - 1);
for (let coordIndex = 0; coordIndex < logicalVertexCount; coordIndex += 1) {
const coordinate = coordinates[coordIndex];
const nextCoordinate =
coordinates[(coordIndex + 1) % logicalVertexCount] ?? coordinate;
if (!coordinate || !nextCoordinate) continue;
candidates.push({
coordinate,
meta: {
kind: "vertex",
geometryType,
polygonIndex,
ringIndex,
coordIndex,
},
});
}
return candidates;
};
export const collectVertexHandleCandidates = (geometry: any) => {
const geometryType = geometry?.getType?.();
if (!geometryType) return [];
if (geometryType === "LineString") {
return collectLineVertexHandleCandidates(
geometry.getCoordinates?.() ?? [],
geometryType,
);
}
if (geometryType === "MultiLineString") {
const parts = geometry.getCoordinates?.() ?? [];
return parts.flatMap((part: number[][], partIndex: number) =>
collectLineVertexHandleCandidates(part, geometryType, partIndex),
);
}
if (geometryType === "Polygon") {
const rings = geometry.getCoordinates?.() ?? [];
return rings.flatMap((ring: number[][], ringIndex: number) =>
collectPolygonRingVertexHandleCandidates(
ring,
geometryType,
undefined,
ringIndex,
),
);
}
if (geometryType === "MultiPolygon") {
const polygons = geometry.getCoordinates?.() ?? [];
return polygons.flatMap((polygon: number[][][], polygonIndex: number) =>
polygon.flatMap((ring: number[][], ringIndex: number) =>
collectPolygonRingVertexHandleCandidates(
ring,
geometryType,
polygonIndex,
ringIndex,
),
),
);
}
return [];
};
export const buildVertexHandleFeatures = (
geometry: any,
map?: any,
): Feature[] => {
const groupedCandidates: Array<{
coordinate: number[];
metaList: VertexHandleMeta[];
sourceCoordinates: number[][];
}> = [];
collectVertexHandleCandidates(geometry).forEach(
(candidate: VertexHandleCandidate) => {
const existing = groupedCandidates.find((group) => {
if (!map) {
return (
buildVertexCoordinateKey(group.coordinate) ===
buildVertexCoordinateKey(candidate.coordinate)
);
}
return (
getSquaredPixelDistance(
map,
group.coordinate,
candidate.coordinate,
) <=
GIS_EDIT_VERTEX_CLUSTER_PIXEL_THRESHOLD ** 2
);
});
if (existing) {
existing.metaList.push(candidate.meta);
existing.sourceCoordinates.push(candidate.coordinate);
existing.coordinate = getAverageCoordinate(existing.sourceCoordinates);
return;
}
groupedCandidates.push({
coordinate: candidate.coordinate,
metaList: [candidate.meta],
sourceCoordinates: [candidate.coordinate],
});
},
);
return groupedCandidates.map(({ coordinate, metaList }) =>
createVertexHandleFeature(coordinate, metaList[0]!, metaList),
);
};
export const collectLineMidpointCandidates = (
coordinates: number[][],
geometryType: string,
partIndex?: number,
) => {
const candidates: VertexHandleCandidate[] = [];
for (
let coordIndex = 0;
coordIndex < coordinates.length - 1;
coordIndex += 1
) {
const startCoordinate = coordinates[coordIndex];
const endCoordinate = coordinates[coordIndex + 1];
if (!startCoordinate || !endCoordinate) continue;
candidates.push({
coordinate: getMidpoint(startCoordinate, endCoordinate),
meta: {
kind: "midpoint",
geometryType,
partIndex,
coordIndex,
},
});
}
return candidates;
};
export const collectPolygonRingMidpointCandidates = (
coordinates: number[][],
geometryType: string,
polygonIndex?: number,
ringIndex?: number,
) => {
const candidates: VertexHandleCandidate[] = [];
const logicalVertexCount = Math.max(0, coordinates.length - 1);
for (let coordIndex = 0; coordIndex < logicalVertexCount; coordIndex += 1) {
const startCoordinate = coordinates[coordIndex];
const endCoordinate = coordinates[(coordIndex + 1) % logicalVertexCount];
if (!startCoordinate || !endCoordinate) continue;
candidates.push({
coordinate: getMidpoint(startCoordinate, endCoordinate),
meta: {
kind: "midpoint",
geometryType,
polygonIndex,
ringIndex,
coordIndex,
},
});
}
return candidates;
};
export const collectMidpointCandidates = (geometry: any) => {
const geometryType = geometry?.getType?.();
if (!geometryType) return [];
if (geometryType === "LineString") {
return collectLineMidpointCandidates(
geometry.getCoordinates?.() ?? [],
geometryType,
);
}
if (geometryType === "MultiLineString") {
const parts = geometry.getCoordinates?.() ?? [];
return parts.flatMap((part: number[][], partIndex: number) =>
collectLineMidpointCandidates(part, geometryType, partIndex),
);
}
if (geometryType === "Polygon") {
const rings = geometry.getCoordinates?.() ?? [];
return rings.flatMap((ring: number[][], ringIndex: number) =>
collectPolygonRingMidpointCandidates(
ring,
geometryType,
undefined,
ringIndex,
),
);
}
if (geometryType === "MultiPolygon") {
const polygons = geometry.getCoordinates?.() ?? [];
return polygons.flatMap((polygon: number[][][], polygonIndex: number) =>
polygon.flatMap((ring: number[][], ringIndex: number) =>
collectPolygonRingMidpointCandidates(
ring,
geometryType,
polygonIndex,
ringIndex,
),
),
);
}
return [];
};
export const getNearestVertexPixelDistance = (
map: any,
geometry: any,
coordinate: number[],
): number => {
return buildVertexHandleFeatures(geometry, map).reduce(
(minimumDistance: number, feature: Feature) => {
const vertexCoordinate = (
feature.getGeometry?.() as any
)?.getCoordinates?.();
if (!Array.isArray(vertexCoordinate)) return minimumDistance;
return Math.min(
minimumDistance,
Math.sqrt(getSquaredPixelDistance(map, coordinate, vertexCoordinate)),
);
},
Number.POSITIVE_INFINITY,
);
};
export const getSegmentCoordinatesFromMeta = (
geometry: any,
meta: VertexHandleMeta,
): [number[], number[]] | null => {
const geometryType = geometry?.getType?.();
if (!geometryType) return null;
if (geometryType === "LineString") {
const coordinates = geometry.getCoordinates?.() ?? [];
return [coordinates[meta.coordIndex], coordinates[meta.coordIndex + 1]];
}
if (geometryType === "MultiLineString") {
const parts = geometry.getCoordinates?.() ?? [];
const targetPart = parts[meta.partIndex ?? 0] ?? [];
return [targetPart[meta.coordIndex], targetPart[meta.coordIndex + 1]];
}
if (geometryType === "Polygon") {
const rings = geometry.getCoordinates?.() ?? [];
const targetRing = rings[meta.ringIndex ?? 0] ?? [];
const logicalVertexCount = Math.max(0, targetRing.length - 1);
if (logicalVertexCount === 0) return null;
return [
targetRing[meta.coordIndex],
targetRing[(meta.coordIndex + 1) % logicalVertexCount],
];
}
if (geometryType === "MultiPolygon") {
const polygons = geometry.getCoordinates?.() ?? [];
const targetPolygon = polygons[meta.polygonIndex ?? 0] ?? [];
const targetRing = targetPolygon[meta.ringIndex ?? 0] ?? [];
const logicalVertexCount = Math.max(0, targetRing.length - 1);
if (logicalVertexCount === 0) return null;
return [
targetRing[meta.coordIndex],
targetRing[(meta.coordIndex + 1) % logicalVertexCount],
];
}
return null;
};
export const findHoveredMidpointCandidate = (
map: any,
geometry: any,
coordinate: number[],
tolerancePx = 18,
): VertexHandleCandidate | null => {
const nearestVertexDistance = getNearestVertexPixelDistance(
map,
geometry,
coordinate,
);
if (nearestVertexDistance <= 14) {
return null;
}
const midpointCandidates = collectMidpointCandidates(geometry);
let bestCandidate: VertexHandleCandidate | null = null;
let minimumDistance = Number.POSITIVE_INFINITY;
midpointCandidates.forEach((candidate: VertexHandleCandidate) => {
const segmentCoordinates = getSegmentCoordinatesFromMeta(
geometry,
candidate.meta,
);
if (!segmentCoordinates) return;
const [startCoordinate, endCoordinate] = segmentCoordinates;
if (!Array.isArray(startCoordinate) || !Array.isArray(endCoordinate))
return;
const segmentDistance = getPixelDistanceToSegment(
map,
coordinate,
startCoordinate,
endCoordinate,
);
if (segmentDistance < minimumDistance) {
minimumDistance = segmentDistance;
bestCandidate = candidate;
}
});
return minimumDistance <= tolerancePx ? bestCandidate : null;
};
+112
View File
@@ -0,0 +1,112 @@
/** 하수관로 GIS 편집에서 사용하는 도구·세션·변경 데이터 타입을 정의한다. */
export type GisEditTool = "ADD" | "MOVE" | "VERTEX_EDIT" | "DELETE";
export type GisEditGeometryType = "Point" | "LineString" | "Polygon";
export type GisEditPreviewColors = {
pointColor: string;
lineColor: string;
fillColor: string;
};
export type GisEditFeatureRef = {
fcltMngNo?: string;
mngInstCd?: string;
fid?: string;
};
export type GisEditPipeBasicInfo = {
[key: string]: string | null | undefined;
fcltMngNo?: string | null;
mngInstCd?: string | null;
instMngNo?: string | null;
instlYmd?: string | null;
mapshtNo?: string | null;
pdmtVl?: string | null;
prlgVl?: string | null;
usgCd?: string | null;
mqltCd?: string | null;
avgGrdn?: string | null;
drtwMltvArea?: string | null;
exclnMltvArea?: string | null;
tmptDpth?: string | null;
tmptMhlMngNo?: string | null;
scendDpth?: string | null;
scendMhlMngNo?: string | null;
trflnCnt?: string | null;
vrtcLen?: string | null;
wdthLen?: string | null;
instlMbdyCd?: string | null;
swtrmtZoneNm?: string | null;
mltvZoneNm?: string | null;
mltvDtdvNm?: string | null;
lineCd?: string | null;
floCd?: string | null;
layCd?: string | null;
};
export type GisEditLayerInfo = {
layerId: string;
layerName: string;
geometryType: GisEditGeometryType;
editableYn: "Y" | "N";
allowedTools: GisEditTool[];
previewColors: GisEditPreviewColors;
disabledReason?: string;
};
export type GisEditChange = {
changeId: string;
editType: GisEditTool;
layerId: string;
layerName: string;
objectId?: string;
fid?: string;
baseEditSn?: string;
featureRef?: GisEditFeatureRef;
objectLabel: string;
beforeGeometry?: Record<string, unknown> | null;
afterGeometry?: Record<string, unknown> | null;
featureProperties?: Record<string, unknown> | null;
basicInfo?: GisEditPipeBasicInfo | null;
basicInfoSavedAt?: string | null;
attributeOnly?: boolean;
summary: string;
createdAt: string;
source: "MAP_SELECTION" | "MAP_CENTER" | "MAP_DRAW";
};
export type GisEditSavePayload = {
screenId: string;
layerId: string;
layerName: string;
saveTargetType: "VERSION" | "FINAL";
view: {
srs: string;
bbox: string | null;
};
changes: Array<{
changeId: string;
editType: GisEditTool;
objectId?: string;
clientTempId?: string;
fid?: string;
baseEditSn?: string;
featureRef?: GisEditFeatureRef;
attributes?: GisEditPipeBasicInfo | null;
beforeGeometry?: Record<string, unknown> | null;
afterGeometry?: Record<string, unknown> | null;
geometry?: Record<string, unknown> | null;
}>;
};
export type GisEditSessionSnapshot = {
isEditMode: boolean;
selectedLayerName: string;
activeTool: GisEditTool | null;
isSnapEnabled: boolean;
changes: GisEditChange[];
lastSavedPayload: GisEditSavePayload | null;
canUndo: boolean;
focusedChangeId: string | null;
};
@@ -0,0 +1,101 @@
/** 꼭지점 메타와 좌표·픽셀 연산의 공통 모델이다. */
export type VertexHandleMeta = {
kind: "vertex" | "midpoint";
geometryType: string;
partIndex?: number;
polygonIndex?: number;
ringIndex?: number;
coordIndex: number;
};
export type VertexHandleCandidate = {
coordinate: number[];
meta: VertexHandleMeta;
};
export type VertexDeleteResult = {
ok: boolean;
message?: string;
};
export const cloneCoordinates = <T>(value: T): T =>
JSON.parse(JSON.stringify(value)) as T;
export const getMidpoint = (start: number[], end: number[]) => [
(Number(start?.[0] ?? 0) + Number(end?.[0] ?? 0)) / 2,
(Number(start?.[1] ?? 0) + Number(end?.[1] ?? 0)) / 2,
];
export const buildVertexCoordinateKey = (coordinate: number[]) =>
`${Number(coordinate?.[0] ?? 0)}:${Number(coordinate?.[1] ?? 0)}`;
export const buildVertexHandleMetaKey = (meta: VertexHandleMeta) =>
[
meta.kind,
meta.geometryType,
meta.partIndex ?? -1,
meta.polygonIndex ?? -1,
meta.ringIndex ?? -1,
meta.coordIndex,
].join(":");
export const buildVertexHandleSelectionKey = (metaList: VertexHandleMeta[]) =>
metaList.map(buildVertexHandleMetaKey).sort().join("|");
export const getSquaredPixelDistance = (
map: any,
startCoordinate: number[],
endCoordinate: number[],
) => {
const [startX = 0, startY = 0] =
map?.getPixelFromCoordinate?.(startCoordinate) ?? [];
const [endX = 0, endY = 0] =
map?.getPixelFromCoordinate?.(endCoordinate) ?? [];
return (endX - startX) ** 2 + (endY - startY) ** 2;
};
export const GIS_EDIT_VERTEX_CLUSTER_PIXEL_THRESHOLD = 12;
export const getAverageCoordinate = (coordinates: number[][]) => {
if (coordinates.length === 0) return [0, 0];
const [sumX, sumY] = coordinates.reduce<[number, number]>(
([accX, accY], [x = 0, y = 0]) => [accX + Number(x), accY + Number(y)],
[0, 0],
);
return [sumX / coordinates.length, sumY / coordinates.length];
};
export const getPixelDistanceToSegment = (
map: any,
coordinate: number[],
startCoordinate: number[],
endCoordinate: number[],
) => {
const [pointX = 0, pointY = 0] =
map?.getPixelFromCoordinate?.(coordinate) ?? [];
const [startX = 0, startY = 0] =
map?.getPixelFromCoordinate?.(startCoordinate) ?? [];
const [endX = 0, endY = 0] =
map?.getPixelFromCoordinate?.(endCoordinate) ?? [];
const deltaX = endX - startX;
const deltaY = endY - startY;
const segmentLengthSquared = deltaX ** 2 + deltaY ** 2;
if (segmentLengthSquared === 0) {
return Math.hypot(pointX - startX, pointY - startY);
}
const ratio = Math.max(
0,
Math.min(
1,
((pointX - startX) * deltaX + (pointY - startY) * deltaY) /
segmentLengthSquared,
),
);
const projectedX = startX + deltaX * ratio;
const projectedY = startY + deltaY * ratio;
return Math.hypot(pointX - projectedX, pointY - projectedY);
};
@@ -0,0 +1,94 @@
import type {
DownloadJob,
DownloadJobStatusListener,
} from "../model/upload-types";
type DownloadApi = {
getData: (url: string) => Promise<unknown>;
postRawJson: (url: string, data: object) => Promise<unknown>;
getBlobDataWithHeaders: (
url: string,
) => Promise<{ blob: Blob; fileName?: string; headers: Headers }>;
};
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;
/** 전송 함수를 주입받아 다운로드 접수·상태 polling·연결 재시도 책임을 소유한다. */
export const createGisDownloadClient = ({
getData,
postRawJson,
getBlobDataWithHeaders,
}: DownloadApi) => {
// 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, {})) as { data?: unknown } | null;
const job = (response?.data ?? response) as DownloadJob | null;
if (!job?.jobId) {
throw new Error("다운로드 작업 접수 정보를 확인하지 못했습니다.");
}
return job;
};
const waitForDownloadJob = async (
jobId: string,
onStatus?: DownloadJobStatusListener,
): 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;
onStatus?.(job);
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 파일 생성 대기 시간이 초과되었습니다. 다시 시도하세요.",
);
};
return { downloadGeoPackage, startDownloadJob, waitForDownloadJob };
};
// Keep the object URL alive until Chrome has accepted the synthetic download click.
export 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);
};
@@ -0,0 +1,7 @@
/** GIS 업로드 부분 성공 상태와 재시도 정책의 공개 경계다. */
export {
createGisUploadRetryGuard,
getGisPartialSuccessNotice,
readGisPartialSuccess,
} from "./model/upload-retry-guard";
export type { GisPartialSuccessBlock } from "./model/upload-retry-guard";
@@ -0,0 +1,24 @@
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
import type { GisUploadResponse } from "../model/upload-types";
/** 성공한 GIS 업로드의 기존 refresh 메시지를 opener에 전달한다. */
export 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 ?? ["tb_ms_swage_ppl"],
),
},
},
window.location.origin,
);
};
@@ -0,0 +1,74 @@
/** GIS 파일 검증·목록 필드·오류 안내의 표시 규칙이다. */
import type { ValidationErrorItem } from "../model/upload-types";
/** 백엔드 검증 코드를 사용자가 이해할 수 있는 한글 오류내용으로 변환한다. */
export const GIS_VALIDATION_ERROR_MESSAGES: Record<string, string> = {
GIS_UPLOAD_MNG_INST_MISMATCH:
"선택한 관리기관과 다른 관로가 포함되어 있습니다.",
GIS_UPLOAD_FID_DUPLICATED: "업로드 파일에 중복된 시설물 식별번호가 있습니다.",
GIS_UPLOAD_DELETE_LIMIT_EXCEEDED:
"삭제 대상 건수가 허용 범위를 초과했습니다.",
};
/** 형상 오류는 같은 오류코드 안에서도 누락과 형식 오류를 구분해 안내한다. */
export const getLocalizedValidationErrorMessage = (
error: ValidationErrorItem,
) => {
const errorCode = String(error.errorCode ?? "").trim();
const errorMessage = String(error.errorMessage ?? "").trim();
// 저장 API가 제공하는 한글 설명을 보존하고 과거 기술용어 응답만 아래에서 변환한다.
if (
/[가-힣]/.test(errorMessage) &&
!/geometry|feature|LineString|count\s*=/i.test(errorMessage)
) {
return errorMessage;
}
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
: "업로드 파일 검증 중 오류가 발생했습니다.";
};
export const getFileExtension = (fileName: string) => {
const lastDotIndex = fileName.lastIndexOf(".");
if (lastDotIndex < 0) return "";
return fileName.slice(lastDotIndex).toLowerCase();
};
export const formatDateTime = (value?: string | null) => {
if (!value) return "-";
return value.replace("T", " ").slice(0, 19);
};
export const toScopeKey = (mngInstCd: string) => mngInstCd || "__UNSELECTED__";
export const buildManagementLabel = (
mngInstCd?: string | null,
mngInstNm?: string | null,
) => {
if (!mngInstCd) return "-";
return mngInstNm || mngInstCd;
};
export 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
);
};
@@ -0,0 +1,58 @@
type ErrorRecord = Record<string, unknown>;
export type GisPartialSuccessBlock = { uploadId: string; downloadId: string };
/** Axios·SN transport의 기존 오류 경계에서 부분 성공 body만 확인한다. */
const errorRecord = (value: unknown): ErrorRecord | null =>
typeof value === "object" && value !== null ? (value as ErrorRecord) : null;
/** BE가 명시한 부분 성공 플래그를 모두 확인하며 일반 500과 구분한다. */
export const readGisPartialSuccess = (
error: unknown,
): { uploadId: string } | null => {
const root = errorRecord(error);
const response = errorRecord(root?.response);
const body = errorRecord(root?.body ?? response?.data);
const candidate = errorRecord(body?.data) ?? body;
if (
candidate?.code !== "GIS_UPLOAD_HISTORY_SAVE_FAILED" ||
candidate.msApplied !== true ||
candidate.retryAllowed !== false
)
return null;
return {
uploadId:
typeof candidate.uploadId === "string" ? candidate.uploadId.trim() : "",
};
};
/** 기존 안내 영역에서 반영 단계와 이력 실패를 구분하고 운영 확인용 ID를 표시한다. */
export const getGisPartialSuccessNotice = (block: GisPartialSuccessBlock) =>
`관로 변경 반영 단계는 완료되었으나 업로드 이력을 저장하지 못했습니다. 같은 파일을 다시 업로드하지 말고 관리자에게 반영 결과와 이력 복구를 확인하세요. 업로드 식별번호: ${block.uploadId || "확인 필요"}. 다음 작업은 최신 관로 자료를 새로 다운로드한 후 진행하세요.`;
/**
* 열린 GIS 관리 세션의 기관 scope별 부분 성공 재시도를 차단한다.
* 파일명·파일선택·기관 전환으로 해제하지 않는다. 현재본 다운로드 완료 뒤
* 이전과 다른 유효 downloadId가 확인된 경우에만 새 작업을 허용한다.
*/
export const createGisUploadRetryGuard = () => {
const blockedScopes = new Map<string, GisPartialSuccessBlock>();
return {
getBlock: (scope: string) => blockedScopes.get(scope) ?? null,
recordFailure: (scope: string, downloadId: string, error: unknown) => {
const partial = readGisPartialSuccess(error);
if (!partial) return null;
const block = { ...partial, downloadId };
blockedScopes.set(scope, block);
return block;
},
/** READY 현재본의 실제 파일 수신·브라우저 저장 요청까지 완료한 호출자만 사용한다. */
acceptFreshDownload: (scope: string, downloadId: string) => {
const block = blockedScopes.get(scope);
const nextId = downloadId.trim();
if (!block || !nextId || nextId === block.downloadId) return null;
blockedScopes.delete(scope);
return block;
},
};
};
@@ -0,0 +1,61 @@
/** GIS 관리 목록·검증·다운로드 작업의 서버 응답 계약이다. */
export type UploadFacilityType = {
facilityTypeCode: string;
facilityTypeName: string;
layerId: string;
allowedExtensions: string[];
maxFileSizeMb: number;
requiredDownloadFormat: string;
};
export type MngInstOption = {
mngInstCd: string;
lwrInstNm: string;
};
export 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;
};
export type GisUploadResponse = {
uploadId: string;
status: "COMPLETED" | "VALIDATION_FAILED" | string;
mapRefreshRequired?: boolean;
refreshLayerTypeNames?: string[];
validationErrors?: ValidationErrorItem[];
invalidCount?: number;
message?: string;
};
export type ValidationErrorItem = {
rowNo?: number | null;
fid?: string | null;
errorCode?: string | null;
errorMessage?: string | null;
};
export type ViewMode = "history" | "validationErrors" | "preview";
export 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;
};
export type DownloadJobStatusListener = (job: DownloadJob) => void;
+3
View File
@@ -0,0 +1,3 @@
/** 지도 레이어 메타·표출 조건과 독립 이벤트 구독의 공개 경계다. */
export * from "./lib/layer-info";
export { subscribeFlowDirectionMoveEnd } from "./lib/flow-direction-listener";
@@ -0,0 +1,17 @@
/**
* 유하방향 moveend 구독 수명을 소유한다. 매 이벤트마다 최신 체크·레이어 상태를 읽는다.
* OpenLayers 해제 함수는 주입받아 모델·계약 테스트에서 지도 엔진 없이 검증할 수 있다.
*/
export const subscribeFlowDirectionMoveEnd = <TLayer, TSubscription>(
map: { on: (event: "moveend", listener: () => void) => TSubscription },
readState: () => { checked: boolean; layerInfo: TLayer | null },
loadLayer: (layerInfo: TLayer) => unknown,
unsubscribe: (key: TSubscription) => void,
): (() => void) => {
const key = map.on("moveend", () => {
const state = readState();
if (!state.checked || !state.layerInfo) return;
loadLayer(state.layerInfo);
});
return () => unsubscribe(key);
};
@@ -0,0 +1,286 @@
/** 유하방향 선/화살표의 색상·대표 선분·중앙 배치를 표출 정책으로 분리한다. */
import Style from "ol/style/Style.js";
import Stroke from "ol/style/Stroke.js";
import Point from "ol/geom/Point.js";
export const FLOW_DIRECTION_DEFAULT_COLOR = "rgba(40, 90, 180, 0.84)";
export const FLOW_DIRECTION_NETWORK_CORRECTION_COLOR =
"rgba(0, 168, 132, 0.95)";
export type FlowDirectionUsageStyle = {
color: string;
lineColor: string;
};
// 관종별 원본 레이어 색을 유하방향 선/화살표에 재사용할 때 투명도만 조정한다.
export const withAlpha = (color: string | null | undefined, alpha: number) => {
const resolvedColor = String(color ?? "").trim();
if (!resolvedColor) return `rgba(40, 90, 180, ${alpha})`;
const rgbaMatch = resolvedColor.match(/^rgba?\(([^)]+)\)$/i);
if (rgbaMatch) {
const [red = "40", green = "90", blue = "180"] = (rgbaMatch[1] ?? "")
.split(",")
.map((part) => part.trim());
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
const hexMatch = resolvedColor.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
if (hexMatch) {
const hex = hexMatch[1] ?? "";
const normalized =
hex.length === 3
? hex
.split("")
.map((char) => char + char)
.join("")
: hex;
const red = parseInt(normalized.slice(0, 2), 16);
const green = parseInt(normalized.slice(2, 4), 16);
const blue = parseInt(normalized.slice(4, 6), 16);
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
return resolvedColor;
};
// 화살표 위치와 대표 선분 선택을 위해 LineString 좌표열의 대략적인 길이를 계산한다.
export const estimateLineLength = (coordinates: number[][]) => {
let length = 0;
for (let i = 1; i < coordinates.length; i += 1) {
const previous = coordinates[i - 1];
const current = coordinates[i];
if (!previous || !current) continue;
const [x1 = 0, y1 = 0] = previous;
const [x2 = 0, y2 = 0] = current;
length += Math.hypot(x2 - x1, y2 - y1);
}
return length;
};
// MultiLineString 관로는 가장 긴 선분을 대표 선으로 삼아 화살표 위치와 각도를 안정적으로 계산한다.
export const getRepresentativeLineCoordinates = (geometry: any): number[][] => {
const type = geometry?.getType?.();
const coordinates = geometry?.getCoordinates?.();
if (type === "LineString") return coordinates ?? [];
if (type === "MultiLineString" && Array.isArray(coordinates)) {
return coordinates.reduce(
(longest: number[][], current: number[][]) =>
estimateLineLength(current) > estimateLineLength(longest)
? current
: longest,
[],
);
}
return [];
};
// 관로 중앙 지점이 속한 실제 선분을 찾아 화살표 위치와 해당 선분의 방향각을 함께 계산한다.
export const getArrowPlacementAtHalfLength = (coordinates: number[][]) => {
if (coordinates.length === 0) return null;
if (coordinates.length === 1) {
const coordinate = coordinates[0];
return coordinate ? { coordinate, angle: 0 } : null;
}
const totalLength = estimateLineLength(coordinates);
if (totalLength === 0) {
const coordinate = coordinates[Math.floor(coordinates.length / 2)];
return coordinate ? { coordinate, angle: 0 } : null;
}
let accumulated = 0;
const targetLength = totalLength / 2;
let lastSegmentAngle = 0;
for (let i = 1; i < coordinates.length; i += 1) {
const previous = coordinates[i - 1];
const current = coordinates[i];
if (!previous || !current) continue;
const [previousX = 0, previousY = 0] = previous;
const [currentX = 0, currentY = 0] = current;
const segmentLength = Math.hypot(
currentX - previousX,
currentY - previousY,
);
if (segmentLength > 0) {
lastSegmentAngle = Math.atan2(currentY - previousY, currentX - previousX);
}
if (accumulated + segmentLength >= targetLength) {
const ratio =
segmentLength === 0 ? 0 : (targetLength - accumulated) / segmentLength;
return {
coordinate: [
previousX + (currentX - previousX) * ratio,
previousY + (currentY - previousY) * ratio,
],
angle: lastSegmentAngle,
};
}
accumulated += segmentLength;
}
const coordinate = coordinates[coordinates.length - 1];
return coordinate ? { coordinate, angle: lastSegmentAngle } : null;
};
// SVG 없이 Canvas renderer로 짧은 꼬리선과 화살촉을 직접 그려 방향성을 분명하게 만든다.
export const createFlowDirectionArrowRenderer = (
color: string,
angle: number,
scale: number,
) => {
return (coordinates: any, state: any) => {
const pixel = Array.isArray(coordinates?.[0])
? coordinates[0]
: coordinates;
const [x, y] = pixel ?? [];
const context = state?.context as CanvasRenderingContext2D | undefined;
if (!context || !Number.isFinite(x) || !Number.isFinite(y)) return;
const length = 17 * scale;
const tailLength = 9 * scale;
const headLength = 7 * scale;
const headHalfWidth = 4.5 * scale;
const shaftWidth = 2.4 * scale;
context.save();
context.translate(x, y);
const viewRotation = Number(state?.rotation ?? 0);
const screenAngle =
(Number.isFinite(viewRotation) ? viewRotation : 0) - angle;
context.rotate(screenAngle);
context.lineCap = "round";
context.lineJoin = "round";
context.strokeStyle = "rgba(255, 255, 255, 0.9)";
context.lineWidth = shaftWidth + 2.4;
context.beginPath();
context.moveTo(-tailLength, 0);
context.lineTo(length - headLength, 0);
context.stroke();
context.fillStyle = "rgba(255, 255, 255, 0.9)";
context.beginPath();
context.moveTo(length, 0);
context.lineTo(length - headLength, -headHalfWidth);
context.lineTo(length - headLength, headHalfWidth);
context.closePath();
context.fill();
context.strokeStyle = color;
context.lineWidth = shaftWidth;
context.beginPath();
context.moveTo(-tailLength, 0);
context.lineTo(length - headLength, 0);
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(length, 0);
context.lineTo(length - headLength, -headHalfWidth);
context.lineTo(length - headLength, headHalfWidth);
context.closePath();
context.fill();
context.restore();
};
};
// 유하방향 신뢰도와 관종 색상에 따라 선과 화살표 스타일을 만든다. LOW는 운영 검수 대상이라 더 흐리게 표시한다.
export const createFlowDirectionStyle = (
feature: any,
usageStyleMap: Record<string, FlowDirectionUsageStyle>,
) => {
const confidence = String(
feature.get("directionConfidence") ??
feature.get("direction_confidence") ??
"",
).toUpperCase();
const geometry = feature.getGeometry();
const coordinates = getRepresentativeLineCoordinates(geometry);
const arrowPlacement = getArrowPlacementAtHalfLength(coordinates);
const usageCode = String(
feature.get("usgCd") ?? feature.get("usg_cd") ?? "",
).trim();
const usageStyle = usageStyleMap[usageCode];
const baseColor = usageStyle?.color ?? FLOW_DIRECTION_DEFAULT_COLOR;
const isNetworkCorrected =
String(
feature.get("networkCorrectionYn") ??
feature.get("network_correction_yn") ??
"",
).toUpperCase() === "Y";
const styleByConfidence: Record<
string,
{
color: string;
lineColor: string;
scale: number;
width: number;
lineDash?: number[];
}
> = {
HIGH: {
color: baseColor,
lineColor: usageStyle?.lineColor ?? withAlpha(baseColor, 0.42),
scale: 1,
width: 1.3,
},
MEDIUM: {
color: baseColor,
lineColor: usageStyle?.lineColor ?? withAlpha(baseColor, 0.42),
scale: 1,
width: 1.3,
},
LOW: {
color: withAlpha(baseColor, 0.72),
lineColor: withAlpha(baseColor, 0.28),
scale: 0.9,
width: 1.1,
},
};
const style = isNetworkCorrected
? {
color: FLOW_DIRECTION_NETWORK_CORRECTION_COLOR,
lineColor: withAlpha(FLOW_DIRECTION_NETWORK_CORRECTION_COLOR, 0.5),
scale: 1.08,
width: 2,
lineDash: [8, 4],
}
: (styleByConfidence[confidence] ?? styleByConfidence.LOW!);
const styles = [
new Style({
stroke: new Stroke({
color: style.lineColor,
width: style.width,
lineDash: style.lineDash,
lineCap: "round",
lineJoin: "round",
}),
}),
];
if (arrowPlacement) {
styles.push(
new Style({
geometry: new Point(arrowPlacement.coordinate),
renderer: createFlowDirectionArrowRenderer(
style.color,
arrowPlacement.angle,
style.scale,
),
}),
);
}
return styles;
};
@@ -0,0 +1,197 @@
/** 레이어 설정 응답의 호환 필드·조회 모드·BBOX 계산을 UI 수명과 분리한다. */
export const FLOW_DIRECTION_LAYER_TYPE = "tb_sn_swage_ppl_flow_direction";
export const FLOW_DIRECTION_LAYER_NAME = "유하방향";
export const FLOW_DIRECTION_DEFAULT_MIN_ZOOM = 13;
export const FLOW_DIRECTION_BBOX_BUFFER_RATIO = 0.35;
export type FlowDirectionMode = "PIPE_START_END" | "PIPE_DEPTH";
// /map은 관로 깊이 기준, /map2는 관로 원천 geometry 시점->종점 기준만 유지한다. 두 화면 모두 BBOX 조회만 사용한다.
export const getFlowDirectionModeByPathname = (
pathname: string | null,
): FlowDirectionMode => {
const normalizedPathname = String(pathname ?? "").replace(/\/$/, "");
if (normalizedPathname.endsWith("/map2")) return "PIPE_START_END";
return "PIPE_DEPTH";
};
export const SWAGE_PRCS_FCLT_LAYER_TYPE = "tb_il_swage_prcs_fclt";
export const RAIN_OBSERVATION_LAYER_TYPE = "tb_ms_rain_obsvtr_pstn_info";
export type SwagePrcsFcltLayerMode = "all" | "gte500" | "lt500" | "none";
// 레이어 설정 응답이 lyrTyNm/lyrTypeNm/lyr_type_nm처럼 혼재되어 내려오는 경우를 단일 기준으로 정규화한다.
export const getLayerTypeName = (layerInfo: any) =>
String(
layerInfo?.lyrTyNm ?? layerInfo?.lyrTypeNm ?? layerInfo?.lyr_type_nm ?? "",
).trim();
export const getLayerFilterSql = (layerInfo: any) =>
String(
layerInfo?.filtrSql ??
layerInfo?.filtr_sql ??
layerInfo?.flterSql ??
layerInfo?.filterSql ??
layerInfo?.filter_sql ??
"",
)
.replace(/\s+/g, "")
.toLowerCase();
export const getSwagePrcsFcltCapacityKind = (
layerInfo: any,
): Exclude<SwagePrcsFcltLayerMode, "all" | "none"> | null => {
if (getLayerTypeName(layerInfo) !== SWAGE_PRCS_FCLT_LAYER_TYPE) return null;
const layerName = String(layerInfo?.lyrNm ?? layerInfo?.name ?? "").replace(
/\s+/g,
"",
);
const filterSql = getLayerFilterSql(layerInfo);
if (
filterSql.includes("fclt_cpct>=500") ||
layerName.includes("500이상") ||
layerName.includes("500톤이상")
)
return "gte500";
if (
filterSql.includes("fclt_cpct<500") ||
layerName.includes("500미만") ||
layerName.includes("500톤미만")
)
return "lt500";
return null;
};
export const getSwagePrcsFcltLayerMode = (
checkedNodesData: any[],
): SwagePrcsFcltLayerMode => {
const checkedKinds = new Set(
checkedNodesData
.map((node) => getSwagePrcsFcltCapacityKind(node?.data ?? node))
.filter(Boolean),
);
const hasGte500 = checkedKinds.has("gte500");
const hasLt500 = checkedKinds.has("lt500");
if (hasGte500 && hasLt500) return "all";
if (hasGte500) return "gte500";
if (hasLt500) return "lt500";
return "none";
};
// 유하방향 노드는 타입명 또는 표시명으로 식별한다. DB DML 반영 전후 응답 차이를 모두 흡수하기 위한 판별 함수이다.
export const isFlowDirectionLayerInfo = (layerInfo: any) => {
const layerTypeName = getLayerTypeName(layerInfo);
const layerName = String(layerInfo?.lyrNm ?? layerInfo?.name ?? "").trim();
return (
layerTypeName === FLOW_DIRECTION_LAYER_TYPE ||
layerName === FLOW_DIRECTION_LAYER_NAME
);
};
// 유하방향 노드를 일반 레이어 토글 대상에서 제외하고, 앱 전용 API vector layer로 처리하도록 속성을 보정한다.
export const normalizeFlowDirectionLayerInfos = (data: any[]): any[] => {
if (!Array.isArray(data)) return data;
return data.map((item) => {
const children = Array.isArray(item.children)
? normalizeFlowDirectionLayerInfos(item.children)
: item.children;
if (!isFlowDirectionLayerInfo(item)) {
return { ...item, children };
}
return {
...item,
children,
lyrTyNm:
item.lyrTyNm ||
item.lyrTypeNm ||
item.lyr_type_nm ||
FLOW_DIRECTION_LAYER_TYPE,
lyrNm: item.lyrNm || FLOW_DIRECTION_LAYER_NAME,
gobjTy: item.gobjTy || "line",
srvcNm: "api",
cmncNm: "bbox",
actlLyrYn: "N",
clickPsblYn: "N",
initEprssYn: "N",
minViewSize:
item.minViewSize ??
item.minZoom ??
String(FLOW_DIRECTION_DEFAULT_MIN_ZOOM),
};
});
};
// 강우관측소는 위치와 라벨만 제공하며, 과거 DB 설정값이 Y여도 일반 속성 패널 선택 대상에서는 제외한다.
export const normalizeRainObservationLayerInteraction = (
data: any[],
): any[] => {
if (!Array.isArray(data)) return data;
return data.map((item) => {
const children = Array.isArray(item.children)
? normalizeRainObservationLayerInteraction(item.children)
: item.children;
return getLayerTypeName(item) === RAIN_OBSERVATION_LAYER_TYPE
? { ...item, children, clickPsblYn: "N" }
: { ...item, children };
});
};
// 레이어 설정의 최소 표출 줌을 읽되, 값이 없으면 유하방향 기본 줌 기준을 적용한다.
export const getFiniteNumber = (value: unknown) => {
if (value === null || value === undefined || String(value).trim() === "")
return null;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
};
export const getFlowDirectionMinZoom = (layerInfo: any) => {
return (
getFiniteNumber(layerInfo?.minViewSize ?? layerInfo?.minZoom) ??
FLOW_DIRECTION_DEFAULT_MIN_ZOOM
);
};
// 유하방향 화살표는 관로 위에 얹는 보조 레이어라 레이어 설정의 drawOrdr를 우선 사용하고 없으면 높은 zIndex를 준다.
export const getFlowDirectionZIndex = (layerInfo: any) => {
return getFiniteNumber(layerInfo?.drawOrdr) ?? 9998;
};
// 현재 지도 화면 BBOX 주변을 함께 조회해 이동 직후 가장자리 유하방향이 비어 보이는 현상을 줄인다.
export const expandFlowDirectionExtent = (extent: number[]) => {
const [minX = 0, minY = 0, maxX = 0, maxY = 0] = extent;
const width = Math.max(0, maxX - minX);
const height = Math.max(0, maxY - minY);
const bufferX = width * FLOW_DIRECTION_BBOX_BUFFER_RATIO;
const bufferY = height * FLOW_DIRECTION_BBOX_BUFFER_RATIO;
return [minX - bufferX, minY - bufferY, maxX + bufferX, maxY + bufferY];
};
// API 요청과 디버깅 출력에 같은 BBOX 문자열 포맷을 사용해 FE 계산값과 네트워크 파라미터를 쉽게 대조한다.
export const formatFlowDirectionBbox = (extent: number[]) =>
extent.map((value: number) => value.toFixed(3)).join(",");
// 유하방향 캐시 중복 제거 키이다. BE 응답은 같은 관로 id가 여러 geometry로 반복될 수 있어 geometry까지 포함한다.
export const getFlowDirectionFeatureCacheKey = (feature: any) => {
const featureId = feature.getId?.();
const fcltMngNo = feature.get("fcltMngNo") ?? feature.get("fclt_mng_no");
const usageCode = feature.get("usgCd") ?? feature.get("usg_cd") ?? "";
const coordinates = feature.getGeometry?.()?.getCoordinates?.();
const geometryKey = JSON.stringify(coordinates);
if (featureId) return `id:${String(featureId)}:${geometryKey}`;
if (fcltMngNo) return `fclt:${String(fcltMngNo).trim()}:${geometryKey}`;
return `geom:${String(usageCode).trim()}:${geometryKey}`;
};
@@ -1,8 +1,14 @@
import { setCookie } from "@/shared/lib/cookie";
import {
isWindowPopupKey,
windowPopupDefinitions,
type WindowPopupKey,
} from "../model/popupDefinitions";
import {
resolveWindowPopupTheme,
WINDOW_POPUP_THEME_PARAM,
} from "../model/popupTheme";
import type {
OpenWindowPopupOptions,
OpenWindowPopupParams,
@@ -105,7 +111,18 @@ export const openWindowPopup = (
const definition: WindowPopupDefinition = windowPopupDefinitions[popupKey];
const shouldMaximize = options?.maximize ?? definition.maximize ?? false;
const popupUrl = `/popup/${popupKey}${buildQueryString(params)}`;
// 새 창은 메인 창의 실시간 테마를 쿼리로 함께 받아 쿠키 갱신 시점과 무관하게 동일한 모드로 연다.
const currentTheme = resolveWindowPopupTheme(
document.documentElement.getAttribute("data-theme"),
);
const popupParams: OpenWindowPopupParams = {
...params,
...(currentTheme ? { [WINDOW_POPUP_THEME_PARAM]: currentTheme } : {}),
};
if (currentTheme) {
setCookie("site-theme-key", currentTheme, { path: "/" });
}
const popupUrl = `/popup/${popupKey}${buildQueryString(popupParams)}`;
const popupFeatures = buildPopupFeatures({
...definition,
width: options?.width ?? definition.width,
@@ -0,0 +1,19 @@
const WINDOW_POPUP_THEMES = ["white", "blue", "green", "red", "black"] as const;
export const WINDOW_POPUP_THEME_PARAM = "_theme";
export type WindowPopupTheme = (typeof WINDOW_POPUP_THEMES)[number];
/** 현재 화면·쿠키의 테마값을 SN이 지원하는 5개 모드로 제한한다. */
export function resolveWindowPopupTheme(
value: string | string[] | null | undefined,
): WindowPopupTheme | undefined {
const rawValue = Array.isArray(value) ? value[0] : value;
const normalizedValue = String(rawValue ?? "").trim().toLowerCase();
const themeValue = normalizedValue === "dark" ? "black" : normalizedValue;
return WINDOW_POPUP_THEMES.includes(themeValue as WindowPopupTheme)
? (themeValue as WindowPopupTheme)
: undefined;
}
export { WINDOW_POPUP_THEMES };
@@ -20,21 +20,26 @@ export default function FloodPreUploadPopupContent() {
cd: string,
id: string,
) => {
const data = await postData("v1/sbmrgPrevnt", {
mngYr: year,
mngQu: quater,
atflId: id,
atflCd: cd,
rgtr: tokenManager.getToken(AUTH_USER_ID) || null,
sbmrgPrevntBizNm: fileNm,
});
// 공통 POST가 reject한 HTTP 오류를 팝업에서 처리해 완료 메시지를 보내지 않는다.
try {
const data = await postData("v1/sbmrgPrevnt", {
mngYr: year,
mngQu: quater,
atflId: id,
atflCd: cd,
rgtr: tokenManager.getToken(AUTH_USER_ID) || null,
sbmrgPrevntBizNm: fileNm,
});
if (data) {
alert("파일이 등록되었습니다.", () =>
postPopupMessageAndClose(
WINDOW_POPUP_MESSAGE_TYPE.FLOOD_PRE_UPLOAD_COMPLETED,
),
);
if (data) {
alert("파일이 등록되었습니다.", () =>
postPopupMessageAndClose(
WINDOW_POPUP_MESSAGE_TYPE.FLOOD_PRE_UPLOAD_COMPLETED,
),
);
}
} catch {
alert("파일 등록에 실패했습니다. 잠시 후 다시 시도해주세요.");
}
};
@@ -20,21 +20,26 @@ export default function OldPpUploadPopupContent() {
cd: string,
id: string,
) => {
const data = await postData("v1/dcrpPpl", {
mngYr: year,
mngQu: quater,
atflCd: cd,
atflId: id,
rgtr: tokenManager.getToken(AUTH_USER_ID) || null,
dcrpPplMtncBizNm: fileNm,
});
// 공통 POST가 reject한 HTTP 오류를 팝업에서 처리해 완료 메시지를 보내지 않는다.
try {
const data = await postData("v1/dcrpPpl", {
mngYr: year,
mngQu: quater,
atflCd: cd,
atflId: id,
rgtr: tokenManager.getToken(AUTH_USER_ID) || null,
dcrpPplMtncBizNm: fileNm,
});
if (data) {
alert("파일이 등록되었습니다.", () =>
postPopupMessageAndClose(
WINDOW_POPUP_MESSAGE_TYPE.OLD_PP_UPLOAD_COMPLETED,
),
);
if (data) {
alert("파일이 등록되었습니다.", () =>
postPopupMessageAndClose(
WINDOW_POPUP_MESSAGE_TYPE.OLD_PP_UPLOAD_COMPLETED,
),
);
}
} catch {
alert("파일 등록에 실패했습니다. 잠시 후 다시 시도해주세요.");
}
};
@@ -0,0 +1,14 @@
"use client";
import { useEffect } from "react";
import type { WindowPopupTheme } from "../model/popupTheme";
/** 서버 렌더를 바꾸지 않고 팝업 마운트 후 메인 창의 현재 테마를 적용한다. */
export default function PopupThemeSync({ theme }: { theme: WindowPopupTheme }) {
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
}, [theme]);
return null;
}
@@ -1,8 +1,12 @@
"use client";
import type { WindowPopupKey } from "../model/popupDefinitions";
import type { WindowPopupRegistryItem } from "../model/types";
import { windowPopupRegistry } from "../registry";
import { getPopupParamValue } from "./popupContentUtils";
import PopupMissingParams from "./PopupMissingParams";
type WindowPopupRendererProps = {
popupKey: WindowPopupKey;
searchParams: Record<string, string | string[] | undefined>;
@@ -16,7 +20,18 @@ export default function WindowPopupRenderer({
popupKey,
searchParams,
}: WindowPopupRendererProps) {
const PopupComponent = windowPopupRegistry[popupKey].component;
const popup: WindowPopupRegistryItem = windowPopupRegistry[popupKey];
const missingParams = (popup.requiredParams ?? []).filter(
(name) => !getPopupParamValue(searchParams[name]).trim(),
);
// 직접 URL 진입이나 잘못된 호출에서도 빈 값으로 API를 실행하지 않고
// 모든 WindowPopup이 동일한 누락 안내를 표시한다.
if (missingParams.length > 0) {
return <PopupMissingParams title={popup.title} missingParams={missingParams} />;
}
const PopupComponent = popup.component;
return <PopupComponent searchParams={searchParams} />;
}
@@ -1,4 +1,4 @@
import type { DredgingRecord } from "@/app/(with-base-layout)/oper/dredging/lib/types";
import type { DredgingRecord } from "@/features/dredging";
import type { WindowPopupContentProps } from "../model/types";