diff --git a/bikes_service/main.py b/bikes_service/main.py index 8887c9d3a6f4ef56f52eb3ffaea8a425dcda6743..b229410882a8921628acf69c411ff59fcc7c35cd 100644 --- a/bikes_service/main.py +++ b/bikes_service/main.py @@ -140,11 +140,14 @@ async def read_available_bikes(): @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,)) + cursor.execute('SELECT * FROM Bikes WHERE bike_id = %s', (bike_id,)) bike = cursor.fetchone() if bike is None: raise HTTPException(status_code=404, detail="Bike not found") + # Format the last_maintenance_date from datetime.date to string + last_maintenance_date_formatted = bike[6].strftime('%Y-%m-%d') if bike[6] else None + # Create a Bike object from the fetched data bike_obj = Bike( model=bike[1], @@ -152,7 +155,7 @@ async def read_bike(bike_id: int): current_location=bike[3], bike_condition=bike[4], price_per_hour=bike[5], - last_maintenance_date=bike[6], + last_maintenance_date=last_maintenance_date_formatted, maintenance_history=bike[7] ) diff --git a/rentals_service/main.py b/rentals_service/main.py index f4224ced693614770e1239396de0792304e71ce6..b17c8c5ae78f46bd2e659e03588eb564bb13f25b 100644 --- a/rentals_service/main.py +++ b/rentals_service/main.py @@ -7,6 +7,7 @@ from pathlib import Path from typing import Optional from fastapi import HTTPException import mysql.connector +from decimal import Decimal app = FastAPI() @@ -214,11 +215,29 @@ async def read_rentals(): @app.get("/rentals/{rental_id}", response_model=Rental) async def read_rental(rental_id: int): - cursor.execute('SELECT * FROM Rentals WHERE rental_id = ?', (rental_id,)) + cursor.execute('SELECT * FROM Rentals WHERE rental_id = %s', (rental_id,)) rental = cursor.fetchone() if rental is None: raise HTTPException(status_code=404, detail="Rental not found") - return rental + + # Convert the tuple to a dictionary + rental_dict = { + 'user_id': rental[1], + 'bike_id': rental[2], + 'year': rental[3], + 'hour': rental[4], + 'season': rental[5], + 'holiday': bool(rental[6]), + 'workingday': bool(rental[7]), + 'weather': rental[8], + 'temp': float(rental[9]), + 'atemp': float(rental[10]), + 'humidity': float(rental[11]), + 'windspeed': float(rental[12]), + 'count': rental[13] + } + + return Rental(**rental_dict) @app.put("/rentals/{rental_id}", response_model=Rental) diff --git a/rentals_service/testcode.py b/rentals_service/testcode.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7779717fcd3ddff007459a650bc94337e99d0e --- /dev/null +++ b/rentals_service/testcode.py @@ -0,0 +1,210 @@ +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from fastapi.middleware.cors import CORSMiddleware # type: ignore +from typing import List +import sqlite3 +from pathlib import Path +from typing import Optional +from fastapi import HTTPException # type: ignore +import mysql.connector + +app = FastAPI() + +# Allow requests from all origins +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["GET", "POST", "PUT", "DELETE"], + 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() + +# 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): + user_id: Optional[int] = None + bike_id: int + year: int + hour: int + season: int + holiday: bool + workingday: bool + weather: int + temp: float + atemp: float + humidity: float + windspeed: float + count: float + + +class PostRental(BaseModel): + id:Optional[int] = None + user_id: Optional[int] = None + bike_id: int + year: int + hour: int + season: int + holiday: bool + workingday: bool + weather: int + temp: float + atemp: float + humidity: float + windspeed: float + count: float + + +@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() + # Get the auto-generated id of the new rental + rental_id = cursor.lastrowid + # Return the created rental with the generated id + rental.id = rental_id + return rental + except Exception as e: + print(f"Error creating rental: {e}") + raise HTTPException(status_code=422, detail=str(e)) + + + +@app.get("/rentals/", response_model=List[Rental]) +async def read_rentals(): + cursor.execute('SELECT * FROM Rentals') + rentals = cursor.fetchall() + rental_objects = [] + # for rental in rentals: + # rental_objects.append(Rental( + # id=rental[0], + # user_id=rental[1], + # bike_id=rental[2], + # year=rental[3], + # hour=rental[4], + # season=rental[5], + # holiday=bool(rental[6]), + # workingday=bool(rental[7]), + # weather=rental[8], + # temp=float(rental[9]), + # atemp=float(rental[10]), + # humidity=float(rental[11]), + # windspeed=float(rental[12]), + # count=int(rental[13]) # Convert to integer + # )) + for rental in rentals: + rental_objects.append(Rental( + user_id=rental[1], + bike_id=rental[2], + year=rental[3], + hour=rental[4], + season=rental[5], + holiday=bool(rental[6]), + workingday=bool(rental[7]), + weather=rental[8], + temp=float(rental[9]), + atemp=float(rental[10]), + humidity=float(rental[11]), + windspeed=float(rental[12]), + count=rental[13] + )) + + return rental_objects + + +@app.get("/rentals/{rental_id}", response_model=Rental) +async def read_rental(rental_id: int): + cursor.execute('SELECT * FROM Rentals WHERE rental_id = ?', (rental_id,)) + rental_data = cursor.fetchone() + if rental_data is None: + raise HTTPException(status_code=404, detail="Rental not found") + + # Construct a Rental instance from the tuple data + rental = Rental( + id=rental_data[0], # Assuming the rental_id is the first column in your table + user_id=rental_data[1], + bike_id=rental_data[2], + year=rental_data[3], + hour=rental_data[4], + season=rental_data[5], + holiday=bool(rental_data[6]), + workingday=bool(rental_data[7]), + weather=rental_data[8], + temp=float(rental_data[9]), + atemp=float(rental_data[10]), + humidity=float(rental_data[11]), + windspeed=float(rental_data[12]), + count=int(rental_data[13]) # Assuming count should be converted to int + ) + + return rental + + +@app.put("/rentals/{rental_id}", response_model=Rental) +async def update_rental(rental_id: int, rental: Rental): + try: + cursor.execute(''' + UPDATE Rentals + SET user_id = ?, bike_id = ?, year = ?, hour = ?, season = ?, + holiday = ?, workingday = ?, weather = ?, temp = ?, atemp = ?, + humidity = ?, windspeed = ?, count = ? + WHERE 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, rental_id + )) + conn.commit() + return rental + except sqlite3.OperationalError as e: + print("SQL error:", e) + raise HTTPException(status_code=400, detail=str(e)) + + +@app.delete("/rentals/{rental_id}") +async def delete_rental(rental_id: int): + cursor.execute('DELETE FROM Rentals WHERE rental_id = ?', (rental_id,)) + conn.commit() + return {"message": "Rental deleted successfully"} diff --git a/users_service/main.py b/users_service/main.py index ed5fc1f36028543ab8e17a6981189b431eff68a0..d4a7d25af203e2fc6144ba05b0699a2cc75a49ab 100644 --- a/users_service/main.py +++ b/users_service/main.py @@ -168,10 +168,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel): for field, value in update_data.dict(exclude_none=True).items(): if value is not None: updates.append(f"{field} = %s") - if field in ["registration_date", "last_login"]: - params.append(value.strftime('%Y-%m-%d %H:%M:%S')) - else: - params.append(value) + params.append(value) if not updates: raise HTTPException(status_code=400, detail="No valid fields provided for update") @@ -199,6 +196,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel): raise HTTPException(status_code=404, detail="Error updating user.") + @app.delete("/users/{user_id}") async def delete_user(user_id: int): cursor.execute('DELETE FROM Users WHERE user_id = %s', (user_id,))