From b53fe1b3f1b164a94d3d10ef38073d3bdd705a66 Mon Sep 17 00:00:00 2001 From: ISA Date: Tue, 9 Jul 2024 08:10:02 +0200 Subject: [PATCH] feat: Refactor utils.js into specialized utility modules - Split utils.js into three separate files to enhance modularity and maintainability: 1. geometryUtils.js: Contains geometry-related functions like parsePoint and findClosestPoints. 2. mapUtils.js: Contains functions related to map operations such as redrawPolyline and saveLineData. 3. markerUtils.js: Contains functions related to marker operations like insertNewMarker and handleEditPoi. - Updated import statements in the relevant files to reflect the new structure. - Ensured that each utility module is self-contained and has clear responsibilities. This refactor improves the separation of concerns, making the codebase more organized and easier to navigate. Future maintenance and enhancements can now be more easily localized to the appropriate utility module. --- components/MapComponent.js | 190 +++---------------------------------- services/apiService.js | 128 +++++++++++++++++++++++++ utils/geometryUtils.js | 21 ++++ utils/mapUtils.js | 63 ++++++++++++ utils/markerUtils.js | 64 +++++++++++++ {utlis => utils}/utils.js | 0 6 files changed, 290 insertions(+), 176 deletions(-) create mode 100644 services/apiService.js create mode 100644 utils/geometryUtils.js create mode 100644 utils/mapUtils.js create mode 100644 utils/markerUtils.js rename {utlis => utils}/utils.js (100%) diff --git a/components/MapComponent.js b/components/MapComponent.js index f613e56f0..41881886c 100644 --- a/components/MapComponent.js +++ b/components/MapComponent.js @@ -39,16 +39,28 @@ import { set } from "lodash"; import { poiLayerVisibleState } from "../store/atoms/poiLayerVisible.js"; import { data } from "autoprefixer"; import plusRoundIcon from "./PlusRoundIcon.js"; -import { +/* import { parsePoint, handleEditPoi, insertNewMarker, redrawPolyline, saveLineData, -} from "../utlis/utils.js"; +} from "../utils/utils.js"; */ +import { parsePoint, findClosestPoints } from "../utils/geometryUtils.js"; +import { handleEditPoi, insertNewMarker } from "../utils/markerUtils.js"; +import { saveLineData, redrawPolyline } from "../utils/mapUtils.js"; import circleIcon from "./CircleIcon"; import startIcon from "./StartIcon"; import endIcon from "./EndIcon"; +import { + fetchGisStatusStations, + fetchPriorityConfig, + fetchPoiData, + updateLocationInDatabase, + checkInternet, + fetchUserRights, + fetchDeviceNameById, +} from "../services/apiService.js"; //--------------------------------------------------------------------- //-------------------- MapComponent ----------------------------------- @@ -61,17 +73,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { const [priorityConfig, setPriorityConfig] = useState([]); - 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); - } - }; - useEffect(() => { fetchPriorityConfig(); }, []); @@ -80,21 +81,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { console.log("Aktualisierte Prioritätskonfiguration:", priorityConfig); }, [priorityConfig]); //--------------------------------------------------------------------- - 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); - } - }; useEffect(() => { fetchGisStatusStations(12, 484); // Beispielaufruf mit idMap = 10 und idUser = 484 @@ -136,24 +122,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { }); }, []); // Lade die Berechtigungen beim Initialisieren der Komponente - const fetchPoiData = async (idPoi) => { - const response = await fetch( - `/api/talas_v5_DB/pois/getPoiById?idPoi=${idPoi}` - ); - if (!response.ok) { - console.error("Fehler beim Abrufen der POI-Daten"); - return; - } - const data = await response.json(); - setCurrentPoiData({ - idPoi, - name: data.name, - description: data.description, - }); - //console.log("POI-Daten2:", currentPoiData); - setShowPoiUpdateModal(true); - }; - const [showVersionInfoModal, setShowVersionInfoModal] = useState(false); const zoomTrigger = useRecoilValue(zoomTriggerState); const offlineTileLayer = "/mapTiles/{z}/{x}/{y}.png"; @@ -239,26 +207,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { const closeVersionInfoModal = () => { setShowVersionInfoModal(false); }; - // Funktion zum Aktualisieren der Position in der Datenbank - const updateLocationInDatabase = async (id, newLatitude, newLongitude) => { - const response = await fetch("/api/talas_v5_DB/pois/updateLocation", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - id, - latitude: newLatitude, - longitude: newLongitude, - }), - }); - - if (response.ok) { - //schreib die neue Kooridnaten in die Console - //akuellisiere die Position in der Datenbank mit den neuen Koordinaten mit updateLocation mit SQL Anweisung UPDATE - } else { - console.error("Fehler beim Aktualisieren der Position"); - } - }; - //--------------------------------------------- //---------------------------------------------------- //-----Kontextmenu---------------- @@ -382,12 +330,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { } //------------------------------------------ //------------------------------------------ - // Funktionen zur Überwachung der Internetverbindung - const checkInternet = () => { - fetch("https://tile.openstreetmap.org/1/1/1.png", { method: "HEAD" }) - .then((response) => setOnline(response.ok)) - .catch(() => setOnline(false)); - }; let initMap = []; //----------------------------------------------------------------- // TALAS Marker hinzufügen @@ -523,18 +465,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { //-------------------------------------------------------------------------------- const mapLayersVisibility = useRecoilValue(mapLayersState); - /* - const handleCheckboxChange = (name, event) => { - const { checked } = event.target; - const internalName = layerNames[name] || name; // Nutzt den internen Namen, wenn vorhanden, sonst den originalen Namen - - setMapLayersVisibility((prev) => { - return { - ...prev, - [internalName]: checked, - }; - }); - }; */ //------------------------------------------ //------------------------------------------ */ @@ -623,29 +553,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { const c = params.get("m"); // Beispielwert für idMap const user = params.get("u"); // Beispielwert für idUser //console.log("serverURL:", serverURL); - const fetchUserRights = async () => { - try { - const response = await fetch( - `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}` - //`${serverURL}/api/talas5/webserviceMap/GisSystemStatic?idMap=${c}&idUser=${user}` //Berechtigung zum hinzufügen von POIs in der Karte - //`${serverURL}/api/rights?idMap=${c}&idUser=${user}` - ); - const data = await response.json(); - //console.log("Benutzerrechte:", data); - const rightsArray = data.Rights; // Nehmen an, dass 'Rights' das Array von Rechten ist - - // Speichert die IDs der Rechte in einem Array - const userRightsIds = rightsArray.map((right) => right.IdRight); - setUserRights(userRightsIds); // Speichert die Rechte in den Zustand - - //console.log("Benutzerrechte:", rightsArray); - //console.log("Benutzerrechte IDs:", userRightsIds); - //console.log("Benutzerrechte in if :", userRightsIds.includes(56)); - setHasRights(userRightsIds.includes(56)); - } catch (error) { - console.error("Fehler beim Abrufen der Benutzerrechte", error); - } - }; useEffect(() => { //console.log("Aktualisierter Status von hasRights: ", hasRights); }, [hasRights]); // Dieser Effekt läuft jedes Mal, wenn sich `hasRights` ändert. @@ -990,26 +897,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { } //------------------------------------------ - - const fetchDeviceNameById = async (idLD) => { - try { - const response = await fetch( - `/api/talas_v5_DB/locationDevice/locationDeviceNameById?idLD=${idLD}` - ); - const data = await response.json(); - if (response.ok) { - return data.name; - } else { - throw new Error(data.error || "Gerät nicht gefunden"); - } - } catch (error) { - console.error( - "Fehler beim Abrufen des Gerätenamens in MapComponent.js:", - error - ); - return "Unbekannt"; - } - }; //-------------------------------------------------- const addItemsToMapContextMenu = () => { @@ -2304,55 +2191,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { //--------------------------------------------------------- - /* function redrawPolyline(lineData) { - if (lineData.polyline) map.removeLayer(lineData.polyline); - lineData.polyline = L.polyline(lineData.coordinates, { - color: lineColors[lineData.idModul] || "#000000", - }).addTo(map); - - lineData.polyline.bindTooltip( - tooltipContents[lineData.idModul] || "Standard-Tooltip-Inhalt", - { - 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 }); - }); - } */ - - /* function 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); - }); - } */ - function updateMarkerPosition(newLatLng, lineData, marker) { const index = lineData.coordinates.findIndex((coord) => L.latLng(coord[0], coord[1]).equals(marker.getLatLng()) diff --git a/services/apiService.js b/services/apiService.js new file mode 100644 index 000000000..ae88e8163 --- /dev/null +++ b/services/apiService.js @@ -0,0 +1,128 @@ +// services/apiService.js + +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); + throw error; // Fehler weiter werfen, um ihn in der Komponente behandeln zu können + } +}; + +// ---------------------------------------------- +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 fetchPoiData = async (idPoi) => { + const response = await fetch( + `/api/talas_v5_DB/pois/getPoiById?idPoi=${idPoi}` + ); + if (!response.ok) { + console.error("Fehler beim Abrufen der POI-Daten"); + return; + } + const data = await response.json(); + setCurrentPoiData({ + idPoi, + name: data.name, + description: data.description, + }); + //console.log("POI-Daten2:", currentPoiData); + setShowPoiUpdateModal(true); +}; + +// ---------------------------------------------- +// Funktion zum Aktualisieren der Position in der Datenbank +export const updateLocationInDatabase = async ( + id, + newLatitude, + newLongitude +) => { + const response = await fetch("/api/talas_v5_DB/pois/updateLocation", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + id, + latitude: newLatitude, + longitude: newLongitude, + }), + }); + + if (response.ok) { + //schreib die neue Kooridnaten in die Console + //akuellisiere die Position in der Datenbank mit den neuen Koordinaten mit updateLocation mit SQL Anweisung UPDATE + } else { + console.error("Fehler beim Aktualisieren der Position"); + } +}; + +// ---------------------------------------------- +// Funktionen zur Überwachung der Internetverbindung +export const checkInternet = () => { + fetch("https://tile.openstreetmap.org/1/1/1.png", { method: "HEAD" }) + .then((response) => setOnline(response.ok)) + .catch(() => setOnline(false)); +}; + +// ---------------------------------------------- +export const fetchUserRights = async () => { + try { + const response = await fetch( + `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}` + //`${serverURL}/api/talas5/webserviceMap/GisSystemStatic?idMap=${c}&idUser=${user}` //Berechtigung zum hinzufügen von POIs in der Karte + //`${serverURL}/api/rights?idMap=${c}&idUser=${user}` + ); + const data = await response.json(); + //console.log("Benutzerrechte:", data); + const rightsArray = data.Rights; // Nehmen an, dass 'Rights' das Array von Rechten ist + + // Speichert die IDs der Rechte in einem Array + const userRightsIds = rightsArray.map((right) => right.IdRight); + setUserRights(userRightsIds); // Speichert die Rechte in den Zustand + + //console.log("Benutzerrechte:", rightsArray); + //console.log("Benutzerrechte IDs:", userRightsIds); + //console.log("Benutzerrechte in if :", userRightsIds.includes(56)); + setHasRights(userRightsIds.includes(56)); + } catch (error) { + console.error("Fehler beim Abrufen der Benutzerrechte", error); + } +}; + +// ---------------------------------------------- +export const fetchDeviceNameById = async (idLD) => { + try { + const response = await fetch( + `/api/talas_v5_DB/locationDevice/locationDeviceNameById?idLD=${idLD}` + ); + const data = await response.json(); + if (response.ok) { + return data.name; + } else { + throw new Error(data.error || "Gerät nicht gefunden"); + } + } catch (error) { + console.error( + "Fehler beim Abrufen des Gerätenamens in MapComponent.js:", + error + ); + return "Unbekannt"; + } +}; diff --git a/utils/geometryUtils.js b/utils/geometryUtils.js new file mode 100644 index 000000000..1240d216f --- /dev/null +++ b/utils/geometryUtils.js @@ -0,0 +1,21 @@ +export const parsePoint = (position) => { + const [longitude, latitude] = position.slice(6, -1).split(" "); + return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) }; +}; + +export const findClosestPoints = (coordinates, newPoint, map) => { + let minDist = Infinity; + let closestPair = []; + for (let i = 1; i < coordinates.length; i++) { + const dist = L.LineUtil.pointToSegmentDistance( + map.latLngToLayerPoint(newPoint), + map.latLngToLayerPoint(coordinates[i - 1]), + map.latLngToLayerPoint(coordinates[i]) + ); + if (dist < minDist) { + minDist = dist; + closestPair = [coordinates[i - 1], coordinates[i], i]; + } + } + return closestPair; +}; diff --git a/utils/mapUtils.js b/utils/mapUtils.js new file mode 100644 index 000000000..4879fd601 --- /dev/null +++ b/utils/mapUtils.js @@ -0,0 +1,63 @@ +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", + 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); + }); +}; diff --git a/utils/markerUtils.js b/utils/markerUtils.js new file mode 100644 index 000000000..ff6cc85f2 --- /dev/null +++ b/utils/markerUtils.js @@ -0,0 +1,64 @@ +import circleIcon from "../components/CircleIcon"; +import { saveLineData, redrawPolyline } from "./mapUtils"; + +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(); + 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 handleEditPoi = ( + marker, + userRights, + setCurrentPoiData, + setShowPoiUpdateModal, + fetchPoiData, + toast +) => { + // 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 + } + + setCurrentPoiData({ + idPoi: marker.options.id, + name: marker.options.name, + description: marker.options.description, + }); + + fetchPoiData(marker.options.id); + + setShowPoiUpdateModal(true); +}; diff --git a/utlis/utils.js b/utils/utils.js similarity index 100% rename from utlis/utils.js rename to utils/utils.js