Skip to content

Commit

Permalink
feat: complete implementation of programme messages & test
Browse files Browse the repository at this point in the history
  • Loading branch information
japsu committed Apr 15, 2023
1 parent 9ffa4c3 commit 1b6cbb9
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 47 deletions.
14 changes: 12 additions & 2 deletions access/models/email_alias_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,22 @@ class EmailAliasDomain(models.Model):
has_internal_aliases = models.BooleanField(default=False)

@classmethod
def get_or_create_dummy(cls, domain_name="example.com"):
def get_or_create_dummy(
cls,
domain_name="example.com",
has_internal_aliases: bool = True,
):
from core.models.organization import Organization

organization, unused = Organization.get_or_create_dummy()

return cls.objects.get_or_create(domain_name=domain_name, defaults=dict(organization=organization))
return cls.objects.get_or_create(
domain_name=domain_name,
defaults=dict(
organization=organization,
has_internal_aliases=has_internal_aliases,
),
)

def __str__(self):
return self.domain_name
Expand Down
17 changes: 9 additions & 8 deletions kompassi/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def mkpath(*parts):
"listings",
"forms",
"metrics",
"background_tasks",
"organizations.tracon_ry",
"events.tracon9",
"events.traconx",
Expand Down Expand Up @@ -420,19 +421,19 @@ def mkpath(*parts):


if env("BROKER_URL", default=""):
INSTALLED_APPS = INSTALLED_APPS + ("background_tasks",)
CELERY_BROKER_URL = env("BROKER_URL")
CELERY_ACCEPT_CONTENT = ["json"]
else:
CELERY_TASK_ALWAYS_EAGER = True

# EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
CELERY_ACCEPT_CONTENT = ["json"]

CELERY_SEND_TASK_ERROR_EMAILS = not DEBUG
CELERY_SERVER_EMAIL = DEFAULT_FROM_EMAIL
CELERY_SEND_TASK_ERROR_EMAILS = not DEBUG
CELERY_SERVER_EMAIL = DEFAULT_FROM_EMAIL

CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"

CELERY_REDIS_SOCKET_KEEPALIVE = True
CELERY_REDIS_SOCKET_KEEPALIVE = True


if "api" in INSTALLED_APPS:
Expand Down
32 changes: 2 additions & 30 deletions mailings/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,6 @@ def _send(self, recipients, resend):
if recipients is None:
recipients = [user.person for user in self.recipient.group.user_set.all()]

# TODO this delay stuff should not be here (only applies to SMS messages)
delay = 0
for person in recipients:
try:
person_message, created = PersonMessage.objects.get_or_create(
Expand All @@ -152,10 +150,8 @@ def _send(self, recipients, resend):
created = False

if created or resend:
person_message.actually_send(delay)
person_message.actually_send()
bodylen = len(person_message.body.text)
delayfactor = ceil(bodylen / 153)
delay += DELAY_PER_MESSAGE_FRAGMENT_MILLIS * delayfactor

def expire(self):
assert self.expired_at is None, "re-expiring an expired message does not make sense"
Expand Down Expand Up @@ -276,15 +272,7 @@ def message_vars(self):
def render_message(self, template):
return Template(template).render(Context(self.message_vars))

def actually_send(self, delay=0):
if self.message.channel == "email":
self._actually_send_email()
# elif self.message.channel == 'sms':
# self._actually_send_sms(delay)
else:
raise NotImplementedError(self.message.channel)

def _actually_send_email(self):
def actually_send(self):
from django.core.mail import EmailMessage

msgbcc = []
Expand All @@ -303,19 +291,3 @@ def _actually_send_email(self):
to=(self.person.name_and_email,),
bcc=msgbcc,
).send(fail_silently=True)

# def _actually_send_sms(self, delay=0):
# from sms.models import SMSMessageOut, SMSEventMeta
# try:
# event = SMSEventMeta.objects.get(event=self.message.event, sms_enabled=True)
# except SMSEventMeta.DoesNotExist:
# pass
# else:
# if 'background_tasks' in settings.INSTALLED_APPS:
# from sms.tasks import message_send
# sendtime = timezone.now() + timedelta(milliseconds=delay)
# sending = SMSMessageOut(message=self.body.text, to=self.person.phone, event=event)
# sending.save()
# message_send.apply_async(args=[sending.pk], eta=sendtime)
# else:
# SMSMessageOut.send(message=self.body.text, to=self.person.phone, event=event)
17 changes: 12 additions & 5 deletions programme/models/programme_event_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ class ProgrammeEventMeta(ContactEmailMixin, EventMetaBase):

use_cbac = True

# if set, would get copies of all programme messages
monitor_email = None

def __init__(self, *args, **kwargs):
if "public" in kwargs:
public = kwargs.pop("public")
Expand All @@ -86,25 +89,29 @@ def get_or_create_dummy(cls):
from django.utils.timezone import now

event, unused = Event.get_or_create_dummy()
admin_group, hosts_group = cls.get_or_create_groups(event, ["admins", "hosts"])
(admin_group,) = cls.get_or_create_groups(event, ["admins"])

return cls.objects.get_or_create(
meta, created = cls.objects.get_or_create(
event=event,
defaults=dict(
admin_group=admin_group,
public_from=now(),
),
)

meta.create_groups()

return meta, created

def create_groups(self):
from .category import Category

subjects: list[str | Category] = ["new", "hosts", "live", "rejected"]

for category in Category.objects.filter(event=self.event):
subjects.append(category)
# for category in Category.objects.filter(event=self.event):
# subjects.append(category)

return subjects
return self.get_or_create_groups(self.event, subjects)

@classmethod
def get_or_create_groups(cls, event, subjects):
Expand Down
44 changes: 42 additions & 2 deletions programme/tests.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import pytest
from django.test import TestCase
from django.utils.timezone import now

from datetime import datetime, timedelta

from dateutil.tz import tzlocal

from access.models import SlackAccess, GroupPrivilege, Privilege
from access.models import SlackAccess, GroupPrivilege, Privilege, InternalEmailAlias, EmailAliasDomain
from labour.models import Signup
from mailings.models import RecipientGroup, Message, PersonMessage

from .utils import next_full_hour
from .models import ProgrammeEventMeta, ProgrammeRole, Programme, Room
from .models import ProgrammeEventMeta, ProgrammeRole, Programme


class UtilsTestCase(TestCase):
Expand Down Expand Up @@ -140,3 +142,41 @@ def test_programmes_without_end_time_showing_as_past(self):

assert not Programme.get_future_programmes(person).exists()
assert Programme.get_past_programmes(person).exists()


@pytest.mark.django_db
def test_programme_mass_messages():
meta, _ = ProgrammeEventMeta.get_or_create_dummy()
EmailAliasDomain.get_or_create_dummy()
InternalEmailAlias.ensure_internal_email_aliases()

hosts_group = meta.get_group("hosts")
recipient = RecipientGroup.objects.get(group=hosts_group)
message = Message(
recipient=recipient,
subject_template="Message 1",
body_template="Body",
)
message.send()

assert not PersonMessage.objects.exists()

role, _ = ProgrammeRole.get_or_create_dummy()
person = role.person
programme = role.programme
programme.apply_state()

person_message = PersonMessage.objects.get()

assert person_message.person == person

message2 = Message(
recipient=recipient,
subject_template="Message 2",
body_template="Body",
)
message2.send()

person_message2 = PersonMessage.objects.get(message=message2)

assert person_message2.person == person

0 comments on commit 1b6cbb9

Please sign in to comment.