Files
travelplanning/useTourStore.ts
T

250 lines
9.3 KiB
TypeScript

import { create } from 'zustand';
interface TourState {
currentTour: any;
legs: any[];
publicTours: any[];
userRole: string | null;
activeLegId: string | null;
mapCenter: [number, number];
setTour: (tour: any) => void;
updateLegs: (legs: any[]) => void;
createTour: (tourData: any) => Promise<any>;
updateTour: (id: string, data: any) => Promise<void>;
deleteTour: (id: string) => Promise<void>;
addLeg: (tourId: string, data: any) => Promise<void>;
initializeLegs: (tourId: string, count: number) => Promise<void>;
updateLeg: (legId: string, data: any) => Promise<void>;
deleteLeg: (legId: string) => Promise<void>;
addLocation: (tourId: string, locationData: any) => Promise<void>;
updateLocation: (locationId: string, data: any) => Promise<void>;
deleteLocation: (locationId: string) => 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;
fetchTour: (id: string) => Promise<void>;
fetchPublicTours: () => Promise<void>;
}
export const useTourStore = create<TourState>((set, get) => ({
currentTour: null,
legs: [],
publicTours: [],
userRole: null,
activeLegId: null,
mapCenter: [10.7769, 106.7009],
setTour: (tour) => set({ currentTour: tour }),
updateLegs: (legs) => set({ legs }),
setActiveLegId: (id) => set({ activeLegId: id }),
setMapCenter: (pos) => set({ mapCenter: pos }),
fetchTour: async (id: string) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${id}`);
const data = await response.json();
// Lấy role từ danh sách participants (dữ liệu mẫu từ seed)
const role = data.participants?.[0]?.role || 'VIEWER_ONLY';
const legs = data.legs || [];
set({
currentTour: data,
legs: legs,
userRole: role,
activeLegId: legs.length > 0 ? legs[0].id : null
});
},
fetchPublicTours: async () => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/explore`);
const data = await response.json();
set({ publicTours: data });
},
createTour: async (tourData: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(tourData),
});
return await response.json();
},
updateTour: async (id: string, data: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Lỗi khi cập nhật Tour');
// Làm mới danh sách khám phá
get().fetchPublicTours();
},
deleteTour: async (id: string) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Lỗi khi xóa Tour');
}
// Reset tour hiện tại nếu đang xem đúng tour vừa xóa
if (get().currentTour?.id === id) set({ currentTour: null });
get().fetchPublicTours();
},
addLeg: async (tourId: string, data: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/legs`, {
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 thêm chặng');
get().fetchTour(tourId);
},
initializeLegs: async (tourId: string, count: number) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/legs/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ count }),
});
if (!response.ok) throw new Error('Lỗi khi khởi tạo chặng');
await get().fetchTour(tourId);
},
updateLeg: async (legId: string, data: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/legs/${legId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Lỗi khi cập nhật chặng');
const { currentTour } = get();
if (currentTour) get().fetchTour(currentTour.id);
},
deleteLeg: async (legId: string) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/legs/${legId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.message || 'Lỗi khi xóa chặng');
}
const { currentTour } = get();
if (currentTour) get().fetchTour(currentTour.id);
},
addLocation: async (tourId: string, locationData: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/tours/${tourId}/locations`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(locationData),
});
if (!response.ok) throw new Error('Lỗi khi thêm địa điểm');
// Làm mới dữ liệu tour hiện tại
get().fetchTour(tourId);
},
updateLocation: async (locationId: string, data: any) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/locations/${locationId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Lỗi khi cập nhật địa điểm');
const { currentTour } = get();
if (currentTour) get().fetchTour(currentTour.id);
},
deleteLocation: async (locationId: string) => {
const API_BASE = `http://${window.location.hostname}:3001`;
const response = await fetch(`${API_BASE}/api/v1/locations/${locationId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
});
if (!response.ok) throw new Error('Lỗi khi xóa địa điểm');
const { currentTour } = get();
if (currentTour) get().fetchTour(currentTour.id);
},
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}`, {
method: 'POST'
});
const { locations, totalDistance } = await response.json();
const { currentTour } = get();
if (currentTour) {
const updatedLegs = currentTour.legs.map((l: any) =>
l.id === legId ? { ...l, locations: locations, totalDistance: totalDistance } : l
);
set({ currentTour: { ...currentTour, legs: updatedLegs }, legs: updatedLegs });
}
},
}));