fix(customers): Auto-generate username when creating customers

The CustomerSerializer was missing a create method to generate a unique
username, causing IntegrityError when trying to create customers.

- Add first_name and last_name as write-only fields
- Remove email from read_only_fields so it can be set on creation
- Generate username from email prefix (with counter for uniqueness)
- Fall back to UUID-based username if no email provided

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
poduck
2025-12-04 10:29:45 -05:00
parent 9073970189
commit a2f74ee769

View File

@@ -38,6 +38,8 @@ class ResourceTypeSerializer(serializers.ModelSerializer):
class CustomerSerializer(serializers.ModelSerializer):
"""Serializer for Customer (User with role=CUSTOMER)"""
name = serializers.SerializerMethodField()
first_name = serializers.CharField(write_only=True, required=False, allow_blank=True)
last_name = serializers.CharField(write_only=True, required=False, allow_blank=True)
total_spend = serializers.SerializerMethodField()
last_visit = serializers.SerializerMethodField()
status = serializers.SerializerMethodField()
@@ -52,11 +54,29 @@ class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'id', 'name', 'email', 'phone', 'city', 'state', 'zip',
'id', 'name', 'first_name', 'last_name', 'email', 'phone', 'city', 'state', 'zip',
'total_spend', 'last_visit', 'status', 'avatar_url', 'tags',
'user_id', 'user_data',
]
read_only_fields = ['id', 'email']
read_only_fields = ['id']
def create(self, validated_data):
"""Create a customer with auto-generated username"""
import uuid
email = validated_data.get('email', '')
# Generate username from email or use a UUID if no email
if email:
base_username = email.split('@')[0]
username = base_username
counter = 1
while User.objects.filter(username=username).exists():
username = f"{base_username}{counter}"
counter += 1
else:
username = f"customer_{uuid.uuid4().hex[:8]}"
validated_data['username'] = username
return super().create(validated_data)
def get_name(self, obj):
return obj.full_name