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.
This commit is contained in:
ISA
2024-07-09 08:10:02 +02:00
parent 467be2c106
commit b53fe1b3f1
6 changed files with 290 additions and 176 deletions

View File

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