diff --git a/.env.local b/.env.local index 21b3fd80a..fb6a0ee81 100644 --- a/.env.local +++ b/.env.local @@ -12,5 +12,6 @@ DB_PORT=3306 #NEXT_PUBLIC_ONLINE_TILE_LAYER="http://127.0.0.1:3000/mapTiles/{z}/{x}/{y}.png" #NEXT_PUBLIC_ONLINE_TILE_LAYER="http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png" #################### +NEXT_PUBLIC_SERVER_URL="http://10.10.0.70" NEXT_PUBLIC_ENABLE_GEOCODER=true diff --git a/components/MapComponent.js b/components/MapComponent.js index 09e342b38..822a64f09 100644 --- a/components/MapComponent.js +++ b/components/MapComponent.js @@ -502,6 +502,7 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { fetchData(); }, []); //-------------------------------------------- + //Tooltip an mouse position anzeigen für die Linien useEffect(() => { if (!map) return; @@ -511,17 +512,10 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { 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 - ); + const { markers: newMarkers, polylines: newPolylines } = setupPolylines(map, linePositions, lineColors, tooltipContents, setNewCoords, tempMarker, polylineVisible); newPolylines.forEach((polyline, index) => { + console.log("polyline: ", polyline); const tooltipContent = tooltipContents[`${linePositions[index].idLD}-${linePositions[index].idModul}`] || "Standard-Tooltip-Inhalt"; polyline.bindTooltip(tooltipContent, { diff --git a/components/PoiUpdateModal.js b/components/PoiUpdateModal.js index 9e4919dbc..d9811ab53 100644 --- a/components/PoiUpdateModal.js +++ b/components/PoiUpdateModal.js @@ -1,5 +1,5 @@ // pages/api/poiUpdateModal.js - +// import React, { useState, useEffect } from "react"; import { useRecoilValue } from "recoil"; import { selectedPoiState } from "../redux/slices/selectedPoiSlice"; @@ -15,22 +15,50 @@ const PoiUpdateModal = ({ onClose, poiData }) => { const [locationDeviceData, setLocationDeviceData] = useState([]); const [deviceName, setDeviceName] = useState(""); const [idLD, setIdLD] = useState(poiData ? poiData.idLD : ""); + const [idLocationDevice, setIdLocationDevice] = useState(""); const [description, setDescription] = useState(poiData ? poiData.description : ""); + // Log the initial POI data useEffect(() => { if (poiData) { - console.log("Initial poiData:", poiData); setPoiId(poiData.idPoi); setName(poiData.name); setPoiTypeId(poiData.idPoiTyp); setIdLD(poiData.idLD); + setDescription(poiData.description); setDeviceName(poiData.idLD); 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]); + /* 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(() => { const fetchDeviceId = async () => { if (poiData && poiData.idLD) { @@ -47,6 +75,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => { fetchDeviceId(); }, [poiData]); + // Function to handle deleting a POI const handleDeletePoi = async () => { if (confirm("Sind Sie sicher, dass Sie diesen POI löschen möchten?")) { try { @@ -55,7 +84,8 @@ const PoiUpdateModal = ({ onClose, poiData }) => { }); if (response.ok) { alert("POI wurde erfolgreich gelöscht."); - onClose(); + onClose(); // Close the modal + //Browser neu laden, um die aktualisierte Liste anzuzeigen window.location.reload(); } else { throw new Error("Fehler beim Löschen des POI."); @@ -67,6 +97,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => { } }; + // Fetch POI types useEffect(() => { const fetchPoiTypData = async () => { try { @@ -86,13 +117,16 @@ const PoiUpdateModal = ({ onClose, poiData }) => { fetchPoiTypData(); }, [selectedPoi]); + // Fetch device data um den Gerät Namen in den dropdown menu anzuzeigen also erstmal die Liste der Geräte abrufen useEffect(() => { const fetchData = async () => { try { // const response = await fetch("/api/talas_v5/location_device"); //"/api/talas_v5_DB/locationDevice/location_device" const response = await fetch("/api/talas_v5_DB/locationDevice/locationDevices"); const data = await response.json(); + //console.log("Standort- und Gerätedaten:", data); setLocationDeviceData(data); + console.log("Standort- und Gerätedaten poiData:", poiData); if (poiData && 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 @@ -105,8 +139,11 @@ const PoiUpdateModal = ({ onClose, poiData }) => { }; fetchData(); }, []); + //-------------------------------------------------------------------------------------------- + // Fetch device name basierend auf der Geräte-ID useEffect(() => { + console.log("currentPoi von PoiUpdateModal.js : ", currentPoi.idLD); fetch("/api/talas_v5_DB/locationDevice/locationDevices") .then((response) => response.json()) .then((data) => { @@ -125,6 +162,10 @@ const PoiUpdateModal = ({ onClose, poiData }) => { }); }, [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) => { event.preventDefault(); const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`); @@ -142,6 +183,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => { description: description, idPoiTyp: poiTypeId, idLD: idLD, + //idLD: parseInt(deviceName, 10), // Konvertieren in eine Ganzzahl }), }); diff --git a/components/ShowAddStationPopup.js b/components/ShowAddStationPopup.js index 205a655af..7b770e0ec 100644 --- a/components/ShowAddStationPopup.js +++ b/components/ShowAddStationPopup.js @@ -102,9 +102,6 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => { onClose(); return newTrigger; }); - - // Browser aktualisieren - window.location.reload(); } else { console.error("Fehler beim Hinzufügen des POI"); } @@ -113,7 +110,6 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => { map.closePopup(); } }; - //-----------------handleSubmit------------------- return ( diff --git a/components/imports.js b/components/imports.js new file mode 100644 index 000000000..a81e36edb --- /dev/null +++ b/components/imports.js @@ -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, +}; diff --git a/config/config.js b/config/config.js index 8a5983fb1..40ee38cd4 100644 --- a/config/config.js +++ b/config/config.js @@ -1,53 +1,55 @@ // /config/config.js import * as urls from "../config/urls.js"; - // Definieren der grundlegenden Umgebungseinstellungen und Konfigurationen der Karte const standardSideMenu = true; // Einstellung, ob ein standardmäßiges Seitenmenü verwendet wird const fullSideMenu = false; // Einstellung, ob ein vollständiges Seitenmenü verwendet wird -// Dynamische Bestimmung der Server-URL basierend auf window.location.origin ohne Port -let serverURL; - -if (typeof window !== "undefined") { - const url = new URL(window.location.origin); - 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!"); +const serverURL = process.env.NEXT_PUBLIC_SERVER_URL; +if (!serverURL) { + throw new Error("Die Umgebungsvariable NEXT_PUBLIC_SERVER_URL ist nicht gesetzt!"); } +console.log("%c 1- serverURL in config:", "color: #006400;", serverURL); -console.log("%c ServerURL (dynamisch ermittelt):", "color: #006400;", serverURL); - -// Initialisieren von Variablen +// Initialisieren von Variablen, die später im Browserkontext gesetzt werden let windowHeight, url_string, url, idMap, idUser; -// URLs für Online-Daten +//Online Daten 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") { - // Initialisierung der Browser-spezifischen Variablen - windowHeight = window.innerHeight; - url_string = window.location.href; - url = new URL(url_string); + // Diese Variablen werden nur im Browser-Kontext initialisiert + windowHeight = window.innerHeight; // Die Höhe des Browserfensters + url_string = window.location.href; // Die vollständige URL als 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 - idMap = url.searchParams.get("m"); // Parameter 'm' (idMap) - idUser = url.searchParams.get("u"); // Parameter 'u' (idUser) + console.log(`4- Parameter 'idMap' : ${idMap}`); + console.log(`5- Parameter 'idUser': ${idUser}`); - console.log(`Parameter 'idMap': ${idMap}`); - console.log(`Parameter 'idUser': ${idUser}`); + // Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen + //http://localhost:3000/?m=10&u=485 - // Konstruktion der URLs basierend auf den Server- und URL-Parametern - mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${idMap}&idUser=${idUser}`; + //-----------------Von WebService------------------------------------------------ + 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}`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${idMap}`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`; 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://192.168.10.14/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 } -// Export der definierten Variablen und URLs +// Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können export { standardSideMenu, fullSideMenu, @@ -64,3 +66,9 @@ export { mapDataIconUrl, 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. + */ diff --git a/config/settings.js b/config/settings.js new file mode 100644 index 000000000..e48bd655d --- /dev/null +++ b/config/settings.js @@ -0,0 +1,2 @@ +// /config/settings.js +export const MAP_VERSION = "1.0.8.2"; diff --git a/hooks/layers/useGmaMarkersLayer - Kopie.js b/hooks/layers/useGmaMarkersLayer - Kopie.js new file mode 100644 index 000000000..46f815b88 --- /dev/null +++ b/hooks/layers/useGmaMarkersLayer - Kopie.js @@ -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( + ` +
+
+ ${area_name} +
+
+ LT : ${lt} °C +
+
+ FBT : ${fbt} °C +
+
+ GT : ${gt} +
+
+ RLF : ${rlf} % +
+
+ `, + { + 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; diff --git a/hooks/layers/useSmsfunkmodemMarkersLayer.js b/hooks/layers/useSmsfunkmodemMarkersLayer.js index 64645b70f..5ebd714c3 100644 --- a/hooks/layers/useSmsfunkmodemMarkersLayer.js +++ b/hooks/layers/useSmsfunkmodemMarkersLayer.js @@ -11,7 +11,7 @@ const useSmsfunkmodemMarkersLayer = (map, oms, GisSystemStatic, priorityConfig, if (!map || !GisSystemStatic) return; // 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); // Hilfsfunktion: Normalisiert Strings diff --git a/hooks/useLineData-back.js b/hooks/useLineData-back.js deleted file mode 100644 index d1934e36e..000000000 --- a/hooks/useLineData-back.js +++ /dev/null @@ -1,124 +0,0 @@ -import { useEffect, useState } from "react"; -import { SERVER_URL } from "../config/urls"; -import { useDispatch, useSelector } from "react-redux"; - -const useLineData = (webserviceGisLinesStatusUrl, setLineStatusData) => { - const dispatch = useDispatch(); - const messages = useSelector((state) => state.messages); - const [lineColors, setLineColors] = useState({}); - const [tooltipContents, setTooltipContents] = useState({}); - - useEffect(() => { - let isCancelled = false; - - const fetchData = async () => { - try { - const response1 = await fetch(webserviceGisLinesStatusUrl); - const data1 = await response1.json(); - - const response2 = await fetch(`${SERVER_URL}:3000/api/talas_v5_DB/gisLines/readGisLines`); - const data2 = await response2.json(); - - const response3 = await fetch(`${SERVER_URL}:3000/api/talas_v5_DB/device/getAllStationsNames`); - const namesData = await response3.json(); - - if (!isCancelled) { - const colorsByModule = {}; - const newTooltipContents = {}; - const valueMap = {}; - - const sortedStatis = [...data1.Statis].sort((a, b) => a.Level - b.Level); - - sortedStatis.forEach((statis) => { - const key = `${statis.IdLD}-${statis.Modul}`; - - if (!valueMap[key]) { - valueMap[key] = { - messages: [], - messwert: undefined, - schleifenwert: undefined, - }; - } - - if (statis.DpName.endsWith("_Messwert") && statis.Value !== "True" && !valueMap[key].messwert) { - valueMap[key].messwert = statis.Value; - } - if (statis.DpName.endsWith("_Schleifenwert") && !valueMap[key].schleifenwert) { - valueMap[key].schleifenwert = statis.Value; - } - - if (statis.Message && statis.Message !== "?") { - valueMap[key].messages.push({ - message: statis.Message, - prioColor: statis.PrioColor && statis.PrioColor !== "#ffffff" ? statis.PrioColor : "green", - }); - } - }); - - sortedStatis.forEach((statis) => { - const key = `${statis.IdLD}-${statis.Modul}`; - const matchingLine = data2.find((item) => item.idLD === statis.IdLD && item.idModul === statis.Modul); - - if (matchingLine) { - const values = valueMap[key]; - - const messageDisplay = values.messages.map((msg) => `${msg.message}
`).join(""); - - const prioNameDisplay = statis.PrioName && statis.PrioName !== "?" ? `(${statis.PrioName})` : ""; - - colorsByModule[key] = values.messages.length > 0 ? values.messages[0].prioColor : "green"; - - newTooltipContents[key] = ` -
- ${statis.ModulName || "Unknown"} -
- ${statis.ModulTyp || "N/A"} -
- Slot: ${statis.Modul || "N/A"} -
- Station: ${namesData[matchingLine.idLD] || "N/A"} -
-
- ${messageDisplay} -
-
- ${values.messwert ? `Messwert: ${values.messwert}
` : ""} - ${values.schleifenwert ? `Schleifenwert: ${values.schleifenwert}` : ""} -
- `; - } - }); - - setLineColors(colorsByModule); - setTooltipContents(newTooltipContents); - setLineStatusData(data1.Statis); - } - } catch (error) { - console.error("Fehler beim Abrufen der Daten:", error); - try { - window.location.reload(); - } catch (reloadError) { - console.error("Fehler beim Neuladen der Seite:", reloadError); - } - } - }; - - const scheduleNextFetch = () => { - if (!isCancelled) { - fetchData(); - setTimeout(scheduleNextFetch, 30000); - } - }; - - fetchData(); - scheduleNextFetch(); - - return () => { - isCancelled = true; - }; - }, [webserviceGisLinesStatusUrl, setLineStatusData]); - - return { lineColors, tooltipContents }; -}; - -export default useLineData; diff --git a/package-lock.json b/package-lock.json index cba77b1a6..d45432f59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "@emotion/styled": "^11.13.0", "@heroicons/react": "^2.1.5", "@mui/icons-material": "^6.0.2", - "@reduxjs/toolkit": "^2.2.7", + "@reduxjs/toolkit": "^2.5.1", "autoprefixer": "^10.4.19", "axios": "^1.7.9", "cookies": "^0.9.1", @@ -28,7 +28,7 @@ "postcss": "^8.4.40", "react": "^18.3.1", "react-dom": "^18.3.1", - "react-redux": "^9.1.2", + "react-redux": "^9.2.0", "react-select": "^5.8.0", "react-toastify": "^10.0.5", "recoil": "^0.7.7", @@ -6656,12 +6656,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -7300,24 +7294,6 @@ "node": ">= 0.8" } }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", diff --git a/package.json b/package.json index c4182bf95..e90a8f33a 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "@emotion/styled": "^11.13.0", "@heroicons/react": "^2.1.5", "@mui/icons-material": "^6.0.2", - "@reduxjs/toolkit": "^2.2.7", + "@reduxjs/toolkit": "^2.5.1", "autoprefixer": "^10.4.19", "axios": "^1.7.9", "cookies": "^0.9.1", @@ -23,7 +23,7 @@ "postcss": "^8.4.40", "react": "^18.3.1", "react-dom": "^18.3.1", - "react-redux": "^9.1.2", + "react-redux": "^9.2.0", "react-select": "^5.8.0", "react-toastify": "^10.0.5", "recoil": "^0.7.7", diff --git a/pages/_app.js b/pages/_app.js index 6102bc0e5..f4d0e26c3 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -1,15 +1,19 @@ -// Pfad: pages/_app.js +// /pages/_app.js import React from "react"; import { RecoilRoot } from "recoil"; import { Provider } from "react-redux"; -import store from "../redux/store"; +import { store } from "../redux/store"; // ← Stelle sicher, dass der Import korrekt ist! import "../styles/global.css"; //import "../public/css/geocoder.css"; function MyApp({ Component, pageProps }) { return ( + {" "} + {/* Redux Provider */} + {" "} + {/* Recoil Provider */} diff --git a/pages/api - Kopie/[...path].js b/pages/api - Kopie/[...path].js new file mode 100644 index 000000000..b270661b1 --- /dev/null +++ b/pages/api - Kopie/[...path].js @@ -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 +}); diff --git a/pages/api - Kopie/get-talasIP.js b/pages/api - Kopie/get-talasIP.js new file mode 100644 index 000000000..1216fbbb7 --- /dev/null +++ b/pages/api - Kopie/get-talasIP.js @@ -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 }); +} diff --git a/pages/api - Kopie/gis-proxy.js b/pages/api - Kopie/gis-proxy.js new file mode 100644 index 000000000..b76883298 --- /dev/null +++ b/pages/api - Kopie/gis-proxy.js @@ -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") || ""; + }); +}; diff --git a/pages/api - Kopie/linesColorApi.js b/pages/api - Kopie/linesColorApi.js new file mode 100644 index 000000000..57ee59262 --- /dev/null +++ b/pages/api - Kopie/linesColorApi.js @@ -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); +} diff --git a/pages/api - Kopie/rights.js b/pages/api - Kopie/rights.js new file mode 100644 index 000000000..507228147 --- /dev/null +++ b/pages/api - Kopie/rights.js @@ -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: [] }); + } +} diff --git a/pages/api - Kopie/talas5/area.js b/pages/api - Kopie/talas5/area.js new file mode 100644 index 000000000..9205aa5ca --- /dev/null +++ b/pages/api - Kopie/talas5/area.js @@ -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(); + }); + }); +} diff --git a/pages/api - Kopie/talas5/location_device.js b/pages/api - Kopie/talas5/location_device.js new file mode 100644 index 000000000..9292690e0 --- /dev/null +++ b/pages/api - Kopie/talas5/location_device.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas5/webserviceMap/GisStationsMeasurements.js b/pages/api - Kopie/talas5/webserviceMap/GisStationsMeasurements.js new file mode 100644 index 000000000..5aba69fc6 --- /dev/null +++ b/pages/api - Kopie/talas5/webserviceMap/GisStationsMeasurements.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api - Kopie/talas5/webserviceMap/GisStationsStaticDistrict.js b/pages/api - Kopie/talas5/webserviceMap/GisStationsStaticDistrict.js new file mode 100644 index 000000000..bf302f3d7 --- /dev/null +++ b/pages/api - Kopie/talas5/webserviceMap/GisStationsStaticDistrict.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api - Kopie/talas5/webserviceMap/GisStationsStatusDistrict.js b/pages/api - Kopie/talas5/webserviceMap/GisStationsStatusDistrict.js new file mode 100644 index 000000000..ae7c25bde --- /dev/null +++ b/pages/api - Kopie/talas5/webserviceMap/GisStationsStatusDistrict.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas5/webserviceMap/GisSystemStatic.js b/pages/api - Kopie/talas5/webserviceMap/GisSystemStatic.js new file mode 100644 index 000000000..b2fb56635 --- /dev/null +++ b/pages/api - Kopie/talas5/webserviceMap/GisSystemStatic.js @@ -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'); + } +}; \ No newline at end of file diff --git a/pages/api - Kopie/talas5/webserviceMap/gisStationsMeasurementsSQL.js b/pages/api - Kopie/talas5/webserviceMap/gisStationsMeasurementsSQL.js new file mode 100644 index 000000000..90c535086 --- /dev/null +++ b/pages/api - Kopie/talas5/webserviceMap/gisStationsMeasurementsSQL.js @@ -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); + }); +} diff --git a/pages/api - Kopie/talas_v5_DB/gisLines/readGisLines.js b/pages/api - Kopie/talas_v5_DB/gisLines/readGisLines.js new file mode 100644 index 000000000..b73448205 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/gisLines/readGisLines.js @@ -0,0 +1,50 @@ +// /pages/api/talas_v5_DB/gisLines/readGisLines.js +import mysql from "mysql2/promise"; +import { store } from "../../../redux/store"; // Redux-Store importieren + +// 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" }); + } + + // **Hole `idLD`-Werte aus Redux** + const state = store.getState(); + const activeLines = state.lineVisibility.activeLines; + const activeIds = Object.keys(activeLines); // Alle `idLD` in Redux + + if (activeIds.length === 0) { + return res.status(404).json({ error: "Keine aktiven Geräte in Redux gefunden" }); + } + + // **SQL-Query mit Filterung** + const query = ` + SELECT * + FROM talas_v5.gis_lines + WHERE idLD IN (${activeIds.map(() => "?").join(",")});`; + + try { + console.log("🔍 Aktive Linien in Redux:", activeIds); + const [results] = await pool.query(query, activeIds); // Verwende aktive `idLD` als Parameter + if (results.length > 0) { + res.status(200).json(results); + console.log("✅ GIS-Linien erfolgreich abgerufen:", results.length, "Linien gefunden."); + } else { + res.status(404).json({ error: "Keine passenden Linien gefunden" }); + } + } catch (error) { + console.error("Fehler beim Abrufen der gis_lines:", error); + res.status(500).json({ error: "Fehler beim Abrufen der gis_lines" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/gisLines/updateLineCoordinates.js b/pages/api - Kopie/talas_v5_DB/gisLines/updateLineCoordinates.js new file mode 100644 index 000000000..4271160a0 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/gisLines/updateLineCoordinates.js @@ -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(); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/locationDevice/getDeviceId.js b/pages/api - Kopie/talas_v5_DB/locationDevice/getDeviceId.js new file mode 100644 index 000000000..8b2326316 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/locationDevice/getDeviceId.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/locationDevice/locationDeviceNameById.js b/pages/api - Kopie/talas_v5_DB/locationDevice/locationDeviceNameById.js new file mode 100644 index 000000000..575541547 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/locationDevice/locationDeviceNameById.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/locationDevice/locationDevices.js b/pages/api - Kopie/talas_v5_DB/locationDevice/locationDevices.js new file mode 100644 index 000000000..082dc2929 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/locationDevice/locationDevices.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/poiTyp/readPoiTyp.js b/pages/api - Kopie/talas_v5_DB/poiTyp/readPoiTyp.js new file mode 100644 index 000000000..baff8f83d --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/poiTyp/readPoiTyp.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/addLocation.js b/pages/api - Kopie/talas_v5_DB/pois/addLocation.js new file mode 100644 index 000000000..864835647 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/addLocation.js @@ -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`); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/deletePoi.js b/pages/api - Kopie/talas_v5_DB/pois/deletePoi.js new file mode 100644 index 000000000..e9132bd6b --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/deletePoi.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/getPoiById.js b/pages/api - Kopie/talas_v5_DB/pois/getPoiById.js new file mode 100644 index 000000000..3bd2f1023 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/getPoiById.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/poi-icons.js b/pages/api - Kopie/talas_v5_DB/pois/poi-icons.js new file mode 100644 index 000000000..407704538 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/poi-icons.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/readLocations.js b/pages/api - Kopie/talas_v5_DB/pois/readLocations.js new file mode 100644 index 000000000..308de78af --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/readLocations.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/pois/updateLocation.js b/pages/api - Kopie/talas_v5_DB/pois/updateLocation.js new file mode 100644 index 000000000..ee61070f2 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/updateLocation.js @@ -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(); + } +} */ diff --git a/pages/api - Kopie/talas_v5_DB/pois/updatePoi.js b/pages/api - Kopie/talas_v5_DB/pois/updatePoi.js new file mode 100644 index 000000000..bc3356a2f --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/pois/updatePoi.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/priorityConfig.js b/pages/api - Kopie/talas_v5_DB/priorityConfig.js new file mode 100644 index 000000000..719007020 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/priorityConfig.js @@ -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" }); + } +} diff --git a/pages/api - Kopie/talas_v5_DB/station/getAllStationsNames.js b/pages/api - Kopie/talas_v5_DB/station/getAllStationsNames.js new file mode 100644 index 000000000..0d5d5ca05 --- /dev/null +++ b/pages/api - Kopie/talas_v5_DB/station/getAllStationsNames.js @@ -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" }); + } +} diff --git a/pages/api back30/[...path].js b/pages/api back30/[...path].js new file mode 100644 index 000000000..0578e8448 --- /dev/null +++ b/pages/api back30/[...path].js @@ -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 +}); diff --git a/pages/api back30/get-talasIP.js b/pages/api back30/get-talasIP.js new file mode 100644 index 000000000..1216fbbb7 --- /dev/null +++ b/pages/api back30/get-talasIP.js @@ -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 }); +} diff --git a/pages/api back30/gis-proxy.js b/pages/api back30/gis-proxy.js new file mode 100644 index 000000000..b76883298 --- /dev/null +++ b/pages/api back30/gis-proxy.js @@ -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") || ""; + }); +}; diff --git a/pages/api back30/linesColorApi.js b/pages/api back30/linesColorApi.js new file mode 100644 index 000000000..57ee59262 --- /dev/null +++ b/pages/api back30/linesColorApi.js @@ -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); +} diff --git a/pages/api back30/rights.js b/pages/api back30/rights.js new file mode 100644 index 000000000..507228147 --- /dev/null +++ b/pages/api back30/rights.js @@ -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: [] }); + } +} diff --git a/pages/api back30/talas5/area.js b/pages/api back30/talas5/area.js new file mode 100644 index 000000000..9205aa5ca --- /dev/null +++ b/pages/api back30/talas5/area.js @@ -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(); + }); + }); +} diff --git a/pages/api back30/talas5/location_device.js b/pages/api back30/talas5/location_device.js new file mode 100644 index 000000000..8c956f459 --- /dev/null +++ b/pages/api back30/talas5/location_device.js @@ -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(); + }); + }); +} diff --git a/pages/api back30/talas5/webserviceMap/GisStationsMeasurements.js b/pages/api back30/talas5/webserviceMap/GisStationsMeasurements.js new file mode 100644 index 000000000..5aba69fc6 --- /dev/null +++ b/pages/api back30/talas5/webserviceMap/GisStationsMeasurements.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api back30/talas5/webserviceMap/GisStationsStaticDistrict.js b/pages/api back30/talas5/webserviceMap/GisStationsStaticDistrict.js new file mode 100644 index 000000000..bf302f3d7 --- /dev/null +++ b/pages/api back30/talas5/webserviceMap/GisStationsStaticDistrict.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api back30/talas5/webserviceMap/GisStationsStatusDistrict.js b/pages/api back30/talas5/webserviceMap/GisStationsStatusDistrict.js new file mode 100644 index 000000000..9d0f2024c --- /dev/null +++ b/pages/api back30/talas5/webserviceMap/GisStationsStatusDistrict.js @@ -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(); + } + } +} diff --git a/pages/api back30/talas5/webserviceMap/GisSystemStatic.js b/pages/api back30/talas5/webserviceMap/GisSystemStatic.js new file mode 100644 index 000000000..b2fb56635 --- /dev/null +++ b/pages/api back30/talas5/webserviceMap/GisSystemStatic.js @@ -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'); + } +}; \ No newline at end of file diff --git a/pages/api back30/talas5/webserviceMap/gisStationsMeasurementsSQL.js b/pages/api back30/talas5/webserviceMap/gisStationsMeasurementsSQL.js new file mode 100644 index 000000000..de3670b6d --- /dev/null +++ b/pages/api back30/talas5/webserviceMap/gisStationsMeasurementsSQL.js @@ -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); + }); +} \ No newline at end of file diff --git a/pages/api back30/talas_v5_DB/gisLines/readGisLines.js b/pages/api back30/talas_v5_DB/gisLines/readGisLines.js new file mode 100644 index 000000000..7d8900a83 --- /dev/null +++ b/pages/api back30/talas_v5_DB/gisLines/readGisLines.js @@ -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" }); + } + }); +} diff --git a/pages/api back30/talas_v5_DB/gisLines/updateLineCoordinates.js b/pages/api back30/talas_v5_DB/gisLines/updateLineCoordinates.js new file mode 100644 index 000000000..48dfa36bc --- /dev/null +++ b/pages/api back30/talas_v5_DB/gisLines/updateLineCoordinates.js @@ -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, + }); + }); + }); + }); +} diff --git a/pages/api back30/talas_v5_DB/locationDevice/getDeviceId.js b/pages/api back30/talas_v5_DB/locationDevice/getDeviceId.js new file mode 100644 index 000000000..fa373c80c --- /dev/null +++ b/pages/api back30/talas_v5_DB/locationDevice/getDeviceId.js @@ -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" }); + } + }); +} diff --git a/pages/api back30/talas_v5_DB/locationDevice/locationDeviceNameById.js b/pages/api back30/talas_v5_DB/locationDevice/locationDeviceNameById.js new file mode 100644 index 000000000..efccd89d9 --- /dev/null +++ b/pages/api back30/talas_v5_DB/locationDevice/locationDeviceNameById.js @@ -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" }); + } +} diff --git a/pages/api back30/talas_v5_DB/locationDevice/locationDevices.js b/pages/api back30/talas_v5_DB/locationDevice/locationDevices.js new file mode 100644 index 000000000..bfaf57654 --- /dev/null +++ b/pages/api back30/talas_v5_DB/locationDevice/locationDevices.js @@ -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); + }); +} diff --git a/pages/api back30/talas_v5_DB/poiTyp/readPoiTyp.js b/pages/api back30/talas_v5_DB/poiTyp/readPoiTyp.js new file mode 100644 index 000000000..062c442cd --- /dev/null +++ b/pages/api back30/talas_v5_DB/poiTyp/readPoiTyp.js @@ -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`); + } +} diff --git a/pages/api back30/talas_v5_DB/pois/addLocation.js b/pages/api back30/talas_v5_DB/pois/addLocation.js new file mode 100644 index 000000000..118704d7d --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/addLocation.js @@ -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`); + } +} diff --git a/pages/api back30/talas_v5_DB/pois/deletePoi.js b/pages/api back30/talas_v5_DB/pois/deletePoi.js new file mode 100644 index 000000000..780a1b755 --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/deletePoi.js @@ -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" }); + } + }); +} diff --git a/pages/api back30/talas_v5_DB/pois/getPoiById.js b/pages/api back30/talas_v5_DB/pois/getPoiById.js new file mode 100644 index 000000000..4ebf5b62c --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/getPoiById.js @@ -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`); + } +} diff --git a/pages/api back30/talas_v5_DB/pois/poi-icons.js b/pages/api back30/talas_v5_DB/pois/poi-icons.js new file mode 100644 index 000000000..ee092c226 --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/poi-icons.js @@ -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" }); + } + }); +} diff --git a/pages/api back30/talas_v5_DB/pois/readLocations.js b/pages/api back30/talas_v5_DB/pois/readLocations.js new file mode 100644 index 000000000..98a33cc88 --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/readLocations.js @@ -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(); + }); + }); +} diff --git a/pages/api back30/talas_v5_DB/pois/updateLocation.js b/pages/api back30/talas_v5_DB/pois/updateLocation.js new file mode 100644 index 000000000..625be5a75 --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/updateLocation.js @@ -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(); + } +} diff --git a/pages/api back30/talas_v5_DB/pois/updatePoi.js b/pages/api back30/talas_v5_DB/pois/updatePoi.js new file mode 100644 index 000000000..0eb9eeed3 --- /dev/null +++ b/pages/api back30/talas_v5_DB/pois/updatePoi.js @@ -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" }); + } + }); +} diff --git a/pages/api back30/talas_v5_DB/priorityConfig.js b/pages/api back30/talas_v5_DB/priorityConfig.js new file mode 100644 index 000000000..06bfefe3d --- /dev/null +++ b/pages/api back30/talas_v5_DB/priorityConfig.js @@ -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(); + }); + }); +} diff --git a/pages/api/[...path].js b/pages/api/[...path].js index f62638598..b270661b1 100644 --- a/pages/api/[...path].js +++ b/pages/api/[...path].js @@ -1,13 +1,13 @@ // pages/api/[...path].js 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 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: `${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 diff --git a/pages/api/talas5/area.js b/pages/api/talas5/area.js new file mode 100644 index 000000000..69f571c97 --- /dev/null +++ b/pages/api/talas5/area.js @@ -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 + } +} diff --git a/pages/api/talas5/webserviceMap/GisStationsMeasurements.js b/pages/api/talas5/webserviceMap/GisStationsMeasurements.js new file mode 100644 index 000000000..5aba69fc6 --- /dev/null +++ b/pages/api/talas5/webserviceMap/GisStationsMeasurements.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js b/pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js new file mode 100644 index 000000000..bf302f3d7 --- /dev/null +++ b/pages/api/talas5/webserviceMap/GisStationsStaticDistrict.js @@ -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'); + } + }; \ No newline at end of file diff --git a/pages/api/talas5/webserviceMap/GisStationsStatusDistrict.js b/pages/api/talas5/webserviceMap/GisStationsStatusDistrict.js new file mode 100644 index 000000000..27b0b442b --- /dev/null +++ b/pages/api/talas5/webserviceMap/GisStationsStatusDistrict.js @@ -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(); + } +} diff --git a/pages/api/talas5/webserviceMap/GisSystemStatic.js b/pages/api/talas5/webserviceMap/GisSystemStatic.js new file mode 100644 index 000000000..b2fb56635 --- /dev/null +++ b/pages/api/talas5/webserviceMap/GisSystemStatic.js @@ -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'); + } +}; \ No newline at end of file diff --git a/pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js b/pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js new file mode 100644 index 000000000..7912816d4 --- /dev/null +++ b/pages/api/talas5/webserviceMap/gisStationsMeasurementsSQL.js @@ -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); + }); +} diff --git a/pages/index.js b/pages/index.js index f919db412..35513d35d 100644 --- a/pages/index.js +++ b/pages/index.js @@ -1,3 +1,4 @@ +"use client"; import React, { useEffect, useState } from "react"; import dynamic from "next/dynamic"; import { useRecoilState, useRecoilValue } from "recoil"; @@ -5,7 +6,6 @@ import { readPoiMarkersStore } from "../redux/slices/readPoiMarkersStoreSlice.js import { poiReadFromDbTriggerAtom } from "../redux/slices/poiReadFromDbTriggerSlice"; const MapComponentWithNoSSR = dynamic(() => import("../components/MapComponent"), { ssr: false }); -// TestScript ohne SSR const TestScriptWithNoSSR = dynamic(() => import("../components/TestScript"), { ssr: false }); export default function Home() { @@ -14,6 +14,7 @@ export default function Home() { const [mParam, setMParam] = useState(""); const [uParam, setUParam] = useState(""); + // Daten abrufen const loadData = async () => { try { 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(() => { + let isMounted = true; + function getURLParameter(name) { const params = new URLSearchParams(window.location.search); return params.get(name); } + setMParam(getURLParameter("m")); setUParam(getURLParameter("u")); - loadData(); - }, [poiReadTrigger]); + const fetchData = async () => { + 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) => { try { const response = await fetch("/api/talas_v5_DB/pois/addLocation", { @@ -48,21 +64,17 @@ export default function Home() { if (!response.ok) { throw new Error("Fehler beim Hinzufügen des Standorts"); } - //console.log("Standort erfolgreich hinzugefügt"); loadData(); } catch (error) { console.error(error.message); } }; + // Standort aktualisieren const handleLocationUpdate = (id, newLatitude, newLongitude) => { setLocations((prevLocations) => prevLocations.map((location) => (location.idPoi === id ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` } : location))); }; - useEffect(() => { - loadData(); - }, [poiReadTrigger]); - return (
diff --git a/redux/actions.js b/redux/actions.js deleted file mode 100644 index d147d7d35..000000000 --- a/redux/actions.js +++ /dev/null @@ -1,9 +0,0 @@ -// /redux/actions.js -export const connectWebSocket = (url) => ({ - type: "WS_CONNECT", - payload: { url }, -}); - -export const disconnectWebSocket = () => ({ - type: "WS_DISCONNECT", -}); diff --git a/redux/reducer.js b/redux/reducer.js deleted file mode 100644 index 2d75946d6..000000000 --- a/redux/reducer.js +++ /dev/null @@ -1,11 +0,0 @@ -// redux/reducer.js -import { combineReducers } from "redux"; -import currentPoiReducer from "./slices/currentPoiSlice"; -import gisStationsStaticDistrictReducer from "./slices/gisStationsStaticDistrictSlice"; - -const rootReducer = combineReducers({ - currentPoi: currentPoiReducer, - gisStationsStaticDistrict: gisStationsStaticDistrictReducer, -}); - -export default rootReducer; diff --git a/redux/slices/lineVisibilitySlice.js b/redux/slices/lineVisibilitySlice.js new file mode 100644 index 000000000..c2e8ca775 --- /dev/null +++ b/redux/slices/lineVisibilitySlice.js @@ -0,0 +1,23 @@ +// /rdux/slices/lineVisibilitySlice.js +import { createSlice } from "@reduxjs/toolkit"; + +const initialState = { + activeLines: {}, // Speichert `idLD -> Active` +}; + +const lineVisibilitySlice = createSlice({ + name: "lineVisibility", + initialState, + reducers: { + updateLineStatus(state, action) { + const { idLD, active } = action.payload; + state.activeLines[idLD] = active; // Speichert `idLD` in Redux + }, + setActiveLines(state, action) { + state.activeLines = action.payload; + }, + }, +}); + +export const { updateLineStatus, setActiveLines } = lineVisibilitySlice.actions; +export default lineVisibilitySlice.reducer; diff --git a/redux/slices/poiReadFromDbTriggerSlice.js b/redux/slices/poiReadFromDbTriggerSlice.js index 4c6c36996..ba59a3c30 100644 --- a/redux/slices/poiReadFromDbTriggerSlice.js +++ b/redux/slices/poiReadFromDbTriggerSlice.js @@ -1,7 +1,15 @@ // redux/slices/poiReadFromDbTriggerSlice.js -import { atom } from 'recoil'; +import { atom } from "recoil"; -export const poiReadFromDbTriggerAtom = atom({ - key: 'poiReadFromDbTriggerAtom', - default: 0, // Sie können auch einen booleschen Wert verwenden -}); +const atomKey = "poiReadFromDbTriggerAtom"; + +export const poiReadFromDbTriggerAtom = + globalThis.poiReadFromDbTriggerAtom || + atom({ + key: atomKey, + default: 0, + }); + +if (process.env.NODE_ENV !== "production") { + globalThis.poiReadFromDbTriggerAtom = poiReadFromDbTriggerAtom; +} diff --git a/redux/slices/readPoiMarkersStoreSlice.js b/redux/slices/readPoiMarkersStoreSlice.js index 7748fae02..89d7d45cc 100644 --- a/redux/slices/readPoiMarkersStoreSlice.js +++ b/redux/slices/readPoiMarkersStoreSlice.js @@ -1,7 +1,17 @@ //redux/slices/readPoiMarkersStoreSlice.js -import { atom } from 'recoil'; +import { atom } from "recoil"; -export const readPoiMarkersStore = atom({ - key: 'readPoiMarkersStore', - default: [], -}); \ No newline at end of file +const storeKey = "readPoiMarkersStore"; + +// 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; +} diff --git a/redux/store.js b/redux/store.js index b41afa444..b231f13df 100644 --- a/redux/store.js +++ b/redux/store.js @@ -1,10 +1,12 @@ import { configureStore } from "@reduxjs/toolkit"; -import websocketMiddleware from "./middleware/websocketMiddleware"; -import rootReducer from "./reducer"; +import lineVisibilityReducer from "./slices/lineVisibilitySlice"; +import currentPoiReducer from "./slices/currentPoiSlice"; +import gisStationsStaticDistrictReducer from "./slices/gisStationsStaticDistrictSlice"; -const store = configureStore({ - reducer: rootReducer, // Kombinierter Root-Reducer - middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(websocketMiddleware), +export const store = configureStore({ + reducer: { + lineVisibility: lineVisibilityReducer, + currentPoi: currentPoiReducer, + gisStationsStaticDistrict: gisStationsStaticDistrictReducer, + }, }); - -export default store; diff --git a/services/apiService.js b/services/apiService.js index be6921939..930a9565f 100644 --- a/services/apiService.js +++ b/services/apiService.js @@ -1,8 +1,6 @@ // services/apiService.js import * as config from "../config/config"; -import SERVER_URL from "../config/urls"; -const url = new URL(window.location.origin); -const originWithoutPort = `${url.protocol}//${url.hostname}`; +import * as urls from "../config/urls"; let timeoutId; @@ -23,22 +21,19 @@ const fetchWithTimeout = async (url, options, timeout = 5000) => { } }; -export const fetchGisStatusStations = async () => { - //idMap und idUser von URL Parameter hersuslesen - const idMap = url.searchParams.get("m"); - const idUser = url.searchParams.get("u"); +export const fetchGisStatusStations = async (idMap, idUser) => { // Verhindere wiederholte schnelle API-Aufrufe durch Debouncing if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(async () => { - //const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL; + const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL; try { // Verwende das Timeout für die API-Anfrage 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", headers: { @@ -141,13 +136,6 @@ export const fetchDeviceNameById = async (idLD) => { // ---------------------------------------------- // services/apiService.js 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 let userRightsRequestCount = localStorage.getItem("userRightsRequestCount") || 0; userRightsRequestCount++; @@ -155,16 +143,7 @@ export const fetchUserRights = async () => { console.log(`fetchUserRights wurde ${userRightsRequestCount} Mal aufgerufen.`); try { - // Basis-URL ohne Port abrufen - 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}`, { + const response = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${config.idMap}&idUser=${config.idUser}`, { method: "GET", headers: { Connection: "close", @@ -182,7 +161,7 @@ export const fetchUserRights = async () => { 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); return userRightsIds; diff --git a/utils/createAndSetDevices.js b/utils/createAndSetDevices.js index 69a8814fe..6218166a3 100644 --- a/utils/createAndSetDevices.js +++ b/utils/createAndSetDevices.js @@ -1,162 +1,133 @@ // /utils/createAndSetDevices.js import L from "leaflet"; import "leaflet.smooth_marker_bouncing"; -import { SERVER_URL } from "../config/urls.js"; +import { toast } from "react-toastify"; import * as config from "../config/config.js"; +import { disablePolylineEvents, enablePolylineEvents } from "./setupPolylines"; +//import { setPolylineEventsDisabled } from "../store/atoms/polylineEventsDisabledState"; +import { store } from "../redux/store"; +import { updateLineStatus } from "../redux/slices/lineVisibilitySlice"; -// Variable zum Speichern der Prioritätskonfiguration (z.B. Level und Farben) -let priorityConfig = []; - -// Funktion zum Abrufen der Prioritätsdaten von der API -const fetchPriorityConfig = async () => { - try { - // Ruft die API auf, um die Prioritätsdaten zu laden - const response = await fetch(`${SERVER_URL}:3000/api/prio`); - - // Konvertiert die Antwort in ein JSON-Format - const data = await response.json(); - - // Gibt die empfangenen Daten in der Konsole aus, um die Struktur zu überprüfen - // console.log("Prioritätsdaten: ", data); - - // Speichert die empfangenen Prioritätsdaten in der Variablen priorityConfig - priorityConfig = data; - } catch (error) { - // Gibt einen Fehler in der Konsole aus, falls die API nicht erreichbar ist - console.error("Fehler beim Abrufen der Prioritätsdaten: ", error); +const determinePriority = (iconPath, priorityConfig) => { + for (let priority of priorityConfig) { + if (iconPath.includes(priority.name.toLowerCase())) { + return priority.level; + } } + return 5; }; -// Funktion zur Bestimmung der Farbe basierend auf dem Level -const getColorClass = (level) => { - // Sucht in priorityConfig nach einem Objekt, dessen level-Wert dem übergebenen Level entspricht - const priority = priorityConfig.find((p) => p.level === level); - - // Gibt die Farbe zurück, wenn das Level gefunden wurde, ansonsten die Standardfarbe (#999999) - return priority ? priority.color : "#999999"; // Fallback-Farbe, wenn kein Level gefunden wurde -}; - -/* // Ruft die Funktion zum Abrufen der Prioritätsdaten auf und wartet, bis sie abgeschlossen ist -fetchPriorityConfig().then(() => { - // Gibt die geladenen Prioritätsdaten in der Konsole aus, um zu überprüfen, ob die Daten korrekt geladen wurden - console.log("Prioritätsdaten wurden geladen:", priorityConfig); - - // Testet die Funktion getColorClass für verschiedene Level und gibt die entsprechenden Farben aus - console.log("Farbe für Level 0:", getColorClass(0)); // Farbe für Level 0 anzeigen - console.log("Farbe für Level 1:", getColorClass(1)); // Farbe für Level 1 anzeigen - console.log("Farbe für Level 2:", getColorClass(2)); // Farbe für Level 2 anzeigen - console.log("Farbe für Level 3:", getColorClass(3)); // Farbe für Level 3 anzeigen - console.log("Farbe für Level 4:", getColorClass(4)); // Farbe für Level 4 anzeigen - console.log("Farbe für Level 100:", getColorClass(100)); // Farbe für Level 100 anzeigen - console.log("Farbe für Level 101:", getColorClass(101)); // Farbe für Level 101 anzeigen -}); */ - -// Funktion zum Erstellen und Setzen von Markern -// Funktion zum Erstellen und Setzen von Markern -export const createAndSetDevices = async (systemId, setMarkersFunction, GisSystemStatic) => { +export const createAndSetDevices = async (systemId, setMarkersFunction, GisSystemStatic, priorityConfig) => { try { - // Lade die statischen Daten const response1 = await fetch(config.mapGisStationsStaticDistrictUrl); const jsonResponse = await response1.json(); const response2 = await fetch(config.mapGisStationsStatusDistrictUrl); const statusResponse = await response2.json(); - //console.log("statusResponse: ", statusResponse); - const getIdSystemAndAllowValueMap = new Map(GisSystemStatic.map((system) => [system.IdSystem, system.Allow])); + if (!jsonResponse.Points || !statusResponse.Statis) { + console.error("❌ Fehlende Daten in API-Response!"); + return; + } - if (jsonResponse.Points && statusResponse.Statis) { - const statisMap = new Map(statusResponse.Statis.map((s) => [s.IdLD, { color: s.Co, level: s.Le }])); + console.log("✅ API-Daten geladen:", jsonResponse.Points.length, "Punkte gefunden."); - // console.log("idLD , Farbe und Level: ", statisMap); + // Erstelle eine Map für Statusinformationen + 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) => { - // Statusdaten für die Station abrufen - const statisForStation = statusResponse.Statis.filter((status) => status.IdLD === station.IdLD); + // Speichere `idLD` und `Active` Werte in Redux + const allLines = jsonResponse.Points.filter((station) => station.System === systemId).map((station) => { + console.log("------------------------"); + console.log("station.IdLD: ", station.IdLD); + console.log("station.Active: ", station.Active); + console.log("------------------------"); - // Niedrigstes Level ermitteln - const minLevel = Math.min(...statisForStation.map((status) => status.Le)); + // Redux: Aktualisiere `idLD` und `Active` Werte + store.dispatch(updateLineStatus({ idLD: station.IdLD, active: station.Active })); - // Farbe für das niedrigste Level bestimmen - const color = getColorClass(minLevel); // Farbe anhand des Levels + return { + idLD: station.IdLD, + active: station.Active, + }; + }); - //console.log(`Station: ${station.LD_Name}, Min Level: ${minLevel}, Color: ${color}`); - const statisData = statisMap.get(station.IdLD); // Hole Farbe und Level - const outerColor = statisData ? statisData.color : "#008013"; // Dynamische Farbe oder Standard-Grün - const innerColor = "rgba(255, 255, 255, 0.8)"; // Weiß mit 80% Deckkraft + console.log("🔄 Alle Linien gespeichert:", allLines); - const marker = L.marker([station.X, station.Y], { - icon: L.divIcon({ - className: `custom-marker`, - html: ` -
- - - - - - - - - - -
`, - iconSize: [30, 45], - iconAnchor: [27, 41], - popupAnchor: [1, -34], - }), - areaName: station.Area_Name, // Stelle sicher, dass dieser Bereich gesetzt wird - link: station.Link, + // Filtere nur aktive Stationen für Marker + const activeStations = jsonResponse.Points.filter((station) => station.System === systemId && station.Active === 1); + console.log("🔍 Gefilterte aktive Stationen:", activeStations); - zIndexOffset: 100 * (6 - minLevel), - }); + let markersData = activeStations.map((station) => { + const statis = statisMap.get(station.IdLD); + const iconPath = statis ? `img/icons/${statis.Na}-marker-icon-${station.Icon}.png` : `img/icons/marker-icon-${station.Icon}.png`; - // Popup-Info dynamisch erstellen - const statusInfo = statisForStation - .map( - (status) => ` -
-
- ${status.Me} (${status.Na}) -
- ` - ) - .join(""); + const priority = determinePriority(iconPath, priorityConfig); + const zIndexOffset = 100 * (5 - priority); - marker.bindPopup(` -
- ${station.LD_Name} - ${station.Device}
- ${station.Area_Short} (${station.Area_Name})
- ${station.Location_Short} (${station.Location_Name}) -
${statusInfo}
-
- `); - - // **Mouseover zeigt Popup** - marker.on("mouseover", function () { - this.openPopup(); - }); - - // **Mouseout schließt Popup** - marker.on("mouseout", function () { - this.closePopup(); - }); - - return marker; + const marker = L.marker([station.X, station.Y], { + icon: L.icon({ + iconUrl: iconPath, + iconSize: [25, 41], + iconAnchor: [12, 41], + popupAnchor: [1, -34], + }), + areaName: station.Area_Name, + link: station.Link, + zIndexOffset: zIndexOffset, }); - setMarkersFunction(markersData); - } + marker.bindPopup(` +
+ ${station.LD_Name} + ${station.Device}
+ ${station.Area_Short} (${station.Area_Name})
+ ${station.Location_Short} (${station.Location_Name}) +
+ ${statusResponse.Statis.filter((status) => status.IdLD === station.IdLD) + .reverse() + .map( + (status) => ` +
+
+ ${status.Me} (${status.Na}) +
+ ` + ) + .join("")} +
+
+ `); + + marker.on("mouseover", function () { + this.openPopup(); + }); + + marker.on("mouseout", function () { + this.closePopup(); + }); + + marker.on("contextmenu", function (event) { + if (event && event.preventDefault) event.preventDefault(); + this.openPopup(); + }); + + document.addEventListener("mouseout", function (event) { + if (event.relatedTarget === null || event.relatedTarget.nodeName === "BODY") { + enablePolylineEvents(window.polylines, window.lineColors); + } + }); + + if (typeof marker.bounce === "function" && statis) { + marker.on("add", () => marker.bounce(3)); + } + + return marker; + }); + + console.log("📌 Marker erstellt:", markersData.length, markersData); + + setMarkersFunction(markersData); } catch (error) { - console.error("Fehler beim Abrufen der Daten: ", error); + console.error("❌ Fehler beim Abrufen der Daten in createAndSetDevices.js: ", error); } }; diff --git a/utils/mapUtils.js b/utils/mapUtils.js index 1250bb44c..89d13493b 100644 --- a/utils/mapUtils.js +++ b/utils/mapUtils.js @@ -1,41 +1,6 @@ // /utils/mapUtils.js import L from "leaflet"; -export const redrawPolyline = (lineData, lineColors, tooltipContents, map) => { - if (!lineData || !lineColors || !tooltipContents || !map) { - console.error("Invalid parameters for redrawPolyline"); - return; - } - - if (!lineData.coordinates || !Array.isArray(lineData.coordinates)) { - console.error("Invalid coordinates in lineData"); - return; - } - - const color = lineColors[lineData.idModul] || "#000000"; - const tooltipContent = tooltipContents[lineData.idModul] || "Standard-Tooltip-Inhalt"; - - if (lineData.polyline) map.removeLayer(lineData.polyline); - - lineData.polyline = L.polyline(lineData.coordinates, { - color: color, - }).addTo(map); - - lineData.polyline.bindTooltip(tooltipContent, { - permanent: false, - direction: "auto", - }); - - lineData.polyline.on("mouseover", () => { - lineData.polyline.setStyle({ weight: 10 }); - lineData.polyline.bringToFront(); - }); - - lineData.polyline.on("mouseout", () => { - lineData.polyline.setStyle({ weight: 5 }); - }); -}; - export const saveLineData = (lineData) => { fetch("/api/talas_v5_DB/gisLines/updateLineCoordinates", { method: "POST", @@ -86,7 +51,8 @@ export const checkOverlappingMarkers = (map, markers, plusIcon) => { // Gruppiere Marker basierend auf ihrer Position markers.forEach((marker) => { - if (map.hasLayer(marker)) { // Überprüfen, ob der Marker sichtbar ist + if (map.hasLayer(marker)) { + // Überprüfen, ob der Marker sichtbar ist const latlngStr = marker.getLatLng().toString(); if (overlappingGroups[latlngStr]) { overlappingGroups[latlngStr].push(marker); @@ -133,7 +99,6 @@ export const checkOverlappingMarkers = (map, markers, plusIcon) => { } }; - export const handlePlusIconClick = (map, markers, oms, clickedLatLng) => { // Debugging-Ausgabe console.log("Plus-Icon Position:", clickedLatLng); diff --git a/utils/mysqlPool.js b/utils/mysqlPool.js index d9cc249fd..80b5f98ef 100644 --- a/utils/mysqlPool.js +++ b/utils/mysqlPool.js @@ -7,7 +7,7 @@ let connectionCount = 0; // Zähler für die aktiven Verbindungen function getPool() { if (!cachedPool) { cachedPool = mysql.createPool({ - host: "127.0.0.1", + host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, diff --git a/utils/setupPOIs.js b/utils/setupPOIs.js index 7aa30d322..7abc7c945 100644 --- a/utils/setupPOIs.js +++ b/utils/setupPOIs.js @@ -83,9 +83,7 @@ export const setupPOIs = async ( `); marker.on("mouseover", function () { - //loaclStorage benutzen statt console.log - //console.log("Device Name:", marker); // Debugging - localStorage.setItem("deviceName", marker.options.name); + console.log("Device Name:", marker); // Debugging handlePoiSelect( { id: location.idPoi, diff --git a/utils/setupPolylines copy.js b/utils/setupPolylines copy.js new file mode 100644 index 000000000..7e28edeeb --- /dev/null +++ b/utils/setupPolylines copy.js @@ -0,0 +1,423 @@ +// 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 }); + }); + }); +} +// Funktion zum Schließen des Kontextmenüs und Entfernen der Markierung +function closePolylineSelectionAndContextMenu(map) { + try { + // Entferne alle markierten Polylinien + if (window.selectedPolyline) { + window.selectedPolyline.setStyle({ weight: 3 }); // Originalstil wiederherstellen + window.selectedPolyline = null; + } + + // Überprüfe, ob map und map.contextmenu definiert sind + if (map && map.contextmenu) { + map.contextmenu.hide(); // Kontextmenü schließen + } else { + console.warn("Kontextmenü ist nicht verfügbar."); + } + } catch (error) { + console.error("Fehler beim Schließen des Kontextmenüs:", error); + window.location.reload(); + } + + // Countdown-Status zurücksetzen + localStorage.removeItem("contextMenuCountdown"); + localStorage.removeItem("contextMenuExpired"); +} + +// Überprüft regelmäßig den Status in localStorage +function monitorContextMenu(map) { + setInterval(() => { + const isContextMenuExpired = localStorage.getItem("contextMenuExpired") === "true"; + if (isContextMenuExpired) { + closePolylineSelectionAndContextMenu(map); + localStorage.removeItem("contextMenuExpired"); // Flagge entfernen, um wiederverwendbar zu sein + } + }, 1000); // Alle 1 Sekunde überprüfen +} + +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(); + }, + } + ); + } else { + 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); + }, + } + ); + } + + // 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; + monitorContextMenu(map); + return { markers, polylines }; +}; diff --git a/utils/setupPolylines.js b/utils/setupPolylines.js index 9cc8f418b..8abfd3d52 100644 --- a/utils/setupPolylines.js +++ b/utils/setupPolylines.js @@ -12,11 +12,7 @@ import { openInNewTab } from "./openInNewTab"; import { toast } from "react-toastify"; import { polylineLayerVisibleState } from "../redux/slices/polylineLayerVisibleSlice"; 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 +import { store } from "../redux/store"; // Importiere den Store // Funktion zum Deaktivieren der Polyline-Ereignisse export function disablePolylineEvents(polylines) { @@ -39,7 +35,7 @@ export function enablePolylineEvents(polylines, lineColors) { polyline.on("mouseover", (e) => { //console.log("Mouseover on polyline", polyline.options); 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("polylineLink", link); }); @@ -87,6 +83,15 @@ function monitorContextMenu(map) { } export const setupPolylines = (map, linePositions, lineColors, tooltipContents, setNewCoords, tempMarker, currentZoom, currentCenter, polylineVisible) => { + // Hole activeLines direkt aus Redux + const state = store.getState(); // Hole den gesamten Zustand + const activeLines = state.lineVisibility.activeLines; // Zugriff auf activeLines + + if (!activeLines) { + console.warn("activeLines ist undefined oder null."); + return { markers: [], polylines: [] }; + } + if (localStorage.getItem("polylineVisible") === null) { localStorage.setItem("polylineVisible", "true"); // Standardwert setzen polylineVisible = true; // Wert in der Funktion initialisieren @@ -110,6 +115,17 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, const editMode = localStorage.getItem("editMode") === "true"; // Prüfen, ob der Bearbeitungsmodus aktiv ist linePositions.forEach((lineData, lineIndex) => { + console.log("LineData:", lineData.idLD, lineData.idModul); + console.log("ActiveLines:", activeLines); + + // **Fix: Sicherstellen, dass activeLines definiert ist und idLD existiert** + const isActive = activeLines && lineData.idLD && activeLines[String(lineData.idLD)] === 1; + + if (!isActive) { + console.warn(`Linie mit idLD ${lineData.idLD} wird ausgeblendet.`); + return; + } + const lineMarkers = []; lineData.coordinates.forEach((coord, index) => { @@ -142,7 +158,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000", }).addTo(map); - updatedPolyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", { + updatedPolyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt setup 1", { permanent: false, direction: "auto", }); @@ -255,7 +271,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, text: "Station öffnen (Tab)", icon: "/img/screen_new.png", 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"); }, }, @@ -314,7 +330,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, text: "Station öffnen (Tab)", icon: "/img/screen_new.png", 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"); }, }, @@ -357,7 +373,7 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, } // Hier wird der Tooltip hinzugefügt - polyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", { + polyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt setup", { permanent: false, direction: "auto", }); @@ -384,11 +400,10 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents, // Jede Sekunde //console.log("Mouseover on polyline", lineData); polyline.setStyle({ weight: 14 }); - const link = `${BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`; - //console.log("Link der Linie:", link); - + 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("Link_der_Linie:", link); + //localStorage.setItem("polylineLink", link); }); polyline.on("mouseout", (e) => { diff --git a/utils/utils.js b/utils/utils.js new file mode 100644 index 000000000..b5d4407c2 --- /dev/null +++ b/utils/utils.js @@ -0,0 +1,211 @@ +// /utils/utils.js +import { useState } from "react"; +import circleIcon from "../components/CircleIcon"; + +export const parsePoint = (position) => { + const [longitude, latitude] = position.slice(6, -1).split(" "); + return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) }; +}; +//---------------------------------------------- + +export const determinePriority = (iconPath) => { + const [priorityConfig, setPriorityConfig] = useState([]); + for (let priority of priorityConfig) { + if (iconPath.includes(priority.name.toLowerCase())) { + return priority.level; + } + } + return 5; // Default priority (lowest) +}; +//---------------------------------------------- +export const createAndSetMarkers = async (systemId, setMarkersFunction) => { + try { + const response1 = await fetch(config.mapGisStationsStaticDistrictUrl); + const jsonResponse = await response1.json(); + const response2 = await fetch(config.mapGisStationsStatusDistrictUrl); + const statusResponse = await response2.json(); + + const getIdSystemAndAllowValueMap = new Map(GisSystemStatic.map((system) => [system.IdSystem, system.Allow])); + //console.log("getIdSystemAndAllowValueMap:", getIdSystemAndAllowValueMap); + + if (jsonResponse.Points && statusResponse.Statis) { + 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) => { + const statis = statisMap.get(station.IdLD); + const iconPath = statis ? `img/icons/${statis.Na}-marker-icon-${station.Icon}.png` : `img/icons/marker-icon-${station.Icon}.png`; + + const priority = determinePriority(iconPath); + const zIndexOffset = 100 * (5 - priority); // Adjusted for simplicity and positive values + + const marker = L.marker([station.X, station.Y], { + icon: L.icon({ + iconUrl: iconPath, + iconSize: [25, 41], + iconAnchor: [12, 41], + popupAnchor: [1, -34], + }), + areaName: station.Area_Name, // Stelle sicher, dass dieser Bereich gesetzt wird + link: station.Link, + zIndexOffset: zIndexOffset, + bounceOnAdd: !!statis, + }); + + if (statis) { + marker.on("add", () => marker.bounce(3)); + } + + const statusInfo = statusResponse.Statis.filter((status) => status.IdLD === station.IdLD) + .reverse() + .map( + (status) => ` +
+
+ ${status.Me} (${status.Na}) +
+ ` + ) + .join(""); + + marker.bindPopup(` +
+ ${station.LD_Name} + ${station.Device}
+ ${station.Area_Short} (${station.Area_Name})
+ ${station.Location_Short} (${station.Location_Name}) +
${statusInfo}
+
+ `); + return marker; + }); + + setMarkersFunction(markersData); + } + } catch (error) { + console.error("Error fetching data: ", error); + } +}; +//---------------------------------------------- +export const fetchPriorityConfig = async () => { + try { + const response = await fetch("/api/talas_v5_DB/priorityConfig"); + const data = await response.json(); + console.log("Prioritätskonfiguration:", data); + setPriorityConfig(data); + } catch (error) { + console.error("Fehler beim Laden der Prioritätskonfiguration:", error); + } +}; +//---------------------------------------------- +export const fetchGisStatusStations = async (idMap, idUser) => { + try { + const response = await fetch(`/api/talas5/webserviceMap/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`); + if (!response.ok) { + throw new Error(`Error: ${response.statusText}`); + } + const data = await response.json(); + console.log("GisStatusStations:", data); + return data; + } catch (error) { + console.error("Fehler beim Abrufen der Daten:", error); + } +}; +//---------------------------------------------- +export const handleEditPoi = (marker) => { + // Prüfung, ob der Benutzer die notwendigen Rechte hat + if (!userRights || !userRights.includes(56)) { + toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", { + position: "top-center", + autoClose: 5000, + hideProgressBar: false, + closeOnClick: true, + pauseOnHover: true, + draggable: true, + progress: undefined, + }); + console.log("Benutzer hat keine Berechtigung zum Bearbeiten."); + return; // Beendet die Funktion frühzeitig, wenn keine Berechtigung vorliegt + } + + //console.log("Selected Marker ID (idPoi):", marker.options.idPoi); + //console.log("Selected Marker Description:", marker.options.description); + + setCurrentPoiData({ + idPoi: marker.options.id, + name: marker.options.name, + description: marker.options.description, + }); + //console.log("POI-Daten1:", currentPoiData); + + fetchPoiData(marker.options.id); + + setShowPoiUpdateModal(true); +}; +//---------------------------------------------- +export const insertNewMarker = (closestPoints, newPoint, lineData, map) => { + const newMarker = L.marker(newPoint, { + icon: circleIcon, + draggable: true, + }).addTo(map); + lineData.coordinates.splice(closestPoints[2], 0, [newPoint.lat, newPoint.lng]); + + // Hier direkt speichern nach Einfügen + saveLineData(lineData); + + redrawPolyline(lineData); + + // Event-Listener für das Verschieben des Markers hinzufügen + newMarker.on("dragend", () => { + const newCoords = newMarker.getLatLng(); + setNewCoords(newCoords); + const newCoordinates = [...lineData.coordinates]; + newCoordinates[closestPoints[2]] = [newCoords.lat, newCoords.lng]; + lineData.coordinates = newCoordinates; + redrawPolyline(lineData); + + updateMarkerPosition(newMarker.getLatLng(), lineData, newMarker); + saveLineData(lineData); // Speichern der neuen Koordinaten nach dem Verschieben + }); +}; +//---------------------------------------------- +/* export const addItemsToMapContextMenu = () => { + const [menuItemAdded, setMenuItemAdded] = useState(false); + if (!menuItemAdded) { + //console.log("contextMenuItems hasRights:", hasRights); + + map.contextmenu.addItem({ + text: "POI hinzufügen", + icon: "img/add_station.png", + className: "background-red", + callback: (event) => addStationCallback(event, hasRights), + }); + + setMenuItemAdded(true); // Menüpunkt wurde hinzugefült, Zustand aktualisieren + } +}; */ +//---------------------------------------------- +export const saveLineData = (lineData) => { + fetch("/api/talas_v5_DB/gisLines/updateLineCoordinates", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + idModul: lineData.idModul, + idLD: lineData.idLD, + newCoordinates: lineData.coordinates, + }), + }) + .then((response) => { + if (!response.ok) { + throw new Error("Fehler beim Speichern der Linienänderungen"); + } + return response.json(); + }) + .then((data) => { + console.log("Linienänderungen gespeichert:", data); + }) + .catch((error) => { + console.error("Fehler beim Speichern der Linienänderungen:", error); + }); +}; +//----------------------------------------------