source: my-react-app/src/App.js@ 8ca35dc

main
Last change on this file since 8ca35dc was 8ca35dc, checked in by Aleksandar Panovski <apano77@…>, 4 months ago

Done with stupid timeslots

  • Property mode set to 100644
File size: 14.8 KB
Line 
1import {BrowserRouter as Router, Navigate, Route, Routes, useNavigate} from 'react-router-dom';
2import Customers from './components/Customers';
3import Layout from "./components/Layout";
4import React, {useContext, useEffect, useState} from 'react';
5import CustomerFormContainer from "./components/CustomerFormContainer";
6import CustomerDetails from "./components/CustomerDetails";
7import ErrorPage from "./components/ErrorPage";
8import Restaurants from "./components/Restaurants";
9import Reservations from "./components/Reservations";
10import RestaurantDetails from "./components/RestaurantDetails";
11import ReservationConfirmation from "./components/ReservationConfirmation";
12import ReservationEdit from "./components/ReservationEdit";
13import axios from "axios";
14import { CuisineContext } from './components/CuisineContext';
15import RestaurantInfo from "./components/RestaurantInfo";
16import AuthForm from "./components/AuthForm";
17import AppContent from "./components/AppContent";
18import ReservationHistory from "./components/ReservationHistory";
19
20const ProtectedRoute = ({ element, isAuthenticated }) => {
21 return isAuthenticated ? element : <Navigate to="/login" />;
22};
23
24const App = () => {
25 const [isAuthenticated, setIsAuthenticated] = React.useState(false);
26
27 React.useEffect(() => {
28 const token = localStorage.getItem('token');
29 if (token) {
30 setIsAuthenticated(true);
31 }
32 }, []);
33
34 return (
35 <Router>
36 <Layout>
37 <Routes>
38 <Route path="/" element={<Home />} />
39 <Route path="/customers" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Customers />} />} />
40 <Route path="/customers/add" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerFormContainer />} />} />
41 <Route path="/customers/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerDetails />} />} />
42 <Route path="/customers/edit/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerFormContainer />} />} />
43 <Route path="/restaurants" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Restaurants />} />} />
44 <Route path="/restaurants/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<RestaurantDetails />} />} />
45 <Route path="/reservations" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Reservations />} />} />
46 <Route path="/reservationConfirmation/:tableNumber/:timeSlot/:restaurantId" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationConfirmation />} />} />
47 <Route path="/reservations/reservationEdit/:reservationId" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationEdit />} />} />
48 <Route path="/reservations-past" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationHistory />} />} />
49 <Route path="/login" element={<AuthForm setIsAuthenticated={setIsAuthenticated} />} />
50
51 <Route path="/error" element={<ErrorPage />} />
52 </Routes>
53 </Layout>
54 </Router>
55 );
56};
57
58
59const Home = () => {
60 const navigate = useNavigate();
61
62 const todayDate = new Date().toISOString().split('T')[0]; // Get today's date in 'YYYY-MM-DD' format
63
64 const [date, setDate] = useState(todayDate);
65 const [selectedTime, setSelectedTime] = useState('');
66 const [numPeople, setNumPeople] = useState(2);
67 const [searchValue, setSearchValue] = useState('');
68 const [timeSlots, setTimeSlots] = useState([]);
69 let [filteredRestaurants, setFilteredRestaurants] = useState([]);
70
71 const cuisineTypes = useContext(CuisineContext);
72 const [showCuisineSearch, setShowCuisineSearch] = useState(true);
73
74 const [formatedDateTime, setFormatedDateTime] = useState('')
75
76 useEffect(() => {
77 if (date) {
78 const selectedDate = new Date(date);
79 const today = new Date();
80 const isToday = selectedDate.toDateString() === today.toDateString();
81
82 // Determine the start hour and minute
83 let startHour = 9;
84 let startMinute = 0;
85 if (isToday) {
86 const currentHour = today.getHours();
87 const currentMinute = today.getMinutes();
88 // If current time is later than 09:00, start from the current hour and minute
89 if (currentHour > 9 || (currentHour === 9 && currentMinute >= 0)) {
90 startHour = currentHour;
91 startMinute = Math.ceil(currentMinute / 15) * 15;
92 }
93 }
94
95 // Create the start time and end time
96 const startTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), startHour, startMinute);
97 const endTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 23, 30);
98
99 // Generate time slots from start time to end time in 15-minute intervals
100 const slots = [];
101 let currentTime = new Date(startTime);
102 while (currentTime <= endTime) {
103 const option = currentTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
104 slots.push(option);
105 currentTime.setMinutes(currentTime.getMinutes() + 15); // Increment by 15 minutes
106 }
107
108 // Update the timeSlots state
109 setTimeSlots(slots);
110 }
111 }, [date]);
112
113 const handleDateChange = (e) => {
114 setDate(e.target.value);
115 };
116
117 const handleTimeChange = (e) => {
118 setSelectedTime(e.target.value);
119 };
120
121 const handleNumPeopleChange = (e) => {
122 setNumPeople(e.target.value);
123 };
124
125 const handleInputChange = (event) => {
126 setSearchValue(event.target.value);
127 };
128
129 const handleSubmit = async (e) => {
130 e.preventDefault();
131 const [year, month, day] = date.split("-");
132 let formattedDateTime;
133
134 if (selectedTime) {
135 const [selectedHours, selectedMinutes] = selectedTime.split(":");
136 // Check if selectedHours and selectedMinutes are valid numbers
137 if (!isNaN(selectedHours) && !isNaN(selectedMinutes)) {
138 const dateTime = new Date(Date.UTC(year, month - 1, day, selectedHours, selectedMinutes));
139 formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' ');
140 setFormatedDateTime(formattedDateTime);
141 }
142 } else {
143 // Find the first available time slot after the current time
144 const now = new Date();
145 const currentTime = now.getHours() * 60 + now.getMinutes(); // Current time in minutes
146 const nextSlot = timeSlots.find(slot => {
147 const [hours, minutes] = slot.split(":");
148 const slotTime = parseInt(hours) * 60 + parseInt(minutes); // Time of the slot in minutes
149 return slotTime > currentTime;
150 });
151
152 // If no slot is found after the current time, use the first slot of the day
153 formattedDateTime = nextSlot ? `${date} ${nextSlot}` : `${date} ${timeSlots[0]}`;
154 }
155
156 const data = {
157 dateTime: formattedDateTime,
158 partySize: numPeople,
159 search: searchValue
160 };
161
162 console.log("Data to be submitted:");
163 console.log(data);
164
165 try {
166 const response = await axios.post('http://localhost:8081/api/search', data);
167 const filteredRestaurants = response.data;
168 setFilteredRestaurants(filteredRestaurants);
169 console.log(filteredRestaurants);
170 setShowCuisineSearch(false);
171 // Handle response accordingly
172 } catch (error) {
173 console.error('Error:', error);
174 }
175 };
176
177 const handleSearchByCuisine = async (cuisine) => {
178 const cuisineName = cuisine.replace('Searching by cuisine: ', '');
179 try {
180 const response = await axios.post(`http://localhost:8081/api/search/shortcut/${cuisineName}`, cuisineName);
181 console.log(response.data);
182 setFilteredRestaurants(response.data)
183 } catch (error) {
184 console.error('Error searching by cuisine:', error);
185 }
186 setShowCuisineSearch(false);
187 };
188
189 const handleTimeSlotClick = (table, timeSlot, restaurant) => {
190 const tableNumber = table.id;
191 const formattedTimeSlot = timeSlot;
192 const restaurantId = restaurant.restaurantId;
193
194 const encodedTableNumber = encodeURI(tableNumber);
195 const encodedTimeSlot = encodeURIComponent(formattedTimeSlot);
196 const encodedRestaurantId = encodeURIComponent(restaurantId);
197
198 navigate(`/reservationConfirmation/${encodedTableNumber}/${encodedTimeSlot}/${encodedRestaurantId}`);
199 }
200
201 const renderTimeSlots = (tablesList, restaurant) => {
202 const [year, month, day] = date.split("-");
203 const [hours, minutes] = selectedTime.split(":");
204 const dateTime = new Date(year, month - 1, day, hours, minutes); // month is zero-based
205
206 let timestamp = dateTime.getTime();
207 if (isNaN(timestamp)) {
208 timestamp = Date.now();
209 }
210
211 let renderedTimeSlots = {}; // Object to store rendered slots for each table capacity
212
213 return tablesList.flatMap(table => {
214 // Render capacity header when encountering a new capacity
215 if (!renderedTimeSlots[table.capacity] && numPeople <= table.capacity) {
216 renderedTimeSlots[table.capacity] = 0;
217 return (
218 <div key={table.capacity}>
219 <h3>Table for: {table.capacity}</h3>
220 {table.timeSlots.map((timeSlot, index) => {
221 let timeSlotTime = new Date(timeSlot).getTime();
222
223 const tableCapacity = table.capacity;
224 // Check if the time slot is after the current time, numPeople is less than or equal to tableCapacity, and limit to 5 slots
225 if (timeSlotTime >= timestamp && numPeople <= tableCapacity && renderedTimeSlots[tableCapacity] < 5) {
226 renderedTimeSlots[tableCapacity]++;
227 const timeSlotDateTime = new Date(timeSlot);
228 const formattedDateTime = timeSlotDateTime.toLocaleString(); // Format for both date and time
229
230 return (
231 <button key={index} className="btn btn-primary me-2 mb-2" onClick={() => handleTimeSlotClick(table, timeSlot, restaurant)}>
232 {formattedDateTime} {/* Display both date and time */}
233 </button>
234 );
235 } else {
236 return null; // Render nothing if the condition is not met
237 }
238 })}
239 </div>
240 );
241 } else {
242 // If capacity has been rendered, return null to avoid duplicate rendering
243 return null;
244 }
245 });
246 }
247
248
249
250// Rest of your component code...
251
252 const today = new Date();
253 const year = today.getFullYear();
254 const month = String(today.getMonth() + 1).padStart(2, '0');
255 const day = String(today.getDate()).padStart(2, '0');
256 const formattedDate = `${year}-${month}-${day}`;
257
258
259 return (
260 <div className="container">
261 <h2 className="display-1">Rezerviraj masa</h2>
262 <form className="row g-2 align-items-center" onSubmit={handleSubmit}>
263 <div className="col-auto">
264 <input className="form-control me-2" type="date" value={date} onChange={handleDateChange}
265 min={formattedDate}/>
266 </div>
267 <div className="col-auto">
268 <select className="form-select" onChange={handleTimeChange}>
269 {timeSlots.map((slot, index) => (
270 <option key={index} value={slot}>{slot}</option>
271 ))}
272 </select>
273 </div>
274 <div className="col-auto">
275 <select className="form-select" value={numPeople} onChange={handleNumPeopleChange}>
276 {[...Array(20).keys()].map((num) => (
277 <option key={num + 1} value={num + 1}>{num + 1}</option>
278 ))}
279 </select>
280 </div>
281 <div className="col-auto">
282 <input
283 className="form-control me-2"
284 type="search"
285 name="search"
286 placeholder="Restaurant or Cuisine"
287 aria-label="Search"
288 value={searchValue} // Set the value of the input field
289 onChange={handleInputChange} // Call the event handler on change
290 />
291 </div>
292 <div className="col-auto">
293 <button className="btn btn-outline-success" type="submit">Search</button>
294 </div>
295
296 <div className="border-0">
297 {filteredRestaurants.map((restaurant) => (
298 <div key={restaurant.id} className="card mb-3">
299 <div className="card-body">
300 <RestaurantInfo key={restaurant.id} restaurant={restaurant}/>
301 <p>Available time slots</p>
302 <div className="d-flex flex-wrap">
303 {renderTimeSlots(restaurant.tablesList.flatMap((table) => table), restaurant)}
304 </div>
305 </div>
306 </div>
307 ))}
308 </div>
309
310
311 {showCuisineSearch && (
312 <div className="mb-3">
313 <h2 className="display-2">Search by cuisine type</h2>
314 <ul className="list-group">
315 {cuisineTypes.map((cuisine, index) => (
316 <li key={index} className="list-group-item">
317 <button type="button" className="btn btn-outline-primary"
318 onClick={() => handleSearchByCuisine(cuisine)}>
319 {cuisine}
320 </button>
321 </li>
322 ))}
323 </ul>
324 </div>)}
325 </form>
326 </div>
327 );
328}
329
330export default App;
Note: See TracBrowser for help on using the repository browser.