Skip to content
Snippets Groups Projects
Commit e33e6b07 authored by Sahu, Pratyush K (PG/T - Comp Sci & Elec Eng)'s avatar Sahu, Pratyush K (PG/T - Comp Sci & Elec Eng)
Browse files

Fixed the duplication issue in Booking Api and added batchjob.py for rental...

Fixed the duplication issue in Booking Api and added batchjob.py for rental service and status issue
parent f0509e7c
No related branches found
No related tags found
No related merge requests found
......@@ -89,6 +89,22 @@ async def read_bikes():
return bike_objects
@app.get("/bikes/available", response_model=List[BikeResponse])
async def read_available_bikes():
cursor.execute("SELECT * FROM Bikes WHERE status = 'available'")
bikes = cursor.fetchall()
bike_objects = [BikeResponse(
id=bike[0],
model=bike[1],
status=bike[2],
location=bike[3],
condition=bike[4],
price_per_hour=bike[5],
last_maintenance_date=bike[6],
maintenance_history=bike[7]
) for bike in bikes]
return bike_objects
@app.get("/bikes/{bike_id}", response_model=Bike)
async def read_bike(bike_id: int):
cursor.execute('SELECT * FROM Bikes WHERE bike_id = ?', (bike_id,))
......
......@@ -2,13 +2,11 @@ from datetime import datetime # Imports the datetime module
import random
from typing import Optional, List
import random
from wsgiref.validate import validator
from fastapi import FastAPI, HTTPException # type: ignore
from pydantic import BaseModel, root_validator # type: ignore
from pydantic import BaseModel # type: ignore
from fastapi.middleware.cors import CORSMiddleware # type: ignore
import sqlite3
from pathlib import Path
from fastapi.responses import JSONResponse # type: ignore
from typing import List
app = FastAPI()
......@@ -97,6 +95,16 @@ async def get_booking(booking_id: int):
@app.post("/bookings/")
async def book_bike(booking: Booking):
# Check for existing active booking
cursor.execute("""
SELECT 1 FROM Bookings
WHERE user_id = ? AND 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.")
# Fetch user details
cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = ?", (booking.user_id,))
user_details = cursor.fetchone()
......@@ -111,28 +119,32 @@ async def book_bike(booking: Booking):
raise HTTPException(status_code=404, detail="Bike not found.")
db_location, price_per_hour = bike_details
# Check if the provided location matches the bike's location
if booking.location != db_location:
raise HTTPException(status_code=400, detail="Bike not available at the specified location.")
# Calculate blocked amount
blocked_amount = price_per_hour * 5
# Calculate the amount to be blocked on the user's wallet
blocked_amount = price_per_hour * booking.duration_hours
# Validate wallet balance
if wallet_balance < blocked_amount:
raise HTTPException(status_code=400, detail="Insufficient wallet balance.")
# Calculate new wallet balance
new_wallet_balance = wallet_balance - blocked_amount
# Generate lock code and current time
lock_code = generate_lock_code()
start_time = datetime.now()
# Update bike status
# Update bike status and user's wallet balance
cursor.execute("UPDATE Bikes SET status = 'booked' WHERE bike_id = ?", (booking.bike_id,))
new_wallet_balance = wallet_balance - blocked_amount
cursor.execute("UPDATE Users SET wallet_balance = ? WHERE user_id = ?", (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', ?, ?)", (booking.user_id, booking.bike_id, booking.location, blocked_amount, start_time, lock_code))
cursor.execute("""
INSERT INTO Bookings (user_id, bike_id, location, blocked_amount, payment_state, start_time, lock_code)
VALUES (?, ?, ?, ?, 'Booked', ?, ?)
""", (booking.user_id, booking.bike_id, booking.location, blocked_amount, start_time, lock_code))
conn.commit()
......
No preview for this file type
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment