diff --git a/noxfile.py b/noxfile.py index b7aeeaf..68307b1 100644 --- a/noxfile.py +++ b/noxfile.py @@ -3,7 +3,7 @@ By default, `uv run nox` runs the sessions that assure code quality: - "format": Format source files with `autoflake`, `black`, `flynt`, `isort`, and `ruff` -- "lint": Lint source files with `flake8`, `isort`, and `ruff` +- "lint": Lint source files with `flake8`, `isort`, `mypy`, and `ruff` - "test": Run the test suite with `pytest` - "doctest": Check if code snippets in the docstrings run @@ -176,17 +176,21 @@ def format_code(session: Session) -> None: @nox.session(name="lint", python=MAIN_PYTHON) def lint_code(session: Session) -> None: - """Lint source files with `flake8`, `isort`, and `ruff`. + """Lint source files with `flake8`, `isort`, `mypy`, and `ruff`. If no extra arguments are provided, all source files are linted. Otherwise, they are interpreted as paths the linters work on recursively. + + `mypy` always checks the entire package regardless + because it needs the whole program to follow types across modules. """ start(session) - # The linters do not need `velofy` installed - # because they work on the source files directly install_pinned( session, + # `mypy` needs the dependencies of `velofy` installed + # because otherwise it treats missing packages as `Any` + ".", "flake8", "flake8-annotations", "flake8-bandit", @@ -204,8 +208,7 @@ def lint_code(session: Session) -> None: "flake8-todos", "flake8-unused-arguments", "isort", - # TODO: See comment on `mypy` below - # 'mypy', + "mypy", "pep8-naming", "pydoclint[flake8]", "ruff", @@ -225,12 +228,8 @@ def lint_code(session: Session) -> None: session.run("ruff", "--version") session.run("ruff", "check", *locations) - # TODO: Include `mypy` once it passes - # - Only for the *.py files to be packaged - # - It then needs the developed package and its dependencies installed - # as it treats missing packages as `Any` and reports false successes - # session.run('mypy', '--version') # noqa:ERA001 - # session.run('mypy', PACKAGE_LOCATION) # noqa:ERA001 + session.run("mypy", "--version") + session.run("mypy", PACKAGE_LOCATION) @nox.session(name="test", python=MAIN_PYTHON) diff --git a/pyproject.toml b/pyproject.toml index 9de9cb9..30e7b64 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -354,28 +354,30 @@ disallow_any_generics = true # Disallow functions with incomplete type annotations disallow_incomplete_defs = true -# Disallow calling functions without type annotations +# Disallow calling functions without type annotations ... disallow_untyped_calls = true +# ... except for libraries without type annotations +untyped_calls_exclude = [ + "folium", +] # Disallow functions without type annotations (or incomplete annotations) disallow_untyped_defs = true +# Require an error code in all "# type: ignore" comments +enable_error_code = ["ignore-without-code"] + +# Report "# type: ignore" comments that are not needed anymore +warn_unused_ignores = true + [[tool.mypy.overrides]] module = [ - "folium.*", "geopy.*", "googlemaps.*", - "matplotlib.*", - "nox.*", - "numpy.*", - "ordered_set.*", - "packaging", "pandas", - "pytest", "rpy2.*", - "sqlalchemy.*", "statsmodels.*", "utm.*", ] diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index 75864e5..3a5ca60 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -112,8 +112,8 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 .filter(db.Grid.side_length == side_length) .filter(db.Forecast.time_step == time_step) .filter(db.Forecast.train_horizon == train_horizon) - .first() - )[0] + .scalar() + ) # ... or start `train_horizon` weeks after the first `Order` # if no `Forecast`s are in the database yet. if last_predict_at is None: diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index 5107fd4..ea72bc5 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -35,8 +35,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 click.echo(f" -> created {len(grid.pixels)} pixels") # Because the number of assigned addresses is the same across - # different `side_length`s, we can take any `grid` from the `city`. - grid = db.session.query(db.Grid).filter_by(city=city).first() + # different `side_length`s, we can take the last `grid` from the `city`. n_assigned = ( db.session.query(db.AddressPixelAssociation) .filter(db.AddressPixelAssociation.grid_id == grid.id) diff --git a/src/velofy/db/__init__.py b/src/velofy/db/__init__.py index 38a32a8..af7a334 100644 --- a/src/velofy/db/__init__.py +++ b/src/velofy/db/__init__.py @@ -4,8 +4,6 @@ from velofy.db.addresses import Address from velofy.db.addresses_addresses import Path from velofy.db.addresses_pixels import AddressPixelAssociation from velofy.db.cities import City -from velofy.db.connection import connection -from velofy.db.connection import engine from velofy.db.connection import session from velofy.db.couriers import Courier from velofy.db.customers import Customer diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index af13c98..4cddf20 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -2,6 +2,7 @@ from __future__ import annotations +import datetime as dt import functools from typing import Any @@ -22,17 +23,56 @@ class Address(meta.Base): __tablename__ = "addresses" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) - primary_id = sa.Column(sa.Integer, nullable=False, index=True) - created_at = sa.Column(sa.DateTime, nullable=False) - place_id = sa.Column(sa.Unicode(length=120), nullable=False, index=True) - latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) - city_name = sa.Column("city", sa.Unicode(length=25), nullable=False) - zip_code = sa.Column(sa.Integer, nullable=False, index=True) - street = sa.Column(sa.Unicode(length=80), nullable=False) - floor = sa.Column(sa.SmallInteger) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=False, + ) + primary_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + created_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + ) + place_id: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=120), + nullable=False, + index=True, + ) + latitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + longitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + city_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) + city_name: orm.Mapped[str] = orm.mapped_column( + "city", + sa.Unicode(length=25), + nullable=False, + ) + zip_code: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + street: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=80), + nullable=False, + ) + floor: orm.Mapped[int | None] = orm.mapped_column( + sa.SmallInteger, + nullable=True, + ) # Constraints __table_args__ = ( @@ -157,7 +197,7 @@ class Address(meta.Base): Returns: `.city.map` for convenience in interactive usage """ - defaults = { + defaults: dict[str, Any] = { "color": f"{config.NEUTRAL_COLOR}", "popup": f"{self.street}, {self.zip_code} {self.city_name}", } diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index ef965ab..682f111 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -39,16 +39,38 @@ class Path(meta.Base): __tablename__ = "addresses_addresses" # Columns - first_address_id = sa.Column(sa.Integer, primary_key=True) - second_address_id = sa.Column(sa.Integer, primary_key=True) - city_id = sa.Column(sa.SmallInteger, nullable=False) + first_address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) + second_address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) + city_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Distances are measured in meters. - air_distance = sa.Column(sa.Integer, nullable=False) - bicycle_distance = sa.Column(sa.Integer, nullable=True) + air_distance: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + ) + bicycle_distance: orm.Mapped[int | None] = orm.mapped_column( + sa.Integer, + nullable=True, + ) # The duration is measured in seconds. - bicycle_duration = sa.Column(sa.Integer, nullable=True) + bicycle_duration: orm.Mapped[int | None] = orm.mapped_column( + sa.Integer, + nullable=True, + ) # An array of latitude-longitude pairs approximating a courier's way. - _directions = sa.Column("directions", postgresql.JSON, nullable=True) + _directions: orm.Mapped[str | None] = orm.mapped_column( + "directions", + postgresql.JSON, + nullable=True, + ) # Constraints __table_args__ = ( @@ -248,6 +270,9 @@ class Path(meta.Base): Implementation detail: This property is cached as none of the underlying attributes (i.e., `._directions`) are to be changed. """ + if not self._directions: + raise RuntimeError("_directions is not set") + points = [utils.Location(*point) for point in json.loads(self._directions)] for point in points: point.relate_to(self.first_address.city.southwest) diff --git a/src/velofy/db/addresses_pixels.py b/src/velofy/db/addresses_pixels.py index d75377b..60133a5 100644 --- a/src/velofy/db/addresses_pixels.py +++ b/src/velofy/db/addresses_pixels.py @@ -19,10 +19,22 @@ class AddressPixelAssociation(meta.Base): __tablename__ = "addresses_pixels" # Columns - address_id = sa.Column(sa.Integer, primary_key=True) - city_id = sa.Column(sa.SmallInteger, nullable=False) - grid_id = sa.Column(sa.SmallInteger, nullable=False) - pixel_id = sa.Column(sa.Integer, primary_key=True) + address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) + city_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + grid_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + pixel_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index f8b1e39..ce7b8b9 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -21,22 +21,49 @@ class City(meta.Base): __tablename__ = "cities" # Generic columns - id = sa.Column( + id: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, primary_key=True, autoincrement=False, ) - name = sa.Column(sa.Unicode(length=10), nullable=False) - kml = sa.Column(sa.UnicodeText, nullable=False) + name: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=10), + nullable=False, + ) + kml: orm.Mapped[str] = orm.mapped_column( + sa.UnicodeText, + nullable=False, + ) # Google Maps related columns - center_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - center_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - northeast_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - northeast_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - southwest_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - southwest_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) - initial_zoom = sa.Column(sa.SmallInteger, nullable=False) + center_latitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + center_longitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + northeast_latitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + northeast_longitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + southwest_latitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + southwest_longitude: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + initial_zoom: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Relationships addresses = orm.relationship("Address", back_populates="city") diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 467a0bc..3ca9d5c 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -1,28 +1,25 @@ """Provide connection utils for the ORM layer. -This module defines fully configured `engine`, `connection`, and `session` -objects to be used as globals within the `velofy` package. +This module defines a fully configured `session` object +to be used as a global within the `velofy` package. -If a database is not guaranteed to be available, they are set to `None`. +If a database is not guaranteed to be available, it is set to `None`. That is the case on the CI server. """ import os +from typing import cast import sqlalchemy as sa -from sqlalchemy import engine as engine_mod from sqlalchemy import orm import velofy if os.getenv("TESTING"): - # Specify the types explicitly to make mypy happy. - engine: engine_mod.Engine = None - connection: engine_mod.Connection = None - session: orm.Session = None + # Placeholder that the test fixtures replace + session: orm.Session = None # type: ignore[assignment] else: # pragma: no cover - engine = sa.create_engine(velofy.config.DATABASE_URI) - connection = engine.connect() - session = orm.sessionmaker(bind=connection)() + engine = sa.create_engine(cast(str, velofy.config.DATABASE_URI)) + session = orm.Session(bind=engine) diff --git a/src/velofy/db/couriers.py b/src/velofy/db/couriers.py index ea7f588..94ad329 100644 --- a/src/velofy/db/couriers.py +++ b/src/velofy/db/couriers.py @@ -1,5 +1,7 @@ """Provide the ORM's `Courier` model.""" +import datetime as dt + import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql @@ -13,13 +15,36 @@ class Courier(meta.Base): __tablename__ = "couriers" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) - created_at = sa.Column(sa.DateTime, nullable=False) - vehicle = sa.Column(sa.Unicode(length=10), nullable=False) - historic_speed = sa.Column("speed", postgresql.DOUBLE_PRECISION, nullable=False) - capacity = sa.Column(sa.SmallInteger, nullable=False) - pay_per_hour = sa.Column(sa.SmallInteger, nullable=False) - pay_per_order = sa.Column(sa.SmallInteger, nullable=False) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=False, + ) + created_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + ) + vehicle: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=10), + nullable=False, + ) + historic_speed: orm.Mapped[float] = orm.mapped_column( + "speed", + postgresql.DOUBLE_PRECISION, + nullable=False, + ) + capacity: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + pay_per_hour: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + pay_per_order: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 4aa0328..aa400d2 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -17,7 +17,11 @@ class Customer(meta.Base): __tablename__ = "customers" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=False, + ) def __repr__(self) -> str: """Non-literal text representation.""" @@ -133,17 +137,17 @@ class Customer(meta.Base): # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. # We cannot show the `Order.restaurant.name` due to the aggregation. - restaurants = ( + restaurants_at_address = ( db.session.query(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) .filter(db.Address.primary_id == address.id) .all() ) - if len(restaurants) == 1: # type:ignore - restaurant = restaurants[0] # type:ignore + if len(restaurants_at_address) == 1: + restaurant = restaurants_at_address[0] tooltip = f"{restaurant.name} (#{restaurant.id})" else: - ids = ", ".join(f"#{r.id}" for r in restaurants) # type:ignore + ids = ", ".join(f"#{r.id}" for r in restaurants_at_address) tooltip = f"Restaurants {ids}" if order_counts: diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 1296978..f33a0dd 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -2,6 +2,7 @@ from __future__ import annotations +import datetime as dt import math from typing import List @@ -23,25 +24,63 @@ class Forecast(meta.Base): __tablename__ = "forecasts" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) - pixel_id = sa.Column(sa.Integer, nullable=False, index=True) - start_at = sa.Column(sa.DateTime, nullable=False) - time_step = sa.Column(sa.SmallInteger, nullable=False) - train_horizon = sa.Column(sa.SmallInteger, nullable=False) - model = sa.Column(sa.Unicode(length=20), nullable=False) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=True, + ) + pixel_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + start_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + ) + time_step: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + train_horizon: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + model: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=20), + nullable=False, + ) # We also store the actual order counts for convenient retrieval. # A `UniqueConstraint` below ensures that redundant values that # are to be expected are consistent across rows. - actual = sa.Column(sa.SmallInteger, nullable=False) + actual: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Raw `.prediction`s are stored as `float`s (possibly negative). # The rounding is then done on the fly if required. - prediction = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) + prediction: orm.Mapped[float] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=False, + ) # The confidence intervals are treated like the `.prediction`s # but they may be nullable as some methods do not calculate them. - low80 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) - high80 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) - low95 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) - high95 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) + low80: orm.Mapped[float | None] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=True, + ) + high80: orm.Mapped[float | None] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=True, + ) + low95: orm.Mapped[float | None] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=True, + ) + high95: orm.Mapped[float | None] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=True, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index dae6013..9821ade 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -22,13 +22,20 @@ class Grid(meta.Base): __tablename__ = "grids" # Columns - id = sa.Column( + id: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, primary_key=True, autoincrement=True, ) - city_id = sa.Column(sa.SmallInteger, nullable=False) - side_length = sa.Column(sa.SmallInteger, nullable=False, unique=True) + city_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + side_length: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + unique=True, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index cf198ff..32e2a97 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -1,6 +1,6 @@ """Provide the ORM's `Order` model.""" -import datetime +import datetime as dt import folium import sqlalchemy as sa @@ -18,64 +18,228 @@ class Order(meta.Base): __tablename__ = "orders" # Generic columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) - _delivery_id = sa.Column("delivery_id", sa.Integer, index=True, unique=True) - customer_id = sa.Column(sa.Integer, nullable=False, index=True) - placed_at = sa.Column(sa.DateTime, nullable=False, index=True) - ad_hoc = sa.Column(sa.Boolean, nullable=False) - scheduled_delivery_at = sa.Column(sa.DateTime, index=True) - scheduled_delivery_at_corrected = sa.Column(sa.Boolean, index=True) - first_estimated_delivery_at = sa.Column(sa.DateTime) - cancelled = sa.Column(sa.Boolean, nullable=False, index=True) - cancelled_at = sa.Column(sa.DateTime) - cancelled_at_corrected = sa.Column(sa.Boolean, index=True) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=False, + ) + _delivery_id: orm.Mapped[int | None] = orm.mapped_column( + "delivery_id", + sa.Integer, + nullable=True, + index=True, + unique=True, + ) + customer_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + placed_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + index=True, + ) + ad_hoc: orm.Mapped[bool] = orm.mapped_column( + sa.Boolean, + nullable=False, + ) + scheduled_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + index=True, + ) + scheduled_delivery_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + first_estimated_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + cancelled: orm.Mapped[bool] = orm.mapped_column( + sa.Boolean, + nullable=False, + index=True, + ) + cancelled_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + cancelled_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) # Price-related columns - sub_total = sa.Column(sa.Integer, nullable=False) - delivery_fee = sa.Column(sa.SmallInteger, nullable=False) - total = sa.Column(sa.Integer, nullable=False) + sub_total: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + ) + delivery_fee: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) + total: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + ) # Restaurant-related columns - restaurant_id = sa.Column(sa.SmallInteger, nullable=False, index=True) - restaurant_notified_at = sa.Column(sa.DateTime) - restaurant_notified_at_corrected = sa.Column(sa.Boolean, index=True) - restaurant_confirmed_at = sa.Column(sa.DateTime) - restaurant_confirmed_at_corrected = sa.Column(sa.Boolean, index=True) - estimated_prep_duration = sa.Column(sa.Integer, index=True) - estimated_prep_duration_corrected = sa.Column(sa.Boolean, index=True) - estimated_prep_buffer = sa.Column(sa.Integer, nullable=False, index=True) + restaurant_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) + restaurant_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + restaurant_notified_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + restaurant_confirmed_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + restaurant_confirmed_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + estimated_prep_duration: orm.Mapped[int | None] = orm.mapped_column( + sa.Integer, + nullable=True, + index=True, + ) + estimated_prep_duration_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + estimated_prep_buffer: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) # Dispatch-related columns - courier_id = sa.Column(sa.Integer, index=True) - dispatch_at = sa.Column(sa.DateTime) - dispatch_at_corrected = sa.Column(sa.Boolean, index=True) - courier_notified_at = sa.Column(sa.DateTime) - courier_notified_at_corrected = sa.Column(sa.Boolean, index=True) - courier_accepted_at = sa.Column(sa.DateTime) - courier_accepted_at_corrected = sa.Column(sa.Boolean, index=True) - utilization = sa.Column(sa.SmallInteger, nullable=False) + courier_id: orm.Mapped[int | None] = orm.mapped_column( + sa.Integer, + nullable=True, + index=True, + ) + dispatch_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + dispatch_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + courier_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + courier_notified_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + courier_accepted_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + courier_accepted_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + utilization: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Pickup-related columns - pickup_address_id = sa.Column(sa.Integer, nullable=False, index=True) - reached_pickup_at = sa.Column(sa.DateTime) - pickup_at = sa.Column(sa.DateTime) - pickup_at_corrected = sa.Column(sa.Boolean, index=True) - pickup_not_confirmed = sa.Column(sa.Boolean) - left_pickup_at = sa.Column(sa.DateTime) - left_pickup_at_corrected = sa.Column(sa.Boolean, index=True) + pickup_address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + reached_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + pickup_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + pickup_not_confirmed: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + ) + left_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + left_pickup_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) # Delivery-related columns - delivery_address_id = sa.Column(sa.Integer, nullable=False, index=True) - reached_delivery_at = sa.Column(sa.DateTime) - delivery_at = sa.Column(sa.DateTime) - delivery_at_corrected = sa.Column(sa.Boolean, index=True) - delivery_not_confirmed = sa.Column(sa.Boolean) - _courier_waited_at_delivery = sa.Column("courier_waited_at_delivery", sa.Boolean) + delivery_address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + reached_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + delivery_at_corrected: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + index=True, + ) + delivery_not_confirmed: orm.Mapped[bool | None] = orm.mapped_column( + sa.Boolean, + nullable=True, + ) + _courier_waited_at_delivery: orm.Mapped[bool | None] = orm.mapped_column( + "courier_waited_at_delivery", + sa.Boolean, + nullable=True, + ) # Statistical columns - logged_delivery_distance = sa.Column(sa.SmallInteger, nullable=True) - logged_avg_speed = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) - logged_avg_speed_distance = sa.Column(sa.SmallInteger, nullable=True) + logged_delivery_distance: orm.Mapped[int | None] = orm.mapped_column( + sa.SmallInteger, + nullable=True, + ) + logged_avg_speed: orm.Mapped[float | None] = orm.mapped_column( + postgresql.DOUBLE_PRECISION, + nullable=True, + ) + logged_avg_speed_distance: orm.Mapped[int | None] = orm.mapped_column( + sa.SmallInteger, + nullable=True, + ) # Constraints __table_args__ = ( @@ -363,7 +527,7 @@ class Order(meta.Base): @property def corrected(self) -> bool: """If any timestamp was corrected as compared to the original data.""" - return ( + return bool( self.scheduled_delivery_at_corrected # => too much logic or self.cancelled_at_corrected or self.restaurant_notified_at_corrected @@ -373,13 +537,13 @@ class Order(meta.Base): or self.courier_accepted_at_corrected or self.pickup_at_corrected or self.left_pickup_at_corrected - or self.delivery_at_corrected + or self.delivery_at_corrected, ) # Timing-related properties @property - def time_to_accept(self) -> datetime.timedelta: + def time_to_accept(self) -> dt.timedelta: """Time until the `.courier` accepted the order. This measures the time it took the UDP to notify the `.courier` after dispatch. @@ -391,7 +555,7 @@ class Order(meta.Base): return self.courier_accepted_at - self.dispatch_at @property - def time_to_react(self) -> datetime.timedelta: + def time_to_react(self) -> dt.timedelta: """Time the `.courier` took to accept an order. A subset of `.time_to_accept`. @@ -403,7 +567,7 @@ class Order(meta.Base): return self.courier_accepted_at - self.courier_notified_at @property - def time_to_pickup(self) -> datetime.timedelta: + def time_to_pickup(self) -> dt.timedelta: """Time from the `.courier`'s acceptance to arrival at `.pickup_address`.""" if not self.courier_accepted_at: raise RuntimeError("courier_accepted_at is not set") @@ -412,7 +576,7 @@ class Order(meta.Base): return self.reached_pickup_at - self.courier_accepted_at @property - def time_at_pickup(self) -> datetime.timedelta: + def time_at_pickup(self) -> dt.timedelta: """Time the `.courier` stayed at the `.pickup_address`.""" if not self.reached_pickup_at: raise RuntimeError("reached_pickup_at is not set") @@ -421,71 +585,83 @@ class Order(meta.Base): return self.pickup_at - self.reached_pickup_at @property - def scheduled_pickup_at(self) -> datetime.datetime: + def scheduled_pickup_at(self) -> dt.datetime: """Point in time at which the pickup was scheduled.""" if not self.restaurant_notified_at: raise RuntimeError("restaurant_notified_at is not set") if not self.estimated_prep_duration: raise RuntimeError("estimated_prep_duration is not set") - delta = datetime.timedelta(seconds=self.estimated_prep_duration) + delta = dt.timedelta(seconds=self.estimated_prep_duration) return self.restaurant_notified_at + delta @property - def courier_early(self) -> datetime.timedelta: + def courier_early(self) -> dt.timedelta: """Time by which the `.courier` is early for pickup. Measured relative to `.scheduled_pickup_at`. - `datetime.timedelta(seconds=0)` if the `.courier` is on time or late. + `dt.timedelta(seconds=0)` if the `.courier` is on time or late. Goes together with `.courier_late`. """ + if not self.reached_pickup_at: + raise RuntimeError("reached_pickup_at is not set") + return max( - datetime.timedelta(), + dt.timedelta(), self.scheduled_pickup_at - self.reached_pickup_at, ) @property - def courier_late(self) -> datetime.timedelta: + def courier_late(self) -> dt.timedelta: """Time by which the `.courier` is late for pickup. Measured relative to `.scheduled_pickup_at`. - `datetime.timedelta(seconds=0)` if the `.courier` is on time or early. + `dt.timedelta(seconds=0)` if the `.courier` is on time or early. Goes together with `.courier_early`. """ + if not self.reached_pickup_at: + raise RuntimeError("reached_pickup_at is not set") + return max( - datetime.timedelta(), + dt.timedelta(), self.reached_pickup_at - self.scheduled_pickup_at, ) @property - def restaurant_early(self) -> datetime.timedelta: + def restaurant_early(self) -> dt.timedelta: """Time by which the `.restaurant` is early for pickup. Measured relative to `.scheduled_pickup_at`. - `datetime.timedelta(seconds=0)` if the `.restaurant` is on time or late. + `dt.timedelta(seconds=0)` if the `.restaurant` is on time or late. Goes together with `.restaurant_late`. """ - return max(datetime.timedelta(), self.scheduled_pickup_at - self.pickup_at) + if not self.pickup_at: + raise RuntimeError("pickup_at is not set") + + return max(dt.timedelta(), self.scheduled_pickup_at - self.pickup_at) @property - def restaurant_late(self) -> datetime.timedelta: + def restaurant_late(self) -> dt.timedelta: """Time by which the `.restaurant` is late for pickup. Measured relative to `.scheduled_pickup_at`. - `datetime.timedelta(seconds=0)` if the `.restaurant` is on time or early. + `dt.timedelta(seconds=0)` if the `.restaurant` is on time or early. Goes together with `.restaurant_early`. """ - return max(datetime.timedelta(), self.pickup_at - self.scheduled_pickup_at) + if not self.pickup_at: + raise RuntimeError("pickup_at is not set") + + return max(dt.timedelta(), self.pickup_at - self.scheduled_pickup_at) @property - def time_to_delivery(self) -> datetime.timedelta: + def time_to_delivery(self) -> dt.timedelta: """Time the `.courier` took from `.pickup_address` to `.delivery_address`.""" if not self.pickup_at: raise RuntimeError("pickup_at is not set") @@ -494,7 +670,7 @@ class Order(meta.Base): return self.reached_delivery_at - self.pickup_at @property - def time_at_delivery(self) -> datetime.timedelta: + def time_at_delivery(self) -> dt.timedelta: """Time the `.courier` stayed at the `.delivery_address`.""" if not self.reached_delivery_at: raise RuntimeError("reached_delivery_at is not set") @@ -503,47 +679,57 @@ class Order(meta.Base): return self.delivery_at - self.reached_delivery_at @property - def courier_waited_at_delivery(self) -> datetime.timedelta: + def courier_waited_at_delivery(self) -> dt.timedelta: """Time the `.courier` waited at the `.delivery_address`.""" if self._courier_waited_at_delivery: return self.time_at_delivery - return datetime.timedelta() + return dt.timedelta() @property - def delivery_early(self) -> datetime.timedelta: + def delivery_early(self) -> dt.timedelta: """Time by which a `.scheduled` order was early. Measured relative to `.scheduled_delivery_at`. - `datetime.timedelta(seconds=0)` if the delivery is on time or late. + `dt.timedelta(seconds=0)` if the delivery is on time or late. Goes together with `.delivery_late`. """ if not self.scheduled: raise AttributeError("Makes sense only for scheduled orders") - return max(datetime.timedelta(), self.scheduled_delivery_at - self.delivery_at) + if not self.scheduled_delivery_at: + raise RuntimeError("scheduled_delivery_at is not set") + if not self.delivery_at: + raise RuntimeError("delivery_at is not set") + return max(dt.timedelta(), self.scheduled_delivery_at - self.delivery_at) @property - def delivery_late(self) -> datetime.timedelta: + def delivery_late(self) -> dt.timedelta: """Time by which a `.scheduled` order was late. Measured relative to `.scheduled_delivery_at`. - `datetime.timedelta(seconds=0)` if the delivery is on time or early. + `dt.timedelta(seconds=0)` if the delivery is on time or early. Goes together with `.delivery_early`. """ if not self.scheduled: raise AttributeError("Makes sense only for scheduled orders") - return max(datetime.timedelta(), self.delivery_at - self.scheduled_delivery_at) + if not self.scheduled_delivery_at: + raise RuntimeError("scheduled_delivery_at is not set") + if not self.delivery_at: + raise RuntimeError("delivery_at is not set") + return max(dt.timedelta(), self.delivery_at - self.scheduled_delivery_at) @property - def total_time(self) -> datetime.timedelta: + def total_time(self) -> dt.timedelta: """Time from order placement to delivery for an `.ad_hoc` order.""" if self.scheduled: raise AttributeError("Scheduled orders have no total_time") if self.cancelled: raise RuntimeError("Cancelled orders have no total_time") + if not self.delivery_at: + raise RuntimeError("delivery_at is not set") return self.delivery_at - self.placed_at # Other Methods diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 10b1901..96cf050 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -28,10 +28,26 @@ class Pixel(meta.Base): __tablename__ = "pixels" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) - grid_id = sa.Column(sa.SmallInteger, nullable=False, index=True) - n_x = sa.Column(sa.SmallInteger, nullable=False, index=True) - n_y = sa.Column(sa.SmallInteger, nullable=False, index=True) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=True, + ) + grid_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) + n_x: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) + n_y: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) # Constraints __table_args__ = ( @@ -208,17 +224,17 @@ class Pixel(meta.Base): for address in addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. - restaurants = ( + restaurants_at_address = ( db.session.query(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) .filter(db.Address.primary_id == address.id) .all() ) - if len(restaurants) == 1: # type:ignore - restaurant = restaurants[0] # type:ignore + if len(restaurants_at_address) == 1: + restaurant = restaurants_at_address[0] tooltip = f"{restaurant.name} (#{restaurant.id})" else: - ids = ", ".join(f"#{r.id}" for r in restaurants) # type:ignore + ids = ", ".join(f"#{r.id}" for r in restaurants_at_address) tooltip = f"Restaurants {ids}" if order_counts: diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index 001d7ab..4e32ceb 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -2,6 +2,8 @@ from __future__ import annotations +import datetime as dt + import sqlalchemy as sa from sqlalchemy import orm @@ -14,43 +16,107 @@ class ReplayedOrder(meta.Base): __tablename__ = "replayed_orders" # Generic columns - simulation_id = sa.Column(sa.Integer, primary_key=True) - actual_order_id = sa.Column(sa.Integer, primary_key=True) + simulation_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) + actual_order_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + ) # `Order`-type related columns # `.ad_hoc` is part of a `ForeignKeyConstraint` to ensure the type # of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line # with the `.actual` order. - ad_hoc = sa.Column(sa.Boolean, nullable=False) - placed_at = sa.Column(sa.DateTime, nullable=False) + ad_hoc: orm.Mapped[bool] = orm.mapped_column( + sa.Boolean, + nullable=False, + ) + placed_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + ) # Depending on `.ad_hoc`, `.scheduled_delivery_at` is either filled in or not. - scheduled_delivery_at = sa.Column(sa.DateTime) + scheduled_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) # If an order is cancelled in a simulation, # some of the columns below do not apply any more. - cancelled_at = sa.Column(sa.DateTime) + cancelled_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) # Restaurant-related columns - estimated_prep_duration = sa.Column(sa.SmallInteger) - restaurant_notified_at = sa.Column(sa.DateTime) - restaurant_confirmed_at = sa.Column(sa.DateTime) - restaurant_ready_at = sa.Column(sa.DateTime) + estimated_prep_duration: orm.Mapped[int | None] = orm.mapped_column( + sa.SmallInteger, + nullable=True, + ) + restaurant_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + restaurant_confirmed_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + restaurant_ready_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) # Dispatch-related columns - dispatch_at = sa.Column(sa.DateTime) - first_estimated_delivery_at = sa.Column(sa.DateTime) - courier_id = sa.Column(sa.Integer, index=True) - courier_notified_at = sa.Column(sa.DateTime) - courier_accepted_at = sa.Column(sa.DateTime) - utilization = sa.Column(sa.SmallInteger) + dispatch_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + first_estimated_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + courier_id: orm.Mapped[int | None] = orm.mapped_column( + sa.Integer, + nullable=True, + index=True, + ) + courier_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + courier_accepted_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + utilization: orm.Mapped[int | None] = orm.mapped_column( + sa.SmallInteger, + nullable=True, + ) # Pickup-related columns - reached_pickup_at = sa.Column(sa.DateTime) - pickup_at = sa.Column(sa.DateTime) - left_pickup_at = sa.Column(sa.DateTime) + reached_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + left_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) # Delivery-related columns - reached_delivery_at = sa.Column(sa.DateTime) - delivery_at = sa.Column(sa.DateTime) + reached_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) + delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( + sa.DateTime, + nullable=True, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index 798a69c..f6bb815 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -15,11 +15,26 @@ class ReplaySimulation(meta.Base): __tablename__ = "replay_simulations" # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) - city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) - strategy = sa.Column(sa.Unicode(length=100), nullable=False, index=True) + id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + primary_key=True, + autoincrement=True, + ) + city_id: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + index=True, + ) + strategy: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=100), + nullable=False, + index=True, + ) # `.run` may be used as random seed. - run = sa.Column(sa.SmallInteger, nullable=False) + run: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 50a0cce..db13cf6 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -2,6 +2,8 @@ from __future__ import annotations +import datetime as dt + import folium import sqlalchemy as sa from sqlalchemy import orm @@ -22,15 +24,28 @@ class Restaurant(meta.Base): __tablename__ = "restaurants" # Columns - id = sa.Column( + id: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, primary_key=True, autoincrement=False, ) - created_at = sa.Column(sa.DateTime, nullable=False) - name = sa.Column(sa.Unicode(length=45), nullable=False) - address_id = sa.Column(sa.Integer, nullable=False, index=True) - estimated_prep_duration = sa.Column(sa.SmallInteger, nullable=False) + created_at: orm.Mapped[dt.datetime] = orm.mapped_column( + sa.DateTime, + nullable=False, + ) + name: orm.Mapped[str] = orm.mapped_column( + sa.Unicode(length=45), + nullable=False, + ) + address_id: orm.Mapped[int] = orm.mapped_column( + sa.Integer, + nullable=False, + index=True, + ) + estimated_prep_duration: orm.Mapped[int] = orm.mapped_column( + sa.SmallInteger, + nullable=False, + ) # Constraints __table_args__ = ( diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 3b6cc1a..826afc6 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -141,7 +141,7 @@ class OrderHistory: start_at; """, # noqa:S608 ), - con=db.connection, + con=db.session.connection(), index_col=["pixel_id", "start_at"], ) @@ -299,7 +299,7 @@ class OrderHistory: # Take only the counts at the `predict_at` time. training_ts = intra_pixel.loc[ - first_start_at : last_start_at : self._n_daily_time_steps, # type:ignore + first_start_at : last_start_at : self._n_daily_time_steps, "n_orders", ] if len(training_ts) != frequency * train_horizon: @@ -370,7 +370,7 @@ class OrderHistory: # Take all the counts between `first_train_day` and `last_train_day`. training_ts = intra_pixel.loc[ - first_start_at:last_start_at, # type:ignore + first_start_at:last_start_at, "n_orders", ] if len(training_ts) != frequency * train_horizon: @@ -392,7 +392,7 @@ class OrderHistory: ) - dt.timedelta(minutes=self._time_step) actuals_ts = intra_pixel.loc[ - first_prediction_at:last_prediction_at, # type:ignore + first_prediction_at:last_prediction_at, "n_orders", ] if not len(actuals_ts): # pragma: no cover @@ -470,7 +470,7 @@ class OrderHistory: # Take all the counts between `first_train_day` and `last_train_day`, # including the ones on the `predict_at` day prior to `predict_at`. training_ts = intra_pixel.loc[ - first_start_at:last_start_at, # type:ignore + first_start_at:last_start_at, "n_orders", ] n_time_steps_on_predict_day = ( diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index 29b1106..1c8bc46 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -13,8 +13,8 @@ from rpy2.robjects import packages as rpackages # Suppress R's messages to stdout and stderr. # Source: https://stackoverflow.com/a/63220287 -rcallbacks.consolewrite_print = lambda _msg: None # pragma: no cover -rcallbacks.consolewrite_warnerror = lambda _msg: None # pragma: no cover +rcallbacks.consolewrite_print = lambda *_args, **_kwargs: None # pragma: no cover +rcallbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: no cover # For clarity and convenience, re-raise the error that results from missing R diff --git a/tests/conftest.py b/tests/conftest.py index e09637c..4ea0d8b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,11 +47,6 @@ def db_connection(request): engine = sa.create_engine(config.DATABASE_URI) connection = engine.connect() - # Monkey patch the package's global `engine` and `connection` objects, - # just in case if it is used somewhere in the code base. - db.engine = engine - db.connection = connection - if request.param == "all_at_once": with connection.begin(): connection.execute(sa.text(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")) diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index e4fdb6d..9d9f91d 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -670,6 +670,13 @@ class TestSyncWithGoogleMaps: class TestProperties: """Test properties in `Path`.""" + def test_waypoints_no_directions(self, path): + """Test `Path.waypoints` property.""" + path._directions = None + + with pytest.raises(RuntimeError, match="not set"): + int(path.waypoints) + def test_waypoints_structure(self, path): """Test `Path.waypoints` property.""" result = path.waypoints diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index 3c12dc5..7a8c5f5 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -916,6 +916,20 @@ class TestProperties: assert bool(result) is False + def test_courier_early_no_reached_pickup_at(self, order): + """Test `Order.courier_early` property.""" + order.reached_pickup_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.courier_early) + + def test_courier_late_no_reached_pickup_at(self, order): + """Test `Order.courier_late` property.""" + order.reached_pickup_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.courier_late) + def test_restaurant_early_at_pickup(self, order): """Test `Order.restaurant_early` property.""" # Manipulate the attribute that determines `Order.scheduled_pickup_at`. @@ -952,6 +966,20 @@ class TestProperties: assert bool(result) is False + def test_restaurant_early_no_pickup_at(self, order): + """Test `Order.restaurant_early` property.""" + order.pickup_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.restaurant_early) + + def test_restaurant_late_no_pickup_at(self, order): + """Test `Order.restaurant_late` property.""" + order.pickup_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.restaurant_late) + def test_time_to_delivery_no_reached_delivery_at(self, order): """Test `Order.time_to_delivery` property.""" order.reached_delivery_at = None @@ -1034,6 +1062,22 @@ class TestProperties: assert bool(result) is False + def test_delivery_early_no_scheduled_delivery_at(self, make_order): + """Test `Order.delivery_early` property.""" + order = make_order(scheduled=True) + order.scheduled_delivery_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.delivery_early) + + def test_delivery_early_no_delivery_at(self, make_order): + """Test `Order.delivery_early` property.""" + order = make_order(scheduled=True) + order.delivery_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.delivery_early) + def test_ad_hoc_order_cannot_be_late(self, order): """Test Order.delivery_late property.""" # By default, the `OrderFactory` creates ad-hoc orders. @@ -1060,6 +1104,22 @@ class TestProperties: assert bool(result) is False + def test_delivery_late_no_scheduled_delivery_at(self, make_order): + """Test `Order.delivery_late` property.""" + order = make_order(scheduled=True) + order.scheduled_delivery_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.delivery_late) + + def test_delivery_late_no_delivery_at(self, make_order): + """Test `Order.delivery_late` property.""" + order = make_order(scheduled=True) + order.delivery_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.delivery_late) + def test_no_total_time_for_scheduled_order(self, make_order): """Test `Order.total_time` property.""" order = make_order(scheduled=True) @@ -1074,6 +1134,13 @@ class TestProperties: with pytest.raises(RuntimeError, match="Cancelled"): int(order.total_time) + def test_total_time_no_delivery_at(self, order): + """Test `Order.total_time` property.""" + order.delivery_at = None + + with pytest.raises(RuntimeError, match="not set"): + int(order.total_time) + def test_total_time_success(self, order): """Test `Order.total_time` property.""" result = order.total_time diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 6c60a06..2fb1db1 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -17,7 +17,7 @@ class TestAggregateOrders: """ @pytest.fixture - def addresses_mock(self, mocker, monkeypatch): + def addresses_mock(self, db_session, mocker, monkeypatch): """A `Mock` whose `.return_value` are to be set ... ... to the addresses that are gridified. The addresses are @@ -29,7 +29,7 @@ class TestAggregateOrders: query = ( mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) - monkeypatch.setattr(db, "session", mock) + monkeypatch.setattr(db_session, "query", mock.query) return query