Skip to content

Commit

Permalink
fixed bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben-Sicat committed Dec 20, 2023
1 parent 1374937 commit e33d911
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 40 deletions.
70 changes: 44 additions & 26 deletions backend/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,67 +402,85 @@ def move_to_completed_reservations(reservation_id):
try:
cursor = connection.cursor()

# Fetch reservation details
query = """
SELECT * FROM Reservations WHERE ReservationID = %s
"""
cursor.execute(query, (reservation_id,))
reservation = cursor.fetchone()

if reservation:
# Convert tuple to dictionary for easier access
reservation_dict = dict(zip(cursor.column_names, reservation))

# Insert into Completed_Reservations table
insert_query = """
INSERT INTO Completed_Reservations(ReservationID, UserID, StartTime, EndTime, Seat, TableFee, ResDate)
INSERT INTO Completed_Reservations(ReservationID, UserID, ResDate, StartTime, EndTime, Seat, TableFee)
VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
values = (
reservation_dict['ReservationID'], reservation_dict['UserID'], reservation_dict['StartTime'], reservation_dict['EndTime'], reservation_dict['Seat'], reservation_dict['TableFee'], reservation_dict['ResDate']
)
values = (
reservation[0], reservation[1], reservation[2], reservation[3], reservation[4], reservation[5], reservation[6]
)
cursor.execute(insert_query, values)

remove_reservation_by_id(reservation_id)
# Delete from Reservations table
delete_query = """
DELETE FROM Reservations WHERE ReservationID = %s
"""
cursor.execute(delete_query, (reservation_id,))

connection.commit()
connection.commit() # Commit changes
cursor.close()
connection.close()

print("Reservation moved to completed reservation")
print(f"Reservation {reservation_id} moved to completed reservations.")

except mysql.connector.Error as err:
print(f"Error moving reservation to completed reservation {err}")
connection.rollback()
print(f"Error moving reservation {reservation_id} to completed reservation: {err}")
connection.rollback() # Rollback in case of error


@app.route('/api/check-reservations-end', methods=['POST'])
def check_reservation_end_route():
try:
current_time = request.json.get('current_time', None)
curr = datetime.strptime(current_time, '%H:%M:%S')
current_time_str = request.json.get('current_time', None)
current_hours, current_minutes = map(int, current_time_str.split(':'))

connection = get_db_connection(db_config)
cursor = connection.cursor(dictionary=True)

query = """
SELECT * FROM Reservations WHERE EndTime <= %s
SELECT * FROM Reservations
"""
connection = get_db_connection(db_config)
cursor = connection.cursor(dictionary=True) # Use dictionary cursor
cursor.execute(query)

cursor.execute(query, (curr,))
reservations = cursor.fetchall()

print(f"Fetched Reservations: {reservations}") # Debugging line

for reservation in reservations:
print(f"EndTime of Reservation {reservation['ReservationID']}: {reservation['EndTime']}")
move_to_completed_reservations(reservation['ReservationID'])

cursor.close()
connection.close()

for reservation in reservations:
end_time_str = reservation['EndTime']
if is_before_or_equal(end_time_str, current_hours, current_minutes):
move_to_completed_reservations(reservation['ReservationID'])

return jsonify({'message': 'Checked and processed reservations successfully.'}), 200

except Exception as e:
print(f"Error checking reservations end: {e}")
return jsonify(error='Error checking reservations end'), 500
return jsonify(error=f'Error checking reservations end: {e}'), 500



def is_before_or_equal(end_time_str, current_hours, current_minutes):
"""
Check if the end_time_str (format: 'HH:MM') is before or equal to the current time components.
"""
end_hours, end_minutes = map(int, end_time_str.split(':'))

if end_hours < current_hours:
return True
elif end_hours == current_hours and end_minutes <= current_minutes:
return True
else:
return False

@app.route('/api/remove-reservation/<string:chair_id>', methods=['DELETE'])
def remove_reservation_route(chair_id):
try:
Expand Down
11 changes: 3 additions & 8 deletions backend/db/init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ CREATE TABLE Completed_Reservations (
ReservationID INT,
UserID INT,
ResDate VARCHAR(225),
StartTime TIME NOT NULL,
EndTime TIME NOT NULL,
StartTime VARCHAR(225) NOT NULL,
EndTime VARCHAR(225) NOT NULL,
Seat VARCHAR(50),
TableFee DECIMAL(10,2) DEFAULT 0.00,
FOREIGN KEY (UserID) REFERENCES Users(UserID) ON DELETE CASCADE
Expand Down Expand Up @@ -76,10 +76,5 @@ VALUES
('google_id_4', 'user_4', '[email protected]', 'password4', 'Bob', 'Smith', '6666666666', 'UName4', '1975-12-10', 'Male', 'School4', 'Occupation4', 'User');


INSERT INTO Reservations (UserID, StartTime, EndTime, Seat)
VALUES
(1, '08:00:00', '12:00:00', 'chair1'),
(2, '09:00:00', '3:00:00', 'chair10'),
(3, '2023-01-03 10:00:00', '2023-01-03 14:00:00', 'chair4'),
(4, '2023-01-04 11:00:00', '2023-01-04 15:00:00', 'chair5');


14 changes: 11 additions & 3 deletions frontend/app/admin_areamap/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ import ModalAdmin from "../components/modal_admin";

function Page() {
const checkReservationsEnd = () => {
const currentTime = new Date().toLocaleTimeString('en-US', { timeZone: 'Asia/Manila', hour12: false });
const currentDate = new Date();

const options = {
timeZone: 'Asia/Manila',
hour12: false,
hour: '2-digit' as const,
minute: '2-digit' as const
};

const currentTime = currentDate.toLocaleTimeString('en-US', options);

console.log("Current time:", currentTime);
fetch("http://localhost:5000/api/check-reservations-end", {
method: "POST",
Expand Down Expand Up @@ -68,8 +78,6 @@ function Page() {
console.log("chairId", chairId);
setModalOpen(!isModalOpen);
console.log("isChairOpen", isChairOpen);


await fetchReservation(chairId);
console.log("reservationData", reservationData)
// Toggle the modal state
Expand Down
6 changes: 3 additions & 3 deletions frontend/app/components/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ const BasicModal: React.FC<BasicModalProps> = ({

if (response.ok) {
console.log("Reserved successfully!");
router.push(
`https://payment-gateway-weld.vercel.app/gcash/login?amountDue=${tableFee}&merchant=Brew and Brains&redirectUrl=${redirectUrl}`
);
// router.push(
// `https://payment-gateway-weld.vercel.app/gcash/login?amountDue=${tableFee}&merchant=Brew and Brains&redirectUrl=${redirectUrl}`
// );
} else {
console.error("Error Reservation", await response.json());
<BasicModalWait isOpen={true} onClose={onClose} chairID={chairId}/>
Expand Down

0 comments on commit e33d911

Please sign in to comment.