refactor(sn): modularize map and features and standardize file naming

This commit is contained in:
2026-10-01 15:47:57 +09:00
parent 7b506320b4
commit 4c7c4c00ab
331 changed files with 15085 additions and 11695 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import { Client } from "@common/network";
import { BASE_URL } from "../config/api";
import { SITE_ID } from "../config/env";
import { setCookie } from "../lib";
import { setCookie } from "../lib/cookie";
setCookie("site-id-key", SITE_ID);
@@ -0,0 +1,59 @@
import {
withSiteIdHeaders,
notifyUnauthorizedResponse,
} from "./service-request-context";
/** CMS/DC/GeoServer의 기존 원문 응답 계약. 업무 코드/지역 변환은 도메인이 담당한다. */
// DC API 호출
export const getDcData = async (
url: string,
resType: string = "json",
): Promise<any> => {
const res = await fetch("/dc-service" + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (res.ok) {
let data;
if (resType === "json") data = await res.json();
else if (resType === "blob") data = await res.blob();
return data;
}
throw new Error("Failed to fetch data");
};
// CMS API 호출
export const getCmsData = async (url: string, data?: object): Promise<any> => {
const res = await fetch("/cms-service" + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (res.ok) {
const data = await res.json();
return data;
}
throw new Error("Failed to fetch data");
};
// GeoServer API 호출
export const getGeoData = async (url: string, data?: object): Promise<any> => {
const res = await fetch("/geoserver" + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (res.ok) {
const data = await res.json();
return data;
}
throw new Error("Failed to fetch data");
};
+130
View File
@@ -0,0 +1,130 @@
import axios, { AxiosError } from "axios";
import {
resolveApiUrl,
DEFAULT_HEADERS,
withSiteIdHeaders,
notifyUnauthorizedResponse,
} from "./service-request-context";
/** 파일 응답/멀티파트 요청 adapter. 기존 헤더·파일명·timeout·오류 계약을 보존한다. */
const parseDownloadFileName = (contentDisposition: string | null) => {
if (!contentDisposition) return undefined;
const utf8Match = contentDisposition.match(
/filename\*\s*=\s*UTF-8''([^;]+)/i,
);
if (utf8Match?.[1]) {
return decodeURIComponent(utf8Match[1].trim());
}
const plainMatch = contentDisposition.match(/filename\s*=\s*"?([^\";]+)"?/i);
return plainMatch?.[1]?.trim();
};
export const postBlobData = async (
url: string,
data: object,
): Promise<{ blob: Blob; fileName?: string }> => {
const res = await fetch(resolveApiUrl(url), {
method: "POST",
headers: withSiteIdHeaders({
"Content-Type": "application/json",
}),
body: JSON.stringify(data),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return {
blob: await res.blob(),
fileName: parseDownloadFileName(res.headers.get("content-disposition")),
};
};
export const postMutiPart = async (
url: string,
data: FormData,
): Promise<any> => {
try {
const res = await axios.post(resolveApiUrl(url), data, {
headers: DEFAULT_HEADERS,
timeout: 600000, // 10분
});
console.log("postMultiPart response:", res);
return res.data.data;
} catch (error) {
if (error instanceof AxiosError) {
const responseBody = error.response?.data;
const serverMessage =
typeof responseBody?.message === "string" && responseBody.message.trim()
? responseBody.message.trim()
: typeof responseBody?.error?.message === "string" &&
responseBody.error.message.trim()
? responseBody.error.message.trim()
: typeof responseBody === "string" && responseBody.trim()
? responseBody.trim()
: null;
const nextError = new Error(
serverMessage ??
`Multipart request failed: ${error.response?.status ?? "UNKNOWN"} ${error.response?.statusText ?? ""}`.trim(),
) as Error & { status?: number; body?: unknown };
nextError.status = error.response?.status;
nextError.body = responseBody;
throw nextError;
}
throw error;
}
};
export const getBlobData = async (url: string): Promise<Blob> => {
const res = await fetch(resolveApiUrl(url), {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return res.blob();
};
export const getBlobDataWithHeaders = async (
url: string,
): Promise<{ blob: Blob; fileName?: string; headers: Headers }> => {
const res = await fetch(resolveApiUrl(url), {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
notifyUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return {
blob: await res.blob(),
fileName: parseDownloadFileName(res.headers.get("content-disposition")),
headers: res.headers,
};
};
+1 -1
View File
@@ -1,4 +1,4 @@
import { deleteData, getData, postRawJson } from "@/components/lib/api";
import { deleteData, getData, postRawJson } from "@/shared/api/sewerage-api";
/** 대량 Excel은 서버 작업으로 생성한다. 목록의 현재 page/size를 전달하지 않는다. */
export async function requestGridExcel(url: string, body: object = {}, fileName = "grid.xlsx"): Promise<void> {
-1
View File
@@ -1,3 +1,2 @@
export { client } from "./client";
/** SN 내부 HTTP 기반의 공개 진입점. 인증·화면 정책은 호출자가 조합한다. */
export { ApiRequestError, createHttpTransport } from "./http-transport";
+21
View File
@@ -0,0 +1,21 @@
import { getData } from "./sewerage-api";
/** 기존 검색 query 생성과 페이지 래퍼 변환. 조건 값과 total 의미를 바꾸지 않는다. */
export const searchData = async <T extends Record<string, any>>(
url: string,
paramObj: T,
) => {
const params = new URLSearchParams(
Object.entries(paramObj)
.filter(([_, value]) => value !== undefined && value !== "") // 값이 있는 항목만 포함
.reduce(
(acc, [key, value]) => {
acc[key] = String(value);
return acc;
},
{} as Record<string, string>,
),
);
const data = await getData(`${url}?${params.toString()}`);
return data && { data: data.content, total: data.totalElements };
};
@@ -0,0 +1,24 @@
import { SITE_ID } from "../config/env";
/** SN 서비스의 공통 요청 정보. 인증 도메인은 여기서 import하지 않는다. */
export const BASE_URL = "/sewerage-service/api";
export const DEFAULT_HEADERS = {
"X-Site-Id": SITE_ID,
};
export const withSiteIdHeaders = (headers: HeadersInit = {}) => ({
...headers,
...DEFAULT_HEADERS,
});
export const resolveApiUrl = (url: string) =>
url.startsWith("/") ? `${url}` : `${BASE_URL}/${url}`;
/** 401 통지 계약. 실제 토큰 만료/로그인 이동 정책은 앱 조립에서 구독한다. */
export const HTTP_UNAUTHORIZED_EVENT = "sn:http-unauthorized";
export function notifyUnauthorizedResponse() {
if (typeof window !== "undefined") {
window.dispatchEvent(new Event(HTTP_UNAUTHORIZED_EVENT));
}
}
+21
View File
@@ -0,0 +1,21 @@
import { createHttpTransport } from "./http-transport";
import {
BASE_URL,
DEFAULT_HEADERS,
notifyUnauthorizedResponse,
} from "./service-request-context";
/** 기존 SN 래퍼/raw 응답 계약을 유지하는 HTTP adapter. 업무 endpoint는 호출자가 소유한다. */
const httpTransport = createHttpTransport({
baseUrl: BASE_URL,
headers: DEFAULT_HEADERS,
onUnauthorized: notifyUnauthorizedResponse,
});
export const {
getData,
postData,
putData,
getRawJson,
postRawJson,
deleteData,
} = httpTransport;
-12
View File
@@ -1,12 +0,0 @@
import type { MenuItem } from "@/entities/menu";
export const BBS_NOTICE_MENU_MARKER = "bbsnotice";
export function isBbsNoticeMenu(item: MenuItem): boolean {
const marker = BBS_NOTICE_MENU_MARKER;
return (
item.urlPath?.toLowerCase().includes(marker) ||
item.menuEngNm?.toLowerCase().includes(marker) ||
item.menuPath?.toLowerCase().includes(marker)
);
}
-7
View File
@@ -4,10 +4,3 @@ export { useMenuStore } from "./use-menu-store";
export { useUserStore } from "./use-user-store";
export { usePrompt } from "./use-prompt";
export { getCookie, setCookie, removeCookie } from "./cookie";
export {
buildStatisticsComponentImportPath,
menuMatchesStatisticsTabId,
parseStatisticsMenuUrlPath,
resolveStatisticsCategory,
resolveStatisticsTabId,
} from "./statistics-menu-url";
@@ -1,84 +0,0 @@
import type { MenuItem } from "@/entities/menu";
export type ParsedStatisticsMenuUrl = {
categoryFromPath: string | null;
componentName: string | null;
rawUrlPath: string;
};
/** 메뉴 `urlPath`에서 통계 화면 카테고리·컴포넌트명을 파싱합니다. */
export function parseStatisticsMenuUrlPath(
urlPath: string,
): ParsedStatisticsMenuUrl {
const trimmed = (urlPath ?? "").trim();
if (!trimmed) {
return { categoryFromPath: null, componentName: null, rawUrlPath: trimmed };
}
let pathPart = trimmed;
let queryString = "";
const queryIndex = trimmed.indexOf("?");
if (queryIndex >= 0) {
pathPart = trimmed.slice(0, queryIndex);
queryString = trimmed.slice(queryIndex + 1);
}
const tabParam = new URLSearchParams(queryString).get("tab")?.trim() || null;
const segments = pathPart.replace(/^\/+/, "").split("/").filter(Boolean);
let categoryFromPath: string | null = null;
if (segments[0] === "statistics" && segments.length >= 2) {
categoryFromPath = segments[1] ?? null;
}
let componentName = tabParam;
if (!componentName) {
if (!pathPart.includes("/") && !queryString) {
componentName = trimmed;
} else if (segments.length === 1 && segments[0] !== "statistics") {
componentName = segments[0] ?? null;
} else if (segments[0] === "statistics" && segments.length >= 3) {
componentName = segments[segments.length - 1] ?? null;
}
}
return { categoryFromPath, componentName, rawUrlPath: trimmed };
}
/** 동적 import용 카테고리 폴더명 (`input`, `review` 등) */
export function resolveStatisticsCategory(
urlPath: string,
parentEngNm: string,
): string {
const { categoryFromPath } = parseStatisticsMenuUrlPath(urlPath);
return categoryFromPath || parentEngNm || "";
}
/** 탭 ID·URL `?tab=` 값 - 컴포넌트 파일명(확장자 제외) */
export function resolveStatisticsTabId(urlPath: string): string {
const { componentName, rawUrlPath } = parseStatisticsMenuUrlPath(urlPath);
return componentName || rawUrlPath;
}
/** `@/src/components/statistics/{category}/{Component}` 또는 루트 컴포넌트 경로 */
export function buildStatisticsComponentImportPath(
urlPath: string,
parentEngNm: string,
): string {
const { componentName } = parseStatisticsMenuUrlPath(urlPath);
const category = resolveStatisticsCategory(urlPath, parentEngNm);
const name = componentName || urlPath;
if (!category) {
return `@/src/components/statistics/${name}`;
}
return `@/src/components/statistics/${category}/${name}`;
}
export function menuMatchesStatisticsTabId(
menu: MenuItem,
tabId: string,
): boolean {
if (!tabId) return false;
if (menu.urlPath === tabId) return true;
return resolveStatisticsTabId(menu.urlPath) === tabId;
}
@@ -1,155 +0,0 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import {
getCommonCodes,
type CommonCodeItem,
} from "@/components/lib/common/apiHelpers";
type CodeLabelMap = Record<string, string>;
type OperCodeGroup =
| "OBSLTBIZSE"
| "EVDNCSBMSNSTTS"
| "CTYFLDNGPRGRSSE"
| "CTYFLDNGDSGNTYPE"
| "BIZPRGRSSTTS";
const COMMON_CODE_GROUPS: OperCodeGroup[] = [
"OBSLTBIZSE",
"EVDNCSBMSNSTTS",
"CTYFLDNGPRGRSSE",
"CTYFLDNGDSGNTYPE",
"BIZPRGRSSTTS",
];
const cachedCodeGroups = new Map<OperCodeGroup, CommonCodeItem[]>();
const pendingCodeGroups = new Map<
OperCodeGroup,
Promise<CommonCodeItem[]>
>();
const loadCodeGroup = async (upCd: OperCodeGroup) => {
const cached = cachedCodeGroups.get(upCd);
if (cached) return cached;
const pending = pendingCodeGroups.get(upCd);
if (pending) return pending;
const request = getCommonCodes(upCd)
.then((codes) => {
cachedCodeGroups.set(upCd, codes);
return codes;
})
.finally(() => {
pendingCodeGroups.delete(upCd);
});
pendingCodeGroups.set(upCd, request);
return request;
};
const toLegacyValueOptions = (codes: CommonCodeItem[]) =>
codes.map((code) => ({
// 현행 운영사업 DB는 한글 설명값을 저장하므로 코드명을 기존 전송값으로 유지한다.
value: code.lwpoCdNm,
label: code.lwpoCdNm,
code: code.lwpoCd,
}));
const toLabelMap = (codes: CommonCodeItem[]): CodeLabelMap => {
const labels: CodeLabelMap = {};
codes.forEach((code) => {
labels[code.lwpoCd] = code.lwpoCdNm;
labels[code.lwpoCdNm] = code.lwpoCdNm;
});
return labels;
};
/** 운영사업의 기존 한글 저장계약을 유지하면서 CMS 선택지·표시명을 제공한다. */
export const useOperBusinessCommonCodes = () => {
const [codeGroups, setCodeGroups] = useState<
Partial<Record<OperCodeGroup, CommonCodeItem[]>>
>(
() =>
Object.fromEntries(cachedCodeGroups.entries()) as Partial<
Record<OperCodeGroup, CommonCodeItem[]>
>,
);
useEffect(() => {
let cancelled = false;
COMMON_CODE_GROUPS.forEach((upCd) => {
loadCodeGroup(upCd)
.then((codes) => {
if (!cancelled) {
setCodeGroups((current) => ({ ...current, [upCd]: codes }));
}
})
.catch((error) => {
console.error(`${upCd} 공통코드 조회에 실패했습니다.`, error);
});
});
return () => {
cancelled = true;
};
}, []);
const obsltBusinessTypeOptions = useMemo(
() =>
codeGroups.OBSLTBIZSE?.length
? toLegacyValueOptions(codeGroups.OBSLTBIZSE)
: [
{ value: "정밀조사", label: "정밀조사", code: "PRCIS_EXMN" },
{ value: "정비사업", label: "정비사업", code: "MNTN_BIZ" },
],
[codeGroups.OBSLTBIZSE],
);
const evidenceStatusOptions = useMemo(
() => toLegacyValueOptions(codeGroups.EVDNCSBMSNSTTS ?? []),
[codeGroups.EVDNCSBMSNSTTS],
);
const cityDesignationTypeOptions = useMemo(
() => toLegacyValueOptions(codeGroups.CTYFLDNGDSGNTYPE ?? []),
[codeGroups.CTYFLDNGDSGNTYPE],
);
const businessProgressOptions = useMemo(
() => toLegacyValueOptions(codeGroups.BIZPRGRSSTTS ?? []),
[codeGroups.BIZPRGRSSTTS],
);
const cityProgressStageLabels = useMemo(
() => toLabelMap(codeGroups.CTYFLDNGPRGRSSE ?? []),
[codeGroups.CTYFLDNGPRGRSSE],
);
const obsltBusinessTypeLabels = useMemo(
() => toLabelMap(codeGroups.OBSLTBIZSE ?? []),
[codeGroups.OBSLTBIZSE],
);
const evidenceStatusLabels = useMemo(
() => toLabelMap(codeGroups.EVDNCSBMSNSTTS ?? []),
[codeGroups.EVDNCSBMSNSTTS],
);
const cityDesignationTypeLabels = useMemo(
() => toLabelMap(codeGroups.CTYFLDNGDSGNTYPE ?? []),
[codeGroups.CTYFLDNGDSGNTYPE],
);
const businessProgressLabels = useMemo(
() => toLabelMap(codeGroups.BIZPRGRSSTTS ?? []),
[codeGroups.BIZPRGRSSTTS],
);
return {
obsltBusinessTypeOptions,
evidenceStatusOptions,
cityDesignationTypeOptions,
businessProgressOptions,
cityProgressStageLabels,
obsltBusinessTypeLabels,
evidenceStatusLabels,
cityDesignationTypeLabels,
businessProgressLabels,
};
};
@@ -6,7 +6,6 @@ import {
createAttachmentStore,
createMenuStore,
createUserStore,
createDataStore,
} from "../store";
type StoreContextType = {
@@ -14,7 +13,6 @@ type StoreContextType = {
attachmentStore: ReturnType<typeof createAttachmentStore>;
menuStore: ReturnType<typeof createMenuStore>;
userStore: ReturnType<typeof createUserStore>;
dataStore: ReturnType<typeof createDataStore>;
};
export const StoreContext = createContext<StoreContextType | undefined>(
@@ -29,7 +27,6 @@ export const StoreProvider = ({ children }: { children: React.ReactNode }) => {
attachmentStore: createAttachmentStore(),
menuStore: createMenuStore(),
userStore: createUserStore(),
dataStore: createDataStore(),
};
}
-89
View File
@@ -1,89 +0,0 @@
import { create } from "zustand";
import { getCmsData } from "@/components/lib/api";
export interface Option { id: number, name: string }
export type BIZ_CD_TYPE = {
lwpoCd: string,
upCd: string,
lwpoCdNm: string,
unit: string,
prntLwpoCd: null
};
export type DataState = {
ctpv: Option[];
sgg: Option[];
BIZ_SE_CD: BIZ_CD_TYPE[];
BIZ_TY_CD: BIZ_CD_TYPE[];
}
export type FetchData = {
fetchCtpvSggData: () => Promise<void>;
fetchBIZ_SE_CD: () => Promise<void>;
fetchBIZ_TY_CD: () => Promise<void>;
};
export type DataStore = DataState & FetchData;
export const defaultInitState: DataState = {
ctpv: [],
sgg: [],
BIZ_SE_CD: [],
BIZ_TY_CD: [],
};
const fetchCtpvSggData = async (set: (state: any) => void) => {
try {
const ctpvData = await getCmsData('/api/v1/code/cache/ADSTDSTRCD');
const ctpvList: Option[] = ctpvData
.filter((item: any) => typeof item.lwpoCd === 'string' && item.lwpoCd.length === 2)
.map((feature: any) => ({
id: feature.lwpoCd,
name: feature.lwpoCdNm
}))
.sort((a: Option, b: Option) => a.name.localeCompare(b.name, 'ko'));
const sggList: Option[] = ctpvData
.filter((item: any) => typeof item.lwpoCd === 'string' && item.lwpoCd.length !== 2)
.map((item: any) => ({
id: item.lwpoCd,
name: item.lwpoCdNm
}))
.sort((a: Option, b: Option) => a.name.localeCompare(b.name, 'ko'));
set({ ctpv: ctpvList, sgg: sggList });
} catch (e: any) {
// alert("시도, 시군구 데이터 로드 실패: " + e.message);
console.error("CTPV 데이터 로드 실패:", e);
}
};
const fetchBIZ_SE_CD = async (set: (state: any) => void) => {
try {
const res = await getCmsData(`/api/v1/code/cache/BIZSECD`);
set({ BIZ_SE_CD: res });
} catch (e: any) {
// alert("BIZ_SE_CD 데이터 로드 실패: " + e.message);
console.error("BIZ_SE_CD 데이터 로드 실패:", e);
}
};
const fetchBIZ_TY_CD = async (set: (state: any) => void) => {
try {
const res = await getCmsData(`/api/v1/code/cache/BIZTYCD`);
set({ BIZ_TY_CD: res });
} catch (e: any) {
// alert("BIZ_TY_CD 데이터 로드 실패: " + e.message);
console.error("BIZ_TY_CD 데이터 로드 실패:", e);
}
};
export const createDataStore = (initState: DataState = defaultInitState) => {
return create<DataStore>((set) => ({
...initState,
fetchCtpvSggData: () => fetchCtpvSggData(set),
fetchBIZ_SE_CD: () => fetchBIZ_SE_CD(set),
fetchBIZ_TY_CD: () => fetchBIZ_TY_CD(set),
}));
};
-1
View File
@@ -2,4 +2,3 @@ export { createAlertStore } from "./alert-store";
export { createAttachmentStore } from "./attachment-store";
export { createMenuStore, type BbsType } from "./menu-store";
export { createUserStore, type IUserInfo } from "./user-store";
export { createDataStore, type DataStore } from "./data-store";