Skip to content

Commit c793643

Browse files
committed
Merge branch 'ericnew' of https://github.com/Ben-Sicat/Study_hub into ericnew
2 parents 8e2236f + 4768fe5 commit c793643

File tree

16 files changed

+322
-183
lines changed

16 files changed

+322
-183
lines changed

backend/app/app.py

Lines changed: 150 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
from flask import Flask, jsonify, make_response, request
2-
from flask_jwt_extended import JWTManager, create_access_token
2+
from flask_jwt_extended import JWTManager, create_access_token, decode_token
33
import mysql.connector
44
from flask_cors import CORS
5+
from apscheduler.schedulers.background import BackgroundScheduler
6+
from datetime import datetime, timedelta
57

68
app = Flask(__name__)
7-
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
8-
app.config["JWT_SECRET_KEY"] = "your-secret-key" # Change this to a secure and secret key
9+
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
910
jwt = JWTManager(app)
1011

11-
# Database configuration
12+
# Database configurations
1213
db_config = {
1314
'user': 'root',
1415
'password': 'root',
@@ -17,37 +18,48 @@
1718
'database': 'BrewandBrain'
1819
}
1920

20-
def get_db_connection():
21+
warehouse_db_config = {
22+
'user': 'root',
23+
'password': 'root',
24+
'host': 'warehouse_db',
25+
'port': '3308',
26+
'database': 'BrewandBrain_warehouse'
27+
}
28+
29+
30+
def get_db_connection(config):
2131
try:
22-
connection = mysql.connector.connect(**db_config)
32+
connection = mysql.connector.connect(**config)
2333
return connection
2434
except mysql.connector.Error as err:
2535
print(f"Error connecting to the database: {err}")
2636
return None
2737

2838
# User-related functions
2939
def write_to_users(data):
30-
connection = get_db_connection()
40+
connection = get_db_connection(db_config)
3141
if connection:
3242
try:
3343
cursor = connection.cursor()
3444
query = """
3545
INSERT INTO Users
36-
(GoogleID, Username, Email, Password, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School)
46+
(GoogleID, Username, Email, Password, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, Occupation)
3747
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
3848
"""
49+
3950
values = (
40-
data['google_id'], data['username'], data['email'], data['password'],
41-
data['first_name'], data['last_name'], data['phone_number'], 'UName', '2003-03-05', 'Male', 'Sample School'
51+
1, data['username'], data['email'], data['password'],
52+
data['firstName'], data['lastName'], data['phoneNumber'], 'UName', data['birthdate'], data['gender'], data['occupation']
4253
)
4354
cursor.execute(query, values)
4455
connection.commit()
4556
cursor.close()
4657
connection.close()
4758
except mysql.connector.Error as err:
4859
print(f"Error writing to Users table: {err}")
60+
4961
def update_user_details(user_id, updated_data):
50-
connection= get_db_connection()
62+
connection = get_db_connection(db_config)
5163
if connection:
5264
try:
5365
cursor = connection.cursor()
@@ -66,8 +78,9 @@ def update_user_details(user_id, updated_data):
6678
connection.close()
6779
except mysql.connector.Error as err:
6880
print(f"Error updating user details: {err}")
81+
6982
def get_all_users():
70-
connection = get_db_connection()
83+
connection = get_db_connection(db_config)
7184
if connection:
7285
try:
7386
cursor = connection.cursor(dictionary=True)
@@ -78,13 +91,14 @@ def get_all_users():
7891
return results
7992
except mysql.connector.Error as err:
8093
print(f"Error: {err}")
94+
8195
def get_user_by_id(user_id):
82-
connection = get_db_connection()
96+
connection = get_db_connection(db_config)
8397
if connection:
8498
try:
8599
cursor = connection.cursor(dictionary=True)
86100
query = """
87-
SELECT UserID, GoogleID, Username, Email, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School
101+
SELECT UserID, GoogleID, Username, Email, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, Occupation
88102
FROM Users
89103
WHERE UserID = %s
90104
"""
@@ -96,14 +110,13 @@ def get_user_by_id(user_id):
96110
except mysql.connector.Error as err:
97111
print(f"Error fetching user by ID: {err}")
98112

99-
100113
def get_user_by_email_or_username(email_or_username):
101-
connection = get_db_connection()
114+
connection = get_db_connection(db_config)
102115
if connection:
103116
try:
104117
cursor = connection.cursor(dictionary=True)
105118
query = """
106-
SELECT UserID, GoogleID, Username, Password, Email, UName, Birthday, Gender, School
119+
SELECT UserID, GoogleID, Username, Password, Email, UName, Birthday, Gender, Occupation
107120
FROM Users
108121
WHERE Email = %s OR Username = %s
109122
"""
@@ -114,63 +127,69 @@ def get_user_by_email_or_username(email_or_username):
114127
return result
115128
except mysql.connector.Error as err:
116129
print(f"Error fetching user by email or username: {err}")
117-
def create_reservation(user_id, reservation_data):
118-
connection = get_db_connection()
119-
if connection:
120-
try:
121-
cursor = connection.cursor()
122-
query = """
123-
INSERT INTO Reservations
124-
(UserID, StartTime, EndTime, Seat)
125-
VALUES (%s, %s, %s, %s)
126-
"""
127-
values = (
128-
user_id,
129-
reservation_data['STime'],
130-
reservation_data['ETime'],
131-
reservation_data['Seat'],
132-
)
133-
cursor.execute(query, values)
134-
connection.commit()
135-
cursor.close()
136-
connection.close()
137-
except mysql.connector.Error as err:
138-
print(f"Error creating reservation: {err}")
139-
def get_user_reservations(user_id):
140-
connection = get_db_connection()
141-
if connection:
142-
try:
143-
cursor = connection.cursor(dictionary=True)
144-
query = """
145-
SELECT ReservationID, StartTime, EndTime, Seat
146-
FROM Reservations
147-
WHERE UserID = %s
148-
"""
149-
cursor.execute(query, (user_id,))
150-
results = cursor.fetchall()
151-
cursor.close()
152-
connection.close()
153-
return results
154-
except mysql.connector.Error as err:
155-
print(f"Error fetching user reservations: {err}")
156-
157-
@app.route('/api/sign-in', methods=['POST'])
158-
def sign_in():
159-
data = request.get_json()
160-
user = get_user_by_email_or_username(data['login'])
161-
162-
if user and user['Password'] == data['password']:
163-
access_token = create_access_token(identity=user['Username'])
164-
165-
# Create a response object
166-
response = make_response(jsonify(access_token=access_token), 200)
167-
168-
# Set HttpOnly flag for the access token cookie
169-
response.set_cookie('access_token', value=access_token, httponly=True)
170-
171-
return response
172-
else:
173-
return jsonify({"message": "Invalid login credentials"}), 401
130+
131+
def perform_warehouse_process():
132+
try:
133+
# Connect to operational database
134+
operational_connection = get_db_connection(db_config)
135+
if operational_connection:
136+
operational_cursor = operational_connection.cursor(dictionary=True)
137+
138+
# Connect to warehouse database
139+
warehouse_connection = get_db_connection(warehouse_db_config)
140+
if warehouse_connection:
141+
warehouse_cursor = warehouse_connection.cursor()
142+
143+
try:
144+
# Extract data from the operational database
145+
operational_cursor.execute("""
146+
SELECT UserID, School, Occupation
147+
FROM Users
148+
""")
149+
users_data = operational_cursor.fetchall()
150+
151+
# Transform and load data into the warehouse
152+
for user in users_data:
153+
# Fetch reservations for the current user
154+
operational_cursor.execute("""
155+
SELECT StartTime, EndTime
156+
FROM Reservations
157+
WHERE UserID = %s
158+
""", (user['UserID'],))
159+
reservations_data = operational_cursor.fetchall()
160+
161+
# Insert user and reservation data into the warehouse
162+
for reservation in reservations_data:
163+
warehouse_cursor.execute(
164+
"""
165+
INSERT INTO UserSummary (UserID, School, Occupation, StartTime, EndTime)
166+
VALUES (%s, %s, %s, %s, %s)
167+
""",
168+
(user['UserID'], user['School'], user['Occupation'],
169+
reservation['StartTime'], reservation['EndTime'])
170+
)
171+
172+
# Commit changes to the warehouse database
173+
warehouse_connection.commit()
174+
print("Warehouse process completed successfully.")
175+
except Exception as e:
176+
print(f"Error during ETL process: {e}")
177+
warehouse_connection.rollback() # Rollback changes in case of an error
178+
179+
warehouse_cursor.close()
180+
warehouse_connection.close()
181+
182+
operational_cursor.close()
183+
operational_connection.close()
184+
185+
except Exception as e:
186+
print(f"Error performing warehouse process: {e}")
187+
188+
# Initialize the BackgroundScheduler
189+
scheduler = BackgroundScheduler()
190+
191+
# Add the scheduled job to run the ETL process every 168 hours or 1 week
192+
scheduler.add_job(perform_warehouse_process, 'interval', hours=168)
174193

175194
@app.route('/api/create-account', methods=['POST'])
176195
def create_account():
@@ -183,7 +202,43 @@ def create_account():
183202
print(f"Error creating account: {e}")
184203
return jsonify(message='Error creating account'), 500
185204

186-
@app.route('/api/update-account/<int:user_id>', methods=['PUT'])
205+
206+
@app.route('/api/sign-in', methods=['POST'])
207+
def sign_in():
208+
data = request.get_json()
209+
user = get_user_by_email_or_username(data['login'])
210+
211+
if user and user['Password'] == data['password']:
212+
213+
# token = create_access_token(identity=user['Username'])
214+
215+
# # Access the access_token directly from create_access_token
216+
# access_token = decode_token(token)['identity']
217+
# print(access_token)
218+
219+
# Fetch additional user data
220+
user_data = get_user_by_id(user['UserID'])
221+
222+
# Create a response object
223+
response_data = {
224+
'user_data': {
225+
'UserID': user_data['UserID'],
226+
'Username': user_data['Username'],
227+
'Email': user_data['Email'],
228+
'PhoneNumber': user_data['PhoneNumber'],
229+
'Gender': user_data['Gender'],
230+
'Occupation': user_data['Occupation'],
231+
232+
# Add other user data fields as needed
233+
}
234+
}
235+
236+
response = make_response(jsonify(response_data), 200)
237+
238+
return response
239+
else:
240+
return jsonify({"message": "Invalid login credentials"}), 401
241+
@app.route('/api/update-account/', methods=['PUT'])
187242
def update_account(user_id):
188243
try:
189244
updated_data = request.get_json()
@@ -194,16 +249,25 @@ def update_account(user_id):
194249
print(f"Error updating account: {e}")
195250
return jsonify(message='Error updating account'), 500
196251

197-
@app.route('/api/reservations', methods=['POST'])
198-
def make_reservation():
199-
try:
200-
data = request.get_json()
201-
user_id = 1 # Replace with the actual user ID; you need to identify the user somehow
202-
result = create_reservation(user_id, data)
203-
return jsonify(result)
204-
except Exception as e:
205-
print(f"Error creating reservation: {e}")
206-
return jsonify(error='Error creating reservation'), 500
252+
# @app.route('/api/get-reservations/<int:user_id>', methods=['GET'])
253+
# def get_reservations(user_id):
254+
# try:
255+
# reservations = get_user_reservations(user_id)
256+
# return jsonify(reservations)
257+
# except Exception as e:
258+
# print(f"Error fetching reservations: {e}")
259+
# return jsonify(error='Error fetching reservations'), 500
260+
261+
# @app.route('/api/reservations', methods=['POST'])
262+
# def make_reservation():
263+
# try:
264+
# data = request.get_json()
265+
# user_id = 5 # Replace with the actual user ID; you need to identify the user somehow
266+
# result = create_reservation(user_id, data)
267+
# return jsonify(result)
268+
# except Exception as e:
269+
# print(f"Error creating reservation: {e}")
270+
# return jsonify(error='Error creating reservation'), 500
207271

208272

209273
# Additional user-related functions
@@ -227,4 +291,5 @@ def index():
227291
return jsonify({'User Data': 'Sample user created'})
228292

229293
if __name__ == '__main__':
294+
scheduler.start()
230295
app.run(host='0.0.0.0', debug=True)

backend/app/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ mysql-connector-python
33
Flask-JWT-Extended
44
bcrypt
55
Flask-CORS
6+
APScheduler

backend/app/tempCodeRunnerFile.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1 @@
1-
@app.route('/test', methods=['GET'])
2-
# def test_route():
3-
# return jsonify(message='Test route works!')
4-
5-
# @app.route('/test-post', methods=['POST'])
6-
# def test_route():
7-
# return jsonify(message='Test route works!')
1+
sign

backend/db/init.sql

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,19 @@ CREATE TABLE Users (
1212
LastName VARCHAR(100) NOT NULL,
1313
PhoneNumber VARCHAR(20),
1414
UName VARCHAR(225) NOT NULL,
15-
Birthday DATE,
15+
Birthday VARCHAR(225),
1616
Gender ENUM('Male', 'Female', 'Other'),
1717
School VARCHAR(225),
18+
Occupation VARCHAR(225),
1819
Level ENUM('User', 'Admin', 'Employee') DEFAULT 'User'
1920
);
2021

2122
CREATE TABLE Reservations (
2223
ReservationID INT AUTO_INCREMENT PRIMARY KEY,
2324
UserID INT,
24-
StartTime TIME NOT NULL,
25+
StartTime VARCHAR(255) NOT NULL,
2526
EndTime VARCHAR(225) NOT NULL,
26-
Seat VARCHAR(50),
27-
FOREIGN KEY (UserID) REFERENCES Users(UserID)
27+
Seat VARCHAR(50)
2828
);
2929

3030

@@ -35,5 +35,3 @@ CREATE TABLE QR_Codes (
3535
FOREIGN KEY (ReservationID) REFERENCES Reservations(ReservationID)
3636
);
3737

38-
INSERT INTO Users (GoogleID, Username, Email, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School)
39-
VALUES ('mel.id', 'mlss_riri', 'melaixrio@gmail.com', 'Melaissa', 'Rioveros', '1234567890', 'Melaissa Rioveros', '2003-03-05', 'Female', 'Adamson University');

backend/db/warehouse_init.sql

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
CREATE DATABASE BrewandBrain_warehouse;
2+
3+
USE BrewandBrain_warehouse;
4+
5+
CREATE TABLE IF NOT EXISTS UserSummary(
6+
UserID INT NOT NULL,
7+
School VARCHAR (100),
8+
Occupation VARCHAR(100),
9+
StartTime DATETIME,
10+
EndTime DATETIME,
11+
PRIMARY KEY (UserID)
12+
);
13+
14+
CREATE INDEX idx_UserSumamry_UserID ON UserSummary(UserID);

0 commit comments

Comments
 (0)