Skip to content
Merged

Dev #12

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
34 changes: 32 additions & 2 deletions backend/apps/accounts/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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",
Expand Down
15 changes: 15 additions & 0 deletions backend/apps/accounts/migrations/0003_user_display_name.py
Original file line number Diff line number Diff line change
@@ -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),
)
]
40 changes: 40 additions & 0 deletions backend/apps/accounts/migrations/0004_user_profile_fields.py
Original file line number Diff line number Diff line change
@@ -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),
),
]
7 changes: 7 additions & 0 deletions backend/apps/accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 35 additions & 0 deletions backend/apps/accounts/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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):
Expand Down
42 changes: 42 additions & 0 deletions backend/apps/accounts/tests/test_otp_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": "[email protected] ",
"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"] == "[email protected]"
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,
Expand Down
9 changes: 9 additions & 0 deletions backend/apps/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
AdminTokenObtainPairSerializer,
OTPRequestSerializer,
OTPVerifySerializer,
UserProfileSerializer,
UserSerializer,
)
from .services import OTPInvalid, OTPRateLimited, request_otp, verify_otp
Expand Down Expand Up @@ -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)
14 changes: 12 additions & 2 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,
ProductRating,
ProductReview,
)

Expand Down Expand Up @@ -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")
Original file line number Diff line number Diff line change
@@ -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",
),
),
]
Original file line number Diff line number Diff line change
@@ -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,
),
),
]
Loading
Loading