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

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

RetaurantServiceImpl problemi
isAvailable od tableEntity...

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