diff --git a/nxtbn/core/currency_middleware.py b/nxtbn/core/currency_middleware.py new file mode 100644 index 0000000..8af8df6 --- /dev/null +++ b/nxtbn/core/currency_middleware.py @@ -0,0 +1,10 @@ +from django.utils.deprecation import MiddlewareMixin +from django.conf import settings + +class CurrencyMiddleware(MiddlewareMixin): + def process_request(self, request): + # Get the currency from the X-Currency header + currency = request.headers.get('Accept-Currency', settings.BASE_CURRENCY) # BASE_CURRENCY is fallback + + # Store the currency in the request object + request.currency = currency diff --git a/nxtbn/product/api/storefront/serializers.py b/nxtbn/product/api/storefront/serializers.py index f05bc12..f91a30b 100644 --- a/nxtbn/product/api/storefront/serializers.py +++ b/nxtbn/product/api/storefront/serializers.py @@ -1,7 +1,9 @@ +from django.conf import settings from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from django.db import transaction +from nxtbn.core.models import CurrencyExchange from nxtbn.product.api.dashboard.serializers import RecursiveCategorySerializer from nxtbn.filemanager.api.dashboard.serializers import ImageSerializer from nxtbn.product.models import Product, Collection, Category, ProductVariant @@ -21,6 +23,14 @@ class Meta: model = ProductVariant fields = '__all__' + def get_price_in_customer_currency(self, obj): # TODO: Implement logic for taxclass in future + if not settings.IS_MULTI_CURRENCY: # If site is in single currency, no currenyc required + return obj.price + else: + currency_code = self.context.get('request').currency + rate = CurrencyExchange.objects.get(base_currency=settings.BASE_CURRENCY, target_currency=currency_code).exchange_rate + return rate + class ProductSerializer(serializers.ModelSerializer): default_variant = ProductVariantSerializer() class Meta: diff --git a/nxtbn/settings.py b/nxtbn/settings.py index 6b6fc4f..018774a 100644 --- a/nxtbn/settings.py +++ b/nxtbn/settings.py @@ -123,7 +123,8 @@ def get_env_var(key, default=None, var_type=str): MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', - 'whitenoise.middleware.WhiteNoiseMiddleware', + 'whitenoise.middleware.WhiteNoiseMiddleware', # TODO: Do we need this? + 'nxtbn.core.currency_middleware.CurrencyMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware',