Files
score/backend/app/models/route.py
2025-11-01 01:03:34 +01:00

284 lines
8.3 KiB
Python

from datetime import timedelta
from typing import TYPE_CHECKING
from sqlalchemy import Interval
from sqlmodel import (
Session,
Relationship,
Field,
)
from . import mixin
from .base import (
BaseSQLModel,
DocumentedStrEnum,
DocumentedStrFlagType,
auto_enum,
RowId,
)
from .hike import (
Hike,
HikeTimeCalculation,
HikeTeamLink,
)
if TYPE_CHECKING:
from .place import Place
# region # Route ###############################################################
class RouteType(DocumentedStrEnum):
START_FINISH = auto_enum() # Start at the start and end at the finish
CIRCULAR = auto_enum() # Start some ware, finish at the last new place
CIRCULAR_BACK_TO_START = auto_enum() # Start and finish on the same random place (CIRCULAR + next to start)
# ##############################################################################
class RouteBase(
mixin.Name,
mixin.Contact,
BaseSQLModel,
):
route_type: RouteType = Field(
default=RouteType.START_FINISH,
nullable=False,
)
time_calculation_override: HikeTimeCalculation | None = Field(
default=None,
nullable=True,
description="Should this route be calculated different then the main hike",
sa_type=DocumentedStrFlagType(HikeTimeCalculation),
)
min_time: timedelta | None = Field(
default=None,
description="Min time correction, None = min of all, positive is used as 0:00, negative is subtracted from min of all time",
sa_type=Interval,
)
max_time: timedelta | None = Field(
default=None,
description="Max time correction, None = max of all, positive is used as max, negative is subtracted from max of all time",
sa_type=Interval,
)
hike_id: RowId = Field(
nullable=False,
foreign_key="hike.id",
)
start_id: RowId | None = Field(
default=None,
nullable=True,
foreign_key="place.id",
ondelete="SET NULL",
description="Start place.id of the route, None for random in CIRCULAR or CIRCULAR_BACK_TO_START",
)
finish_id: RowId | None = Field(
default=None,
nullable=True,
foreign_key="place.id",
ondelete="SET NULL",
description="Finish place.id of the route, None for random or decremented",
)
# Properties to receive via API on creation
class RouteCreate(RouteBase):
pass
# Properties to receive via API on update, all are optional
class RouteUpdate(RouteBase):
route_type: RouteType | None = Field(default=None) # type: ignore
hike_id: RowId | None = Field(default=None) # type: ignore
class Route(mixin.RowId, RouteBase, table=True):
# --- database only items --------------------------------------------------
# --- read only items ------------------------------------------------------
# --- back_populates links -------------------------------------------------
hike: "Hike" = Relationship(back_populates="routes")
teams: list["HikeTeamLink"] = Relationship(back_populates="route")
start: "Place" = Relationship(sa_relationship_kwargs={"foreign_keys": "[Route.start_id]"})
finish: "Place" = Relationship(sa_relationship_kwargs={"foreign_keys": "[Route.finish_id]"})
places: list["Place"] = Relationship(
sa_relationship_kwargs={
"primaryjoin": "or_("
"Place.id==Route.start_id,"
"Place.id==Route.finish_id,"
"Place.id==RoutePart.place_id,"
"Place.id==RoutePart.to_place_id,"
")",
"foreign_keys": "["
"Route.start_id,"
"Route.finish_id,"
"RoutePart.place_id,"
"RoutePart.to_place_id"
"]",
"viewonly": True,
},
)
route_parts: list["RoutePart"] = Relationship(back_populates="route")
# --- CRUD actions ---------------------------------------------------------
@classmethod
def create(cls, *, session: Session, create_obj: RouteCreate) -> "Route":
data_obj = create_obj.model_dump(exclude_unset=True)
db_obj = cls.model_validate(data_obj)
session.add(db_obj)
session.commit()
session.refresh(db_obj)
return db_obj
@classmethod
def update(
cls, *, session: Session, db_obj: "Route", in_obj: RouteUpdate
) -> "Route":
data_obj = in_obj.model_dump(exclude_unset=True)
db_obj.sqlmodel_update(data_obj)
session.add(db_obj)
session.commit()
session.refresh(db_obj)
return db_obj
# Properties to return via API, id is always required
class RoutePublic(mixin.RowIdPublic, RouteBase):
pass
class RoutesPublic(BaseSQLModel):
data: list[RoutePublic]
count: int
# endregion
# region # Route / Place link ##################################################
class RoutePartBase(
mixin.NameOveride,
mixin.ShortNameOveride,
BaseSQLModel,
):
route_id: RowId = Field(
nullable=False,
foreign_key="route.id",
)
place_id: RowId = Field(
nullable=False,
foreign_key="place.id",
)
to_place_id: RowId = Field(
nullable=False,
foreign_key="place.id",
)
travel_time: timedelta | None = Field(
default=None,
nullable=True,
description="Time to travel during test walk, only used for information",
sa_type=Interval,
)
travel_distance: int | None = Field(
default=None,
nullable=True,
ge=0,
description="Distance in meters to travel, only used for information",
)
# TODO: Convert to time groups
free_walk_time: bool | None = Field(
default=False,
description="If true, travel time is not add to calculated for travel time",
)
# Properties to receive via API on creation
class RoutePartBaseCreate(RoutePartBase):
pass
# Properties to receive via API on update, all are optional
class RoutePartBaseUpdate(RoutePartBase):
route_id: RowId | None = Field(default=None) # type: ignore
place_id: RowId | None = Field(default=None) # type: ignore
to_place_id: RowId | None = Field(default=None) # type: ignore
free_walk_time: bool | None = Field(default=None) # type: ignore
class RoutePart(mixin.RowId, RoutePartBase, table=True):
# --- database only items --------------------------------------------------
# --- read only items ------------------------------------------------------
# --- back_populates links -------------------------------------------------
route: "Route" = Relationship(back_populates="route_parts")
place: "Place" = Relationship(back_populates="route_parts", sa_relationship_kwargs={"foreign_keys": "[RoutePart.place_id]"})
place_to: "Place" = Relationship(sa_relationship_kwargs={"foreign_keys": "[RoutePart.to_place_id]"})
places: list["Place"] = Relationship(
sa_relationship_kwargs={
"primaryjoin": "or_("
"Place.id==RoutePart.place_id,"
"Place.id==RoutePart.to_place_id,"
")",
"foreign_keys": "["
"RoutePart.place_id,"
"RoutePart.to_place_id"
"]",
"viewonly": True,
},
)
# --- CRUD actions ---------------------------------------------------------
@classmethod
def create(cls, *, session: Session, create_obj: RouteCreate) -> "RoutePart":
data_obj = create_obj.model_dump(exclude_unset=True)
db_obj = cls.model_validate(data_obj)
session.add(db_obj)
session.commit()
session.refresh(db_obj)
return db_obj
@classmethod
def update(
cls, *, session: Session, db_obj: "RoutePart", in_obj: RouteUpdate
) -> "RoutePart":
data_obj = in_obj.model_dump(exclude_unset=True)
db_obj.sqlmodel_update(data_obj)
session.add(db_obj)
session.commit()
session.refresh(db_obj)
return db_obj
# Properties to return via API, id is always required
class RoutePartPublic(mixin.RowIdPublic, RoutePartBase):
pass
class RoutePartsPublic(BaseSQLModel):
data: list[RoutePartPublic]
count: int
# endregion