From 9a971579e12dd89e894ca8afeb7e235bf7708355 Mon Sep 17 00:00:00 2001 From: Jonathan Tsai Date: Sat, 14 Oct 2023 22:01:56 +0000 Subject: [PATCH] adds Slack notification for when an OrganizationInvitation is created (initially sent) --- apps/organizations/apps.py | 38 +++++++++++++++++++++++++++++++++++- apps/organizations/models.py | 15 ++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/apps/organizations/apps.py b/apps/organizations/apps.py index cbcd3a5b..2b9462e7 100644 --- a/apps/organizations/apps.py +++ b/apps/organizations/apps.py @@ -1,9 +1,37 @@ +# Third Party (PyPI) Imports +import rollbar + # Django Imports from django.apps import AppConfig +from django.conf import settings from django.db.models import signals # HTK Imports from htk.app_config import HtkAppConfig +from htk.decorators.classes import disable_for_loaddata +from htk.utils import ( + htk_setting, + resolve_model_dynamically, +) + + +# isort: off + + +@disable_for_loaddata +def organization_invitation_created(sender, instance, created, **kwargs): + """Signal handler for when a new OrganizationInvitation object is created""" + if created: + invitation = instance + + if not settings.TEST and htk_setting('HTK_SLACK_NOTIFICATIONS_ENABLED'): + try: + from htk.utils.notifications import slack_notify + + msg = invitation.build_notification_message__created() + slack_notify(msg) + except: + rollbar.report_exc_info() class HtkOrganizationAppConfig(HtkAppConfig): @@ -12,4 +40,12 @@ class HtkOrganizationAppConfig(HtkAppConfig): verbose_name = 'Organizations' def ready(self): - pass + OrganizationInvitation = resolve_model_dynamically( + htk_setting('HTK_ORGANIZATION_INVITATION_MODEL') + ) + + signals.post_save.connect( + organization_invitation_created, + sender=OrganizationInvitation, + dispatch_uid='htk_organization_invitation_created', + ) diff --git a/apps/organizations/models.py b/apps/organizations/models.py index 9def70dc..e5864814 100644 --- a/apps/organizations/models.py +++ b/apps/organizations/models.py @@ -317,6 +317,21 @@ def status(self) -> str: return status + ## + # Notifications + + def build_notification_message__created(self): + """Builds a message that will be displayed as an internal Slack notification + when this invitation object is created. + """ + msg = '{invited_by_name} ({invited_by_username}) has sent an invitation for organization {organization_name} to {email}'.format( + invited_by_name=self.invited_by.profile.get_full_name(), + invited_by_username=self.invited_by.username, + organization_name=self.organization.name, + email=self.email, + ) + return msg + class BaseAbstractOrganizationTeam(HtkBaseModel): name = models.CharField(max_length=128)