Merge branch 'v1.0.8.1' into fix/ohne-externe-babel

This commit is contained in:
ISA
2025-02-05 10:27:36 +01:00
88 changed files with 5425 additions and 459 deletions

View File

@@ -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

View File

@@ -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, {

View File

@@ -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
}),
});

View File

@@ -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 (

162
components/imports.js Normal file
View File

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

View File

@@ -1,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.
*/

2
config/settings.js Normal file
View File

@@ -0,0 +1,2 @@
// /config/settings.js
export const MAP_VERSION = "1.0.8.2";

View File

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

View File

@@ -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

View File

@@ -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) => `<span class="inline-block text-gray-800"><span class="inline-block w-2 h-2 rounded-full mr-2" style="background-color: ${msg.prioColor};"></span>${msg.message}</span><br>`).join("");
const prioNameDisplay = statis.PrioName && statis.PrioName !== "?" ? `(${statis.PrioName})` : "";
colorsByModule[key] = values.messages.length > 0 ? values.messages[0].prioColor : "green";
newTooltipContents[key] = `
<div class="bg-white rounded-lg m-0 p-2 w-[210px]">
<span class="text-lg font-semibold text-gray-900">${statis.ModulName || "Unknown"}</span>
<br>
<span class="text-md font-bold text-gray-800">${statis.ModulTyp || "N/A"}</span>
<br>
<span class="text-md font-bold text-gray-800">Slot: ${statis.Modul || "N/A"}</span>
<br>
<span class="text-md font-bold text-gray-800">Station: ${namesData[matchingLine.idLD] || "N/A"}</span>
<br>
<div style="max-width: 100%; overflow-wrap: break-word; word-break: break-word; white-space: normal;">
${messageDisplay}
</div>
<br>
${values.messwert ? `<span class="inline-block text-gray-800">Messwert: ${values.messwert}</span><br>` : ""}
${values.schleifenwert ? `<span class="inline-block text-gray-800">Schleifenwert: ${values.schleifenwert}</span>` : ""}
</div>
`;
}
});
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;

28
package-lock.json generated
View File

@@ -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",

View File

@@ -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",

View File

@@ -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 (
<Provider store={store}>
{" "}
{/* Redux Provider */}
<RecoilRoot>
{" "}
{/* Recoil Provider */}
<Component {...pageProps} />
</RecoilRoot>
</Provider>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,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" });
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,13 @@
// pages/api/[...path].js
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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,3 +1,4 @@
"use client";
import React, { useEffect, useState } from "react";
import 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 (
<div>
<MapComponentWithNoSSR locations={locations} onAddLocation={handleAddLocation} onLocationUpdate={handleLocationUpdate} />

View File

@@ -1,9 +0,0 @@
// /redux/actions.js
export const connectWebSocket = (url) => ({
type: "WS_CONNECT",
payload: { url },
});
export const disconnectWebSocket = () => ({
type: "WS_DISCONNECT",
});

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -1,7 +1,17 @@
//redux/slices/readPoiMarkersStoreSlice.js
import { atom } from 'recoil';
import { atom } from "recoil";
export const readPoiMarkersStore = atom({
key: 'readPoiMarkersStore',
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;
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -1,126 +1,90 @@
// /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
//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
const marker = L.marker([station.X, station.Y], {
icon: L.divIcon({
className: `custom-marker`,
html: `
<div >
<!-- SVG direkt eingebettet -->
<svg width="50" height="50" viewBox="0 0 25 41" xmlns="http://www.w3.org/2000/svg">
<!-- Äußere Form -->
<path id="outer" fill="${outerColor}" stroke="#000000" stroke-width="0.3"
d="M 5.0582559,3.8656758 19.50163,3.616274 c 0,0 1.960457,0.6522815 2.770647,1.5827418 0.910212,1.0455689 0.670156,2.3789089 0.670156,2.3789089 l 0.120028,13.2470683 c 0,0 -0.460107,0.911276 -1.250292,1.649889 -0.630147,0.594727 -1.620378,1.055162 -1.620378,1.055162 0,0 -0.500117,0.508395 -4.190979,1.314155 0,0 -0.869675,1.874293 -1.31978,3.457035 -1.020238,3.577955 -2.304224,6.276531 -2.304224,6.276531 0,0 -0.824931,-2.365549 -1.84517,-5.972281 -0.480112,-1.717035 -1.4124335,-3.81884 -1.4124335,-3.81884 0,0 -3.7708809,-0.681058 -3.8609019,-0.748205 0,0 -1.2102827,-0.441249 -1.8804393,-1.170269 -0.7601775,-0.824944 -1.190278,-1.860921 -1.190278,-1.860921 L 2.0575549,7.0407517 C 1.5174288,7.0599367 4.3580923,3.8848605 5.0582559,3.8656758 Z" />
<!-- Innere Form -->
<path id="inner" fill="${innerColor}" stroke="#000000" stroke-width="0.27"
d="m 5.1425811,7.1294233 c -0.5874766,0.6413053 -0.8634128,1.398402 -0.8634128,1.398402 0,0 0.2492327,12.0779207 0.2492327,12.0779207 0,0 0.5162673,0.641304 1.1927556,1.166818 0.5785757,0.445352 1.4686917,0.623491 1.4686917,0.623491 0.979128,0.01781 11.3845877,-0.338466 11.3845877,-0.338466 0,0 0.747696,-0.240489 1.30847,-0.863981 0.45396,-0.498793 0.818907,-0.855074 0.818907,-0.855074 0,0 -0.07122,-11.8641507 -0.07122,-11.7572665 0,0.071256 -0.23143,-0.9797723 -0.863412,-1.6834268 -0.400548,-0.4364441 -1.308466,-0.6502126 -1.308466,-0.6502126 0,0 -12.0699763,0 -12.0699763,0 0,0 -0.7922036,0.3919091 -1.2461636,0.8817952 z" />
</svg>
<!-- Inneres Icon -->
<img src="img/icons/marker-icon-${station.Icon}.svg"
style="position: absolute;
top: 8px;
left: 15px;
width: 20px;
height: 20px;
" />
</div>`,
iconSize: [30, 45],
iconAnchor: [27, 41],
popupAnchor: [1, -34],
}),
areaName: station.Area_Name, // Stelle sicher, dass dieser Bereich gesetzt wird
link: station.Link,
zIndexOffset: 100 * (6 - minLevel),
return {
idLD: station.IdLD,
active: station.Active,
};
});
// Popup-Info dynamisch erstellen
const statusInfo = statisForStation
console.log("🔄 Alle Linien gespeichert:", allLines);
// 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);
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`;
const priority = determinePriority(iconPath, priorityConfig);
const zIndexOffset = 100 * (5 - priority);
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,
});
marker.bindPopup(`
<div class="bg-white rounded-lg">
<span class="text-lg font-semibold text-gray-900">${station.LD_Name}</span>
<span class="text-md font-bold text-gray-800"> ${station.Device}</span><br>
<span class="text-gray-800"><strong> ${station.Area_Short} </strong>(${station.Area_Name})</span><br>
<span class="text-gray-800"><strong>${station.Location_Short} </strong> (${station.Location_Name})</span>
<div class="mt-2">
${statusResponse.Statis.filter((status) => status.IdLD === station.IdLD)
.reverse()
.map(
(status) => `
<div class="flex items-center my-1">
@@ -129,34 +93,41 @@ export const createAndSetDevices = async (systemId, setMarkersFunction, GisSyste
</div>
`
)
.join("");
marker.bindPopup(`
<div class="bg-white rounded-lg">
<span class="text-lg font-semibold text-gray-900">${station.LD_Name}</span>
<span class="text-md font-bold text-gray-800"> ${station.Device}</span><br>
<span class="text-gray-800"><strong> ${station.Area_Short} </strong>(${station.Area_Name})</span><br>
<span class="text-gray-800"><strong>${station.Location_Short} </strong> (${station.Location_Name})</span>
<div class="mt-2">${statusInfo}</div>
.join("")}
</div>
</div>
`);
// **Mouseover zeigt Popup**
marker.on("mouseover", function () {
this.openPopup();
});
// **Mouseout schließt Popup**
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);
}
};

View File

@@ -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);

View File

@@ -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,

View File

@@ -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,

View File

@@ -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 };
};

View File

@@ -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) => {

211
utils/utils.js Normal file
View File

@@ -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) => `
<div class="flex items-center my-1">
<div class="w-2 h-2 mr-2 inline-block rounded-full" style="background-color: ${status.Co};"></div>
${status.Me}&nbsp;<span style="color: ${status.Co};">(${status.Na})</span>
</div>
`
)
.join("");
marker.bindPopup(`
<div class=" bg-white rounded-lg ">
<span class="text-lg font-semibold text-gray-900">${station.LD_Name}</span>
<span class="text-md font-bold text-gray-800"> ${station.Device}</span><br>
<span class="text-gray-800"><strong> ${station.Area_Short} </strong>(${station.Area_Name})</span><br>
<span class="text-gray-800"><strong>${station.Location_Short} </strong> (${station.Location_Name})</span>
<div class="mt-2">${statusInfo}</div>
</div>
`);
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);
});
};
//----------------------------------------------