From e95c04b6cafe997a546ec53d86f246f6f6e27db1 Mon Sep 17 00:00:00 2001 From: Saeed Date: Tue, 18 Aug 2026 16:43:56 +0330 Subject: [PATCH] feat: add product reviews and ratings --- backend/apps/catalog/admin.py | 10 + .../catalog/migrations/0004_productreview.py | 79 +++++ backend/apps/catalog/models.py | 56 ++++ backend/apps/catalog/serializers.py | 105 +++++++ backend/apps/catalog/tests/test_api.py | 93 ++++++ backend/apps/catalog/urls.py | 12 +- backend/apps/catalog/views.py | 73 ++++- frontend/src/main.tsx | 297 ++++++++++++++++++ frontend/src/styles.css | 259 +++++++++++++++ 9 files changed, 980 insertions(+), 4 deletions(-) create mode 100644 backend/apps/catalog/migrations/0004_productreview.py diff --git a/backend/apps/catalog/admin.py b/backend/apps/catalog/admin.py index 5a5baeb..bd31913 100644 --- a/backend/apps/catalog/admin.py +++ b/backend/apps/catalog/admin.py @@ -6,6 +6,7 @@ MobileSpecification, Product, ProductImage, + ProductReview, ) @@ -53,3 +54,12 @@ class ProductAdmin(admin.ModelAdmin): search_fields = ("name", "sku", "slug") prepopulated_fields = {"slug": ("name",)} inlines = (ProductImageInline, LaptopSpecificationInline, MobileSpecificationInline) + + +@admin.register(ProductReview) +class ProductReviewAdmin(admin.ModelAdmin): + list_display = ("product", "user", "parent", "rating", "created_at") + list_filter = ("rating", "created_at") + search_fields = ("product__name", "user__phone", "body") + autocomplete_fields = ("product", "user", "parent") + readonly_fields = ("created_at", "updated_at") diff --git a/backend/apps/catalog/migrations/0004_productreview.py b/backend/apps/catalog/migrations/0004_productreview.py new file mode 100644 index 0000000..843546d --- /dev/null +++ b/backend/apps/catalog/migrations/0004_productreview.py @@ -0,0 +1,79 @@ +# Generated by Django 6.0.7 on 2026-08-18 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("catalog", "0003_product_brand_product_product_type_and_more"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="ProductReview", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ("body", models.TextField(max_length=1500)), + ("rating", models.PositiveSmallIntegerField(blank=True, null=True)), + ( + "parent", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + related_name="replies", + to="catalog.productreview", + ), + ), + ( + "product", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="reviews", + to="catalog.product", + ), + ), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="product_reviews", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={"ordering": ("-created_at", "-id")}, + ), + migrations.AddConstraint( + model_name="productreview", + constraint=models.CheckConstraint( + condition=models.Q( + ("rating__isnull", True), + models.Q(("rating__gte", 1), ("rating__lte", 5)), + _connector="OR", + ), + name="catalog_review_rating_between_one_and_five", + ), + ), + migrations.AddConstraint( + model_name="productreview", + constraint=models.UniqueConstraint( + condition=models.Q(("parent__isnull", True)), + fields=("product", "user"), + name="catalog_one_root_review_per_customer", + ), + ), + ] diff --git a/backend/apps/catalog/models.py b/backend/apps/catalog/models.py index 89db6e0..9315538 100644 --- a/backend/apps/catalog/models.py +++ b/backend/apps/catalog/models.py @@ -1,5 +1,6 @@ from decimal import Decimal +from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.db.models import F, Q @@ -152,3 +153,58 @@ class Meta: def __str__(self) -> str: return f"{self.product.name} image" + + +class ProductReview(TimeStampedModel): + product = models.ForeignKey( + Product, on_delete=models.CASCADE, related_name="reviews" + ) + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="product_reviews", + ) + parent = models.ForeignKey( + "self", + null=True, + blank=True, + on_delete=models.CASCADE, + related_name="replies", + ) + body = models.TextField(max_length=1500) + rating = models.PositiveSmallIntegerField(null=True, blank=True) + + class Meta: + ordering = ("-created_at", "-id") + constraints = [ + models.CheckConstraint( + condition=Q(rating__isnull=True) | Q(rating__gte=1, rating__lte=5), + name="catalog_review_rating_between_one_and_five", + ), + models.UniqueConstraint( + fields=("product", "user"), + condition=Q(parent__isnull=True), + name="catalog_one_root_review_per_customer", + ), + ] + + def clean(self) -> None: + super().clean() + if self.rating is not None and not 1 <= self.rating <= 5: + raise ValidationError({"rating": "Rating must be between 1 and 5."}) + if self.parent_id: + if self.parent.product_id != self.product_id: + raise ValidationError( + {"parent": "Reply must belong to the same product."} + ) + if self.parent.parent_id: + raise ValidationError( + {"parent": "Replies can only target a root review."} + ) + if self.rating is not None: + raise ValidationError({"rating": "Replies cannot have a rating."}) + elif self.rating is None: + raise ValidationError({"rating": "A product review must include a rating."}) + + def __str__(self) -> str: + return f"Review for {self.product} by {self.user}" diff --git a/backend/apps/catalog/serializers.py b/backend/apps/catalog/serializers.py index 0ea5811..5fdb321 100644 --- a/backend/apps/catalog/serializers.py +++ b/backend/apps/catalog/serializers.py @@ -1,3 +1,4 @@ +from django.db.models import Avg, Count from rest_framework import serializers from .models import ( @@ -6,6 +7,7 @@ MobileSpecification, Product, ProductImage, + ProductReview, ) @@ -62,12 +64,14 @@ def get_primary_image(self, product: Product) -> str | None: class ProductDetailSerializer(ProductListSerializer): images = ProductImageSerializer(many=True, read_only=True) specifications = serializers.SerializerMethodField() + rating_summary = serializers.SerializerMethodField() class Meta(ProductListSerializer.Meta): fields = ProductListSerializer.Meta.fields + ( "description", "sku", "specifications", + "rating_summary", "images", ) @@ -82,6 +86,15 @@ def get_specifications(self, product: Product) -> dict | None: return None return MobileSpecificationSerializer(specification).data + def get_rating_summary(self, product: Product) -> dict[str, float | int]: + summary = product.reviews.filter(parent__isnull=True).aggregate( + average=Avg("rating"), count=Count("id") + ) + return { + "average": round(float(summary["average"] or 0), 1), + "count": summary["count"], + } + class LaptopSpecificationSerializer(serializers.ModelSerializer): class Meta: @@ -105,3 +118,95 @@ class Meta: "network", "battery_mah", ) + + +class ProductReviewReplySerializer(serializers.ModelSerializer): + author_label = serializers.SerializerMethodField() + + class Meta: + model = ProductReview + fields = ("id", "body", "author_label", "created_at") + + def get_author_label(self, review: ProductReview) -> str: + if review.user.is_admin: + return "پشتیبانی فروشگاه" + return f"کاربر {review.user.phone[-4:]}" + + +class ProductReviewSerializer(serializers.ModelSerializer): + author_label = serializers.SerializerMethodField() + replies = serializers.SerializerMethodField() + + class Meta: + model = ProductReview + fields = ("id", "body", "rating", "author_label", "created_at", "replies") + + def get_author_label(self, review: ProductReview) -> str: + if review.user.is_admin: + return "پشتیبانی فروشگاه" + return f"کاربر {review.user.phone[-4:]}" + + def get_replies(self, review: ProductReview) -> list[dict]: + return ProductReviewReplySerializer(review.replies.all(), many=True).data + + +class ProductReviewCreateSerializer(serializers.ModelSerializer): + parent = serializers.PrimaryKeyRelatedField( + queryset=ProductReview.objects.select_related("product"), + required=False, + allow_null=True, + ) + + class Meta: + model = ProductReview + fields = ("body", "rating", "parent") + + def validate_body(self, value: str) -> str: + value = value.strip() + if not value: + raise serializers.ValidationError("Comment text cannot be empty.") + return value + + def validate_rating(self, value: int | None) -> int | None: + if value is not None and not 1 <= value <= 5: + raise serializers.ValidationError("Rating must be between 1 and 5.") + return value + + def validate(self, attrs: dict) -> dict: + product: Product = self.context["product"] + request = self.context["request"] + parent = attrs.get("parent") + rating = attrs.get("rating") + + if parent is not None: + if parent.product_id != product.id: + raise serializers.ValidationError( + {"parent": "Reply must belong to the current product."} + ) + if parent.parent_id: + raise serializers.ValidationError( + {"parent": "Replies can only target a root review."} + ) + if rating is not None: + raise serializers.ValidationError( + {"rating": "Replies cannot have a rating."} + ) + else: + if rating is None: + raise serializers.ValidationError( + {"rating": "A rating between 1 and 5 is required."} + ) + if ProductReview.objects.filter( + product=product, user=request.user, parent__isnull=True + ).exists(): + raise serializers.ValidationError( + {"detail": "You have already reviewed this product."} + ) + return attrs + + def create(self, validated_data: dict) -> ProductReview: + return ProductReview.objects.create( + product=self.context["product"], + user=self.context["request"].user, + **validated_data, + ) diff --git a/backend/apps/catalog/tests/test_api.py b/backend/apps/catalog/tests/test_api.py index 9984c77..7e0b45b 100644 --- a/backend/apps/catalog/tests/test_api.py +++ b/backend/apps/catalog/tests/test_api.py @@ -3,12 +3,14 @@ import pytest from rest_framework.test import APIClient +from apps.accounts.models import User from apps.catalog.models import ( Category, LaptopSpecification, MobileSpecification, Product, ProductImage, + ProductReview, ) @@ -165,3 +167,94 @@ def test_product_api_rejects_invalid_filter_values() -> None: assert response.status_code == 400 assert "network" in response.data + + +@pytest.mark.django_db +def test_product_reviews_require_authentication_and_expose_rating_summary() -> None: + category = Category.objects.create(name="Laptops", slug="laptops") + product = create_product(category, slug="reviewed-laptop") + customer = User.objects.create_user(phone="989121234567") + client = APIClient() + + anonymous_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "A well-balanced laptop.", "rating": 5}, + ) + + assert anonymous_response.status_code == 401 + + client.force_authenticate(customer) + create_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "A well-balanced laptop.", "rating": 5}, + ) + duplicate_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "A second root review.", "rating": 4}, + ) + invalid_rating_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "A bad rating.", "rating": 6}, + ) + detail_response = APIClient().get(f"/api/v1/catalog/products/{product.slug}/") + + assert create_response.status_code == 201 + assert create_response.data["author_label"] == "کاربر 4567" + assert duplicate_response.status_code == 400 + assert invalid_rating_response.status_code == 400 + assert detail_response.data["rating_summary"] == {"average": 5.0, "count": 1} + + +@pytest.mark.django_db +def test_product_review_reply_is_limited_to_the_same_root_review() -> None: + category = Category.objects.create(name="Mobiles", slug="mobiles") + product = create_product(category, slug="reviewed-mobile") + other_product = create_product(category, slug="other-mobile") + author = User.objects.create_user(phone="989121234567") + responder = User.objects.create_user(phone="989198765432") + root_review = ProductReview.objects.create( + product=product, + user=author, + body="Battery life is great.", + rating=4, + ) + client = APIClient() + client.force_authenticate(responder) + + reply_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "Thanks for the useful review.", "parent": root_review.id}, + ) + invalid_rating_response = client.post( + f"/api/v1/catalog/products/{product.slug}/reviews/", + {"body": "This cannot be rated.", "parent": root_review.id, "rating": 5}, + ) + invalid_product_response = client.post( + f"/api/v1/catalog/products/{other_product.slug}/reviews/", + {"body": "This targets another product.", "parent": root_review.id}, + ) + list_response = APIClient().get(f"/api/v1/catalog/products/{product.slug}/reviews/") + + assert reply_response.status_code == 201 + assert invalid_rating_response.status_code == 400 + assert invalid_product_response.status_code == 400 + assert list_response.status_code == 200 + assert list_response.data["results"] == [ + { + "id": root_review.id, + "body": "Battery life is great.", + "rating": 4, + "author_label": "کاربر 4567", + "created_at": list_response.data["results"][0]["created_at"], + "replies": [ + { + "id": reply_response.data["id"], + "body": "Thanks for the useful review.", + "author_label": "کاربر 5432", + "created_at": list_response.data["results"][0]["replies"][0][ + "created_at" + ], + } + ], + } + ] diff --git a/backend/apps/catalog/urls.py b/backend/apps/catalog/urls.py index f2662ad..075623a 100644 --- a/backend/apps/catalog/urls.py +++ b/backend/apps/catalog/urls.py @@ -1,12 +1,22 @@ from django.urls import path -from .views import CategoryListAPIView, ProductDetailAPIView, ProductListAPIView +from .views import ( + CategoryListAPIView, + ProductDetailAPIView, + ProductListAPIView, + ProductReviewListCreateAPIView, +) app_name = "catalog" urlpatterns = [ path("categories/", CategoryListAPIView.as_view(), name="category-list"), path("products/", ProductListAPIView.as_view(), name="product-list"), + path( + "products//reviews/", + ProductReviewListCreateAPIView.as_view(), + name="product-review-list-create", + ), path( "products//", ProductDetailAPIView.as_view(), name="product-detail" ), diff --git a/backend/apps/catalog/views.py b/backend/apps/catalog/views.py index 3e6a9d4..999e3f0 100644 --- a/backend/apps/catalog/views.py +++ b/backend/apps/catalog/views.py @@ -1,14 +1,21 @@ from decimal import Decimal, InvalidOperation -from django.db.models import Q +from django.db import IntegrityError +from django.db.models import Prefetch, Q +from django.shortcuts import get_object_or_404 +from rest_framework import status from rest_framework.exceptions import ValidationError -from rest_framework.generics import ListAPIView, RetrieveAPIView +from rest_framework.generics import ListAPIView, ListCreateAPIView, RetrieveAPIView +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.response import Response -from .models import Category, MobileSpecification, Product +from .models import Category, MobileSpecification, Product, ProductReview from .serializers import ( CategorySerializer, ProductDetailSerializer, ProductListSerializer, + ProductReviewCreateSerializer, + ProductReviewSerializer, ) @@ -131,3 +138,63 @@ class ProductDetailAPIView(RetrieveAPIView): .select_related("laptop_specification", "mobile_specification") .prefetch_related("images") ) + + +class ProductReviewListCreateAPIView(ListCreateAPIView): + permission_classes = (AllowAny,) + + def get_permissions(self): + if self.request.method == "POST": + return (IsAuthenticated(),) + return super().get_permissions() + + def get_product(self) -> Product: + if not hasattr(self, "_product"): + self._product = get_object_or_404( + Product.objects.filter( + status=Product.Status.PUBLISHED, + category__is_active=True, + ), + slug=self.kwargs["slug"], + ) + return self._product + + def get_queryset(self): + return ( + ProductReview.objects.filter( + product=self.get_product(), parent__isnull=True + ) + .select_related("user") + .prefetch_related( + Prefetch( + "replies", + queryset=ProductReview.objects.select_related("user").order_by( + "created_at", "id" + ), + ) + ) + ) + + def get_serializer_class(self): + if self.request.method == "POST": + return ProductReviewCreateSerializer + return ProductReviewSerializer + + def get_serializer_context(self): + context = super().get_serializer_context() + context["product"] = self.get_product() + return context + + def create(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + try: + review = serializer.save() + except IntegrityError as error: + raise ValidationError( + {"detail": "You have already reviewed this product."} + ) from error + response_serializer = ProductReviewSerializer( + review, context=self.get_serializer_context() + ) + return Response(response_serializer.data, status=status.HTTP_201_CREATED) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index a1f62c6..f23642d 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -55,8 +55,29 @@ type ProductDetail = Product & { network?: "4g" | "5g"; battery_mah?: number; } | null; + rating_summary: { average: number; count: number }; images: { id: number; image_url: string | null; alt_text: string }[]; }; +type ProductReviewReply = { + id: number; + body: string; + author_label: string; + created_at: string; +}; +type ProductReview = { + id: number; + body: string; + rating: number; + author_label: string; + created_at: string; + replies: ProductReviewReply[]; +}; +type ProductReviewsResponse = { + count: number; + next: string | null; + previous: string | null; + results: ProductReview[]; +}; type CartItem = { id: number; product: Product; @@ -2625,12 +2646,280 @@ function AdminChatPage({ user }: { user: AuthUser | null }) { ); } +function ProductReviews({ + slug, + initialSummary, + user, + onSignIn, +}: { + slug: string; + initialSummary: ProductDetail["rating_summary"]; + user: AuthUser | null; + onSignIn: () => void; +}) { + const [reviews, setReviews] = useState(null); + const [summary, setSummary] = useState(initialSummary); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + const [body, setBody] = useState(""); + const [rating, setRating] = useState(5); + const [replyTo, setReplyTo] = useState(null); + const [replyBody, setReplyBody] = useState(""); + const [pending, setPending] = useState(false); + const [refreshKey, setRefreshKey] = useState(0); + + useEffect(() => { + setSummary(initialSummary); + }, [initialSummary]); + + useEffect(() => { + const controller = new AbortController(); + setLoading(true); + setError(""); + fetch( + `${apiBaseUrl}/api/v1/catalog/products/${encodeURIComponent(slug)}/reviews/`, + { signal: controller.signal }, + ) + .then((response) => (response.ok ? response.json() : Promise.reject())) + .then((data: ProductReviewsResponse) => setReviews(data)) + .catch((reason) => { + if (!(reason instanceof DOMException && reason.name === "AbortError")) { + setError("دریافت نظرها ناموفق بود."); + } + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false); + }); + return () => controller.abort(); + }, [slug, refreshKey]); + + async function submitReview(event: FormEvent) { + event.preventDefault(); + if (!user) { + onSignIn(); + return; + } + setPending(true); + setError(""); + try { + const response = await fetchAuthenticated( + `/api/v1/catalog/products/${encodeURIComponent(slug)}/reviews/`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ body, rating }), + }, + ); + if (!response.ok) throw new Error(await getError(response)); + const nextCount = summary.count + 1; + setSummary({ + average: Number( + ((summary.average * summary.count + rating) / nextCount).toFixed(1), + ), + count: nextCount, + }); + setBody(""); + setRating(5); + setRefreshKey((value) => value + 1); + } catch (reason) { + setError( + reason instanceof Error ? reason.message : "ثبت نظر ناموفق بود.", + ); + } finally { + setPending(false); + } + } + + async function submitReply( + event: FormEvent, + parent: number, + ) { + event.preventDefault(); + if (!user) { + onSignIn(); + return; + } + setPending(true); + setError(""); + try { + const response = await fetchAuthenticated( + `/api/v1/catalog/products/${encodeURIComponent(slug)}/reviews/`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ body: replyBody, parent }), + }, + ); + if (!response.ok) throw new Error(await getError(response)); + setReplyTo(null); + setReplyBody(""); + setRefreshKey((value) => value + 1); + } catch (reason) { + setError( + reason instanceof Error ? reason.message : "ثبت پاسخ ناموفق بود.", + ); + } finally { + setPending(false); + } + } + + return ( +
+
+
+

تجربه خریداران

+

نظرها و امتیاز کاربران

+
+
+ {summary.average.toLocaleString("fa-IR")} + ★ از ۵ + {summary.count.toLocaleString("fa-IR")} نظر +
+
+ + {!user ? ( +
+

برای ثبت نظر یا پاسخ، ابتدا وارد حساب کاربری شوید.

+ +
+ ) : ( +
+