From f9a17095109c6405b5a3f3ea2eb55c5799fad14d Mon Sep 17 00:00:00 2001 From: Saeed Date: Mon, 17 Aug 2026 23:00:40 +0330 Subject: [PATCH] feat: add catalog filters and customer order dashboard --- backend/apps/catalog/admin.py | 26 +- ...uct_brand_product_product_type_and_more.py | 89 +++ backend/apps/catalog/models.py | 54 ++ backend/apps/catalog/serializers.py | 53 +- backend/apps/catalog/tests/test_api.py | 82 ++- backend/apps/catalog/views.py | 84 ++- backend/apps/chat/consumers.py | 24 +- backend/apps/chat/services.py | 6 +- backend/apps/chat/tests/test_chat_api.py | 32 + backend/apps/chat/views.py | 5 +- backend/apps/orders/serializers.py | 6 +- backend/apps/orders/services.py | 3 +- .../orders/tests/test_admin_orders_api.py | 10 +- .../apps/orders/tests/test_checkout_api.py | 30 + backend/apps/orders/urls.py | 2 + backend/apps/orders/views.py | 28 +- frontend/src/main.tsx | 640 ++++++++++++++---- frontend/src/styles.css | 350 ++++++++++ 18 files changed, 1347 insertions(+), 177 deletions(-) create mode 100644 backend/apps/catalog/migrations/0003_product_brand_product_product_type_and_more.py diff --git a/backend/apps/catalog/admin.py b/backend/apps/catalog/admin.py index 1a985b4..5a5baeb 100644 --- a/backend/apps/catalog/admin.py +++ b/backend/apps/catalog/admin.py @@ -1,6 +1,12 @@ from django.contrib import admin -from .models import Category, Product, ProductImage +from .models import ( + Category, + LaptopSpecification, + MobileSpecification, + Product, + ProductImage, +) class ProductImageInline(admin.TabularInline): @@ -9,6 +15,18 @@ class ProductImageInline(admin.TabularInline): fields = ("image", "alt_text", "display_order") +class LaptopSpecificationInline(admin.StackedInline): + model = LaptopSpecification + extra = 0 + max_num = 1 + + +class MobileSpecificationInline(admin.StackedInline): + model = MobileSpecification + extra = 0 + max_num = 1 + + @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ("name", "slug", "is_active", "display_order") @@ -23,13 +41,15 @@ class ProductAdmin(admin.ModelAdmin): list_display = ( "name", "category", + "product_type", + "brand", "price", "stock_quantity", "status", "is_featured", ) list_editable = ("price", "stock_quantity", "status", "is_featured") - list_filter = ("status", "is_featured", "category") + list_filter = ("product_type", "status", "is_featured", "category") search_fields = ("name", "sku", "slug") prepopulated_fields = {"slug": ("name",)} - inlines = (ProductImageInline,) + inlines = (ProductImageInline, LaptopSpecificationInline, MobileSpecificationInline) diff --git a/backend/apps/catalog/migrations/0003_product_brand_product_product_type_and_more.py b/backend/apps/catalog/migrations/0003_product_brand_product_product_type_and_more.py new file mode 100644 index 0000000..55e9193 --- /dev/null +++ b/backend/apps/catalog/migrations/0003_product_brand_product_product_type_and_more.py @@ -0,0 +1,89 @@ +# Generated by Django 6.0.7 on 2026-08-17 18:39 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("catalog", "0002_productimage_image"), + ] + + operations = [ + migrations.AddField( + model_name="product", + name="brand", + field=models.CharField(blank=True, max_length=80), + ), + migrations.AddField( + model_name="product", + name="product_type", + field=models.CharField( + choices=[("laptop", "Laptop"), ("mobile", "Mobile")], + default="laptop", + max_length=16, + ), + ), + migrations.CreateModel( + name="LaptopSpecification", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("processor", models.CharField(max_length=120)), + ("ram_gb", models.PositiveSmallIntegerField()), + ("storage_gb", models.PositiveIntegerField()), + ( + "display_size_inches", + models.DecimalField(decimal_places=1, max_digits=3), + ), + ("graphics", models.CharField(blank=True, max_length=120)), + ( + "product", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="laptop_specification", + to="catalog.product", + ), + ), + ], + ), + migrations.CreateModel( + name="MobileSpecification", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("ram_gb", models.PositiveSmallIntegerField()), + ("storage_gb", models.PositiveIntegerField()), + ("camera_megapixels", models.PositiveSmallIntegerField()), + ( + "network", + models.CharField( + choices=[("4g", "4G"), ("5g", "5G")], max_length=2 + ), + ), + ("battery_mah", models.PositiveIntegerField()), + ( + "product", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="mobile_specification", + to="catalog.product", + ), + ), + ], + ), + ] diff --git a/backend/apps/catalog/models.py b/backend/apps/catalog/models.py index 15f2951..89db6e0 100644 --- a/backend/apps/catalog/models.py +++ b/backend/apps/catalog/models.py @@ -30,6 +30,10 @@ def __str__(self) -> str: class Product(TimeStampedModel): + class Type(models.TextChoices): + LAPTOP = "laptop", "Laptop" + MOBILE = "mobile", "Mobile" + class Status(models.TextChoices): DRAFT = "draft", "Draft" PUBLISHED = "published", "Published" @@ -38,6 +42,10 @@ class Status(models.TextChoices): category = models.ForeignKey( Category, on_delete=models.PROTECT, related_name="products" ) + product_type = models.CharField( + max_length=16, choices=Type.choices, default=Type.LAPTOP + ) + brand = models.CharField(max_length=80, blank=True) name = models.CharField(max_length=180) slug = models.SlugField(unique=True) sku = models.CharField(max_length=64, unique=True) @@ -84,6 +92,52 @@ def clean(self) -> None: ) +class LaptopSpecification(models.Model): + product = models.OneToOneField( + Product, on_delete=models.CASCADE, related_name="laptop_specification" + ) + processor = models.CharField(max_length=120) + ram_gb = models.PositiveSmallIntegerField() + storage_gb = models.PositiveIntegerField() + display_size_inches = models.DecimalField(max_digits=3, decimal_places=1) + graphics = models.CharField(max_length=120, blank=True) + + def clean(self) -> None: + super().clean() + if self.product.product_type != Product.Type.LAPTOP: + raise ValidationError( + {"product": "Laptop details require a laptop product."} + ) + + def __str__(self) -> str: + return f"Laptop details for {self.product}" + + +class MobileSpecification(models.Model): + class Network(models.TextChoices): + FOUR_G = "4g", "4G" + FIVE_G = "5g", "5G" + + product = models.OneToOneField( + Product, on_delete=models.CASCADE, related_name="mobile_specification" + ) + ram_gb = models.PositiveSmallIntegerField() + storage_gb = models.PositiveIntegerField() + camera_megapixels = models.PositiveSmallIntegerField() + network = models.CharField(max_length=2, choices=Network.choices) + battery_mah = models.PositiveIntegerField() + + def clean(self) -> None: + super().clean() + if self.product.product_type != Product.Type.MOBILE: + raise ValidationError( + {"product": "Mobile details require a mobile product."} + ) + + def __str__(self) -> str: + return f"Mobile details for {self.product}" + + class ProductImage(TimeStampedModel): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="images" diff --git a/backend/apps/catalog/serializers.py b/backend/apps/catalog/serializers.py index 6e0a86e..0ea5811 100644 --- a/backend/apps/catalog/serializers.py +++ b/backend/apps/catalog/serializers.py @@ -1,6 +1,12 @@ from rest_framework import serializers -from .models import Category, Product, ProductImage +from .models import ( + Category, + LaptopSpecification, + MobileSpecification, + Product, + ProductImage, +) class CategorySerializer(serializers.ModelSerializer): @@ -34,6 +40,8 @@ class Meta: "id", "name", "slug", + "product_type", + "brand", "short_description", "price", "compare_at_price", @@ -53,6 +61,47 @@ def get_primary_image(self, product: Product) -> str | None: class ProductDetailSerializer(ProductListSerializer): images = ProductImageSerializer(many=True, read_only=True) + specifications = serializers.SerializerMethodField() class Meta(ProductListSerializer.Meta): - fields = ProductListSerializer.Meta.fields + ("description", "sku", "images") + fields = ProductListSerializer.Meta.fields + ( + "description", + "sku", + "specifications", + "images", + ) + + def get_specifications(self, product: Product) -> dict | None: + if product.product_type == Product.Type.LAPTOP: + specification = getattr(product, "laptop_specification", None) + if specification is None: + return None + return LaptopSpecificationSerializer(specification).data + specification = getattr(product, "mobile_specification", None) + if specification is None: + return None + return MobileSpecificationSerializer(specification).data + + +class LaptopSpecificationSerializer(serializers.ModelSerializer): + class Meta: + model = LaptopSpecification + fields = ( + "processor", + "ram_gb", + "storage_gb", + "display_size_inches", + "graphics", + ) + + +class MobileSpecificationSerializer(serializers.ModelSerializer): + class Meta: + model = MobileSpecification + fields = ( + "ram_gb", + "storage_gb", + "camera_megapixels", + "network", + "battery_mah", + ) diff --git a/backend/apps/catalog/tests/test_api.py b/backend/apps/catalog/tests/test_api.py index c672ca6..9984c77 100644 --- a/backend/apps/catalog/tests/test_api.py +++ b/backend/apps/catalog/tests/test_api.py @@ -3,7 +3,13 @@ import pytest from rest_framework.test import APIClient -from apps.catalog.models import Category, Product, ProductImage +from apps.catalog.models import ( + Category, + LaptopSpecification, + MobileSpecification, + Product, + ProductImage, +) def create_product( @@ -85,3 +91,77 @@ def test_product_api_uses_minio_url_for_uploaded_images() -> None: "display_order": 0, }, ] + + +@pytest.mark.django_db +def test_product_api_filters_laptops_with_common_and_laptop_specific_filters() -> None: + category = Category.objects.create(name="Laptops", slug="laptops") + laptop = create_product(category, slug="laptop", price=Decimal(30000000)) + laptop.product_type = Product.Type.LAPTOP + laptop.brand = "Nexora" + laptop.stock_quantity = 2 + laptop.save(update_fields=["product_type", "brand", "stock_quantity"]) + LaptopSpecification.objects.create( + product=laptop, + processor="Core Ultra 7", + ram_gb=16, + storage_gb=1024, + display_size_inches=Decimal("14.0"), + ) + lower_spec = create_product(category, slug="lower-spec", price=Decimal(20000000)) + LaptopSpecification.objects.create( + product=lower_spec, + processor="Core i5", + ram_gb=8, + storage_gb=512, + display_size_inches=Decimal("15.6"), + ) + + response = APIClient().get( + "/api/v1/catalog/products/?type=laptop&brand=nexora&min_price=25000000" + "&ram_min=16&storage_min=1024&processor=ultra&in_stock=true" + ) + + assert response.status_code == 200 + assert [item["slug"] for item in response.data["results"]] == ["laptop"] + + +@pytest.mark.django_db +def test_product_detail_and_mobile_filters_expose_mobile_specifications() -> None: + category = Category.objects.create(name="Mobiles", slug="mobiles") + mobile = create_product(category, slug="mobile", price=Decimal(18000000)) + mobile.product_type = Product.Type.MOBILE + mobile.brand = "Nexora Mobile" + mobile.save(update_fields=["product_type", "brand"]) + MobileSpecification.objects.create( + product=mobile, + ram_gb=12, + storage_gb=256, + camera_megapixels=50, + network=MobileSpecification.Network.FIVE_G, + battery_mah=5000, + ) + + list_response = APIClient().get( + "/api/v1/catalog/products/?type=mobile&ram_min=8&storage_min=128&network=5g" + ) + detail_response = APIClient().get("/api/v1/catalog/products/mobile/") + + assert list_response.status_code == 200 + assert [item["slug"] for item in list_response.data["results"]] == ["mobile"] + assert detail_response.status_code == 200 + assert detail_response.data["specifications"] == { + "ram_gb": 12, + "storage_gb": 256, + "camera_megapixels": 50, + "network": "5g", + "battery_mah": 5000, + } + + +@pytest.mark.django_db +def test_product_api_rejects_invalid_filter_values() -> None: + response = APIClient().get("/api/v1/catalog/products/?type=mobile&network=6g") + + assert response.status_code == 400 + assert "network" in response.data diff --git a/backend/apps/catalog/views.py b/backend/apps/catalog/views.py index e592636..3e6a9d4 100644 --- a/backend/apps/catalog/views.py +++ b/backend/apps/catalog/views.py @@ -1,6 +1,10 @@ +from decimal import Decimal, InvalidOperation + +from django.db.models import Q +from rest_framework.exceptions import ValidationError from rest_framework.generics import ListAPIView, RetrieveAPIView -from .models import Category, Product +from .models import Category, MobileSpecification, Product from .serializers import ( CategorySerializer, ProductDetailSerializer, @@ -17,6 +21,30 @@ class CategoryListAPIView(ListAPIView): class ProductListAPIView(ListAPIView): serializer_class = ProductListSerializer + def _positive_decimal(self, name: str) -> Decimal | None: + raw_value = self.request.query_params.get(name) + if raw_value in (None, ""): + return None + try: + value = Decimal(raw_value) + except InvalidOperation as error: + raise ValidationError({name: "Enter a valid number."}) from error + if value < 0: + raise ValidationError({name: "Enter a non-negative number."}) + return value + + def _positive_integer(self, name: str) -> int | None: + raw_value = self.request.query_params.get(name) + if raw_value in (None, ""): + return None + try: + value = int(raw_value) + except ValueError as error: + raise ValidationError({name: "Enter a valid whole number."}) from error + if value < 0: + raise ValidationError({name: "Enter a non-negative whole number."}) + return value + def get_queryset(self): queryset = ( Product.objects.filter( @@ -24,12 +52,65 @@ def get_queryset(self): category__is_active=True, ) .select_related("category") + .select_related("laptop_specification", "mobile_specification") .prefetch_related("images") ) if category := self.request.query_params.get("category"): queryset = queryset.filter(category__slug=category) + if query := self.request.query_params.get("q", "").strip(): + queryset = queryset.filter( + Q(name__icontains=query) + | Q(sku__icontains=query) + | Q(brand__icontains=query) + ) if self.request.query_params.get("featured") == "true": queryset = queryset.filter(is_featured=True) + product_type = self.request.query_params.get("type", "").strip() + if product_type: + valid_types = {value for value, _ in Product.Type.choices} + if product_type not in valid_types: + raise ValidationError({"type": "Unsupported product type."}) + queryset = queryset.filter(product_type=product_type) + if brand := self.request.query_params.get("brand", "").strip(): + queryset = queryset.filter(brand__iexact=brand) + min_price = self._positive_decimal("min_price") + max_price = self._positive_decimal("max_price") + if min_price is not None and max_price is not None and min_price > max_price: + raise ValidationError({"max_price": "Must be greater than min_price."}) + if min_price is not None: + queryset = queryset.filter(price__gte=min_price) + if max_price is not None: + queryset = queryset.filter(price__lte=max_price) + if self.request.query_params.get("in_stock") == "true": + queryset = queryset.filter(stock_quantity__gt=0) + + ram_min = self._positive_integer("ram_min") + storage_min = self._positive_integer("storage_min") + if product_type == Product.Type.LAPTOP: + if ram_min is not None: + queryset = queryset.filter(laptop_specification__ram_gb__gte=ram_min) + if storage_min is not None: + queryset = queryset.filter( + laptop_specification__storage_gb__gte=storage_min + ) + if processor := self.request.query_params.get("processor", "").strip(): + queryset = queryset.filter( + laptop_specification__processor__icontains=processor + ) + if product_type == Product.Type.MOBILE: + if ram_min is not None: + queryset = queryset.filter(mobile_specification__ram_gb__gte=ram_min) + if storage_min is not None: + queryset = queryset.filter( + mobile_specification__storage_gb__gte=storage_min + ) + if network := self.request.query_params.get("network", "").strip(): + valid_networks = { + value for value, _ in MobileSpecification.Network.choices + } + if network not in valid_networks: + raise ValidationError({"network": "Unsupported mobile network."}) + queryset = queryset.filter(mobile_specification__network=network) ordering = self.request.query_params.get("ordering") return queryset.order_by( {"price": "price", "-price": "-price", "newest": "-created_at"}.get( @@ -47,5 +128,6 @@ class ProductDetailAPIView(RetrieveAPIView): category__is_active=True, ) .select_related("category") + .select_related("laptop_specification", "mobile_specification") .prefetch_related("images") ) diff --git a/backend/apps/chat/consumers.py b/backend/apps/chat/consumers.py index 29afdf7..1c07398 100644 --- a/backend/apps/chat/consumers.py +++ b/backend/apps/chat/consumers.py @@ -25,12 +25,15 @@ async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def receive_json(self, content, **kwargs): - serializer = CreateMessageSerializer(data={"body": content.get("body")}) + payload = {"body": content.get("body")} + if content.get("client_message_id") is not None: + payload["client_message_id"] = content["client_message_id"] + serializer = CreateMessageSerializer(data=payload) if not serializer.is_valid(): await self.send_json({"type": "error", "detail": serializer.errors}) return try: - message = await self._create_message( + message, created = await self._create_message( self.scope["user"], self.conversation_id, serializer.validated_data["body"], @@ -45,10 +48,13 @@ async def receive_json(self, content, **kwargs): } ) return - await self.channel_layer.group_send( - self.group_name, - {"type": "chat.message", "message": message}, - ) + if created: + await self.channel_layer.group_send( + self.group_name, + {"type": "chat.message", "message": message}, + ) + else: + await self.send_json({"type": "message", "message": message}) async def chat_message(self, event): await self.send_json({"type": "message", "message": event["message"]}) @@ -64,11 +70,11 @@ def _can_access_conversation(self, user, conversation_id) -> bool: @database_sync_to_async def _create_message( self, user, conversation_id, body: str, client_message_id - ) -> dict: - message = create_message( + ) -> tuple[dict, bool]: + message, created = create_message( user=user, conversation_id=conversation_id, body=body, client_message_id=client_message_id, ) - return message_payload(message) + return message_payload(message), created diff --git a/backend/apps/chat/services.py b/backend/apps/chat/services.py index 77deceb..f91c621 100644 --- a/backend/apps/chat/services.py +++ b/backend/apps/chat/services.py @@ -34,7 +34,7 @@ def get_conversation_for_user(*, user, conversation_id) -> Conversation: @transaction.atomic def create_message( *, user, conversation_id, body: str, client_message_id=None -) -> Message: +) -> tuple[Message, bool]: queryset = Conversation.objects.select_for_update().select_related("customer") if not is_platform_admin(user): queryset = queryset.filter(customer=user) @@ -48,7 +48,7 @@ def create_message( if existing is not None: if existing.sender_id != user.id: raise PermissionDenied("Message identifier belongs to another user.") - return existing + return existing, False message = Message.objects.create( conversation=conversation, sender=user, @@ -61,7 +61,7 @@ def create_message( conversation.status = Conversation.Status.OPEN update_fields.append("status") conversation.save(update_fields=update_fields) - return message + return message, True def message_payload(message: Message) -> dict: diff --git a/backend/apps/chat/tests/test_chat_api.py b/backend/apps/chat/tests/test_chat_api.py index 58f76bc..c8ebcbc 100644 --- a/backend/apps/chat/tests/test_chat_api.py +++ b/backend/apps/chat/tests/test_chat_api.py @@ -198,3 +198,35 @@ async def run_scenario() -> None: async_to_sync(run_scenario)() assert Message.objects.get(conversation=conversation).body == "Customer message" + + +@pytest.mark.django_db(transaction=True) +def test_websocket_client_message_identifier_is_idempotent(customer: User) -> None: + conversation = Conversation.objects.create(customer=customer) + token = str(AccessToken.for_user(customer)) + client_message_id = "31a2143d-faa0-4747-97c3-49a91a6a15c2" + + async def run_scenario() -> None: + communicator = WebsocketCommunicator( + application, + f"/ws/chat/{conversation.id}/", + subprotocols=["access_token", token], + ) + try: + connected, _ = await communicator.connect() + assert connected is True + payload = { + "body": "Retry-safe message", + "client_message_id": client_message_id, + } + await communicator.send_json_to(payload) + first = await communicator.receive_json_from() + await communicator.send_json_to(payload) + second = await communicator.receive_json_from() + assert first["message"]["id"] == second["message"]["id"] + assert first["message"]["client_message_id"] == client_message_id + finally: + await communicator.disconnect() + + async_to_sync(run_scenario)() + assert Message.objects.filter(conversation=conversation).count() == 1 diff --git a/backend/apps/chat/views.py b/backend/apps/chat/views.py index ca1aae5..3767121 100644 --- a/backend/apps/chat/views.py +++ b/backend/apps/chat/views.py @@ -122,11 +122,12 @@ def post(self, request, conversation_id): conversation = self.get_conversation() serializer = CreateMessageSerializer(data=request.data) serializer.is_valid(raise_exception=True) - message = create_message( + message, created = create_message( user=request.user, conversation_id=conversation.id, body=serializer.validated_data["body"], client_message_id=serializer.validated_data.get("client_message_id"), ) - publish_message(message) + if created: + publish_message(message) return Response(MessageSerializer(message).data, status=status.HTTP_201_CREATED) diff --git a/backend/apps/orders/serializers.py b/backend/apps/orders/serializers.py index eee06a5..3ff609e 100644 --- a/backend/apps/orders/serializers.py +++ b/backend/apps/orders/serializers.py @@ -47,9 +47,13 @@ class Meta: class OrderStatusEventSerializer(serializers.ModelSerializer): + changed_by_phone = serializers.CharField( + source="changed_by.phone", read_only=True, default=None + ) + class Meta: model = OrderStatusEvent - fields = ("from_status", "to_status", "created_at") + fields = ("from_status", "to_status", "changed_by_phone", "created_at") class OrderSerializer(serializers.ModelSerializer): diff --git a/backend/apps/orders/services.py b/backend/apps/orders/services.py index 4c6b5d7..e75f6e5 100644 --- a/backend/apps/orders/services.py +++ b/backend/apps/orders/services.py @@ -91,7 +91,7 @@ def create_order_from_cart(*, user, address_id: int) -> Order: @transaction.atomic -def transition_order_status(*, order_number, target_status: str) -> Order: +def transition_order_status(*, order_number, target_status: str, changed_by) -> Order: order = ( Order.objects.select_for_update() .select_related("user") @@ -138,6 +138,7 @@ def transition_order_status(*, order_number, target_status: str) -> Order: order=order, from_status=previous_status, to_status=target_status, + changed_by=changed_by, ) return order diff --git a/backend/apps/orders/tests/test_admin_orders_api.py b/backend/apps/orders/tests/test_admin_orders_api.py index 6745cee..8e6036e 100644 --- a/backend/apps/orders/tests/test_admin_orders_api.py +++ b/backend/apps/orders/tests/test_admin_orders_api.py @@ -5,7 +5,7 @@ from apps.accounts.models import User from apps.catalog.models import Category, Product -from apps.orders.models import Order, OrderItem, PaymentAttempt +from apps.orders.models import Order, OrderItem, OrderStatusEvent, PaymentAttempt @pytest.fixture @@ -107,7 +107,7 @@ def test_admin_gets_an_order_summary( @pytest.mark.django_db def test_admin_can_move_paid_order_through_fulfilment( - admin_client: APIClient, paid_order: Order + admin_client: APIClient, admin: User, paid_order: Order ) -> None: processing = admin_client.patch( f"/api/v1/orders/admin/{paid_order.number}/status/", @@ -122,6 +122,12 @@ def test_admin_can_move_paid_order_through_fulfilment( assert processing.data["status"] == Order.Status.PROCESSING assert shipped.status_code == 200 assert shipped.data["status"] == Order.Status.SHIPPED + assert ( + OrderStatusEvent.objects.get( + order=paid_order, to_status=Order.Status.PROCESSING + ).changed_by_id + == admin.id + ) @pytest.mark.django_db diff --git a/backend/apps/orders/tests/test_checkout_api.py b/backend/apps/orders/tests/test_checkout_api.py index c636f3d..1443919 100644 --- a/backend/apps/orders/tests/test_checkout_api.py +++ b/backend/apps/orders/tests/test_checkout_api.py @@ -213,3 +213,33 @@ def test_orders_are_visible_only_to_owner( assert len(client.get("/api/v1/orders/").data["results"]) == 1 assert other_client.get("/api/v1/orders/").data["results"] == [] + + +@pytest.mark.django_db +def test_customer_can_filter_and_summarize_own_orders( + client: APIClient, user: User, product: Product, address: Address +) -> None: + cart = Cart.objects.create(user=user) + CartItem.objects.create(cart=cart, product=product) + client.post("/api/v1/orders/checkout/", {"address_id": address.id}) + Order.objects.create( + user=user, + status=Order.Status.SHIPPED, + subtotal=Decimal(100000), + shipping_full_name="Test User", + shipping_phone=user.phone, + shipping_province="Tehran", + shipping_city="Tehran", + shipping_address_line="Street", + shipping_postal_code="1234567890", + ) + + filtered = client.get("/api/v1/orders/?status=shipped") + summary = client.get("/api/v1/orders/summary/") + + assert filtered.status_code == 200 + assert filtered.data["count"] == 1 + assert summary.status_code == 200 + assert summary.data["total"] == 2 + assert summary.data["by_status"][Order.Status.PENDING] == 1 + assert summary.data["by_status"][Order.Status.SHIPPED] == 1 diff --git a/backend/apps/orders/urls.py b/backend/apps/orders/urls.py index 21d763b..cc0f766 100644 --- a/backend/apps/orders/urls.py +++ b/backend/apps/orders/urls.py @@ -6,6 +6,7 @@ AdminOrderStatusAPIView, AdminOrderSummaryAPIView, CheckoutAPIView, + CustomerOrderSummaryAPIView, OrderListAPIView, StartPaymentAPIView, ZarinpalCallbackAPIView, @@ -26,6 +27,7 @@ AdminOrderStatusAPIView.as_view(), name="admin-order-status", ), + path("summary/", CustomerOrderSummaryAPIView.as_view(), name="order-summary"), path("", OrderListAPIView.as_view(), name="order-list"), path("checkout/", CheckoutAPIView.as_view(), name="checkout"), path( diff --git a/backend/apps/orders/views.py b/backend/apps/orders/views.py index 41225f2..871b345 100644 --- a/backend/apps/orders/views.py +++ b/backend/apps/orders/views.py @@ -49,9 +49,30 @@ class OrderListAPIView(ListAPIView): serializer_class = OrderSerializer def get_queryset(self): - return Order.objects.filter(user=self.request.user).prefetch_related( - "items", "status_events" + queryset = Order.objects.filter(user=self.request.user).prefetch_related( + "items", "status_events__changed_by" ) + requested_status = self.request.query_params.get("status", "").strip() + if requested_status: + valid_statuses = {choice for choice, _ in Order.Status.choices} + if requested_status not in valid_statuses: + raise ValidationError({"status": "Invalid order status."}) + queryset = queryset.filter(status=requested_status) + return queryset + + +class CustomerOrderSummaryAPIView(APIView): + permission_classes = (IsAuthenticated,) + + def get(self, request): + by_status = {status: 0 for status, _ in Order.Status.choices} + for item in ( + Order.objects.filter(user=request.user) + .values("status") + .annotate(count=Count("id")) + ): + by_status[item["status"]] = item["count"] + return Response({"total": sum(by_status.values()), "by_status": by_status}) class AdminOrderListAPIView(ListAPIView): @@ -60,7 +81,7 @@ class AdminOrderListAPIView(ListAPIView): def get_queryset(self): queryset = Order.objects.select_related("user").prefetch_related( - "items", "status_events" + "items", "status_events__changed_by" ) requested_status = self.request.query_params.get("status", "").strip() if requested_status: @@ -96,6 +117,7 @@ def patch(self, request, order_number): order = transition_order_status( order_number=order_number, target_status=serializer.validated_data["status"], + changed_by=request.user, ) return Response(AdminOrderSerializer(order).data) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 6fc7767..a1f62c6 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -32,6 +32,8 @@ type Product = { id: number; name: string; slug: string; + product_type: "laptop" | "mobile"; + brand: string; short_description: string; price: string; compare_at_price: string | null; @@ -43,6 +45,16 @@ type Product = { type ProductDetail = Product & { description: string; sku: string; + specifications: { + processor?: string; + ram_gb: number; + storage_gb: number; + display_size_inches?: string; + graphics?: string; + camera_megapixels?: number; + network?: "4g" | "5g"; + battery_mah?: number; + } | null; images: { id: number; image_url: string | null; alt_text: string }[]; }; type CartItem = { @@ -80,6 +92,7 @@ type OrderItem = { type OrderStatusEvent = { from_status: string; to_status: string; + changed_by_phone: string | null; created_at: string; }; type Order = { @@ -164,6 +177,16 @@ const apiBaseUrl = ( ).replace(/\/$/, ""); const categoryIcons = ["⌁", "◒", "⌂", "✦"]; const categoryTones = ["blue", "peach", "mint", "lilac"]; +const specificationLabels: Record = { + processor: "پردازنده", + ram_gb: "حافظه رم", + storage_gb: "حافظه داخلی", + display_size_inches: "اندازه نمایشگر", + graphics: "پردازنده گرافیکی", + camera_megapixels: "دوربین اصلی", + network: "شبکه", + battery_mah: "ظرفیت باتری", +}; function formatPrice(value: string) { return new Intl.NumberFormat("fa-IR").format(Number(value)); @@ -608,11 +631,13 @@ function ProductCard({ product }: { product: Product }) { ) : (
{product.name.slice(0, 1)}
)} - {product.category.name} + + {product.product_type === "laptop" ? "لپ‌تاپ" : "موبایل"} +
- {product.category.name} + {product.brand || product.category.name} {product.in_stock ? "موجود" : "ناموجود"} @@ -631,13 +656,6 @@ function ProductCard({ product }: { product: Product }) {
- ); } @@ -808,10 +826,59 @@ function CatalogPage({ categories: Category[]; category: string | null; }) { + const filters = new URLSearchParams(location.search); + const productType = filters.get("type") as Product["product_type"] | null; + const queryString = filters.toString(); const catalog = useProducts( - category ? `?category=${encodeURIComponent(category)}` : "?ordering=newest", + queryString ? `?${queryString}` : "?ordering=newest", ); const selected = categories.find((item) => item.slug === category); + + function catalogPath(nextFilters: URLSearchParams) { + const nextQuery = nextFilters.toString(); + return nextQuery ? `/products?${nextQuery}` : "/products"; + } + + function updateFilter(name: string, value: string | boolean) { + const nextFilters = new URLSearchParams(location.search); + if (!value) nextFilters.delete(name); + else nextFilters.set(name, String(value)); + if (name === "type") { + ["ram_min", "storage_min", "processor", "network"].forEach((key) => + nextFilters.delete(key), + ); + } + navigate(catalogPath(nextFilters)); + } + + function categoryPath(slug: string | null) { + const nextFilters = new URLSearchParams(location.search); + if (slug) nextFilters.set("category", slug); + else nextFilters.delete("category"); + return catalogPath(nextFilters); + } + + function submitFilters(event: FormEvent) { + event.preventDefault(); + const nextFilters = new URLSearchParams(location.search); + const data = new FormData(event.currentTarget); + [ + "q", + "brand", + "min_price", + "max_price", + "ram_min", + "storage_min", + "processor", + "network", + ].forEach((name) => { + const value = String(data.get(name) ?? "").trim(); + if (value) nextFilters.set(name, value); + else nextFilters.delete(name); + }); + navigate(catalogPath(nextFilters)); + } + return (
@@ -823,12 +890,15 @@ function CatalogPage({

- +
+ +
+
+ {catalog.products.length} کالا در این صفحه + +
+ +
+
); } @@ -1267,9 +1507,11 @@ function ProfilePage({ onSignOut: () => void; }) { const [orders, setOrders] = useState([]); + const [summary, setSummary] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [page, setPage] = useState(1); + const [statusFilter, setStatusFilter] = useState(""); const [ordersResponse, setOrdersResponse] = useState( null, ); @@ -1280,14 +1522,27 @@ function ProfilePage({ } setLoading(true); setError(""); - fetchAuthenticated(`/api/v1/orders/?page=${page}`) - .then(async (response) => { - if (!response.ok) throw new Error(await getError(response)); - return response.json() as Promise; + const params = new URLSearchParams({ page: String(page) }); + if (statusFilter) params.set("status", statusFilter); + Promise.all([ + fetchAuthenticated(`/api/v1/orders/?${params.toString()}`), + fetchAuthenticated("/api/v1/orders/summary/"), + ]) + .then(async ([ordersApiResponse, summaryApiResponse]) => { + if (!ordersApiResponse.ok) + throw new Error(await getError(ordersApiResponse)); + if (!summaryApiResponse.ok) + throw new Error(await getError(summaryApiResponse)); + const [ordersData, summaryData] = await Promise.all([ + ordersApiResponse.json() as Promise, + summaryApiResponse.json() as Promise, + ]); + return [ordersData, summaryData] as const; }) - .then((data) => { - setOrders(data.results); - setOrdersResponse(data); + .then(([ordersData, summaryData]) => { + setOrders(ordersData.results); + setOrdersResponse(ordersData); + setSummary(summaryData); }) .catch((reason) => setError( @@ -1297,7 +1552,7 @@ function ProfilePage({ ), ) .finally(() => setLoading(false)); - }, [page, user?.id]); + }, [page, statusFilter, user?.id]); if (!user) return ( {user.role === "admin" ? "پروفایل مدیر" : "پروفایل من"}

اطلاعات حساب و سفارش‌های ثبت‌شدهٔ خودت را اینجا ببین.

-
-
- -
-
-
-
شمارهٔ موبایل
-
{user.phone}
+
+
- - {user.role === "admin" && ( -
- - نمای کلی مدیریت - - - مدیریت سفارش‌ها - - - گفت‌وگوهای پشتیبانی + {user.role === "admin" ? "حساب مدیر" : "حساب کاربری"} + {user.phone} + + {user.role === "admin" ? ( +
+ + نمای کلی مدیریت + + + مدیریت سفارش‌ها + + + گفت‌وگوهای پشتیبانی + +
+ ) : ( + + گفت‌وگو با پشتیبانی -
- )} - {user.role === "customer" && ( - - گفت‌وگو با پشتیبانی - - )} -
-
-
-
-

پیگیری خرید

-

سفارش‌های من

-
- {ordersResponse?.count ?? 0} سفارش -
- {loading ? ( -

در حال دریافت سفارش‌ها…

- ) : error ? ( -

{error}

- ) : !orders.length ? ( -

هنوز سفارشی ثبت نکرده‌ای.

- ) : ( -
- {orders.map((order) => ( -
-
-
- کد سفارش - {order.number} -
- - {orderStatusLabels[order.status] ?? order.status} - -
-
-
-
زمان ثبت
-
{formatDate(order.created_at)}
-
-
-
مبلغ
-
{formatPrice(order.subtotal)} تومان
-
- {order.status === "pending" && order.expires_at && ( -
-
مهلت پرداخت
-
{formatDate(order.expires_at)}
-
- )} -
-
    - {order.items.map((item) => ( -
  • - {item.product_name} - - {item.quantity} × {formatPrice(item.unit_price)} تومان - -
  • - ))} -
- {!!order.status_events.length && ( -
    - {order.status_events.map((event, index) => ( -
  1. - - {orderStatusLabels[event.to_status] ?? - event.to_status} - - -
  2. - ))} -
- )} -
- ))} -
- )} - {!loading && - !error && - ordersResponse && - (ordersResponse.next || ordersResponse.previous) && ( - )} -
+ + +
+
+
+ کل سفارش‌ها + {summary?.total ?? "—"} +
+
+ در انتظار پرداخت + {summary?.by_status.pending ?? "—"} +
+
+ در حال ارسال + {summary?.by_status.processing ?? "—"} +
+
+ ارسال‌شده + {summary?.by_status.shipped ?? "—"} +
+
+
+
+
+

پیگیری خرید

+

سفارش‌های من

+
+ {ordersResponse?.count ?? 0} سفارش +
+ {loading ? ( +

در حال دریافت سفارش‌ها…

+ ) : error ? ( +

{error}

+ ) : !orders.length ? ( +

سفارشی با این وضعیت وجود ندارد.

+ ) : ( +
+ {orders.map((order) => ( +
+
+
+ کد سفارش + {order.number} +
+ + {orderStatusLabels[order.status] ?? order.status} + +
+
+
+
زمان ثبت
+
{formatDate(order.created_at)}
+
+
+
مبلغ نهایی
+
{formatPrice(order.subtotal)} تومان
+
+
+
تعداد آیتم‌ها
+
{order.items.length} کالا
+
+ {order.status === "pending" && order.expires_at && ( +
+
مهلت پرداخت
+
{formatDate(order.expires_at)}
+
+ )} +
+
    + {order.items.map((item) => ( +
  • +
    + {item.product_name} + {item.product_sku} +
    + {item.quantity} عدد + {formatPrice(item.unit_price)} تومان + {formatPrice(item.line_total)} تومان +
  • + ))} +
+ {!!order.status_events.length && ( +
    + {order.status_events.map((event, index) => ( +
  1. + + {orderStatusLabels[event.to_status] ?? + event.to_status} + {event.changed_by_phone + ? ` — ${event.changed_by_phone}` + : ""} + + +
  2. + ))} +
+ )} +
+ ))} +
+ )} + {!loading && + !error && + ordersResponse && + (ordersResponse.next || ordersResponse.previous) && ( + + )} +
+
+ ); } @@ -2439,6 +2758,29 @@ function ProductPage({
{product.category.name}
+ {product.specifications && ( +
+ {Object.entries(product.specifications).map(([key, value]) => { + if (value === "" || value === undefined) return null; + const suffix = + key === "ram_gb" || key === "storage_gb" + ? " گیگابایت" + : key === "camera_megapixels" + ? " مگاپیکسل" + : key === "battery_mah" + ? " میلی‌آمپرساعت" + : key === "display_size_inches" + ? " اینچ" + : ""; + return ( +
+
{specificationLabels[key] ?? key}
+
{`${value}${suffix}`}
+
+ ); + })} +
+ )}
ضمانت اصالت کالا و امکان بازگشت طبق شرایط فروشگاه diff --git a/frontend/src/styles.css b/frontend/src/styles.css index c4a0c1f..1d5df5e 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1425,6 +1425,28 @@ footer small { font-size: 0.74rem; font-weight: 700; } +.product-specifications { + margin: 0 0 23px; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} +.product-specifications div { + padding: 11px 12px; + border: 1px solid #e4e9e1; + border-radius: 11px; + background: #fbfcf9; +} +.product-specifications dt { + color: #7d867d; + font-size: 0.64rem; +} +.product-specifications dd { + margin: 3px 0 0; + color: #315f47; + font-size: 0.74rem; + font-weight: 800; +} .detail-notice { padding: 13px; display: flex; @@ -1491,6 +1513,9 @@ footer small { .detail-meta { grid-template-columns: 1fr; } + .product-specifications { + grid-template-columns: 1fr; + } .product-detail-dialog { padding: 18px; } @@ -1521,6 +1546,94 @@ footer small { .profile-summary .profile-details { flex: 1; } +.profile-dashboard-layout { + display: grid; + grid-template-columns: 230px minmax(0, 1fr); + align-items: start; + gap: 22px; +} +.profile-sidebar { + position: sticky; + top: 22px; + padding: 22px; + display: grid; + justify-items: start; + gap: 9px; + border: 1px solid #e2e8df; + border-radius: 17px; + background: #fffefa; + box-shadow: 0 12px 30px #2532290a; +} +.profile-sidebar > strong { + margin-top: 4px; + color: #2d4736; + font-size: 0.9rem; +} +.profile-sidebar > span { + color: #778278; + font-size: 0.68rem; +} +.profile-navigation { + width: 100%; + margin: 15px 0 3px; + padding: 10px 0; + display: grid; + gap: 4px; + border-top: 1px solid #edf0ea; + border-bottom: 1px solid #edf0ea; +} +.profile-navigation button { + min-height: 37px; + padding: 0 9px; + border: 0; + border-radius: 8px; + color: #647066; + background: transparent; + cursor: pointer; + text-align: right; + font: + 700 0.68rem Vazirmatn, + Tahoma, + sans-serif; +} +.profile-navigation button:hover, +.profile-navigation button.active { + color: #315f47; + background: #eef5eb; +} +.profile-sidebar .admin-dashboard-link, +.profile-sidebar .signout-button { + width: 100%; + margin-top: 0; +} +.profile-dashboard-content { + min-width: 0; + display: grid; + gap: 20px; +} +.profile-overview-cards { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 11px; +} +.profile-overview-cards div { + min-height: 93px; + padding: 15px; + display: grid; + align-content: space-between; + border: 1px solid #e1e8de; + border-radius: 14px; + background: linear-gradient(135deg, #fffefa, #f4f8f2); +} +.profile-overview-cards span { + color: #748075; + font-size: 0.65rem; + line-height: 1.7; +} +.profile-overview-cards strong { + color: #315f47; + font-size: 1.2rem; +} .orders-section { padding: 25px; border: 1px solid #e8ebe3; @@ -1620,6 +1733,46 @@ footer small { color: #5d695f; font-size: 0.72rem; } +.order-line-items { + margin: 0; + padding: 0; + display: grid; + list-style: none; +} +.order-line-items li { + padding: 13px 0; + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto auto; + align-items: center; + gap: 14px; + border-bottom: 1px solid #edf0ea; + color: #647066; + font-size: 0.68rem; +} +.order-line-items li:last-child { + border-bottom: 0; +} +.order-line-items div { + min-width: 0; + display: grid; + gap: 3px; +} +.order-line-items div strong { + overflow: hidden; + color: #344338; + font-size: 0.72rem; + text-overflow: ellipsis; + white-space: nowrap; +} +.order-line-items small { + color: #909a91; + font-size: 0.59rem; +} +.order-line-items > strong { + color: #315f47; + font-size: 0.68rem; + white-space: nowrap; +} .orders-state { margin: 0; padding: 24px 0 4px; @@ -2187,6 +2340,142 @@ footer small { border-color: #315f47; background: #315f47; } +.catalog-layout { + display: grid; + grid-template-columns: minmax(235px, 0.28fr) minmax(0, 1fr); + align-items: start; + gap: 22px; +} +.catalog-filters { + position: sticky; + top: 22px; + padding: 19px; + border: 1px solid #e0e6dd; + border-radius: 17px; + background: #fffefa; + box-shadow: 0 12px 30px #2532290a; +} +.catalog-filters-heading, +.catalog-results-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.catalog-filters-heading h2 { + margin: 4px 0 0; + color: #26382b; + font-size: 1rem; +} +.catalog-filters-heading button { + border: 0; + color: #8a5d4e; + background: transparent; + cursor: pointer; + font: + 700 0.68rem Vazirmatn, + Tahoma, + sans-serif; +} +.product-type-filter { + margin: 18px 0; + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 5px; +} +.product-type-filter button { + min-height: 34px; + border: 1px solid #dfe6dc; + border-radius: 8px; + color: #667368; + background: #f8faf7; + cursor: pointer; + font: + 700 0.64rem Vazirmatn, + Tahoma, + sans-serif; +} +.product-type-filter button.active { + color: #fff; + border-color: #315f47; + background: #315f47; +} +.catalog-filters form { + display: grid; + gap: 12px; +} +.catalog-filters label { + display: grid; + gap: 5px; + color: #657168; + font-size: 0.67rem; + font-weight: 700; +} +.catalog-filters input, +.catalog-filters select, +.catalog-results-heading select { + min-width: 0; + min-height: 38px; + padding: 0 10px; + border: 1px solid #dbe3d8; + border-radius: 9px; + color: #344338; + background: #fff; + font: + 0.68rem Vazirmatn, + Tahoma, + sans-serif; +} +.catalog-filters input:focus, +.catalog-filters select:focus, +.catalog-results-heading select:focus { + outline: 0; + border-color: #527b60; + box-shadow: 0 0 0 3px #4c7b5518; +} +.price-filter-row { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} +.catalog-filters .stock-filter { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; +} +.catalog-filters .stock-filter input { + min-height: auto; + accent-color: #315f47; +} +.catalog-filter-submit { + min-height: 41px; + border: 0; + border-radius: 10px; + color: #fff; + background: #315f47; + cursor: pointer; + font: + 700 0.72rem Vazirmatn, + Tahoma, + sans-serif; +} +.catalog-results { + min-width: 0; +} +.catalog-results-heading { + min-height: 48px; + margin-bottom: 15px; + padding: 0 2px; + color: #6e796f; + font-size: 0.72rem; +} +.catalog-results-heading label { + display: flex; + align-items: center; + gap: 8px; + font-weight: 700; +} .breadcrumbs { display: flex; flex-wrap: wrap; @@ -2246,6 +2535,12 @@ footer small { .product-page .detail-content { padding: 26px 0 4px; } + .catalog-layout { + grid-template-columns: 1fr; + } + .catalog-filters { + position: static; + } } .add-to-cart-button, @@ -2417,6 +2712,42 @@ footer small { line-height: 1.8; } @media (max-width: 760px) { + .profile-dashboard-layout { + grid-template-columns: 1fr; + } + .profile-sidebar { + position: static; + grid-template-columns: auto 1fr; + column-gap: 14px; + } + .profile-sidebar > strong { + margin: 0; + } + .profile-sidebar > span { + grid-column: 2; + } + .profile-navigation { + grid-column: 1 / -1; + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .profile-sidebar .admin-dashboard-link, + .profile-sidebar .signout-button { + grid-column: span 1; + } + .profile-overview-cards { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .order-line-items li { + grid-template-columns: minmax(0, 1fr) auto; + gap: 8px 14px; + } + .order-line-items li > span:nth-of-type(1) { + grid-column: 1; + } + .order-line-items li > span:nth-of-type(2), + .order-line-items li > strong { + grid-column: 2; + } .cart-page { padding: 42px 20px 65px; } @@ -2435,6 +2766,25 @@ footer small { } } @media (max-width: 460px) { + .profile-sidebar { + grid-template-columns: 1fr; + } + .profile-sidebar > span { + grid-column: 1; + } + .profile-navigation { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .profile-overview-cards { + grid-template-columns: 1fr; + } + .orders-section { + padding: 18px; + } + .orders-heading { + align-items: start; + flex-direction: column; + } .cart-item { grid-template-columns: 75px minmax(0, 1fr); }