diff --git a/batchjob.py b/batchjob.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/booking_service/main.py b/booking_service/main.py index 1a1f0b1c9d86471d9c9d948f54dc6aedb6a38554..ce274e8e9e58e2c4fb8acdc1626adc7d51ac0fe7 100644 --- a/booking_service/main.py +++ b/booking_service/main.py @@ -8,6 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware # type: ignore import sqlite3 from pathlib import Path from typing import List +import mysql.connector app = FastAPI() @@ -20,10 +21,15 @@ app.add_middleware( allow_headers=["*"], ) -parent_directory = Path(__file__).resolve().parent.parent -db_file_path = parent_directory / "my_ride.db" -conn = sqlite3.connect(db_file_path, check_same_thread=False) -cursor = conn.cursor() +db_connection = mysql.connector.connect( + host='database-1.cz0ucmk42cu5.us-east-1.rds.amazonaws.com', # or '127.0.0.1' for IPv4 loopback + port='3306', # Specify the port number here + user='admin', + password='Test#321', + database='cycle_connect' +) +cursor = db_connection.cursor() + class Booking(BaseModel): user_id: int @@ -73,7 +79,7 @@ async def get_all_bookings(): @app.get("/bookings/{booking_id}", response_model=BookingResponse) async def get_booking(booking_id: int): # Execute the SQL query to fetch booking details by booking_id - cursor.execute("SELECT booking_id, user_id, bike_id, location, blocked_amount, payment_state, start_time, end_time, lock_code FROM Bookings WHERE booking_id = ?", (booking_id,)) + cursor.execute("SELECT booking_id, user_id, bike_id, location, blocked_amount, payment_state, start_time, end_time, lock_code FROM Bookings WHERE booking_id = %s", (booking_id,)) booking = cursor.fetchone() # If no booking is found, raise a 404 error @@ -98,7 +104,7 @@ async def book_bike(booking: Booking): # Check for existing active booking for the user_id or bike_id cursor.execute(""" SELECT 1 FROM Bookings - WHERE (user_id = ? OR bike_id = ?) AND payment_state = 'Booked' + WHERE (user_id = %s OR bike_id = %s) AND payment_state = 'Booked' """, (booking.user_id, booking.bike_id)) existing_booking = cursor.fetchone() @@ -106,20 +112,20 @@ async def book_bike(booking: Booking): raise HTTPException(status_code=400, detail="Already Booked") # Fetch user details - cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = ?", (booking.user_id,)) + cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = %s", (booking.user_id,)) user_details = cursor.fetchone() if not user_details: raise HTTPException(status_code=404, detail="User not found.") wallet_balance = user_details[0] # Fetch bike details and validate the location - cursor.execute("SELECT location, price_per_hour FROM Bikes WHERE bike_id = ?", (booking.bike_id,)) + cursor.execute("SELECT current_location, price_per_hour FROM Bikes WHERE bike_id = %s", (booking.bike_id,)) bike_details = cursor.fetchone() if not bike_details: raise HTTPException(status_code=404, detail="Bike not found.") db_location, price_per_hour = bike_details - if booking.location != db_location: + if booking.current_location != db_location: raise HTTPException(status_code=400, detail="Bike not available at the specified location.") # Calculate the amount to be blocked on the user's wallet @@ -137,16 +143,16 @@ async def book_bike(booking: Booking): start_time = datetime.now() # Update bike status and user's wallet balance - cursor.execute("UPDATE Bikes SET status = 'booked' WHERE bike_id = ?", (booking.bike_id,)) - cursor.execute("UPDATE Users SET wallet_balance = ? WHERE user_id = ?", (new_wallet_balance, booking.user_id)) + cursor.execute("UPDATE Bikes SET status = 'booked' WHERE bike_id = %s", (booking.bike_id,)) + cursor.execute("UPDATE Users SET wallet_balance = %s WHERE user_id = %s", (new_wallet_balance, booking.user_id)) # Insert a new booking record with lock code cursor.execute(""" INSERT INTO Bookings (user_id, bike_id, location, blocked_amount, payment_state, start_time, lock_code) - VALUES (?, ?, ?, ?, 'Booked', ?, ?) + VALUES (%s, %s, %s, %s, 'Booked', %s, %s) """, (booking.user_id, booking.bike_id, booking.location, blocked_amount, start_time, lock_code)) - conn.commit() + db_connection.commit() return { "user_id": booking.user_id, @@ -162,6 +168,16 @@ async def book_bike(booking: Booking): @app.put("/bookings/") async def update_booking(update: UpdateBooking): + # Establish a database connection + db_connection = mysql.connector.connect( + host='database-1.cz0ucmk42cu5.us-east-1.rds.amazonaws.com', + port='3306', + user='admin', + password='Test#321', + database='cycle_connect' + ) + cursor = db_connection.cursor() + # Check if the booking with provided booking_id, user_id, and bike_id exists cursor.execute(""" SELECT @@ -171,7 +187,7 @@ async def update_booking(update: UpdateBooking): JOIN Bikes Bi ON B.bike_id = Bi.bike_id JOIN Users U ON B.user_id = U.user_id WHERE - B.booking_id = ? AND B.user_id = ? AND B.bike_id = ? + B.booking_id = %s AND B.user_id = %s AND B.bike_id = %s """, (update.booking_id, update.user_id, update.bike_id)) booking = cursor.fetchone() @@ -181,9 +197,13 @@ async def update_booking(update: UpdateBooking): # Unpack fetched details start_time, blocked_amount, price_per_hour, current_wallet_balance = booking + # Handle start_time type appropriately + if not isinstance(start_time, datetime): + start_time = datetime.fromisoformat(start_time) + # Calculate total runtime in hours end_time = datetime.now() - total_runtime = (end_time - datetime.fromisoformat(start_time)).total_seconds() / 3600 + total_runtime = (end_time - start_time).total_seconds() / 3600 # Determine final price based on total runtime if total_runtime <= 5: @@ -195,10 +215,11 @@ async def update_booking(update: UpdateBooking): new_wallet_balance = current_wallet_balance + final_price # Update Booking and Users records - cursor.execute("UPDATE Bookings SET end_time = ?, payment_state = 'Ride Completed' WHERE booking_id = ?", (end_time, update.booking_id)) - cursor.execute("UPDATE Users SET wallet_balance = ? WHERE user_id = ?", (new_wallet_balance, update.user_id)) + cursor.execute("UPDATE Bookings SET end_time = %s, payment_state = 'Ride Completed' WHERE booking_id = %s", (end_time.strftime('%Y-%m-%d %H:%M:%S'), update.booking_id)) + cursor.execute("UPDATE Users SET wallet_balance = %s WHERE user_id = %s", (new_wallet_balance, update.user_id)) - conn.commit() + db_connection.commit() + db_connection.close() return { "message": "Booking updated and charges applied successfully", diff --git a/rentals_service/main.py b/rentals_service/main.py index ab91660a4c79e51228a55403925f0a04f085b960..b1c85945e5ef443c3472440c7b049d1dba61154c 100644 --- a/rentals_service/main.py +++ b/rentals_service/main.py @@ -20,21 +20,6 @@ app.add_middleware( allow_headers=["*"], ) -# # SQLite connection -# parent_directory = Path(__file__).resolve().parent.parent -# db_file_path = parent_directory / "my_ride.db" -# # print(db_file_path) -# conn = sqlite3.connect(db_file_path) -# cursor = conn.cursor() - -# db_connection = mysql.connector.connect( -# host='database_mysql', # or '127.0.0.1' for IPv4 loopback -# port='3306', # Specify the port number here -# user='root', -# password='root_password', -# database='your_database' -# ) - db_connection = mysql.connector.connect( host='database-1.cz0ucmk42cu5.us-east-1.rds.amazonaws.com', # or '127.0.0.1' for IPv4 loopback port='3306', # Specify the port number here @@ -45,30 +30,6 @@ db_connection = mysql.connector.connect( cursor = db_connection.cursor() -# # Create the Rentals table if it doesn't exist -# cursor.execute(''' -# CREATE TABLE IF NOT EXISTS Rentals ( -# rental_id INTEGER PRIMARY KEY, -# id INT, -# user_id INT, -# bike_id INT, -# year INT, -# hour INT, -# season INT, -# holiday BOOLEAN, -# workingday BOOLEAN, -# weather INT, -# temp DECIMAL(5, 2), -# atemp DECIMAL(5, 2), -# humidity DECIMAL(5, 2), -# windspeed DECIMAL(5, 2), -# count INT, -# FOREIGN KEY (user_id) REFERENCES Users(user_id), -# FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id) -# ) -# ''') -# conn.commit() - # Rental model class Rental(BaseModel): @@ -88,64 +49,6 @@ class Rental(BaseModel): count: int -# # Routes -# @app.post("/rentals/", response_model=Rental) -# async def create_rental(rental: Rental): -# cursor.execute(''' -# INSERT INTO Rentals -# (id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) -# VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) -# ''', ( -# rental.id, rental.user_id, rental.bike_id, rental.year, rental.hour, -# rental.season, rental.holiday, rental.workingday, rental.weather, -# rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count -# )) -# conn.commit() -# return rental - - -# @app.post("/rentals/", response_model=Rental) -# async def create_rental(rental: Rental): -# try: -# cursor.execute(''' -# INSERT INTO Rentals -# (id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) -# VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) -# ''', ( -# rental.id, rental.user_id, rental.bike_id, rental.year, rental.hour, -# rental.season, rental.holiday, rental.workingday, rental.weather, -# rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count -# )) -# conn.commit() -# return rental -# except Exception as e: -# # Log the exception -# print(f"Error creating rental: {e}") -# # Raise an HTTPException with status code 422 and error message -# raise HTTPException(status_code=422, detail=str(e)) - - -# @app.post("/rentals/", response_model=Rental) -# async def create_rental(rental: Rental): -# try: -# cursor.execute(''' -# INSERT INTO Rentals -# (id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) -# VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) -# ''', ( -# rental.id, rental.user_id, rental.bike_id, rental.year, rental.hour, -# rental.season, rental.holiday, rental.workingday, rental.weather, -# rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count -# )) -# conn.commit() -# return rental -# except Exception as e: -# # Log the exception -# print(f"Error creating rental: {e}") -# # Raise an HTTPException with status code 422 and error message -# raise HTTPException(status_code=422, detail=str(e)) - - @app.post("/rentals/", response_model=Rental) async def create_rental(rental: Rental): try: diff --git a/requirements.txt b/requirements.txt index f29908118997bfd82eb9cdfb82ea7e8593b23233..14602c3a19269be96ba1eb42b289e4f53dbd38df 100644 --- a/requirements.txt +++ b/requirements.txt @@ -33,3 +33,4 @@ uvloop==0.19.0 watchfiles==0.21.0 websockets==12.0 mysql-connector-python +apscheduler