timetracker/games/convert_price.py

49 lines
1.7 KiB
Python
Raw Normal View History

import requests
from games.models import ExchangeRate, Purchase
def update_converted_prices():
purchases = Purchase.objects.filter(
converted_price__isnull=True, converted_currency__isnull=True
)
for purchase in purchases:
if purchase.price == 0:
continue
year = purchase.date_purchased.year
currency_from = purchase.price_currency
# fixme: save preferred currency in user model
currency_to = "CZK"
exchange_rate = ExchangeRate.objects.filter(
currency_from=currency_from, currency_to=currency_to, year=year
).first()
if not exchange_rate:
try:
response = requests.get(
f"https://api.exchangeratesapi.io/{year}-01-01",
params={"base": currency_to, "symbols": "currency_from"},
)
response.raise_for_status()
data = response.json()
rate = data["rates"].get(currency_from)
if rate:
exchange_rate = ExchangeRate.objects.create(
currency_from=currency_from,
currency_to=currency_to,
year=year,
rate=rate,
)
except requests.RequestException as e:
print(
f"Failed to fetch exchange rate for {currency_from} in {year}: {e}"
)
if exchange_rate:
converted_price = purchase.price * exchange_rate.rate
purchase.converted_price = converted_price
purchase.converted_currency = currency_to
purchase.save()