Compare commits

..

2 Commits

Author SHA1 Message Date
4ec1cf5f28
Improve purchase __str__ 2025-01-30 11:41:01 +01:00
d936fdc60d
Fix currency API endpoint accepting only lowercase currency strings
Signed-off-by: Lukáš Kucharczyk <lukas@kucharczyk.xyz>
2025-01-30 11:40:22 +01:00
2 changed files with 26 additions and 15 deletions

@ -3,7 +3,7 @@ from datetime import timedelta
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import F, Sum
from django.template.defaultfilters import slugify
from django.template.defaultfilters import floatformat, slugify
from django.utils import timezone
from common.time import format_duration
@ -131,6 +131,22 @@ class Purchase(models.Model):
)
created_at = models.DateTimeField(auto_now_add=True)
@property
def standardized_price(self):
return (
f"{floatformat(self.converted_price)} {self.converted_currency}"
if self.converted_price
else None
)
@property
def num_purchases(self):
return self.games.count()
@property
def has_one_item(self):
return self.games.count() == 1
@property
def standardized_name(self):
return self.name if self.name else self.first_game.name
@ -140,19 +156,7 @@ class Purchase(models.Model):
return self.games.first()
def __str__(self):
additional_info = [
self.get_type_display() if self.type != Purchase.GAME else "",
(
f"{self.first_game.platform} version on {self.platform}"
if self.platform != self.first_game.platform
else self.platform
),
self.first_game.year_released,
self.get_ownership_type_display(),
]
return (
f"{self.first_game} ({', '.join(filter(None, map(str, additional_info)))})"
)
return f"{self.standardized_name} ({self.num_purchases}, {self.date_purchased}, {self.standardized_price})"
def is_game(self):
return self.type == self.GAME

@ -32,6 +32,9 @@ def convert_prices():
).first()
if not exchange_rate:
print(
f"Getting exchange rate from {currency_from} to {currency_to} for {year}..."
)
try:
# this API endpoint only accepts lowercase currency string
response = requests.get(
@ -39,15 +42,19 @@ def convert_prices():
)
response.raise_for_status()
data = response.json()
rate = data[currency_from].get(currency_to)
currency_from_data = data.get(currency_from.lower())
rate = currency_from_data.get(currency_to.lower())
if rate:
print(f"Got {rate}, saving...")
exchange_rate = ExchangeRate.objects.create(
currency_from=currency_from,
currency_to=currency_to,
year=year,
rate=rate,
)
else:
print("Could not get an exchange rate.")
except requests.RequestException as e:
print(
f"Failed to fetch exchange rate for {currency_from}->{currency_to} in {year}: {e}"