From e1688629a36822afa452a09fc95ba4dc74110f6f Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Tue, 16 Apr 2024 12:41:00 +0100 Subject: [PATCH] Trip distance by means of transport: air and rail Closes: #148 --- agenda/types.py | 20 ++++++++++++++++++++ templates/trip_page.html | 9 +++++++++ 2 files changed, 29 insertions(+) diff --git a/agenda/types.py b/agenda/types.py index d150db6..b1bca73 100644 --- a/agenda/types.py +++ b/agenda/types.py @@ -2,6 +2,7 @@ import datetime import typing +from collections import Counter from dataclasses import dataclass, field from pycountry.db import Country @@ -141,6 +142,25 @@ class Trip: else None ) + def distances_by_transport_type(self) -> list[tuple[str, float]]: + """Calculate the total distance travelled for each type of transport. + + Any travel item with a missing or None 'distance' field is ignored. + """ + transport_distances: Counter[float] = Counter() + + for item in self.travel: + distance = item.get("distance") + if distance: + transport_type = item.get("type", "unknown") + transport_distances[transport_type] += distance + + return list(transport_distances.items()) + + +# Example usage: +# You would call the function with your travel list here to get the results. + @dataclass class Holiday: diff --git a/templates/trip_page.html b/templates/trip_page.html index da05843..afe8321 100644 --- a/templates/trip_page.html +++ b/templates/trip_page.html @@ -61,6 +61,7 @@ {% set end = trip.end %} {% set total_distance = trip.total_distance() %} +{% set distances_by_transport_type = trip.distances_by_transport_type() %} {% block content %}
@@ -87,6 +88,14 @@
{% endif %} + {% if distances_by_transport_type %} + {% for transport_type, distance in distances_by_transport_type %} +
{{ transport_type | title }} distance: + {{ "{:,.0f} km / {:,.0f} miles".format(distance, distance / 1.60934) }} +
+ {% endfor %} + {% endif %} + {% set delta = human_readable_delta(trip.start) %} {% if delta %}