fix: Behebt Endlosschleife und doppelte Recoil-Atom-Registrierung

- `index.js` als Client-Komponente deklariert (`"use client"`) zur Vermeidung von SSR-Problemen.
- `useEffect` optimiert, um unendliche API-Requests durch `isMounted`-Check zu verhindern.
- `loadData()` angepasst, um API-Fehler korrekt abzufangen und erneute Ladeversuche zu vermeiden.
- Doppelte Registrierung von `poiReadFromDbTriggerAtom` durch HMR verhindert.
- Ungültige MySQL-Option `acquireTimeout` entfernt, um Verbindungsfehler zu beheben.

Diese Änderungen verhindern unerwartete Reloads und verbessern die Stabilität der Anwendung.
This commit is contained in:
Ismail Ali
2025-02-02 13:01:04 +01:00
parent de0ff741f7
commit 5b2cb762cc
82 changed files with 5710 additions and 189 deletions

View File

@@ -1,47 +1,17 @@
#.env.local #.env.local
#je nach dem Mysql Server, ob localhost freigegeben ist oder die IP Adresse des Servers, manchmal die beide und manchmal nur eine #je nach dem Mysql Server, ob localhost freigegeben ist oder die IP Adresse des Servers, manchmal die beide und manchmal nur eine
#DB_HOST=10.10.0.13 DB_HOST=192.168.10.33
#DB_USER=root
#DB_PASSWORD="root#$"
#DB_NAME=talas_v5
#DB_PORT=3306
#########################
#NEXT_PUBLIC_BASE_URL="http://10.10.0.13/talas5/devices/"
#NEXT_PUBLIC_SERVER_URL="http://10.10.0.13"
#NEXT_PUBLIC_PROXY_TARGET="http://10.10.0.13"
#NEXT_PUBLIC_ONLINE_TILE_LAYER="http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"
#########################
#DB_HOST=10.10.0.70
DB_HOST=127.0.0.1
DB_USER=root DB_USER=root
DB_PASSWORD="root#$" DB_PASSWORD="root#$"
DB_NAME=talas_v5 DB_NAME=talas_v5
DB_PORT=3306 DB_PORT=3306
#########################
#device nur Verlinkung wenn die gleiche DB ist
#NEXT_PUBLIC_BASE_URL="http://10.10.0.70/talas5/devices/"
#NEXT_PUBLIC_SERVER_URL="http://10.10.0.70"
#NEXT_PUBLIC_PROXY_TARGET="http://10.10.0.70"
#NEXT_PUBLIC_ONLINE_TILE_LAYER="http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"
NEXT_PUBLIC_ONLINE_TILE_LAYER="http://127.0.0.1:3000/mapTiles/{z}/{x}/{y}.png"
######################### #########################
#DB_HOST=192.168.10.168 NEXT_PUBLIC_BASE_URL="http://192.168.10.33/talas5/devices/"
#DB_USER=root NEXT_PUBLIC_SERVER_URL="http://192.168.10.33"
#DB_PASSWORD="root#$" NEXT_PUBLIC_PROXY_TARGET="http://192.168.10.33"
#DB_NAME=talas_v5 NEXT_PUBLIC_ONLINE_TILE_LAYER="http://192.168.10.33/talas5/TileMap/mapTiles/{z}/{x}/{y}.png"
#DB_PORT=3306
######################### #########################
#URLs für den Client (clientseitig)
#NEXT_PUBLIC_BASE_URL="http://192.168.10.168/talas5/devices/"
#NEXT_PUBLIC_SERVER_URL="http://192.168.10.168"
#NEXT_PUBLIC_PROXY_TARGET="http://192.168.10.168"
#NEXT_PUBLIC_ONLINE_TILE_LAYER="http://192.168.10.14:3000/mapTiles/{z}/{x}/{y}.png"
######################### online
#NEXT_PUBLIC_ONLINE_TILE_LAYER="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"

View File

@@ -0,0 +1,732 @@
// components/MapComponent.js
import React, { useEffect, useRef, useState, useCallback } from "react";
import L, { marker } from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
import "leaflet-contextmenu";
import * as config from "../config/config.js";
import * as urls from "../config/urls.js";
import "leaflet.smooth_marker_bouncing";
import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet";
import DataSheet from "./DataSheet.js";
import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import { gisStationsStaticDistrictState } from "../store/atoms/gisStationState.js";
import { gisSystemStaticState } from "../store/atoms/gisSystemState.js";
import { mapLayersState } from "../store/atoms/mapLayersState.js";
import { selectedAreaState } from "../store/atoms/selectedAreaState.js";
import { zoomTriggerState } from "../store/atoms/zoomTriggerState.js";
import { poiTypState } from "../store/atoms/poiTypState.js";
import AddPoiModalWindow from "./pois/AddPoiModalWindow.js";
import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom.js";
import { InformationCircleIcon } from "@heroicons/react/20/solid"; // oder 'outline'
import PoiUpdateModal from "./pois/PoiUpdateModal.js";
import { selectedPoiState } from "../store/atoms/poiState.js";
import { currentPoiState } from "../store/atoms/currentPoiState.js";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { mapIdState, userIdState } from "../store/atoms/urlParameterState.js";
import { poiLayerVisibleState } from "../store/atoms/poiLayerVisibleState.js";
import plusRoundIcon from "./PlusRoundIcon.js";
import { parsePoint, findClosestPoints } from "../utils/geometryUtils.js";
import { insertNewPOI, removePOI, handleEditPoi } from "../utils/poiUtils.js";
import { createAndSetDevices } from "../utils/createAndSetDevices.js";
import { redrawPolyline, restoreMapSettings, checkOverlappingMarkers } from "../utils/mapUtils.js";
import circleIcon from "./gisPolylines/icons/CircleIcon.js";
import startIcon from "./gisPolylines/icons/StartIcon.js";
import endIcon from "./gisPolylines/icons/EndIcon.js";
import { fetchGisStatusStations, fetchPriorityConfig, fetchPoiData, updateLocationInDatabase, fetchUserRights, fetchDeviceNameById } from "../services/apiService.js";
import { addContextMenuToMarker } from "../utils/addContextMenuToMarker.js";
import { MAP_VERSION } from "../config/settings.js";
import * as layers from "../config/layers.js";
import { zoomIn, zoomOut, centerHere } from "../utils/zoomAndCenterUtils.js";
import { initializeMap } from "../utils/initializeMap.js";
import { addItemsToMapContextMenu } from "./useMapContextMenu.js";
import useGmaMarkersLayer from "../hooks/layers/useGmaMarkersLayer.js"; // Import the custom hook
import useTalasMarkersLayer from "../hooks/layers/useTalasMarkersLayer.js"; // Import the custom hook
import useEciMarkersLayer from "../hooks/layers/useEciMarkersLayer.js";
import useGsmModemMarkersLayer from "../hooks/layers/useGsmModemMarkersLayer.js";
import useCiscoRouterMarkersLayer from "../hooks/layers/useCiscoRouterMarkersLayer.js";
import useLteModemMarkersLayer from "../hooks/layers/useLteModemMarkersLayer";
import useWagoMarkersLayer from "../hooks/layers/useWagoMarkersLayer.js";
import useSiemensMarkersLayer from "../hooks/layers/useSiemensMarkersLayer.js";
import useOtdrMarkersLayer from "../hooks/layers/useOtdrMarkersLayer.js";
import useWdmMarkersLayer from "../hooks/layers/useWdmMarkersLayer.js";
import useMessstellenMarkersLayer from "../hooks/layers/useMessstellenMarkersLayer.js";
import useTalasiclMarkersLayer from "../hooks/layers/useTalasiclMarkersLayer.js";
import useDauzMarkersLayer from "../hooks/layers/useDauzMarkersLayer.js";
import useSmsfunkmodemMarkersLayer from "../hooks/layers/useSmsfunkmodemMarkersLayer.js";
import useUlafMarkersLayer from "../hooks/layers/useUlafMarkersLayer.js";
import useSonstigeMarkersLayer from "../hooks/layers/useSonstigeMarkersLayer.js";
import handlePoiSelect from "../utils/handlePoiSelect.js";
import { fetchGisStationsStaticDistrict, fetchGisStationsStatusDistrict, fetchGisStationsMeasurements, fetchGisSystemStatic } from "../services/fetchData.js";
import { setupPolylines } from "../utils/setupPolylines.js";
import { setupPOIs } from "../utils/setupPOIs.js";
import VersionInfoModal from "./VersionInfoModal.js";
//--------------------------------------------
import PoiUpdateModalWrapper from "./pois/PoiUpdateModalWrapper";
import AddPoiModalWindowWrapper from "./pois/AddPoiModalWindowWrapper";
import useFetchPoiData from "../hooks/useFetchPoiData";
import usePoiTypData from "../hooks/usePoiTypData";
import useMarkerLayers from "../hooks/useMarkerLayers";
import useLayerVisibility from "../hooks/useLayerVisibility";
import useLineData from "../hooks/useLineData.js";
import useCreateAndSetDevices from "../hooks/useCreateAndSetDevices";
//import { useCreateAndSetDevices } from "../hooks/useCreateAndSetDevices";
import { useMapComponentState } from "../hooks/useMapComponentState";
import { polylineEventsDisabledState } from "../store/atoms/polylineEventsDisabledState";
import { disablePolylineEvents, enablePolylineEvents } from "../utils/setupPolylines";
import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState";
const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
const polylineVisible = useRecoilValue(polylineLayerVisibleState);
const [editMode, setEditMode] = useState(false); // editMode Zustand
const { deviceName, setDeviceName } = useMapComponentState();
const { poiTypData, isPoiTypLoaded } = usePoiTypData("/api/talas_v5_DB/poiTyp/readPoiTyp");
//const [deviceName, setDeviceName] = useState("");
const [locationDeviceData, setLocationDeviceData] = useState([]);
const [priorityConfig, setPriorityConfig] = useState([]);
const [menuItemAdded, setMenuItemAdded] = useState(false);
const poiLayerVisible = useRecoilValue(poiLayerVisibleState);
const [isRightsLoaded, setIsRightsLoaded] = useState(false);
const [hasRights, setHasRights] = useState(false);
const [mapId, setMapId] = useRecoilState(mapIdState);
const [userId, setUserId] = useRecoilState(userIdState);
const [AddPoiModalWindowState, setAddPoiModalWindowState] = useState(false);
const [userRights, setUserRights] = useState(null);
const setSelectedPoi = useSetRecoilState(selectedPoiState);
const [showPoiUpdateModal, setShowPoiUpdateModal] = useState(false);
const [currentPoiData, setCurrentPoiData] = useState(null);
const setCurrentPoi = useSetRecoilState(currentPoiState);
const [showVersionInfoModal, setShowVersionInfoModal] = useState(false);
const zoomTrigger = useRecoilValue(zoomTriggerState);
const [gisSystemStaticLoaded, setGisSystemStaticLoaded] = useState(false);
const [poiTypMap, setPoiTypMap] = useState(new Map());
const [showPopup, setShowPopup] = useState(false);
const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom);
const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker
const mapRef = useRef(null); // Referenz auf das DIV-Element der Karte
const [map, setMap] = useState(null); // Zustand der Karteninstanz
const [oms, setOms] = useState(null); // State für OMS-Instanz
const [GisStationsStaticDistrict, setGisStationsStaticDistrict] = useRecoilState(gisStationsStaticDistrictState);
const [GisStationsStatusDistrict, setGisStationsStatusDistrict] = useState([]); // Zustand für Statusdaten
const [GisStationsMeasurements, setGisStationsMeasurements] = useState([]); // Zustand für Messdaten
const [GisSystemStatic, setGisSystemStatic] = useRecoilState(gisSystemStaticState); // Zustand für Systemdaten
// Konstanten für die URLs
const mapGisStationsStaticDistrictUrl = config.mapGisStationsStaticDistrictUrl;
const mapGisStationsStatusDistrictUrl = config.mapGisStationsStatusDistrictUrl;
const mapGisStationsMeasurementsUrl = config.mapGisStationsMeasurementsUrl;
const mapGisSystemStaticUrl = config.mapGisSystemStaticUrl;
const webserviceGisLinesStatusUrl = config.webserviceGisLinesStatusUrl;
//console.log("priorityConfig in MapComponent1: ", priorityConfig);
/*
const talasMarkers = useTalasMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const eciMarkers = useEciMarkersLayer(map, eciMarkers, oms, layers.MAP_LAYERS.ECI);
const gsmModemMarkers = useGsmModemMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const ciscoRouterMarkers = useCiscoRouterMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const wagoMarkers = useWagoMarkersLayer(map, oms, GisSystemStatic, priorityConfig);
const siemensMarkers = useSiemensMarkersLayer(map, oms, GisSystemStatic, priorityConfig);
const otdrMarkers = useOtdrMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const wdmMarkers = useWdmMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const messstellenMarkers = useMessstellenMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const talasiclMarkers = useTalasiclMarkersLayer(map, oms, GisSystemStatic, priorityConfig);
const dauzMarkers = useDauzMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const smsfunkmodemMarkers = useSmsfunkmodemMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
const ulafMarkers = useUlafMarkersLayer(map, oms, GisSystemStatic, priorityConfig);
const sonstigeMarkers = useSonstigeMarkersLayer(map, oms, GisSystemStatic, priorityConfig); // Use the new custom hook
*/
const [gmaMarkers, setGmaMarkers] = useState([]); //--------------------station.System === 11 alle sind untetschiedlich Nummern
const [talasMarkers, setTalasMarkers] = useState([]);
const [eciMarkers, setEciMarkers] = useState([]);
const [gsmModemMarkers, setGsmModemMarkers] = useState([]);
const [ciscoRouterMarkers, setCiscoRouterMarkers] = useState([]);
const [wagoMarkers, setWagoMarkers] = useState([]);
const [siemensMarkers, setSiemensMarkers] = useState([]);
const [otdrMarkers, setOtdrMarkers] = useState([]);
const [wdmMarkers, setWdmMarkers] = useState([]);
const [messstellenMarkers, setMessstellenMarkers] = useState([]);
const [talasiclMarkers, setTalasiclMarkers] = useState([]);
const [dauzMarkers, setDauzMarkers] = useState([]);
const [smsfunkmodemMarkers, setSmsfunkmodemMarkers] = useState([]);
const [ulafMarkers, setUlafMarkers] = useState([]);
const [sonstigeMarkers, setSonstigeMarkers] = useState([]);
const [lteModemMarkers, setLteModemMarkers] = useState([]);
const [lineStatusData, setLineStatusData] = useState([]);
const [linesData, setLinesData] = useState([]);
const mapLayersVisibility = useRecoilValue(mapLayersState);
const selectedArea = useRecoilValue(selectedAreaState);
const poiData = useFetchPoiData("/api/talas_v5_DB/pois/poi-icons");
const [linePositions, setLinePositions] = useState([]);
const { lineColors, tooltipContents } = useLineData(webserviceGisLinesStatusUrl, setLineStatusData);
const [polylines, setPolylines] = useState([]);
const [markers, setMarkers] = useState([]);
const closePopup = () => setShowPopup(false);
const [newPoint, setNewPoint] = useState(null);
const [newCoords, setNewCoords] = useState(null);
const [tempMarker, setTempMarker] = useState(null);
const [popupCoordinates, setPopupCoordinates] = useState({
lat: 52.52,
lng: 13.405,
});
const handleAddStation = (stationData) => {
setAddPoiModalWindowState(false);
closePopup(); // Schließt das Popup nach dem Hinzufügen
};
const openVersionInfoModal = () => {
setShowVersionInfoModal(true);
};
const closeVersionInfoModal = () => {
setShowVersionInfoModal(false);
};
const [currentZoom, setCurrentZoom] = useState(() => {
const storedZoom = localStorage.getItem("mapZoom");
return storedZoom ? parseInt(storedZoom, 10) : 12;
});
const [currentCenter, setCurrentCenter] = useState(() => {
const storedCenter = localStorage.getItem("mapCenter");
try {
return storedCenter ? JSON.parse(storedCenter) : [53.111111, 8.4625];
} catch (e) {
console.error("Error parsing stored map center:", e);
return [53.111111, 8.4625];
}
});
const [polylineEventsDisabled, setPolylineEventsDisabled] = useRecoilState(polylineEventsDisabledState); // Recoil State
//---------------------------------------------------------------
/* useEffect(() => {
fetchGisStatusStations(12, 484); // Beispielaufruf mit idMap = 10 und idUser = 484
}, []); */
useEffect(() => {
const params = new URL(window.location.href).searchParams;
setMapId(params.get("m"));
setUserId(params.get("u"));
}, [setMapId, setUserId]);
useEffect(() => {
if (map && poiLayerRef.current && isPoiTypLoaded && !menuItemAdded && isRightsLoaded) {
//console.log("Überprüfung der Berechtigung vor addItemsToMapContextMenu: ", hasRights);
addItemsToMapContextMenu(hasRights);
}
}, [
map,
poiLayerRef,
isPoiTypLoaded,
menuItemAdded, // Hinzufügen zu den Abhängigkeiten, um den Effekt korrekt zu steuern
hasRights, // Sicherstellen, dass hasRights berücksichtigt wird
isRightsLoaded, // Überprüfung, ob die Rechte geladen sind
]);
useEffect(() => {
const fetchAndSetUserRights = async () => {
const rights = await fetchUserRights();
setUserRights(rights);
setIsRightsLoaded(true);
// Sicherstellen, dass `rights` ein Array ist, bevor `.includes()` aufgerufen wird
setHasRights(localStorage.getItem("editMode") && Array.isArray(rights) && rights.includes(56));
};
fetchAndSetUserRights();
}, []);
useGmaMarkersLayer(map, gmaMarkers, GisStationsMeasurements, layers.MAP_LAYERS.GMA, oms); // Verwende den ausgelagerten Hook
useEffect(() => {
const fetchWebServiceMap = async () => {
try {
// Zähler für externe API-Aufrufe in localStorage speichern
let requestCount = localStorage.getItem("fetchWebServiceMap") || 0;
requestCount = parseInt(requestCount, 10);
const fetchOptions = {
method: "GET",
headers: {
Connection: "close", // Keep-Alive-Header hinzufügen
},
};
// Fetch GIS Stations Static District
await fetchGisStationsStaticDistrict(mapGisStationsStaticDistrictUrl, setGisStationsStaticDistrict, fetchOptions);
requestCount++; // Zähler erhöhen
localStorage.setItem("fetchWebServiceMap", requestCount);
//console.log(`fetchWebServiceMap in MapComponent wurde ${requestCount} Mal aufgerufen.`);
// Fetch GIS Stations Status District
await fetchGisStationsStatusDistrict(mapGisStationsStatusDistrictUrl, setGisStationsStatusDistrict, fetchOptions);
requestCount++; // Zähler erhöhen
localStorage.setItem("fetchWebServiceMap", requestCount);
//console.log(`fetchWebServiceMap in MapComponent wurde ${requestCount} Mal aufgerufen.`);
// Fetch GIS Stations Measurements
await fetchGisStationsMeasurements(mapGisStationsMeasurementsUrl, setGisStationsMeasurements, fetchOptions);
requestCount++; // Zähler erhöhen
localStorage.setItem("fetchWebServiceMap", requestCount);
//console.log(`fetchWebServiceMap in MapComponent wurde ${requestCount} Mal aufgerufen.`);
// Fetch GIS System Static
await fetchGisSystemStatic(mapGisSystemStaticUrl, setGisSystemStatic, setGisSystemStaticLoaded, fetchOptions);
requestCount++; // Zähler erhöhen
localStorage.setItem("fetchWebServiceMap", requestCount);
//console.log(`fetchWebServiceMap in MapComponent wurde ${requestCount} Mal aufgerufen.`);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchWebServiceMap();
}, []);
//--------------------------------------------------------
useEffect(() => {
const endpoint = "/api/talas_v5_DB/gisLines/readGisLines";
//const endpoint = "http://localhost/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=10";
fetch(endpoint)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => {
const newLinePositions = data.map((item) => {
//console.log("item.idLD", item.idLD);
//console.log("item.idModul", item.idModul);
if (item.points && Array.isArray(item.points)) {
return {
coordinates: item.points.map((point) => [point.x, point.y]),
idModul: item.idModul,
idLD: item.idLD,
};
} else {
throw new Error("Points missing or not an array");
}
});
setLinePositions(newLinePositions);
})
.catch((error) => {
console.error("Error fetching data:", error.message);
});
}, []);
//--------------------------------------------
useEffect(() => {
const fetchPoiTypData = async () => {
try {
const response = await fetch("/api/talas_v5_DB/poiTyp/readPoiTyp");
const data = await response.json();
const map = new Map();
data.forEach((item) => map.set(item.idPoiTyp, item.name));
setPoiTypMap(map);
} catch (error) {
console.error("Fehler beim Abrufen der poiTyp-Daten-1:", error);
}
};
//--------------------------------------------
const fetchPoiData = async () => {
try {
const response = await fetch("/api/talas_v5_DB/pois/poi-icons");
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
} catch (error) {
console.error("Fehler beim Abrufen der poiData-2:", error);
}
};
//--------------------------------------------
fetchPoiTypData();
fetchPoiData();
}, []);
useEffect(() => {
if (map) {
const dbLayer = new L.LayerGroup().addTo(map); // Define dbLayer here
return () => {
dbLayer.remove();
};
}
}, [map]);
useEffect(() => {
if (map && !poiLayerRef.current) {
poiLayerRef.current = new L.LayerGroup().addTo(map);
}
return () => {
if (map && poiLayerRef.current) {
map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map);
}
locations.forEach((location) => {});
};
//console.log("trigger in MapComponent.js:", poiReadTrigger);
}, [map, locations, poiReadTrigger]);
//--------------------------------------------
useEffect(() => {
if (poiData.length === 0) return;
setupPOIs(map, locations, poiData, poiTypMap, userRights, poiLayerRef, setSelectedPoi, setLocationDeviceData, setDeviceName, setCurrentPoi, poiLayerVisible, fetchPoiData, toast, setShowPoiUpdateModal, setCurrentPoiData, deviceName);
}, [map, locations, onLocationUpdate, poiReadTrigger, isPoiTypLoaded, userRights, poiLayerVisible, poiData, poiTypMap]);
//---------------------------------------------
//console.log("priorityConfig in MapComponent2: ", priorityConfig);
useEffect(() => {
if (gisSystemStaticLoaded && map) {
/*
createAndSetDevices(1, GisSystemStatic, priorityConfig); // TALAS-System
createAndSetDevices(2, GisSystemStatic, priorityConfig); // ECI-System
createAndSetDevices(5, GisSystemStatic, priorityConfig); // GSM-Modem-System
createAndSetDevices(6, GisSystemStatic, priorityConfig); // Cisco-Router-System
createAndSetDevices(7, GisSystemStatic, priorityConfig); // WAGO-System
createAndSetDevices(8, GisSystemStatic, priorityConfig); // Siemens-System
createAndSetDevices(9, GisSystemStatic, priorityConfig); // OTDR-System
createAndSetDevices(10, GisSystemStatic, priorityConfig); // WDM-System
createAndSetDevices(13, GisSystemStatic, priorityConfig); // Messstellen-System
createAndSetDevices(100, GisSystemStatic, priorityConfig); // TALASICL-System
createAndSetDevices(110, GisSystemStatic, priorityConfig); // DAUZ-System
createAndSetDevices(111, GisSystemStatic, priorityConfig); // SMS-Funkmodem-System
createAndSetDevices(200, GisSystemStatic, priorityConfig); // Sonstige-System
createAndSetDevices(0, GisSystemStatic, priorityConfig); // ULAF-System
*/
createAndSetDevices(11, setGmaMarkers, GisSystemStatic, priorityConfig); // GMA-System
createAndSetDevices(1, setTalasMarkers, GisSystemStatic, priorityConfig); // TALAS-System
createAndSetDevices(2, setEciMarkers, GisSystemStatic, priorityConfig); // ECI-System
createAndSetDevices(5, setGsmModemMarkers, GisSystemStatic, priorityConfig); // GSM-Modem-System
createAndSetDevices(5, setLteModemMarkers, GisSystemStatic, priorityConfig); //LTE Modem
createAndSetDevices(6, setCiscoRouterMarkers, GisSystemStatic, priorityConfig); // Cisco-Router-System
createAndSetDevices(7, setWagoMarkers, GisSystemStatic, priorityConfig); // WAGO-System
createAndSetDevices(8, setSiemensMarkers, GisSystemStatic, priorityConfig); // Siemens-System
createAndSetDevices(9, setOtdrMarkers, GisSystemStatic, priorityConfig); // OTDR-System
createAndSetDevices(10, setWdmMarkers, GisSystemStatic, priorityConfig); // WDM-System
createAndSetDevices(13, setMessstellenMarkers, GisSystemStatic, priorityConfig); // Messstellen-System
createAndSetDevices(100, setTalasiclMarkers, GisSystemStatic, priorityConfig); // TALASICL-System
createAndSetDevices(110, setDauzMarkers, GisSystemStatic, priorityConfig); // DAUZ-System
createAndSetDevices(111, setSmsfunkmodemMarkers, GisSystemStatic, priorityConfig); // SMS-Funkmodem-System
createAndSetDevices(200, setSonstigeMarkers, GisSystemStatic, priorityConfig); // Sonstige-System
createAndSetDevices(0, setUlafMarkers, GisSystemStatic, priorityConfig); // ULAF-System
}
}, [gisSystemStaticLoaded, map, GisSystemStatic, priorityConfig]);
//useCreateAndSetDevices(1, talasMarkers, GisSystemStatic, priorityConfig);
useLayerVisibility(map, talasMarkers, mapLayersVisibility, "TALAS", oms);
useLayerVisibility(map, eciMarkers, mapLayersVisibility, "ECI", oms);
useLayerVisibility(map, gsmModemMarkers, mapLayersVisibility, "GSMModem", oms);
useLayerVisibility(map, ciscoRouterMarkers, mapLayersVisibility, "CiscoRouter", oms);
useLayerVisibility(map, lteModemMarkers, mapLayersVisibility, "LTEModem", oms);
useLayerVisibility(map, wagoMarkers, mapLayersVisibility, "WAGO", oms);
useLayerVisibility(map, siemensMarkers, mapLayersVisibility, "Siemens", oms);
useLayerVisibility(map, otdrMarkers, mapLayersVisibility, "OTDR", oms);
useLayerVisibility(map, wdmMarkers, mapLayersVisibility, "WDM", oms);
useLayerVisibility(map, gmaMarkers, mapLayersVisibility, "GMA", oms);
useLayerVisibility(map, sonstigeMarkers, mapLayersVisibility, "Sonstige", oms);
useLayerVisibility(map, talasiclMarkers, mapLayersVisibility, "TALASICL", oms);
useLayerVisibility(map, dauzMarkers, mapLayersVisibility, "DAUZ", oms);
useLayerVisibility(map, smsfunkmodemMarkers, mapLayersVisibility, "SMSFunkmodem", oms);
useLayerVisibility(map, messstellenMarkers, mapLayersVisibility, "Messstellen", oms);
useLayerVisibility(map, ulafMarkers, mapLayersVisibility, "ULAF", oms);
useEffect(() => {
if (map) {
var x = 51.41321407879154;
var y = 7.739617925303934;
var zoom = 7;
if (map && map.flyTo) {
map.flyTo([x, y], zoom);
} else {
console.error("Map object is not ready or does not have flyTo method");
}
}
}, [map, zoomTrigger]);
useEffect(() => {
if (map) {
const allMarkers = [
...talasMarkers,
...eciMarkers,
...gsmModemMarkers,
...ciscoRouterMarkers,
...wagoMarkers,
...siemensMarkers,
...otdrMarkers,
...wdmMarkers,
...gmaMarkers,
...messstellenMarkers,
...talasiclMarkers,
...dauzMarkers,
...smsfunkmodemMarkers,
...sonstigeMarkers,
...ulafMarkers,
...lteModemMarkers,
];
checkOverlappingMarkers(map, allMarkers, plusRoundIcon);
}
}, [map, talasMarkers, eciMarkers, ciscoRouterMarkers, wagoMarkers, siemensMarkers, otdrMarkers, wdmMarkers, gmaMarkers, messstellenMarkers, talasiclMarkers, dauzMarkers, smsfunkmodemMarkers, sonstigeMarkers, ulafMarkers, lteModemMarkers]);
useEffect(() => {
const fetchData = async () => {
try {
const response1 = await fetch(webserviceGisLinesStatusUrl);
const data1 = await response1.json();
//console.log("data1.Statis", data1.Statis);
const reversedData = data1.Statis.reverse();
setLineStatusData(reversedData);
const response2 = await fetch("/api/talas_v5_DB/gisLines/readGisLines");
const data2 = await response2.json();
const colorsByModule = {};
reversedData.forEach((stat) => {
const matchingLine = data2.find((item) => item.idLD === stat.IdLD && item.idModul === stat.Modul);
if (matchingLine) {
colorsByModule[matchingLine.idModul] = stat.PrioColor;
//console.log("Übereinstimmung gefunden für: ", stat);
setLinesData(matchingLine);
}
});
//setLineColors(colorsByModule);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
//--------------------------------------------
//Tooltip an mouse position anzeigen für die Linien
useEffect(() => {
if (!map) return;
// Entferne alte Marker und Polylinien
markers.forEach((marker) => marker.remove());
polylines.forEach((polyline) => polyline.remove());
// Setze neue Marker und Polylinien mit den aktuellen Daten
const { markers: newMarkers, polylines: newPolylines } = setupPolylines(
map,
linePositions,
lineColors,
tooltipContents,
setNewCoords,
tempMarker,
polylineVisible // polylineVisible wird jetzt korrekt übergeben
);
newPolylines.forEach((polyline, index) => {
const tooltipContent = tooltipContents[`${linePositions[index].idLD}-${linePositions[index].idModul}`] || "Standard-Tooltip-Inhalt";
polyline.bindTooltip(tooltipContent, {
permanent: false,
direction: "auto",
sticky: true,
offset: [20, 0],
pane: "tooltipPane",
});
polyline.on("mouseover", (e) => {
const tooltip = polyline.getTooltip();
if (tooltip) {
const mousePos = e.containerPoint;
const mapSize = map.getSize();
let direction = "right";
if (mousePos.x > mapSize.x - 100) {
direction = "left";
} else if (mousePos.x < 100) {
direction = "right";
}
if (mousePos.y > mapSize.y - 100) {
direction = "top";
} else if (mousePos.y < 100) {
direction = "bottom";
}
tooltip.options.direction = direction;
polyline.openTooltip(e.latlng);
}
});
polyline.on("mouseout", () => {
polyline.closeTooltip();
});
});
setMarkers(newMarkers);
setPolylines(newPolylines);
}, [map, linePositions, lineColors, tooltipContents, newPoint, newCoords, tempMarker, polylineVisible]);
//--------------------------------------------
useEffect(() => {
if (map) {
restoreMapSettings(map);
}
}, [map]);
useEffect(() => {
if (map) {
const handleMapMoveEnd = (event) => {
const newCenter = map.getCenter();
const newZoom = map.getZoom();
setCurrentCenter([newCenter.lat, newCenter.lng]);
setCurrentZoom(newZoom);
localStorage.setItem("mapCenter", JSON.stringify([newCenter.lat, newCenter.lng]));
localStorage.setItem("mapZoom", newZoom);
};
map.on("moveend", handleMapMoveEnd);
map.on("zoomend", handleMapMoveEnd);
return () => {
map.off("moveend", handleMapMoveEnd);
map.off("zoomend", handleMapMoveEnd);
};
}
}, [map]);
//--------------------------------------------
useEffect(() => {
if (selectedArea && map) {
const station = GisStationsStaticDistrict.find((s) => s.Area_Name === selectedArea);
if (station) {
map.flyTo([station.X, station.Y], 14);
}
}
}, [selectedArea, map, GisStationsStaticDistrict]);
useEffect(() => {
if (zoomTrigger && map) {
map.flyTo([51.41321407879154, 7.739617925303934], 7);
}
}, [zoomTrigger, map]);
useEffect(() => {
if (map && poiLayerRef.current && isPoiTypLoaded && !menuItemAdded && isRightsLoaded) {
addItemsToMapContextMenu(map, menuItemAdded, setMenuItemAdded, hasRights, setShowPopup, setPopupCoordinates);
}
}, [map, poiLayerRef, isPoiTypLoaded, menuItemAdded, hasRights, isRightsLoaded]);
//--------------------------------------------
// rote Marker ganz oben wenn überlappen sind
useEffect(() => {
const fetchPriorityConfig = async () => {
try {
const res = await fetch("/api/talas_v5_DB/priorityConfig");
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data = await res.json();
setPriorityConfig(data);
} catch (error) {
console.error("Failed to load priority configuration:", error);
}
};
fetchPriorityConfig();
}, []);
//--------------------------------------------
useEffect(() => {
if (mapRef.current && !map) {
initializeMap(mapRef, setMap, setOms, setMenuItemAdded, addItemsToMapContextMenu, hasRights, setPolylineEventsDisabled);
}
}, [mapRef, map, hasRights, setPolylineEventsDisabled]);
useEffect(() => {
if (map) {
if (polylineEventsDisabled) {
disablePolylineEvents(window.polylines);
} else {
enablePolylineEvents(window.polylines, window.lineColors);
}
}
}, [map, polylineEventsDisabled]);
useEffect(() => {
if (map) {
console.log("6- Karteninstanz (map) wurde jetzt erfolgreich initialisiert");
// Setze die Karteninstanz in den Recoil-Atom
}
}, [map]);
//--------------------------------------------
useEffect(() => {
const initializeContextMenu = () => {
if (map) {
map.whenReady(() => {
setTimeout(() => {
if (map.contextmenu) {
//console.log("Contextmenu ist vorhanden");
} else {
console.warn("Contextmenu ist nicht verfügbar.");
}
}, 500);
});
}
};
initializeContextMenu();
}, [map]);
//--------------------------------------------
return (
<>
<ToastContainer />
<div>{showPoiUpdateModal && <PoiUpdateModal onClose={() => setShowPoiUpdateModal(false)} poiData={currentPoiData} onSubmit={() => {}} latlng={popupCoordinates} />}</div>
<div>
{showPopup && (
<div className="fixed inset-0 bg-black bg-opacity-10 flex justify-center items-center z-[1000]" onClick={closePopup}>
<div className="relative bg-white p-6 rounded-lg shadow-lg" onClick={(e) => e.stopPropagation()}>
<button onClick={closePopup} className="absolute top-0 right-0 mt-2 mr-2 p-1 text-gray-700 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600" aria-label="Close">
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<AddPoiModalWindow onClose={closePopup} onSubmit={handleAddStation} latlng={popupCoordinates} />
</div>
</div>
)}
</div>
<DataSheet className="z-50" />
<div id="map" ref={mapRef} className="z-0" style={{ height: "100vh", width: "100vw" }}></div>
<div className="absolute bottom-3 left-3 w-72 p-4 bg-white rounded-lg shadow-md z-50">
<div className="flex justify-between items-center">
<div>
<span className="text-black text-lg font-semibold"> TALAS.Map </span>
<br />
<span className="text-black text-lg">Version {MAP_VERSION}</span>
</div>
<div>
<button onClick={openVersionInfoModal}>
<InformationCircleIcon className="text-blue-900 h-8 w-8 pr-1" title="Weitere Infos" />
</button>
</div>
</div>
</div>
<VersionInfoModal showVersionInfoModal={showVersionInfoModal} closeVersionInfoModal={closeVersionInfoModal} MAP_VERSION={MAP_VERSION} />
</>
);
};
export default MapComponent;

View File

@@ -1,5 +1,5 @@
// pages/api/poiUpdateModal.js // pages/api/poiUpdateModal.js
//
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
import { selectedPoiState } from "../store/atoms/poiState"; import { selectedPoiState } from "../store/atoms/poiState";
@@ -15,22 +15,50 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
const [locationDeviceData, setLocationDeviceData] = useState([]); const [locationDeviceData, setLocationDeviceData] = useState([]);
const [deviceName, setDeviceName] = useState(""); const [deviceName, setDeviceName] = useState("");
const [idLD, setIdLD] = useState(poiData ? poiData.idLD : ""); const [idLD, setIdLD] = useState(poiData ? poiData.idLD : "");
const [idLocationDevice, setIdLocationDevice] = useState("");
const [description, setDescription] = useState(poiData ? poiData.description : ""); const [description, setDescription] = useState(poiData ? poiData.description : "");
// Log the initial POI data
useEffect(() => { useEffect(() => {
if (poiData) { if (poiData) {
console.log("Initial poiData:", poiData);
setPoiId(poiData.idPoi); setPoiId(poiData.idPoi);
setName(poiData.name); setName(poiData.name);
setPoiTypeId(poiData.idPoiTyp); setPoiTypeId(poiData.idPoiTyp);
setIdLD(poiData.idLD); setIdLD(poiData.idLD);
setDescription(poiData.description); setDescription(poiData.description);
setDeviceName(poiData.idLD); setDeviceName(poiData.idLD);
console.log("Loaded POI Data for editing:", poiData); console.log("Loaded POI Data for editing:", poiData);
console.log("POI ID:", poiData.idPoi);
console.log("POI Name:", poiData.name);
console.log("POI Typ ID:", poiData.idPoiTyp);
console.log("POI Beschreibung:", poiData.description);
console.log("POI Geräte-ID:", poiData.idLD);
} }
}, [poiData]); }, [poiData]);
/* const fetchDeviceNameById = async (idLD) => {
try {
const response = await fetch(`/api/getDeviceNameById?idLD=${idLD}`);
const data = await response.json();
setDeviceName(data.deviceName);
} catch (error) {
console.error("Error fetching device name:", error);
}
}; */
/* const fetchDeviceNameById = async (idLD) => {
try {
const response = await fetch(`/api/talas_v5_DB/locationDevice/locationDeviceNameById?idLD=${idLD}`);
const data = await response.json();
setDeviceName(data.deviceName);
} catch (error) {
console.error("Error fetching device name:", error);
}
}; */
// Beim Öffnen des Modals die Geräte-ID basierend auf dem Gerätenamen abrufen, wenn vorhanden
useEffect(() => { useEffect(() => {
const fetchDeviceId = async () => { const fetchDeviceId = async () => {
if (poiData && poiData.idLD) { if (poiData && poiData.idLD) {
@@ -47,6 +75,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
fetchDeviceId(); fetchDeviceId();
}, [poiData]); }, [poiData]);
// Function to handle deleting a POI
const handleDeletePoi = async () => { const handleDeletePoi = async () => {
if (confirm("Sind Sie sicher, dass Sie diesen POI löschen möchten?")) { if (confirm("Sind Sie sicher, dass Sie diesen POI löschen möchten?")) {
try { try {
@@ -55,7 +84,8 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
}); });
if (response.ok) { if (response.ok) {
alert("POI wurde erfolgreich gelöscht."); alert("POI wurde erfolgreich gelöscht.");
onClose(); onClose(); // Close the modal
//Browser neu laden, um die aktualisierte Liste anzuzeigen
window.location.reload(); window.location.reload();
} else { } else {
throw new Error("Fehler beim Löschen des POI."); throw new Error("Fehler beim Löschen des POI.");
@@ -67,6 +97,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
} }
}; };
// Fetch POI types
useEffect(() => { useEffect(() => {
const fetchPoiTypData = async () => { const fetchPoiTypData = async () => {
try { try {
@@ -86,15 +117,15 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
fetchPoiTypData(); fetchPoiTypData();
}, [selectedPoi]); }, [selectedPoi]);
// Fetch device data um den Gerät Namen in den dropdown menu anzuzeigen also erstmal die Liste der Geräte abrufen
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchData = async () => {
try { try {
// const response = await fetch("/api/talas_v5/location_device"); //"/api/talas_v5_DB/locationDevice/location_device" const response = await fetch("/api/talas_v5/location_device");
const response = await fetch(
"/api/talas_v5_DB/locationDevice/locationDevices"
);
const data = await response.json(); const data = await response.json();
//console.log("Standort- und Gerätedaten:", data);
setLocationDeviceData(data); setLocationDeviceData(data);
console.log("Standort- und Gerätedaten poiData:", poiData);
if (poiData && poiData.idLD) { if (poiData && poiData.idLD) {
const selectedDevice = data.find((device) => device.id === poiData.idLD); const selectedDevice = data.find((device) => device.id === poiData.idLD);
setDeviceName(selectedDevice ? selectedDevice.id : data[0].id); // Hier wird die ID als initialer Zustand gesetzt setDeviceName(selectedDevice ? selectedDevice.id : data[0].id); // Hier wird die ID als initialer Zustand gesetzt
@@ -107,8 +138,11 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
}; };
fetchData(); fetchData();
}, []); }, []);
//--------------------------------------------------------------------------------------------
// Fetch device name basierend auf der Geräte-ID
useEffect(() => { useEffect(() => {
console.log("currentPoi von PoiUpdateModal.js : ", currentPoi.idLD);
fetch("/api/talas_v5_DB/locationDevice/locationDevices") fetch("/api/talas_v5_DB/locationDevice/locationDevices")
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
@@ -127,6 +161,10 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
}); });
}, [poiData?.idLD, currentPoi]); }, [poiData?.idLD, currentPoi]);
//--------------------------------------------------------------------------------------------
// Angenommen, deviceName enthält die Geräte-ID
//const idLD = deviceName; // Stellen Sie sicher, dass dies eine ID ist und kein Name
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`); const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`);
@@ -144,6 +182,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
description: description, description: description,
idPoiTyp: poiTypeId, idPoiTyp: poiTypeId,
idLD: idLD, idLD: idLD,
//idLD: parseInt(deviceName, 10), // Konvertieren in eine Ganzzahl
}), }),
}); });
@@ -208,7 +247,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
</div> </div>
<button <button
type="button" type="button" // Use button type to prevent form submission
onClick={handleDeletePoi} onClick={handleDeletePoi}
className="bg-red-400 hover:bg-red-600 text-white font-bold py-2 px-4 rounded w-full mb-4" className="bg-red-400 hover:bg-red-600 text-white font-bold py-2 px-4 rounded w-full mb-4"
> >

View File

@@ -109,9 +109,6 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => {
onClose(); onClose();
return newTrigger; return newTrigger;
}); });
// Browser aktualisieren
window.location.reload();
} else { } else {
console.error("Fehler beim Hinzufügen des POI"); console.error("Fehler beim Hinzufügen des POI");
} }
@@ -120,7 +117,6 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => {
map.closePopup(); map.closePopup();
} }
}; };
//-----------------handleSubmit------------------- //-----------------handleSubmit-------------------
return ( return (

162
components/imports.js Normal file
View File

@@ -0,0 +1,162 @@
// imports.js
import React, { useEffect, useRef, useState, useCallback } from "react";
import L, { marker } from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
import "leaflet-contextmenu";
import * as config from "../config/config.js";
import * as urls from "../config/urls.js";
import "leaflet.smooth_marker_bouncing";
import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet";
import DataSheet from "./DataSheet.js";
import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import { gisStationsStaticDistrictState } from "../store/atoms/gisStationState.js";
import { gisSystemStaticState } from "../store/atoms/gisSystemState.js";
import { mapLayersState } from "../store/atoms/mapLayersState.js";
import { selectedAreaState } from "../store/atoms/selectedAreaState.js";
import { zoomTriggerState } from "../store/atoms/zoomTriggerState.js";
import { poiTypState } from "../store/atoms/poiTypState.js";
import AddPoiModalWindow from "./pois/AddPoiModalWindow.js";
import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom.js";
import { InformationCircleIcon } from "@heroicons/react/20/solid"; // oder 'outline'
import PoiUpdateModal from "./pois/PoiUpdateModal.js";
import { selectedPoiState } from "../store/atoms/poiState.js";
import { currentPoiState } from "../store/atoms/currentPoiState.js";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { mapIdState, userIdState } from "../store/atoms/urlParameterState.js";
import { poiLayerVisibleState } from "../store/atoms/poiLayerVisibleState.js";
import plusRoundIcon from "./PlusRoundIcon.js";
import { parsePoint, findClosestPoints } from "../utils/geometryUtils.js";
import { insertNewPOI, removePOI, handleEditPoi } from "../utils/poiUtils.js";
import { createAndSetDevices } from "../utils/createAndSetDevices.js";
import { redrawPolyline, restoreMapSettings, checkOverlappingMarkers } from "../utils/mapUtils.js";
import circleIcon from "./gisPolylines/icons/CircleIcon.js";
import startIcon from "./gisPolylines/icons/StartIcon.js";
import endIcon from "./gisPolylines/icons/EndIcon.js";
import { fetchGisStatusStations, fetchPriorityConfig, fetchPoiData, updateLocationInDatabase, fetchUserRights, fetchDeviceNameById } from "../services/apiService.js";
import { addContextMenuToMarker } from "../utils/addContextMenuToMarker.js";
import { MAP_VERSION } from "../config/settings.js";
import * as layers from "../config/layers.js";
import { zoomIn, zoomOut, centerHere } from "../utils/zoomAndCenterUtils.js";
import { initializeMap } from "../utils/initializeMap.js";
import { addItemsToMapContextMenu } from "./useMapContextMenu.js";
import useGmaMarkersLayer from "../hooks/layers/useGmaMarkersLayer.js"; // Import the custom hook
import useTalasMarkersLayer from "../hooks/layers/useTalasMarkersLayer.js"; // Import the custom hook
import useEciMarkersLayer from "../hooks/layers/useEciMarkersLayer.js";
import useGsmModemMarkersLayer from "../hooks/layers/useGsmModemMarkersLayer.js";
import useCiscoRouterMarkersLayer from "../hooks/layers/useCiscoRouterMarkersLayer.js";
import useWagoMarkersLayer from "../hooks/layers/useWagoMarkersLayer.js";
import useSiemensMarkersLayer from "../hooks/layers/useSiemensMarkersLayer.js";
import useOtdrMarkersLayer from "../hooks/layers/useOtdrMarkersLayer.js";
import useWdmMarkersLayer from "../hooks/layers/useWdmMarkersLayer.js";
import useMessstellenMarkersLayer from "../hooks/layers/useMessstellenMarkersLayer.js";
import useTalasiclMarkersLayer from "../hooks/layers/useTalasiclMarkersLayer.js";
import useDauzMarkersLayer from "../hooks/layers/useDauzMarkersLayer.js";
import useSmsfunkmodemMarkersLayer from "../hooks/layers/useSmsfunkmodemMarkersLayer.js";
import useUlafMarkersLayer from "../hooks/layers/useUlafMarkersLayer.js";
import useSonstigeMarkersLayer from "../hooks/layers/useSonstigeMarkersLayer.js";
import handlePoiSelect from "../utils/handlePoiSelect.js";
import { fetchGisStationsStaticDistrict, fetchGisStationsStatusDistrict, fetchGisStationsMeasurements, fetchGisSystemStatic } from "../services/fetchData.js";
import { setupPolylines } from "../utils/setupPolylines.js";
import { setupPOIs } from "../utils/setupPOIs.js";
import VersionInfoModal from "./VersionInfoModal.js";
//--------------------------------------------
import PoiUpdateModalWrapper from "./pois/PoiUpdateModalWrapper";
import AddPoiModalWindowWrapper from "./pois/AddPoiModalWindowWrapper";
import useFetchPoiData from "../hooks/useFetchPoiData";
import usePoiTypData from "../hooks/usePoiTypData";
import useMarkerLayers from "../hooks/useMarkerLayers";
import useLayerVisibility from "../hooks/useLayerVisibility";
import useLineData from "../hooks/useLineData.js";
export {
React,
useEffect,
useRef,
useState,
useCallback,
L,
marker,
config,
urls,
OverlappingMarkerSpiderfier,
DataSheet,
useRecoilState,
useRecoilValue,
useSetRecoilState,
gisStationsStaticDistrictState,
gisSystemStaticState,
mapLayersState,
selectedAreaState,
zoomTriggerState,
poiTypState,
AddPoiModalWindow,
poiReadFromDbTriggerAtom,
InformationCircleIcon,
PoiUpdateModal,
selectedPoiState,
currentPoiState,
ToastContainer,
toast,
mapIdState,
userIdState,
poiLayerVisibleState,
plusRoundIcon,
parsePoint,
findClosestPoints,
insertNewPOI,
removePOI,
createAndSetDevices,
handleEditPoi,
redrawPolyline,
restoreMapSettings,
checkOverlappingMarkers,
circleIcon,
startIcon,
endIcon,
fetchGisStatusStations,
fetchPriorityConfig,
fetchPoiData,
updateLocationInDatabase,
fetchUserRights,
fetchDeviceNameById,
addContextMenuToMarker,
MAP_VERSION,
layers,
zoomIn,
zoomOut,
centerHere,
initializeMap,
addItemsToMapContextMenu,
useGmaMarkersLayer,
useTalasMarkersLayer,
useEciMarkersLayer,
useGsmModemMarkersLayer,
useCiscoRouterMarkersLayer,
useWagoMarkersLayer,
useSiemensMarkersLayer,
useOtdrMarkersLayer,
useWdmMarkersLayer,
useMessstellenMarkersLayer,
useTalasiclMarkersLayer,
useDauzMarkersLayer,
useSmsfunkmodemMarkersLayer,
useUlafMarkersLayer,
useSonstigeMarkersLayer,
handlePoiSelect,
fetchGisStationsStaticDistrict,
fetchGisStationsStatusDistrict,
fetchGisStationsMeasurements,
fetchGisSystemStatic,
setupPolylines,
setupPOIs,
VersionInfoModal,
PoiUpdateModalWrapper,
AddPoiModalWindowWrapper,
useFetchPoiData,
usePoiTypData,
useMarkerLayers,
useLayerVisibility,
useLineData,
};

View File

@@ -1,54 +1,73 @@
// /config/config.js // /config/config.js
import * as urls from "../config/urls.js"; import * as urls from "../config/urls.js";
// Definieren der grundlegenden Umgebungseinstellungen und Konfigurationen der Karte // Definieren der grundlegenden Umgebungseinstellungen und Konfigurationen der Karte
const mapVersion = "0.5.3"; // Die Version der verwendeten Karte const mapVersion = "0.5.3"; // Die Version der verwendeten Karte
const standardSideMenu = true; // Einstellung, ob ein standardmäßiges Seitenmenü verwendet wird const standardSideMenu = true; // Einstellung, ob ein standardmäßiges Seitenmenü verwendet wird
const fullSideMenu = false; // Einstellung, ob ein vollständiges Seitenmenü verwendet wird const fullSideMenu = false; // Einstellung, ob ein vollständiges Seitenmenü verwendet wird
//const serverURL = "/api"; // Die Basis-URL des Servers, von dem Daten bezogen werden
// Dynamische Bestimmung der Server-URL basierend auf window.location.origin ohne Port //const serverURL = "http://10.10.0.13";
let serverURL; //const serverURL = "http://10.10.0.70";
const serverURL = process.env.NEXT_PUBLIC_SERVER_URL;
if (typeof window !== "undefined") { if (!serverURL) {
const url = new URL(window.location.origin); throw new Error("Die Umgebungsvariable NEXT_PUBLIC_SERVER_URL ist nicht gesetzt!");
serverURL = `${url.protocol}//${url.hostname}`; // Nur Protokoll und Hostname, ohne Port
} else {
throw new Error("ServerURL kann nicht bestimmt werden, da der Code nicht im Browser läuft!");
} }
console.log("%c 1- serverURL in config:", "color: #006400;", serverURL);
console.log("%c ServerURL (dynamisch ermittelt):", "color: #006400;", serverURL); // Initialisieren von Variablen, die später im Browserkontext gesetzt werden
// Initialisieren von Variablen
let windowHeight, url_string, url, idMap, idUser; let windowHeight, url_string, url, idMap, idUser;
// URLs für Online-Daten //Online Daten
let mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl, mapDataIconUrl, webserviceGisLinesStatusUrl; let mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl, mapDataIconUrl, webserviceGisLinesStatusUrl;
// Prüfen, ob der Code im Browser ausgeführt wird // Prüfen, ob das Code im Browser ausgeführt wird
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
// Initialisierung der Browser-spezifischen Variablen // Diese Variablen werden nur im Browser-Kontext initialisiert
windowHeight = window.innerHeight; windowHeight = window.innerHeight; // Die Höhe des Browserfensters
url_string = window.location.href; url_string = window.location.href; // Die vollständige URL als String
url = new URL(url_string); url = new URL(url_string); // Die URL als URL-Objekt, um Teile der URL einfacher zu handhaben
console.log("%c 2- URL in config:", "color: #006400; font-size: 16px; background-color: #f0f0f0;", url);
console.log("%c Aktuelle URL:", "color: #006400;", url); console.log("%c 3- URL origin in config:", "color: #006400;", url.origin); //http://localhost:3000
idMap = url.searchParams.get("m"); // Ein Parameter aus der URL, Standardwert ist '10'
idUser = url.searchParams.get("u"); // Ein weiterer Parameter aus der URL, Standardwert ist '484 admin zu testen von Stationen ausblenden und einblenden in der Card'
// Extrahiere URL-Parameter console.log(`4- Parameter 'idMap' : ${idMap}`);
idMap = url.searchParams.get("m"); // Parameter 'm' (idMap) console.log(`5- Parameter 'idUser': ${idUser}`);
idUser = url.searchParams.get("u"); // Parameter 'u' (idUser)
console.log(`Parameter 'idMap': ${idMap}`); // Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen
console.log(`Parameter 'idUser': ${idUser}`); //http://localhost:3000/?m=10&u=485
// Konstruktion der URLs basierend auf den Server- und URL-Parametern //-----------------Von WebService------------------------------------------------
mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${idMap}&idUser=${idUser}`; mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${idMap}&idUser=${idUser}`; //idMap: 10, idUser: 484
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`; mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${idMap}`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${idMap}`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`;
//webserviceGisLinesStatusUrl = `http://10.10.0.13/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`;
//webserviceGisLinesStatusUrl = `http://localhost:3000/api/linesColorApi`;
//webserviceGisLinesStatusUrl = `http://localhost:3000/api/linesColorApi`;
//webserviceGisLinesStatusUrl = `${"serverURL"}:3000/api/linesColorApi`;
// webserviceGisLinesStatusUrl = `http://localhost:3000/api/linesColorApi`;
//webserviceGisLinesStatusUrl = `http://192.168.10.14/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`;
webserviceGisLinesStatusUrl = `${serverURL}/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`; webserviceGisLinesStatusUrl = `${serverURL}/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`;
//http://10.10.0.13/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=12&idUser=484
/* mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict`;
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; */
/* mapGisStationsStaticDistrictUrl = `${serverURL}/api/talas5/webserviceMap/GisStationsStaticDistrict?idMap=${idMap}&idUser=${idUser}`;
mapGisStationsStatusDistrictUrl = `${serverURL}/api/talas5/webserviceMap/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`;
mapGisStationsMeasurementsUrl = `${serverURL}/api/talas5/webserviceMap/GisStationsMeasurements?idMap=${idMap}`;
mapGisStationsMeasurementsUrl = `${serverURL}/api/talas5/webserviceMap/gisStationsMeasurementsSQL?idMap=${idMap}`;
mapGisSystemStaticUrl = `${serverURL}/api/talas5/webserviceMap/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`;
mapDataIconUrl = `${serverURL}/api/talas5/webserviceMap/GetIconsStatic`; */
} }
// Export der definierten Variablen und URLs // Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können
export { export {
mapVersion, mapVersion,
standardSideMenu, standardSideMenu,
@@ -66,3 +85,9 @@ export {
mapDataIconUrl, mapDataIconUrl,
webserviceGisLinesStatusUrl, webserviceGisLinesStatusUrl,
}; };
/*
Access to fetch at 'http://localhost:3000/api/linesColorApi' from origin 'http://10.10.0.13:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
*/

View File

@@ -1,5 +1,5 @@
// /config/settings.js // /config/settings.js
// Definieren der grundlegenden Umgebungseinstellungen und Konfigurationen der Karte // Definieren der grundlegenden Umgebungseinstellungen und Konfigurationen der Karte
export const MAP_VERSION = "1.0.8"; export const MAP_VERSION = "1.0.8.1";
//export const STANDARD_SIDE_MENU = true; //export const STANDARD_SIDE_MENU = true;
//export const FULL_SIDE_MENU = false; //export const FULL_SIDE_MENU = false;

View File

@@ -1,38 +1,9 @@
// /config/urls.js // /config/urls.js
// Dynamische Bestimmung der URLs basierend auf window.location.origin ohne Port export const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL; //Station in Tab öffnen
let BASE_URL, SERVER_URL, PROXY_TARGET, ONLINE_TILE_LAYER, OFFLINE_TILE_LAYER, MAP_TILES_LAYER;
if (typeof window !== "undefined") {
// Client-seitige Logik
const url = new URL(window.location.origin);
const originWithoutPort = `${url.protocol}//${url.hostname}`; // Protokoll und Hostname, ohne Port
BASE_URL = `${originWithoutPort}/api`; // Dynamische Basis-URL
SERVER_URL = originWithoutPort; // Dynamisch ermittelt, ohne Port
PROXY_TARGET = `${originWithoutPort}:3000`; // Dynamisch für einen Proxy
ONLINE_TILE_LAYER = `https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`;
OFFLINE_TILE_LAYER = `${originWithoutPort}:3000/mapTiles/{z}/{x}/{y}.png`;
MAP_TILES_LAYER = ONLINE_TILE_LAYER; // Standardwert
} else {
// Server-seitige Logik (Fallback)
const originWithoutPort = "http://fallback-url.com"; // Ersetze dies durch die gewünschte Fallback-URL
BASE_URL = `${originWithoutPort}/api`;
SERVER_URL = originWithoutPort;
PROXY_TARGET = `${originWithoutPort}:3000`;
ONLINE_TILE_LAYER = `https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`;
OFFLINE_TILE_LAYER = `${originWithoutPort}:3000/mapTiles/{z}/{x}/{y}.png`;
MAP_TILES_LAYER = ONLINE_TILE_LAYER; // Standardwert
}
// Export der dynamischen Werte
export { BASE_URL, SERVER_URL, PROXY_TARGET, ONLINE_TILE_LAYER, OFFLINE_TILE_LAYER, MAP_TILES_LAYER };
/* export const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL; //Station in Tab öffnen
export const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL; //Die Konstante ist in MapComponent.js und useLineData.js verwendet export const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL; //Die Konstante ist in MapComponent.js und useLineData.js verwendet
export const PROXY_TARGET = process.env.NEXT_PUBLIC_PROXY_TARGET; // damit nodejs auf Port 3000 auf dem Server Talas5 auf Port 80 aufgerufen kann, ansonsten gibt CORS Fehler export const PROXY_TARGET = process.env.NEXT_PUBLIC_PROXY_TARGET; // damit nodejs auf Port 3000 auf dem Server Talas5 auf Port 80 aufgerufen kann, ansonsten gibt CORS Fehler
export const ONLINE_TILE_LAYER = process.env.NEXT_PUBLIC_ONLINE_TILE_LAYER; //Map von Talas_v5 Server */ export const ONLINE_TILE_LAYER = process.env.NEXT_PUBLIC_ONLINE_TILE_LAYER; //Map von Talas_v5 Server
//----------------------------------- //-----------------------------------
//export const ONLINE_TILE_LAYER = "http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"; //Map von Talas_v5 Server //export const ONLINE_TILE_LAYER = "http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"; //Map von Talas_v5 Server
// export const PROXY_TARGET = "http://10.10.0.70"; // damit nodejs auf Port 3000 auf dem Server Talas5 auf Port 80 aufgerufen kann, ansonsten gibt CORS Fehler // export const PROXY_TARGET = "http://10.10.0.70"; // damit nodejs auf Port 3000 auf dem Server Talas5 auf Port 80 aufgerufen kann, ansonsten gibt CORS Fehler

View File

@@ -0,0 +1,79 @@
import { useEffect } from "react";
import { addContextMenuToMarker } from "../../utils/addContextMenuToMarker";
const useMarkersLayer = (map, markers, GisStationsMeasurements, GMA, oms) => {
useEffect(() => {
if (!map) return;
// Entferne alte Marker
GMA.clearLayers();
// Hinzufügen neuer Marker
markers.forEach((marker) => {
// Finde die Messungen, die zu diesem Marker gehören
const relevantMeasurements = GisStationsMeasurements.filter((m) => m.Area_Name === marker.options.areaName);
let measurements = {};
let area_name = marker.options.areaName;
relevantMeasurements.forEach((m) => {
measurements[m.Na] = m.Val;
});
// Überprüfe, ob die Messwerte vorhanden sind, und setze Standardwerte
const lt = measurements["LT"] || "---";
const fbt = measurements["FBT"] || "---";
const gt = measurements["GT"] || "---";
const rlf = measurements["RLF"] || "---";
console.log(`Station oder Bereich ${area_name} - LT: ${lt}, FBT: ${fbt}, GT: ${gt}, RLF: ${rlf}`);
// Tooltip für den Marker binden
marker.bindTooltip(
`
<div class="p-0 rounded-lg bg-white bg-opacity-90">
<div class="font-bold text-sm text-black">
<span>${area_name}</span>
</div>
<div class="font-bold text-xxs text-blue-700">
<span>LT : ${lt} °C</span>
</div>
<div class="font-bold text-xxs text-red-700">
<span>FBT : ${fbt} °C</span>
</div>
<div class="font-bold text-xxs text-yellow-500">
<span>GT : ${gt}</span>
</div>
<div class="font-bold text-xxs text-green-700">
<span>RLF : ${rlf} %</span>
</div>
</div>
`,
{
permanent: true,
direction: "auto",
offset: [60, 0],
}
);
// Ereignisse für das Öffnen und Schließen des Tooltips
marker.on("mouseover", function () {
this.openPopup();
});
marker.on("mouseout", function () {
this.closePopup();
});
// Kontextmenü hinzufügen
addContextMenuToMarker(marker);
// Füge den Marker zur Layer-Gruppe hinzu
GMA.addLayer(marker);
oms.addMarker(marker);
});
map.addLayer(GMA);
}, [map, markers, GisStationsMeasurements, GMA, oms]);
};
export default useMarkersLayer;

View File

@@ -28,7 +28,7 @@ const useMarkersLayer = (map, markers, GisStationsMeasurements, GMA, oms, isVisi
const gt = measurements["GT"] || "---"; const gt = measurements["GT"] || "---";
const rlf = measurements["RLF"] || "---"; const rlf = measurements["RLF"] || "---";
//console.log(`Station oder Bereich ${area_name} - LT: ${lt}, FBT: ${fbt}, GT: ${gt}, RLF: ${rlf}`); console.log(`Station oder Bereich ${area_name} - LT: ${lt}, FBT: ${fbt}, GT: ${gt}, RLF: ${rlf}`);
// Tooltip für den Marker binden // Tooltip für den Marker binden
marker.bindTooltip( marker.bindTooltip(

View File

@@ -11,7 +11,7 @@ const useSmsfunkmodemMarkersLayer = (map, oms, GisSystemStatic, priorityConfig,
if (!map || !GisSystemStatic) return; if (!map || !GisSystemStatic) return;
// Debugging: Logge die Sichtbarkeit und die übergebenen Daten // Debugging: Logge die Sichtbarkeit und die übergebenen Daten
//console.log("isVisible für SMS Modem:", isVisible); console.log("isVisible für SMS Modem:", isVisible);
console.log("Alle Stationen in GisSystemStatic:", GisSystemStatic); console.log("Alle Stationen in GisSystemStatic:", GisSystemStatic);
// Hilfsfunktion: Normalisiert Strings // Hilfsfunktion: Normalisiert Strings

View File

@@ -0,0 +1,20 @@
// pages/api/[...path].js
import { createProxyMiddleware } from "http-proxy-middleware";
//import { SERVER_URL } from "../config/urls.js";
//console.log("SERVER_URL:", SERVER_URL); // Debug-Ausgabe
export default createProxyMiddleware({
//target: "http://192.168.10.58:3001",
// Stationen bekommen
//target: "http://10.10.0.13", // Ziel-URL des Proxys // API Aufruf zum mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl und mapDataIconUrl
target: `${process.env.NEXT_PUBLIC_SERVER_URL}`, //
//target: urls.PROXY_TARGET,
//target: "http://localhost:3000", // Ziel-URL des Proxys
//target: "http://192.168.10.187:3000", // Ziel-URL des Proxys
//target: "http://192.168.10.14",
changeOrigin: true,
pathRewrite: {
"^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert
},
logLevel: "debug", // Setzt das Logging-Level auf "debug" für detaillierte Ausgaben
});

View File

@@ -0,0 +1,20 @@
// pages/api/get-talasIP.js
export default function handler(req, res) {
// Der x-forwarded-for Header könnte mehrere IP-Adressen enthalten, getrennt durch Kommas
let clientIp =
req.headers["x-forwarded-for"]?.split(",").map((ip) => ip.trim())[0] ||
req.socket.remoteAddress;
// Entfernen möglicher IPv6 "mapped" IPv4 Adressen
if (clientIp?.includes("::ffff:")) {
clientIp = clientIp.split("::ffff:")[1];
}
// Nur IPv4 Adressen weitergeben, IPv6 Adressen ausschließen
if (clientIp && clientIp.includes(":")) {
clientIp = ""; // Dies setzt die IP auf leer, wenn es sich um eine IPv6-Adresse handelt
}
res.status(200).json({ ip: clientIp });
}

View File

@@ -0,0 +1,34 @@
// /pages/api/gis-proxy.js
// Importieren der erforderlichen Module
import httpProxy from "http-proxy";
import Cookies from "cookies";
// Erstellen eines Proxy-Servers
const proxy = httpProxy.createProxyServer();
export default (req, res) => {
return new Promise((resolve) => {
// CORS-Headers einstellen
res.setHeader("Access-Control-Allow-Credentials", true);
res.setHeader("Access-Control-Allow-Origin", "*");
// Cookies initialisieren
const cookies = new Cookies(req, res);
const targetUrl = `${process.env.NEXT_PUBLIC_SERVER_URL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`;
// Proxy-Konfiguration und Event-Listener
req.on("data", () => {});
req.on("end", () => {
proxy.web(req, res, { target: targetUrl, changeOrigin: true, selfHandleResponse: false }, (e) => {
if (e) {
console.error(e);
res.status(500).json({ error: "Proxy-Fehler", e });
}
resolve();
});
});
// Weiterleitung der Headers
req.headers.cookie = cookies.get("cookie-name") || "";
});
};

View File

@@ -0,0 +1,64 @@
// /pages/api/linesColorApi.js
// http://10.10.0.13/talas5/ClientData/WebServiceMap.asmx/GisStationsStatusDistrict
//In DB gis_lines idLD und idModul anpassen entsprechend
// /pages/api/linesColorApi.js
import NextCors from "nextjs-cors";
export default async function handler(req, res) {
// Run the cors middleware
await NextCors(req, res, {
// Options
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
origin: "*", // Erlauben Sie alle Ursprünge, oder geben Sie spezifische Ursprünge an
optionsSuccessStatus: 200, // Legacy-Browser-Unterstützung für 204
});
const response = {
Name: "Liste aller Statis der Linien",
Zeitstempel: new Date().toISOString(), // Aktuellen Zeitstempel hinzufügen
IdMap: "10",
Statis: [
/* {
IdLD: 50922,
Modul: 1,
DpName: "KUE01_Ausfall",
ModulName: "42 Wippershain Sender",
// ModulTyp: "nicht vorhanden",
ModulTyp: "KÜ705-FO",
Message: "KUEG 01: 42 Wippershain Sender Messwerkausfall kommend",
Level: 4,
PrioColor: "#FFFF00",
PrioName: "system",
Value: "10 MOhm",
},
{
IdLD: 25440,
Modul: 3,
DpName: "KUE03_Ausfall",
ModulName: "42 Solz Sender",
//ModulTyp: "nicht vorhanden",
ModulTyp: "KÜSS V2",
Message: "KUEG 03: 42 Solz Sender Messwerkausfall kommend",
Level: 4,
PrioColor: "#FF0000",
PrioName: "system",
Value: "10 MOhm",
},
{
IdLD: 25440,
Modul: 4,
DpName: "KUE04_Ausfall",
ModulName: "42/13 Bad Hersfeld Gaswerk",
ModulTyp: "Kue705-FO",
Message: "KUEG 04: 42/13 Bad Hersfeld Gaswerk Messwerkausfall kommend",
Level: 4,
PrioColor: "#FF00FF",
PrioName: "system",
Value: "10 MOhm",
}, */
],
};
res.status(200).json(response);
}

View File

@@ -0,0 +1,29 @@
// pages/api/rights.js
export default function handler(req, res) {
const { idMap, idUser } = req.query;
// Beispielhafte Rechte, die je nach idMap und idUser variieren können
const rights = {
'10': [
{ IdRight: 1, Name: "Zugriff auf Dashboard" },
{ IdRight: 56, Name: "Erweiterte Berechtigungen" }
],
'2': [
{ IdRight: 2, Name: "Zugriff auf Einstellungen" }
],
'1': [
{ IdRight: 10, Name: "Admin-Zugriff" },
{ IdRight: 11, Name: "Zugriff auf alle Daten" }
]
};
// Prüfung, ob eine gültige idMap und idUser vorhanden sind
if (rights[idMap] && idUser === '484') {
// Rückgabe der spezifischen Rechte basierend auf der idMap und idUser
res.status(200).json({ Rights: rights[idMap] });
} else {
// Rückgabe leerer Rechte für ungültige idMap oder andere Benutzer
res.status(200).json({ Rights: [] });
}
}

View File

@@ -0,0 +1,40 @@
// pages/api/talas_v5/area.js
// Lesen von talas_v5 MySQL-Datenbank -> area Tabelle enthält DAUZ Geräte
// Wenn gebraucht wird, dann nutzen ansonsten löschen
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
//console.log("my dbconfig: ", dbConfig);
export default function handler(req, res) {
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
res.status(500).json({ error: "Verbindungsfehler zur Datenbank" });
return;
}
//console.log("Verbunden als ID", connection.threadId);
//Fehler weil, existiertdie Tabelle auf localhost:3000 nicht
connection.query("SELECT ..., ..., ..., ... FROM ... WHERE ... = ...", (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
return;
}
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results);
connection.end();
});
});
}

View File

@@ -0,0 +1,42 @@
// Importieren des mysql2 Pakets
import mysql from "mysql2";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
// Ein Hilfsfunktion, um Anfragen zu vereinfachen
function queryDatabase(query, params) {
return new Promise((resolve, reject) => {
pool.query(query, params, (error, results) => {
if (error) {
return reject(error);
}
resolve(results);
});
});
}
// API-Handler
export default async function handler(req, res) {
try {
// Dein SQL-Query und die Parameter
const sql = "SELECT idLD, iddevice, name FROM location_device WHERE iddevice = ?";
const params = [160]; // Beispielparameter
// Ausführen der Datenbankabfrage
const results = await queryDatabase(sql, params);
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
}
}

View File

@@ -0,0 +1,116 @@
// /pages/api/talas5/webserviceMap/GisStationsMeasurements.js
const GisStationsMeasurements = {
"Name": "Liste aller Messungen der Geraete",
"Zeitstempel": "2024-05-31T15:25:32.5047629+02:00",
"IdMap": "10",
"Statis": [
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 3,
"Na": "FBT",
"Val": "20.5",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 10,
"Na": "GT",
"Val": "nicht ermittelbar",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 2,
"Na": "LT",
"Val": "Datenlücke",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 6,
"Na": "RLF",
"Val": "100.0",
"Unit": "%",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 11,
"Na": "TPT",
"Val": "8.3",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 12,
"Na": "TT1",
"Val": "---",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 16,
"Na": "WFD",
"Val": "0.12",
"Unit": "mm",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 8,
"Na": "WGM",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 9,
"Na": "WGS",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10') {
// If the conditions are met, return the GisStationsMeasurements object with a 200 status code.
res.status(200).json(GisStationsMeasurements);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,281 @@
// /pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js
const GisStationsStaticDistrict = {
"Name": "Liste aller Geraete einer bestimmten Karte",
"Zeitstempel": "2024-05-31T15:26:56.9235766+02:00",
"IdMap": "10",
"Points": [
{
"LD_Name": "CPL Bentheim",
"IdLD": 50017,
"Device": "CPL V3.5 mit 16 Kü",
"Link": "cpl.aspx?ver=35&kue=16&id=50017",
"Location_Name": "Technikraum",
"Location_Short": "BEHE",
"IdLocation": 17448,
"Area_Name": "Bad-Bentheim",
"Area_Short": "BEHE--00",
"IdArea": 16418,
"X": 51.5728,
"Y": 9.00056,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Drucker",
"IdLD": 50084,
"Device": "Basisgerät",
"Link": "basis.aspx?ver=1&id=50084",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 14,
"System": 200,
"Active": 0
},
{
"LD_Name": "Türkontakt",
"IdLD": 50666,
"Device": "ECI",
"Link": "eci.aspx?ver=1&id=50666",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 17,
"System": 2,
"Active": 0
},
{
"LD_Name": "Triptis",
"IdLD": 50888,
"Device": "CPL 200",
"Link": "cpl.aspx?ver=30&kue=16&id=50888",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn I",
"IdLD": 50889,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50889",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn II",
"IdLD": 50900,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50900",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Hermsdorf",
"IdLD": 50901,
"Device": "CPL V3.5 mit 24 Kü",
"Link": "cpl.aspx?ver=35&kue=24&id=50901",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 1
},
{
"LD_Name": "GMA Littwin (TEST)",
"IdLD": 50004,
"Device": "Glättemeldeanlage",
"Link": "gma.aspx?ver=1&id=50004",
"Location_Name": "RG Relaisraum",
"Location_Short": "REZR",
"IdLocation": 18624,
"Area_Name": "Renzenhof (RG)",
"Area_Short": "REZHRG00",
"IdArea": 16570,
"X": 53.246036,
"Y": 8.163293,
"Icon": 1,
"System": 11,
"Active": 0
},
{
"LD_Name": "NRS Testserver",
"IdLD": 50005,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50005",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Gateway 2",
"IdLD": 50007,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50007",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Basisgerät mit SNMP MVP",
"IdLD": 50669,
"Device": "Basisgerät + SNMP",
"Link": "basisSNMP.aspx?&ver=1&id=50669",
"Location_Name": "Mylinghauserstraße Engelbert",
"Location_Short": "G-GEVELSBE-1",
"IdLocation": 24012,
"Area_Name": "Gevelsberg",
"Area_Short": "GMA-GEVELSBE",
"IdArea": 20919,
"X": 51.316799,
"Y": 7.33281,
"Icon": 14,
"System": 200,
"Active": 1
},
{
"LD_Name": "Server 3",
"IdLD": 50009,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50009",
"Location_Name": "Militärringstraße Militärringstraße",
"Location_Short": "G-KÃLN-1",
"IdLocation": 24015,
"Area_Name": "Köln",
"Area_Short": "GMA-KÃLN",
"IdArea": 20921,
"X": 50.898399,
"Y": 6.92278,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "ICL Test 5",
"IdLD": 50054,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50054",
"Location_Name": "Recheder Mühlenweg Dortmund-Ems-Kanal",
"Location_Short": "G-OLFEN-SE-1",
"IdLocation": 24022,
"Area_Name": "Olfen-Selm",
"Area_Short": "GMA-OLFEN-SE",
"IdArea": 20926,
"X": 51.702202,
"Y": 7.40822,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "ICL Test 3",
"IdLD": 50052,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50052",
"Location_Name": "Weidenstraße Hestenberg",
"Location_Short": "G-PLETTENB-1",
"IdLocation": 24024,
"Area_Name": "Plettenberg",
"Area_Short": "GMA-PLETTENB",
"IdArea": 20928,
"X": 51.224098,
"Y": 7.86969,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "Test Februar Kai",
"IdLD": 50912,
"Device": "Dauerzählstelle DZ",
"Link": "dauz.aspx?ver=1&id=50912",
"Location_Name": "In der Hoffnung Kiesberg - BG Ost",
"Location_Short": "G-WUPPERTA-4",
"IdLocation": 24039,
"Area_Name": "Wuppertal",
"Area_Short": "GMA-WUPPERTA",
"IdArea": 20937,
"X": 51.238899,
"Y": 7.12715,
"Icon": 14,
"System": 110,
"Active": 1
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the GisStationsStaticDistrict object with a 200 status code.
res.status(200).json(GisStationsStaticDistrict);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,84 @@
// /pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js
import mysql from "mysql2/promise";
// Erstellen eines Verbindungspools anstelle einer einzelnen Verbindung
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
const { idMap, idUser } = req.query;
if (!idMap || !idUser) {
return res.status(400).json({ error: "idMap and idUser are required" });
}
try {
let onlySystem = -1;
let districtCounter = 0;
// Get onlySystem
const [mapResult] = await pool.query("SELECT idsystem_typ FROM maps WHERE id = ?", [idMap]);
if (mapResult.length > 0) {
onlySystem = mapResult[0].idsystem_typ ?? -1;
}
// Get districtCounter
if (idUser > 0) {
const [userLayerResult] = await pool.query("SELECT count(*) as count FROM user_User_layer1 WHERE iduser = ?", [idUser]);
districtCounter = userLayerResult[0].count;
}
// Building the query
let query = `
SELECT ld.idLD, dc.message, p.level, p.name, p.color, ld.idDevice, de.isService, dc.idIcon
FROM location as l
LEFT JOIN location_coordinates AS co ON l.idLocation = co.idLocation and co.idMaps = ?
LEFT JOIN location_device AS ld ON ld.idLocation = l.idLocation
LEFT JOIN datapoint as d ON d.idLD = ld.idLD
LEFT JOIN datapoint_conditions AS dc ON dc.idcondition = d.last_message_condition
LEFT JOIN prio AS p ON p.idPrio = dc.idprio
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN area as a on a.idArea = l.idArea
WHERE p.level < 100 AND co.X > 0
`;
const queryParams = [idMap];
if (districtCounter > 0) {
query += ` AND a.iddistrict IN (SELECT iddistrict FROM user_user_layer1 WHERE iduser = ?)`;
queryParams.push(idUser);
}
if (onlySystem >= 0) {
query += ` AND de.idsystem_typ = ?`;
queryParams.push(onlySystem);
}
query += ` ORDER BY p.level desc`;
const [results] = await pool.query(query, queryParams);
const mpss = {
IdMap: idMap.toString(),
Statis: results.map((row) => ({
IdLD: row.idLD ?? -1,
Le: row.level ?? -1,
Me: row.message ?? "?",
Na: row.name ?? "?",
Co: row.color ?? "#ffffff",
Feld: row.idDevice ?? -1,
Icon: row.idIcon ?? 0,
})),
};
res.status(200).json(mpss);
} catch (error) {
console.error("Fehler beim Laden der Daten:", error);
res.status(500).json({ error: "Interner Serverfehler" });
}
}

View File

@@ -0,0 +1,273 @@
// /pages/api/webServiceMap.js
const gisSystemStatic = {
"Name": "Liste aller angezeigten Systeme",
"Zeitstempel": "2024-05-31T15:08:49.8599542+02:00",
"IdMap": "10",
"Systems": [
{
"IdSystem": 1,
"Name": "TALAS",
"Longname": "Talas Meldestationen",
"Allow": 1,
"Icon": 1
},
{
"IdSystem": 2,
"Name": "ECI",
"Longname": "ECI Geräte",
"Allow": 1,
"Icon": 2
},
{
"IdSystem": 5,
"Name": "GSM Modem",
"Longname": "LR77 GSM Modems",
"Allow": 1,
"Icon": 5
},
{
"IdSystem": 6,
"Name": "Cisco Router",
"Longname": "Cisco Router",
"Allow": 1,
"Icon": 6
},
{
"IdSystem": 7,
"Name": "WAGO",
"Longname": "WAGO I/O Systeme",
"Allow": 1,
"Icon": 7
},
{
"IdSystem": 8,
"Name": "Siemens",
"Longname": "Siemens Notrufsystem",
"Allow": 0,
"Icon": 8
},
{
"IdSystem": 9,
"Name": "OTDR",
"Longname": "Glasfaserüberwachung OTU",
"Allow": 0,
"Icon": 9
},
{
"IdSystem": 10,
"Name": "WDM",
"Longname": " Wavelength Division Multiplexing",
"Allow": 0,
"Icon": 10
},
{
"IdSystem": 11,
"Name": "GMA",
"Longname": "Glättemeldeanlagen",
"Allow": 1,
"Icon": 11
},
{
"IdSystem": 13,
"Name": "Messstellen",
"Longname": "Messstellen",
"Allow": 0,
"Icon": 13
},
{
"IdSystem": 100,
"Name": "TALAS ICL",
"Longname": "Talas ICL Unterstationen",
"Allow": 1,
"Icon": 100
},
{
"IdSystem": 110,
"Name": "DAUZ",
"Longname": "Dauerzählstellen",
"Allow": 1,
"Icon": 110
},
{
"IdSystem": 111,
"Name": "SMS-Funkmodem",
"Longname": "SMS-Funkmodem",
"Allow": 0,
"Icon": 111
},
{
"IdSystem": 200,
"Name": "Sonstige",
"Longname": "Sonstige",
"Allow": 1,
"Icon": 200
}
],
"Rights": [
{
"IdRight": 1
},
{
"IdRight": 2
},
{
"IdRight": 3
},
{
"IdRight": 5
},
{
"IdRight": 6
},
{
"IdRight": 7
},
{
"IdRight": 8
},
{
"IdRight": 10
},
{
"IdRight": 11
},
{
"IdRight": 12
},
{
"IdRight": 20
},
{
"IdRight": 22
},
{
"IdRight": 23
},
{
"IdRight": 25
},
{
"IdRight": 30
},
{
"IdRight": 40
},
{
"IdRight": 41
},
{
"IdRight": 42
},
{
"IdRight": 43
},
{
"IdRight": 44
},
{
"IdRight": 45
},
{
"IdRight": 46
},
{
"IdRight": 47
},
{
"IdRight": 48
},
{
"IdRight": 49
},
{
"IdRight": 50
},
{
"IdRight": 51
},
{
"IdRight": 52
},
{
"IdRight": 55
},
{
"IdRight": 56
},
{
"IdRight": 60
},
{
"IdRight": 61
},
{
"IdRight": 62
},
{
"IdRight": 63
},
{
"IdRight": 64
},
{
"IdRight": 65
},
{
"IdRight": 68
},
{
"IdRight": 69
},
{
"IdRight": 70
},
{
"IdRight": 71
},
{
"IdRight": 72
},
{
"IdRight": 73
},
{
"IdRight": 79
},
{
"IdRight": 80
},
{
"IdRight": 90
},
{
"IdRight": 93
},
{
"IdRight": 94
},
{
"IdRight": 95
},
{
"IdRight": 96
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the gisSystemStatic object with a 200 status code.
res.status(200).json(gisSystemStatic);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,74 @@
// /pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js
import mysql from "mysql2";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
pool.on("connection", function (connection) {
console.log("Database connected successfully.");
});
pool.on("error", function (err) {
console.error("Fehler beim Verbinden:", err);
});
export default function handler(req, res) {
const idMap = req.query.idMap;
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const sqlQuery = `
SELECT
ld.idLD,
dp.idDP,
dp.name AS Na,
dp.value AS Val,
dp.unit AS Unit,
mg.name AS Gr,
ld.idLocation,
area.Name AS Area_Name
FROM location_device as ld
LEFT JOIN location_coordinates AS co ON ld.idLocation = co.idLocation and co.idMaps = ?
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN datapoint AS dp ON ld.idLD = dp.idLD
LEFT JOIN message_group AS mg ON dp.idmessage_group = mg.idmessage_group
LEFT JOIN location AS loc ON ld.idLocation = loc.idLocation
LEFT JOIN area AS area ON loc.idArea = area.idArea
WHERE co.X > 0 AND dp.idmessage_group>0 AND length(dp.unit)> 0 AND length(dp.value)> 0
`;
pool.query(sqlQuery, [idMap], (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der gis_lines:", error);
return res.status(500).json({ error: "Fehler beim Abrufen der gis_lines" });
}
const response = {
Name: "Liste aller Messungen der Geraete",
Zeitstempel: new Date().toISOString(),
IdMap: idMap,
Statis: results.map((row) => ({
IdLD: row.idLD,
IdDP: row.idDP,
Na: row.Na,
Val: row.Val,
Unit: row.Unit,
Gr: row.Gr,
IdLocation: row.idLocation,
Area_Name: row.Area_Name,
})),
};
res.json(response);
});
}

View File

@@ -0,0 +1,34 @@
// /pages/api/talas_v5_DB/gisLines/readGisLines.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = "SELECT * FROM talas_v5.gis_lines;";
try {
const [results] = await pool.query(query);
if (results.length > 0) {
res.status(200).json(results);
} else {
res.status(404).json({ error: "Gerät nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Abrufen der gis_lines:", error);
res.status(500).json({ error: "Fehler beim Abrufen der gis_lines" });
}
}

View File

@@ -0,0 +1,58 @@
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Nur POST Methode erlaubt" });
}
const { idLD, idModul, newCoordinates } = req.body;
if (!idLD || !idModul || !newCoordinates) {
return res.status(400).json({ error: "Fehlende Daten" });
}
const newLineString = `LINESTRING(${newCoordinates.map((coord) => `${coord[0]} ${coord[1]}`).join(",")})`;
const query = "UPDATE talas_v5.gis_lines SET points = ST_GeomFromText(?) WHERE idLD = ? AND idModul = ?;";
let connection;
try {
// Hole eine Verbindung aus dem Pool
connection = await pool.getConnection();
// Beginne eine Transaktion
await connection.beginTransaction();
// Führe die Abfrage aus
const [results] = await connection.query(query, [newLineString, idLD, idModul]);
// Commit der Transaktion
await connection.commit();
console.log("Transaction Complete.");
res.status(200).json({
success: "Updated successfully.",
affectedRows: results.affectedRows,
});
} catch (error) {
// Rollback im Falle eines Fehlers
if (connection) await connection.rollback();
console.error("Fehler beim Aktualisieren der gis_lines:", error);
res.status(500).json({ error: "Fehler beim Aktualisieren der gis_lines" });
} finally {
// Stelle sicher, dass die Verbindung zurückgegeben wird
if (connection) connection.release();
}
}

View File

@@ -0,0 +1,41 @@
// API in /api/talas_v5_DB/locationDevice/getDeviceId.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const { deviceName } = req.query;
if (!deviceName) {
return res.status(400).json({ error: "deviceName ist erforderlich" });
}
const query = "SELECT idLD FROM location_device WHERE name = ?";
try {
// Ausführen der Abfrage mit dem Pool
const [results] = await pool.query(query, [deviceName]);
if (results.length > 0) {
res.status(200).json({ idLD: results[0].idLD });
} else {
res.status(404).json({ error: "Gerät nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Abrufen der Geräte-ID:", error);
res.status(500).json({ error: "Fehler beim Abrufen der Geräte-ID" });
}
}

View File

@@ -0,0 +1,40 @@
// API in /api/talas_v5_DB/locationDevice/locationDeviceNameById.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const { idLD } = req.query;
if (!idLD) {
return res.status(400).json({ error: "idLD ist erforderlich" });
}
try {
const query = "SELECT name FROM location_device WHERE idLD = ?";
const [results] = await pool.query(query, [idLD]);
if (results.length > 0) {
res.status(200).json({ name: results[0].name });
} else {
res.status(404).json({ error: "Gerät nicht gefunden", idLD });
}
} catch (error) {
console.error("Fehler beim Abrufen des Gerätenamens:", error);
res.status(500).json({ error: "Fehler beim Abrufen des Gerätenamens" });
}
}

View File

@@ -0,0 +1,32 @@
// API in /api/talas_v5_DB/locationDevice/locationDevices.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = "SELECT * FROM location_device WHERE iddevice = 160";
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query);
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abrufen der Geräteinformationen:", error);
res.status(500).json({ error: "Fehler beim Abrufen der Geräteinformationen" });
}
}

View File

@@ -0,0 +1,37 @@
// pages/api/talas_v5_DB/poiTyp/readPoiTyp.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
const query = "SELECT * FROM poityp";
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query);
if (results.length === 0) {
return res.status(404).json({ message: "Keine Einträge gefunden" });
}
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abfragen der Datenbank:", error);
res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
}
}

View File

@@ -0,0 +1,37 @@
// pages/api/addLocation.js
import mysql from "mysql";
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
connectionLimit: 10, // Maximale Anzahl gleichzeitiger Verbindungen
});
export default function handler(req, res) {
if (req.method === "POST") {
const { name, poiTypeId, latitude, longitude, idLD } = req.body;
console.log("Received data:", req.body); // Überprüfen der empfangenen Daten
const query = "INSERT INTO poi (description, idPoiTyp, position, idLD) VALUES (?, ?, ST_GeomFromText(?),?)";
const point = `POINT(${longitude} ${latitude})`;
const values = [name, poiTypeId, point, idLD];
// Verwende den Pool, um eine Verbindung zu bekommen und die Query auszuführen
pool.query(query, values, (error, results) => {
if (error) {
console.error("Fehler beim Einfügen des Standorts:", error);
return res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
}
res.status(200).json({
id: results.insertId,
message: "Standort erfolgreich hinzugefügt",
});
});
} else {
res.setHeader("Allow", ["POST"]);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}

View File

@@ -0,0 +1,42 @@
// pages/api/talas_v5_DB/pois/deletePoi.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "DELETE") {
return res.status(405).json({ error: "Nur DELETE Methode erlaubt" });
}
const { id } = req.query; // ID aus der Anfrage holen
if (!id) {
return res.status(400).json({ error: "POI ID ist erforderlich" });
}
const query = "DELETE FROM poi WHERE idPoi = ?";
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query, [id]);
if (results.affectedRows > 0) {
res.status(200).json({ message: "POI erfolgreich gelöscht" });
} else {
res.status(404).json({ error: "POI nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Löschen des POI 3:", error);
res.status(500).json({ error: "Fehler beim Löschen des POI" });
}
}

View File

@@ -0,0 +1,43 @@
// pages/api/talas_v5_DB/pois/getPoiById.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
const { idPoi } = req.query;
if (!idPoi) {
return res.status(400).json({ error: "idPoi ist erforderlich" });
}
const query = "SELECT description FROM poi WHERE idPoi = ?";
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query, [idPoi]);
if (results.length === 0) {
return res.status(404).json({ error: "POI nicht gefunden" });
}
res.status(200).json(results[0]);
} catch (error) {
console.error("Fehler bei der Abfrage:", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
}
}

View File

@@ -0,0 +1,36 @@
// pages/api/talas_v5_DB/pois/poi-icons.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = `
SELECT p.idPoi, i.path
FROM poi p
JOIN poiTyp pt ON p.idPoiTyp = pt.idPoiTyp
JOIN poiicons i ON pt.icon = i.idpoiicons;
`;
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query);
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abrufen der Icons:", error);
res.status(500).json({ error: "Fehler beim Abrufen der Icons" });
}
}

View File

@@ -0,0 +1,32 @@
// pages/api/talas_v5_DB/pois/readLocations.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
const query = `
SELECT idPoi, description, idPoiTyp, idLD, ST_AsText(position) AS position
FROM poi
`;
try {
// Ausführen der Abfrage mit dem Verbindungspool
const [results] = await pool.query(query);
// Senden der Antwort zurück
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abrufen der API:", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
}
}

View File

@@ -0,0 +1,82 @@
// pages/api/talas_v5_DB/pois/updateLocation.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
charset: "utf8mb4",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
const { id, latitude, longitude } = req.body;
if (!id || latitude === undefined || longitude === undefined) {
return res.status(400).json({ error: "id, latitude, und longitude sind erforderlich" });
}
const query = "UPDATE poi SET position = POINT(?, ?) WHERE idPoi = ?";
try {
const [result] = await pool.query(query, [longitude, latitude, id]);
if (result.affectedRows > 0) {
res.status(200).json({ success: true });
} else {
res.status(404).json({ error: "POI nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Aktualisieren der Position:", error);
res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
}
}
/* import mysql from "mysql";
import util from "util";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
charset: "utf8mb4",
};
export default async function handler(req, res) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
const { id, latitude, longitude } = req.body;
const connection = mysql.createConnection(dbConfig);
// Promisify the query method
const query = util.promisify(connection.query).bind(connection);
try {
await query("UPDATE poi SET position = POINT(?, ?) WHERE idPoi = ?", [
longitude,
latitude,
id,
]);
res.status(200).json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
} finally {
connection.end();
}
} */

View File

@@ -0,0 +1,45 @@
// pages/api/talas_v5_DB/pois/updatePoi.js
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Nur POST Methode erlaubt" });
}
const { idPoi, description, idPoiTyp, idLD } = req.body;
if (!idPoi) {
return res.status(400).json({ error: "POI ID ist erforderlich" });
}
const query = `
UPDATE talas_v5.poi
SET description = ?, idPoiTyp = ?, idLD = ?
WHERE idPoi = ?
`;
try {
const [results] = await pool.query(query, [description, idPoiTyp, idLD, idPoi]);
if (results.affectedRows > 0) {
res.status(200).json({ message: "POI erfolgreich aktualisiert" });
} else {
res.status(404).json({ error: "POI nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Aktualisieren des POI:", error);
res.status(500).json({ error: "Fehler beim Aktualisieren des POI" });
}
}

View File

@@ -0,0 +1,31 @@
// pages/api/talas_v5_DB/priorityConfig.js
// in tals5 http://10.10.0.13/talas5/Management/PriorityConfig.aspx beinhaltet die Tabelle prio die Prioritäten der Meldungen (Level 1-4) oder (0-4) je nachdem DB-Design
// das ist die API, die die Prioritäten zurückgibt
import mysql from "mysql2/promise";
// Erstellen eines Pools von Datenbankverbindungen
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
try {
// Ausführen der Datenbankabfrage
const query = "SELECT idprio, level, name, color FROM prio";
const results = await pool.query(query);
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results[0]); // Da mysql2 Tuple [rows, fields] zurückgibt, wählen wir nur rows mit [0]
} catch (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
}
}

View File

@@ -0,0 +1,43 @@
// /pages/api/talas_v5_DB/station/getAllStationsNames.js
import mysql from "mysql2/promise";
// Verbindungspool-Konfiguration
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export default async function handler(req, res) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
try {
// Abrufen aller idLD und ihrer Namen
const [results] = await pool.query("SELECT idLD, name FROM location_device");
if (results.length === 0) {
return res.status(404).json({ error: "No data found" });
}
// Struktur der Antwort anpassen
const namesMap = results.reduce((map, { idLD, name }) => {
if (!map[idLD]) {
map[idLD] = name; // Stelle sicher, dass hier keine Duplikate oder Überschreibungen entstehen
}
return map;
}, {});
res.status(200).json(namesMap);
} catch (err) {
console.error("Fehler beim Abrufen der Daten:", err);
res.status(500).json({ error: "Error retrieving data from the database" });
}
}

View File

@@ -0,0 +1,20 @@
// pages/api/[...path].js
import { createProxyMiddleware } from "http-proxy-middleware";
import { SERVER_URL } from "../config/urls.js";
console.log("SERVER_URL:", SERVER_URL); // Debug-Ausgabe
export default createProxyMiddleware({
//target: "http://192.168.10.58:3001",
// Stationen bekommen
//target: "http://10.10.0.13", // Ziel-URL des Proxys // API Aufruf zum mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl und mapDataIconUrl
target: `${SERVER_URL}`, //
//target: urls.PROXY_TARGET,
//target: "http://localhost:3000", // Ziel-URL des Proxys
//target: "http://192.168.10.187:3000", // Ziel-URL des Proxys
//target: "http://192.168.10.14",
changeOrigin: true,
pathRewrite: {
"^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert
},
logLevel: "debug", // Setzt das Logging-Level auf "debug" für detaillierte Ausgaben
});

View File

@@ -0,0 +1,20 @@
// pages/api/get-talasIP.js
export default function handler(req, res) {
// Der x-forwarded-for Header könnte mehrere IP-Adressen enthalten, getrennt durch Kommas
let clientIp =
req.headers["x-forwarded-for"]?.split(",").map((ip) => ip.trim())[0] ||
req.socket.remoteAddress;
// Entfernen möglicher IPv6 "mapped" IPv4 Adressen
if (clientIp?.includes("::ffff:")) {
clientIp = clientIp.split("::ffff:")[1];
}
// Nur IPv4 Adressen weitergeben, IPv6 Adressen ausschließen
if (clientIp && clientIp.includes(":")) {
clientIp = ""; // Dies setzt die IP auf leer, wenn es sich um eine IPv6-Adresse handelt
}
res.status(200).json({ ip: clientIp });
}

View File

@@ -0,0 +1,34 @@
// /pages/api/gis-proxy.js
// Importieren der erforderlichen Module
import httpProxy from "http-proxy";
import Cookies from "cookies";
// Erstellen eines Proxy-Servers
const proxy = httpProxy.createProxyServer();
export default (req, res) => {
return new Promise((resolve) => {
// CORS-Headers einstellen
res.setHeader("Access-Control-Allow-Credentials", true);
res.setHeader("Access-Control-Allow-Origin", "*");
// Cookies initialisieren
const cookies = new Cookies(req, res);
const targetUrl = `${process.env.NEXT_PUBLIC_SERVER_URL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`;
// Proxy-Konfiguration und Event-Listener
req.on("data", () => {});
req.on("end", () => {
proxy.web(req, res, { target: targetUrl, changeOrigin: true, selfHandleResponse: false }, (e) => {
if (e) {
console.error(e);
res.status(500).json({ error: "Proxy-Fehler", e });
}
resolve();
});
});
// Weiterleitung der Headers
req.headers.cookie = cookies.get("cookie-name") || "";
});
};

View File

@@ -0,0 +1,64 @@
// /pages/api/linesColorApi.js
// http://10.10.0.13/talas5/ClientData/WebServiceMap.asmx/GisStationsStatusDistrict
//In DB gis_lines idLD und idModul anpassen entsprechend
// /pages/api/linesColorApi.js
import NextCors from "nextjs-cors";
export default async function handler(req, res) {
// Run the cors middleware
await NextCors(req, res, {
// Options
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
origin: "*", // Erlauben Sie alle Ursprünge, oder geben Sie spezifische Ursprünge an
optionsSuccessStatus: 200, // Legacy-Browser-Unterstützung für 204
});
const response = {
Name: "Liste aller Statis der Linien",
Zeitstempel: new Date().toISOString(), // Aktuellen Zeitstempel hinzufügen
IdMap: "10",
Statis: [
/* {
IdLD: 50922,
Modul: 1,
DpName: "KUE01_Ausfall",
ModulName: "42 Wippershain Sender",
// ModulTyp: "nicht vorhanden",
ModulTyp: "KÜ705-FO",
Message: "KUEG 01: 42 Wippershain Sender Messwerkausfall kommend",
Level: 4,
PrioColor: "#FFFF00",
PrioName: "system",
Value: "10 MOhm",
},
{
IdLD: 25440,
Modul: 3,
DpName: "KUE03_Ausfall",
ModulName: "42 Solz Sender",
//ModulTyp: "nicht vorhanden",
ModulTyp: "KÜSS V2",
Message: "KUEG 03: 42 Solz Sender Messwerkausfall kommend",
Level: 4,
PrioColor: "#FF0000",
PrioName: "system",
Value: "10 MOhm",
},
{
IdLD: 25440,
Modul: 4,
DpName: "KUE04_Ausfall",
ModulName: "42/13 Bad Hersfeld Gaswerk",
ModulTyp: "Kue705-FO",
Message: "KUEG 04: 42/13 Bad Hersfeld Gaswerk Messwerkausfall kommend",
Level: 4,
PrioColor: "#FF00FF",
PrioName: "system",
Value: "10 MOhm",
}, */
],
};
res.status(200).json(response);
}

View File

@@ -0,0 +1,29 @@
// pages/api/rights.js
export default function handler(req, res) {
const { idMap, idUser } = req.query;
// Beispielhafte Rechte, die je nach idMap und idUser variieren können
const rights = {
'10': [
{ IdRight: 1, Name: "Zugriff auf Dashboard" },
{ IdRight: 56, Name: "Erweiterte Berechtigungen" }
],
'2': [
{ IdRight: 2, Name: "Zugriff auf Einstellungen" }
],
'1': [
{ IdRight: 10, Name: "Admin-Zugriff" },
{ IdRight: 11, Name: "Zugriff auf alle Daten" }
]
};
// Prüfung, ob eine gültige idMap und idUser vorhanden sind
if (rights[idMap] && idUser === '484') {
// Rückgabe der spezifischen Rechte basierend auf der idMap und idUser
res.status(200).json({ Rights: rights[idMap] });
} else {
// Rückgabe leerer Rechte für ungültige idMap oder andere Benutzer
res.status(200).json({ Rights: [] });
}
}

View File

@@ -0,0 +1,40 @@
// pages/api/talas_v5/area.js
// Lesen von talas_v5 MySQL-Datenbank -> area Tabelle enthält DAUZ Geräte
// Wenn gebraucht wird, dann nutzen ansonsten löschen
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
//console.log("my dbconfig: ", dbConfig);
export default function handler(req, res) {
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
res.status(500).json({ error: "Verbindungsfehler zur Datenbank" });
return;
}
//console.log("Verbunden als ID", connection.threadId);
//Fehler weil, existiertdie Tabelle auf localhost:3000 nicht
connection.query("SELECT ..., ..., ..., ... FROM ... WHERE ... = ...", (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
return;
}
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results);
connection.end();
});
});
}

View File

@@ -0,0 +1,39 @@
// pages/api/talas_v5/location_device.js
// talas_v5 Datenbank -> location_device Tabelle enthält DAUZ Geräte
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
//console.log("my dbconfig: ", dbConfig);
export default function handler(req, res) {
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
res.status(500).json({ error: "Verbindungsfehler zur Datenbank" });
return;
}
//console.log("Verbunden als ID", connection.threadId);
//Fehler weil, existiertdie Tabelle auf localhost:3000 nicht
connection.query("SELECT idLD, iddevice, iddevice, name FROM location_device WHERE iddevice = 160", (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
return;
}
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results);
connection.end();
});
});
}

View File

@@ -0,0 +1,116 @@
// /pages/api/talas5/webserviceMap/GisStationsMeasurements.js
const GisStationsMeasurements = {
"Name": "Liste aller Messungen der Geraete",
"Zeitstempel": "2024-05-31T15:25:32.5047629+02:00",
"IdMap": "10",
"Statis": [
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 3,
"Na": "FBT",
"Val": "20.5",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 10,
"Na": "GT",
"Val": "nicht ermittelbar",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 2,
"Na": "LT",
"Val": "Datenlücke",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 6,
"Na": "RLF",
"Val": "100.0",
"Unit": "%",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 11,
"Na": "TPT",
"Val": "8.3",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 12,
"Na": "TT1",
"Val": "---",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 16,
"Na": "WFD",
"Val": "0.12",
"Unit": "mm",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 8,
"Na": "WGM",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 9,
"Na": "WGS",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10') {
// If the conditions are met, return the GisStationsMeasurements object with a 200 status code.
res.status(200).json(GisStationsMeasurements);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,281 @@
// /pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js
const GisStationsStaticDistrict = {
"Name": "Liste aller Geraete einer bestimmten Karte",
"Zeitstempel": "2024-05-31T15:26:56.9235766+02:00",
"IdMap": "10",
"Points": [
{
"LD_Name": "CPL Bentheim",
"IdLD": 50017,
"Device": "CPL V3.5 mit 16 Kü",
"Link": "cpl.aspx?ver=35&kue=16&id=50017",
"Location_Name": "Technikraum",
"Location_Short": "BEHE",
"IdLocation": 17448,
"Area_Name": "Bad-Bentheim",
"Area_Short": "BEHE--00",
"IdArea": 16418,
"X": 51.5728,
"Y": 9.00056,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Drucker",
"IdLD": 50084,
"Device": "Basisgerät",
"Link": "basis.aspx?ver=1&id=50084",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 14,
"System": 200,
"Active": 0
},
{
"LD_Name": "Türkontakt",
"IdLD": 50666,
"Device": "ECI",
"Link": "eci.aspx?ver=1&id=50666",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 17,
"System": 2,
"Active": 0
},
{
"LD_Name": "Triptis",
"IdLD": 50888,
"Device": "CPL 200",
"Link": "cpl.aspx?ver=30&kue=16&id=50888",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn I",
"IdLD": 50889,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50889",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn II",
"IdLD": 50900,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50900",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Hermsdorf",
"IdLD": 50901,
"Device": "CPL V3.5 mit 24 Kü",
"Link": "cpl.aspx?ver=35&kue=24&id=50901",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 1
},
{
"LD_Name": "GMA Littwin (TEST)",
"IdLD": 50004,
"Device": "Glättemeldeanlage",
"Link": "gma.aspx?ver=1&id=50004",
"Location_Name": "RG Relaisraum",
"Location_Short": "REZR",
"IdLocation": 18624,
"Area_Name": "Renzenhof (RG)",
"Area_Short": "REZHRG00",
"IdArea": 16570,
"X": 53.246036,
"Y": 8.163293,
"Icon": 1,
"System": 11,
"Active": 0
},
{
"LD_Name": "NRS Testserver",
"IdLD": 50005,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50005",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Gateway 2",
"IdLD": 50007,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50007",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Basisgerät mit SNMP MVP",
"IdLD": 50669,
"Device": "Basisgerät + SNMP",
"Link": "basisSNMP.aspx?&ver=1&id=50669",
"Location_Name": "Mylinghauserstraße Engelbert",
"Location_Short": "G-GEVELSBE-1",
"IdLocation": 24012,
"Area_Name": "Gevelsberg",
"Area_Short": "GMA-GEVELSBE",
"IdArea": 20919,
"X": 51.316799,
"Y": 7.33281,
"Icon": 14,
"System": 200,
"Active": 1
},
{
"LD_Name": "Server 3",
"IdLD": 50009,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50009",
"Location_Name": "Militärringstraße Militärringstraße",
"Location_Short": "G-KÃLN-1",
"IdLocation": 24015,
"Area_Name": "Köln",
"Area_Short": "GMA-KÃLN",
"IdArea": 20921,
"X": 50.898399,
"Y": 6.92278,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "ICL Test 5",
"IdLD": 50054,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50054",
"Location_Name": "Recheder Mühlenweg Dortmund-Ems-Kanal",
"Location_Short": "G-OLFEN-SE-1",
"IdLocation": 24022,
"Area_Name": "Olfen-Selm",
"Area_Short": "GMA-OLFEN-SE",
"IdArea": 20926,
"X": 51.702202,
"Y": 7.40822,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "ICL Test 3",
"IdLD": 50052,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50052",
"Location_Name": "Weidenstraße Hestenberg",
"Location_Short": "G-PLETTENB-1",
"IdLocation": 24024,
"Area_Name": "Plettenberg",
"Area_Short": "GMA-PLETTENB",
"IdArea": 20928,
"X": 51.224098,
"Y": 7.86969,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "Test Februar Kai",
"IdLD": 50912,
"Device": "Dauerzählstelle DZ",
"Link": "dauz.aspx?ver=1&id=50912",
"Location_Name": "In der Hoffnung Kiesberg - BG Ost",
"Location_Short": "G-WUPPERTA-4",
"IdLocation": 24039,
"Area_Name": "Wuppertal",
"Area_Short": "GMA-WUPPERTA",
"IdArea": 20937,
"X": 51.238899,
"Y": 7.12715,
"Icon": 14,
"System": 110,
"Active": 1
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the GisStationsStaticDistrict object with a 200 status code.
res.status(200).json(GisStationsStaticDistrict);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,100 @@
import mysql from "mysql2/promise";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
export default async function handler(req, res) {
const { idMap, idUser } = req.query;
if (!idMap || !idUser) {
res.status(400).json({ error: "idMap and idUser are required" });
return;
}
let connection;
try {
connection = await mysql.createConnection(dbConfig);
let onlySystem = -1;
let districtCounter = 0;
// Get onlySystem
const [mapResult] = await connection.execute(
"SELECT idsystem_typ FROM maps WHERE id = ?",
[idMap]
);
if (mapResult.length > 0) {
onlySystem = mapResult[0].idsystem_typ ?? -1;
}
// Get districtCounter
if (idUser > 0) {
const [userLayerResult] = await connection.execute(
"SELECT count(*) as count FROM user_User_layer1 WHERE iduser = ?",
[idUser]
);
districtCounter = userLayerResult[0].count;
}
// Get GisStatusStations
let query = `
SELECT ld.idLD, dc.message, p.level, p.name, p.color, ld.idDevice, de.isService, dc.idIcon
FROM location as l
LEFT JOIN location_coordinates AS co ON l.idLocation = co.idLocation and co.idMaps = ?
LEFT JOIN location_device AS ld ON ld.idLocation = l.idLocation
LEFT JOIN datapoint as d ON d.idLD = ld.idLD
LEFT JOIN datapoint_conditions AS dc ON dc.idcondition = d.last_message_condition
LEFT JOIN prio AS p ON p.idPrio = dc.idprio
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN area as a on a.idArea = l.idArea
WHERE p.level < 100 AND co.X > 0
`;
if (districtCounter > 0) {
query += ` AND a.iddistrict IN (SELECT iddistrict FROM user_user_layer1 WHERE iduser = ?)`;
}
if (onlySystem >= 0) {
query += ` AND de.idsystem_typ = ?`;
}
query += ` ORDER BY p.level desc`;
const queryParams = [idMap];
if (districtCounter > 0) {
queryParams.push(idUser);
}
if (onlySystem >= 0) {
queryParams.push(onlySystem);
}
const [results] = await connection.execute(query, queryParams);
const mpss = {
IdMap: idMap.toString(),
Statis: results.map((row) => ({
IdLD: row.idLD ?? -1,
Le: row.level ?? -1,
Me: row.message ?? "?",
Na: row.name ?? "?",
Co: row.color ?? "#ffffff",
Feld: row.idDevice ?? -1,
Icon: row.idIcon ?? 0,
})),
};
res.status(200).json(mpss);
} catch (error) {
console.error("Fehler beim Laden der Daten:", error);
res.status(500).json({ error: "Interner Serverfehler" });
} finally {
if (connection) {
await connection.end();
}
}
}

View File

@@ -0,0 +1,273 @@
// /pages/api/webServiceMap.js
const gisSystemStatic = {
"Name": "Liste aller angezeigten Systeme",
"Zeitstempel": "2024-05-31T15:08:49.8599542+02:00",
"IdMap": "10",
"Systems": [
{
"IdSystem": 1,
"Name": "TALAS",
"Longname": "Talas Meldestationen",
"Allow": 1,
"Icon": 1
},
{
"IdSystem": 2,
"Name": "ECI",
"Longname": "ECI Geräte",
"Allow": 1,
"Icon": 2
},
{
"IdSystem": 5,
"Name": "GSM Modem",
"Longname": "LR77 GSM Modems",
"Allow": 1,
"Icon": 5
},
{
"IdSystem": 6,
"Name": "Cisco Router",
"Longname": "Cisco Router",
"Allow": 1,
"Icon": 6
},
{
"IdSystem": 7,
"Name": "WAGO",
"Longname": "WAGO I/O Systeme",
"Allow": 1,
"Icon": 7
},
{
"IdSystem": 8,
"Name": "Siemens",
"Longname": "Siemens Notrufsystem",
"Allow": 0,
"Icon": 8
},
{
"IdSystem": 9,
"Name": "OTDR",
"Longname": "Glasfaserüberwachung OTU",
"Allow": 0,
"Icon": 9
},
{
"IdSystem": 10,
"Name": "WDM",
"Longname": " Wavelength Division Multiplexing",
"Allow": 0,
"Icon": 10
},
{
"IdSystem": 11,
"Name": "GMA",
"Longname": "Glättemeldeanlagen",
"Allow": 1,
"Icon": 11
},
{
"IdSystem": 13,
"Name": "Messstellen",
"Longname": "Messstellen",
"Allow": 0,
"Icon": 13
},
{
"IdSystem": 100,
"Name": "TALAS ICL",
"Longname": "Talas ICL Unterstationen",
"Allow": 1,
"Icon": 100
},
{
"IdSystem": 110,
"Name": "DAUZ",
"Longname": "Dauerzählstellen",
"Allow": 1,
"Icon": 110
},
{
"IdSystem": 111,
"Name": "SMS-Funkmodem",
"Longname": "SMS-Funkmodem",
"Allow": 0,
"Icon": 111
},
{
"IdSystem": 200,
"Name": "Sonstige",
"Longname": "Sonstige",
"Allow": 1,
"Icon": 200
}
],
"Rights": [
{
"IdRight": 1
},
{
"IdRight": 2
},
{
"IdRight": 3
},
{
"IdRight": 5
},
{
"IdRight": 6
},
{
"IdRight": 7
},
{
"IdRight": 8
},
{
"IdRight": 10
},
{
"IdRight": 11
},
{
"IdRight": 12
},
{
"IdRight": 20
},
{
"IdRight": 22
},
{
"IdRight": 23
},
{
"IdRight": 25
},
{
"IdRight": 30
},
{
"IdRight": 40
},
{
"IdRight": 41
},
{
"IdRight": 42
},
{
"IdRight": 43
},
{
"IdRight": 44
},
{
"IdRight": 45
},
{
"IdRight": 46
},
{
"IdRight": 47
},
{
"IdRight": 48
},
{
"IdRight": 49
},
{
"IdRight": 50
},
{
"IdRight": 51
},
{
"IdRight": 52
},
{
"IdRight": 55
},
{
"IdRight": 56
},
{
"IdRight": 60
},
{
"IdRight": 61
},
{
"IdRight": 62
},
{
"IdRight": 63
},
{
"IdRight": 64
},
{
"IdRight": 65
},
{
"IdRight": 68
},
{
"IdRight": 69
},
{
"IdRight": 70
},
{
"IdRight": 71
},
{
"IdRight": 72
},
{
"IdRight": 73
},
{
"IdRight": 79
},
{
"IdRight": 80
},
{
"IdRight": 90
},
{
"IdRight": 93
},
{
"IdRight": 94
},
{
"IdRight": 95
},
{
"IdRight": 96
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the gisSystemStatic object with a 200 status code.
res.status(200).json(gisSystemStatic);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,70 @@
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
console.log("Database connected successfully.");
});
export default function handler(req, res) {
const idMap = req.query.idMap;
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
connection.query(`
SELECT
ld.idLD,
dp.idDP,
dp.name AS Na,
dp.value AS Val,
dp.unit AS Unit,
mg.name AS Gr,
ld.idLocation,
area.Name AS Area_Name
FROM location_device as ld
LEFT JOIN location_coordinates AS co ON ld.idLocation = co.idLocation and co.idMaps = ${idMap}
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN datapoint AS dp ON ld.idLD = dp.idLD
LEFT JOIN message_group AS mg ON dp.idmessage_group = mg.idmessage_group
LEFT JOIN location AS loc ON ld.idLocation = loc.idLocation
LEFT JOIN area AS area ON loc.idArea = area.idArea
WHERE co.X > 0 AND dp.idmessage_group>0 AND length(dp.unit)> 0 AND length(dp.value)> 0
`, (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der gis_lines:", error);
return res
.status(500)
.json({ error: "Fehler beim Abrufen der gis_lines" });
}
const response = {
"Name": "Liste aller Messungen der Geraete",
"Zeitstempel": new Date().toISOString(),
"IdMap":idMap,
"Statis": results.map((row) => ({
IdLD: row.idLD,
IdDP: row.idDP,
Na: row.Na,
Val: row.Val,
Unit: row.Unit,
Gr: row.Gr,
IdLocation: row.IdLocation,
Area_Name: row.Area_Name,
})),
};
res.json(response);
});
}

View File

@@ -0,0 +1,37 @@
// /pages/api/talas_v5_DB/gisLines/readGisLines.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
//console.log("Database connected successfully.");
});
export default function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = "SELECT * FROM talas_v5.gis_lines;";
connection.query(query, (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der gis_lines:", error);
return res.status(500).json({ error: "Fehler beim Abrufen der gis_lines" });
}
if (results.length > 0) {
res.json(results);
} else {
res.status(404).json({ error: "Gerät nicht gefunden" });
}
});
}

View File

@@ -0,0 +1,61 @@
// /pages/api/talas_v5_DB/gisLines/updateLineCoordinates.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
//console.log("Database connected successfully.");
});
export default function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Nur POST Methode erlaubt" });
}
const { idLD, idModul, newCoordinates } = req.body;
if (!idLD || !idModul || !newCoordinates) {
return res.status(400).json({ error: "Fehlende Daten" });
}
const newLineString = `LINESTRING(${newCoordinates.map((coord) => `${coord[0]} ${coord[1]}`).join(",")})`;
const query = "UPDATE talas_v5.gis_lines SET points = ST_GeomFromText(?) WHERE idLD = ? AND idModul = ?;";
connection.beginTransaction((err) => {
if (err) {
throw err;
}
connection.query(query, [newLineString, idLD, idModul], (error, results, fields) => {
if (error) {
return connection.rollback(() => {
console.error("Fehler beim Aktualisieren der gis_lines:", error);
res.status(500).json({ error: "Fehler beim Aktualisieren der gis_lines" });
});
}
connection.commit((err) => {
if (err) {
return connection.rollback(() => {
throw err;
});
}
console.log("Transaction Complete.");
res.status(200).json({
success: "Updated successfully.",
affectedRows: results.affectedRows,
});
});
});
});
}

View File

@@ -0,0 +1,40 @@
// API in /api/talas_v5_DB/locationDevice/getDeviceId.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
});
export default function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const { deviceName } = req.query;
const query = "SELECT idLD FROM location_device WHERE name = ?";
connection.query(query, [deviceName], (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der Geräte-ID:", error);
return res
.status(500)
.json({ error: "Fehler beim Abrufen der Geräte-ID" });
}
if (results.length > 0) {
res.json({ idLD: results[0].idLD });
} else {
res.status(404).json({ error: "Gerät nicht gefunden" });
}
});
}

View File

@@ -0,0 +1,46 @@
// API in /api/talas_v5_DB/locationDevice/locationDeviceNameById.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
});
export default async function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const { idLD } = req.query;
try {
const query = "SELECT name FROM location_device WHERE idLD = ?";
const [results] = await new Promise((resolve, reject) => {
connection.query(query, [idLD], (error, results) => {
if (error) {
return reject(error);
}
resolve(results);
});
});
if (results.length > 0) {
res.json({ name: results[0].name });
} else {
res.status(404).json({ error: "Gerät nicht gefunden", idLD, results });
}
} catch (error) {
console.error("Fehler beim Abrufen des Gerätenamens in locationDeviceNameById.js :", error);
res.status(500).json({ error: "Fehler beim Abrufen des Gerätenamens" });
}
}

View File

@@ -0,0 +1,35 @@
// API in /api/talas_v5_DB/locationDevice/locationDevices.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
});
export default function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = "SELECT * FROM location_device WHERE iddevice = 160";
connection.query(query, (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der Geräteinformationen:", error);
return res
.status(500)
.json({ error: "Fehler beim Abrufen der Geräteinformationen" });
}
res.json(results);
});
}

View File

@@ -0,0 +1,33 @@
// pages/api/talas_v5_DB/poiTyp/readPoiTyp.js
import mysql from "mysql";
const pool = mysql.createPool({
//connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
});
export default function handler(req, res) {
if (req.method === "GET") {
const query = "SELECT * FROM poityp";
pool.query(query, (error, results) => {
if (error) {
console.error("Fehler beim Abfragen der Datenbank:", error);
return res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
}
if (results.length === 0) {
return res.status(404).json({ message: "Keine Einträge gefunden" });
}
res.status(200).json(results);
});
} else {
res.setHeader("Allow", ["GET"]);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}

View File

@@ -0,0 +1,38 @@
// pages/api/talas_v5_DB/pois/addLocation.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
export default function handler(req, res) {
if (req.method === "POST") {
const { name, poiTypeId, latitude, longitude, idLD } = req.body;
console.log("Received data:", req.body); // Überprüfen der empfangenen Daten
const connection = mysql.createConnection(dbConfig);
const query =
"INSERT INTO poi (description, idPoiTyp, position, idLD) VALUES (?, ?, ST_GeomFromText(?),?)";
const point = `POINT(${longitude} ${latitude})`;
const values = [name, poiTypeId, point, idLD]; // Stellen Sie sicher, dass poiTypeId korrekt ist
connection.query(query, values, (error, results) => {
connection.end();
if (error) {
console.error("Fehler beim Einfügen des Standorts:", error);
return res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
}
res.status(200).json({
id: results.insertId,
message: "Standort erfolgreich hinzugefügt",
});
});
} else {
res.setHeader("Allow", ["POST"]);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}

View File

@@ -0,0 +1,45 @@
// pages/api/talas_v5_DB/pois/deletePoi.js
import mysql from "mysql";
// Datenbankkonfiguration
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
console.log("Verbunden als ID", connection.threadId);
});
export default function handler(req, res) {
if (req.method !== "DELETE") {
return res.status(405).json({ error: "Nur DELETE Methode erlaubt" });
}
const { id } = req.query; // ID aus der Anfrage holen
if (!id) {
return res.status(400).json({ error: "POI ID ist erforderlich" });
}
const query = "DELETE FROM poi WHERE idPoi = ?";
connection.query(query, [id], (error, results) => {
if (error) {
console.error("Fehler beim Löschen des POI 4:", error);
return res.status(500).json({ error: "Fehler beim Löschen des POI" });
}
if (results.affectedRows > 0) {
res.json({ message: "POI erfolgreich gelöscht" });
} else {
res.status(404).json({ error: "POI nicht gefunden" });
}
});
}

View File

@@ -0,0 +1,42 @@
// pages/api/talas_v5_DB/pois/getPoiById.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
export default function handler(req, res) {
if (req.method === "GET") {
const { idPoi } = req.query;
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return res
.status(500)
.json({ error: "Verbindungsfehler zur Datenbank" });
}
const query = "SELECT description FROM poi WHERE idPoi = ?";
connection.query(query, [idPoi], (error, results) => {
connection.end();
if (error) {
console.error("Fehler bei der Abfrage:", error);
return res.status(500).json({ error: "Fehler bei der Abfrage" });
}
if (results.length === 0) {
return res.status(404).json({ error: "POI nicht gefunden" });
}
res.status(200).json(results[0]);
});
});
} else {
res.setHeader("Allow", ["GET"]);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}

View File

@@ -0,0 +1,42 @@
// pages/api/talas_v5_DB/pois/poi-icons.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
});
export default function handler(req, res) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const query = `SELECT p.idPoi, i.path
FROM poi p
JOIN poiTyp pt ON p.idPoiTyp = pt.idPoiTyp
JOIN poiicons i ON pt.icon = i.idpoiicons;`;
connection.query(query, (error, results) => {
try {
if (error) {
throw error;
}
res.json(results);
} catch (err) {
console.error("Fehler beim Abrufen der icons:", err);
res.status(500).json({ error: "Fehler beim Abrufen der icons" });
}
});
}

View File

@@ -0,0 +1,42 @@
// pages/api/talas_v5_DB/pois/readLocations.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
//console.log("my dbconfig: ", dbConfig);
export default function handler(req, res) {
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
res.status(500).json({ error: "Verbindungsfehler zur Datenbank" });
return;
}
//console.log("Verbunden als ID", connection.threadId);
connection.query("SELECT idPoi, description, idPoiTyp, idLD, ST_AsText(position) AS position FROM poi", (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
return;
}
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results);
/* console.log(
"--------------- location.js ---------------",
"results in location.js : ",
results,
"---------------------- location.js end ---------------------------"
); */
connection.end();
});
});
}

View File

@@ -0,0 +1,39 @@
// pages/api/talas_v5_DB/pois/updateLocation.js
import mysql from "mysql";
import util from "util";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
charset: "utf8mb4",
};
export default async function handler(req, res) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
const { id, latitude, longitude } = req.body;
const connection = mysql.createConnection(dbConfig);
// Promisify the query method
const query = util.promisify(connection.query).bind(connection);
try {
await query("UPDATE poi SET position = POINT(?, ?) WHERE idPoi = ?", [
longitude,
latitude,
id,
]);
res.status(200).json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
} finally {
connection.end();
}
}

View File

@@ -0,0 +1,46 @@
// pages/api/talas_v5_DB/pois/updatePoi.js
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
return;
}
//console.log("Verbunden als ID", connection.threadId);
});
export default function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Nur POST Methode erlaubt" });
}
const { idPoi, description, idPoiTyp, idLD } = req.body; // Stellen Sie sicher, dass die Felder korrekt benannt sind
//console.log("Empfangene Daten:", req.body); // Loggen der empfangenen Daten zur Überprüfung
if (!idPoi) {
return res.status(400).json({ error: "POI ID ist erforderlich" });
}
const query = "UPDATE talas_v5.poi SET description = ?, idPoiTyp = ?, idLD = ? WHERE idPoi = ?";
connection.query(query, [description, idPoiTyp, idLD, idPoi], (error, results) => {
if (error) {
console.error("Fehler beim Aktualisieren des POI:", error);
return res.status(500).json({ error: "Fehler beim Aktualisieren des POI" });
}
if (results.affectedRows > 0) {
res.json({ message: "POI erfolgreich aktualisiert" });
} else {
res.status(404).json({ error: "POI nicht gefunden" });
}
});
}

View File

@@ -0,0 +1,40 @@
// pages/api/talas_v5_DB/priorityConfig.js
// in tals5 http://10.10.0.13/talas5/Management/PriorityConfig.aspx beinhaltet die Tabelle prio die Prioritäten der Meldungen (Level 1-4) oder (0-4) je nachdem DB-Design
// das ist die API, die die Prioritäten zurückgibt
import mysql from "mysql";
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
};
//console.log("my dbconfig: ", dbConfig);
export default function handler(req, res) {
const connection = mysql.createConnection(dbConfig);
connection.connect((err) => {
if (err) {
console.error("Fehler beim Verbinden:", err.stack);
res.status(500).json({ error: "Verbindungsfehler zur Datenbank" });
return;
}
//console.log("Verbunden als ID", connection.threadId);
//Fehler weil, existiertdie Tabelle auf localhost:3000 nicht
connection.query("SELECT idprio, level, name, color FROM prio ", (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
return;
}
// Wichtig: Senden Sie die Antwort zurück
res.status(200).json(results);
connection.end();
});
});
}

View File

@@ -1,13 +1,13 @@
// pages/api/[...path].js // pages/api/[...path].js
import { createProxyMiddleware } from "http-proxy-middleware"; import { createProxyMiddleware } from "http-proxy-middleware";
import { SERVER_URL } from "../../config/urls.js"; //import { SERVER_URL } from "../config/urls.js";
//console.log("SERVER_URL:", SERVER_URL); // Debug-Ausgabe //console.log("SERVER_URL:", SERVER_URL); // Debug-Ausgabe
export default createProxyMiddleware({ export default createProxyMiddleware({
//target: "http://192.168.10.58:3001", //target: "http://192.168.10.58:3001",
// Stationen bekommen // Stationen bekommen
//target: "http://10.10.0.13", // Ziel-URL des Proxys // API Aufruf zum mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl und mapDataIconUrl //target: "http://10.10.0.13", // Ziel-URL des Proxys // API Aufruf zum mapGisStationsStaticDistrictUrl, mapGisStationsStatusDistrictUrl, mapGisStationsMeasurementsUrl, mapGisSystemStaticUrl und mapDataIconUrl
target: `${SERVER_URL}`, // target: `${process.env.NEXT_PUBLIC_SERVER_URL}`, //
//target: urls.PROXY_TARGET, //target: urls.PROXY_TARGET,
//target: "http://localhost:3000", // Ziel-URL des Proxys //target: "http://localhost:3000", // Ziel-URL des Proxys
//target: "http://192.168.10.187:3000", // Ziel-URL des Proxys //target: "http://192.168.10.187:3000", // Ziel-URL des Proxys

24
pages/api/talas5/area.js Normal file
View File

@@ -0,0 +1,24 @@
// pages/api/talas_v5/area.js
// Lesen von talas_v5 MySQL-Datenbank -> area Tabelle enthält DAUZ Geräte
import getPool from "../../utils/mysqlPool"; // Verwende den Singleton-Pool
export default async function handler(req, res) {
let connection;
try {
const pool = getPool(); // Hole den Pool
connection = await pool.getConnection(); // Hole die Verbindung
// Führe die Abfrage aus
const [results] = await connection.query("SELECT id, name FROM area WHERE id = ?", [req.query.id]);
// Sende die Antwort zurück
res.status(200).json(results);
} catch (error) {
console.error("Fehler beim Abrufen der API", error);
res.status(500).json({ error: "Fehler bei der Abfrage" });
} finally {
if (connection) connection.release(); // Gib die Verbindung zurück in den Pool
}
}

View File

@@ -0,0 +1,116 @@
// /pages/api/talas5/webserviceMap/GisStationsMeasurements.js
const GisStationsMeasurements = {
"Name": "Liste aller Messungen der Geraete",
"Zeitstempel": "2024-05-31T15:25:32.5047629+02:00",
"IdMap": "10",
"Statis": [
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 3,
"Na": "FBT",
"Val": "20.5",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 10,
"Na": "GT",
"Val": "nicht ermittelbar",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 2,
"Na": "LT",
"Val": "Datenlücke",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 6,
"Na": "RLF",
"Val": "100.0",
"Unit": "%",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 11,
"Na": "TPT",
"Val": "8.3",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 12,
"Na": "TT1",
"Val": "---",
"Unit": "°C",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 16,
"Na": "WFD",
"Val": "0.12",
"Unit": "mm",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 8,
"Na": "WGM",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
},
{
"IdLD": 50004,
"IdL": 18624,
"IdDP": 9,
"Na": "WGS",
"Val": "---",
"Unit": "m/s",
"Gr": "GMA",
"Area_Name": "Renzenhof (RG)"
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10') {
// If the conditions are met, return the GisStationsMeasurements object with a 200 status code.
res.status(200).json(GisStationsMeasurements);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,281 @@
// /pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js
const GisStationsStaticDistrict = {
"Name": "Liste aller Geraete einer bestimmten Karte",
"Zeitstempel": "2024-05-31T15:26:56.9235766+02:00",
"IdMap": "10",
"Points": [
{
"LD_Name": "CPL Bentheim",
"IdLD": 50017,
"Device": "CPL V3.5 mit 16 Kü",
"Link": "cpl.aspx?ver=35&kue=16&id=50017",
"Location_Name": "Technikraum",
"Location_Short": "BEHE",
"IdLocation": 17448,
"Area_Name": "Bad-Bentheim",
"Area_Short": "BEHE--00",
"IdArea": 16418,
"X": 51.5728,
"Y": 9.00056,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Drucker",
"IdLD": 50084,
"Device": "Basisgerät",
"Link": "basis.aspx?ver=1&id=50084",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 14,
"System": 200,
"Active": 0
},
{
"LD_Name": "Türkontakt",
"IdLD": 50666,
"Device": "ECI",
"Link": "eci.aspx?ver=1&id=50666",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 17,
"System": 2,
"Active": 0
},
{
"LD_Name": "Triptis",
"IdLD": 50888,
"Device": "CPL 200",
"Link": "cpl.aspx?ver=30&kue=16&id=50888",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn I",
"IdLD": 50889,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50889",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Rodaborn II",
"IdLD": 50900,
"Device": "cpl.mio V>6",
"Link": "cplmio.aspx?ver=1&id=50900",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 0
},
{
"LD_Name": "Hermsdorf",
"IdLD": 50901,
"Device": "CPL V3.5 mit 24 Kü",
"Link": "cpl.aspx?ver=35&kue=24&id=50901",
"Location_Name": "Technikraum",
"Location_Short": "SLUE",
"IdLocation": 17776,
"Area_Name": "Schlüchtern II",
"Area_Short": "SLUE--00",
"IdArea": 14688,
"X": 53.2455,
"Y": 8.1614,
"Icon": 20,
"System": 1,
"Active": 1
},
{
"LD_Name": "GMA Littwin (TEST)",
"IdLD": 50004,
"Device": "Glättemeldeanlage",
"Link": "gma.aspx?ver=1&id=50004",
"Location_Name": "RG Relaisraum",
"Location_Short": "REZR",
"IdLocation": 18624,
"Area_Name": "Renzenhof (RG)",
"Area_Short": "REZHRG00",
"IdArea": 16570,
"X": 53.246036,
"Y": 8.163293,
"Icon": 1,
"System": 11,
"Active": 0
},
{
"LD_Name": "NRS Testserver",
"IdLD": 50005,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50005",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Gateway 2",
"IdLD": 50007,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50007",
"Location_Name": "(EV Ammersricht BZR REL)",
"Location_Short": "AMME",
"IdLocation": 21118,
"Area_Name": "Ammersricht BZR (FGN)",
"Area_Short": "AMMER--00",
"IdArea": 15958,
"X": 52.52726,
"Y": 12.165488,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "Basisgerät mit SNMP MVP",
"IdLD": 50669,
"Device": "Basisgerät + SNMP",
"Link": "basisSNMP.aspx?&ver=1&id=50669",
"Location_Name": "Mylinghauserstraße Engelbert",
"Location_Short": "G-GEVELSBE-1",
"IdLocation": 24012,
"Area_Name": "Gevelsberg",
"Area_Short": "GMA-GEVELSBE",
"IdArea": 20919,
"X": 51.316799,
"Y": 7.33281,
"Icon": 14,
"System": 200,
"Active": 1
},
{
"LD_Name": "Server 3",
"IdLD": 50009,
"Device": "Notruf Server",
"Link": "nrs_server.aspx?ver=1&id=50009",
"Location_Name": "Militärringstraße Militärringstraße",
"Location_Short": "G-KÃLN-1",
"IdLocation": 24015,
"Area_Name": "Köln",
"Area_Short": "GMA-KÃLN",
"IdArea": 20921,
"X": 50.898399,
"Y": 6.92278,
"Icon": 19,
"System": 8,
"Active": 0
},
{
"LD_Name": "ICL Test 5",
"IdLD": 50054,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50054",
"Location_Name": "Recheder Mühlenweg Dortmund-Ems-Kanal",
"Location_Short": "G-OLFEN-SE-1",
"IdLocation": 24022,
"Area_Name": "Olfen-Selm",
"Area_Short": "GMA-OLFEN-SE",
"IdArea": 20926,
"X": 51.702202,
"Y": 7.40822,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "ICL Test 3",
"IdLD": 50052,
"Device": "ICL",
"Link": "icl.aspx?ver=1&id=50052",
"Location_Name": "Weidenstraße Hestenberg",
"Location_Short": "G-PLETTENB-1",
"IdLocation": 24024,
"Area_Name": "Plettenberg",
"Area_Short": "GMA-PLETTENB",
"IdArea": 20928,
"X": 51.224098,
"Y": 7.86969,
"Icon": 23,
"System": 100,
"Active": 0
},
{
"LD_Name": "Test Februar Kai",
"IdLD": 50912,
"Device": "Dauerzählstelle DZ",
"Link": "dauz.aspx?ver=1&id=50912",
"Location_Name": "In der Hoffnung Kiesberg - BG Ost",
"Location_Short": "G-WUPPERTA-4",
"IdLocation": 24039,
"Area_Name": "Wuppertal",
"Area_Short": "GMA-WUPPERTA",
"IdArea": 20937,
"X": 51.238899,
"Y": 7.12715,
"Icon": 14,
"System": 110,
"Active": 1
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the GisStationsStaticDistrict object with a 200 status code.
res.status(200).json(GisStationsStaticDistrict);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,81 @@
// /pages/api/talas5/webserviceMap/GisStationsStatusDistrict.js
import getPool from "../../../../utils/mysqlPool"; // Singleton-Pool importieren
export default async function handler(req, res) {
const pool = getPool(); // Singleton-Pool verwenden
let connection; // Verbindung deklarieren
const { idMap, idUser } = req.query;
if (!idMap || !idUser) {
return res.status(400).json({ error: "idMap and idUser are required" });
}
try {
// Verbindung aus dem Pool holen
connection = await pool.getConnection();
let onlySystem = -1;
let districtCounter = 0;
// Get onlySystem
const [mapResult] = await connection.query("SELECT idsystem_typ FROM maps WHERE id = ?", [idMap]);
if (mapResult.length > 0) {
onlySystem = mapResult[0].idsystem_typ ?? -1;
}
// Get districtCounter
if (idUser > 0) {
const [userLayerResult] = await connection.query("SELECT count(*) as count FROM user_User_layer1 WHERE iduser = ?", [idUser]);
districtCounter = userLayerResult[0].count;
}
// Query erstellen
let query = `
SELECT ld.idLD, dc.message, p.level, p.name, p.color, ld.idDevice, de.isService, dc.idIcon
FROM location as l
LEFT JOIN location_coordinates AS co ON l.idLocation = co.idLocation and co.idMaps = ?
LEFT JOIN location_device AS ld ON ld.idLocation = l.idLocation
LEFT JOIN datapoint as d ON d.idLD = ld.idLD
LEFT JOIN datapoint_conditions AS dc ON dc.idcondition = d.last_message_condition
LEFT JOIN prio AS p ON p.idPrio = dc.idprio
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN area as a on a.idArea = l.idArea
WHERE p.level < 100 AND co.X > 0
`;
const queryParams = [idMap];
if (districtCounter > 0) {
query += ` AND a.iddistrict IN (SELECT iddistrict FROM user_user_layer1 WHERE iduser = ?)`;
queryParams.push(idUser);
}
if (onlySystem >= 0) {
query += ` AND de.idsystem_typ = ?`;
queryParams.push(onlySystem);
}
query += ` ORDER BY p.level desc`;
const [results] = await connection.query(query, queryParams);
const mpss = {
IdMap: idMap.toString(),
Statis: results.map((row) => ({
IdLD: row.idLD ?? -1,
Le: row.level ?? -1,
Me: row.message ?? "?",
Na: row.name ?? "?",
Co: row.color ?? "#ffffff",
Feld: row.idDevice ?? -1,
Icon: row.idIcon ?? 0,
})),
};
res.status(200).json(mpss);
} catch (error) {
console.error("Fehler beim Laden der Daten:", error);
res.status(500).json({ error: "Interner Serverfehler" });
} finally {
// Stelle sicher, dass die Verbindung zurück in den Pool gegeben wird
if (connection) connection.release();
}
}

View File

@@ -0,0 +1,273 @@
// /pages/api/webServiceMap.js
const gisSystemStatic = {
"Name": "Liste aller angezeigten Systeme",
"Zeitstempel": "2024-05-31T15:08:49.8599542+02:00",
"IdMap": "10",
"Systems": [
{
"IdSystem": 1,
"Name": "TALAS",
"Longname": "Talas Meldestationen",
"Allow": 1,
"Icon": 1
},
{
"IdSystem": 2,
"Name": "ECI",
"Longname": "ECI Geräte",
"Allow": 1,
"Icon": 2
},
{
"IdSystem": 5,
"Name": "GSM Modem",
"Longname": "LR77 GSM Modems",
"Allow": 1,
"Icon": 5
},
{
"IdSystem": 6,
"Name": "Cisco Router",
"Longname": "Cisco Router",
"Allow": 1,
"Icon": 6
},
{
"IdSystem": 7,
"Name": "WAGO",
"Longname": "WAGO I/O Systeme",
"Allow": 1,
"Icon": 7
},
{
"IdSystem": 8,
"Name": "Siemens",
"Longname": "Siemens Notrufsystem",
"Allow": 0,
"Icon": 8
},
{
"IdSystem": 9,
"Name": "OTDR",
"Longname": "Glasfaserüberwachung OTU",
"Allow": 0,
"Icon": 9
},
{
"IdSystem": 10,
"Name": "WDM",
"Longname": " Wavelength Division Multiplexing",
"Allow": 0,
"Icon": 10
},
{
"IdSystem": 11,
"Name": "GMA",
"Longname": "Glättemeldeanlagen",
"Allow": 1,
"Icon": 11
},
{
"IdSystem": 13,
"Name": "Messstellen",
"Longname": "Messstellen",
"Allow": 0,
"Icon": 13
},
{
"IdSystem": 100,
"Name": "TALAS ICL",
"Longname": "Talas ICL Unterstationen",
"Allow": 1,
"Icon": 100
},
{
"IdSystem": 110,
"Name": "DAUZ",
"Longname": "Dauerzählstellen",
"Allow": 1,
"Icon": 110
},
{
"IdSystem": 111,
"Name": "SMS-Funkmodem",
"Longname": "SMS-Funkmodem",
"Allow": 0,
"Icon": 111
},
{
"IdSystem": 200,
"Name": "Sonstige",
"Longname": "Sonstige",
"Allow": 1,
"Icon": 200
}
],
"Rights": [
{
"IdRight": 1
},
{
"IdRight": 2
},
{
"IdRight": 3
},
{
"IdRight": 5
},
{
"IdRight": 6
},
{
"IdRight": 7
},
{
"IdRight": 8
},
{
"IdRight": 10
},
{
"IdRight": 11
},
{
"IdRight": 12
},
{
"IdRight": 20
},
{
"IdRight": 22
},
{
"IdRight": 23
},
{
"IdRight": 25
},
{
"IdRight": 30
},
{
"IdRight": 40
},
{
"IdRight": 41
},
{
"IdRight": 42
},
{
"IdRight": 43
},
{
"IdRight": 44
},
{
"IdRight": 45
},
{
"IdRight": 46
},
{
"IdRight": 47
},
{
"IdRight": 48
},
{
"IdRight": 49
},
{
"IdRight": 50
},
{
"IdRight": 51
},
{
"IdRight": 52
},
{
"IdRight": 55
},
{
"IdRight": 56
},
{
"IdRight": 60
},
{
"IdRight": 61
},
{
"IdRight": 62
},
{
"IdRight": 63
},
{
"IdRight": 64
},
{
"IdRight": 65
},
{
"IdRight": 68
},
{
"IdRight": 69
},
{
"IdRight": 70
},
{
"IdRight": 71
},
{
"IdRight": 72
},
{
"IdRight": 73
},
{
"IdRight": 79
},
{
"IdRight": 80
},
{
"IdRight": 90
},
{
"IdRight": 93
},
{
"IdRight": 94
},
{
"IdRight": 95
},
{
"IdRight": 96
}
]
}
// Export an async function handler for the API route.
export default async function handler(req, res) {
// Initialize an empty params object to store query parameters.
const params = {
idMap: req.query.idMap,
idUser: req.query.idUser
};
// Check if the requested ID map and user match certain conditions.
if (params.idMap === '10' && params.idUser === '484') {
// If the conditions are met, return the gisSystemStatic object with a 200 status code.
res.status(200).json(gisSystemStatic);
} else {
// If not, return a 404 error with the message "Not Found".
res.status(404).send('Not Found');
}
};

View File

@@ -0,0 +1,56 @@
// /pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js
import getPool from "../../../../utils/mysqlPool"; // Singleton-Pool importieren
export default function handler(req, res) {
const pool = getPool(); // Singleton-Pool verwenden
const idMap = req.query.idMap;
if (req.method !== "GET") {
return res.status(405).json({ error: "Nur GET Methode erlaubt" });
}
const sqlQuery = `
SELECT
ld.idLD,
dp.idDP,
dp.name AS Na,
dp.value AS Val,
dp.unit AS Unit,
mg.name AS Gr,
ld.idLocation,
area.Name AS Area_Name
FROM location_device as ld
LEFT JOIN location_coordinates AS co ON ld.idLocation = co.idLocation and co.idMaps = ?
LEFT JOIN devices AS de ON de.idDevice = ld.idDevice
LEFT JOIN datapoint AS dp ON ld.idLD = dp.idLD
LEFT JOIN message_group AS mg ON dp.idmessage_group = mg.idmessage_group
LEFT JOIN location AS loc ON ld.idLocation = loc.idLocation
LEFT JOIN area AS area ON loc.idArea = area.idArea
WHERE co.X > 0 AND dp.idmessage_group>0 AND length(dp.unit)> 0 AND length(dp.value)> 0
`;
pool.query(sqlQuery, [idMap], (error, results) => {
if (error) {
console.error("Fehler beim Abrufen der gis_lines:", error);
return res.status(500).json({ error: "Fehler beim Abrufen der gis_lines" });
}
const response = {
Name: "Liste aller Messungen der Geraete",
Zeitstempel: new Date().toISOString(),
IdMap: idMap,
Statis: results.map((row) => ({
IdLD: row.idLD,
IdDP: row.idDP,
Na: row.Na,
Val: row.Val,
Unit: row.Unit,
Gr: row.Gr,
IdLocation: row.idLocation,
Area_Name: row.Area_Name,
})),
};
res.json(response);
});
}

View File

@@ -1,3 +1,4 @@
"use client";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import { useRecoilState, useRecoilValue } from "recoil"; import { useRecoilState, useRecoilValue } from "recoil";
@@ -5,7 +6,6 @@ import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore";
import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom"; import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom";
const MapComponentWithNoSSR = dynamic(() => import("../components/MapComponent"), { ssr: false }); const MapComponentWithNoSSR = dynamic(() => import("../components/MapComponent"), { ssr: false });
// TestScript ohne SSR
const TestScriptWithNoSSR = dynamic(() => import("../components/TestScript"), { ssr: false }); const TestScriptWithNoSSR = dynamic(() => import("../components/TestScript"), { ssr: false });
export default function Home() { export default function Home() {
@@ -14,6 +14,7 @@ export default function Home() {
const [mParam, setMParam] = useState(""); const [mParam, setMParam] = useState("");
const [uParam, setUParam] = useState(""); const [uParam, setUParam] = useState("");
// Daten abrufen
const loadData = async () => { const loadData = async () => {
try { try {
const response = await fetch("/api/talas_v5_DB/pois/readLocations"); const response = await fetch("/api/talas_v5_DB/pois/readLocations");
@@ -27,17 +28,32 @@ export default function Home() {
} }
}; };
// Verhindert mehrfaches Laden durch doppelte Registrierung
useEffect(() => { useEffect(() => {
let isMounted = true;
function getURLParameter(name) { function getURLParameter(name) {
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
return params.get(name); return params.get(name);
} }
setMParam(getURLParameter("m")); setMParam(getURLParameter("m"));
setUParam(getURLParameter("u")); setUParam(getURLParameter("u"));
loadData(); const fetchData = async () => {
}, [poiReadTrigger]); await loadData();
};
if (isMounted) {
fetchData();
}
return () => {
isMounted = false;
};
}, [poiReadTrigger]); // Nur einmal bei Änderung von poiReadTrigger ausführen
// POI hinzufügen
const handleAddLocation = async (name, type, lat, lng) => { const handleAddLocation = async (name, type, lat, lng) => {
try { try {
const response = await fetch("/api/talas_v5_DB/pois/addLocation", { const response = await fetch("/api/talas_v5_DB/pois/addLocation", {
@@ -48,21 +64,17 @@ export default function Home() {
if (!response.ok) { if (!response.ok) {
throw new Error("Fehler beim Hinzufügen des Standorts"); throw new Error("Fehler beim Hinzufügen des Standorts");
} }
//console.log("Standort erfolgreich hinzugefügt");
loadData(); loadData();
} catch (error) { } catch (error) {
console.error(error.message); console.error(error.message);
} }
}; };
// Standort aktualisieren
const handleLocationUpdate = (id, newLatitude, newLongitude) => { const handleLocationUpdate = (id, newLatitude, newLongitude) => {
setLocations((prevLocations) => prevLocations.map((location) => (location.idPoi === id ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` } : location))); setLocations((prevLocations) => prevLocations.map((location) => (location.idPoi === id ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` } : location)));
}; };
useEffect(() => {
loadData();
}, [poiReadTrigger]);
return ( return (
<div> <div>
<MapComponentWithNoSSR locations={locations} onAddLocation={handleAddLocation} onLocationUpdate={handleLocationUpdate} /> <MapComponentWithNoSSR locations={locations} onAddLocation={handleAddLocation} onLocationUpdate={handleLocationUpdate} />

View File

@@ -1,8 +1,6 @@
// services/apiService.js // services/apiService.js
import * as config from "../config/config"; import * as config from "../config/config";
import SERVER_URL from "../config/urls"; import * as urls from "../config/urls";
const url = new URL(window.location.origin);
const originWithoutPort = `${url.protocol}//${url.hostname}`;
let timeoutId; let timeoutId;
@@ -23,22 +21,19 @@ const fetchWithTimeout = async (url, options, timeout = 5000) => {
} }
}; };
export const fetchGisStatusStations = async () => { export const fetchGisStatusStations = async (idMap, idUser) => {
//idMap und idUser von URL Parameter hersuslesen
const idMap = url.searchParams.get("m");
const idUser = url.searchParams.get("u");
// Verhindere wiederholte schnelle API-Aufrufe durch Debouncing // Verhindere wiederholte schnelle API-Aufrufe durch Debouncing
if (timeoutId) { if (timeoutId) {
clearTimeout(timeoutId); clearTimeout(timeoutId);
} }
timeoutId = setTimeout(async () => { timeoutId = setTimeout(async () => {
//const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL; const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;
try { try {
// Verwende das Timeout für die API-Anfrage // Verwende das Timeout für die API-Anfrage
const response = await fetchWithTimeout( const response = await fetchWithTimeout(
`${originWithoutPort}/talas5/ClientData/WebServiceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`, `${SERVER_URL}/talas5/ClientData/WebServiceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`,
{ {
method: "GET", method: "GET",
headers: { headers: {
@@ -141,13 +136,6 @@ export const fetchDeviceNameById = async (idLD) => {
// ---------------------------------------------- // ----------------------------------------------
// services/apiService.js // services/apiService.js
export const fetchUserRights = async () => { export const fetchUserRights = async () => {
// Aktuelle URL abrufen
const url = new URL(window.location.href);
// idMap und idUser von URL-Parametern abrufen
const idMap = url.searchParams.get("m");
const idUser = url.searchParams.get("u");
// Zähler für API-Aufrufe in localStorage speichern // Zähler für API-Aufrufe in localStorage speichern
let userRightsRequestCount = localStorage.getItem("userRightsRequestCount") || 0; let userRightsRequestCount = localStorage.getItem("userRightsRequestCount") || 0;
userRightsRequestCount++; userRightsRequestCount++;
@@ -155,16 +143,7 @@ export const fetchUserRights = async () => {
console.log(`fetchUserRights wurde ${userRightsRequestCount} Mal aufgerufen.`); console.log(`fetchUserRights wurde ${userRightsRequestCount} Mal aufgerufen.`);
try { try {
// Basis-URL ohne Port abrufen const response = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${config.idMap}&idUser=${config.idUser}`, {
const protocol = window.location.protocol; // z. B. 'http:' oder 'https:'
const hostname = window.location.hostname; // z. B. 'example.com'
const originWithoutPort = `${protocol}//${hostname}`; // z. B. 'https://example.com'
console.log("originWithoutPort in fetchUserRights", originWithoutPort);
console.log("idMap in fetchUserRights", idMap);
console.log("idUser in fetchUserRights", idUser);
const response = await fetch(`${originWithoutPort}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`, {
method: "GET", method: "GET",
headers: { headers: {
Connection: "close", Connection: "close",
@@ -182,7 +161,7 @@ export const fetchUserRights = async () => {
throw new Error("Invalid response structure"); throw new Error("Invalid response structure");
} }
const rightsArray = data.Rights; // Rechte-Array abrufen const rightsArray = data.Rights; // Nehmen an, dass 'Rights' das Array von Rechten ist
const userRightsIds = rightsArray.map((right) => right.IdRight); const userRightsIds = rightsArray.map((right) => right.IdRight);
return userRightsIds; return userRightsIds;

View File

@@ -1,7 +1,14 @@
// store/atoms/poiReadFromDbTriggerAtom.js import { atom } from "recoil";
import { atom } from 'recoil';
export const poiReadFromDbTriggerAtom = atom({ const atomKey = "poiReadFromDbTriggerAtom";
key: 'poiReadFromDbTriggerAtom',
default: 0, // Sie können auch einen booleschen Wert verwenden export const poiReadFromDbTriggerAtom =
}); globalThis.poiReadFromDbTriggerAtom ||
atom({
key: atomKey,
default: 0,
});
if (process.env.NODE_ENV !== "production") {
globalThis.poiReadFromDbTriggerAtom = poiReadFromDbTriggerAtom;
}

View File

@@ -1,7 +1,16 @@
//store/selectors/readPoiMarkersStore.js import { atom } from "recoil";
import { atom } from 'recoil';
export const readPoiMarkersStore = atom({ const storeKey = "readPoiMarkersStore";
key: 'readPoiMarkersStore',
default: [], // Verhindert doppelte Registrierung bei HMR
}); export const readPoiMarkersStore =
globalThis.readPoiMarkersStore ||
atom({
key: storeKey,
default: [],
});
// Speichert das Atom im globalen Namespace (nur in Dev)
if (process.env.NODE_ENV !== "production") {
globalThis.readPoiMarkersStore = readPoiMarkersStore;
}

View File

@@ -7,7 +7,6 @@ import { toast } from "react-toastify";
import * as config from "../config/config.js"; import * as config from "../config/config.js";
import { disablePolylineEvents, enablePolylineEvents } from "./setupPolylines"; // Importiere die Funktion zum Deaktivieren der Polyline-Ereignisse import { disablePolylineEvents, enablePolylineEvents } from "./setupPolylines"; // Importiere die Funktion zum Deaktivieren der Polyline-Ereignisse
import { setPolylineEventsDisabled } from "../store/atoms/polylineEventsDisabledState"; // Importiere den Recoil-Atom-Zustand import { setPolylineEventsDisabled } from "../store/atoms/polylineEventsDisabledState"; // Importiere den Recoil-Atom-Zustand
import { SERVER_URL } from "../config/urls.js";
// Funktion zum Bestimmen der Priorität basierend auf dem Icon-Pfad // Funktion zum Bestimmen der Priorität basierend auf dem Icon-Pfad
const determinePriority = (iconPath, priorityConfig) => { const determinePriority = (iconPath, priorityConfig) => {
@@ -32,15 +31,13 @@ export const createAndSetDevices = async (systemId, setMarkersFunction, GisSyste
const jsonResponse = await response1.json(); const jsonResponse = await response1.json();
const response2 = await fetch(config.mapGisStationsStatusDistrictUrl); const response2 = await fetch(config.mapGisStationsStatusDistrictUrl);
const statusResponse = await response2.json(); const statusResponse = await response2.json();
const BASE_URL = SERVER_URL; const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const getIdSystemAndAllowValueMap = new Map(GisSystemStatic.map((system) => [system.IdSystem, system.Allow])); const getIdSystemAndAllowValueMap = new Map(GisSystemStatic.map((system) => [system.IdSystem, system.Allow]));
if (jsonResponse.Points && statusResponse.Statis) { if (jsonResponse.Points && statusResponse.Statis) {
//console.log("jsonResponse.Points: ", jsonResponse.Points); console.log("jsonResponse.Points: ", jsonResponse.Points);
//console.log("statusResponse.Statis: ", statusResponse.Statis); console.log("statusResponse.Statis: ", statusResponse.Statis);
localStorage.setItem("jsonResponse.Points", JSON.stringify(jsonResponse.Points));
localStorage.setItem("statusResponse.Statis", JSON.stringify(statusResponse.Statis));
const statisMap = new Map(statusResponse.Statis.map((s) => [s.IdLD, s])); const statisMap = new Map(statusResponse.Statis.map((s) => [s.IdLD, s]));
let markersData = jsonResponse.Points.filter((station) => station.System === systemId && getIdSystemAndAllowValueMap.get(station.System) === 1).map((station) => { let markersData = jsonResponse.Points.filter((station) => station.System === systemId && getIdSystemAndAllowValueMap.get(station.System) === 1).map((station) => {
const statis = statisMap.get(station.IdLD); const statis = statisMap.get(station.IdLD);
@@ -114,6 +111,7 @@ export const createAndSetDevices = async (systemId, setMarkersFunction, GisSyste
</div> </div>
`); `);
return marker; return marker;
}); });

View File

@@ -103,12 +103,9 @@ export const checkOverlappingMarkers = (map, markers, plusIcon) => {
const latLng = L.latLng(coords.match(/[-.\d]+/g).map(Number)); const latLng = L.latLng(coords.match(/[-.\d]+/g).map(Number));
const plusMarker = L.marker(latLng, { icon: plusIcon }); const plusMarker = L.marker(latLng, { icon: plusIcon });
plusMarker.addTo(map); plusMarker.addTo(map);
//localStorage benutzen statt console.log
//console.log("Adding plus icon marker at", latLng); console.log("Adding plus icon marker at", latLng);
localStorage.setItem("Adding plus icon marker at", plusMarker);
} }
} }
//localStorage benutzen statt console.log console.log("overlappingGroups", overlappingGroups);
//console.log("overlappingGroups", overlappingGroups);
localStorage.setItem("overlappingGroups", overlappingGroups);
}; };

View File

@@ -7,7 +7,7 @@ let connectionCount = 0; // Zähler für die aktiven Verbindungen
function getPool() { function getPool() {
if (!cachedPool) { if (!cachedPool) {
cachedPool = mysql.createPool({ cachedPool = mysql.createPool({
host: "127.0.0.1", host: process.env.DB_HOST,
user: process.env.DB_USER, user: process.env.DB_USER,
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
database: process.env.DB_NAME, database: process.env.DB_NAME,

View File

@@ -1,8 +1,7 @@
// utils/openInNewTab.js // utils/openInNewTab.js
import SERVER_URL from "../config/urls";
export function openInNewTab(e, target) { export function openInNewTab(e, target) {
const BASE_URL = SERVER_URL; const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
let link; let link;
// Prüfen, ob der Kontextmenü-Eintrag aufgerufen wird, ohne dass ein Marker oder Polyline direkt angesprochen wird // Prüfen, ob der Kontextmenü-Eintrag aufgerufen wird, ohne dass ein Marker oder Polyline direkt angesprochen wird

View File

@@ -83,9 +83,7 @@ export const setupPOIs = async (
`); `);
marker.on("mouseover", function () { marker.on("mouseover", function () {
//loaclStorage benutzen statt console.log console.log("Device Name:", marker); // Debugging
//console.log("Device Name:", marker); // Debugging
localStorage.setItem("deviceName", marker.options.name);
handlePoiSelect( handlePoiSelect(
{ {
id: location.idPoi, id: location.idPoi,

View File

@@ -0,0 +1,341 @@
// utils/setupPolylines.js
import { findClosestPoints } from "./geometryUtils";
import handlePoiSelect from "./handlePoiSelect";
import { updateLocationInDatabase } from "../services/apiService";
import { handleEditPoi, insertNewPOI, removePOI } from "./poiUtils";
import { parsePoint } from "./geometryUtils";
import circleIcon from "../components/gisPolylines/icons/CircleIcon";
import startIcon from "../components/gisPolylines/icons/StartIcon";
import endIcon from "../components/gisPolylines/icons/EndIcon";
import { redrawPolyline } from "./mapUtils";
import { openInNewTab } from "./openInNewTab";
import { toast } from "react-toastify";
import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState";
import { useRecoilValue } from "recoil";
// Funktion zum Deaktivieren der Polyline-Ereignisse
export function disablePolylineEvents(polylines) {
polylines.forEach((polyline) => {
polyline.off("mouseover");
polyline.off("mouseout");
});
}
// Funktion zum Aktivieren der Polyline-Ereignisse
export function enablePolylineEvents(polylines, lineColors) {
// Überprüfe, ob polylines definiert ist und ob es Elemente enthält
if (!polylines || polylines.length === 0) {
//console.warn("Keine Polylinien vorhanden oder polylines ist undefined.");
return;
}
// Falls Polylinien vorhanden sind, wende die Events an
polylines.forEach((polyline) => {
polyline.on("mouseover", (e) => {
//console.log("Mouseover on polyline", polyline.options);
polyline.setStyle({ weight: 14 });
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?id=${polyline.options.idLD}`;
//localStorage.setItem("lastElementType", "polyline");
//localStorage.setItem("polylineLink", link);
});
polyline.on("mouseout", (e) => {
//console.log("Mouseout from polyline", polyline.options);
polyline.setStyle({ weight: 3 });
});
});
}
export const setupPolylines = (map, linePositions, lineColors, tooltipContents, setNewCoords, tempMarker, currentZoom, currentCenter, polylineVisible) => {
if (localStorage.getItem("polylineVisible") === null) {
localStorage.setItem("polylineVisible", "true"); // Standardwert setzen
polylineVisible = true; // Wert in der Funktion initialisieren
} else {
polylineVisible = localStorage.getItem("polylineVisible") === "true";
}
if (!polylineVisible) {
// Entferne alle Polylinien, wenn sie ausgeblendet werden sollen
if (window.polylines) {
window.polylines.forEach((polyline) => {
if (map.hasLayer(polyline)) {
map.removeLayer(polyline);
}
});
}
return { markers: [], polylines: [] };
}
const markers = [];
const polylines = [];
const editMode = localStorage.getItem("editMode") === "true"; // Prüfen, ob der Bearbeitungsmodus aktiv ist
linePositions.forEach((lineData, lineIndex) => {
const lineMarkers = [];
lineData.coordinates.forEach((coord, index) => {
let icon = circleIcon;
if (index === 0) {
icon = startIcon;
} else if (index === lineData.coordinates.length - 1) {
icon = endIcon;
}
// Nur Marker mit circleIcon ausblenden, wenn Bearbeitungsmodus deaktiviert ist
if (icon !== circleIcon || editMode) {
const marker = L.marker(coord, {
icon: icon,
draggable: editMode, // Nur verschiebbar, wenn Bearbeitungsmodus aktiv ist
contextmenu: true,
contextmenuInheritItems: false,
contextmenuItems: [],
}).addTo(map);
marker.on("dragend", () => {
console.log("Marker wurde verschoben in setupPolylines.js");
if (editMode) {
const newCoords = marker.getLatLng();
setNewCoords(newCoords);
const newCoordinates = [...lineData.coordinates];
newCoordinates[index] = [newCoords.lat, newCoords.lng];
const updatedPolyline = L.polyline(newCoordinates, {
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
}).addTo(map);
updatedPolyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
permanent: false,
direction: "auto",
});
updatedPolyline.on("mouseover", () => {
updatedPolyline.setStyle({ weight: 20 });
updatedPolyline.bringToFront();
});
updatedPolyline.on("mouseout", () => {
updatedPolyline.setStyle({ weight: 3 });
});
polylines[lineIndex].remove();
polylines[lineIndex] = updatedPolyline;
lineData.coordinates = newCoordinates;
const requestData = {
idModul: lineData.idModul,
idLD: lineData.idLD,
newCoordinates,
};
fetch("/api/talas_v5_DB/gisLines/updateLineCoordinates", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestData),
})
.then((response) => {
if (!response.ok) {
return response.json().then((data) => {
throw new Error(data.error || "Unbekannter Fehler");
});
}
return response.json();
})
.then((data) => {
console.log("Koordinaten erfolgreich aktualisiert:", data);
})
.catch((error) => {
console.error("Fehler beim Aktualisieren der Koordinaten:", error.message);
});
} else {
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
}
});
marker.on("mouseover", function () {
this.bindContextMenu({
contextmenuItems: [
{
text: "Stützpunkt entfernen",
icon: "/img/icons/gisLines/remove-support-point.svg",
callback: () => {
if (editMode) {
const newCoords = marker.getLatLng();
const newCoordinates = [...lineData.coordinates];
newCoordinates[index] = [newCoords.lat, newCoords.lng];
removePOI(marker, lineData, currentZoom, currentCenter);
polylines[lineIndex].remove();
lineData.coordinates = newCoordinates;
} else {
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
}
},
},
],
});
});
marker.on("mouseout", function () {
this.unbindContextMenu();
});
lineMarkers.push(marker);
}
});
const polyline = L.polyline(lineData.coordinates, {
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
weight: 3,
contextmenu: true,
contextmenuInheritItems: false, // Standard-Kontextmenü deaktivieren
contextmenuItems: [],
}).addTo(map);
// Füge "Stützpunkt hinzufügen" nur hinzu, wenn editMode aktiv ist
if (editMode) {
polyline.options.contextmenuItems.push(
{
text: "Station öffnen (Tab)",
icon: "/img/screen_new.png",
callback: (e) => {
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
window.open(link, "_blank");
},
},
{ separator: true },
{
text: "Koordinaten anzeigen",
icon: "/img/not_listed_location.png",
callback: (e) => {
alert("Breitengrad: " + e.latlng.lat.toFixed(5) + "\nLängengrad: " + e.latlng.lng.toFixed(5));
},
},
{ separator: true },
{
text: "Reinzoomen",
icon: "/img/zoom_in.png",
callback: (e) => map.zoomIn(),
},
{
text: "Rauszoomen",
icon: "/img/zoom_out.png",
callback: (e) => map.zoomOut(),
},
{
text: "Hier zentrieren",
icon: "/img/center_focus.png",
callback: (e) => map.panTo(e.latlng),
},
{ separator: true },
{
text: "POI hinzufügen",
icon: "/img/add_station.png",
callback: (e) => {
// Hier kannst du die Logik für das Hinzufügen eines POIs implementieren
alert("POI hinzufügen an: " + e.latlng);
},
},
{
text: "Stützpunkt hinzufügen",
icon: "/img/icons/gisLines/add-support-point.svg",
callback: (e) => {
if (tempMarker) {
tempMarker.remove();
}
const newPoint = e.latlng;
const closestPoints = findClosestPoints(lineData.coordinates, newPoint, map);
insertNewPOI(closestPoints, newPoint, lineData, map);
redrawPolyline(lineData, lineColors, tooltipContents, map);
window.location.reload();
},
}
);
}
// Hier wird der Tooltip hinzugefügt
polyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
permanent: false,
direction: "auto",
});
polyline.on("mouseover", (e) => {
const startTime = Date.now(); // Startzeit erfassen
localStorage.setItem("contextMenuStartTime", startTime); // Speichern in localStorage
// Starte einen Intervall-Timer, um die Differenz zu berechnen
const countdownInterval = setInterval(() => {
const currentTime = Date.now();
const elapsedTime = (currentTime - startTime) / 1000; // Differenz in Sekunden
// Speichern der abgelaufenen Zeit in localStorage
localStorage.setItem("contextMenuCountdown", elapsedTime);
// Wenn die Zeit 17 Sekunden erreicht, schließe das Menü
if (elapsedTime >= 17) {
clearInterval(countdownInterval);
const contextMenu = map.contextmenu; // Zugriff auf das Kontextmenü
contextMenu.hide(); // Kontextmenü schließen
}
}, 1000); // Jede Sekunde
//console.log("Mouseover on polyline", lineData);
polyline.setStyle({ weight: 14 });
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
console.log("Link der Linie:", link);
//localStorage.setItem("lastElementType", "polyline");
//localStorage.setItem("polylineLink", link);
});
polyline.on("mouseout", (e) => {
// console.log("Mouseout from polyline", lineData);
polyline.setStyle({ weight: 3 });
// Setze den Countdown auf 0, wenn mouseout ausgelöst wird
localStorage.setItem("contextMenuCountdown", 0);
});
// Speichere den Link bei einem Rechtsklick (Kontextmenü)
/*
polyline.on("contextmenu", (e) => {
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
console.log("Link der Linie (via Rechtsklick):", link);
localStorage.setItem("lastElementType", "polyline");
localStorage.setItem("polylineLink", link);
});
*/
// Starte den Timer zum Schließen des Kontextmenüs nach 15 Sekunden
polyline.on("contextmenu", function (e) {
const contextMenu = this._map.contextmenu; // Zugriff auf das Kontextmenü
const closeMenu = () => contextMenu.hide(); // Funktion zum Schließen des Menüs
const countdown = parseInt(localStorage.getItem("contextMenuCountdown"), 30);
if (countdown >= 28) {
closeMenu();
}
});
polylines.push(polyline);
markers.push(...lineMarkers);
});
// Speichere Polylines und LineColors global für den Zugriff in anderen Funktionen
window.polylines = polylines;
window.lineColors = lineColors;
return { markers, polylines };
};

View File

@@ -13,11 +13,6 @@ import { toast } from "react-toastify";
import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState"; import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
const protocol = window.location.protocol; // z. B. 'http:' oder 'https:'
const hostname = window.location.hostname; // z. B. 'example.com'
const originWithoutPort = `${protocol}//${hostname}`; // z. B. 'https://example.com'
const BASE_URL = `${originWithoutPort}/talas5/devices/`; // Dynamische Basis-URL
// Funktion zum Deaktivieren der Polyline-Ereignisse // Funktion zum Deaktivieren der Polyline-Ereignisse
export function disablePolylineEvents(polylines) { export function disablePolylineEvents(polylines) {
polylines.forEach((polyline) => { polylines.forEach((polyline) => {
@@ -39,7 +34,7 @@ export function enablePolylineEvents(polylines, lineColors) {
polyline.on("mouseover", (e) => { polyline.on("mouseover", (e) => {
//console.log("Mouseover on polyline", polyline.options); //console.log("Mouseover on polyline", polyline.options);
polyline.setStyle({ weight: 14 }); polyline.setStyle({ weight: 14 });
const link = `${BASE_URL}cpl.aspx?id=${polyline.options.idLD}`; const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?id=${polyline.options.idLD}`;
//localStorage.setItem("lastElementType", "polyline"); //localStorage.setItem("lastElementType", "polyline");
//localStorage.setItem("polylineLink", link); //localStorage.setItem("polylineLink", link);
}); });
@@ -255,7 +250,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents,
text: "Station öffnen (Tab)", text: "Station öffnen (Tab)",
icon: "/img/screen_new.png", icon: "/img/screen_new.png",
callback: (e) => { callback: (e) => {
const link = `${BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`; const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
window.open(link, "_blank"); window.open(link, "_blank");
}, },
}, },
@@ -314,7 +309,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents,
text: "Station öffnen (Tab)", text: "Station öffnen (Tab)",
icon: "/img/screen_new.png", icon: "/img/screen_new.png",
callback: (e) => { callback: (e) => {
const link = `${BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`; const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
window.open(link, "_blank"); window.open(link, "_blank");
}, },
}, },
@@ -384,11 +379,10 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents,
// Jede Sekunde // Jede Sekunde
//console.log("Mouseover on polyline", lineData); //console.log("Mouseover on polyline", lineData);
polyline.setStyle({ weight: 14 }); polyline.setStyle({ weight: 14 });
const link = `${BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`; const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
//console.log("Link der Linie:", link); console.log("Link der Linie:", link);
//localStorage.setItem("lastElementType", "polyline"); //localStorage.setItem("lastElementType", "polyline");
localStorage.setItem("Link_der_Linie:", link); //localStorage.setItem("polylineLink", link);
}); });
polyline.on("mouseout", (e) => { polyline.on("mouseout", (e) => {