diff --git a/openwisp_notifications/base/models.py b/openwisp_notifications/base/models.py index 43417a17..29e33778 100644 --- a/openwisp_notifications/base/models.py +++ b/openwisp_notifications/base/models.py @@ -309,11 +309,19 @@ def save(self, *args, **kwargs): with transaction.atomic(): if not self.organization and not self.type: try: - original = self.__class__.objects.get(pk=self.pk) + previous_state = self.__class__.objects.only('email').get( + pk=self.pk + ) updates = {'web': self.web} - # Update 'email' only if it's different from the previous state - if not self.web or self.email != original.email: + # If global web notifiations are disabled, then disable email notifications as well + if not self.web: + updates['email'] = False + + # Update email notifiations only if it's different from the previous state + # Otherwise, it would overwrite the email notification settings for specific + # setting that were enabled by the user after disabling global email notifications + if self.email != previous_state.email: updates['email'] = self.email self.user.notificationsetting_set.exclude(pk=self.pk).update( diff --git a/openwisp_notifications/tests/test_notification_setting.py b/openwisp_notifications/tests/test_notification_setting.py index 44c9ac1b..16a2712b 100644 --- a/openwisp_notifications/tests/test_notification_setting.py +++ b/openwisp_notifications/tests/test_notification_setting.py @@ -291,7 +291,7 @@ def test_global_notification_setting_update(self): global_setting.save() with self.subTest( - 'Update global web to False while ensuring at least one email setting is True' + 'Test global web to False while ensuring at least one email setting is True' ): # Set the default type notification setting's email to True NotificationSetting.objects.filter( @@ -308,6 +308,22 @@ def test_global_notification_setting_update(self): ).exists() ) + with self.subTest('Test global web to False'): + global_setting.web = False + global_setting.full_clean() + global_setting.save() + + self.assertFalse( + NotificationSetting.objects.filter( + user=admin, organization=org, web=True + ).exists() + ) + self.assertFalse( + NotificationSetting.objects.filter( + user=admin, organization=org, email=True + ).exists() + ) + def test_global_notification_setting_delete(self): admin = self._get_admin() global_setting = NotificationSetting.objects.get(