This commit is contained in:
65
backend/modules/crm/services.py
Normal file
65
backend/modules/crm/services.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from django.db import transaction, IntegrityError
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from .models import Client
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ClientService:
|
||||
@staticmethod
|
||||
def create_client(data: dict, user=None) -> Client:
|
||||
"""
|
||||
Create a Client instance with model validation and handle IntegrityError.
|
||||
"""
|
||||
# Instantiate model and run model-level validation
|
||||
client = Client(**data)
|
||||
try:
|
||||
client.full_clean()
|
||||
except Exception as e:
|
||||
logger.error(f"Client validation failed: {e}")
|
||||
raise ValidationError({"detail": str(e)})
|
||||
|
||||
try:
|
||||
with transaction.atomic():
|
||||
client.save()
|
||||
except IntegrityError as exc:
|
||||
logger.error(f"Integrity error creating client: {exc}")
|
||||
# Convert DB integrity errors into DRF ValidationError for the API layer
|
||||
raise ValidationError({"detail": str(exc)})
|
||||
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def update_client(instance: Client, data: dict, user=None) -> Client:
|
||||
"""
|
||||
Update the given Client instance. Validate and save.
|
||||
"""
|
||||
for attr, value in data.items():
|
||||
setattr(instance, attr, value)
|
||||
|
||||
try:
|
||||
instance.full_clean()
|
||||
except Exception as e:
|
||||
logger.error(f"Client validation failed on update: {e}")
|
||||
raise ValidationError({"detail": str(e)})
|
||||
|
||||
try:
|
||||
with transaction.atomic():
|
||||
instance.save()
|
||||
except IntegrityError as exc:
|
||||
logger.error(f"Integrity error updating client: {exc}")
|
||||
raise ValidationError({"detail": str(exc)})
|
||||
|
||||
return instance
|
||||
|
||||
@staticmethod
|
||||
def delete_client(instance: Client, user=None) -> Client:
|
||||
"""
|
||||
Soft-delete the client (if you want soft delete).
|
||||
If hard delete is desired, call instance.delete() instead.
|
||||
"""
|
||||
instance.is_active = False
|
||||
instance.save()
|
||||
return instance
|
||||
Reference in New Issue
Block a user