From 021cd805f41294e1f36d832fbdd4c190698e6834 Mon Sep 17 00:00:00 2001
From: pratyushkrsahu <ps01598@surrey.ac.uk>
Date: Mon, 6 May 2024 01:43:17 +0100
Subject: [PATCH] Fixed the duplication of user booking api and added rental
 scheduler

---
 microservices/batchjob.py                 |  75 ++++++++++++++++++++++
 microservices/booking_service/main.py     |   6 +-
 microservices/my_ride.db                  | Bin 65536 -> 65536 bytes
 microservices/rentals_service/batchjob.py |  40 ------------
 my_ride.db                                |   0
 5 files changed, 78 insertions(+), 43 deletions(-)
 create mode 100644 microservices/batchjob.py
 delete mode 100644 microservices/rentals_service/batchjob.py
 create mode 100644 my_ride.db

diff --git a/microservices/batchjob.py b/microservices/batchjob.py
new file mode 100644
index 0000000..370bc10
--- /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 24f4e35..0c02fd5 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
GIT binary patch
delta 411
zcmZo@U}<PznIO#=H&Mo!F>YhRl6+=ip8m<~1+rYcdAt@p|9DRD^lvUyNaU$E7ZzY(
zU}R)sWaQxBWCsF9RzCI@!b}d<6Mg<gb^UO#ur=FqJCe`ALF3oE=B+Os%zb}&ztHFu
zHxUAA<m6;x<b-Ktf5GJ7u&&*5P5Chg&7d;X@ZW|G!A$)r+VevkJmQW1ZvI$cWFZK%
zj+28CXj?ryBQq2G3sEK}2Ytq~$~$UrIhgDX5(=2O$RV&^e*2#ViVn^`Ru&eP{q`mT
zFbg?3Aua{#bFkj6!Env$vV%ka(&MKNEpYI>y)b!6!4e1Mq!~$btDPdu_@TNOIXOWV
zvNM8gV{uUDJjtj!@tm}SO8f@PVw0H;A-`vfv)Fh!=(EV{-ftAr)a0A|uU2dGrCK8<
zHDUgR4E!JY-|#=@f5d;6{|5hM{&V~%`H%4L=ikM@m45^OYW`*X3pXn?l=DlnFf%X;
Ug9srIAqXM_Km`BhUHxta08^cF#{d8T

delta 87
zcmV-d0I2_ffCPYm1dtm6U6C9^0bQ|Rq;CTb4W^R^a2>O8Ac747DGrnVeJZokeKG<d
t4iCBj5AhG|59bf!58V&g57Q6M56KV255Et(5Bv}Ivk|bC53{<DMsParA#nfz

diff --git a/microservices/rentals_service/batchjob.py b/microservices/rentals_service/batchjob.py
deleted file mode 100644
index 88b8fcc..0000000
--- 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 0000000..e69de29
-- 
GitLab