Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix] Store notification verb in configuration #335

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions openwisp_notifications/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,16 @@ def get_message(self):
try:
config = get_notification_configuration(self.type)
data = self.data or {}
# Create a context with notification_verb
context = dict(notification=self, **data)
if 'message' in data:
md_text = data['message'].format(notification=self, **data)
md_text = data['message'].format(**context)
elif 'message' in config:
md_text = config['message'].format(notification=self, **data)
md_text = config['message'].format(**context)
else:
md_text = render_to_string(
config['message_template'], context=dict(notification=self, **data)
config['message_template'],
context=context
).strip()
except (AttributeError, KeyError, NotificationRenderException) as exception:
self._invalid_notification(
Expand Down Expand Up @@ -235,6 +238,17 @@ def redirect_view_url(self):
reverse('notifications:notification_read_redirect', args=(self.pk,))
)

@property
def notification_verb(self):
"""
Returns notification verb from type configuration if verb is None,
otherwise returns the stored verb
"""
if self.verb is None and self.type:
config = get_notification_configuration(self.type)
return config.get('verb', '')
return self.verb or ''


class AbstractNotificationSetting(UUIDModel):
_RECEIVE_HELP = (
Expand Down
8 changes: 6 additions & 2 deletions openwisp_notifications/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,14 @@ def notify_handler(**kwargs):
except NotificationRenderException as error:
logger.error(f'Error encountered while creating notification: {error}')
return

verb = kwargs.pop('verb', None)
if verb is None and notification_type:
verb = None

level = kwargs.pop(
'level', notification_template.get('level', Notification.LEVELS.info)
)
verb = notification_template.get('verb', kwargs.pop('verb', None))
user_app_name = User._meta.app_label

where = Q(is_superuser=True)
Expand Down Expand Up @@ -139,7 +143,7 @@ def notify_handler(**kwargs):
notification = Notification(
recipient=recipient,
actor=actor,
verb=str(verb),
verb=verb,
public=public,
description=description,
timestamp=timestamp,
Expand Down
17 changes: 17 additions & 0 deletions openwisp_notifications/migrations/0008_alter_notification_verb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.19 on 2025-02-15 06:11

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("openwisp_notifications", "0007_notificationsetting_deleted"),
]

operations = [
migrations.AlterField(
model_name="notification",
name="verb",
field=models.CharField(max_length=128, null=True),
),
]
12 changes: 12 additions & 0 deletions openwisp_notifications/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
AbstractNotification,
AbstractNotificationSetting,
)
from .types import get_notification_configuration


class Notification(AbstractNotification):
Expand All @@ -13,6 +14,17 @@ class Meta(AbstractNotification.Meta):
app_label = 'openwisp_notifications'
swappable = swappable_setting('openwisp_notifications', 'Notification')

@property
def notification_verb(self):
"""
Returns notification verb from type configuration if verb is None,
otherwise returns the stored verb
"""
if self.verb is None and self.type:
config = get_notification_configuration(self.type)
return config.get('verb', '')
return self.verb


class NotificationSetting(AbstractNotificationSetting):
class Meta(AbstractNotificationSetting.Meta):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% block head %} {{ notification.level }} : {{notification.target}} {{ notification.verb }} {% endblock head %}
{% block head %} {{ notification.level }} : {{notification.target}} {{ notification.notification_verb }} {% endblock head %}
{% block body %}
{% if notification.actor_link %}[{{notification.actor}}]({{notification.actor_link}}){% else %}{{notification.actor}}{% endif %}
reports
{% if notification.target_link %}[{{notification.target}}]({{notification.target_link}}){% else %}{{notification.target}}{% endif %}
{{ notification.verb }}.
{{ notification.notification_verb }}.
{% endblock body %}
42 changes: 39 additions & 3 deletions openwisp_notifications/tests/test_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.db.models.signals import post_migrate, post_save
from django.template import TemplateDoesNotExist
from django.test import TransactionTestCase
from django.test import TransactionTestCase, TestCase
from django.urls import reverse
from django.utils import timezone
from django.utils.timesince import timesince
Expand All @@ -33,6 +33,7 @@
from openwisp_notifications.types import (
_unregister_notification_choice,
get_notification_configuration,
NOTIFICATION_TYPES,
)
from openwisp_notifications.utils import _get_absolute_url
from openwisp_users.tests.utils import TestOrganizationMixin
Expand Down Expand Up @@ -319,7 +320,8 @@ def test_default_notification_type(self):
self._create_notification()
n = notification_queryset.first()
self.assertEqual(n.level, 'info')
self.assertEqual(n.verb, 'default verb')
self.assertIsNone(n.verb)
self.assertEqual(n.notification_verb, 'default verb')
self.assertIn(
'Default notification with default verb and level info by', n.message
)
Expand Down Expand Up @@ -356,7 +358,8 @@ def test_generic_notification_type(self):
self._create_notification()
n = notification_queryset.first()
self.assertEqual(n.level, 'info')
self.assertEqual(n.verb, 'generic verb')
self.assertIsNone(n.verb)
self.assertEqual(n.notification_verb, 'generic verb')
expected_output = (
'<p><a href="https://example.com{user_path}">admin</a></p>'
).format(
Expand Down Expand Up @@ -999,3 +1002,36 @@ def test_notification_cache_update(self):
self.assertEqual(notification.target.username, 'new operator name')
# Done for populating cache
self.assertEqual(operator_cache.username, 'new operator name')


class TestNotificationVerb(TestCase):
def setUp(self):
self.admin = User.objects.create_superuser(
username='admin',
password='admin',
email='admin@admin.com'
)

def test_notification_verb_update(self):
# Create notification with default type
notify.send(
sender=self.admin,
type='default',
recipient=self.admin,
)

notification = self.admin.notifications.first()
# Verify verb is None in database
self.assertIsNone(notification.verb)
# Verify notification shows verb from configuration
self.assertEqual(notification.notification_verb, 'default verb')

# Change verb in notification type
old_config = NOTIFICATION_TYPES['default'].copy()
NOTIFICATION_TYPES['default']['verb'] = 'updated verb'

# Verify notification shows updated verb
self.assertEqual(notification.notification_verb, 'updated verb')

# Restore original configuration
NOTIFICATION_TYPES['default'] = old_config