feat(PoiUpdateModal): Display correct POI type in dropdown on modal open

- Added logic to store the selected POI type in localStorage during POI selection.
- Updated PoiUpdateModal to pre-select the correct POI type from localStorage when opening the modal.
- Implemented fallback to fetch POI types if not found in localStorage.
- Ensured the selected device is also pre-filled in the dropdown.
This commit is contained in:
ISA
2024-09-13 10:21:07 +02:00
parent 56f4a585ae
commit 864644c543
3 changed files with 34 additions and 236 deletions

View File

@@ -10,34 +10,34 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
const [poiId, setPoiId] = useState(poiData ? poiData.idPoi : ""); const [poiId, setPoiId] = useState(poiData ? poiData.idPoi : "");
const [name, setName] = useState(poiData ? poiData.name : ""); const [name, setName] = useState(poiData ? poiData.name : "");
const [poiTypData, setPoiTypData] = useState([]); const [poiTypData, setPoiTypData] = useState([]);
const [poiTypeId, setPoiTypeId] = useState(""); const [poiTypeId, setPoiTypeId] = useState(""); // Sicherstellen, dass der Typ korrekt vorgewählt ist
const [locationDeviceData, setLocationDeviceData] = useState([]); const [locationDeviceData, setLocationDeviceData] = useState([]);
const [deviceName, setDeviceName] = useState(""); const [deviceName, setDeviceName] = useState("");
const [idLD, setIdLD] = useState(poiData ? poiData.idLD : ""); const [idLD, setIdLD] = useState(poiData ? poiData.idLD : "");
const [description, setDescription] = useState(poiData ? poiData.description : ""); const [description, setDescription] = useState(poiData ? poiData.description : "");
// Debugging // Beim Öffnen des Modals den POI-Typ aus dem localStorage laden
useEffect(() => {
console.log("poiData:", poiData);
if (!poiData.idLD) {
console.error("Fehlender idLD in poiData");
console.log("poiData:", poiData);
}
}, [poiData]);
// Fetch and set POI data
useEffect(() => { useEffect(() => {
if (poiData) { if (poiData) {
setPoiId(poiData.idPoi); setPoiId(poiData.idPoi);
setName(poiData.name); setName(poiData.name);
setPoiTypeId(poiData.idPoiTyp); setPoiTypeId(poiData.idPoiTyp); // Setze den Typ-ID
// Prüfe, ob der Typ im localStorage gespeichert ist
const selectedPoiType = localStorage.getItem("selectedPoiType");
if (selectedPoiType) {
const matchingType = poiTypData.find((type) => type.name === selectedPoiType);
if (matchingType) {
setPoiTypeId(matchingType.idPoiTyp); // Setze die Typ-ID auf den gespeicherten Wert
}
}
setIdLD(poiData.idLD); setIdLD(poiData.idLD);
setDescription(poiData.description); setDescription(poiData.description);
console.log("Initial Device ID (idLD):", poiData.idLD);
} }
}, [poiData]); }, [poiData, poiTypData]);
// Fetch POI types and pre-select the current POI type // Fetch POI types and set the current POI type in the dropdown
useEffect(() => { useEffect(() => {
const fetchPoiTypData = async () => { const fetchPoiTypData = async () => {
const cachedPoiTypData = localStorage.getItem("poiTypData"); const cachedPoiTypData = localStorage.getItem("poiTypData");
@@ -45,7 +45,7 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
const data = JSON.parse(cachedPoiTypData); const data = JSON.parse(cachedPoiTypData);
setPoiTypData(data); setPoiTypData(data);
if (poiData) { if (poiData) {
setPoiTypeId(poiData.idPoiTyp); // Set the selected POI type ID setPoiTypeId(poiData.idPoiTyp);
} }
} else { } else {
try { try {
@@ -54,7 +54,7 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
setPoiTypData(data); setPoiTypData(data);
localStorage.setItem("poiTypData", JSON.stringify(data)); localStorage.setItem("poiTypData", JSON.stringify(data));
if (poiData) { if (poiData) {
setPoiTypeId(poiData.idPoiTyp); // Set the selected POI type ID setPoiTypeId(poiData.idPoiTyp);
} }
} catch (error) { } catch (error) {
console.error("Fehler beim Abrufen der poiTyp Daten:", error); console.error("Fehler beim Abrufen der poiTyp Daten:", error);
@@ -73,36 +73,13 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
setLocationDeviceData(data); setLocationDeviceData(data);
if (poiData && poiData.idLD) { if (poiData && poiData.idLD) {
const selectedDevice = data.find((device) => device.idLD === poiData.idLD); const selectedDevice = data.find((device) => device.idLD === poiData.idLD);
console.log("Selected Device:", selectedDevice); // Debugging
setDeviceName(selectedDevice ? selectedDevice.name : ""); setDeviceName(selectedDevice ? selectedDevice.name : "");
if (!selectedDevice) {
console.error(`Kein Gerät mit idLD: ${poiData.idLD} gefunden.`);
}
} }
} }
}; };
fetchLocationDevices(); fetchLocationDevices();
}, [poiData]); }, [poiData]);
const handleDeletePoi = async () => {
if (confirm("Sind Sie sicher, dass Sie diesen POI löschen möchten?")) {
try {
const response = await fetch(`/api/talas_v5_DB/pois/deletePoi?id=${poiId}`, {
method: "DELETE",
});
if (response.ok) {
onClose();
window.location.reload();
} else {
throw new Error("Fehler beim Löschen des POI.");
}
} catch (error) {
console.error("Fehler beim Löschen des POI:", error);
alert("Fehler beim Löschen des POI.");
}
}
};
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`); const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`);
@@ -119,7 +96,7 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
idPoi: poiId, idPoi: poiId,
name: name, name: name,
description: description, description: description,
idPoiTyp: poiTypeId, idPoiTyp: poiTypeId, // Den ausgewählten Typ mitsenden
idLD: idLD, idLD: idLD,
}), }),
}); });
@@ -167,10 +144,10 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
</div> </div>
<div className="flex items-center mb-4"> <div className="flex items-center mb-4">
<label htmlFor="idPoiTyp2" className="block mr-2 flex-none"> <label htmlFor="idPoiTyp" className="block mr-2 flex-none">
Typ: Typ:
</label> </label>
<select id="idPoiTyp2" name="idPoiTyp2" value={poiTypeId} onChange={(e) => setPoiTypeId(e.target.value)} className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"> <select id="idPoiTyp" name="idPoiTyp" value={poiTypeId} onChange={(e) => setPoiTypeId(e.target.value)} className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm">
{poiTypData.map((poiTyp) => ( {poiTypData.map((poiTyp) => (
<option key={poiTyp.idPoiTyp} value={poiTyp.idPoiTyp}> <option key={poiTyp.idPoiTyp} value={poiTyp.idPoiTyp}>
{poiTyp.name} {poiTyp.name}
@@ -179,10 +156,6 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
</select> </select>
</div> </div>
<button type="button" onClick={handleDeletePoi} className="bg-red-400 hover:bg-red-600 text-white font-bold py-2 px-4 rounded w-full mb-4">
POI löschen
</button>
<button type="submit" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full"> <button type="submit" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full">
POI aktualisieren POI aktualisieren
</button> </button>

View File

@@ -1,173 +0,0 @@
// services/apiService.js
import * as config from "../config/config";
import * as urls from "../config/urls";
let timeoutId;
const fetchWithTimeout = async (url, options, timeout = 5000) => {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
} catch (error) {
clearTimeout(id); // Im Falle eines Fehlers den Timeout abbrechen
throw error;
}
};
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;
try {
// Verwende das Timeout für die API-Anfrage
const response = await fetchWithTimeout(
`${SERVER_URL}/talas5/ClientData/WebServiceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`,
null,
5000 // Timeout auf 5 Sekunden gesetzt
);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Fehler beim Abrufen der Daten:", error);
throw error;
}
}, 500); // Debounce-Zeit auf 500ms gesetzt
};
// ----------------------------------------------
/* 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) => {
try {
const response = await fetch(`/api/talas_v5_DB/pois/getPoiById?idPoi=${idPoi}`);
if (!response.ok) {
throw new Error("Fehler beim Abrufen der POI-Daten");
}
const data = await response.json();
return {
idPoi,
name: data.name,
description: data.description,
idLD: data.idLD,
};
} catch (error) {
console.error("Fehler beim Abrufen der POI-Daten", error);
return null;
}
};
// ----------------------------------------------
// 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 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");
throw new Error("Gerät nicht gefunden in apiService.js");
}
} catch (error) {
console.error("Fehler beim Abrufen des Gerätenamens in apiService.js:", error);
return "Unbekannt";
}
};
// ----------------------------------------------
// services/apiService.js
export const fetchUserRights = async () => {
// Zähler für API-Aufrufe in localStorage speichern
let userRightsRequestCount = localStorage.getItem("userRightsRequestCount") || 0;
userRightsRequestCount++;
localStorage.setItem("userRightsRequestCount", userRightsRequestCount);
console.log(`fetchUserRights wurde ${userRightsRequestCount} Mal aufgerufen.`);
// Debouncing, um wiederholte schnelle API-Aufrufe zu verhindern
if (timeoutId) {
clearTimeout(timeoutId); // Falls innerhalb der Debounce-Zeit wieder ein Aufruf erfolgt, wird der alte abgebrochen
}
timeoutId = setTimeout(async () => {
try {
const response = await fetchWithTimeout(
`${process.env.NEXT_PUBLIC_SERVER_URL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${config.idMap}&idUser=${config.idUser}`,
null,
5000 // Timeout für die API-Anfrage auf 5 Sekunden gesetzt
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Überprüfen der Struktur der Antwort
if (!data || !data.Rights || !Array.isArray(data.Rights)) {
throw new Error("Invalid response structure");
}
const rightsArray = data.Rights; // Nehmen an, dass 'Rights' das Array von Rechten ist
const userRightsIds = rightsArray.map((right) => right.IdRight);
return userRightsIds;
} catch (error) {
console.error("Fehler beim Abrufen der Benutzerrechte", error);
return [];
}
}, 500); // Debounce-Zeit auf 500 ms gesetzt
};

View File

@@ -1,37 +1,35 @@
// utils/handlePoiSelect.js // utils/handlePoiSelect.js
const handlePoiSelect = async (poiData, setSelectedPoi, setLocationDeviceData, setDeviceName, poiLayerRef, poiTypMap) => { const handlePoiSelect = async (poiData, setSelectedPoi, setLocationDeviceData, setDeviceName, poiLayerRef, poiTypMap) => {
setSelectedPoi(poiData); // poiData should be the data of the selected POI setSelectedPoi(poiData); // Setzt das ausgewählte POI
//console.log("Selected POI:", poiData);
//console.log("Selected POI idLD:", poiData.deviceId);
try { try {
const response = await fetch("/api/talas_v5_DB/locationDevice/locationDevices"); const response = await fetch("/api/talas_v5_DB/locationDevice/locationDevices");
const data = await response.json(); const data = await response.json();
setLocationDeviceData(data); setLocationDeviceData(data);
//console.log("Standort- und Gerätedaten:", data);
const currentDevice = data.find((device) => device.idLD === poiData.deviceId); const currentDevice = data.find((device) => device.idLD === poiData.deviceId);
if (currentDevice) { if (currentDevice) {
setDeviceName(currentDevice.name); setDeviceName(currentDevice.name);
//console.log("Current Device name in poiUpdate2:", currentDevice.name);
// Update the marker popup with the device name and type // Hier speichern wir den POI-Typ im localStorage
const poiTypeName = poiTypMap.get(poiData.idPoiTyp);
localStorage.setItem("selectedPoiType", poiTypeName);
// Optional: Update des Markers mit dem POI-Typ
const marker = poiLayerRef.current.getLayers().find((m) => m.options.id === poiData.id); const marker = poiLayerRef.current.getLayers().find((m) => m.options.id === poiData.id);
if (marker) { if (marker) {
marker.setPopupContent( marker.setPopupContent(`
` <div>
<div> <b class="text-xl text-black-700">${poiData.description || "Unbekannt"}</b><br>
<b class="text-xl text-black-700">${poiData.description || "Unbekannt"}</b><br> ${currentDevice.name}<br>
${currentDevice.name}<br> ${poiTypeName || "Unbekannt"}<br>
${poiTypMap.get(poiData.idPoiTyp) || "Unbekannt"}<br> </div>
</div> `);
`,
);
marker.openPopup(); marker.openPopup();
} }
} }
} catch (error) { } catch (error) {
console.error("Fehler beim Abrufen der Gerätedaten2:", error); console.error("Fehler beim Abrufen der Gerätedaten:", error);
setLocationDeviceData([]); setLocationDeviceData([]);
} }
}; };