Merge branch 'iipbs/sn/dev'
@@ -18,5 +18,5 @@ apps/wr/.next/**/*
|
||||
apps/fo/.next/**/*
|
||||
|
||||
# env
|
||||
.env*
|
||||
#.env*
|
||||
.qodo
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
NEXT_PUBLIC_SITE_ID = SN
|
||||
NEXT_PUBLIC_PORT = 11302
|
||||
NEXT_PUBLIC_PROXY_HOST = http://con.mind-one.co.kr:11302
|
||||
NEXT_PUBLIC_SERVER_API_URL = http://dev.onasys.co.kr:8000
|
||||
NEXT_PUBLIC_GEOSERVER_URL = http://rsone.iptime.org:10010/geoserver
|
||||
NEXT_PUBLIC_LX_GEOSERVER_URL = http://con.mind-one.co.kr:11306/geoserver #TODO 운영에서 바꿔야 함
|
||||
NEXT_PUBLIC_CLAIM_NAME = Authorization
|
||||
NEXT_PUBLIC_AUTH_USER_ID = token-id
|
||||
NEXT_PUBLIC_ACCESS_TOKEN = access-token
|
||||
NEXT_PUBLIC_REFRESH_TOKEN = refresh-token
|
||||
|
||||
NEXT_PUBLIC_SEWERAGE_API_URL=http://con.mind-one.co.kr:11083/sewerage-service/api # 개발 서버 API
|
||||
@@ -0,0 +1,16 @@
|
||||
NEXT_PUBLIC_SITE_ID = SN
|
||||
NEXT_PUBLIC_PORT = 3002
|
||||
NEXT_PUBLIC_PROXY_HOST = http://localhost:3002
|
||||
NEXT_PUBLIC_ADDR_URL = http://con.mind-one.co.kr:11082
|
||||
NEXT_PUBLIC_SERVER_API_URL = http://dev.onasys.co.kr:8000
|
||||
NEXT_PUBLIC_GEOSERVER_URL = http://rsone.iptime.org:10010/geoserver
|
||||
NEXT_PUBLIC_LX_GEOSERVER_URL = http://con.mind-one.co.kr:11306/geoserver
|
||||
NEXT_PUBLIC_RSONE_DC_URL = https://apigateway.rsonesoft.com #자료관 데이터
|
||||
NEXT_PUBLIC_CLAIM_NAME = Authorization
|
||||
NEXT_PUBLIC_AUTH_USER_ID = token-id
|
||||
NEXT_PUBLIC_ACCESS_TOKEN = access-token
|
||||
NEXT_PUBLIC_REFRESH_TOKEN = refresh-token
|
||||
|
||||
NEXT_PUBLIC_SEWERAGE_API_URL=http://con.mind-one.co.kr:11083/sewerage-service/api # 개발 서버 API
|
||||
#NEXT_PUBLIC_SEWERAGE_API_URL=http://192.168.1.128:8883/sewerage-service/api # 최용성 부장님 API
|
||||
#NEXT_PUBLIC_SEWERAGE_API_URL=http://192.168.1.222:8883/sewerage-service/api # 박이정 차장님 API
|
||||
@@ -0,0 +1,14 @@
|
||||
NEXT_PUBLIC_SITE_ID = SN
|
||||
NEXT_PUBLIC_PORT = 11302
|
||||
NEXT_PUBLIC_PROXY_HOST = http://con.mind-one.co.kr:11302
|
||||
NEXT_PUBLIC_ADDR_URL = http://con.mind-one.co.kr:11082
|
||||
NEXT_PUBLIC_SERVER_API_URL = http://dev.onasys.co.kr:8000
|
||||
NEXT_PUBLIC_GEOSERVER_URL = http://172.29.143.87:8080/geoserver
|
||||
NEXT_PUBLIC_LX_GEOSERVER_URL = http://rsone.iptime.org:10010/geoserver_swl
|
||||
NEXT_PUBLIC_RSONE_DC_URL = https://apigateway.rsonesoft.com #자료관 데이터
|
||||
NEXT_PUBLIC_CLAIM_NAME = Authorization
|
||||
NEXT_PUBLIC_AUTH_USER_ID = token-id
|
||||
NEXT_PUBLIC_ACCESS_TOKEN = access-token
|
||||
NEXT_PUBLIC_REFRESH_TOKEN = refresh-token
|
||||
|
||||
NEXT_PUBLIC_SEWERAGE_API_URL=http://con.mind-one.co.kr:11083/sewerage-service/api # 개발 서버 API
|
||||
@@ -0,0 +1,34 @@
|
||||
"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";
|
||||
|
||||
export default function MapLayout({
|
||||
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 (
|
||||
<BaseLayout
|
||||
queryClient={queryClient}
|
||||
currentPath={pathname ?? ""}
|
||||
handleMenuClick={handleMenuClick}
|
||||
>
|
||||
{children}
|
||||
</BaseLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import FeatureClickEventPopup from './featureClickEventPopup';
|
||||
import React, { useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { UiModal, UiTable } from '@common/business_components/ui';
|
||||
import { UiModal, UiTable, DatePickerRange } from '@common/business_components/ui';
|
||||
import { Button, Input, Label } from '@common/components';
|
||||
import { UiTable2 } from '@common/business_components/ui/table/index-2';
|
||||
import { UITab2 } from '@common/business_components/ui/tab/index-2';
|
||||
import { SelectBox2 } from '@common/business_components/ui/select/index-2';
|
||||
import { YearRangeSelectBox } from '@/components/ui/YearRangeSelectBox';
|
||||
import { SidoSigunguSelectBox } from '@/components/ui/SidoSigunguSelectBox';
|
||||
import { SwtrmtFcltCol, SwtrmtPrcsZoneCol } from './components/common/table';
|
||||
import { MsSwagePplCol2, SwtrmtFcltCol2, SwtrmtPrcsZoneCol2, MsSwageMhlCol2, ExclnSewagePumpCol2, stofcbrCol2 } from './components/common/table';
|
||||
import LoadingOverlay from '@/components/ui/LoadingBar';
|
||||
//import { useDcTree, flattenFolders, useSggCd, useCityCd } from './components/searchModalReportApi';
|
||||
import { useDcTree,flattenFolders, useSggCd, useCityCd, addFileName, getFileDownload } from './components/searchModalReportApi';
|
||||
import { useCityCdStore, type SelectDataType } from './commonStore';
|
||||
|
||||
const API_URL = `${process.env.NEXT_PUBLIC_SEWERAGE_API_URL}`;
|
||||
|
||||
@@ -24,10 +27,11 @@ const BASIC_TYPES = [
|
||||
{ val: "tb_ms_swage_ppl", text: "하수관로" },
|
||||
{ val: "tb_il_swage_prcs_fclt", text: "하수처리시설" },
|
||||
{ val: "tb_ms_swage_prcs_zone", text: "하수처리구역" },
|
||||
{ val: "tb_ms_swage_mh", text: "하수맨홀" },
|
||||
{ val: "tb_ms_swage_psmtn_1", text: "오수펌프" },
|
||||
{ val: "tb_ms_swage_psmtn_2", text: "빗물펌프" },
|
||||
{ val: "tb_ms_otfl", text: "우수토실" },
|
||||
{ val: "tb_ms_swage_mhl", text: "하수맨홀" },
|
||||
{ val: "tb_ms_swage_pmstn", text: "하수펌프장" },
|
||||
// { val: "tb_ms_swage_psmtn_1", text: "오수펌프" },
|
||||
// { val: "tb_ms_swage_psmtn_2", text: "빗물펌프" },
|
||||
{ val: "tb_ms_stofcbr", text: "우수토실" },
|
||||
];
|
||||
// 운영정보 '구분' 선택 목록
|
||||
const WORK_TYPES = [
|
||||
@@ -37,38 +41,7 @@ const WORK_TYPES = [
|
||||
];
|
||||
|
||||
const YEARS = Array.from({ length: 100 }, (_, i) => `${2025 - i}`);
|
||||
// 테이블 헤더 리스트
|
||||
// 하수관로
|
||||
const swagePplTableHeadlist = [
|
||||
{ id: 'pipeNumber', title: '관로번호' },
|
||||
{ id: 'gisManageNumber', title: '관리번호(GIS)' },
|
||||
{ id: 'managingInstitution', title: '관리기관' },
|
||||
{ id: 'drawingNumber', title: '도엽번호' },
|
||||
{ id: 'installationLocation', title: '설치위치' },
|
||||
{ id: 'usage', title: '용도' },
|
||||
{ id: 'pipeDiameter', title: '관경' },
|
||||
{ id: 'pipeLength', title: '관로연장' },
|
||||
{ id: 'pipeType', title: '관종' },
|
||||
{ id: 'burialDepth', title: '매설심도' },
|
||||
{ id: 'constructionYear', title: '개보수 년도' },
|
||||
{ id: 'installationSubject', title: '설치 주체' },
|
||||
{ id: 'area', title: '구역' },
|
||||
{ id: 'division', title: '분구' },
|
||||
{ id: 'alignmentType', title: '지선/간선 구분' },
|
||||
{ id: 'flowType', title: '흐름 방식' },
|
||||
{ id: 'boxCount', title: '박스 열수' },
|
||||
{ id: 'height', title: '높이' },
|
||||
{ id: 'width', title: '폭' },
|
||||
{ id: 'startManholeNumber', title: '시점 맨홀번호' },
|
||||
{ id: 'endManholeNumber', title: '종점 맨홀번호' },
|
||||
{ id: 'startElevation', title: '시점관저고' },
|
||||
{ id: 'endElevation', title: '종점관저고' },
|
||||
]
|
||||
|
||||
// 하수맨홀 (추후 작성 예정)
|
||||
const swageMhTableHeadlist = [
|
||||
{ id: "swtrmtFcltCd", title: "하수처리시설코드" },
|
||||
];
|
||||
// 운영정보
|
||||
const operationTableHeadlist = [
|
||||
{ id: "no", title: "NO" },
|
||||
@@ -81,28 +54,15 @@ const operationTableHeadlist = [
|
||||
// 하수도정비 기본계획 보고서
|
||||
const reportTableHeadlist = [
|
||||
{ id: "no", title: "NO" },
|
||||
{ id: "approvalYear", title: "승인년도" },
|
||||
{ id: "sido", title: "시도" },
|
||||
{ id: "sigungu", title: "시군구" },
|
||||
{ id: "treatmentPlant", title: "하수처리장" },
|
||||
{ id: "treatmentZone", title: "하수처리구역" },
|
||||
{ id: "reportCount", title: "보고서(00건)" },
|
||||
{ id: "planMapCount", title: "하수도대장 평면도(00건)" },
|
||||
{ id: "approvalYear", title: "승인년도" },
|
||||
{ id: "plantZoneGugun", title: "구분" },
|
||||
{ id: "reportGubun", title: "보고서구분" },
|
||||
{ id: "fileName", title: "파일명" },
|
||||
{ id: "regDate", title: "등록일자" },
|
||||
];
|
||||
|
||||
const 처리구역List = [
|
||||
{ val: "0", text: "선택" },
|
||||
{ val: "a", text: "A" },
|
||||
{ val: "b", text: "B" },
|
||||
];
|
||||
|
||||
interface SearchModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onFeatureSelect: (row: any) => void;
|
||||
}
|
||||
|
||||
// 날짜 조합 함수
|
||||
const getDateString = (
|
||||
year: string,
|
||||
@@ -117,6 +77,12 @@ const getDateString = (
|
||||
return `${y}${m}${d}`;
|
||||
};
|
||||
|
||||
interface SearchModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onFeatureSelect: (row: any) => void;
|
||||
}
|
||||
|
||||
const SearchModal: React.FC<SearchModalProps> = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
@@ -129,9 +95,10 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
const [tableCount, setTableCount] = useState<number>(0);
|
||||
const [curPage, setCurPage] = useState(1);
|
||||
const [basicType, setBasicType] = useState(BASIC_TYPES[0]?.val ?? "");
|
||||
const [시도, set시도] = useState(0);
|
||||
const [시군구, set시군구] = useState(0);
|
||||
const [처리구역, set처리구역] = useState("");
|
||||
const [ctpvCd, setCtpvCd] = useState('0');
|
||||
const [sigungu, setSigungu] = useState('0');
|
||||
//const [swageProcessingZone, set처리구역] = useState("");
|
||||
const [gubun, setGubun] = useState(""); // 하수정비기본계획 report
|
||||
// 날짜 상태 선언
|
||||
const [시작1, set시작1] = useState("");
|
||||
const [시작2, set시작2] = useState("");
|
||||
@@ -145,34 +112,57 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
const [yearFilter, setYearFilter] = useState({
|
||||
시작: "",
|
||||
종료: "",
|
||||
경과년도: "",
|
||||
// 경과년도: "",
|
||||
});
|
||||
|
||||
const [가동개시_시작_월, set가동개시_시작_월] = useState('');
|
||||
const [가동개시_종료_월, set가동개시_종료_월] = useState('');
|
||||
const [가동개시_시작_일, set가동개시_시작_일] = useState('');
|
||||
const [가동개시_종료_일, set가동개시_종료_일] = useState('');
|
||||
const [fromDate, setFromDate] = useState(() => { const date = new Date(); date.setDate(date.getDate() - 7); return date })
|
||||
const [toDate, setToDate] = useState(new Date())
|
||||
const [filteredSiguns, setFilteredSiguns] = useState<SelectDataType[]>([{ val: '0', text: '전체', sido: '0' }]);
|
||||
|
||||
// 로딩바
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
// 상세 정보 조회를 위한 상태 추가
|
||||
const [popupFeature, setPopupFeature] = useState<any>(null);
|
||||
|
||||
const sidos = useCityCd();
|
||||
const siguns = useSggCd();
|
||||
const reportOriginData = useDcTree(""); //:Folder[]
|
||||
|
||||
// 오늘 날짜 구하기
|
||||
const today = new Date();
|
||||
const todayYear = today.getFullYear().toString();
|
||||
const todayMonth = (today.getMonth() + 1).toString().padStart(2, "0");
|
||||
const todayDate = today.getDate().toString().padStart(2, "0");
|
||||
|
||||
const isDateInRanges = (date: Date) => {
|
||||
const standYear = parseInt(fromDate.getFullYear().toString());
|
||||
const dateRanges = [];
|
||||
dateRanges.push({
|
||||
start: new Date(standYear, 0, 1),
|
||||
end: new Date(standYear, 11, 31)
|
||||
});
|
||||
|
||||
return dateRanges.some(range => {
|
||||
const start = new Date(range.start);
|
||||
const end = new Date(range.end);
|
||||
return date >= start && date <= end;
|
||||
});
|
||||
};
|
||||
|
||||
// UiTable2에 넘길 headlist를 BASIC_TYPES 값에 따라 분기 처리
|
||||
let dynamicHeadlist = SwtrmtPrcsZoneCol; // default 값
|
||||
let dynamicHeadlist = MsSwagePplCol2; // default 값
|
||||
if (activeTab === 'operation') dynamicHeadlist = operationTableHeadlist; // 운영정보
|
||||
else if (activeTab === 'report') dynamicHeadlist = reportTableHeadlist; // 하수도정비기본계획보고서
|
||||
else if (basicType === 'tb_ms_swage_ppl') dynamicHeadlist = swagePplTableHeadlist; // 하수관로
|
||||
else if (basicType === 'tb_il_swage_prcs_fclt') dynamicHeadlist = SwtrmtFcltCol; // 하수처리시설
|
||||
else if (basicType === 'tb_ms_swage_prcs_zone') dynamicHeadlist = SwtrmtPrcsZoneCol; // 하수처리구역
|
||||
else if (basicType === 'tb_ms_swage_mh') dynamicHeadlist = swageMhTableHeadlist; // 하수맨홀
|
||||
else if (basicType === 'tb_ms_swage_ppl') dynamicHeadlist = MsSwagePplCol2; // 하수관로
|
||||
else if (basicType === 'tb_il_swage_prcs_fclt') dynamicHeadlist = SwtrmtFcltCol2; // 하수처리시설
|
||||
else if (basicType === 'tb_ms_swage_prcs_zone') dynamicHeadlist = SwtrmtPrcsZoneCol2; // 하수처리구역
|
||||
else if (basicType === 'tb_ms_swage_mhl') dynamicHeadlist = MsSwageMhlCol2; // 하수맨홀
|
||||
else if (basicType === 'tb_ms_swage_pmstn') dynamicHeadlist = ExclnSewagePumpCol2; // 하수펌프장
|
||||
else if (basicType === 'tb_ms_stofcbr') dynamicHeadlist = stofcbrCol2; // 우수토실
|
||||
|
||||
|
||||
// 조회 버튼 클릭 시 1페이지로 이동하도록 수정
|
||||
const handleSearch = () => {
|
||||
setCurPage(1); // 페이지를 1로 초기화
|
||||
@@ -181,15 +171,36 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
};
|
||||
|
||||
// cellClick 함수 타입 지정
|
||||
const handleCellClick = (index?: number, headId?: string) => {
|
||||
const handleCellClick = (index?: number) => {
|
||||
if (typeof index === "number") {
|
||||
onFeatureSelect(tableData[index % 10]); // 10은 page size 하드 코딩한 숫자
|
||||
onOpenChange(false); // SearchModal 닫기
|
||||
}
|
||||
};
|
||||
// 하수도정비기본계획.table cellClick
|
||||
const handleReportCellClick = (index: number) => {
|
||||
console.log(index);
|
||||
const reportData = tableData[index];
|
||||
const fileName = reportData.fileName;
|
||||
if (reportData.fileSn !== "") {
|
||||
getFileDownload(reportData.fileSn, fileName);
|
||||
}
|
||||
};
|
||||
|
||||
// 구분(basicType)이 바뀔 때마다 queryParams, filterParams 초기화
|
||||
React.useEffect(() => {
|
||||
const handleCtpvCdChange = (val: string|number) => { // 하수도정비기본계획.시도
|
||||
const sidoOption = sidos.find((n) => n.val === val);
|
||||
setCtpvCd(String(val));
|
||||
if (val !== '0') {
|
||||
const filterSiguns = siguns.filter(item => item.sido === sidoOption?.text);
|
||||
filterSiguns.unshift({ val: '0', text: '전체', sido: '0' });
|
||||
setFilteredSiguns(filterSiguns);
|
||||
}
|
||||
setSigungu("0");
|
||||
setGubun("");
|
||||
setYearFilter({시작: "",종료: "",});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// filterParams 초기화
|
||||
// setFilterParams({});
|
||||
set시작1("");
|
||||
@@ -204,22 +215,21 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
set가동개시_종료_월("");
|
||||
set가동개시_시작_일("");
|
||||
set가동개시_종료_일("");
|
||||
set시도(0);
|
||||
set시군구(0);
|
||||
set처리구역("");
|
||||
setCtpvCd('0');
|
||||
setSigungu('0');
|
||||
setYearFilter({
|
||||
시작: "",
|
||||
종료: "",
|
||||
경과년도: "",
|
||||
// 경과년도: "",
|
||||
});
|
||||
setShowTable(false);
|
||||
setTableCount(0);
|
||||
setTableData([]);
|
||||
// queryParams는 fetchFilteredData 내에서 매번 새로 생성되므로 별도 상태 초기화는 필요 없음
|
||||
}, [activeTab, basicType]);
|
||||
}, [activeTab, basicType, open]);
|
||||
|
||||
// 페이지 변경 시마다 데이터 fetch
|
||||
React.useEffect(() => {
|
||||
useEffect(() => {
|
||||
// showTable이 true일 때만 fetch (최초 렌더 방지)
|
||||
if (showTable) {
|
||||
fetchFilteredData(); // 실제 API 사용 시
|
||||
@@ -227,14 +237,95 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
}
|
||||
}, [curPage]);
|
||||
|
||||
|
||||
// 검색 API 호출 함수
|
||||
const fetchFilteredData = async () => {
|
||||
setIsLoading(true); // 로딩 시작
|
||||
try {
|
||||
const queryParams = new URLSearchParams({
|
||||
lyrTypeNm: basicType,
|
||||
page: `${curPage - 1}`,
|
||||
size: '10',
|
||||
sort: 'string',
|
||||
});
|
||||
|
||||
let cqlFilters: string[] = [];
|
||||
if (activeTab === 'basic') {
|
||||
if (basicType === 'tb_ms_swage_prcs_zone') cqlFilters = zoneCqlFilters(); // 하수처리구역
|
||||
else if (basicType === 'tb_il_swage_prcs_fclt') cqlFilters = facilityCqlFilters(); // 하수처리시설
|
||||
else if (basicType === 'tb_ms_swage_ppl') cqlFilters = pplCqlFilters(); // 하수관로
|
||||
else if (basicType === 'tb_ms_swage_mhl') cqlFilters = mhCqlFilters(); // 하수맨홀
|
||||
else if (basicType === 'tb_ms_swage_pmstn') cqlFilters = psmtnCqlFilters(); // 하수펌프장
|
||||
else if (basicType === 'tb_ms_stofcbr') cqlFilters = otflCqlFilters(); // 우수토실
|
||||
} else if (activeTab === 'operation') {
|
||||
cqlFilters = zoneCqlFilters();
|
||||
} else {
|
||||
cqlFilters = reportCqlFilters();
|
||||
}
|
||||
|
||||
if (cqlFilters.length > 0) queryParams.append('cqlFiter', cqlFilters.join(' and '));
|
||||
|
||||
if (activeTab === 'report') {
|
||||
//const reportOriginData = await getDcTree('경기도');
|
||||
const reportData = flattenFolders(reportOriginData);
|
||||
let filterReportData = reportData;
|
||||
if (ctpvCd !== "0") { // 시도검색
|
||||
const sidoOption = sidos.find((n) => n.val === ctpvCd);
|
||||
filterReportData = filterReportData.filter(item => item.sido === sidoOption?.text);
|
||||
}
|
||||
if (sigungu !== "0") { // 시군구검색
|
||||
const sigunguOption = filteredSiguns.find((n) => n.val === sigungu);
|
||||
filterReportData = filterReportData.filter(item => item.sigungu === sigunguOption?.text);
|
||||
}
|
||||
if (yearFilter.시작 != "" && yearFilter.종료 == "") //승인년도검색
|
||||
filterReportData = filterReportData.filter(item => (item.approvalYear)? item.approvalYear >= yearFilter.시작+"년" : null);
|
||||
if (yearFilter.시작 == "" && yearFilter.종료 != "")
|
||||
filterReportData = filterReportData.filter(item => (item.approvalYear)? item.approvalYear <= yearFilter.종료+"년" : null);
|
||||
if (yearFilter.시작 != "" && yearFilter.종료 != "") {
|
||||
filterReportData = filterReportData.filter(item => {
|
||||
return (item.approvalYear)? item.approvalYear >= yearFilter.시작+"년" && item.approvalYear <= yearFilter.종료+"년": null;
|
||||
});
|
||||
}
|
||||
if (gubun !== "") { // 구분검색
|
||||
filterReportData = filterReportData.filter(item => (item.plantZoneGugun)? String(item.plantZoneGugun).includes(String(gubun)) : null);
|
||||
}
|
||||
console.log('report count:', filterReportData.length);
|
||||
setTableCount(filterReportData.length || 0);
|
||||
filterReportData = filterReportData.slice((curPage-1)*10, curPage*10); // paging
|
||||
filterReportData = filterReportData?.map((item, index)=>({...item, no:(curPage-1)*10+index+1}));
|
||||
//const fileList = await getDcFile("CLS20250530000041");
|
||||
addFileName(filterReportData).then(data => {
|
||||
filterReportData = data;
|
||||
setTableData(filterReportData || []);
|
||||
});
|
||||
setTableData(filterReportData || []);
|
||||
} else {
|
||||
console.log('API URL:', `${API_URL}/v1/fclts?${queryParams.toString()}`);
|
||||
const res = await axios.get(`${API_URL}/v1/fclts?${queryParams.toString()}`);
|
||||
console.log('필터링된 API 결과(개수):', res.data.count);
|
||||
console.log('필터링된 API 결과(데이터):', res.data.data);
|
||||
setTableData(res.data.data || []);
|
||||
setTableCount(res.data.count || []);
|
||||
console.log('tableCount 상태 업데이트 후:', res.data.count); // tableCount 로그 추가
|
||||
}
|
||||
|
||||
setShowTable(true);
|
||||
} catch (err) {
|
||||
console.error('API ERROR:', err);
|
||||
setTableData([]);
|
||||
} finally {
|
||||
setIsLoading(false); // 로딩 종료
|
||||
}
|
||||
};
|
||||
|
||||
// 하수관로용 CQL 필터 생성
|
||||
const pplCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
// 추후 작성 예정
|
||||
if (변수1) cqlFilters.push(`용도코드='${변수1}'`);
|
||||
if (변수2) cqlFilters.push(`재질코드='${변수2}'`);
|
||||
if (변수3) cqlFilters.push(`행정읍면동코드='${변수3}'`);
|
||||
if (변수4) cqlFilters.push(`경과년도='${변수4}'`);
|
||||
if (변수1) cqlFilters.push(`usg_cd='${변수1}'`);
|
||||
if (변수2) cqlFilters.push(`mqlt_cd='${변수2}'`);
|
||||
if (변수3) cqlFilters.push(`pbadms_emd_cd='${변수3}'`);
|
||||
// if (변수4) cqlFilters.push(`경과년도='${변수4}'`);
|
||||
// 설치년도 범위
|
||||
const startDate = getDateString(
|
||||
yearFilter.시작,
|
||||
@@ -249,19 +340,20 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
`${todayYear}${todayMonth}${todayDate}`,
|
||||
);
|
||||
cqlFilters.push(
|
||||
`설치시작년도 >= '${startDate}' and 설치시작년도 <= '${endDate}'`,
|
||||
`instl_ymd >= '${startDate}' and instl_ymd <= '${endDate}'`,
|
||||
);
|
||||
// 관경(mm) 범위
|
||||
if (시작1 && 종료1) cqlFilters.push(`관경 BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`관경 >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`관경 <= ${종료1}`);
|
||||
if (시작1 && 종료1) cqlFilters.push(`pdmt BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`pdmt >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`pdmt <= ${종료1}`);
|
||||
// 연장(m) 범위
|
||||
if (시작2 && 종료2) cqlFilters.push(`연장 BETWEEN ${시작2} AND ${종료2}`);
|
||||
else if (시작2) cqlFilters.push(`연장 >= ${시작2}`);
|
||||
else if (종료2) cqlFilters.push(`연장 <= ${종료2}`);
|
||||
if (시작2 && 종료2) cqlFilters.push(`prlg BETWEEN ${시작2} AND ${종료2}`);
|
||||
else if (시작2) cqlFilters.push(`prlg >= ${시작2}`);
|
||||
else if (종료2) cqlFilters.push(`prlg <= ${종료2}`);
|
||||
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 하수처리시설용 CQL 필터 생성
|
||||
const facilityCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
@@ -290,19 +382,21 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
if (변수1) cqlFilters.push(`swtrmt_fclt_nm ILIKE '%${변수1}%'`);
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 하수처리구역용 CQL 필터 생성
|
||||
const zoneCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
if (시도) cqlFilters.push(`ctpv_cd='${시도}'`);
|
||||
if (시군구) cqlFilters.push(`sgg_cd='${시군구}'`);
|
||||
if (ctpvCd) cqlFilters.push(`ctpv_cd='${ctpvCd}'`);
|
||||
if (sigungu) cqlFilters.push(`sgg_cd='${sigungu}'`);
|
||||
if (변수1) cqlFilters.push(`swtrmt_zone_nm ILIKE '%${변수1}%'`);
|
||||
if (변수2) cqlFilters.push(`swtrmt_fclt_nm ILIKE '%${변수2}%'`);
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 하수맨홀용 CQL 필터 생성
|
||||
const mhCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
// 설치년도 범위
|
||||
// // 설치년도 범위
|
||||
const startDate = getDateString(
|
||||
yearFilter.시작,
|
||||
가동개시_시작_월,
|
||||
@@ -316,17 +410,18 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
`${todayYear}${todayMonth}${todayDate}`,
|
||||
);
|
||||
cqlFilters.push(
|
||||
`설치시작년도 >= '${startDate}' and 설치시작년도 <= '${endDate}'`,
|
||||
`instl_ymd >= '${startDate}' and instl_ymd <= '${endDate}'`,
|
||||
);
|
||||
if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
if (변수2) cqlFilters.push(`용도코드='${변수2}'`);
|
||||
// if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
if (변수2) cqlFilters.push(`usg_cd='${변수2}'`);
|
||||
// 구경(mm) 범위
|
||||
if (시작1 && 종료1) cqlFilters.push(`구경 BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`구경 >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`구경 <= ${종료1}`);
|
||||
if (시작1 && 종료1) cqlFilters.push(`swage_mh_diam BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`swage_mh_diam >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`swage_mh_diam <= ${종료1}`);
|
||||
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 하수펌프장용 CQL 필터 생성
|
||||
const psmtnCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
@@ -344,22 +439,23 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
`${todayYear}${todayMonth}${todayDate}`,
|
||||
);
|
||||
cqlFilters.push(
|
||||
`설치시작년도 >= '${startDate}' and 설치시작년도 <= '${endDate}'`,
|
||||
`instl_ymd >= '${startDate}' and instl_ymd <= '${endDate}'`,
|
||||
);
|
||||
if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
// if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
// 일일처리용량 범위
|
||||
if (시작1 && 종료1)
|
||||
cqlFilters.push(`일일처리용량 BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`일일처리용량 >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`일일처리용량 <= ${종료1}`);
|
||||
cqlFilters.push(`daily_prcs_cpct BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`daily_prcs_cpct >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`daily_prcs_cpct <= ${종료1}`);
|
||||
// 우수양수능력 범위
|
||||
if (시작2 && 종료2)
|
||||
cqlFilters.push(`우수양수능력 BETWEEN ${시작2} AND ${종료2}`);
|
||||
else if (시작2) cqlFilters.push(`우수양수능력 >= ${시작2}`);
|
||||
else if (종료2) cqlFilters.push(`우수양수능력 <= ${종료2}`);
|
||||
cqlFilters.push(`excln_wpmp_ablt BETWEEN ${시작2} AND ${종료2}`);
|
||||
else if (시작2) cqlFilters.push(`excln_wpmp_ablt >= ${시작2}`);
|
||||
else if (종료2) cqlFilters.push(`excln_wpmp_ablt <= ${종료2}`);
|
||||
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 우수토실용 CQL 필터 생성
|
||||
const otflCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
@@ -377,18 +473,19 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
`${todayYear}${todayMonth}${todayDate}`,
|
||||
);
|
||||
cqlFilters.push(
|
||||
`설치시작년도 >= '${startDate}' and 설치시작년도 <= '${endDate}'`,
|
||||
`instl_ymd >= '${startDate}' and instl_ymd <= '${endDate}'`,
|
||||
);
|
||||
if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
if (변수2) cqlFilters.push(`하천명 ILIKE '%${변수1}%'`);
|
||||
// if (변수1) cqlFilters.push(`경과년도='${변수1}'`);
|
||||
// if (변수2) cqlFilters.push(`하천명 ILIKE '%${변수1}%'`);
|
||||
// 계획방류량 범위
|
||||
if (시작1 && 종료1)
|
||||
cqlFilters.push(`계획방류량 BETWEEN ${시작1} AND ${종료1}`);
|
||||
else if (시작1) cqlFilters.push(`계획방류량 >= ${시작1}`);
|
||||
else if (종료1) cqlFilters.push(`계획방류량 <= ${종료1}`);
|
||||
// if (시작1 && 종료1)
|
||||
// cqlFilters.push(`계획방류량 BETWEEN ${시작1} AND ${종료1}`);
|
||||
// else if (시작1) cqlFilters.push(`계획방류량 >= ${시작1}`);
|
||||
// else if (종료1) cqlFilters.push(`계획방류량 <= ${종료1}`);
|
||||
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 운영정보용 CQL 필터 생성
|
||||
const operationCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
@@ -410,73 +507,17 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
);
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 하수도정비기본계획보고서용 CQL 필터 생성
|
||||
const reportCqlFilters = () => {
|
||||
const cqlFilters: string[] = [];
|
||||
// 설치년도 범위
|
||||
if (시도) cqlFilters.push(`ctpv_cd='${시도}'`);
|
||||
if (시군구) cqlFilters.push(`sgg_cd='${시군구}'`);
|
||||
if (처리구역) cqlFilters.push(`처리구역='${처리구역}'`);
|
||||
if (변수1) cqlFilters.push(`처리구역코드='${변수1}'`);
|
||||
const startDate = getDateString(
|
||||
yearFilter.시작,
|
||||
가동개시_시작_월,
|
||||
가동개시_시작_일,
|
||||
"19000101",
|
||||
);
|
||||
const endDate = getDateString(
|
||||
yearFilter.종료,
|
||||
가동개시_종료_월,
|
||||
가동개시_종료_일,
|
||||
`${todayYear}${todayMonth}${todayDate}`,
|
||||
);
|
||||
cqlFilters.push(
|
||||
`설치시작년도 >= '${startDate}' and 설치시작년도 <= '${endDate}'`,
|
||||
);
|
||||
if (ctpvCd) cqlFilters.push(`ctpv_cd='${ctpvCd}'`);
|
||||
if (sigungu) cqlFilters.push(`sgg_cd='${sigungu}'`);
|
||||
|
||||
return cqlFilters;
|
||||
};
|
||||
|
||||
// 검색 API 호출 함수
|
||||
const fetchFilteredData = async () => {
|
||||
setIsLoading(true); // 로딩 시작
|
||||
try {
|
||||
const queryParams = new URLSearchParams({
|
||||
lyrTypeNm: basicType,
|
||||
page: `${curPage - 1}`,
|
||||
size: '10',
|
||||
sort: 'string',
|
||||
});
|
||||
|
||||
let cqlFilters: string[] = [];
|
||||
if (activeTab === 'basic') {
|
||||
if (basicType === 'tb_ms_swage_prcs_zone') cqlFilters = zoneCqlFilters();
|
||||
else if (basicType === 'tb_il_swage_prcs_fclt') cqlFilters = facilityCqlFilters();
|
||||
else if (basicType === 'tb_ms_swage_ppl') cqlFilters = pplCqlFilters();
|
||||
} else if (activeTab === 'operation') {
|
||||
cqlFilters = zoneCqlFilters();
|
||||
} else {
|
||||
cqlFilters = reportCqlFilters();
|
||||
}
|
||||
|
||||
if (cqlFilters.length > 0) queryParams.append('cqlFiter', cqlFilters.join(' and '));
|
||||
|
||||
console.log('API URL:', `${API_URL}/v1/fclts?${queryParams.toString()}`);
|
||||
const res = await axios.get(`${API_URL}/v1/fclts?${queryParams.toString()}`);
|
||||
console.log('필터링된 API 결과(개수):', res.data.count);
|
||||
console.log('필터링된 API 결과(데이터):', res.data.data);
|
||||
|
||||
setTableData(res.data.data || []);
|
||||
setTableCount(res.data.count || []);
|
||||
console.log('tableCount 상태 업데이트 후:', res.data.count); // tableCount 로그 추가
|
||||
setShowTable(true);
|
||||
} catch (err) {
|
||||
console.error('API ERROR:', err);
|
||||
setTableData([]);
|
||||
} finally {
|
||||
setIsLoading(false); // 로딩 종료
|
||||
}
|
||||
};
|
||||
|
||||
const renderBody = () => (
|
||||
<>
|
||||
{/* 탭 영역 */}
|
||||
@@ -527,7 +568,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
/>
|
||||
|
||||
{/* 경과년도 */}
|
||||
<div className="flex items-center">
|
||||
{/* <div className="flex items-center">
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
경과년도
|
||||
</Label>
|
||||
@@ -541,7 +582,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div> */}
|
||||
{/* 용도코드 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
용도코드
|
||||
@@ -702,13 +743,13 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
<div className="mb-3">
|
||||
<div className="mb-2 flex items-center">
|
||||
<SidoSigunguSelectBox
|
||||
sido={시도}
|
||||
sigungu={시군구}
|
||||
sido={ctpvCd}
|
||||
sigungu={sigungu}
|
||||
onSidoChange={(sidoId) => {
|
||||
set시도(sidoId);
|
||||
set시군구(0);
|
||||
setCtpvCd(sidoId);
|
||||
setSigungu(0);
|
||||
}}
|
||||
onSigunguChange={set시군구}
|
||||
onSigunguChange={setSigungu}
|
||||
/>
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
하수처리구역명
|
||||
@@ -736,7 +777,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{/* 분기처리: 하수맨홀 */}
|
||||
{basicType === "tb_ms_swage_mh" && (
|
||||
{basicType === "tb_ms_swage_mhl" && (
|
||||
<div className="mb-3">
|
||||
<div className="mb-2 flex items-center">
|
||||
{/* 설치년도 */}
|
||||
@@ -754,7 +795,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
endLabel=""
|
||||
/>
|
||||
{/* 경과년도 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
{/* <Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
경과년도
|
||||
</Label>
|
||||
<Input
|
||||
@@ -766,9 +807,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
const val = e.target.value.replace(/[^0-9]/g, "");
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center mb-2'>
|
||||
/> */}
|
||||
{/* 용도코드 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
용도코드
|
||||
@@ -812,8 +851,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{/* 분기처리: 하수펌프장 */}
|
||||
{(basicType === "tb_ms_swage_psmtn_1" ||
|
||||
basicType === "tb_ms_swage_psmtn_2") && (
|
||||
{basicType === "tb_ms_swage_pmstn" && (
|
||||
<div className="mb-3">
|
||||
{/* 설치년도 */}
|
||||
<div className="flex items-center mb-2">
|
||||
@@ -825,19 +863,17 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
endLabel=""
|
||||
/>
|
||||
{/* 경과년도 */}
|
||||
<Label className="w-auto text-xl text-gray-600 mr-2">경과년도</Label>
|
||||
<Input
|
||||
className='!text-xl w-[100px] placeholder:text-center mr-8'
|
||||
placeholder="입력"
|
||||
value={yearFilter.경과년도}
|
||||
onChange={(e) => {
|
||||
// 숫자만 입력 허용
|
||||
const val = e.target.value.replace(/[^0-9]/g, '');
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center mb-2">
|
||||
{/* <Label className="w-auto text-xl text-gray-600 mr-2">경과년도</Label>
|
||||
<Input
|
||||
className='!text-xl w-[100px] placeholder:text-center mr-8'
|
||||
placeholder="입력"
|
||||
value={yearFilter.경과년도}
|
||||
onChange={(e) => {
|
||||
// 숫자만 입력 허용
|
||||
const val = e.target.value.replace(/[^0-9]/g, '');
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/> */}
|
||||
{/* 일일처리용량 - 오수맨홀 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
일일처리용량
|
||||
@@ -892,7 +928,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{/* 분기처리: 우수토실? 토구? */}
|
||||
{basicType === "tb_ms_otfl" && (
|
||||
{basicType === "tb_ms_stofcbr" && (
|
||||
<div className="mb-3">
|
||||
{/* 설치년도 */}
|
||||
<div className="flex items-center mb-2">
|
||||
@@ -904,7 +940,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
endLabel=""
|
||||
/>
|
||||
{/* 경과년도 */}
|
||||
<Label className="w-auto text-xl text-gray-600 mr-2">경과년도</Label>
|
||||
{/* <Label className="w-auto text-xl text-gray-600 mr-2">경과년도</Label>
|
||||
<Input
|
||||
className='!text-xl w-[100px] placeholder:text-center mr-8'
|
||||
placeholder="입력"
|
||||
@@ -914,11 +950,9 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
const val = e.target.value.replace(/[^0-9]/g, '');
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center mb-2">
|
||||
/> */}
|
||||
{/* 하천명 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
{/* <Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
하천명
|
||||
</Label>
|
||||
<Input
|
||||
@@ -928,9 +962,9 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
onChange={(e) => {
|
||||
set변수1(e.target.value);
|
||||
}}
|
||||
/>
|
||||
/> */}
|
||||
{/* 계획방류량 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
{/* <Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
계획방류량
|
||||
</Label>
|
||||
<Input
|
||||
@@ -953,7 +987,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
const val = e.target.value.replace(/[^0-9]/g, "");
|
||||
set종료1(val);
|
||||
}}
|
||||
/>
|
||||
/> */}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -966,7 +1000,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
)}
|
||||
{/* 운영정보 탭 */}
|
||||
{activeTab === 'operation' && (
|
||||
<div className="relative flex flex-col border rounded-lg p-6 mb-4 w-full h-[23vh]">
|
||||
<div className="relative flex flex-col border rounded-lg p-6 mt-4 w-full h-[23vh]">
|
||||
<div className="flex items-center mb-6">
|
||||
<SelectBox2
|
||||
className="w-60 mr-8"
|
||||
@@ -980,76 +1014,77 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
value={workType}
|
||||
/>
|
||||
|
||||
{/* 설치년도 */}
|
||||
<YearRangeSelectBox
|
||||
start={yearFilter.시작}
|
||||
end={yearFilter.종료}
|
||||
onChange={(range) =>
|
||||
setYearFilter({
|
||||
...yearFilter,
|
||||
시작: range.start,
|
||||
종료: range.end,
|
||||
})
|
||||
}
|
||||
startLabel="설치년도"
|
||||
endLabel=""
|
||||
/>
|
||||
<div className="flex items-center">
|
||||
{/* 경과년도 */}
|
||||
<Label className="mr-2 w-auto text-xl text-gray-600">
|
||||
경과년도
|
||||
</Label>
|
||||
<Input
|
||||
className="mr-8 w-[100px] !text-xl placeholder:text-center"
|
||||
placeholder="입력"
|
||||
value={yearFilter.경과년도}
|
||||
onChange={(e) => {
|
||||
// 숫자만 입력 허용
|
||||
const val = e.target.value.replace(/[^0-9]/g, "");
|
||||
setYearFilter({ ...yearFilter, 경과년도: val });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* 조회 버튼 중앙 정렬 */}
|
||||
<div className="absolute bottom-4 right-4 mr-2">
|
||||
<Button className="text-base py-2" onClick={handleSearch}>조회</Button>
|
||||
</div>
|
||||
{/* 수행기간 */}
|
||||
{/* <YearRangeSelectBox
|
||||
start={yearFilter.시작}
|
||||
end={yearFilter.종료}
|
||||
onChange={(range) =>
|
||||
setYearFilter({
|
||||
...yearFilter,
|
||||
시작: range.start,
|
||||
종료: range.end,
|
||||
})
|
||||
}
|
||||
startLabel="수행기간"
|
||||
endLabel=""
|
||||
/> */}
|
||||
<DatePickerRange
|
||||
mode="single" //고정
|
||||
selected={fromDate} // 처음에 선택할 날짜 - 타입은 date타입
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} // 선택했을 때 이벤트 (주로 set)
|
||||
className="w-full p-1 border rounded bg-white" // 스타일
|
||||
disabled={(date) => !isDateInRanges(date)} // 선택못하게 하는 날짜 - 없으면 안넣어도 됨
|
||||
defaultMonth={fromDate} // 처음에 시작할 날짜 selected랑 같이 같은 날짜 넣으면 됨
|
||||
/>
|
||||
<span className='text-xl m-4'>~</span>
|
||||
<DatePickerRange
|
||||
mode="single" //고정
|
||||
selected={toDate} // 처음에 선택할 날짜 - 타입은 date타입
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} // 선택했을 때 이벤트 (주로 set)
|
||||
className="w-full p-1 border rounded bg-white" // 스타일
|
||||
disabled={(date) => !isDateInRanges(date)} // 선택못하게 하는 날짜 - 없으면 안넣어도 됨
|
||||
defaultMonth={toDate} // 처음에 시작할 날짜 selected랑 같이 같은 날짜 넣으면 됨
|
||||
/>
|
||||
</div>
|
||||
{/* 조회 버튼 중앙 정렬 */}
|
||||
<div className="absolute bottom-4 right-4 mr-2">
|
||||
<Button className="text-base py-2" onClick={handleSearch}>조회</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 하수도정비기본계획보고서 탭 */}
|
||||
{activeTab === 'report' && (
|
||||
<div className="relative flex flex-col border rounded-lg p-6 mb-4 w-full h-[23vh]">
|
||||
<div className="relative flex flex-col border rounded-lg p-6 mt-4 w-full h-[23vh]">
|
||||
{/* 시도, 시군구, 하수처리구역 한 줄 */}
|
||||
<div className="mb-6 flex items-center">
|
||||
<SidoSigunguSelectBox
|
||||
sido={시도}
|
||||
sigungu={시군구}
|
||||
onSidoChange={(sidoId) => {
|
||||
set시도(sidoId);
|
||||
set시군구(0);
|
||||
}}
|
||||
onSigunguChange={set시군구}
|
||||
/>
|
||||
<SelectBox2
|
||||
className="w-[150px] mr-8"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label="시도"
|
||||
selectArray={sidos}
|
||||
value={ctpvCd}
|
||||
onSelectValue={handleCtpvCdChange}
|
||||
/>
|
||||
<SelectBox2
|
||||
className="w-48"
|
||||
selectClass="w-48 rounded-lg bg-white truncate"
|
||||
label="시군구"
|
||||
selectArray={filteredSiguns}
|
||||
value={sigungu}
|
||||
onSelectValue={val => setSigungu(String(val))}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<SelectBox2
|
||||
className="w-auto mr-2"
|
||||
selectClass="rounded-lg bg-white text-xl"
|
||||
label="하수처리구역"
|
||||
selectArray={처리구역List.map(opt => ({ val: opt.val, text: opt.text }))}
|
||||
onSelectValue={val => set처리구역(String(val))}
|
||||
value={처리구역}
|
||||
/>
|
||||
<label className="inline-block w-auto whitespace-nowrap text-xl text-gray-600 mr-2">구분</label>
|
||||
<Input
|
||||
className='!text-xl w-[100px] placeholder:text-center mr-8'
|
||||
placeholder="입력"
|
||||
value={변수1}
|
||||
value={gubun}
|
||||
onChange={(e) => {
|
||||
// 숫자만 입력 허용
|
||||
const val = e.target.value.replace(/[^0-9]/g, '');
|
||||
set변수1(val);
|
||||
const val = e.target.value;
|
||||
setGubun(val);
|
||||
}}
|
||||
/>
|
||||
<YearRangeSelectBox
|
||||
@@ -1060,6 +1095,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
endLabel=""
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 조회 버튼 중앙 정렬 */}
|
||||
<div className="absolute bottom-4 right-4 mr-2">
|
||||
<Button className="text-base py-2" onClick={handleSearch}>조회</Button>
|
||||
@@ -1071,40 +1107,39 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
|
||||
{/* 📋 결과 리스트 */}
|
||||
<div className="h-[60vh] w-full space-y-2 overflow-hidden rounded-lg border">
|
||||
{/* 테이블 영역 (가로/세로 스크롤 가능) */}
|
||||
<div className="flex-1 px-2 pb-2">
|
||||
<LoadingOverlay isLoading={isLoading}/>
|
||||
<UiTable2
|
||||
headName={
|
||||
(() => {
|
||||
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})건
|
||||
</>
|
||||
);
|
||||
})()
|
||||
}
|
||||
{/* 테이블 영역 (가로/세로 스크롤 가능) */}
|
||||
<div className="flex-1 px-2 pb-2">
|
||||
<LoadingOverlay isLoading={isLoading} />
|
||||
<UiTable2
|
||||
headName={
|
||||
(() => {
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1121,6 +1156,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
|
||||
z-[101]
|
||||
`}
|
||||
body={renderBody()}
|
||||
useDirectRender={true}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -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<CityCdStore>((set) => ({
|
||||
cityCd: '',
|
||||
setCityCd: (cityCd: string) => set({ cityCd }),
|
||||
sidos: [],
|
||||
setSidos: (sidos: SelectDataType[]) => set({ sidos }),
|
||||
siguns: [],
|
||||
setSiguns: (siguns: SelectDataType[]) => set({ siguns }),
|
||||
}));
|
||||
@@ -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<InputSectionProps> = ({ title, data, sectionKey, onInputChange }) => {
|
||||
return (
|
||||
<div>
|
||||
{/* 섹션 제목 */}
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">{title}</h3>
|
||||
</div>
|
||||
{/* 테이블 */}
|
||||
<div className="card !m-[1.2rem] !p-0r">
|
||||
<Table variant="secondary" className="w-full">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-[80px]">년도</TableHead>
|
||||
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-auto">구분</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.map((row, index) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell className="border border-gray-300 px-2 py-2 text-sm w-[80px]">
|
||||
<input
|
||||
type="text"
|
||||
value={row.year}
|
||||
onChange={(e) => onInputChange(sectionKey, index, "year", e.target.value)}
|
||||
className="w-full text-xl border-radius-0 px-3 py-2 text-base text-center leading-normal"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="border border-gray-300 px-2 py-2 text-sm text-center leading-normal w-auto">
|
||||
{row.type}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InputSection;
|
||||
@@ -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<LayerComponentProps>;
|
||||
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<LayerComponentProps> | 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<React.SetStateAction<{ year: string; type: string }[]>>;
|
||||
};
|
||||
}
|
||||
) => {
|
||||
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);
|
||||
};
|
||||
@@ -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'
|
||||
];
|
||||
@@ -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<any>({});
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
<InputSection
|
||||
title="보수 및 갱신"
|
||||
data={repairData}
|
||||
sectionKey="repair"
|
||||
onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)}
|
||||
/>
|
||||
<InputSection
|
||||
title="청소 및 준설"
|
||||
data={cleaningData}
|
||||
sectionKey="cleaning"
|
||||
onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)}
|
||||
/>
|
||||
<InputSection
|
||||
title="점검 및 진단"
|
||||
data={inspectionData}
|
||||
sectionKey="inspection"
|
||||
onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default MsSwagePpl
|
||||
@@ -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<any>({});
|
||||
const [mntrngsData, setMntrngsData] = useState<any[]>([]); // 수량/수질 측정 정보
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number>(-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 = () => (
|
||||
<div className='grid grid-cols-1 gap-4 p-4'>
|
||||
{/* 강우정보 테이블 */}
|
||||
<UiTable
|
||||
headName='강우정보'
|
||||
tableData={Array.isArray(rainMeasureData) ? rainMeasureData : []}
|
||||
headlist={untrtSwgRainCol3}
|
||||
pageSize={10}
|
||||
total={Array.isArray(rainMeasureData) ? rainMeasureData.length : 0}
|
||||
cellClick={handleCellClick}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Rain data page change:', page);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 측정정보 테이블 */}
|
||||
<UiTable
|
||||
headName='측정정보'
|
||||
tableData={Array.isArray(rainMeasureData) ? rainMeasureData : []}
|
||||
headlist={untrtSwgRainCol4}
|
||||
pageSize={10}
|
||||
total={Array.isArray(rainMeasureData) ? rainMeasureData.length : 0}
|
||||
cellClick={handleCellClick}
|
||||
// onPageChange={setCurPage}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Rain data page change:', page);
|
||||
}}
|
||||
resetPageNo={false}
|
||||
// index={curPage}
|
||||
>
|
||||
{/* 커스텀 헤더 */}
|
||||
<TableRow>
|
||||
<TableHead colSpan={5} className="text-center bg-blue-100 font-bold">수량</TableHead>
|
||||
<TableHead colSpan={3} className="text-center bg-blue-100 font-bold">수질</TableHead>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableHead className="text-center">측정시작일시</TableHead>
|
||||
<TableHead className="text-center">측정종료일시</TableHead>
|
||||
<TableHead className="text-center">측정간격(분)</TableHead>
|
||||
<TableHead className="text-center">측정기기설치위치</TableHead>
|
||||
<TableHead className="text-center">유량계 종류 및 모델명</TableHead>
|
||||
<TableHead className="text-center">채수시작일시</TableHead>
|
||||
<TableHead className="text-center">채수종료일시</TableHead>
|
||||
<TableHead className="text-center">채수횟수</TableHead>
|
||||
</TableRow>
|
||||
</UiTable>
|
||||
|
||||
{/* 수량/수질측정 정보 테이블 */}
|
||||
<UiTable
|
||||
headName='수량/수질측정 정보'
|
||||
tableData={Array.isArray(mntrngsData) ? mntrngsData : []}
|
||||
headlist={untrtSwgRainCol5}
|
||||
pageSize={10}
|
||||
total={Array.isArray(mntrngsData) ? mntrngsData.length : 0}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Quality data page change:', page);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!isMainSsc && (
|
||||
<VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
)}
|
||||
|
||||
{isMainSsc && (
|
||||
<div>
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">중점우수토실 운영정보</h3>
|
||||
</div>
|
||||
<Button
|
||||
className='mx-auto block w-64 mt-3 py-2 text-white rounded-sm text-sm font-medium hover:bg-blue-700 bg-blue-600'
|
||||
onClick={openModal}
|
||||
>
|
||||
상세보기
|
||||
</Button>
|
||||
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
bodyClass={`
|
||||
h-[100vh]
|
||||
w-[60vw]
|
||||
max-w-none
|
||||
max-h-none
|
||||
overflow-visible
|
||||
z-[101]
|
||||
`}
|
||||
body={renderModalBody()}
|
||||
noHeaderYn='Y'
|
||||
noFooterYn='N'
|
||||
// footerContent={renderFooterContent()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Ssc
|
||||
@@ -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<string>('');
|
||||
const openModal = (title: string) => {
|
||||
setIsModalOpen(true);
|
||||
setModalTitle(title)
|
||||
};
|
||||
const closeModal = () => {
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
return (
|
||||
<div>
|
||||
<VerticalTable children={{
|
||||
title: <Button onClick={() => openModal('하수도정비 기본계획보고서')}>보고서</Button>,
|
||||
cad: <Button onClick={() => openModal('하수도대장 평면도')}>평면도</Button>,
|
||||
}} headName='디지털 자료관 연계정보' tableData={[]} headlist={headList} pageSize={20} total={0} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}></VerticalTable>
|
||||
<Modal isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} closeModal={closeModal}>
|
||||
<div className='grid grid-col-2'>
|
||||
<UiTable headName={modalTitle} tableData={[]} headlist={modalHeadList} pageSize={20} total={0} cellClick={undefined} children={undefined} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}
|
||||
}></UiTable>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SwtrmtFclt
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
@@ -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<HTMLButtonElement>(null); // 버튼 참조
|
||||
const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
|
||||
const [selectedAplcnYm, setSelectedAplcnYm] = useState("");
|
||||
const [inftwtAnlss, setInftwtAnlss] = useState<TInftwtAnls[]>([]);
|
||||
const [inftwtAnlsInfos, setInftwtAnlsInfos] = useState<any[]>([{ val: 0, text: '선택' }]); // 침입수분석정보 options
|
||||
const [inftwtAnls, setInftwtAnls] = useState<TInftwtAnls | null>(null); // 침입수분석정보
|
||||
const [selectedInftwtAnls, setSelectedInftwtAnls] = useState<number>(0); // 침입수분석 정보 선택시 사용
|
||||
const [chartData, setChartData] = useState<{ chartData1: DataType[]; chartData2: DataType[] }>({
|
||||
chartData1: [], chartData2: [],
|
||||
});
|
||||
const [inftwtQty, setInftwtQty] = useState<number>(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 = () => (
|
||||
<>
|
||||
<div className="text-black text-3xl font-bold mb-5">침입수분석결과</div>
|
||||
|
||||
<div className='grid grid-cols-[1fr_3fr] gap-4'>
|
||||
<div className="h-[90%] grid grid-rows-4 gap-4 mb-4">
|
||||
<Button className="bg-white text-white w-[130px] font-bold px-4 mt-2 py-2" onClick={openPopup}>
|
||||
분석 입력현황 조회
|
||||
</Button>
|
||||
{/* 상수사용량 적용연월 */}
|
||||
<div className="bg-white px-4 py-2 ">
|
||||
<span className="text-2xl text-red-600 font-bold">상수사용량 적용연월</span>
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">
|
||||
{(selectedAplcnYm) ? moment(selectedAplcnYm, "YYYYMM").format("YYYY-MM") : ""}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/* 침입수량 분석결과 */}
|
||||
<div className="bg-white px-4 py-2 ">
|
||||
<span className="text-2xl text-red-600 font-bold">침입수량 분석결과</span>
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">{inftwtQty}</span>
|
||||
<span className="ml-2 text-black text-xl">m³/d</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 차트 */}
|
||||
<div className="h-[90%] bg-white text-3xl">
|
||||
<MainChart chartConfig={chartConfig} chartForm={chartForm} chartData={chartData} chartTitle={'관로유량'}
|
||||
yFieldText2="시간" yFieldText="유량(m³/h)"/>
|
||||
</div>
|
||||
</div>
|
||||
{popupOpen && (
|
||||
<div
|
||||
className="absolute bg-gray-100 border border-gray-300 w-[440px] shadow-lg p-6 rounded text-2xl"
|
||||
style={{
|
||||
top: popupPosition.top,
|
||||
left: popupPosition.left,
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<div className="font-bold mb-6 text-3xl">침입수분석 입력현황</div>
|
||||
<div className='flex flex-col'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">상수사용월:</Label>
|
||||
<SelectBox
|
||||
className="w-[220px] mr-8 z-[51] mb-2"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=''
|
||||
selectArray={aplcnYms}
|
||||
value={selectedAplcnYm}
|
||||
onSelectValue={handleAplcnYmChange}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">분석정보:</Label>
|
||||
<SelectBox
|
||||
className="w-[220px] mr-8 z-[51] mb-2"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=''
|
||||
selectArray={inftwtAnlsInfos}
|
||||
value={selectedInftwtAnls}
|
||||
onSelectValue={handleInftwtAnlsSnChange}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">오수전환율:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={inftwtAnls?.drtwSwtcRt ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">시간패턴 파일명:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={inftwtAnls?.atflHrPttnNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">수용가-맨홀 매칭:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={inftwtAnls?.atflMpngNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">관망도 파일명:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={inftwtAnls?.atflInpNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">유량 파일명:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={inftwtAnls?.atflOilqNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end mt-4 space-x-2">
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closePopup}>
|
||||
분석결과 도표
|
||||
</button>
|
||||
</div>
|
||||
</div>)}
|
||||
{/* </Modal > */}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
headerTitle=""
|
||||
bodyClass={`
|
||||
min-h-[50vh]
|
||||
w-[50vw]
|
||||
max-w-none
|
||||
max-h-none
|
||||
overflow-visible
|
||||
z-[50]
|
||||
`}
|
||||
body={renderBody()}
|
||||
noFooterYn='Y'
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(InfilChart);
|
||||
@@ -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<HTMLButtonElement>(null); // 버튼 참조
|
||||
const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
|
||||
const [aplcnYm, setAplcnYm] = useState("");
|
||||
const [rdiiAnlss, setRdiiAnlss] = useState<TRdiiAnls[]>([]);
|
||||
const [rdiiAnlsInfos, setRdiiAnlsInfos] = useState<any[]>([{ val: 0, text: '선택' }]); // 강우유입수분석정보 options
|
||||
const [rdiiAnls, setRdiiAnls] = useState<TRdiiAnls | null>(null); // 강우유입수분석정보
|
||||
const [rainInfwtAnlsSn, setRainInfwtAnlsSn] = useState<number>(0); // 강우유입수분석 정보 선택시 사용
|
||||
const [chartData, setChartData] = useState<{ chartData1: DataType[]; }>({
|
||||
chartData1: [], //chartData2: [],
|
||||
});
|
||||
const [rdiiQty, setRdiiQty] = useState<number>(0); // 강우유입수량
|
||||
const [totalVolume, setTotalVolume] = useState<number>(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 = () => (
|
||||
<>
|
||||
<div className="text-black text-3xl font-bold mb-5">RDII분석결과</div>
|
||||
|
||||
<div className='grid grid-cols-[1fr_3fr] gap-4'>
|
||||
<div className="grid grid-rows-4 gap-4 mb-4">
|
||||
<Button className="bg-white text-white w-[130px] font-bold px-4 mt-2 py-2" onClick={openPopup}>
|
||||
분석 입력현황 조회
|
||||
</Button>
|
||||
{/* 상수사용량 적용연월 */}
|
||||
<div className="bg-white px-4 py-2 ">
|
||||
<span className="text-2xl text-red-600 font-bold">상수사용량 적용연월</span>
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">
|
||||
{(aplcnYm)? moment(aplcnYm, "YYYYMM").format("YYYY-MM"):""}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 강우유입수량 분석결과 */}
|
||||
<div className="bg-white px-4 py-2 ">
|
||||
<span className="text-2xl text-red-600 font-bold">강우유입수량 분석결과</span>
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">{rdiiQty}</span>
|
||||
<span className="ml-2 text-black">m³/d</span>
|
||||
</div>
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">{totalVolume}</span>
|
||||
<span className="ml-2 text-black">m³/mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 차트 */}
|
||||
<div className="h-[90%] bg-white text-2xl">
|
||||
<MainChart chartConfig={chartConfig} chartForm={chartForm} chartData={chartData} chartTitle={'관로유량'}
|
||||
yFieldText2="시간" yFieldText="유량(m³/h)" />
|
||||
</div>
|
||||
</div>
|
||||
{popupOpen && (
|
||||
<div
|
||||
className="absolute bg-gray-100 border border-gray-300 w-[440px] shadow-lg p-6 rounded text-2xl"
|
||||
style={{
|
||||
top: popupPosition.top,
|
||||
left: popupPosition.left,
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<div className="font-bold mb-6 text-3xl">강우유입수분석 입력현황</div>
|
||||
<div className='flex flex-col'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">상수사용월:</Label>
|
||||
<SelectBox
|
||||
className="w-[220px] mr-8 z-[51] mb-2"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=''
|
||||
selectArray={aplcnYms}
|
||||
value={aplcnYm}
|
||||
onSelectValue={(val) => {
|
||||
setAplcnYm(String(val));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">분석정보:</Label>
|
||||
<SelectBox
|
||||
className="w-[220px] mr-8 z-[51] mb-2"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=''
|
||||
selectArray={rdiiAnlsInfos}
|
||||
value={rainInfwtAnlsSn}
|
||||
onSelectValue={(val) => {
|
||||
setRainInfwtAnlsSn(Number(val));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">오수전환율:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={rdiiAnls?.drtwSwtcRt ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">수용가-맨홀 매칭:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={rdiiAnls?.atflMpngNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">관망도 파일명:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={rdiiAnls?.atflInpNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">강우 파일명:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={rdiiAnls?.atflRainNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className="mr-2 w-auto text-2xl text-gray-600 whitespace-nowrap">RTK계수 출처:</Label>
|
||||
<Input
|
||||
className="mr-8 w-[220px] !text-xl placeholder:text-center mb-2"
|
||||
placeholder=""
|
||||
value={rdiiAnls?.srcNm ?? ""}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end mt-4 space-x-2">
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closePopup}>
|
||||
분석결과 도표
|
||||
</button>
|
||||
</div>
|
||||
</div>)}
|
||||
{/* </Modal > */}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
headerTitle=""
|
||||
bodyClass={`
|
||||
min-h-[50vh]
|
||||
w-[50vw]
|
||||
max-w-none
|
||||
max-h-none
|
||||
overflow-visible
|
||||
z-[50]
|
||||
`}
|
||||
body={renderBody()}
|
||||
noFooterYn = 'Y'
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(RdiiChart);
|
||||
@@ -0,0 +1,16 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
interface ModalStore {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export const useInfilChartModalStore = create<ModalStore>((set) => ({
|
||||
isOpen: false,
|
||||
setIsOpen: (open: boolean) => set({ isOpen: open }),
|
||||
}));
|
||||
|
||||
export const useRdiiChartModalStore = create<ModalStore>((set) => ({
|
||||
isOpen: false,
|
||||
setIsOpen: (open: boolean) => set({ isOpen: open }),
|
||||
}));
|
||||
@@ -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<any>({});
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={isDrtwSewagePump ? drtwInputColumn : exclnInputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default sewagePump
|
||||
@@ -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<any>({});
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Smh;
|
||||
@@ -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<string, any> }) => {
|
||||
const validKey = inputColumn.map((item) => item.id);
|
||||
const filteredData = featureData && Object.entries(featureData).filter(([key]) => validKey.includes(key)).reduce((obj: Record<string, any>, [key, value]) => { obj[key] = value; return obj; }, {});
|
||||
return (
|
||||
<VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={[filteredData]}
|
||||
headlist={inputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default StormWaterPump
|
||||
@@ -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<SelectDataType[]> => {
|
||||
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<SelectDataType[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetch = async () => {
|
||||
const result = await getSggCd();
|
||||
if (result) {
|
||||
setData(result);
|
||||
}
|
||||
};
|
||||
fetch();
|
||||
console.log("useSggCd호출");
|
||||
}, []);
|
||||
return data;
|
||||
};
|
||||
|
||||
// 시군구 데이터
|
||||
export const getSggCd = async (): Promise<SelectDataType[]> => {
|
||||
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<SelectDataType[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetch = async () => {
|
||||
const result = await getCityCd();
|
||||
if (result) {
|
||||
setData(result);
|
||||
}
|
||||
};
|
||||
fetch();
|
||||
console.log("useCityCd호출");
|
||||
}, []);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -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<number[]>; treeData: { lyrSn: number }[] | null; gisCore: any; gisMap: any; };
|
||||
const [layerNm, setLayerNm] = useState<string>(""); // 레이어 이름 상태
|
||||
const [tableData, setTableData] = useState<any>(null); // 피처 데이터
|
||||
const [rainMeasureData, setRainMeasureData] = useState<any[]>([]); // 강우/측정 측정 정보
|
||||
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<any>(); // api 호출여부
|
||||
const contentRef = useRef<HTMLDivElement>(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<string, any> = {}
|
||||
|
||||
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 (
|
||||
<div id="popup" className="absolute top-0 right-0 w-[350px] h-[calc(100vh-10rem)] bg-white border-r border-gray-300 flex flex-col overflow-hidden transition-all duration-300 z-[50]">
|
||||
<div className="card-header bg-primary flex items-center justify-between p-4">
|
||||
<div className="flex items-center">
|
||||
<h3 className="text-2xl font-medium text-white text-label whitespace-nowrap">{layerNm} 정보</h3>
|
||||
{/* <div className="font-medium text-white text-label">(00구 00리 하수관로)</div> */}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
{/* 🎯 하수관로일 때만 Infil/RDII 버튼 표시 */}
|
||||
{layerNm === '하수관로' && (
|
||||
<>
|
||||
<Button onClick={() => setIsModalInfil(true)}
|
||||
className="px-2 py-1 text-xl text-blue-600 border border-blue-600 rounded hover:bg-gray-700"
|
||||
color="white"
|
||||
>
|
||||
침입수분석
|
||||
</Button>
|
||||
<Button onClick={() => setIsModalRdii(true)}
|
||||
className="px-2 py-1 text-xl text-gray-600 border border-gray-600 rounded hover:bg-gray-700"
|
||||
color="white"
|
||||
>
|
||||
RDII분석
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className="text-white hover:text-gray-300 focus:outline-none ml-2"
|
||||
>
|
||||
✕
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-y-auto overflow-x-hidden flex-1" ref={contentRef}>
|
||||
<VerticalTable
|
||||
headName='기본정보'
|
||||
tableName1={layerNm === '중점우수토실' ? "측정지점" : undefined}
|
||||
tableData={[tableData]}
|
||||
headlist={headlist}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
// 두 번째 테이블 조건부 props
|
||||
showSecondTable={layerNm === '중점우수토실' ? true : false}
|
||||
tableName2={layerNm === '중점우수토실' ? "시설현황" : undefined}
|
||||
tableData2={layerNm === '중점우수토실' && tableData ? [tableData] : []}
|
||||
headlist2={layerNm === '중점우수토실' ? headlist2 : undefined}
|
||||
pageSize2={20}
|
||||
total2={0}
|
||||
isEditable2={buttonChk}
|
||||
/>
|
||||
<Modal isModalOpen={isModalOpen} title="자체입력정보 저장" setIsModalOpen={setIsModalOpen} closeModal={handleModalClose} saveModal={handleModalSave}><div className="text-lg">정보를 저장하시겠습니까?</div></Modal>
|
||||
{ContentComponent &&
|
||||
<ContentComponent
|
||||
featureData={tableData}
|
||||
isMainSsc={isMainSsc}
|
||||
isDrtwSewagePump={isDrtwSewagePump}
|
||||
rainMeasureData={rainMeasureData}
|
||||
onSaveClick={handleSaveClick}
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* 🎯 InfilChart 및 RdiiChart 컴포넌트 추가 */}
|
||||
<InfilChart pplMngNo={pplMngNo} />
|
||||
<RdiiChart pplMngNo={pplMngNo} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default FeatureClickEventPopup;
|
||||
@@ -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}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -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']
|
||||
};
|
||||
@@ -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<void>;
|
||||
}
|
||||
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<ApiSelectOption[]>([]);
|
||||
const [treatmentFacilityOptions, setTreatmentFacilityOptions] = useState<ApiSelectOption[]>([]);
|
||||
const [isLoadingAreaData, setIsLoadingAreaData] = useState<boolean>(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 (
|
||||
<Form {...form} className="min-h-screen flex flex-col">
|
||||
<LoadingOverlay isLoading={isLoading ?? false} />
|
||||
<ListDiv>
|
||||
{/* searchBox.title이 있으면 h3 태그로 제목을 표시합니다. */}
|
||||
{selectBox?.title && (
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl font-medium">{selectBox.title}</h3>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center w-full">
|
||||
{showDatePicker && ( // showDatePicker 값에 따라 DatePicker 렌더링
|
||||
<>
|
||||
<Label className="ml-4 w-20 text-xl text-gray-600 whitespace-nowrap">분석기간</Label>
|
||||
<DateMonthPicker
|
||||
field={{
|
||||
value: aplcnYmFrom || (() => { // aplcnYm이 없으면 현재 연월을 기본값으로 설정
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
return `${year}${month}`;
|
||||
})(), // yyyyMM 형식
|
||||
onChange: (value: string) => {
|
||||
setAplcnYmFrom?.(value); // string 값을 직접 전달
|
||||
}
|
||||
}}
|
||||
selectClass="ml-5 w-[100px]"
|
||||
startYear={1900} // 시작 연도 설정
|
||||
/>
|
||||
<span className="font-semibold text-xl mx-2">~</span>
|
||||
<DateMonthPicker
|
||||
field={{
|
||||
value: aplcnYmTo || (() => { // aplcnYm이 없으면 현재 연월을 기본값으로 설정
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
return `${year}${month}`;
|
||||
})(), // yyyyMM 형식
|
||||
onChange: (value: string) => {
|
||||
setAplcnYmTo?.(value); // string 값을 직접 전달
|
||||
}
|
||||
}}
|
||||
selectClass="ml-5 w-[100px]"
|
||||
startYear={1900} // 시작 연도 설정
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<GovSidoSigunguSearchForm
|
||||
isShowPart={true}
|
||||
setRtnEnvPartValue={(val) => setEnoCd?.(val)}
|
||||
setRtnEnvPartSidoValue={(val) => setCtpvCd?.(val)}
|
||||
setRtnEnvPartSigunValue={setSigungu} // 선택된 시군구 값을 받을 콜백 함수 전달
|
||||
>
|
||||
<SelectBox2 label={"하수처리장"} value={selectedSwageTreatmentPlant} selectArray={treatmentFacilityOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageTreatmentPlantChange?.(val)} />
|
||||
{/* <SelectBox2 label={"하수처리구역"} value={selectedSwageProcessingZone} selectArray={processingZoneOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageProcessingZoneChange?.(val)} /> */}
|
||||
</GovSidoSigunguSearchForm>
|
||||
{selectBox?.searchChk ? <SearchFormRight><Button size="sm" onClick={() => selectBox.onSearchClick?.()}>조회</Button></SearchFormRight> : null}
|
||||
</div>
|
||||
</ListDiv>
|
||||
<ListDiv>
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl font-medium">{titleName.firstCardTitle}</h3>
|
||||
<div>
|
||||
{graphBtn ? <Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile}>파일 다운로드</Button> : null}
|
||||
{/* 그래프 있을 시 */}
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile}>삭제</Button> : null}
|
||||
{/* 분석 버튼 */}
|
||||
{analysisBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={onAnalysis}>{analysisBtn}</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmitEvent)} className="flex-grow flex flex-col">
|
||||
<div className="card !m-[1.2rem] flex-grow flex flex-col">
|
||||
{/* 폼 정보 입력 칸 */}
|
||||
{children?.[0]}
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ListDiv>
|
||||
{
|
||||
children?.[1] != null ? <ListDiv>
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">{titleName?.secondCardTitle}</h3>
|
||||
<div>
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm">파일 다운로드</Button> : null}
|
||||
{/* 그래프 있을 시 */}
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm">삭제</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card !m-[1.2rem]">{children?.[1]}</div>
|
||||
</ListDiv> : null
|
||||
}
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseLayout
|
||||
@@ -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<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
managenm: "",
|
||||
region: "",
|
||||
suyeonga: 0,
|
||||
inputdate: new Date(),
|
||||
rtkSource: "",
|
||||
suyeongaPlace: "",
|
||||
pattern: ""
|
||||
}
|
||||
})
|
||||
|
||||
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
||||
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<ApiSelectOption>({ val: '0', text: '전체' }); // 시군구 상태를 객체로 변경
|
||||
const [select4, setSelect4] = useState<string | number>('0'); // 하수처리장코드
|
||||
const [select5, setSelect5] = useState<string | number>('0'); // 하수처리구역코드
|
||||
const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(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 (
|
||||
<>
|
||||
<BaseLayout
|
||||
titleName={{ mainTitle: '침입수 분석', firstCardTitle: '침입수 분석 자료 입력' }}
|
||||
form={form}
|
||||
onSubmitEvent={() => { }}
|
||||
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}
|
||||
>
|
||||
{[<div key="irsetting-layout-key" className="grid gap-4">
|
||||
<FormSection name='suyeongaPlace' form={form} titleNm='▷ 오수관망도'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".inp"}
|
||||
fileIdx={0} />
|
||||
</FormSection>
|
||||
<FormSection name='suyeonga' form={form} titleNm='▷ 수용가-맨홀 매칭결과'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-1-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(1, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={1} />
|
||||
</FormSection>
|
||||
<FormSection name='pattern' form={form} titleNm='▷ 오수량 시간패턴'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-2-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(2, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={2} />
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='inputdate'
|
||||
form={form}
|
||||
titleNm='▷ 상수사용량 적용월'>
|
||||
{/* 연월 선택 라이브러리로 수정 필요 */}
|
||||
<DateMonthPicker
|
||||
field={{
|
||||
value: selectedDate, // yyyyMM 형식
|
||||
onChange: (value: string) => {
|
||||
setSelectedDate(value);
|
||||
}
|
||||
}}
|
||||
selectClass="ml-5 w-[150px]"
|
||||
startYear={1900} // 시작 연도 설정
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='rtkSource'
|
||||
form={form}
|
||||
titleNm='▷ 오수전환율'>
|
||||
<Input
|
||||
value={input1}
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='analysis information'
|
||||
form={form}
|
||||
titleNm='▷ 분석 정보'>
|
||||
<Input
|
||||
value={input2}
|
||||
onChange={(e) => setInput2(e.target.value)}
|
||||
className="ml-5 h-[3.2rem] text-center text-xl w-[150px]" />
|
||||
</FormSection>
|
||||
<ListDiv>
|
||||
<div className="card !m-[1.2rem]">
|
||||
<FormSection name='region' form={form} titleNm='▷ 유량자료 등록'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-3-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(3, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={3}
|
||||
/>
|
||||
</FormSection>
|
||||
</div>
|
||||
</ListDiv>
|
||||
</div>]}
|
||||
</BaseLayout>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default IrSetting
|
||||
@@ -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<typeof formSchema>;
|
||||
// 기본 폼 값 정의 (테스트 편의를 위해 초기값 설정, 추후 삭제 필요)
|
||||
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<boolean>(false); // 로딩 상태
|
||||
|
||||
// FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
|
||||
// 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
|
||||
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
||||
initialFileInfo, // 0: 오수관망도
|
||||
initialFileInfo, // 1: 수용가-맨홀 매칭결과
|
||||
initialFileInfo, // 2: 강우자료
|
||||
]);
|
||||
|
||||
const [select1, setSelect1] = useState('0'); // 환경청코드 (enoCd)
|
||||
const [select2, setSelect2] = useState('0'); // 시도코드 (ctpvCd)
|
||||
const [select3, setSelect3] = useState<ApiSelectOption>({ val: '0', text: '전체' }); // 시군구 (sggCd)
|
||||
const [select4, setSelect4] = useState<string | number>('0'); // 하수처리장 (swageTmplntCd)
|
||||
const [select5, setSelect5] = useState<string | number>('0'); // 하수처리구역 (swtrmtZoneCd)
|
||||
|
||||
// form 인스턴스 생성
|
||||
const form = useForm<FormSchemaType>({
|
||||
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<typeof formSchema>) => {
|
||||
console.log("✅ 제출 데이터:", data)
|
||||
}
|
||||
|
||||
// 단위도 계수 테이블 설정 (EditableTableHeadItem 타입 사용 및 id 수정)
|
||||
const unitFactorHeadlist: EditableTableHeadItem<FormSchemaType['unitFactors'][number]>[] = [
|
||||
{ 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<FormSchemaType['initialDepths'][number]>[] = [
|
||||
{ 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 (
|
||||
// <BaseLayout searchBox={{ title: '분석 대상지역 선택' }} titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }} form={form} onSubmitEvent={() => { }} graphBtn={false} >
|
||||
<BaseLayout
|
||||
selectBox={{ title: '분석 대상지역 선택' }}
|
||||
titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }}
|
||||
form={form} // react-hook-form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div className="space-y-[1.2rem] overflow-x-auto pt-4 pb-4 px-2" key="form-section">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSection name="rtkSource" form={form} titleNm="○ RTK계수 출처">
|
||||
<Input {...form.register("rtkSource")} className="h-12 text-center text-xl w-[225px]" />
|
||||
</FormSection>
|
||||
<FormSection name="rdiiArea" form={form} titleNm="○ RDII 기여면적(ha)">
|
||||
<Input {...form.register("rdiiArea")} className="h-12 text-center text-xl w-[225px]" />
|
||||
</FormSection></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label className="mb-2 text-xl font-medium">○ 단위도 계수</Label>
|
||||
<EditableFormTable
|
||||
form={form}
|
||||
name="unitFactors"
|
||||
fields={unitFactorFields}
|
||||
headlist={unitFactorHeadlist}
|
||||
tableClassName="w-[400px]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="mb-[1.2rem] text-xl font-medium">○ 초기 차단 깊이</Label>
|
||||
<EditableFormTable
|
||||
form={form}
|
||||
name="initialDepths"
|
||||
fields={initialDepthFields}
|
||||
headlist={initialDepthHeadlist}
|
||||
tableClassName="w-[400px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSection name="suyeonga" form={form} titleNm="○ 오수관망도"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".inp"}
|
||||
fileIdx={0} />
|
||||
</div></FormSection>
|
||||
<FormSection name="regopm" form={form} titleNm="○ 수용가-맨홀 매칭결과"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-1-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(1, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={1} />
|
||||
</div></FormSection>
|
||||
<FormSection name="rain" form={form} titleNm="○ 강우자료"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-2-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(2, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={2} />
|
||||
</div></FormSection>
|
||||
<FormSection name='rate' form={form} titleNm='○ 오수전환율'>
|
||||
<Input
|
||||
value={form.watch("rate")} // form의 rate 값을 가져옴
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection name='date' form={form} titleNm='○ 상수사용량 적용월'>
|
||||
<DateMonthPicker
|
||||
field={{
|
||||
value: form.watch("date"), // form의 date 값을 직접 사용
|
||||
onChange: (value: string) => {
|
||||
form.setValue("date", value, { shouldValidate: true }); // form의 date 필드에 직접 설정
|
||||
}
|
||||
}}
|
||||
selectClass="ml-5 w-[200px]"
|
||||
startYear={1900} // 시작 연도 설정
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection name='rate' form={form} titleNm='○ 분석 정보'>
|
||||
<Input {...form.register("analysisInfo")} className="h-12 text-center text-xl w-[225px] ml-5" />
|
||||
</FormSection>
|
||||
</div>
|
||||
{/* <div className="flex justify-end mt-1">
|
||||
<Button size="sm" type="submit" onClick={handleAnalysisClick}>RDII분석 실행</Button>
|
||||
</div> */}
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout >
|
||||
)
|
||||
}
|
||||
@@ -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<typeof formSchema>
|
||||
|
||||
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<ResultFormValues>({
|
||||
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<any[]>([]); // API 조회 결과 저장 상태
|
||||
const [totalData, setTotalData] = useState(0) //총 데이터 수
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
|
||||
const [selectedRowData, setSelectedRowData] = useState<any>(null);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
|
||||
const [resetSelection, setResetSelection] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
// setCurPage(1);
|
||||
handleSearchButtonClick();
|
||||
}, [])
|
||||
|
||||
|
||||
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
|
||||
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<ResultFormValues> = {
|
||||
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
|
||||
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
|
||||
titleName={{ mainTitle: '분석결과', firstCardTitle: 'RDII 산정결과 현황' }}
|
||||
form={form} // form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div key='table1' className="h-[55vh] flex flex-col p-4 border rounded-lg bg-white shadow-md">
|
||||
<div className="mb-[1.2rem] text-xl font-medium">○ RDII 분석결과 현황</div>
|
||||
<div className="flex-grow overflow-auto">
|
||||
<UiTable
|
||||
headName=''
|
||||
headlist={tableColumn}
|
||||
tableData={tableData}
|
||||
total={totalData}
|
||||
pageSize={10}
|
||||
children={undefined}
|
||||
cellClick={handleCellClick}
|
||||
onPageChange={(e) => { }}
|
||||
resetSelection={resetSelection}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Result
|
||||
@@ -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<typeof formSchema>
|
||||
|
||||
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<ResultFormValues>({
|
||||
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<any[]>([]); // API 조회 결과 저장 상태
|
||||
const [totalData, setTotalData] = useState(0) //총 데이터 수
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
|
||||
const [selectedRowData, setSelectedRowData] = useState<any>(null);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
|
||||
const [resetSelection, setResetSelection] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
// setCurPage(1);
|
||||
handleSearchButtonClick();
|
||||
}, [])
|
||||
|
||||
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
|
||||
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<ResultFormValues> = {
|
||||
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
|
||||
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
|
||||
titleName={{ mainTitle: '분석결과', firstCardTitle: '분석이력' }}
|
||||
form={form} // form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div key='table1' className="h-[55vh] flex flex-col p-4 border rounded-lg bg-white shadow-md">
|
||||
<div className="mb-[1.2rem] text-xl font-medium">○ 침입수 산정결과 현황</div>
|
||||
<div className="flex-grow overflow-auto">
|
||||
<UiTable
|
||||
headName=''
|
||||
headlist={tableColumn}
|
||||
tableData={tableData}
|
||||
total={totalData}
|
||||
pageSize={10}
|
||||
children={undefined}
|
||||
cellClick={handleCellClick}
|
||||
onPageChange={(e) => { }}
|
||||
resetSelection={resetSelection}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Result
|
||||
@@ -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 (
|
||||
<BaseLayout
|
||||
queryClient={queryClient}
|
||||
currentPath={pathname ?? ""}
|
||||
handleMenuClick={handleMenuClick}
|
||||
>
|
||||
<PageLayout>{children}</PageLayout>
|
||||
</BaseLayout>
|
||||
);
|
||||
}
|
||||
@@ -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<any>([{}]) //테이블 데이터
|
||||
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 (
|
||||
<>
|
||||
<LoadingOverlay isLoading={isLoading ?? false} />
|
||||
<SearchDiv>
|
||||
<SearchFormLeft>
|
||||
<div className='flex items-center gap-5'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
|
||||
<DatePicker mode={'single'}
|
||||
selected={fromDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }}
|
||||
modifiers={{
|
||||
disabled: { after: new Date() }
|
||||
}}
|
||||
/>
|
||||
<span>~</span>
|
||||
<DatePicker mode={'single'}
|
||||
selected={toDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }}
|
||||
modifiers={{
|
||||
disabled: { after: new Date() }
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록자</Label>
|
||||
<Input
|
||||
className='w-[100px]'
|
||||
value={usr}
|
||||
onChange={(e) => setUsr(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">파일명</Label>
|
||||
<Input
|
||||
className='w-[100px]'
|
||||
value={pjNm}
|
||||
onChange={(e) => setpjNm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SearchFormLeft>
|
||||
<SearchFormRight>
|
||||
<div className='flex items-center gap-5'>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={async () => await fetchData()} >조회</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={handleRegisterClick} >등록</Button>
|
||||
</div>
|
||||
</SearchFormRight>
|
||||
</SearchDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
|
||||
<div>
|
||||
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile} >파일 다운로드</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile} >삭제</Button>
|
||||
</div>
|
||||
</div>
|
||||
<UiTable
|
||||
headName=''
|
||||
tableData={tableData}
|
||||
headlist={tableHeadlist}
|
||||
pageSize={10}
|
||||
total={totalData}
|
||||
cellClick={(index) => {
|
||||
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() }}
|
||||
/>
|
||||
</ListDiv>
|
||||
{/* 파일 업로드 모달 */}
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
bodyClass="w-auto max-w-[90vw] min-w-[600px] h-auto"
|
||||
noHeaderYn="N"
|
||||
noFooterYn="Y"
|
||||
body={
|
||||
<OperFileUploadForm
|
||||
title='도시침수 예방사업 추진현황 등록'
|
||||
onSubmit={async (file, year, quater, cd, id) => {
|
||||
await registFile(file, year, quater, cd, id)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
@@ -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: '등록자' }
|
||||
]
|
||||
@@ -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<Date>(() => { const date = new Date(); date.setDate(date.getDate() - 7); return date });
|
||||
const [toDate, setToDate] = useState<Date>(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<any>([{}])
|
||||
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 (
|
||||
<>
|
||||
<LoadingOverlay isLoading={isLoading ?? false} />
|
||||
<SearchDiv>
|
||||
<SearchFormLeft>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex items-center space-x-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
|
||||
<DatePicker mode={'single'}
|
||||
selected={fromDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }}
|
||||
modifiers={{
|
||||
disabled: { after: new Date() }
|
||||
}} />
|
||||
<span>~</span>
|
||||
<DatePicker mode={'single'}
|
||||
selected={toDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }}
|
||||
modifiers={{
|
||||
disabled: { after: new Date() }
|
||||
}} />
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록자</Label>
|
||||
<Input
|
||||
className='w-[100px] !text-2xl'
|
||||
value={usr}
|
||||
onChange={(e) => setUsr(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">파일명</Label>
|
||||
<Input
|
||||
className='w-[100px] !text-2xl'
|
||||
value={pjNm}
|
||||
onChange={(e) => { setpjNm(e.target.value) }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SearchFormLeft>
|
||||
<SearchFormRight>
|
||||
<div className='flex items-center gap-5'>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={async () => await fetchData()} >조회</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={handleRegisterClick} >등록</Button>
|
||||
</div>
|
||||
</SearchFormRight>
|
||||
</SearchDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
|
||||
<div>
|
||||
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile}>파일 다운로드</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile}>삭제</Button>
|
||||
</div>
|
||||
</div>
|
||||
<UiTable
|
||||
headName=''
|
||||
tableData={tableData}
|
||||
headlist={tableHeadlistOldPp}
|
||||
pageSize={10}
|
||||
total={totalData}
|
||||
children={undefined}
|
||||
cellClick={(index) => {
|
||||
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() }}
|
||||
/>
|
||||
</ListDiv>
|
||||
{/* 파일 업로드 모달 */}
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
bodyClass="w-auto max-w-[90vw] min-w-[600px] h-auto"
|
||||
noHeaderYn="N"
|
||||
noFooterYn="Y"
|
||||
body={
|
||||
<OperFileUploadForm
|
||||
title='노후 하수관로 정비사업 추진현황 등록'
|
||||
onSubmit={async (file, year, quater, cd, id) => {
|
||||
await registFile(file, year, quater, cd, id)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
@@ -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;
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { BaseLayout } from "@common/components";
|
||||
|
||||
export function ClientLayout({ children }: { children: React.ReactNode }) {
|
||||
return <BaseLayout>{children}</BaseLayout>;
|
||||
}
|
||||
@@ -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<any> => {
|
||||
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<any> => {
|
||||
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<any> => {
|
||||
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<any> => {
|
||||
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<any> => {
|
||||
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<any> => {
|
||||
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;
|
||||
};
|
||||
@@ -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<IUserInfo>(
|
||||
`${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 };
|
||||
@@ -1,24 +1,24 @@
|
||||
import { getData } from "../api";
|
||||
|
||||
export const searchData = async<T extends Record<string, any>>(url: string, paramObj: T) => {
|
||||
const params = new URLSearchParams(
|
||||
Object.entries(paramObj)
|
||||
.filter(([_, value]) => value !== undefined && value !== '') // 값이 있는 항목만 포함
|
||||
.reduce((acc, [key, value]) => {
|
||||
acc[key] = String(value);
|
||||
return acc;
|
||||
}, {} as Record<string, string>)
|
||||
);
|
||||
const data = await getData(`${url}?${params.toString()}`);
|
||||
return data && { data: data.content, total: data.totalElements }
|
||||
const params = new URLSearchParams(
|
||||
Object.entries(paramObj)
|
||||
.filter(([_, value]) => value !== undefined && value !== '') // 값이 있는 항목만 포함
|
||||
.reduce((acc, [key, value]) => {
|
||||
acc[key] = String(value);
|
||||
return acc;
|
||||
}, {} as Record<string, string>)
|
||||
);
|
||||
const data = await getData(`${url}?${params.toString()}`);
|
||||
return data && { data: data.content, total: data.totalElements }
|
||||
}
|
||||
|
||||
// 상위코드로 하위코드 조회
|
||||
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;
|
||||
}
|
||||
@@ -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}일`;
|
||||
};
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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'
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [internalAtflId, setInternalAtflId] = useState<string | null>(null);
|
||||
const [currentFile, setCurrentFile] = useState<File | null>(null); // 현재 선택된 파일을 저장할 상태
|
||||
const [fileName, setFileName] = useState<string>('');
|
||||
const [files, setFiles] = useState<FileList | null>(null);
|
||||
const [upload, setUpload] = useState<Upload | null>(null);
|
||||
const uniqueId = useId(); // 각 FileUploadForm 인스턴스에 대한 고유 ID 생성
|
||||
const [internalAtflCd, setInternalAtflCd] = useState<string | null>(null);
|
||||
const [internalAtflId, setInternalAtflId] = useState<string | null>(null);
|
||||
const [currentFile, setCurrentFile] = useState<File | null>(null); // 현재 선택된 파일을 저장할 상태
|
||||
const [fileName, setFileName] = useState<string>('');
|
||||
const [files, setFiles] = useState<FileList | null>(null);
|
||||
const [upload, setUpload] = useState<Upload | null>(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<string>(yearOptions[0]?.val || '');
|
||||
const [selectedQuarter, setSelectedQuarter] = useState<string>(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<string>(yearOptions[0]?.val || '');
|
||||
const [selectedQuarter, setSelectedQuarter] = useState<string>(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> {/* 컴포넌트 루트 div */}
|
||||
<div className="card p-6"> {/* 카드 스타일링 */}
|
||||
<div className='flex items-center gap-2'> {/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
|
||||
<div className="w-[300px] mr-4"> {/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
|
||||
<FileUploader
|
||||
id={uniqueId}
|
||||
className="!h-auto !max-w-none flex-row items-center gap-2"
|
||||
accept={accept}
|
||||
onUpload={(e) => {
|
||||
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> {/* 컴포넌트 루트 div */}
|
||||
<div className="card p-6"> {/* 카드 스타일링 */}
|
||||
<div className='flex items-center gap-2'> {/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
|
||||
<div className="w-[300px] mr-4"> {/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
|
||||
<FileUploader
|
||||
key={uploaderKey} // key 추가: 변경 시 컴포넌트 재마운트됨
|
||||
id={uniqueId}
|
||||
className="!h-auto !max-w-none flex-row items-center gap-2"
|
||||
accept={accept}
|
||||
onUpload={(e) => {
|
||||
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 ? (
|
||||
<div className="file-uploader-preview">
|
||||
{files && files.length > 0
|
||||
? fileName
|
||||
: "파일을 선택하세요."}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{showButton ? ( // showButton이 true일 때만 버튼 렌더링
|
||||
<Button
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
console.log(files?.[0]?.name)
|
||||
if (!currentFile) {
|
||||
alert('파일을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!selectedYear) {
|
||||
alert('등록년도를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!selectedQuarter) {
|
||||
alert('분기를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
const fileNm = currentFile.name;
|
||||
if (onSubmit) {
|
||||
// 부모에게 전달할 때는 내부 상태인 internalAtflCd, internalAtflId 사용
|
||||
onSubmit(fileNm, selectedYear, selectedQuarter, internalAtflCd || '', internalAtflId || '');
|
||||
setFiles(null); // 파일 업로드 후 파일 목록 초기화
|
||||
setFileName(''); // 파일명 초기화
|
||||
}
|
||||
}}
|
||||
>
|
||||
등록
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
handleUpload(selectedFiles, {
|
||||
handleUploadStart: setUpload,
|
||||
handleSuccess: setUpload,
|
||||
// handleResponse는 tus-js-client의 Upload 인스턴스 콜백과 연동 필요
|
||||
// 여기서는 handleUpload 유틸리티가 응답을 직접 처리한다고 가정
|
||||
handleResponse: internalHandleUploadResponse(firstFile),
|
||||
});
|
||||
}}
|
||||
customPreview={
|
||||
showPreview ? (
|
||||
<div className="file-uploader-preview">
|
||||
{files && files.length > 0
|
||||
? fileName
|
||||
: "파일을 선택하세요."}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{showButton ? ( // showButton이 true일 때만 버튼 렌더링
|
||||
<Button
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
console.log(files?.[0]?.name)
|
||||
if (!currentFile) {
|
||||
alert('파일을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!selectedYear) {
|
||||
alert('등록년도를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!selectedQuarter) {
|
||||
alert('분기를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
const fileNm = currentFile.name;
|
||||
if (onSubmit) {
|
||||
// 부모에게 전달할 때는 내부 상태인 internalAtflCd, internalAtflId 사용
|
||||
onSubmit(fileNm, selectedYear, selectedQuarter, internalAtflCd || '', internalAtflId || '');
|
||||
setFiles(null); // 파일 업로드 후 파일 목록 초기화
|
||||
setFileName(''); // 파일명 초기화
|
||||
// 파일 업로드 후 FileUploader 컴포넌트를 재마운트하기 위해 key 값 변경
|
||||
setUploaderKey(prev => prev + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
등록
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FileUploadForm
|
||||
@@ -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 (
|
||||
<div className="grid grid-cols-[200px_1fr] items-center">
|
||||
<div className="text-xl font-medium">{titleNm}</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={name}
|
||||
render={({ field }) => children}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div className="grid grid-cols-[200px_1fr] items-center">
|
||||
<div className="text-xl font-medium">{titleNm}</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={name}
|
||||
render={({ field }) => children}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FormSection
|
||||
@@ -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<ModalProps> = ({ isModalOpen, setIsModalOpen, title, children, closeModal,saveModal }) => {
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
|
||||
<DialogOverlay className='z-[200]' />
|
||||
<DialogContent className="w-auto max-w-[1200px] min-w-[400px] min-h-[150px] h-auto max-h-[450px] overflow-auto z-[1000]">
|
||||
{title ? <DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader> : null}
|
||||
{children}
|
||||
<DialogFooter>
|
||||
<DialogClose>
|
||||
<div className='flex justify-end gap-2'>
|
||||
{saveModal ? <button className="px-4 py-2 bg-primary text-white rounded" onClick={saveModal}>저장</button> : null}
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closeModal}>닫기</button>
|
||||
</div>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
const Modal: React.FC<ModalProps> = ({ isModalOpen, setIsModalOpen, title, children, closeModal, saveModal }) => {
|
||||
return (
|
||||
<Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
|
||||
<DialogOverlay className='z-[200]' />
|
||||
<DialogContent className="w-auto max-w-[1200px] min-w-[400px] min-h-[150px] h-auto max-h-[450px] overflow-auto z-[1000]" aria-describedby={undefined}>
|
||||
{title ? <DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader> : null}
|
||||
{children}
|
||||
<DialogFooter>
|
||||
<div className='flex justify-end gap-2'>
|
||||
{saveModal ? <button className="px-4 py-2 bg-primary text-white rounded" onClick={saveModal}>저장</button> : null}
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closeModal}>닫기</button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default Modal
|
||||
@@ -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<string | null>(null);
|
||||
const [atflId, setAtflId] = useState<string | null>(null);
|
||||
const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (files: string, year: string, quarter: string, code: string, id: string) => void }) => {
|
||||
const [atflCd, setAtflCd] = useState<string | null>(null);
|
||||
const [atflId, setAtflId] = useState<string | null>(null);
|
||||
|
||||
const [selectedYear, setSelectedYear] = useState<string>(yearOptions[0]?.val || '');
|
||||
const [quaterOptions, setQuaterOptions] = useState(() => getQuarterOptions(selectedYear));
|
||||
const [selectedQuarter, setSelectedQuarter] = useState<string>(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<string>(yearOptions[0]?.val || '');
|
||||
const [selectedQuarter, setSelectedQuarter] = useState<string>(quater[0]?.val || '');
|
||||
// 년도가 변경될 때 분기 옵션 업데이트
|
||||
useEffect(() => {
|
||||
const updatedQuarterOptions = getQuarterOptions(selectedYear);
|
||||
setQuaterOptions(updatedQuarterOptions);
|
||||
// 분기 옵션이 변경되면 첫 번째 옵션으로 자동 선택
|
||||
setSelectedQuarter(updatedQuarterOptions[0]?.val || '');
|
||||
}, [selectedYear]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className='card-header'>
|
||||
<h3 className="text-2xl font-medium">{title}</h3>
|
||||
</div>
|
||||
<div className="card p-6">
|
||||
<div className="grid grid-col-2 items-center space-x-4">
|
||||
<div className='flex'>
|
||||
<SelectBox
|
||||
className="w-50 mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label="년도"
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={(value: string | number) => setSelectedYear(String(value))}
|
||||
/><SelectBox
|
||||
className="w-50"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label="분기"
|
||||
selectArray={quater}
|
||||
onSelectValue={(value: string | number) => setSelectedQuarter(String(value))}
|
||||
/>
|
||||
<FileUploadForm
|
||||
onSubmit={(files, year, quarter, code, id) => {
|
||||
onSubmit(files, (selectedYear ?? year) || '', (selectedQuarter ?? quarter) || '', code, id);
|
||||
}}
|
||||
showButton={true}
|
||||
showPreview={true}
|
||||
accept={""} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
// 년도 변경 핸들러
|
||||
const handleYearChange = (value: string | number) => {
|
||||
const yearValue = String(value);
|
||||
setSelectedYear(yearValue);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className='card-header'>
|
||||
<h3 className="text-2xl font-medium">{title}</h3>
|
||||
</div>
|
||||
<div className="card p-6">
|
||||
<div className="grid grid-col-2 items-center space-x-4">
|
||||
<div className='flex'>
|
||||
<SelectBox
|
||||
className="w-50 mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label="년도"
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={handleYearChange}
|
||||
value={selectedYear}
|
||||
/>
|
||||
<SelectBox
|
||||
className="w-50"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label="분기"
|
||||
selectArray={quaterOptions}
|
||||
onSelectValue={(value: string | number) => setSelectedQuarter(String(value))}
|
||||
value={selectedQuarter}
|
||||
/>
|
||||
<FileUploadForm
|
||||
onSubmit={(files, year, quarter, code, id) => {
|
||||
onSubmit(files, (selectedYear ?? year) || '', (selectedQuarter ?? quarter) || '', code, id);
|
||||
}}
|
||||
showButton={true}
|
||||
showPreview={true}
|
||||
accept={""} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default operFileUploadForm
|
||||
@@ -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<string, React.ReactNode> | 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<string, React.ReactNode> | 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<string, React.ReactNode> | 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<string, React.ReactNode> | 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<number>(1);
|
||||
const [formData, setFormData] = useState<{ [key: string]: string | number | boolean }>({});
|
||||
useEffect(() => {
|
||||
if (resetPageNo) {
|
||||
setCur(1);
|
||||
onPageChange(1);
|
||||
}
|
||||
}, [onPageChange, resetPageNo]);
|
||||
const [cur, setCur] = useState<number>(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 ? (
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">{headName}</h3>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={`card !m-[1.2rem] !p-0r ${className}`}>
|
||||
{tableName1 && ( // tableName prop이 있으면 표시
|
||||
<div className="text-xl font-semibold my-2 mx-3">{tableName1}</div>
|
||||
)}
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{headlist?.map((head) => (
|
||||
<TableRow key={head.id}>
|
||||
{/* 컬럼 제목 */}
|
||||
<TableCell className="font-bold bg-blue-100 text-xs">
|
||||
{head.title}
|
||||
</TableCell>
|
||||
{/* 데이터 값 또는 입력 필드 */}
|
||||
<TableCell className="text-xs">
|
||||
{children && children[head.id] ? children[head.id] : isEditable ? (
|
||||
head.type === "select" ? (
|
||||
<select
|
||||
id={head.id}
|
||||
value={formData[head.id] ?? "-"}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
|
||||
>
|
||||
{head.options?.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : head.type === "input" ? (
|
||||
<input
|
||||
id={head.id}
|
||||
type="text"
|
||||
value={formData[head.id] ?? ""}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
|
||||
/>
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
return (
|
||||
<>
|
||||
{headName ? (
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">{headName}</h3>
|
||||
{showSaveButton && onSaveClick && (
|
||||
<Button
|
||||
onClick={onSaveClick}
|
||||
className="px-4 mr-3 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
|
||||
>
|
||||
저장
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={`card !m-[1.2rem] !p-0r ${className}`}>
|
||||
{tableName1 && ( // tableName prop이 있으면 표시
|
||||
<div className="text-xl font-semibold my-2 mx-3">{tableName1}</div>
|
||||
)}
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{headlist?.map((head) => (
|
||||
<TableRow key={head.id}>
|
||||
{/* 컬럼 제목 */}
|
||||
<TableCell className="font-bold bg-blue-100 text-xs">
|
||||
{head.title}
|
||||
</TableCell>
|
||||
{/* 데이터 값 또는 입력 필드 */}
|
||||
<TableCell className="text-xs">
|
||||
{children && children[head.id] ? children[head.id] : isEditable ? (
|
||||
head.type === "select" ? (
|
||||
<select
|
||||
id={head.id}
|
||||
value={String(formData[head.id]) ?? "-"}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
|
||||
>
|
||||
{head.options?.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{tableName2 && ( // tableName prop이 있으면 표시
|
||||
<div className="text-xl font-semibold mt-8 my-2 mx-3">{tableName2}</div>
|
||||
)}
|
||||
{showSecondTable && (
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{headlist2?.map((head) => (
|
||||
<TableRow key={head.id}>
|
||||
{/* 컬럼 제목 */}
|
||||
<TableCell className="font-bold bg-blue-100 text-xs w-fit whitespace-nowrap">
|
||||
{head.title}
|
||||
</TableCell>
|
||||
{/* 데이터 값 또는 입력 필드 */}
|
||||
<TableCell className="text-xs">
|
||||
{children && children[head.id] ? children[head.id] : isEditable2 ? (
|
||||
head.type === "select" ? (
|
||||
<select
|
||||
id={head.id}
|
||||
value={formData[head.id] ?? "-"}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
|
||||
>
|
||||
{head.options?.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : head.type === "input" ? (
|
||||
<input
|
||||
id={head.id}
|
||||
type="text"
|
||||
value={formData[head.id] ?? ""}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
|
||||
/>
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
{total > 0 && (
|
||||
<UiPageNations
|
||||
total={total}
|
||||
cur={cur}
|
||||
pageSize={pageSize}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
</select>
|
||||
) : head.type === "input" ? (
|
||||
<input
|
||||
id={head.id}
|
||||
type="text"
|
||||
value={String(formData[head.id] ?? "")}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
|
||||
/>
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{tableName2 && ( // tableName prop이 있으면 표시
|
||||
<div className="text-xl font-semibold mt-8 my-2 mx-3">{tableName2}</div>
|
||||
)}
|
||||
{showSecondTable && (
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{headlist2?.map((head) => (
|
||||
<TableRow key={head.id}>
|
||||
{/* 컬럼 제목 */}
|
||||
<TableCell className="font-bold bg-blue-100 text-xs w-fit whitespace-nowrap">
|
||||
{head.title}
|
||||
</TableCell>
|
||||
{/* 데이터 값 또는 입력 필드 */}
|
||||
<TableCell className="text-xs">
|
||||
{children && children[head.id] ? children[head.id] : isEditable2 ? (
|
||||
head.type === "select" ? (
|
||||
<select
|
||||
id={head.id}
|
||||
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
|
||||
>
|
||||
{head.options?.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : head.type === "input" ? (
|
||||
<input
|
||||
id={head.id}
|
||||
type="text"
|
||||
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
|
||||
onChange={(e) => handleInputChange(head.id, e.target.value)}
|
||||
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
|
||||
/>
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)
|
||||
) : (
|
||||
<span>{formData[head.id] ?? "-"}</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
{total > 0 && (
|
||||
<UiPageNations
|
||||
total={total}
|
||||
cur={cur}
|
||||
pageSize={pageSize}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<void>;
|
||||
}
|
||||
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<ApiSelectOption[]>([]);
|
||||
const [treatmentFacilityOptions, setTreatmentFacilityOptions] = useState<ApiSelectOption[]>([]);
|
||||
const [isLoadingAreaData, setIsLoadingAreaData] = useState<boolean>(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 (
|
||||
<Form {...form} className="min-h-screen flex flex-col">
|
||||
<ContentLayout title={titleName.mainTitle} className="flex-grow flex flex-col overflow-hidden" isLoading={isLoading}>
|
||||
<ListDiv>
|
||||
{/* searchBox.title이 있으면 h3 태그로 제목을 표시합니다. */}
|
||||
{selectBox?.title && (
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl font-medium">{selectBox.title}</h3>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center w-full">
|
||||
{showDatePicker && ( // showDatePicker 값에 따라 DatePicker 렌더링
|
||||
<>
|
||||
<Label className="ml-4 w-20 text-xl text-gray-600 whitespace-nowrap">분석기간</Label>
|
||||
<DatePicker
|
||||
mode={"single"}
|
||||
field={{
|
||||
value: aplcnYm ?? new Date(),
|
||||
onChange: setAplcnYm ?? ((date: Date | undefined) => console.log("DatePicker onChange:", date))
|
||||
}}
|
||||
selectClass="ml-5 date-picker-trigger" />
|
||||
</>
|
||||
)}
|
||||
<GovSidoSigunguSearchForm
|
||||
isShowPart={true}
|
||||
setRtnEnvPartValue={(val) => setEnoCd?.(val)}
|
||||
setRtnEnvPartSidoValue={(val) => setCtpvCd?.(val)}
|
||||
setRtnEnvPartSigunValue={setSigungu} // 선택된 시군구 값을 받을 콜백 함수 전달
|
||||
>
|
||||
<SelectBox2 label={"하수처리장"} value={selectedSwageTreatmentPlant} selectArray={treatmentFacilityOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageTreatmentPlantChange?.(val)} />
|
||||
<SelectBox2 label={"하수처리구역"} value={selectedSwageProcessingZone} selectArray={processingZoneOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageProcessingZoneChange?.(val)} />
|
||||
</GovSidoSigunguSearchForm>
|
||||
{selectBox?.searchChk ? <SearchFormRight><Button size="sm" onClick={() => selectBox.onSearchClick?.()}>조회</Button></SearchFormRight> : null}
|
||||
</div>
|
||||
</ListDiv>
|
||||
<ListDiv>
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl font-medium">{titleName.firstCardTitle}</h3>
|
||||
<div>
|
||||
{graphBtn ? <Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile}>파일 다운로드</Button> : null}
|
||||
{/* 그래프 있을 시 */}
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile}>삭제</Button> : null}
|
||||
{/* 분석 버튼 */}
|
||||
{analysisBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={onAnalysis}>{analysisBtn}</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmitEvent)} className="flex-grow flex flex-col">
|
||||
<div className="card !m-[1.2rem] flex-grow flex flex-col">
|
||||
{/* 폼 정보 입력 칸 */}
|
||||
{children?.[0]}
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ListDiv>
|
||||
{
|
||||
children?.[1] != null ? <ListDiv>
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">{titleName?.secondCardTitle}</h3>
|
||||
<div>
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm">파일 다운로드</Button> : null}
|
||||
{/* 그래프 있을 시 */}
|
||||
{graphBtn ? <Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm">삭제</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card !m-[1.2rem]">{children?.[1]}</div>
|
||||
</ListDiv> : null
|
||||
}
|
||||
</ContentLayout >
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseLayout
|
||||
@@ -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<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
managenm: "",
|
||||
region: "",
|
||||
suyeonga: 0,
|
||||
inputdate: new Date(),
|
||||
rtkSource: "",
|
||||
suyeongaPlace: "",
|
||||
pattern: ""
|
||||
}
|
||||
})
|
||||
|
||||
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
||||
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<ApiSelectOption>({ val: '0', text: '전체' }); // 시군구 상태를 객체로 변경
|
||||
const [select4, setSelect4] = useState<string | number>('0'); // 하수처리장코드
|
||||
const [select5, setSelect5] = useState<string | number>('0'); // 하수처리구역코드
|
||||
const [formResetKey, setFormResetKey] = useState(0); // FileUploadForm 리셋을 위한 key 상태
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(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 (
|
||||
<>
|
||||
<BaseLayout
|
||||
titleName={{ mainTitle: '침입수 분석', firstCardTitle: '침입수 분석 자료 입력' }}
|
||||
form={form}
|
||||
onSubmitEvent={() => { }}
|
||||
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}
|
||||
>
|
||||
{[<div className="grid gap-4">
|
||||
<FormSection name='suyeongaPlace' form={form} titleNm='▷ 오수관망도'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={""}
|
||||
fileIdx={0} />
|
||||
</FormSection>
|
||||
<FormSection name='suyeonga' form={form} titleNm='▷ 수용가-맨홀 매칭결과'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-1-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(1, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={1} />
|
||||
</FormSection>
|
||||
<FormSection name='pattern' form={form} titleNm='▷ 오수량 시간패턴'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-2-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(2, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={2} />
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='inputdate'
|
||||
form={form}
|
||||
titleNm='▷ 상수사용량 적용기간'>
|
||||
<DatePicker
|
||||
mode={"single"}
|
||||
field={{
|
||||
value: selectedDate, // 현재 페이지의 selectedDate 상태 사용
|
||||
onChange: (date: Date | undefined) => {
|
||||
if (date) {
|
||||
setSelectedDate(date);
|
||||
form.setValue('inputdate', date, { shouldValidate: true });
|
||||
}
|
||||
}
|
||||
}}
|
||||
selectClass="ml-5 date-picker-trigger" // date-picker.css의 스타일 적용
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='rtkSource'
|
||||
form={form}
|
||||
titleNm='▷ 오수전환율'>
|
||||
<Input
|
||||
value={input1}
|
||||
onChange={(e) => {
|
||||
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" />
|
||||
</FormSection>
|
||||
<FormSection
|
||||
name='analysis information'
|
||||
form={form}
|
||||
titleNm='▷ 분석 정보'>
|
||||
<Input
|
||||
value={input2}
|
||||
onChange={(e) => setInput2(e.target.value)}
|
||||
className="ml-5 h-[3.2rem] text-center text-xl w-[150px]" />
|
||||
</FormSection>
|
||||
<ListDiv>
|
||||
<div className="card !m-[1.2rem]">
|
||||
<FormSection name='region' form={form} titleNm='▷ 유량자료 등록'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-3-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(3, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={3}
|
||||
/>
|
||||
</FormSection>
|
||||
</div>
|
||||
</ListDiv>
|
||||
</div>]}
|
||||
{/* <div className="flex items-center gap-4">
|
||||
<FormSection
|
||||
name='region' form={form} titleNm='▷ 유량자료 등록'>
|
||||
<FileUploadForm
|
||||
key={`file-upload-3-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(3, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={3} />
|
||||
</FormSection>
|
||||
<div className="flex justify-center mt-1">
|
||||
<Button size="sm" type="submit" onClick={handleAnalysisClick}>침입수분석 실행</Button>
|
||||
</div>
|
||||
</div> */}
|
||||
</BaseLayout>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default IrSetting
|
||||
@@ -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<typeof formSchema>;
|
||||
// 기본 폼 값 정의 (테스트 편의를 위해 초기값 설정, 추후 삭제 필요)
|
||||
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<boolean>(false); // 로딩 상태
|
||||
|
||||
// FileUploadForm에서 전달받은 파일 정보를 저장할 상태 배열
|
||||
// 각 인덱스는 FileUploadForm의 fileIdx와 매칭됨
|
||||
const [uploadedFilesData, setUploadedFilesData] = useState<UploadedFileInfo[]>([
|
||||
initialFileInfo, // 0: 오수관망도
|
||||
initialFileInfo, // 1: 수용가-맨홀 매칭결과
|
||||
initialFileInfo, // 2: 강우자료
|
||||
]);
|
||||
|
||||
const [select1, setSelect1] = useState('0'); // 환경청코드 (enoCd)
|
||||
const [select2, setSelect2] = useState('0'); // 시도코드 (ctpvCd)
|
||||
const [select3, setSelect3] = useState<ApiSelectOption>({ val: '0', text: '전체' }); // 시군구 (sggCd)
|
||||
const [select4, setSelect4] = useState<string | number>('0'); // 하수처리장 (swageTmplntCd)
|
||||
const [select5, setSelect5] = useState<string | number>('0'); // 하수처리구역 (swtrmtZoneCd)
|
||||
|
||||
|
||||
// form 인스턴스 생성
|
||||
const form = useForm<FormSchemaType>({
|
||||
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<typeof formSchema>) => {
|
||||
console.log("✅ 제출 데이터:", data)
|
||||
}
|
||||
|
||||
// 단위도 계수 테이블 설정 (EditableTableHeadItem 타입 사용 및 id 수정)
|
||||
const unitFactorHeadlist: EditableTableHeadItem<FormSchemaType['unitFactors'][number]>[] = [
|
||||
{ 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<FormSchemaType['initialDepths'][number]>[] = [
|
||||
{ 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 (
|
||||
// <BaseLayout searchBox={{ title: '분석 대상지역 선택' }} titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }} form={form} onSubmitEvent={() => { }} graphBtn={false} >
|
||||
<BaseLayout
|
||||
selectBox={{ title: '분석 대상지역 선택' }}
|
||||
titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }}
|
||||
form={form} // react-hook-form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div className="space-y-[1.2rem] overflow-x-auto pt-4 pb-4 px-2" key="form-section">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSection name="rtkSource" form={form} titleNm="○ RTK계수 출처">
|
||||
<Input {...form.register("rtkSource")} className="h-12 text-center text-xl w-[225px]" />
|
||||
</FormSection>
|
||||
<FormSection name="rdiiArea" form={form} titleNm="○ RDII 기여면적(ha)">
|
||||
<Input {...form.register("rdiiArea")} className="h-12 text-center text-xl w-[225px]" />
|
||||
</FormSection></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label className="mb-2 text-xl font-medium">○ 단위도 계수</Label>
|
||||
<EditableFormTable
|
||||
form={form}
|
||||
name="unitFactors"
|
||||
fields={unitFactorFields}
|
||||
headlist={unitFactorHeadlist}
|
||||
tableClassName="w-[400px]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="mb-[1.2rem] text-xl font-medium">○ 초기 차단 깊이</Label>
|
||||
<EditableFormTable
|
||||
form={form}
|
||||
name="initialDepths"
|
||||
fields={initialDepthFields}
|
||||
headlist={initialDepthHeadlist}
|
||||
tableClassName="w-[400px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSection name="suyeonga" form={form} titleNm="○ 오수관망도"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-0-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(0, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={""}
|
||||
fileIdx={0} />
|
||||
</div></FormSection>
|
||||
<FormSection name="regopm" form={form} titleNm="○ 수용가-맨홀 매칭결과"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-1-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(1, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={1} />
|
||||
</div></FormSection>
|
||||
<FormSection name="rain" form={form} titleNm="○ 강우자료"><div className="w-[350px]">
|
||||
<FileUploadForm
|
||||
key={`file-upload-2-${formResetKey}`} // 폼 초기화를 위한 key
|
||||
onFileSelect={(file, cd, id) => handleFileSelection(2, file, cd, id)}
|
||||
showButton={false}
|
||||
showPreview={true}
|
||||
accept={".xls, .xlsx, .xlsm, .xltx"}
|
||||
fileIdx={2} />
|
||||
</div></FormSection>
|
||||
<FormSection name='rate' form={form} titleNm='○ 오수전환율'>
|
||||
<Input {...form.register("rate")} className="h-12 text-center text-xl w-[225px] ml-5" />
|
||||
</FormSection>
|
||||
<FormSection name='date' form={form} titleNm='○ 상수사용량 적용기간'>
|
||||
{/* <DatePicker
|
||||
selected={form.watch("date")}
|
||||
onSelect={(date: Date | undefined) => {
|
||||
if (date) {
|
||||
form.setValue("date", date, { shouldValidate: true });
|
||||
}
|
||||
}}
|
||||
mode={"single"}
|
||||
className="ml-5"
|
||||
/> */}
|
||||
<DatePicker
|
||||
mode={"single"} // mode는 DayPickerSingleProps에서 오므로 그대로 사용 가능
|
||||
field={{
|
||||
value: form.watch("date"), // react-hook-form의 "date" 필드 값 사용
|
||||
onChange: (date: Date | undefined) => {
|
||||
if (date) {
|
||||
form.setValue("date", date, { shouldValidate: true });
|
||||
}
|
||||
}
|
||||
}}
|
||||
// className을 직접 사용하거나, DatePicker 내부에서 selectClass를 처리하도록 수정 필요
|
||||
// 여기서는 DatePicker의 selectClass prop을 사용하고, date-picker.css의 스타일을 적용
|
||||
selectClass="ml-5 date-picker-trigger"
|
||||
/>
|
||||
</FormSection>
|
||||
<FormSection name='rate' form={form} titleNm='○ 분석 정보'>
|
||||
<Input {...form.register("analysisInfo")} className="h-12 text-center text-xl w-[225px] ml-5" />
|
||||
</FormSection>
|
||||
</div>
|
||||
{/* <div className="flex justify-end mt-1">
|
||||
<Button size="sm" type="submit" onClick={handleAnalysisClick}>RDII분석 실행</Button>
|
||||
</div> */}
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout >
|
||||
)
|
||||
}
|
||||
@@ -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<typeof formSchema>
|
||||
|
||||
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<ResultFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
enoCd: '0',
|
||||
ctpvCd: '0',
|
||||
sggCd: { val: '0', text: '전체' },
|
||||
swageTmplntCd: '0',
|
||||
swtrmtZoneCd: '0',
|
||||
aplcnYm: new Date(),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
const [tableData, setTableData] = useState<any[]>([]); // API 조회 결과 저장 상태
|
||||
const [totalData, setTotalData] = useState(0) //총 데이터 수
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
|
||||
const [selectedRowData, setSelectedRowData] = useState<any>(null);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
|
||||
|
||||
|
||||
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
|
||||
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<ResultFormValues> = {
|
||||
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
|
||||
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
|
||||
titleName={{ mainTitle: '분석결과', firstCardTitle: 'RDII 산정결과 현황' }}
|
||||
form={form} // form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div key='table1' className="h-[55vh] flex flex-col p-4 border rounded-lg bg-white shadow-md">
|
||||
<div className="mb-[1.2rem] text-xl font-medium">○ RDII 분석결과 현황</div>
|
||||
<div className="flex-grow overflow-auto">
|
||||
<UiTable
|
||||
headName=''
|
||||
headlist={tableColumn}
|
||||
tableData={tableData}
|
||||
total={totalData}
|
||||
pageSize={10}
|
||||
children={undefined}
|
||||
cellClick={handleCellClick}
|
||||
onPageChange={(e) => { }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Result
|
||||
@@ -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<typeof formSchema>
|
||||
|
||||
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<ResultFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
enoCd: '0',
|
||||
ctpvCd: '0',
|
||||
sggCd: { val: '0', text: '전체' },
|
||||
swageTmplntCd: '0',
|
||||
swtrmtZoneCd: '0',
|
||||
aplcnYm: new Date(),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
const [tableData, setTableData] = useState<any[]>([]); // API 조회 결과 저장 상태
|
||||
const [totalData, setTotalData] = useState(0) //총 데이터 수
|
||||
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
|
||||
const [selectedRowData, setSelectedRowData] = useState<any>(null);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
|
||||
|
||||
|
||||
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
|
||||
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<ResultFormValues> = {
|
||||
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
|
||||
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
|
||||
titleName={{ mainTitle: '분석결과', firstCardTitle: '분석이력' }}
|
||||
form={form} // form 인스턴스 전달
|
||||
onSubmitEvent={() => { }} // 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}
|
||||
>
|
||||
{[<div key='table1' className="h-[55vh] flex flex-col p-4 border rounded-lg bg-white shadow-md">
|
||||
<div className="mb-[1.2rem] text-xl font-medium">○ 침입수 산정결과 현황</div>
|
||||
<div className="flex-grow overflow-auto">
|
||||
<UiTable
|
||||
headName=''
|
||||
headlist={tableColumn}
|
||||
tableData={tableData}
|
||||
total={totalData}
|
||||
pageSize={10}
|
||||
children={undefined}
|
||||
cellClick={handleCellClick}
|
||||
onPageChange={(e) => { }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
]}
|
||||
</BaseLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Result
|
||||
@@ -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 (
|
||||
<html lang="en" data-theme={theme?.value}>
|
||||
<body>
|
||||
<StoreProvider>
|
||||
<AuthWrapper>
|
||||
<ClientLayout>{children}</ClientLayout>
|
||||
</AuthWrapper>
|
||||
</StoreProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
export default App;
|
||||
@@ -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<InputSectionProps> = ({ title, data, sectionKey, onInputChange }) => {
|
||||
return (
|
||||
<div>
|
||||
{/* 섹션 제목 */}
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">{title}</h3>
|
||||
</div>
|
||||
{/* 테이블 */}
|
||||
<div className="card !m-[1.2rem] !p-0r">
|
||||
<Table variant="secondary" className="w-full">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="border border-gray-300 px-2 py-2 text-sm">년도</TableHead>
|
||||
<TableHead className="border border-gray-300 px-2 py-2 text-sm">구분</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.map((row, index) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell className="border border-gray-300 px-2 py-2 text-sm">
|
||||
<input
|
||||
type="text"
|
||||
value={row.year}
|
||||
onChange={(e) => onInputChange(sectionKey, index, "year", e.target.value)}
|
||||
className="w-full text-xl border-radius-0 px-3 py-2 text-base text-center leading-normal"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="border border-gray-300 px-2 py-2 text-sm text-center leading-normal">
|
||||
{row.type}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InputSection;
|
||||
@@ -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<LayerComponentProps>;
|
||||
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<LayerComponentProps> | 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<React.SetStateAction<{ year: string; type: string }[]>>;
|
||||
};
|
||||
}
|
||||
) => {
|
||||
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);
|
||||
};
|
||||
@@ -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)' }
|
||||
];
|
||||
@@ -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<string>("");
|
||||
const openModal = (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
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 (
|
||||
<div>
|
||||
<VerticalTable headName='자체 입력정보' tableData={[]} headlist={inputColumn} pageSize={20} total={0} children={undefined} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}></VerticalTable>
|
||||
<InputSection title="보수 및 갱신" data={repairData} sectionKey="repair" onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)} />
|
||||
<InputSection title="청소 및 준설" data={cleaningData} sectionKey="cleaning" onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)} />
|
||||
<InputSection title="점검 및 진단" data={inspectionData} sectionKey="inspection" onInputChange={(section, index, field, value) => handleInputChange(section, index, field, value, dataMap)} />
|
||||
<div className="absolute bottom-0 left-0 w-full flex justify-start space-x-2 p-4">
|
||||
<Button
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
||||
onClick={openModal}
|
||||
>
|
||||
Infil
|
||||
</Button>
|
||||
<Button
|
||||
className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
|
||||
onClick={openModal}
|
||||
>
|
||||
RDII
|
||||
</Button>
|
||||
</div>
|
||||
<InfilChart btnTxt={btnTxt} isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} closeModal={closeModal} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SwtrmtFclt
|
||||
@@ -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 = () => (
|
||||
<div className='grid grid-cols-1 gap-4 p-4'>
|
||||
{/* 강우정보 테이블 */}
|
||||
<UiTable
|
||||
headName='강우정보'
|
||||
tableData={preprocessedData}
|
||||
headlist={untrtSwgRainCol3}
|
||||
pageSize={10}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Rain data page change:', page);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 측정정보 테이블 */}
|
||||
<UiTable
|
||||
headName='측정정보'
|
||||
tableData={preprocessedData}
|
||||
headlist={untrtSwgRainCol4}
|
||||
pageSize={10}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Measure data page change:', page);
|
||||
}}
|
||||
>
|
||||
{/* 커스텀 헤더 */}
|
||||
<TableRow>
|
||||
<TableHead colSpan={5} className="text-center bg-blue-100 font-bold">수량</TableHead>
|
||||
<TableHead colSpan={3} className="text-center bg-blue-100 font-bold">수질</TableHead>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableHead className="text-center">측정시작일시</TableHead>
|
||||
<TableHead className="text-center">측정종료일시</TableHead>
|
||||
<TableHead className="text-center">측정간격(분)</TableHead>
|
||||
<TableHead className="text-center">측정기기설치위치</TableHead>
|
||||
<TableHead className="text-center">유량계 종류 및 모델명</TableHead>
|
||||
<TableHead className="text-center">채수시작일시</TableHead>
|
||||
<TableHead className="text-center">채수종료일시</TableHead>
|
||||
<TableHead className="text-center">채수횟수</TableHead>
|
||||
</TableRow>
|
||||
</UiTable>
|
||||
|
||||
{/* 수량/수질측정 정보 테이블 */}
|
||||
<UiTable
|
||||
headName='수량/수질측정 정보'
|
||||
tableData={additionalData}
|
||||
headlist={untrtSwgRainCol5}
|
||||
pageSize={10}
|
||||
total={additionalData.length}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (page: number): void {
|
||||
console.log('Quality data page change:', page);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* <VerticalTable
|
||||
headName='자체 입력정보'
|
||||
tableData={[]}
|
||||
headlist={inputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}}
|
||||
/> */}
|
||||
|
||||
{!chkMainSsc ? null :
|
||||
<div>
|
||||
<div className="card-header">
|
||||
<h3 className="text-2xl mx-3 font-medium text-label">중점우수토실 운영정보</h3>
|
||||
</div>
|
||||
<Button
|
||||
className='mx-auto block w-64 mt-3 py-2 text-white rounded-sm text-sm font-medium hover:bg-blue-700 bg-blue-600'
|
||||
onClick={openModal}
|
||||
>
|
||||
상세보기
|
||||
</Button>
|
||||
|
||||
<UiModal
|
||||
open={isModalOpen}
|
||||
onOpenChange={setIsModalOpen}
|
||||
bodyClass={`
|
||||
h-[100vh]
|
||||
w-[60vw]
|
||||
max-w-none
|
||||
max-h-none
|
||||
overflow-visible
|
||||
z-[101]
|
||||
`}
|
||||
body={renderModalBody()}
|
||||
noHeaderYn='Y'
|
||||
noFooterYn='N'
|
||||
// footerContent={renderFooterContent()}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Ssc
|
||||
@@ -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<string>('');
|
||||
const openModal = (title:string) => {
|
||||
setIsModalOpen(true);
|
||||
setModalTitle(title)
|
||||
};
|
||||
const closeModal = () => {
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
return (
|
||||
<div>
|
||||
<VerticalTable children={{
|
||||
title: <Button onClick={() => openModal('하수도정비 기본계획보고서')}>보고서</Button>,
|
||||
cad: <Button onClick={() => openModal('하수도대장 평면도')}>평면도</Button>,
|
||||
}} headName='디지털 자료관 연계정보' tableData={[]} headlist={headList} pageSize={20} total={0} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}></VerticalTable>
|
||||
<Modal isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} closeModal={closeModal}>
|
||||
<div className='grid grid-col-2'>
|
||||
<UiTable headName={modalTitle} tableData={[]} headlist={modalHeadList} pageSize={20} total={0} cellClick={undefined} children={undefined} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}
|
||||
}></UiTable>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SwtrmtFclt
|
||||
@@ -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<HTMLButtonElement>(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<string, { label: string; color: string }>) 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 (
|
||||
<Modal isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} closeModal={closeModal}>
|
||||
{/* 분석 입력현황 조회 */}
|
||||
<div className='grid grid-cols-4 gap-4'>
|
||||
<div className="grid grid-rows-4 gap-4 mb-4">
|
||||
<Button className="bg-white text-white w-[130px] font-bold px-4 mt-2 py-2" onClick={openPopup}>
|
||||
분석 입력현황 조회
|
||||
</Button>
|
||||
|
||||
{/* 침입수량 분석결과 */}
|
||||
<div className="bg-white text-red-600 font-bold px-4 py-2 ">
|
||||
침입수량 분석결과
|
||||
<div className="flex items-center mt-2">
|
||||
<span className="text-black text-xl font-bold">120</span>
|
||||
<span className="ml-2 text-black">m³/d</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 차트 */}
|
||||
<div className="w-[500px] h-[300px] bg-white p-4">
|
||||
<MainChart chartConfig={chartConfig} chartForm={chartForm} chartData={chartData} chartTitle={'관로유량'} />
|
||||
</div>
|
||||
</div>
|
||||
{popupOpen && (
|
||||
<div
|
||||
className="absolute bg-gray-100 border border-gray-300 w-[320px] shadow-lg p-4 rounded"
|
||||
style={{
|
||||
top: popupPosition.top,
|
||||
left: popupPosition.left,
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<div className="text-lg font-bold mb-2">분석 입력현황</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>상수사용량 정보:</div>
|
||||
<div>
|
||||
<input type='month' defaultValue={getCurrentDate()} className="border border-gray-300 rounded px-2 py-1"/>
|
||||
</div>
|
||||
<div>오수 전환율:</div>
|
||||
<div>
|
||||
<select className="border border-gray-300 rounded px-2 py-1">
|
||||
<option>0.85</option>
|
||||
<option>0.90</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>수용가-맨홀 매칭:</div>
|
||||
<div>
|
||||
<select className="border border-gray-300 rounded px-2 py-1">
|
||||
<option>매칭(양평).shp</option>
|
||||
<option>매칭(서울).shp</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>관망도 자료:</div>
|
||||
<div>
|
||||
<select className="border border-gray-300 rounded px-2 py-1">
|
||||
<option>양평.inp</option>
|
||||
<option>서울.inp</option>
|
||||
</select>
|
||||
</div>
|
||||
{btnTxt === 'RDII' ? <><div>강우 자료:</div>
|
||||
<div>
|
||||
<select className="border border-gray-300 rounded px-2 py-1">
|
||||
<option>R20240815.xlsx</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>RTX 계수 출처:</div>
|
||||
<div>
|
||||
<select className="border border-gray-300 rounded px-2 py-1">
|
||||
<option>2015년 하수도정비기본계획</option>
|
||||
</select>
|
||||
</div>
|
||||
</> : null}
|
||||
</div>
|
||||
<div className="flex justify-end mt-4 space-x-2">
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closePopup}>
|
||||
저장
|
||||
</button>
|
||||
<button className="px-4 py-2 bg-gray-600 text-white rounded" onClick={closePopup}>
|
||||
종료
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default InfilChart
|
||||
@@ -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 (
|
||||
<div><VerticalTable headName='자체 입력정보' tableData={[]} headlist={inputColumn} pageSize={0} total={0} children={undefined} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default sewagePump
|
||||
@@ -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 (
|
||||
<div>
|
||||
<VerticalTable headName='자체 입력정보' tableData={[]} headlist={inputColumn} pageSize={20} total={0} children={undefined} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}></VerticalTable>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Smh;
|
||||
@@ -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<string, any> }) => {
|
||||
const validKey = inputColumn.map((item) => item.id);
|
||||
const filteredData = featureData && Object.entries(featureData).filter(([key]) => validKey.includes(key)).reduce((obj: Record<string, any>, [key, value]) => {obj[key] = value; return obj;}, {});
|
||||
return (
|
||||
<div><VerticalTable headName='자체 입력정보' tableData={[filteredData]} headlist={inputColumn} pageSize={0} total={0} children={undefined} cellClick={undefined} isEditable={true} onPageChange={function (page: number): void {
|
||||
throw new Error('Function not implemented.');
|
||||
}} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StormWaterPump
|
||||
@@ -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<any>([{}]) //테이블 데이터
|
||||
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 (
|
||||
<ContentLayout title='도시침수 예방사업' isLoading={isLoading}>
|
||||
<SearchDiv>
|
||||
<SearchFormLeft>
|
||||
<div className='flex items-center gap-5'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
|
||||
<DatePicker mode={'single'}
|
||||
selected={fromDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} />
|
||||
<span>~</span>
|
||||
<DatePicker mode={'single'}
|
||||
selected={toDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }} />
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">관리년도</Label>
|
||||
<SelectBox
|
||||
className="w-[90px] mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=""
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={(value: string | number) => setManageYear(String(value))}
|
||||
/>
|
||||
<span>~</span>
|
||||
<SelectBox
|
||||
className="w-[90px] mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=""
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={(value: string | number) => setMngQu(String(value))}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록자</Label>
|
||||
<Input
|
||||
className='w-[100px]'
|
||||
value={usr}
|
||||
onChange={(e) => setUsr(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">파일명</Label>
|
||||
<Input
|
||||
className='w-[100px]'
|
||||
value={pjNm}
|
||||
onChange={(e) => setpjNm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SearchFormLeft>
|
||||
<SearchFormRight>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={async () => await fetchData()} >조회</Button>
|
||||
</SearchFormRight>
|
||||
</SearchDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
|
||||
<div>
|
||||
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile} >파일 다운로드</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile} >삭제</Button>
|
||||
</div>
|
||||
</div>
|
||||
<UiTable headName='' tableData={tableData} headlist={tableHeadlist} pageSize={10} total={totalData} cellClick={(index) => { 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() }}></UiTable>
|
||||
</ListDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<OperFileUploadForm title='도시침수 예방사업 사업추진현황 등록' onSubmit={async (file, year, quater, cd, id) => { await registFile(file, year, quater, cd, id) }} />
|
||||
</ListDiv>
|
||||
</ContentLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
@@ -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: '등록자' }
|
||||
]
|
||||
@@ -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<Date>(()=>{const date = new Date(); date.setDate(date.getDate()-7); return date});
|
||||
const [toDate, setToDate] = useState<Date>(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<any>([{}])
|
||||
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 (
|
||||
<ContentLayout title='노후 하수관로 정비사업' isLoading={isLoading}>
|
||||
<SearchDiv>
|
||||
<SearchFormLeft>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex items-center space-x-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
|
||||
<DatePicker mode={'single'}
|
||||
selected={fromDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} />
|
||||
<span>~</span>
|
||||
<DatePicker mode={'single'}
|
||||
selected={toDate}
|
||||
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }} />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Label className="w-20 text-xl text-gray-600">관리년도</Label>
|
||||
<SelectBox
|
||||
className="w-[90px] mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=""
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={(value: string | number) => setManageYear(String(value))}
|
||||
/>
|
||||
<span>~</span>
|
||||
<SelectBox
|
||||
className="w-[90px] mr-3 ml-4"
|
||||
selectClass="rounded-lg bg-white"
|
||||
label=""
|
||||
selectArray={yearOptions}
|
||||
onSelectValue={(value: string | number) => setMngQu(String(value))}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">등록자</Label>
|
||||
<Input
|
||||
className='w-[100px] !text-2xl'
|
||||
value={usr}
|
||||
onChange={(e) => setUsr(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex items-center'>
|
||||
<Label className="w-20 text-xl text-gray-600">파일명</Label>
|
||||
<Input
|
||||
className='w-[100px] !text-2xl'
|
||||
value={pjNm}
|
||||
onChange={(e) => {setpjNm(e.target.value)}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SearchFormLeft>
|
||||
<SearchFormRight>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 mr-2" size="sm" onClick={async () => {await fetchData()}}>조회</Button>
|
||||
</SearchFormRight>
|
||||
</SearchDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
|
||||
<div>
|
||||
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile}>파일 다운로드</Button>
|
||||
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile}>삭제</Button>
|
||||
</div>
|
||||
</div>
|
||||
<UiTable headName='' tableData={tableData} headlist={tableHeadlistOldPp} pageSize={10} total={totalData} children={undefined} cellClick={(index) => { 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()}}></UiTable>
|
||||
</ListDiv>
|
||||
<ListDiv className="mt-4">
|
||||
<OperFileUploadForm title='노후 하수관로 정비사업 주진현황 등록' onSubmit={async (file, year, quater, cd, id) => { await registFile(file, year, quater, cd, id) }} />
|
||||
</ListDiv>
|
||||
</ContentLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
@@ -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 (
|
||||
<div>
|
||||
<div><h3 className="text-2xl text-bold gap-4 mx-4">하수관망도</h3>
|
||||
<div className="flex flex-row gap-4 p-4">
|
||||
<Link href={"/map"}><Button>하수관망도</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
<div><h3 className="text-2xl text-bold gap-4 mx-4">운영정보 관리</h3>
|
||||
<div className="flex flex-row gap-4 p-4">
|
||||
<Link href={"/oper/floodPre"}><Button>도시침수 예방사업</Button></Link>
|
||||
<Link href={"/oper/oldPp"}><Button>노후 하수관로 정비사업</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
<div><h3 className="text-2xl text-bold gap-4 mx-4">I/I 분석(기초정보 설정)</h3>
|
||||
<div className="flex flex-row gap-4 p-4">
|
||||
<Link href={"/ii/irsetting"}><Button>침입수 분석</Button></Link>
|
||||
<Link href={"/ii/rdii"}><Button>RDII 분석</Button></Link>
|
||||
<Link href={"/ii/result"}><Button>침입수 분석 결과</Button></Link>
|
||||
<Link href={"/ii/rdii_result"}><Button>RDII 분석 결과</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
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");
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { useUserStore, type IUserInfo } from "./user-store";
|
||||
@@ -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<UserStore>()(
|
||||
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<UserStore>()((set) => ({
|
||||
...initState,
|
||||
setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })),
|
||||
}));
|
||||
};
|
||||
@@ -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*",
|
||||
],
|
||||
|
||||
};
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 455 B |
|
After Width: | Height: | Size: 167 B |
|
After Width: | Height: | Size: 167 B |
|
After Width: | Height: | Size: 164 B |
|
After Width: | Height: | Size: 165 B |
|
After Width: | Height: | Size: 165 B |
|
After Width: | Height: | Size: 163 B |
@@ -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 (
|
||||
<html lang="ko" data-theme={theme?.value}>
|
||||
<body>
|
||||
<AppProvider>{children}</AppProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
};
|
||||
|
||||
export { App };
|
||||
@@ -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 (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StoreProvider>
|
||||
<PromptProvider>
|
||||
<ConfirmProvider>
|
||||
<AuthWrapper>
|
||||
<MenuWrapper>
|
||||
<DndProvider
|
||||
backend={MultiBackend}
|
||||
options={getBackendOptions()}
|
||||
>
|
||||
{children}
|
||||
</DndProvider>
|
||||
</MenuWrapper>
|
||||
<AlertDialog />
|
||||
<PromptDialog />
|
||||
<ConfirmDialog />
|
||||
</AuthWrapper>
|
||||
</ConfirmProvider>
|
||||
</PromptProvider>
|
||||
</StoreProvider>
|
||||
<div className="text-2xl">
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</div>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export { AppProvider };
|
||||
@@ -0,0 +1 @@
|
||||
export { AppProvider } from "./app-provider";
|
||||
@@ -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<void>;
|
||||
silentRefresh(): Promise<void>;
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -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<IUserInfo>(
|
||||
`${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 };
|
||||
@@ -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;
|
||||
@@ -0,0 +1 @@
|
||||
export { MenuAuthorityApi } from "../api/menu-authority-service";
|
||||
@@ -0,0 +1 @@
|
||||
export { AuthorityButton } from "../ui/authority-button";
|
||||
@@ -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<MenuAuthorityList> {
|
||||
const response = await client.get<MenuAuthorityList>(
|
||||
`${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
|
||||
{ params },
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
public async getPageMenuAuthority(
|
||||
menuCd: number,
|
||||
): Promise<PageMenuAuthority[]> {
|
||||
const response = await client.get<PageMenuAuthority[]>(
|
||||
`${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}/pageinfo/${menuCd}`,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
public async saveMenuAuthority(data: MenuAuthorityPayload[]): Promise<void> {
|
||||
const response = await client.post<void>(
|
||||
`${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
|
||||
data,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const MenuAuthorityApi = new MenuAuthorityApiService();
|
||||
@@ -0,0 +1,2 @@
|
||||
export { AuthorityButton } from "./ui/authority-button";
|
||||
export { ManagementAuthorityDialog } from "./ui/management-authority-dialog";
|
||||
@@ -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<typeof menuAuthoritySchema>;
|
||||
export type MenuAuthorityList = PageableList<MenuAuthority>;
|
||||
export type MenuAuthorityPayload = z.infer<typeof menuAuthorityPayloadSchema>;
|
||||
export type MenuAuthorityFormData = z.infer<typeof menuAuthorityFormSchema>;
|
||||
|
||||
export interface MenuAuthorityService {
|
||||
getMenuAuthorityList(params: MenuAuthorityParams): Promise<MenuAuthorityList>;
|
||||
getPageMenuAuthority(menuCd: number): Promise<PageMenuAuthority[]>;
|
||||
saveMenuAuthority(data: MenuAuthorityPayload[]): Promise<void>;
|
||||
}
|
||||
@@ -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<MenuAuthorityFormData>,
|
||||
): ColumnDef<MenuAuthority>[] => {
|
||||
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 (
|
||||
<Checkbox
|
||||
checked={getCurrentRow(row.index)?.mngAuthrtYn === "Y"}
|
||||
onCheckedChange={(checked) => {
|
||||
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 (
|
||||
<Checkbox
|
||||
checked={getCurrentRow(row.index)?.regAuthrtYn === "Y"}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
handleCheckedChange(
|
||||
row.index,
|
||||
"inqAuthrtYn",
|
||||
)(checked as boolean);
|
||||
}
|
||||
handleCheckedChange(row.index, "regAuthrtYn")(checked as boolean);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "mdfcnAuthrtYn",
|
||||
header: "수정권한 ",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Checkbox
|
||||
checked={getCurrentRow(row.index)?.mdfcnAuthrtYn === "Y"}
|
||||
onCheckedChange={handleCheckedChange(row.index, "mdfcnAuthrtYn")}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "delAuthrtYn",
|
||||
header: "삭제권한",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Checkbox
|
||||
checked={getCurrentRow(row.index)?.delAuthrtYn === "Y"}
|
||||
onCheckedChange={handleCheckedChange(row.index, "delAuthrtYn")}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inqAuthrtYn",
|
||||
header: "조회권한",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Checkbox
|
||||
checked={getCurrentRow(row.index)?.inqAuthrtYn === "Y"}
|
||||
onCheckedChange={handleCheckedChange(row.index, "inqAuthrtYn")}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -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 (
|
||||
<Button className={cn(className, !isAuthority && "hidden")} {...props}>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export { AuthorityButton };
|
||||
@@ -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<typeof Dialog>;
|
||||
|
||||
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<MenuAuthorityFormData>({
|
||||
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 (
|
||||
<Dialog {...props}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="gap-3" disabled={!menuCd}>
|
||||
<i className="diveicon di-personal-information" />
|
||||
권한관리
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>그룹별 메뉴 권한</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="max-h-[40rem] overflow-auto">
|
||||
<DataTable table={table} />
|
||||
</div>
|
||||
<DialogFooter className="!justify-center">
|
||||
<Button size="lg" onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
<DialogClose asChild>
|
||||
<Button size="lg" color="white">
|
||||
취소
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export { ManagementAuthorityDialog };
|
||||
@@ -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<MenuItem[]> {
|
||||
const response = await client.get<MenuItem[]>(
|
||||
`${ENDPOINT.CMS_SERVICE.MENU_ROLES}/${siteId}`,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const MenuApi = new MenuApiService();
|
||||
@@ -0,0 +1,2 @@
|
||||
export { MenuWrapper } from "./lib/menu-wrapper";
|
||||
export type { MenuItem } from "./model/menu-interface";
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { MenuAuthorityApi } from "@/entities/menu-authority/@x/menu";
|
||||
import { useAlertStore, useMenuStore } from "@/shared/lib";
|
||||
import { getCookie } from "@/shared/lib";;
|
||||
import { SITE_ID } from "@/shared/config";
|
||||
import { MenuApi } from "../api/menu-service";
|
||||
import { getCurrentMenu } from "./utils";
|
||||
|
||||
const MenuWrapper = ({ children }: { children: React.ReactNode }) => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { pageMenuAuthority, setCurrentMenuInfo, setPageMenuAuthority } =
|
||||
useMenuStore((state) => state);
|
||||
|
||||
const getCurrentMenuInfo = async () => {
|
||||
const menuRoles = await MenuApi.getMenuRoles(SITE_ID);
|
||||
if (!menuRoles) return;
|
||||
return getCurrentMenu(menuRoles, pathname ?? "");
|
||||
};
|
||||
|
||||
const getPageMenuAuthority = async () => {
|
||||
const menuCd = getCookie("menu-code-key");
|
||||
if (!menuCd) return;
|
||||
const response = await MenuAuthorityApi.getPageMenuAuthority(
|
||||
parseInt(menuCd),
|
||||
);
|
||||
return response;
|
||||
};
|
||||
|
||||
const checkInquiryAuthority = () => {
|
||||
return pageMenuAuthority?.inqAuthrtYn === "Y";
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const currentMenu = await getCurrentMenuInfo();
|
||||
if (currentMenu) setCurrentMenuInfo(currentMenu);
|
||||
|
||||
const response = await getPageMenuAuthority();
|
||||
if (response?.length) setPageMenuAuthority(response[0]!);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pageMenuAuthority) return;
|
||||
const inquiryAuthority = checkInquiryAuthority();
|
||||
if (!inquiryAuthority)
|
||||
alert("페이지에 대한 조회 권한이 없습니다.", () => router.push("/"));
|
||||
}, [pageMenuAuthority]);
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
export { MenuWrapper };
|
||||