Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ben #49

Merged
merged 2 commits into from
Jan 3, 2024
Merged

Ben #49

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions backend/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,10 +334,12 @@ def create_reservation(user_id, reservation_data):
reservation_data['resdate']
)
cursor.execute(query, values)
reservation_id = cursor.lastrowid

connection.commit()
cursor.close()
connection.close()
return {'message': 'Reservation created successfully'}
return {'message': 'Reservation created successfully', 'reservation_id': reservation_id}
except mysql.connector.Error as err:
print(f"Error creating reservation: {err}")
connection.rollback()
Expand Down Expand Up @@ -376,6 +378,22 @@ def get_all_waitlist_entries():
except mysql.connector.Error as err:
print(f"Error fetching waitlist entries: {err}")
return None
def get_reservation_by_id(reservation_id):
connection = get_db_connection(db_config)
if connection:
try:
cursor = connection.cursor(dictionary=True)
query = """
SELECT * FROM Reservations WHERE ReservationID = %s
"""
cursor.execute(query, (reservation_id,))
result = cursor.fetchone()
cursor.close()
connection.close()
return result
except mysql.connector.Error as err:
print(f"Error fetching reservation by ID: {err}")
return None

def remove_reservation_by_id(reservation_id):
connection = get_db_connection(db_config)
Expand Down Expand Up @@ -504,6 +522,20 @@ def update_endtime_route(chair_id, endtime):
except Exception as e:
print(f"Error updating reservation: {e}")
return jsonify(error='Error updating reservation'), 500


@app.route('/api/get-reservation-by-id/<int:reservation_id>', methods=['GET'])
def get_reservation_by_id_route(reservation_id):
try:
reservation = get_reservation_by_id(reservation_id)
if reservation:
return jsonify({'reservation': reservation}), 200
else:
return jsonify({'error': 'Reservation not found'}), 404
except Exception as e:
print(f"Error fetching reservation by ID: {e}")
return jsonify({'error': str(e)}), 500


@app.route('/api/get-reservation-by-seat/<string:seat>', methods=['GET'])
def get_reservation_by_seat_route(seat):
Expand Down Expand Up @@ -558,8 +590,12 @@ def create_reservation_route():
if existing_reservation and is_overlapping(start_time, end_time, existing_reservation['StartTime'], existing_reservation['EndTime']):
return jsonify({'error': 'Seat already booked for this time range!'}), 400

create_reservation(user_id, data)
return jsonify({'message': 'Reservation created successfully'}), 200
response = create_reservation(user_id, data)

if 'error' in response:
return jsonify(response), 500
else:
return jsonify(response), 200
except Exception as e:
print(f"Error creating reservation: {e}")
return jsonify(message='Error creating reservation'), 500
Expand Down
4 changes: 2 additions & 2 deletions frontend/app/admin_areamap/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ function Page() {
const checkReservationsEnd = () => {
const currentDate = new Date();

const options = {
timeZone: 'Asia/Manila',
const options = {
timeZone: 'Asia/Manila',
hour12: false,
hour: '2-digit' as const,
minute: '2-digit' as const
Expand Down
107 changes: 102 additions & 5 deletions frontend/app/components/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ const BasicModal: React.FC<BasicModalProps> = ({
}));
};

const redirectUrl = "http://localhost:3000/qr_success_reservation";
const baseTableFee = 50; // Base price per hour

const handleCreateReservation = async () => {
Expand Down Expand Up @@ -79,8 +78,83 @@ const BasicModal: React.FC<BasicModalProps> = ({
endtime: formData.EndTime,
user_id: userID,
tablefee: tableFee,

};

console.log(apiData)
console.log(tableFee)



const response = await fetch(
"http://localhost:5000/api/create-reservation",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(apiData),
}
);

if (response.ok) {
console.log("Reserved successfully!");
const responseData = await response.json();

//push the reservationid to the local storage

if(localStorage.getItem("reservation_id") === null){
localStorage.setItem("reservation_id", responseData.reservation_id)
}else{
localStorage.removeItem("reservation_id")
localStorage.setItem("reservation_id", responseData.reservation_id)
}
console.log(responseData.reservation_id)
const redirectUrl = `http://localhost:3000/qr_success_reservation`;


const reservationID = responseData.reservation_id;
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}/>
}
} catch (error) {
console.error("Error Reservation", error);
<BasicModalWait isOpen={true} onClose={onClose} chairID={chairId}/>
}
};
const handleCreateReservationCash = async () => {
try {
const storedUserData = localStorage.getItem("user");
const parsedUserData = storedUserData ? JSON.parse(storedUserData) : null;
const initialFormData = parsedUserData?.updated_user || null;
let userID = initialFormData ? initialFormData.UserID : "";
if (userID == undefined || userID == null || userID === "") {
userID = parsedUserData ? parsedUserData.UserID : "";
}

const startMoment = moment(formData.StartTime, "HH:mm");
const endMoment = moment(formData.EndTime, "HH:mm");
const durationInHours = moment
.duration(endMoment.diff(startMoment))
.asHours();
const tableFee = Math.ceil(durationInHours) * baseTableFee;

const apiData = {
seat: chairId,
resdate: formData.Date
? moment(formData.Date).format("YYYY-MM-DD")
: null,
starttime: formData.StartTime,
endtime: formData.EndTime,
user_id: userID,
tablefee: tableFee,

};

console.log(apiData)
console.log(tableFee)

Expand All @@ -99,9 +173,24 @@ 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}`
// );
const responseData = await response.json();

//push the reservationid to the local storage

if(localStorage.getItem("reservation_id") === null){
localStorage.setItem("reservation_id", responseData.reservation_id)
}else{
localStorage.removeItem("reservation_id")
localStorage.setItem("reservation_id", responseData.reservation_id)
}
console.log(responseData.reservation_id)



const reservationID = responseData.reservation_id;
router.push(
`http://localhost:3000/qr_success_reservation`
);
} else {
console.error("Error Reservation", await response.json());
<BasicModalWait isOpen={true} onClose={onClose} chairID={chairId}/>
Expand All @@ -112,6 +201,7 @@ const BasicModal: React.FC<BasicModalProps> = ({
}
};


return (
<Modal
open={isOpen}
Expand Down Expand Up @@ -149,11 +239,18 @@ const BasicModal: React.FC<BasicModalProps> = ({

<Butt
onClick={handleCreateReservation}
title="Reserve"
title="Gcash"
Bgcolor="#EBE0D0"
width="325px"
height="34px"
/>
<Butt
onClick={handleCreateReservationCash}
title="Cash"
Bgcolor="#EBE0D0"
width="325px"
height="34px"
/>
</Box>
</Modal>
);
Expand Down
Empty file.
82 changes: 58 additions & 24 deletions frontend/app/qr_success_reservation/page.tsx
Original file line number Diff line number Diff line change
@@ -1,59 +1,93 @@
"use client";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import Teste from "../components/account";
import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos";
import Link from "next/link";

// ... other imports ...

import QR from "../components/QR";
import Butt from "../components/button";

import Info from "../components/qr_info";
import { useRouter } from "next/navigation";

function Page() {
const router = useRouter();

const [reservationData, setReservationData] = useState({
reservationId: "",
startTime: "",
endTime: "",
seat: "",
resDate: "",
tableFee: "",
userId: "",
});

const handleBackButtonClick = () => {
router.back();
};

useEffect(() => {
// Set the title directly for the browser tab
document.title = "Success Reservation";
}, []);
document.title = "Today's Reservation";

const reservationData = {
reservationId: "7",
name: "user_1",
Stime: "10:00 PM",
ETime: "11:30 PM",
tableNumber: "h2",
reservedTime: "10:00",
duration: "1 hour and 30 min",
paymentDetails: "GCash",
};
// Get reservation_id from localStorage
const resId = localStorage.getItem('reservation_id');

if (resId) {
// Fetch reservation details using the endpoint
fetch(`http://localhost:5000/api/get-reservation-by-id/${resId}`)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
if (data && data.reservation) {
const fetchedReservation = data.reservation;
setReservationData({
reservationId: fetchedReservation.ReservationID.toString(),
startTime: fetchedReservation.StartTime,
endTime: fetchedReservation.EndTime,
seat: fetchedReservation.Seat,
resDate: fetchedReservation.ResDate,
tableFee: fetchedReservation.TableFee,
userId: fetchedReservation.UserID.toString(),
});
} else {
console.log("Reservation not found");
}
})
.catch((error) => {
console.error("Error fetching reservation:", error);
});
}
}, []);

const qrCodeData = JSON.stringify(reservationData);
console.log(qrCodeData);

return (
<div className="flex min-h-full flex-col bg-backcolor">
<Teste
backButtonIcon={<ArrowBackIosIcon style={{ fontSize: 20 }} />}
onBackButtonClick={handleBackButtonClick}
title="Reserved Successfully"
title="Today's Reservation"
subTitle1="Simply scan the QR Code, and our friendly staff will be delighted to assist you with any inquiries or requests you may have during your time with us."
/>

<div className="text-center text-qr mt-7 mb-5">
<div className="text-center text-qr mt-7 mb-10">
<div className="flex justify-center items-center">
<QR data={qrCodeData} size={200} />
</div>
</div>

<Link href="/todays_reservation">
<Butt title="View Transaction" Bgcolor="#FFF1E4" />
</Link>
<Info title={`Seat: `} value={reservationData.seat} />
<Info title={`Start Time: `} value={reservationData.startTime} />
<Info title={`End Time: `} value={reservationData.endTime} />
<Info title={`Date: `} value={reservationData.resDate} />
<Info title={`Table Fee: `} value={reservationData.tableFee} />

<div className="mt-5"></div>

<Butt title="Cancel Reservation" Bgcolor="#FFF1E4" />
</div>
);
}
Expand Down
Loading
Loading