75 lines
2.9 KiB
Python
75 lines
2.9 KiB
Python
from django.db import transaction
|
|
|
|
from apps.account.models import User
|
|
from apps.banker.models import Contact, ContactField, ContactGroup, MessageTemplate
|
|
|
|
|
|
class GroupService:
|
|
@staticmethod
|
|
def get_or_create_general(user: User) -> ContactGroup:
|
|
"""گروه عمومی کاربر را برمیگرداند؛ اگر هنوز ندارد، میسازد.
|
|
|
|
هر کاربر دقیقاً یک گروه با is_general=True دارد — بدون فیلد سفارشی،
|
|
برای کاربرانی که نیاز به پیچیدگی ندارند.
|
|
"""
|
|
import uuid
|
|
|
|
general = ContactGroup.objects.filter(user=user, is_general=True).first()
|
|
if general:
|
|
return general
|
|
return ContactGroup.objects.create(
|
|
id=str(uuid.uuid4()),
|
|
user=user,
|
|
name="عمومی",
|
|
color=0xFF667EEA,
|
|
is_general=True,
|
|
)
|
|
|
|
|
|
class BackupService:
|
|
@staticmethod
|
|
def build_snapshot(user: User) -> dict:
|
|
return {
|
|
"contact_fields": list(
|
|
ContactField.objects.filter(user=user).values("id", "group_id", "label", "sort_order")
|
|
),
|
|
"contacts": list(
|
|
Contact.objects.filter(user=user).values(
|
|
"id", "name", "phone", "device_contact_id", "field_values", "channel_ids"
|
|
)
|
|
),
|
|
"groups": list(
|
|
ContactGroup.objects.filter(user=user).values(
|
|
"id", "name", "color", "is_general", "member_ids"
|
|
)
|
|
),
|
|
"templates": list(
|
|
MessageTemplate.objects.filter(user=user).values("id", "group_id", "name", "body", "mode")
|
|
),
|
|
}
|
|
|
|
@staticmethod
|
|
@transaction.atomic
|
|
def replace_snapshot(user: User, data: dict) -> dict:
|
|
"""جایگزینی کامل دیتای کاربر روی سرور با آنچه از اپ فرستاده شده (منبع حقیقت، خودِ اپ است)"""
|
|
ContactField.objects.filter(user=user).delete()
|
|
Contact.objects.filter(user=user).delete()
|
|
MessageTemplate.objects.filter(user=user).delete()
|
|
ContactGroup.objects.filter(user=user).delete()
|
|
|
|
groups = list(data.get("groups", []))
|
|
if groups:
|
|
ContactGroup.objects.bulk_create(ContactGroup(user=user, **item) for item in groups)
|
|
if not any(g.get("is_general") for g in groups):
|
|
GroupService.get_or_create_general(user)
|
|
|
|
ContactField.objects.bulk_create(
|
|
ContactField(user=user, **item) for item in data.get("contact_fields", [])
|
|
)
|
|
Contact.objects.bulk_create(Contact(user=user, **item) for item in data.get("contacts", []))
|
|
MessageTemplate.objects.bulk_create(
|
|
MessageTemplate(user=user, **item) for item in data.get("templates", [])
|
|
)
|
|
|
|
return BackupService.build_snapshot(user)
|