timetracker/games/convert_price.py

57 lines
2.0 KiB
Python
Raw Normal View History

import requests
from games.models import ExchangeRate, Purchase
2024-11-10 22:40:07 +00:00
# fixme: save preferred currency in user model
currency_to = "CZK"
2024-11-10 23:07:03 +00:00
currency_to = currency_to.lower()
2024-11-10 22:40:07 +00:00
def save_converted_info(purchase, converted_price, converted_currency):
purchase.converted_price = converted_price
purchase.converted_currency = converted_currency
purchase.save()
def update_converted_prices():
2024-11-10 23:07:03 +00:00
purchases = Purchase.objects.filter(
converted_price__isnull=True, converted_currency__isnull=True
)
for purchase in purchases:
2024-11-10 23:07:03 +00:00
if purchase.price_currency.lower() == currency_to or purchase.price == 0:
save_converted_info(
purchase, purchase.price, purchase.price_currency.lower()
)
continue
year = purchase.date_purchased.year
2024-11-10 23:07:03 +00:00
currency_from = purchase.price_currency.lower()
exchange_rate = ExchangeRate.objects.filter(
currency_from=currency_from, currency_to=currency_to, year=year
).first()
if not exchange_rate:
try:
response = requests.get(
2024-11-10 22:40:07 +00:00
f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{year}-01-01/v1/currencies/{currency_from}.json"
)
response.raise_for_status()
data = response.json()
2024-11-10 22:40:07 +00:00
rate = data[currency_from].get(currency_to)
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(
2024-11-10 22:40:07 +00:00
f"Failed to fetch exchange rate for {currency_from}->{currency_to} in {year}: {e}"
)
if exchange_rate:
2024-11-10 22:40:07 +00:00
save_converted_info(
purchase, purchase.price * exchange_rate.rate, currency_to
)