mirror of
https://github.com/pretix/pretix.git
synced 2026-08-20 12:26:27 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec68ca6a54 |
@@ -628,14 +628,9 @@ class Order(LockModel, LoggedModel):
|
||||
def set_expires(self, now_dt=None, subevents=None):
|
||||
now_dt = now_dt or now()
|
||||
tz = ZoneInfo(self.event.settings.timezone)
|
||||
|
||||
sales_channel_suffix = "_" + self.sales_channel.identifier.replace(".", "_")
|
||||
if not (mode := self.event.settings.get(f'payment_term_mode{sales_channel_suffix}')):
|
||||
mode = self.event.settings.get('payment_term_mode')
|
||||
sales_channel_suffix = ""
|
||||
|
||||
mode = self.event.settings.get('payment_term_mode')
|
||||
if mode == 'days':
|
||||
exp_by_date = now_dt.astimezone(tz) + timedelta(days=self.event.settings.get(f'payment_term_days{sales_channel_suffix}', as_type=int))
|
||||
exp_by_date = now_dt.astimezone(tz) + timedelta(days=self.event.settings.get('payment_term_days', as_type=int))
|
||||
exp_by_date = exp_by_date.astimezone(tz).replace(hour=23, minute=59, second=59, microsecond=0)
|
||||
if self.event.settings.get('payment_term_weekdays'):
|
||||
if exp_by_date.weekday() == 5:
|
||||
@@ -643,7 +638,7 @@ class Order(LockModel, LoggedModel):
|
||||
elif exp_by_date.weekday() == 6:
|
||||
exp_by_date += timedelta(days=1)
|
||||
elif mode == 'minutes':
|
||||
exp_by_date = now_dt.astimezone(tz) + timedelta(minutes=self.event.settings.get(f'payment_term_minutes{sales_channel_suffix}', as_type=int))
|
||||
exp_by_date = now_dt.astimezone(tz) + timedelta(minutes=self.event.settings.get('payment_term_minutes', as_type=int))
|
||||
else:
|
||||
raise ValueError("'payment_term_mode' has an invalid value '{}'.".format(mode))
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ from django.conf import settings
|
||||
from django.core.mail import get_connection
|
||||
from django.core.validators import MinLengthValidator, RegexValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.db.models import Exists, OuterRef, Q
|
||||
from django.urls import reverse
|
||||
from django.utils.crypto import get_random_string
|
||||
from django.utils.functional import cached_property
|
||||
@@ -312,6 +312,25 @@ class Organizer(LoggedModel):
|
||||
)
|
||||
i += 1
|
||||
|
||||
def get_users_with_permission(self, permission):
|
||||
"""
|
||||
Returns a queryset of users who have a specific permission to this organizer.
|
||||
|
||||
:return: Iterable of User
|
||||
"""
|
||||
from .auth import User
|
||||
|
||||
if permission:
|
||||
qs = Team.objects.with_organizer_permission(permission)
|
||||
else:
|
||||
qs = Team.objects.all()
|
||||
|
||||
team_with_perm = qs.filter(
|
||||
members__pk=OuterRef('pk'),
|
||||
organizer=self,
|
||||
)
|
||||
return User.objects.annotate(twp=Exists(team_with_perm)).filter(twp=True)
|
||||
|
||||
|
||||
def generate_invite_token():
|
||||
return get_random_string(length=32, allowed_chars=string.ascii_lowercase + string.digits)
|
||||
|
||||
@@ -35,12 +35,13 @@
|
||||
import logging
|
||||
from collections import OrderedDict, namedtuple
|
||||
from itertools import groupby
|
||||
from typing import Union
|
||||
|
||||
from django.dispatch import receiver
|
||||
from django.utils.formats import date_format
|
||||
from django.utils.translation import gettext_lazy as _, pgettext_lazy
|
||||
|
||||
from pretix.base.models import Event, LogEntry
|
||||
from pretix.base.models import Event, LogEntry, Organizer
|
||||
from pretix.base.signals import register_notification_types
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.helpers.urls import mainreverse_absolute
|
||||
@@ -57,7 +58,8 @@ class Notification:
|
||||
"""
|
||||
Represents a notification that is sent/shown to a user. A notification consists of:
|
||||
|
||||
* one ``event`` reference
|
||||
* one ``event`` reference (can be ``Ǹone``)
|
||||
* one ``organizer`` reference
|
||||
* one ``title`` text that is shown e.g. in the email subject or in a headline
|
||||
* optionally one ``detail`` text that may or may not be shown depending on the notification method
|
||||
* optionally one ``url`` that should be absolute and point to the context of an notification (e.g. an order)
|
||||
@@ -67,8 +69,10 @@ class Notification:
|
||||
each consisting of a button label and an absolute URL to point to.
|
||||
"""
|
||||
|
||||
def __init__(self, event: Event, title: str, detail: str=None, url: str=None):
|
||||
def __init__(self, event: Event, title: str, detail: str=None, url: str=None, organizer: Organizer=None):
|
||||
assert event or organizer
|
||||
self.title = title
|
||||
self.organizer = organizer or event.organizer
|
||||
self.event = event
|
||||
self.detail = detail
|
||||
self.url = url
|
||||
@@ -91,8 +95,16 @@ class Notification:
|
||||
|
||||
|
||||
class NotificationType:
|
||||
def __init__(self, event: Event = None):
|
||||
self.event = event
|
||||
def __init__(self, event_or_organizer: Union[Event, Organizer] = None):
|
||||
if isinstance(event_or_organizer, Event):
|
||||
self.event = event_or_organizer
|
||||
self.organizer = event_or_organizer.organizer
|
||||
elif isinstance(event_or_organizer, Organizer):
|
||||
self.event = None
|
||||
self.organizer = event_or_organizer
|
||||
else:
|
||||
self.event = None
|
||||
self.organizer = None
|
||||
|
||||
def __repr__(self):
|
||||
return '<NotificationType: {}>'.format(self.action_type)
|
||||
@@ -121,31 +133,39 @@ class NotificationType:
|
||||
"""
|
||||
raise NotImplementedError() # NOQA
|
||||
|
||||
@property
|
||||
def is_event_level(self) -> bool:
|
||||
"""
|
||||
Return `True` if this notification type can be configured per event (the default).
|
||||
"""
|
||||
return True
|
||||
|
||||
def build_notification(self, logentry: LogEntry) -> Notification:
|
||||
"""
|
||||
This is the main function that you should override. It is supposed to turn a log entry
|
||||
object into a notification object that can then be rendered e.g. into an email.
|
||||
"""
|
||||
return Notification(
|
||||
logentry.event,
|
||||
logentry.display()
|
||||
event=logentry.event,
|
||||
title=logentry.display(),
|
||||
organizer=logentry.organizer,
|
||||
)
|
||||
|
||||
|
||||
def get_all_notification_types(event=None):
|
||||
def get_all_notification_types(event_or_organizer=None):
|
||||
global _ALL_TYPES
|
||||
|
||||
if event is None and _ALL_TYPES:
|
||||
if event_or_organizer is None and _ALL_TYPES:
|
||||
return _ALL_TYPES
|
||||
|
||||
types = OrderedDict()
|
||||
for recv, ret in register_notification_types.send(event):
|
||||
for recv, ret in register_notification_types.send(event_or_organizer):
|
||||
if isinstance(ret, (list, tuple)):
|
||||
for r in ret:
|
||||
types[r.action_type] = r
|
||||
else:
|
||||
types[ret.action_type] = ret
|
||||
if event is None:
|
||||
if event_or_organizer is None:
|
||||
_ALL_TYPES = types
|
||||
return types
|
||||
|
||||
@@ -181,6 +201,7 @@ class ParametrizedOrderNotificationType(NotificationType):
|
||||
|
||||
n = Notification(
|
||||
event=logentry.event,
|
||||
organizer=logentry.organizer,
|
||||
title=self._title.format(order=order, event=logentry.event),
|
||||
url=order_url
|
||||
)
|
||||
|
||||
@@ -47,14 +47,14 @@ def notify(logentry_ids: list):
|
||||
logentry_ids = [logentry_ids]
|
||||
|
||||
qs = LogEntry.all.select_related(
|
||||
'event', 'event__organizer'
|
||||
'event', 'event__organizer', 'organizer'
|
||||
).order_by(
|
||||
'action_type', 'event_id',
|
||||
'action_type', 'event_id', 'organizer_id',
|
||||
).filter(id__in=logentry_ids)
|
||||
|
||||
_event, _at, notify_specific, notify_global = None, None, None, None
|
||||
_event, _organizer, _at, notify_specific, notify_global = None, None, None, None, None
|
||||
for logentry in qs:
|
||||
if not logentry.event:
|
||||
if not logentry.event and not logentry.organizer:
|
||||
break # Ignore, we only have event-related notifications right now
|
||||
|
||||
notification_type = logentry.notification_type
|
||||
@@ -62,25 +62,36 @@ def notify(logentry_ids: list):
|
||||
if not notification_type:
|
||||
break # No suitable plugin
|
||||
|
||||
if _event != logentry.event or _at != logentry.action_type or notify_global is None:
|
||||
if _event != logentry.event or _organizer != logentry.organizer or _at != logentry.action_type or notify_global is None:
|
||||
_event = logentry.event
|
||||
_organizer = logentry.organizer
|
||||
_at = logentry.action_type
|
||||
# All users that have the permission to get the notification
|
||||
users = logentry.event.get_users_with_permission(
|
||||
notification_type.required_permission
|
||||
).filter(notifications_send=True, is_active=True)
|
||||
|
||||
if logentry.event:
|
||||
# All users that have the permission to get the notification
|
||||
users = logentry.event.get_users_with_permission(
|
||||
notification_type.required_permission
|
||||
).filter(notifications_send=True, is_active=True)
|
||||
else:
|
||||
users = logentry.organizer.get_users_with_permission(
|
||||
notification_type.required_permission
|
||||
).filter(notifications_send=True, is_active=True)
|
||||
|
||||
if logentry.user:
|
||||
users = users.exclude(pk=logentry.user.pk)
|
||||
|
||||
# Get all notification settings, both specific to this event as well as global
|
||||
notify_specific = {
|
||||
(ns.user, ns.method): ns.enabled
|
||||
for ns in NotificationSetting.objects.filter(
|
||||
event=logentry.event,
|
||||
action_type=notification_type.action_type,
|
||||
user__pk__in=users.values_list('pk', flat=True)
|
||||
)
|
||||
}
|
||||
if logentry.event:
|
||||
notify_specific = {
|
||||
(ns.user, ns.method): ns.enabled
|
||||
for ns in NotificationSetting.objects.filter(
|
||||
event=logentry.event,
|
||||
action_type=notification_type.action_type,
|
||||
user__pk__in=users.values_list('pk', flat=True)
|
||||
)
|
||||
}
|
||||
else:
|
||||
notify_specific = {}
|
||||
notify_global = {
|
||||
(ns.user, ns.method): ns.enabled
|
||||
for ns in NotificationSetting.objects.filter(
|
||||
@@ -106,7 +117,9 @@ def notify(logentry_ids: list):
|
||||
priority=get_task_priority("notifications", logentry.organizer_id),
|
||||
)
|
||||
|
||||
notification.send(logentry.event, logentry_id=logentry.id, notification_type=notification_type.action_type)
|
||||
if logentry.event:
|
||||
# FIXME: Signal is currently event-only
|
||||
notification.send(logentry.event, logentry_id=logentry.id, notification_type=notification_type.action_type)
|
||||
|
||||
|
||||
@app.task(base=ProfiledTask, acks_late=True, max_retries=9, default_retry_delay=900)
|
||||
@@ -158,13 +171,19 @@ def send_notification_mail(notification: Notification, user: User):
|
||||
body_plain = tpl_plain.render(ctx)
|
||||
|
||||
guid = uuid.uuid4()
|
||||
settings_holder = notification.event or notification.organizer
|
||||
prefix = settings_holder.settings.mail_prefix
|
||||
if not prefix and notification.event:
|
||||
prefix = notification.event.slug.upper()
|
||||
elif notification.organizer:
|
||||
prefix = notification.organizer.name
|
||||
m = OutgoingMail.objects.create(
|
||||
guid=guid,
|
||||
user=user,
|
||||
to=[user.email],
|
||||
subject='[{}] {}: {}'.format(
|
||||
settings.PRETIX_INSTANCE_NAME,
|
||||
notification.event.settings.mail_prefix or notification.event.slug.upper(),
|
||||
prefix,
|
||||
notification.title
|
||||
),
|
||||
body_plain=body_plain,
|
||||
|
||||
@@ -979,12 +979,12 @@ DEFAULTS = {
|
||||
'form_class': forms.IntegerField,
|
||||
'serializer_class': serializers.IntegerField,
|
||||
'write_permission': 'event.settings.payment:write',
|
||||
'form_kwargs': lambda suffix="", parent=0: dict(
|
||||
'form_kwargs': dict(
|
||||
label=_('Payment term in days'),
|
||||
widget=forms.NumberInput(
|
||||
attrs={
|
||||
'data-display-dependency': f'#id_payment_term_mode{suffix}_{parent}',
|
||||
'data-required-if': f'#id_payment_term_mode{suffix}_{parent}'
|
||||
'data-display-dependency': '#id_payment_term_mode_0',
|
||||
'data-required-if': '#id_payment_term_mode_0'
|
||||
},
|
||||
),
|
||||
help_text=_("The number of days after placing an order the user has to pay to preserve their reservation. If "
|
||||
@@ -1023,7 +1023,7 @@ DEFAULTS = {
|
||||
'form_class': forms.IntegerField,
|
||||
'serializer_class': serializers.IntegerField,
|
||||
'write_permission': 'event.settings.payment:write',
|
||||
'form_kwargs': lambda suffix="", parent=1: dict(
|
||||
'form_kwargs': dict(
|
||||
label=_('Payment term in minutes'),
|
||||
help_text=_("The number of minutes after placing an order the user has to pay to preserve their reservation. "
|
||||
"Only use this if you exclusively offer real-time payment methods. Please note that for technical reasons, "
|
||||
@@ -1032,8 +1032,8 @@ DEFAULTS = {
|
||||
MaxValueValidator(1440)],
|
||||
widget=forms.NumberInput(
|
||||
attrs={
|
||||
'data-display-dependency': f'#id_payment_term_mode{suffix}_{parent}',
|
||||
'data-required-if': f'#id_payment_term_mode{suffix}_{parent}'
|
||||
'data-display-dependency': '#id_payment_term_mode_1',
|
||||
'data-required-if': '#id_payment_term_mode_1'
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
@@ -605,15 +605,14 @@ subclass of pretix.base.ticketoutput.BaseTicketOutput
|
||||
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
|
||||
"""
|
||||
|
||||
register_notification_types = EventPluginSignal()
|
||||
register_notification_types = GlobalSignal()
|
||||
"""
|
||||
This signal is sent out to get all known notification types. Receivers should return an
|
||||
instance of a subclass of pretix.base.notifications.NotificationType or a list of such
|
||||
instances.
|
||||
|
||||
As with all event-plugin signals, the ``sender`` keyword argument will contain the event,
|
||||
however for this signal, the ``sender`` **may also be None** to allow creating the general
|
||||
notification settings!
|
||||
When called for actually sending notifications, ``sender`` will be the event or organizer,
|
||||
depending on context.
|
||||
"""
|
||||
|
||||
register_event_permission_groups = GlobalSignal()
|
||||
|
||||
@@ -856,50 +856,6 @@ class PaymentSettingsForm(EventSettingsValidationMixin, SettingsForm):
|
||||
'tax_rule_payment',
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.term_channel_fields = {}
|
||||
for c in self.obj.organizer.sales_channels.all():
|
||||
if c.type_instance.payment_restrictions_supported and c.identifier != "web":
|
||||
# At the moment, it seems sufficient to allow this for the same channel types as other payment settings
|
||||
# We can always introduce more flags later if needed
|
||||
suffix = '_' + c.identifier.replace(".", "_")
|
||||
self.term_channel_fields[c] = [
|
||||
'payment_term_mode' + suffix,
|
||||
'payment_term_days' + suffix,
|
||||
'payment_term_minutes' + suffix,
|
||||
]
|
||||
self.fields['payment_term_mode' + suffix] = DEFAULTS['payment_term_mode']['form_class'](
|
||||
label=_("Payment term"),
|
||||
widget=forms.RadioSelect,
|
||||
required=False,
|
||||
choices=(
|
||||
('', _("same as above")),
|
||||
('days', _("different payment term in days")),
|
||||
('minutes', _("different payment term in minutes"))
|
||||
),
|
||||
)
|
||||
self.fields['payment_term_days' + suffix] = DEFAULTS['payment_term_days']['form_class'](
|
||||
required=False,
|
||||
**DEFAULTS['payment_term_days']['form_kwargs'](suffix, 1),
|
||||
)
|
||||
self.fields['payment_term_minutes' + suffix] = DEFAULTS['payment_term_minutes']['form_class'](
|
||||
required=False,
|
||||
**DEFAULTS['payment_term_minutes']['form_kwargs'](suffix, 2),
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
for c in self.term_channel_fields.keys():
|
||||
suffix = '_' + c.identifier.replace(".", "_")
|
||||
mode = self.cleaned_data.get(f'payment_term_mode{suffix}')
|
||||
if mode == 'days' and self.cleaned_data.get(f'payment_term_days{suffix}') is None:
|
||||
raise ValidationError({f'payment_term_days{suffix}': _("This field is required.")})
|
||||
if mode == 'minutes' and self.cleaned_data.get(f'payment_term_minutes{suffix}') is None:
|
||||
raise ValidationError({f'payment_term_minutes{suffix}': _("This field is required.")})
|
||||
return data
|
||||
|
||||
def clean_payment_term_days(self):
|
||||
value = self.cleaned_data.get('payment_term_days')
|
||||
if self.cleaned_data.get('payment_term_mode') == 'days' and value is None:
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load bootstrap3 %}
|
||||
{% load getitem %}
|
||||
{% block inside %}
|
||||
<h1>{% trans "Payment settings" %}</h1>
|
||||
<form action="" method="post" class="form-horizontal">
|
||||
<form action="" method="post" class="form-horizontal form-plugins">
|
||||
{% csrf_token %}
|
||||
<div class="tabbed-form">
|
||||
<fieldset>
|
||||
@@ -72,37 +71,14 @@
|
||||
{% bootstrap_form_errors form layout="control" %}
|
||||
{% bootstrap_field form.payment_term_mode layout="control" %}
|
||||
{% bootstrap_field form.payment_term_days layout="control" %}
|
||||
{% bootstrap_field form.payment_term_minutes layout="control" %}
|
||||
{% bootstrap_field form.payment_term_weekdays layout="control" %}
|
||||
{% bootstrap_field form.payment_term_minutes layout="control" %}
|
||||
{% bootstrap_field form.payment_term_last layout="control" %}
|
||||
{% bootstrap_field form.payment_term_expire_automatically layout="control" %}
|
||||
{% trans "days" context "unit" as days %}
|
||||
{% bootstrap_field form.payment_term_expire_delay_days layout="control" addon_after=days %}
|
||||
{% bootstrap_field form.payment_term_accept_late layout="control" %}
|
||||
{% bootstrap_field form.payment_pending_hidden layout="control" %}
|
||||
|
||||
{% for c, fields in form.term_channel_fields.items %}
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
{% if "." in c.icon %}
|
||||
<img src="{% static c.icon %}" class="fa-like-image"
|
||||
data-toggle="tooltip" title="{{ c.type_instance.verbose_name }}">
|
||||
{% else %}
|
||||
<span class="fa fa-fw fa-{{ c.icon }} text-muted"
|
||||
data-toggle="tooltip" title="{{ c.type_instance.verbose_name }}"></span>
|
||||
{% endif %}
|
||||
{{ c.label }}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
{% for f in fields %}
|
||||
{% bootstrap_field form|getitem:f layout="control" %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{% trans "Advanced" %}</legend>
|
||||
|
||||
@@ -771,6 +771,7 @@ class UserNotificationsEditView(TemplateView):
|
||||
{k: a.get(t) for k, a in self.global_set.items()},
|
||||
)
|
||||
for t, tv in self.types.items()
|
||||
if tv.is_event_level or not self.event
|
||||
]
|
||||
ctx['event'] = self.event
|
||||
if self.event:
|
||||
|
||||
@@ -286,30 +286,6 @@ def test_expiry_dst(event):
|
||||
assert (localex.hour, localex.minute) == (23, 59)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_expiry_per_channel(event):
|
||||
today = now()
|
||||
event.settings.set('payment_term_mode', 'minutes')
|
||||
event.settings.set('payment_term_minutes', 30)
|
||||
event.settings.set('payment_term_mode_baz', 'minutes')
|
||||
event.settings.set('payment_term_minutes_baz', 15)
|
||||
order = _create_order(event, email='dummy@example.org', positions=[],
|
||||
now_dt=today,
|
||||
sales_channel=event.organizer.sales_channels.get(identifier="baz"),
|
||||
payment_requests=[{
|
||||
"id": "test0",
|
||||
"provider": "free",
|
||||
"max_value": None,
|
||||
"min_value": None,
|
||||
"multi_use_supported": False,
|
||||
"info_data": {},
|
||||
"pprov": FreeOrderProvider(event),
|
||||
}],
|
||||
locale='de')[0]
|
||||
assert (order.expires - today).days == 0
|
||||
assert (order.expires - today).seconds == 15 * 60
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_expiring(event):
|
||||
o1 = Order.objects.create(
|
||||
|
||||
Reference in New Issue
Block a user