add map to new mission on rowAction of operators #7

Merged
aminghasempoor merged 1 commits from feature/routing into develop 2026-06-14 06:35:03 +00:00
8 changed files with 368 additions and 46 deletions
Showing only changes of commit a9a996e1e8 - Show all commits

View File

@@ -0,0 +1,28 @@
import { Box, Typography } from "@mui/material";
const AlarmText = ({ isSource }) => {
if (isSource) return null;
return (
<Box
sx={{
position: "absolute",
top: 5,
left: 5,
zIndex: 1000,
border: "1px solid #ed0f02",
backgroundColor: "#f19898",
py: 0.5,
px: 1,
borderRadius: 2,
opacity: 0.8,
boxShadow: "rgba(0, 0, 0, 0.35) 0px 5px 15px",
}}
>
<Typography variant="caption" sx={{ fontWeight: "bold" }} color="#ed0f02">
با کلیک بر روی مارکر موقعیت را انتخاب کنید
</Typography>
</Box>
);
};
export default AlarmText;

View File

@@ -0,0 +1,53 @@
import { Box, Button, TextField } from "@mui/material";
const DataBox = ({ isSource, isDest, sourcePosition, destPosition, editingTarget, onEditSource, onEditDest }) => {
if (!isSource) return null;
return (
<Box
sx={{
position: "absolute",
bottom: 5,
left: 5,
zIndex: 1000,
backgroundColor: "white",
border: "1px solid #e1e1e1",
padding: 1,
borderRadius: 2,
opacity: 0.8,
gap: 1,
display: "flex",
flexDirection: "column",
}}
>
<div style={{ display: "flex", alignItems: "end", gap: 4 }}>
<TextField
variant="outlined"
size="small"
readOnly
value={sourcePosition ? `${sourcePosition.lat.toFixed(6)}, ${sourcePosition.lng.toFixed(6)}` : ""}
/>
{isSource && isDest && (
<Button variant="contained" color="success" size="small" onClick={onEditSource}>
ویرایش مبدا
</Button>
)}
</div>
{isDest && (
<div style={{ display: "flex", alignItems: "end", gap: 4 }}>
<TextField
size="small"
variant="outlined"
readOnly
value={destPosition ? `${destPosition.lat.toFixed(6)}, ${destPosition.lng.toFixed(6)}` : ""}
/>
<Button variant="contained" color="error" size="small" onClick={onEditDest}>
ویرایش مقصد
</Button>
</div>
)}
</Box>
);
};
export default DataBox;

View File

@@ -0,0 +1,46 @@
import { useEffect, useRef } from "react";
import { Marker, Polyline, useMap } from "react-leaflet";
import L from "leaflet";
import polyline from "@mapbox/polyline";
import SourceIcon from "@/assets/images/source-icon.svg";
import DestIcon from "@/assets/images/destination-icon.svg";
const ShowRoute = ({ area }) => {
const map = useMap();
const defaultIconSize = [35, 35];
const createCustomIcon = (size, iconUrl) => {
return L.icon({
iconUrl: iconUrl,
iconSize: size,
iconAnchor: [size[0] / 2, size[1]],
popupAnchor: [0, -size[1]],
});
};
useEffect(() => {
if (coords.length > 0) {
map.flyToBounds(coords, { padding: [50, 50], duration: 1.5 });
}
}, [area]);
const sourceIcon = createCustomIcon(defaultIconSize, SourceIcon.src);
const destIcon = createCustomIcon(defaultIconSize, DestIcon.src);
if (!area) return null;
const coords = polyline.decode(area, 6);
if (coords.length === 0) return null;
const sourcePosition = coords[0];
const destPosition = coords[coords.length - 1];
return (
<>
<Polyline positions={coords} color="#015688" weight={7} opacity={1} />
<Marker position={sourcePosition} icon={sourceIcon} />
<Marker position={destPosition} icon={destIcon} />
</>
);
};
export default ShowRoute;

View File

@@ -0,0 +1,219 @@
import { Marker, Polyline, useMapEvents } from "react-leaflet";
import L from "leaflet";
import polyline from "@mapbox/polyline";
import SourceIcon from "@/assets/images/source-icon.svg";
import PrevSourceIcon from "@/assets/images/prev-source-icon.svg";
import PrevDestIcon from "@/assets/images/prev-destination-icon.svg";
import DestIcon from "@/assets/images/destination-icon.svg";
import { useEffect, useRef, useState } from "react";
import DataBox from "./DataBox";
import AlarmText from "./AlarmText";
const Routing = ({ setArea, setLocations, locations, area }) => {
const mapPrevSourceMarker = useRef();
const mapPrevDestMarker = useRef();
const mapRef = useRef(null);
const defaultIconSize = [35, 35];
const [isSource, setIsSource] = useState(false);
const [sourcePosition, setSourcePosition] = useState(null);
const [isDest, setIsDest] = useState(false);
const [destPosition, setDestPosition] = useState(null);
const [routeCoords, setRouteCoords] = useState([]);
const [alternateCoords, setAlternateCoords] = useState([]);
const [editingTarget, setEditingTarget] = useState(null);
const [selectedRoute, setSelectedRoute] = useState(null);
const createCustomIcon = (size, iconUrl) => {
return L.icon({
iconUrl: iconUrl,
iconSize: size,
iconAnchor: [size[0] / 2, size[1]],
popupAnchor: [0, -size[1]],
});
};
const defaultIcon = createCustomIcon(
defaultIconSize,
isSource && editingTarget !== "source" ? SourceIcon.src : PrevSourceIcon.src
);
const prevDestIcon = createCustomIcon(
defaultIconSize,
isDest && editingTarget !== "dest" ? DestIcon.src : PrevDestIcon.src
);
const isMovingSource = !isSource || editingTarget === "source";
const isMovingDest = isSource && (!isDest || editingTarget === "dest");
const map = useMapEvents({
move(e) {
if (isMovingSource) mapPrevSourceMarker.current.setLatLng(e.target.getCenter());
if (isMovingDest && mapPrevDestMarker.current) mapPrevDestMarker.current.setLatLng(e.target.getCenter());
},
movestart() {
if (isMovingSource) mapPrevSourceMarker.current.setIcon(createCustomIcon([45, 45], PrevSourceIcon.src));
if (isMovingDest && mapPrevDestMarker.current)
mapPrevDestMarker.current.setIcon(createCustomIcon([45, 45], PrevDestIcon.src));
},
moveend() {
if (isMovingSource)
mapPrevSourceMarker.current.setIcon(createCustomIcon(defaultIconSize, PrevSourceIcon.src));
if (isMovingDest && mapPrevDestMarker.current)
mapPrevDestMarker.current.setIcon(createCustomIcon(defaultIconSize, PrevDestIcon.src));
},
});
useEffect(() => {
mapRef.current = map;
}, [map]);
useEffect(() => {
if (locations.length < 2) return;
const restoredSource = { lat: locations[0].lat, lng: locations[0].lon };
const restoredDest = { lat: locations[1].lat, lng: locations[1].lon };
setSourcePosition(restoredSource);
setDestPosition(restoredDest);
setIsSource(true);
setIsDest(true);
if (area) {
const decoded = polyline.decode(area, 6);
setRouteCoords(decoded);
setSelectedRoute({ index: "main", coords: decoded });
setTimeout(() => {
mapRef.current?.flyToBounds(decoded, { padding: [50, 50], duration: 1.5 });
}, 100);
} else {
fetchRoute(restoredSource, restoredDest);
}
}, []);
const fetchRoute = async (source, dest) => {
const locs = [
{ lat: source.lat, lon: source.lng },
{ lat: dest.lat, lon: dest.lng },
];
try {
const response = await fetch("https://jouya.141.ir/api/router/drive", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: locs }),
});
const data = await response.json();
const shape = data.trip.legs[0].shape;
setLocations(locs);
setArea(shape);
const decoded = polyline.decode(shape, 6);
setRouteCoords(decoded);
setSelectedRoute({ index: "main", coords: decoded });
if (data.alternates?.length > 0) {
const decodedAlternates = data.alternates.map((alt) => polyline.decode(alt.trip.legs[0].shape, 6));
setAlternateCoords(decodedAlternates);
} else {
setAlternateCoords([]);
}
map.flyToBounds(decoded, { padding: [50, 50], duration: 1.5 });
} catch (error) {
console.error("Routing error:", error);
}
};
const handleMarkerClick = async () => {
if (!isSource || editingTarget === "source") {
const clickedPosition = mapPrevSourceMarker.current.getLatLng();
setSourcePosition(clickedPosition);
setIsSource(true);
setEditingTarget(null);
setRouteCoords([]);
setAlternateCoords([]);
setSelectedRoute(null);
if (editingTarget === "source" && destPosition) {
await fetchRoute(clickedPosition, destPosition);
}
}
};
const handleDestMarkerClick = async () => {
if (!isDest || editingTarget === "dest") {
const clickedPosition = mapPrevDestMarker.current.getLatLng();
setDestPosition(clickedPosition);
setIsDest(true);
setEditingTarget(null);
await fetchRoute(sourcePosition, clickedPosition);
}
};
const handleEditSource = () => {
setEditingTarget("source");
setRouteCoords([]);
setAlternateCoords([]);
setSelectedRoute(null);
};
const handleEditDest = () => {
setEditingTarget("dest");
setRouteCoords([]);
setAlternateCoords([]);
setSelectedRoute(null);
};
const handleSelectRoute = (index, coords) => {
setSelectedRoute({ index, coords });
const encoded = polyline.encode(coords, 6);
setArea(encoded);
map.flyToBounds(coords, { padding: [50, 50], duration: 0.3 });
};
return (
<>
<DataBox
isSource={isSource}
isDest={isDest}
sourcePosition={sourcePosition}
destPosition={destPosition}
editingTarget={editingTarget}
onEditSource={handleEditSource}
onEditDest={handleEditDest}
/>
<AlarmText isSource={isSource} />
<Marker
position={sourcePosition || map.getCenter()}
ref={mapPrevSourceMarker}
eventHandlers={{ click: handleMarkerClick }}
icon={defaultIcon}
/>
{isSource && (
<Marker
position={destPosition || map.getCenter()}
ref={mapPrevDestMarker}
eventHandlers={{ click: handleDestMarkerClick }}
icon={prevDestIcon}
/>
)}
{alternateCoords.map((coords, index) => (
<Polyline
key={`alternate-${index}-${selectedRoute?.index === index}`}
positions={coords}
color={selectedRoute?.index === index ? "#015688" : "#91B2C6"}
weight={selectedRoute?.index === index ? 7 : 6}
opacity={selectedRoute?.index === index ? 1 : 0.7}
eventHandlers={{ click: () => handleSelectRoute(index, coords) }}
/>
))}
{routeCoords.length > 0 && (
<Polyline
key={`main-${selectedRoute?.index === "main"}`}
positions={routeCoords}
color={selectedRoute?.index === "main" ? "#015688" : "#91B2C6"}
weight={selectedRoute?.index === "main" ? 7 : 6}
opacity={selectedRoute?.index === "main" ? 1 : 0.7}
eventHandlers={{ click: () => handleSelectRoute("main", routeCoords) }}
/>
)}
</>
);
};
export default Routing;

View File

@@ -2,41 +2,29 @@ import MapLoading from "@/core/components/MapLayer/Loading";
import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material";
import dynamic from "next/dynamic";
import { useCallback, useState } from "react";
import MapControlPolygon from "./MapControlPolygon";
import MapControlPolyline from "./MapControlPolyline";
import SelectBoundType from "./SelectBoundType";
import OldBoundLayer from "./OldBoundLayer";
import Routing from "./Routing";
const MapLayer = dynamic(() => import("@/core/components/MapLayer"), {
loading: () => <MapLoading />,
ssr: false,
});
const Area = ({ allData, setAllData, handlePrev, setTabState, oldBound }) => {
const [bound, setBound] = useState(allData.bound);
const [boundType, setBoundType] = useState(allData.bound_type);
const Area = ({ allData, setAllData, handlePrev, setTabState }) => {
const [area, setArea] = useState(allData.area);
const [locations, setLocations] = useState(allData.locations);
const handleNext = useCallback(() => {
setAllData({ bound: bound });
setAllData({ area: area });
setAllData({ locations: locations });
setTabState((s) => s + 1);
}, [bound]);
}, [area]);
return (
<>
<DialogContent dividers>
<Stack spacing={2}>
<SelectBoundType
boundType={boundType}
setBoundType={setBoundType}
setBound={setBound}
setAllData={setAllData}
/>
<Box sx={{ width: "100%", height: "400px" }}>
<MapLayer style={{ borderRadius: "4px" }}>
{boundType == "polygon" ? (
<MapControlPolygon bound={bound} setBound={setBound} boundType={boundType} />
) : (
<MapControlPolyline bound={bound} setBound={setBound} boundType={boundType} />
)}
<OldBoundLayer bound={oldBound} />
<Routing area={area} setArea={setArea} locations={locations} setLocations={setLocations} />
</MapLayer>
</Box>
</Stack>
@@ -45,8 +33,8 @@ const Area = ({ allData, setAllData, handlePrev, setTabState, oldBound }) => {
<Button onClick={handlePrev} variant="outlined" color="secondary" size="large">
{"مرحله قبلی"}
</Button>
<Button variant="contained" size="large" disabled={!bound} onClick={handleNext}>
{!bound ? "در انتظار ترسیم" : "مرحله بعد"}
<Button variant="contained" size="large" disabled={!area} onClick={handleNext}>
{!area ? "در انتظار ترسیم" : "مرحله بعد"}
</Button>
</DialogActions>
</>

View File

@@ -5,7 +5,7 @@ import { Box, Button, Chip, DialogActions, DialogContent, Divider, Stack, Typogr
import moment from "jalali-moment";
import dynamic from "next/dynamic";
import { useCallback } from "react";
import ShowBound from "../../../../../../Actions/showBound";
import ShowRoute from "../Area/Routing/ShowRoute";
const MapLayer = dynamic(() => import("@/core/components/MapLayer"), {
loading: () => <MapLoading />,
ssr: false,
@@ -23,7 +23,7 @@ const Verify = ({ allData, handlePrev, submitForm, submitting }) => {
<Stack spacing={2}>
<Box sx={{ width: "100%", height: "200px" }}>
<MapLayer style={{ borderRadius: "4px" }}>
<ShowBound bound={allData.bound} />
<ShowRoute area={allData.area} />
</MapLayer>
</Box>
<Stack spacing={1}>
@@ -93,11 +93,11 @@ const Verify = ({ allData, handlePrev, submitForm, submitting }) => {
label={`${allData.machine.machine_code} | ${allData.machine.car_name}`}
/>
</Stack>
<Stack direction={"row"} alignItems={"center"} spacing={1}>
{/* <Stack direction={"row"} alignItems={"center"} spacing={1}>
<Typography variant="body2">راننده</Typography>
<Divider sx={{ flex: 1 }} />
<Chip size="small" label={`${allData.driver.code} | ${allData.driver.name}`} />
</Stack>
</Stack> */}
</Stack>
<Stack spacing={1}>
<Divider>

View File

@@ -25,6 +25,8 @@ const reducer = (state, action) => {
};
const CreateForm = ({ defaultValues, submitForm, setOpen, submitting, oldBound }) => {
console.log("defaultValues", defaultValues);
const [allData, dispatch] = useReducer(reducer, defaultValues);
const [tabState, setTabState] = useState(0);
const handleClose = () => {
@@ -84,7 +86,6 @@ const CreateForm = ({ defaultValues, submitForm, setOpen, submitting, oldBound }
</TabPanel>
<TabPanel value={tabState} index={2}>
<Area
oldBound={oldBound}
allData={allData}
setAllData={(data) => {
dispatch({ type: "changeData", data });

View File

@@ -10,22 +10,12 @@ const DialogAdd = ({ mutate, setOpen, oldBound, rahdaran, machine, row }) => {
const submitForm = async (result) => {
setSubmitting(true);
const bound = result.bound.getLatLngs();
let area =
result.bound_type === "polygon"
? bound.map((ring) => ring.map((latlng) => [latlng.lng, latlng.lat]))[0]
: bound.map((latlng) => [latlng.lng, latlng.lat]);
// بستن polygon
if (result.bound_type === "polygon" && area.length > 0) {
const firstPoint = area[0];
area.push({ ...firstPoint });
}
await requestServer(`${REQUEST_MISSION_CONTINUE_MISSION}/${row.original.id}`, "post", {
data: {
...(result.rahdaran.length != 0 ? { rahdaran: result.rahdaran.map((r) => r.id) } : {}),
machine_id: result.machine.id,
driver: result.driver.id,
encoded_route: result.area,
driver: row.original.driver_id,
zone: result.region,
type: result.type,
...(result.type == 1
@@ -36,10 +26,6 @@ const DialogAdd = ({ mutate, setOpen, oldBound, rahdaran, machine, row }) => {
end_date: result.end_date,
}),
end_point: result.end_point,
area: {
type: result.bound_type,
coordinates: area,
},
category_id: result.category_id,
explanation: result.explanation,
...(result.category_id == 3
@@ -65,7 +51,6 @@ const DialogAdd = ({ mutate, setOpen, oldBound, rahdaran, machine, row }) => {
defaultValues={{
explanation: "",
category_id: "",
bound: null,
rahdaran: rahdaran.filter((r) => !r.is_driver),
bound_type: "polyline",
type: "",
@@ -74,7 +59,9 @@ const DialogAdd = ({ mutate, setOpen, oldBound, rahdaran, machine, row }) => {
end_point: "",
region: "",
machine: machine,
driver: rahdaran.find((r) => r.is_driver),
driver: row.original.driver_id,
area: null,
locations: [],
}}
oldBound={oldBound}
submitForm={submitForm}