Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/apps/catalog/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
MobileSpecification,
Product,
ProductImage,
ProductReview,
)


Expand Down Expand Up @@ -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")
79 changes: 79 additions & 0 deletions backend/apps/catalog/migrations/0004_productreview.py
Original file line number Diff line number Diff line change
@@ -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",
),
),
]
56 changes: 56 additions & 0 deletions backend/apps/catalog/models.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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}"
105 changes: 105 additions & 0 deletions backend/apps/catalog/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.db.models import Avg, Count
from rest_framework import serializers

from .models import (
Expand All @@ -6,6 +7,7 @@
MobileSpecification,
Product,
ProductImage,
ProductReview,
)


Expand Down Expand Up @@ -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",
)

Expand All @@ -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:
Expand All @@ -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,
)
Loading
Loading