Browse Source

Refactored database, added direct relationship between driver and vehicle

main
Madiwka3 1 year ago
parent
commit
b9b15939b1
15 changed files with 363 additions and 49 deletions
  1. +3
    -1
      app/alembic/env.py
  2. +30
    -0
      app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py
  3. +30
    -0
      app/alembic/versions/95369c9d99cc_fix.py
  4. +62
    -0
      app/alembic/versions/a92339978636_fix.py
  5. +60
    -0
      app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py
  6. +61
    -0
      app/alembic/versions/f272ebbba83d_edit_driver_assignment.py
  7. +10
    -4
      app/apis/v1/route_user.py
  8. +35
    -9
      app/apis/v1/route_vehicle.py
  9. +3
    -3
      app/db/base.py
  10. +14
    -0
      app/db/base_class.py
  11. +4
    -2
      app/db/models/user.py
  12. +4
    -3
      app/db/models/vehicle.py
  13. +7
    -0
      app/db/repository/user.py
  14. +33
    -21
      app/db/repository/vehicle.py
  15. +7
    -6
      app/schemas/vehicle.py

+ 3
- 1
app/alembic/env.py View File

@@ -26,7 +26,9 @@ if config.config_file_name is not None:
# from myapp import mymodel # from myapp import mymodel
# target_metadata = mymodel.Base.metadata # target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata target_metadata = Base.metadata

print("Alembic env.py target_metadata: ", target_metadata)
print("Alembic env.py settings: ", settings.DATABASE_URL)
print("Alembic env.py config: ", Base)
# other values from the config, defined by the needs of env.py, # other values from the config, defined by the needs of env.py,
# can be acquired: # can be acquired:
# my_important_option = config.get_main_option("my_important_option") # my_important_option = config.get_main_option("my_important_option")


+ 30
- 0
app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py View File

@@ -0,0 +1,30 @@
"""Edit vehicle table, fix due to SRS

Revision ID: 47f450cb5e82
Revises: aa72d2118245
Create Date: 2023-09-04 15:18:23.713730

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '47f450cb5e82'
down_revision: Union[str, None] = 'aa72d2118245'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

+ 30
- 0
app/alembic/versions/95369c9d99cc_fix.py View File

@@ -0,0 +1,30 @@
"""Fix

Revision ID: 95369c9d99cc
Revises: f272ebbba83d
Create Date: 2023-09-04 16:02:51.465863

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '95369c9d99cc'
down_revision: Union[str, None] = 'f272ebbba83d'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

+ 62
- 0
app/alembic/versions/a92339978636_fix.py View File

@@ -0,0 +1,62 @@
"""Fix

Revision ID: a92339978636
Revises: 95369c9d99cc
Create Date: 2023-09-04 16:03:42.207089

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'a92339978636'
down_revision: Union[str, None] = '95369c9d99cc'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('vehicle',
sa.Column('Id', sa.Integer(), nullable=False),
sa.Column('Model', sa.String(), nullable=False),
sa.Column('Year', sa.Integer(), nullable=False),
sa.Column('LicensePlate', sa.String(), nullable=False),
sa.Column('CurrentLocation', sa.ARRAY(sa.String()), nullable=True),
sa.Column('Fuel', sa.Integer(), nullable=False),
sa.Column('Mileage', sa.Integer(), nullable=False),
sa.Column('Status', sa.String(), nullable=False),
sa.Column('Capacity', sa.Integer(), nullable=False),
sa.Column('MaintenanceNotes', sa.ARRAY(sa.String()), nullable=True),
sa.PrimaryKeyConstraint('Id')
)
op.create_index(op.f('ix_vehicle_Id'), 'vehicle', ['Id'], unique=False)
op.create_table('user',
sa.Column('Id', sa.Integer(), nullable=False),
sa.Column('Name', sa.String(), nullable=False),
sa.Column('MiddleName', sa.String(), nullable=True),
sa.Column('LastName', sa.String(), nullable=False),
sa.Column('BirthDate', sa.DateTime(), nullable=False),
sa.Column('ContactNumber', sa.String(), nullable=False),
sa.Column('Email', sa.String(), nullable=False),
sa.Column('Role', sa.String(), nullable=False),
sa.Column('DrivingLicenseNumber', sa.String(), nullable=True),
sa.Column('AssignedVehicle', sa.Integer(), nullable=True),
sa.Column('HashedPassword', sa.String(), nullable=False),
sa.ForeignKeyConstraint(['AssignedVehicle'], ['vehicle.Id'], ),
sa.PrimaryKeyConstraint('Id')
)
op.create_index(op.f('ix_user_Id'), 'user', ['Id'], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_user_Id'), table_name='user')
op.drop_table('user')
op.drop_index(op.f('ix_vehicle_Id'), table_name='vehicle')
op.drop_table('vehicle')
# ### end Alembic commands ###

+ 60
- 0
app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py View File

@@ -0,0 +1,60 @@
"""Edit vehicle table, fix due to SRS

Revision ID: aa72d2118245
Revises: 9a0214838ac8
Create Date: 2023-09-04 15:16:55.278355

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = 'aa72d2118245'
down_revision: Union[str, None] = '9a0214838ac8'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_vehicles_Id', table_name='vehicles')
op.drop_table('vehicles')
op.drop_index('ix_users_Id', table_name='users')
op.drop_table('users')
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('Id', sa.INTEGER(), server_default=sa.text('nextval(\'"users_Id_seq"\'::regclass)'), autoincrement=True, nullable=False),
sa.Column('Name', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('MiddleName', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('LastName', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('BirthDate', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
sa.Column('ContactNumber', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Email', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Role', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('DrivingLicenseNumber', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('HashedPassword', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint('Id', name='users_pkey')
)
op.create_index('ix_users_Id', 'users', ['Id'], unique=False)
op.create_table('vehicles',
sa.Column('Id', sa.INTEGER(), server_default=sa.text('nextval(\'"vehicles_Id_seq"\'::regclass)'), autoincrement=True, nullable=False),
sa.Column('Model', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Year', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('LicensePlate', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Type', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('AssignedDriverIds', postgresql.ARRAY(sa.INTEGER()), autoincrement=False, nullable=True),
sa.Column('CurrentLocation', postgresql.ARRAY(sa.VARCHAR()), autoincrement=False, nullable=True),
sa.Column('Fuel', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('Mileage', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('MaintenanceNotes', postgresql.ARRAY(sa.VARCHAR()), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('Id', name='vehicles_pkey')
)
op.create_index('ix_vehicles_Id', 'vehicles', ['Id'], unique=False)
# ### end Alembic commands ###

+ 61
- 0
app/alembic/versions/f272ebbba83d_edit_driver_assignment.py View File

@@ -0,0 +1,61 @@
"""Edit driver assignment

Revision ID: f272ebbba83d
Revises: 47f450cb5e82
Create Date: 2023-09-04 15:36:52.916595

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = 'f272ebbba83d'
down_revision: Union[str, None] = '47f450cb5e82'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_vehicles_Id', table_name='vehicles')
op.drop_table('vehicles')
op.drop_index('ix_users_Id', table_name='users')
op.drop_table('users')
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('Id', sa.INTEGER(), server_default=sa.text('nextval(\'"users_Id_seq"\'::regclass)'), autoincrement=True, nullable=False),
sa.Column('Name', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('MiddleName', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('LastName', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('BirthDate', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
sa.Column('ContactNumber', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Email', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Role', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('DrivingLicenseNumber', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('HashedPassword', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint('Id', name='users_pkey')
)
op.create_index('ix_users_Id', 'users', ['Id'], unique=False)
op.create_table('vehicles',
sa.Column('Id', sa.INTEGER(), server_default=sa.text('nextval(\'"vehicles_Id_seq"\'::regclass)'), autoincrement=True, nullable=False),
sa.Column('Model', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Year', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('LicensePlate', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('AssignedDriverIds', postgresql.ARRAY(sa.INTEGER()), autoincrement=False, nullable=True),
sa.Column('CurrentLocation', postgresql.ARRAY(sa.VARCHAR()), autoincrement=False, nullable=True),
sa.Column('Fuel', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('Mileage', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('Status', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('Capacity', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('MaintenanceNotes', postgresql.ARRAY(sa.VARCHAR()), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('Id', name='vehicles_pkey')
)
op.create_index('ix_vehicles_Id', 'vehicles', ['Id'], unique=False)
# ### end Alembic commands ###

+ 10
- 4
app/apis/v1/route_user.py View File

@@ -14,9 +14,12 @@ router = APIRouter()




@router.post("/", response_model=ShowUser, status_code=status.HTTP_201_CREATED) @router.post("/", response_model=ShowUser, status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
if current_user.Role != "Admin":
raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
def create_user(
user: UserCreate,
db: Session = Depends(get_db),
):
# if current_user.Role != "Admin":
# raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
user = create_new_user(user=user, db=db) user = create_new_user(user=user, db=db)
return user return user


@@ -31,7 +34,10 @@ def get_all_users(db: Session = Depends(get_db), role: str = None):




@router.get("/me", response_model=ShowUser, status_code=status.HTTP_200_OK) @router.get("/me", response_model=ShowUser, status_code=status.HTTP_200_OK)
def get_user_me(current_user: Annotated[User, Depends(get_current_user)], db: Annotated[Session, Depends(get_db)]):
def get_user_me(
current_user: Annotated[User, Depends(get_current_user)],
db: Annotated[Session, Depends(get_db)],
):
print("Getting current user...") print("Getting current user...")
return current_user return current_user




+ 35
- 9
app/apis/v1/route_vehicle.py View File

@@ -19,9 +19,15 @@ router = APIRouter()




@router.post("/", response_model=OutputVehicle, status_code=status.HTTP_201_CREATED) @router.post("/", response_model=OutputVehicle, status_code=status.HTTP_201_CREATED)
async def create_vehicle(vehicle: CreateVehicle, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
async def create_vehicle(
vehicle: CreateVehicle,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if current_user.Role != "Admin": if current_user.Role != "Admin":
raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
raise HTTPException(
status_code=403, detail="You are not authorized to perform this action"
)
vehicle = create_new_vehicle(vehicle=vehicle, db=db) vehicle = create_new_vehicle(vehicle=vehicle, db=db)
return vehicle return vehicle


@@ -52,9 +58,16 @@ async def create_vehicle(vehicle: CreateVehicle, db: Session = Depends(get_db),
response_model=OutputVehicle, response_model=OutputVehicle,
status_code=status.HTTP_200_OK, status_code=status.HTTP_200_OK,
) )
async def assign_driver(vehicle_id: int, driver_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
async def assign_driver(
vehicle_id: int,
driver_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if current_user.Role != "Admin": if current_user.Role != "Admin":
raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
raise HTTPException(
status_code=403, detail="You are not authorized to perform this action"
)
vehicle = assign_vehicle_driver(vehicle_id=vehicle_id, driver_id=driver_id, db=db) vehicle = assign_vehicle_driver(vehicle_id=vehicle_id, driver_id=driver_id, db=db)
if vehicle == "nodriver": if vehicle == "nodriver":
raise HTTPException( raise HTTPException(
@@ -67,7 +80,7 @@ async def assign_driver(vehicle_id: int, driver_id: int, db: Session = Depends(g
if vehicle == "alreadyassigned": if vehicle == "alreadyassigned":
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail=f"Driver with id {driver_id} is already assigned to vehicle with id {vehicle_id}",
detail=f"A driver is already assigned to vehicle with id {vehicle_id}",
) )
return vehicle return vehicle


@@ -92,22 +105,35 @@ async def get_vehicle(vehicle_id: int, db: Session = Depends(get_db)):
"/{vehicle_id}", response_model=OutputVehicle, status_code=status.HTTP_200_OK "/{vehicle_id}", response_model=OutputVehicle, status_code=status.HTTP_200_OK
) )
def update_vehicle( def update_vehicle(
vehicle_id: int, vehicle: UpdateVehicle, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
vehicle_id: int,
vehicle: UpdateVehicle,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
): ):
if current_user.Role != "Admin": if current_user.Role != "Admin":
raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
raise HTTPException(
status_code=403, detail="You are not authorized to perform this action"
)
vehicleRes = replace_vehicle_data(id=vehicle_id, vehicle=vehicle, db=db) vehicleRes = replace_vehicle_data(id=vehicle_id, vehicle=vehicle, db=db)
if vehicleRes == "vehicleNotFound": if vehicleRes == "vehicleNotFound":
raise HTTPException(status_code=404, detail="Vehicle not found") raise HTTPException(status_code=404, detail="Vehicle not found")
elif vehicleRes == "badreq": elif vehicleRes == "badreq":
raise HTTPException(status_code=502, detail="Bad request") raise HTTPException(status_code=502, detail="Bad request")
elif vehicleRes == "driverNotFound":
raise HTTPException(status_code=404, detail="Driver not found")
return vehicleRes return vehicleRes




@router.delete("/{vehicle_id}", status_code=status.HTTP_200_OK) @router.delete("/{vehicle_id}", status_code=status.HTTP_200_OK)
def delete_vehicle(vehicle_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def delete_vehicle(
vehicle_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if current_user.Role != "Admin": if current_user.Role != "Admin":
raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
raise HTTPException(
status_code=403, detail="You are not authorized to perform this action"
)
result = delete_vehicle_data(id=vehicle_id, db=db) result = delete_vehicle_data(id=vehicle_id, db=db)
if result == "vehicleNotFound": if result == "vehicleNotFound":
raise HTTPException(status_code=404, detail="Vehicle not found") raise HTTPException(status_code=404, detail="Vehicle not found")


+ 3
- 3
app/db/base.py View File

@@ -1,4 +1,4 @@
# Base class for all sqlalchemy models # Base class for all sqlalchemy models
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from db.base_class import Base
from db.models.user import User
from db.models.vehicle import Vehicle

+ 14
- 0
app/db/base_class.py View File

@@ -0,0 +1,14 @@
from typing import Any

from sqlalchemy.ext.declarative import as_declarative, declared_attr


@as_declarative()
class Base:
id: Any
__name__: str

# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

+ 4
- 2
app/db/models/user.py View File

@@ -1,10 +1,10 @@
# PostgreSQL table model for users # PostgreSQL table model for users
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from db.base import Base from db.base import Base




class User(Base): class User(Base):
__tablename__ = "users"
Id = Column(Integer, primary_key=True, index=True) Id = Column(Integer, primary_key=True, index=True)
Name = Column(String, nullable=False) Name = Column(String, nullable=False)
MiddleName = Column(String, nullable=True) MiddleName = Column(String, nullable=True)
@@ -14,4 +14,6 @@ class User(Base):
Email = Column(String, nullable=False) Email = Column(String, nullable=False)
Role = Column(String, nullable=False) Role = Column(String, nullable=False)
DrivingLicenseNumber = Column(String, nullable=True) DrivingLicenseNumber = Column(String, nullable=True)
AssignedVehicle = Column(Integer, ForeignKey("vehicle.Id"), nullable=True)
vehicle = relationship("Vehicle", back_populates="driver")
HashedPassword = Column(String, nullable=False) HashedPassword = Column(String, nullable=False)

+ 4
- 3
app/db/models/vehicle.py View File

@@ -5,18 +5,19 @@ from sqlalchemy import (
String, String,
ARRAY, ARRAY,
) )
from sqlalchemy.orm import relationship
from db.base import Base from db.base import Base




class Vehicle(Base): class Vehicle(Base):
__tablename__ = "vehicles"
Id = Column(Integer, primary_key=True, index=True) Id = Column(Integer, primary_key=True, index=True)
Model = Column(String, nullable=False) Model = Column(String, nullable=False)
Year = Column(Integer, nullable=False) Year = Column(Integer, nullable=False)
LicensePlate = Column(String, nullable=False) LicensePlate = Column(String, nullable=False)
Type = Column(String, nullable=False)
AssignedDriverIds = Column(ARRAY(Integer), nullable=True)
CurrentLocation = Column(ARRAY(String), nullable=True) CurrentLocation = Column(ARRAY(String), nullable=True)
Fuel = Column(Integer, nullable=False) Fuel = Column(Integer, nullable=False)
Mileage = Column(Integer, nullable=False) Mileage = Column(Integer, nullable=False)
Status = Column(String, nullable=False)
Capacity = Column(Integer, nullable=False)
MaintenanceNotes = Column(ARRAY(String), nullable=True) MaintenanceNotes = Column(ARRAY(String), nullable=True)
driver = relationship("User", back_populates="vehicle")

+ 7
- 0
app/db/repository/user.py View File

@@ -47,6 +47,13 @@ def verify_driver_exists(driver_id: int, db: Session):
return True return True




def get_car_driver(vehicle_id: int, db: Session):
driver = db.query(User).filter(User.AssignedVehicle == vehicle_id).first()
if not driver:
return False
return driver


def list_users(db: Session, role: str = "Any"): def list_users(db: Session, role: str = "Any"):
users = db.query(User).filter((User.Role == role) | (role == "Any")).all() users = db.query(User).filter((User.Role == role) | (role == "Any")).all()
return users return users

+ 33
- 21
app/db/repository/vehicle.py View File

@@ -1,51 +1,59 @@
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from schemas.vehicle import CreateVehicle, UpdateVehicle from schemas.vehicle import CreateVehicle, UpdateVehicle
from db.models.vehicle import Vehicle from db.models.vehicle import Vehicle
from db.repository.user import verify_driver_exists
from db.base import User
from db.repository.user import get_car_driver




def create_new_vehicle(vehicle: CreateVehicle, db: Session): def create_new_vehicle(vehicle: CreateVehicle, db: Session):
vehicle_object = Vehicle( vehicle_object = Vehicle(
**vehicle.model_dump(), **vehicle.model_dump(),
Fuel=0, Fuel=0,
AssignedDriverIds=[],
Status="Inactive",
CurrentLocation=[], CurrentLocation=[],
MaintenanceNotes=[] MaintenanceNotes=[]
) )
db.add(vehicle_object) db.add(vehicle_object)
db.commit() db.commit()
db.refresh(vehicle_object) db.refresh(vehicle_object)
return vehicle
return vehicle_object




def assign_vehicle_driver(vehicle_id: int, driver_id: int, db: Session): def assign_vehicle_driver(vehicle_id: int, driver_id: int, db: Session):
vehicledb = db.query(Vehicle).filter(Vehicle.Id == vehicle_id)
vehicle = vehicledb.first()
driver = (
db.query(User).filter((User.Id == driver_id) & (User.Role == "Driver")).first()
)
print(driver)
vehicle = db.query(Vehicle).filter(Vehicle.Id == vehicle_id).first()
if not vehicle: if not vehicle:
return "novehicle" return "novehicle"
if driver_id in vehicle.AssignedDriverIds:
return "alreadyassigned"
if verify_driver_exists(driver_id=driver_id, db=db):
print(vehicle.AssignedDriverIds)
vehicledb.update(
{"AssignedDriverIds": vehicle.AssignedDriverIds + [driver_id]}
)
print(vehicle.AssignedDriverIds)
db.add(vehicle)
db.commit()
db.refresh(vehicle)
return vehicle
# return a 404 error if the driver does not exist
return "nodriver"
if not driver:
return "nodriver"
driver.AssignedVehicle = vehicle_id
db.add(driver)
db.commit()
return vehicle




def list_vehicles(db: Session): def list_vehicles(db: Session):
vehicles = db.query(Vehicle).all() vehicles = db.query(Vehicle).all()
# assign AssignedDriver to all vehicles based on their drivers
for vehicle in vehicles:
driver = get_car_driver(vehicle.Id, db)
if driver:
vehicle.AssignedDriver = driver.Id
else:
vehicle.AssignedDriver = None
return vehicles return vehicles




def get_vehicle_by_id(vehicle_id: int, db: Session): def get_vehicle_by_id(vehicle_id: int, db: Session):
vehicle = db.query(Vehicle).filter(Vehicle.Id == vehicle_id).first() vehicle = db.query(Vehicle).filter(Vehicle.Id == vehicle_id).first()
driver = get_car_driver(vehicle.Id, db)
if driver:
vehicle.AssignedDriver = driver.Id
else:
vehicle.AssignedDriver = None
return vehicle return vehicle




@@ -54,18 +62,22 @@ def replace_vehicle_data(id: int, vehicle: UpdateVehicle, db: Session):
vehicle_object = vehicle_db.first() vehicle_object = vehicle_db.first()
if not vehicle_object: if not vehicle_object:
return "vehiclenotfound" return "vehiclenotfound"
vehicle_object.AssignedDriverIds = vehicle.AssignedDriverIds
vehicle_object.CurrentLocation = vehicle.CurrentLocation vehicle_object.CurrentLocation = vehicle.CurrentLocation
vehicle_object.Fuel = vehicle.Fuel vehicle_object.Fuel = vehicle.Fuel
vehicle_object.LicensePlate = vehicle.LicensePlate vehicle_object.LicensePlate = vehicle.LicensePlate
vehicle_object.MaintenanceNotes = vehicle.MaintenanceNotes vehicle_object.MaintenanceNotes = vehicle.MaintenanceNotes
vehicle_object.Mileage = vehicle.Mileage vehicle_object.Mileage = vehicle.Mileage
vehicle_object.Model = vehicle.Model vehicle_object.Model = vehicle.Model
vehicle_object.Type = vehicle.Type
vehicle_object.Status = vehicle.Status
res = assign_vehicle_driver(id, vehicle.AssignedDriver, db)
if res == "nodriver":
return "driverNotFound"
vehicle_object.Capacity = vehicle.Capacity
vehicle_object.Year = vehicle.Year vehicle_object.Year = vehicle.Year
print(vehicle_object) print(vehicle_object)
db.add(vehicle_object) db.add(vehicle_object)
db.commit() db.commit()
vehicle_object.AssignedDriver = vehicle.AssignedDriver
return vehicle_object return vehicle_object






+ 7
- 6
app/schemas/vehicle.py View File

@@ -3,12 +3,11 @@ from pydantic import BaseModel




class CreateVehicle(BaseModel): class CreateVehicle(BaseModel):
Id: int
Model: str Model: str
Year: int Year: int
LicensePlate: str LicensePlate: str
Type: str
Mileage: int Mileage: int
Capacity: int




class OutputVehicle(BaseModel): class OutputVehicle(BaseModel):
@@ -16,21 +15,23 @@ class OutputVehicle(BaseModel):
Model: str Model: str
Year: int Year: int
LicensePlate: str LicensePlate: str
Type: str
Mileage: int Mileage: int
CurrentLocation: Optional[list[str]] = None CurrentLocation: Optional[list[str]] = None
Fuel: Optional[int] = 0 Fuel: Optional[int] = 0
MaintenanceNotes: Optional[list[str]] = None MaintenanceNotes: Optional[list[str]] = None
AssignedDriverIds: Optional[list[int]] = None
AssignedDriver: Optional[int] = None
Capacity: int
Status: str




class UpdateVehicle(BaseModel): class UpdateVehicle(BaseModel):
Model: str Model: str
Year: int Year: int
LicensePlate: str LicensePlate: str
Type: str
Capacity: int
Mileage: int Mileage: int
Status: str
CurrentLocation: Optional[list[str]] = None CurrentLocation: Optional[list[str]] = None
Fuel: Optional[int] = 0 Fuel: Optional[int] = 0
MaintenanceNotes: Optional[list[str]] = None MaintenanceNotes: Optional[list[str]] = None
AssignedDriverIds: Optional[list[int]] = None
AssignedDriver: Optional[int] = None

Loading…
Cancel
Save