Files
qlockify-backend-deployment/apps/clients/services/clients.py

58 lines
2.2 KiB
Python

from rest_framework.exceptions import ValidationError
from apps.clients.models import Client
from apps.workspaces.models import WorkspaceMembership
def create_client(user, workspace_id, name, notes="", thumbnail=None):
"""
Creates a new client after validating workspace membership and name uniqueness.
"""
is_workspace_member = WorkspaceMembership.objects.filter(
workspace_id=workspace_id,
user=user,
is_active=True
).exists()
if not is_workspace_member:
raise ValidationError({"workspace": "شما عضو این فضای کاری نیستید."})
if Client.objects.filter(workspace_id=workspace_id, name=name, is_deleted=False).exists():
raise ValidationError({"name": "مشتری با این نام در این فضای کاری وجود دارد."})
return Client.objects.create(
workspace_id=workspace_id,
name=name,
notes=notes,
thumbnail=thumbnail,
created_by=user,
updated_by=user,
)
def update_client(client, name=None, notes=None, thumbnail=None, clear_thumbnail=False):
"""
Updates an existing client while validating name uniqueness within the workspace.
"""
if name is not None and name != client.name:
if Client.objects.filter(workspace_id=client.workspace_id, name=name, is_deleted=False).exists():
raise ValidationError({"name": "مشتری با این نام در این فضای کاری وجود دارد."})
client.name = name
if notes is not None:
client.notes = notes
old_thumbnail_name = client.thumbnail.name if client.thumbnail else None
if clear_thumbnail and client.thumbnail:
client.thumbnail.delete(save=False)
client.thumbnail = None
if thumbnail is not None:
client.thumbnail = thumbnail
client.save(update_fields=["name", "notes", "thumbnail", "updated_at"])
if old_thumbnail_name and client.thumbnail and client.thumbnail.name != old_thumbnail_name:
storage = client.thumbnail.storage
if storage.exists(old_thumbnail_name):
storage.delete(old_thumbnail_name)
return client