feat: Add MapComponent for displaying location on a map and TrackingPage for tracking shipments
This commit is contained in:
68
components/MapComponent.js
Normal file
68
components/MapComponent.js
Normal file
@@ -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(`
|
||||
<div style="font-family: 'Segoe UI', sans-serif;">
|
||||
<h4 style="margin: 0 0 8px 0; color: #004d99;">${name}</h4>
|
||||
<p style="margin: 4px 0;"><strong>📍 Adres:</strong><br>${description.street} ${description.houseNumber}<br>${description.zipCode} ${description.city}</p>
|
||||
<p style="margin: 4px 0;"><strong>🏢 Typ:</strong> ${officeType === 'UP' ? 'Urząd Pocztowy' : officeType}</p>
|
||||
</div>
|
||||
`, {
|
||||
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 <div id="map" style={{ height: '400px', borderRadius: '8px' }}></div>;
|
||||
};
|
||||
|
||||
export default MapComponent;
|
||||
@@ -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' }) {
|
||||
|
||||
367
pages/tracking.js
Normal file
367
pages/tracking.js
Normal file
@@ -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 (
|
||||
<Layout title="Śledzenie przesyłek">
|
||||
<div className="p-6 max-w-7xl mx-auto">
|
||||
{/* Page Header */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Śledzenie przesyłek
|
||||
</h1>
|
||||
<p className="text-gray-600">
|
||||
Sprawdź status przesyłki
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Input Card */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader className="border-b bg-gray-50">
|
||||
<CardTitle>Wyszukiwanie przesyłki</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6">
|
||||
<form onSubmit={handleSubmit} className="flex flex-wrap gap-4">
|
||||
<input
|
||||
type="text"
|
||||
value={trackingNumber}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2.5 px-5 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? 'Wyszukiwanie...' : 'Szukaj'}
|
||||
</button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center p-4 mb-6">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
|
||||
<span className="ml-3 text-blue-600 font-medium">Pobieranie danych...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-lg">
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{trackingData && trackingData.mailInfo && (
|
||||
<>
|
||||
{/* Package Information Card */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader className="border-b bg-gray-50">
|
||||
<CardTitle>Dane przesyłki</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6">
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold text-gray-700 min-w-[140px]">Numer przesyłki:</span>
|
||||
<span className="text-gray-900">{trackingData.mailInfo.number}</span>
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="ml-2 text-xs border border-blue-600 text-blue-600 hover:bg-blue-600 hover:text-white px-2 py-1 rounded transition-colors"
|
||||
>
|
||||
Kopiuj
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center">
|
||||
<span className="font-semibold text-gray-700 min-w-[140px]">Typ przesyłki:</span>
|
||||
<span className="text-gray-900">{trackingData.mailInfo.typeOfMailName}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center">
|
||||
<span className="font-semibold text-gray-700 min-w-[140px]">Doręczono:</span>
|
||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${
|
||||
trackingData.mailInfo.finished
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{trackingData.mailInfo.finished ? "✓ Tak" : "⏳ Nie"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 mt-4 pt-4 border-t border-gray-200">
|
||||
<div className="flex items-center gap-2 bg-gray-50 px-4 py-3 rounded-lg">
|
||||
<span className="text-gray-700">🏁 Nadanie:</span>
|
||||
<span className="font-medium">
|
||||
{getCountryFlag(trackingData.mailInfo.dispatchCountryCode)} {trackingData.mailInfo.dispatchCountryName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 bg-gray-50 px-4 py-3 rounded-lg">
|
||||
<span className="text-gray-700">🎯 Doręczenie:</span>
|
||||
<span className="font-medium">
|
||||
{getCountryFlag(trackingData.mailInfo.recipientCountryCode)} {trackingData.mailInfo.recipientCountryName}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Package History Card */}
|
||||
<Card>
|
||||
<CardHeader className="border-b bg-gray-50">
|
||||
<CardTitle>Historia przesyłki</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6">
|
||||
{getTimeline(trackingData.mailInfo).length > 0 ? (
|
||||
<div className="relative pl-8 border-l-2 border-blue-500 ml-4">
|
||||
{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 (
|
||||
<div key={`state-${index}`} className="mb-8 relative">
|
||||
<div className="absolute -left-[29px] w-6 h-6 bg-blue-600 rounded-full border-4 border-white"></div>
|
||||
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-3">
|
||||
<div className="font-medium text-blue-700">📦 {item.data.name}</div>
|
||||
<div className="text-sm text-gray-600 mt-1">🕒 {formatDate(item.data.time)}</div>
|
||||
</div>
|
||||
{relatedEvents.map((event, eventIndex) => (
|
||||
<div key={`related-event-${eventIndex}`} className="ml-4 bg-blue-50 rounded-lg p-4 mb-3 border-l-4 border-blue-400">
|
||||
<div className="font-medium text-blue-800">📋 {event.name}</div>
|
||||
<div className="text-sm text-gray-600 mt-1">🕒 {formatDate(event.time)}</div>
|
||||
{event.postOffice && event.postOffice.description && (
|
||||
<div className="mt-2 text-sm bg-white p-2 rounded border border-gray-200">
|
||||
📍 {event.postOffice.description.city}, {event.postOffice.description.street} {event.postOffice.description.houseNumber}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
} 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 (
|
||||
<div key={`event-${index}`} className="mb-8 relative">
|
||||
<div className="absolute -left-[29px] w-6 h-6 bg-gray-400 rounded-full border-4 border-white"></div>
|
||||
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
|
||||
<div className="font-medium text-gray-700">📋 {item.data.name}</div>
|
||||
<div className="text-sm text-gray-600 mt-1">🕒 {formatDate(item.data.time)}</div>
|
||||
{item.data.postOffice && item.data.postOffice.description && (
|
||||
<div className="mt-2 text-sm bg-gray-50 p-2 rounded border border-gray-200">
|
||||
📍 {item.data.postOffice.description.city}, {item.data.postOffice.description.street} {item.data.postOffice.description.houseNumber}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 bg-gray-50 rounded-lg">
|
||||
<p className="text-gray-600">Brak dostępnych informacji o historii przesyłki</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user