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

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

Authorization layer

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