[d24f17c] | 1 | import React, { useState, useEffect } from 'react';
|
---|
| 2 | import { useParams } from 'react-router-dom';
|
---|
| 3 | import axios from 'axios';
|
---|
| 4 | import { useNavigate } from 'react-router-dom';
|
---|
[e15e8d9] | 5 | import { useLocation } from 'react-router-dom';
|
---|
| 6 | import { jwtDecode } from "jwt-decode";
|
---|
[f5b256e] | 7 | import {request} from "../axios_helper";
|
---|
| 8 | import restaurants from "./Restaurants";
|
---|
[d24f17c] | 9 |
|
---|
| 10 | const 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);
|
---|
| 29 |
|
---|
[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),
|
---|
| 58 | restaurant: restaurant,
|
---|
| 59 | reservationDateTime: adjustedTimeSlot,
|
---|
| 60 | partySize: parseInt(partySize, 10),
|
---|
| 61 | status: 'Reserved',
|
---|
| 62 | specialRequests: specialRequests.trim(),
|
---|
| 63 | paymentStatus: 'Pending',
|
---|
[e15e8d9] | 64 | preOrderedItems: preOrderedItems.map(item => `${item.itemName}:${item.quantity}:${item.price}`)
|
---|
[f5b256e] | 65 | };
|
---|
[d24f17c] | 66 |
|
---|
[8ca35dc] | 67 |
|
---|
[f5b256e] | 68 | try {
|
---|
| 69 | const response = await axios.post('http://localhost:8081/api/reservations', payload);
|
---|
| 70 | console.log('Reservation created successfully:', response.data);
|
---|
| 71 | navigate("/reservations")
|
---|
[d24f17c] | 72 | } catch (error) {
|
---|
[f5b256e] | 73 | if (error.response) {
|
---|
| 74 | alert('The selected time slot is no longer available. Please choose another time.');
|
---|
| 75 | } else {
|
---|
| 76 | alert('Network error. Please check your internet connection.');
|
---|
| 77 | }
|
---|
[d24f17c] | 78 | }
|
---|
| 79 | };
|
---|
| 80 |
|
---|
[f5b256e] | 81 | const calculateCheckOutTime = (checkInTime) => {
|
---|
| 82 | const checkIn = new Date(checkInTime);
|
---|
| 83 | checkIn.setHours(checkIn.getHours() + 2);
|
---|
| 84 | return checkIn.toISOString();
|
---|
| 85 | };
|
---|
| 86 |
|
---|
[d24f17c] | 87 | const initialRemainingTime = localStorage.getItem('remainingTime') || 300;
|
---|
[f5b256e] | 88 | const [remainingTime, setRemainingTime] = useState(parseInt(initialRemainingTime, 10));
|
---|
[d24f17c] | 89 |
|
---|
| 90 | useEffect(() => {
|
---|
| 91 | const timer = setInterval(() => {
|
---|
| 92 | setRemainingTime((prevTime) => {
|
---|
| 93 | const newTime = prevTime - 1;
|
---|
[f5b256e] | 94 | localStorage.setItem('remainingTime', newTime.toString());
|
---|
[d24f17c] | 95 | return newTime;
|
---|
| 96 | });
|
---|
| 97 | }, 1000);
|
---|
| 98 |
|
---|
| 99 | return () => clearInterval(timer);
|
---|
| 100 | }, []);
|
---|
| 101 |
|
---|
| 102 | useEffect(() => {
|
---|
| 103 | if (remainingTime <= 0) {
|
---|
| 104 | localStorage.removeItem('remainingTime');
|
---|
[f5b256e] | 105 | alert("Time has expired. Please try reserving again.");
|
---|
| 106 | navigate('/restaurants'); // Redirect or take necessary action
|
---|
[d24f17c] | 107 | }
|
---|
[f5b256e] | 108 | }, [remainingTime, navigate]);
|
---|
[d24f17c] | 109 |
|
---|
| 110 | const formatTime = (timeInSeconds) => {
|
---|
| 111 | const minutes = Math.floor(timeInSeconds / 60);
|
---|
| 112 | const seconds = timeInSeconds % 60;
|
---|
| 113 | return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
---|
| 114 | };
|
---|
| 115 |
|
---|
[f5b256e] | 116 | const formatTimeSlot = (timeSlot) => {
|
---|
| 117 | const utcDate = new Date(timeSlot);
|
---|
| 118 | const localDate = new Date(utcDate.toLocaleString("en-US", { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }));
|
---|
| 119 | const formattedDate = localDate.toLocaleDateString();
|
---|
| 120 | const formattedTime = localDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
---|
| 121 | return `${formattedDate} - ${formattedTime}`;
|
---|
| 122 | };
|
---|
| 123 |
|
---|
[e15e8d9] | 124 | const grandTotal = preOrderedItems.reduce((acc, item) => acc + item.price * item.quantity, 0).toFixed(2);
|
---|
| 125 | const itemQuantityString = preOrderedItems
|
---|
| 126 | .map(item => `${item.itemName}:${item.quantity}`)
|
---|
| 127 | .join(',');
|
---|
| 128 |
|
---|
[d24f17c] | 129 | return (
|
---|
| 130 | <div className="container mt-5">
|
---|
| 131 | <div className="row justify-content-center">
|
---|
| 132 | <div className="col-md-6">
|
---|
| 133 | <div className="card">
|
---|
| 134 | <div className="card-header">
|
---|
| 135 | <h3 className="text-center">Reservation Confirmation</h3>
|
---|
| 136 | <p>Remaining Time: {formatTime(remainingTime)}</p>
|
---|
| 137 | </div>
|
---|
| 138 | <form onSubmit={handleSubmit}>
|
---|
| 139 | <div className="card-body">
|
---|
| 140 | <h5 className="card-title">Reservation Details</h5>
|
---|
| 141 | <p className="card-text">
|
---|
[f5b256e] | 142 | <strong>Restaurant:</strong> {restaurant.name || 'Loading...'} <br />
|
---|
| 143 | <strong>Cuisine type:</strong> {restaurant.cuisineType || 'Loading...'} <br />
|
---|
| 144 | <strong>Selected Time Slot:</strong> {formatTimeSlot(timeSlot)} <br />
|
---|
| 145 | <strong>Party size:</strong>{' '}
|
---|
| 146 | <input
|
---|
| 147 | type="number"
|
---|
| 148 | max={table.capacity}
|
---|
| 149 | value={partySize}
|
---|
| 150 | onChange={(e) => setPartySize(e.target.value)}
|
---|
| 151 | />
|
---|
| 152 | <strong>Table size:</strong> {table.capacity} <br />
|
---|
| 153 | <strong>Special Requests:</strong>{' '}
|
---|
| 154 | <input
|
---|
| 155 | type="text"
|
---|
| 156 | value={specialRequests}
|
---|
| 157 | onChange={(e) => setSpecialRequests(e.target.value)}
|
---|
| 158 | />
|
---|
| 159 | <br />
|
---|
[d24f17c] | 160 | </p>
|
---|
| 161 | <p className="card-text text-success">
|
---|
[f5b256e] | 162 | <strong>
|
---|
| 163 | Check-in Time: Grace period of 15 minutes +/- the slot. For more information, call the restaurant.
|
---|
| 164 | </strong>
|
---|
| 165 | <br />
|
---|
[d24f17c] | 166 | </p>
|
---|
[e15e8d9] | 167 | {preOrderedItems.length > 0 ? (
|
---|
| 168 | <div className="row">
|
---|
| 169 | {preOrderedItems.map((item) => (
|
---|
| 170 | <div key={item.menuID} className="col-md-4 mb-4">
|
---|
| 171 | <div className="list-group shadow-sm p-3">
|
---|
| 172 | <p className="item"><strong>Item:</strong> {item.itemName}</p>
|
---|
| 173 | <p className="item"><strong>Price:</strong> ${item.price.toFixed(2)}</p>
|
---|
| 174 | <p className="item"><strong>Quantity:</strong> {item.quantity}</p>
|
---|
| 175 | <p className="item"><strong>Total:</strong> ${(item.price * item.quantity).toFixed(2)}</p>
|
---|
| 176 | </div>
|
---|
| 177 | </div>
|
---|
| 178 | ))}
|
---|
| 179 |
|
---|
| 180 | <div className="col-12 mt-4">
|
---|
| 181 | <div className="list-group shadow-sm p-4 text-center">
|
---|
| 182 | <h4>Grand Total: ${grandTotal}</h4>
|
---|
| 183 | </div>
|
---|
| 184 | </div>
|
---|
| 185 | </div>
|
---|
| 186 | ) : (
|
---|
| 187 | <p>No pre-ordered items.</p>
|
---|
| 188 | )}
|
---|
[d24f17c] | 189 | </div>
|
---|
| 190 | <div className="card-footer">
|
---|
| 191 | <button type="submit" className="btn btn-primary">Submit</button>
|
---|
[f5b256e] | 192 | <a href="/restaurants" className="btn btn-secondary mx-2">Back to Restaurants</a>
|
---|
| 193 | <a href="/" className="btn btn-secondary">Back to Home</a>
|
---|
[d24f17c] | 194 | </div>
|
---|
| 195 | </form>
|
---|
| 196 | </div>
|
---|
| 197 | </div>
|
---|
| 198 | </div>
|
---|
| 199 | </div>
|
---|
| 200 | );
|
---|
| 201 | };
|
---|
| 202 |
|
---|
[f5b256e] | 203 | export default ReservationConfirmation; |
---|