Compare commits

...
Author SHA1 Message Date
mind-one003 c72fa450bc 엑셀다운로드 자연수까지 나오도록 array추가 2025-09-23 14:06:45 +09:00
mind-one003 400d6cf732 엑셀 숫자형식 다운로드 추가 2025-09-23 11:07:23 +09:00
swcho 39e2734a49 fix: searchBar.tsx 하수처리시설 검색 에러 수정 2025-09-22 09:54:35 +09:00
mind-one003 d92d4d3949 - 테이블 비율 고정 변수 추가(wideFixed)
- store headerlist 에서 비율 변수 추가(widePercent)
2025-09-17 16:15:11 +09:00
mind-one003 b93efa5503 라인바, 라인차트 x축 라벨 크기 확대 2025-09-11 11:17:37 +09:00
swcho 0b8559891a remove: Gis.js에서 SearchView 컴포넌트 props 삭제 2025-09-09 09:54:40 +09:00
mind-one003 ffa1781005 라인바 차트 좌측 여백 및 라벨 좌측으로 좀 더 이동 2025-09-05 14:21:39 +09:00
mind-one003 b47c0dff2b 라인바 차트 크기 수정, custom left 축 만드는 로직 추가 2025-09-05 13:49:22 +09:00
mind-one003 83f5d878e7 라인바 y축 범위 수정 2025-09-02 16:44:43 +09:00
swcho e815b9662f remove: comboSearchBar index 삭제 2025-09-02 16:00:49 +09:00
swcho 2e6cbad49c remove, refactor:
- comboSearchBar.tsx 삭제
- any 타입 추가
- procSearchBar 시군구, 시설 가나다순 정렬
2025-09-02 15:52:13 +09:00
swcho ede5ef6a21 refactor: GisTree.js 주석 추가 및 최신화 2025-09-02 11:06:37 +09:00
11 changed files with 250 additions and 402 deletions
@@ -109,6 +109,41 @@ export default function LineBarchart({
const lineMaxValue = getMaxValue(chartData, 'lineVal');
const barMaxValue = getMaxValue(chartData, 'barVal');
/**
* 최대값과 구간 수에 따른 범례 만들기
* maxValue : 최대값, segments : 구간 수 (구간수가 5면 눈금은 6)
*/
const makeNiceScale = (maxValue: number, segments = 5) => {
// 최대값이 이상할 경우 0, 0으로 반환
if (!isFinite(maxValue) || maxValue <= 0) {
return { max: 0, ticks: [0] };
}
const exponent = Math.floor(Math.log10(maxValue));
const base = Math.pow(10, exponent);
const fraction = maxValue / base;
let niceFraction: number;
if (fraction <= 1) niceFraction = 1;
else if (fraction <= 2) niceFraction = 2;
else if (fraction <= 3) niceFraction = 3;
else if (fraction <= 4) niceFraction = 4;
else if (fraction <= 5) niceFraction = 5;
else if (fraction <= 6) niceFraction = 6;
else if (fraction <= 7) niceFraction = 7;
else if (fraction <= 8) niceFraction = 8;
else if (fraction <= 9) niceFraction = 9;
else niceFraction = 10;
const niceMax = niceFraction * base; // round up to 1/2/5 * 10^k
const step = niceMax / segments;
const ticks = Array.from({ length: segments + 1 }, (_, i) => Number((i * step).toFixed(10)));
return { max: niceMax, ticks };
};
const leftScale = makeNiceScale(lineMaxValue, 5);
const rightScale = makeNiceScale(barMaxValue, 5);
const getTicks = (data : any []) => {
const monthSet = new Set<string>();
const rtnData : string[] = [];
@@ -135,7 +170,7 @@ export default function LineBarchart({
return (
<text
x={x - padding} // 맨 좌측 바깥
y={y + height / 2} // 수직 중앙
y={y + height / 2 - 12} // 수직 중앙
textAnchor="middle"
transform={`rotate(-90, ${x - padding}, ${y + height / 2})`}
className="text-[12px] font-bold"
@@ -166,26 +201,27 @@ export default function LineBarchart({
</div>
) : null}
<div className="h-[calc(100%-42px)] w-[calc(100%-40px)] ">
<ChartContainer config={chartConfig ?? {}} className="h-full w-full">
<ChartContainer config={chartConfig ?? {}} className="h-full w-[100%] ml-5">
<ComposedChart
data={chartData}
height={graphSize * 7.5}
width={graphSize * 12.5}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
margin={{ top: 5, right: 20, left: 30, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
{setXAxisYearTick?
<XAxis dataKey="label" ticks={monthTicks} tickFormatter={(value) => value.slice(0,7)} fontSize="8px" fontWeight="bold"/> :
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
<XAxis dataKey="label" ticks={monthTicks} tickFormatter={(value) => value.slice(0,7)} className="text-[12px] font-bold" /> :
<XAxis dataKey="label" className="text-[12px] font-bold" />
}
{/* 왼쪽 Y축: lineVal */}
{yFieldText && <YAxis
yAxisId="left"
className="text-[12px] font-bold"
tickCount={6}
className="text-[12px] font-bold"
tickFormatter={(value) =>
typeof value === "number" ? value.toLocaleString() : value
}
domain={[0, leftScale.max]}
ticks={leftScale.ticks}
orientation="left"
label={(props) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}
/>}
@@ -193,12 +229,13 @@ export default function LineBarchart({
{yFieldText2 && <YAxis
yAxisId="right"
className="text-[12px] font-bold"
tickCount={6}
orientation="right"
tickFormatter={(value) =>
typeof value === "number" ? value.toLocaleString() : value
}
label={(props) => <CustomAxisText {...props} fieldText={yFieldText} position="right" />}
domain={[0, rightScale.max]}
ticks={rightScale.ticks}
label={(props) => <CustomAxisText {...props} fieldText={yFieldText2} position="right" />}
reversed={true}
/>}
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
@@ -235,15 +235,13 @@ export default function Linechart({
{setXAxisYearTick ?
<XAxis
dataKey="label"
fontSize="8px"
fontWeight="bold"
className="text-[12px] font-bold"
ticks={monthTicks}
tickFormatter={(value) => value.slice(0,7)}
/> :
<XAxis
dataKey="label"
fontSize="8px"
fontWeight="bold"
className="text-[12px] font-bold"
/>
}
@@ -6,6 +6,10 @@ type ExcelDownloadProps = {
fileName: string;
sheetNameArray: string[];
headerRange?: string;
decimalArray0? : number[];
decimalArray1? : number[];
decimalArray2? : number[];
decimalArray3? : number[];
}
export const downloadExcel = ({ data, fileName = new Date().getTime().toString() + '.xlsx', sheetNameArray = ["Sheet1"], headerRange='A1:V3'}: ExcelDownloadProps) => {
@@ -15,6 +19,45 @@ export const downloadExcel = ({ data, fileName = new Date().getTime().toString()
excelStyle(XLSX.write(workbook, { bookType: "xlsx", type: "buffer" }), headerRange, fileName);
};
export const downloadExcelFormat = ({ data, fileName = new Date().getTime().toString() + '.xlsx', sheetNameArray = ["Sheet1"], headerRange='A1:V3', decimalArray0=[], decimalArray1=[], decimalArray2=[], decimalArray3=[]}: ExcelDownloadProps) => {
const worksheet = XLSX.utils.json_to_sheet(Array.isArray(data) ? data : [data]);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, sheetNameArray[0]);
console.log('decimalArray0 : ', decimalArray0);
const headerEnd = XLSX.utils.decode_range(headerRange).e.r; // 0-based index
const startRow = headerEnd + 1;
// 🔹 전체 범위
const range = XLSX.utils.decode_range(worksheet["!ref"] as string);
const chaneValue = (array: number[], decimal: number) => {
for (let row = startRow; row <= range.e.r; row++) {
if(array.length>0){
for(let idx=0; idx<array.length; idx++){
const cellAddr = XLSX.utils.encode_cell({ r: row, c: Number(array[idx]) });
const cell = worksheet[cellAddr];
if (cell && typeof cell.v === "number") {
if(decimal===1){
cell.z = "#,##0.0"; // 소수점 3자리
}else if(decimal===2){
cell.z = "#,##0.00";
}else if(decimal===3){
cell.z = "#,##0.000";
}else{
cell.z = "#,##0"; // 기본 천단위 콤마
}
}
}
}
}
};
chaneValue(decimalArray0, 0);
chaneValue(decimalArray1, 1);
chaneValue(decimalArray2, 2);
chaneValue(decimalArray3, 3);
excelStyle(XLSX.write(workbook, { bookType: "xlsx", type: "buffer" }), headerRange, fileName);
};
export type SheetParameter = {
data: any[][];
headerNum: number;
@@ -331,11 +331,7 @@ function Gis({
)}
{/* SearchView가 존재할 때만 렌더링 */}
{SearchView && (
<SearchView
open={isSearchModalOpen}
onOpenChange={setIsSearchModalOpen}
onFeatureSelect={handleFeatureSelect}
/>
<SearchView />
)}
{/* 시도/시군구 조회 영역 */}
{SearchBar && (
@@ -10,6 +10,24 @@ import React, { useEffect, useState, useRef, useCallback } from "react";
import { useGisContext } from "./Gis";
import GisApp from "./lib/gis.core";
/**
* GisTree (React memoized component)
*
* 계층형 GIS 레이어 트리를 렌더링하고, 체크 상태에 따라 지도상의 레이어 On/Off를 제어합니다.
* 또한 특정 순서/간격으로 레이어를 자동으로 토글하는 애니메이션 기능을 제공합니다.
*
* Props 요약
* - checkedNodes, setCheckedNodes: (선택) 외부 관리 체크 상태 (현재 내부 state 사용)
* - visible, setVisible: 사이드 패널 가시성 on/off
* - onCheckedChange(checkedIds, checkedNodesData): 체크 변경 시 콜백
* - onLayerIconClick(nodeNm): 각 노드의 미리보기/아이콘 클릭 시 콜백
* - imageVisible: 레이어 옆 아이콘(썸네일) 노출 여부
* - isPlaying, setIsPlaying: 자동 애니메이션 재생 상태 제어
* - targetLayerTypes: 자동 애니메이션 대상이 되는 레이어 type 배열 (예: ['tb_ms_swage_mhl'])
* - orderedLayers: 레이어 재생 순서를 지정하는 id 배열 (lyrSn)
* - checkInterval: 자동 애니메이션 토글 간격(ms)
* - onProgressChange(total, current): 애니메이션 진행상태 콜백
*/
export default React.memo(function GisTree({
checkedNodes = [],
setCheckedNodes = () => { },
@@ -25,17 +43,29 @@ export default React.memo(function GisTree({
onProgressChange = () => { },
}) {
const { gisCore, treeData } = useGisContext();
// 체크/확장/노드/탭 상태
const [checked, setChecked] = useState([]);
const [expanded, setExpanded] = useState([]);
const [nodes, setNodes] = useState([]);
const [activeTab, setActiveTab] = useState("layers");
// 자동 애니메이션 관련 ref (실행 인덱스, 대상 노드 목록, 일시정지, 타이머)
const currentAnimationIndexRef = useRef(0);
const targetNodesRef = useRef([]);
const isPausedRef = useRef(false);
const timeoutIdRef = useRef(null);
// ===== 유틸 =====
// =====================
// 유틸리티: 트리 탐색 관련 함수들
// =====================
/**
* 주어진 id의 모든 하위(자손) 노드 id를 평탄 배열로 반환합니다.
* @param {number|string} id 기준 노드 id
* @param {Array} all 전체 노드 배열
* @returns {Array} 자손 노드 id 배열
*/
const getDescendants = (id, all) => {
const children = all.filter((n) => n.parent === id);
return children.reduce(
@@ -44,40 +74,64 @@ export default React.memo(function GisTree({
);
};
/**
* 주어진 id의 모든 상위(조상) 노드 id를 상단부터 배열로 반환합니다.
* @param {number|string} id 기준 노드 id
* @param {Array} all 전체 노드 배열
* @returns {Array} 조상 노드 id 배열
*/
const getAncestors = (id, all) => {
const node = all.find((n) => n.id === id);
if (!node || node.parent == null) return [];
return [node.parent, ...getAncestors(node.parent, all)];
};
const getChildren = (parentId, all) =>
all.filter((n) => n.parent === parentId);
/**
* 특정 parentId의 직계 자식 노드 리스트를 반환합니다.
*/
const getChildren = (parentId, all) => all.filter((n) => n.parent === parentId);
/**
* parentId의 모든 직계 자식이 checkedIds에 포함되어 있는지 확인합니다.
*/
const areAllChildrenChecked = (parentId, all, checkedIds) => {
const children = getChildren(parentId, all);
return children.length > 0 && children.every((c) => checkedIds.includes(c.id));
};
/**
* 어떤 노드의 체크 변경 이후, 상위 부모까지 올라가며 체크 상태를 전파/정리합니다.
* - 모든 자식이 체크되면 부모도 체크
* - 일부라도 해제되면 부모 해제
*/
const updateParentCheckState = (nodeId, all, checkedIds) => {
const parent = all.find((n) => n.id === nodeId)?.parent;
if (parent == null) return checkedIds;
if (areAllChildrenChecked(parent, all, checkedIds)) {
if (!checkedIds.includes(parent)) {
checkedIds.push(parent);
}
if (!checkedIds.includes(parent)) checkedIds.push(parent);
} else {
checkedIds = checkedIds.filter((id) => id !== parent);
}
return updateParentCheckState(parent, all, checkedIds);
};
/**
* parentId의 모든 직계 자식이 checked 배열에 포함되어 있는지 확인합니다.
*/
const isEveryChildChecked = (parentId, all, checked) => {
const children = getChildren(parentId, all);
return children.length > 0 && children.every((c) => checked.includes(c.id));
};
// ===== 기본 체크 노드 =====
// =====================
// 기본 체크 노드 계산
// =====================
/**
* 초기 렌더 시 기본으로 체크할 노드 id 목록을 반환합니다.
* - data.initEprssYn === 'Y' 인 노드 + 부모 전파
*/
const getDefaultCheckedNodes = (nodes) => {
let checkedIds = nodes
.filter((n) => n.data.initEprssYn === "Y")
@@ -90,7 +144,13 @@ export default React.memo(function GisTree({
return Array.from(new Set(checkedIds));
};
// ===== 초기 로딩 =====
// =====================
// 초기 로딩: 트리 데이터 세팅 & 초기 체크/확장 & 지도 반영
// =====================
/**
* treeData가 들어오면 노드 변환 후, 모든 레이어를 지도에서 잠시 비활성화합니다.
*/
useEffect(() => {
if (treeData && treeData.length > 0) {
const nodeData = setNodeValues(treeData);
@@ -99,11 +159,15 @@ export default React.memo(function GisTree({
}
}, [treeData]);
/**
* nodes가 준비되면 기본 체크/확장 상태를 계산하고, 실제 지도 레이어 on/off 반영 및 콜백 호출.
*/
useEffect(() => {
if (nodes.length > 0) {
const defaultChecked = getDefaultCheckedNodes(nodes);
setChecked(defaultChecked);
// 기본 확장 = 체크된 노드 + 그 조상들
const defaultExpanded = Array.from(
new Set([
...defaultChecked,
@@ -112,6 +176,7 @@ export default React.memo(function GisTree({
);
setExpanded(defaultExpanded);
// 지도 반영
gisCore.setLayerOnMap(defaultChecked, true);
const defaultCheckedNodesData = nodes.filter((node) =>
@@ -121,7 +186,16 @@ export default React.memo(function GisTree({
}
}, [nodes]);
// ===== 체크 이벤트 =====
// =====================
// 체크 이벤트: 트리에서 체크 박스 클릭 시 처리
// =====================
/**
* 단일 노드 체크/해제 처리 핸들러
* - 체크 시: 자신 + 모든 자손 체크
* - 해제 시: 자신 + 모든 자손 해제
* - 이후 부모 상태 전파 및 지도 레이어 on/off 반영, 콜백 호출
*/
const handleCheck = (id) => {
setChecked((prevChecked) => {
let newChecked = [...prevChecked];
@@ -312,6 +386,9 @@ export default React.memo(function GisTree({
isPausedRef.current = true;
}, []);
/**
* 재생/정지/대상/간격 변경에 반응하여 애니메이션을 관리합니다.
*/
useEffect(() => {
if (isPlaying)
handleAutoCheckAnimation(true, targetLayerTypes, checkInterval);
@@ -324,15 +401,23 @@ export default React.memo(function GisTree({
pauseAnimation,
]);
/**
* 언마운트 시 타이머 정리.
*/
useEffect(() => {
return () => {
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current);
}
if (timeoutIdRef.current) clearTimeout(timeoutIdRef.current);
};
}, []);
// ===== 노드 세팅 =====
// =====================
// 노드/아이콘 렌더링 데이터 준비
// =====================
/**
* 서버에서 내려온 트리 데이터를 Tree 컴포넌트가 요구하는 구조로 변환합니다.
* - id, text, parent, droppable, data, icon
*/
const setNodeValues = (result) => {
return result.map((item) => {
const src = makeLegendSrc(item);
@@ -347,7 +432,9 @@ export default React.memo(function GisTree({
});
};
/**
* 레이어 정보로부터 범례 이미지 경로 또는 동적 생성 이미지를 반환합니다.
*/
const makeLegendSrc = (layerinfo) => {
if (!layerinfo.gobjTy) return null;
if (layerinfo.iconNm) {
@@ -357,6 +444,9 @@ export default React.memo(function GisTree({
}
};
/**
* 레이어 스타일 정보를 기반으로 작은 캔버스에 간단한 범례 이미지를 그려 dataURL을 생성합니다.
*/
const makeLegendImage = (layerinfo) => {
let image = document.createElement("img");
let canvas = document.createElement("canvas");
@@ -401,11 +491,18 @@ export default React.memo(function GisTree({
return image;
};
/**
* 각 레이어 행의 아이콘 클릭 시 호출. 선택되지 않은 레이어면 경고, 선택된 경우 콜백 전달.
*/
const handleLayerImgClick = (nodeNm, nodeId) => {
if (!checked.includes(nodeId)) alert("시설을 선택해주세요");
else onLayerIconClick(nodeNm);
};
// =====================
// 렌더링
// =====================
if (!treeData || treeData.length === 0) return null;
return (
@@ -1,341 +0,0 @@
"use client";
import { SelectBox, type SelectDataType } from "../../../ui";
import { Button } from "@common/components/ui";
import { useCallback, useEffect, useState } from "react";
const geoserverUrl =
"/geoserver/hasudo/ows?service=WFS&version=1.0.0&request=GetFeature&outputFormat=application/json";
const FACILITY_TYPE_URL_MAP: Record<string, string> = {
tb_il_swage_prcs_fclt: geoserverUrl, //하수처리시설
tb_wr_bdst_ruse_fclt:
"/reuse-service/reuseFc/pubDetailList/{year}/{sggCd}/1/1000", //재이용시설 post
tb_wr_rnwtr_utztn_fclt: "/reuse-service/reuseFc/rainyInfoList/1/1000/{sggCd}", //빗물이용시설 get
tb_wr_rswtr_fclt: "/reuse-service/reuseFc/waterreuseFc/1/1000/{sggCd}", //중수도시설 get
tb_wr_htdfl_fclt: "/reuse-service/drain/facilityList/1/1000/{sggCd}", //온배수시설 get
tb_wr_ruse_fclt_dmd_co: "/reuse-service/reuseFc/request/1/1000/{sggCd}", //수요처 get
tb_wr_tmpr_dmd_co:
"/reuse-service/reuseFc/request/temp/1/1000/{sidoNm} {sggNm}", //잠재수요처 get
};
interface SearchBarProps {
onFeatureSelect: (feature: any) => void;
gisMaps: React.RefObject<any>;
facilityTypes: { text: string; val: string }[];
}
export const ComboSearchBar = ({
onFeatureSelect,
gisMaps,
facilityTypes,
}: SearchBarProps) => {
const [sidoValue, setSidoValue] = useState("0");
const [sigunValue, setSigunValue] = useState("0");
const [sidoData, setSidoData] = useState<SelectDataType[]>([
{ text: "선택", val: "0" },
]);
const [sigunData, setSigunData] = useState<SelectDataType[]>([
{ text: "선택", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<SelectDataType[]>([
{ text: "선택", val: "0" },
]);
const [facilityData, setFacilityData] = useState<SelectDataType[]>([
{ text: "선택", val: "0" },
]);
const [facilityValue, setFacilityValue] = useState("0");
const [facilityType, setFacilityType] = useState(
facilityTypes?.length === 1 && facilityTypes[0]
? facilityTypes[0].val
: "0",
);
//시도, 시군구 조회
const fetchSido = async () => {
const url = `/geoserver/hasudo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hasudo:tb_ms_ctpv&outputFormat=application/json&propertyName=mctpv_korn_nm,mctpv_cd`;
const res = await fetch(url).then(res => res.json());
const list = res.features
.map((f: any) => ({
text: f.properties.mctpv_korn_nm,
val: f.properties.mctpv_cd,
})).sort((a, b) => {
// 커스텀 순서 정의
const customOrder = [
"서울특별시",
"부산광역시",
"대구광역시",
"인천광역시",
"광주광역시",
"대전광역시",
"울산광역시",
"세종특별자치시",
"경기도",
"강원특별자치도", // 경기도 다음에 배치
"충청북도",
"충청남도",
"전북특별자치도", // 충청남도 다음에 배치
"전라남도",
"경상북도",
"경상남도",
"제주특별자치도"
];
const indexA = customOrder.indexOf(a.text);
const indexB = customOrder.indexOf(b.text);
// 둘 다 커스텀 순서에 있으면 해당 순서로
if (indexA !== -1 && indexB !== -1) {
return indexA - indexB;
}
// 하나만 커스텀 순서에 있으면 그것을 앞으로
if (indexA !== -1) return -1;
if (indexB !== -1) return 1;
// 둘 다 커스텀 순서에 없으면 기본 알파벳 순서
return a.text.localeCompare(b.text, 'ko');
});
setSidoData([{ text: "선택", val: "0" }, ...list]);
};
const fetchSigungu = async () => {
const url = `/geoserver/hasudo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hasudo:tb_ms_sgg&outputFormat=application/json&propertyName=sgg_cd,sgg_korn_nm`;
const res = await fetch(url).then(res => res.json());
const list = res.features
.map((f: any) => ({
text: f.properties.sgg_korn_nm,
val: f.properties.sgg_cd,
}))
.sort((a, b) => a.text.localeCompare(b.text, 'ko'));
setSigunData(list);
};
//시설명 콤보박스 조회
const fetchFacilitiesBySggNm = async (
sggCd: string,
sggNm: string,
sidoNm: string,
currentFacilityType?: string,
) => {
const type = currentFacilityType ?? facilityType;
if (!type || type === "0") return;
const baseUrlTemplate = FACILITY_TYPE_URL_MAP[type];
if (!baseUrlTemplate) return;
const year = new Date().getFullYear().toString();
let url = baseUrlTemplate
.replace("{year}", year)
.replace("{sggCd}", sggCd)
.replace("{sidoNm}", encodeURIComponent(sidoNm))
.replace("{sggNm}", encodeURIComponent(sggNm));
let list: SelectDataType[] = [];
if (
type === "tb_il_swage_prcs_fclt" //하수처리시설
) {
const cqlFilter = `ctpv_nm='${encodeURIComponent(sidoNm)}' AND sgg_nm='${encodeURIComponent(sggNm)}'`;
url = `${url}&typeName=hasudo:${type}&cql_filter=${cqlFilter}`;
const res = await fetch(url);
const json = await res.json();
list = json.features.map((f: any) => ({
text: f.properties.swtrmt_fclt_nm ?? "(이름없음)",
val: f.id,
}));
} else if (
type === "tb_wr_bdst_ruse_fclt" // 재이용시설
) {
//재용에서 참조하는 하수처리시설 목록
const paramsRes = await fetch("/reuse-service/reuseFc/pubFc");
const paramsJson = await paramsRes.json();
const params = paramsJson.data;
const res = await fetch(url, {
method: "POST",
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(params),
});
const json = await res.json();
list = (json.data || []).map((item: any) => ({
text: item.ruseUtztnFcltNm ?? "(이름없음)",
val: item.pbnstRuseFcltId,
}));
} else if (
type === "tb_wr_ruse_fclt_dmd_co" //수요처
) {
const res = await fetch(url);
const json = await res.json();
list = (json.data || []).map((item: any) => ({
text: item.dmdCoNm ?? "(이름없음)",
val: item.dmdInfoId,
}));
} else if (
type === "tb_wr_tmpr_dmd_co" //잠재수요처
) {
// GET 방식
const res = await fetch(url);
const json = await res.json();
list = (json.data || []).map((item: any) => ({
text: item.dmdCoNm ?? "(이름없음)",
val: item.fctryMngSn,
}));
} else {
// GET 방식
const res = await fetch(url);
const json = await res.json();
list = (json.data || []).map((item: any) => ({
text: item.bdstNm ?? "(이름없음)",
val: item.bdstInfoSn,
}));
}
setFacilityData([{ text: "선택", val: "0" }, ...list]);
setFacilityValue("0");
};
//시도, 시군구 초기 데이터 조회
useEffect(() => {
fetchSido();
fetchSigungu();
}, []);
//시군구 데이터 초기화
const initializeSigunData = useCallback(
(sidoCd: string) => {
if (sidoCd === "0") {
setFilteredSigunData([{ text: "선택", val: "0" }]);
setSigunValue("0");
return;
}
const prefix = sidoCd.substring(0, 2);
const filtered = sigunData.filter((item) => item.val.startsWith(prefix));
setFilteredSigunData([{ text: "선택", val: "0" }, ...filtered]);
setSigunValue("0");
},
[sigunData],
);
//콤보박스 선택시 연관 콤보박스 처리
const onSelectValue = useCallback(
(val: string, type: string) => {
if (type === "ctpvCd") {
setSidoValue(val);
initializeSigunData(val);
setFacilityData([{ text: "선택", val: "0" }]);
setFacilityValue("0");
} else if (type === "sggCd") {
setSigunValue(val);
const sidoNm =
sidoData.find((item) => item.val === sidoValue)?.text || "";
const sggNm = sigunData.find((item) => item.val === val)?.text || "";
const sggCd = sigunData.find((item) => item.val === val)?.val || "";
if (sggNm && sidoNm)
fetchFacilitiesBySggNm(sggCd, sggNm, sidoNm, facilityType);
} else if (type === "facilityType") {
setFacilityType(val);
setFacilityValue("0");
setFacilityData([{ text: "선택", val: "0" }]);
const sidoNm =
sidoData.find((item) => item.val === sidoValue)?.text || "";
const sggNm =
sigunData.find((item) => item.val === sigunValue)?.text || "";
const sggCd =
sigunData.find((item) => item.val === sigunValue)?.val || "";
if (sggNm && sidoNm) fetchFacilitiesBySggNm(sggCd, sggNm, sidoNm, val);
} else if (type === "fcltCd") {
setFacilityValue(val);
}
},
[initializeSigunData, sigunData, sigunValue, sidoData, sidoValue],
);
//조회 버튼 클릭
const handleSearch = () => {
if (!gisMaps.current || facilityValue === "0") return;
const layers = gisMaps.current.getLayers().getArray();
for (const layer of layers) {
const source = layer.getSource?.();
const feature = source?.getFeatureById?.(facilityValue);
if (feature) {
onFeatureSelect(feature);
return;
}
}
alert("해당 처리시설을 지도에서 찾을 수 없습니다.");
};
return (
<div className="grid grid-cols-4 gap-4">
<div className="col-span-4">
<div className="card card-border flex">
<div className="col-span-10 flex flex-row">
{facilityTypes.length > 1 && (
<SelectBox
labelClass="w-[120px]"
className="mr-10 w-[190px]"
selectClass="rounded-lg bg-white"
label="시설물유형"
selectArray={[{ text: "선택", val: "0" }, ...facilityTypes]}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "facilityType")
}
value={facilityType}
/>
)}
<SelectBox
labelClass="w-[40px]"
className="mr-5 w-[150px]"
selectClass="rounded-lg bg-white"
label=""
selectArray={sidoData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "ctpvCd")
}
value={sidoValue}
/>
<SelectBox
labelClass="w-[65px]"
className="mr-5 w-[150px]"
selectClass="rounded-lg bg-white"
label=""
selectArray={filteredSigunData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "sggCd")
}
value={sigunValue}
/>
<SelectBox
labelClass="w-[60px]"
className="mr-3 w-[180px]"
selectClass="rounded-lg bg-white"
label="시설명"
selectArray={facilityData}
onSelectValue={(val: any) =>
onSelectValue(val.toString(), "fcltCd")
}
value={facilityValue}
/>
</div>
<div className="flex flex-row space-x-2">
<Button
color="primary"
className="mx-2 ml-5 mt-1"
size={"sm"}
onClick={handleSearch}
>
조회
</Button>
</div>
</div>
</div>
</div>
);
};
@@ -1,3 +1,2 @@
export * from "./comboSearchBar";
export * from "./procSearchBar";
export * from './searchBar'
@@ -18,19 +18,10 @@ interface SearchBarProps {
export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
const [sidoValue, setSidoValue] = useState("0");
const [sigunValue, setSigunValue] = useState("0");
const [sidoData, setSidoData] = useState<SelectDataType[]>([
{ text: "시도", val: "0" },
]);
const [sigunData, setSigunData] = useState<SelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [filteredSigunData, setFilteredSigunData] = useState<SelectDataType[]>([
{ text: "시군구", val: "0" },
]);
const [facilityData, setFacilityData] = useState<SelectDataType[]>([
{ text: "하수처리시설", val: "0" },
]);
const [sidoData, setSidoData] = useState<SelectDataType[]>([{ text: "시도", val: "0" }]);
const [sigunData, setSigunData] = useState<SelectDataType[]>([{ text: "시군구", val: "0" }]);
const [filteredSigunData, setFilteredSigunData] = useState<SelectDataType[]>([{ text: "시군구", val: "0" }]);
const [facilityData, setFacilityData] = useState<SelectDataType[]>([{ text: "하수처리시설", val: "0" }]);
const [facilityValue, setFacilityValue] = useState("0");
const [facilityType, setFacilityType] = useState(
@@ -48,7 +39,7 @@ export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
text: f.properties.mctpv_korn_nm,
val: f.properties.mctpv_cd,
}))
.sort((a, b) => {
.sort((a: any, b: any) => {
// 커스텀 순서 정의
const customOrder = [
"서울특별시",
@@ -92,10 +83,12 @@ export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
const url = `/geoserver/hasudo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hasudo:tb_ms_sgg&outputFormat=application/json&propertyName=sgg_cd,sgg_korn_nm`;
const res = await fetch(url).then(res => res.json());
const list = res.features.map((f: any) => ({
text: f.properties.sgg_korn_nm,
val: f.properties.sgg_cd,
}));
const list = res.features
.map((f: any) => ({
text: f.properties.sgg_korn_nm,
val: f.properties.sgg_cd,
}))
.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
setSigunData(list);
};
@@ -128,10 +121,12 @@ export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
url = `${url}&typeName=hasudo:${type}&cql_filter=${cqlFilter}`;
const res = await fetch(url);
const json = await res.json();
list = json.features.map((f: any) => ({
text: f.properties.swtrmt_fclt_nm ?? "(이름없음)",
val: f.id,
}));
list = json.features
.map((f: any) => ({
text: f.properties.swtrmt_fclt_nm ?? "(이름없음)",
val: f.id,
}))
.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
} else if (
type === "tb_wr_bdst_ruse_fclt" // 재이용시설
) {
@@ -59,7 +59,7 @@ export const SearchBar = ({
const sidoList = json
.filter((item: any) => item.lwpoCd?.length === 2)
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }))
.sort((a, b) => {
.sort((a: any, b: any) => {
// 커스텀 순서 정의
const customOrder = [
"서울특별시",
@@ -99,7 +99,7 @@ export const SearchBar = ({
const sigunList = json
.filter((item: any) => item.lwpoCd?.length > 2)
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }))
.sort((a, b) => a.text.localeCompare(b.text, 'ko'));
.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
setSidoData([{ text: "시도", val: "0" }, ...sidoList]);
setSigunData(sigunList);
};
@@ -165,7 +165,10 @@ export const SearchBar = ({
let list: SelectDataType[] = [];
if (type === "tb_il_swage_prcs_fclt") {
const cqlFilter = `ctpv_nm='${sidoNm}' and sgg_nm='${sggNm}' and swtrmt_fclt_nm like '%${fcltyNm}%'`;
// 하수처리시설
let cqlFilter = `swtrmt_fclt_nm like '%${fcltyNm}%'`;
if (sggNm !== "시군구" && sggNm) cqlFilter = `sgg_nm='${sggNm}' and ` + cqlFilter;
if (sidoNm !== "시도" && sidoNm) cqlFilter = `ctpv_nm='${sidoNm}' and ` + cqlFilter;
url += encodeURIComponent(cqlFilter);
const res = await fetch(url);
const json = await res.json();
@@ -8,7 +8,8 @@ interface TableUpperProps {
row? : number;
rowSpan?: number;
colSpan?: number;
visible?:boolean;
visible?:boolean;
widthPercent?: number;
}
const HeadMakeColSpan = ({ upHeadList }: { upHeadList: TableUpperProps[] }) => {
@@ -52,7 +53,7 @@ const HeadMakeColSpan = ({ upHeadList }: { upHeadList: TableUpperProps[] }) => {
colSpan={head.colSpan || 1}
rowSpan={head.rowSpan || 1}
style={{ whiteSpace: 'pre-line' }}
className="bg-gray-50"
className="bg-gray-50"
>
{head.title}
</TableHead>
@@ -32,6 +32,7 @@ type UiTableProps = {
index?: number;
curPage?: number;
headButton?: React.ReactNode | undefined;
widthFixed?: boolean;
};
type UiHeadProps = {
@@ -39,6 +40,9 @@ type UiHeadProps = {
title: string;
align?: string;
visible?: boolean;
row?: number;
widthPercent?: number;
rowSpan?: number;
};
export function UiTable({
@@ -57,6 +61,7 @@ export function UiTable({
index = -1,
curPage = 1,
headButton = undefined,
widthFixed = false
}: UiTableProps) {
const [cur, setCur] = useState<number>(curPage);
const [idx, setIdx] = useState<number>(index);
@@ -104,6 +109,15 @@ export function UiTable({
}
};
const getLeafCols = (list: UiHeadProps[]) => {
const maxRow = list?.reduce((max, head) => Math.max(max, head.row || 0), 0);
return list
.filter(h => h.visible !== false)
.filter(h => ((h.row ?? 0) + (h.rowSpan ?? 1) - 1) >= maxRow)
;
};
const leafCols = getLeafCols(headlist);
return (
<>
@@ -122,7 +136,13 @@ export function UiTable({
<></>
)}
<div className={`card !p-0r !m-[1.2rem] ${className}`}>
<Table variant="secondary">
<Table variant="secondary" className={widthFixed?"table-fixed":""}>
{widthFixed?
<colgroup>
{leafCols.map(col => (
<col key={col.id} style={{ width: col.widthPercent ? `${col.widthPercent}%` : undefined }} />
))}
</colgroup>:""}
<TableHeader ref={headerRef} className="font-bold">
{children ? children : <HeadMakeColSpan upHeadList={headlist} />}
</TableHeader>