kios-webapp/astro/src/components/KiosMap.tsx

249 lines
6.0 KiB
TypeScript

import React, { useEffect } from 'react';
import { MapContainer, TileLayer, Marker, CircleMarker, Popup, Polyline, LayerGroup, GeoJSON, } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L, { LatLngBounds } from 'leaflet';
import { useQuery, useMutation, useQueryClient, queryOptions } from "@tanstack/react-query";
import axios from "axios";
//Todo: Move types to own file
type User = {
name: string;
id: string;
email: string;
phoneNumber: string;
}
type Product = {
id: string;
title: string;
weight?: number;
picture: string;
createdAt: string;
updatedAt: string;
};
// type Location = {
// latitude: number;
// longitude: number;
// }
type Maker = {
id: string;
name: string;
email: string;
phoneNumber?: string;
location: [number, number];
stock: Product[];
createdAt: string;
updatedAt: string;
};
type Retailer = {
id: string;
name: string;
email: string;
phoneNumber?: string;
location: [number, number];
stock: Product[];
createdAt: string;
updatedAt: string;
};
const DISPATCH_STATUS = ['requested', 'accepted', 'archived'] as const;
type DispatchStatus = typeof DISPATCH_STATUS[number];
type Dispatch = {
id: string;
dispatchesCode?: string; //Human readable id
createdAt: string;
updatedAt: string;
maker?: Maker;
retailer?: Retailer;
products: Product[];
courier?: User;
timeSensitive: boolean;
status: DispatchStatus[];
departureDate: string;
arrivalDate: string;
weightAllowance: number;
}
//Todo: update fetch url endpoints
//Todo: Move queryclient and hooks to own file
//Todo: Move axios stuff
const API_URL = "http://localhost:3001"
const headers = {
"Content-Type": "application/json",
}
const getMakers = async () => {
const url = `${API_URL}/api/makers`
console.log("Fetching url:", url)
const response = await axios.get(url);
const makers: Maker[] = response.data.docs;
console.log(`Fetch result from ${url}`, makers)
return makers;
}
const useGetMakers = () => {
return useQuery<Maker[]>({
queryFn: () => getMakers(),
queryKey: ['makers'],
enabled: true
})
}
const getRetailers = async () => {
const url = `${API_URL}/api/retailers`
console.log("Fetching url:", url)
const response = await axios.get(url);
const retailers:Retailer[] = response.data.docs;
console.log(`Fetch result from ${url}`, retailers)
return retailers;
}
const useGetRetailers = () => {
return useQuery<Retailer[]>({
queryFn: () => getRetailers(),
queryKey: ['retailers'],
enabled: true
})
}
const getDispatches = async () => {
const url = `${API_URL}/api/dispatches`
console.log("Fetching url:", url)
const response = await axios.get(url);
const dispatches:Dispatch[] = response.data.docs;
console.log(`Fetch result from ${url}`, dispatches)
return dispatches;
}
const useGetDispatches = () => {
return useQuery<Dispatch[]>({
queryFn: () => getDispatches(),
queryKey: ['retailers'],
enabled: true
})
}
export const KiosMap = () => {
const { data: makers, isLoading: isLoadingMakers } = useGetMakers();
const { data: retailers, isLoading: isLoadingRetailers } = useGetRetailers();
const { data: dispatches, isLoading: isLoadingDispatches } = useGetDispatches();
const blackDotIcon = L.divIcon({
className: 'bg-gray-950 rounded-full',
iconSize: [20, 20],
iconAnchor: [10, 10]
});
const bounds = new LatLngBounds(
[-90, -180], // Southwest corner
[90, 180] // Northeast corner
);
return (
<div className='w-full flex justify-center align-middle'>
<MapContainer
id="map"
center={[-6.1815, 106.8228]}
zoom={3}
maxBounds={bounds} // Restrict panning beyond these bounds
maxBoundsViscosity={0.9} // How strongly to snap the map's bounds to the restricted area
style={{ height: '800px', width: '100%' }}
>
<TileLayer url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
maxZoom={19}
attribution='&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
/>
{makers &&
<LayerGroup>
{makers.map((maker: any, index: number) => (
<Marker
key={index}
position={[maker.location[0], maker.location[1]]}
icon={blackDotIcon}
>
<Popup>{maker.name}</Popup>
</Marker>
))}
</LayerGroup>
}
{retailers &&
<LayerGroup>
{retailers.map((retailer: any, index: number) => (
<Marker
key={index}
position={[retailer.location[0], retailer.location[1]]}
icon={blackDotIcon}
>
<Popup>{retailer.name}</Popup>
</Marker>
))}
</LayerGroup>
}
{dispatches &&
<LayerGroup>
{dispatches.map((dispatch: any, index: number) => {
const start = dispatch.maker.location;
const end = dispatch.retailer.location;
let productsString = '';
dispatch.products.forEach((product: any, i: number) => {
productsString += product.productTitle + (i + 1 < dispatch.products.length ? ', ' : '');
});
const myDashArray =
dispatch.status === 'requested' ? '20, 10' :
dispatch.status === 'archived' ? '1, 5' :
'0, 0';
return (
<div key={index}>
<Marker position={[start[0], start[1]]}
icon={blackDotIcon}
>
<Popup>{dispatch.startingPoint.name}</Popup>
</Marker>
<Marker position={[end[0], end[1]]}
icon={blackDotIcon}
>
<Popup>{dispatch.endPoint.name}</Popup>
</Marker>
<Polyline
positions={[[start[0], start[1]], [end[0], end[1]]]}
color="#000"
dashArray={myDashArray} />
</div>
);
})}
</LayerGroup>
}
</MapContainer >
</div>
);
};