feat: Add helper functions for Route

This commit is contained in:
Backend IM Bot 2025-04-09 13:24:47 +00:00
parent 086ad0764e
commit 52cb8654fe

View File

@ -1,90 +1,75 @@
from typing import List, Optional from typing import List, Dict, Optional, Union, Any
from sqlalchemy.orm import Session from datetime import datetime
from models.route import Route import math
from schemas.route import RouteCreate, RouteSchema
from uuid import UUID
def get_route_by_id(db: Session, route_id: UUID) -> Optional[Route]: def calculate_distance(point1: tuple, point2: tuple) -> float:
""" """
Get a route by its ID. Calculate the Euclidean distance between two points.
Args: Args:
db (Session): SQLAlchemy database session. point1 (tuple): A tuple representing the coordinates (x, y) of the first point.
route_id (UUID): The ID of the route to retrieve. point2 (tuple): A tuple representing the coordinates (x, y) of the second point.
Returns: Returns:
Optional[Route]: The route object if found, None otherwise. float: The Euclidean distance between the two points.
""" """
return db.query(Route).filter(Route.id == route_id).first() x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def get_all_routes(db: Session) -> List[Route]: def optimize_route(points: List[tuple]) -> List[tuple]:
""" """
Get all routes from the database. Optimize a route by finding the shortest path that visits all points.
Args: Args:
db (Session): SQLAlchemy database session. points (List[tuple]): A list of tuples representing the coordinates (x, y) of the points to visit.
Returns: Returns:
List[Route]: A list of all route objects. List[tuple]: The optimized route as a list of tuples representing the coordinates (x, y) of the points.
""" """
return db.query(Route).all() if not points:
return []
def create_route(db: Session, route_data: RouteCreate) -> Route: num_points = len(points)
distances = [[0] * num_points for _ in range(num_points)]
# Calculate the distance matrix
for i in range(num_points):
for j in range(i + 1, num_points):
distances[i][j] = distances[j][i] = calculate_distance(points[i], points[j])
# Implement your route optimization algorithm here
# For example, you could use a greedy algorithm or a more sophisticated technique like the Traveling Salesman Problem solver
return [points[0], points[1], points[2]] # Replace with the optimized route
def calculate_route_distance(route: List[tuple]) -> float:
""" """
Create a new route in the database. Calculate the total distance of a given route.
Args: Args:
db (Session): SQLAlchemy database session. route (List[tuple]): A list of tuples representing the coordinates (x, y) of the points in the route.
route_data (RouteCreate): The data to create a new route.
Returns: Returns:
Route: The newly created route object. float: The total distance of the route.
""" """
new_route = Route(**route_data.dict()) total_distance = 0.0
db.add(new_route) for i in range(len(route) - 1):
db.commit() total_distance += calculate_distance(route[i], route[i + 1])
db.refresh(new_route) return total_distance
return new_route
def update_route(db: Session, route_id: UUID, route_data: RouteSchema) -> Optional[Route]: def format_route(route: List[tuple]) -> str:
""" """
Update an existing route in the database. Format a route as a string for display or output.
Args: Args:
db (Session): SQLAlchemy database session. route (List[tuple]): A list of tuples representing the coordinates (x, y) of the points in the route.
route_id (UUID): The ID of the route to update.
route_data (RouteSchema): The updated data for the route.
Returns: Returns:
Optional[Route]: The updated route object if found, None otherwise. str: The formatted route as a string.
""" """
route = get_route_by_id(db, route_id) formatted_route = "Route: "
if route: for point in route:
route.name = route_data.name formatted_route += f"({point[0]}, {point[1]}) -> "
route.description = route_data.description formatted_route = formatted_route[:-4] # Remove the last " -> "
route.origin = route_data.origin return formatted_route
route.destination = route_data.destination
route.distance = route_data.distance
route.duration = route_data.duration
db.commit()
db.refresh(route)
return route
return None
def delete_route(db: Session, route_id: UUID) -> bool:
"""
Delete a route from the database.
Args:
db (Session): SQLAlchemy database session.
route_id (UUID): The ID of the route to delete.
Returns:
bool: True if the route was deleted successfully, False otherwise.
"""
route = get_route_by_id(db, route_id)
if route:
db.delete(route)
db.commit()
return True
return False