source: my-react-app/src/components/ReservationConfirmation.js@ b67dfd3

main
Last change on this file since b67dfd3 was b67dfd3, checked in by Aleksandar Panovski <apano77@…>, 13 days ago

Normalization needed to continue, till here done

  • Property mode set to 100644
File size: 9.7 KB
RevLine 
[d24f17c]1import React, { useState, useEffect } from 'react';
2import { useParams } from 'react-router-dom';
3import axios from 'axios';
4import { useNavigate } from 'react-router-dom';
[e15e8d9]5import { useLocation } from 'react-router-dom';
6import { jwtDecode } from "jwt-decode";
[f5b256e]7import {request} from "../axios_helper";
8import restaurants from "./Restaurants";
[d24f17c]9
10const ReservationConfirmation = () => {
11 const navigate = useNavigate();
12
[e15e8d9]13 const location = useLocation();
14 const preOrderedItems = location.state?.preOrderedItems || [];
[d24f17c]15 const [restaurant, setRestaurant] = useState({});
[f5b256e]16 const [user, setUser] = useState({});
[d24f17c]17 const [table, setTable] = useState({});
18 const [reservationDateTime, setReservationDateTime] = useState('');
19 const [partySize, setPartySize] = useState('');
20 const [specialRequests, setSpecialRequests] = useState('');
21 const { tableNumber, timeSlot, restaurantId } = useParams();
22
[f5b256e]23 const adjustedTimeSlot = new Date(new Date(timeSlot).getTime() + 60 * 60 * 1000).toISOString();
[d24f17c]24 useEffect(() => {
[f5b256e]25 const fetchDetails = async () => {
[d24f17c]26 try {
[8ca35dc]27 const tableResponse = await axios.get(`http://localhost:8081/api/tables/${tableNumber}`);
[d24f17c]28 setTable(tableResponse.data);
[b67dfd3]29 console.log(tableResponse.data)
[8ca35dc]30 const restaurantResponse = await axios.get(`http://localhost:8081/api/restaurants/${restaurantId}`);
[d24f17c]31 setRestaurant(restaurantResponse.data);
[f5b256e]32
33 const token = localStorage.getItem("token");
34 if (!token) {
35 console.error("No token found");
36 return;
37 }
38 const decodedToken = jwtDecode(token);
39 const userId = decodedToken.iss;
40
41 const userResponse = await axios.get(`http://localhost:8081/api/user/${userId}`);
42 setUser(userResponse.data);
[d24f17c]43 } catch (error) {
[f5b256e]44 console.error('Error fetching table or restaurant details:', error);
[d24f17c]45 }
46 };
[f5b256e]47 fetchDetails();
[d24f17c]48 }, [tableNumber, restaurantId]);
49
50 const handleSubmit = async (e) => {
51 e.preventDefault();
[8ca35dc]52
[f5b256e]53 const payload = {
54 reservationID: 0,
55 userEmail: user.email,
56 rating: parseFloat(restaurant.rating) || null,
57 tableNumber: parseInt(table.id, 10),
[2518b3a]58 restaurantId: restaurant.restaurantId,
[f5b256e]59 reservationDateTime: adjustedTimeSlot,
60 partySize: parseInt(partySize, 10),
61 status: 'Reserved',
62 specialRequests: specialRequests.trim(),
63 paymentStatus: 'Pending',
[2518b3a]64 preOrderedItems: preOrderedItems.map(item => ({
[b67dfd3]65 preorderedItemName: item.itemName,
[2518b3a]66 quantity: item.quantity,
67 price: item.price
68 }))
[f5b256e]69 };
[d24f17c]70
[8ca35dc]71
[f5b256e]72 try {
[2518b3a]73 const response = await axios.post('http://localhost:8081/api/reservations', payload, {
74 headers: {
75 'Content-Type': 'application/json'
76 }
77 });
[f5b256e]78 console.log('Reservation created successfully:', response.data);
79 navigate("/reservations")
[d24f17c]80 } catch (error) {
[f5b256e]81 if (error.response) {
82 alert('The selected time slot is no longer available. Please choose another time.');
83 } else {
84 alert('Network error. Please check your internet connection.');
85 }
[d24f17c]86 }
87 };
88
[f5b256e]89 const calculateCheckOutTime = (checkInTime) => {
90 const checkIn = new Date(checkInTime);
91 checkIn.setHours(checkIn.getHours() + 2);
92 return checkIn.toISOString();
93 };
94
[d24f17c]95 const initialRemainingTime = localStorage.getItem('remainingTime') || 300;
[f5b256e]96 const [remainingTime, setRemainingTime] = useState(parseInt(initialRemainingTime, 10));
[d24f17c]97
98 useEffect(() => {
99 const timer = setInterval(() => {
100 setRemainingTime((prevTime) => {
101 const newTime = prevTime - 1;
[f5b256e]102 localStorage.setItem('remainingTime', newTime.toString());
[d24f17c]103 return newTime;
104 });
105 }, 1000);
106
107 return () => clearInterval(timer);
108 }, []);
109
110 useEffect(() => {
111 if (remainingTime <= 0) {
112 localStorage.removeItem('remainingTime');
[f5b256e]113 alert("Time has expired. Please try reserving again.");
114 navigate('/restaurants'); // Redirect or take necessary action
[d24f17c]115 }
[f5b256e]116 }, [remainingTime, navigate]);
[d24f17c]117
118 const formatTime = (timeInSeconds) => {
119 const minutes = Math.floor(timeInSeconds / 60);
120 const seconds = timeInSeconds % 60;
121 return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
122 };
123
[f5b256e]124 const formatTimeSlot = (timeSlot) => {
125 const utcDate = new Date(timeSlot);
126 const localDate = new Date(utcDate.toLocaleString("en-US", { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }));
127 const formattedDate = localDate.toLocaleDateString();
128 const formattedTime = localDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
129 return `${formattedDate} - ${formattedTime}`;
130 };
131
[e15e8d9]132 const grandTotal = preOrderedItems.reduce((acc, item) => acc + item.price * item.quantity, 0).toFixed(2);
133 const itemQuantityString = preOrderedItems
134 .map(item => `${item.itemName}:${item.quantity}`)
135 .join(',');
136
[d24f17c]137 return (
138 <div className="container mt-5">
139 <div className="row justify-content-center">
140 <div className="col-md-6">
141 <div className="card">
142 <div className="card-header">
143 <h3 className="text-center">Reservation Confirmation</h3>
144 <p>Remaining Time: {formatTime(remainingTime)}</p>
145 </div>
146 <form onSubmit={handleSubmit}>
147 <div className="card-body">
148 <h5 className="card-title">Reservation Details</h5>
149 <p className="card-text">
[f5b256e]150 <strong>Restaurant:</strong> {restaurant.name || 'Loading...'} <br />
151 <strong>Cuisine type:</strong> {restaurant.cuisineType || 'Loading...'} <br />
152 <strong>Selected Time Slot:</strong> {formatTimeSlot(timeSlot)} <br />
153 <strong>Party size:</strong>{' '}
154 <input
155 type="number"
156 max={table.capacity}
157 value={partySize}
158 onChange={(e) => setPartySize(e.target.value)}
159 />
160 <strong>Table size:</strong> {table.capacity} <br />
161 <strong>Special Requests:</strong>{' '}
162 <input
163 type="text"
164 value={specialRequests}
165 onChange={(e) => setSpecialRequests(e.target.value)}
166 />
167 <br />
[d24f17c]168 </p>
169 <p className="card-text text-success">
[f5b256e]170 <strong>
171 Check-in Time: Grace period of 15 minutes +/- the slot. For more information, call the restaurant.
172 </strong>
173 <br />
[d24f17c]174 </p>
[e15e8d9]175 {preOrderedItems.length > 0 ? (
176 <div className="row">
177 {preOrderedItems.map((item) => (
178 <div key={item.menuID} className="col-md-4 mb-4">
179 <div className="list-group shadow-sm p-3">
180 <p className="item"><strong>Item:</strong> {item.itemName}</p>
181 <p className="item"><strong>Price:</strong> ${item.price.toFixed(2)}</p>
182 <p className="item"><strong>Quantity:</strong> {item.quantity}</p>
183 <p className="item"><strong>Total:</strong> ${(item.price * item.quantity).toFixed(2)}</p>
184 </div>
185 </div>
186 ))}
187
188 <div className="col-12 mt-4">
189 <div className="list-group shadow-sm p-4 text-center">
190 <h4>Grand Total: ${grandTotal}</h4>
191 </div>
192 </div>
193 </div>
194 ) : (
195 <p>No pre-ordered items.</p>
196 )}
[d24f17c]197 </div>
198 <div className="card-footer">
199 <button type="submit" className="btn btn-primary">Submit</button>
[f5b256e]200 <a href="/restaurants" className="btn btn-secondary mx-2">Back to Restaurants</a>
201 <a href="/" className="btn btn-secondary">Back to Home</a>
[d24f17c]202 </div>
203 </form>
204 </div>
205 </div>
206 </div>
207 </div>
208 );
209};
210
[f5b256e]211export default ReservationConfirmation;
Note: See TracBrowser for help on using the repository browser.