Compare commits

...

3 Commits

Author SHA1 Message Date
toqvist ed420d5ff1 Make map nodes selectable and stylish
continuous-integration/drone/push Build is passing Details
2024-04-05 15:03:18 +02:00
toqvist 12c43e9a00 Style dispatches 2024-04-05 13:38:19 +02:00
toqvist 1a2d143c4f Fix dispatches 2024-04-05 13:07:17 +02:00
4 changed files with 166 additions and 109 deletions

View File

@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import { MapContainer, TileLayer, Marker, CircleMarker, Popup, Polyline, LayerGroup, GeoJSON, } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L, { LatLngBounds } from 'leaflet';
@ -7,30 +7,33 @@ import { useQuery, useMutation, useQueryClient, queryOptions } from "@tanstack/r
import axios from "axios";
//Todo: Move types to own file
type User = {
interface User {
name: string;
id: string;
email: string;
phoneNumber: string;
}
type Product = {
interface Node {
name: string;
id: string;
title: string;
}
interface Product extends Node {
id: string;
name: string;
weight?: number;
picture: string;
createdAt: string;
updatedAt: string;
};
// type Location = {
// interface Location = {
// latitude: number;
// longitude: number;
// }
type Maker = {
id: string;
name: string;
interface Maker extends Node {
email: string;
phoneNumber?: string;
location: [number, number];
@ -39,9 +42,7 @@ type Maker = {
updatedAt: string;
};
type Retailer = {
id: string;
name: string;
interface Retailer extends Node {
email: string;
phoneNumber?: string;
location: [number, number];
@ -53,7 +54,7 @@ type Retailer = {
const DISPATCH_STATUS = ['requested', 'accepted', 'archived'] as const;
type DispatchStatus = typeof DISPATCH_STATUS[number];
type Dispatch = {
interface Dispatch {
id: string;
dispatchesCode?: string; //Human readable id
createdAt: string;
@ -64,9 +65,9 @@ type Dispatch = {
products: Product[];
courier?: User;
timeSensitive: boolean;
status: DispatchStatus[];
status: DispatchStatus;
departureDate: string;
arrivalDate: string;
@ -83,8 +84,6 @@ const headers = {
"Content-Type": "application/json",
}
const getMakers = async () => {
const url = `${API_URL}/api/makers`
console.log("Fetching url:", url)
@ -109,7 +108,7 @@ const getRetailers = async () => {
console.log("Fetching url:", url)
const response = await axios.get(url);
const retailers:Retailer[] = response.data.docs;
const retailers: Retailer[] = response.data.docs;
console.log(`Fetch result from ${url}`, retailers)
return retailers;
@ -128,7 +127,8 @@ const getDispatches = async () => {
console.log("Fetching url:", url)
const response = await axios.get(url);
const dispatches:Dispatch[] = response.data.docs;
const dispatches: Dispatch[] = response.data.docs;
console.log(`Fetch result from ${url}`, dispatches)
return dispatches;
@ -137,23 +137,68 @@ const getDispatches = async () => {
const useGetDispatches = () => {
return useQuery<Dispatch[]>({
queryFn: () => getDispatches(),
queryKey: ['retailers'],
queryKey: ['dispatches'],
enabled: true
})
}
//Payload longitude and latitude are mislabeled in payload (lol)
const locationSwitcharoo = (location: number[]) => {
if (location.length === 2) {
const correctedLocation = [location[1], location[0]]
return correctedLocation;
}
console.error("locationSwitcharoo: Location array malformed")
return location
}
const dashArrays: Record<DispatchStatus, string> = {
requested: '20, 10',
accepted: '0, 0',
archived: '1, 5',
}
const dashColors: Record<DispatchStatus, string> = {
requested: '#000',
accepted: '#000',
archived: '#000',
}
const dashColorSelected: string = '#f87171' //same as tw red 400
const dashOpacities: Record<DispatchStatus, number> = {
requested: 0.7,
accepted: 0.7,
archived: 0.5
}
export const KiosMap = () => {
const { data: makers, isLoading: isLoadingMakers } = useGetMakers();
const { data: retailers, isLoading: isLoadingRetailers } = useGetRetailers();
const { data: dispatches, isLoading: isLoadingDispatches } = useGetDispatches();
const [selectedNodeId, setSelectedNodeId] = useState<string>('')
const handleSelectNode = (nodeId: string) => {
setSelectedNodeId(nodeId)
console.log("set id:", nodeId)
}
const blackDotIcon = L.divIcon({
className: 'bg-gray-950 rounded-full',
iconSize: [20, 20],
iconAnchor: [10, 10]
});
const selectedDotIcon = L.divIcon({
className: 'bg-red-400 rounded-full ring-offset-2 ring-4 ring-red-400 ring-dashed',
iconSize: [20, 20],
iconAnchor: [10, 10]
});
const bounds = new LatLngBounds(
[-90, -180], // Southwest corner
@ -162,86 +207,94 @@ export const KiosMap = () => {
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>'
/>
<div className=''>
<div></div>
</div>
<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>
}
{(makers && !isLoadingMakers) &&
<LayerGroup>
{makers.map((maker: any, index: number) => (
<Marker
eventHandlers={{
click: () => handleSelectNode(maker.id)
}}
key={maker.id}
position={[locationSwitcharoo(maker.location)[0], locationSwitcharoo(maker.location)[1]]}
icon={selectedNodeId === maker.id ? selectedDotIcon : 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>
}
{(retailers && !isLoadingRetailers) &&
<LayerGroup>
{retailers.map((retailer: any, index: number) => (
<Marker
eventHandlers={{
click: () => handleSelectNode(retailer.id)
}}
key={retailer.id}
position={[locationSwitcharoo(retailer.location)[0], locationSwitcharoo(retailer.location)[1]]}
icon={selectedNodeId === retailer.id ? selectedDotIcon : 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;
{(dispatches && !isLoadingDispatches) &&
<LayerGroup>
{dispatches.map((dispatch: any, index: number) => {
let productsString = '';
dispatch.products.forEach((product: any, i: number) => {
productsString += product.productTitle + (i + 1 < dispatch.products.length ? ', ' : '');
});
if (dispatch.maker && dispatch.retailer) {
const myDashArray =
dispatch.status === 'requested' ? '20, 10' :
dispatch.status === 'archived' ? '1, 5' :
'0, 0';
const start = locationSwitcharoo(dispatch.maker.location);
const end = locationSwitcharoo(dispatch.retailer.location);
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 >
let productsString = '';
dispatch.products.forEach((product: any, i: number) => {
productsString += product.productTitle + (i + 1 < dispatch.products.length ? ', ' : '');
});
//status type should already be inferred when list of dispatches is created, weird that is is required
const status: DispatchStatus = dispatch.status;
const dashArray: string = dashArrays[status]
const dashColor: string = dashColors[status]
const dashOpacity: number = dashOpacities[status]
return (
<Polyline
eventHandlers={{
click: () => handleSelectNode(dispatch.id)
}}
key={dispatch.id}
positions={[[start[0], start[1]], [end[0], end[1]]]}
pathOptions={{color: selectedNodeId === dispatch.id ? dashColorSelected : dashColor}}
opacity={dashOpacity}
dashArray={dashArray} />
);
}
})}
</LayerGroup>
}
</MapContainer >
</div>
);
};

View File

@ -52,17 +52,18 @@ export interface Courier {
}
export interface Dispatch {
id: string;
code: string;
products: string[] | Product[];
courier?: string | Courier;
maker?: string | Maker;
retailer?: string | Retailer;
status: ('requested' | 'accepted' | 'archived')[];
maker: string | Maker;
retailer: string | Retailer;
status: 'requested' | 'accepted' | 'archived';
updatedAt: string;
createdAt: string;
}
export interface Product {
id: string;
title: string;
name: string;
picture: string | Media;
weight?: number;
updatedAt: string;

View File

@ -3,17 +3,20 @@ import { CollectionConfig } from 'payload/types';
const Dispatches: CollectionConfig = {
slug: 'dispatches',
admin: {
useAsTitle: 'dispatchesCode',
useAsTitle: 'code',
},
access: {
read: () => true,
},
fields: [
// {
// name: 'dispatchesCode',
// type: 'text',
// required: false,
// },
{
name: 'code',
type: 'text',
required: true,
maxLength: 20,
unique: true,
label: "Code, a unique name for the dispatch"
},
{
name: 'products',
type: 'relationship',
@ -33,19 +36,19 @@ const Dispatches: CollectionConfig = {
type: 'relationship',
relationTo: 'makers',
hasMany: false,
required: false
required: true
},
{
name: 'retailer',
type: 'relationship',
relationTo: 'retailers',
hasMany: false,
required: false
required: true
},
{
name: 'status',
type: 'select',
hasMany: true,
hasMany: false,
required: true,
options: [
{

View File

@ -3,14 +3,14 @@ import { CollectionConfig } from 'payload/types';
const Products: CollectionConfig = {
slug: 'products',
admin: {
useAsTitle: 'productTitle',
useAsTitle: 'name',
},
access: {
read: () => true,
},
fields: [
{
name: 'title',
name: 'name',
type: 'text',
required: true,
},