- ({ val: opt.val, text: opt.text }))}
- onSelectValue={val => set처리구역(String(val))}
- value={처리구역}
- />
+
{
// 숫자만 입력 허용
- const val = e.target.value.replace(/[^0-9]/g, '');
- set변수1(val);
+ const val = e.target.value;
+ setGubun(val);
}}
/>
= ({
endLabel=""
/>
+
{/* 조회 버튼 중앙 정렬 */}
@@ -1071,40 +1107,39 @@ const SearchModal: React.FC
= ({
{/* 📋 결과 리스트 */}
- {/* 테이블 영역 (가로/세로 스크롤 가능) */}
-
-
- {
- const resultCount = tableData.length;
- const label =
- activeTab === "basic"
- ? BASIC_TYPES.find((type) => type.val === basicType)?.text
- : activeTab === "operation"
- ? WORK_TYPES.find((type) => type.val === workType)?.text
- : activeTab === "report"
- ? "하수도정비기본계획보고서"
- : TABS.find((tab) => tab.val === activeTab)?.text;
- return (
- <>
- {label} 조회 결과 ({tableCount})건
- >
- );
- })()
- }
+ {/* 테이블 영역 (가로/세로 스크롤 가능) */}
+
+
+ {
+ const label =
+ activeTab === "basic"
+ ? BASIC_TYPES.find((type) => type.val === basicType)?.text
+ : activeTab === "operation"
+ ? WORK_TYPES.find((type) => type.val === workType)?.text
+ : activeTab === "report"
+ ? "하수도정비기본계획보고서"
+ : TABS.find((tab) => tab.val === activeTab)?.text;
+ return (
+ <>
+ {label} 조회 결과 ({tableCount})건
+ >
+ );
+ })()
+ }
tableData={tableData}
headlist={dynamicHeadlist}
pageSize={tableData.length < 10 ? tableData.length : 10}
total={tableCount}
children={undefined}
- cellClick={handleCellClick}
+ cellClick={(activeTab!=='report')?handleCellClick:handleReportCellClick}
onPageChange={setCurPage}
resetPageNo={false}
cur={curPage}
/>
+
-
>
);
@@ -1121,6 +1156,7 @@ const SearchModal: React.FC = ({
z-[101]
`}
body={renderBody()}
+ useDirectRender={true}
/>
);
};
diff --git a/apps/sn/app/(map-layout)/map/commonStore.ts b/apps/sn/app/(map-layout)/map/commonStore.ts
new file mode 100644
index 000000000..ff903e1e7
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/commonStore.ts
@@ -0,0 +1,25 @@
+import { create } from 'zustand';
+
+export type SelectDataType = {
+ text: string;
+ val: string;
+ sido?: string; // 시도 코드 (선택 사항)
+}
+
+interface CityCdStore {
+ cityCd: string;
+ setCityCd: (cityCd: string) => void;
+ sidos: SelectDataType[];
+ setSidos: (sidos: SelectDataType[]) => void;
+ siguns : SelectDataType[];
+ setSiguns: (siguns: SelectDataType[]) => void;
+}
+
+export const useCityCdStore = create((set) => ({
+ cityCd: '',
+ setCityCd: (cityCd: string) => set({ cityCd }),
+ sidos: [],
+ setSidos: (sidos: SelectDataType[]) => set({ sidos }),
+ siguns: [],
+ setSiguns: (siguns: SelectDataType[]) => set({ siguns }),
+}));
diff --git a/apps/sn/app/(map-layout)/map/components/InputSection.tsx b/apps/sn/app/(map-layout)/map/components/InputSection.tsx
new file mode 100644
index 000000000..209361293
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/InputSection.tsx
@@ -0,0 +1,50 @@
+import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@common/components/ui";
+import React from "react";
+
+interface InputSectionProps {
+ title: string;
+ data: { year: string; type: string }[];
+ sectionKey: string;
+ onInputChange: (section: string, index: number, field: string, value: string) => void;
+}
+
+const InputSection: React.FC = ({ title, data, sectionKey, onInputChange }) => {
+ return (
+
+ {/* 섹션 제목 */}
+
+
{title}
+
+ {/* 테이블 */}
+
+
+ );
+};
+
+export default InputSection;
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/common/index.ts b/apps/sn/app/(map-layout)/map/components/common/index.ts
new file mode 100644
index 000000000..055c7062a
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/common/index.ts
@@ -0,0 +1,65 @@
+import MsSwagePpl from "../popupComponent/MsSwagePpl";
+import sewagePump from "../popupComponent/sewagePump";
+import smh from "../popupComponent/smh";
+import Ssc from "../popupComponent/Ssc";
+import StormWaterPump from "../popupComponent/stormWaterPump";
+import SwtrmtFclt from "../popupComponent/SwtrmtFclt";
+
+type LayerComponentProps = {
+ featureData: any;
+ isMainSsc?: boolean;
+ isDrtwSewagePump?: boolean;
+ rainMeasureData?: any;
+ onSaveClick?: () => void;
+ onFormDataChange?: (data: any) => void; // 추가
+};
+type LayerContentMap = {
+ [key: string]: {
+ component?: React.FC;
+ props?: any;
+ };
+};
+// 레이어 이름과 컴포넌트를 매핑
+// 레이어 선택시 변경되는 팝업 컨텐츠 동적으로 변경하도록 작업
+const layerContentMap: LayerContentMap = {
+ "하수처리시설": { component: SwtrmtFclt, },
+ "하수처리구역": {},
+ "우수토실": { component: Ssc, },
+ "중점우수토실": { component: Ssc, }, // 중점우수토실 여부 설정
+ "하수관로": { component: MsSwagePpl, },
+ "하수맨홀": { component: smh, },
+ "하수펌프장": { component: sewagePump },
+ // "빗물펌프": { component: StormWaterPump },
+ // "오수펌프": { component: sewagePump },
+};
+
+// 동적 컴포넌트 반환 함수
+export const getLayerContentComponent = (layerNm: string): React.FC | null => {
+ const component = layerContentMap[layerNm];
+ if (!component || !component.component) {
+ // component가 없으면 null 반환
+ return () => null;
+ }
+ return component.component
+};
+// 사용자 입력 필드 (보수 및 갱신, 청소 및 준설, 점검 및 진단)
+export const handleInputChange = (section: string,
+ index: number,
+ field: string,
+ value: string,
+ dataMap: {
+ [key: string]: {
+ data: { year: string; type: string }[];
+ setData: React.Dispatch>;
+ };
+ }
+) => {
+ const target = dataMap[section];
+ if (!target) return;
+
+ const updated = [...target.data];
+ if (updated[index]) {
+ updated[index][field as keyof typeof updated[number]] = value;
+ }
+ target.setData(updated);
+};
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/common/table.ts b/apps/sn/app/(map-layout)/map/components/common/table.ts
new file mode 100644
index 000000000..0b89ad652
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/common/table.ts
@@ -0,0 +1,689 @@
+// 하수관로
+export const MsSwagePplCol = [
+ { id: 'fclt_mng_no', title: '시설관리번호' },
+ { id: 'inst_mng_no', title: '기관관리번호' },
+ { id: 'instl_ymd', title: '설치일자' },
+ { id: 'mapsht_no', title: '도엽번호' },
+ { id: 'pdmt', title: '관경(mm)' },
+ { id: 'prlg', title: '연장(m)' },
+ { id: 'usg_cd', title: '용도코드' },
+ { id: 'mqlt_cd', title: '재질코드' },
+ { id: 'avg_grdn', title: '평균구배(m/m)' },
+ { id: 'drtw_mltv_area', title: '오수배수면적(m²)' },
+ { id: 'excln_mltv_area', title: '우수배수면적(m²)' },
+ { id: 'tmpt_dpth', title: '시점깊이(m)' },
+ { id: 'tmpt_mhl_mng_no', title: '시점맨홀관리번호' },
+ { id: 'scend_dpth', title: '종점깊이(m)' },
+ { id: 'scend_mhl_mng_no', title: '종점맨홀관리번호' },
+ { id: 'trfln_cnt', title: '차선수' },
+ { id: 'vrtc_len', title: '세로길이(m)' },
+ { id: 'wdth_len', title: '가로길이(m)' },
+ // { id: 'rnyssn_fvlc', title: '우기 시 유속(m/s)' },
+ // { id: 'clar_fvlc', title: '건기 시 유속(m/s)' },
+ // { id: 'mng_inst_cd', title: '관리기관코드' },
+ // { id: 'pbadms_emd_cd', title: '행정읍면동코드' },
+ // { id: 'fclty_shp_cd', title: '시설물형태코드' },
+ // { id: 'fid', title: 'FID' },
+ // { id: 'ftre_smbol_cd', title: '지형지물부호코드' },
+ // { id: 'lyrTypeNm', title: '레이어타입명' },
+]
+export const MsSwagePplCol2 = [
+ { id: 'fcltMngNo', title: '시설관리번호' },
+ { id: 'instMngNo', title: '기관관리번호' },
+ { id: 'instlYmd', title: '설치일자' },
+ { id: 'mapshtNo', title: '도엽번호' },
+ { id: 'pdmt', title: '관경(mm)' },
+ { id: 'prlg', title: '연장(m)' },
+ { id: 'avgGrdn', title: '평균구배(m/m)' },
+ { id: 'rnysnFvlc', title: '우기 시 유속(m/s)' },
+ { id: 'clarFvlc', title: '건기 시 유속(m/s)' },
+ { id: 'drtwMltvArea', title: '오수배수면적(m²)' },
+ { id: 'exclnMltvArea', title: '우수배수면적(m²)' },
+ { id: 'tmptDpth', title: '시점깊이(m)' },
+ { id: 'tmptMhlMngNo', title: '시점맨홀관리번호' },
+ { id: 'scendDpth', title: '종점깊이(m)' },
+ { id: 'scendMhlMngNo', title: '종점맨홀관리번호' },
+ { id: 'trflnCnt', title: '차선수' },
+ { id: 'vrtcLen', title: '세로길이(m)' },
+ { id: 'wdthLen', title: '가로길이(m)' },
+ // { id: 'fcltyShpCd', title: '시설물형태코드' },
+ // { id: 'fid', title: 'FID' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ // { id: 'mqltCd', title: '재질코드' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ // { id: 'usgCd', title: '용도코드' },
+ // { id: 'lyrTypeNm', title: '레이어타입명' },
+]
+// 하수관로 용도 코드표
+export const MS_SWAGE_PPL_USE_CODES = [
+ { val: "SBA000", text: "미분류" },
+ { val: "SBA001", text: "합류관" },
+ { val: "SBA002", text: "차집관" },
+ { val: "SBA003", text: "우수관" },
+ { val: "SBA004", text: "오수관" },
+ { val: "SBA999", text: "기타" },
+ { val: "그 외", text: "미분류" },
+];
+// 하수관로 재질 코드표
+export const MS_SWAGE_PPL_CODES = [
+ { val: "MOP000", text: "미분류" },
+ { val: "MOP001", text: "닥타일주철관(DCIP)" },
+ { val: "MOP002", text: "강관(SP)" },
+ { val: "MOP003", text: "아연도강관(GS)" },
+ { val: "MOP004", text: "염화비닐관(PVC)" },
+ { val: "MOP005", text: "폴리에틸렌관(PE)" },
+ { val: "MOP006", text: "스테인레스관(SSP)" },
+ { val: "MOP007", text: "동관(COP)" },
+ { val: "MOP008", text: "P.S.콘크리트관(PC)" },
+ { val: "MOP009", text: "석면시멘트관(AS)" },
+ { val: "MOP010", text: "회주철관(CIP)" },
+ { val: "MOP011", text: "연관(LP)" },
+ { val: "MOP012", text: "흉관(HP)" },
+ { val: "MOP013", text: "철근콘크리트관(RC)" },
+ { val: "MOP014", text: "강관(ST)" },
+ { val: "MOP015", text: "주철관(CI)" },
+ { val: "MOP016", text: "화학제품류관(PV)" },
+ { val: "MOP017", text: "도관(VC)" },
+ { val: "MOP018", text: "석축(SE)" },
+ { val: "MOP019", text: "도복장 강관(SP)" },
+ { val: "MOP020", text: "흉관(EP)" },
+ { val: "MOP021", text: "아연도강관(GP)" },
+ { val: "MOP022", text: "청동관(BR)" },
+ { val: "MOP023", text: "고무몰딩(RM)" },
+ { val: "MOP024", text: "주강(CS)" },
+ { val: "MOP025", text: "VR관" },
+ { val: "MOP026", text: "HDPE관" },
+ { val: "MOP027", text: "시멘트라이닝주철관(C)" },
+ { val: "MOP028", text: "수도용 PE관(PE)" },
+ { val: "MOP029", text: "석면시멘트관(AC)" },
+ { val: "MOP030", text: "폴리에틸렌분체라이닝강관(PEP)" },
+ { val: "MOP031", text: "에폭시코팅강관(EPS)" },
+ { val: "MOP032", text: "HI-3P" },
+ { val: "MOP033", text: "철근콘크리트박스(RCB)" },
+ { val: "MOP034", text: "콘크리트중선함(CD)" },
+ { val: "MOP035", text: "후랙시불전선함(FP)" },
+ { val: "MOP036", text: "전선함(FD)" },
+ { val: "MOP038", text: "이중보온관" },
+ { val: "MOP039", text: "폴리에틸렌피복강관(PLP)" },
+ { val: "MOP041", text: "FRP" },
+ { val: "MOP042", text: "강재" },
+ { val: "MOP999", text: "기타" },
+ { val: "MOP800", text: "2중벽PE관" },
+ { val: "MOP801", text: "3중벽PE관" },
+ { val: "MOP802", text: "가스배관용 강관" },
+ { val: "MOP803", text: "강관(피복 Double, 용접접합)" },
+ { val: "MOP804", text: "강관(피복 Single, 용접접합)" },
+ { val: "MOP805", text: "강관(CP)" },
+ { val: "MOP806", text: "강철" },
+ { val: "MOP807", text: "강화플라스틱복합관" },
+ { val: "MOP808", text: "경질염화비닐관(HI-VP)" },
+ { val: "MOP809", text: "고강성PVC이중벽관" },
+ { val: "MOP810", text: "고광도PVC이중벽관" },
+ { val: "MOP811", text: "고밀도폴리에틸렌관(THP)" },
+ { val: "MOP812", text: "고밀도폴리에틸렌파상형이중벽관" },
+ { val: "MOP813", text: "공장제 박스관거" },
+ { val: "MOP814", text: "관로없음(알케이블)" },
+ { val: "MOP815", text: "나선형강관" },
+ { val: "MOP816", text: "내충격수도관" },
+ { val: "MOP817", text: "내충격용하수도용경질염화비닐관(HI-VG)" },
+ { val: "MOP818", text: "내충격HI-VG2관" },
+ { val: "MOP819", text: "내충격PVC하수관" },
+ { val: "MOP820", text: "녹석(돌산호과 일종)" },
+ { val: "MOP821", text: "동관(구리관, 용접)" },
+ { val: "MOP822", text: "둥근잔돌" },
+ { val: "MOP823", text: "무근콘크리트" },
+ { val: "MOP824", text: "백관" },
+ { val: "MOP825", text: "복합철판파형관" },
+ { val: "MOP826", text: "분체라이닝관" },
+ { val: "MOP827", text: "석축박스" },
+ { val: "MOP828", text: "석축철콘" },
+ { val: "MOP829", text: "수도용경질염화비관" },
+ { val: "MOP830", text: "수도용경질염화비닐이음관" },
+ { val: "MOP831", text: "수도용엑포시수지분체내외면코팅강관" },
+ { val: "MOP832", text: "수지파형강관(PCS)" },
+ { val: "MOP833", text: "수지CSP" },
+ { val: "MOP834", text: "스테인레스 주름관" },
+ { val: "MOP835", text: "스테인레스관(STS)" },
+ { val: "MOP836", text: "스테인레스스틸파이프관" },
+ { val: "MOP837", text: "아스콘" },
+ { val: "MOP838", text: "아스팔트" },
+ { val: "MOP839", text: "아스팔트도복장강관(ASP)" },
+ { val: "MOP840", text: "아연" },
+ { val: "MOP841", text: "아연도금(백관)" },
+ { val: "MOP842", text: "알루미늄" },
+ { val: "MOP843", text: "알루미늄합금" },
+ { val: "MOP844", text: "압력배관용 탄소강관" },
+ { val: "MOP845", text: "양철관" },
+ { val: "MOP846", text: "양철주름관(CSP)" },
+ { val: "MOP847", text: "연합인슈강판" },
+ { val: "MOP848", text: "와사관(GSP)" },
+ { val: "MOP849", text: "원심력철근콘크리트" },
+ { val: "MOP850", text: "유리섬유관(GRP)" },
+ { val: "MOP851", text: "유리섬유복합관(GRP)" },
+ { val: "MOP852", text: "이음매없는동및동합금관" },
+ { val: "MOP853", text: "일반배관용스테인리스강관" },
+ { val: "MOP854", text: "전압 콘크리트관" },
+ { val: "MOP855", text: "주름관" },
+ { val: "MOP856", text: "주름주철파형강관" },
+ { val: "MOP857", text: "지중 저압케이블 입상관" },
+ { val: "MOP858", text: "진동및전압철근콘크리트관" },
+ { val: "MOP859", text: "철근콘크리트" },
+ { val: "MOP860", text: "철근콘크리트 블록" },
+ { val: "MOP861", text: "철근콘크리트조립흙막이" },
+ { val: "MOP862", text: "철판매입관" },
+ { val: "MOP863", text: "청동" },
+ { val: "MOP864", text: "코아식프리스트레스트콘크리트관" },
+ { val: "MOP865", text: "콘크리트" },
+ { val: "MOP866", text: "콘크리트 폴륨관" },
+ { val: "MOP867", text: "콘크리트블록" },
+ { val: "MOP868", text: "탄소강" },
+ { val: "MOP869", text: "탄소강(카본스틸)" },
+ { val: "MOP870", text: "탄소주강" },
+ { val: "MOP871", text: "트러후" },
+ { val: "MOP872", text: "파선형강관(RCF)" },
+ { val: "MOP873", text: "파형강관(CSP)" },
+ { val: "MOP874", text: "파형관" },
+ { val: "MOP875", text: "파형플라스틱관" },
+ { val: "MOP876", text: "폴리머관" },
+ { val: "MOP877", text: "폴리에스테르수지콘크리트관" },
+ { val: "MOP878", text: "폴리에틸렌 전선관" },
+ { val: "MOP879", text: "폴리에틸렌 피복강관" },
+ { val: "MOP880", text: "폴리에틸렌관 1호관" },
+ { val: "MOP881", text: "폴리에틸렌관 2호관" },
+ { val: "MOP882", text: "폴리에틸렌관(2중벽)" },
+ { val: "MOP883", text: "폴리에틸렌관(3중벽)" },
+ { val: "MOP884", text: "폴리에틸렌분체라이닝" },
+ { val: "MOP885", text: "폴리에틸렌이중벽하수관" },
+ { val: "MOP886", text: "폴리탄산에스테르" },
+ { val: "MOP887", text: "프리스트레스트콘크리트실린더관" },
+ { val: "MOP888", text: "플라스틱" },
+ { val: "MOP889", text: "플라스틱주름관" },
+ { val: "MOP890", text: "하수도용고강성경질염화비닐이중벽주름관" },
+ { val: "MOP891", text: "현장타설관" },
+ { val: "MOP892", text: "현장타설철근콘크리트관" },
+ { val: "MOP893", text: "흑관" },
+ { val: "MOP894", text: "흙" },
+ { val: "MOP895", text: "AP" },
+ { val: "MOP896", text: "API관" },
+ { val: "MOP897", text: "ASP" },
+ { val: "MOP898", text: "CMCIP" },
+ { val: "MOP899", text: "CSP" },
+ { val: "MOP900", text: "DRP" },
+ { val: "MOP901", text: "DSP" },
+ { val: "MOP902", text: "DTC관" },
+ { val: "MOP903", text: "ELP" },
+ { val: "MOP904", text: "EPP" },
+ { val: "MOP905", text: "FC관" },
+ { val: "MOP906", text: "H" },
+ { val: "MOP907", text: "H6" },
+ { val: "MOP908", text: "HCP" },
+ { val: "MOP909", text: "HI_2P관" },
+ { val: "MOP910", text: "HI-KP" },
+ { val: "MOP911", text: "HL" },
+ { val: "MOP912", text: "IP" },
+ { val: "MOP913", text: "KCGP" },
+ { val: "MOP914", text: "KP관" },
+ { val: "MOP915", text: "P2S관" },
+ { val: "MOP916", text: "PC박스(PCB)" },
+ { val: "MOP917", text: "PCS" },
+ { val: "MOP918", text: "PDP" },
+ { val: "MOP919", text: "PE이중벽관" },
+ { val: "MOP920", text: "PE적측벽1종관" },
+ { val: "MOP921", text: "PFP관" },
+ { val: "MOP922", text: "PG관" },
+ { val: "MOP923", text: "PIP관(이중보온관)" },
+ { val: "MOP924", text: "PLCSP" },
+ { val: "MOP925", text: "PS" },
+ { val: "MOP926", text: "PUB" },
+ { val: "MOP927", text: "PVB" },
+ { val: "MOP928", text: "PVC이중벽관(PVC2)" },
+ { val: "MOP929", text: "PVC-DC" },
+ { val: "MOP930", text: "PVC-DV" },
+ { val: "MOP931", text: "SBK" },
+ { val: "MOP932", text: "SCP" },
+ { val: "MOP933", text: "SEB" },
+ { val: "MOP934", text: "SIS관(이중보온관)" },
+ { val: "MOP935", text: "SMC" },
+ { val: "MOP936", text: "STW" },
+ { val: "MOP937", text: "SUS" },
+ { val: "MOP938", text: "THP나선관" },
+ { val: "MOP939", text: "U관" },
+ { val: "MOP940", text: "VG2" },
+ { val: "MOP941", text: "WSP(와사피)" },
+ { val: "MOP942", text: "Steel Grating" },
+ { val: "MOP943", text: "모래" },
+ { val: "MOP944", text: "인조석" },
+ { val: "MOP945", text: "SPOL" },
+ { val: "MOP946", text: "PCF관(강판보강 PE 나선형관)" },
+ { val: "MOP947", text: "PVC3(PVC3중벽관)" },
+ { val: "MOP948", text: "PE다중벽관" },
+ { val: "MOP977", text: "전주용입상관" },
+ { val: "MOP978", text: "MD관" },
+ { val: "그 외", text: "미분류" },
+];
+
+// 하수처리시설
+export const SwtrmtFcltCol = [
+ { id: 'swtrmt_fclt_nm', title: '하수처리시설명' },
+ { id: 'fclt_cpct', title: '시설용량(㎥/d)' },
+ { id: 'rgn_expln', title: '지역설명' },
+ { id: 'cmcn_ymd', title: '준공일자' },
+ { id: 'oprtng_strt_ymd', title: '가동개시일자' },
+ { id: 'clsg_ymd', title: '폐쇄일자' },
+ // { id: 'prcs_msrc_cd', title: '처리공법코드' },
+ // { id: 'lae_cd', title: '지자체코드' },
+ { id: 'lae_nm', title: '지자체명' },
+ { id: 'ctpv_nm', title: '시도명' },
+ { id: 'sgg_nm', title: '시군구명' },
+ // { id: 'sarea_cd', title: '권역코드' },
+ { id: 'sarea_nm', title: '권역명' },
+ { id: 'lrge_sarea_nm', title: '대권역명' },
+ { id: 'rvr_nm', title: '하천명' },
+ { id: 'addr', title: '주소' },
+ { id: 'dtl_addr', title: '상세주소' },
+ { id: 'rdnm_addr', title: '도로명주소' },
+ { id: 'dtl_rdnm_addr', title: '상세도로명주소' },
+ { id: 'dschg_wtst_nm', title: '방류수계명' },
+ { id: 'plln_area', title: '부지면적(m²)' },
+ { id: 'mng_rprtv_bzenty_nm', title: '관리대행업제명' },
+ { id: 'swtrmt_ppltn_cnt', title: '하수처리인구수(인)' },
+ { id: 'prcs_zone_area_sum', title: '처리구역면적합계(m²)' },
+ { id: 'xcrd', title: 'X좌표' },
+ { id: 'ycrd', title: 'Y좌표' },
+ // { id: 'oprtngSttsCd', title: '가동상태코드' },
+ { id: 'rprs_msrc_cn', title: '대표공법내용' },
+ { id: 'stty_crtr_bod', title: '법정기준생물화학적산소요구량(mg/L)' },
+ { id: 'stty_crtr_toc', title: '법정기준TOC((mg/L))' },
+ { id: 'stty_crtr_ss', title: '법정기준SS(mg/L)' },
+ { id: 'stty_crtr_tn', title: '법정기준총질소(mg/L)' },
+ { id: 'stty_crtr_tph', title: '법정기준총인(mg/L)' },
+ { id: 'stty_crtr_clbcl_cnt', title: '법정기준대장균수(군수/100mL)' },
+ { id: 'bsn_nm', title: '유역명' },
+ // { id: 'obsrvnSptCd', title: '관측지점코드' },
+];
+export const SwtrmtFcltCol2 = [
+ { id: 'swtrmtFcltNm', title: '하수처리시설명' },
+ { id: 'fcltCpct', title: '시설용량(㎥/d)' },
+ { id: 'rgnExpln', title: '지역설명' },
+ { id: 'cmcnYmd', title: '준공일자' },
+ { id: 'oprtngStrtYmd', title: '가동개시일자' },
+ { id: 'clsgYmd', title: '폐쇄일자' },
+ // { id: 'prcsMsrcCd', title: '처리공법코드' },
+ // { id: 'laeCd', title: '지자체코드' },
+ { id: 'laeNm', title: '지자체명' },
+ { id: 'ctpvNm', title: '시도명' },
+ { id: 'sggNm', title: '시군구명' },
+ // { id: 'sareaCd', title: '권역코드' },
+ { id: 'sareaNm', title: '권역명' },
+ { id: 'lrgeSareaNm', title: '대권역명' },
+ { id: 'rvrNm', title: '하천명' },
+ { id: 'addr', title: '주소' },
+ { id: 'dtlAddr', title: '상세주소' },
+ { id: 'rdnmAddr', title: '도로명주소' },
+ { id: 'dtlRdnmAddr', title: '상세도로명주소' },
+ { id: 'dschgWtstNm', title: '방류수계명' },
+ { id: 'pllnArea', title: '부지면적(m²)' },
+ { id: 'mngRprtvBzentyNm', title: '관리대행업제명' },
+ { id: 'swtrmtPpltnCnt', title: '하수처리인구수(인)' },
+ { id: 'prcsZoneAreaSum', title: '처리구역면적합계(m²)' },
+ { id: 'xcrd', title: 'X좌표' },
+ { id: 'ycrd', title: 'Y좌표' },
+ // { id: 'oprtngSttsCd', title: '가동상태코드' },
+ { id: 'rprsMsrcCn', title: '대표공법내용' },
+ { id: 'sttyCrtrBod', title: '법정기준생물화학적산소요구량(mg/L)' },
+ { id: 'sttyCrtrToc', title: '법정기준TOC(mg/L)' },
+ { id: 'sttyCrtrSs', title: '법정기준SS(mg/L)' },
+ { id: 'sttyCrtrTn', title: '법정기준총질소(mg/L)' },
+ { id: 'sttyCrtrTph', title: '법정기준총인(mg/L)' },
+ { id: 'sttyCrtrClbclCnt', title: '법정기준대장균수(군수/100mL)' },
+ { id: 'bsnNm', title: '유역명' },
+ // { id: 'obsrvnSptCd', title: '관측지점코드' },
+];
+
+// 하수처리구역
+export const SwtrmtPrcsZoneCol = [
+ // { id: 'swtrmtZoneSn', title: '하수처리구역 일련번호' },
+ { id: 'swtrmt_zone_nm', title: '하수처리구역명' },
+ // { id: 'swtrmt_fclt_cd', title: '하수처리시설코드' },
+ // { id: 'ctpv_cd', title: '시도코드' },
+ { id: 'ctpv_nm', title: '시도명' },
+ // { id: 'sgg_cd', title: '시군구코드' },
+ { id: 'sgg_nm', title: '시군구명' },
+ { id: 'swtrmt_fclt_nm', title: '하수처리시설명' },
+];
+export const SwtrmtPrcsZoneCol2 = [
+ // { id: 'swtrmtZoneSn', title: '하수처리구역 일련번호' },
+ { id: 'swtrmtZoneNm', title: '하수처리구역명' },
+ // { id: 'swtrmt_fclt_cd', title: '하수처리시설코드' },
+ // { id: 'ctpv_cd', title: '시도코드' },
+ { id: 'ctpvNm', title: '시도명' },
+ // { id: 'sgg_cd', title: '시군구코드' },
+ { id: 'sggNm', title: '시군구명' },
+ { id: 'swtrmtFcltNm', title: '하수처리시설명' },
+];
+
+// 하수맨홀
+export const MsSwageMhlCol = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftre_smbol_cd', title: '지형지물부호코드' },
+ { id: 'fclt_mng_no', title: '시설관리번호' },
+ // { id: 'pbadms_emd_cd', title: '행정읍면동코드' },
+ { id: 'mapsht_no', title: '도엽번호' },
+ // { id: 'mng_inst_cd', title: '관리기관코드' },
+ { id: 'instl_ymd', title: '설치일자' },
+ { id: 'last_drdgn_ymd', title: '최종준설일자' },
+ // { id: 'usg_cd', title: '용도코드' },
+ // { id: 'fclty_shp_cd', title: '시설물형태코드' },
+ // { id: 'mhl_knd_cd', title: '맨홀종류코드' },
+ { id: 'swage_mh_diam', title: '하수맨홀구경(mm)' },
+ { id: 'mqlt_cd', title: '재질코드' },
+ { id: 'wdth_len', title: '가로길이(m)' },
+ { id: 'vrtc_len', title: '세로길이(m)' },
+ // { id: 'ang_dir', title: '표고' },
+ { id: 'altd_vl', title: '표고(EL.m)' },
+ { id: 'dpthlVl', title: '심도(m)' },
+ // { id: 'inst_mng_no', title: '기관관리번호' }
+];
+export const MsSwageMhlCol2 = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ { id: 'fcltMngNo', title: '시설관리번호' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ { id: 'mapshtNo', title: '도엽번호' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ { id: 'instlYmd', title: '설치일자' },
+ // { id: 'lastDrdgnYmd', title: '최종준설일자' },
+ // { id: 'usgCd', title: '용도코드' },
+ // { id: 'fcltyShpCd', title: '시설물형태코드' },
+ // { id: 'mhlKndCd', title: '맨홀종류코드' },
+ { id: 'swageMhDiam', title: '하수맨홀구경(mm)' },
+ { id: 'mqltCd', title: '재질코드' },
+ { id: 'wdthLen', title: '가로길이(m)' },
+ { id: 'vrtcLen', title: '세로길이(m)' },
+ // { id: 'angDir', title: '표고' },
+ { id: 'altdVl', title: '표고(EL.m)' },
+ { id: 'dpthlVl', title: '심도(m)' },
+ // { id: 'instMngNo', title: '기관관리번호' }
+];
+// 하수맨홀 뚜껑재질 코드표
+export const MS_SWAGE_MHL_CODES = [
+ { val: "SBC000", text: "미분류" },
+ { val: "SBC001", text: "주철" },
+ { val: "SBC002", text: "철판" },
+ { val: "SBC003", text: "콘크리트" },
+ { val: "SBC004", text: "그레이팅" },
+ { val: "SBC091", text: "칼라" },
+ { val: "SBC092", text: "S.G" },
+ { val: "SBC999", text: "기타" },
+ { val: "SBC900", text: "각주철" },
+ { val: "SBC901", text: "강재" },
+ { val: "SBC902", text: "나무" },
+ { val: "SBC903", text: "나무,널판지,합판" },
+ { val: "SBC904", text: "대리석" },
+ { val: "SBC905", text: "뚜껑없음" },
+ { val: "SBC906", text: "보도용콘크리트" },
+ { val: "SBC907", text: "스틸(ST)" },
+ { val: "SBC908", text: "신형 CON" },
+ { val: "SBC909", text: "알루미늄" },
+ { val: "SBC910", text: "염화비닐(PE)" },
+ { val: "SBC911", text: "인조석" },
+ { val: "SBC912", text: "인조석(주철)" },
+ { val: "SBC913", text: "인조CONC" },
+ { val: "SBC914", text: "철, 철근" },
+ { val: "SBC915", text: "칼라콘크리트" },
+ { val: "SBC916", text: "플라스틱" },
+ { val: "SBC917", text: "PVC" },
+ { val: "SBC918", text: "SP" },
+ { val: "SBC919", text: "SS" },
+ { val: "SBC920", text: "닥타일주철" },
+ { val: "SBC921", text: "철근G" },
+ { val: "SBC922", text: "폴리에틸렌(PE)" },
+ { val: "SBC923", text: "회주철" }
+];
+// 하수맨홀 용도 코드표
+export const MS_SWAGE_MHL_USE_CODES = [
+ { val: "SMU000", text: "미분류" },
+ { val: "SMU001", text: "우수" },
+ { val: "SMU002", text: "오수" },
+ { val: "SMU003", text: "집수" },
+ { val: "SMU004", text: "합류" },
+ { val: "SMU005", text: "차집" },
+ { val: "SMU999", text: "기타" },
+ { val: "SMU900", text: "1호" },
+ { val: "SMU901", text: "2호" },
+ { val: "SMU902", text: "3호" },
+ { val: "SMU903", text: "4호" },
+ { val: "SMU904", text: "5호" },
+ { val: "SMU905", text: "6호" },
+ { val: "SMU906", text: "7호" },
+ { val: "SMU907", text: "8호" },
+ { val: "SMU908", text: "구거용맨홀" },
+ { val: "SMU909", text: "부관부착맨홀" },
+ { val: "SMU910", text: "조립식맨홀" },
+ { val: "SMU911", text: "특1호" },
+ { val: "SMU912", text: "특2호" },
+ { val: "SMU913", text: "특3호" },
+ { val: "SMU914", text: "특4호" },
+ { val: "SMU915", text: "특5호" },
+ { val: "SMU916", text: "하수맨홀용도" },
+ { val: "SMU917", text: "현장타설관거용" }
+];
+
+// 우수펌프장
+export const ExclnSewagePumpCol = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ { id: 'fclt_mng_no', title: '시설관리번호' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ { id: 'mapsht_no', title: '도엽번호' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ { id: 'instl_ymd', title: '설치일자' },
+ { id: 'swage_pmstn_nm', title: '하수펌프장명' },
+ { id: 'plln_area', title: '부지면적(m²)' },
+ // { id: 'opngSttsCd', title: '개통상태코드' },
+ // { id: 'usgCd', title: '용도코드' },
+ { id: 'daily_prcs_cpct', title: '일일처리용량(㎥)' },
+ { id: 'max_impnd_cpct', title: '최대저수용량(㎥)' },
+ { id: 'altd_vl', title: '표고(EL.m)' },
+ { id: 'wtlv_vl', title: '수위(m)' },
+ { id: 'excln_wpmp_ablt', title: '우수양수능력(m²/d)' },
+ // { id: 'instMngNo', title: '기관관리번호' },
+]
+export const ExclnSewagePumpCol2 = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ { id: 'fcltMngNo', title: '시설관리번호' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ { id: 'mapshtNo', title: '도엽번호' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ { id: 'instlYmd', title: '설치일자' },
+ { id: 'swagePmstnNm', title: '하수펌프장명' },
+ { id: 'pllnArea', title: '부지면적(m²)' },
+ // { id: 'opngSttsCd', title: '개통상태코드' },
+ // { id: 'usgCd', title: '용도코드' },
+ { id: 'dailyPrcsCpct', title: '일일처리용량(㎥)' },
+ { id: 'max_impndCpct', title: '최대저수용량(㎥)' },
+ { id: 'altdVl', title: '표고(EL.m)' },
+ { id: 'wtlvVl', title: '수위(m)' },
+ { id: 'exclnWpmpAblt', title: '우수양수능력(m²/d)' },
+ // { id: 'instMngNo', title: '기관관리번호' },
+]
+// 오수펌프장
+export const DrtwSewagePumpCol1 = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ { id: 'fclt_mng_no', title: '시설관리번호' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ { id: 'mapsht_no', title: '도엽번호' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ { id: 'instl_ymd', title: '설치일자' },
+ { id: 'swage_pmstn_nm', title: '하수펌프장명' },
+ { id: 'plln_area', title: '부지면적(m²)' },
+ // { id: 'opngSttsCd', title: '개통상태코드' },
+ // { id: 'usgCd', title: '용도코드' },
+ { id: 'daily_prcs_cpct', title: '일일처리용량(㎥)' },
+ { id: 'max_impnd_cpct', title: '최대저수용량(㎥)' },
+ { id: 'altd_vl', title: '표고(EL.m)' },
+ { id: 'wtlv_vl', title: '수위(m)' },
+ { id: 'excln_wpmp_ablt', title: '오수양수능력(m²/d)' },
+ // { id: 'instMngNo', title: '기관관리번호' },
+]
+export const DrtwSewagePumpCol2 = [
+ // { id: 'fid', title: 'FID' },
+ // { id: 'geom', title: 'geometry' },
+ // { id: 'ftreSmbolCd', title: '지형지물부호코드' },
+ { id: 'fcltMngNo', title: '시설관리번호' },
+ // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
+ { id: 'mapshtNo', title: '도엽번호' },
+ // { id: 'mngInstCd', title: '관리기관코드' },
+ { id: 'instlYmd', title: '설치일자' },
+ { id: 'swagePmstnNm', title: '하수펌프장명' },
+ { id: 'pllnArea', title: '부지면적(m²)' },
+ // { id: 'opngSttsCd', title: '개통상태코드' },
+ // { id: 'usgCd', title: '용도코드' },
+ { id: 'dailyPrcsCpct', title: '일일처리용량(㎥)' },
+ { id: 'max_impndCpct', title: '최대저수용량(㎥)' },
+ { id: 'altdVl', title: '표고(EL.m)' },
+ { id: 'wtlvVl', title: '수위(m)' },
+ { id: 'exclnWpmpAblt', title: '오수양수능력(m²/d)' },
+ // { id: 'instMngNo', title: '기관관리번호' },
+]
+// 펌프장 용도 코드표
+export const DRTW_SEWAGE_PUMP_USE_CODES = [
+ { val: "SBE000", text: "미분류" },
+ { val: "SBE001", text: "빗물펌프장" },
+ { val: "SBE002", text: "오수펌프장" },
+ { val: "SBE003", text: "처리장내펌프장" },
+ { val: "SBE900", text: "오수배제" },
+ { val: "SBE901", text: "우수배제" },
+ { val: "SBE999", text: "기타" },
+ { val: "그 외", text: "미분류" },
+];
+
+// 우수토실
+export const stofcbrCol = [
+ // { id: 'ftre_smbol_cd', title: '지형지물부호코드' },
+ { id: 'pbadms_emd_cd', title: '시설관리번호' },
+ // { id: 'pbadms_emd_cd', title: '행정읍면동코드' },
+ { id: 'mapsht_no', title: '도엽번호' },
+ // { id: 'mng_inst_cd', title: '관리기관코드' },
+ { id: 'instl_ymd', title: '설치일자' },
+ // { id: 'fclty_shp_cd', title: '시설물형태코드' },
+ { id: 'worflw_wall_hgt', title: '월류벽높이(m)' },
+ // { id: 'mhl_exst_yn_cd', title: '맨홀존재여부코드' },
+ // { id: 'swage_mhl_ftre_smbol_cd', title: '하수맨홀지형지물부호코드' },
+ { id: 'swage_mhl_mng_no', title: '하수맨홀관리번호' },
+ { id: 'drtn_angl', title: '방향각도(°)' },
+]
+export const stofcbrCol2 = [
+ // { id: 'ftre_smbol_cd', title: '지형지물부호코드' },
+ { id: 'pbadmsEmdCd', title: '시설관리번호' },
+ // { id: 'pbadms_emd_cd', title: '행정읍면동코드' },
+ { id: 'mapshtNo', title: '도엽번호' },
+ // { id: 'mng_inst_cd', title: '관리기관코드' },
+ { id: 'instlYmd', title: '설치일자' },
+ // { id: 'fclty_shp_cd', title: '시설물형태코드' },
+ { id: 'worflwWallHgt', title: '월류벽높이(m)' },
+ // { id: 'mhl_exst_yn_cd', title: '맨홀존재여부코드' },
+ // { id: 'swage_mhl_ftre_smbol_cd', title: '하수맨홀지형지물부호코드' },
+ { id: 'swageMhlMngNo', title: '하수맨홀관리번호' },
+ { id: 'drtnAngl', title: '방향각도(°)' },
+]
+
+// 중점우수토실 측정지점
+export const untrtSwgRainCol1 = [
+ { id: 'manage_no', title: '관리번호' },
+ { id: 'swr_ppl_eqp_nm', title: '처리구역' },
+ { id: 'swr_ppl_trt_nm', title: '처리분구' },
+ { id: 'addr', title: '인근주소' },
+ { id: 'chmbr_xcnts', title: '토실 위도' },
+ { id: 'chmbr_ydnts', title: '토실 경도' }
+];
+
+// 중점우수토실 측정지점 시설현황
+export const untrtSwgRainCol2 = [
+ { id: 'flwmtr_mesure_tp_etc', title: '구분' },
+ { id: 'discharge_pipe_spec', title: '방류관로 규격(m)' },
+ { id: 'swr_ppl_eqp_ar', title: '배수구역 면적(m²)' },
+ { id: 'swr_trt_popl', title: '하수처리 인구(인)' },
+ { id: 'screen_instl_at', title: '스크린설치 여부' },
+ { id: 'weir_hg', title: '위어 높이(m)' },
+ { id: 'weir_lt', title: '위어 길이(m)' }
+];
+
+// 중점우수토실 강우정보 (id값 틀릴 수 있음)
+export const untrtSwgRainCol3 = [
+ { id: 'rainBeginDt', title: '강우시작일시' },
+ { id: 'rainEndDt', title: '강우종료일시' },
+ { id: 'precdngDry', title: '선행건기(h)' },
+ { id: 'rainInfo', title: '강우정보' },
+ { id: 'rainFall', title: '누적강우량(mm)' },
+ { id: 'cntncTime', title: '지속시간(h)' },
+ { id: 'rainIn', title: '강우강도(mm/h)' }
+];
+
+// 중점우수토실 측정정보 (id값 틀릴 수 있음)
+export const untrtSwgRainCol4 = [
+ { id: 'mesureBeginDt', title: '측정시작일시' },
+ { id: 'mesureEndDt', title: '측정종료일시' },
+ { id: 'mesureIntrvl', title: '측정간격(분)' },
+ { id: 'mesureMhrlsInstlLc', title: '측정기기 설치위치' },
+ { id: 'flwmtrCombined', title: '유량계 종류 및 모델명' }, // 합쳐진 컬럼
+ { id: 'qltwtrBeginDt', title: '채수시작일시' },
+ { id: 'qltwtrEndDt', title: '채수종료일시' },
+ { id: 'qltwtrCo', title: '채수횟수' }
+];
+
+// 중점우수토실 수량/수질측정 정보
+export const untrtSwgRainCol5 = [
+ { id: 'odr', title: '회차' },
+ { id: 'mesureDt', title: '측정일자' },
+ { id: 'mesureQy', title: '수량(m)' },
+ { id: 'mesureBod', title: 'BOD(mg/L)' },
+ { id: 'mesureToc', title: 'TOC(mg/L)' },
+ { id: 'mesureLoad', title: '오염부하량(kg)' }
+];
+
+// 🎯 날짜 필드들 (yyyymmdd -> yyyy년 mm월 dd일)
+export const dateFields = [
+ 'instl_ymd', 'last_drdgn_ymd', 'cmcn_ymd', 'oprtng_strt_ymd', 'clsg_ymd',
+ 'mesure_begin_dt', 'mesure_end_dt', 'qltwtr_begin_dt', 'qltwtr_end_dt',
+ 'rain_begin_dt', 'rain_end_dt', 'mesureDt',
+ // 🎯 camelCase 버전 추가
+ 'instlYmd', 'lastDrdgnYmd', 'cmcnYmd', 'oprtngStrtYmd', 'clsgYmd',
+ 'mesureBeginDt', 'mesureEndDt', 'qltwtrBeginDt', 'qltwtrEndDt',
+ 'rainBeginDt', 'rainEndDt'
+];
+
+// 🎯 연월 필드들 (yyyymm -> yyyy년 m월)
+export const yearMonthFields = ['aplcnYm',];
+
+// 🎯 날짜시간 필드들 (yyyy-mm-dd hh:mm:ss -> yyyy년 m월 d일 hh:mm)
+export const dateTimeFields = ['regDt',];
+
+// 🎯 숫자 필드들 (천 단위 구분자)
+export const numberFields = [
+ 'pdmt', 'prlg', 'avg_grdn', 'drtw_mltv_area', 'excln_mltv_area', 'tmpt_dpth', 'scend_dpth', 'trfln_cnt', 'vrtc_len', 'wdth_len',
+ 'fclt_cpct', 'plln_area', 'prcs_zone_area_sum', 'swtrmt_ppltn_cnt', 'stty_crtr_bod', 'stty_crtr_toc', 'stty_crtr_ss', 'stty_crtr_tn', 'stty_crtr_tph', 'stty_crtr_clbcl_cnt',
+ 'swage_mh_diam', 'wdth_len', 'vrtc_len', 'altd_vl', 'dpthlVl',
+ 'plln_area', 'daily_prcs_cpct', 'max_impnd_cpct', 'altd_vl', 'wtlv_vl', 'excln_wpmp_ablt',
+ 'worflw_wall_hgt',
+ 'swr_ppl_eqp_ar', 'swr_trt_popl', 'weir_hg', 'weir_lt',
+ 'precdng_dry', 'rain_fall', 'cntnc_time', 'rain_in',
+ 'mesure_intrvl', 'qltwtr_co', 'mesureQy', 'mesureBod', 'mesureToc', 'mesureLoad',
+ // 🎯 camelCase 버전 추가
+ 'avgGrdn', 'drtwMltvArea', 'exclnMltvArea', 'tmptDpth', 'scendDpth', 'trflnCnt', 'vrtcLen', 'wdthLen',
+ 'fcltCpct', 'pllnArea', 'prcsZoneAreaSum', 'swtrmtPpltnCnt', 'sttyCltrBod', 'sttyCltrToc', 'sttyCltrSs', 'sttyCltrTn', 'sttyCltrTph', 'sttyCltrClbclCnt',
+ 'swageMhDiam', 'altdVl', 'dpthlVl',
+ 'dailyPrcsCpct', 'maxImpndCpct', 'wtlvVl', 'exclnWpmpAblt',
+ 'worflwWallHgt',
+ 'swrPplEqpAr', 'swrTrtPopl', 'weirHg', 'weirLt',
+ 'precdngDry', 'rainFall', 'cntncTime', 'rainIn',
+ 'mesureIntrvl', 'qltwtrCo', 'rnysnFvlc', 'clarFvlc'
+];
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/MsSwagePpl.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/MsSwagePpl.tsx
new file mode 100644
index 000000000..38b0c25d6
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/MsSwagePpl.tsx
@@ -0,0 +1,100 @@
+'use client'
+import { VerticalTable } from '@/components/ui/verticalTable';
+import React, { useState, useEffect } from 'react'
+import InputSection from '../InputSection';
+import { handleInputChange } from '../common';
+
+// 하수관로
+const inputColumn = [
+ { id: "instlMbdyCd", title: "설치주제", type: "select", options: ["BTL", "재정사업"] },
+ { id: "swtrmtZoneCd", title: "처리구역", type: "input" },
+ { id: "mltvZoneNm", title: "배수구역", type: "input" },
+ { id: "mltvDtdvNm", title: "배수분구", type: "input" },
+ { id: "lineCd", title: "지선/간선", type: "select", options: ["지선", "간선"] },
+ { id: "floCd", title: "흐름방식", type: "select", options: ["자연유하", "압송"] },
+ { id: "layCd", title: "매설위치", type: "select", options: ["도로", "하상"] },
+];
+
+const MsSwagePpl = ({ featureData, onSaveClick }: { featureData: any, onSaveClick?: () => void }) => {
+ const [repairData, setRepairData] = useState([
+ { year: "2025", type: "개대체" },
+ { year: "2025", type: "보수" },
+ ]);
+ const [cleaningData, setCleaningData] = useState([
+ { year: "2025", type: "청소" },
+ { year: "2025", type: "준설" },
+ ]);
+ const [inspectionData, setInspectionData] = useState([
+ { year: "2025", type: "관로기술진단" },
+ { year: "2025", type: "관로기술진단" },
+ ]);
+ const dataMap = {
+ repair: { data: repairData, setData: setRepairData },
+ cleaning: { data: cleaningData, setData: setCleaningData },
+ inspection: { data: inspectionData, setData: setInspectionData },
+ };
+
+ const [formData, setFormData] = useState({});
+
+ // featureData가 변경될 때 formData 초기화
+ useEffect(() => {
+ if (featureData) {
+ setFormData(featureData);
+ }
+ }, [featureData]);
+
+ // 폼 데이터가 변경될 때 호출될 핸들러
+ const handleFormDataChange = (newFormData: any) => {
+ setFormData(newFormData);
+ };
+
+ // 저장 버튼 클릭 시 최신 formData를 부모에게 전달
+ const handleSaveClick = () => {
+ if (onSaveClick) {
+ // 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
+ onSaveClick();
+ }
+ };
+
+
+ return (
+ <>
+
+ handleInputChange(section, index, field, value, dataMap)}
+ />
+ handleInputChange(section, index, field, value, dataMap)}
+ />
+ handleInputChange(section, index, field, value, dataMap)}
+ />
+ >
+ )
+}
+
+export default MsSwagePpl
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/Ssc.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/Ssc.tsx
new file mode 100644
index 000000000..8eb1b23bf
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/Ssc.tsx
@@ -0,0 +1,237 @@
+// 우수토실
+import { UiModal, UiTable } from '@common/business_components/ui';
+import { Button, TableHead, TableRow } from '@common/components/ui';
+import React, { useState, useEffect, useCallback } from 'react';
+import { untrtSwgRainCol3, untrtSwgRainCol4, untrtSwgRainCol5 } from '../common/table';
+import { VerticalTable } from '@/components/ui/verticalTable';
+import { getData } from "@/components/lib/api";
+import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
+
+const inputColumn = [
+ { id: "prrtymngYn", title: "중점여부", type: "select", options: ["중점우수토실", "우수토실"] },
+ { id: "swtrmtZoneCd", title: "처리구역", type: "input" },
+];
+
+const Ssc = ({ featureData, isMainSsc, rainMeasureData, onSaveClick }: {
+ featureData: any,
+ isMainSsc?: boolean,
+ rainMeasureData?: any,
+ onSaveClick?: () => void
+}) => {
+ const [isModalOpen, setIsModalOpen] = useState(false);
+ const [isDataLoaded, setIsDataLoaded] = useState(false);
+ const [formData, setFormData] = useState({});
+ const [mntrngsData, setMntrngsData] = useState([]); // 수량/수질 측정 정보
+ const [selectedRowIndex, setSelectedRowIndex] = useState(-1);
+
+ // console.log('featureData data received:', featureData); // 추가 데이터 확인용
+ // console.log('rainMeasureData received:', rainMeasureData); // 추가 데이터 확인용
+
+ const openModal = () => {
+ setIsModalOpen(true);
+ };
+
+ const closeModal = () => {
+ setIsModalOpen(false);
+ if (!isDataLoaded) {
+ setTimeout(() => setIsDataLoaded(true), 100);
+ }
+ };
+
+ // featureData가 변경될 때 formData 초기화
+ useEffect(() => {
+ if (featureData) {
+ setFormData(featureData);
+ setMntrngsData([]);
+ }
+ }, [featureData]);
+
+ // 폼 데이터가 변경될 때 호출될 핸들러
+ const handleFormDataChange = (newFormData: any) => {
+ setFormData(newFormData);
+ };
+
+ // 저장 버튼 클릭 시 최신 formData를 부모에게 전달
+ const handleSaveClick = () => {
+ if (onSaveClick) {
+ // 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
+ onSaveClick();
+ }
+ };
+
+ // 테이블 셀 클릭 핸들러 추가
+ const handleCellClick = async (index: number | undefined, headId: string) => {
+ if (index !== undefined && rainMeasureData) {
+ const data = await fetchMntrngsData(rainMeasureData[index].adstDstrCd, rainMeasureData[index].manageNo);
+
+ setMntrngsData(data);
+ setSelectedRowIndex(index);
+ }
+ };
+
+ // 🎯 추가 데이터 API 호출 함수 (독립적으로 실행)
+ const fetchMntrngsData = useCallback(async (adstDstrCd: string, manageNo: string) => {
+ if (!adstDstrCd || !manageNo) {
+ console.warn('추가 데이터 호출 실패: 필수 매개변수 누락', { adstDstrCd, manageNo });
+ return [];
+ }
+
+ try {
+ const queryParams = new URLSearchParams({
+ pageable: `{}`,
+ });
+
+ console.log(`SSC 추가 데이터 API 호출 시작: v1/onsemiro/swgRain?${queryParams.toString()}`);
+
+ const result = await getData(`v1/onsemiro/swgRain/${adstDstrCd}/${manageNo}/mntrngs?${queryParams.toString()}`);
+
+ console.log('SSC 추가 데이터 API 호출 성공:', result);
+
+ // 🎯 result가 페이지네이션 객체인 경우 content 배열 추출
+ let dataArray: any[] = [];
+ if (result && typeof result === 'object' && 'content' in result && Array.isArray(result.content)) {
+ dataArray = result.content;
+ } else if (Array.isArray(result)) {
+ dataArray = result;
+ } else {
+ console.warn('예상치 못한 API 응답 형식:', result);
+ return [];
+ }
+
+ // 🎯 각 아이템을 전처리하여 반환
+ const processedDataArray = dataArray.map((data: any) => {
+ // 🎯 formatDisplayData로 기본 포맷팅 적용
+ const formattedItem = formatDisplayData(data);
+
+ // 🎯 추가 데이터 조합
+ return {
+ ...formattedItem,
+ };
+ });
+
+ console.log('processedDataArray', processedDataArray);
+
+ return processedDataArray;
+ } catch (error) {
+ console.error('추가 데이터 로딩 실패:', error);
+ return [];
+ }
+ }, []);
+
+ const renderModalBody = () => (
+
+ {/* 강우정보 테이블 */}
+
+
+ {/* 측정정보 테이블 */}
+
+ {/* 커스텀 헤더 */}
+
+ 수량
+ 수질
+
+
+ 측정시작일시
+ 측정종료일시
+ 측정간격(분)
+ 측정기기설치위치
+ 유량계 종류 및 모델명
+ 채수시작일시
+ 채수종료일시
+ 채수횟수
+
+
+
+ {/* 수량/수질측정 정보 테이블 */}
+
+
+ )
+
+ return (
+
+ {!isMainSsc && (
+
+ )}
+
+ {isMainSsc && (
+
+
+
중점우수토실 운영정보
+
+
+
+
+
+ )}
+
+ )
+}
+
+export default Ssc
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/SwtrmtFclt.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/SwtrmtFclt.tsx
new file mode 100644
index 000000000..50d6d5606
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/SwtrmtFclt.tsx
@@ -0,0 +1,49 @@
+import Modal from '@/components/ui/modal';
+import { VerticalTable } from '@/components/ui/verticalTable';
+import { UiTable } from '@common/business_components/ui';
+import { Button, TableCell } from '@common/components/ui';
+import React, { useState } from 'react'
+
+// 하수처리시설
+const headList = [
+ { id: "title", title: "하수도정비 기본계획보고서" },
+ { id: "cad", title: "하수도대장 평면도" },]
+const modalHeadList = [
+ { id: "no", title: "번호" },
+ { id: "year", title: "승인연도" },
+ { id: "cad", title: '평면도' },
+ { id: "fileNm", title: "파일명" },
+ { id: "date", title: "입력시간" },
+]
+
+const SwtrmtFclt = () => {
+ const [isModalOpen, setIsModalOpen] = useState(false);
+ const [modalTitle, setModalTitle] = useState('');
+ const openModal = (title: string) => {
+ setIsModalOpen(true);
+ setModalTitle(title)
+ };
+ const closeModal = () => {
+ setIsModalOpen(false);
+ };
+ return (
+
+
openModal('하수도정비 기본계획보고서')}>보고서,
+ cad: ,
+ }} headName='디지털 자료관 연계정보' tableData={[]} headlist={headList} pageSize={20} total={0} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
+ throw new Error("Function not implemented.");
+ }}>
+
+
+
+
+
+
+ )
+}
+
+export default SwtrmtFclt
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/chart/aplcnYms.ts b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/aplcnYms.ts
new file mode 100644
index 000000000..81daed0ed
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/aplcnYms.ts
@@ -0,0 +1,254 @@
+import {useState, useEffect} from 'react';
+import { getData, getDcData } from '@/components/lib/api';
+import moment from "moment";
+
+export type TInftwtAnls = {
+ inftwtAnlsSn:number;
+ aplcnYm: string;
+ enoCd: string;
+ ctpvCd: string;
+ sggCd: string;
+ swageTmplntCd: string;
+ swageTmplntNm: string;
+ swtrmtZoneCd: string;
+ swtrmtZoneNm: string;
+ atflCd: string;
+ atflId: string;
+ atflInpNm: string;
+ atflHrPttnNm: string;
+ atflMpngNm: string;
+ atflOilqNm: string;
+ atflNm: string;
+ drtwSwtcRt:number;
+ anlsInfo: string;
+ scsYn: string;
+};
+export type TInftwtAnlsRslt = {
+ inftwtAnlsSn: number;
+ pplMngNo: string;
+ anlsTm: string;
+ predcOilq:number;
+}
+export type TRdiiAnls = {
+ rainInfwtAnlsSn:number;
+ aplcnYm: string;
+ enoCd: string;
+ ctpvCd: string;
+ sggCd: string;
+ swageTmplntCd: string;
+ swageTmplntNm: string;
+ swtrmtZoneCd: string;
+ swtrmtZoneNm: string;
+ atflCd: string;
+ atflId: string;
+ atflInpNm: string;
+ atflHrPttnNm: string;
+ atflMpngNm: string;
+ atflRainNm: string;
+ atflNm: string;
+ drtwSwtcRt:number;
+ anlsInfo: string;
+ scsYn: string;
+ srcNm: string; // 출처이름
+};
+export type TRdiiAnlsRslt = {
+ rainInfwtAnlsSn: number;
+ pplMngNo: string;
+ anlsTm: string;
+ predcOilq:number;
+ minq:number;
+}
+export type TOilqData = {
+ inftwtAnlsSn: number; // 침입수분석 일련번호
+ pplMngNo: string; // 관로관리번호
+ mtrngDt: string; // 계측일시
+ oilq: number; // 유량
+}
+
+const getOptionsAplcnYm = (yyyymms: string[]): { text: string; val: string, hidden?: boolean }[] => {
+ const yyyymms1 = yyyymms.map(dateStr => {
+ const year = dateStr.slice(0, 4);
+ const month = dateStr.slice(4, 6);
+ return {
+ text: `${year}-${month}`,
+ val: dateStr
+ };
+ });
+ yyyymms1.unshift({ val: '0', text: '선택', hidden: true });
+ return yyyymms1;
+};
+const selectAplcnYms = async(gubun:string) => { // 상수사용월
+ try {
+ const queryString = '';
+ const result = await getData(`v1/${gubun}/aplcnYm${queryString ? `?${queryString}` : ''}`);
+ if (result && result.length > 0) {
+ console.log("selectAplcnYms", result);
+ return getOptionsAplcnYm(result);
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+
+export const useAplcnYms = (gubun:string) => {
+ const [data, setData] = useState<{ text: string; val: string }[]>([]);
+
+ useEffect(() => {
+ const fetch = async (gubun:string) => {
+ const result = await selectAplcnYms(gubun);
+ if (result) setData(result);
+ };
+ fetch(gubun);
+ }, [gubun]);
+
+ return data;
+};
+export const getOptionsInftwtAnlsInfo = (anlsArr: TInftwtAnls[]): { text: string; val: number, hidden?: boolean }[] => {
+ const options = anlsArr.map(anls => ({
+ text: anls.anlsInfo,
+ val: anls.inftwtAnlsSn,
+ }));
+ options.unshift({ val: 0, text: '선택', hidden: true });
+ return options;
+};
+
+export const selectInftwtAnls = async(aplcnYm:String) => { // 침입수분석
+ try {
+ const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : '';
+ const result = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
+ if (result && result.numberOfElements > 0) {
+ console.log("selectInftwtAnls", result.content);
+ return result.content;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+export const getChartDataInftwtAnlsRslt = (arr: TInftwtAnlsRslt[]): { label: string; val: number }[] => {
+ const options = arr.map(anlsRslt => ({
+ label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("HH시"),
+ val: anlsRslt.predcOilq,
+ }));
+ return options;
+};
+export const selectInftwtAnlsRslt = async(inftwtAnlsSn:number, pplMngNo:string) => { // 침입수분석 결과
+ try {
+ if ((inftwtAnlsSn === undefined || inftwtAnlsSn === 0) || !pplMngNo) {
+ console.warn("inftwtAnlsSn or pplMngNo is not provided");
+ return [];
+ }
+ const result = await getData(`v1/inftwtAnlsRslt/ppl/${inftwtAnlsSn}/${pplMngNo}`);
+ if (result && result.numberOfElements > 0) {
+ console.log("selectInftwtAnlsRslt", result.content);
+ return result.content;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+export const getChartDataOilq = (arr: TOilqData[]): { label: string; val: number }[] => {
+ const options = arr.map(anlsRslt => ({
+ label: anlsRslt.mtrngDt,
+ val: anlsRslt.oilq,
+ }));
+ return options;
+};
+export const selectOilq = async(inftwtAnlsSn:number, pplMngNo:string) => { // 유량
+ try {
+ if ((inftwtAnlsSn === undefined || inftwtAnlsSn === 0) || !pplMngNo) {
+ console.warn("inftwtAnlsSn or pplMngNo is not provided");
+ return [];
+ }
+ const result = await getData(`v1/inftwtAnlsRslt/oilqPpl/${inftwtAnlsSn}/${pplMngNo}`);
+ if (result && result.numberOfElements > 0) {
+ console.log("selectOilq", result.content);
+ return result.content;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+export const selectPplInftwtQty = async(inftwtAnlsSn:number, pplMngNo:string) => { // 침입수량
+ try {
+ if ((inftwtAnlsSn === undefined || inftwtAnlsSn === 0) || !pplMngNo) {
+ console.warn("inftwtAnlsSn or pplMngNo is not provided");
+ return [];
+ }
+ const result = await getData(`v1/inftwtAnlsRslt/pplInftwtQty/${inftwtAnlsSn}/${pplMngNo}`);
+ if (result.length > 0) {
+ console.log("selectPplInftwtQty", result);
+ return result[0].avg_day_flow;
+ } else {
+ return 0; // 데이터가 없을 경우 0 반환
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+//----------
+export const selectPplRdiiQty = async(rainInfwtAnlsSn:number, pplMngNo:string) => { // rdii값
+ try {
+ if ((rainInfwtAnlsSn === undefined || rainInfwtAnlsSn === 0) || !pplMngNo) {
+ console.warn("rainInfwtAnlsSn or pplMngNo is not provided");
+ return [];
+ }
+ const result = await getData(`v1/rdiiAnlsRslt/pplRdiiQty/${rainInfwtAnlsSn}/${pplMngNo}`);
+ if (result?.sustaintime > 0) {
+ console.log("selectPplRdiiQty", result);
+ return result;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+
+export const getOptionsRdiiAnlsInfo = (anlsArr: TRdiiAnls[]): { text: string; val: number, hidden?: boolean }[] => {
+ const options = anlsArr.map(anls => ({
+ text: anls.anlsInfo,
+ val: anls.rainInfwtAnlsSn,
+ }));
+ options.unshift({ val: 0, text: '선택', hidden: true });
+ return options;
+};
+
+export const selectRdiiAnls = async(aplcnYm:String) => { // 침입수분석
+ try {
+ const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : '';
+ const result = await getData(`v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
+ if (result && result.numberOfElements > 0) {
+ console.log("selectRdiiAnls", result.content);
+ return result.content;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
+export const getChartDataRdiiAnlsRslt = (arr: TRdiiAnlsRslt[]): { label: string; val: number }[] => {
+ const options = arr.map(anlsRslt => ({
+ label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
+ val: anlsRslt.predcOilq,
+ }));
+ return options;
+};
+export const getChartDataRdiiAnlsRsltMinq = (arr: TRdiiAnlsRslt[]): { label: string; val: number }[] => {
+ const options = arr.map(anlsRslt => ({
+ label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
+ val: anlsRslt.minq,
+ }));
+ return options;
+};
+export const selectRdiiAnlsRslt = async(rainInfwtAnlsSn:number, pplMngNo:string) => { // 침입수분석 결과
+ try {
+ if ((rainInfwtAnlsSn === undefined || rainInfwtAnlsSn === 0) || !pplMngNo) {
+ console.warn("RdiiAnlsSn or pplMngNo is not provided");
+ return [];
+ }
+ const result = await getData(`v1/rdiiAnlsRslt/ppl/${rainInfwtAnlsSn}/${pplMngNo}`);
+ if (result && result.numberOfElements > 0) {
+ console.log("selectRdiiAnlsRslt", result.content);
+ return result.content;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+};
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/chart/infilChart.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/infilChart.tsx
new file mode 100644
index 000000000..ed39d9548
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/infilChart.tsx
@@ -0,0 +1,280 @@
+'use client'
+import { CHART_FORM, type ChartConfig, MainChart, UiModal } from "@common/business_components";
+import { SelectBox } from '@common/business_components/ui';
+import { Button, Input, Label } from '@common/components';
+import React, { useEffect, useState } from 'react';
+import moment from "moment";
+
+import type { TInftwtAnls, TOilqData } from './aplcnYms';
+import * as fn from './aplcnYms';
+import { useInfilChartModalStore } from '../chartModalStore'; // 모달 상태 관리 스토어
+type ModalOpenProp = {
+ pplMngNo?: string, // 관로관리번호
+}
+type DataType = { label: string; val: number };
+
+const InfilChart = ({ pplMngNo }: ModalOpenProp) => {
+ const { isOpen: isModalOpen, setIsOpen: setIsModalOpen } = useInfilChartModalStore(); // 모달 상태 관리 스토어
+ const [popupOpen, setPopupOpen] = React.useState(false); // 조회조건팝업
+ const buttonRef = React.useRef(null); // 버튼 참조
+ const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
+ const [selectedAplcnYm, setSelectedAplcnYm] = useState("");
+ const [inftwtAnlss, setInftwtAnlss] = useState([]);
+ const [inftwtAnlsInfos, setInftwtAnlsInfos] = useState([{ val: 0, text: '선택' }]); // 침입수분석정보 options
+ const [inftwtAnls, setInftwtAnls] = useState(null); // 침입수분석정보
+ const [selectedInftwtAnls, setSelectedInftwtAnls] = useState(0); // 침입수분석 정보 선택시 사용
+ const [chartData, setChartData] = useState<{ chartData1: DataType[]; chartData2: DataType[] }>({
+ chartData1: [], chartData2: [],
+ });
+ const [inftwtQty, setInftwtQty] = useState(0); // 침입수량
+ const aplcnYms = fn.useAplcnYms('inftwtAnlsRslt'); // 상수사용월 데이터 가져오기
+
+ pplMngNo = "L" + pplMngNo; // inp파일에 하수관로와 맨홀의 번호가 같으면 분석 오류가 발행하여
+ const openPopup = () => {
+ if (buttonRef.current) {
+ const rect = buttonRef.current.getBoundingClientRect(); // 버튼 위치 계산
+ setPopupPosition({
+ top: rect.bottom + window.scrollY, // 버튼 아래쪽
+ left: rect.left + window.scrollX, // 버튼 왼쪽
+ });
+ }
+ setPopupOpen(true); // 팝업 열기
+ };
+
+ const chartForm = CHART_FORM.LINE;
+ const chartConfig = {
+ chartData1: { label: '순오수량(m³/h)', color: "red", },
+ chartData2: { label: '실측하수량(m³/h)', color: "orange", }
+ } as ChartConfig;
+
+ useEffect(() => {
+ if (isModalOpen === false) {
+ setPopupOpen(true); // 모달이 닫힐 때 조회조건팝업은 열어두기
+ setSelectedAplcnYm(""); // 상수사용월 초기화
+ setInftwtAnlss([]); // 침입수분석 초기화
+ setInftwtAnlsInfos([{ val: 0, text: '선택' }]); // 침입수분석정보 초기화
+ setInftwtAnls(null); // 침입수분석정보 초기화
+ setSelectedInftwtAnls(0); // 침입수분석 일련번호 초기화
+ setChartData({ chartData1: [], chartData2: [], }); // 차트 데이터 초기화
+ setInftwtQty(0); // 침입수량 초기화
+ }
+ }, [isModalOpen]);
+
+ // 상수사용월 변경 핸들러
+ const handleAplcnYmChange = async (val: string | number) => {
+ const selectedValue = String(val);
+ console.log("선택된 상수사용월:", selectedValue);
+
+ setSelectedAplcnYm(selectedValue);
+
+ // 즉시 관련 상태 초기화
+ setInftwtAnls(null);
+
+ // 빈 값이면 초기화만 하고 종료
+ if (!selectedValue || selectedValue === "0" || selectedValue === "") {
+ setInftwtAnlsInfos([{ val: 0, text: '선택' }]);
+ return;
+ }
+
+ // API 호출
+ try {
+ const data = await fn.selectInftwtAnls(selectedValue);
+ setInftwtAnlss(data ?? []);
+ setInftwtAnlsInfos(fn.getOptionsInftwtAnlsInfo(data));
+ } catch (error) {
+ console.error("selectInftwtAnls 에러:", error);
+ setInftwtAnlss([]);
+ setInftwtAnlsInfos([{ val: 0, text: '선택' }]);
+ }
+ setSelectedInftwtAnls(0);
+ };
+
+ // 분석정보 변경 핸들러
+ const handleInftwtAnlsSnChange = (val: string | number) => {
+ const selectedValue = Number(val);
+ setSelectedInftwtAnls(selectedValue);
+
+ // 선택된 침입수분석 정보에 대한 처리 로직
+ if (selectedValue === 0) {
+ setInftwtAnls(null);
+ return;
+ }
+
+ const selectedAnls = inftwtAnlss.find(anls => anls.inftwtAnlsSn === selectedValue);
+ if (selectedAnls) {
+ setInftwtAnls(selectedAnls);
+ }
+ };
+
+ const closePopup = () => { // 팝업 닫기
+
+ fn.selectInftwtAnlsRslt(selectedInftwtAnls, pplMngNo).then((data) => {// 침입수분석 결과 조회
+ const rsltData = fn.getChartDataInftwtAnlsRslt(data ?? []);
+ setChartData(prev => ({
+ ...prev,
+ chartData1: rsltData // 침입수분석결과
+ }));
+ });
+ fn.selectOilq(selectedInftwtAnls, pplMngNo).then((data) => {// 유량 조회
+ const rsltData = fn.getChartDataOilq(data ?? []);
+ setChartData(prev => ({
+ ...prev,
+ chartData2: rsltData // 유량
+ }));
+ }).catch((err) => {
+ console.error("selectOilq 에러:", err);
+ setChartData(prev => ({
+ ...prev,
+ chartData2: [] // 유량 데이터 초기화
+ }));
+ });
+ fn.selectPplInftwtQty(selectedInftwtAnls, pplMngNo).then((data) => {// 침입수량 조회
+ if (data > 0) {
+ setInftwtQty(data);
+ }
+ });
+ setPopupOpen(false);
+ };
+
+ const renderBody = () => (
+ <>
+ 침입수분석결과
+
+
+
+
+ {/* 상수사용량 적용연월 */}
+
+
상수사용량 적용연월
+
+
+ {(selectedAplcnYm) ? moment(selectedAplcnYm, "YYYYMM").format("YYYY-MM") : ""}
+
+
+
+ {/* 침입수량 분석결과 */}
+
+
침입수량 분석결과
+
+ {inftwtQty}
+ m³/d
+
+
+
+ {/* 차트 */}
+
+
+
+
+ {popupOpen && (
+
+
침입수분석 입력현황
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
)}
+ {/* */}
+ >
+ )
+
+ return (
+
+ )
+}
+
+export default React.memo(InfilChart);
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/chart/rdiiChart.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/rdiiChart.tsx
new file mode 100644
index 000000000..33b65ace0
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/chart/rdiiChart.tsx
@@ -0,0 +1,266 @@
+'use client'
+import { CHART_FORM, type ChartConfig, MainChart, UiModal } from "@common/business_components";
+import { SelectBox } from '@common/business_components/ui';
+import { Button, Input, Label } from '@common/components';
+import React, { useEffect, useState } from 'react';
+import moment from "moment";
+
+import type { TRdiiAnls, TRdiiAnlsRslt, TOilqData } from './aplcnYms';
+import * as fn from './aplcnYms';
+import { useRdiiChartModalStore } from '../chartModalStore'; // 모달 상태 관리 스토어
+type ModalOpenProp = {
+ pplMngNo: string, // 관로관리번호
+}
+type DataType = {label: string; val: number};
+
+const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
+ const { isOpen: isModalOpen, setIsOpen: setIsModalOpen } = useRdiiChartModalStore(); // 모달 상태 관리 스토어
+ const [popupOpen, setPopupOpen] = React.useState(false); // 조회조건팝업
+ const buttonRef = React.useRef(null); // 버튼 참조
+ const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
+ const [aplcnYm, setAplcnYm] = useState("");
+ const [rdiiAnlss, setRdiiAnlss] = useState([]);
+ const [rdiiAnlsInfos, setRdiiAnlsInfos] = useState([{ val: 0, text: '선택' }]); // 강우유입수분석정보 options
+ const [rdiiAnls, setRdiiAnls] = useState(null); // 강우유입수분석정보
+ const [rainInfwtAnlsSn, setRainInfwtAnlsSn] = useState(0); // 강우유입수분석 정보 선택시 사용
+ const [chartData, setChartData] = useState<{ chartData1: DataType[]; }>({
+ chartData1: [], //chartData2: [],
+ });
+ const [rdiiQty, setRdiiQty] = useState(0); // 강우유입수량
+ const [totalVolume, setTotalVolume] = useState(0); // 총체적 m³/mm
+ const aplcnYms = fn.useAplcnYms('rdiiAnlsRslt'); // 상수사용월 데이터 가져오기
+ pplMngNo = "L"+pplMngNo; // "L13101003";
+ console.log("pplMngNo", pplMngNo);
+ const openPopup = () => {
+ if (buttonRef.current) {
+ const rect = buttonRef.current.getBoundingClientRect(); // 버튼 위치 계산
+ setPopupPosition({
+ top: rect.bottom + window.scrollY, // 버튼 아래쪽
+ left: rect.left + window.scrollX, // 버튼 왼쪽
+ });
+ }
+ setPopupOpen(true); // 팝업 열기
+ };
+
+ const chartForm = CHART_FORM.LINE;
+ const chartConfig = {
+ chartData1: { label: 'RDII(m³/h)', color: "red", },
+ //chartData2: { label: '순오수량(m³/h)', color: "orange", },
+ } as ChartConfig;
+
+ useEffect(() => {
+ if (isModalOpen === false) {
+ setPopupOpen(true); // 모달이 닫힐 때 팝업은
+ setAplcnYm(""); // 상수사용월 초기화
+ setRdiiAnlss([]); // 강우유입수분석 초기화
+ setRdiiAnlsInfos([{ val: 0, text: '선택' }]); // 강우유입수분석정보 초기화
+ setRdiiAnls(null); // 강우유입수분석정보 초기화
+ setRainInfwtAnlsSn(0); // 강우유입수분석 일련번호 초기화
+ setChartData({chartData1: [], }); // 차트 데이터 초기화
+ setRdiiQty(0); // 강우유입수량 초기화
+ setTotalVolume(0); // 총체적 m³/mm 초기화
+ }
+ }, [isModalOpen]);
+
+ // 상수사용월 변경시 분석 정보 리스트 가져오기
+ useEffect(() => {
+ // aplcnYm이 비어있거나 "0"이면 API 호출하지 않음
+ if (!aplcnYm || aplcnYm === "0" || aplcnYm === "") {
+ setRainInfwtAnlsSn(0); // 초기화
+ setRdiiAnlsInfos([]);
+ return;
+ }
+ console.log(moment(aplcnYm).format("YYYY-MM"));
+ fn.selectRdiiAnls(aplcnYm)
+ .then((data) => {
+ setRdiiAnlss(data ?? []); // 선택한 월의 분석성공한 RDII분석데이터[]
+ setRdiiAnlsInfos(fn.getOptionsRdiiAnlsInfo(data));
+ setRdiiAnls(null); // 오수전환율 이후 초기화
+ setRainInfwtAnlsSn(0); // 초기화
+ })
+ .catch((error) => {
+ console.error("selectrdiiAnls 에러:", error);
+ setRdiiAnlss([]);
+ setRdiiAnlsInfos([]);
+ });
+ }, [aplcnYm]);
+
+ // 값 표시
+ useEffect(() => {
+ // 선택된 강우유입수분석 정보에 대한 처리 로직
+ if (rainInfwtAnlsSn === 0) return;
+ const selectedAnls = rdiiAnlss.find(anls => anls.rainInfwtAnlsSn === rainInfwtAnlsSn);
+ if (selectedAnls) {
+ setRdiiAnls(selectedAnls);
+ }
+ }, [rainInfwtAnlsSn]);
+
+ const closePopup = () => { // 팝업 닫기
+ fn.selectRdiiAnlsRslt(rainInfwtAnlsSn, pplMngNo).then((data) => {// 강우유입수분석 결과 조회
+ const rsltData1 = fn.getChartDataRdiiAnlsRslt(data ?? []);
+ //const rsltData2 = fn.getChartDataRdiiAnlsRsltMinq(data ?? []);
+ setChartData(prev => ({
+ chartData1: rsltData1, // 순오수량(m³/h)
+ // chartData2: rsltData2 // RDII(m³/h) 강우유입수분석결과
+ }));
+ });
+ fn.selectPplRdiiQty(rainInfwtAnlsSn, pplMngNo).then((data) => {// 강우유입수량 조회
+ setRdiiQty(Math.round(data.rdiih*24)); // cmd: m³/d 단위로 변환
+ if (data.raintotal && data.rainTotal !== 0) {
+ setTotalVolume(Math.round(data.rdiih * data.sustaintime / data.raintotal)); // 총체적 m³/mm
+ }
+ });
+ setPopupOpen(false);
+ };
+
+ const renderBody = () => (
+ <>
+ RDII분석결과
+
+
+
+
+ {/* 상수사용량 적용연월 */}
+
+
상수사용량 적용연월
+
+
+ {(aplcnYm)? moment(aplcnYm, "YYYYMM").format("YYYY-MM"):""}
+
+
+
+
+ {/* 강우유입수량 분석결과 */}
+
+
강우유입수량 분석결과
+
+ {rdiiQty}
+ m³/d
+
+
+ {totalVolume}
+ m³/mm
+
+
+
+ {/* 차트 */}
+
+
+
+
+ {popupOpen && (
+
+
강우유입수분석 입력현황
+
+
+
+ {
+ setAplcnYm(String(val));
+ }}
+ />
+
+
+
+ {
+ setRainInfwtAnlsSn(Number(val));
+ }}
+ />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
)}
+ {/* */}
+ >
+ )
+
+ return (
+
+ )
+}
+
+export default React.memo(RdiiChart);
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/chartModalStore.ts b/apps/sn/app/(map-layout)/map/components/popupComponent/chartModalStore.ts
new file mode 100644
index 000000000..c84fa48a7
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/chartModalStore.ts
@@ -0,0 +1,16 @@
+import { create } from 'zustand';
+
+interface ModalStore {
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+export const useInfilChartModalStore = create((set) => ({
+ isOpen: false,
+ setIsOpen: (open: boolean) => set({ isOpen: open }),
+}));
+
+export const useRdiiChartModalStore = create((set) => ({
+ isOpen: false,
+ setIsOpen: (open: boolean) => set({ isOpen: open }),
+}));
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/sewagePump.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/sewagePump.tsx
new file mode 100644
index 000000000..d8f004cac
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/sewagePump.tsx
@@ -0,0 +1,59 @@
+import { VerticalTable } from '@/components/ui/verticalTable';
+import React, { useState, useEffect } from 'react'
+// 빗물펌프 자체 입력 정보
+const exclnInputColumn = [
+ { id: "swtrmtZoneCd", title: "배수구역", type: "input" },
+ { id: "mltvDtdvNm", title: "배수분구", type: "input" },
+ { id: "dsgnFrqnc", title: "설계빈도(년)", type: "input" },
+]
+// 오수펌프 자체 입력 정보
+const drtwInputColumn = [
+ { id: "swtrmt_zone_cd", title: "배수구역", type: "input" },
+ { id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
+]
+
+// 하수펌프장
+const sewagePump = ({ featureData, isDrtwSewagePump, onSaveClick }: { featureData: any, isDrtwSewagePump?: boolean, onSaveClick?: () => void }) => {
+ const [formData, setFormData] = useState({});
+
+ // featureData가 변경될 때 formData 초기화
+ useEffect(() => {
+ if (featureData) {
+ setFormData(featureData);
+ }
+ }, [featureData]);
+
+ // 폼 데이터가 변경될 때 호출될 핸들러
+ const handleFormDataChange = (newFormData: any) => {
+ setFormData(newFormData);
+ };
+
+ // 저장 버튼 클릭 시 최신 formData를 부모에게 전달
+ const handleSaveClick = () => {
+ if (onSaveClick) {
+ // 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
+ onSaveClick();
+ }
+ };
+
+ return (
+
+ )
+}
+
+export default sewagePump
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/smh.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/smh.tsx
new file mode 100644
index 000000000..e2a2cc747
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/smh.tsx
@@ -0,0 +1,53 @@
+// 하수맨홀
+import { VerticalTable } from '@/components/ui/verticalTable';
+import React, { useState, useEffect } from 'react'
+const inputColumn = [
+ { id: "swtrmtZoneCd", title: "처리구역", type: "input" },
+ { id: "mltvZoneNm", title: "배수구역", type: "input" },
+ { id: "mltvDtdvNm", title: "배수분구", type: "input" },
+ { id: "layCd", title: "매설위치", type: "select", options: ["도로", "하상"] },
+];
+const Smh = ({ featureData, onSaveClick }: { featureData: any, onSaveClick?: () => void }) => {
+ const [formData, setFormData] = useState({});
+
+ // featureData가 변경될 때 formData 초기화
+ useEffect(() => {
+ if (featureData) {
+ setFormData(featureData);
+ }
+ }, [featureData]);
+
+ // 폼 데이터가 변경될 때 호출될 핸들러
+ const handleFormDataChange = (newFormData: any) => {
+ setFormData(newFormData);
+ };
+
+ // 저장 버튼 클릭 시 최신 formData를 부모에게 전달
+ const handleSaveClick = () => {
+ if (onSaveClick) {
+ // 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
+ onSaveClick();
+ }
+ };
+
+ return (
+
+ )
+}
+
+export default Smh;
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/popupComponent/stormWaterPump.tsx b/apps/sn/app/(map-layout)/map/components/popupComponent/stormWaterPump.tsx
new file mode 100644
index 000000000..a73c344a5
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/popupComponent/stormWaterPump.tsx
@@ -0,0 +1,28 @@
+import { VerticalTable } from '@/components/ui/verticalTable';
+import React from 'react'
+const inputColumn = [
+ { id: "swtrmt_zone_cd", title: "처리구역", type: "input" },
+ { id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
+]
+// 빗물펌프
+const StormWaterPump = ({ featureData }: { featureData: Record }) => {
+ const validKey = inputColumn.map((item) => item.id);
+ const filteredData = featureData && Object.entries(featureData).filter(([key]) => validKey.includes(key)).reduce((obj: Record, [key, value]) => { obj[key] = value; return obj; }, {});
+ return (
+
+ )
+}
+
+export default StormWaterPump
\ No newline at end of file
diff --git a/apps/sn/app/(map-layout)/map/components/searchModalReportApi.ts b/apps/sn/app/(map-layout)/map/components/searchModalReportApi.ts
new file mode 100644
index 000000000..9d1ae43e0
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/components/searchModalReportApi.ts
@@ -0,0 +1,229 @@
+import {useState, useEffect} from 'react';
+import { getDcData } from '@/components/lib/api';
+
+const ADDR_URL = process.env.NEXT_PUBLIC_ADDR_URL;
+
+export type Folder = {
+ clsfSystmSn: string;
+ upClsfSystmSn: string;
+ clsfSystmNm: string;
+ children: Folder[];
+ };
+
+export type FlattenedFolder = {
+ [key: string]: string|number|undefined;
+};
+
+type SelectDataType = {
+ text: string;
+ val: string;
+ sido?: string; // 시도 코드 (선택 사항)
+}
+
+type ReportDataFile = {
+ no : number;
+ fileTitle : string;
+ regDt : string;
+ fileSn : string;
+ filePath : string;
+}
+const isYear = (value: string): boolean => {
+ return /^[0-9]{4}년$/.test(value);
+};
+
+export function flattenFolders(data: Folder[]): FlattenedFolder[] {
+ const result: FlattenedFolder[] = [];
+ const exceptNodeNm = ["부분","통합","전체"];
+ const addNodeNm = ["보고서","요약보고서","부록","기타"]; // level5
+ const columnNms: { [key: number]: string } = { 0: "root", 1:"sido", 2:"sigungu", 3:"approvalYear"
+ ,4:"plantZoneGugun", 5:"reportGubun", 7:"fileName", 8:"regDate" };
+
+ function traverse(
+ node: Folder,
+ path: { [key: string]: string| number },
+ level: number
+ ) {
+ if (level === 2 && isYear(node.clsfSystmNm)) {
+ level++;
+ }
+ if (level === 4 && addNodeNm.includes(node.clsfSystmNm)) {
+ level++; // 레벨을 증가시켜 하위값에 추가되도록 함.
+ }
+
+ const newPath = {
+ ...path,
+ [`${columnNms[level]}`]: node.clsfSystmNm,
+ };
+
+ if (node.children.length === 0) {
+ newPath.no = result.length + 1;
+ newPath.clsfSystmSn = node.clsfSystmSn; // 파일 조회를 위한 고유번호
+ result.push(newPath);
+ } else {
+ if (level === 4) {
+ if (exceptNodeNm.includes(node.clsfSystmNm)) {
+ level--; // 제외할 노드 이름인 경우, 현재의 레벨에 하위값이 써지도록 함.
+ }
+ }
+ node.children.forEach((child) => {
+ traverse(child, newPath, level + 1);
+ });
+ }
+ }
+
+ data.forEach((root) => traverse(root, {}, 0));
+ console.log(result.slice(0, 10));
+ return result;
+}
+
+export const getDcTree = async (clsfSystmNm:string) => {
+ //const cityName = encodeURIComponent(clsfSystmNm);
+ const queryString = 'clsfSystmNm='+clsfSystmNm;
+ console.log("getDcTree queryString:", queryString);
+ //const result = await getDcData(`/api/v1/dc/clsf${queryString ? `?${queryString}` : ''}`);
+ const result = await getDcData("/api/v1/dc/clsf?clsfSystmNm=" + clsfSystmNm);
+ return result;
+};
+export const useDcTree = (clsfSystmNm:string) => {
+ const [data, setData] = useState([]);
+
+ useEffect(() => {
+ const fetch = async () => {
+ const result = await getDcTree(clsfSystmNm);
+ if (result) {
+ setData(result);
+ }
+ };
+ fetch();
+ console.log("useDcTree호출");
+ }, [clsfSystmNm]);
+
+ return data;
+};
+export const getDcFile = async (clsfSystmSn:string) => {
+ const queryString = 'clsfSystmSn='+clsfSystmSn;
+ const result = await getDcData(`/api/v1/dc/file${queryString ? `?${queryString}` : ''}`);
+ return result;
+};
+export const addFileName = async (data:FlattenedFolder[]) => {
+ const fileReportData = await Promise.all(
+ data.map(async (item) => {
+ const filenameArr:ReportDataFile[] = await getDcFile(String(item.clsfSystmSn));
+ const f = filenameArr[0];
+ const result = {...item, fileName:f?.fileTitle, regDate:f?.regDt, fileSn:f?.fileSn, filePath:""};
+ // if (f !== undefined && f.fileSn !== "") {
+ // const fprcs = await getDcFileprcs(f?.fileSn);
+ // if (fprcs.length>0)
+ // result.filePath = fprcs[0].filePath;
+ // }
+ return result;
+ })
+ );
+ return fileReportData;
+}
+export const getDcFileprcs = async (fileSn:string) => {
+ const queryString = 'fileSn='+fileSn;
+ console.log("getDcTree queryString:", queryString);
+ const result = await getDcData(`/api/v1/dc/fileprcs${queryString ? `?${queryString}` : ''}`);
+ return result;
+};
+
+export const getDcFileDownload = async (filePath:string) => {
+ const queryString = 'filePath='+ encodeURIComponent(filePath);
+ const response = await fetch(`/dc-service/api/v1/dc/file/download?${queryString}`, {
+ method: 'GET',
+ });
+ if (!response.ok) {
+ throw new Error(`File download failed: ${response.status}`);
+ }
+ const blob = await response.blob(); // PDF, image 등은 blob으로 받아야 함
+ return blob;
+};
+export const fileDownload = (data:Blob, fileName:string) => { // Blob데이터 임시link로 연결
+ const url = window.URL.createObjectURL(data);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileName; // 원하는 파일명 지정
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.URL.revokeObjectURL(url);
+}
+export const getFileDownload = async (fileSn:string, fileName:string) => {
+ const fileprcsData = await getDcFileprcs(fileSn); // filePath 조회
+ if (fileprcsData?.length === 0 ) { alert("filePath 조회 오류"); }
+ if (fileprcsData[0].filePath === "") alert("filePath 정보 없으므로 다운로드 불가");
+ const blobData = await getDcFileDownload(fileprcsData[0].filePath); // 실제 다운로드 API
+ fileDownload(blobData, fileName);
+}
+// 시도 데이터
+export const getCityCd = async (): Promise => {
+ try {
+ const response = await fetch(`${ADDR_URL}/api/v1/addr/city`, { method: "GET", headers: { accept: "application/json" } });
+ if (!response.ok) throw new Error(`시도 데이터 오류: ${response.status}`);
+ const res = await response.json();
+ const city = res.data;
+ const cityCd = city.map((item: any) => ({
+ val: item.adstDstrCd,
+ text: item.sido,
+ }));
+ cityCd.unshift({ val: '0', text: '전체' });
+ return cityCd;
+ } catch (error) {
+ console.error('시도 데이터를 가져오는데 실패했습니다:', error);
+ return [{ val: '0', text: '전체', sido: '0' }];
+ }
+ };
+
+export const useSggCd = () => {
+ const [data, setData] = useState([]);
+
+ useEffect(() => {
+ const fetch = async () => {
+ const result = await getSggCd();
+ if (result) {
+ setData(result);
+ }
+ };
+ fetch();
+ console.log("useSggCd호출");
+ }, []);
+ return data;
+};
+
+// 시군구 데이터
+export const getSggCd = async (): Promise => {
+ try {
+ const response = await fetch(`${ADDR_URL}/api/v1/addr/sgg`, { method: "GET", headers: { accept: "application/json" } });
+ if (!response.ok) throw new Error(`시군구 데이터 오류: ${response.status}`);
+ const res = await response.json();
+ const sgg = res.data;
+ const sggCd = sgg.map((item: any) => ({
+ val: item.adstDstrCd,
+ sido: item.sido,
+ text: item.gugun,
+ }));
+ sggCd.unshift({ val: '0', text: '전체' }); // "전체" 옵션 추가
+ return sggCd;
+ } catch (error) {
+ console.error('시군구 데이터를 가져오는데 실패했습니다:', error);
+ return [{ val: '0', text: '전체', sido: '0' }];
+ }
+};
+
+export const useCityCd = () => {
+ const [data, setData] = useState([]);
+
+ useEffect(() => {
+ const fetch = async () => {
+ const result = await getCityCd();
+ if (result) {
+ setData(result);
+ }
+ };
+ fetch();
+ console.log("useCityCd호출");
+ }, []);
+ return data;
+};
+
diff --git a/apps/sn/app/(map-layout)/map/featureClickEventPopup.tsx b/apps/sn/app/(map-layout)/map/featureClickEventPopup.tsx
new file mode 100644
index 000000000..e2cfa0115
--- /dev/null
+++ b/apps/sn/app/(map-layout)/map/featureClickEventPopup.tsx
@@ -0,0 +1,485 @@
+'use client'
+import { getData, postData } from "@/components/lib/api";
+import Modal from "@/components/ui/modal";
+import { VerticalTable } from "@/components/ui/verticalTable";
+import { useGisContext } from "@common/business_components/ui/map/Gis";
+import { Button } from "@common/components/ui";
+import { useEffect, useRef, useState, useCallback, useMemo } from "react";
+import { getLayerContentComponent } from "./components/common";
+import { SwtrmtFcltCol, SwtrmtPrcsZoneCol, untrtSwgRainCol1, untrtSwgRainCol2, MsSwagePplCol, ExclnSewagePumpCol, MsSwageMhlCol, stofcbrCol, MS_SWAGE_MHL_CODES, DRTW_SEWAGE_PUMP_USE_CODES } from "./components/common/table";
+import InfilChart from './components/popupComponent/chart/infilChart';
+import RdiiChart from './components/popupComponent/chart/rdiiChart';
+import { useInfilChartModalStore, useRdiiChartModalStore } from "./components/popupComponent/chartModalStore";
+import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
+
+
+// TODO:
+const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void, featureData: any }) => {
+ const { gisMap } = useGisContext() as unknown as { checkedLayerIds: React.MutableRefObject; treeData: { lyrSn: number }[] | null; gisCore: any; gisMap: any; };
+ const [layerNm, setLayerNm] = useState(""); // 레이어 이름 상태
+ const [tableData, setTableData] = useState(null); // 피처 데이터
+ const [rainMeasureData, setRainMeasureData] = useState([]); // 강우/측정 측정 정보
+ const [headlist, setHeadlist] = useState<{ id: string; title: string; }[]>([]); // 컬럼리스트 변경상태
+ const [headlist2, setHeadlist2] = useState<{ id: string; title: string; }[]>([]); // 컬럼리스트 변경상태
+ const [buttonChk, setButtonChk] = useState(true)
+ const [fetchData, setfetchData] = useState(); // api 호출여부
+ const contentRef = useRef(null);
+ const [isModalOpen, setIsModalOpen] = useState(false); // 모달 열기 상태
+ const [isMainSsc, setIsMainSsc] = useState(false); // 중점우수토실 여부
+ const [isDrtwSewagePump, setIsDrtwSewagePump] = useState(false); // 오수펌프장 여부
+ // 🎯 InfilChart 및 RdiiChart 관련 상태 추가
+ const { setIsOpen: setIsModalInfil } = useInfilChartModalStore();
+ const { setIsOpen: setIsModalRdii } = useRdiiChartModalStore();
+ const [curPage, setCurPage] = useState(1); // 현재 페이지 상태
+
+ // 🎯 관로관리번호 추출
+ const pplMngNo = featureData?.values_?.fclt_mng_no || "";
+ // const featureId = featureData.getId(); // 피처의 id 가져오기
+
+ const featureId = typeof featureData.getId === 'function'
+ ? featureData.getId()
+ : featureData.fid;
+ console.log('featureId', featureId);
+
+ // 🎯 데이터 전처리 메모이제이션
+ const processedData = useMemo(() => {
+ if (!featureData?.values_) return null;
+
+ return {
+ ...featureData.values_,
+ discharge_pipe_spec: `직경: ${featureData.values_.pipe_diameter || '-'} / 높이: ${featureData.values_.pipe_hg || '-'} / 길이: ${featureData.values_.pipe_lt || '-'}`
+ };
+ }, [featureData?.values_]);
+
+ // 피쳐데이터의 현재 레이어 이름 가져오는 함수
+ const getSelectedLayers = () => {
+ let result = null;
+ const layers = gisMap.getLayers().getArray(); // gisMap에서 모든 레이어 가져오기
+ let featureLayer: { get: (key: string) => any }; // 피처가 속한 레이어를 찾기 위한 변수
+ layers.forEach((layer: any) => {
+ const source = layer.getSource();
+ if (source && source.hasFeature && featureData
+ && typeof featureData.getId === 'function' && source.hasFeature(featureData)) {
+ featureLayer = layer; // 피처가 속한 레이어 찾기
+ }
+ });
+ // console.log("featureLayer.get('lyrTyNm');", featureLayer.get('lyrTyNm'));
+ // SearchModal 클릭 이벤트와 Gis 클릭 이벤트 구분하기
+ if (featureLayer.get('lyrNm') === null) {
+ if (featureData.lyrTypeNm === 'tb_il_swage_prcs_fclt') result = '하수처리시설';
+ else if (featureData.lyrTypeNm === 'tb_ms_swage_prcs_zone') result = '하수처리구역';
+ else if (featureData.lyrTypeNm === 'tb_ms_stofcbr') result = '우수토실';
+ else if (featureData.lyrTypeNm === 'om_dt_untrt_swg_rain') result = '중점우수토실';
+ else if (featureData.lyrTypeNm === 'tb_ms_swage_ppl') result = '하수관로';
+ else if (featureData.lyrTypeNm === 'tb_ms_swage_pmstn') {
+ const drtwPumpCode = DRTW_SEWAGE_PUMP_USE_CODES.find(code => code.text === '오수펌프장');
+ console.log('값 비교', featureData.values_.usg_cd.trim(), drtwPumpCode?.val);
+ if (drtwPumpCode && featureData.values_.usg_cd.trim() === drtwPumpCode.val) {
+ setIsDrtwSewagePump(true);
+ } else {
+ setIsDrtwSewagePump(false);
+ }
+ result = '하수펌프장';
+ }
+ else if (featureData.lyrTypeNm === 'tb_ms_swage_mhl') result = '하수맨홀';
+ }
+ else {
+ const lyrTyNm = featureLayer.get('lyrTyNm');
+ if (lyrTyNm === 'tb_il_swage_prcs_fclt') result = '하수처리시설';
+ else if (lyrTyNm === 'tb_ms_swage_prcs_zone') result = '하수처리구역';
+ else if (lyrTyNm === 'tb_ms_stofcbr') result = '우수토실';
+ else if (lyrTyNm === 'om_dt_untrt_swg_rain') result = '중점우수토실';
+ else if (lyrTyNm === 'tb_ms_swage_ppl') result = '하수관로';
+ else if (lyrTyNm === 'tb_ms_swage_pmstn') {
+ const drtwPumpCode = DRTW_SEWAGE_PUMP_USE_CODES.find(code => code.text === '오수펌프장');
+ console.log('값 비교', featureData.values_.usg_cd.trim(), drtwPumpCode?.val);
+ if (drtwPumpCode && featureData.values_.usg_cd.trim() === drtwPumpCode.val) {
+ setIsDrtwSewagePump(true);
+ } else {
+ setIsDrtwSewagePump(false);
+ }
+ result = '하수펌프장';
+ }
+ else if (lyrTyNm === 'tb_ms_swage_mhl') result = '하수맨홀';
+ else result = featureLayer.get('lyrNm');
+ }
+
+ return result;
+ // return featureLayer.get('lyrNm'); // 레이어 이름 출력
+ };
+
+ useEffect(() => {
+ const fetchData = async () => {
+ if (!featureId) return;
+
+ try {
+ const selectedLayerName = getSelectedLayers(); // 레이어 이름 가져오기
+ setLayerNm(selectedLayerName); // 상태 업데이트
+
+ console.log('gis data', featureData.values_);
+ const data = featureData.values_;
+
+ // 하수맨홀인 경우 용도코드를 텍스트로 변환
+ if (selectedLayerName === '하수맨홀' && data) {
+ // mqlt_cd 값 변환 (재질코드)
+ if (data.mqlt_cd) {
+ const materialCodeItem = MS_SWAGE_MHL_CODES.find(
+ code => code.val === data.mqlt_cd.trim()
+ );
+ if (materialCodeItem) data.mqlt_cd = `${materialCodeItem.text}`;
+ }
+ }
+
+ // 🎯 기본 데이터 포맷팅
+ const formattedData = formatDisplayData(data);
+
+ setfetchData(formattedData);
+ setTableData(formattedData);
+
+ switch (selectedLayerName) {
+ case '하수처리시설':
+ setHeadlist(SwtrmtFcltCol);
+ setButtonChk(false)
+ break;
+ case '하수처리구역':
+ setHeadlist(SwtrmtPrcsZoneCol)
+ setButtonChk(false)
+ break;
+ case '중점우수토실':
+ setHeadlist(untrtSwgRainCol1)
+ setHeadlist2(untrtSwgRainCol2)
+ setButtonChk(false)
+ setIsMainSsc(true)
+ // 🎯 processedData도 포맷팅하여 설정
+ const processedFormattedData = formatDisplayData(processedData);
+
+ setfetchData([processedFormattedData])
+ setTableData(processedFormattedData);
+ // setIsLoading(false); // 기본 렌더링 완료
+
+ // 강우/측정 정보 데이터 호출
+ if (data?.chmbr_xcnts && data?.chmbr_ydnts) {
+ fetchRainMeasureData(data.chmbr_xcnts, data.chmbr_ydnts)
+ .then(response => {
+ console.log('additionalResponse', response);
+ setRainMeasureData(response || []);
+ })
+ .catch(error => {
+ console.error('추가 데이터 로딩 실패:', error);
+ setRainMeasureData(false);
+ });
+ }
+ break;
+ case '우수토실':
+ setHeadlist(stofcbrCol)
+ setButtonChk(true)
+ setIsMainSsc(false)
+ break;
+ case '하수관로':
+ setHeadlist(MsSwagePplCol)
+ setButtonChk(true)
+ break;
+ // case '오수펌프':
+ // setButtonChk(true)
+ // break;
+ // case '빗물펌프':
+ // setButtonChk(true)
+ // break;
+ case '하수펌프장':
+ setHeadlist(ExclnSewagePumpCol)
+ setButtonChk(true)
+ break;
+ case '하수맨홀':
+ setHeadlist(MsSwageMhlCol)
+ setButtonChk(true)
+ break;
+ default:
+ break;
+ }
+
+ // API 엔드포인트 선택
+ let apiEndpoint = '';
+ const getFeatureId = featureId.toString().split('.').pop() || null;
+ if (selectedLayerName === '하수관로') apiEndpoint = `v1/fcltppl/${getFeatureId}`;
+ else if (selectedLayerName === '우수토실') apiEndpoint = `v1/fcltstofcbr/${getFeatureId}`;
+ else if (selectedLayerName === '오수펌프' || selectedLayerName === '빗물펌프') apiEndpoint = `v1/fcltpump/${getFeatureId}`;
+ else if (selectedLayerName === '하수맨홀') apiEndpoint = `v1/fcltmhl/${getFeatureId}`;
+
+ // API에서 상세 데이터 가져오기
+ if (apiEndpoint) {
+ try {
+ console.log(`API 호출: ${apiEndpoint}`);
+ const result = await getData(apiEndpoint);
+
+ if (result) {
+ console.log('API 데이터 로드 성공:', result);
+
+ // 하수맨홀인 경우 용도코드를 텍스트로 변환
+ if (selectedLayerName === '하수맨홀') {
+ const processedData = { ...result };
+
+ // mqlt_cd 값 변환 (재질코드)
+ if (processedData.mqlt_cd) {
+ const materialCodeItem = MS_SWAGE_MHL_CODES.find(
+ code => code.val === processedData.mqlt_cd.trim()
+ );
+ if (materialCodeItem) {
+ processedData.mqlt_cd = `${materialCodeItem.text}`;
+ }
+ }
+
+ setfetchData(processedData);
+ } // 🎯 우수토실인 경우 prrtymngYn 값 변환
+ else if (selectedLayerName === '우수토실' && data) {
+ const processedData = { ...result, ...data };
+
+ // prrtymngYn 값 변환
+ if (processedData.prrtymngYn === 'Y') processedData.prrtymngYn = '중점우수토실';
+ else if (processedData.prrtymngYn === 'N') processedData.prrtymngYn = '우수토실';
+
+ console.log('processedData', processedData);
+
+ setfetchData(processedData);
+ } else {
+ setfetchData(result);
+ }
+ }
+ } catch (apiError) {
+ console.error('API 데이터 로딩 중 오류:', apiError);
+ }
+ }
+ } catch (error) {
+ console.error('데이터 로딩 중 오류:', error);
+ }
+ };
+
+ fetchData();
+ }, [featureId, processedData]);
+
+ // 🎯 추가 데이터 API 호출 함수 (독립적으로 실행)
+ const fetchRainMeasureData = useCallback(async (chmbrXcnts: string, chmbrYdnts: string) => {
+ if (!chmbrXcnts || !chmbrYdnts) {
+ console.warn('추가 데이터 호출 실패: 필수 매개변수 누락', { chmbrXcnts, chmbrYdnts });
+ return [];
+ }
+
+ try {
+ const queryParams = new URLSearchParams({
+ chmbrXcnts: chmbrXcnts,
+ chmbrYdnts: chmbrYdnts,
+ pageable: `{}`,
+ });
+
+ console.log(`추가 데이터 API 호출 시작: v1/onsemiro/getSwgRainsByGeomety?${queryParams.toString()}`);
+
+ const result = await getData(`v1/onsemiro/getSwgRainsByGeomety?${queryParams.toString()}`);
+
+ console.log('추가 데이터 API 호출 성공:', result);
+
+ // 🎯 result가 페이지네이션 객체인 경우 content 배열 추출
+ let dataArray: any[] = [];
+ if (result && typeof result === 'object' && 'content' in result && Array.isArray(result.content)) {
+ dataArray = result.content;
+ } else if (Array.isArray(result)) {
+ dataArray = result;
+ } else {
+ console.warn('예상치 못한 API 응답 형식:', result);
+ return [];
+ }
+
+ // 🎯 각 아이템을 전처리하여 반환
+ const processedDataArray = dataArray.map((data: any) => {
+ // 🎯 formatDisplayData로 기본 포맷팅 적용
+ const formattedItem = formatDisplayData(data);
+
+ // 🎯 추가 데이터 조합
+ return {
+ ...formattedItem,
+ flwmtrCombined: `${data.flwmtrMesureTpEtc || '-'} / ${data.flwmtrKnd || '-'}`,
+ };
+ });
+
+ return processedDataArray;
+ } catch (error) {
+ console.error('추가 데이터 로딩 실패:', error);
+ return [];
+ }
+ }, []);
+
+ // 🎯 추가 데이터는 별도 useEffect로 비동기 로딩
+ useEffect(() => {
+ if (layerNm === '중점우수토실' && featureData?.values_) {
+ const data = featureData.values_;
+
+ if (data?.chmbr_xcnts && data?.chmbr_ydnts) {
+ // 🎯 추가 데이터를 비동기로 로딩 (UI 블로킹 없음)
+ fetchRainMeasureData(data.chmbr_xcnts, data.chmbr_ydnts)
+ .then(response => {
+ console.log('추가 데이터 로딩 완료:', response);
+ setRainMeasureData(response || []);
+ })
+ .catch(error => {
+ console.error('추가 데이터 최종 로딩 실패:', error);
+ setRainMeasureData(false);
+ });
+ }
+ }
+ }, [layerNm, featureData?.values_, fetchRainMeasureData]);
+
+ // 저장 시 모달 띄우기
+ const handleSaveClick = () => {
+ setIsModalOpen(true); // 모달 열기
+ };
+
+ const handleModalSave = () => {
+ setIsModalOpen(false); // 모달 닫기
+ btnClickEvent(); // 저장 이벤트 실행
+ };
+
+ const handleModalClose = () => {
+ setIsModalOpen(false); // 모달 닫기
+ };
+
+ // 저장 버튼 이벤트
+ const btnClickEvent = async () => {
+ const bodyData: Record = {}
+
+ if (buttonChk && contentRef.current) {
+ const inputElements = contentRef.current.querySelectorAll('input');
+ const selectElements = contentRef.current.querySelectorAll('select');
+
+ // 카멜케이스 변환 함수
+ const toCamelCase = (str: string) =>
+ str.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
+
+ // select 태그의 값 가져오기
+ selectElements.forEach((select) => {
+ const camelCaseId = toCamelCase(select.id);
+ bodyData[camelCaseId] = select.value;
+ });
+
+ // // input 태그의 값 가져오기
+ inputElements.forEach((input) => {
+ const camelCaseId = toCamelCase(input.id);
+ bodyData[camelCaseId] = input.value;
+ });
+
+ // 레이어명에 따라 API 엔드포인트 분기처리
+ let apiEndpoint = '';
+ let result = null;
+
+ if (layerNm === '하수관로') apiEndpoint = 'v1/fcltppl';
+ else if (layerNm === '우수토실') apiEndpoint = 'v1/fcltstofcbr';
+ else if (layerNm === '하수펌프장') apiEndpoint = 'v1/fcltpump';
+ else if (layerNm === '하수맨홀') apiEndpoint = 'v1/fcltmhl';
+
+ bodyData['fid'] = featureId.toString().split('.').pop() || null;
+ // 빈 키 제거
+ if (bodyData[""] !== undefined) delete bodyData[""];
+
+ // 🎯 우수토실일 경우 prrtymngYn 값 변환
+ if (layerNm === '우수토실' && bodyData.prrtymngYn) {
+ if (bodyData.prrtymngYn === '중점우수토실') {
+ bodyData.prrtymngYn = 'Y';
+ } else if (bodyData.prrtymngYn === '우수토실') {
+ bodyData.prrtymngYn = 'N';
+ }
+ }
+ console.log('bodyData', bodyData);
+ console.log('apiEndpoint', apiEndpoint);
+
+ try {
+ result = await postData(apiEndpoint, bodyData);
+ console.log('result', result);
+
+ if (result) {
+ alert('저장되었습니다');
+ setfetchData(result.data || result);
+ } else {
+ alert('저장에 실패했습니다');
+ console.error('API 응답 오류:', result);
+ }
+ } catch (error) {
+ alert('저장 중 오류가 발생했습니다');
+ console.error('API 요청 오류:', error);
+ }
+ }
+ }
+
+ // 레이어명에 따라 상세페이지 렌더링
+ const ContentComponent = layerNm ? getLayerContentComponent(layerNm) : null;
+
+ return (
+
+ )
+}
+export default FeatureClickEventPopup;
\ No newline at end of file
diff --git a/apps/sn/app/map/page.tsx b/apps/sn/app/(map-layout)/map/page.tsx
similarity index 83%
rename from apps/sn/app/map/page.tsx
rename to apps/sn/app/(map-layout)/map/page.tsx
index e1a90d5f1..36f72a5da 100644
--- a/apps/sn/app/map/page.tsx
+++ b/apps/sn/app/(map-layout)/map/page.tsx
@@ -1,12 +1,36 @@
"use client";
import Gis, { useGisContext } from "@common/business_components/ui/map/Gis";
-import { mapService } from "@service";
+import { getData } from "../../components/lib/api";
import { useCallback, useEffect, useRef, useState } from "react";
import GisApp from "@common/business_components/ui/map/lib/gis.core";
import SearchModal from "./SearchModal";
import FeatureClickEventPopup from "./featureClickEventPopup";
+// 타입 정의 추가
+export type LyrStngProps = {
+ lyr_sn: string;
+ lyr_nm: string;
+ upper_lyr_sn: string;
+ drawOrdr: string;
+ flterSql: string;
+ gobjTy: string;
+ lyrTpNm: string;
+ useYn: string;
+ minViewSize: string;
+ iconNm: string;
+ lblAtrbNm: string;
+ fontNm: string;
+ fontIntnColor: string;
+ fontExtnColor: string;
+ fontExtnWdth: string;
+ lnWdth: string;
+ lnColor: string;
+ polgnColor: string;
+ initEprssYn: string;
+ clickPsblYn: string;
+};
+
const Map = () => {
const [treeData, setTreeData] = useState([]); // 초기값을 객체 또는 null로 설정
const [selectedFeature, setSelectedFeature] = useState(null); // 선택된 피처 상태
@@ -14,20 +38,19 @@ const Map = () => {
const [isOpen, setIsOpen] = useState(false); // 팝업 열기/닫기 상태
const [isSearchModalOpen, setIsSearchModalOpen] = useState(false); // SearchModal 열림 상태
const [featureData, setFeatureData] = useState(null); // 선택된 피쳐 데이터
+
const fetchData = async () => {
try {
- const response = await mapService.getLyrStngs();
- setTreeData(response.data); // API 응답 저장
+ const data = await getData('v1/map/lyrStngs/SN_NETWORK');
+ setTreeData(data);
} catch (error) {
console.error("데이터 불러오기 실패:", error);
}
};
- // 컴포넌트 마운트 시 1회 실행
useEffect(() => {
fetchData();
}, []);
-
// SearchModal, GisContent 등에서 호출
const onFeatureSelect = (data: any) => {
let map = gisMaps.current;
@@ -96,7 +119,7 @@ const Map = () => {
treeData={treeData}
isSearch={true}
gisMaps={gisMaps}
- isMiniMap={true}
+ isMiniMap={false}
searchView={SearchModal}
detailView={FeatureClickEventPopup}
onFeatureSelect={onFeatureSelect}
@@ -106,6 +129,7 @@ const Map = () => {
setIsSearchModalOpen={setIsSearchModalOpen}
isOpen={isOpen}
isSearchModalOpen={isSearchModalOpen}
+ onCheckedLayersChange={undefined}
/>
);
diff --git a/apps/sn/app/(with-base-layout)/fileValidation.tsx b/apps/sn/app/(with-base-layout)/fileValidation.tsx
new file mode 100644
index 000000000..c0711a7d2
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/fileValidation.tsx
@@ -0,0 +1,48 @@
+/**
+ * 파일 확장자 검증 유틸리티
+ */
+
+// 파일 확장자 검증 함수
+export const validateFileExtension = (file: File, allowedExtensions: string[]): boolean => {
+ const fileName = file.name.toLowerCase();
+ return allowedExtensions.some(ext => fileName.endsWith(ext.toLowerCase()));
+};
+
+// 파일 확장자 검증 결과 타입
+export interface FileValidationResult {
+ isValid: boolean;
+ errorMessage?: string;
+}
+
+// 파일 검증 설정 타입
+export interface FileValidationConfig {
+ file: File;
+ allowedExtensions: string[];
+ fileDescription: string;
+}
+
+/**
+ * 여러 파일의 확장자를 한 번에 검증하는 함수
+ * @param validationConfigs 검증할 파일들의 설정 배열
+ * @returns 검증 결과. 실패 시 첫 번째 에러 메시지 반환
+ */
+export const validateMultipleFiles = (validationConfigs: FileValidationConfig[]): FileValidationResult => {
+ for (const config of validationConfigs) {
+ if (!validateFileExtension(config.file, config.allowedExtensions)) {
+ const allowedExtStr = config.allowedExtensions.join(', ');
+ return {
+ isValid: false,
+ errorMessage: `${config.fileDescription} 파일은 ${allowedExtStr} 확장자만 업로드 가능합니다.`
+ };
+ }
+ }
+
+ return { isValid: true };
+};
+
+// 자주 사용되는 확장자 상수
+export const FILE_EXTENSIONS = {
+ INP: ['.inp'],
+ EXCEL: ['.xls', '.xlsx', '.xlsm', '.xltx'],
+ ALL_OFFICE: ['.xls', '.xlsx', '.xlsm', '.xltx', '.doc', '.docx', '.ppt', '.pptx']
+};
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/ii/BaseLayout.tsx b/apps/sn/app/(with-base-layout)/ii/BaseLayout.tsx
new file mode 100644
index 000000000..86ae34f46
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/ii/BaseLayout.tsx
@@ -0,0 +1,305 @@
+'use client'
+import { getData } from '@/components/lib/api'
+import ContentLayout from '@/components/ui/contentLayout'
+import { GovSidoSigunguSearchForm } from '@/components/ui/govSidoSigunguSearchForm'
+import { DatePicker, DateMonthPicker, Form, SearchFormRight, SelectBox } from '@common/business_components/ui'
+import ListDiv from '@common/business_components/ui/list_div'
+import { SelectBox2 } from '@common/business_components/ui/select/index-2'
+import { Button, Label } from '@common/components/ui'
+import { useEffect, useState, type ReactNode } from 'react'
+import LoadingOverlay from '@/components/ui/LoadingBar'
+
+type TitleName = {
+ mainTitle: string
+ firstCardTitle: string
+ secondCardTitle?: string
+}
+type SelectBox = {
+ labelNm?: Label
+ searchChk?: boolean
+ title?: string;
+ onSearchClick?: () => Promise
;
+}
+type Label = {
+ first: string
+ second: string
+ third: string
+ fourth: string
+}
+// API로부터 받아올 데이터 타입을 정의 (SelectBox에 사용될 형태)
+interface ApiSelectOption {
+ text: string;
+ val: string;
+}
+type BaseLayout = {
+ children?: ReactNode[]
+ titleName: TitleName
+ form: any
+ onSubmitEvent: Function
+ graphBtn?: boolean
+ analysisBtn?: string
+ firstDivBtn?: boolean
+ selectBox?: SelectBox
+ showDatePicker?: boolean;
+ enoCd?: string | number
+ setEnoCd?: (enoCd: string) => void
+ ctpvCd?: string | number
+ setCtpvCd?: (ctpvCd: string) => void
+ sigungu?: ApiSelectOption
+ setSigungu?: (sigungu: ApiSelectOption) => void
+ selectedSwageTreatmentPlant?: string | number;
+ onSwageTreatmentPlantChange?: (value: string | number) => void;
+ selectedSwageProcessingZone?: string | number;
+ onSwageProcessingZoneChange?: (value: string | number) => void;
+ aplcnYmFrom?: string
+ setAplcnYmFrom?: (aplcnYmFrom: string) => void;
+ aplcnYmTo?: string
+ setAplcnYmTo?: (aplcnYmTo: string) => void;
+ isLoading?: boolean;
+ // Excel 다운로드 관련 props 추가
+ onExcelDownload?: () => void;
+ onDeleteFile?: () => void;
+ onAnalysis?: () => void;
+ selectedRowData?: any;
+}
+// TODO: 나중에 이벤트 추가되면 파라미터 추가 필요 ?
+/**
+ *
+ * @param children
+ * @param titleName : 메인 타이틀, 첫번째 요소 타이틀, 두번째 요소 타이틀
+ * @param form : zod 스키마
+ * @param onSubmitEvent : 폼 이벤트 처리
+ * @param graphBtn : 하단에 그래프 버튼 유무 처리
+ * @returns
+ */
+const BaseLayout = ({
+ children,
+ titleName,
+ form,
+ onSubmitEvent,
+ graphBtn = false,
+ analysisBtn,
+ selectBox,
+ showDatePicker = false,
+ enoCd,
+ setEnoCd,
+ ctpvCd,
+ setCtpvCd,
+ sigungu,
+ setSigungu,
+ selectedSwageTreatmentPlant,
+ onSwageTreatmentPlantChange,
+ selectedSwageProcessingZone,
+ onSwageProcessingZoneChange,
+ aplcnYmFrom,
+ setAplcnYmFrom,
+ aplcnYmTo,
+ setAplcnYmTo,
+ isLoading,
+ // Excel 다운로드 관련 props 추가
+ onExcelDownload,
+ onDeleteFile,
+ onAnalysis,
+ selectedRowData
+}: BaseLayout) => {
+
+ const defaultOption: ApiSelectOption = { val: '0', text: '전체' };
+
+ const [processingZoneOptions, setProcessingZoneOptions] = useState([]);
+ const [treatmentFacilityOptions, setTreatmentFacilityOptions] = useState([]);
+ const [isLoadingAreaData, setIsLoadingAreaData] = useState(isLoading || false);
+ const [atflId, setAtflId] = useState('')
+ const [fileNm, setFileNm] = useState('')
+ const [dcrpPplMtncBizSn, setDcrpPplMtncBizSn] = useState('')
+
+ useEffect(() => {
+ const fetchData = async () => {
+ if (!sigungu || sigungu.val === '0' || !sigungu.val) {
+ console.log("BaseLayout: Skipping fetchData because sigungu.val is:", sigungu?.val);
+ setProcessingZoneOptions([defaultOption]);
+ setTreatmentFacilityOptions([defaultOption]);
+ setIsLoadingAreaData(false);
+ return;
+ }
+
+ setIsLoadingAreaData(true);
+ try {
+ // const queryParamsZone = new URLSearchParams({
+ // lyrTypeNm: 'tb_ms_swage_prcs_zone',
+ // page: '0',
+ // size: '100000',
+ // sort: 'string',
+ // });
+ // const cqlFiltersZone: string[] = [];
+ // if (sigungu.val && sigungu.val !== '0') {
+ // // console.log("시군구 코드", sigungu.val);
+ // cqlFiltersZone.push(`sgg_cd='${sigungu.val}'`);
+ // }
+ // if (cqlFiltersZone.length > 0) {
+ // queryParamsZone.append('cqlFiter', cqlFiltersZone.join(' and '));
+ // }
+
+ const queryParamsFacility = new URLSearchParams({
+ lyrTypeNm: 'tb_il_swage_prcs_fclt',
+ page: '0',
+ size: '100000', // 요청하신 URL에 맞게 50으로 변경 가능
+ sort: 'string',
+ });
+ const cqlFiltersFacility: string[] = [];
+ if (sigungu.text && sigungu.val !== '0') {
+ cqlFiltersFacility.push(`sgg_nm ILIKE '%${sigungu.text}%'`);
+ }
+ if (cqlFiltersFacility.length > 0) {
+ queryParamsFacility.append('cqlFiter', cqlFiltersFacility.join(' and ')); // API 명세에 따라 cqlFilter 또는 cqlFiter
+ }
+
+ // console.log("BaseLayout API URL for Zones:", `v1/fclts?${queryParamsZone.toString()}`);
+ console.log("BaseLayout API URL for Facilities:", `v1/fclts?${queryParamsFacility.toString()}`);
+
+ // const [zoneRes, facilityRes] = await Promise.all([
+ // getData(`v1/fclts?${queryParamsZone.toString()}`),
+ // getData(`v1/fclts?${queryParamsFacility.toString()}`)
+ // ]);
+ const facilityRes = await getData(`v1/fclts?${queryParamsFacility.toString()}`);
+ // const zones = (zoneRes.data || []).map((item: any) => ({
+ // text: item.swtrmtZoneNm || item.name || `구역 ${item.id || item.gid || item.objectid}`,
+ // val: item.fid || item.id || item.gid || item.objectid
+ // }));
+ // setProcessingZoneOptions([defaultOption, ...zones]);
+ // console.log("BaseLayout Fetched Processing Zones:", [defaultOption, ...zones]);
+
+
+ const facilities = (facilityRes.data || []).map((item: any) => ({
+ text: item.swtrmtFcltNm || item.name || `시설 ${item.id || item.gid || item.objectid}`,
+ val: item.fid || item.id || item.gid || item.objectid
+ }));
+ setTreatmentFacilityOptions([defaultOption, ...facilities]);
+ console.log("BaseLayout Fetched Treatment Facilities:", [defaultOption, ...facilities]);
+
+ } catch (error) {
+ console.error("BaseLayout: 지역/시설 데이터 조회 중 오류 발생:", error);
+ setProcessingZoneOptions([defaultOption]);
+ setTreatmentFacilityOptions([defaultOption]);
+ } finally {
+ setIsLoadingAreaData(false);
+ }
+ };
+
+ fetchData();
+ }, [sigungu]); // sigungu 상태가 변경될 때마다 실행
+
+ // 파일 다운로드
+ const isChckFile = () => {
+ // Excel 다운로드 함수가 있으면 Excel 다운로드 실행
+ if (onExcelDownload) {
+ onExcelDownload();
+ return;
+ }
+ return true
+ }
+ // 파일 삭제
+ const isDeleteFile = async () => {
+ // Excel 다운로드 함수가 있으면 Excel 다운로드 실행
+ if (onDeleteFile) {
+ onDeleteFile();
+ return;
+ }
+ }
+
+ return (
+
+
+ {
+ children?.[1] != null ?
+
+
{titleName?.secondCardTitle}
+
+ {graphBtn ? : null}
+ {/* 그래프 있을 시 */}
+ {graphBtn ? : null}
+
+
+ {children?.[1]}
+ : null
+ }
+
+ )
+}
+
+export default BaseLayout
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/ii/irsetting/page.tsx b/apps/sn/app/(with-base-layout)/ii/irsetting/page.tsx
new file mode 100644
index 000000000..0e7a5c331
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/ii/irsetting/page.tsx
@@ -0,0 +1,451 @@
+'use client'
+import { postData } from '@/components/lib/api'
+import FileUploadForm from '@/components/ui/fileUploadForm'
+import FormSection from '@/components/ui/formSection'
+import { DateMonthPicker, filePicked } from '@common/business_components/ui'
+import ListDiv from '@common/business_components/ui/list_div'
+import { Input } from '@common/components/ui'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { z } from 'zod'
+import { excelToFlowRateData, excelToMatchingResultData, excelToTimePatternData } from '@/components/lib/utils'
+import BaseLayout from '../BaseLayout'
+import { validateMultipleFiles, FILE_EXTENSIONS, type FileValidationConfig } from '../../fileValidation';
+import { validateBasicSelectionsWithAlert } from '../../selectionValidation';
+
+const formSchema = z.object({
+ managenm: z.string(),
+ region: z.string(),
+ suyeonga: z.number(),
+ inputdate: z.coerce.date(),
+ rtkSource: z.string(),
+ suyeongaPlace: z.string(),
+ pattern: z.string()
+})
+
+// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
+interface UploadedFileInfo {
+ file: File | null;
+ atflCd: string | null;
+ atflId: string | null;
+ // 필요하다면 파일 이름 등 추가 정보 저장 가능
+ // fileName: string;
+}
+// 초기 파일 정보 상태
+const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
+
+interface ApiSelectOption {
+ text: string;
+ val: string;
+}
+
+const IrSetting = () => {
+ const form = useForm>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ managenm: "",
+ region: "",
+ suyeonga: 0,
+ inputdate: new Date(),
+ rtkSource: "",
+ suyeongaPlace: "",
+ pattern: ""
+ }
+ })
+
+ const [uploadedFilesData, setUploadedFilesData] = useState([
+ initialFileInfo, // 0: 오수관망도
+ initialFileInfo, // 1: 수용가-맨홀 매칭결과
+ initialFileInfo, // 2: 오수량 시간패턴
+ initialFileInfo // 3: 유량자료 등록
+ ]);
+
+ // selectedDate를 yyyyMM 문자열 형식으로 변경
+ const [selectedDate, setSelectedDate] = useState(() => {
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ });
+ const [input1, setInput1] = useState('');
+ const [input2, setInput2] = useState('');
+ const [select1, setSelect1] = useState('0'); // 환경청코드
+ const [select2, setSelect2] = useState('0'); // 시도코드
+ const [select3, setSelect3] = useState({ val: '0', text: '전체' }); // 시군구 상태를 객체로 변경
+ const [select4, setSelect4] = useState('0'); // 하수처리장코드
+ const [select5, setSelect5] = useState('0'); // 하수처리구역코드
+ const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
+ const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
+
+ // 폼 초기화 함수
+ const resetAllForms = () => {
+ form.reset({ // react-hook-form 초기화
+ managenm: "",
+ region: "",
+ suyeonga: 0,
+ inputdate: new Date(),
+ rtkSource: "",
+ suyeongaPlace: "",
+ pattern: ""
+ });
+ setUploadedFilesData([ // 파일 업로드 상태 초기화
+ initialFileInfo,
+ initialFileInfo,
+ initialFileInfo,
+ initialFileInfo
+ ]);
+ // selectedDate를 현재 연월로 초기화
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ setSelectedDate(`${year}${month}`);
+ setInput1(''); // 입력 필드 초기화
+ setInput2(''); // 입력 필드 초기화
+ setSelect1('0'); // 선택 필드 초기화
+ setSelect2('0');
+ setSelect3({ val: '0', text: '전체' });
+ setSelect4(0);
+ setSelect5(0);
+ setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
+ };
+
+ // FileUploadForm의 onFileSelect prop으로 전달될 콜백 함수
+ const handleFileSelection = (
+ index: number, // FileUploadForm의 fileIdx 값
+ selectedFile: File | null,
+ cd: string | null,
+ id: string | null
+ ) => {
+ setUploadedFilesData(prevData => {
+ const newData = [...prevData];
+ newData[index] = {
+ file: selectedFile,
+ atflCd: cd,
+ atflId: id,
+ };
+ return newData;
+ });
+ console.log(`Page: File data received for form index ${index}`, { fileName: selectedFile?.name, cd, id });
+ };
+
+
+ const registFile = async (analysisData: any) => {
+ setIsLoadingResult(true); // 로딩 상태 시작
+ console.log("Submitting combined analysis data to backend:", analysisData);
+ // 추후 API 엔드포인트에 맞게 URL 수정 필요
+ const data = await postData('v1/inftwtAnls', analysisData);
+ console.log("Response from backend:", data);
+ if (data) {
+ setIsLoadingResult(false); // 로딩 상태 시작
+ alert("분석 데이터가 성공적으로 제출되었습니다.");
+ resetAllForms(); // 성공 시 폼 초기화 함수 호출
+ } else {
+ setIsLoadingResult(false); // 로딩 상태 시작
+ alert("분석 데이터 제출 중 오류가 발생했습니다.");
+ }
+ };
+
+ // 침입수 분석 실행 버튼 클릭 핸들러
+ const handleAnalysisClick = async () => {
+ setIsLoadingResult(true); // 로딩 상태 시작
+
+ // 기본 선택 항목들 검증 (환경청, 시도, 시군구, 하수처리장)
+ if (!validateBasicSelectionsWithAlert(select1, select2, select3, select4, {
+ requireEnv: true,
+ requireSido: true,
+ requireSigungu: true,
+ requireTreatmentPlant: true
+ })) {
+ setIsLoadingResult(false);
+ return;
+ }
+
+ console.log(uploadedFilesData);
+ const file1 = uploadedFilesData[0]; // 오수관망도
+ const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
+ const file3 = uploadedFilesData[2]; // 오수량 시간패턴
+ const file4 = uploadedFilesData[3]; // 유량자료
+
+ console.log("오수관망도 정보:", file1?.file);
+ console.log("수용가-맨홀 매칭결과 정보:", file2);
+ console.log("오수량 시간패턴 정보:", file3);
+ console.log("유량자료 정보:", file4);
+
+ // 모든 필수 파일이 선택되었는지 확인 (UploadedFileInfo 객체와 그 안의 file 객체 모두 확인)
+ // 유량자료는 선택값
+ if (!file1?.file || !file2?.file || !file3?.file) {
+ setIsLoadingResult(false);
+ alert('모든 분석용 파일을 선택해주세요.');
+ return;
+ }
+
+ // 파일 확장자 검증 (분리된 유틸리티 사용)
+ const validationConfigs: FileValidationConfig[] = [
+ {
+ file: file1.file,
+ allowedExtensions: FILE_EXTENSIONS.INP,
+ fileDescription: '오수관망도'
+ },
+ {
+ file: file2.file,
+ allowedExtensions: FILE_EXTENSIONS.EXCEL,
+ fileDescription: '수용가-맨홀 매칭결과'
+ },
+ {
+ file: file3.file,
+ allowedExtensions: FILE_EXTENSIONS.EXCEL,
+ fileDescription: '오수량 시간패턴'
+ }
+ ];
+
+ // 유량자료 파일이 있는 경우 검증 목록에 추가
+ if (file4?.file) {
+ validationConfigs.push({
+ file: file4.file,
+ allowedExtensions: FILE_EXTENSIONS.EXCEL,
+ fileDescription: '유량자료'
+ });
+ }
+
+ // 파일 확장자 검증 실행
+ const validationResult = validateMultipleFiles(validationConfigs);
+ if (!validationResult.isValid) {
+ setIsLoadingResult(false);
+ alert(validationResult.errorMessage);
+ return;
+ }
+
+ // 오수전환율 값 0 ~ 1 사이인지 검증
+ if (input1 === '' || input1 === null || input1 === undefined) {
+ setIsLoadingResult(false);
+ console.error('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ alert('오수전환율을 입력해주세요.');
+ return;
+ }
+
+ const numericInput1 = parseFloat(input1);
+ if (isNaN(numericInput1) || numericInput1 < 0 || numericInput1 > 1) {
+ setIsLoadingResult(false);
+ console.error('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ alert('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ return;
+ }
+
+ type MatchingResult = { anlsSn: number; mhlMngNo: string; rcptrNo: string; };
+ type TimePattern = { hrId: number; rt?: number | null | undefined; };
+ type FlowRate = { pplMngNo: string; mtrngDt: string; oilq?: number | null | undefined; };
+
+ const filePickers: {
+ file: UploadedFileInfo;
+ parser: (excelData: any) => MatchingResult[] | TimePattern[] | FlowRate[];
+ }[] = [
+ { file: file2, parser: excelToMatchingResultData },
+ { file: file3, parser: excelToTimePatternData }
+ ];
+
+ if (file4?.file) {
+ filePickers.push({ file: file4, parser: excelToFlowRateData });
+ }
+
+ try {
+ const parsedResults = await Promise.all(
+ filePickers.map(async ({ file, parser }) => {
+ if (!file || !file.file) return null;
+
+ const jsonData = await filePicked(file.file, 0);
+
+ if (jsonData === undefined) {
+ console.warn(`Warning: filePicked returned undefined for ${file.file.name}`);
+ return {
+ fileName: file.file.name,
+ atflCd: file.atflCd,
+ atflId: file.atflId,
+ parsedData: null
+ };
+ }
+
+ // jsonData를 각 parser 함수로 처리
+ const parsedDataBySpecificFunction = parser(jsonData);
+
+ return {
+ fileName: file.file.name,
+ atflCd: file.atflCd,
+ atflId: file.atflId,
+ parsedData: parsedDataBySpecificFunction
+ };
+ })
+ );
+
+ // 각 파싱 결과 접근
+ const matchingResultData = parsedResults.find(r => r && r.fileName === file2.file?.name)?.parsedData;
+ const timePatternData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
+ const flowRateData = file4?.file
+ ? parsedResults.find(r => r && r.fileName === file4.file?.name)?.parsedData
+ : null;
+
+ // 새로운 JSON 데이터 생성
+ const combinedAnalysisData = {
+ enoCd: (select1 && select1 !== '0') ? select1.toString() : null, // 환경청코드 (선택값)
+ ctpvCd: (select2 && select2 !== '0') ? select2.toString() : null, // 시도코드 (선택값)
+ sggCd: (select3.val && select3.val !== '0') ? select3.val.toString() : null, // 시군구코드 (선택값)
+ swageTmplntCd: (select4 && select4 !== '0' && select4 !== 0)
+ ? select4.toString().split('.').pop() || null // '.'으로 split해서 마지막 부분만 사용
+ : null, // 하수처리장코드 (선택값)
+ swtrmtZoneCd: (select5 && select5 !== '0' && select5 !== 0)
+ ? select5.toString().split('.').pop() || null // '.'으로 split해서 마지막 부분만 사용
+ : null, // 하수처리구역코드 (선택값)
+ aplcnYm: selectedDate, // 적용연월
+ drtwSwtcRt: parseFloat(input1) || null, // 오수전환율 (숫자로 변환)
+ anlsInfo: input2, // 분석정보
+ atflCd: file1?.atflCd, // 첨부파일CD (오수관망도)
+ atflId: file1?.atflId, // 첨부파일ID (오수관망도)
+ atflInpNm: file1?.file?.name, // 오수관망도 파일명
+ atflHrPttnNm: file3?.file?.name, // 오수량 시간패턴 파일명
+ atflMpngNm: file2?.file?.name, // 수용가-맨홀 매칭결과 파일명
+ atflOilqNm: file4?.file?.name || null, // 유량자료 파일명 (없을 수 있음)
+ tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
+ tbSnHrPttn: timePatternData, // 오수량 시간패턴
+ tbSnOilqData: flowRateData, // 유량자료 (없을 수 있음)
+ };
+
+ console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
+
+ // 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
+ await registFile(combinedAnalysisData);
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("파일 파싱 중 오류 발생:", error);
+ alert("파일 처리 중 오류가 발생했습니다.");
+ return;
+ }
+ }
+
+ return (
+ <>
+ { }}
+ graphBtn={false}
+ analysisBtn={'침입수분석 실행'}
+ selectBox={{ title: '분석 대상지역 선택' }}
+ enoCd={select1}
+ setEnoCd={setSelect1}
+ ctpvCd={select2}
+ setCtpvCd={setSelect2}
+ sigungu={select3}
+ setSigungu={setSelect3}
+ selectedSwageTreatmentPlant={select4}
+ onSwageTreatmentPlantChange={setSelect4}
+ selectedSwageProcessingZone={select5}
+ onSwageProcessingZoneChange={setSelect5}
+ isLoading={isLoadingResult}
+ onAnalysis={handleAnalysisClick}
+ >
+ {[
+
+ handleFileSelection(0, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".inp"}
+ fileIdx={0} />
+
+
+ handleFileSelection(1, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".xls, .xlsx, .xlsm, .xltx"}
+ fileIdx={1} />
+
+
+ handleFileSelection(2, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".xls, .xlsx, .xlsm, .xltx"}
+ fileIdx={2} />
+
+
+ {/* 연월 선택 라이브러리로 수정 필요 */}
+ {
+ setSelectedDate(value);
+ }
+ }}
+ selectClass="ml-5 w-[150px]"
+ startYear={1900} // 시작 연도 설정
+ />
+
+
+ {
+ const newValue = e.target.value;
+
+ if (newValue === "") {
+ setInput1(newValue);
+ return;
+ }
+
+ // 숫자와 '.'만 허용하고, '.'은 최대 하나인지 확인
+ const isValidChars = /^[0-9]*\.?[0-9]*$/.test(newValue);
+ if (!isValidChars) return; // 유효하지 않은 문자 또는 여러 개의 '.' 포함
+
+ // '.' 기호가 포함된 경우, 처음이나 끝에 오면 안 됨
+ if (newValue.includes('.') && newValue.startsWith('.')) return; // '.'이 처음에는 올 수 없음
+
+ // 숫자 값으로 변환하여 범위 체크 (0 이상 1 이하)
+ const numericValue = parseFloat(newValue);
+ if (isNaN(numericValue) || numericValue < 0 || numericValue > 1) return;
+
+ setInput1(newValue);
+ }}
+ className="ml-5 h-[3.2rem] text-center text-xl w-[150px]"
+ placeholder="예: 0.75"
+ />
+
+
+ setInput2(e.target.value)}
+ className="ml-5 h-[3.2rem] text-center text-xl w-[150px]" />
+
+
+
+
+ handleFileSelection(3, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".xls, .xlsx, .xlsm, .xltx"}
+ fileIdx={3}
+ />
+
+
+
+
]}
+
+ >
+ )
+}
+
+export default IrSetting
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/ii/rdii/page.tsx b/apps/sn/app/(with-base-layout)/ii/rdii/page.tsx
new file mode 100644
index 000000000..970c6d1a9
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/ii/rdii/page.tsx
@@ -0,0 +1,517 @@
+"use client"
+
+import { postData } from '@/components/lib/api'
+import FileUploadForm from "@/components/ui/fileUploadForm"
+import FormSection from "@/components/ui/formSection"
+import BaseLayout from "../BaseLayout"
+import { DateMonthPicker, filePicked } from "@common/business_components/ui"
+import { Input } from "@common/components/ui"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Label } from '@radix-ui/react-label'
+import { useState } from "react"
+import { useFieldArray, useForm } from "react-hook-form"
+import { z } from "zod"
+import { excelToMatchingResultData, excelToRainData } from '@/components/lib/utils'
+import { EditableFormTable, type EditableTableHeadItem } from '../../../components/ui/EditableFormTable'
+import { validateMultipleFiles, FILE_EXTENSIONS, type FileValidationConfig } from '../../fileValidation';
+import { validateBasicSelectionsWithAlert } from '../../selectionValidation';
+
+
+// zod 스키마 정의
+const formSchema = z.object({
+ enoCd: z.string(), // 환경청코드
+ ctpvCd: z.string(), // 시도코드
+ sggCd: z.string(), // 시군구코드
+ swageTmplntCd: z.string(), // 하수처리장코드
+ swtrmtZoneCd: z.string(), // 하수처리구역코드
+ rtkSource: z.string(), // RTK계수 출처
+ rdiiArea: z.string(), // RDII 기여면적
+ unitFactors: z.array(z.object({ // 단위도 계수
+ response: z.string(),
+ R: z.string(),
+ T: z.string(),
+ K: z.string(),
+ })),
+ initialDepths: z.array(z.object({ // 초기 차단 깊이
+ response: z.string(),
+ Dmax: z.string(),
+ Drec: z.string(),
+ Do: z.string(),
+ })),
+ // osumap: z.instanceof(File).optional(), // 오수관망도
+ // matching: z.instanceof(File).optional(), // 수용가-맨홀 매칭결과
+ aplcnYm: z.string(), // 상수사용량 적용월 (YYYYMM 형식)
+ rate: z.string(), // 오수전환율
+ // rain: z.instanceof(File).optional(), // 강우자료
+ analysisInfo: z.string().optional(), // 분석 정보
+ date: z.string(), // Date 객체에서 string(yyyyMM 형식)으로 변경
+ // date: z.coerce.date(),
+})
+// zod 스키마 타입 추론
+type FormSchemaType = z.infer;
+// 기본 폼 값 정의 (테스트 편의를 위해 초기값 설정, 추후 삭제 필요)
+const defaultFormValues: FormSchemaType = {
+ enoCd: "",
+ ctpvCd: "",
+ sggCd: "",
+ swageTmplntCd: "",
+ swtrmtZoneCd: "",
+ rtkSource: "출처",
+ rdiiArea: "123", // 문자열로 기본값 설정
+ unitFactors: [
+ { response: "Short-Term", R: "0.040", T: "0.5", K: "1" }, // 문자열로 기본값 설정
+ { response: "Medium-Term", R: "0.005", T: "1", K: "2" },
+ { response: "Long-Term", R: "0.005", T: "2", K: "3" },
+ ],
+ initialDepths: [
+ { response: "Short-Term", Dmax: "0", Drec: "0", Do: "0" }, // 문자열로 기본값 설정
+ { response: "Medium-Term", Dmax: "0", Drec: "0", Do: "0" },
+ { response: "Long-Term", Dmax: "0", Drec: "0", Do: "0" },
+ ],
+ // osumap: undefined,
+ // matchingResultFile: undefined,
+ aplcnYm: "",
+ rate: "0.8", // 문자열로 기본값 설정
+ // rainFile: undefined,
+ analysisInfo: "test 분석정보",
+ date: (() => { // 현재 연월을 yyyyMM 형식으로 설정
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ })(),
+};
+
+// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
+interface UploadedFileInfo {
+ file: File | null;
+ atflCd: string | null;
+ atflId: string | null;
+}
+
+// 초기 파일 정보 상태
+const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
+
+interface ApiSelectOption {
+ text: string;
+ val: string;
+}
+
+export default function RTKForm() {
+ const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
+ const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
+
+ // FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
+ // 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
+ const [uploadedFilesData, setUploadedFilesData] = useState([
+ initialFileInfo, // 0: 오수관망도
+ initialFileInfo, // 1: 수용가-맨홀 매칭결과
+ initialFileInfo, // 2: 강우자료
+ ]);
+
+ const [select1, setSelect1] = useState('0'); // 환경청코드 (enoCd)
+ const [select2, setSelect2] = useState('0'); // 시도코드 (ctpvCd)
+ const [select3, setSelect3] = useState({ val: '0', text: '전체' }); // 시군구 (sggCd)
+ const [select4, setSelect4] = useState('0'); // 하수처리장 (swageTmplntCd)
+ const [select5, setSelect5] = useState('0'); // 하수처리구역 (swtrmtZoneCd)
+
+ // form 인스턴스 생성
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues: defaultFormValues
+ });
+
+ // 폼 초기화 함수
+ const resetAllForms = () => {
+ form.reset(defaultFormValues); // 폼 값 초기화
+ setUploadedFilesData([ // 파일 업로드 상태 초기화 (3개 파일)
+ initialFileInfo,
+ initialFileInfo,
+ initialFileInfo,
+ ]);
+ setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
+ setSelect1('0');
+ setSelect2('0');
+ setSelect3({ val: '0', text: '전체' });
+ setSelect4('0');
+ setSelect5('0');
+ };
+
+ // FileUploadForm의 onFileSelect prop으로 전달될 콜백 함수
+ const handleFileSelection = (
+ index: number, // FileUploadForm의 fileIdx 값
+ selectedFile: File | null,
+ cd: string | null,
+ id: string | null
+ ) => {
+ setUploadedFilesData(prevData => {
+ const newData = [...prevData];
+ newData[index] = {
+ file: selectedFile,
+ atflCd: cd,
+ atflId: id,
+ };
+ return newData;
+ });
+ console.log(`Page: File data received for form index ${index}`, { fileName: selectedFile?.name, cd, id });
+ };
+
+ const registFile = async (analysisData: any) => {
+ console.log("Submitting combined analysis data to backend");
+ // 추후 API 엔드포인트에 맞게 URL 수정 필요
+ const data = await postData('v1/rdiiAnls', analysisData);
+ if (data) {
+ alert("분석 데이터가 성공적으로 제출되었습니다.");
+ resetAllForms(); // 성공 시 폼 초기화 함수 호출
+ } else alert("분석 데이터 제출 중 오류가 발생했습니다.");
+ };
+
+ // 침입수 분석 실행 버튼 클릭 핸들러
+ const handleAnalysisClick = async () => {
+ setIsLoadingResult(true); // 로딩 상태 시작
+
+ // 기본 선택 항목들 검증 (환경청, 시도, 시군구, 하수처리장)
+ if (!validateBasicSelectionsWithAlert(select1, select2, select3, select4, {
+ requireEnv: true,
+ requireSido: true,
+ requireSigungu: true,
+ requireTreatmentPlant: true
+ })) {
+ setIsLoadingResult(false);
+ return;
+ }
+
+ const formData = form.getValues();
+ console.log(uploadedFilesData);
+ const file1 = uploadedFilesData[0]; // 오수관망도
+ const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
+ const file3 = uploadedFilesData[2]; // 강우자료
+
+ console.log("오수관망도 정보:", file1?.file);
+ console.log("수용가-맨홀 매칭결과 정보:", file2);
+ console.log("강우자료:", file3);
+
+ // 모든 필수 파일이 선택되었는지 확인
+ if (!file1?.file || !file2?.file || !file3?.file) {
+ setIsLoadingResult(false);
+ alert('모든 분석용 파일을 선택해주세요.');
+ return;
+ }
+
+ // 파일 확장자 검증 (분리된 유틸리티 사용)
+ const validationConfigs: FileValidationConfig[] = [
+ {
+ file: file1.file,
+ allowedExtensions: FILE_EXTENSIONS.INP,
+ fileDescription: '오수관망도'
+ },
+ {
+ file: file2.file,
+ allowedExtensions: FILE_EXTENSIONS.EXCEL,
+ fileDescription: '수용가-맨홀 매칭결과'
+ },
+ {
+ file: file3.file,
+ allowedExtensions: FILE_EXTENSIONS.EXCEL,
+ fileDescription: '오수량 시간패턴'
+ }
+ ];
+
+ // 파일 확장자 검증 실행
+ const validationResult = validateMultipleFiles(validationConfigs);
+ if (!validationResult.isValid) {
+ setIsLoadingResult(false);
+ alert(validationResult.errorMessage);
+ return;
+ }
+
+ // 오수전환율 값 0 ~ 1 사이인지 검증
+ const rateValue = form.getValues().rate;
+ if (rateValue === '' || rateValue === null || rateValue === undefined) {
+ setIsLoadingResult(false);
+ console.error('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ alert('오수전환율을 입력해주세요.');
+ return;
+ }
+
+ const numericInput1 = parseFloat(rateValue);
+ if (isNaN(numericInput1) || numericInput1 < 0 || numericInput1 > 1) {
+ setIsLoadingResult(false);
+ console.error('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ alert('오수전환율은 0에서 1 사이의 값으로 입력해야 합니다.');
+ return;
+ }
+
+ const filePickers = [
+ { file: file2, parser: excelToMatchingResultData },
+ { file: file3, parser: excelToRainData },
+ ];
+
+ try {
+ const parsedResults = await Promise.all(
+ filePickers.map(async ({ file, parser }) => {
+ if (!file || !file.file) return null; // fileInfo 객체 및 file 객체 null 체크
+
+ // filePicked 함수에 File 객체와 headerNum 전달
+ const jsonData = await filePicked(file.file, 0);
+
+ if (jsonData === undefined) {
+ console.warn(`Warning: filePicked returned undefined for ${file.file.name}`);
+ return {
+ fileName: file.file.name,
+ atflCd: file.atflCd,
+ atflId: file.atflId,
+ parsedData: null // 또는 적절한 기본값
+ };
+ }
+
+ // jsonData를 각 parser 함수로 처리
+ // parser 함수가 filePicked가 반환하는 JSON 형식을 직접 처리한다고 가정
+ const parsedDataBySpecificFunction = parser(jsonData);
+
+ return {
+ fileName: file.file.name,
+ atflCd: file.atflCd,
+ atflId: file.atflId,
+ parsedData: parsedDataBySpecificFunction
+ };
+ })
+ );
+
+ // 각 파싱 결과 접근
+ const matchingResultData = parsedResults.find(r => r && r.fileName === file2.file?.name)?.parsedData;
+ const rainData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
+
+ // 새로운 JSON 데이터 생성
+ const combinedAnalysisData = {
+ enoCd: (select1 && select1 !== '0') ? select1.toString() : null, // 환경청코드 (선택값)
+ aplcnYm: formData.date, // 적용연월 (YYYYMM 형식)
+ ctpvCd: (select2 && select2 !== '0') ? select2.toString() : null, // 시도코드 (선택값)
+ sggCd: (select3.val && select3.val !== '0') ? select3.val.toString() : null, // 시군구코드 (선택값)
+ swageTmplntCd: (select4 && select4 !== '0' && select4 !== 0)
+ ? select4.toString().split('.').pop() || null // '.'으로 split해서 마지막 부분만 사용
+ : null, // 하수처리장코드 (선택값)
+ swtrmtZoneCd: (select5 && select5 !== '0' && select5 !== 0)
+ ? select5.toString().split('.').pop() || null // '.'으로 split해서 마지막 부분만 사용
+ : null, // 하수처리구역코드 (선택값)
+ atflCd: file1?.atflCd, // 첨부파일CD (오수관망도)
+ atflId: file1?.atflId, // 첨부파일ID (오수관망도)
+ atflInpNm: file1?.file?.name || "", // 오수관망도 파일명
+ atflMpngNm: file2?.file?.name || "", // 수용가-맨홀 매칭결과 파일명
+ atflRainNm: file3?.file?.name || "", // 강우자료 파일명
+ cntbArea: parseFloat(formData.rdiiArea) || null, // RDII 기여면적(ha)
+ srcNm: formData.rtkSource, // 출처이름 (RTK계수 출처)
+
+ shortPrdR: parseFloat(formData.unitFactors[0]?.R || "0"),
+ shortPrdT: parseFloat(formData.unitFactors[0]?.T || "0"),
+ shortPrdK: parseFloat(formData.unitFactors[0]?.K || "0"),
+
+ mdPrdR: parseFloat(formData.unitFactors[1]?.R || "0"),
+ mdPrdT: parseFloat(formData.unitFactors[1]?.T || "0"),
+ mdPrdK: parseFloat(formData.unitFactors[1]?.K || "0"),
+
+ longPrdR: parseFloat(formData.unitFactors[2]?.R || "0"),
+ longPrdT: parseFloat(formData.unitFactors[2]?.T || "0"),
+ longPrdK: parseFloat(formData.unitFactors[2]?.K || "0"),
+
+ shortPrdMaxDpth: parseFloat(formData.initialDepths[0]?.Dmax || "0"),
+ shortPrdRcvryRt: parseFloat(formData.initialDepths[0]?.Drec || "0"),
+ shortPrdBgngDpth: parseFloat(formData.initialDepths[0]?.Do || "0"),
+
+ mdPrdMaxDpth: parseFloat(formData.initialDepths[1]?.Dmax || "0"),
+ mdPrdRcvryRt: parseFloat(formData.initialDepths[1]?.Drec || "0"),
+ mdPrdBgngDpth: parseFloat(formData.initialDepths[1]?.Do || "0"),
+
+ longTermMaxDpth: parseFloat(formData.initialDepths[2]?.Dmax || "0"),
+ longTermRcvryRt: parseFloat(formData.initialDepths[2]?.Drec || "0"),
+ longTermBgngDpth: parseFloat(formData.initialDepths[2]?.Do || "0"),
+
+ drtwSwtcRt: parseFloat(formData.rate || "0"), // 오수전환율
+ anlsInfo: formData.analysisInfo, // 분석정보
+
+ tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
+ tbSnRainData: rainData, // 강우자료
+ };
+
+ console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
+
+ // 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
+ await registFile(combinedAnalysisData);
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("파일 파싱 중 오류 발생:", error);
+ alert("파일 처리 중 오류가 발생했습니다.");
+ return;
+ }
+ }
+
+ const { fields: unitFactorFields } = useFieldArray({
+ control: form.control,
+ name: "unitFactors"
+ })
+
+ const { fields: initialDepthFields } = useFieldArray({
+ control: form.control,
+ name: "initialDepths"
+ })
+
+ const onSubmit = (data: z.infer) => {
+ console.log("✅ 제출 데이터:", data)
+ }
+
+ // 단위도 계수 테이블 설정 (EditableTableHeadItem 타입 사용 및 id 수정)
+ const unitFactorHeadlist: EditableTableHeadItem[] = [
+ { id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
+ { id: 'R', title: 'R', editable: true, inputProps: { type: 'text' } },
+ { id: 'T', title: 'T', editable: true, inputProps: { type: 'text' } },
+ { id: 'K', title: 'K', editable: true, inputProps: { type: 'text' } }
+ ];
+
+ // 초기 차단 깊이 테이블 설정 (EditableTableHeadItem 타입 사용)
+ const initialDepthHeadlist: EditableTableHeadItem[] = [
+ { id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
+ { id: 'Dmax', title: 'Dmax', editable: true, inputProps: { type: 'text' } },
+ { id: 'Drec', title: 'Drec', editable: true, inputProps: { type: 'text' } },
+ { id: 'Do', title: 'Do', editable: true, inputProps: { type: 'text' } }
+ ];
+
+ // 테이블 페이지 변경 핸들러
+ const handlePageChange = (page: number) => {
+ console.log('Page changed:', page)
+ }
+
+ return (
+ // { }} graphBtn={false} >
+ { }} // BaseLayout의 form 태그에 연결될 onSubmit
+ graphBtn={false}
+ analysisBtn={'RDII분석 실행'}
+ enoCd={select1}
+ setEnoCd={setSelect1}
+ ctpvCd={select2}
+ setCtpvCd={setSelect2}
+ sigungu={select3}
+ setSigungu={setSelect3}
+ selectedSwageTreatmentPlant={select4}
+ onSwageTreatmentPlantChange={setSelect4}
+ selectedSwageProcessingZone={select5}
+ onSwageProcessingZoneChange={setSelect5}
+ isLoading={isLoadingResult}
+ onAnalysis={handleAnalysisClick}
+ >
+ {[
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ handleFileSelection(0, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".inp"}
+ fileIdx={0} />
+
+
+ handleFileSelection(1, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".xls, .xlsx, .xlsm, .xltx"}
+ fileIdx={1} />
+
+
+ handleFileSelection(2, file, cd, id)}
+ showButton={false}
+ showPreview={true}
+ accept={".xls, .xlsx, .xlsm, .xltx"}
+ fileIdx={2} />
+
+
+ {
+ const newValue = e.target.value;
+
+ if (newValue === "") {
+ form.setValue("rate", newValue); // form의 rate 필드에 설정
+ return;
+ }
+
+ // 숫자와 '.'만 허용하고, '.'은 최대 하나인지 확인
+ const isValidChars = /^[0-9]*\.?[0-9]*$/.test(newValue);
+ if (!isValidChars) return; // 유효하지 않은 문자 또는 여러 개의 '.' 포함
+
+ // '.' 기호가 처음에 오면 안 됨
+ if (newValue.startsWith('.')) return;
+
+ // 완성된 숫자인 경우에만 범위 체크 (입력 중인 경우 허용)
+ if (!newValue.endsWith('.')) {
+ const numericValue = parseFloat(newValue);
+ if (isNaN(numericValue) || numericValue < 0 || numericValue > 1) return;
+ }
+
+ form.setValue("rate", newValue, { shouldValidate: true }); // form의 rate 필드에 설정
+ }}
+ className="h-12 text-center text-xl w-[225px] ml-5"
+ placeholder="예: 0.75"
+ />
+
+
+ {
+ form.setValue("date", value, { shouldValidate: true }); // form의 date 필드에 직접 설정
+ }
+ }}
+ selectClass="ml-5 w-[200px]"
+ startYear={1900} // 시작 연도 설정
+ />
+
+
+
+
+
+ {/*
+
+
*/}
+
+ ]}
+
+ )
+}
diff --git a/apps/sn/app/(with-base-layout)/ii/rdiiResult/page.tsx b/apps/sn/app/(with-base-layout)/ii/rdiiResult/page.tsx
new file mode 100644
index 000000000..2af9cfc19
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/ii/rdiiResult/page.tsx
@@ -0,0 +1,333 @@
+'use client'
+import { deleteData, getData } from '@/components/lib/api'
+import { UiTable, downloadExcelWithKoreanHeaders } from '@common/business_components/ui'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useState, useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+import { z } from 'zod'
+import BaseLayout from '../BaseLayout'
+import { handleDelete } from '@/components/lib/utils'
+import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
+
+
+const formSchema = z.object({
+ enoCd: z.string().default('0'), // 환경청코드
+ ctpvCd: z.string().default('0'), // 시도코드
+ sggCd: z.object({ // 시군구
+ val: z.string().default('0'),
+ text: z.string().default('전체'),
+ }).default({ val: '0', text: '전체' }),
+ swageTmplntCd: z.string().default('0'), // 하수처리장
+ swtrmtZoneCd: z.string().default('0'), // 하수처리구역
+ aplcnYmFrom: z.string().default(() => { // Date에서 string(yyyyMM 형식)으로 변경
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ }), // 분석기간 시작연월
+ aplcnYmTo: z.string().default(() => { // Date에서 string(yyyyMM 형식)으로 변경
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ }), // 분석기간 종료연월
+})
+
+type ResultFormValues = z.infer
+
+const tableColumn = [
+ { id: 'rowNumber', title: '일련번호' },
+ { id: 'enoNm', title: '환경청' },
+ { id: 'ctpvNm', title: '시도' },
+ { id: 'sggNm', title: '시군구' },
+ { id: 'swageTmplntNm', title: '하수처리장' },
+ // { id: 'swtrmtZoneNm', title: '처리구역' },
+ { id: 'aplcnYm', title: '상수사용연월' },
+ { id: 'drtwSwtcRt', title: '오수 전환율' },
+ { id: 'srcNm', title: 'RTK 계수 출처' },
+ { id: 'cntbArea', title: 'RDII 기여면적' },
+ { id: 'anlsInfo', title: 'RDII 분석정보' },
+ { id: 'regDt', title: '분석일자' },
+ { id: 'rgtrNm', title: '분석자' },
+ { id: 'scsYn', title: '분석성공여부' }
+]
+
+const Result = () => {
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ enoCd: '0',
+ ctpvCd: '0',
+ sggCd: { val: '0', text: '전체' },
+ swageTmplntCd: '0',
+ swtrmtZoneCd: '0',
+ aplcnYmFrom: (() => { // 현재 연월을 yyyyMM 형식으로 설정
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ })(),
+ aplcnYmTo: (() => { // 현재 연월을 yyyyMM 형식으로 설정
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ })(),
+ }
+ })
+
+
+ const [tableData, setTableData] = useState([]); // API 조회 결과 저장 상태
+ const [totalData, setTotalData] = useState(0) //총 데이터 수
+ const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
+ const [selectedRowData, setSelectedRowData] = useState(null);
+ const [selectedRowIndex, setSelectedRowIndex] = useState(undefined);
+ const [resetSelection, setResetSelection] = useState(false);
+
+ useEffect(() => {
+ // setCurPage(1);
+ handleSearchButtonClick();
+ }, [])
+
+
+ const handleSearchButtonClick = async (customFormValues?: Partial) => {
+ setIsLoadingResult(true);
+ const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
+ console.log("formValues", formValues);
+
+ let inftwtAnlsSearchDto;
+
+ // swageTmplntCd 처리 로직 추가
+ const processedSwageTmplntCd = formValues.swageTmplntCd && formValues.swageTmplntCd !== '0'
+ ? (() => {
+ const valString = String(formValues.swageTmplntCd);
+ const parts = valString.split('.');
+ return parts.length > 1 ? parts[1] : valString;
+ })()
+ : null;
+
+ if (customFormValues) {
+ inftwtAnlsSearchDto = {
+ "aplcnYmFrom": formValues.aplcnYmFrom,
+ "aplcnYmTo": formValues.aplcnYmTo,
+ "enoCd": formValues.enoCd,
+ "ctpvCd": formValues.ctpvCd,
+ "sggCd": formValues.sggCd,
+ "swageTmplntCd": processedSwageTmplntCd,
+ };
+ } else {
+ inftwtAnlsSearchDto = {
+ "aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
+ "aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
+ "enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
+ "ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
+ "sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
+ "swageTmplntCd": processedSwageTmplntCd,
+ };
+ }
+ console.log("Search DTO:", inftwtAnlsSearchDto);
+
+ const queryParams = new URLSearchParams({
+ page: '0',
+ size: '10000000',
+ sort: 'rainInfwtAnlsSn,desc'
+ });
+ Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
+ if (value !== undefined && value !== null && String(value).trim() !== '') { // undefined, null, 빈 문자열이 아닌 경우에만 추가
+ queryParams.append(key, String(value));
+ }
+ });
+ const queryString = queryParams.toString();
+
+ console.log("API: ", `v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
+ try {
+ const data = await getData(`v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
+
+ // 🎯 각 아이템을 개별적으로 포맷팅하면서 일련번호 추가
+ const dataWithRowNumber = (data.content || []).map((item: any, index: number) => {
+ // 🎯 먼저 각 아이템을 포맷팅
+ const formattedItem = formatDisplayData(item);
+
+ // 추가 처리 및 일련번호 추가
+ return {
+ ...formattedItem,
+ rowNumber: index + 1, // 1부터 시작하는 일련번호 추가
+ scsYn: item.scsYn === null || item.scsYn === undefined ? 'N' : item.scsYn // scsYn이 null이면 'N'으로 변경
+ };
+ });
+
+ // setTableData(data.content || []);
+ // setTotalData(tableData.length);
+ setTableData(dataWithRowNumber);
+ setTotalData(dataWithRowNumber.length);
+ console.log("response:", data);
+ console.log("response data:", dataWithRowNumber);
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("Error fetching analysis result data:", error);
+ alert("분석결과 조회 중 오류가 발생했습니다.");
+ setTableData([]);
+ setTotalData(0);
+ }
+ };
+
+ // 테이블 셀 클릭 핸들러 추가
+ const handleCellClick = (index: number | undefined, headId: string) => {
+ if (index !== undefined && tableData[index]) {
+ setSelectedRowData(tableData[index]);
+ setSelectedRowIndex(index);
+ console.log("Selected row data:", tableData[index]);
+ }
+ };
+
+ // Excel 다운로드 핸들러 추가
+ const handleExcelDownload = async () => {
+ setIsLoadingResult(true);
+ console.log("Selected row data for download:", selectedRowData);
+ if (!selectedRowData || selectedRowData.rainInfwtAnlsSn === undefined) {
+ setIsLoadingResult(false);
+ alert('다운로드할 데이터를 선택해주세요.');
+ return;
+ }
+
+ try {
+ const data = await getData(`v1/rdiiAnlsRslt/ppl/${selectedRowData.rainInfwtAnlsSn}`);
+
+ // 선택된 행 데이터를 Excel 다운로드 형식으로 변환
+ const excelData = data.content; // 배열로 감싸서 전달
+
+ // 헤더 매핑 정의
+ const headerMapping: { [key: string]: string } = {
+ 'rainInfwtAnlsSn': 'RDII분석\n일련번호',
+ 'pplMngNo': '관로\n관리번호',
+ 'anlsTm': '분석시각',
+ 'predcOilq': '예측유량\n(m³/h)'
+ };
+
+ // 파일명 생성 (분석번호 기반)
+ const fileName = `RDII분석결과_${selectedRowData.swageTmplntNm}_${selectedRowData.aplcnYm}_${selectedRowData.rainInfwtAnlsSn}`;
+
+ await downloadExcelWithKoreanHeaders({
+ data: excelData as JSON[],
+ fileName: fileName,
+ sheetNameArray: ["RDII 분석결과"],
+ headerRange: "A1:D1",
+ headerMapping: headerMapping
+ });
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("Excel 다운로드 중 오류 발생:", error);
+ alert("Excel 다운로드 중 오류가 발생했습니다. 다시 시도해주세요.");
+ }
+ };
+
+ // 파일 삭제 핸들러 추가
+ const handleFileDelete = async () => {
+ setIsLoadingResult(true);
+ console.log("Selected row data for deletion:", selectedRowData);
+ if (!selectedRowData || selectedRowData.rainInfwtAnlsSn === undefined) {
+ alert('삭제할 파일을 선택해주세요.');
+ return;
+ }
+ // 삭제 확인 대화상자
+ const confirmDelete = window.confirm('선택된 분석 결과를 삭제하시겠습니까?');
+ if (!confirmDelete) {
+ return;
+ }
+
+ try {
+ // 삭제 API 호출
+ const response1 = await deleteData(`v1/rdiiAnlsRslt/${selectedRowData.rainInfwtAnlsSn}`);
+ const response2 = await deleteData(`v1/rdiiAnls/${selectedRowData.rainInfwtAnlsSn}`);
+ // 첨부파일(inp파일) 삭제 API 호출
+ handleDelete(selectedRowData.atflCd, {
+ handleDeleteStart: () => console.log("파일 삭제 시작"),
+ handleDeleteSuccess: (response) => console.log("파일 삭제 성공:", response),
+ handleDeleteError: (error) => console.error("파일 삭제 실패:", error),
+ });
+ console.log("File delete response1:", response1);
+ console.log("File delete response2:", response2);
+
+ // 테이블 선택 상태 초기화 트리거
+ setResetSelection(true);
+
+ // 삭제 후 테이블 새로고침을 위해 재검색
+ const customFormValues: Partial = {
+ aplcnYmFrom: selectedRowData.aplcnYmFrom || null,
+ aplcnYmTo: selectedRowData.aplcnYmTo || null,
+ enoCd: selectedRowData.enoCd || null,
+ ctpvCd: selectedRowData.ctpvCd || null,
+ sggCd: selectedRowData.sggCd || null,
+ swageTmplntCd: selectedRowData.swageTmplntCd || null,
+ };
+ await handleSearchButtonClick(customFormValues);
+
+ // 선택된 행 초기화
+ setSelectedRowData(null);
+ setSelectedRowIndex(undefined);
+ setIsLoadingResult(false);
+
+ alert('삭제가 완료되었습니다.');
+
+ setTimeout(() => {
+ setResetSelection(false);
+ }, 100);
+ } catch (error) {
+ console.error("분석결과 파일 삭제 중 오류 발생:", error);
+ alert("분석결과 파일 삭제 중 오류가 발생했습니다. 다시 시도해주세요.");
+ }
+ setIsLoadingResult(false);
+ };
+
+ return (
+ { }} // BaseLayout의 form 태그에 연결될 onSubmit
+ graphBtn={true}
+ showDatePicker={true}
+ enoCd={form.watch("enoCd")}
+ setEnoCd={(val) => form.setValue("enoCd", val)}
+ ctpvCd={form.watch("ctpvCd")}
+ setCtpvCd={(val) => form.setValue("ctpvCd", val)}
+ sigungu={form.watch("sggCd")}
+ setSigungu={(val) => form.setValue("sggCd", val)}
+ selectedSwageTreatmentPlant={form.watch("swageTmplntCd")}
+ onSwageTreatmentPlantChange={(val) => form.setValue("swageTmplntCd", String(val))}
+ selectedSwageProcessingZone={form.watch("swtrmtZoneCd")}
+ onSwageProcessingZoneChange={(val) => form.setValue("swtrmtZoneCd", String(val))}
+ aplcnYmFrom={form.watch("aplcnYmFrom")}
+ setAplcnYmFrom={(val: string) => { form.setValue("aplcnYmFrom", val) }}
+ aplcnYmTo={form.watch("aplcnYmTo")}
+ setAplcnYmTo={(val: string) => { form.setValue("aplcnYmTo", val) }}
+ isLoading={isLoadingResult}
+ // Excel 다운로드 핸들러 추가
+ onExcelDownload={handleExcelDownload}
+ onDeleteFile={handleFileDelete}
+ selectedRowData={selectedRowData}
+ >
+ {[
+
○ RDII 분석결과 현황
+
+ { }}
+ resetSelection={resetSelection}
+ />
+
+
+ ]}
+
+ )
+}
+
+export default Result
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/ii/result/page.tsx b/apps/sn/app/(with-base-layout)/ii/result/page.tsx
new file mode 100644
index 000000000..ab8d397e0
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/ii/result/page.tsx
@@ -0,0 +1,336 @@
+'use client'
+import { deleteData, getData } from '@/components/lib/api'
+import { UiTable, downloadExcel, downloadExcelWithKoreanHeaders } from '@common/business_components/ui'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useState, useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+import { z } from 'zod'
+import BaseLayout from '../BaseLayout'
+import { handleDelete } from '@/components/lib/utils'
+import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
+
+
+const formSchema = z.object({
+ enoCd: z.string().default('0'), // 환경청코드
+ ctpvCd: z.string().default('0'), // 시도코드
+ sggCd: z.object({ // 시군구
+ val: z.string().default('0'),
+ text: z.string().default('전체'),
+ }).default({ val: '0', text: '전체' }),
+ swageTmplntCd: z.string().default('0'), // 하수처리장
+ swtrmtZoneCd: z.string().default('0'), // 하수처리구역
+ aplcnYmFrom: z.string().default(() => { // Date에서 string(yyyyMM 형식)으로 변경
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ }), // 분석기간 시작연월
+ aplcnYmTo: z.string().default(() => { // Date에서 string(yyyyMM 형식)으로 변경
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ }), // 분석기간 종료연월
+})
+
+type ResultFormValues = z.infer
+
+const tableColumn = [
+ { id: 'rowNumber', title: '일련번호' },
+ { id: 'enoNm', title: '환경청' },
+ { id: 'ctpvNm', title: '시도' },
+ { id: 'sggNm', title: '시군구' },
+ { id: 'swageTmplntNm', title: '하수처리장' },
+ // { id: 'swtrmtZoneNm', title: '처리구역' },
+ { id: 'aplcnYm', title: '적용연월' },
+ { id: 'drtwSwtcRt', title: '오수 전환율' },
+ { id: 'anlsInfo', title: '침입수 분석정보' },
+ { id: 'regDt', title: '분석일자' },
+ { id: 'rgtrNm', title: '분석자' },
+ { id: 'scsYn', title: '분석성공여부' }
+]
+
+const Result = () => {
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ enoCd: '0',
+ ctpvCd: '0',
+ sggCd: { val: '0', text: '전체' },
+ swageTmplntCd: '0',
+ swtrmtZoneCd: '0',
+ aplcnYmFrom: (() => { // 현재 연월을 yyyyMM 형식으로 설정
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ })(),
+ aplcnYmTo: (() => { // 현재 연월을 yyyyMM 형식으로 설정
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ return `${year}${month}`;
+ })(),
+ }
+ })
+
+
+ const [tableData, setTableData] = useState([]); // API 조회 결과 저장 상태
+ const [totalData, setTotalData] = useState(0) //총 데이터 수
+ const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
+ const [selectedRowData, setSelectedRowData] = useState(null);
+ const [selectedRowIndex, setSelectedRowIndex] = useState(undefined);
+ const [resetSelection, setResetSelection] = useState(false);
+
+ useEffect(() => {
+ // setCurPage(1);
+ handleSearchButtonClick();
+ }, [])
+
+ const handleSearchButtonClick = async (customFormValues?: Partial) => {
+ setIsLoadingResult(true);
+ const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
+ console.log("formValues", formValues);
+
+ let inftwtAnlsSearchDto;
+
+ // swageTmplntCd 처리 로직 추가
+ const processedSwageTmplntCd = formValues.swageTmplntCd && formValues.swageTmplntCd !== '0'
+ ? (() => {
+ const valString = String(formValues.swageTmplntCd);
+ const parts = valString.split('.');
+ return parts.length > 1 ? parts[1] : valString;
+ })()
+ : null;
+
+ if (customFormValues) {
+ inftwtAnlsSearchDto = {
+ "aplcnYmFrom": formValues.aplcnYmFrom,
+ "aplcnYmTo": formValues.aplcnYmTo,
+ "enoCd": formValues.enoCd,
+ "ctpvCd": formValues.ctpvCd,
+ "sggCd": formValues.sggCd,
+ "swageTmplntCd": processedSwageTmplntCd,
+ // "swtrmtZoneCd": formValues.swtrmtZoneCd,
+ };
+ } else {
+ inftwtAnlsSearchDto = {
+ "aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
+ "aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
+ "enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
+ "ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
+ "sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
+ "swageTmplntCd": processedSwageTmplntCd,
+ // "swtrmtZoneCd": formValues.swtrmtZoneCd === '0' ? null : formValues.swtrmtZoneCd,
+ };
+ }
+ console.log("Search DTO:", inftwtAnlsSearchDto);
+
+ const queryParams = new URLSearchParams({
+ page: '0',
+ size: '10000000',
+ sort: 'inftwtAnlsSn,desc'
+ });
+ Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
+ if (value !== undefined && value !== null && String(value).trim() !== '') { // undefined, null, 빈 문자열이 아닌 경우에만 추가
+ queryParams.append(key, String(value));
+ }
+ });
+ const queryString = queryParams.toString();
+
+ console.log("API: ", `v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
+ try {
+ const data = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
+
+ // 🎯 각 아이템을 개별적으로 포맷팅하면서 일련번호 추가
+ const dataWithRowNumber = (data.content || []).map((item: any, index: number) => {
+ // 🎯 먼저 각 아이템을 포맷팅
+ const formattedItem = formatDisplayData(item);
+
+ // 추가 처리 및 일련번호 추가
+ return {
+ ...formattedItem,
+ rowNumber: index + 1, // 1부터 시작하는 일련번호 추가
+ scsYn: item.scsYn === null || item.scsYn === undefined ? 'N' : item.scsYn // scsYn이 null이면 'N'으로 변경
+ };
+ });
+ // setTableData(data.content || []);
+ // setTotalData(tableData.length);
+ setTableData(dataWithRowNumber);
+ setTotalData(dataWithRowNumber.length);
+ console.log("response:", data);
+ console.log("response data:", dataWithRowNumber);
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("Error fetching analysis result data:", error);
+ alert("분석결과 조회 중 오류가 발생했습니다.");
+ setTableData([]);
+ setTotalData(0);
+ }
+ };
+
+ // 테이블 셀 클릭 핸들러 추가
+ const handleCellClick = (index: number | undefined, headId: string) => {
+ if (index !== undefined && tableData[index]) {
+ setSelectedRowData(tableData[index]);
+ setSelectedRowIndex(index);
+ console.log("Selected row data:", tableData[index]);
+ }
+ };
+
+ // Excel 다운로드 핸들러 추가
+ const handleExcelDownload = async () => {
+ setIsLoadingResult(true);
+ console.log("Selected row data for download:", selectedRowData);
+ if (!selectedRowData || selectedRowData.inftwtAnlsSn === undefined) {
+ setIsLoadingResult(false);
+ alert('다운로드할 데이터를 선택해주세요.');
+ return;
+ }
+
+ try {
+ const data = await getData(`v1/inftwtAnlsRslt/ppl/${selectedRowData.inftwtAnlsSn}`);
+
+ // 선택된 행 데이터를 Excel 다운로드 형식으로 변환
+ const excelData = data.content; // 배열로 감싸서 전달
+
+ // 헤더 매핑 정의
+ const headerMapping: { [key: string]: string } = {
+ 'inftwtAnlsSn': '침입수분석\n일련번호',
+ 'pplMngNo': '관로\n관리번호',
+ 'anlsTm': '분석시각',
+ 'predcOilq': '예측유량\n(m³/h)'
+ };
+
+ // 파일명 생성 (분석번호 기반)
+ const fileName = `침입수분석결과_${selectedRowData.swageTmplntNm}_${selectedRowData.aplcnYm}_${selectedRowData.inftwtAnlsSn}`;
+
+ await downloadExcelWithKoreanHeaders({
+ data: excelData as JSON[],
+ fileName: fileName,
+ sheetNameArray: ["침입수 분석결과"],
+ headerRange: "A1:D1",
+ headerMapping: headerMapping
+ });
+ setIsLoadingResult(false);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("Excel 다운로드 중 오류 발생:", error);
+ alert("Excel 다운로드 중 오류가 발생했습니다. 다시 시도해주세요.");
+ }
+ };
+
+ // 파일 삭제 핸들러 추가
+ const handleFileDelete = async () => {
+ setIsLoadingResult(true);
+ console.log("Selected row data for deletion:", selectedRowData);
+ if (!selectedRowData || selectedRowData.inftwtAnlsSn === undefined) {
+ setIsLoadingResult(false);
+ alert('삭제할 파일을 선택해주세요.');
+ return;
+ }
+ // 삭제 확인 대화상자
+ const confirmDelete = window.confirm('선택된 분석 결과를 삭제하시겠습니까?');
+ if (!confirmDelete) {
+ return;
+ }
+
+ try {
+ // // 삭제 API 호출
+ console.log("Deleting analysis result with inftwtAnlsSn:", selectedRowData.inftwtAnlsSn);
+ const response1 = await deleteData(`v1/inftwtAnlsRslt/${selectedRowData.inftwtAnlsSn}`);
+ const response2 = await deleteData(`v1/inftwtAnls/${selectedRowData.inftwtAnlsSn}`);
+ // 첨부파일(inp파일) 삭제 API 호출
+ handleDelete(selectedRowData.atflCd, {
+ handleDeleteStart: () => console.log("파일 삭제 시작"),
+ handleDeleteSuccess: (response) => console.log("파일 삭제 성공:", response),
+ handleDeleteError: (error) => console.error("파일 삭제 실패:", error),
+ });
+ console.log("File delete response1:", response1);
+ console.log("File delete response2:", response2);
+
+ // 테이블 선택 상태 초기화 트리거
+ setResetSelection(true);
+
+ // 삭제 후 테이블 새로고침을 위해 재검색
+ const customFormValues: Partial = {
+ aplcnYmFrom: selectedRowData.aplcnYmFrom || null,
+ aplcnYmTo: selectedRowData.aplcnYmTo || null,
+ enoCd: selectedRowData.enoCd || null,
+ ctpvCd: selectedRowData.ctpvCd || null,
+ sggCd: selectedRowData.sggCd || null,
+ swageTmplntCd: selectedRowData.swageTmplntCd || null,
+ // swtrmtZoneCd: selectedRowData.swtrmtZoneCd || null,
+ };
+ await handleSearchButtonClick(customFormValues);
+
+ // 선택된 행 초기화
+ setSelectedRowData(null);
+ setSelectedRowIndex(undefined);
+ setIsLoadingResult(false);
+
+ alert('삭제가 완료되었습니다.');
+
+ setTimeout(() => {
+ setResetSelection(false);
+ }, 100);
+ } catch (error) {
+ setIsLoadingResult(false);
+ console.error("분석결과 파일 삭제 중 오류 발생:", error);
+ alert("분석결과 파일 삭제 중 오류가 발생했습니다. 다시 시도해주세요.");
+ }
+ };
+
+
+
+ return (
+ { }} // BaseLayout의 form 태그에 연결될 onSubmit
+ graphBtn={true}
+ showDatePicker={true}
+ enoCd={form.watch("enoCd")}
+ setEnoCd={(val) => form.setValue("enoCd", val)}
+ ctpvCd={form.watch("ctpvCd")}
+ setCtpvCd={(val) => form.setValue("ctpvCd", val)}
+ sigungu={form.watch("sggCd")}
+ setSigungu={(val) => form.setValue("sggCd", val)}
+ selectedSwageTreatmentPlant={form.watch("swageTmplntCd")}
+ onSwageTreatmentPlantChange={(val) => form.setValue("swageTmplntCd", String(val))}
+ selectedSwageProcessingZone={form.watch("swtrmtZoneCd")}
+ onSwageProcessingZoneChange={(val) => form.setValue("swtrmtZoneCd", String(val))}
+ aplcnYmFrom={form.watch("aplcnYmFrom")}
+ setAplcnYmFrom={(val: string) => { form.setValue("aplcnYmFrom", val) }}
+ aplcnYmTo={form.watch("aplcnYmTo")}
+ setAplcnYmTo={(val: string) => { form.setValue("aplcnYmTo", val) }}
+ isLoading={isLoadingResult} // 로딩 상태 전달
+ // Excel 다운로드 핸들러 추가
+ onExcelDownload={handleExcelDownload}
+ onDeleteFile={handleFileDelete}
+ selectedRowData={selectedRowData}
+ >
+ {[
+
○ 침입수 산정결과 현황
+
+ { }}
+ resetSelection={resetSelection}
+ />
+
+
+ ]}
+
+ )
+}
+
+export default Result
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/layout.tsx b/apps/sn/app/(with-base-layout)/layout.tsx
new file mode 100644
index 000000000..3c1a527d7
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/layout.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { usePathname, useRouter } from "next/navigation";
+import { useQueryClient } from "@tanstack/react-query";
+import { BaseLayout } from "@common/components";
+import type { MenuItem } from "@/entities/menu";
+import { useMenuStore } from "@/shared/lib";
+import { PageLayout } from "@/shared/ui/page-layout";
+
+export default function WithBaseLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const queryClient = useQueryClient();
+
+ const setCurrentMenuInfo = useMenuStore((state) => state.setCurrentMenuInfo);
+
+ const handleMenuClick = (item: MenuItem) => {
+ setCurrentMenuInfo(item);
+ router.push(item.urlPath);
+ };
+
+ return (
+
+ {children}
+
+ );
+}
diff --git a/apps/sn/app/(with-base-layout)/oper/floodPre/page.tsx b/apps/sn/app/(with-base-layout)/oper/floodPre/page.tsx
new file mode 100644
index 000000000..c67c34482
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/oper/floodPre/page.tsx
@@ -0,0 +1,208 @@
+'use client'
+import { deleteData, postData } from '@/components/lib/api'
+import { searchData } from '@/components/lib/common/apiHelpers'
+import { formatDate, handleDownload } from '@/components/lib/utils'
+import LoadingOverlay from '@/components/ui/LoadingBar'
+import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable, UiModal } from '@common/business_components/ui'
+import ListDiv from '@common/business_components/ui/list_div'
+import { Button, DatePicker, Input, Label } from '@common/components/ui'
+import { useEffect, useState } from 'react'
+import { tableHeadlist } from '..'
+import OperFileUploadForm from '../../../components/ui/operFileUploadForm'
+
+
+const Page = () => {
+ // 조회조건
+ const [fromDate, setFromDate] = useState(() => { const date = new Date(); date.setDate(date.getDate() - 7); return date })
+ const [toDate, setToDate] = useState(new Date())
+ const [usr, setUsr] = useState('')
+ const [pjNm, setpjNm] = useState('')
+ // 파일업로드 관련 상태
+ const [fileNm, setFileNm] = useState('') //파일명
+ const [atflId, setAtflId] = useState('') //파일 ID
+ const [sbmrgPrevntBizSn, setSbmrgPrevntBizSn] = useState('') //파일 일련번호
+ const [tableData, setTableData] = useState([{}]) //테이블 데이터
+ const [curPage, setCurPage] = useState(1) //현재 페이지
+ const [totalData, setTotalData] = useState(0) //총 데이터 수
+ const [isLoading, setIsLoading] = useState(true) //로딩 상태
+ const [isModalOpen, setIsModalOpen] = useState(false) // 모달 상태
+
+ // 조회
+ const fetchData = async () => {
+ setIsLoading(true)
+ // searchCmmnCd('SITEKNDCD')
+ try {
+ const { data, total } = await searchData('v1/sbmrgPrevnt', {
+ fromRegDt: formatDate(fromDate),
+ toRegDt: formatDate(toDate),
+ sbmrgPrevntBizNm: pjNm,
+ rgtrNm: usr,
+ page: curPage - 1,
+ size: '10'
+ })
+ // 일련번호를 추가한 데이터로 변환 (전체 데이터 기준으로 일련번호 계산)
+ const dataWithRowNumber = (data || []).map((item: any, index: number) => ({
+ ...item,
+ rowNumber: (curPage - 1) * 10 + index + 1, // 페이지 기준 일련번호 계산
+ }));
+ setTableData(dataWithRowNumber)
+ setTotalData(total)
+ }
+ catch (error) { console.error('Error fetching data:', error) }
+ finally {
+ setFileNm('');
+ setAtflId('');
+ setSbmrgPrevntBizSn('');
+ setIsLoading(false);
+ }
+ }
+
+ useEffect(() => {
+ setCurPage(1)
+ fetchData()
+ }, [])
+
+ // 파일 다운로드
+ const isChckFile = () => {
+ if (fileNm === '' || fileNm === undefined) {
+ alert('파일을 선택해주세요')
+ return false
+ }
+ handleDownload(`/attach-service/api/v1/download/${atflId}`, fileNm)
+ }
+
+ // 선택 파일 삭제
+ const isDeleteFile = async () => {
+ if (sbmrgPrevntBizSn === '' || sbmrgPrevntBizSn === undefined) {
+ alert('삭제할 파일을 선택해주세요')
+ return false
+ }
+ const data = await deleteData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
+ if (data) {
+ const delData = await deleteData(`v1/sbmrgPrevnt/${sbmrgPrevntBizSn}`)
+ if (delData.status === 200) {
+ alert('삭제되었습니다.')
+ fetchData()
+ }
+ }
+ }
+
+ // 현황 등록
+ const registFile = async (fileName: string, year: string, quater: string, cd: string, id: string) => {
+ const data = await postData('v1/sbmrgPrevnt', {
+ atflNm: fileName,
+ mngYr: year,
+ mngQu: quater,
+ atflCd: cd,
+ atflId: id,
+ sbmrgPrevntBizNm: fileName
+ })
+ if (data) {
+ alert('파일이 등록되었습니다.');
+ setIsModalOpen(false);
+ fetchData();
+ }
+ }
+
+ // 등록 버튼 클릭 핸들러
+ const handleRegisterClick = () => {
+ setIsModalOpen(true);
+ }
+
+
+ return (
+ <>
+
+
+
+
+
+
+ { if (date) setFromDate(date) }}
+ modifiers={{
+ disabled: { after: new Date() }
+ }}
+ />
+ ~
+ { if (date) setToDate(date) }}
+ modifiers={{
+ disabled: { after: new Date() }
+ }}
+ />
+
+
+
+ setUsr(e.target.value)}
+ />
+
+
+
+ setpjNm(e.target.value)}
+ />
+
+
+
+
+
+
+
+
+
+
+
+
+
사업정보 등록현황
+
+
+
+
+
+ {
+ if (index != null) {
+ const fileName = tableData[index]?.sbmrgPrevntBizNm ?? "";
+ const id = tableData[index]?.atflId ?? '';
+ setFileNm(fileName);
+ setAtflId(id);
+ setSbmrgPrevntBizSn(tableData[index]?.sbmrgPrevntBizSn);
+ }
+ }}
+ onPageChange={async (page: number) => { setCurPage(page); await fetchData() }}
+ />
+
+ {/* 파일 업로드 모달 */}
+ {
+ await registFile(file, year, quater, cd, id)
+ }}
+ />
+ }
+ />
+ >
+ )
+}
+
+export default Page
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/oper/index.ts b/apps/sn/app/(with-base-layout)/oper/index.ts
new file mode 100644
index 000000000..b9dd98685
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/oper/index.ts
@@ -0,0 +1,19 @@
+export const tableHeadlist = [
+ { id: 'rowNumber', title: '일련번호' },
+ // { id: 'sbmrgPrevntBizSn', title: '일련번호' },
+ { id: 'sbmrgPrevntBizNm', title: '파일명' },
+ { id: 'mngYr', title: '년도' },
+ { id: 'mngQu', title: '분기' },
+ { id: 'regDt', title: '등록 일자' },
+ { id: 'rgtr', title: '등록자' }
+
+]
+export const tableHeadlistOldPp = [
+ { id: 'rowNumber', title: '일련번호' },
+ // { id: 'dcrpPplMtncBizSn', title: '일련번호' },
+ { id: 'dcrpPplMtncBizNm', title: '파일명' },
+ { id: 'mngYr', title: '년도' },
+ { id: 'mngQu', title: '분기' },
+ { id: 'regDt', title: '등록 일자' },
+ { id: 'rgtr', title: '등록자' }
+]
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/oper/oldPp/page.tsx b/apps/sn/app/(with-base-layout)/oper/oldPp/page.tsx
new file mode 100644
index 000000000..fb1725f55
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/oper/oldPp/page.tsx
@@ -0,0 +1,207 @@
+'use client'
+import { deleteData, postData } from '@/components/lib/api'
+import { searchData } from '@/components/lib/common/apiHelpers'
+import { formatDate, handleDownload, yearOptions } from '@/components/lib/utils'
+import LoadingOverlay from '@/components/ui/LoadingBar'
+import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable, UiModal } from '@common/business_components/ui'
+import ListDiv from '@common/business_components/ui/list_div'
+import { Button, DatePicker, Input, Label } from '@common/components/ui'
+import { useEffect, useState } from 'react'
+import { tableHeadlistOldPp } from '..'
+import OperFileUploadForm from '../../../components/ui/operFileUploadForm'
+
+
+const Page = () => {
+ const [fromDate, setFromDate] = useState(() => { const date = new Date(); date.setDate(date.getDate() - 7); return date });
+ const [toDate, setToDate] = useState(new Date());
+ const [usr, setUsr] = useState('')
+ const [pjNm, setpjNm] = useState('')
+ const [fileNm, setFileNm] = useState('')
+ const [atflId, setAtflId] = useState('')
+ const [dcrpPplMtncBizSn, setDcrpPplMtncBizSn] = useState('')
+ const [tableData, setTableData] = useState([{}])
+ const [curPage, setCurPage] = useState(1)
+ const [totalData, setTotalData] = useState(0) //총 데이터 수
+ const [isLoading, setIsLoading] = useState(true) //로딩 상태
+ const [isModalOpen, setIsModalOpen] = useState(false) // 모달 상태
+
+ // 데이터 조회
+ const fetchData = async () => {
+ setIsLoading(true)
+ try {
+ const { data, total } = await searchData('v1/dcrpPpl', {
+ fromRegDt: formatDate(fromDate),
+ toRegDt: formatDate(toDate),
+ dcrpPplMtncBizNm: pjNm,
+ rgtrNm: usr,
+ page: curPage - 1,
+ size: '10'
+ })
+ // 일련번호를 추가한 데이터로 변환 (전체 데이터 기준으로 일련번호 계산)
+ const dataWithRowNumber = (data || []).map((item: any, index: number) => ({
+ ...item,
+ rowNumber: (curPage - 1) * 10 + index + 1, // 페이지 기준 일련번호 계산
+ }));
+ setTableData(dataWithRowNumber)
+ setTotalData(total)
+ } catch (error) {
+ console.error('Error fetching data:', error)
+ } finally {
+ setFileNm('');
+ setAtflId('');
+ setDcrpPplMtncBizSn('');
+ setIsLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ setCurPage(1)
+ fetchData()
+ }, [])
+
+ // 파일 다운로드
+ const isChckFile = () => {
+ if (fileNm === '' || fileNm === undefined) {
+ alert('파일을 선택해주세요')
+ return false
+ }
+ handleDownload(`/attach-service/api/v1/download/${atflId}`, fileNm)
+ return true
+ }
+
+ // 파일 삭제
+ const isDeleteFile = async () => {
+ if (dcrpPplMtncBizSn === '' || dcrpPplMtncBizSn === undefined) {
+ alert('삭제할 파일을 선택해주세요')
+ return false
+ }
+ const data = await deleteData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
+ if (data) {
+ const delData = await deleteData(`v1/dcrpPpl/${dcrpPplMtncBizSn}`)
+ if (delData.status == 200) {
+ alert('삭제되었습니다.')
+ fetchData()
+ } else {
+ alert('삭제에 실패했습니다.')
+ }
+ }
+ }
+
+ // 파일 등록
+ const registFile = async (fileNm: string, year: string, quater: string, cd: string, id: string) => {
+ const data = await postData('v1/dcrpPpl', {
+ atflNm: fileNm,
+ mngYr: year,
+ mngQu: quater,
+ atflCd: cd,
+ atflId: id,
+ dcrpPplMtncBizNm: fileNm
+ })
+ if (data) {
+ alert('파일이 등록되었습니다.');
+ setIsModalOpen(false);
+ fetchData();
+ }
+ }
+
+ // 등록 버튼 클릭 핸들러
+ const handleRegisterClick = () => {
+ setIsModalOpen(true);
+ }
+
+
+ return (
+ <>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
사업정보 등록현황
+
+
+
+
+
+ {
+ if (index != null) {
+ const fileName = tableData[index]?.dcrpPplMtncBizNm ?? "";
+ const id = tableData[index]?.atflId ?? '';
+ setFileNm(fileName);
+ setAtflId(id);
+ setDcrpPplMtncBizSn(tableData[index]?.dcrpPplMtncBizSn);
+ }
+ }}
+ onPageChange={async (page: number) => { setCurPage(page); await fetchData() }}
+ />
+
+ {/* 파일 업로드 모달 */}
+ {
+ await registFile(file, year, quater, cd, id)
+ }}
+ />
+ }
+ />
+ >
+ )
+}
+
+export default Page
\ No newline at end of file
diff --git a/apps/sn/app/(with-base-layout)/selectionValidation.tsx b/apps/sn/app/(with-base-layout)/selectionValidation.tsx
new file mode 100644
index 000000000..8cc506d0e
--- /dev/null
+++ b/apps/sn/app/(with-base-layout)/selectionValidation.tsx
@@ -0,0 +1,161 @@
+/**
+ * 선택 항목 검증 유틸리티
+ */
+
+export interface ApiSelectOption {
+ text: string;
+ val: string;
+}
+
+// 선택 항목 검증 설정 타입
+export interface SelectionValidationConfig {
+ value: string | number | ApiSelectOption;
+ description: string;
+ required: boolean;
+}
+
+// 선택 항목 검증 결과 타입
+export interface SelectionValidationResult {
+ isValid: boolean;
+ errorMessage?: string;
+}
+
+/**
+ * 단일 선택 항목이 유효한지 검증하는 함수
+ * @param value 검증할 값
+ * @param isRequired 필수 선택 여부
+ * @returns 유효한지 여부
+ */
+export const isValidSelection = (
+ value: string | number | ApiSelectOption,
+ isRequired: boolean = true
+): boolean => {
+ if (!isRequired) return true;
+
+ if (typeof value === 'object' && value !== null) {
+ // ApiSelectOption 객체인 경우
+ return value.val !== '0' && value.val !== '' && value.val !== null && value.val !== undefined;
+ }
+
+ // 문자열 또는 숫자인 경우
+ return value !== '0' && value !== 0 && value !== '' && value !== null && value !== undefined;
+};
+
+/**
+ * 여러 선택 항목을 한 번에 검증하는 함수
+ * @param validationConfigs 검증할 선택 항목들의 설정 배열
+ * @returns 검증 결과. 실패 시 첫 번째 에러 메시지 반환
+ */
+export const validateMultipleSelections = (
+ validationConfigs: SelectionValidationConfig[]
+): SelectionValidationResult => {
+ for (const config of validationConfigs) {
+ if (!isValidSelection(config.value, config.required)) {
+ return {
+ isValid: false,
+ errorMessage: `${config.description}을(를) 선택해주세요.`
+ };
+ }
+ }
+
+ return { isValid: true };
+};
+
+/**
+ * 여러 선택 항목을 한 번에 검증하고 alert 표시하는 함수
+ * @param validationConfigs 검증할 선택 항목들의 설정 배열
+ * @returns 검증 결과
+ */
+export const validateMultipleSelectionsWithAlert = (
+ validationConfigs: SelectionValidationConfig[]
+): boolean => {
+ const result = validateMultipleSelections(validationConfigs);
+ if (!result.isValid && result.errorMessage) {
+ alert(result.errorMessage);
+ return false;
+ }
+ return true;
+};
+
+/**
+ * 기본 선택 항목들 검증 (환경청, 시도, 시군구, 하수처리장)
+ * @param select1 환경청코드
+ * @param select2 시도코드
+ * @param select3 시군구 객체
+ * @param select4 하수처리장코드
+ * @param options 각 항목의 필수 여부 설정
+ * @returns 검증 결과
+ */
+export const validateBasicSelections = (
+ select1: string,
+ select2: string,
+ select3: ApiSelectOption,
+ select4: string | number,
+ options: {
+ requireEnv?: boolean;
+ requireSido?: boolean;
+ requireSigungu?: boolean;
+ requireTreatmentPlant?: boolean;
+ } = {}
+): SelectionValidationResult => {
+ const {
+ requireEnv = true,
+ requireSido = true,
+ requireSigungu = true,
+ requireTreatmentPlant = true
+ } = options;
+
+ const validationConfigs: SelectionValidationConfig[] = [
+ {
+ value: select1,
+ description: '환경청',
+ required: requireEnv
+ },
+ {
+ value: select2,
+ description: '시도',
+ required: requireSido
+ },
+ {
+ value: select3,
+ description: '시군구',
+ required: requireSigungu
+ },
+ {
+ value: select4,
+ description: '하수처리장',
+ required: requireTreatmentPlant
+ }
+ ];
+
+ return validateMultipleSelections(validationConfigs);
+};
+
+/**
+ * 기본 선택 항목들 검증 및 alert 표시
+ * @param select1 환경청코드
+ * @param select2 시도코드
+ * @param select3 시군구 객체
+ * @param select4 하수처리장코드
+ * @param options 각 항목의 필수 여부 설정
+ * @returns 검증 결과
+ */
+export const validateBasicSelectionsWithAlert = (
+ select1: string,
+ select2: string,
+ select3: ApiSelectOption,
+ select4: string | number,
+ options: {
+ requireEnv?: boolean;
+ requireSido?: boolean;
+ requireSigungu?: boolean;
+ requireTreatmentPlant?: boolean;
+ } = {}
+): boolean => {
+ const result = validateBasicSelections(select1, select2, select3, select4, options);
+ if (!result.isValid && result.errorMessage) {
+ alert(result.errorMessage);
+ return false;
+ }
+ return true;
+};
\ No newline at end of file
diff --git a/apps/sn/app/clientLayout.tsx b/apps/sn/app/clientLayout.tsx
deleted file mode 100644
index e8fdbe032..000000000
--- a/apps/sn/app/clientLayout.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-'use client'
-
-import { BaseLayout } from "@common/components";
-
-export function ClientLayout({ children }: { children: React.ReactNode }) {
- return {children};
-}
\ No newline at end of file
diff --git a/apps/sn/app/components/lib/api/index.ts b/apps/sn/app/components/lib/api/index.ts
index d7db93f77..55d111074 100644
--- a/apps/sn/app/components/lib/api/index.ts
+++ b/apps/sn/app/components/lib/api/index.ts
@@ -1,68 +1,82 @@
-const BASE_URL = process.env.NEXT_PUBLIC_SEWERAGE_API_URL || '';
+const BASE_URL = 'http://con.mind-one.co.kr:11083/sewerage-service/api';
export const postData = async (url: string, data: object): Promise => {
- const options: RequestInit = {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- };
- const res = await fetch(`${BASE_URL}/${url}`, options);
- if (res.ok) {
- const resData = await res.json();
- return resData;
- // const text = await res.text();
- // if (text) {
- // return JSON.parse(text); // JSON 데이터가 있으면 파싱하여 반환
- // }
- // return true; // 응답 본문이 비어 있으면 true 반환
- }
+ const options: RequestInit = {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ };
+ const res = await fetch(`${BASE_URL}/${url}`, options);
+ console.log('res', res);
+ console.log('res.status', res.status);
+ if (res.ok) {
+ const resData = await res.json();
+ return resData;
+ // const text = await res.text();
+ // if (text) {
+ // return JSON.parse(text); // JSON 데이터가 있으면 파싱하여 반환
+ // }
+ // return true; // 응답 본문이 비어 있으면 true 반환
+ }
};
export const postMutiPart = async (url: string, data: FormData): Promise => {
- const options: RequestInit = {
- method: "POST",
- body: data,
- };
- const res = await fetch(`${BASE_URL}/${url}`, options);
- const resData = await res.json();
- return resData;
+ const options: RequestInit = {
+ method: "POST",
+ body: data,
+ };
+ const res = await fetch(`${BASE_URL}/${url}`, options);
+ const resData = await res.json();
+ return resData;
};
export const putData = async (url: string, data: object): Promise => {
- const options: RequestInit = {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- };
- const res = await fetch(`${BASE_URL}/${url}`, options);
- const resData = await res.json();
- return resData;
+ const options: RequestInit = {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ };
+ const res = await fetch(`${BASE_URL}/${url}`, options);
+ const resData = await res.json();
+ return resData;
};
export const getData = async (url: string, data?: object): Promise => {
- const res = await fetch(url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`, {
- method: "GET",
- });
- if (res.ok) {
- const data = await res.json();
- return data;
- }
- throw new Error('Failed to fetch data');
+ const res = await fetch(url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`, {
+ method: "GET",
+ });
+ if (res.ok) {
+ const data = await res.json();
+ return data;
+ }
+ throw new Error('Failed to fetch data');
+};
+
+export const getDcData = async (url: string, data?: object): Promise => {
+ console.log(url);
+ const res = await fetch('/dc-service'+url, {
+ method: "GET",
+ });
+ if (res.ok) {
+ const data = await res.json();
+ return data;
+ }
+ throw new Error('Failed to fetch data');
};
export const deleteData = async (url: string, data?: object): Promise => {
- const options: RequestInit = {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- body: data ? JSON.stringify(data) : undefined,
- };
- const res = await fetch(url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`, options);
- if (res.status === 204) return true
- return res;
+ const options: RequestInit = {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: data ? JSON.stringify(data) : undefined,
+ };
+ const res = await fetch(url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`, options);
+ if (res.status === 204) return true
+ return res;
};
\ No newline at end of file
diff --git a/apps/sn/app/components/lib/auth/lib/auth-wrapper.tsx b/apps/sn/app/components/lib/auth/lib/auth-wrapper.tsx
deleted file mode 100644
index 0b72cc768..000000000
--- a/apps/sn/app/components/lib/auth/lib/auth-wrapper.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-"use client";
-
-import { useEffect } from "react";
-import { useRouter, usePathname } from "next/navigation";
-import axios from "axios";
-import Cookies from "js-cookie";
-import { useUserStore, type IUserInfo } from "@store";
-import { getCookie } from "@utils";
-import { LoginApi } from "../api/login-service";
-import { tokenManager } from "../lib/token-manager";
-
-const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
-const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
-
-const ENDPOINT = {
- USER_SERVICE: {
- LOGIN: "/user-service/login",
- USERS: "/user-service/api/v1/users",
- SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
- AUTHORIZATIONS: "/user-service/api/v1/authorizations",
- ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations",
- },
-};
-
-const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
- const router = useRouter();
- const pathname = usePathname(); // 현재 경로
- const { userInfo, setUserInfo } = useUserStore((state) => state);
-
- async function authCheck() {
- const checkToken = getCookie(AUTH_USER_ID);
-
-
- if (!checkToken) {
- //TODO 나중에 수정해야....
- const userId = "admin1gmail";
- const password = "test1234!";
- await LoginApi.login({ userId, password });
- // window.location.href = "http://dev.onasys.co.kr/auth/login";
- // throw new Error("Missing required authentication tokens");
- }
-
- const accessToken = tokenManager.getToken(CLAIM_NAME);
- const tokenId = tokenManager.getToken(AUTH_USER_ID);
-
- const response = await axios.get(
- `${ENDPOINT.USER_SERVICE.USERS}/info/me`,
- {
- withCredentials: true,
- headers: {
- [CLAIM_NAME]: accessToken,
- [AUTH_USER_ID]: tokenId ?? "",
- },
- },
- );
-
- if (!userInfo) setUserInfo(response.data);
- }
-
- useEffect(() => {
- (async () => {
- try {
- await authCheck();
- } catch (error) {
- console.error("Auth check failed:", error);
-
- try {
- await LoginApi.silentRefresh();
- await authCheck();
- } catch (refreshError) {
- console.error("Token refresh failed:", refreshError);
- setUserInfo(null);
-
- // TODO 운영에 반영 할때 수정해야.....
- // 현재 경로가 로그인 페이지가 아닐 때만 redirect
- // if (!pathname.startsWith("/auth/login")) {
- // window.location.href = "http://dev.onasys.co.kr/auth/login";
- // }
- }
- }
- })();
- }, [pathname]); // pathname도 의존성에 포함
-
- return <>{children}>;
-};
-
-export { AuthWrapper };
diff --git a/apps/sn/app/components/lib/common/apiHelpers.ts b/apps/sn/app/components/lib/common/apiHelpers.ts
index caaa3b050..4963516f7 100644
--- a/apps/sn/app/components/lib/common/apiHelpers.ts
+++ b/apps/sn/app/components/lib/common/apiHelpers.ts
@@ -1,24 +1,24 @@
import { getData } from "../api";
export const searchData = async>(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)
- );
- const data = await getData(`${url}?${params.toString()}`);
- return data && { data: data.content, total: data.totalElements }
+ const params = new URLSearchParams(
+ Object.entries(paramObj)
+ .filter(([_, value]) => value !== undefined && value !== '') // 값이 있는 항목만 포함
+ .reduce((acc, [key, value]) => {
+ acc[key] = String(value);
+ return acc;
+ }, {} as Record)
+ );
+ const data = await getData(`${url}?${params.toString()}`);
+ return data && { data: data.content, total: data.totalElements }
}
// 상위코드로 하위코드 조회
export const searchCmmnCd = async (upCd: string) => {
- const data = await getData(`/cms-service/api/v1/code/cache/${upCd}`);
- const filteredData = data.map((item: any) => ({
- lwpoCd: item.lwpoCd,
- lwpoCdNm: item.lwpoCdNm,
- }));
- return filteredData;
+ const data = await getData(`/cms-service/api/v1/code/cache/${upCd}`);
+ const filteredData = data.map((item: any) => ({
+ lwpoCd: item.lwpoCd,
+ lwpoCdNm: item.lwpoCdNm,
+ }));
+ return filteredData;
}
\ No newline at end of file
diff --git a/apps/sn/app/components/lib/utils/date.ts b/apps/sn/app/components/lib/utils/date.ts
index 75e3cbf32..a401ad738 100644
--- a/apps/sn/app/components/lib/utils/date.ts
+++ b/apps/sn/app/components/lib/utils/date.ts
@@ -1,13 +1,110 @@
export const formatDate = (date: Date): string => {
- if (!date) return '';
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // 월은 0부터 시작하므로 +1
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
+ if (!date) return '';
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // 월은 0부터 시작하므로 +1
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
};
- // 현재 년도부터 10년 전까지의 년도 옵션 생성
- export const yearOptions = Array.from({ length: 10 }, (_, i) => {
- const year = new Date().getFullYear() - i;
- return { text: `${year}년`, val: year.toString() };
- });
+// 현재 년도부터 10년 전까지의 년도 옵션 생성
+export const yearOptions = Array.from({ length: 10 }, (_, i) => {
+ const year = new Date().getFullYear() - i;
+ return { text: `${year}년`, val: year.toString() };
+});
+
+// 현재 날짜를 기준으로 현재 분기까지의 분기 옵션 생성
+export const getQuarterOptions = (selectedYear?: string): { text: string; val: string }[] => {
+ const currentDate = new Date();
+ const currentYear = currentDate.getFullYear().toString();
+ const currentMonth = currentDate.getMonth() + 1; // 0부터 시작하므로 +1
+
+ // 현재 년도인 경우에만 현재 날짜까지의 분기 표시
+ if (selectedYear === currentYear) {
+ // 현재 월을 기준으로 현재 분기 계산
+ const currentQuarter = Math.ceil(currentMonth / 3);
+
+ // 현재 분기까지의 분기 옵션 생성
+ const quarterOptions = [];
+ for (let i = 1; i <= currentQuarter; i++) {
+ quarterOptions.push({
+ text: `${i}분기`,
+ val: i.toString()
+ });
+ }
+
+ return quarterOptions;
+ } else {
+ // 이전 년도인 경우 모든 분기 표시
+ return [
+ { text: "1분기", val: "1" },
+ { text: "2분기", val: "2" },
+ { text: "3분기", val: "3" },
+ { text: "4분기", val: "4" }
+ ];
+ }
+};
+
+// ["202506", "202505", "202502", "202405"] 을 SelectBox의 옵션으로 변환
+export const convertToTextValArray = (yyyymms: string[]): { text: string; val: string }[] => {
+ return yyyymms.map(dateStr => {
+ const year = dateStr.slice(0, 4);
+ const month = dateStr.slice(4, 6);
+ return {
+ text: `${year}-${month}`,
+ val: dateStr
+ };
+ });
+};
+
+// 🎯 날짜 유효성 검사 함수 (8자리 또는 6자리 지원)
+export const isValidDateString = (dateStr: string): boolean => {
+ // 숫자만 추출
+ const cleanStr = dateStr.replace(/\D/g, '');
+
+ // 8자리 (yyyymmdd) 또는 6자리 (yyyymm) 확인
+ if (cleanStr.length === 8) {
+ // 연도, 월, 일 추출
+ const year = parseInt(cleanStr.substring(0, 4));
+ const month = parseInt(cleanStr.substring(4, 6));
+ const day = parseInt(cleanStr.substring(6, 8));
+
+ // 기본 범위 검사
+ if (year < 1900 || year > 2200) return false;
+ if (month < 1 || month > 12) return false;
+ if (day < 1 || day > 31) return false;
+
+ // Date 객체로 실제 유효한 날짜인지 검사
+ const date = new Date(year, month - 1, day);
+ return date.getFullYear() === year &&
+ date.getMonth() === month - 1 &&
+ date.getDate() === day;
+ }
+ else if (cleanStr.length === 6) {
+ // 연도, 월 추출
+ const year = parseInt(cleanStr.substring(0, 4));
+ const month = parseInt(cleanStr.substring(4, 6));
+
+ // 기본 범위 검사
+ if (year < 1900 || year > 2200) return false;
+ if (month < 1 || month > 12) return false;
+
+ return true;
+ }
+
+ return false;
+};
+
+// 🎯 날짜 포맷팅 함수
+export const formatDateString = (dateStr: string): string => {
+ const cleanStr = dateStr.replace(/\D/g, ''); // 숫자만 추출
+
+ if (!isValidDateString(cleanStr)) {
+ return dateStr; // 유효하지 않은 날짜면 원본 반환
+ }
+
+ const year = cleanStr.substring(0, 4);
+ const month = parseInt(cleanStr.substring(4, 6)); // parseInt로 앞의 0 제거
+ const day = parseInt(cleanStr.substring(6, 8)); // parseInt로 앞의 0 제거
+
+ return `${year}년 ${month}월 ${day}일`;
+};
\ No newline at end of file
diff --git a/apps/sn/app/components/lib/utils/fileDeleteUtil.tsx b/apps/sn/app/components/lib/utils/fileDeleteUtil.tsx
index bf8a70130..4cadd12e8 100644
--- a/apps/sn/app/components/lib/utils/fileDeleteUtil.tsx
+++ b/apps/sn/app/components/lib/utils/fileDeleteUtil.tsx
@@ -1,4 +1,4 @@
-import { getCookie } from "@utils";
+import { getCookie } from "@/shared/lib";
import { ENDPOINT } from "../api/attachment/attachment-service";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
diff --git a/apps/sn/app/components/lib/utils/fileUploadUtil.tsx b/apps/sn/app/components/lib/utils/fileUploadUtil.tsx
index 9b3721cd0..3bfb35f00 100644
--- a/apps/sn/app/components/lib/utils/fileUploadUtil.tsx
+++ b/apps/sn/app/components/lib/utils/fileUploadUtil.tsx
@@ -1,5 +1,5 @@
import { Upload, type HttpResponse } from "tus-js-client";
-import { getCookie, setCookie } from "@utils";
+import { getCookie, setCookie } from "@/shared/lib";
import { ENDPOINT } from "../api/attachment/attachment-service";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
diff --git a/apps/sn/app/components/lib/utils/formatDisplayValue.tsx b/apps/sn/app/components/lib/utils/formatDisplayValue.tsx
new file mode 100644
index 000000000..858453291
--- /dev/null
+++ b/apps/sn/app/components/lib/utils/formatDisplayValue.tsx
@@ -0,0 +1,96 @@
+import { dateFields, numberFields, yearMonthFields, dateTimeFields } from "../../../(map-layout)/map/components/common/table";
+import { isValidDateString, formatDateString } from "./date";
+
+// 🎯 데이터 객체 전체를 포맷팅하는 함수
+export const formatDisplayData = (data: { [key: string]: any }): { [key: string]: string } => {
+ if (!data) return {};
+
+ const formattedData: { [key: string]: string } = {};
+
+ Object.keys(data).forEach(fieldId => {
+ const value = data[fieldId];
+
+ if (value === null || value === undefined || value === "") {
+ formattedData[fieldId] = "-";
+ return;
+ }
+
+ // 🎯 연월 포맷팅 (yyyymm -> yyyy년 m월)
+ if (yearMonthFields.includes(fieldId)) {
+ const dateStr = String(value).trim();
+ if (/^\d{6}$/.test(dateStr)) {
+ const year = dateStr.substring(0, 4);
+ const month = parseInt(dateStr.substring(4, 6));
+ formattedData[fieldId] = `${year}년 ${month}월`;
+ } else {
+ formattedData[fieldId] = String(value);
+ }
+ return;
+ }
+
+ // 🎯 날짜시간 포맷팅 (yyyy-mm-dd hh:mm:ss -> yyyy년 m월 d일 hh:mm)
+ if (dateTimeFields.includes(fieldId)) {
+ const dateTimeStr = String(value).trim();
+ // yyyy-mm-dd hh:mm:ss 형식 확인
+ const dateTimeRegex = /^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/;
+ const match = dateTimeStr.match(dateTimeRegex);
+
+ if (match && match.length >= 6) {
+ const year = match[1];
+ const month = match[2];
+ const day = match[3];
+ const hour = match[4];
+ const minute = match[5];
+ const second = match[6];
+
+ // 🎯 undefined 체크 후 parseInt 적용
+ if (year && month && day && hour && minute) {
+ const formattedMonth = parseInt(month);
+ const formattedDay = parseInt(day);
+ formattedData[fieldId] = `${year}년 ${formattedMonth}월 ${formattedDay}일 ${hour}시 ${minute}분 ${second}초`;
+ } else {
+ formattedData[fieldId] = String(value);
+ }
+ } else {
+ formattedData[fieldId] = String(value);
+ }
+ return;
+ }
+
+ // 🎯 기존 날짜 포맷팅 (yyyymmdd -> yyyy년 m월 d일)
+ if (dateFields.includes(fieldId)) {
+ const dateStr = String(value).trim();
+
+ // 숫자 타입이거나 숫자로만 구성된 문자열인지 확인
+ if (/^\d+$/.test(dateStr)) {
+ formattedData[fieldId] = formatDateString(dateStr);
+ } else {
+ formattedData[fieldId] = String(value);
+ }
+ return;
+ }
+
+ // 🎯 숫자 필드는 천 단위 구분자 추가
+ if (numberFields.includes(fieldId)) {
+ const numValue = Number(value);
+ if (!isNaN(numValue) && isFinite(numValue)) {
+ formattedData[fieldId] = numValue.toLocaleString('ko-KR');
+ } else {
+ formattedData[fieldId] = String(value);
+ }
+ return;
+ }
+
+ // 나머지는 문자열로 처리
+ formattedData[fieldId] = String(value);
+ });
+
+ return formattedData;
+};
+
+// 🎯 단일 값만 포맷팅하는 함수 (기존 호환성을 위해 유지)
+export const formatDisplayValue = (value: any, fieldId: string): string => {
+ const tempData = { [fieldId]: value };
+ const formatted = formatDisplayData(tempData);
+ return formatted[fieldId] || String(value);
+};
\ No newline at end of file
diff --git a/apps/sn/app/components/lib/utils/index.tsx b/apps/sn/app/components/lib/utils/index.tsx
index 0b9999c87..8bc8cf9be 100644
--- a/apps/sn/app/components/lib/utils/index.tsx
+++ b/apps/sn/app/components/lib/utils/index.tsx
@@ -1,4 +1,7 @@
-export { getCookie, setCookie, removeCookie } from "./cookie";
-export { handleUpload } from "./fileUploadUtil";
+export * from "./fileUploadUtil";
export * from "./fileDownload";
export * from './date'
+export * from './excelToJson'
+export * from './fileDeleteUtil'
+export * from './fileDownload'
+export * from './formatDisplayValue'
diff --git a/apps/sn/app/components/ui/fileUploadForm.tsx b/apps/sn/app/components/ui/fileUploadForm.tsx
index 0760b3252..fb626348e 100644
--- a/apps/sn/app/components/ui/fileUploadForm.tsx
+++ b/apps/sn/app/components/ui/fileUploadForm.tsx
@@ -1,148 +1,153 @@
"use client"
import { FileUploader } from "@common/components";
import { Button } from '@common/components/ui';
-import { handleUpload } from "@utils";
+import { handleUpload } from "@/components/lib/utils";
import { useId, useState } from 'react';
import type { HttpResponse, Upload } from "tus-js-client";
interface FileUploadFormProps {
- onSubmit?: (files: string, year: string, quarter: string, code: string, id: string) => void;
- onFileSelect?: (file: File | null, atflCd: string | null, atflId: string | null) => void; // 파일 선택 시 호출될 콜백 추가
- showButton?: boolean; // 버튼 표시 여부 (기본값 true)
- showPreview?: boolean; // 파일명 프리뷰 표시 여부
- accept?: string; // 파일 형식 지정
- fileIdx?: number; // 부모가 어떤 FileUploadForm인지 구분하기 위한 인덱스
+ onSubmit?: (files: string, year: string, quarter: string, code: string, id: string) => void;
+ onFileSelect?: (file: File | null, atflCd: string | null, atflId: string | null) => void; // 파일 선택 시 호출될 콜백 추가
+ showButton?: boolean; // 버튼 표시 여부 (기본값 true)
+ showPreview?: boolean; // 파일명 프리뷰 표시 여부
+ accept?: string; // 파일 형식 지정
+ fileIdx?: number; // 부모가 어떤 FileUploadForm인지 구분하기 위한 인덱스
}
const FileUploadForm = ({
- onSubmit,
- onFileSelect,
- showButton = true,
- showPreview = false,
- accept = ".jpeg, .jpg, .png",
- fileIdx // props에서 fileIdx 받기
+ onSubmit,
+ onFileSelect,
+ showButton = true,
+ showPreview = false,
+ accept = ".jpeg, .jpg, .png",
+ fileIdx // props에서 fileIdx 받기
}: FileUploadFormProps) => {
- const [internalAtflCd, setInternalAtflCd] = useState(null);
- const [internalAtflId, setInternalAtflId] = useState(null);
- const [currentFile, setCurrentFile] = useState(null); // 현재 선택된 파일을 저장할 상태
- const [fileName, setFileName] = useState('');
- const [files, setFiles] = useState(null);
- const [upload, setUpload] = useState(null);
- const uniqueId = useId(); // 각 FileUploadForm 인스턴스에 대한 고유 ID 생성
+ const [internalAtflCd, setInternalAtflCd] = useState(null);
+ const [internalAtflId, setInternalAtflId] = useState(null);
+ const [currentFile, setCurrentFile] = useState(null); // 현재 선택된 파일을 저장할 상태
+ const [fileName, setFileName] = useState('');
+ const [files, setFiles] = useState(null);
+ const [upload, setUpload] = useState(null);
+ const uniqueId = useId(); // 각 FileUploadForm 인스턴스에 대한 고유 ID 생성
+ // FileUploader 컴포넌트를 강제로 재마운트하기 위한 key 상태 추가
+ const [uploaderKey, setUploaderKey] = useState(0);
- const quater = [{ text: '1분기', val: '1' }, { text: '2분기', val: '2' }, { text: '3분기', val: '3' }, { text: '4분기', val: '4' }];
- // 현재 년도부터 10년 전까지의 년도 옵션 생성
- const yearOptions = Array.from({ length: 10 }, (_, i) => {
- const year = new Date().getFullYear() - i;
- return { text: `${year}년`, val: year.toString() };
- });
- const [selectedYear, setSelectedYear] = useState(yearOptions[0]?.val || '');
- const [selectedQuarter, setSelectedQuarter] = useState(quater[0]?.val || '');
+ const quater = [{ text: '1분기', val: '1' }, { text: '2분기', val: '2' }, { text: '3분기', val: '3' }, { text: '4분기', val: '4' }];
+ // 현재 년도부터 10년 전까지의 년도 옵션 생성
+ const yearOptions = Array.from({ length: 10 }, (_, i) => {
+ const year = new Date().getFullYear() - i;
+ return { text: `${year}년`, val: year.toString() };
+ });
+ const [selectedYear, setSelectedYear] = useState(yearOptions[0]?.val || '');
+ const [selectedQuarter, setSelectedQuarter] = useState(quater[0]?.val || '');
- const internalHandleUploadResponse = (file: File) => async (res: HttpResponse) => {
- const fileInfo = res.getHeader("X-File-Info");
- if (!fileInfo) {
- if (onFileSelect) onFileSelect(file, null, null);
- return;
- }
- const { atflCd: newAtflCd, atflId: newAtflId } = JSON.parse(fileInfo) ?? {};
- const orgnlFileNm = file.name;
- console.log(`FileUploadForm (idx: ${fileIdx ?? 'N/A'}) - orgnlFileNm:`, orgnlFileNm, 'New AtflCd:', newAtflCd, 'New AtflId:', newAtflId);
- setFileName(orgnlFileNm);
- setInternalAtflCd(newAtflCd);
- setInternalAtflId(newAtflId);
+ const internalHandleUploadResponse = (file: File) => async (res: HttpResponse) => {
+ const fileInfo = res.getHeader("X-File-Info");
+ if (!fileInfo) {
+ if (onFileSelect) onFileSelect(file, null, null);
+ return;
+ }
+ const { atflCd: newAtflCd, atflId: newAtflId } = JSON.parse(fileInfo) ?? {};
+ const orgnlFileNm = file.name;
+ console.log(`FileUploadForm (idx: ${fileIdx ?? 'N/A'}) - orgnlFileNm:`, orgnlFileNm, 'New AtflCd:', newAtflCd, 'New AtflId:', newAtflId);
+ setFileName(orgnlFileNm);
+ setInternalAtflCd(newAtflCd);
+ setInternalAtflId(newAtflId);
- if (onFileSelect) {
- onFileSelect(file, newAtflCd, newAtflId);
- }
- };
+ if (onFileSelect) {
+ onFileSelect(file, newAtflCd, newAtflId);
+ }
+ };
- return (
- {/* 컴포넌트 루트 div */}
-
{/* 카드 스타일링 */}
-
{/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
-
{/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
-
{
- const selectedFiles = e.target.files;
- if (!selectedFiles || selectedFiles.length === 0) {
- setFiles(null);
- setCurrentFile(null);
- setInternalAtflCd(null);
- setInternalAtflId(null);
- if (onFileSelect) {
- onFileSelect(null, null, null); // 파일 선택 취소 시 null 전달
- }
- return;
- }
+ return (
+ {/* 컴포넌트 루트 div */}
+
{/* 카드 스타일링 */}
+
{/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
+
{/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
+
{
+ const selectedFiles = e.target.files;
+ if (!selectedFiles || selectedFiles.length === 0) {
+ setFiles(null);
+ setCurrentFile(null);
+ setInternalAtflCd(null);
+ setInternalAtflId(null);
+ if (onFileSelect) {
+ onFileSelect(null, null, null); // 파일 선택 취소 시 null 전달
+ }
+ return;
+ }
- const firstFile = selectedFiles[0];
- if (!firstFile) return; // 타입스크립트 undefined 가능성 제거
+ const firstFile = selectedFiles[0];
+ if (!firstFile) return; // 타입스크립트 undefined 가능성 제거
- setFiles(selectedFiles);
- setCurrentFile(firstFile);
+ setFiles(selectedFiles);
+ setCurrentFile(firstFile);
- if (onFileSelect) {
- onFileSelect(firstFile, internalAtflCd, internalAtflId);
- }
+ if (onFileSelect) {
+ onFileSelect(firstFile, internalAtflCd, internalAtflId);
+ }
- handleUpload(selectedFiles, {
- handleUploadStart: setUpload,
- handleSuccess: setUpload,
- // handleResponse는 tus-js-client의 Upload 인스턴스 콜백과 연동 필요
- // 여기서는 handleUpload 유틸리티가 응답을 직접 처리한다고 가정
- handleResponse: internalHandleUploadResponse(firstFile),
- });
- }}
- customPreview={
- showPreview ? (
-
- {files && files.length > 0
- ? fileName
- : "파일을 선택하세요."}
-
- ) : null
- }
- />
-
- {showButton ? ( // showButton이 true일 때만 버튼 렌더링
-
- ) : null}
-
-
+ handleUpload(selectedFiles, {
+ handleUploadStart: setUpload,
+ handleSuccess: setUpload,
+ // handleResponse는 tus-js-client의 Upload 인스턴스 콜백과 연동 필요
+ // 여기서는 handleUpload 유틸리티가 응답을 직접 처리한다고 가정
+ handleResponse: internalHandleUploadResponse(firstFile),
+ });
+ }}
+ customPreview={
+ showPreview ? (
+
+ {files && files.length > 0
+ ? fileName
+ : "파일을 선택하세요."}
+
+ ) : null
+ }
+ />
+
+ {showButton ? ( // showButton이 true일 때만 버튼 렌더링
+
+ ) : null}
- )
+
+
+ )
}
export default FileUploadForm
\ No newline at end of file
diff --git a/apps/sn/app/components/ui/formSection.tsx b/apps/sn/app/components/ui/formSection.tsx
index 90bc8f735..384808aee 100644
--- a/apps/sn/app/components/ui/formSection.tsx
+++ b/apps/sn/app/components/ui/formSection.tsx
@@ -2,23 +2,23 @@ import { FormField } from '@common/business_components/ui'
import React, { type ReactElement } from 'react'
interface FormSectionProps {
- children: ReactElement
- titleNm: string
- form: any
- name: string
+ children: ReactElement
+ titleNm: string
+ form: any
+ name: string
}
const FormSection = ({ children, titleNm, form, name }: FormSectionProps) => {
- return (
-
-
{titleNm}
-
children}
- />
-
- )
+ return (
+
+
{titleNm}
+
children}
+ />
+
+ )
}
export default FormSection
\ No newline at end of file
diff --git a/apps/sn/app/components/ui/modal.tsx b/apps/sn/app/components/ui/modal.tsx
index f1dda48a6..afc2b5c9a 100644
--- a/apps/sn/app/components/ui/modal.tsx
+++ b/apps/sn/app/components/ui/modal.tsx
@@ -1,35 +1,34 @@
-import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose, DialogOverlay } from '@common/components/ui'
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogOverlay } from '@common/components/ui'
import React from 'react'
interface ModalProps {
- isModalOpen: boolean;
- setIsModalOpen: (open: boolean) => void;
- title?: string;
- children: React.ReactNode;
- closeModal: () => void;
- saveModal?: () => void
+ isModalOpen: boolean;
+ setIsModalOpen: (open: boolean) => void;
+ title?: string;
+ children: React.ReactNode;
+ closeModal: () => void;
+ saveModal?: () => void;
+ description?: string;
}
-const Modal: React.FC
= ({ isModalOpen, setIsModalOpen, title, children, closeModal,saveModal }) => {
- return (
-
- )
+const Modal: React.FC = ({ isModalOpen, setIsModalOpen, title, children, closeModal, saveModal }) => {
+ return (
+
+ )
}
export default Modal
\ No newline at end of file
diff --git a/apps/sn/app/components/ui/operFileUploadForm.tsx b/apps/sn/app/components/ui/operFileUploadForm.tsx
index bd1c67996..3c37673d2 100644
--- a/apps/sn/app/components/ui/operFileUploadForm.tsx
+++ b/apps/sn/app/components/ui/operFileUploadForm.tsx
@@ -1,51 +1,67 @@
"use client"
import { SelectBox } from '@common/business_components/ui';
-import React, { useState } from 'react'
+import React, { useState, useEffect } from 'react'
import FileUploadForm from './fileUploadForm';
-import { yearOptions } from '../lib/utils';
+import { yearOptions, getQuarterOptions } from '@/components/lib/utils';
-const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (files: string, year: string, quarter: string, code:string, id:string) => void }) => {
- const [atflCd, setAtflCd] = useState(null);
- const [atflId, setAtflId] = useState(null);
+const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (files: string, year: string, quarter: string, code: string, id: string) => void }) => {
+ const [atflCd, setAtflCd] = useState(null);
+ const [atflId, setAtflId] = useState(null);
+ const [selectedYear, setSelectedYear] = useState(yearOptions[0]?.val || '');
+ const [quaterOptions, setQuaterOptions] = useState(() => getQuarterOptions(selectedYear));
+ const [selectedQuarter, setSelectedQuarter] = useState(quaterOptions[0]?.val || '');
- const quater = [{ text: '1분기', val: '1' }, { text: '2분기', val: '2' }, { text: '3분기', val: '3' }, { text: '4분기', val: '4' }]
- const [selectedYear, setSelectedYear] = useState(yearOptions[0]?.val || '');
- const [selectedQuarter, setSelectedQuarter] = useState(quater[0]?.val || '');
+ // 년도가 변경될 때 분기 옵션 업데이트
+ useEffect(() => {
+ const updatedQuarterOptions = getQuarterOptions(selectedYear);
+ setQuaterOptions(updatedQuarterOptions);
+ // 분기 옵션이 변경되면 첫 번째 옵션으로 자동 선택
+ setSelectedQuarter(updatedQuarterOptions[0]?.val || '');
+ }, [selectedYear]);
- return (
-
-
-
{title}
-
-
-
-
- setSelectedYear(String(value))}
- /> setSelectedQuarter(String(value))}
- />
- {
- onSubmit(files, (selectedYear ?? year) || '', (selectedQuarter ?? quarter) || '', code, id);
- }}
- showButton={true}
- showPreview={true}
- accept={""} />
-
-
-
+ // 년도 변경 핸들러
+ const handleYearChange = (value: string | number) => {
+ const yearValue = String(value);
+ setSelectedYear(yearValue);
+ };
+
+ return (
+
+
+
{title}
+
+
+
+
+
+ setSelectedQuarter(String(value))}
+ value={selectedQuarter}
+ />
+ {
+ onSubmit(files, (selectedYear ?? year) || '', (selectedQuarter ?? quarter) || '', code, id);
+ }}
+ showButton={true}
+ showPreview={true}
+ accept={""} />
+
- )
+
+
+ )
}
export default operFileUploadForm
\ No newline at end of file
diff --git a/apps/sn/app/components/ui/verticalTable.tsx b/apps/sn/app/components/ui/verticalTable.tsx
index e5e506796..abdad03bb 100644
--- a/apps/sn/app/components/ui/verticalTable.tsx
+++ b/apps/sn/app/components/ui/verticalTable.tsx
@@ -1,206 +1,221 @@
import UiPageNations from "@common/business_components/ui/table/uiPageNations";
-import { Table, TableBody, TableCell, TableRow } from "@common/components";
+import { Table, TableBody, TableCell, TableRow, Button } from "@common/components";
import { useEffect, useState } from "react";
type UiTableProps = {
- headName: React.ReactNode | undefined;
- tableName1?: React.ReactNode | undefined;
- tableData: { [key: string]: string | number | boolean | object }[];
- headlist: UiHeadProps[];
- pageSize: number;
- total: number;
- children: Record
| undefined;
- cellClick: ((index: number | undefined, headId: string) => void) | undefined;
- onPageChange: (page: number) => void;
- className?: string;
- resetPageNo?: boolean;
- isEditable?: boolean;
- tableName2?: React.ReactNode | undefined;
- tableData2?: { [key: string]: string | number | boolean | object }[];
- headlist2?: UiHeadProps[];
- pageSize2?: number;
- total2?: number;
- children2?: Record | undefined;
- cellClick2?: ((index: number | undefined, headId: string) => void) | undefined;
- onPageChange2?: (page: number) => void;
- className2?: string;
- resetPageNo2?: boolean;
- isEditable2?: boolean;
- showSecondTable?: boolean;
+ headName: React.ReactNode | undefined;
+ tableName1?: React.ReactNode | undefined;
+ tableData: { [key: string]: string | number | boolean | object }[];
+ headlist: UiHeadProps[];
+ pageSize: number;
+ total: number;
+ children?: Record | undefined;
+ cellClick: ((index: number | undefined, headId: string) => void) | undefined;
+ onPageChange: (page: number) => void;
+ className?: string;
+ resetPageNo?: boolean;
+ isEditable?: boolean;
+ tableName2?: React.ReactNode | undefined;
+ tableData2?: { [key: string]: string | number | boolean | object }[];
+ headlist2?: UiHeadProps[];
+ pageSize2?: number;
+ total2?: number;
+ children2?: Record | undefined;
+ cellClick2?: ((index: number | undefined, headId: string) => void) | undefined;
+ onPageChange2?: (page: number) => void;
+ className2?: string;
+ resetPageNo2?: boolean;
+ isEditable2?: boolean;
+ showSecondTable?: boolean;
+ showSaveButton?: boolean;
+ onSaveClick?: () => void;
+ onFormDataChange?: (formData: { [key: string]: string | number | boolean }) => void; // 추가
};
type UiHeadProps = {
- id: string;
- title: string;
- align?: string;
- type?: string;
- options?: string[];
+ id: string;
+ title: string;
+ align?: string;
+ type?: string;
+ options?: string[];
};
export function VerticalTable({
- headName,
- tableName1,
- tableData,
- headlist,
- pageSize,
- total,
- children,
- cellClick,
- onPageChange,
- className = "",
- resetPageNo = false,
- isEditable = false,
- tableName2,
- tableData2,
- headlist2,
- pageSize2,
- total2,
- children2,
- cellClick2,
- onPageChange2,
- className2 = "",
- resetPageNo2 = false,
- isEditable2 = false,
- showSecondTable = false,
+ headName,
+ tableName1,
+ tableData,
+ headlist,
+ pageSize,
+ total,
+ children,
+ onPageChange,
+ className = "",
+ resetPageNo = false,
+ isEditable = false,
+ tableName2,
+ headlist2,
+ isEditable2 = false,
+ showSecondTable = false,
+ showSaveButton = false,
+ onSaveClick,
+ onFormDataChange,
}: UiTableProps) {
- const [cur, setCur] = useState(1);
- const [formData, setFormData] = useState<{ [key: string]: string | number | boolean }>({});
- useEffect(() => {
- if (resetPageNo) {
- setCur(1);
- onPageChange(1);
- }
- }, [onPageChange, resetPageNo]);
+ const [cur, setCur] = useState(1);
+ const [formData, setFormData] = useState<{ [key: string]: string | number | boolean }>({});
+ useEffect(() => {
+ if (resetPageNo) {
+ setCur(1);
+ onPageChange(1);
+ }
+ }, [onPageChange, resetPageNo]);
- useEffect(() => {
- if (tableData.length > 0 && tableData[0]) {
- setFormData(tableData[0] as { [key: string]: string | number | boolean });
- }
- }, [tableData]);
+ useEffect(() => {
+ if (tableData.length > 0 && tableData[0]) {
+ // 깊은 복사를 통해 새로운 객체 생성
+ const newData = JSON.parse(JSON.stringify(tableData[0]));
+ setFormData(newData);
+ console.log("Form data initialized:", newData); // 디버깅용
+ }
+ }, [tableData]);
- const handleInputChange = (id: string, value: string | number | boolean) => {
- setFormData((prev) => ({
- ...prev,
- [id]: value,
- }));
+ const handleInputChange = (id: string, value: string | number | boolean) => {
+ console.log(`Input change: ${id} = ${value}`); // 디버깅용
+ const newFormData = {
+ ...formData,
+ [id]: value,
};
+ console.log("New form data:", newFormData); // 디버깅용
+ setFormData(newFormData);
- const handlePageChange = (page: number) => {
- setCur(page);
- onPageChange(page);
- };
+ // 폼 데이터가 변경될 때마다 부모에게 알림
+ if (onFormDataChange) {
+ onFormDataChange(newFormData);
+ }
+ };
+ const handlePageChange = (page: number) => {
+ setCur(page);
+ onPageChange(page);
+ };
- return (
- <>
- {headName ? (
-
-
{headName}
-
- ) : null}
-
- {tableName1 && ( // tableName prop이 있으면 표시
-
{tableName1}
- )}
-
-
- {headlist?.map((head) => (
-
- {/* 컬럼 제목 */}
-
- {head.title}
-
- {/* 데이터 값 또는 입력 필드 */}
-
- {children && children[head.id] ? children[head.id] : isEditable ? (
- head.type === "select" ? (
-
- ) : head.type === "input" ? (
- handleInputChange(head.id, e.target.value)}
- className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
- />
- ) : (
- {formData[head.id] ?? "-"}
- )
- ) : (
- {formData[head.id] ?? "-"}
- )}
-
-
+ return (
+ <>
+ {headName ? (
+
+
{headName}
+ {showSaveButton && onSaveClick && (
+
+ )}
+
+ ) : null}
+
+ {tableName1 && ( // tableName prop이 있으면 표시
+
{tableName1}
+ )}
+
+
+ {headlist?.map((head) => (
+
+ {/* 컬럼 제목 */}
+
+ {head.title}
+
+ {/* 데이터 값 또는 입력 필드 */}
+
+ {children && children[head.id] ? children[head.id] : isEditable ? (
+ head.type === "select" ? (
+
-
- {tableName2 && ( // tableName prop이 있으면 표시
-
{tableName2}
- )}
- {showSecondTable && (
-
- )}
- {total > 0 && (
-
- )}
-
- >
- );
+
+ ) : head.type === "input" ? (
+ handleInputChange(head.id, e.target.value)}
+ className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
+ />
+ ) : (
+ {formData[head.id] ?? "-"}
+ )
+ ) : (
+ {formData[head.id] ?? "-"}
+ )}
+
+
+ ))}
+
+
+ {tableName2 && ( // tableName prop이 있으면 표시
+
{tableName2}
+ )}
+ {showSecondTable && (
+
+ )}
+ {total > 0 && (
+
+ )}
+
+ >
+ );
}
\ No newline at end of file
diff --git a/apps/sn/app/ii/BaseLayout.tsx b/apps/sn/app/ii/BaseLayout.tsx
deleted file mode 100644
index 544802744..000000000
--- a/apps/sn/app/ii/BaseLayout.tsx
+++ /dev/null
@@ -1,276 +0,0 @@
-'use client'
-import { getData } from '@/components/lib/api'
-import ContentLayout from '@/components/ui/contentLayout'
-import { GovSidoSigunguSearchForm } from '@/components/ui/govSidoSigunguSearchForm'
-import { DatePicker, Form, SearchFormRight, SelectBox } from '@common/business_components/ui'
-import ListDiv from '@common/business_components/ui/list_div'
-import { SelectBox2 } from '@common/business_components/ui/select/index-2'
-import { Button, Label } from '@common/components/ui'
-import { useEffect, useState, type ReactNode } from 'react'
-
-type TitleName = {
- mainTitle: string
- firstCardTitle: string
- secondCardTitle?: string
-}
-type SelectBox = {
- labelNm?: Label
- searchChk?: boolean
- title?: string;
- onSearchClick?: () => Promise;
-}
-type Label = {
- first: string
- second: string
- third: string
- fourth: string
-}
-// API로부터 받아올 데이터 타입을 정의 (SelectBox에 사용될 형태)
-interface ApiSelectOption {
- text: string;
- val: string;
-}
-type BaseLayout = {
- children?: ReactNode[]
- titleName: TitleName
- form: any
- onSubmitEvent: Function
- graphBtn?: boolean
- analysisBtn?: string
- firstDivBtn?: boolean
- selectBox?: SelectBox
- showDatePicker?: boolean;
- enoCd?: string | number
- setEnoCd?: (enoCd: string) => void
- ctpvCd?: string | number
- setCtpvCd?: (ctpvCd: string) => void
- sigungu?: ApiSelectOption
- setSigungu?: (sigungu: ApiSelectOption) => void
- selectedSwageTreatmentPlant?: string | number;
- onSwageTreatmentPlantChange?: (value: string | number) => void;
- selectedSwageProcessingZone?: string | number;
- onSwageProcessingZoneChange?: (value: string | number) => void;
- aplcnYm?: Date
- setAplcnYm?: (aplcnYm: Date | undefined) => void;
- isLoading?: boolean;
- // Excel 다운로드 관련 props 추가
- onExcelDownload?: () => void;
- onDeleteFile?: () => void;
- onAnalysis?: () => void;
- selectedRowData?: any;
-}
-// TODO: 나중에 이벤트 추가되면 파라미터 추가 필요 ?
-/**
- *
- * @param children
- * @param titleName : 메인 타이틀, 첫번째 요소 타이틀, 두번째 요소 타이틀
- * @param form : zod 스키마
- * @param onSubmitEvent : 폼 이벤트 처리
- * @param graphBtn : 하단에 그래프 버튼 유무 처리
- * @returns
- */
-const BaseLayout = ({
- children,
- titleName,
- form,
- onSubmitEvent,
- graphBtn = false,
- analysisBtn,
- selectBox,
- showDatePicker = false,
- enoCd,
- setEnoCd,
- ctpvCd,
- setCtpvCd,
- sigungu,
- setSigungu,
- selectedSwageTreatmentPlant,
- onSwageTreatmentPlantChange,
- selectedSwageProcessingZone,
- onSwageProcessingZoneChange,
- aplcnYm,
- setAplcnYm,
- isLoading,
- // Excel 다운로드 관련 props 추가
- onExcelDownload,
- onDeleteFile,
- onAnalysis,
- selectedRowData
-}: BaseLayout) => {
-
- const defaultOption: ApiSelectOption = { val: '0', text: '선택' };
-
- const [processingZoneOptions, setProcessingZoneOptions] = useState([]);
- const [treatmentFacilityOptions, setTreatmentFacilityOptions] = useState([]);
- const [isLoadingAreaData, setIsLoadingAreaData] = useState(false);
- const [atflId, setAtflId] = useState('')
- const [fileNm, setFileNm] = useState('')
- const [dcrpPplMtncBizSn, setDcrpPplMtncBizSn] = useState('')
-
- useEffect(() => {
- const fetchData = async () => {
- if (!sigungu || sigungu.val === '0' || !sigungu.val) {
- console.log("BaseLayout: Skipping fetchData because sigungu.val is:", sigungu?.val);
- setProcessingZoneOptions([defaultOption]);
- setTreatmentFacilityOptions([defaultOption]);
- setIsLoadingAreaData(false);
- return;
- }
-
- setIsLoadingAreaData(true);
- try {
- const queryParamsZone = new URLSearchParams({
- lyrTypeNm: 'tb_ms_swage_prcs_zone',
- page: '0',
- size: '100000',
- sort: 'string',
- });
- const cqlFiltersZone: string[] = [];
- if (sigungu.val && sigungu.val !== '0') {
- cqlFiltersZone.push(`sgg_cd='${sigungu.val}'`);
- }
- if (cqlFiltersZone.length > 0) {
- queryParamsZone.append('cqlFiter', cqlFiltersZone.join(' and '));
- }
-
- const queryParamsFacility = new URLSearchParams({
- lyrTypeNm: 'tb_il_swage_prcs_fclt',
- page: '0',
- size: '100000', // 요청하신 URL에 맞게 50으로 변경 가능
- sort: 'string',
- });
- const cqlFiltersFacility: string[] = [];
- if (sigungu.text && sigungu.val !== '0') {
- cqlFiltersFacility.push(`sgg_nm ILIKE '%${sigungu.text}%'`);
- }
- if (cqlFiltersFacility.length > 0) {
- queryParamsFacility.append('cqlFiter', cqlFiltersFacility.join(' and ')); // API 명세에 따라 cqlFilter 또는 cqlFiter
- }
-
- console.log("BaseLayout API URL for Zones:", `v1/fclts?${queryParamsZone.toString()}`);
- console.log("BaseLayout API URL for Facilities:", `v1/fclts?${queryParamsFacility.toString()}`);
-
- const [zoneRes, facilityRes] = await Promise.all([
- getData(`v1/fclts?${queryParamsZone.toString()}`),
- getData(`v1/fclts?${queryParamsFacility.toString()}`)
- ]);
-
- const zones = (zoneRes.data || []).map((item: any) => ({
- text: item.swtrmtZoneNm || item.name || `구역 ${item.id || item.gid || item.objectid}`,
- val: item.fid || item.id || item.gid || item.objectid
- }));
- setProcessingZoneOptions([defaultOption, ...zones]);
- console.log("BaseLayout Fetched Processing Zones:", [defaultOption, ...zones]);
-
-
- const facilities = (facilityRes.data || []).map((item: any) => ({
- text: item.swtrmtFcltNm || item.name || `시설 ${item.id || item.gid || item.objectid}`,
- val: item.fid || item.id || item.gid || item.objectid
- }));
- setTreatmentFacilityOptions([defaultOption, ...facilities]);
- console.log("BaseLayout Fetched Treatment Facilities:", [defaultOption, ...facilities]);
-
- } catch (error) {
- console.error("BaseLayout: 지역/시설 데이터 조회 중 오류 발생:", error);
- setProcessingZoneOptions([defaultOption]);
- setTreatmentFacilityOptions([defaultOption]);
- } finally {
- setIsLoadingAreaData(false);
- }
- };
-
- fetchData();
- }, [sigungu]); // sigungu 상태가 변경될 때마다 실행
-
- // 파일 다운로드
- const isChckFile = () => {
- // Excel 다운로드 함수가 있으면 Excel 다운로드 실행
- if (onExcelDownload) {
- onExcelDownload();
- return;
- }
- return true
- }
- // 파일 삭제
- const isDeleteFile = async () => {
- // Excel 다운로드 함수가 있으면 Excel 다운로드 실행
- if (onDeleteFile) {
- onDeleteFile();
- return;
- }
- }
-
- return (
-
-
- {
- children?.[1] != null ?
-
-
{titleName?.secondCardTitle}
-
- {graphBtn ? : null}
- {/* 그래프 있을 시 */}
- {graphBtn ? : null}
-
-
- {children?.[1]}
- : null
- }
-
-
- )
-}
-
-export default BaseLayout
\ No newline at end of file
diff --git a/apps/sn/app/ii/irsetting/page.tsx b/apps/sn/app/ii/irsetting/page.tsx
deleted file mode 100644
index 2944af9c0..000000000
--- a/apps/sn/app/ii/irsetting/page.tsx
+++ /dev/null
@@ -1,380 +0,0 @@
-'use client'
-import { postData } from '@/components/lib/api'
-import FileUploadForm from '@/components/ui/fileUploadForm'
-import FormSection from '@/components/ui/formSection'
-import { DatePicker, filePicked } from '@common/business_components/ui'
-import ListDiv from '@common/business_components/ui/list_div'
-import { Input } from '@common/components/ui'
-import { zodResolver } from '@hookform/resolvers/zod'
-import { useState } from 'react'
-import { useForm } from 'react-hook-form'
-import { z } from 'zod'
-import { excelToFlowRateData, excelToMatchingResultData, excelToTimePatternData } from '../../components/lib/utils/excelToJson'
-import BaseLayout from '../BaseLayout'
-
-const formSchema = z.object({
- managenm: z.string(),
- region: z.string(),
- suyeonga: z.number(),
- inputdate: z.coerce.date(),
- rtkSource: z.string(),
- suyeongaPlace: z.string(),
- pattern: z.string()
-})
-
-// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
-interface UploadedFileInfo {
- file: File | null;
- atflCd: string | null;
- atflId: string | null;
- // 필요하다면 파일 이름 등 추가 정보 저장 가능
- // fileName: string;
-}
-// 초기 파일 정보 상태
-const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
-
-interface ApiSelectOption {
- text: string;
- val: string;
-}
-
-const IrSetting = () => {
- const form = useForm>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- managenm: "",
- region: "",
- suyeonga: 0,
- inputdate: new Date(),
- rtkSource: "",
- suyeongaPlace: "",
- pattern: ""
- }
- })
-
- const [uploadedFilesData, setUploadedFilesData] = useState([
- initialFileInfo, // 0: 오수관망도
- initialFileInfo, // 1: 수용가-맨홀 매칭결과
- initialFileInfo, // 2: 오수량 시간패턴
- initialFileInfo // 3: 유량자료 등록
- ]);
-
- const [selectedDate, setSelectedDate] = useState(new Date());
- const [input1, setInput1] = useState('');
- const [input2, setInput2] = useState('');
- const [select1, setSelect1] = useState('0'); // 환경청코드
- const [select2, setSelect2] = useState('0'); // 시도코드
- const [select3, setSelect3] = useState({ val: '0', text: '전체' }); // 시군구 상태를 객체로 변경
- const [select4, setSelect4] = useState('0'); // 하수처리장코드
- const [select5, setSelect5] = useState('0'); // 하수처리구역코드
- const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
- const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
-
- // 폼 초기화 함수
- const resetAllForms = () => {
- form.reset({ // react-hook-form 초기화
- managenm: "",
- region: "",
- suyeonga: 0,
- inputdate: new Date(),
- rtkSource: "",
- suyeongaPlace: "",
- pattern: ""
- });
- setUploadedFilesData([ // 파일 업로드 상태 초기화
- initialFileInfo,
- initialFileInfo,
- initialFileInfo,
- initialFileInfo
- ]);
- setSelectedDate(new Date()); // 날짜 선택 초기화
- setInput1(''); // 입력 필드 초기화
- setInput2(''); // 입력 필드 초기화
- setSelect1('0'); // 선택 필드 초기화
- setSelect2('0');
- setSelect3({ val: '0', text: '전체' });
- setSelect4(0);
- setSelect5(0);
- setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
- };
-
- // FileUploadForm의 onFileSelect prop으로 전달될 콜백 함수
- const handleFileSelection = (
- index: number, // FileUploadForm의 fileIdx 값
- selectedFile: File | null,
- cd: string | null,
- id: string | null
- ) => {
- setUploadedFilesData(prevData => {
- const newData = [...prevData];
- newData[index] = {
- file: selectedFile,
- atflCd: cd,
- atflId: id,
- };
- return newData;
- });
- console.log(`Page: File data received for form index ${index}`, { fileName: selectedFile?.name, cd, id });
- };
-
-
- const registFile = async (analysisData: any) => {
- setIsLoadingResult(true); // 로딩 상태 시작
- console.log("Submitting combined analysis data to backend:", analysisData);
- // 추후 API 엔드포인트에 맞게 URL 수정 필요
- const data = await postData('v1/inftwtAnls', analysisData);
- console.log("Response from backend:", data);
- if (data) {
- alert("분석 데이터가 성공적으로 제출되었습니다.");
- resetAllForms(); // 성공 시 폼 초기화 함수 호출
- } else alert("분석 데이터 제출 중 오류가 발생했습니다.");
- setIsLoadingResult(false); // 로딩 상태 시작
- };
-
- // 침입수 분석 실행 버튼 클릭 핸들러
- const handleAnalysisClick = async () => {
- setIsLoadingResult(true); // 로딩 상태 시작
- console.log(uploadedFilesData);
- const file1 = uploadedFilesData[0]; // 오수관망도
- const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
- const file3 = uploadedFilesData[2]; // 오수량 시간패턴
- const file4 = uploadedFilesData[3]; // 유량자료
-
- console.log("오수관망도 정보:", file1?.file);
- console.log("수용가-맨홀 매칭결과 정보:", file2);
- console.log("오수량 시간패턴 정보:", file3);
- console.log("유량자료 정보:", file4);
-
- // 모든 필수 파일이 선택되었는지 확인 (UploadedFileInfo 객체와 그 안의 file 객체 모두 확인)
- // 유량자료는 선택값
- if (!file1?.file || !file2?.file || !file3?.file) {
- setIsLoadingResult(false);
- alert('모든 분석용 파일을 선택해주세요.');
- return;
- }
-
- type MatchingResult = { anlsSn: number; mhlMngNo: string; rcptrNo: string; };
- type TimePattern = { hrId: number; rt?: number | null | undefined; };
- type FlowRate = { pplMngNo: string; mtrngDt: string; oilq?: number | null | undefined; };
-
- const filePickers: {
- file: UploadedFileInfo;
- parser: (excelData: any) => MatchingResult[] | TimePattern[] | FlowRate[];
- }[] = [
- { file: file2, parser: excelToMatchingResultData },
- { file: file3, parser: excelToTimePatternData }
- ];
-
- if (file4?.file) {
- filePickers.push({ file: file4, parser: excelToFlowRateData });
- }
-
- try {
- const parsedResults = await Promise.all(
- filePickers.map(async ({ file, parser }) => {
- if (!file || !file.file) return null;
-
- const jsonData = await filePicked(file.file, 0);
-
- if (jsonData === undefined) {
- console.warn(`Warning: filePicked returned undefined for ${file.file.name}`);
- return {
- fileName: file.file.name,
- atflCd: file.atflCd,
- atflId: file.atflId,
- parsedData: null
- };
- }
-
- // jsonData를 각 parser 함수로 처리
- const parsedDataBySpecificFunction = parser(jsonData);
-
- return {
- fileName: file.file.name,
- atflCd: file.atflCd,
- atflId: file.atflId,
- parsedData: parsedDataBySpecificFunction
- };
- })
- );
-
- // 각 파싱 결과 접근
- const matchingResultData = parsedResults.find(r => r && r.fileName === file2.file?.name)?.parsedData;
- const timePatternData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
- const flowRateData = file4?.file
- ? parsedResults.find(r => r && r.fileName === file4.file?.name)?.parsedData
- : null;
-
- // 새로운 JSON 데이터 생성
- const combinedAnalysisData = {
- enoCd: select1.toString(), // 환경청코드
- ctpvCd: select2.toString(), // 시도코드
- sggCd: select3.val.toString(), // 시군구코드
- swageTmplntCd: select4.toString(), // 하수처리장코드
- swtrmtZoneCd: select5.toString(), // 하수처리구역코드
- aplcnYm: new Date(selectedDate).toISOString().substring(0, 7).replace("-", ""), // 적용연월
- drtwSwtcRt: parseFloat(input1) || null, // 오수전환율 (숫자로 변환)
- anlsInfo: input2, // 분석정보
- atflCd: file1?.atflCd, // 첨부파일CD (오수관망도)
- atflId: file1?.atflId, // 첨부파일ID (오수관망도)
- atflInpNm: file1?.file?.name, // 오수관망도 파일명
- atflHrPttnNm: file3?.file?.name, // 오수량 시간패턴 파일명
- atflMpngNm: file2?.file?.name, // 수용가-맨홀 매칭결과 파일명
- atflOilqNm: file4?.file?.name || null, // 유량자료 파일명 (없을 수 있음)
- tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
- tbSnHrPttn: timePatternData, // 오수량 시간패턴
- tbSnOilqData: flowRateData, // 유량자료 (없을 수 있음)
- };
-
- console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
-
- // 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
- await registFile(combinedAnalysisData);
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("파일 파싱 중 오류 발생:", error);
- alert("파일 처리 중 오류가 발생했습니다.");
- return;
- }
- }
-
- return (
- <>
- { }}
- graphBtn={false}
- analysisBtn={'침입수분석 실행'}
- selectBox={{ title: '분석 대상지역 선택' }}
- enoCd={select1}
- setEnoCd={setSelect1}
- ctpvCd={select2}
- setCtpvCd={setSelect2}
- sigungu={select3}
- setSigungu={setSelect3}
- selectedSwageTreatmentPlant={select4}
- onSwageTreatmentPlantChange={setSelect4}
- selectedSwageProcessingZone={select5}
- onSwageProcessingZoneChange={setSelect5}
- isLoading={isLoadingResult}
- onAnalysis={handleAnalysisClick}
- >
- {[
-
- handleFileSelection(0, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={""}
- fileIdx={0} />
-
-
- handleFileSelection(1, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={1} />
-
-
- handleFileSelection(2, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={2} />
-
-
- {
- if (date) {
- setSelectedDate(date);
- form.setValue('inputdate', date, { shouldValidate: true });
- }
- }
- }}
- selectClass="ml-5 date-picker-trigger" // date-picker.css의 스타일 적용
- />
-
-
- {
- const newValue = e.target.value;
-
- if (newValue === "") {
- setInput1(newValue);
- return;
- }
-
- // 숫자와 '.'만 허용하고, '.'은 최대 하나인지 확인
- const isValidChars = /^[0-9]*\.?[0-9]*$/.test(newValue);
- if (!isValidChars) return; // 유효하지 않은 문자 또는 여러 개의 '.' 포함
-
- // '.' 기호가 포함된 경우, 처음이나 끝에 오면 안 됨
- if (newValue.includes('.') && newValue.startsWith('.')) return; // '.'이 처음에는 올 수 없음
-
- setInput1(newValue);
- }}
- className="ml-5 h-[3.2rem] text-center text-xl w-[150px]"
- placeholder="예: 0.75" />
-
-
- setInput2(e.target.value)}
- className="ml-5 h-[3.2rem] text-center text-xl w-[150px]" />
-
-
-
-
- handleFileSelection(3, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={3}
- />
-
-
-
-
]}
- {/*
-
- handleFileSelection(3, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={3} />
-
-
-
-
-
*/}
-
- >
- )
-}
-
-export default IrSetting
\ No newline at end of file
diff --git a/apps/sn/app/ii/rdii/page.tsx b/apps/sn/app/ii/rdii/page.tsx
deleted file mode 100644
index 2f61b57b9..000000000
--- a/apps/sn/app/ii/rdii/page.tsx
+++ /dev/null
@@ -1,438 +0,0 @@
-"use client"
-
-import { postData } from '@/components/lib/api'
-import FileUploadForm from "@/components/ui/fileUploadForm"
-import FormSection from "@/components/ui/formSection"
-import BaseLayout from "@/ii/BaseLayout"
-import { DatePicker, filePicked } from "@common/business_components/ui"
-import { Input } from "@common/components/ui"
-import { zodResolver } from "@hookform/resolvers/zod"
-import { Label } from '@radix-ui/react-label'
-import { useState } from "react"
-import { useFieldArray, useForm } from "react-hook-form"
-import { z } from "zod"
-import { excelToMatchingResultData, excelToRainData } from '../../components/lib/utils/excelToJson'
-import { EditableFormTable, type EditableTableHeadItem } from '../../components/ui/EditableFormTable'
-
-
-// zod 스키마 정의
-const formSchema = z.object({
- enoCd: z.string(), // 환경청코드
- ctpvCd: z.string(), // 시도코드
- sggCd: z.string(), // 시군구코드
- swageTmplntCd: z.string(), // 하수처리장코드
- swtrmtZoneCd: z.string(), // 하수처리구역코드
- rtkSource: z.string(), // RTK계수 출처
- rdiiArea: z.string(), // RDII 기여면적
- unitFactors: z.array(z.object({ // 단위도 계수
- response: z.string(),
- R: z.string(),
- T: z.string(),
- K: z.string(),
- })),
- initialDepths: z.array(z.object({ // 초기 차단 깊이
- response: z.string(),
- Dmax: z.string(),
- Drec: z.string(),
- Do: z.string(),
- })),
- // osumap: z.instanceof(File).optional(), // 오수관망도
- // matching: z.instanceof(File).optional(), // 수용가-맨홀 매칭결과
- aplcnYm: z.string(), // 상수사용량 적용기간 (YYYYMM 형식)
- rate: z.string(), // 오수전환율
- // rain: z.instanceof(File).optional(), // 강우자료
- analysisInfo: z.string().optional(), // 분석 정보
- date: z.date(),
- // date: z.coerce.date(),
-})
-// zod 스키마 타입 추론
-type FormSchemaType = z.infer;
-// 기본 폼 값 정의 (테스트 편의를 위해 초기값 설정, 추후 삭제 필요)
-const defaultFormValues: FormSchemaType = {
- enoCd: "",
- ctpvCd: "",
- sggCd: "",
- swageTmplntCd: "",
- swtrmtZoneCd: "",
- rtkSource: "출처",
- rdiiArea: "123", // 문자열로 기본값 설정
- unitFactors: [
- { response: "Short-Term", R: "0.040", T: "0.5", K: "1" }, // 문자열로 기본값 설정
- { response: "Medium-Term", R: "0.005", T: "1", K: "2" },
- { response: "Long-Term", R: "0.005", T: "2", K: "3" },
- ],
- initialDepths: [
- { response: "Short-Term", Dmax: "0", Drec: "0", Do: "0" }, // 문자열로 기본값 설정
- { response: "Medium-Term", Dmax: "0", Drec: "0", Do: "0" },
- { response: "Long-Term", Dmax: "0", Drec: "0", Do: "0" },
- ],
- // osumap: undefined,
- // matchingResultFile: undefined,
- aplcnYm: "",
- rate: "0.8", // 문자열로 기본값 설정
- // rainFile: undefined,
- analysisInfo: "test 분석정보",
- date: new Date(),
-};
-
-// 각 파일 업로드 폼의 데이터를 저장할 인터페이스 정의
-interface UploadedFileInfo {
- file: File | null;
- atflCd: string | null;
- atflId: string | null;
-}
-
-// 초기 파일 정보 상태
-const initialFileInfo: UploadedFileInfo = { file: null, atflCd: null, atflId: null };
-
-interface ApiSelectOption {
- text: string;
- val: string;
-}
-
-export default function RTKForm() {
- const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
- const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
-
- // FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
- // 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
- const [uploadedFilesData, setUploadedFilesData] = useState([
- initialFileInfo, // 0: 오수관망도
- initialFileInfo, // 1: 수용가-맨홀 매칭결과
- initialFileInfo, // 2: 강우자료
- ]);
-
- const [select1, setSelect1] = useState('0'); // 환경청코드 (enoCd)
- const [select2, setSelect2] = useState('0'); // 시도코드 (ctpvCd)
- const [select3, setSelect3] = useState({ val: '0', text: '전체' }); // 시군구 (sggCd)
- const [select4, setSelect4] = useState('0'); // 하수처리장 (swageTmplntCd)
- const [select5, setSelect5] = useState('0'); // 하수처리구역 (swtrmtZoneCd)
-
-
- // form 인스턴스 생성
- const form = useForm({
- resolver: zodResolver(formSchema),
- defaultValues: defaultFormValues
- });
-
- // 폼 초기화 함수
- const resetAllForms = () => {
- form.reset(defaultFormValues); // 폼 값 초기화
- setUploadedFilesData([ // 파일 업로드 상태 초기화 (3개 파일)
- initialFileInfo,
- initialFileInfo,
- initialFileInfo,
- ]);
- setFormResetKey(prevKey => prevKey + 1); // FileUploadForm 재마운트를 위해 key 변경
- setSelect1('0');
- setSelect2('0');
- setSelect3({ val: '0', text: '전체' });
- setSelect4('0');
- setSelect5('0');
- };
-
- // FileUploadForm의 onFileSelect prop으로 전달될 콜백 함수
- const handleFileSelection = (
- index: number, // FileUploadForm의 fileIdx 값
- selectedFile: File | null,
- cd: string | null,
- id: string | null
- ) => {
- setUploadedFilesData(prevData => {
- const newData = [...prevData];
- newData[index] = {
- file: selectedFile,
- atflCd: cd,
- atflId: id,
- };
- return newData;
- });
- console.log(`Page: File data received for form index ${index}`, { fileName: selectedFile?.name, cd, id });
- };
-
- const registFile = async (analysisData: any) => {
- console.log("Submitting combined analysis data to backend");
- // 추후 API 엔드포인트에 맞게 URL 수정 필요
- const data = await postData('v1/rdiiAnls', analysisData);
- if (data) {
- alert("분석 데이터가 성공적으로 제출되었습니다.");
- resetAllForms(); // 성공 시 폼 초기화 함수 호출
- } else alert("분석 데이터 제출 중 오류가 발생했습니다.");
- };
-
- // 침입수 분석 실행 버튼 클릭 핸들러
- const handleAnalysisClick = async () => {
- setIsLoadingResult(true); // 로딩 상태 시작
- const formData = form.getValues();
- console.log(uploadedFilesData);
- const file1 = uploadedFilesData[0]; // 오수관망도
- const file2 = uploadedFilesData[1]; // 수용가-맨홀 매칭결과
- const file3 = uploadedFilesData[2]; // 강우자료
-
- console.log("오수관망도 정보:", file1?.file);
- console.log("수용가-맨홀 매칭결과 정보:", file2);
- console.log("강우자료:", file3);
-
- // 모든 필수 파일이 선택되었는지 확인
- if (!file1?.file || !file2?.file || !file3?.file) {
- setIsLoadingResult(false);
- alert('모든 분석용 파일을 선택해주세요.');
- return;
- }
-
- const filePickers = [
- { file: file2, parser: excelToMatchingResultData },
- { file: file3, parser: excelToRainData },
- ];
-
- try {
- const parsedResults = await Promise.all(
- filePickers.map(async ({ file, parser }) => {
- if (!file || !file.file) return null; // fileInfo 객체 및 file 객체 null 체크
-
- // filePicked 함수에 File 객체와 headerNum 전달
- const jsonData = await filePicked(file.file, 0);
-
- if (jsonData === undefined) {
- console.warn(`Warning: filePicked returned undefined for ${file.file.name}`);
- return {
- fileName: file.file.name,
- atflCd: file.atflCd,
- atflId: file.atflId,
- parsedData: null // 또는 적절한 기본값
- };
- }
-
- // jsonData를 각 parser 함수로 처리
- // parser 함수가 filePicked가 반환하는 JSON 형식을 직접 처리한다고 가정
- const parsedDataBySpecificFunction = parser(jsonData);
-
- return {
- fileName: file.file.name,
- atflCd: file.atflCd,
- atflId: file.atflId,
- parsedData: parsedDataBySpecificFunction
- };
- })
- );
-
- // 각 파싱 결과 접근
- const matchingResultData = parsedResults.find(r => r && r.fileName === file2.file?.name)?.parsedData;
- const rainData = parsedResults.find(r => r && r.fileName === file3.file?.name)?.parsedData;
-
- // 새로운 JSON 데이터 생성
- const combinedAnalysisData = {
- enoCd: select1.toString(), // 환경청코드
- aplcnYm: new Date(formData.date).toISOString().substring(0, 7).replace("-", ""), // 적용연월 (YYYYMM 형식)
- ctpvCd: select2.toString(), // 시도코드
- sggCd: select3.val.toString(), // 시군구코드
- swageTmplntCd: select4.toString(), // 하수처리장코드
- swtrmtZoneCd: select5.toString(), // 하수처리구역코드
- atflCd: file1?.atflCd, // 첨부파일CD (오수관망도)
- atflId: file1?.atflId, // 첨부파일ID (오수관망도)
- atflInpNm: file1?.file?.name || "", // 오수관망도 파일명
- atflMpngNm: file2?.file?.name || "", // 수용가-맨홀 매칭결과 파일명
- atflRainNm: file3?.file?.name || "", // 강우자료 파일명
- cntbArea: parseFloat(formData.rdiiArea) || null, // RDII 기여면적(ha)
- srcNm: formData.rtkSource, // 출처이름 (RTK계수 출처)
-
- shortPrdR: parseFloat(formData.unitFactors[0]?.R || "0"),
- shortPrdT: parseFloat(formData.unitFactors[0]?.T || "0"),
- shortPrdK: parseFloat(formData.unitFactors[0]?.K || "0"),
-
- mdPrdR: parseFloat(formData.unitFactors[1]?.R || "0"),
- mdPrdT: parseFloat(formData.unitFactors[1]?.T || "0"),
- mdPrdK: parseFloat(formData.unitFactors[1]?.K || "0"),
-
- longPrdR: parseFloat(formData.unitFactors[2]?.R || "0"),
- longPrdT: parseFloat(formData.unitFactors[2]?.T || "0"),
- longPrdK: parseFloat(formData.unitFactors[2]?.K || "0"),
-
- shortPrdMaxDpth: parseFloat(formData.initialDepths[0]?.Dmax || "0"),
- shortPrdRcvryRt: parseFloat(formData.initialDepths[0]?.Drec || "0"),
- shortPrdBgngDpth: parseFloat(formData.initialDepths[0]?.Do || "0"),
-
- mdPrdMaxDpth: parseFloat(formData.initialDepths[1]?.Dmax || "0"),
- mdPrdRcvryRt: parseFloat(formData.initialDepths[1]?.Drec || "0"),
- mdPrdBgngDpth: parseFloat(formData.initialDepths[1]?.Do || "0"),
-
- longTermMaxDpth: parseFloat(formData.initialDepths[2]?.Dmax || "0"),
- longTermRcvryRt: parseFloat(formData.initialDepths[2]?.Drec || "0"),
- longTermBgngDpth: parseFloat(formData.initialDepths[2]?.Do || "0"),
-
- drtwSwtcRt: parseFloat(formData.rate || "0"), // 오수전환율
- anlsInfo: formData.analysisInfo, // 분석정보
-
- tbSnRcptrMhlMpng: matchingResultData, // 수용가-맨홀 매칭결과
- tbSnRainData: rainData, // 강우자료
- };
-
- console.log("통합 분석 데이터 (JSON):", combinedAnalysisData);
-
- // 수정된 registFile 함수를 호출하여 combinedAnalysisData를 전송합니다.
- await registFile(combinedAnalysisData);
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("파일 파싱 중 오류 발생:", error);
- alert("파일 처리 중 오류가 발생했습니다.");
- return;
- }
- }
-
- const { fields: unitFactorFields } = useFieldArray({
- control: form.control,
- name: "unitFactors"
- })
-
- const { fields: initialDepthFields } = useFieldArray({
- control: form.control,
- name: "initialDepths"
- })
-
- const onSubmit = (data: z.infer) => {
- console.log("✅ 제출 데이터:", data)
- }
-
- // 단위도 계수 테이블 설정 (EditableTableHeadItem 타입 사용 및 id 수정)
- const unitFactorHeadlist: EditableTableHeadItem[] = [
- { id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
- { id: 'R', title: 'R', editable: true, inputProps: { type: 'text' } },
- { id: 'T', title: 'T', editable: true, inputProps: { type: 'text' } },
- { id: 'K', title: 'K', editable: true, inputProps: { type: 'text' } }
- ];
-
- // 초기 차단 깊이 테이블 설정 (EditableTableHeadItem 타입 사용)
- const initialDepthHeadlist: EditableTableHeadItem[] = [
- { id: 'response', title: 'Response', editable: false, width: '150px' }, // width 속성 추가
- { id: 'Dmax', title: 'Dmax', editable: true, inputProps: { type: 'text' } },
- { id: 'Drec', title: 'Drec', editable: true, inputProps: { type: 'text' } },
- { id: 'Do', title: 'Do', editable: true, inputProps: { type: 'text' } }
- ];
-
- // 테이블 페이지 변경 핸들러
- const handlePageChange = (page: number) => {
- console.log('Page changed:', page)
- }
-
- return (
- // { }} graphBtn={false} >
- { }} // BaseLayout의 form 태그에 연결될 onSubmit
- graphBtn={false}
- analysisBtn={'RDII분석 실행'}
- enoCd={select1}
- setEnoCd={setSelect1}
- ctpvCd={select2}
- setCtpvCd={setSelect2}
- sigungu={select3}
- setSigungu={setSelect3}
- selectedSwageTreatmentPlant={select4}
- onSwageTreatmentPlantChange={setSelect4}
- selectedSwageProcessingZone={select5}
- onSwageProcessingZoneChange={setSelect5}
- isLoading={isLoadingResult}
- onAnalysis={handleAnalysisClick}
- >
- {[
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- handleFileSelection(0, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={""}
- fileIdx={0} />
-
-
- handleFileSelection(1, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={1} />
-
-
- handleFileSelection(2, file, cd, id)}
- showButton={false}
- showPreview={true}
- accept={".xls, .xlsx, .xlsm, .xltx"}
- fileIdx={2} />
-
-
-
-
-
- {/* {
- if (date) {
- form.setValue("date", date, { shouldValidate: true });
- }
- }}
- mode={"single"}
- className="ml-5"
- /> */}
- {
- if (date) {
- form.setValue("date", date, { shouldValidate: true });
- }
- }
- }}
- // className을 직접 사용하거나, DatePicker 내부에서 selectClass를 처리하도록 수정 필요
- // 여기서는 DatePicker의 selectClass prop을 사용하고, date-picker.css의 스타일을 적용
- selectClass="ml-5 date-picker-trigger"
- />
-
-
-
-
-
- {/*
-
-
*/}
-
- ]}
-
- )
-}
diff --git a/apps/sn/app/ii/rdii_result/page.tsx b/apps/sn/app/ii/rdii_result/page.tsx
deleted file mode 100644
index 130c25419..000000000
--- a/apps/sn/app/ii/rdii_result/page.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-'use client'
-import { deleteData, getData } from '@/components/lib/api'
-import { UiTable, downloadExcel } from '@common/business_components/ui'
-import { zodResolver } from '@hookform/resolvers/zod'
-import { useState } from 'react'
-import { useForm } from 'react-hook-form'
-import { z } from 'zod'
-import BaseLayout from '../BaseLayout'
-import { handleDelete } from '@/components/lib/utils/fileDeleteUtil'
-
-
-const formSchema = z.object({
- enoCd: z.string().default('0'), // 환경청코드
- ctpvCd: z.string().default('0'), // 시도코드
- sggCd: z.object({ // 시군구
- val: z.string().default('0'),
- text: z.string().default('전체'),
- }).default({ val: '0', text: '전체' }),
- swageTmplntCd: z.string().default('0'), // 하수처리장
- swtrmtZoneCd: z.string().default('0'), // 하수처리구역
- aplcnYm: z.date().default(new Date()), // 분석일자 (DatePicker와 연동)
-})
-
-type ResultFormValues = z.infer
-
-const tableColumn = [
- { id: 'rainInfwtAnlsSn', title: '분석번호' },
- { id: 'swageTmplntNm', title: '하수처리장' },
- { id: 'swtrmtZoneNm', title: '처리구역' },
- { id: 'aplcnYm', title: '상수사용연월' },
- { id: 'drtwSwtcRt', title: '오수 전환율' },
- { id: 'srcNm', title: 'RTX 계수 출처' },
- { id: 'cntbArea', title: 'RDII 기여면적' },
- { id: 'anlsInfo', title: 'RDII 분석정보' },
- { id: 'regDt', title: '분석일자' },
- { id: 'rgtrNm', title: '분석자' }
-]
-
-const Result = () => {
- const form = useForm({
- resolver: zodResolver(formSchema),
- defaultValues: {
- enoCd: '0',
- ctpvCd: '0',
- sggCd: { val: '0', text: '전체' },
- swageTmplntCd: '0',
- swtrmtZoneCd: '0',
- aplcnYm: new Date(),
- }
- })
-
-
- const [tableData, setTableData] = useState([]); // API 조회 결과 저장 상태
- const [totalData, setTotalData] = useState(0) //총 데이터 수
- const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
- const [selectedRowData, setSelectedRowData] = useState(null);
- const [selectedRowIndex, setSelectedRowIndex] = useState(undefined);
-
-
- const handleSearchButtonClick = async (customFormValues?: Partial) => {
- setIsLoadingResult(true);
- const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
- console.log("formValues", formValues);
-
- let inftwtAnlsSearchDto;
-
- if (customFormValues) {
- inftwtAnlsSearchDto = {
- "aplcnYm": formValues.aplcnYm,
- "enoCd": formValues.enoCd,
- "ctpvCd": formValues.ctpvCd,
- "sggCd": formValues.sggCd,
- "swtrmtZoneCd": formValues.swtrmtZoneCd,
- };
- } else {
- inftwtAnlsSearchDto = {
- "aplcnYm": formValues.aplcnYm ? formValues.aplcnYm.toISOString().substring(0, 7).replace("-", "") : null,
- "enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
- "ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
- "sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
- "swtrmtZoneCd": formValues.swtrmtZoneCd === '0' ? null : formValues.swtrmtZoneCd,
- };
- }
- console.log("Search DTO:", inftwtAnlsSearchDto);
-
- const queryParams = new URLSearchParams({
- page: '0',
- size: '10',
- sort: 'rainInfwtAnlsSn,desc'
- });
- Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
- if (value !== undefined && value !== null && String(value).trim() !== '') { // undefined, null, 빈 문자열이 아닌 경우에만 추가
- queryParams.append(key, String(value));
- }
- });
- const queryString = queryParams.toString();
-
- console.log("API: ", `v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
- try {
- const data = await getData(`v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
- setTableData(data.content || []);
- setTotalData(tableData.length);
- console.log("response:", data);
- console.log("response data:", data.content || []);
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("Error fetching analysis result data:", error);
- alert("분석결과 조회 중 오류가 발생했습니다.");
- setTableData([]);
- setTotalData(0);
- }
- };
-
- // 테이블 셀 클릭 핸들러 추가
- const handleCellClick = (index: number | undefined, headId: string) => {
- if (index !== undefined && tableData[index]) {
- setSelectedRowData(tableData[index]);
- setSelectedRowIndex(index);
- console.log("Selected row data:", tableData[index]);
- }
- };
-
- // Excel 다운로드 핸들러 추가
- const handleExcelDownload = async () => {
- setIsLoadingResult(true);
- console.log("Selected row data for download:", selectedRowData);
- if (!selectedRowData || selectedRowData.rainInfwtAnlsSn === undefined) {
- setIsLoadingResult(false);
- alert('다운로드할 데이터를 선택해주세요.');
- return;
- }
-
- try {
- const data = await getData(`v1/rdiiAnlsRslt/ppl/${selectedRowData.rainInfwtAnlsSn}`);
-
- // 선택된 행 데이터를 Excel 다운로드 형식으로 변환
- const excelData = data.content; // 배열로 감싸서 전달
-
- // 파일명 생성 (분석번호 기반)
- const fileName = `RDII분석결과_${selectedRowData.rainInfwtAnlsSn}_${selectedRowData.aplcnYm}`;
-
- downloadExcel({
- data: excelData as JSON[],
- fileName: fileName,
- sheetNameArray: ["RDII 분석결과"],
- headerRange: "A1:D1" // 테이블 컬럼 수에 맞춰 조정
- });
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("Excel 다운로드 중 오류 발생:", error);
- alert("Excel 다운로드 중 오류가 발생했습니다. 다시 시도해주세요.");
- }
- };
-
- // 파일 삭제 핸들러 추가
- const handleFileDelete = async () => {
- setIsLoadingResult(true);
- console.log("Selected row data for deletion:", selectedRowData);
- if (!selectedRowData || selectedRowData.rainInfwtAnlsSn === undefined) {
- alert('삭제할 파일을 선택해주세요.');
- return;
- }
- // 삭제 확인 대화상자
- const confirmDelete = window.confirm('선택된 분석 결과를 삭제하시겠습니까?');
- if (!confirmDelete) {
- return;
- }
-
- try {
- // 삭제 API 호출
- const response1 = await deleteData(`v1/rdiiAnlsRslt/${selectedRowData.rainInfwtAnlsSn}`);
- const response2 = await deleteData(`v1/rdiiAnls/${selectedRowData.rainInfwtAnlsSn}`);
- // 첨부파일(inp파일) 삭제 API 호출
- handleDelete(selectedRowData.atflCd, {
- handleDeleteStart: () => console.log("파일 삭제 시작"),
- handleDeleteSuccess: (response) => console.log("파일 삭제 성공:", response),
- handleDeleteError: (error) => console.error("파일 삭제 실패:", error),
- });
- console.log("File delete response1:", response1);
- console.log("File delete response2:", response2);
-
- // 삭제 후 테이블 새로고침을 위해 재검색
- const customFormValues: Partial = {
- aplcnYm: selectedRowData.aplcnYm || '0',
- enoCd: selectedRowData.enoCd || '0',
- ctpvCd: selectedRowData.ctpvCd || '0',
- sggCd: selectedRowData.sggCd || '0',
- swtrmtZoneCd: selectedRowData.swtrmtZoneCd || '0',
- };
- await handleSearchButtonClick(customFormValues);
-
- // 선택된 행 초기화
- setSelectedRowData(null);
- setSelectedRowIndex(undefined);
-
- alert('삭제가 완료되었습니다.');
- } catch (error) {
- console.error("분석결과 파일 삭제 중 오류 발생:", error);
- alert("분석결과 파일 삭제 중 오류가 발생했습니다. 다시 시도해주세요.");
- }
- setIsLoadingResult(false);
- };
-
- return (
- { }} // BaseLayout의 form 태그에 연결될 onSubmit
- graphBtn={true}
- showDatePicker={true}
- enoCd={form.watch("enoCd")}
- setEnoCd={(val) => form.setValue("enoCd", val)}
- ctpvCd={form.watch("ctpvCd")}
- setCtpvCd={(val) => form.setValue("ctpvCd", val)}
- sigungu={form.watch("sggCd")}
- setSigungu={(val) => form.setValue("sggCd", val)}
- selectedSwageTreatmentPlant={form.watch("swageTmplntCd")}
- onSwageTreatmentPlantChange={(val) => form.setValue("swageTmplntCd", String(val))}
- selectedSwageProcessingZone={form.watch("swtrmtZoneCd")}
- onSwageProcessingZoneChange={(val) => form.setValue("swtrmtZoneCd", String(val))}
- aplcnYm={form.watch("aplcnYm")}
- setAplcnYm={(val) => {
- if (val instanceof Date) {
- form.setValue("aplcnYm", val)
- } else if (val) {
- form.setValue("aplcnYm", new Date(val))
- }
- }}
- isLoading={isLoadingResult}
- // Excel 다운로드 핸들러 추가
- onExcelDownload={handleExcelDownload}
- onDeleteFile={handleFileDelete}
- selectedRowData={selectedRowData}
- >
- {[
-
○ RDII 분석결과 현황
-
- { }}
- />
-
-
- ]}
-
- )
-}
-
-export default Result
\ No newline at end of file
diff --git a/apps/sn/app/ii/result/page.tsx b/apps/sn/app/ii/result/page.tsx
deleted file mode 100644
index e2015c8d9..000000000
--- a/apps/sn/app/ii/result/page.tsx
+++ /dev/null
@@ -1,259 +0,0 @@
-'use client'
-import { deleteData, getData } from '@/components/lib/api'
-import { UiTable, downloadExcel } from '@common/business_components/ui'
-import { zodResolver } from '@hookform/resolvers/zod'
-import { useState } from 'react'
-import { useForm } from 'react-hook-form'
-import { z } from 'zod'
-import BaseLayout from '../BaseLayout'
-import { handleDelete } from '@/components/lib/utils/fileDeleteUtil'
-
-
-const formSchema = z.object({
- enoCd: z.string().default('0'), // 환경청코드
- ctpvCd: z.string().default('0'), // 시도코드
- sggCd: z.object({ // 시군구
- val: z.string().default('0'),
- text: z.string().default('전체'),
- }).default({ val: '0', text: '전체' }),
- swageTmplntCd: z.string().default('0'), // 하수처리장
- swtrmtZoneCd: z.string().default('0'), // 하수처리구역
- aplcnYm: z.date().default(new Date()), // 분석일자 (DatePicker와 연동)
-})
-
-type ResultFormValues = z.infer
-
-const tableColumn = [
- // { id: 'no', title: '번호' },
- { id: 'inftwtAnlsSn', title: '분석번호' },
- { id: 'swageTmplntNm', title: '하수처리장' },
- { id: 'swtrmtZoneNm', title: '처리구역' },
- { id: 'aplcnYm', title: '적용연월' },
- { id: 'drtwSwtcRt', title: '오수 전환율' },
- { id: 'anlsInfo', title: '침입수 분석정보' },
- { id: 'regDt', title: '분석일자' },
- { id: 'rgtrNm', title: '분석자' }
-]
-
-const Result = () => {
- const form = useForm({
- resolver: zodResolver(formSchema),
- defaultValues: {
- enoCd: '0',
- ctpvCd: '0',
- sggCd: { val: '0', text: '전체' },
- swageTmplntCd: '0',
- swtrmtZoneCd: '0',
- aplcnYm: new Date(),
- }
- })
-
-
- const [tableData, setTableData] = useState([]); // API 조회 결과 저장 상태
- const [totalData, setTotalData] = useState(0) //총 데이터 수
- const [isLoadingResult, setIsLoadingResult] = useState(false); // 로딩 상태
- const [selectedRowData, setSelectedRowData] = useState(null);
- const [selectedRowIndex, setSelectedRowIndex] = useState(undefined);
-
-
- const handleSearchButtonClick = async (customFormValues?: Partial) => {
- setIsLoadingResult(true);
- const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
- console.log("formValues", formValues);
-
- let inftwtAnlsSearchDto;
-
- if (customFormValues) {
- inftwtAnlsSearchDto = {
- "aplcnYm": formValues.aplcnYm,
- "enoCd": formValues.enoCd,
- "ctpvCd": formValues.ctpvCd,
- "sggCd": formValues.sggCd,
- "swtrmtZoneCd": formValues.swtrmtZoneCd,
- };
- } else {
- inftwtAnlsSearchDto = {
- "aplcnYm": formValues.aplcnYm ? formValues.aplcnYm.toISOString().substring(0, 7).replace("-", "") : null,
- "enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
- "ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
- "sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
- "swtrmtZoneCd": formValues.swtrmtZoneCd === '0' ? null : formValues.swtrmtZoneCd,
- };
- }
- console.log("Search DTO:", inftwtAnlsSearchDto);
-
- const queryParams = new URLSearchParams({
- page: '0',
- size: '10',
- sort: 'inftwtAnlsSn,desc'
- });
- Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
- if (value !== undefined && value !== null && String(value).trim() !== '') { // undefined, null, 빈 문자열이 아닌 경우에만 추가
- queryParams.append(key, String(value));
- }
- });
- const queryString = queryParams.toString();
-
- console.log("API: ", `v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
- try {
- const data = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
- setTableData(data.content || []);
- setTotalData(tableData.length);
- console.log("response:", data);
- console.log("response data:", data.content || []);
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("Error fetching analysis result data:", error);
- alert("분석결과 조회 중 오류가 발생했습니다.");
- setTableData([]);
- setTotalData(0);
- }
- };
-
- // 테이블 셀 클릭 핸들러 추가
- const handleCellClick = (index: number | undefined, headId: string) => {
- if (index !== undefined && tableData[index]) {
- setSelectedRowData(tableData[index]);
- setSelectedRowIndex(index);
- console.log("Selected row data:", tableData[index]);
- }
- };
-
- // Excel 다운로드 핸들러 추가
- const handleExcelDownload = async () => {
- setIsLoadingResult(true);
- console.log("Selected row data for download:", selectedRowData);
- if (!selectedRowData || selectedRowData.inftwtAnlsSn === undefined) {
- setIsLoadingResult(false);
- alert('다운로드할 데이터를 선택해주세요.');
- return;
- }
-
- try {
- const data = await getData(`v1/inftwtAnlsRslt/ppl/${selectedRowData.inftwtAnlsSn}`);
-
- // 선택된 행 데이터를 Excel 다운로드 형식으로 변환
- const excelData = data.content; // 배열로 감싸서 전달
-
- // 파일명 생성 (분석번호 기반)
- const fileName = `침입수분석결과_${selectedRowData.inftwtAnlsSn}_${selectedRowData.aplcnYm}`;
-
- downloadExcel({
- data: excelData as JSON[],
- fileName: fileName,
- sheetNameArray: ["침입수 분석결과"],
- headerRange: "A1:D1" // 테이블 컬럼 수에 맞춰 조정
- });
- setIsLoadingResult(false);
- } catch (error) {
- setIsLoadingResult(false);
- console.error("Excel 다운로드 중 오류 발생:", error);
- alert("Excel 다운로드 중 오류가 발생했습니다. 다시 시도해주세요.");
- }
- };
-
- // 파일 삭제 핸들러 추가
- const handleFileDelete = async () => {
- setIsLoadingResult(true);
- console.log("Selected row data for deletion:", selectedRowData);
- if (!selectedRowData || selectedRowData.inftwtAnlsSn === undefined) {
- setIsLoadingResult(false);
- alert('삭제할 파일을 선택해주세요.');
- return;
- }
- // 삭제 확인 대화상자
- const confirmDelete = window.confirm('선택된 분석 결과를 삭제하시겠습니까?');
- if (!confirmDelete) {
- return;
- }
-
- try {
- // 삭제 API 호출
- const response1 = await deleteData(`v1/inftwtAnlsRslt/${selectedRowData.inftwtAnlsSn}`);
- const response2 = await deleteData(`v1/inftwtAnls/${selectedRowData.inftwtAnlsSn}`);
- // 첨부파일(inp파일) 삭제 API 호출
- handleDelete(selectedRowData.atflCd, {
- handleDeleteStart: () => console.log("파일 삭제 시작"),
- handleDeleteSuccess: (response) => console.log("파일 삭제 성공:", response),
- handleDeleteError: (error) => console.error("파일 삭제 실패:", error),
- });
- console.log("File delete response1:", response1);
- console.log("File delete response2:", response2);
-
- // 삭제 후 테이블 새로고침을 위해 재검색
- const customFormValues: Partial = {
- aplcnYm: selectedRowData.aplcnYm || '0',
- enoCd: selectedRowData.enoCd || '0',
- ctpvCd: selectedRowData.ctpvCd || '0',
- sggCd: selectedRowData.sggCd || '0',
- swtrmtZoneCd: selectedRowData.swtrmtZoneCd || '0',
- };
- await handleSearchButtonClick(customFormValues);
-
- // 선택된 행 초기화
- setSelectedRowData(null);
- setSelectedRowIndex(undefined);
- setIsLoadingResult(false);
-
- alert('삭제가 완료되었습니다.');
- } catch (error) {
- setIsLoadingResult(false);
- console.error("분석결과 파일 삭제 중 오류 발생:", error);
- alert("분석결과 파일 삭제 중 오류가 발생했습니다. 다시 시도해주세요.");
- }
- };
-
- return (
- { }} // BaseLayout의 form 태그에 연결될 onSubmit
- graphBtn={true}
- showDatePicker={true}
- enoCd={form.watch("enoCd")}
- setEnoCd={(val) => form.setValue("enoCd", val)}
- ctpvCd={form.watch("ctpvCd")}
- setCtpvCd={(val) => form.setValue("ctpvCd", val)}
- sigungu={form.watch("sggCd")}
- setSigungu={(val) => form.setValue("sggCd", val)}
- selectedSwageTreatmentPlant={form.watch("swageTmplntCd")}
- onSwageTreatmentPlantChange={(val) => form.setValue("swageTmplntCd", String(val))}
- selectedSwageProcessingZone={form.watch("swtrmtZoneCd")}
- onSwageProcessingZoneChange={(val) => form.setValue("swtrmtZoneCd", String(val))}
- aplcnYm={form.watch("aplcnYm")}
- setAplcnYm={(val) => {
- if (val instanceof Date) {
- form.setValue("aplcnYm", val)
- } else if (val) {
- form.setValue("aplcnYm", new Date(val))
- }
- }}
- isLoading={isLoadingResult} // 로딩 상태 전달
- // Excel 다운로드 핸들러 추가
- onExcelDownload={handleExcelDownload}
- onDeleteFile={handleFileDelete}
- selectedRowData={selectedRowData}
- >
- {[
-
○ 침입수 산정결과 현황
-
- { }}
- />
-
-
- ]}
-
- )
-}
-
-export default Result
\ No newline at end of file
diff --git a/apps/sn/app/layout.tsx b/apps/sn/app/layout.tsx
index f983b20bc..066d9646b 100644
--- a/apps/sn/app/layout.tsx
+++ b/apps/sn/app/layout.tsx
@@ -1,10 +1,5 @@
-import "./styles/base.css";
-import "./styles/components.css";
import type { Metadata } from "next";
-import { cookies } from "next/headers";
-import { StoreProvider } from "./store/store-provider";
-import { AuthWrapper } from "./components/lib/auth";
-import { ClientLayout } from "./clientLayout";
+import { App } from "@/app";
export const metadata: Metadata = {
title: "디지털 하수관로",
@@ -16,22 +11,4 @@ export const metadata: Metadata = {
}
};
-export default async function RootLayout({
- children,
-}: Readonly<{
- children: React.ReactNode;
-}>) {
- const theme = (await cookies()).get("site-theme-key");
-
- return (
-
-
-
-
- {children}
-
-
-
-
- );
-}
+export default App;
\ No newline at end of file
diff --git a/apps/sn/app/map/components/InputSection.tsx b/apps/sn/app/map/components/InputSection.tsx
deleted file mode 100644
index 6c411e2cf..000000000
--- a/apps/sn/app/map/components/InputSection.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@common/components/ui";
-import React from "react";
-
-interface InputSectionProps {
- title: string;
- data: { year: string; type: string }[];
- sectionKey: string;
- onInputChange: (section: string, index: number, field: string, value: string) => void;
-}
-
-const InputSection: React.FC = ({ title, data, sectionKey, onInputChange }) => {
- return (
-
- {/* 섹션 제목 */}
-
-
{title}
-
- {/* 테이블 */}
-
-
- );
-};
-
-export default InputSection;
\ No newline at end of file
diff --git a/apps/sn/app/map/components/common/index.ts b/apps/sn/app/map/components/common/index.ts
deleted file mode 100644
index b72ec26d5..000000000
--- a/apps/sn/app/map/components/common/index.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import MsSwagePpl from "../popupComponent/MsSwagePpl";
-import sewagePump from "../popupComponent/sewagePump";
-import smh from "../popupComponent/smh";
-import Ssc from "../popupComponent/Ssc";
-import StormWaterPump from "../popupComponent/stormWaterPump";
-import SwtrmtFclt from "../popupComponent/SwtrmtFclt";
-
-type LayerComponentProps = {
- featureData: any;
- chkMainSsc?: boolean;
- additionalData?: any;
-};
-type LayerContentMap = {
- [key: string]: {
- component?: React.FC;
- props?: any;
- };
-};
-// 레이어 이름과 컴포넌트를 매핑
-// 레이어 선택시 변경되는 팝업 컨텐츠 동적으로 변경하도록 작업
-const layerContentMap: LayerContentMap = {
- // TODO: gis데이터 추가되면 추가 작업 필요
- "하수처리시설": { component: SwtrmtFclt, },
- "하수처리구역": { },
- "우수토실":{component: Ssc,},
- "중점우수토실":{component: Ssc, }, // 중점우수토실 여부 설정
- "하수관로":{component: MsSwagePpl,},
- "하수맨홀":{component: smh,},
- "빗물펌프":{component:StormWaterPump},
- "오수펌프":{component:sewagePump},
-};
-
-// 동적 컴포넌트 반환 함수
-export const getLayerContentComponent = (layerNm: string): React.FC | null => {
- const component = layerContentMap[layerNm];
- if (!component || !component.component) {
- // component가 없으면 null 반환
- return () => null;
- }
- return component.component
-};
-// 사용자 입력 필드 (보수 및 갱신, 청소 및 준설, 점검 및 진단)
-export const handleInputChange = (section: string,
- index: number,
- field: string,
- value: string,
- dataMap: {
- [key: string]: {
- data: { year: string; type: string }[];
- setData: React.Dispatch>;
- };
- }
-) => {
- const target = dataMap[section];
- if (!target) return;
-
- const updated = [...target.data];
- if (updated[index]) {
- updated[index][field as keyof typeof updated[number]] = value;
- }
- target.setData(updated);
-};
\ No newline at end of file
diff --git a/apps/sn/app/map/components/common/table.ts b/apps/sn/app/map/components/common/table.ts
deleted file mode 100644
index 6c641f9be..000000000
--- a/apps/sn/app/map/components/common/table.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-// 하수처리시설
-export const SwtrmtFcltCol = [
- { id: 'swtrmtFcltNm', title: '하수처리시설명' },
- { id: 'fcltCpct', title: '시설용량' },
- { id: 'rgnExpln', title: '지역설명' },
- { id: 'cmcnYmd', title: '준공일자' },
- { id: 'oprtngStrtYmd', title: '가동개시일자' },
- { id: 'clsgYmd', title: '폐쇄일자' },
- { id: 'prcsMsrcCd', title: '처리공법코드' },
- // { id: 'laeCd', title: '지자체코드' },
- { id: 'laeNm', title: '지자체명' },
- { id: 'ctpvNm', title: '시도명' },
- { id: 'sggNm', title: '시군구명' },
- // { id: 'sareaCd', title: '권역코드' },
- { id: 'sareaNm', title: '권역명' },
- { id: 'lrgeSareaNm', title: '대권역명' },
- { id: 'rvrNm', title: '하천명' },
- { id: 'addr', title: '주소' },
- { id: 'daddr', title: '상세주소' },
- { id: 'rdnmAddr', title: '도로명주소' },
- { id: 'dtlRdnmAddr', title: '상세도로명주소' },
- { id: 'dschgWtstNm', title: '방류수계명' },
- { id: 'pllnArea', title: '부지면적' },
- { id: 'mngRprtvBzentyNm', title: '관리대행업제명' },
- { id: 'swtrmtPpltnCnt', title: '하수처리인구수' },
- { id: 'prcsZoneAreaSum', title: '처리구역면적합계' },
- { id: 'xcrd', title: 'X좌표' },
- { id: 'ycrd', title: 'Y좌표' },
- // { id: 'oprtngSttsCd', title: '가동상태코드' },
- { id: 'rprsMsrcCn', title: '대표공법내용' },
- { id: 'sttyCrtrBod', title: '법정기준생물화학적산소요구량' },
- { id: 'sttyCrtrToc', title: '법정기준TOC' },
- { id: 'sttyCrtrSs', title: '법정기준SS' },
- { id: 'sttyCrtrTn', title: '법정기준총질소' },
- { id: 'sttyCrtrTph', title: '법정기준총인' },
- { id: 'sttyCrtrClbclCnt', title: '법정기준대장균수' },
- { id: 'bsnNm', title: '유역명' },
- // { id: 'obsrvnSptCd', title: '관측지점코드' },
-];
-
-// 하수처리구역
-export const SwtrmtPrcsZoneCol = [
- { id: 'swtrmtZoneSn', title: '하수처리구역 일련번호' },
- { id: 'swtrmtZoneNm', title: '하수처리구역명' },
- // { id: 'swtrmtFcltCd', title: '하수처리시설코드' },
- // { id: 'ctpvCd', title: '시도코드' },
- { id: 'ctpvNm', title: '시도명' },
- // { id: 'sggCd', title: '시군구코드' },
- { id: 'sggNm', title: '시군구명' },
- { id: 'swtrmtFcltNm', title: '하수처리시설명' },
-];
-
-// 하수맨홀
-export const MsSwageMhlCol = [
- { id: 'fid', title: 'FID' },
- { id: 'geom', title: 'geometry' },
- { id: 'ftreSmblCd', title: '지형지물부호코드' },
- { id: 'mngNo', title: '관리번호' },
- // { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
- { id: 'mapshtNo', title: '도엽번호' },
- // { id: 'mngInstCd', title: '관리기관코드' },
- { id: 'instlYmd', title: '설치일자' },
- { id: 'lastDrdgnYmd', title: '최종준설일자' },
- { id: 'usgCd', title: '용도코드' },
- // { id: 'fcltyShpCd', title: '시설물형태코드' },
- { id: 'mhlKndCd', title: '맨홀종류코드' },
- { id: 'swageMhDiam', title: '하수맨홀구경' },
- { id: 'wdthLen', title: '가로길이' },
- { id: 'vrtcLen', title: '세로길이' },
- // { id: 'mqltCd', title: '재질코드' },
- { id: 'altdVl', title: '표고값' },
- { id: 'dpthlVl', title: '심도값' },
- { id: 'instMngNo', title:'기관관리번호'}
-];
-
-// 중점우수토실 측정지점
-export const untrtSwgRainCol1 = [
- { id: 'manage_no', title: '관리번호' },
- { id: 'swr_ppl_eqp_nm', title: '처리구역' },
- { id: 'swr_ppl_trt_nm', title: '처리분구' },
- { id: 'addr', title: '인근주소' },
- { id: 'chmbr_xcnts', title: '토실 위도' },
- { id: 'chmbr_ydnts', title: '토실 경도' }
-];
-
-// 중점우수토실 측정지점 시설현황
-export const untrtSwgRainCol2 = [
- { id: 'flwmtr_mesure_tp_etc', title: '구분' },
- { id: 'discharge_pipe_spec', title: '방류관로 규격' },
- { id: 'swr_ppl_eqp_ar', title: '배수구역 면적(m²)' },
- { id: 'swr_trt_popl', title: '하수처리 인구(인)' },
- { id: 'screen_instl_at', title: '스크린설치 여부' },
- { id: 'weir_hg', title: '위어 높이(m)' },
- { id: 'weir_lt', title: '위어 길이(m)' }
-];
-
-// 중점우수토실 강우정보 (id값 틀릴 수 있음)
-export const untrtSwgRainCol3 = [
- { id: 'rain_begin_dt', title: '강우시작일시' },
- { id: 'rain_end_dt', title: '강우종료일시' },
- { id: 'precdng_dry', title: '선행건기(h)' },
- { id: 'rain_info', title: '강우정보' },
- { id: 'rain_fall', title: '누적강우량(mm)' },
- { id: 'cntnc_time', title: '지속시간(h)' },
- { id: 'rain_in', title: '강우강도(mm/h)' }
-];
-
-// 중점우수토실 측정정보 (id값 틀릴 수 있음)
-export const untrtSwgRainCol4 = [
- { id: 'mesure_begin_dt', title: '측정시작일시' },
- { id: 'mesure_end_dt', title: '측정종료일시' },
- { id: 'mesure_intrvl', title: '측정간격(분)' },
- { id: 'mesure_mhrls_instl_lc', title: '측정기기 설치위치' },
- { id: 'flwmtr_combined', title: '유량계 종류 및 모델명' }, // 합쳐진 컬럼
- { id: 'qltwtr_begin_dt', title: '채수시작일시' },
- { id: 'qltwtr_end_dt', title: '채수종료일시' },
- { id: 'qltwtr_co', title: '채수횟수' }
-];
-
-// 중점우수토실 수량/수질측정 정보
-export const untrtSwgRainCol5 = [
- { id: 'odr', title: '회차' },
- { id: 'mesureDt', title: '측정일자' },
- { id: 'mesureQy', title: '수량(m)' },
- { id: 'mesureBod', title: 'BOD(mg/L)' },
- { id: 'mesureToc', title: 'TOC(mg/L)' },
- { id: 'mesureLoad', title: '오염부하량(kg)' }
-];
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/MsSwagePpl.tsx b/apps/sn/app/map/components/popupComponent/MsSwagePpl.tsx
deleted file mode 100644
index 1db284c8e..000000000
--- a/apps/sn/app/map/components/popupComponent/MsSwagePpl.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { VerticalTable } from '@/components/ui/verticalTable';
-import React, { useState } from 'react'
-import InputSection from '../InputSection';
-import { handleInputChange } from '../common';
-import { Button } from '@common/components/ui';
-import InfilChart from './chart/infilChart';
-// 하수관로
-// TODO: RDII 버튼인가 그거 팝업 두개 구현 필요
-const inputColumn = [
- { id: "title", title: "설치주제", type: "select", options: ["BTL", "재정사업"] },
- { id: "swtrmt_zone_cd", title: "처리구역", type: "select", options: ["구역1", "구역2"] },
- { id: "basu", title: "배수구역", type: "input" },
- { id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
- { id: "wltjs", title: "지선/간선", type: "select", options: ["지선", "간선"] },
- { id: "flow", title: "흐름방식", type: "select", options: ["자연유하", "압송"] },
- { id: "place", title: "매설위치", type: "select", options: ["도로", "하상"] },
-];
-const SwtrmtFclt = ({ featureData }: { featureData: any }) => {
- console.log("featureData", featureData);
- const [isModalOpen, setIsModalOpen] = React.useState(false);
- const [btnTxt, setBtnTxt] = useState("");
- const openModal = (e: React.MouseEvent) => {
- e.currentTarget.textContent && setBtnTxt(e.currentTarget.textContent)
- setIsModalOpen(true);
- };
- const closeModal = () => {
- setIsModalOpen(false);
- };
- const [repairData, setRepairData] = useState([
- { year: "2025", type: "개대체" },
- { year: "2025", type: "보수" },
- ]);
- const [cleaningData, setCleaningData] = useState([
- { year: "2025", type: "청소" },
- { year: "2025", type: "준설" },
- ]);
- const [inspectionData, setInspectionData] = useState([
- { year: "2025", type: "관로기술진단" },
- { year: "2025", type: "관로기술진단" },
- ]);
- const dataMap = {
- repair: { data: repairData, setData: setRepairData },
- cleaning: { data: cleaningData, setData: setCleaningData },
- inspection: { data: inspectionData, setData: setInspectionData },
- };
- const keysToExtract = [
- "swtrmt_zone_cd",
- "mltv_dtdv_nm",
- "fid",
- "lyrTypeNm",
- "reg_dt",
- "mdfcn_dt",
- "rgtr",
- "mdfr",
- ];
- // const filteredData = Object.entries(featureData)
- // .filter(([key]) => keysToExtract.includes(key)) // 필요한 키만 필터링
- // .map(([key, value]) => ({ key, value: value ?? "N/A" })); // 테이블 데이터 형식으로 변환
-
- return (
-
-
-
handleInputChange(section, index, field, value, dataMap)} />
- handleInputChange(section, index, field, value, dataMap)} />
- handleInputChange(section, index, field, value, dataMap)} />
-
-
-
-
-
-
- )
-}
-
-export default SwtrmtFclt
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/Ssc.tsx b/apps/sn/app/map/components/popupComponent/Ssc.tsx
deleted file mode 100644
index 2ca7c174d..000000000
--- a/apps/sn/app/map/components/popupComponent/Ssc.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-// 우수토실
-import { UiModal, UiTable } from '@common/business_components/ui';
-import { Button, TableHead, TableRow } from '@common/components/ui';
-import React from 'react';
-import { untrtSwgRainCol3, untrtSwgRainCol4, untrtSwgRainCol5 } from '../common/table';
-
-const Ssc = ({ featureData, chkMainSsc, additionalData }: {
- featureData: any,
- chkMainSsc?: boolean,
- additionalData?: any
-}) => {
- console.log('Additional data received:', additionalData); // 추가 데이터 확인용
-
- const [isModalOpen, setIsModalOpen] = React.useState(false);
- const openModal = () => {
- setIsModalOpen(true);
- };
- const closeModal = () => {
- setIsModalOpen(false);
- };
-
- // 데이터 전처리: 합쳐진 필드 추가
- const preprocessedData = featureData ? [{
- ...featureData,
- flwmtr_combined: `${featureData.flwmtr_mesure_tp_etc || '-'} / ${featureData.flwmtr_knd || '-'}`
- }] : [];
-
- const renderModalBody = () => (
-
- {/* 강우정보 테이블 */}
-
-
- {/* 측정정보 테이블 */}
-
- {/* 커스텀 헤더 */}
-
- 수량
- 수질
-
-
- 측정시작일시
- 측정종료일시
- 측정간격(분)
- 측정기기설치위치
- 유량계 종류 및 모델명
- 채수시작일시
- 채수종료일시
- 채수횟수
-
-
-
- {/* 수량/수질측정 정보 테이블 */}
-
-
- );
-
- return (
-
- {/*
*/}
-
- {!chkMainSsc ? null :
-
-
-
중점우수토실 운영정보
-
-
-
-
-
- }
-
- )
-}
-
-export default Ssc
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/SwtrmtFclt.tsx b/apps/sn/app/map/components/popupComponent/SwtrmtFclt.tsx
deleted file mode 100644
index eef14ea5e..000000000
--- a/apps/sn/app/map/components/popupComponent/SwtrmtFclt.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import Modal from '@/components/ui/modal';
-import { VerticalTable } from '@/components/ui/verticalTable';
-import { UiTable } from '@common/business_components/ui';
-import { Button, TableCell } from '@common/components/ui';
-import React, { useState } from 'react'
-
-// 하수처리시설
-const headList = [
- { id: "title", title: "하수도정비 기본계획보고서" },
- { id: "cad", title: "하수도대장 평면도" },]
-const modalHeadList = [
- { id: "no", title: "번호" },
- { id: "year", title: "승인연도" },
- { id: "cad", title: '평면도'},
- { id: "fileNm", title: "파일명" },
- { id: "date", title: "입력시간" },
-]
-
-const SwtrmtFclt = () => {
- const [isModalOpen, setIsModalOpen] = useState(false);
- const [modalTitle, setModalTitle] = useState('');
- const openModal = (title:string) => {
- setIsModalOpen(true);
- setModalTitle(title)
- };
- const closeModal = () => {
- setIsModalOpen(false);
- };
- return (
-
-
openModal('하수도정비 기본계획보고서')}>보고서,
- cad: ,
- }} headName='디지털 자료관 연계정보' tableData={[]} headlist={headList} pageSize={20} total={0} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
- throw new Error("Function not implemented.");
- }}>
-
-
-
-
-
-
- )
-}
-
-export default SwtrmtFclt
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/chart/infilChart.tsx b/apps/sn/app/map/components/popupComponent/chart/infilChart.tsx
deleted file mode 100644
index ba0b70455..000000000
--- a/apps/sn/app/map/components/popupComponent/chart/infilChart.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import React, { useState } from 'react'
-import { type ChartConfig, MainChart, CHART_FORM } from "@common/business_components";
-import Modal from '@/components/ui/modal';
-import { Button } from '@common/components/ui';
-type ModalOpenProp = {
- isModalOpen: boolean,
- setIsModalOpen: (open: boolean) => void,
- closeModal: () => void,
- btnTxt?: string,
-}
-const InfilChart = ({ btnTxt, isModalOpen, setIsModalOpen, closeModal }: ModalOpenProp) => {
- const [popupOpen, setPopupOpen] = React.useState(false);
- const buttonRef = React.useRef(null); // 버튼 참조
- const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
- const openPopup = () => {
- if (buttonRef.current) {
- const rect = buttonRef.current.getBoundingClientRect(); // 버튼 위치 계산
- setPopupPosition({
- top: rect.bottom + window.scrollY, // 버튼 아래쪽
- left: rect.left + window.scrollX, // 버튼 왼쪽
- });
- }
- setPopupOpen(true); // 팝업 열기
- };
- console.log("btnTxt", btnTxt);
- const closePopup = () => {setPopupOpen(false);}; // 팝업 닫기
- const chartForm = CHART_FORM.LINE;
- const chartData = {
- chartData1: [
- { label: "1", val: 20 },
- { label: "3", val: 40 },
- { label: "5", val: 60 },
- ],
- chartData2: [
- { label: "1", val: 15 },
- { label: "3", val: 35 },
- { label: "5", val: 55 },
- ],
- }
- const chartConfig = Object.values(chartData).flat().reduce((config, element) => {
- config[element.label] = {
- label: element.label,
- color: "hsl(var(--chart-1))",
- };
- return config;
- }, {} as Record) satisfies ChartConfig;
- const getCurrentDate = () => {
- const today = new Date();
- const year = today.getFullYear();
- const month = String(today.getMonth() + 1).padStart(2, "0"); // 월은 0부터 시작하므로 +1
- return `${year}-${month}`;
- };
- return (
-
- {/* 분석 입력현황 조회 */}
-
-
-
-
- {/* 침입수량 분석결과 */}
-
- 침입수량 분석결과
-
- 120
- m³/d
-
-
-
- {/* 차트 */}
-
-
-
-
- {popupOpen && (
-
-
분석 입력현황
-
-
상수사용량 정보:
-
-
-
-
오수 전환율:
-
-
-
-
수용가-맨홀 매칭:
-
-
-
-
관망도 자료:
-
-
-
- {btnTxt === 'RDII' ? <>
강우 자료:
-
-
-
-
RTX 계수 출처:
-
-
-
- > : null}
-
-
-
-
-
-
- )}
-
- )
-}
-
-export default InfilChart
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/sewagePump.tsx b/apps/sn/app/map/components/popupComponent/sewagePump.tsx
deleted file mode 100644
index 5776df5b2..000000000
--- a/apps/sn/app/map/components/popupComponent/sewagePump.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { VerticalTable } from '@/components/ui/verticalTable';
-import React from 'react'
-const inputColumn = [
- { id: "swtrmt_zone_cd", title: "처리구역", type: "select", options: ["구역1", "구역2"] },
- { id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
- { id: "freq", title: "설계빈도", type: "input" },
-]
-// 오수펌프
-const sewagePump = ({ featureData }: { featureData: any }) => {
- return (
-
-
- )
-}
-
-export default sewagePump
diff --git a/apps/sn/app/map/components/popupComponent/smh.tsx b/apps/sn/app/map/components/popupComponent/smh.tsx
deleted file mode 100644
index e693a28ce..000000000
--- a/apps/sn/app/map/components/popupComponent/smh.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-// 하수맨홀
-import { VerticalTable } from '@/components/ui/verticalTable';
-import React from 'react'
-const inputColumn = [
- { id: "guyeok", title: "처리구역", type: "select", options: ["구역1", "구역2"] },
- { id: "basu", title: "배수구역", type: "input" },
- { id: "bungu", title: "배수분구", type: "input" },
- { id: "place", title: "매설위치", type: "select", options: ["도로", "하상"] },
- {id:'spec', title:'규격', type:'input'},
-];
-const Smh = () => {
- return (
-
-
-
- )
-}
-
-export default Smh;
\ No newline at end of file
diff --git a/apps/sn/app/map/components/popupComponent/stormWaterPump.tsx b/apps/sn/app/map/components/popupComponent/stormWaterPump.tsx
deleted file mode 100644
index eefef8b3b..000000000
--- a/apps/sn/app/map/components/popupComponent/stormWaterPump.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { VerticalTable } from '@/components/ui/verticalTable';
-import React from 'react'
-const inputColumn = [
- { id: "swtrmt_zone_cd", title: "처리구역", type: "input" },
- { id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
-]
-// 빗물펌프
-const StormWaterPump = ({ featureData }: { featureData: Record }) => {
- const validKey = inputColumn.map((item) => item.id);
- const filteredData = featureData && Object.entries(featureData).filter(([key]) => validKey.includes(key)).reduce((obj: Record, [key, value]) => {obj[key] = value; return obj;}, {});
- return (
-
-
- )
-}
-
-export default StormWaterPump
\ No newline at end of file
diff --git a/apps/sn/app/oper/floodPre/page.tsx b/apps/sn/app/oper/floodPre/page.tsx
deleted file mode 100644
index 013b1a36c..000000000
--- a/apps/sn/app/oper/floodPre/page.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-'use client'
-import { SearchDiv, SearchFormLeft, SearchFormRight, SelectBox, UiTable } from '@common/business_components/ui'
-import { Button, DatePicker, Input, Label, LoadingWithAnimation } from '@common/components/ui'
-import React, { useEffect, useState } from 'react'
-import OperFileUploadForm from '../../components/ui/operFileUploadForm'
-import ListDiv from '@common/business_components/ui/list_div'
-import ContentLayout from '@/components/ui/contentLayout'
-import { searchCmmnCd, searchData } from '@/components/lib/common/apiHelpers'
-import { tableHeadlist } from '..'
-import { handleDownload } from '@/components/lib/utils/fileDownload'
-import { formatDate, yearOptions } from '@/components/lib/utils/date'
-import { deleteData, postData } from '@/components/lib/api'
-import LoadingOverlay from '@/components/ui/LoadingBar'
-
-const Page = () => {
- // 조회조건
- const [fromDate, setFromDate] = useState(() => { const date = new Date(); date.setDate(date.getDate() - 7); return date })
- const [toDate, setToDate] = useState(new Date())
- const [manageYear, setManageYear] = useState(yearOptions[0]?.val || '');
- const [mngQu, setMngQu] = useState(yearOptions[0]?.val || '');
- const [usr, setUsr] = useState('')
- const [pjNm, setpjNm] = useState('')
- // 파일업로드 관련 상태
- const [fileNm, setFileNm] = useState('') //파일명
- const [atflId, setAtflId] = useState('') //파일 ID
- const [sbmrgPrevntBizSn, setSbmrgPrevntBizSn] = useState('') //파일 일련번호
- const [tableData, setTableData] = useState([{}]) //테이블 데이터
- const [curPage, setCurPage] = useState(1) //현재 페이지
- const [totalData, setTotalData] = useState(0) //총 데이터 수
- const [isLoading, setIsLoading] = useState(true) //로딩 상태
- const fetchData = async () => {
- setIsLoading(true)
- searchCmmnCd('SITEKNDCD')
- try {
- const { data, total } = await searchData('v1/sbmrgPrevnt', {
- fromRegDt: formatDate(fromDate),
- fromMngYr: manageYear,
- toMngYr: mngQu,
- toRegDt: formatDate(toDate),
- atflNm: pjNm,
- rgtrNm: usr,
- page: curPage - 1,
- size: '10'
- })
- setTableData(data)
- setTotalData(total)
- }
- catch (error) { console.error('Error fetching data:', error) }
- finally { setIsLoading(false); }
- }
- useEffect(() => {
- setCurPage(1)
- fetchData()
- }, [])
- // 파일 다운로드
- const isChckFile = () => {
- if (fileNm === '' || fileNm === undefined) {
- alert('파일을 선택해주세요')
- return false
- }
- handleDownload(`/attach-service/api/v1/download/${atflId}`, fileNm)
- }
- // 선택 파일 삭제
- const isDeleteFile = async () => {
- if (sbmrgPrevntBizSn === '' || sbmrgPrevntBizSn === undefined) {
- alert('삭제할 파일을 선택해주세요')
- return false
- }
- const data = await deleteData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
- if (data) {
- const delData = await deleteData(`v1/sbmrgPrevnt/${sbmrgPrevntBizSn}`)
- if (delData.status === 200) {
- alert('삭제되었습니다.')
- fetchData()
- }
- }
- }
- // 현황 등록
- const registFile = async (fileName: string, year: string, quater: string, cd: string, id: string) => {
- const data = await postData('v1/sbmrgPrevnt', {
- atflNm: fileName,
- mngYr: year,
- mngQu: quater,
- atflCd: cd,
- atflId: id,
- sbmrgPrevntBizNm: fileName
- })
- if (data) { alert('파일이 등록되었습니다.'); fetchData() }
- }
- return (
-
-
-
-
-
-
- { if (date) setFromDate(date) }} />
- ~
- { if (date) setToDate(date) }} />
-
-
-
- setManageYear(String(value))}
- />
- ~
- setMngQu(String(value))}
- />
-
-
-
- setUsr(e.target.value)}
- />
-
-
-
- setpjNm(e.target.value)}
- />
-
-
-
-
-
-
-
-
-
-
사업정보 등록현황
-
-
-
-
-
- { if (index != null) { const fileName = tableData[index]?.sbmrgPrevntBizNm ?? ""; setFileNm(fileName); const id = tableData[index]?.atflId ?? ''; setAtflId(id); setSbmrgPrevntBizSn(tableData[index]?.sbmrgPrevntBizSn); } }} onPageChange={async (page: number) => { setCurPage(page); await fetchData() }}>
-
-
- { await registFile(file, year, quater, cd, id) }} />
-
-
- )
-}
-
-export default Page
\ No newline at end of file
diff --git a/apps/sn/app/oper/index.ts b/apps/sn/app/oper/index.ts
deleted file mode 100644
index 54ba00374..000000000
--- a/apps/sn/app/oper/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export const tableHeadlist = [
- { id: 'sbmrgPrevntBizSn', title: '일련번호' },
- { id: 'sbmrgPrevntBizNm', title: '파일명' },
- { id: 'mngYr', title: '년도' },
- { id: 'mngQu', title: '분기' },
- { id: 'regDt', title: '등록 일자' },
- { id: 'rgtr', title: '등록자' }
-
-]
-export const tableHeadlistOldPp = [
- { id: 'dcrpPplMtncBizSn', title: '일련번호' },
- { id: 'dcrpPplMtncBizNm', title: '파일명' },
- { id: 'mngYr', title: '년도' },
- { id: 'mngQu', title: '분기' },
- { id: 'regDt', title: '등록 일자' },
- { id: 'rgtr', title: '등록자' }
-]
\ No newline at end of file
diff --git a/apps/sn/app/oper/oldPp/page.tsx b/apps/sn/app/oper/oldPp/page.tsx
deleted file mode 100644
index 92d7fe6aa..000000000
--- a/apps/sn/app/oper/oldPp/page.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-'use client'
-import { SearchDiv, SearchFormLeft, SearchFormRight, SelectBox, UiTable } from '@common/business_components/ui'
-import { Button, DatePicker, Input, Label } from '@common/components/ui'
-import React, { useEffect, useState } from 'react'
-import OperFileUploadForm from '../../components/ui/operFileUploadForm'
-import ListDiv from '@common/business_components/ui/list_div'
-import ContentLayout from '@/components/ui/contentLayout'
-import { tableHeadlistOldPp } from '..'
-import { handleDownload } from '@/components/lib/utils/fileDownload'
-import { searchData } from '@/components/lib/common/apiHelpers'
-import { formatDate, yearOptions } from '@/components/lib/utils/date'
-import { deleteData, postData } from '@/components/lib/api'
-const Page = () => {
- const [fromDate, setFromDate] = useState(()=>{const date = new Date(); date.setDate(date.getDate()-7); return date});
- const [toDate, setToDate] = useState(new Date());
- const [manageYear, setManageYear] = useState(yearOptions[0]?.val || '');
- const [mngQu, setMngQu] = useState(yearOptions[0]?.val || '');
- const [usr, setUsr] = useState('')
- const [pjNm, setpjNm] = useState('')
- const [fileNm, setFileNm] = useState('')
- const [atflId, setAtflId] = useState('')
- const [dcrpPplMtncBizSn, setDcrpPplMtncBizSn] = useState('')
- const [tableData, setTableData] = useState([{}])
- const [curPage, setCurPage] = useState(1)
- const [totalData, setTotalData] = useState(0) //총 데이터 수
- const [isLoading, setIsLoading] = useState(true) //로딩 상태
- // 데이터 조회
- const fetchData = async () => {
- setIsLoading(true)
- try {
- const {data, total} = await searchData('v1/dcrpPpl', {
- fromRegDt: formatDate(fromDate),
- fromMngYr: manageYear,
- toMngYr: mngQu,
- toRegDt: formatDate(toDate),
- dcrpPplMtncBizNm: pjNm,
- rgtrNm: usr,
- page: curPage - 1,
- size: '10'
- })
- setTableData(data)
- setTotalData(total)
- console.log(data, total)
- }catch (error) {
- console.error('Error fetching data:', error)}finally{setIsLoading(false)}
- }
- useEffect(() => {
- setCurPage(1)
- fetchData()
- }, [])
- // 파일 다운로드
- const isChckFile = () => {
- if (fileNm === '' || fileNm === undefined) {
- alert('파일을 선택해주세요')
- return false
- }
- handleDownload(`/attach-service/api/v1/download/${atflId}`, fileNm)
- return true
- }
- // 파일 삭제
- const isDeleteFile = async () => {
- if (dcrpPplMtncBizSn === '' || dcrpPplMtncBizSn === undefined) {
- alert('삭제할 파일을 선택해주세요')
- return false
- }
- const data = await deleteData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
- if (data) {
- const delData = await deleteData(`v1/dcrpPpl/${dcrpPplMtncBizSn}`)
- if (delData.status == 200) {
- alert('삭제되었습니다.')
- fetchData()
- } else {
- alert('삭제에 실패했습니다.')
- }
- }
- }
- // 파일 등록
- const registFile = async (fileNm: string, year: string, quater: string, cd: string, id: string) => {
- const data = await postData('v1/dcrpPpl', {
- atflNm: fileNm,
- mngYr: year,
- mngQu: quater,
- atflCd: cd,
- atflId: id,
- dcrpPplMtncBizNm: fileNm
- })
- if (data) {alert('파일이 등록되었습니다.');fetchData() }
- }
- return (
-
-
-
-
-
-
-
-
-
-
-
-
사업정보 등록현황
-
-
-
-
-
- { if (index != null) { const fileName = tableData[index]?.dcrpPplMtncBizNm ?? ""; setFileNm(fileName); const id = tableData[index]?.atflId ?? ''; setAtflId(id); setDcrpPplMtncBizSn(tableData[index]?.dcrpPplMtncBizSn) } }} onPageChange={async (page:number)=>{setCurPage(page); await fetchData()}}>
-
-
- { await registFile(file, year, quater, cd, id) }} />
-
-
- )
-}
-
-export default Page
\ No newline at end of file
diff --git a/apps/sn/app/page.tsx b/apps/sn/app/page.tsx
index 36295f554..9bfdbb656 100644
--- a/apps/sn/app/page.tsx
+++ b/apps/sn/app/page.tsx
@@ -1,29 +1,29 @@
-'use client'
-import Link from "next/link";
-import { Button } from "@common/components/ui";
+"use client";
+import { LoginApi } from "@/entities/auth";
+import { useEffect } from "react";
+import { getCookie } from "@/shared/lib";
+import { AUTH_USER_ID } from "@/shared/config";
+import { useRouter } from "next/navigation";
export default function Home() {
- return (
-
-
-
운영정보 관리
-
-
-
-
-
-
I/I 분석(기초정보 설정)
-
-
-
-
-
-
-
-
- );
+ const router = useRouter();
+ const userId = "admin1gmail";
+ const password = "test1234!";
+ const checkToken = getCookie(AUTH_USER_ID);
+
+ useEffect(() => {
+ if (!checkToken) {
+ async function doLogin() {
+ try {
+ await LoginApi.login({ userId, password });
+ window.location.href = "/map";
+ } catch (err) {
+ console.error("로그인 실패", err);
+ }
+ }
+ doLogin();
+ } else {
+ router.push("/map");
+ }
+ }, []);
}
diff --git a/apps/sn/app/store/index.tsx b/apps/sn/app/store/index.tsx
deleted file mode 100644
index a9fc1288d..000000000
--- a/apps/sn/app/store/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { useUserStore, type IUserInfo } from "./user-store";
diff --git a/apps/sn/app/store/user-store.tsx b/apps/sn/app/store/user-store.tsx
deleted file mode 100644
index 8719dc842..000000000
--- a/apps/sn/app/store/user-store.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-
-import { create } from "zustand";
-import { persist } from "zustand/middleware";
-import { createStore } from "zustand/vanilla";
-
-export interface IUserInfo {
- regDt: string;
- mdfcnDt: string;
- rgtr: string;
- mdfr: string;
- adminRoleYn: string;
- userUnqId: string;
- userId: string;
- userName: string;
- email: string;
- encryptedPassword: string;
- refreshToken: string;
- userStateCode: string;
- lastLoginDate: string;
- loginFailCount: number;
- pswdHnt: string;
- pswdAns: string;
- mphn: string;
- telno: string;
- zip: string;
- addr: string;
- daddr: string;
- laeSeCd: string;
- ogdpSeCd: string;
- aprvYn: string;
- autzrId: string;
- expryYmd: string;
- lastPswdChgDt: string;
- googleId: string;
- kakaoId: string;
- naverId: string;
- isSocialUser: boolean;
- hasPassword: boolean;
- }
-
-export type UserState = {
- userInfo: IUserInfo | null;
-};
-
-type UserStore = {
- userInfo: IUserInfo | null;
- setUserInfo: (userInfo: IUserInfo | null) => void;
-};
-
-// ✅ zustand 기본 create + persist 적용
-export const useUserStore = create()(
- persist(
- (set) => ({
- userInfo: null,
- setUserInfo: (userInfo) => set({ userInfo }),
- }),
- {
- name: "user-store", // localStorage 키
- partialize: (state) => ({ userInfo: state.userInfo }), // 선택적 저장
- },
- ),
-);
-
-export const defaultInitState: UserState = {
- userInfo: null,
-};
-
-export const createUserStore = (initState: UserState = defaultInitState) => {
- return createStore()((set) => ({
- ...initState,
- setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })),
- }));
-};
diff --git a/apps/sn/middleware.ts b/apps/sn/middleware.ts
index f76696f53..8fe638ebe 100644
--- a/apps/sn/middleware.ts
+++ b/apps/sn/middleware.ts
@@ -1,10 +1,13 @@
import { NextRequest, NextResponse } from "next/server";
+import path from "path";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL || "";
-const GEOSERVER_URL = process.env.NEXT_PUBLIC_GEOSERVER_URL || "";
const SEWERAGE_API_URL = process.env.NEXT_PUBLIC_SEWERAGE_API_URL || "";
+const GEOSERVER_URL = process.env.NEXT_PUBLIC_GEOSERVER_URL || "";
+const LX_GEOSERVER_URL = process.env.NEXT_PUBLIC_LX_GEOSERVER_URL || "";
+const RSONE_DC_URL = process.env.NEXT_PUBLIC_RSONE_DC_URL || "";
export function middleware(req: NextRequest) {
console.log("Middleware 진입:", req.nextUrl.pathname);
@@ -12,33 +15,63 @@ export function middleware(req: NextRequest) {
const searchParams = req.nextUrl.searchParams;
if (pathname.startsWith("/server")) {
- const queryParams = searchParams.toString();
+
+ const decodedParams = Array.from(searchParams.entries())
+ .map(([key, value]) => `${key}=${decodeURIComponent(value)}`)
+ .join("&");
+
const newUrl = `${SERVER_API_URL}${pathname.replace("/server", "")}${
- queryParams ? `?${queryParams}` : ""
+ decodedParams ? `?${decodedParams}` : ""
}`;
- console.log(`[Middleware] Rewriting from '/server' path to: ${newUrl}`);
return NextResponse.rewrite(new URL(newUrl));
}
-
+
if (pathname.startsWith("/geoserver")) {
- const queryParams = searchParams.toString();
- const newUrl = `${GEOSERVER_URL}${pathname.replace("/geoserver", "")}${
- queryParams ? `?${queryParams}` : ""
- }`;
+ let queryParams = searchParams.toString();
+ const typename = searchParams.get("TYPENAME");
+
+ let newUrl = `${GEOSERVER_URL}${pathname.replace("/geoserver", "")}${queryParams ? `?${queryParams}` : ""}`;
+
+ if (
+ typename == "hasudo:tb_il_swage_prcs_fclt" //하수처리시설
+ || typename == "hasudo:tb_ms_swage_prcs_zone" //하수처리구역
+ || typename == "hasudo:tb_ms_sbmrg_dngr_map" //침수위험지도
+ || typename == "hasudo:tb_ms_flood_dngr_map" //도시침수지도
+ ) {
+ newUrl = `${GEOSERVER_URL}${pathname.replace("/geoserver", "")}${queryParams ? `?${queryParams}` : ""}`;
+ }
+ else if (
+ typename == "hasudo:tb_ms_swage_ppl" //관로
+ || typename == "hasudo:tb_ms_swage_mhl" //맨홀
+ || typename == "hasudo:tb_ms_swage_pmstn" //펌프장
+ || typename == "hasudo:tb_ms_stofcbr" //우수토실
+ ) {
+ newUrl = `${LX_GEOSERVER_URL}${pathname.replace("/geoserver", "")}${queryParams ? `?${queryParams}` : ""}`;
+ }
+ else if (
+ typename == "hasudo:om_dt_untrt_swg_rain" //중점우수토실
+ || typename == "hasudo:om_wqlt_station" //관측소
+ || typename == "hasudo:tb_wr_bdst_ruse_fclt" //재이용시설
+ || typename == "hasudo:tb_wr_rnwtr_utztn_fclt" //빗물이용시설
+ || typename == "hasudo:tb_wr_rswtr_fclt" //중수도시설
+ || typename == "hasudo:tb_wr_htdfl_fclt" //온배수시설
+ || typename == "hasudo:tb_wr_ruse_fclt_dmd_co" //수요처
+ || typename == "hasudo:tb_wr_tmpr_dmd_co" //잠재수요처
+ ){
+ const url = req.nextUrl.clone();
+ url.searchParams.set('TYPENAME', typename.replace("hasudo:",""));
+ queryParams = url.searchParams.toString();
+ newUrl = `${SEWERAGE_API_URL}/v1/map/geometry${queryParams ? `?${queryParams}` : ""}`;
+ }
+
console.log(`[Middleware] Rewriting from '/geoserver' path to: ${newUrl}`);
return NextResponse.rewrite(new URL(newUrl));
}
-
- if (pathname.startsWith("/sewerage-service/api/v1/map/geometry")) {
- const queryParams = searchParams.toString();
- const newUrl = `${SEWERAGE_API_URL}${pathname.replace("/sewerage-service/api", "")}${
- queryParams ? `?${queryParams}` : ""
- }`;
- console.log(`[Middleware] Rewriting from '/geoserver' path to: ${newUrl}`);
- return NextResponse.rewrite(new URL(newUrl));
- }
-
- if (pathname.startsWith("/attach-service") || pathname.startsWith("/cms-service")) {
+
+ if (
+ pathname.startsWith("/attach-service") ||
+ pathname.startsWith("/cms-service")
+ ) {
const requestHeaders = new Headers(req.headers);
const token = req.cookies.get(CLAIM_NAME)?.value;
const userId = req.cookies.get(AUTH_USER_ID)?.value;
@@ -54,7 +87,7 @@ export function middleware(req: NextRequest) {
headers: requestHeaders,
});
}
-
+
if (pathname.startsWith("/user-service")) {
const requestHeaders = new Headers(req.headers);
const newUrl = `${SERVER_API_URL}${pathname}`;
@@ -66,7 +99,21 @@ export function middleware(req: NextRequest) {
headers: requestHeaders,
});
}
-
+
+ if (pathname.startsWith("/dc-service")) {
+ const requestHeaders = new Headers(req.headers);
+ const decodedParams = Array.from(searchParams.entries())
+ .map(([key, value]) => `${key}=${decodeURIComponent(value)}`)
+ .join("&");
+
+ const newUrl = `${RSONE_DC_URL}${pathname}${decodedParams ? `?${decodedParams}` : ""}`;
+ console.log(
+ `[Middleware] Rewriting from '/dc-service' path to: ${newUrl}`,
+ );
+ return NextResponse.rewrite(new URL(newUrl), {
+ headers: requestHeaders,
+ });
+ }
return NextResponse.next();
}
@@ -77,6 +124,7 @@ export const config = {
"/attach-service/:path*",
"/user-service/:path*",
"/cms-service/:path*",
- "/sewerage-service/api/v1/map/geometry/:path*",
+ "/dc-service/:path*",
],
+
};
diff --git a/apps/sn/package.json b/apps/sn/package.json
index 42c19afa7..83e13a8ed 100644
--- a/apps/sn/package.json
+++ b/apps/sn/package.json
@@ -5,7 +5,7 @@
"scripts": {
"dev": "next dev -p 3002",
"build": "next build",
- "start": "next start",
+ "start:sn": "next start -p 3002",
"lint": "next lint"
},
"dependencies": {
@@ -14,6 +14,7 @@
"@common/components": "workspace:*",
"@frontend-opensource/use-react-hooks": "^1.1.4",
"@hookform/resolvers": "^4.1.3",
+ "@minoru/react-dnd-treeview": "3.5.1-alpha.1",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-query": "^5.67.1",
@@ -22,8 +23,10 @@
"chart.js": "^4.4.8",
"dayjs": "^1.11.13",
"js-cookie": "^3.0.5",
+ "moment": "^2.30.1",
"next": "15.1.7",
"react-chartjs-2": "^5.3.0",
+ "react-dnd": "^16.0.1",
"react-hook-form": "^7.54.2",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2",
@@ -49,3 +52,6 @@
"typescript": "^5"
}
}
+
+
+
diff --git a/apps/sn/public/images/map/layericon/SWL_MANH_PS_ORANGE.png b/apps/sn/public/images/map/layericon/SWL_MANH_PS_ORANGE.png
new file mode 100644
index 000000000..288d1afa8
Binary files /dev/null and b/apps/sn/public/images/map/layericon/SWL_MANH_PS_ORANGE.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_BLACK.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_BLACK.png
new file mode 100644
index 000000000..395abeb78
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_BLACK.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_GREEN.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_GREEN.png
new file mode 100644
index 000000000..33933b9e0
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_GREEN.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_ORANGE.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_ORANGE.png
new file mode 100644
index 000000000..7a78c3466
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_ORANGE.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_PURPLE.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_PURPLE.png
new file mode 100644
index 000000000..ef25607cf
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_PURPLE.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_RED.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_RED.png
new file mode 100644
index 000000000..26fd5f68e
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_RED.png differ
diff --git a/apps/sn/public/images/map/layericon/WTL_RSRV_PS_YELLOW.png b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_YELLOW.png
new file mode 100644
index 000000000..76718e865
Binary files /dev/null and b/apps/sn/public/images/map/layericon/WTL_RSRV_PS_YELLOW.png differ
diff --git a/apps/sn/src/app/index.tsx b/apps/sn/src/app/index.tsx
new file mode 100644
index 000000000..692b55ef0
--- /dev/null
+++ b/apps/sn/src/app/index.tsx
@@ -0,0 +1,20 @@
+import "./styles/base.css";
+import "./styles/components.css";
+import "@fontsource-variable/noto-sans-kr";
+
+import { AppProvider } from "./providers";
+import { cookies } from "next/headers";
+
+const App = async ({ children }: Readonly<{ children: React.ReactNode }>) => {
+ const theme = (await cookies()).get("site-theme-key");
+
+ return (
+
+
+ {children}
+
+
+ );
+};
+
+export { App };
diff --git a/apps/sn/src/app/providers/app-provider.tsx b/apps/sn/src/app/providers/app-provider.tsx
new file mode 100644
index 000000000..81821a635
--- /dev/null
+++ b/apps/sn/src/app/providers/app-provider.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import { DndProvider } from "react-dnd";
+import { MultiBackend, getBackendOptions } from "@minoru/react-dnd-treeview";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import { ConfirmProvider } from "@frontend-opensource/use-react-hooks";
+import { AuthWrapper } from "@/entities/auth";
+import { MenuWrapper } from "@/entities/menu";
+import { PromptProvider, StoreProvider } from "@/shared/providers";
+import { AlertDialog } from "@/shared/ui/alert-dialog";
+import { PromptDialog } from "@/shared/ui/prompt-dialog";
+import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
+
+
+const AppProvider = ({ children }: Readonly<{ children: React.ReactNode }>) => {
+ const queryClient = new QueryClient();
+ return (
+
+
+
+
+
+
+
+ {children}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export { AppProvider };
diff --git a/apps/sn/src/app/providers/index.ts b/apps/sn/src/app/providers/index.ts
new file mode 100644
index 000000000..15f99b7fd
--- /dev/null
+++ b/apps/sn/src/app/providers/index.ts
@@ -0,0 +1 @@
+export { AppProvider } from "./app-provider";
diff --git a/apps/sn/app/styles/base.css b/apps/sn/src/app/styles/base.css
similarity index 100%
rename from apps/sn/app/styles/base.css
rename to apps/sn/src/app/styles/base.css
diff --git a/apps/sn/app/styles/components.css b/apps/sn/src/app/styles/components.css
similarity index 100%
rename from apps/sn/app/styles/components.css
rename to apps/sn/src/app/styles/components.css
diff --git a/apps/sn/app/components/lib/auth/api/login-service.tsx b/apps/sn/src/entities/auth/api/login-service.ts
similarity index 69%
rename from apps/sn/app/components/lib/auth/api/login-service.tsx
rename to apps/sn/src/entities/auth/api/login-service.ts
index 44b7da488..c1968fe36 100644
--- a/apps/sn/app/components/lib/auth/api/login-service.tsx
+++ b/apps/sn/src/entities/auth/api/login-service.ts
@@ -1,31 +1,14 @@
import { AxiosError } from "axios";
+import {
+ ENDPOINT,
+ JWT_EXPIRATION_TIME,
+ ACCESS_TOKEN,
+ AUTH_USER_ID,
+ CLAIM_NAME,
+} from "@/shared/config";
+import type { LoginService, ILogin } from "../model/login-interface";
import { tokenManager } from "../lib/token-manager";
-const ENDPOINT = {
- USER_SERVICE: {
- LOGIN: "/user-service/login",
- USERS: "/user-service/api/v1/users",
- SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
- AUTHORIZATIONS: "/user-service/api/v1/authorizations",
- ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations",
- },
-};
-const JWT_EXPIRATION_TIME = 1800000;
-const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
-const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
-const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
-
-
-export interface ILogin {
- userId: string;
- password: string;
-}
-
-export interface LoginService {
- login(payload: ILogin): Promise;
- silentRefresh(): Promise;
-}
-
export class LoginApiService implements LoginService {
private static instance: LoginApiService;
@@ -51,14 +34,13 @@ export class LoginApiService implements LoginService {
const data = await response.json();
const accessToken = data[ACCESS_TOKEN];
const tokenId = data[AUTH_USER_ID];
-
+
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(CLAIM_NAME, accessToken);
tokenManager.setToken(AUTH_USER_ID, tokenId);
-
tokenManager.setupRefreshTimer(
() => this.silentRefresh(),
JWT_EXPIRATION_TIME,
@@ -75,14 +57,12 @@ export class LoginApiService implements LoginService {
try {
const response = await fetch(
`/api/proxy${ENDPOINT.USER_SERVICE.SILENT_REFRESH}`,
- {
- method: "PUT",
- },
+ { method: "PUT" },
);
const data = await response.json();
- const accessToken = response.headers.get("access-token");
- const tokenId = response.headers.get("token-id");
+ const accessToken = data[ACCESS_TOKEN];
+ const tokenId = data[AUTH_USER_ID];
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
diff --git a/apps/sn/app/components/lib/auth/index.tsx b/apps/sn/src/entities/auth/index.ts
similarity index 100%
rename from apps/sn/app/components/lib/auth/index.tsx
rename to apps/sn/src/entities/auth/index.ts
diff --git a/apps/sn/src/entities/auth/lib/auth-wrapper.tsx b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx
new file mode 100644
index 000000000..f0710e249
--- /dev/null
+++ b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { client } from "@/shared/api";
+import type { IUserInfo } from "@/shared/store";
+import { useUserStore } from "@/shared/lib";
+import { ENDPOINT, AUTH_USER_ID } from "@/shared/config";
+import { getCookie } from "@/shared/lib";
+import { LoginApi } from "../api/login-service";
+
+const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
+
+const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
+ const router = useRouter();
+ const { userInfo, setUserInfo } = useUserStore((state) => state);
+
+ async function authCheck() {
+ const userId = getCookie(AUTH_USER_ID);
+ if (!userId) {
+ throw new Error("Missing required authentication tokens");
+ }
+
+ const response = await client.get(
+ `${ENDPOINT.USER_SERVICE.USERS}/info/me`,
+ );
+ if (!userInfo) setUserInfo(response.data);
+ }
+
+ useEffect(() => {
+ (async () => {
+ try {
+ await authCheck();
+ } catch (error) {
+ console.error(error);
+
+ try {
+ await LoginApi.silentRefresh();
+ await authCheck();
+ } catch (refreshError) {
+ console.error("Token refresh failed:", refreshError);
+ setUserInfo(null);
+ router.push("/");
+ }
+ }
+ })();
+ }, []);
+
+ return <>{children}>;
+};
+
+export { AuthWrapper };
diff --git a/apps/sn/app/components/lib/auth/lib/token-manager.tsx b/apps/sn/src/entities/auth/lib/token-manager.ts
similarity index 86%
rename from apps/sn/app/components/lib/auth/lib/token-manager.tsx
rename to apps/sn/src/entities/auth/lib/token-manager.ts
index 9feab4af0..6387f06e5 100644
--- a/apps/sn/app/components/lib/auth/lib/token-manager.tsx
+++ b/apps/sn/src/entities/auth/lib/token-manager.ts
@@ -1,7 +1,5 @@
-import { getCookie, setCookie, removeCookie } from "@utils";
-
-const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
-const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
+import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config";
+import { getCookie, setCookie, removeCookie } from "@/shared/lib";;
export class TokenManager {
private static instance: TokenManager;
diff --git a/apps/sn/app/components/lib/auth/model/login-interface.tsx b/apps/sn/src/entities/auth/model/login-interface.ts
similarity index 100%
rename from apps/sn/app/components/lib/auth/model/login-interface.tsx
rename to apps/sn/src/entities/auth/model/login-interface.ts
diff --git a/apps/sn/src/entities/menu-authority/@x/menu.ts b/apps/sn/src/entities/menu-authority/@x/menu.ts
new file mode 100644
index 000000000..86479f859
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/@x/menu.ts
@@ -0,0 +1 @@
+export { MenuAuthorityApi } from "../api/menu-authority-service";
diff --git a/apps/sn/src/entities/menu-authority/@x/posting.ts b/apps/sn/src/entities/menu-authority/@x/posting.ts
new file mode 100644
index 000000000..bfe84fa0d
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/@x/posting.ts
@@ -0,0 +1 @@
+export { AuthorityButton } from "../ui/authority-button";
diff --git a/apps/sn/src/entities/menu-authority/api/menu-authority-service.ts b/apps/sn/src/entities/menu-authority/api/menu-authority-service.ts
new file mode 100644
index 000000000..14988eee0
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/api/menu-authority-service.ts
@@ -0,0 +1,40 @@
+import { client } from "@/shared/api";
+import { ENDPOINT } from "@/shared/config";
+import type {
+ MenuAuthorityList,
+ MenuAuthorityParams,
+ MenuAuthorityPayload,
+ MenuAuthorityService,
+ PageMenuAuthority,
+} from "../model/menu-authority-interface";
+
+export class MenuAuthorityApiService implements MenuAuthorityService {
+ public async getMenuAuthorityList(
+ params: MenuAuthorityParams,
+ ): Promise {
+ const response = await client.get(
+ `${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
+ { params },
+ );
+ return response.data;
+ }
+
+ public async getPageMenuAuthority(
+ menuCd: number,
+ ): Promise {
+ const response = await client.get(
+ `${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}/pageinfo/${menuCd}`,
+ );
+ return response.data;
+ }
+
+ public async saveMenuAuthority(data: MenuAuthorityPayload[]): Promise {
+ const response = await client.post(
+ `${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
+ data,
+ );
+ return response.data;
+ }
+}
+
+export const MenuAuthorityApi = new MenuAuthorityApiService();
diff --git a/apps/sn/src/entities/menu-authority/index.ts b/apps/sn/src/entities/menu-authority/index.ts
new file mode 100644
index 000000000..2a555b77e
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/index.ts
@@ -0,0 +1,2 @@
+export { AuthorityButton } from "./ui/authority-button";
+export { ManagementAuthorityDialog } from "./ui/management-authority-dialog";
diff --git a/apps/sn/src/entities/menu-authority/model/menu-authority-interface.ts b/apps/sn/src/entities/menu-authority/model/menu-authority-interface.ts
new file mode 100644
index 000000000..b59574c2f
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/model/menu-authority-interface.ts
@@ -0,0 +1,48 @@
+import { z } from "zod";
+import type { PageableList, PageableParams } from "@/shared/model";
+
+export interface MenuAuthorityParams extends PageableParams {
+ groupId?: string;
+ menuCd?: number;
+ useYn?: string;
+}
+
+export interface PageMenuAuthority {
+ mngAuthrtYn: string;
+ inqAuthrtYn: string;
+ regAuthrtYn: string;
+ mdfcnAuthrtYn: string;
+ delAuthrtYn: string;
+}
+
+export const menuAuthoritySchema = z.object({
+ groupId: z.string(),
+ groupNm: z.string(),
+ menuCd: z.number(),
+ mngAuthrtYn: z.string(),
+ inqAuthrtYn: z.string(),
+ regAuthrtYn: z.string(),
+ mdfcnAuthrtYn: z.string(),
+ delAuthrtYn: z.string(),
+ useYn: z.string(),
+ mode: z.string(),
+});
+
+export const menuAuthorityPayloadSchema = menuAuthoritySchema.omit({
+ groupNm: true,
+});
+
+export const menuAuthorityFormSchema = z.object({
+ menuAuthority: z.array(menuAuthorityPayloadSchema),
+});
+
+export type MenuAuthority = z.infer;
+export type MenuAuthorityList = PageableList;
+export type MenuAuthorityPayload = z.infer;
+export type MenuAuthorityFormData = z.infer;
+
+export interface MenuAuthorityService {
+ getMenuAuthorityList(params: MenuAuthorityParams): Promise;
+ getPageMenuAuthority(menuCd: number): Promise;
+ saveMenuAuthority(data: MenuAuthorityPayload[]): Promise;
+}
diff --git a/apps/sn/src/entities/menu-authority/model/menu-authority-table-columns.tsx b/apps/sn/src/entities/menu-authority/model/menu-authority-table-columns.tsx
new file mode 100644
index 000000000..6969a85e9
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/model/menu-authority-table-columns.tsx
@@ -0,0 +1,117 @@
+import type { ColumnDef } from "@tanstack/react-table";
+import type { UseFormReturn } from "react-hook-form";
+import { Checkbox } from "@common/components";
+import type {
+ MenuAuthority,
+ MenuAuthorityFormData,
+ MenuAuthorityPayload,
+} from "./menu-authority-interface";
+
+export const createColumns = (
+ form: UseFormReturn,
+): ColumnDef[] => {
+ const getCurrentRow = (i: number) => form.watch("menuAuthority")[i];
+
+ const handleCheckedChange =
+ (i: number, key: keyof MenuAuthorityPayload) => (checked: boolean) => {
+ if (getCurrentRow(i)?.mode === "R") {
+ form.setValue(`menuAuthority.${i}.mode`, "U");
+ }
+ form.setValue(`menuAuthority.${i}.${key}`, checked ? "Y" : "N");
+ };
+
+ return [
+ {
+ accessorKey: "groupNm",
+ header: "그룹명",
+ },
+ {
+ accessorKey: "mngAuthrtYn",
+ header: "관리권한",
+ cell: ({ row }) => {
+ return (
+ {
+ if (checked) {
+ handleCheckedChange(
+ row.index,
+ "regAuthrtYn",
+ )(checked as boolean);
+ handleCheckedChange(
+ row.index,
+ "mdfcnAuthrtYn",
+ )(checked as boolean);
+ handleCheckedChange(
+ row.index,
+ "delAuthrtYn",
+ )(checked as boolean);
+ handleCheckedChange(
+ row.index,
+ "inqAuthrtYn",
+ )(checked as boolean);
+ }
+ handleCheckedChange(row.index, "mngAuthrtYn")(checked as boolean);
+ }}
+ />
+ );
+ },
+ },
+ {
+ accessorKey: "regAuthrtYn",
+ header: "등록권한",
+ cell: ({ row }) => {
+ return (
+ {
+ if (checked) {
+ handleCheckedChange(
+ row.index,
+ "inqAuthrtYn",
+ )(checked as boolean);
+ }
+ handleCheckedChange(row.index, "regAuthrtYn")(checked as boolean);
+ }}
+ />
+ );
+ },
+ },
+ {
+ accessorKey: "mdfcnAuthrtYn",
+ header: "수정권한 ",
+ cell: ({ row }) => {
+ return (
+
+ );
+ },
+ },
+ {
+ accessorKey: "delAuthrtYn",
+ header: "삭제권한",
+ cell: ({ row }) => {
+ return (
+
+ );
+ },
+ },
+ {
+ accessorKey: "inqAuthrtYn",
+ header: "조회권한",
+ cell: ({ row }) => {
+ return (
+
+ );
+ },
+ },
+ ];
+};
diff --git a/apps/sn/src/entities/menu-authority/ui/authority-button.tsx b/apps/sn/src/entities/menu-authority/ui/authority-button.tsx
new file mode 100644
index 000000000..257ab6e5d
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/ui/authority-button.tsx
@@ -0,0 +1,26 @@
+import { useMenuStore } from "@/shared/lib";
+import { Button, cn, type ButtonProps } from "@common/components";
+import type { PageMenuAuthority } from "../model/menu-authority-interface";
+
+type AuthorityButtonProps = {
+ authority: keyof PageMenuAuthority;
+} & ButtonProps;
+
+function AuthorityButton({
+ authority,
+ className,
+ children,
+ ...props
+}: AuthorityButtonProps) {
+ const pageMenuAuthority = useMenuStore((state) => state.pageMenuAuthority);
+
+ const isAuthority = pageMenuAuthority?.[authority] === "Y";
+
+ return (
+
+ );
+}
+
+export { AuthorityButton };
diff --git a/apps/sn/src/entities/menu-authority/ui/management-authority-dialog.tsx b/apps/sn/src/entities/menu-authority/ui/management-authority-dialog.tsx
new file mode 100644
index 000000000..4a73cb596
--- /dev/null
+++ b/apps/sn/src/entities/menu-authority/ui/management-authority-dialog.tsx
@@ -0,0 +1,103 @@
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useQuery } from "@tanstack/react-query";
+import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
+import { useConfirm } from "@frontend-opensource/use-react-hooks";
+import {
+ Button,
+ DataTable,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@common/components";
+import { ENDPOINT } from "@/shared/config";
+import { useAlertStore, useMutationWrapper } from "@/shared/lib";
+import {
+ menuAuthorityFormSchema,
+ type MenuAuthorityFormData,
+ type MenuAuthorityPayload,
+} from "../model/menu-authority-interface";
+import { createColumns } from "../model/menu-authority-table-columns";
+import { MenuAuthorityApi } from "../api/menu-authority-service";
+
+type ManagementAuthorityDialogProps = {
+ menuCd?: number;
+} & React.ComponentProps;
+
+function ManagementAuthorityDialog({
+ menuCd,
+ ...props
+}: ManagementAuthorityDialogProps) {
+ const { confirm } = useConfirm();
+ const alert = useAlertStore((state) => state.setMessage);
+
+ const { data: menuAuthorityList } = useQuery({
+ queryKey: [ENDPOINT.CMS_SERVICE.MENU_AUTHRTS, menuCd],
+ queryFn: () => MenuAuthorityApi.getMenuAuthorityList({ menuCd }),
+ enabled: !!menuCd,
+ });
+
+ const { mutateAsync: saveMenuAuthority } = useMutationWrapper({
+ mutationFn: (data: MenuAuthorityPayload[]) =>
+ MenuAuthorityApi.saveMenuAuthority(data),
+ onSuccess: () => {
+ alert("저장되었습니다.");
+ },
+ });
+
+ const form = useForm({
+ resolver: zodResolver(menuAuthorityFormSchema),
+ values: {
+ menuAuthority: menuAuthorityList?.content ?? [],
+ },
+ });
+
+ const table = useReactTable({
+ data: menuAuthorityList?.content ?? [],
+ columns: createColumns(form),
+ getCoreRowModel: getCoreRowModel(),
+ });
+
+ const handleSave = async () => {
+ if (await confirm("저장하시겠습니까?")) {
+ const data = form.getValues("menuAuthority");
+ const filteredData = data.filter((item) => item.mode !== "R");
+ await saveMenuAuthority(filteredData);
+ }
+ };
+
+ return (
+
+ );
+}
+
+export { ManagementAuthorityDialog };
diff --git a/apps/sn/src/entities/menu/api/menu-service.ts b/apps/sn/src/entities/menu/api/menu-service.ts
new file mode 100644
index 000000000..4424f8d37
--- /dev/null
+++ b/apps/sn/src/entities/menu/api/menu-service.ts
@@ -0,0 +1,14 @@
+import { client } from "@/shared/api";
+import { ENDPOINT } from "@/shared/config";
+import type { MenuItem, MenuService } from "../model/menu-interface";
+
+export class MenuApiService implements MenuService {
+ async getMenuRoles(siteId: string): Promise