models: Add method to convert ScheduleMessage objects into dicts.

This commit is contained in:
Aman Agrawal 2023-04-20 02:11:24 +00:00 committed by Tim Abbott
parent 963fe566d7
commit 4cb238fb6e
2 changed files with 27 additions and 31 deletions

View File

@ -4281,6 +4281,16 @@ class ScheduledMessageNotificationEmail(models.Model):
scheduled_timestamp = models.DateTimeField(db_index=True)
class ScheduledMessageDict(TypedDict):
scheduled_message_id: int
to: List[int]
type: str
content: str
rendered_content: str
topic: str
deliver_at: int
class ScheduledMessage(models.Model):
sender = models.ForeignKey(UserProfile, on_delete=CASCADE)
recipient = models.ForeignKey(Recipient, on_delete=CASCADE)
@ -4316,6 +4326,19 @@ class ScheduledMessage(models.Model):
def set_topic_name(self, topic_name: str) -> None:
self.subject = topic_name
def to_dict(self) -> ScheduledMessageDict:
recipient, recipient_type_str = get_recipient_ids(self.recipient, self.sender.id)
return ScheduledMessageDict(
scheduled_message_id=self.id,
to=recipient,
type=recipient_type_str,
content=self.content,
rendered_content=self.rendered_content,
topic=self.topic_name(),
deliver_at=int(self.scheduled_timestamp.timestamp() * 1000),
)
EMAIL_TYPES = {
"followup_day1": ScheduledEmail.WELCOME,

View File

@ -1,21 +1,9 @@
from typing import List, TypedDict
from django.http import HttpRequest, HttpResponse
from zerver.actions.scheduled_messages import delete_scheduled_message
from zerver.lib.request import has_request_variables
from zerver.lib.response import json_success
from zerver.models import ScheduledMessage, UserProfile, get_recipient_ids
class ScheduledMessageDict(TypedDict):
scheduled_message_id: int
to: List[int]
type: str
content: str
rendered_content: str
topic: str
deliver_at: int
from zerver.models import ScheduledMessage, UserProfile
@has_request_variables
@ -23,24 +11,9 @@ def fetch_scheduled_messages(request: HttpRequest, user_profile: UserProfile) ->
scheduled_messages = ScheduledMessage.objects.filter(
sender=user_profile, delivered=False, delivery_type=ScheduledMessage.SEND_LATER
).order_by("scheduled_timestamp")
scheduled_message_dicts: List[ScheduledMessageDict] = []
for scheduled_message in scheduled_messages:
recipient, recipient_type_str = get_recipient_ids(
scheduled_message.recipient, user_profile.id
)
msg_to_dict: ScheduledMessageDict = {
"scheduled_message_id": scheduled_message.id,
"to": recipient,
"type": recipient_type_str,
"content": scheduled_message.content,
"rendered_content": scheduled_message.rendered_content,
"topic": scheduled_message.topic_name(),
"deliver_at": int(scheduled_message.scheduled_timestamp.timestamp() * 1000),
}
scheduled_message_dicts.append(msg_to_dict)
scheduled_message_dicts = [
scheduled_message.to_dict() for scheduled_message in scheduled_messages
]
return json_success(request, data={"scheduled_messages": scheduled_message_dicts})