import {BrowserRouter as Router, Navigate, Route, Routes, useNavigate} from 'react-router-dom'; import Layout from "./components/Layout"; import React, {useContext, useEffect, useState} from 'react'; import ErrorPage from "./components/ErrorPage"; import Restaurants from "./components/Restaurants"; import Reservations from "./components/Reservations"; import RestaurantDetails from "./components/RestaurantDetails"; import ReservationConfirmation from "./components/ReservationConfirmation"; import ReservationEdit from "./components/ReservationEdit"; import axios from "axios"; import { CuisineContext } from './components/CuisineContext'; import RestaurantInfo from "./components/RestaurantInfo"; import AuthForm from "./components/AuthForm"; import AppContent from "./components/AppContent"; import ReservationHistory from "./components/ReservationHistory"; import AuthContent from "./components/AuthContent"; import MenuList from "./components/MenuList"; import ReadOnlyMenuList from "./components/ReadOnlyMenuList"; const ProtectedRoute = ({ element, isAuthenticated }) => { return isAuthenticated ? element : ; }; const App = () => { const [isAuthenticated, setIsAuthenticated] = useState(false); useEffect(() => { const token = localStorage.getItem('token'); if (token) { setIsAuthenticated(true); } }, []); return ( } /> } />} /> } />} /> } />} /> } />} /> } />} /> } />} /> } /> } /> ); }; const Home = () => { const navigate = useNavigate(); const todayDate = new Date().toISOString().split('T')[0]; const [date, setDate] = useState(todayDate); const [selectedTime, setSelectedTime] = useState(''); const [numPeople, setNumPeople] = useState(2); const [searchValue, setSearchValue] = useState(''); const [timeSlots, setTimeSlots] = useState([]); let [filteredRestaurants, setFilteredRestaurants] = useState([]); const cuisineTypes = useContext(CuisineContext); const [showCuisineSearch, setShowCuisineSearch] = useState(true); const [formatedDateTime, setFormatedDateTime] = useState('') useEffect(() => { if (date) { const selectedDate = new Date(date); const today = new Date(); const isToday = selectedDate.toDateString() === today.toDateString(); let startHour = 9; let startMinute = 0; if (isToday) { const currentHour = today.getHours(); const currentMinute = today.getMinutes(); if (currentHour > 9 || (currentHour === 9 && currentMinute >= 0)) { startHour = currentHour; startMinute = Math.ceil(currentMinute / 15) * 15; } } const startTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), startHour, startMinute); const endTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 23, 30); const slots = []; let currentTime = new Date(startTime); while (currentTime <= endTime) { const option = currentTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }); slots.push(option); currentTime.setMinutes(currentTime.getMinutes() + 15); } setTimeSlots(slots); } }, [date]); const handleGoToRestaurant = (restaurantId) => { navigate(`/restaurants/${restaurantId}`); }; const handleDateChange = (e) => { setDate(e.target.value); }; const handleTimeChange = (e) => { setSelectedTime(e.target.value); }; const handleNumPeopleChange = (e) => { setNumPeople(e.target.value); }; const handleInputChange = (event) => { setSearchValue(event.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); const [year, month, day] = date.split("-"); let formattedDateTime; if (selectedTime) { const [selectedHours, selectedMinutes] = selectedTime.split(":"); if (!isNaN(selectedHours) && !isNaN(selectedMinutes)) { const dateTime = new Date(Date.UTC(year, month - 1, day, selectedHours, selectedMinutes)); formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' '); setFormatedDateTime(formattedDateTime); } } else { const now = new Date(); const currentTime = now.getHours() * 60 + now.getMinutes(); const nextSlot = timeSlots.find(slot => { const [hours, minutes] = slot.split(":"); const slotTime = parseInt(hours) * 60 + parseInt(minutes); return slotTime > currentTime; }); formattedDateTime = nextSlot ? `${date} ${nextSlot}` : `${date} ${timeSlots[0]}`; } const data = { dateTime: formattedDateTime, partySize: numPeople, search: searchValue }; try { const response = await axios.post('http://localhost:8081/api/search', data); const filteredRestaurants = response.data; setFilteredRestaurants(filteredRestaurants); console.log(filteredRestaurants) setShowCuisineSearch(false); } catch (error) { console.error('Error:', error); } }; const handleSearchByCuisine = async (cuisine) => { const cuisineName = cuisine.replace('Searching by cuisine: ', ''); try { const response = await axios.post(`http://localhost:8081/api/search/shortcut/${cuisineName}`, cuisineName); setFilteredRestaurants(response.data) console.log(response.data) } catch (error) { console.error('Error searching by cuisine:', error); } setShowCuisineSearch(false); }; const parseTime = (timeString) => { const [hours, minutes] = timeString.trim().split(':').map(Number); return new Date().setHours(hours, minutes, 0, 0); }; const roundToNextQuarter = (date) => { const minutes = date.getMinutes(); const roundedMinutes = Math.floor(minutes / 15) * 15; date.setMinutes(roundedMinutes, 0, 0); return date; }; const shouldMoveToNextDay = (currentTime, endTime) => { return (endTime - currentTime) <= 2 * 60 * 60 * 1000; }; const generateTimeSlots = (operatingHours) => { const timeSlots = []; const [startTimeStr, endTimeStr] = operatingHours.split('-').map((time) => time.trim()); const startTime = parseTime(startTimeStr); let endTime = parseTime(endTimeStr); const currentTime = new Date().getTime(); if (shouldMoveToNextDay(currentTime, endTime)) { endTime += 24 * 60 * 60 * 1000; } let currentTimeSlot = new Date(startTime); currentTimeSlot = roundToNextQuarter(currentTimeSlot); while (currentTimeSlot.getTime() < endTime) { timeSlots.push(currentTimeSlot.toISOString()); currentTimeSlot.setMinutes(currentTimeSlot.getMinutes() + 15); } return timeSlots; }; const today = new Date(); const year = today.getFullYear(); const month = String(today.getMonth() + 1).padStart(2, '0'); const day = String(today.getDate()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; const handleTimeSlotClick = (table, timeSlot, restaurant) => { const tableNumber = table.id; const formattedTimeSlot = timeSlot; const restaurantId = restaurant.restaurantId; const encodedTableNumber = encodeURIComponent(tableNumber); const encodedTimeSlot = encodeURIComponent(formattedTimeSlot); const encodedRestaurantId = encodeURIComponent(restaurantId); navigate(`/reservationConfirmation/${encodedTableNumber}/${encodedTimeSlot}/${encodedRestaurantId}`); }; const renderTimeSlots = (tablesList, restaurant) => { const currentTime = new Date().getTime(); let renderedTimeSlots = {}; if (tablesList.length === 0) { return

No tables available for reservations at this restaurant.

; } return tablesList.flatMap((table) => { const tableTimeSlots = generateTimeSlots(restaurant.operatingHours); if (!renderedTimeSlots[table.capacity]) { renderedTimeSlots[table.capacity] = 0; return (

Table for {table.capacity} guests

{tableTimeSlots.map((timeSlot, index) => { const timeSlotTime = new Date(timeSlot).getTime(); if (timeSlotTime > currentTime && renderedTimeSlots[table.capacity] < 3) { renderedTimeSlots[table.capacity]++; const timeSlotDateTime = new Date(timeSlot); const formattedTime = timeSlotDateTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return ( );
} else { return null; } })}
); } else { return null; } }); }; return (

Rezerviraj masa

{filteredRestaurants.map((restaurant) => (
{restaurant.tablesList && restaurant.tablesList.length > 0 ? ( renderTimeSlots(restaurant.tablesList, restaurant) ) : (

No tables available for reservations at this restaurant

)}
))}
{showCuisineSearch && (

Search by cuisine type

    {cuisineTypes.map((cuisine, index) => (
  • ))}
)}
); } export default App;