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