diff --git a/components/MapComponent.js b/components/MapComponent.js new file mode 100644 index 0000000..092e40e --- /dev/null +++ b/components/MapComponent.js @@ -0,0 +1,68 @@ +import { useEffect, useState } from 'react'; + +const MapComponent = ({ latitude, longitude, name, description, officeType }) => { + const [mapLoaded, setMapLoaded] = useState(false); + + useEffect(() => { + // Load Leaflet on client-side only + if (typeof window !== 'undefined' && latitude && longitude) { + // Import Leaflet dynamically + import('leaflet').then((L) => { + // Safety check to see if map element exists + const mapElement = document.getElementById('map'); + if (!mapElement) return; + + // Clean up any existing map instance + if (mapElement._leaflet_map) { + mapElement._leaflet_map.remove(); + } + + // Initialize map + const map = L.map('map').setView([latitude, longitude], 15); + + // Store the map instance on the DOM element to clean up later + mapElement._leaflet_map = map; + + // Add OpenStreetMap tiles + L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { + attribution: '© OpenStreetMap contributors', + maxZoom: 19 + }).addTo(map); + + // Add marker for post office + const marker = L.marker([latitude, longitude]) + .addTo(map) + .bindPopup(` +
+

${name}

+

📍 Adres:
${description.street} ${description.houseNumber}
${description.zipCode} ${description.city}

+

🏢 Typ: ${officeType === 'UP' ? 'Urząd Pocztowy' : officeType}

+
+ `, { + maxWidth: 300 + }); + + // Open popup by default + marker.openPopup(); + + // Make sure map renders correctly + setTimeout(() => { + map.invalidateSize(); + setMapLoaded(true); + }, 300); + }); + } + + // Clean up function + return () => { + const mapElement = document.getElementById('map'); + if (mapElement && mapElement._leaflet_map) { + mapElement._leaflet_map.remove(); + } + }; + }, [latitude, longitude, name, description, officeType]); + + return
; +}; + +export default MapComponent; diff --git a/components/ui/Layout.js b/components/ui/Layout.js index 6440698..cd582b5 100644 --- a/components/ui/Layout.js +++ b/components/ui/Layout.js @@ -10,13 +10,15 @@ import { Bars3Icon as MenuIcon, XMarkIcon as XIcon, UserIcon, - ArrowRightOnRectangleIcon as LogoutIcon + ArrowRightOnRectangleIcon as LogoutIcon, + TruckIcon } from '@heroicons/react/24/outline'; const navigationItems = [ { name: 'Przekrój terenu', href: '/', icon: HomeIcon }, { name: 'Siatka', href: '/cross', icon: GridIcon }, { name: 'Uziomy', href: '/uziomy', icon: LightningBoltIcon }, + { name: 'Śledzenie przesyłek', href: '/tracking', icon: TruckIcon }, ]; export default function Layout({ children, title = 'Wastpol' }) { diff --git a/pages/tracking.js b/pages/tracking.js new file mode 100644 index 0000000..0eb12c1 --- /dev/null +++ b/pages/tracking.js @@ -0,0 +1,367 @@ +import { useState, useEffect, useRef } from 'react'; +import Head from 'next/head'; +import { useRouter } from 'next/router'; +import Layout from "../components/ui/Layout"; +import { Card, CardHeader, CardContent, CardTitle } from "../components/ui/components"; + +export default function TrackingPage() { + const router = useRouter(); + const [trackingNumber, setTrackingNumber] = useState(''); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + const [trackingData, setTrackingData] = useState(null); + + // Use ref to keep track of if the component is mounted + const isMounted = useRef(true); + + // Handle tracking number from URL query parameter + useEffect(() => { + if (router.query.number) { + setTrackingNumber(router.query.number); + fetchTrackingData(router.query.number); + } + + return () => { + isMounted.current = false; + }; + }, [router.query.number]); + + // Copy text to clipboard function + const copyToClipboard = (text) => { + navigator.clipboard.writeText(text).catch(err => { + console.error('Failed to copy text: ', err); + }); + }; + + // Format date to Polish locale + const formatDate = (dateString) => { + const date = new Date(dateString); + return date.toLocaleString('pl-PL', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); + }; + + // Get country flag emoji + const getCountryFlag = (countryCode) => { + const flags = { + 'PL': '🇵🇱', + 'DE': '🇩🇪', + 'FR': '🇫🇷', + 'GB': '🇬🇧', + 'US': '🇺🇸', + 'IT': '🇮🇹', + 'ES': '🇪🇸', + 'NL': '🇳🇱', + 'BE': '🇧🇪', + 'CZ': '🇨🇿', + 'SK': '🇸🇰', + 'AT': '🇦🇹', + 'CH': '🇨🇭' + }; + return flags[countryCode] || '🌍'; + }; + + // Validate tracking number format + const isValidTrackingNumber = (number) => { + return number && number.length >= 13 && /^[0-9A-Z]+$/.test(number.replace(/\s/g, '')); + }; + + // No longer needed - removed map-related function + + // Handle form submission + const handleSubmit = (e) => { + e.preventDefault(); + if (trackingNumber) { + fetchTrackingData(trackingNumber); + } + }; + + // Fetch tracking data from API + const fetchTrackingData = async (number) => { + if (!number) { + setError('Proszę wprowadzić numer przesyłki.'); + return; + } + + if (!isValidTrackingNumber(number)) { + setError('Nieprawidłowy format numeru przesyłki. Numer powinien zawierać tylko cyfry i litery.'); + return; + } + + setLoading(true); + setError(''); + setTrackingData(null); + + const apiKey = + "GI42fpjWMcTGI2oY0DAN4IulxR3QZy8+XhA2oPE17HB6P5JA+BTvuY5gIH0imCa2ZmH/vieaE66A/bRnSlsh3RIWVPHPtR5qVflsHx2mBtDAnzWFBmzZeDg8zVIPIPRN7TyM/SzqHDkt5IdfnRDRXKO5p/Bc/1Jpj0JpNKs+NTk=.RjcxMEEwRjI3NjA1QURGMjNCNzc4NTVGOTY0NkQ0RTA5NDQ4NTgxNzE2RTNEREFGMTkwNkU2QjlFRTlEMzEzRg==.443a0acd4c7d4417b55e1ae9e755d91a"; + const url = `https://uss.poczta-polska.pl/uss/v2.0/tracking/checkmailex?language=PL&number=${number}&addPostOfficeInfo=true&events=true&states=true`; + + try { + const response = await fetch(url, { + method: "GET", + headers: { + Accept: "application/json", + "Content-Type": "application/json", + api_key: apiKey, + }, + }); + + if (!response.ok) { + if (response.status === 404) { + throw new Error('Nie znaleziono przesyłki o podanym numerze.'); + } else if (response.status === 403) { + throw new Error('Brak autoryzacji do API. Skontaktuj się z administratorem.'); + } else { + throw new Error(`Błąd serwera: ${response.status}. Spróbuj ponownie później.`); + } + } + + const data = await response.json(); + + if (!data.mailInfo) { + throw new Error('Brak danych o przesyłce. Sprawdź numer i spróbuj ponownie.'); + } + + if (isMounted.current) { + setTrackingData(data); + } + } catch (error) { + console.error("Error fetching tracking data:", error); + if (isMounted.current) { + setError(error.message || 'Wystąpił błąd podczas pobierania danych. Sprawdź połączenie internetowe i spróbuj ponownie.'); + } + } finally { + if (isMounted.current) { + setLoading(false); + } + } + }; + + // Create a comprehensive timeline combining states and events + const getTimeline = (mailInfo) => { + if (!mailInfo) return []; + + const timeline = []; + + // Add states to timeline + if (mailInfo.states) { + mailInfo.states.forEach(state => { + timeline.push({ + type: 'state', + data: state, + time: new Date(state.time) + }); + }); + } + + // Add events to timeline + if (mailInfo.events) { + mailInfo.events.forEach(event => { + timeline.push({ + type: 'event', + data: event, + time: new Date(event.time) + }); + }); + } + + // Sort timeline by time (oldest first) + return timeline.sort((a, b) => a.time - b.time); + }; + + // Handle button click for copying tracking number + const handleCopy = () => { + if (trackingData?.mailInfo?.number) { + copyToClipboard(trackingData.mailInfo.number); + } + }; + + return ( + +
+ {/* Page Header */} +
+

+ Śledzenie przesyłek +

+

+ Sprawdź status przesyłki +

+
+ + {/* Input Card */} + + + Wyszukiwanie przesyłki + + +
+ setTrackingNumber(e.target.value)} + placeholder="Wprowadź numer przesyłki (np. 00659007734210841438)" + maxLength="50" + className="flex-1 min-w-[250px] block rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 transition-colors p-2.5 border" + /> + +
+
+
+ + {loading && ( +
+
+ Pobieranie danych... +
+ )} + + {error && ( +
+

{error}

+
+ )} + + {trackingData && trackingData.mailInfo && ( + <> + {/* Package Information Card */} + + + Dane przesyłki + + +
+
+ Numer przesyłki: + {trackingData.mailInfo.number} + +
+ +
+ Typ przesyłki: + {trackingData.mailInfo.typeOfMailName} +
+ +
+ Doręczono: + + {trackingData.mailInfo.finished ? "✓ Tak" : "⏳ Nie"} + +
+ +
+
+ 🏁 Nadanie: + + {getCountryFlag(trackingData.mailInfo.dispatchCountryCode)} {trackingData.mailInfo.dispatchCountryName} + +
+
+ 🎯 Doręczenie: + + {getCountryFlag(trackingData.mailInfo.recipientCountryCode)} {trackingData.mailInfo.recipientCountryName} + +
+
+
+
+
+ + {/* Package History Card */} + + + Historia przesyłki + + + {getTimeline(trackingData.mailInfo).length > 0 ? ( +
+ {getTimeline(trackingData.mailInfo).map((item, index) => { + if (item.type === 'state') { + // Find related events for this state + const relatedEvents = trackingData.mailInfo.events ? + trackingData.mailInfo.events.filter(event => + event.state && event.state.code === item.data.code + ) : []; + + return ( +
+
+
+
📦 {item.data.name}
+
🕒 {formatDate(item.data.time)}
+
+ {relatedEvents.map((event, eventIndex) => ( +
+
📋 {event.name}
+
🕒 {formatDate(event.time)}
+ {event.postOffice && event.postOffice.description && ( +
+ 📍 {event.postOffice.description.city}, {event.postOffice.description.street} {event.postOffice.description.houseNumber} +
+ )} +
+ ))} +
+ ); + } else if (item.type === 'event') { + // Only show standalone events (not linked to states) + const isLinkedToState = trackingData.mailInfo.states && + trackingData.mailInfo.states.some(state => + item.data.state && item.data.state.code === state.code + ); + + if (!isLinkedToState) { + return ( +
+
+
+
📋 {item.data.name}
+
🕒 {formatDate(item.data.time)}
+ {item.data.postOffice && item.data.postOffice.description && ( +
+ 📍 {item.data.postOffice.description.city}, {item.data.postOffice.description.street} {item.data.postOffice.description.houseNumber} +
+ )} +
+
+ ); + } + return null; + } + return null; + })} +
+ ) : ( +
+

Brak dostępnych informacji o historii przesyłki

+
+ )} +
+
+ + )} + +
+
+ ); +}