diff --git a/microservices/batchjob.py b/microservices/batchjob.py new file mode 100644 index 0000000000000000000000000000000000000000..370bc10110d9fb6592982a2c10aa63e17550d92c --- /dev/null +++ b/microservices/batchjob.py @@ -0,0 +1,75 @@ +import math +import random +import sqlite3 +from datetime import datetime +from pathlib import Path +from apscheduler.schedulers.background import BackgroundScheduler + +def insert_into_rentals(conn): + cursor = conn.cursor() + cursor.execute(""" + SELECT user_id, bike_id, start_time, end_time + FROM Bookings + WHERE end_time IS NOT NULL + """) + rows = cursor.fetchall() + + for row in rows: + user_id, bike_id, start_time, end_time = row + start_time = datetime.fromisoformat(start_time) + end_time = datetime.fromisoformat(end_time) + + year = start_time.year + hour = start_time.hour + season = random.randint(1, 4) + holiday = random.randint(0, 1) + workingday = random.randint(0, 1) + weather = random.randint(1, 4) + temp = random.uniform(10, 35) + atemp = random.uniform(10, 35) + humidity = random.uniform(20, 100) + windspeed = random.uniform(0, 50) + count = random.randint(0, 100) + + cursor.execute(""" + INSERT INTO rentals ( + user_id, bike_id, year, hour, + season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, ( + user_id, bike_id, year, hour, + season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count + )) + conn.commit() + +def scheduled_job(): + print("Running scheduled job...") + parent_directory = Path(__file__).resolve().parent.parent + db_file_path = parent_directory / "microservices" / "my_ride.db" + print(f"Using database at: {db_file_path}") # For debugging + + with sqlite3.connect(db_file_path, check_same_thread=False) as conn: + try: + insert_into_rentals(conn) + print("Data has been successfully inserted into rentals.") + except Exception as e: + print(f"An error occurred: {e}") + +def main(): + scheduler = BackgroundScheduler() + scheduler.add_job(scheduled_job, 'interval', hours=1) + scheduler.start() + + print("Press Ctrl+{0} to exit".format('Break' if os.name == 'nt' else 'C')) + + try: + # This is here to simulate application activity (which keeps the main thread alive). + while True: + pass + except (KeyboardInterrupt, SystemExit): + # Not strictly necessary if daemonic mode is enabled but should be done if possible + scheduler.shutdown() + +if __name__ == "__main__": + main() diff --git a/microservices/booking_service/main.py b/microservices/booking_service/main.py index 24f4e35b71acea8d9f0ef15752301a76454f4764..0c02fd5d3b9662d372179df956aee5c722dd3c54 100644 --- a/microservices/booking_service/main.py +++ b/microservices/booking_service/main.py @@ -95,15 +95,15 @@ async def get_booking(booking_id: int): @app.post("/bookings/") async def book_bike(booking: Booking): - # Check for existing active booking + # Check for existing active booking for the user_id or bike_id cursor.execute(""" SELECT 1 FROM Bookings - WHERE user_id = ? AND bike_id = ? AND payment_state = 'Booked' + WHERE (user_id = ? OR bike_id = ?) AND payment_state = 'Booked' """, (booking.user_id, booking.bike_id)) existing_booking = cursor.fetchone() if existing_booking: - raise HTTPException(status_code=400, detail="Already Booked: This bike is currently booked.") + raise HTTPException(status_code=400, detail="Already Booked") # Fetch user details cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = ?", (booking.user_id,)) diff --git a/microservices/my_ride.db b/microservices/my_ride.db index 78d5f5f0d3c0af09e1641ab29f9892d200f0ba20..20193ca32c083c3dba4bc768cd23085d2f4bc772 100644 Binary files a/microservices/my_ride.db and b/microservices/my_ride.db differ diff --git a/microservices/rentals_service/batchjob.py b/microservices/rentals_service/batchjob.py deleted file mode 100644 index 88b8fccc7428883cbeeaf13775a18a2817d0a2ef..0000000000000000000000000000000000000000 --- a/microservices/rentals_service/batchjob.py +++ /dev/null @@ -1,40 +0,0 @@ -from fastapi import FastAPI -from apscheduler.schedulers.background import BackgroundScheduler -import datetime -import sqlite3 -from pydantic import BaseModel -from typing import List -import sqlite3 -from datetime import datetime -import math - -def insert_into_rentals(): - conn = sqlite3.connect("my_ride.db") - cursor = conn.cursor() - - # Assume that this function is called right after a booking update where end_time is set - cursor.execute(""" - SELECT user_id, bike_id, start_time, end_time - FROM Bookings - WHERE end_time IS NOT NULL - """) - - rows = cursor.fetchall() - for row in rows: - user_id, bike_id, start_time, end_time = row - start_time = datetime.fromisoformat(start_time) - end_time = datetime.fromisoformat(end_time) - - duration_hours = math.ceil((end_time - start_time).total_seconds() / 3600) - duration_hours = max(1, duration_hours) # Ensure minimum of 1 hour - - year = start_time.year - hour = start_time.hour - - cursor.execute(""" - INSERT INTO rentals (user_id, bike_id, year, hour, duration_hours) - VALUES (?, ?, ?, ?, ?) - """, (user_id, bike_id, year, hour, duration_hours)) - - conn.commit() - conn.close() \ No newline at end of file diff --git a/my_ride.db b/my_ride.db new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391