from django.conf import settings from django.db import models from apps.core.models import PersianTextNormalizationMixin, PublicIdModel class Message(PersianTextNormalizationMixin, PublicIdModel, models.Model): persian_text_fields = {"body": True} class Type(models.TextChoices): PUBLIC="PUBLIC","عمومی"; INTERNAL_NOTE="INTERNAL_NOTE","یادداشت داخلی" ticket=models.ForeignKey("tickets.Ticket",on_delete=models.PROTECT,related_name="ticket_messages"); author=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,related_name="authored_messages"); body=models.TextField(blank=True); message_type=models.CharField(max_length=20,choices=Type.choices,default=Type.PUBLIC); is_internal=models.BooleanField(default=False); created_at=models.DateTimeField(auto_now_add=True,db_index=True); updated_at=models.DateTimeField(auto_now=True); edited_at=models.DateTimeField(null=True,blank=True); deleted_at=models.DateTimeField(null=True,blank=True); deleted_by=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,null=True,blank=True,related_name="deleted_messages") class Meta: ordering=["created_at","id"] permissions=[("add_internal_note","Can add internal note"),("edit_own_message","Can edit own message"),("delete_own_message","Can delete own message"),("view_deleted_message_content","Can view deleted content"),("view_message_revisions","Can view revisions")] @property def author_name(self): profile=getattr(self.author,"staff_profile",None) or getattr(self.author,"customer_profile",None) return str(profile) if profile else self.author.username class MessageRevision(PersianTextNormalizationMixin, models.Model): persian_text_fields = {"body": True} message=models.ForeignKey(Message,on_delete=models.CASCADE,related_name="revisions"); body=models.TextField(); edited_by=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT); created_at=models.DateTimeField(auto_now_add=True) class MessageMention(models.Model): message=models.ForeignKey(Message,on_delete=models.CASCADE,related_name="mentions"); mentioned_user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE); created_at=models.DateTimeField(auto_now_add=True) class Meta: constraints=[models.UniqueConstraint(fields=["message","mentioned_user"],name="unique_message_mention")] class MessageReadReceipt(models.Model): message=models.ForeignKey(Message,on_delete=models.CASCADE,related_name="read_receipts") user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="message_read_receipts") read_at=models.DateTimeField(auto_now_add=True,db_index=True) class Meta: ordering=["read_at","id"] constraints=[models.UniqueConstraint(fields=["message","user"],name="unique_message_read_receipt")] @property def reader_name(self): profile=getattr(self.user,"staff_profile",None) or getattr(self.user,"customer_profile",None) return str(profile) if profile else self.user.username