feat(currencies): configurable retention for automatic exchange rates

Replace the single exchange rate option with a limit of rates kept per
currency pair (oldest deleted first) and an option to keep one rate per
day. Services that kept a single rate migrate to a limit of 1.
This commit is contained in:
Herculino Trotta committed 2026-11-05 11:07:47 -03:00
1 parent 3e4e9f4220
commit 99c6ca08a2
5 files changed
+131 -68

No files matched your search

+31 -62
View File
@@ -165,6 +165,31 @@ class ExchangeRateFetcher:
return target_currencies_qs, exchange_currencies
@staticmethod
def _store_rate(service, from_currency, to_currency, rate):
now = timezone.now()
rates = ExchangeRate.objects.filter(
automatic=True, from_currency=from_currency, to_currency=to_currency
)
today = rates.filter(date__date=timezone.localdate(now)).order_by("-date")
existing = today.first() if service.one_per_day else None
if existing:
existing.rate, existing.date = rate, now
existing.save()
else:
ExchangeRate.objects.create(
automatic=True,
from_currency=from_currency,
to_currency=to_currency,
rate=rate,
date=now,
)
if service.max_rates:
stale = rates.order_by("-date").values_list("id", flat=True)[
service.max_rates :
]
ExchangeRate.objects.filter(id__in=list(stale)).delete()
@staticmethod
def _fetch_service_rates(service: ExchangeRateService) -> None:
"""Fetch rates for a specific service"""
@@ -192,71 +217,15 @@ class ExchangeRateFetcher:
processed_pairs = set()
for from_currency, to_currency, rate in rates:
# Create a unique identifier for this currency pair
if provider.rates_inverted:
from_currency, to_currency = to_currency, from_currency
pair_key = (from_currency.id, to_currency.id)
if pair_key in processed_pairs:
continue
if provider.rates_inverted:
# If rates are inverted, we need to swap currencies
if service.singleton:
# Try to get the last automatically created exchange rate
exchange_rate = (
ExchangeRate.objects.filter(
automatic=True,
from_currency=to_currency,
to_currency=from_currency,
)
.order_by("-date")
.first()
)
else:
exchange_rate = None
if not exchange_rate:
ExchangeRate.objects.create(
automatic=True,
from_currency=to_currency,
to_currency=from_currency,
rate=rate,
date=timezone.now(),
)
else:
exchange_rate.rate = rate
exchange_rate.date = timezone.now()
exchange_rate.save()
processed_pairs.add((to_currency.id, from_currency.id))
else:
# If rates are not inverted, we can use them as is
if service.singleton:
# Try to get the last automatically created exchange rate
exchange_rate = (
ExchangeRate.objects.filter(
automatic=True,
from_currency=from_currency,
to_currency=to_currency,
)
.order_by("-date")
.first()
)
else:
exchange_rate = None
if not exchange_rate:
ExchangeRate.objects.create(
automatic=True,
from_currency=from_currency,
to_currency=to_currency,
rate=rate,
date=timezone.now(),
)
else:
exchange_rate.rate = rate
exchange_rate.date = timezone.now()
exchange_rate.save()
processed_pairs.add((from_currency.id, to_currency.id))
ExchangeRateFetcher._store_rate(
service, from_currency, to_currency, rate
)
processed_pairs.add(pair_key)
service.last_fetch = timezone.now()
service.failure_count = 0
+4 -2
View File
@@ -107,7 +107,8 @@ class ExchangeRateServiceForm(forms.ModelForm):
"fetch_interval",
"target_currencies",
"target_accounts",
"singleton",
"one_per_day",
"max_rates",
]
def __init__(self, *args, **kwargs):
@@ -120,7 +121,6 @@ class ExchangeRateServiceForm(forms.ModelForm):
"name",
"service_type",
Switch("is_active"),
Switch("singleton"),
"api_key",
Row(
Column("interval_type"),
@@ -128,6 +128,8 @@ class ExchangeRateServiceForm(forms.ModelForm):
),
"target_currencies",
"target_accounts",
Switch("one_per_day"),
"max_rates",
)
if self.instance and self.instance.pk:
@@ -0,0 +1,43 @@
import django.core.validators
from django.db import migrations, models
def singleton_to_max_rates(apps, schema_editor):
Service = apps.get_model("currencies", "ExchangeRateService")
Service.objects.filter(singleton=True).update(max_rates=1)
def max_rates_to_singleton(apps, schema_editor):
Service = apps.get_model("currencies", "ExchangeRateService")
Service.objects.filter(max_rates=1).update(singleton=True)
class Migration(migrations.Migration):
dependencies = [
("currencies", "0025_alter_exchangerateservice_service_type"),
]
operations = [
migrations.AddField(
model_name="exchangerateservice",
name="one_per_day",
field=models.BooleanField(
default=False,
help_text="Update the day's exchange rate on each fetch instead of adding a new one.",
verbose_name="One exchange rate per day",
),
),
migrations.AddField(
model_name="exchangerateservice",
name="max_rates",
field=models.PositiveIntegerField(
blank=True,
null=True,
validators=[django.core.validators.MinValueValidator(1)],
help_text="Keep at most this many automatic exchange rates per currency pair, deleting the oldest first. Leave empty to keep all.",
verbose_name="Exchange rates to keep",
),
),
migrations.RunPython(singleton_to_max_rates, max_rates_to_singleton),
migrations.RemoveField(model_name="exchangerateservice", name="singleton"),
]
+12 -3
View File
@@ -160,11 +160,20 @@ class ExchangeRateService(models.Model):
blank=True,
)
singleton = models.BooleanField(
verbose_name=_("Single exchange rate"),
one_per_day = models.BooleanField(
verbose_name=_("One exchange rate per day"),
default=False,
help_text=_(
"Create one exchange rate and keep updating it. Avoids database clutter."
"Update the day's exchange rate on each fetch instead of adding a new one."
),
)
max_rates = models.PositiveIntegerField(
verbose_name=_("Exchange rates to keep"),
null=True,
blank=True,
validators=[MinValueValidator(1)],
help_text=_(
"Keep at most this many automatic exchange rates per currency pair, deleting the oldest first. Leave empty to keep all."
),
)
@@ -1,10 +1,11 @@
import datetime
from decimal import Decimal
from unittest.mock import patch, MagicMock
from django.test import TestCase
from django.utils import timezone
from apps.currencies.models import Currency, ExchangeRateService
from apps.currencies.models import Currency, ExchangeRate, ExchangeRateService
from apps.currencies.exchange_rates.fetcher import ExchangeRateFetcher
@@ -107,3 +108,42 @@ class ExchangeRateServiceFailureTrackingTests(TestCase):
self.service.refresh_from_db()
self.assertIsNotNone(self.service.last_fetch)
self.assertEqual(self.service.failure_count, 0)
class ExchangeRateRetentionTests(TestCase):
def setUp(self):
self.usd = Currency.objects.create(code="USD", name="Dollar", decimal_places=2)
self.eur = Currency.objects.create(
code="EUR", name="Euro", decimal_places=2, exchange_currency=self.usd
)
self.service = ExchangeRateService.objects.create(
name="S", service_type=ExchangeRateService.ServiceType.FRANKFURTER
)
def fetch(self, rate, when):
with patch("django.utils.timezone.now", return_value=when):
ExchangeRateFetcher._store_rate(self.service, self.eur, self.usd, Decimal(rate))
def rates(self):
return list(
ExchangeRate.objects.order_by("date").values_list("rate", flat=True)
)
def test_keeps_every_fetch_by_default(self):
for hour in (1, 2, 3):
self.fetch(hour, timezone.now().replace(hour=hour))
self.assertEqual(len(self.rates()), 3)
def test_max_rates_deletes_the_oldest(self):
self.service.max_rates = 2
for hour in (1, 2, 3):
self.fetch(hour, timezone.now().replace(hour=hour))
self.assertEqual(self.rates(), [Decimal(2), Decimal(3)])
def test_one_per_day_updates_the_days_rate(self):
self.service.one_per_day = True
day = timezone.localtime().replace(hour=10)
self.fetch(1, day)
self.fetch(2, day.replace(hour=11))
self.fetch(3, day + datetime.timedelta(days=1))
self.assertEqual(self.rates(), [Decimal(2), Decimal(3)])