feat(clients): add clients app basic structure and endpoints
This commit is contained in:
42
apps/clients/services/clients.py
Normal file
42
apps/clients/services/clients.py
Normal file
@@ -0,0 +1,42 @@
|
||||
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=""):
|
||||
"""
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
def update_client(client, name=None, notes=None):
|
||||
"""
|
||||
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
|
||||
|
||||
client.save(update_fields=["name", "notes", "updated_at"])
|
||||
return client
|
||||
Reference in New Issue
Block a user