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

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

RetaurantServiceImpl problemi
isAvailable od tableEntity...

  • Property mode set to 100644
File size: 9.6 KB
RevLine 
[d24f17c]1import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
2import Customers from './components/Customers';
3import Layout from "./components/Layout";
[cfc16a3]4import React, {useContext, useEffect, useState} from 'react';
[d24f17c]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";
[65b6638]13import axios from "axios";
[cfc16a3]14import { CuisineContext } from './components/CuisineContext';
[d24f17c]15
16const App = () => {
17 return (
18 <Router>
19 <Layout>
20 <Routes>
21 <Route path="/" element={<Home />} />
22 <Route path="/customers" element={<Customers />} />
23 <Route path="/customers/add" element={<CustomerFormContainer/>} />
24 <Route path="/customers/:id" element={<CustomerDetails />} />
25 <Route path="/customers/edit/:id" element={<CustomerFormContainer/>} />
26 <Route path="/restaurants" element={<Restaurants />} />
27 <Route path="/restaurants/:id" element={<RestaurantDetails />} />
28 <Route path="/reservations" element={<Reservations />} />
29 <Route path="/reservationConfirmation/:tableNumber/:timeSlot/:restaurantId" element={<ReservationConfirmation />} />
30 <Route path="/reservations/reservationEdit/:reservationId" element={<ReservationEdit />} />
31 <Route path="/error" element={<ErrorPage/>}/>
32 </Routes>
33 </Layout>
34 </Router>
35 );
36}
37
38
39const Home = () => {
40 const todayDate = new Date().toISOString().split('T')[0]; // Get today's date in 'YYYY-MM-DD' format
41
42 const [date, setDate] = useState(todayDate);
43 const [selectedTime, setSelectedTime] = useState('');
44 const [numPeople, setNumPeople] = useState(2);
45 const [searchValue, setSearchValue] = useState('');
46 const [timeSlots, setTimeSlots] = useState([]);
47
[cfc16a3]48 const cuisineTypes = useContext(CuisineContext);
49
[d24f17c]50 useEffect(() => {
51 if (date) {
52 const selectedDate = new Date(date);
53 const today = new Date();
54 const isToday = selectedDate.toDateString() === today.toDateString();
55
[65b6638]56 // Determine the start hour and minute
57 let startHour = 9;
58 let startMinute = 0;
59 if (isToday) {
60 const currentHour = today.getHours();
61 const currentMinute = today.getMinutes();
62 // If current time is later than 09:00, start from the current hour and minute
63 if (currentHour > 9 || (currentHour === 9 && currentMinute >= 0)) {
64 startHour = currentHour;
65 startMinute = Math.ceil(currentMinute / 15) * 15;
66 }
67 }
[d24f17c]68
[65b6638]69 // Create the start time and end time
70 const startTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), startHour, startMinute);
[d24f17c]71 const endTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 23, 30);
72
[65b6638]73 // Generate time slots from start time to end time in 15-minute intervals
[d24f17c]74 const slots = [];
[65b6638]75 let currentTime = new Date(startTime);
[d24f17c]76 while (currentTime <= endTime) {
77 const option = currentTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
78 slots.push(option);
79 currentTime.setMinutes(currentTime.getMinutes() + 15); // Increment by 15 minutes
80 }
81
[65b6638]82 // Update the timeSlots state
[d24f17c]83 setTimeSlots(slots);
84 }
85 }, [date]);
86
87 const handleDateChange = (e) => {
88 setDate(e.target.value);
89 };
90
91 const handleTimeChange = (e) => {
92 setSelectedTime(e.target.value);
93 };
94
95 const handleNumPeopleChange = (e) => {
96 setNumPeople(e.target.value);
97 };
98
99 const handleInputChange = (event) => {
100 setSearchValue(event.target.value);
101 };
102
[65b6638]103 const handleSubmit = async (e) => {
[d24f17c]104 e.preventDefault();
[65b6638]105 const [year, month, day] = date.split("-");
106 let formattedDateTime;
[cfc16a3]107
108 if (selectedTime) {
109 const [selectedHours, selectedMinutes] = selectedTime.split(":");
110 // Check if selectedHours and selectedMinutes are valid numbers
111 if (!isNaN(selectedHours) && !isNaN(selectedMinutes)) {
112 const dateTime = new Date(Date.UTC(year, month - 1, day, selectedHours, selectedMinutes));
113 formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' ');
114 }
[65b6638]115 } else {
[cfc16a3]116 // Find the first available time slot after the current time
[65b6638]117 const now = new Date();
[cfc16a3]118 const currentTime = now.getHours() * 60 + now.getMinutes(); // Current time in minutes
119 const nextSlot = timeSlots.find(slot => {
120 const [hours, minutes] = slot.split(":");
121 const slotTime = parseInt(hours) * 60 + parseInt(minutes); // Time of the slot in minutes
122 return slotTime > currentTime;
123 });
124
125 // If no slot is found after the current time, use the first slot of the day
126 formattedDateTime = nextSlot ? `${date} ${nextSlot}` : `${date} ${timeSlots[0]}`;
[65b6638]127 }
128
129 const data = {
130 dateTime: formattedDateTime,
131 partySize: numPeople,
132 search: searchValue
133 };
134
[cfc16a3]135 console.log("Data to be submitted:");
136 console.log(data);
[65b6638]137
138 try {
139 const response = await axios.post('http://localhost:8080/api/search', data);
140 const filteredRestaurants = response.data;
141 console.log(filteredRestaurants);
142 // Handle response accordingly
143 } catch (error) {
144 console.error('Error:', error);
145 }
[d24f17c]146 };
147
[cfc16a3]148 const handleSearchByCuisine = async (cuisine) => {
149 const cuisineName = cuisine.replace('Searching by cuisine: ', '');
150 try {
151 const response = await axios.post(`http://localhost:8080/api/search/shortcut/${cuisineName}`, cuisineName);
152 // Handle the response as needed
153 console.log(response.data); // Log the response data, for example
154 } catch (error) {
155 console.error('Error searching by cuisine:', error);
156 // Handle errors, such as displaying an error message to the user
157 }
158 };
[65b6638]159
160
161// Rest of your component code...
162
163 const today = new Date();
164 const year = today.getFullYear();
165 const month = String(today.getMonth() + 1).padStart(2, '0');
166 const day = String(today.getDate()).padStart(2, '0');
167 const formattedDate = `${year}-${month}-${day}`;
168
[d24f17c]169
170 return (
171 <div className="container">
[cfc16a3]172 <h2 className="display-1">Rezerviraj masa</h2>
[d24f17c]173 <form className="row g-2 align-items-center" onSubmit={handleSubmit}>
174 <div className="col-auto">
175 <input className="form-control me-2" type="date" value={date} onChange={handleDateChange}
[65b6638]176 min={formattedDate}/>
[d24f17c]177 </div>
178 <div className="col-auto">
179 <select className="form-select" onChange={handleTimeChange}>
180 {timeSlots.map((slot, index) => (
181 <option key={index} value={slot}>{slot}</option>
182 ))}
183 </select>
184 </div>
185 <div className="col-auto">
186 <select className="form-select" value={numPeople} onChange={handleNumPeopleChange}>
187 {[...Array(20).keys()].map((num) => (
188 <option key={num + 1} value={num + 1}>{num + 1}</option>
189 ))}
190 </select>
191 </div>
192 <div className="col-auto">
193 <input
194 className="form-control me-2"
195 type="search"
196 name="search"
197 placeholder="Restaurant or Cuisine"
198 aria-label="Search"
199 value={searchValue} // Set the value of the input field
200 onChange={handleInputChange} // Call the event handler on change
201 />
202 </div>
203 <div className="col-auto">
204 <button className="btn btn-outline-success" type="submit">Search</button>
205 </div>
[cfc16a3]206 <form>
207 <div className="mb-3">
208 <h2 className="display-2">Search by cuisine type</h2>
209 <ul className="list-group">
210 {cuisineTypes.map((cuisine, index) => (
211 <li key={index} className="list-group-item">
212 <button type="button" className="btn btn-outline-primary"
213 onClick={() => handleSearchByCuisine(cuisine)}>
214 {cuisine}
215 </button>
216 </li>
217 ))}
218 </ul>
219 </div>
220 </form>
221
222
[d24f17c]223 </form>
224 </div>
225 );
226}
227
228
229export default App;
Note: See TracBrowser for help on using the repository browser.