diff --git a/backend/apps/accounts/admin.py b/backend/apps/accounts/admin.py index baf4ba0..5de8eaf 100644 --- a/backend/apps/accounts/admin.py +++ b/backend/apps/accounts/admin.py @@ -9,11 +9,34 @@ class CustomUserAdmin(UserAdmin): model = User ordering = ("-joined_at",) - list_display = ("phone", "role", "is_staff", "is_active", "joined_at") + list_display = ( + "phone", + "display_name", + "email", + "role", + "is_staff", + "is_active", + "joined_at", + ) list_filter = ("role", "is_staff", "is_active") search_fields = ("phone",) fieldsets = ( - (None, {"fields": ("phone", "password")}), + ( + None, + { + "fields": ( + "phone", + "display_name", + "email", + "birth_date", + "province", + "city", + "home_address", + "postal_code", + "password", + ) + }, + ), (_("Role"), {"fields": ("role",)}), ( _("Permissions"), @@ -37,6 +60,13 @@ class CustomUserAdmin(UserAdmin): "classes": ("wide",), "fields": ( "phone", + "display_name", + "email", + "birth_date", + "province", + "city", + "home_address", + "postal_code", "role", "password1", "password2", diff --git a/backend/apps/accounts/migrations/0003_user_display_name.py b/backend/apps/accounts/migrations/0003_user_display_name.py new file mode 100644 index 0000000..64562b0 --- /dev/null +++ b/backend/apps/accounts/migrations/0003_user_display_name.py @@ -0,0 +1,15 @@ +# Generated by Django 6.0.7 on 2026-08-18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [("accounts", "0002_otpchallenge")] + + operations = [ + migrations.AddField( + model_name="user", + name="display_name", + field=models.CharField(blank=True, max_length=80), + ) + ] diff --git a/backend/apps/accounts/migrations/0004_user_profile_fields.py b/backend/apps/accounts/migrations/0004_user_profile_fields.py new file mode 100644 index 0000000..46dc520 --- /dev/null +++ b/backend/apps/accounts/migrations/0004_user_profile_fields.py @@ -0,0 +1,40 @@ +# Generated by Django 6.0.7 on 2026-08-18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [("accounts", "0003_user_display_name")] + + operations = [ + migrations.AddField( + model_name="user", + name="birth_date", + field=models.DateField(blank=True, null=True), + ), + migrations.AddField( + model_name="user", + name="city", + field=models.CharField(blank=True, max_length=80), + ), + migrations.AddField( + model_name="user", + name="email", + field=models.EmailField(blank=True, max_length=254), + ), + migrations.AddField( + model_name="user", + name="home_address", + field=models.TextField(blank=True), + ), + migrations.AddField( + model_name="user", + name="postal_code", + field=models.CharField(blank=True, max_length=10), + ), + migrations.AddField( + model_name="user", + name="province", + field=models.CharField(blank=True, max_length=80), + ), + ] diff --git a/backend/apps/accounts/models.py b/backend/apps/accounts/models.py index 3c74b5e..2c47f07 100644 --- a/backend/apps/accounts/models.py +++ b/backend/apps/accounts/models.py @@ -13,6 +13,13 @@ class Role(models.TextChoices): ADMIN = "admin", "Admin" phone = models.CharField(max_length=15, unique=True) + display_name = models.CharField(max_length=80, blank=True) + email = models.EmailField(blank=True) + birth_date = models.DateField(null=True, blank=True) + province = models.CharField(max_length=80, blank=True) + city = models.CharField(max_length=80, blank=True) + home_address = models.TextField(blank=True) + postal_code = models.CharField(max_length=10, blank=True) role = models.CharField(max_length=16, choices=Role.choices, default=Role.CUSTOMER) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) diff --git a/backend/apps/accounts/serializers.py b/backend/apps/accounts/serializers.py index b2c1e26..528e7d4 100644 --- a/backend/apps/accounts/serializers.py +++ b/backend/apps/accounts/serializers.py @@ -3,6 +3,7 @@ from rest_framework.exceptions import AuthenticationFailed from rest_framework_simplejwt.serializers import TokenObtainPairSerializer +from .models import User from .phone import normalize_iranian_mobile @@ -25,7 +26,41 @@ class OTPVerifySerializer(OTPRequestSerializer): class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) phone = serializers.CharField(read_only=True) + display_name = serializers.CharField(read_only=True) + email = serializers.EmailField(read_only=True) + birth_date = serializers.DateField(read_only=True) + province = serializers.CharField(read_only=True) + city = serializers.CharField(read_only=True) + home_address = serializers.CharField(read_only=True) + postal_code = serializers.CharField(read_only=True) role = serializers.CharField(read_only=True) + joined_at = serializers.DateTimeField(read_only=True) + + +class UserProfileSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ( + "display_name", + "email", + "birth_date", + "province", + "city", + "home_address", + "postal_code", + ) + + def validate_display_name(self, value: str) -> str: + return value.strip() + + def validate_email(self, value: str) -> str: + return value.strip().lower() + + def validate_postal_code(self, value: str) -> str: + value = value.strip() + if value and (not value.isdigit() or len(value) != 10): + raise serializers.ValidationError("Enter a 10-digit postal code.") + return value class AdminTokenObtainPairSerializer(TokenObtainPairSerializer): diff --git a/backend/apps/accounts/tests/test_otp_api.py b/backend/apps/accounts/tests/test_otp_api.py index fd4963e..134d901 100644 --- a/backend/apps/accounts/tests/test_otp_api.py +++ b/backend/apps/accounts/tests/test_otp_api.py @@ -72,6 +72,48 @@ def test_otp_verify_creates_user_returns_tokens_and_authenticates( assert client.get("/api/v1/auth/me/").status_code == 200 +@pytest.mark.django_db +def test_current_user_can_set_a_display_name(client: APIClient) -> None: + user = User.objects.create_user(phone="989121234567") + client.force_authenticate(user=user) + + response = client.patch("/api/v1/auth/me/", {"display_name": " سعید "}) + + assert response.status_code == 200 + assert response.data["display_name"] == "سعید" + user.refresh_from_db() + assert user.display_name == "سعید" + + +@pytest.mark.django_db +def test_current_user_can_update_profile_but_phone_is_read_only( + client: APIClient, +) -> None: + user = User.objects.create_user(phone="989121234567") + client.force_authenticate(user=user) + + response = client.patch( + "/api/v1/auth/me/", + { + "display_name": "سعید", + "email": "SaEed@example.com ", + "birth_date": "1995-04-12", + "province": "Tehran", + "city": "Tehran", + "home_address": "Example street", + "postal_code": "1234567890", + "phone": "989199999999", + }, + ) + + assert response.status_code == 200 + assert response.data["phone"] == "989121234567" + assert response.data["email"] == "saeed@example.com" + assert response.data["postal_code"] == "1234567890" + user.refresh_from_db() + assert str(user.birth_date) == "1995-04-12" + + @pytest.mark.django_db def test_otp_verify_invalidates_challenge_after_maximum_attempts( client: APIClient, diff --git a/backend/apps/accounts/views.py b/backend/apps/accounts/views.py index 9bd6deb..9313771 100644 --- a/backend/apps/accounts/views.py +++ b/backend/apps/accounts/views.py @@ -12,6 +12,7 @@ AdminTokenObtainPairSerializer, OTPRequestSerializer, OTPVerifySerializer, + UserProfileSerializer, UserSerializer, ) from .services import OTPInvalid, OTPRateLimited, request_otp, verify_otp @@ -84,3 +85,11 @@ class CurrentUserView(APIView): def get(self, request): return Response(UserSerializer(request.user).data) + + def patch(self, request): + serializer = UserProfileSerializer( + request.user, data=request.data, partial=True + ) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(UserSerializer(request.user).data) diff --git a/backend/apps/catalog/admin.py b/backend/apps/catalog/admin.py index bd31913..dd547ee 100644 --- a/backend/apps/catalog/admin.py +++ b/backend/apps/catalog/admin.py @@ -6,6 +6,7 @@ MobileSpecification, Product, ProductImage, + ProductRating, ProductReview, ) @@ -58,8 +59,17 @@ class ProductAdmin(admin.ModelAdmin): @admin.register(ProductReview) class ProductReviewAdmin(admin.ModelAdmin): - list_display = ("product", "user", "parent", "rating", "created_at") - list_filter = ("rating", "created_at") + list_display = ("product", "user", "parent", "moderation_status", "created_at") + list_filter = ("moderation_status", "created_at") search_fields = ("product__name", "user__phone", "body") autocomplete_fields = ("product", "user", "parent") readonly_fields = ("created_at", "updated_at") + + +@admin.register(ProductRating) +class ProductRatingAdmin(admin.ModelAdmin): + list_display = ("product", "user", "score", "updated_at") + list_filter = ("score", "updated_at") + search_fields = ("product__name", "user__phone") + autocomplete_fields = ("product", "user") + readonly_fields = ("created_at", "updated_at") diff --git a/backend/apps/catalog/migrations/0005_productrating_remove_productreview_rating_and_more.py b/backend/apps/catalog/migrations/0005_productrating_remove_productreview_rating_and_more.py new file mode 100644 index 0000000..c33484f --- /dev/null +++ b/backend/apps/catalog/migrations/0005_productrating_remove_productreview_rating_and_more.py @@ -0,0 +1,86 @@ +# 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 + + +def copy_review_ratings(apps, schema_editor): + ProductRating = apps.get_model("catalog", "ProductRating") + ProductReview = apps.get_model("catalog", "ProductReview") + + for review in ProductReview.objects.filter( + parent__isnull=True, rating__isnull=False + ).iterator(): + ProductRating.objects.update_or_create( + product_id=review.product_id, + user_id=review.user_id, + defaults={"score": review.rating}, + ) + + +class Migration(migrations.Migration): + dependencies = [ + ("catalog", "0004_productreview"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="ProductRating", + 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)), + ("score", models.PositiveSmallIntegerField()), + ( + "product", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="ratings", + to="catalog.product", + ), + ), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="product_ratings", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.RunPython(copy_review_ratings, migrations.RunPython.noop), + migrations.RemoveConstraint( + model_name="productreview", + name="catalog_review_rating_between_one_and_five", + ), + migrations.RemoveConstraint( + model_name="productreview", + name="catalog_one_root_review_per_customer", + ), + migrations.RemoveField(model_name="productreview", name="rating"), + migrations.AddConstraint( + model_name="productrating", + constraint=models.CheckConstraint( + condition=models.Q(("score__gte", 1), ("score__lte", 5)), + name="catalog_rating_between_one_and_five", + ), + ), + migrations.AddConstraint( + model_name="productrating", + constraint=models.UniqueConstraint( + fields=("product", "user"), + name="catalog_one_rating_per_customer", + ), + ), + ] diff --git a/backend/apps/catalog/migrations/0006_productreview_moderation_status.py b/backend/apps/catalog/migrations/0006_productreview_moderation_status.py new file mode 100644 index 0000000..74b380f --- /dev/null +++ b/backend/apps/catalog/migrations/0006_productreview_moderation_status.py @@ -0,0 +1,21 @@ +# Generated by Django 6.0.7 on 2026-08-18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("catalog", "0005_productrating_remove_productreview_rating_and_more") + ] + + operations = [ + migrations.AddField( + model_name="productreview", + name="moderation_status", + field=models.CharField( + choices=[("approved", "Approved"), ("rejected", "Rejected")], + default="approved", + max_length=16, + ), + ), + ] diff --git a/backend/apps/catalog/models.py b/backend/apps/catalog/models.py index 9315538..493ee6e 100644 --- a/backend/apps/catalog/models.py +++ b/backend/apps/catalog/models.py @@ -156,6 +156,10 @@ def __str__(self) -> str: class ProductReview(TimeStampedModel): + class ModerationStatus(models.TextChoices): + APPROVED = "approved", "Approved" + REJECTED = "rejected", "Rejected" + product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="reviews" ) @@ -172,26 +176,17 @@ class ProductReview(TimeStampedModel): related_name="replies", ) body = models.TextField(max_length=1500) - rating = models.PositiveSmallIntegerField(null=True, blank=True) + moderation_status = models.CharField( + max_length=16, + choices=ModerationStatus.choices, + default=ModerationStatus.APPROVED, + ) 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( @@ -201,10 +196,38 @@ def clean(self) -> None: 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}" + + +class ProductRating(TimeStampedModel): + product = models.ForeignKey( + Product, on_delete=models.CASCADE, related_name="ratings" + ) + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="product_ratings", + ) + score = models.PositiveSmallIntegerField() + + class Meta: + constraints = [ + models.CheckConstraint( + condition=Q(score__gte=1, score__lte=5), + name="catalog_rating_between_one_and_five", + ), + models.UniqueConstraint( + fields=("product", "user"), + name="catalog_one_rating_per_customer", + ), + ] + + def clean(self) -> None: + super().clean() + if not 1 <= self.score <= 5: + raise ValidationError({"score": "Rating must be between 1 and 5."}) + + def __str__(self) -> str: + return f"{self.score}/5 for {self.product} by {self.user}" diff --git a/backend/apps/catalog/permissions.py b/backend/apps/catalog/permissions.py new file mode 100644 index 0000000..bd2be7a --- /dev/null +++ b/backend/apps/catalog/permissions.py @@ -0,0 +1,9 @@ +from rest_framework.permissions import BasePermission + + +class IsPlatformAdmin(BasePermission): + message = "Administrator access is required." + + def has_permission(self, request, view) -> bool: + user = request.user + return bool(user and user.is_authenticated and user.is_admin and user.is_staff) diff --git a/backend/apps/catalog/serializers.py b/backend/apps/catalog/serializers.py index 5fdb321..8c373d3 100644 --- a/backend/apps/catalog/serializers.py +++ b/backend/apps/catalog/serializers.py @@ -7,10 +7,19 @@ MobileSpecification, Product, ProductImage, + ProductRating, ProductReview, ) +def product_rating_summary(product: Product) -> dict[str, float | int]: + summary = product.ratings.aggregate(average=Avg("score"), count=Count("id")) + return { + "average": round(float(summary["average"] or 0), 1), + "count": summary["count"], + } + + class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category @@ -87,13 +96,7 @@ def get_specifications(self, product: Product) -> dict | 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"], - } + return product_rating_summary(product) class LaptopSpecificationSerializer(serializers.ModelSerializer): @@ -128,9 +131,7 @@ class Meta: 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:]}" + return review.user.display_name or "کاربر" class ProductReviewSerializer(serializers.ModelSerializer): @@ -139,15 +140,81 @@ class ProductReviewSerializer(serializers.ModelSerializer): class Meta: model = ProductReview - fields = ("id", "body", "rating", "author_label", "created_at", "replies") + fields = ("id", "body", "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:]}" + return review.user.display_name or "کاربر" def get_replies(self, review: ProductReview) -> list[dict]: - return ProductReviewReplySerializer(review.replies.all(), many=True).data + return ProductReviewReplySerializer( + review.replies.filter( + moderation_status=ProductReview.ModerationStatus.APPROVED + ), + many=True, + ).data + + +class AdminProductSerializer(serializers.ModelSerializer): + class Meta: + model = Product + fields = ( + "id", + "category", + "product_type", + "brand", + "name", + "slug", + "sku", + "short_description", + "description", + "price", + "compare_at_price", + "stock_quantity", + "status", + "is_featured", + "created_at", + ) + read_only_fields = ("id", "created_at") + + +class AdminProductReviewSerializer(serializers.ModelSerializer): + product_name = serializers.CharField(source="product.name", read_only=True) + product_slug = serializers.CharField(source="product.slug", read_only=True) + customer_phone = serializers.CharField(source="user.phone", read_only=True) + customer_name = serializers.SerializerMethodField() + + class Meta: + model = ProductReview + fields = ( + "id", + "product_name", + "product_slug", + "customer_phone", + "customer_name", + "body", + "parent", + "moderation_status", + "created_at", + ) + read_only_fields = ( + "id", + "product_name", + "product_slug", + "customer_phone", + "customer_name", + "body", + "parent", + "created_at", + ) + + def get_customer_name(self, review: ProductReview) -> str: + return review.user.display_name or "کاربر" + + +class ProductReviewModerationSerializer(serializers.ModelSerializer): + class Meta: + model = ProductReview + fields = ("moderation_status",) class ProductReviewCreateSerializer(serializers.ModelSerializer): @@ -159,7 +226,7 @@ class ProductReviewCreateSerializer(serializers.ModelSerializer): class Meta: model = ProductReview - fields = ("body", "rating", "parent") + fields = ("body", "parent") def validate_body(self, value: str) -> str: value = value.strip() @@ -167,16 +234,14 @@ def validate_body(self, value: str) -> str: 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 "rating" in self.initial_data: + raise serializers.ValidationError( + {"rating": "Submit ratings through the product rating endpoint."} + ) if parent is not None: if parent.product_id != product.id: @@ -187,21 +252,6 @@ def validate(self, attrs: dict) -> dict: 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: @@ -210,3 +260,14 @@ def create(self, validated_data: dict) -> ProductReview: user=self.context["request"].user, **validated_data, ) + + +class ProductRatingSerializer(serializers.ModelSerializer): + class Meta: + model = ProductRating + fields = ("score",) + + def validate_score(self, value: int) -> int: + if not 1 <= value <= 5: + raise serializers.ValidationError("Rating must be between 1 and 5.") + return value diff --git a/backend/apps/catalog/tests/test_api.py b/backend/apps/catalog/tests/test_api.py index 7e0b45b..39e5272 100644 --- a/backend/apps/catalog/tests/test_api.py +++ b/backend/apps/catalog/tests/test_api.py @@ -170,39 +170,60 @@ def test_product_api_rejects_invalid_filter_values() -> None: @pytest.mark.django_db -def test_product_reviews_require_authentication_and_expose_rating_summary() -> None: +def test_product_reviews_allow_multiple_comments_and_ratings_are_independent() -> None: category = Category.objects.create(name="Laptops", slug="laptops") product = create_product(category, slug="reviewed-laptop") customer = User.objects.create_user(phone="989121234567") + other_customer = User.objects.create_user(phone="989198765432") client = APIClient() - anonymous_response = client.post( + anonymous_review = client.post( f"/api/v1/catalog/products/{product.slug}/reviews/", - {"body": "A well-balanced laptop.", "rating": 5}, + {"body": "A well-balanced laptop."}, + ) + anonymous_rating = client.put( + f"/api/v1/catalog/products/{product.slug}/rating/", {"score": 5} ) - assert anonymous_response.status_code == 401 + assert anonymous_review.status_code == 401 + assert anonymous_rating.status_code == 401 client.force_authenticate(customer) - create_response = client.post( + first_comment = client.post( f"/api/v1/catalog/products/{product.slug}/reviews/", - {"body": "A well-balanced laptop.", "rating": 5}, + {"body": "A well-balanced laptop."}, ) - duplicate_response = client.post( + second_comment = client.post( f"/api/v1/catalog/products/{product.slug}/reviews/", - {"body": "A second root review.", "rating": 4}, + {"body": "The screen is bright too."}, ) - invalid_rating_response = client.post( - f"/api/v1/catalog/products/{product.slug}/reviews/", - {"body": "A bad rating.", "rating": 6}, + first_rating = client.put( + f"/api/v1/catalog/products/{product.slug}/rating/", {"score": 5} + ) + updated_rating = client.put( + f"/api/v1/catalog/products/{product.slug}/rating/", {"score": 3} + ) + client.force_authenticate(other_customer) + other_rating = client.put( + f"/api/v1/catalog/products/{product.slug}/rating/", {"score": 4} ) 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} + assert first_comment.status_code == 201 + assert second_comment.status_code == 201 + assert first_comment.data["author_label"] == "کاربر" + assert first_rating.data == {"average": 5.0, "count": 1, "my_score": 5} + assert updated_rating.data == {"average": 3.0, "count": 1, "my_score": 3} + assert other_rating.data == {"average": 3.5, "count": 2, "my_score": 4} + assert detail_response.data["rating_summary"] == {"average": 3.5, "count": 2} + + customer.display_name = "سعید" + customer.save(update_fields=("display_name",)) + comments_response = APIClient().get( + f"/api/v1/catalog/products/{product.slug}/reviews/" + ) + + assert comments_response.data["results"][0]["author_label"] == "سعید" @pytest.mark.django_db @@ -216,7 +237,6 @@ def test_product_review_reply_is_limited_to_the_same_root_review() -> None: product=product, user=author, body="Battery life is great.", - rating=4, ) client = APIClient() client.force_authenticate(responder) @@ -243,14 +263,13 @@ def test_product_review_reply_is_limited_to_the_same_root_review() -> None: { "id": root_review.id, "body": "Battery life is great.", - "rating": 4, - "author_label": "کاربر 4567", + "author_label": "کاربر", "created_at": list_response.data["results"][0]["created_at"], "replies": [ { "id": reply_response.data["id"], "body": "Thanks for the useful review.", - "author_label": "کاربر 5432", + "author_label": "کاربر", "created_at": list_response.data["results"][0]["replies"][0][ "created_at" ], @@ -258,3 +277,64 @@ def test_product_review_reply_is_limited_to_the_same_root_review() -> None: ], } ] + + +@pytest.mark.django_db +def test_admin_can_create_products_and_moderate_reviews() -> None: + category = Category.objects.create(name="Laptops", slug="laptops") + customer = User.objects.create_user(phone="989121234567") + admin = User.objects.create_user( + phone="989198765432", role=User.Role.ADMIN, is_staff=True + ) + product = create_product(category, slug="reviewed-product") + review = ProductReview.objects.create( + product=product, user=customer, body="This should be moderated." + ) + client = APIClient() + + client.force_authenticate(customer) + assert ( + client.post( + "/api/v1/catalog/admin/products/", + { + "category": category.id, + "product_type": "laptop", + "name": "Unauthorized product", + "slug": "unauthorized-product", + "sku": "UNAUTHORIZED", + "price": "1000000", + }, + ).status_code + == 403 + ) + + client.force_authenticate(admin) + product_response = client.post( + "/api/v1/catalog/admin/products/", + { + "category": category.id, + "product_type": "laptop", + "name": "Admin product", + "slug": "admin-product", + "sku": "ADMIN-001", + "price": "1000000", + "stock_quantity": 2, + "status": "published", + }, + ) + reviews_response = client.get("/api/v1/catalog/admin/reviews/") + moderation_response = client.patch( + f"/api/v1/catalog/admin/reviews/{review.id}/", + {"moderation_status": "rejected"}, + ) + public_reviews = APIClient().get( + f"/api/v1/catalog/products/{product.slug}/reviews/" + ) + + assert product_response.status_code == 201 + assert product_response.data["slug"] == "admin-product" + assert reviews_response.status_code == 200 + assert reviews_response.data["results"][0]["moderation_status"] == "approved" + assert moderation_response.status_code == 200 + assert moderation_response.data["moderation_status"] == "rejected" + assert public_reviews.data["results"] == [] diff --git a/backend/apps/catalog/urls.py b/backend/apps/catalog/urls.py index 075623a..7f0bf1c 100644 --- a/backend/apps/catalog/urls.py +++ b/backend/apps/catalog/urls.py @@ -1,15 +1,34 @@ from django.urls import path from .views import ( + AdminProductCreateAPIView, + AdminProductReviewListAPIView, + AdminProductReviewModerationAPIView, CategoryListAPIView, ProductDetailAPIView, ProductListAPIView, + ProductRatingAPIView, ProductReviewListCreateAPIView, ) app_name = "catalog" urlpatterns = [ + path( + "admin/products/", + AdminProductCreateAPIView.as_view(), + name="admin-product-create", + ), + path( + "admin/reviews/", + AdminProductReviewListAPIView.as_view(), + name="admin-review-list", + ), + path( + "admin/reviews//", + AdminProductReviewModerationAPIView.as_view(), + name="admin-review-moderate", + ), path("categories/", CategoryListAPIView.as_view(), name="category-list"), path("products/", ProductListAPIView.as_view(), name="product-list"), path( @@ -17,6 +36,11 @@ ProductReviewListCreateAPIView.as_view(), name="product-review-list-create", ), + path( + "products//rating/", + ProductRatingAPIView.as_view(), + name="product-rating", + ), path( "products//", ProductDetailAPIView.as_view(), name="product-detail" ), diff --git a/backend/apps/catalog/views.py b/backend/apps/catalog/views.py index 999e3f0..06357c3 100644 --- a/backend/apps/catalog/views.py +++ b/backend/apps/catalog/views.py @@ -1,21 +1,32 @@ from decimal import Decimal, InvalidOperation -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, ListCreateAPIView, RetrieveAPIView +from rest_framework.generics import ( + CreateAPIView, + ListAPIView, + ListCreateAPIView, + RetrieveAPIView, +) from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response +from rest_framework.views import APIView from .models import Category, MobileSpecification, Product, ProductReview +from .permissions import IsPlatformAdmin from .serializers import ( + AdminProductReviewSerializer, + AdminProductSerializer, CategorySerializer, ProductDetailSerializer, ProductListSerializer, + ProductRatingSerializer, ProductReviewCreateSerializer, + ProductReviewModerationSerializer, ProductReviewSerializer, + product_rating_summary, ) @@ -162,7 +173,9 @@ def get_product(self) -> Product: def get_queryset(self): return ( ProductReview.objects.filter( - product=self.get_product(), parent__isnull=True + product=self.get_product(), + parent__isnull=True, + moderation_status=ProductReview.ModerationStatus.APPROVED, ) .select_related("user") .prefetch_related( @@ -188,13 +201,87 @@ def get_serializer_context(self): 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 + review = serializer.save() response_serializer = ProductReviewSerializer( review, context=self.get_serializer_context() ) return Response(response_serializer.data, status=status.HTTP_201_CREATED) + + +class ProductRatingAPIView(APIView): + permission_classes = (AllowAny,) + + def get_permissions(self): + if self.request.method in {"PUT", "PATCH"}: + 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(self, request, *args, **kwargs): + product = self.get_product() + response_data = product_rating_summary(product) + response_data["my_score"] = None + if request.user.is_authenticated: + response_data["my_score"] = ( + product.ratings.filter(user=request.user) + .values_list("score", flat=True) + .first() + ) + return Response(response_data) + + def put(self, request, *args, **kwargs): + serializer = ProductRatingSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + product = self.get_product() + rating, _ = product.ratings.update_or_create( + user=request.user, + defaults={"score": serializer.validated_data["score"]}, + ) + response_data = product_rating_summary(product) + response_data["my_score"] = rating.score + return Response(response_data) + + patch = put + + +class AdminProductCreateAPIView(CreateAPIView): + permission_classes = (IsPlatformAdmin,) + serializer_class = AdminProductSerializer + + +class AdminProductReviewListAPIView(ListAPIView): + permission_classes = (IsPlatformAdmin,) + serializer_class = AdminProductReviewSerializer + + def get_queryset(self): + queryset = ProductReview.objects.select_related("product", "user", "parent") + moderation_status = self.request.query_params.get("status", "").strip() + if moderation_status: + valid_statuses = { + choice for choice, _ in ProductReview.ModerationStatus.choices + } + if moderation_status not in valid_statuses: + raise ValidationError({"status": "Invalid review status."}) + queryset = queryset.filter(moderation_status=moderation_status) + return queryset + + +class AdminProductReviewModerationAPIView(APIView): + permission_classes = (IsPlatformAdmin,) + + def patch(self, request, review_id): + review = get_object_or_404(ProductReview, pk=review_id) + serializer = ProductReviewModerationSerializer(review, data=request.data) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(AdminProductReviewSerializer(review).data) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index f23642d..bd8a862 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -67,7 +67,6 @@ type ProductReviewReply = { type ProductReview = { id: number; body: string; - rating: number; author_label: string; created_at: string; replies: ProductReviewReply[]; @@ -78,6 +77,9 @@ type ProductReviewsResponse = { previous: string | null; results: ProductReview[]; }; +type ProductRatingResponse = ProductDetail["rating_summary"] & { + my_score: number | null; +}; type CartItem = { id: number; product: Product; @@ -100,7 +102,30 @@ type Address = { postal_code: string; is_default: boolean; }; -type AuthUser = { id: number; phone: string; role: "customer" | "admin" }; +type AuthUser = { + id: number; + phone: string; + display_name: string; + email: string; + birth_date: string | null; + province: string; + city: string; + home_address: string; + postal_code: string; + role: "customer" | "admin"; + joined_at: string; +}; +type AdminReview = { + id: number; + product_name: string; + product_slug: string; + customer_phone: string; + customer_name: string; + body: string; + parent: number | null; + moderation_status: "approved" | "rejected"; + created_at: string; +}; type AuthResponse = { access: string; refresh: string; user: AuthUser }; type OrderItem = { id: number; @@ -190,6 +215,7 @@ type Route = | { name: "profile" } | { name: "admin-dashboard" } | { name: "admin-orders" } + | { name: "admin-catalog" } | { name: "chat" } | { name: "admin-chat" } | { name: "not-found" }; @@ -225,6 +251,8 @@ function getRoute(): Route { return { name: "admin-dashboard" }; if (parts[0] === "admin" && parts[1] === "orders" && parts.length === 2) return { name: "admin-orders" }; + if (parts[0] === "admin" && parts[1] === "catalog" && parts.length === 2) + return { name: "admin-catalog" }; if (parts[0] === "chat" && parts.length === 1) return { name: "chat" }; if (parts[0] === "admin" && parts[1] === "chat" && parts.length === 2) return { name: "admin-chat" }; @@ -1523,9 +1551,11 @@ function formatDate(value: string) { function ProfilePage({ user, onSignOut, + onUserUpdated, }: { user: AuthUser | null; onSignOut: () => void; + onUserUpdated: (user: AuthUser) => void; }) { const [orders, setOrders] = useState([]); const [summary, setSummary] = useState(null); @@ -1536,6 +1566,28 @@ function ProfilePage({ const [ordersResponse, setOrdersResponse] = useState( null, ); + const [profile, setProfile] = useState({ + display_name: user?.display_name ?? "", + email: user?.email ?? "", + birth_date: user?.birth_date ?? "", + province: user?.province ?? "", + city: user?.city ?? "", + home_address: user?.home_address ?? "", + postal_code: user?.postal_code ?? "", + }); + const [profileMessage, setProfileMessage] = useState(""); + const [profilePending, setProfilePending] = useState(false); + useEffect(() => { + setProfile({ + display_name: user?.display_name ?? "", + email: user?.email ?? "", + birth_date: user?.birth_date ?? "", + province: user?.province ?? "", + city: user?.city ?? "", + home_address: user?.home_address ?? "", + postal_code: user?.postal_code ?? "", + }); + }, [user]); useEffect(() => { if (!user) { setLoading(false); @@ -1581,6 +1633,30 @@ function ProfilePage({ text="اطلاعات حساب و سفارش‌ها به حساب کاربری شما متصل هستند." /> ); + + async function updateProfile(event: FormEvent) { + event.preventDefault(); + setProfilePending(true); + setProfileMessage(""); + try { + const response = await fetchAuthenticated("/api/v1/auth/me/", { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(profile), + }); + if (!response.ok) throw new Error(await getError(response)); + const nextUser = (await response.json()) as AuthUser; + onUserUpdated(nextUser); + setProfileMessage("مشخصات پروفایل ذخیره شد."); + } catch (reason) { + setProfileMessage( + reason instanceof Error ? reason.message : "ذخیرهٔ پروفایل ناموفق بود.", + ); + } finally { + setProfilePending(false); + } + } + return (
@@ -1595,8 +1671,111 @@ function ProfilePage({
- {user.role === "admin" ? "حساب مدیر" : "حساب کاربری"} + {user.display_name || "کاربر"} {user.phone} + {user.role === "admin" ? "مدیر سامانه" : "کاربر"} +
+ + + + + + +