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
swcho 621d222799 remove: GisTree, Gis 에서 orderedLayers porps 삭제 2025-09-02 10:55:16 +09:00
mind-one003 01df37d0b3 라인차트 호출 시 config color에 dash붙을시 해당색상의 대시라인 생성 2025-09-01 17:01:18 +09:00
swcho 072a5337a3 Merge branch 'iipbs/common/main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/common/main 2025-09-01 13:07:49 +09:00
swcho 2a0f5dce25 remove: 상류관로 보기 함수 삭제 2025-09-01 13:07:46 +09:00
mind-one003 26f2c60f4c 라인바 차트
- 데이터가 NaN이거나 null인 경우 툴팁에서 제외
- NULL인 경우 0으로 라인을 그리는 현상 다음 있는데이터로 라인을 그리도록 수정
2025-08-29 14:59:10 +09:00
swcho 28d0e21815 feat: UiTable에 페이지 번호 props 추가 2025-08-28 17:32:52 +09:00
swcho 49c475709f feat:
- 시설 검색, 다중 시설 검색 시 이전 검색 시설 레이어 삭제 기능 추가
- 시설 위치 정보 없을 때 alert 추가
- 시설 검색 시 해당 시설 아이콘 이미지 표출
2025-08-28 17:11:35 +09:00
mind-one003 31b8152d37 차트 좌우 axis custom 추가 2025-08-27 14:56:02 +09:00
swcho b9f5eb50e5 feat: UiTable 내부 셀 줄바꿈 처리 pre-line 적용 2025-08-26 18:42:36 +09:00
mind-one003 c7772a0a23 빌드에러 수정 2025-08-26 17:50:50 +09:00
mind-one003 392ccefb16 라인바 차트property 추가 (setXAxisYearTick - 날짜 x축일경우 (년도-월)별로 만들어주는 속성) 2025-08-26 17:47:51 +09:00
mind-one003 aeaf507c47 차트property 추가 (setXAxisYearTick - 날짜 x축일경우 (년도-월)별로 만들어주는 속성) 2025-08-26 17:39:07 +09:00
mind-one003 2f4cfa0d78 바차트 툴팁 숫자의 경우 천자리 쉼포 추가 2025-08-26 13:30:24 +09:00
swcho ebfc520d67 feat:
- 여러 개의 검색 결과를 GeoJSON으로 표시 함수 추가
- 피쳐 ID로 지오서버에서 검색해서 여러개 피처의 벡터소스 리턴하는 함수 추가
- 여러 extent 배열을 받아 중앙값 extent를 반환하는 함수 추가
2025-08-20 18:50:08 +09:00
swcho 4df286b086 feat: UiTable 컴포넌트에 headButton props 추가 2025-08-19 15:24:52 +09:00
swcho 262cf21546 remove: 잘못 추가된 물재이용(wr)의 가뭄지도 팝업 페이지 삭제 2025-08-13 17:20:40 +09:00
swcho 056b7bae3c fix: defaultZoom props 수정 2025-08-13 16:31:01 +09:00
swcho 428f617802 fix: defaultZoom props 수정 2025-08-13 16:20:15 +09:00
swcho e797bdbdf7 feat: Gis.js defaultZoom, defaultLonLat props 추가 2025-08-13 16:11:33 +09:00
mind-one005 cb11ec839e UiModal <div> <> 2025-08-13 15:50:23 +09:00
swcho 772dd1c1aa refactor: 시도, 시군구 순서 Custom 정렬 2025-08-13 15:40:07 +09:00
swcho 579e599eb1 feat searchBar 시설명 가나다 순으로 정렬 2025-08-11 18:23:05 +09:00
16 changed files with 1198 additions and 901 deletions
@@ -19,6 +19,14 @@ const customStyles = {
} as CSSProperties,
};
const fncNumberFormet = (value : string | number) => {
return String(value).includes('.')?
String(parseFloat(value.toString().replace(/,/g, ''))).split('.').map((part, index) =>
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
).join('.')
: String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
type BarChartProps = {
chartConfig: ChartConfig | undefined;
chartData: any[] | undefined;
@@ -51,7 +59,7 @@ const CustomTooltip = ({
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
{/* 색상 박스 추가 (범례 색상과 동일) */}
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value}`}</span>
<span className="text-[11px] font-bold">{` ${item.name} : ${fncNumberFormet(item.value)}`}</span>
</div>
))}
</div>
@@ -6,6 +6,8 @@ import {
type ChartConfig
} from "./lib/chart";
import type { ContentType } from "recharts/types/component/DefaultLegendContent";
import type { set } from "date-fns";
import React from "react";
// 툴크 커스텀 css
/** 차트 기본 스타일 */
@@ -29,6 +31,7 @@ type LineBarChartProps = {
yFieldText?: string | undefined;
yFieldText2?: string | undefined;
showLegend?: boolean;
setXAxisYearTick?: boolean;
}
type LegendEntry = {
@@ -86,7 +89,8 @@ export default function LineBarchart({
graphSize = 40,
yFieldText,
yFieldText2,
showLegend = true
showLegend = true,
setXAxisYearTick = false
}: LineBarChartProps) {
if (!chartData || chartData.length === 0) {
return <div>데이터가 없습니다.</div>;
@@ -105,6 +109,90 @@ 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[] = [];
for(const item of data){
const month = String(item.label).slice(0,7);
if(!monthSet.has(month)){
monthSet.add(month);
rtnData.push(item.label);
}
}
return rtnData;
}
let monthTicks : string[] = [];
if(setXAxisYearTick){
monthTicks = getTicks(chartData);
}
const CustomAxisText : React.FC<{ viewBox: any, fieldText: string, position:string }> = ({ viewBox, fieldText, position }) => {
const { x, y, width, height } = viewBox; // 축 영역
const padding = 5; // 차트 바깥으로 띄우기
if('left' == position) {
return (
<text
x={x - padding} // 맨 좌측 바깥
y={y + height / 2 - 12} // 수직 중앙
textAnchor="middle"
transform={`rotate(-90, ${x - padding}, ${y + height / 2})`}
className="text-[12px] font-bold"
>
{fieldText}
</text>
);
}else{
return (
<text
x={x + height / 2 } // 맨 좌측 바깥
y={y - width + padding } // 수직 중앙
textAnchor="middle"
transform={`rotate(90, ${x}, ${y})`}
className="text-[12px] font-bold"
>
{fieldText}
</text>
);
}
}
return (
<div className={chartClassName}>
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
@@ -112,33 +200,42 @@ export default function LineBarchart({
{chartTitle}
</div>
) : null}
<div className="h-[calc(100%-42px)] flex justify-center">
<ChartContainer config={chartConfig ?? {}} className="h-full w-full">
<div className="h-[calc(100%-42px)] w-[calc(100%-40px)] ">
<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" />
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
{setXAxisYearTick?
<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}
orientation="left"
domain={[0, Math.ceil(lineMaxValue * 1)]}
label={{ value: yFieldText, angle: -90, position: 'insideLeft', offset: -8 }}
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" />}
/>}
{/* 오른쪽 Y축: barVal */}
{yFieldText2 && <YAxis
yAxisId="right"
className="text-[12px] font-bold"
tickCount={6}
orientation="right"
domain={[0, Math.ceil(barMaxValue * 1)]}
label={{ value: yFieldText2, angle: -90, position: 'insideRight' }}
orientation="right"
tickFormatter={(value) =>
typeof value === "number" ? value.toLocaleString() : value
}
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} />} />
@@ -15,6 +15,7 @@ type LineChartProps = {
graphSize?: number;
yFieldText?: string;
showLegend?: boolean;
setXAxisYearTick?: boolean;
}
/** 차트 기본 스타일 */
@@ -64,11 +65,11 @@ const CustomTooltip = ({ active, payload, label }: { active?: boolean; payload?:
return (
<div className="w-[180px] rounded bg-white p-2.5 shadow-[0px_2px_10px_rgba(0,0,0,0.2)]">
<p className="text-[12px] font-bold m-3">{label}</p>
{payload.map((item, index) => (
{payload.filter(item => item.value != null && String(item.value) != 'NaN' && item.value != undefined).map((item, index) => (
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
{/* 색상 박스 추가 (범례 색상과 동일) */}
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value}`}</span>
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value.toString().replace(',','')}`}</span>
</div>
))}
</div>
@@ -128,6 +129,37 @@ const CustomLegend = (props: LegendProps) => {
);
};
const CustomAxisText : React.FC<{ viewBox: any, fieldText: string, position:string }> = ({ viewBox, fieldText, position }) => {
const { x, y, width, height } = viewBox; // 축 영역
const padding = 5; // 차트 바깥으로 띄우기
if('left' == position) {
return (
<text
x={x - padding} // 맨 좌측 바깥
y={y + height / 2} // 수직 중앙
textAnchor="middle"
transform={`rotate(-90, ${x - padding}, ${y + height / 2})`}
className="text-[12px] font-bold"
>
{fieldText}
</text>
);
}else{
return (
<text
x={x + height / 2 } // 맨 좌측 바깥
y={y - width + padding } // 수직 중앙
textAnchor="middle"
transform={`rotate(90, ${x}, ${y})`}
className="text-[12px] font-bold"
>
{fieldText}
</text>
);
}
}
type DataType = {label: string; val: string};
type ChartDataType = {
@@ -141,7 +173,8 @@ export default function Linechart({
chartClassName = 'w-full h-full',
graphSize = 40,
yFieldText,
showLegend = true
showLegend = true,
setXAxisYearTick = false,
}: LineChartProps) {
if (!chartData || Object.keys(chartData).length === 0) {
return <div>데이터가 없습니다.</div>;
@@ -164,18 +197,24 @@ export default function Linechart({
return acc;
}, []);
// 데이터의 최대값 계산
const getMaxValue = (data: ChartDataType): number => {
return Math.max(...Object.values(data).flatMap(dataset =>
dataset.map(entry => {
const val = parseFloat(entry.val);
return isNaN(val) ? 0 : val;
})
));
};
const lineMaxValue = getMaxValue(chartData);
const getTicks = (data : any []) => {
const monthSet = new Set<string>();
const rtnData : string[] = [];
for(const item of data){
const month = String(item.label).slice(0,7);
if(!monthSet.has(month)){
monthSet.add(month);
rtnData.push(item.label);
}
}
return rtnData;
}
let monthTicks : string[] = [];
if(setXAxisYearTick){
monthTicks = getTicks(mergedData);
}
return (
<div className={chartClassName}>
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
@@ -192,8 +231,28 @@ export default function Linechart({
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid vertical={false} />
<XAxis dataKey="label" fontSize="8px" fontWeight="bold" />
<YAxis yAxisId="left" className="text-[12px] font-bold" tickFormatter={(value) => value.toLocaleString()} tickCount={6} orientation="left" label={{ value: yFieldText, className:"text-[12px] font-bold", angle: -90, position: 'insideLeft' }} />
{setXAxisYearTick ?
<XAxis
dataKey="label"
className="text-[12px] font-bold"
ticks={monthTicks}
tickFormatter={(value) => value.slice(0,7)}
/> :
<XAxis
dataKey="label"
className="text-[12px] font-bold"
/>
}
<YAxis
yAxisId="left"
className="text-[12px] font-bold"
orientation="left"
tickFormatter={(value) =>
typeof value === "number" ? value.toLocaleString() : value
}
label={(props) => <CustomAxisText {...props} fieldText={yFieldText} position="left" />}/>
<Tooltip content={<CustomTooltip />} />
{showLegend && <Legend content={CustomLegend as ContentType}/>}
{Object.keys(chartData).map((key) => {
@@ -206,8 +265,10 @@ export default function Linechart({
type="linear"
strokeWidth={2}
dot={false}
connectNulls={true}
name={String(config?.label || "X축")}
stroke={config?.color}
stroke={config?.color?.includes('dash')?config?.color?.replace('dash',''):config?.color}
strokeDasharray={config?.color?.includes("dash")?"4 4":undefined}
/>
);
})}
@@ -56,6 +56,7 @@ type MainChartProps = {
yFieldText? : string | undefined;
yFieldText2? : string | undefined;
showLegend? : boolean;
setXAxisYearTick ?: boolean;
}
function MainChart(props: MainChartProps) {
@@ -65,7 +66,7 @@ function MainChart(props: MainChartProps) {
);
} else if( props.chartForm == CHART_FORM.LINE ){
return (
<LineChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} showLegend={props.showLegend}/>
<LineChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} showLegend={props.showLegend} setXAxisYearTick={props.setXAxisYearTick}/>
);
} else if( props.chartForm == CHART_FORM.DN ){
return (
@@ -73,7 +74,7 @@ function MainChart(props: MainChartProps) {
);
} else if (props.chartForm == CHART_FORM.LINEBAR){
return (
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} yFieldText2={props.yFieldText2} showLegend={props.showLegend}/>
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} yFieldText2={props.yFieldText2} showLegend={props.showLegend} setXAxisYearTick={props.setXAxisYearTick}/>
);
} else if (props.chartForm == CHART_FORM.LINEBAR2){
return (
@@ -41,7 +41,7 @@ export function UiModal({
{(open && body) ?
useDirectRender
? body
: <div>{body}</div>
: <>{body}</>
: <></>
}
{noFooterYn === 'N' && (
@@ -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;
@@ -29,75 +29,6 @@ export const GisContext = createContext({
checkedLayerIds: null,
});
export const useGisContext = () => useContext(GisContext);
export const searchUpperPpls = async (fcltMngNo) => {
const BASE_URL = process.env.NEXT_PUBLIC_SEWERAGE_API_URL || "";
const res = await fetch(`${BASE_URL}/v1/fcltmhl/upperPpls/${fcltMngNo}`, {
method: "GET",
});
let data = null;
if (res.ok) {
try {
// 응답이 비어있는지 확인
const contentLength = res.headers.get("content-length");
if (contentLength === "0")
alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
// 응답 텍스트를 먼저 가져와서 빈 문자열인지 확인
const text = await res.text();
if (!text || text.trim() === "")
alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
// JSON 파싱 시도
data = JSON.parse(text);
} catch (error) {
console.error("JSON parsing error:", error);
alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
}
}
const select = GisApp.Module.select;
const gisMap = GisApp.Module.core?.map;
let foundFeature = null;
data.forEach((item) => {
const pplMngNo = item.ppl_mng_no.trim();
gisMap
.getLayers()
.getArray()
.filter((e) => e.get("lyrTyNm") == "tb_ms_swage_ppl")
.forEach((layer) => {
const source = layer.getSource?.();
if (source?.getFeatures) {
const features = source.getFeatures();
for (const f of features) {
if (f.values_.fclt_mng_no.trim() === pplMngNo) {
foundFeature = f;
break;
}
}
}
});
if (foundFeature) select.selectMultiFeature(foundFeature, true);
});
if (!foundFeature) alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
let geometry = foundFeature?.getGeometry();
if (geometry) {
let extent = geometry.getExtent();
gisMap.getView().fit(extent, {
duration: 300,
padding: [50, 50, 50, 50],
maxZoom: 14,
constrainResolution: true,
nearest: true,
});
}
};
function Gis({
isOpen, //우측 상세 레이어 팝업
@@ -120,11 +51,12 @@ function Gis({
isPlaying = false,
setIsPlaying = () => { },
targetLayerTypes = [],
orderedLayers = [],
checkInterval = 3000,
height: height = "h-[calc(100vh-5rem)]",
onOpenPopup = (data) => { },
droughtDates = { startYmd: '', endYmd: '' }
droughtDates = { startYmd: '', endYmd: '' },
defaultZoom = 15,
defaultLonLat = [127.4875, 37.4916],
}) {
const mapRef = useRef();
const [mapObject, setMapObject] = useState({});
@@ -209,9 +141,9 @@ function Gis({
}).extend([]),
view: new View({
projection: GisApp.TO_PROJ,
zoom: gisCore.defaults.zoom,
zoom: defaultZoom ?? gisCore.defaults.zoom,
center: olProj.transform(
[127.4875, 37.4916],
defaultLonLat,
GisApp.FROM_PROJ,
GisApp.TO_PROJ,
),
@@ -372,7 +304,6 @@ function Gis({
isPlaying={isPlaying}
setIsPlaying={setIsPlaying}
targetLayerTypes={targetLayerTypes}
orderedLayers={orderedLayers}
checkInterval={checkInterval}
onProgressChange={handleProgressChange}
/>
@@ -400,11 +331,7 @@ function Gis({
)}
{/* SearchView가 존재할 때만 렌더링 */}
{SearchView && (
<SearchView
open={isSearchModalOpen}
onOpenChange={setIsSearchModalOpen}
onFeatureSelect={handleFeatureSelect}
/>
<SearchView />
)}
{/* 시도/시군구 조회 영역 */}
{SearchBar && (
File diff suppressed because it is too large Load Diff
@@ -569,14 +569,249 @@ GisOlLayer.prototype = {
cesiumScene.camera.moveEnd.addEventListener(cesiumScene._moveEndListener);
}
},
getFeatureById: function(featureId){
this.layers
.getArray()
.forEach(layer => {
const source = layer.getSource();
const feature = source.getFeatureById(String(featureId).trim());
if (feature) return feature;
});
getFeatureById: function (featureId) {
let returnFeature;
this.layers.getArray().some(function (layer) {
const source = layer.getSource();
if (source instanceof VectorSource) {
const feature = source.getFeatureById(featureId);
if (feature) {
returnFeature = feature;
return true;
}
}
});
return returnFeature;
},
getOpenLayersZoom: function (cesiumScene) {
const cameraHeight = cesiumScene.camera.positionCartographic.height;
const maxResolution = 156543.03392804097; // OpenLayers 기본 해상도 (Google Mercator 기준)
const tileSize = 256; // 기본 타일 크기
return Math.ceil(Math.log2(maxResolution / (cameraHeight / tileSize)));
},
ensureSearchLayer: function (option) {
let layer = this.searchLayer;
if (!layer) {
let source;
try {
if (option.cmncNm == 'bbox') {
source = this.getVectorSourceBbox(option);
} else {
source = this.getVectorSourceAll(option);
}
} catch (error) {
console.warn(option);
}
layer = new VectorImageLayer({
...option,
id: 'search-layer',
source: source,
zIndex: 9999
});
layer.setStyle(this.gisStyle.getLayerStyleFunction(layer, option));
let map = GisApp.Module.core.map;
map.addLayer(layer);
this.searchLayer = layer;
}
return layer;
},
clearSearchLayer: function (option) {
const layer = this.ensureSearchLayer(option);
layer.getSource().clear(true);
if (this.searchLayer) {
GisApp.Module.core.map.removeLayer(this.searchLayer);
this.searchLayer = null;
}
},
showSearchResultsFromGeoJSON: function (lyrTyNm, featureId) {
//레이어 타입 설정(point, line 등. 이걸 style에서 사용)
const layerCode = GisApp.layerCode;
const matched = Object.values(layerCode).find(obj => obj.lyrTyNm === lyrTyNm);
// 이전 검색 레이어 완전히 제거
this.clearSearchLayer(matched);
// 새로운 검색 레이어 생성
const layer = this.ensureSearchLayer(matched);
layer.set("gobjTy", matched.gobjTy);
// 새 소스 만들기
const source = this.getFeatureSourceFromGeoserver(lyrTyNm, featureId, matched);
// 1) 로드 완료시 extent 맞추기
const onLoadEnd = () => {
if (Object.keys(source.nullGeometryFeatures_).length > 0) alert('해당 시설의 위치 정보가 없습니다.');
const feats = source.getFeatures();
if (feats && feats.length > 0) {
const select = GisApp.Module.select;
select.selectFeature(feats[0], false);
} else {
console.warn('[search-layer] GeoJSON에 피처가 없습니다.');
}
// 한번만 쓰고 이벤트 정리
source.un('featuresloadend', onLoadEnd);
source.un('featuresloaderror', onLoadError);
};
const onLoadError = (e) => {
console.error('[search-layer] GeoJSON 로드 실패:', e);
source.un('featuresloadend', onLoadEnd);
source.un('featuresloaderror', onLoadError);
};
// 이벤트를 먼저 걸고 → setSource
source.once('featuresloadend', onLoadEnd);
source.once('featuresloaderror', onLoadError);
// 레이어에 소스 적용(이때부터 로딩 시작)
layer.setSource(source);
// 필요시 명시적으로 재요청
source.refresh();
},
/**
* 피쳐 ID로 지오서버에서 검색해서 피처의 벡터소스를 리턴
* @param {} lyrTyNm
* @param {*} featureId
* @returns
*/
getFeatureSourceFromGeoserver: function (lyrTyNm, featureId, option) {
const typeName = this.storageNm + lyrTyNm;
const srsName = GisApp.TO_PROJ;
const baseUrl = GisApp.GEOSERVER_URL;
const source = new VectorSource({
...option,
format: new GeoJSON(),
url: () => {
const params = new URLSearchParams({
SERVICE: 'WFS',
VERSION: '1.1.0',
REQUEST: 'GetFeature',
TYPENAME: typeName,
SRSNAME: srsName,
OUTPUTFORMAT: 'application/json',
FEATUREID: featureId,
});
return `${baseUrl}?${params.toString()}`;
},
strategy: all,
});
return source;
},
/**
* 여러 개의 검색 결과를 GeoJSON으로 표시
* @param {string} lyrTyNm 레이어 타입명
* @param {Array|string} featureIds 피처 ID 배열 또는 단일 ID
*/
showMultipleSearchResultsFromGeoJSON: function (lyrTyNm, featureIds) {
const layerCode = GisApp.layerCode;
const matched = Object.values(layerCode).find(obj => obj.lyrTyNm === lyrTyNm);
// 이전 검색 레이어 완전히 제거
this.clearSearchLayer(matched);
// 새로운 검색 레이어 생성
const layer = this.ensureSearchLayer(matched);
layer.set("gobjTy", matched.gobjTy);
const source = this.getMultiFeatureSourceFromGeoserver(lyrTyNm, featureIds);
const onLoadEnd = async () => {
const feats = source.getFeatures();
if (feats && feats.length > 0) {
const select = GisApp.Module.select;
await select.resetSelectedFeature();
for (const feature of feats) select.selectMultiFeature(feature, true);
const geometries = feats.map(f => f.getGeometry());
if (geometries.length > 0) {
const extent = this.combineExtents(geometries.map(g => g?.getExtent()));
let map = GisApp.Module.core.map;
map.getView().fit(extent, {
duration: 300,
padding: [50, 50, 50, 50],
maxZoom: 16
});
}
} else {
console.warn('[search-layer] GeoJSON에 피처가 없습니다.');
}
source.un('featuresloadend', onLoadEnd);
source.un('featuresloaderror', onLoadError);
};
const onLoadError = (e) => {
console.error('[search-layer] GeoJSON 로드 실패:', e);
source.un('featuresloadend', onLoadEnd);
source.un('featuresloaderror', onLoadError);
};
source.once('featuresloadend', onLoadEnd);
source.once('featuresloaderror', onLoadError);
layer.setSource(source);
source.refresh();
},
/**
* 피쳐 ID로 지오서버에서 검색해서 여러개 피처의 벡터소스를 리턴
* @param {} lyrTyNm
* @param {*} featureId
* @returns
*/
getMultiFeatureSourceFromGeoserver: function (lyrTyNm, featureId) {
const typeName = this.storageNm + lyrTyNm;
const srsName = GisApp.TO_PROJ;
const baseUrl = GisApp.GEOSERVER_URL;
const ids = Array.isArray(featureId) ? featureId : [featureId];
const source = new VectorSource({
format: new GeoJSON(),
url: () => {
const params = new URLSearchParams({
SERVICE: 'WFS',
VERSION: '1.1.0',
REQUEST: 'GetFeature',
TYPENAME: typeName,
SRSNAME: srsName,
OUTPUTFORMAT: 'application/json',
FEATUREID: ids.join(','),
});
return `${baseUrl}?${params.toString()}`;
},
strategy: all,
});
return source;
},
/**
* 여러 extent 배열을 받아 결합된 extent를 반환
* @param {Array<Array<number>>} extents [[minX,minY,maxX,maxY], ...]
* @returns {Array<number>|null}
*/
combineExtents: function (extents) {
if (!extents || extents.length === 0) return null;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const e of extents) {
if (!e || e.length < 4) continue;
minX = Math.min(minX, e[0]);
minY = Math.min(minY, e[1]);
maxX = Math.max(maxX, e[2]);
maxY = Math.max(maxY, e[3]);
}
if (!isFinite(minX) || !isFinite(minY) || !isFinite(maxX) || !isFinite(maxY)) return null;
return [minX, minY, maxX, maxY];
}
};
@@ -284,6 +284,7 @@ GisOlSelect.prototype = {
selectedFeatures.forEach(feature => {
selectedFeatures.remove(feature);
});
selectedFeatures.clear();
},
/**
* SELECT 이벤트 활성화
@@ -1,302 +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,
}));
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,
}));
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(
@@ -43,21 +34,61 @@ export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
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,
}));
setSidoData([{ text: "선택", val: "0" }, ...list]);
const list = res.features
.map((f: any) => ({
text: f.properties.mctpv_korn_nm,
val: f.properties.mctpv_cd,
}))
.sort((a: any, b: any) => {
// 커스텀 순서 정의
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,
}));
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);
};
@@ -90,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" // 재이용시설
) {
@@ -144,7 +177,9 @@ export const ProcSearchBar = ({ gisMaps, facilityTypes }: SearchBarProps) => {
}));
}
setFacilityData([{ text: "시도", val: "0" }, ...list]);
// 가나다순 정렬 후 set
const sorted = list.slice().sort((a, b) => a.text.localeCompare(b.text, 'ko'));
setFacilityData([{ text: "시도", val: "0" }, ...sorted]);
setFacilityValue("0");
};
@@ -58,10 +58,48 @@ export const SearchBar = ({
const json = await res.json();
const sidoList = json
.filter((item: any) => item.lwpoCd?.length === 2)
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }));
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }))
.sort((a: any, b: any) => {
// 커스텀 순서 정의
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');
});
const sigunList = json
.filter((item: any) => item.lwpoCd?.length > 2)
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }));
.map((item: any) => ({ val: item.lwpoCd, text: item.lwpoCdNm }))
.sort((a: any, b: any) => a.text.localeCompare(b.text, 'ko'));
setSidoData([{ text: "시도", val: "0" }, ...sidoList]);
setSigunData(sigunList);
};
@@ -127,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>
@@ -30,6 +30,9 @@ type UiTableProps = {
boldArray?: number[];
resetSelection?: boolean;
index?: number;
curPage?: number;
headButton?: React.ReactNode | undefined;
widthFixed?: boolean;
};
type UiHeadProps = {
@@ -37,6 +40,9 @@ type UiHeadProps = {
title: string;
align?: string;
visible?: boolean;
row?: number;
widthPercent?: number;
rowSpan?: number;
};
export function UiTable({
@@ -53,8 +59,11 @@ export function UiTable({
boldArray = [],
resetSelection = false,
index = -1,
curPage = 1,
headButton = undefined,
widthFixed = false
}: UiTableProps) {
const [cur, setCur] = useState<number>(1);
const [cur, setCur] = useState<number>(curPage);
const [idx, setIdx] = useState<number>(index);
const [headerHeight, setHeaderHeight] = useState<number>(0);
const headerRef = useRef<HTMLTableSectionElement>(null);
@@ -82,6 +91,10 @@ export function UiTable({
setIdx(index);
}, [index])
useEffect(() => {
setCur(curPage);
}, [curPage])
const handlePageChange = (page: number) => {
setCur(page);
onPageChange(page);
@@ -96,18 +109,40 @@ 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 (
<>
{headName ? (
<div className="card-header">
<h3 className="text-2xl font-medium text-label">{headName}</h3>
</div>
headButton ? (
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium text-label">{headName}</h3>
<>{headButton}</>
</div>
) : (
<div className="card-header">
<h3 className="text-2xl font-medium text-label">{headName}</h3>
</div>
)
) : (
<></>
)}
<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>
@@ -128,7 +163,7 @@ export function UiTable({
: cellClick
? "cursor-pointer"
: ""
} sticky top-20 z-40 bg-secondary !font-bold`}
} sticky top-20 z-40 bg-secondary !font-bold whitespace-pre-line`}
style={{ top: `${headerHeight + index * 32 - 4}px` }}
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
@@ -159,7 +194,7 @@ export function UiTable({
: cellClick
? "cursor-pointer"
: ""
} mt-[${boldArray.length * 40}px]`}
} mt-[${boldArray.length * 40}px] whitespace-pre-line`}
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>