fix: 테스트 위젯 최종 수정 및 충돌 해결

This commit is contained in:
leeheejin
2025-10-29 13:50:08 +09:00
parent 8edd5e4ca6
commit 398c47618b
7 changed files with 291 additions and 201 deletions

View File

@@ -67,8 +67,8 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const [geoJsonData, setGeoJsonData] = useState<any>(null);
const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
console.log("🧪 MapTestWidgetV2 렌더링!", element);
console.log("📍 마커:", markers.length, "🔷 폴리곤:", polygons.length);
// // console.log("🧪 MapTestWidgetV2 렌더링!", element);
// // console.log("📍 마커:", markers.length, "🔷 폴리곤:", polygons.length);
// dataSources를 useMemo로 추출 (circular reference 방지)
const dataSources = useMemo(() => {
@@ -80,11 +80,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const dataSourcesList = dataSources;
if (!dataSources || dataSources.length === 0) {
console.log("⚠️ 데이터 소스가 없습니다.");
// // console.log("⚠️ 데이터 소스가 없습니다.");
return;
}
console.log(`🔄 ${dataSources.length}개의 데이터 소스 로딩 시작...`);
// // console.log(`🔄 ${dataSources.length}개의 데이터 소스 로딩 시작...`);
setLoading(true);
setError(null);
@@ -93,7 +93,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const results = await Promise.allSettled(
dataSources.map(async (source) => {
try {
console.log(`📡 데이터 소스 "${source.name || source.id}" 로딩 중...`);
// // console.log(`📡 데이터 소스 "${source.name || source.id}" 로딩 중...`);
if (source.type === "api") {
return await loadRestApiData(source);
@@ -114,21 +114,21 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const allPolygons: PolygonData[] = [];
results.forEach((result, index) => {
console.log(`🔍 결과 ${index}:`, result);
// // console.log(`🔍 결과 ${index}:`, result);
if (result.status === "fulfilled" && result.value) {
const value = result.value as { markers: MarkerData[]; polygons: PolygonData[] };
console.log(`✅ 데이터 소스 ${index} 성공:`, value);
// // console.log(`✅ 데이터 소스 ${index} 성공:`, value);
// 마커 병합
if (value.markers && Array.isArray(value.markers)) {
console.log(` → 마커 ${value.markers.length}개 추가`);
// // console.log(` → 마커 ${value.markers.length}개 추가`);
allMarkers.push(...value.markers);
}
// 폴리곤 병합
if (value.polygons && Array.isArray(value.polygons)) {
console.log(` → 폴리곤 ${value.polygons.length}개 추가`);
// // console.log(` → 폴리곤 ${value.polygons.length}개 추가`);
allPolygons.push(...value.polygons);
}
} else if (result.status === "rejected") {
@@ -136,9 +136,9 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
}
});
console.log(`✅ 총 ${allMarkers.length}개의 마커, ${allPolygons.length}개의 폴리곤 로딩 완료`);
console.log("📍 최종 마커 데이터:", allMarkers);
console.log("🔷 최종 폴리곤 데이터:", allPolygons);
// // console.log(`✅ 총 ${allMarkers.length}개의 마커, ${allPolygons.length}개의 폴리곤 로딩 완료`);
// // console.log("📍 최종 마커 데이터:", allMarkers);
// // console.log("🔷 최종 폴리곤 데이터:", allPolygons);
setMarkers(allMarkers);
setPolygons(allPolygons);
@@ -153,13 +153,13 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 수동 새로고침 핸들러
const handleManualRefresh = useCallback(() => {
console.log("🔄 수동 새로고침 버튼 클릭");
// // console.log("🔄 수동 새로고침 버튼 클릭");
loadMultipleDataSources();
}, [loadMultipleDataSources]);
// REST API 데이터 로딩
const loadRestApiData = async (source: ChartDataSource): Promise<{ markers: MarkerData[]; polygons: PolygonData[] }> => {
console.log(`🌐 REST API 데이터 로딩 시작:`, source.name, `mapDisplayType:`, source.mapDisplayType);
// // console.log(`🌐 REST API 데이터 로딩 시작:`, source.name, `mapDisplayType:`, source.mapDisplayType);
if (!source.endpoint) {
throw new Error("API endpoint가 없습니다.");
@@ -215,10 +215,10 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 텍스트 형식 데이터 체크 (기상청 API 등)
if (data && typeof data === 'object' && data.text && typeof data.text === 'string') {
console.log("📄 텍스트 형식 데이터 감지, CSV 파싱 시도");
// // console.log("📄 텍스트 형식 데이터 감지, CSV 파싱 시도");
const parsedData = parseTextData(data.text);
if (parsedData.length > 0) {
console.log(`✅ CSV 파싱 성공: ${parsedData.length}개 행`);
// // console.log(`✅ CSV 파싱 성공: ${parsedData.length}개 행`);
// 컬럼 매핑 적용
const mappedData = applyColumnMapping(parsedData, source.columnMapping);
return convertToMapData(mappedData, source.name || source.id || "API", source.mapDisplayType, source);
@@ -244,7 +244,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// Database 데이터 로딩
const loadDatabaseData = async (source: ChartDataSource): Promise<{ markers: MarkerData[]; polygons: PolygonData[] }> => {
console.log(`💾 Database 데이터 로딩 시작:`, source.name, `mapDisplayType:`, source.mapDisplayType);
// // console.log(`💾 Database 데이터 로딩 시작:`, source.name, `mapDisplayType:`, source.mapDisplayType);
if (!source.query) {
throw new Error("SQL 쿼리가 없습니다.");
@@ -287,7 +287,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// XML 데이터 파싱 (UTIC API 등)
const parseXmlData = (xmlText: string): any[] => {
try {
console.log(" 📄 XML 파싱 시작");
// // console.log(" 📄 XML 파싱 시작");
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "text/xml");
@@ -306,7 +306,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
results.push(obj);
}
console.log(` ✅ XML 파싱 완료: ${results.length}개 레코드`);
// // console.log(` ✅ XML 파싱 완료: ${results.length}개 레코드`);
return results;
} catch (error) {
console.error(" ❌ XML 파싱 실패:", error);
@@ -317,11 +317,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 텍스트 데이터 파싱 (CSV, 기상청 형식 등)
const parseTextData = (text: string): any[] => {
try {
console.log(" 🔍 원본 텍스트 (처음 500자):", text.substring(0, 500));
// // console.log(" 🔍 원본 텍스트 (처음 500자):", text.substring(0, 500));
// XML 형식 감지
if (text.trim().startsWith("<?xml") || text.trim().startsWith("<result>")) {
console.log(" 📄 XML 형식 데이터 감지");
// // console.log(" 📄 XML 형식 데이터 감지");
return parseXmlData(text);
}
@@ -333,7 +333,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
!trimmed.startsWith('---');
});
console.log(` 📝 유효한 라인: ${lines.length}`);
// // console.log(` 📝 유효한 라인: ${lines.length}개`);
if (lines.length === 0) return [];
@@ -344,7 +344,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const line = lines[i];
const values = line.split(',').map(v => v.trim().replace(/,=$/g, ''));
console.log(` 라인 ${i}:`, values);
// // console.log(` 라인 ${i}:`, values);
// 기상특보 형식: 지역코드, 지역명, 하위코드, 하위지역명, 발표시각, 특보종류, 등급, 발표상태, 설명
if (values.length >= 4) {
@@ -364,11 +364,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
obj.name = obj.subRegion || obj.region || obj.code;
result.push(obj);
console.log(` ✅ 파싱 성공:`, obj);
// console.log(` ✅ 파싱 성공:`, obj);
}
}
console.log(" 📊 최종 파싱 결과:", result.length, "개");
// // console.log(" 📊 최종 파싱 결과:", result.length, "개");
return result;
} catch (error) {
console.error(" ❌ 텍스트 파싱 오류:", error);
@@ -383,9 +383,9 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
mapDisplayType?: "auto" | "marker" | "polygon",
dataSource?: ChartDataSource
): { markers: MarkerData[]; polygons: PolygonData[] } => {
console.log(`🔄 ${sourceName} 데이터 변환 시작:`, rows.length, "개 행");
console.log(` 📌 mapDisplayType:`, mapDisplayType, `(타입: ${typeof mapDisplayType})`);
console.log(` 🎨 마커 색상:`, dataSource?.markerColor, `폴리곤 색상:`, dataSource?.polygonColor);
// // console.log(`🔄 ${sourceName} 데이터 변환 시작:`, rows.length, "개 행");
// // console.log(` 📌 mapDisplayType:`, mapDisplayType, `(타입: ${typeof mapDisplayType})`);
// // console.log(` 🎨 마커 색상:`, dataSource?.markerColor, `폴리곤 색상:`, dataSource?.polygonColor);
if (rows.length === 0) return { markers: [], polygons: [] };
@@ -393,13 +393,13 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
const polygons: PolygonData[] = [];
rows.forEach((row, index) => {
console.log(`${index}:`, row);
// // console.log(` 행 ${index}:`, row);
// 텍스트 데이터 체크 (기상청 API 등)
if (row && typeof row === 'object' && row.text && typeof row.text === 'string') {
console.log(" 📄 텍스트 형식 데이터 감지, CSV 파싱 시도");
// // console.log(" 📄 텍스트 형식 데이터 감지, CSV 파싱 시도");
const parsedData = parseTextData(row.text);
console.log(` ✅ CSV 파싱 결과: ${parsedData.length}개 행`);
// // console.log(` ✅ CSV 파싱 결과: ${parsedData.length}개 행`);
// 파싱된 데이터를 재귀적으로 변환 (색상 정보 전달)
const result = convertToMapData(parsedData, sourceName, mapDisplayType, dataSource);
@@ -410,11 +410,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 폴리곤 데이터 체크 (coordinates 필드가 배열인 경우 또는 강제 polygon 모드)
if (row.coordinates && Array.isArray(row.coordinates) && row.coordinates.length > 0) {
console.log(` → coordinates 발견:`, row.coordinates.length, "개");
// // console.log(` → coordinates 발견:`, row.coordinates.length, "개");
// coordinates가 [lat, lng] 배열의 배열인지 확인
const firstCoord = row.coordinates[0];
if (Array.isArray(firstCoord) && firstCoord.length === 2) {
console.log(` → 폴리곤으로 처리:`, row.name);
// console.log(` → 폴리곤으로 처리:`, row.name);
polygons.push({
id: row.id || row.code || `polygon-${index}`,
name: row.name || row.title || `영역 ${index + 1}`,
@@ -431,7 +431,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 지역명으로 해상 구역 확인 (auto 또는 polygon 모드일 때만)
const regionName = row.name || row.area || row.region || row.location || row.subRegion;
if (regionName && MARITIME_ZONES[regionName] && mapDisplayType !== "marker") {
console.log(` → 해상 구역 발견: ${regionName}, 폴리곤으로 처리`);
// // console.log(` → 해상 구역 발견: ${regionName}, 폴리곤으로 처리`);
polygons.push({
id: `${sourceName}-polygon-${index}-${row.code || row.id || Date.now()}`, // 고유 ID 생성
name: regionName,
@@ -451,24 +451,24 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 위도/경도가 없으면 지역 코드/지역명으로 변환 시도
if ((lat === undefined || lng === undefined) && (row.code || row.areaCode || row.regionCode || row.tmFc || row.stnId)) {
const regionCode = row.code || row.areaCode || row.regionCode || row.tmFc || row.stnId;
console.log(` → 지역 코드 발견: ${regionCode}, 위도/경도 변환 시도`);
// // console.log(` → 지역 코드 발견: ${regionCode}, 위도/경도 변환 시도`);
const coords = getCoordinatesByRegionCode(regionCode);
if (coords) {
lat = coords.lat;
lng = coords.lng;
console.log(` → 변환 성공: (${lat}, ${lng})`);
// console.log(` → 변환 성공: (${lat}, ${lng})`);
}
}
// 지역명으로도 시도
if ((lat === undefined || lng === undefined) && (row.name || row.area || row.region || row.location)) {
const regionName = row.name || row.area || row.region || row.location;
console.log(` → 지역명 발견: ${regionName}, 위도/경도 변환 시도`);
// // console.log(` → 지역명 발견: ${regionName}, 위도/경도 변환 시도`);
const coords = getCoordinatesByRegionName(regionName);
if (coords) {
lat = coords.lat;
lng = coords.lng;
console.log(` → 변환 성공: (${lat}, ${lng})`);
// console.log(` → 변환 성공: (${lat}, ${lng})`);
}
}
@@ -476,7 +476,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
if (mapDisplayType === "polygon") {
const regionName = row.name || row.subRegion || row.region || row.area;
if (regionName) {
console.log(` 🔷 강제 폴리곤 모드: ${regionName} → 폴리곤으로 추가 (GeoJSON 매칭)`);
// console.log(` 🔷 강제 폴리곤 모드: ${regionName} → 폴리곤으로 추가 (GeoJSON 매칭)`);
polygons.push({
id: `${sourceName}-polygon-${index}-${row.code || row.id || Date.now()}`,
name: regionName,
@@ -487,14 +487,14 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
color: dataSource?.polygonColor || getColorByStatus(row.status || row.level),
});
} else {
console.log(` ⚠️ 강제 폴리곤 모드지만 지역명 없음 - 스킵`);
// console.log(` ⚠️ 강제 폴리곤 모드지만 지역명 없음 - 스킵`);
}
return; // 폴리곤으로 처리했으므로 마커로는 추가하지 않음
}
// 위도/경도가 있고 marker 모드가 아니면 마커로 처리
if (lat !== undefined && lng !== undefined && mapDisplayType !== "polygon") {
console.log(` → 마커로 처리: (${lat}, ${lng})`);
// // console.log(` → 마커로 처리: (${lat}, ${lng})`);
markers.push({
id: `${sourceName}-marker-${index}-${row.code || row.id || Date.now()}`, // 고유 ID 생성
lat: Number(lat),
@@ -511,7 +511,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 위도/경도가 없는 육지 지역 → 폴리곤으로 추가 (GeoJSON 매칭용)
const regionName = row.name || row.subRegion || row.region || row.area;
if (regionName) {
console.log(` 📍 위도/경도 없지만 지역명 있음: ${regionName} → 폴리곤으로 추가 (GeoJSON 매칭)`);
// console.log(` 📍 위도/경도 없지만 지역명 있음: ${regionName} → 폴리곤으로 추가 (GeoJSON 매칭)`);
polygons.push({
id: `${sourceName}-polygon-${index}-${row.code || row.id || Date.now()}`,
name: regionName,
@@ -522,13 +522,13 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
color: dataSource?.polygonColor || getColorByStatus(row.status || row.level),
});
} else {
console.log(` ⚠️ 위도/경도 없고 지역명도 없음 - 스킵`);
console.log(` 데이터:`, row);
// console.log(` ⚠️ 위도/경도 없고 지역명도 없음 - 스킵`);
// console.log(` 데이터:`, row);
}
}
});
console.log(`${sourceName}: 마커 ${markers.length}개, 폴리곤 ${polygons.length}개 변환 완료`);
// // console.log(`✅ ${sourceName}: 마커 ${markers.length}개, 폴리곤 ${polygons.length}개 변환 완료`);
return { markers, polygons };
};
@@ -757,7 +757,7 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
try {
const response = await fetch("/geojson/korea-municipalities.json");
const data = await response.json();
console.log("🗺️ GeoJSON 로드 완료:", data.features?.length, "개 시/군/구");
// // console.log("🗺️ GeoJSON 로드 완료:", data.features?.length, "개 시/군/구");
setGeoJsonData(data);
} catch (err) {
console.error("❌ GeoJSON 로드 실패:", err);
@@ -769,11 +769,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 초기 로드
useEffect(() => {
const dataSources = element?.dataSources || element?.chartConfig?.dataSources;
console.log("🔄 useEffect 트리거! dataSources:", dataSources);
// // console.log("🔄 useEffect 트리거! dataSources:", dataSources);
if (dataSources && dataSources.length > 0) {
loadMultipleDataSources();
} else {
console.log("⚠️ dataSources가 없거나 비어있음");
// // console.log("⚠️ dataSources가 없거나 비어있음");
setMarkers([]);
setPolygons([]);
}
@@ -791,15 +791,15 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
if (intervals.length === 0) return;
const minInterval = Math.min(...intervals);
console.log(`⏱️ 자동 새로고침 설정: ${minInterval}초마다`);
// // console.log(`⏱️ 자동 새로고침 설정: ${minInterval}초마다`);
const intervalId = setInterval(() => {
console.log("🔄 자동 새로고침 실행");
// // console.log("🔄 자동 새로고침 실행");
loadMultipleDataSources();
}, minInterval * 1000);
return () => {
console.log("⏹️ 자동 새로고침 정리");
// // console.log("⏹️ 자동 새로고침 정리");
clearInterval(intervalId);
};
}, [dataSources, loadMultipleDataSources]);
@@ -876,11 +876,11 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
{/* 폴리곤 렌더링 */}
{/* GeoJSON 렌더링 (육지 지역 경계선) */}
{(() => {
console.log(`🗺️ GeoJSON 렌더링 조건 체크:`, {
geoJsonData: !!geoJsonData,
polygonsLength: polygons.length,
polygonNames: polygons.map(p => p.name),
});
// console.log(`🗺️ GeoJSON 렌더링 조건 체크:`, {
// geoJsonData: !!geoJsonData,
// polygonsLength: polygons.length,
// polygonNames: polygons.map(p => p.name),
// });
return null;
})()}
{geoJsonData && polygons.length > 0 ? (
@@ -897,31 +897,31 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
// 정확한 매칭
if (p.name === sigName) {
console.log(`✅ 정확 매칭: ${p.name} === ${sigName}`);
// console.log(`✅ 정확 매칭: ${p.name} === ${sigName}`);
return true;
}
if (p.name === ctpName) {
console.log(`✅ 정확 매칭: ${p.name} === ${ctpName}`);
// console.log(`✅ 정확 매칭: ${p.name} === ${ctpName}`);
return true;
}
// 부분 매칭 (GeoJSON 지역명에 폴리곤 이름이 포함되는지)
if (sigName && sigName.includes(p.name)) {
console.log(`✅ 부분 매칭: ${sigName} includes ${p.name}`);
// console.log(`✅ 부분 매칭: ${sigName} includes ${p.name}`);
return true;
}
if (ctpName && ctpName.includes(p.name)) {
console.log(`✅ 부분 매칭: ${ctpName} includes ${p.name}`);
// console.log(`✅ 부분 매칭: ${ctpName} includes ${p.name}`);
return true;
}
// 역방향 매칭 (폴리곤 이름에 GeoJSON 지역명이 포함되는지)
if (sigName && p.name.includes(sigName)) {
console.log(`✅ 역방향 매칭: ${p.name} includes ${sigName}`);
// console.log(`✅ 역방향 매칭: ${p.name} includes ${sigName}`);
return true;
}
if (ctpName && p.name.includes(ctpName)) {
console.log(`✅ 역방향 매칭: ${p.name} includes ${ctpName}`);
// console.log(`✅ 역방향 매칭: ${p.name} includes ${ctpName}`);
return true;
}
@@ -969,7 +969,9 @@ export default function MapTestWidgetV2({ element }: MapTestWidgetV2Props) {
}}
/>
) : (
<>{console.log(`⚠️ GeoJSON 렌더링 안 됨: geoJsonData=${!!geoJsonData}, polygons=${polygons.length}`)}</>
<>
{/* console.log(`⚠️ GeoJSON 렌더링 안 됨: geoJsonData=${!!geoJsonData}, polygons=${polygons.length}`) */}
</>
)}
{/* 폴리곤 렌더링 (해상 구역만) */}