From b9b15939b1563c175a4e537d94e6d27f36d7f02c Mon Sep 17 00:00:00 2001 From: Madiwka3 Date: Mon, 4 Sep 2023 16:37:41 +0600 Subject: [PATCH] Refactored database, added direct relationship between driver and vehicle --- app/alembic/env.py | 4 +- ...b5e82_edit_vehicle_table_fix_due_to_srs.py | 30 +++++++++ app/alembic/versions/95369c9d99cc_fix.py | 30 +++++++++ app/alembic/versions/a92339978636_fix.py | 62 +++++++++++++++++++ ...18245_edit_vehicle_table_fix_due_to_srs.py | 60 ++++++++++++++++++ .../f272ebbba83d_edit_driver_assignment.py | 61 ++++++++++++++++++ app/apis/v1/route_user.py | 14 +++-- app/apis/v1/route_vehicle.py | 44 ++++++++++--- app/db/base.py | 6 +- app/db/base_class.py | 14 +++++ app/db/models/user.py | 6 +- app/db/models/vehicle.py | 7 ++- app/db/repository/user.py | 7 +++ app/db/repository/vehicle.py | 54 +++++++++------- app/schemas/vehicle.py | 13 ++-- 15 files changed, 363 insertions(+), 49 deletions(-) create mode 100644 app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py create mode 100644 app/alembic/versions/95369c9d99cc_fix.py create mode 100644 app/alembic/versions/a92339978636_fix.py create mode 100644 app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py create mode 100644 app/alembic/versions/f272ebbba83d_edit_driver_assignment.py create mode 100644 app/db/base_class.py diff --git a/app/alembic/env.py b/app/alembic/env.py index 51a66db..fdaa581 100644 --- a/app/alembic/env.py +++ b/app/alembic/env.py @@ -26,7 +26,9 @@ if config.config_file_name is not None: # from myapp import mymodel # target_metadata = mymodel.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, # can be acquired: # my_important_option = config.get_main_option("my_important_option") diff --git a/app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py b/app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py new file mode 100644 index 0000000..919f81e --- /dev/null +++ b/app/alembic/versions/47f450cb5e82_edit_vehicle_table_fix_due_to_srs.py @@ -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 ### diff --git a/app/alembic/versions/95369c9d99cc_fix.py b/app/alembic/versions/95369c9d99cc_fix.py new file mode 100644 index 0000000..9bb8679 --- /dev/null +++ b/app/alembic/versions/95369c9d99cc_fix.py @@ -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 ### diff --git a/app/alembic/versions/a92339978636_fix.py b/app/alembic/versions/a92339978636_fix.py new file mode 100644 index 0000000..593fee8 --- /dev/null +++ b/app/alembic/versions/a92339978636_fix.py @@ -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 ### diff --git a/app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py b/app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py new file mode 100644 index 0000000..f9d70ff --- /dev/null +++ b/app/alembic/versions/aa72d2118245_edit_vehicle_table_fix_due_to_srs.py @@ -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 ### diff --git a/app/alembic/versions/f272ebbba83d_edit_driver_assignment.py b/app/alembic/versions/f272ebbba83d_edit_driver_assignment.py new file mode 100644 index 0000000..a29280c --- /dev/null +++ b/app/alembic/versions/f272ebbba83d_edit_driver_assignment.py @@ -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 ### diff --git a/app/apis/v1/route_user.py b/app/apis/v1/route_user.py index ea1a331..86b9cf1 100644 --- a/app/apis/v1/route_user.py +++ b/app/apis/v1/route_user.py @@ -14,9 +14,12 @@ router = APIRouter() @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) 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) -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...") return current_user diff --git a/app/apis/v1/route_vehicle.py b/app/apis/v1/route_vehicle.py index 8fb2a81..cf895ab 100644 --- a/app/apis/v1/route_vehicle.py +++ b/app/apis/v1/route_vehicle.py @@ -19,9 +19,15 @@ router = APIRouter() @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": - 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) return vehicle @@ -52,9 +58,16 @@ async def create_vehicle(vehicle: CreateVehicle, db: Session = Depends(get_db), response_model=OutputVehicle, 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": - 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) if vehicle == "nodriver": raise HTTPException( @@ -67,7 +80,7 @@ async def assign_driver(vehicle_id: int, driver_id: int, db: Session = Depends(g if vehicle == "alreadyassigned": raise HTTPException( 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 @@ -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 ) 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": - 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) if vehicleRes == "vehicleNotFound": raise HTTPException(status_code=404, detail="Vehicle not found") elif vehicleRes == "badreq": raise HTTPException(status_code=502, detail="Bad request") + elif vehicleRes == "driverNotFound": + raise HTTPException(status_code=404, detail="Driver not found") return vehicleRes @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": - 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) if result == "vehicleNotFound": raise HTTPException(status_code=404, detail="Vehicle not found") diff --git a/app/db/base.py b/app/db/base.py index e9b7650..2662b7f 100644 --- a/app/db/base.py +++ b/app/db/base.py @@ -1,4 +1,4 @@ # 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 diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..1e2aabe --- /dev/null +++ b/app/db/base_class.py @@ -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() diff --git a/app/db/models/user.py b/app/db/models/user.py index de4af6a..6f328fc 100644 --- a/app/db/models/user.py +++ b/app/db/models/user.py @@ -1,10 +1,10 @@ # 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 class User(Base): - __tablename__ = "users" Id = Column(Integer, primary_key=True, index=True) Name = Column(String, nullable=False) MiddleName = Column(String, nullable=True) @@ -14,4 +14,6 @@ class User(Base): Email = Column(String, nullable=False) Role = Column(String, nullable=False) DrivingLicenseNumber = Column(String, nullable=True) + AssignedVehicle = Column(Integer, ForeignKey("vehicle.Id"), nullable=True) + vehicle = relationship("Vehicle", back_populates="driver") HashedPassword = Column(String, nullable=False) diff --git a/app/db/models/vehicle.py b/app/db/models/vehicle.py index ddd386e..1c3adce 100644 --- a/app/db/models/vehicle.py +++ b/app/db/models/vehicle.py @@ -5,18 +5,19 @@ from sqlalchemy import ( String, ARRAY, ) +from sqlalchemy.orm import relationship from db.base import Base class Vehicle(Base): - __tablename__ = "vehicles" Id = Column(Integer, primary_key=True, index=True) Model = Column(String, nullable=False) Year = Column(Integer, nullable=False) LicensePlate = Column(String, nullable=False) - Type = Column(String, nullable=False) - AssignedDriverIds = Column(ARRAY(Integer), nullable=True) CurrentLocation = Column(ARRAY(String), nullable=True) Fuel = 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) + driver = relationship("User", back_populates="vehicle") diff --git a/app/db/repository/user.py b/app/db/repository/user.py index 754b664..6737f48 100644 --- a/app/db/repository/user.py +++ b/app/db/repository/user.py @@ -47,6 +47,13 @@ def verify_driver_exists(driver_id: int, db: Session): 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"): users = db.query(User).filter((User.Role == role) | (role == "Any")).all() return users diff --git a/app/db/repository/vehicle.py b/app/db/repository/vehicle.py index 0690482..fcd87ed 100644 --- a/app/db/repository/vehicle.py +++ b/app/db/repository/vehicle.py @@ -1,51 +1,59 @@ from sqlalchemy.orm import Session from schemas.vehicle import CreateVehicle, UpdateVehicle 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): vehicle_object = Vehicle( **vehicle.model_dump(), Fuel=0, - AssignedDriverIds=[], + Status="Inactive", CurrentLocation=[], MaintenanceNotes=[] ) db.add(vehicle_object) db.commit() db.refresh(vehicle_object) - return vehicle + return vehicle_object 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: 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): 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 def get_vehicle_by_id(vehicle_id: int, db: Session): 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 @@ -54,18 +62,22 @@ def replace_vehicle_data(id: int, vehicle: UpdateVehicle, db: Session): vehicle_object = vehicle_db.first() if not vehicle_object: return "vehiclenotfound" - vehicle_object.AssignedDriverIds = vehicle.AssignedDriverIds vehicle_object.CurrentLocation = vehicle.CurrentLocation vehicle_object.Fuel = vehicle.Fuel vehicle_object.LicensePlate = vehicle.LicensePlate vehicle_object.MaintenanceNotes = vehicle.MaintenanceNotes vehicle_object.Mileage = vehicle.Mileage 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 print(vehicle_object) db.add(vehicle_object) db.commit() + vehicle_object.AssignedDriver = vehicle.AssignedDriver return vehicle_object diff --git a/app/schemas/vehicle.py b/app/schemas/vehicle.py index 73bba43..f00ca3a 100644 --- a/app/schemas/vehicle.py +++ b/app/schemas/vehicle.py @@ -3,12 +3,11 @@ from pydantic import BaseModel class CreateVehicle(BaseModel): - Id: int Model: str Year: int LicensePlate: str - Type: str Mileage: int + Capacity: int class OutputVehicle(BaseModel): @@ -16,21 +15,23 @@ class OutputVehicle(BaseModel): Model: str Year: int LicensePlate: str - Type: str Mileage: int CurrentLocation: Optional[list[str]] = None Fuel: Optional[int] = 0 MaintenanceNotes: Optional[list[str]] = None - AssignedDriverIds: Optional[list[int]] = None + AssignedDriver: Optional[int] = None + Capacity: int + Status: str class UpdateVehicle(BaseModel): Model: str Year: int LicensePlate: str - Type: str + Capacity: int Mileage: int + Status: str CurrentLocation: Optional[list[str]] = None Fuel: Optional[int] = 0 MaintenanceNotes: Optional[list[str]] = None - AssignedDriverIds: Optional[list[int]] = None + AssignedDriver: Optional[int] = None