Files
2026-10-14 12:27:55 +03:30

101 lines
5.0 KiB
Python

from django.conf import settings
from django.db import models
from django.db import transaction
from django.core.exceptions import ValidationError
from apps.core.models import PersianTextNormalizationMixin, TimeStampedModel
class ContactGroup(PersianTextNormalizationMixin, TimeStampedModel):
"""A unit-owned address-book group; contacts may belong to many groups."""
persian_text_fields = {"name": False, "description": True}
name = models.CharField(max_length=150)
unit = models.ForeignKey(
"staff.OrganizationalUnit",
on_delete=models.CASCADE,
related_name="contact_groups",
)
description = models.TextField(blank=True)
is_active = models.BooleanField(default=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["unit", "name"], name="unique_contact_group_name_per_unit")
]
ordering = ["unit__name", "name"]
verbose_name = "گروه مخاطبان"
verbose_name_plural = "گروه‌های مخاطبان"
def __str__(self):
return f"{self.unit}: {self.name}"
class CustomerProfile(PersianTextNormalizationMixin, TimeStampedModel):
persian_text_fields = {"first_name": False, "last_name": False, "organization_name": False, "province": False, "city": False}
class Type(models.TextChoices):
PERSON="PERSON","شخص"; CONSUMER="CONSUMER","مصرف‌کننده نهایی"; SHOP="SHOP","فروشگاه"; REPRESENTATIVE="REPRESENTATIVE","نمایندگی"; COMPANY="COMPANY","شرکت"; OTHER="OTHER","سایر"
class StakeholderType(models.TextChoices):
CUSTOMER = "CUSTOMER", "مشتری"
SUPPLIER = "SUPPLIER", "تامین‌کننده"
CARRIER = "CARRIER", "باربری"
OTHER = "OTHER", "سایر"
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="customer_profile")
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
customer_type = models.CharField(max_length=20, choices=Type.choices, blank=True)
stakeholder_type = models.CharField(
max_length=20,
choices=StakeholderType.choices,
default=StakeholderType.CUSTOMER,
db_index=True,
)
organization_name = models.CharField(max_length=180, blank=True)
groups = models.ManyToManyField(ContactGroup, blank=True, related_name="contacts")
province = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank=True)
login_blocked = models.BooleanField("مسدود کردن ورود مشتری / مخاطب", default=False)
login_block_reason = models.TextField(
"دلیل مسدودی ورود", blank=True,
help_text="این متن به مشتری یا مخاطب نمایش داده می‌شود. ورود کارکنان و کارشناسان تحت تأثیر نیست.",
)
login_access_version = models.PositiveIntegerField(default=0, editable=False)
def clean(self):
super().clean()
if self.login_blocked and not self.login_block_reason.strip():
raise ValidationError({"login_block_reason": "برای مسدود کردن ورود، دلیل مسدودی را بنویسید."})
def save(self, *args, **kwargs):
# Keep old sessions revoked even if the administrator later unblocks access.
with transaction.atomic():
previous = type(self).objects.select_for_update().filter(pk=self.pk).first()
if previous is None and self.login_blocked:
self.login_access_version = 1
if previous is not None:
self.login_access_version = previous.login_access_version
fields = kwargs.get("update_fields")
changes_access = fields is None or "login_blocked" in fields
if changes_access and self.login_blocked and not previous.login_blocked:
self.login_access_version += 1
if fields is not None:
kwargs["update_fields"] = set(fields) | {"login_access_version"}
super().save(*args, **kwargs)
def __str__(self): return (f"{self.first_name} {self.last_name}".strip() or self.user.mobile or self.user.username)
class ContactEditLog(models.Model):
"""Persistent record of changes made through the staff contact editor."""
contact = models.ForeignKey(CustomerProfile, on_delete=models.SET_NULL, null=True, related_name="edit_logs")
contact_public_id = models.UUIDField(db_index=True)
actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="contact_edits")
actor_name = models.CharField(max_length=150)
changes = models.JSONField()
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
class Meta:
ordering = ["-created_at", "-pk"]
verbose_name = "سابقه ویرایش مخاطب"
verbose_name_plural = "سوابق ویرایش مخاطبان"