source: my-react-app/src/App.js@ 748b7f6

main
Last change on this file since 748b7f6 was e35d0e9, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

RetaurantServiceImpl problemi
isAvailable od tableEntity...

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