from sqlalchemy.orm import Session from schemas.vehicle import CreateVehicle, OutputVehicle, UpdateVehicle from db.models.vehicle import Vehicle from db.repository.user import verify_driver_exists def create_new_vehicle(vehicle: CreateVehicle, db: Session): vehicle_object = Vehicle( **vehicle.model_dump(), Fuel=0, AssignedDriverIds=[], CurrentLocation=[], MaintenanceNotes=[] ) db.add(vehicle_object) db.commit() db.refresh(vehicle_object) return vehicle def assign_vehicle_driver(vehicle_id: int, driver_id: int, db: Session): vehicledb = db.query(Vehicle).filter(Vehicle.Id == vehicle_id) vehicle = vehicledb.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" def list_vehicles(db: Session): vehicles = db.query(Vehicle).all() return vehicles def get_vehicle_by_id(vehicle_id: int, db: Session): vehicle = db.query(Vehicle).filter(Vehicle.Id == vehicle_id).first() return vehicle def replace_vehicle_data(id: int, vehicle: UpdateVehicle, db: Session): vehicle_db = db.query(Vehicle).filter(Vehicle.Id == id) 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.Year = vehicle.Year print(vehicle_object) db.add(vehicle_object) db.commit() return vehicle_object