Sửa lỗi hiển thị điểm đầu và điểm cuối của lộ trình trên bản đồ
This commit is contained in:
+109
-57
@@ -32,7 +32,12 @@ function MapTracker() {
|
||||
moveend: (e) => {
|
||||
const map = e.target;
|
||||
const center = map.getCenter();
|
||||
setMapCenter([center.lat, center.lng]);
|
||||
const zoom = map.getZoom();
|
||||
const coords: [number, number] = [center.lat, center.lng];
|
||||
|
||||
setMapCenter(coords);
|
||||
// Lưu vị trí và mức zoom vào localStorage để sử dụng cho lần sau
|
||||
localStorage.setItem('map_view_state', JSON.stringify({ center: coords, zoom }));
|
||||
},
|
||||
});
|
||||
return null;
|
||||
@@ -40,20 +45,38 @@ function MapTracker() {
|
||||
|
||||
export const ExploreMap = ({ onBack, onLogout, user, onViewTour }: { onBack: () => void, onLogout?: () => void, user?: any, onViewTour: (id: string) => void }) => {
|
||||
const { publicTours, fetchPublicTours, fetchTour, updateTour, deleteTour, mapCenter, setMapCenter } = useTourStore();
|
||||
const [userPos, setUserPos] = useState<[number, number]>([10.7769, 106.7009]); // Mặc định TP.HCM
|
||||
|
||||
// Khởi tạo vị trí từ localStorage nếu có, nếu không dùng mặc định (TP.HCM)
|
||||
const [initialViewState] = useState(() => {
|
||||
const saved = localStorage.getItem('map_view_state');
|
||||
if (saved) {
|
||||
try { return JSON.parse(saved); } catch (e) { return null; }
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const [userPos, setUserPos] = useState<[number, number]>(initialViewState?.center || [10.7769, 106.7009]);
|
||||
const [mapZoom] = useState(initialViewState?.zoom || 13);
|
||||
const [isAdminModalOpen, setIsAdminModalOpen] = useState(false);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPublicTours();
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const posArray: [number, number] = [pos.coords.latitude, pos.coords.longitude];
|
||||
setUserPos(posArray);
|
||||
setMapCenter(posArray);
|
||||
},
|
||||
() => console.log("Không thể lấy vị trí người dùng")
|
||||
);
|
||||
|
||||
// Nếu không có vị trí lưu từ trước, mới yêu cầu lấy vị trí hiện tại của thiết bị
|
||||
if (!initialViewState) {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const posArray: [number, number] = [pos.coords.latitude, pos.coords.longitude];
|
||||
setUserPos(posArray);
|
||||
setMapCenter(posArray);
|
||||
},
|
||||
() => console.log("Không thể lấy vị trí người dùng")
|
||||
);
|
||||
} else {
|
||||
// Cập nhật store để đồng bộ với vị trí khởi tạo từ cache
|
||||
setMapCenter(initialViewState.center);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleEditTour = async (tour: any) => {
|
||||
@@ -128,7 +151,7 @@ export const ExploreMap = ({ onBack, onLogout, user, onViewTour }: { onBack: ()
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MapContainer center={mapCenter} zoom={13} className="h-full w-full">
|
||||
<MapContainer center={userPos} zoom={mapZoom} className="h-full w-full">
|
||||
<TileLayer
|
||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
attribution='© OpenStreetMap contributors'
|
||||
@@ -141,57 +164,86 @@ export const ExploreMap = ({ onBack, onLogout, user, onViewTour }: { onBack: ()
|
||||
<RecenterMap position={userPos} />
|
||||
|
||||
{publicTours.map((tour) => {
|
||||
const location = tour.legs?.[0]?.locations?.[0];
|
||||
if (!location) return null;
|
||||
const startLoc = tour.legs?.[0]?.locations?.[0];
|
||||
if (!startLoc) return null;
|
||||
|
||||
const lastLeg = tour.legs?.[tour.legs.length - 1];
|
||||
const endLoc = lastLeg?.locations?.[lastLeg.locations.length - 1];
|
||||
|
||||
const tourImage = tour.photos?.[0]?.imageUrl || `https://picsum.photos/seed/${tour.id}/200/200`;
|
||||
|
||||
return (
|
||||
<Marker
|
||||
key={tour.id}
|
||||
position={[location.latitude, location.longitude]}
|
||||
icon={L.divIcon({
|
||||
className: 'custom-bubble',
|
||||
html: `
|
||||
<div class="relative group">
|
||||
<div class="w-12 h-12 rounded-full border-4 border-white shadow-lg overflow-hidden transition-transform group-hover:scale-110">
|
||||
<img src="${tourImage}" class="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div class="absolute -bottom-1 -right-1 bg-blue-600 rounded-full p-1 border-2 border-white">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
|
||||
</div>
|
||||
const commonPopup = (
|
||||
<Popup className="custom-popup">
|
||||
<div className="p-1 max-w-[200px]">
|
||||
<img src={tourImage} className="w-full h-32 object-cover rounded-lg mb-2" />
|
||||
<h4 className="font-bold text-gray-900 leading-tight mb-1">{tour.title}</h4>
|
||||
<button
|
||||
onClick={() => onViewTour(tour.id)}
|
||||
className="text-xs font-bold text-blue-600 flex items-center gap-1">
|
||||
Xem chi tiết hình ảnh <ImageIcon className="w-3 h-3" />
|
||||
</button>
|
||||
|
||||
{user && (
|
||||
<div className="flex gap-2 mt-3 pt-3 border-t border-gray-100">
|
||||
<button
|
||||
onClick={() => handleEditTour(tour)}
|
||||
className="flex-1 flex items-center justify-center gap-1 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-[10px] font-bold hover:bg-blue-100 transition-colors">
|
||||
<Edit2 className="w-3 h-3" /> Sửa
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteTour(tour.id)}
|
||||
className="flex-1 flex items-center justify-center gap-1 py-1.5 bg-red-50 text-red-600 rounded-lg text-[10px] font-bold hover:bg-red-100 transition-colors">
|
||||
<Trash2 className="w-3 h-3" /> Xóa
|
||||
</button>
|
||||
</div>
|
||||
`,
|
||||
iconSize: [48, 48],
|
||||
})}
|
||||
>
|
||||
<Popup className="custom-popup">
|
||||
<div className="p-1 max-w-[200px]">
|
||||
<img src={tourImage} className="w-full h-32 object-cover rounded-lg mb-2" />
|
||||
<h4 className="font-bold text-gray-900 leading-tight mb-1">{tour.title}</h4>
|
||||
<button
|
||||
onClick={() => onViewTour(tour.id)}
|
||||
className="text-xs font-bold text-blue-600 flex items-center gap-1">
|
||||
Xem chi tiết hình ảnh <ImageIcon className="w-3 h-3" />
|
||||
</button>
|
||||
|
||||
{user && (
|
||||
<div className="flex gap-2 mt-3 pt-3 border-t border-gray-100">
|
||||
<button
|
||||
onClick={() => handleEditTour(tour)}
|
||||
className="flex-1 flex items-center justify-center gap-1 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-[10px] font-bold hover:bg-blue-100 transition-colors">
|
||||
<Edit2 className="w-3 h-3" /> Sửa
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteTour(tour.id)}
|
||||
className="flex-1 flex items-center justify-center gap-1 py-1.5 bg-red-50 text-red-600 rounded-lg text-[10px] font-bold hover:bg-red-100 transition-colors">
|
||||
<Trash2 className="w-3 h-3" /> Xóa
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</Popup>
|
||||
);
|
||||
|
||||
return (
|
||||
<React.Fragment key={tour.id}>
|
||||
{/* Start Marker - Blue with 'S' Badge */}
|
||||
<Marker
|
||||
position={[startLoc.latitude, startLoc.longitude]}
|
||||
icon={L.divIcon({
|
||||
className: 'custom-bubble',
|
||||
html: `
|
||||
<div class="relative group">
|
||||
<div class="w-12 h-12 rounded-full border-4 border-white shadow-lg overflow-hidden transition-transform group-hover:scale-110">
|
||||
<img src="${tourImage}" class="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div class="absolute -bottom-1 -right-1 bg-blue-600 rounded-full w-5 h-5 border-2 border-white flex items-center justify-center text-[10px] font-black text-white">
|
||||
S
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
`,
|
||||
iconSize: [48, 48],
|
||||
iconAnchor: [24, 24]
|
||||
})}
|
||||
>
|
||||
{commonPopup}
|
||||
</Marker>
|
||||
|
||||
{/* End Marker - Green with 'E' (Only if different from start) */}
|
||||
{endLoc && (endLoc.latitude !== startLoc.latitude || endLoc.longitude !== startLoc.longitude) && (
|
||||
<Marker
|
||||
position={[endLoc.latitude, endLoc.longitude]}
|
||||
icon={L.divIcon({
|
||||
className: 'custom-end-marker',
|
||||
html: `
|
||||
<div class="w-8 h-8 bg-green-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center text-xs font-black text-white hover:scale-110 transition-transform">
|
||||
E
|
||||
</div>
|
||||
`,
|
||||
iconSize: [32, 32],
|
||||
iconAnchor: [16, 16]
|
||||
})}
|
||||
>
|
||||
{commonPopup}
|
||||
</Marker>
|
||||
)}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</MapContainer>
|
||||
|
||||
+162
-39
@@ -4,7 +4,8 @@ import { ExpenseManager } from './ExpenseManager.js';
|
||||
import { useTourStore } from './useTourStore.js';
|
||||
import { AddLocationModal } from './AddLocationModal.js';
|
||||
import { MapContainer, TileLayer, Marker, Popup, useMapEvents, Polyline } from 'react-leaflet';
|
||||
import {
|
||||
import { useMap } from 'react-leaflet';
|
||||
import {
|
||||
Map as MapIcon,
|
||||
Wallet,
|
||||
Image as ImageIcon,
|
||||
@@ -24,42 +25,91 @@ import L from 'leaflet';
|
||||
// Định nghĩa kiểu dữ liệu cho Địa điểm để khớp với Schema Prisma
|
||||
type LocationType = 'MOVE' | 'VISIT' | 'REST' | 'EAT';
|
||||
|
||||
|
||||
// Component Helper để tự động điều chỉnh khung nhìn bản đồ bao phủ toàn bộ lộ trình
|
||||
const MapTourBounds = ({ locations }: { locations: any[] }) => {
|
||||
const map = useMap();
|
||||
// Tạo một key dựa trên giá trị tọa độ để tránh chạy lại khi chỉ thay đổi tham chiếu mảng
|
||||
const locKey = useMemo(() => JSON.stringify(locations.map(l => [l.latitude, l.longitude])), [locations]);
|
||||
|
||||
useEffect(() => {
|
||||
if (locations.length > 0) {
|
||||
const bounds = L.latLngBounds(locations.map(l => [l.latitude, l.longitude]));
|
||||
if (locations.length === 1) {
|
||||
// Chỉ thực hiện nếu bản đồ chưa ở đúng vị trí (tránh trigger moveend liên tục)
|
||||
map.setView([locations[0].latitude, locations[0].longitude], 15, { animate: true });
|
||||
} else {
|
||||
map.fitBounds(bounds, { padding: [50, 50], maxZoom: 15 });
|
||||
}
|
||||
}
|
||||
}, [locKey, map]);
|
||||
|
||||
return null;
|
||||
};
|
||||
// Menu ngữ cảnh cho bản đồ
|
||||
const MapContextMenu = ({ onAction }: { onAction: (action: string, latlng: L.LatLng) => void }) => {
|
||||
const [menuPos, setMenuPos] = useState<{ x: number, y: number, latlng: L.LatLng } | null>(null);
|
||||
const { legs, setMapCenter } = useTourStore();
|
||||
const menuRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// Sử dụng selector để tránh re-render khi mapCenter thay đổi
|
||||
const legs = useTourStore(state => state.legs);
|
||||
const setMapCenter = useTourStore(state => state.setMapCenter);
|
||||
|
||||
useMapEvents({
|
||||
contextmenu: (e) => {
|
||||
// Ngăn menu mặc định của trình duyệt hiện lên.
|
||||
// Điều này là cần thiết để menu tùy chỉnh của Leaflet có thể tương tác được.
|
||||
// Nếu không có, menu của trình duyệt sẽ đè lên và chặn các sự kiện click.
|
||||
if (e.originalEvent) {
|
||||
L.DomEvent.preventDefault(e.originalEvent);
|
||||
L.DomEvent.stopPropagation(e.originalEvent);
|
||||
}
|
||||
|
||||
console.log(`[MAP] Context menu triggered at: ${e.latlng.lat}, ${e.latlng.lng}`);
|
||||
setMenuPos({ x: e.containerPoint.x, y: e.containerPoint.y, latlng: e.latlng });
|
||||
},
|
||||
click: () => setMenuPos(null),
|
||||
dragstart: () => setMenuPos(null),
|
||||
|
||||
moveend: (e) => {
|
||||
const map = e.target;
|
||||
const center = map.getCenter();
|
||||
setMapCenter([center.lat, center.lng]);
|
||||
}
|
||||
const zoom = map.getZoom();
|
||||
const coords: [number, number] = [center.lat, center.lng];
|
||||
|
||||
// Chỉ cập nhật store nếu tọa độ thay đổi đáng kể (> 0.0001) để tránh loop
|
||||
const currentStored = useTourStore.getState().mapCenter;
|
||||
const diff = Math.abs(currentStored[0] - coords[0]) + Math.abs(currentStored[1] - coords[1]);
|
||||
|
||||
if (diff > 0.0001) {
|
||||
setMapCenter(coords);
|
||||
}
|
||||
|
||||
localStorage.setItem('map_view_state', JSON.stringify({ center: coords, zoom }));
|
||||
},
|
||||
click: () => setMenuPos(null),
|
||||
dragstart: () => setMenuPos(null),
|
||||
});
|
||||
|
||||
// Ngăn chặn các sự kiện của bản đồ khi tương tác với menu
|
||||
useEffect(() => {
|
||||
if (menuPos && menuRef.current) {
|
||||
L.DomEvent.disableClickPropagation(menuRef.current);
|
||||
L.DomEvent.disableScrollPropagation(menuRef.current);
|
||||
}
|
||||
}, [menuPos]);
|
||||
|
||||
if (!menuPos) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="absolute z-[2000] bg-white rounded-2xl shadow-2xl border border-gray-100 py-2 w-48 animate-in zoom-in-95 duration-200"
|
||||
style={{ top: menuPos.y, left: menuPos.x }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<button onClick={() => { onAction('START', menuPos.latlng); setMenuPos(null); }} className="w-full text-left px-4 py-2 hover:bg-blue-50 text-sm font-bold text-gray-700 flex items-center gap-2">
|
||||
<div className="w-2 h-2 rounded-full bg-blue-600" /> Bắt đầu từ đây
|
||||
</button>
|
||||
<button onClick={() => { onAction('END', menuPos.latlng); setMenuPos(null); }} className="w-full text-left px-4 py-2 hover:bg-green-50 text-sm font-bold text-gray-700 flex items-center gap-2 border-b border-gray-50">
|
||||
<div className="w-2 h-2 rounded-full bg-green-500" /> Kết thúc ở đây
|
||||
<div className="w-2 h-2 rounded-full bg-green-600" /> Kết thúc ở đây
|
||||
</button>
|
||||
<div className="px-4 py-2 text-[10px] font-black text-gray-400 uppercase tracking-widest">Thêm vào chặng</div>
|
||||
{legs.map(leg => (
|
||||
@@ -79,9 +129,38 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
const [activeTab, setActiveTab] = useState<'plan' | 'expense' | 'photo' | 'settings'>('plan');
|
||||
const [viewMode, setViewMode] = useState<'map' | 'timeline'>('timeline');
|
||||
const [isAddLocationOpen, setIsAddLocationOpen] = useState(false);
|
||||
const { currentTour, fetchTour, fetchPublicTours, publicTours, userRole, legs, addLocation, mapCenter } = useTourStore();
|
||||
|
||||
// Khôi phục vị trí và mức zoom từ localStorage
|
||||
const [initialViewState] = useState(() => {
|
||||
const saved = localStorage.getItem('map_view_state');
|
||||
if (saved) {
|
||||
try { return JSON.parse(saved); } catch (e) { return null; }
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
// SỬA LỖI: Sử dụng các selectors riêng lẻ để tránh re-render trang khi mapCenter trong store thay đổi
|
||||
const currentTour = useTourStore(state => state.currentTour);
|
||||
const legs = useTourStore(state => state.legs);
|
||||
const fetchTour = useTourStore(state => state.fetchTour);
|
||||
const fetchPublicTours = useTourStore(state => state.fetchPublicTours);
|
||||
const publicTours = useTourStore(state => state.publicTours);
|
||||
const userRole = useTourStore(state => state.userRole);
|
||||
const mapCenter = useTourStore(state => state.mapCenter);
|
||||
const setMapCenter = useTourStore(state => state.setMapCenter);
|
||||
const updateTourStartPoint = useTourStore(state => state.updateTourStartPoint);
|
||||
const updateTourEndPoint = useTourStore(state => state.updateTourEndPoint);
|
||||
const addLocation = useTourStore(state => state.addLocation);
|
||||
|
||||
const [mapZoom] = useState(initialViewState?.zoom || 13);
|
||||
|
||||
// Memoize danh sách tọa độ để MapTourBounds không bị trigger thừa
|
||||
const allLocations = useMemo(() => legs.flatMap(l => l.locations), [legs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialViewState) {
|
||||
setMapCenter(initialViewState.center);
|
||||
}
|
||||
const loadData = async () => {
|
||||
// Nếu chưa có tour nào trong store, thử tải danh sách public trước
|
||||
if (publicTours.length === 0) {
|
||||
@@ -100,10 +179,13 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
|
||||
// Hàm xử lý các hành động từ Context Menu của bản đồ
|
||||
const handleMapAction = async (action: string, latlng: L.LatLng) => {
|
||||
// Bước 1: Lấy tọa độ (lat, lng) tại vị trí click (đã nhận qua tham số latlng)
|
||||
console.log(`[FRONTEND] Triggered ${action} at:`, { lat: latlng.lat, lng: latlng.lng });
|
||||
|
||||
// Đảm bảo có tour và ít nhất một chặng để ghim
|
||||
const currentLegs = useTourStore.getState().legs;
|
||||
if (!currentTour || currentLegs.length === 0) {
|
||||
alert("Tour chưa có chặng nào. Vui lòng tạo chặng trước khi thêm địa điểm.");
|
||||
alert("Tour chưa có chặng nào. Vui lòng tạo chặng (Leg) trước khi thực hiện.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -125,26 +207,64 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
// Loại địa điểm mặc định vẫn là VISIT nếu thêm vào chặng cụ thể
|
||||
}
|
||||
|
||||
// Tự động lấy tên địa điểm từ tọa độ (Reverse Geocoding)
|
||||
// Bước 2: Gửi request đến dịch vụ bản đồ để phân tích tọa độ thành tên địa điểm cụ thể
|
||||
let detectedName = "";
|
||||
try {
|
||||
const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latlng.lat}&lon=${latlng.lng}`);
|
||||
const data = await res.json();
|
||||
detectedName = data.display_name?.split(',')[0] || "";
|
||||
} catch (e) {}
|
||||
const addr = data.address;
|
||||
// Ưu tiên lấy tên Location/Tòa nhà/Tên đường, bỏ qua Tỉnh/Thành phố nếu có thông tin chi tiết hơn
|
||||
detectedName = addr.amenity || addr.building || addr.historic || addr.tourist ||
|
||||
addr.shop || addr.office || addr.leisure || addr.attraction ||
|
||||
addr.road || addr.neighbourhood || addr.suburb ||
|
||||
data.display_name?.split(',')[0] || "";
|
||||
console.log(`[FRONTEND] Geocoding Result: "${detectedName}"`);
|
||||
} catch (e) {
|
||||
console.warn("[FRONTEND] Reverse Geocoding failed:", e);
|
||||
}
|
||||
|
||||
const name = window.prompt("Xác nhận tên địa điểm:", detectedName || defaultName);
|
||||
if (name) {
|
||||
await addLocation(currentTour.id, {
|
||||
name,
|
||||
address: '', // Gửi chuỗi rỗng cho địa chỉ nếu không có
|
||||
latitude: latlng.lat,
|
||||
longitude: latlng.lng,
|
||||
legId: targetLegId,
|
||||
type: locationType as any,
|
||||
plannedStart: null, // Gửi null cho thời gian nếu không có
|
||||
plannedEnd: null, // Gửi null cho thời gian nếu không có
|
||||
});
|
||||
try {
|
||||
if (action === 'START') {
|
||||
// Bước 3: Mutate State & UI - Đặt startLocationName = resolvedPlaceName
|
||||
const resolvedPlaceName = detectedName || "Điểm xuất phát";
|
||||
console.log(`[FRONTEND] Updating START point to: ${resolvedPlaceName} at`, latlng);
|
||||
await updateTourStartPoint(currentTour.id, {
|
||||
name: resolvedPlaceName,
|
||||
latitude: latlng.lat,
|
||||
longitude: latlng.lng,
|
||||
});
|
||||
console.log("[FRONTEND] START point updated successfully.");
|
||||
// Giao diện Top Banner và Ghim màu xanh sẽ tự động cập nhật
|
||||
// khi store fetch lại dữ liệu tour và re-render.
|
||||
} else if (action === 'END') {
|
||||
// Bước 2: Thiết lập Điểm kết thúc
|
||||
const finalName = detectedName || "Điểm kết thúc";
|
||||
await updateTourEndPoint(currentTour.id, {
|
||||
name: finalName,
|
||||
latitude: latlng.lat,
|
||||
longitude: latlng.lng,
|
||||
});
|
||||
} else {
|
||||
// Đối với việc thêm địa điểm vào chặng, vẫn sử dụng Prompt để người dùng đặt tên theo ý muốn
|
||||
const name = window.prompt("Xác nhận tên địa điểm tham quan:", detectedName || defaultName);
|
||||
if (!name) return;
|
||||
|
||||
await addLocation(currentTour.id, {
|
||||
name,
|
||||
address: '',
|
||||
latitude: latlng.lat,
|
||||
longitude: latlng.lng,
|
||||
legId: targetLegId,
|
||||
type: locationType as any,
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
// Xử lý lỗi từ API (Ví dụ: Tour chưa có chặng nào)
|
||||
if (error.message.includes('Không tìm thấy chặng')) {
|
||||
alert("Lỗi: Bạn cần tạo ít nhất một Chặng (Leg) trước khi xác định điểm Bắt đầu/Kết thúc.");
|
||||
} else {
|
||||
alert("Đã xảy ra lỗi: " + error.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -206,13 +326,13 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
<div className="max-w-2xl mx-auto space-y-4">
|
||||
<h2 className="text-3xl font-black tracking-tight drop-shadow-md">{tourInfo.title}</h2>
|
||||
{/* Dòng tóm tắt Lộ trình */}
|
||||
<div className="mt-3 text-sm font-bold text-blue-100 bg-blue-800/30 backdrop-blur-sm px-4 py-2 rounded-xl border border-white/5 inline-block max-w-full truncate">
|
||||
<div className="mt-3 text-[11px] sm:text-sm font-bold text-white bg-black/40 backdrop-blur-md px-4 py-2 rounded-xl border border-white/10 inline-flex items-center max-w-full">
|
||||
<span className="text-white/60 mr-1">Lộ trình:</span>
|
||||
<span>Điểm xuất phát: </span>
|
||||
<span className="text-white">{startPoint?.name || '...'}</span>
|
||||
<span className="mx-2 text-white/40">-</span>
|
||||
<span>Điểm kết thúc: </span>
|
||||
<span className="text-white">{endPoint?.name || '...'}</span>
|
||||
<span className="text-blue-300">Điểm xuất phát:</span>
|
||||
<span className="ml-1 text-white banner-location-text" title={startPoint?.name}>{startPoint?.name || '...'}</span>
|
||||
<span className="mx-2 text-white/30">-</span>
|
||||
<span className="text-green-300">Điểm kết thúc:</span>
|
||||
<span className="ml-1 text-white banner-location-text" title={endPoint?.name}>{endPoint?.name || '...'}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-4 text-sm font-medium opacity-90">
|
||||
@@ -344,10 +464,13 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
<ItineraryTimeline />
|
||||
) : (
|
||||
<div className="h-[60vh] w-full rounded-3xl overflow-hidden shadow-xl border-4 border-white relative">
|
||||
<MapContainer center={mapCenter} zoom={13} className="h-full w-full">
|
||||
<MapContainer center={initialViewState?.center || mapCenter} zoom={mapZoom} className="h-full w-full">
|
||||
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
|
||||
<MapContextMenu onAction={handleMapAction} />
|
||||
|
||||
{/* Tự động đóng khung Start và End khi dữ liệu thay đổi */}
|
||||
<MapTourBounds locations={allLocations} />
|
||||
|
||||
{/* Vẽ đường Polyline nối các điểm */}
|
||||
{legs.map(leg => {
|
||||
const positions = leg.locations.map((l: any) => [l.latitude, l.longitude]);
|
||||
@@ -362,16 +485,16 @@ export const TourDetailPage = ({ onBack }: { onBack: () => void }) => {
|
||||
if (isStart) {
|
||||
customIcon = L.divIcon({
|
||||
className: 'custom-marker',
|
||||
html: `<div class="w-5 h-5 bg-blue-600 rounded-full border-2 border-white shadow-lg"></div>`,
|
||||
iconSize: [20, 20],
|
||||
iconAnchor: [10, 10]
|
||||
html: `<div class="w-6 h-6 bg-blue-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center text-[10px] font-black text-white">S</div>`,
|
||||
iconSize: [24, 24],
|
||||
iconAnchor: [12, 12]
|
||||
});
|
||||
} else if (isEnd) {
|
||||
customIcon = L.divIcon({
|
||||
className: 'custom-marker',
|
||||
html: `<div class="w-5 h-5 bg-green-500 rounded-full border-2 border-white shadow-lg"></div>`,
|
||||
iconSize: [20, 20],
|
||||
iconAnchor: [10, 10]
|
||||
html: `<div class="w-6 h-6 bg-green-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center text-[10px] font-black text-white">E</div>`,
|
||||
iconSize: [24, 24],
|
||||
iconAnchor: [12, 12]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# KẾ HOẠCH PHÁT TRIỂN TÍNH NĂNG ĐỊNH VỊ LỘ TRÌNH (AGENT SPECIFICATION)
|
||||
|
||||
## 1. Phân Tích Trạng Thái Giao Diện Hiện Tại (Context Analysis)
|
||||
* **Màn hình**: Tour Dashboard (Tên tour người dùng tự đặt khi tạo tour mới).
|
||||
* **Tab Active**: Lộ trình (Mặc định).
|
||||
* **Sub-view Active**: Bản đồ (Component bản đồ đang hiển thị ở nửa dưới màn hình).
|
||||
* **Thành phần cần can thiệp**: Lớp tương tác (Interaction Layer) của thư viện Bản đồ (Mapbox / Google Maps API / Leaflet) đang render phía dưới.
|
||||
|
||||
## 2. Đặc Tả Kỹ Thuật Đóng Gói (Functional Requirements)
|
||||
|
||||
### 2.1. Quản lý Trạng thái Thực thể (Data State Management)
|
||||
Agent cần ánh xạ sự kiện trên UI vào hai trường dữ liệu trong Database Schema:
|
||||
* **Điểm xuất phát (StartLocation)**: Ánh xạ vào Location đầu tiên của Tour với sequence: 0 hoặc cấu hình tọa độ trực tiếp vào cấu trúc metadata của Tour.
|
||||
* **Điểm kết thúc (EndLocation)**: Ánh xạ vào Location cuối cùng của Tour hoặc trường đích của Tour.
|
||||
|
||||
### 2.2. Chi Tiết Bản Ghép Logic Sự Kiện (Event Mapping)
|
||||
|
||||
| Thao tác Người dùng | Trình kích hoạt (Trigger) | Hành động Hệ thống (System Action) | Phản hồi Giao diện (UI Feedback) |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Xác định Điểm xuất phát** | - Tìm kiếm trên Map Search Box<br>- Hoặc Right-Click (Desktop)<br>- Hoặc Long-Press (Mobile) | 1. Trích xuất tọa độ (lat, lng).<br>2. Gọi API khởi tạo điểm đầu.<br>3. Cập nhật nhãn "Điểm xuất phát:..." trên Top Banner. | Tạo 1 Ghim (Marker) Màu Xanh Blue tại tọa độ được chọn. |
|
||||
| **Xác định Điểm kết thúc** | - Tìm kiếm trên Map Search Box<br>- Hoặc Right-Click (Desktop)<br>- Hoặc Long-Press (Mobile) | 1. Trích xuất tọa độ (lat, lng).<br>2. Gọi API khởi tạo điểm cuối.<br>3. Cập nhật nhãn "Điểm kết thúc:..." trên Top Banner. | Tạo 1 Ghim (Marker) Màu Xanh Green tại tọa độ được chọn. |
|
||||
|
||||
## 3. Kiến Trúc Mã Nguồn Gợi Ý Cho AI Agent (Pseudocode / Implementation Guide)
|
||||
Agent cần triển khai component bản đồ với cấu trúc xử lý sự kiện (Context Menu) như sau:
|
||||
|
||||
### 3.1. Cấu trúc Menu Ngữ Cảnh (Custom Context Menu Component)
|
||||
Khi sự kiện click chuột phải/nhấn giữ xảy ra, lấy ra tọa độ (lat, lng) của điểm chạm và hiển thị menu pop-up tại vị trí con trỏ:
|
||||
|
||||
```typescript
|
||||
interface ContextMenuProps {
|
||||
x: number; // Tọa độ pixel trên màn hình
|
||||
y: number;
|
||||
latLng: { lat: number; lng: number };
|
||||
onSelectStart: (latLng: { lat: number; lng: number }) => void;
|
||||
onSelectEnd: (latLng: { lat: number; lng: number }) => void;
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2. Thuật toán xử lý ghim (Marker Rendering Logic)
|
||||
Mô tả logic bằng mã giả để Agent tiến hành sinh code xử lý:
|
||||
|
||||
```javascript
|
||||
// Trạng thái lưu trữ tọa độ trên Frontend
|
||||
const [startCoords, setStartCoords] = useState(null);
|
||||
const [endCoords, setEndCoords] = useState(null);
|
||||
|
||||
// Hàm xử lý khi chọn "Bắt đầu từ đây"
|
||||
function handleSetStartPoint(latLng) {
|
||||
// 1. Cập nhật state để render ghim Blue
|
||||
setStartCoords(latLng);
|
||||
|
||||
// 2. Gọi API cập nhật Database thông qua UUID của Tour hiện tại
|
||||
API.updateTourStartPoint(tourId, {
|
||||
latitude: latLng.lat,
|
||||
longitude: latLng.lng,
|
||||
locationType: 'START'
|
||||
});
|
||||
|
||||
// 3. Render Marker Blue lên Bản đồ
|
||||
map.renderMarker({
|
||||
position: latLng,
|
||||
icon: 'blue-pin.png',
|
||||
label: 'S'
|
||||
});
|
||||
}
|
||||
|
||||
// Hàm xử lý khi chọn "Kết thúc ở đây"
|
||||
function handleSetEndPoint(latLng) {
|
||||
// 1. Cập nhật state để render ghim Green
|
||||
setEndCoords(latLng);
|
||||
|
||||
// 2. Gọi API cập nhật Database
|
||||
API.updateTourEndPoint(tourId, {
|
||||
latitude: latLng.lat,
|
||||
longitude: latLng.lng,
|
||||
locationType: 'END'
|
||||
});
|
||||
|
||||
// 3. Render Marker Green lên Bản đồ
|
||||
map.renderMarker({
|
||||
position: latLng,
|
||||
icon: 'green-pin.png',
|
||||
label: 'E'
|
||||
});
|
||||
}
|
||||
```
|
||||
Vendored
+58
-24
@@ -1,5 +1,5 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
import { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { MapContainer, TileLayer, Marker, Popup, useMap, useMapEvents } from 'react-leaflet';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
@@ -27,23 +27,44 @@ function MapTracker() {
|
||||
moveend: (e) => {
|
||||
const map = e.target;
|
||||
const center = map.getCenter();
|
||||
setMapCenter([center.lat, center.lng]);
|
||||
const zoom = map.getZoom();
|
||||
const coords = [center.lat, center.lng];
|
||||
setMapCenter(coords);
|
||||
localStorage.setItem('map_view_state', JSON.stringify({ center: coords, zoom }));
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
export const ExploreMap = ({ onBack, onLogout, user, onViewTour }) => {
|
||||
const { publicTours, fetchPublicTours, fetchTour, updateTour, deleteTour, mapCenter, setMapCenter } = useTourStore();
|
||||
const [userPos, setUserPos] = useState([10.7769, 106.7009]);
|
||||
const [initialViewState] = useState(() => {
|
||||
const saved = localStorage.getItem('map_view_state');
|
||||
if (saved) {
|
||||
try {
|
||||
return JSON.parse(saved);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
const [userPos, setUserPos] = useState(initialViewState?.center || [10.7769, 106.7009]);
|
||||
const [mapZoom] = useState(initialViewState?.zoom || 13);
|
||||
const [isAdminModalOpen, setIsAdminModalOpen] = useState(false);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
fetchPublicTours();
|
||||
navigator.geolocation.getCurrentPosition((pos) => {
|
||||
const posArray = [pos.coords.latitude, pos.coords.longitude];
|
||||
setUserPos(posArray);
|
||||
setMapCenter(posArray);
|
||||
}, () => console.log("Không thể lấy vị trí người dùng"));
|
||||
if (!initialViewState) {
|
||||
navigator.geolocation.getCurrentPosition((pos) => {
|
||||
const posArray = [pos.coords.latitude, pos.coords.longitude];
|
||||
setUserPos(posArray);
|
||||
setMapCenter(posArray);
|
||||
}, () => console.log("Không thể lấy vị trí người dùng"));
|
||||
}
|
||||
else {
|
||||
setMapCenter(initialViewState.center);
|
||||
}
|
||||
}, []);
|
||||
const handleEditTour = async (tour) => {
|
||||
const newTitle = window.prompt("Nhập tên mới cho Tour:", tour.title);
|
||||
@@ -66,25 +87,38 @@ export const ExploreMap = ({ onBack, onLogout, user, onViewTour }) => {
|
||||
}
|
||||
}
|
||||
};
|
||||
return (_jsxs("div", { className: "h-screen w-full relative", children: [_jsx("button", { onClick: onBack, className: "absolute top-6 left-6 z-[1000] bg-white p-3 rounded-full shadow-xl hover:bg-gray-50 transition-all", children: _jsx(X, { className: "w-6 h-6 text-gray-800" }) }), onLogout && (_jsxs("button", { onClick: onLogout, className: "absolute top-6 right-6 z-[1000] bg-white px-4 py-3 rounded-2xl shadow-xl hover:bg-red-50 hover:text-red-600 transition-all flex items-center gap-2 font-bold text-gray-700", children: [_jsx(LogOut, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "\u0110\u0103ng xu\u1EA5t" })] })), user?.isAdmin && (_jsxs("button", { onClick: () => setIsAdminModalOpen(true), className: "absolute top-6 right-40 z-[1000] bg-blue-600 px-4 py-3 rounded-2xl shadow-xl hover:bg-blue-700 text-white transition-all flex items-center gap-2 font-bold", children: [_jsx(Settings, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "Qu\u1EA3n l\u00FD h\u1EC7 th\u1ED1ng" })] })), user && (_jsxs("button", { onClick: () => setIsCreateModalOpen(true), className: "absolute top-6 right-80 z-[1000] bg-green-600 px-4 py-3 rounded-2xl shadow-xl hover:bg-green-700 text-white transition-all flex items-center gap-2 font-bold", children: [_jsx(Navigation, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "T\u1EA1o Tour m\u1EDBi" })] })), _jsx("div", { className: "absolute top-6 left-20 z-[1000] bg-white/90 backdrop-blur-md px-6 py-3 rounded-2xl shadow-xl border border-white/20 hidden sm:block", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Navigation, { className: "w-4 h-4 text-blue-600" }), _jsx("span", { className: "font-bold text-gray-800", children: "\u0110ang kh\u00E1m ph\u00E1 khu v\u1EF1c c\u1EE7a b\u1EA1n" })] }) }), _jsxs(MapContainer, { center: mapCenter, zoom: 13, className: "h-full w-full", children: [_jsx(TileLayer, { url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", attribution: '\u00A9 OpenStreetMap contributors' }), _jsx(MapTracker, {}), _jsx(RecenterMap, { position: userPos }), publicTours.map((tour) => {
|
||||
const location = tour.legs?.[0]?.locations?.[0];
|
||||
if (!location)
|
||||
return (_jsxs("div", { className: "h-screen w-full relative", children: [_jsx("button", { onClick: onBack, className: "absolute top-6 left-6 z-[1000] bg-white p-3 rounded-full shadow-xl hover:bg-gray-50 transition-all", children: _jsx(X, { className: "w-6 h-6 text-gray-800" }) }), onLogout && (_jsxs("button", { onClick: onLogout, className: "absolute top-6 right-6 z-[1000] bg-white px-4 py-3 rounded-2xl shadow-xl hover:bg-red-50 hover:text-red-600 transition-all flex items-center gap-2 font-bold text-gray-700", children: [_jsx(LogOut, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "\u0110\u0103ng xu\u1EA5t" })] })), user?.isAdmin && (_jsxs("button", { onClick: () => setIsAdminModalOpen(true), className: "absolute top-6 right-40 z-[1000] bg-blue-600 px-4 py-3 rounded-2xl shadow-xl hover:bg-blue-700 text-white transition-all flex items-center gap-2 font-bold", children: [_jsx(Settings, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "Qu\u1EA3n l\u00FD h\u1EC7 th\u1ED1ng" })] })), user && (_jsxs("button", { onClick: () => setIsCreateModalOpen(true), className: "absolute top-6 right-80 z-[1000] bg-green-600 px-4 py-3 rounded-2xl shadow-xl hover:bg-green-700 text-white transition-all flex items-center gap-2 font-bold", children: [_jsx(Navigation, { className: "w-5 h-5" }), _jsx("span", { className: "hidden sm:inline", children: "T\u1EA1o Tour m\u1EDBi" })] })), _jsx("div", { className: "absolute top-6 left-20 z-[1000] bg-white/90 backdrop-blur-md px-6 py-3 rounded-2xl shadow-xl border border-white/20 hidden sm:block", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Navigation, { className: "w-4 h-4 text-blue-600" }), _jsx("span", { className: "font-bold text-gray-800", children: "\u0110ang kh\u00E1m ph\u00E1 khu v\u1EF1c c\u1EE7a b\u1EA1n" })] }) }), _jsxs(MapContainer, { center: userPos, zoom: mapZoom, className: "h-full w-full", children: [_jsx(TileLayer, { url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", attribution: '\u00A9 OpenStreetMap contributors' }), _jsx(MapTracker, {}), _jsx(RecenterMap, { position: userPos }), publicTours.map((tour) => {
|
||||
const startLoc = tour.legs?.[0]?.locations?.[0];
|
||||
if (!startLoc)
|
||||
return null;
|
||||
const lastLeg = tour.legs?.[tour.legs.length - 1];
|
||||
const endLoc = lastLeg?.locations?.[lastLeg.locations.length - 1];
|
||||
const tourImage = tour.photos?.[0]?.imageUrl || `https://picsum.photos/seed/${tour.id}/200/200`;
|
||||
return (_jsx(Marker, { position: [location.latitude, location.longitude], icon: L.divIcon({
|
||||
className: 'custom-bubble',
|
||||
html: `
|
||||
<div class="relative group">
|
||||
<div class="w-12 h-12 rounded-full border-4 border-white shadow-lg overflow-hidden transition-transform group-hover:scale-110">
|
||||
<img src="${tourImage}" class="w-full h-full object-cover" />
|
||||
const commonPopup = (_jsx(Popup, { className: "custom-popup", children: _jsxs("div", { className: "p-1 max-w-[200px]", children: [_jsx("img", { src: tourImage, className: "w-full h-32 object-cover rounded-lg mb-2" }), _jsx("h4", { className: "font-bold text-gray-900 leading-tight mb-1", children: tour.title }), _jsxs("button", { onClick: () => onViewTour(tour.id), className: "text-xs font-bold text-blue-600 flex items-center gap-1", children: ["Xem chi ti\u1EBFt h\u00ECnh \u1EA3nh ", _jsx(ImageIcon, { className: "w-3 h-3" })] }), user && (_jsxs("div", { className: "flex gap-2 mt-3 pt-3 border-t border-gray-100", children: [_jsxs("button", { onClick: () => handleEditTour(tour), className: "flex-1 flex items-center justify-center gap-1 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-[10px] font-bold hover:bg-blue-100 transition-colors", children: [_jsx(Edit2, { className: "w-3 h-3" }), " S\u1EEDa"] }), _jsxs("button", { onClick: () => handleDeleteTour(tour.id), className: "flex-1 flex items-center justify-center gap-1 py-1.5 bg-red-50 text-red-600 rounded-lg text-[10px] font-bold hover:bg-red-100 transition-colors", children: [_jsx(Trash2, { className: "w-3 h-3" }), " X\u00F3a"] })] }))] }) }));
|
||||
return (_jsxs(React.Fragment, { children: [_jsx(Marker, { position: [startLoc.latitude, startLoc.longitude], icon: L.divIcon({
|
||||
className: 'custom-bubble',
|
||||
html: `
|
||||
<div class="relative group">
|
||||
<div class="w-12 h-12 rounded-full border-4 border-white shadow-lg overflow-hidden transition-transform group-hover:scale-110">
|
||||
<img src="${tourImage}" class="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div class="absolute -bottom-1 -right-1 bg-blue-600 rounded-full w-5 h-5 border-2 border-white flex items-center justify-center text-[10px] font-black text-white">
|
||||
S
|
||||
</div>
|
||||
</div>
|
||||
<div class="absolute -bottom-1 -right-1 bg-blue-600 rounded-full p-1 border-2 border-white">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
iconSize: [48, 48],
|
||||
}), children: _jsx(Popup, { className: "custom-popup", children: _jsxs("div", { className: "p-1 max-w-[200px]", children: [_jsx("img", { src: tourImage, className: "w-full h-32 object-cover rounded-lg mb-2" }), _jsx("h4", { className: "font-bold text-gray-900 leading-tight mb-1", children: tour.title }), _jsxs("button", { onClick: () => onViewTour(tour.id), className: "text-xs font-bold text-blue-600 flex items-center gap-1", children: ["Xem chi ti\u1EBFt h\u00ECnh \u1EA3nh ", _jsx(ImageIcon, { className: "w-3 h-3" })] }), user && (_jsxs("div", { className: "flex gap-2 mt-3 pt-3 border-t border-gray-100", children: [_jsxs("button", { onClick: () => handleEditTour(tour), className: "flex-1 flex items-center justify-center gap-1 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-[10px] font-bold hover:bg-blue-100 transition-colors", children: [_jsx(Edit2, { className: "w-3 h-3" }), " S\u1EEDa"] }), _jsxs("button", { onClick: () => handleDeleteTour(tour.id), className: "flex-1 flex items-center justify-center gap-1 py-1.5 bg-red-50 text-red-600 rounded-lg text-[10px] font-bold hover:bg-red-100 transition-colors", children: [_jsx(Trash2, { className: "w-3 h-3" }), " X\u00F3a"] })] }))] }) }) }, tour.id));
|
||||
`,
|
||||
iconSize: [48, 48],
|
||||
iconAnchor: [24, 24]
|
||||
}), children: commonPopup }), endLoc && (endLoc.latitude !== startLoc.latitude || endLoc.longitude !== startLoc.longitude) && (_jsx(Marker, { position: [endLoc.latitude, endLoc.longitude], icon: L.divIcon({
|
||||
className: 'custom-end-marker',
|
||||
html: `
|
||||
<div class="w-8 h-8 bg-green-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center text-xs font-black text-white hover:scale-110 transition-transform">
|
||||
E
|
||||
</div>
|
||||
`,
|
||||
iconSize: [32, 32],
|
||||
iconAnchor: [16, 16]
|
||||
}), children: commonPopup }))] }, tour.id));
|
||||
})] }), _jsx(UserManagementModal, { isOpen: isAdminModalOpen, onClose: () => setIsAdminModalOpen(false) }), _jsx(CreateTourModal, { isOpen: isCreateModalOpen, onClose: () => setIsCreateModalOpen(false), onSuccess: (tour) => {
|
||||
fetchTour(tour.id);
|
||||
onViewTour(tour.id);
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+128
-31
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+78
-4
@@ -129,8 +129,9 @@ let TourController = class TourController {
|
||||
}
|
||||
});
|
||||
}
|
||||
async addLocation(tourId, body) {
|
||||
async addLocation(tourId, body, req) {
|
||||
const legId = body.legId;
|
||||
console.log(`[USER ACTION] User ${req.user.id} added a NEW VISIT point to Tour ${tourId}: "${body.name}"`);
|
||||
const leg = legId
|
||||
? await this.prisma.leg.findUnique({ where: { id: legId } })
|
||||
: await this.prisma.leg.findFirst({ where: { tourId } });
|
||||
@@ -149,6 +150,58 @@ let TourController = class TourController {
|
||||
}
|
||||
});
|
||||
}
|
||||
async updateTourStartPoint(tourId, body, req) {
|
||||
const { latitude, longitude, name } = body;
|
||||
console.log(`[USER ACTION] User ${req.user.id} set START point for Tour ${tourId}: "${name}" at [${latitude}, ${longitude}]`);
|
||||
await this.prisma.location.deleteMany({
|
||||
where: {
|
||||
leg: { tourId: tourId },
|
||||
plannedStart: new Date(0)
|
||||
}
|
||||
});
|
||||
const firstLeg = await this.prisma.leg.findFirst({
|
||||
where: { tourId },
|
||||
orderBy: { sequence: 'asc' }
|
||||
});
|
||||
if (!firstLeg)
|
||||
throw new NotFoundException('Không tìm thấy chặng đầu tiên cho Tour này');
|
||||
return this.prisma.location.create({
|
||||
data: {
|
||||
name: name || 'Điểm xuất phát',
|
||||
latitude,
|
||||
longitude,
|
||||
type: 'MOVE',
|
||||
legId: firstLeg.id,
|
||||
plannedStart: new Date(0),
|
||||
}
|
||||
});
|
||||
}
|
||||
async updateTourEndPoint(tourId, body, req) {
|
||||
const { latitude, longitude, name } = body;
|
||||
console.log(`[USER ACTION] User ${req.user.id} set END point for Tour ${tourId}: "${name}" at [${latitude}, ${longitude}]`);
|
||||
await this.prisma.location.deleteMany({
|
||||
where: {
|
||||
leg: { tourId: tourId },
|
||||
plannedEnd: new Date(0)
|
||||
}
|
||||
});
|
||||
const lastLeg = await this.prisma.leg.findFirst({
|
||||
where: { tourId },
|
||||
orderBy: { sequence: 'desc' }
|
||||
});
|
||||
if (!lastLeg)
|
||||
throw new NotFoundException('Không tìm thấy chặng cuối cùng cho Tour này');
|
||||
return this.prisma.location.create({
|
||||
data: {
|
||||
name: name || 'Điểm kết thúc',
|
||||
latitude,
|
||||
longitude,
|
||||
type: 'MOVE',
|
||||
legId: lastLeg.id,
|
||||
plannedEnd: new Date(0),
|
||||
}
|
||||
});
|
||||
}
|
||||
async addLeg(tourId, body) {
|
||||
const tour = await this.prisma.tour.findUnique({
|
||||
where: { id: tourId },
|
||||
@@ -186,9 +239,9 @@ let TourController = class TourController {
|
||||
include: {
|
||||
photos: { take: 1 },
|
||||
legs: {
|
||||
take: 1,
|
||||
orderBy: { sequence: 'asc' },
|
||||
include: {
|
||||
locations: { take: 1 }
|
||||
locations: { orderBy: { plannedStart: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,10 +281,31 @@ __decorate([
|
||||
Post(':tourId/locations'),
|
||||
__param(0, Param('tourId', ParseUUIDPipe)),
|
||||
__param(1, Body()),
|
||||
__param(2, Req()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [String, Object]),
|
||||
__metadata("design:paramtypes", [String, Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], TourController.prototype, "addLocation", null);
|
||||
__decorate([
|
||||
UseGuards(JwtAuthGuard),
|
||||
Post(':tourId/start-point'),
|
||||
__param(0, Param('tourId', ParseUUIDPipe)),
|
||||
__param(1, Body()),
|
||||
__param(2, Req()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [String, Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], TourController.prototype, "updateTourStartPoint", null);
|
||||
__decorate([
|
||||
UseGuards(JwtAuthGuard),
|
||||
Post(':tourId/end-point'),
|
||||
__param(0, Param('tourId', ParseUUIDPipe)),
|
||||
__param(1, Body()),
|
||||
__param(2, Req()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [String, Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], TourController.prototype, "updateTourEndPoint", null);
|
||||
__decorate([
|
||||
UseGuards(JwtAuthGuard),
|
||||
Post(':tourId/legs'),
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
@@ -14,6 +14,8 @@ interface TourState {
|
||||
updateLeg: (legId: string, data: any) => Promise<void>;
|
||||
deleteLeg: (legId: string) => Promise<void>;
|
||||
addLocation: (tourId: string, locationData: any) => Promise<void>;
|
||||
updateTourStartPoint: (tourId: string, data: any) => Promise<void>;
|
||||
updateTourEndPoint: (tourId: string, data: any) => Promise<void>;
|
||||
optimizeRouting: (legId: string) => Promise<void>;
|
||||
setActiveLegId: (id: string | null) => void;
|
||||
setMapCenter: (pos: [number, number]) => void;
|
||||
|
||||
Vendored
+29
@@ -131,6 +131,35 @@ export const useTourStore = create((set, get) => ({
|
||||
throw new Error('Lỗi khi thêm địa điểm');
|
||||
get().fetchTour(tourId);
|
||||
},
|
||||
updateTourStartPoint: async (tourId, data) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/start-point`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
console.log(`[STORE] updateTourStartPoint API Status: ${response.status}`);
|
||||
if (!response.ok)
|
||||
throw new Error('Lỗi khi thiết lập điểm bắt đầu');
|
||||
await get().fetchTour(tourId);
|
||||
},
|
||||
updateTourEndPoint: async (tourId, data) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/end-point`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!response.ok)
|
||||
throw new Error('Lỗi khi thiết lập điểm kết thúc');
|
||||
await get().fetchTour(tourId);
|
||||
},
|
||||
optimizeRouting: async (legId) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/routing/optimize/${legId}`, {
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -6,4 +6,22 @@
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.banner-location-text {
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
max-width: 80px;
|
||||
display: inline-block;
|
||||
vertical-align: bottom;
|
||||
cursor: help; /* Hiển thị biểu tượng giúp đỡ để gợi ý có tooltip */
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.banner-location-text {
|
||||
max-width: 150px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,8 +110,11 @@ class TourController {
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post(':tourId/locations')
|
||||
async addLocation(@Param('tourId', ParseUUIDPipe) tourId: string, @Body() body: any) {
|
||||
async addLocation(@Param('tourId', ParseUUIDPipe) tourId: string, @Body() body: any, @Req() req: any) {
|
||||
const legId = body.legId;
|
||||
|
||||
console.log(`[USER ACTION] User ${req.user.id} added a NEW VISIT point to Tour ${tourId}: "${body.name}"`);
|
||||
|
||||
const leg = legId
|
||||
? await this.prisma.leg.findUnique({ where: { id: legId } })
|
||||
: await this.prisma.leg.findFirst({ where: { tourId } });
|
||||
@@ -132,6 +135,78 @@ class TourController {
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post(':tourId/start-point')
|
||||
async updateTourStartPoint(@Param('tourId', ParseUUIDPipe) tourId: string, @Body() body: any, @Req() req: any) {
|
||||
const { latitude, longitude, name } = body;
|
||||
|
||||
console.log(`[USER ACTION] User ${req.user.id} set START point for Tour ${tourId}: "${name}" at [${latitude}, ${longitude}]`);
|
||||
|
||||
// 1. Xóa tất cả các điểm bắt đầu cũ của Tour này (được đánh dấu bằng plannedStart = 0)
|
||||
// để đảm bảo tính duy nhất và sạch sẽ của dữ liệu.
|
||||
await this.prisma.location.deleteMany({
|
||||
where: {
|
||||
leg: { tourId: tourId },
|
||||
plannedStart: new Date(0)
|
||||
}
|
||||
});
|
||||
|
||||
// Tìm chặng đầu tiên của tour để ghim điểm xuất phát
|
||||
const firstLeg = await this.prisma.leg.findFirst({
|
||||
where: { tourId },
|
||||
orderBy: { sequence: 'asc' }
|
||||
});
|
||||
|
||||
if (!firstLeg) throw new NotFoundException('Không tìm thấy chặng đầu tiên cho Tour này');
|
||||
|
||||
// 2. Tạo mới điểm xuất phát tại Chặng 1
|
||||
return this.prisma.location.create({
|
||||
data: {
|
||||
name: name || 'Điểm xuất phát',
|
||||
latitude,
|
||||
longitude,
|
||||
type: 'MOVE',
|
||||
legId: firstLeg.id,
|
||||
plannedStart: new Date(0),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post(':tourId/end-point')
|
||||
async updateTourEndPoint(@Param('tourId', ParseUUIDPipe) tourId: string, @Body() body: any, @Req() req: any) {
|
||||
const { latitude, longitude, name } = body;
|
||||
|
||||
console.log(`[USER ACTION] User ${req.user.id} set END point for Tour ${tourId}: "${name}" at [${latitude}, ${longitude}]`);
|
||||
|
||||
// Xóa điểm kết thúc cũ (được đánh dấu bằng plannedEnd = 0) để tránh trùng lặp ghim trên bản đồ
|
||||
await this.prisma.location.deleteMany({
|
||||
where: {
|
||||
leg: { tourId: tourId },
|
||||
plannedEnd: new Date(0)
|
||||
}
|
||||
});
|
||||
|
||||
// Tìm chặng cuối cùng của tour để ghim điểm kết thúc
|
||||
const lastLeg = await this.prisma.leg.findFirst({
|
||||
where: { tourId },
|
||||
orderBy: { sequence: 'desc' }
|
||||
});
|
||||
|
||||
if (!lastLeg) throw new NotFoundException('Không tìm thấy chặng cuối cùng cho Tour này');
|
||||
|
||||
return this.prisma.location.create({
|
||||
data: {
|
||||
name: name || 'Điểm kết thúc',
|
||||
latitude,
|
||||
longitude,
|
||||
type: 'MOVE',
|
||||
legId: lastLeg.id,
|
||||
plannedEnd: new Date(0), // Đánh dấu đây là điểm kết thúc đặc biệt
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post(':tourId/legs')
|
||||
async addLeg(@Param('tourId', ParseUUIDPipe) tourId: string, @Body() body: any) {
|
||||
@@ -182,9 +257,9 @@ class TourController {
|
||||
include: {
|
||||
photos: { take: 1 },
|
||||
legs: {
|
||||
take: 1,
|
||||
orderBy: { sequence: 'asc' },
|
||||
include: {
|
||||
locations: { take: 1 }
|
||||
locations: { orderBy: { plannedStart: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ interface TourState {
|
||||
updateLeg: (legId: string, data: any) => Promise<void>;
|
||||
deleteLeg: (legId: string) => Promise<void>;
|
||||
addLocation: (tourId: string, locationData: any) => Promise<void>;
|
||||
updateTourStartPoint: (tourId: string, data: any) => Promise<void>;
|
||||
updateTourEndPoint: (tourId: string, data: any) => Promise<void>;
|
||||
optimizeRouting: (legId: string) => Promise<void>;
|
||||
setActiveLegId: (id: string | null) => void;
|
||||
setMapCenter: (pos: [number, number]) => void;
|
||||
@@ -158,6 +160,34 @@ export const useTourStore = create<TourState>((set, get) => ({
|
||||
// Làm mới dữ liệu tour hiện tại
|
||||
get().fetchTour(tourId);
|
||||
},
|
||||
updateTourStartPoint: async (tourId: string, data: any) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/start-point`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
console.log(`[STORE] updateTourStartPoint API Status: ${response.status}`);
|
||||
if (!response.ok) throw new Error('Lỗi khi thiết lập điểm bắt đầu');
|
||||
await get().fetchTour(tourId);
|
||||
},
|
||||
updateTourEndPoint: async (tourId: string, data: any) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/end-point`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!response.ok) throw new Error('Lỗi khi thiết lập điểm kết thúc');
|
||||
await get().fetchTour(tourId);
|
||||
},
|
||||
optimizeRouting: async (legId: string) => {
|
||||
const API_BASE = `http://${window.location.hostname}:3001`;
|
||||
const response = await fetch(`${API_BASE}/api/v1/routing/optimize/${legId}`, {
|
||||
|
||||
Reference in New Issue
Block a user