Skip to content

Commit

Permalink
last stretch (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben-Sicat authored Dec 17, 2023
2 parents 8de188e + 2fd7d98 commit 6af47d8
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 23 deletions.
62 changes: 60 additions & 2 deletions backend/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import time

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}}, methods=["POST", "OPTIONS", "PUT"])
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}}, methods=["POST", "OPTIONS", "PUT", "GET", "DELETE"])

jwt = JWTManager(app)

Expand Down Expand Up @@ -240,7 +240,7 @@ def create_reservation(user_id, reservation_data):
cursor = connection.cursor()
query = """
INSERT INTO Reservations (UserID, StartTime, EndTime, Seat, TableFee, ResDate)
VALUES (%s, %s, %s, %s, %s)
VALUES (%s, %s, %s, %s, %s, %s)
"""
values = (
user_id,
Expand All @@ -260,6 +260,64 @@ def create_reservation(user_id, reservation_data):
connection.rollback()
return {'error': f"Error creating reservation: {err}"}

def create_waitlist_entry(user_id, username):
connection = get_db_connection(db_config)
if connection:
try:
cursor = connection.cursor()
query = """
INSERT INTO Waitlist (UserID, Username)
VALUES (%s, %s)
"""
values = (user_id, username)
cursor.execute(query, values)
connection.commit()
cursor.close()
connection.close()
return {'message': 'Waitlist entry created successfully'}
except mysql.connector.Error as err:
print(f"Error creating waitlist entry: {err}")
connection.rollback()
return {'error': f"Error creating waitlist entry: {err}"}

def get_all_waitlist_entries():
connection = get_db_connection(db_config)
if connection:
try:
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM Waitlist')
entries = cursor.fetchall()
cursor.close()
connection.close()
return entries
except mysql.connector.Error as err:
print(f"Error fetching waitlist entries: {err}")
return None

@app.route('/api/get-waitlist-entries', methods=['GET'])
def get_waitlist_entries_route():
try:
entries = get_all_waitlist_entries()
if entries:
return jsonify({'waitlist_entries': entries})
else:
return jsonify(error='No waitlist entries found'), 404
except Exception as e:
print(f"Error fetching waitlist entries: {e}")
return jsonify(error='Error fetching waitlist entries'), 500

@app.route('/api/create-waitlist-entry', methods=['POST'])
def create_waitlist_entry_route():
try:
data = request.get_json()
user_id = data.get('user_id') # Change this to fetch the user_id from your authentication mechanism
username = data.get('username')
create_waitlist_entry(user_id, username)
return jsonify({'message': 'Waitlist entry created successfully'}), 200
except Exception as e:
print(f"Error creating waitlist entry: {e}")
return jsonify(message='Error creating waitlist entry'), 500


@app.route('/api/create-reservation', methods=['POST'])
def create_reservation_route():
Expand Down
16 changes: 15 additions & 1 deletion backend/db/init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ CREATE TABLE QR_Codes (
FOREIGN KEY (ReservationID) REFERENCES Reservations(ReservationID)
);

CREATE TABLE Waitlist (
WaitlistID INT AUTO_INCREMENT PRIMARY KEY,
UserID INT,
Username VARCHAR(225) NOT NULL,
Seat VARCHAR(50)
);


INSERT INTO Waitlist(UserID, Username,Seat)
VALUES
(1, 'user_1' ,'chair1'),
(2, 'user_2','chair2'),
(3, 'user_3','chair3'),
(4, 'user_4','chair4');

INSERT INTO Users (GoogleID, Username, Email, Password, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School, Occupation, Level)
VALUES
Expand All @@ -53,6 +67,6 @@ 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');

6 changes: 3 additions & 3 deletions frontend/app/components/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ const BasicModal: React.FC<BasicModalProps> = ({ isOpen, onClose, chairId }) =>
};
console.log(apiData)
console.log(tableFee)
// 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}`
);

const response = await fetch(
"http://localhost:5000/api/create-reservation",
Expand Down
102 changes: 85 additions & 17 deletions frontend/app/components/modal_wait.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import Modal from "@mui/material/Modal";
import Butt from "./button";
import Link from "next/link";
import ModalExtend from "./modal_extend"; // Import your ModalExtend component
import ModalExtend from "./modal_extend";
import InfoTable from "./waitlist_table";

type UserInfo = {
Expand All @@ -13,6 +11,13 @@ type UserInfo = {
// Add more properties as needed
};

type WaitlistEntry = {
WaitlistID: number;
UserID: number;
Username: string;
Seat: string;
};

const style = {
position: "absolute" as "absolute",
top: "50%",
Expand All @@ -33,6 +38,40 @@ interface BasicModalProps {

function BasicModal({ isOpen, onClose }: BasicModalProps) {
const [showExtendModal, setShowExtendModal] = useState(false);
const [waitlistEntries, setWaitlistEntries] = useState<UserInfo[]>([]);

const fetchWaitlistEntries = async () => {
try {
const response = await fetch(`http://localhost:5000/api/get-all-waitlist-entries`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});

if (!response.ok) {
throw new Error(`Failed to fetch waitlist entries: ${response.statusText}`);
}

const data = await response.json();
// Map WaitlistEntry to UserInfo
const mappedEntries = data.waitlist_entries.map((entry: WaitlistEntry) => ({
id: entry.UserID,
name: entry.Username,
}));
setWaitlistEntries(mappedEntries);
} catch (error) {
console.error(error);
setWaitlistEntries([]); // Set an empty array in case of an error
}
};

useEffect(() => {
if (isOpen) {
// Fetch waitlist entries when the component mounts
fetchWaitlistEntries();
}
}, [isOpen]);

const handleOpen = () => {
setShowExtendModal(true);
Expand All @@ -42,20 +81,47 @@ function BasicModal({ isOpen, onClose }: BasicModalProps) {
setShowExtendModal(false);
onClose();
};

const handleEnterButtonClick = 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 : "";
}

let username = initialFormData ? initialFormData.Username : "";
if (username == undefined || username == null || username === "") {
username = parsedUserData ? parsedUserData.Username : "";
}


// Make a POST request to add the user to the waitlist
const response = await fetch(`http://localhost:5000/api/create-waitlist-entry`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user_id: userID,
username: username,
}),
});

const userData = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Smith" },
{ id: 101, name: "Gian Limbaga" },
{ id: 102, name: "The Fourth" },
{ id: 103, name: "Melaissa Rioveros" },
{ id: 104, name: "Chen Leonor" },
{ id: 105, name: "Eric Ramos" },
// Add more user data as needed
];
if (!response.ok) {
throw new Error(`Failed to add user to waitlist: ${response.statusText}`);
}

// Optionally, update the waitlist entries in the local state
// You may need to fetch the updated waitlist entries again
fetchWaitlistEntries();
} catch (error) {
console.error(error);
}
};

const [data, setData] = useState<UserInfo[]>(userData);
const [filteredData, setFilteredData] = useState<UserInfo[]>(data);

return (
<div>
Expand All @@ -72,7 +138,8 @@ function BasicModal({ isOpen, onClose }: BasicModalProps) {

<div className="container">
<div className="container bg-gray-200 rounded-lg mt-8 mb-3 text-xs">
<InfoTable data={filteredData} />
{/* Pass the modified waitlistEntries to InfoTable */}
<InfoTable data={waitlistEntries} />
</div>

<div className="flex justify-center space-x-5 text-xs">
Expand All @@ -89,6 +156,7 @@ function BasicModal({ isOpen, onClose }: BasicModalProps) {
width="160px"
height="30px"
borderRadius="10px"
onClick={handleEnterButtonClick}
/>
</div>
</div>
Expand Down

0 comments on commit 6af47d8

Please sign in to comment.