From d0992c5b9017221d65ddd8be945a037329e6df23 Mon Sep 17 00:00:00 2001 From: Saeed Date: Tue, 18 Aug 2026 17:53:58 +0330 Subject: [PATCH 1/2] feat: separate product ratings from reviews --- backend/apps/accounts/admin.py | 12 +- .../migrations/0003_user_display_name.py | 15 ++ backend/apps/accounts/models.py | 1 + backend/apps/accounts/serializers.py | 11 + backend/apps/accounts/tests/test_otp_api.py | 13 ++ backend/apps/accounts/views.py | 9 + backend/apps/catalog/admin.py | 14 +- ...ng_remove_productreview_rating_and_more.py | 86 +++++++ backend/apps/catalog/models.py | 50 ++-- backend/apps/catalog/serializers.py | 67 +++--- backend/apps/catalog/tests/test_api.py | 59 +++-- backend/apps/catalog/urls.py | 6 + backend/apps/catalog/views.py | 57 ++++- frontend/src/main.tsx | 219 ++++++++++++++---- frontend/src/styles.css | 76 +++++- 15 files changed, 550 insertions(+), 145 deletions(-) create mode 100644 backend/apps/accounts/migrations/0003_user_display_name.py create mode 100644 backend/apps/catalog/migrations/0005_productrating_remove_productreview_rating_and_more.py diff --git a/backend/apps/accounts/admin.py b/backend/apps/accounts/admin.py index baf4ba0..623ea59 100644 --- a/backend/apps/accounts/admin.py +++ b/backend/apps/accounts/admin.py @@ -9,11 +9,18 @@ class CustomUserAdmin(UserAdmin): model = User ordering = ("-joined_at",) - list_display = ("phone", "role", "is_staff", "is_active", "joined_at") + list_display = ( + "phone", + "display_name", + "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", "password")}), (_("Role"), {"fields": ("role",)}), ( _("Permissions"), @@ -37,6 +44,7 @@ class CustomUserAdmin(UserAdmin): "classes": ("wide",), "fields": ( "phone", + "display_name", "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/models.py b/backend/apps/accounts/models.py index 3c74b5e..c3cf43a 100644 --- a/backend/apps/accounts/models.py +++ b/backend/apps/accounts/models.py @@ -13,6 +13,7 @@ class Role(models.TextChoices): ADMIN = "admin", "Admin" phone = models.CharField(max_length=15, unique=True) + display_name = models.CharField(max_length=80, 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..0e1d9bc 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,9 +26,19 @@ 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) role = serializers.CharField(read_only=True) +class UserProfileSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ("display_name",) + + def validate_display_name(self, value: str) -> str: + return value.strip() + + class AdminTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) diff --git a/backend/apps/accounts/tests/test_otp_api.py b/backend/apps/accounts/tests/test_otp_api.py index fd4963e..5ba16fc 100644 --- a/backend/apps/accounts/tests/test_otp_api.py +++ b/backend/apps/accounts/tests/test_otp_api.py @@ -72,6 +72,19 @@ 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_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..69a9a71 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", "created_at") + list_filter = ("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/models.py b/backend/apps/catalog/models.py index 9315538..25fa8df 100644 --- a/backend/apps/catalog/models.py +++ b/backend/apps/catalog/models.py @@ -172,26 +172,12 @@ class ProductReview(TimeStampedModel): 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( @@ -201,10 +187,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/serializers.py b/backend/apps/catalog/serializers.py index 5fdb321..a040d98 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,12 +140,10 @@ 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 @@ -159,7 +158,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 +166,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 +184,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 +192,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..b871252 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" ], diff --git a/backend/apps/catalog/urls.py b/backend/apps/catalog/urls.py index 075623a..7e2416d 100644 --- a/backend/apps/catalog/urls.py +++ b/backend/apps/catalog/urls.py @@ -4,6 +4,7 @@ CategoryListAPIView, ProductDetailAPIView, ProductListAPIView, + ProductRatingAPIView, ProductReviewListCreateAPIView, ) @@ -17,6 +18,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..9ff3187 100644 --- a/backend/apps/catalog/views.py +++ b/backend/apps/catalog/views.py @@ -1,6 +1,5 @@ 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 @@ -8,14 +7,17 @@ from rest_framework.generics import 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 .serializers import ( CategorySerializer, ProductDetailSerializer, ProductListSerializer, + ProductRatingSerializer, ProductReviewCreateSerializer, ProductReviewSerializer, + product_rating_summary, ) @@ -188,13 +190,54 @@ 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 diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index f23642d..03b1084 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,12 @@ 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; + role: "customer" | "admin"; +}; type AuthResponse = { access: string; refresh: string; user: AuthUser }; type OrderItem = { id: number; @@ -1523,9 +1530,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 +1545,12 @@ function ProfilePage({ const [ordersResponse, setOrdersResponse] = useState( null, ); + const [displayName, setDisplayName] = useState(user?.display_name ?? ""); + const [nameMessage, setNameMessage] = useState(""); + const [namePending, setNamePending] = useState(false); + useEffect(() => { + setDisplayName(user?.display_name ?? ""); + }, [user?.display_name]); useEffect(() => { if (!user) { setLoading(false); @@ -1581,6 +1596,30 @@ function ProfilePage({ text="اطلاعات حساب و سفارش‌ها به حساب کاربری شما متصل هستند." /> ); + + async function updateDisplayName(event: FormEvent) { + event.preventDefault(); + setNamePending(true); + setNameMessage(""); + try { + const response = await fetchAuthenticated("/api/v1/auth/me/", { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ display_name: displayName }), + }); + if (!response.ok) throw new Error(await getError(response)); + const nextUser = (await response.json()) as AuthUser; + onUserUpdated(nextUser); + setNameMessage("نام نمایشی ذخیره شد."); + } catch (reason) { + setNameMessage( + reason instanceof Error ? reason.message : "ذخیرهٔ نام ناموفق بود.", + ); + } finally { + setNamePending(false); + } + } + return (
@@ -1595,8 +1634,23 @@ function ProfilePage({
- {user.role === "admin" ? "حساب مدیر" : "حساب کاربری"} + {user.display_name || "کاربر"} {user.phone} +
+ + + {nameMessage && {nameMessage}} +
) : ( -
-