mirror of
https://github.com/pretix/pretix.git
synced 2026-08-05 09:57:49 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ed69a8ef7 | ||
|
|
ba37f2eb47 | ||
|
|
8ec81f80e8 | ||
|
|
257bb2e4b7 | ||
|
|
3953d57c2e | ||
|
|
2f1025c3a6 | ||
|
|
19f4dce267 | ||
|
|
e44f91530a | ||
|
|
d985fd61a1 | ||
|
|
803964da0e | ||
|
|
7e6df3d427 | ||
|
|
7b93cc57db | ||
|
|
21d62c5078 | ||
|
|
988dc112ac | ||
|
|
3843448812 | ||
|
|
49893ca9df | ||
|
|
4eade5070e | ||
|
|
32b1997208 | ||
|
|
eaf4a310f6 | ||
|
|
8dc0f7c1b2 | ||
|
|
dd3e6c4692 | ||
|
|
c7437336b4 |
@@ -19,4 +19,4 @@
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
__version__ = "2026.3.0.dev0"
|
||||
__version__ = "2026.3.4"
|
||||
|
||||
@@ -1122,7 +1122,7 @@ class CheckinViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
permission = 'event.orders:read'
|
||||
|
||||
def get_queryset(self):
|
||||
qs = Checkin.all.filter().select_related(
|
||||
qs = Checkin.all.filter(list__event=self.request.event).select_related(
|
||||
"position",
|
||||
"device",
|
||||
)
|
||||
|
||||
@@ -69,7 +69,9 @@ class ReusableMediaExporter(OrganizerLevelExportMixin, ListExporter):
|
||||
date_format(medium.expires, 'SHORT_DATETIME_FORMAT') if medium.expires else '',
|
||||
medium.customer.identifier if medium.customer_id else '',
|
||||
f"{medium.linked_orderposition.order.code}-{medium.linked_orderposition.positionid}" if medium.linked_orderposition_id else '',
|
||||
medium.linked_giftcard.secret if medium.linked_giftcard_id else '',
|
||||
# we cannot determine here whether user has permission organizer.giftcards:read
|
||||
# so default to not showing giftcard secret
|
||||
medium.linked_giftcard.secret[:3] + "…" if medium.linked_giftcard_id else '',
|
||||
medium.notes,
|
||||
]
|
||||
yield row
|
||||
|
||||
@@ -196,8 +196,7 @@ class RegistrationForm(forms.Form):
|
||||
def clean_password(self):
|
||||
password1 = self.cleaned_data.get('password', '')
|
||||
user = User(email=self.cleaned_data.get('email'))
|
||||
if validate_password(password1, user=user) is not None:
|
||||
raise forms.ValidationError(_(password_validators_help_texts()), code='pw_invalid')
|
||||
validate_password(password1, user=user)
|
||||
return password1
|
||||
|
||||
def clean_email(self):
|
||||
|
||||
@@ -22,9 +22,7 @@
|
||||
import datetime
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import textwrap
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
@@ -58,8 +56,8 @@ from pretix.base.services.currencies import SOURCE_NAMES
|
||||
from pretix.base.signals import register_invoice_renderers
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.helpers.reportlab import (
|
||||
FontFallbackParagraph, ThumbnailingImageReader, register_ttf_font_if_new,
|
||||
reshaper,
|
||||
FontFallbackParagraph, PlainTextParagraph, ThumbnailingImageReader,
|
||||
normalize_text, register_ttf_font_if_new, reshaper,
|
||||
)
|
||||
from pretix.presale.style import get_fonts
|
||||
|
||||
@@ -259,18 +257,8 @@ class BaseReportlabInvoiceRenderer(BaseInvoiceRenderer):
|
||||
register_ttf_font_if_new(family + ' B I', finders.find(styles['bolditalic']['truetype']))
|
||||
|
||||
def _normalize(self, text):
|
||||
# reportlab does not support unicode combination characters
|
||||
# It's important we do this before we use ArabicReshaper
|
||||
text = unicodedata.normalize("NFKC", text)
|
||||
|
||||
# reportlab does not support RTL, ligature-heavy scripts like Arabic. Therefore, we use ArabicReshaper
|
||||
# to resolve all ligatures and python-bidi to switch RTL texts.
|
||||
try:
|
||||
text = "<br />".join(get_display(reshaper.reshape(l)) for l in re.split("<br ?/>", text))
|
||||
except:
|
||||
logger.exception('Reshaping/Bidi fixes failed on string {}'.format(repr(text)))
|
||||
|
||||
return text
|
||||
# alias kept for plugin compatibility
|
||||
return normalize_text(text)
|
||||
|
||||
def _upper(self, val):
|
||||
# We uppercase labels, but not in every language
|
||||
@@ -351,10 +339,15 @@ class BaseReportlabInvoiceRenderer(BaseInvoiceRenderer):
|
||||
return 'invoice.pdf', 'application/pdf', buffer.read()
|
||||
|
||||
def _clean_text(self, text, tags=None):
|
||||
return self._normalize(bleach.clean(
|
||||
text,
|
||||
tags=set(tags) if tags else set()
|
||||
).strip().replace('<br>', '<br />').replace('\n', '<br />\n'))
|
||||
# For backwards compatibility with customer content, we need to support tags like <br> and <b> in a few text
|
||||
# fields. Therefore, we can't use PlainTextParagraph for these, but run bleach instead to limit the allowed
|
||||
# tags.
|
||||
return self._normalize(
|
||||
bleach.clean(
|
||||
text,
|
||||
tags=set(tags) if tags else set()
|
||||
).strip().replace('<br>', '<br />').replace('\n', '<br />\n')
|
||||
)
|
||||
|
||||
|
||||
class PaidMarker(Flowable):
|
||||
@@ -405,8 +398,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
invoice_to_top = 52 * mm
|
||||
|
||||
def _draw_invoice_to(self, canvas):
|
||||
p = FontFallbackParagraph(self._clean_text(self.invoice.address_invoice_to),
|
||||
style=self.stylesheet['Normal'])
|
||||
p = PlainTextParagraph(self.invoice.address_invoice_to, style=self.stylesheet['Normal'])
|
||||
p.wrapOn(canvas, self.invoice_to_width, self.invoice_to_height)
|
||||
p_size = p.wrap(self.invoice_to_width, self.invoice_to_height)
|
||||
p.drawOn(canvas, self.invoice_to_left, self.pagesize[1] - p_size[1] - self.invoice_to_top)
|
||||
@@ -417,8 +409,8 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
invoice_from_top = 17 * mm
|
||||
|
||||
def _draw_invoice_from(self, canvas):
|
||||
p = FontFallbackParagraph(
|
||||
self._clean_text(self.invoice.full_invoice_from),
|
||||
p = PlainTextParagraph(
|
||||
self.invoice.full_invoice_from,
|
||||
style=self.stylesheet['InvoiceFrom']
|
||||
)
|
||||
p.wrapOn(canvas, self.invoice_from_width, self.invoice_from_height)
|
||||
@@ -548,13 +540,12 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
def _draw_event(self, canvas):
|
||||
def shorten(txt):
|
||||
txt = str(txt)
|
||||
txt = bleach.clean(txt, tags=set()).strip()
|
||||
p = FontFallbackParagraph(self._normalize(txt.strip().replace('\n', '<br />\n')), style=self.stylesheet['Normal'])
|
||||
p = PlainTextParagraph(txt, style=self.stylesheet['Normal'])
|
||||
p_size = p.wrap(self.event_width, self.event_height)
|
||||
|
||||
while p_size[1] > 2 * self.stylesheet['Normal'].leading:
|
||||
txt = ' '.join(txt.replace('…', '').split()[:-1]) + '…'
|
||||
p = FontFallbackParagraph(self._normalize(txt.strip().replace('\n', '<br />\n')), style=self.stylesheet['Normal'])
|
||||
p = PlainTextParagraph(txt, style=self.stylesheet['Normal'])
|
||||
p_size = p.wrap(self.event_width, self.event_height)
|
||||
return txt
|
||||
|
||||
@@ -572,7 +563,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
else:
|
||||
p_str = shorten(self.invoice.event.name)
|
||||
|
||||
p = FontFallbackParagraph(self._normalize(p_str.strip().replace('\n', '<br />\n')), style=self.stylesheet['Normal'])
|
||||
p = PlainTextParagraph(p_str, style=self.stylesheet['Normal'])
|
||||
p.wrapOn(canvas, self.event_width, self.event_height)
|
||||
p_size = p.wrap(self.event_width, self.event_height)
|
||||
p.drawOn(canvas, self.event_left, self.pagesize[1] - self.event_top - p_size[1])
|
||||
@@ -645,39 +636,37 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
|
||||
type_info_text = self.invoice.transmission_type_instance.pdf_info_text()
|
||||
if type_info_text:
|
||||
story.append(FontFallbackParagraph(
|
||||
story.append(PlainTextParagraph(
|
||||
type_info_text,
|
||||
self.stylesheet['WarningBlock']
|
||||
))
|
||||
|
||||
if self.invoice.custom_field:
|
||||
story.append(FontFallbackParagraph(
|
||||
story.append(PlainTextParagraph(
|
||||
'{}: {}'.format(
|
||||
self._clean_text(str(self.invoice.event.settings.invoice_address_custom_field)),
|
||||
self._clean_text(self.invoice.custom_field),
|
||||
str(self.invoice.event.settings.invoice_address_custom_field),
|
||||
self.invoice.custom_field,
|
||||
),
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
if self.invoice.internal_reference:
|
||||
story.append(FontFallbackParagraph(
|
||||
self._normalize(pgettext('invoice', 'Customer reference: {reference}').format(
|
||||
reference=self._clean_text(self.invoice.internal_reference),
|
||||
)),
|
||||
story.append(PlainTextParagraph(
|
||||
pgettext('invoice', 'Customer reference: {reference}').format(
|
||||
reference=self.invoice.internal_reference,
|
||||
),
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
if self.invoice.invoice_to_vat_id:
|
||||
story.append(FontFallbackParagraph(
|
||||
self._normalize(pgettext('invoice', 'Customer VAT ID')) + ': ' +
|
||||
self._clean_text(self.invoice.invoice_to_vat_id),
|
||||
story.append(PlainTextParagraph(
|
||||
pgettext('invoice', 'Customer VAT ID') + ': ' + self.invoice.invoice_to_vat_id,
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
if self.invoice.invoice_to_beneficiary:
|
||||
story.append(FontFallbackParagraph(
|
||||
self._normalize(pgettext('invoice', 'Beneficiary')) + ':<br />' +
|
||||
self._clean_text(self.invoice.invoice_to_beneficiary),
|
||||
story.append(PlainTextParagraph(
|
||||
pgettext('invoice', 'Beneficiary') + ':\n' + self.invoice.invoice_to_beneficiary,
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
@@ -707,11 +696,11 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
|
||||
story = [
|
||||
NextPageTemplate('FirstPage'),
|
||||
FontFallbackParagraph(
|
||||
self._normalize(
|
||||
PlainTextParagraph(
|
||||
(
|
||||
pgettext('invoice', 'Tax Invoice') if str(self.invoice.invoice_from_country) == 'AU'
|
||||
else pgettext('invoice', 'Invoice')
|
||||
) if not self.invoice.is_cancellation else self._normalize(pgettext('invoice', 'Cancellation')),
|
||||
) if not self.invoice.is_cancellation else pgettext('invoice', 'Cancellation'),
|
||||
self.stylesheet['Heading1']
|
||||
),
|
||||
Spacer(1, 5 * mm),
|
||||
@@ -733,17 +722,17 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
]
|
||||
if has_taxes:
|
||||
tdata = [(
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Description')), self.stylesheet['Bold']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Qty')), self.stylesheet['BoldRightNoSplit']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Tax rate')), self.stylesheet['BoldRightNoSplit']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Net')), self.stylesheet['BoldRightNoSplit']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Gross')), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Description'), self.stylesheet['Bold']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Qty'), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Tax rate'), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Net'), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Gross'), self.stylesheet['BoldRightNoSplit']),
|
||||
)]
|
||||
else:
|
||||
tdata = [(
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Description')), self.stylesheet['Bold']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Qty')), self.stylesheet['BoldRightNoSplit']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Amount')), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Description'), self.stylesheet['Bold']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Qty'), self.stylesheet['BoldRightNoSplit']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Amount'), self.stylesheet['BoldRightNoSplit']),
|
||||
)]
|
||||
|
||||
def _group_key(line):
|
||||
@@ -780,8 +769,8 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
max_height = self.stylesheet['Normal'].leading * 5
|
||||
p_style = self.stylesheet['Normal']
|
||||
for __ in range(1000):
|
||||
p = FontFallbackParagraph(
|
||||
self._clean_text(curr_description, tags=['br']),
|
||||
p = PlainTextParagraph(
|
||||
curr_description,
|
||||
p_style
|
||||
)
|
||||
h = p.wrap(max_width, doc.height)[1]
|
||||
@@ -862,7 +851,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
# Group together at the end of the invoice
|
||||
request_show_service_date = period_line
|
||||
elif period_line:
|
||||
description_p_list.append(FontFallbackParagraph(
|
||||
description_p_list.append(PlainTextParagraph(
|
||||
period_line,
|
||||
self.stylesheet['Fineprint']
|
||||
))
|
||||
@@ -874,7 +863,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
net_price=money_filter(net_value, self.invoice.event.currency),
|
||||
gross_price=money_filter(gross_value, self.invoice.event.currency),
|
||||
)
|
||||
description_p_list.append(FontFallbackParagraph(
|
||||
description_p_list.append(PlainTextParagraph(
|
||||
single_price_line,
|
||||
self.stylesheet['Fineprint']
|
||||
))
|
||||
@@ -883,11 +872,11 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
description_p_list.pop(0),
|
||||
str(len(lines)),
|
||||
localize(tax_rate) + " %",
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(net_value * len(lines), self.invoice.event.currency).replace('\xa0', ' '),
|
||||
self.stylesheet['NormalRight']
|
||||
),
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(gross_value * len(lines), self.invoice.event.currency).replace('\xa0', ' '),
|
||||
self.stylesheet['NormalRight']
|
||||
),
|
||||
@@ -904,14 +893,14 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
single_price_line = pgettext('invoice', 'Single price: {price}').format(
|
||||
price=money_filter(gross_value, self.invoice.event.currency),
|
||||
)
|
||||
description_p_list.append(FontFallbackParagraph(
|
||||
description_p_list.append(PlainTextParagraph(
|
||||
single_price_line,
|
||||
self.stylesheet['Fineprint']
|
||||
))
|
||||
tdata.append((
|
||||
description_p_list.pop(0),
|
||||
str(len(lines)),
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(gross_value * len(lines), self.invoice.event.currency).replace('\xa0', ' '),
|
||||
self.stylesheet['NormalRight']
|
||||
),
|
||||
@@ -944,12 +933,12 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
|
||||
if has_taxes:
|
||||
tdata.append([
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Invoice total')), self.stylesheet['Bold']), '', '', '',
|
||||
PlainTextParagraph(pgettext('invoice', 'Invoice total'), self.stylesheet['Bold']), '', '', '',
|
||||
money_filter(total, self.invoice.event.currency)
|
||||
])
|
||||
else:
|
||||
tdata.append([
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Invoice total')), self.stylesheet['Bold']), '',
|
||||
PlainTextParagraph(pgettext('invoice', 'Invoice total'), self.stylesheet['Bold']), '',
|
||||
money_filter(total, self.invoice.event.currency)
|
||||
])
|
||||
|
||||
@@ -958,12 +947,12 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
pending_sum = self.invoice.order.pending_sum
|
||||
if pending_sum != total:
|
||||
tdata.append(
|
||||
[FontFallbackParagraph(self._normalize(pgettext('invoice', 'Received payments')), self.stylesheet['Normal'])] +
|
||||
[PlainTextParagraph(pgettext('invoice', 'Received payments'), self.stylesheet['Normal'])] +
|
||||
(['', '', ''] if has_taxes else ['']) +
|
||||
[money_filter(pending_sum - total, self.invoice.event.currency)]
|
||||
)
|
||||
tdata.append(
|
||||
[FontFallbackParagraph(self._normalize(pgettext('invoice', 'Outstanding payments')), self.stylesheet['Bold'])] +
|
||||
[PlainTextParagraph(pgettext('invoice', 'Outstanding payments'), self.stylesheet['Bold'])] +
|
||||
(['', '', ''] if has_taxes else ['']) +
|
||||
[money_filter(pending_sum, self.invoice.event.currency)]
|
||||
)
|
||||
@@ -980,12 +969,12 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
s=Sum('amount')
|
||||
)['s'] or Decimal('0.00')
|
||||
tdata.append(
|
||||
[FontFallbackParagraph(self._normalize(pgettext('invoice', 'Paid by gift card')), self.stylesheet['Normal'])] +
|
||||
[PlainTextParagraph(pgettext('invoice', 'Paid by gift card'), self.stylesheet['Normal'])] +
|
||||
(['', '', ''] if has_taxes else ['']) +
|
||||
[money_filter(giftcard_sum, self.invoice.event.currency)]
|
||||
)
|
||||
tdata.append(
|
||||
[FontFallbackParagraph(self._normalize(pgettext('invoice', 'Remaining amount')), self.stylesheet['Bold'])] +
|
||||
[PlainTextParagraph(pgettext('invoice', 'Remaining amount'), self.stylesheet['Bold'])] +
|
||||
(['', '', ''] if has_taxes else ['']) +
|
||||
[money_filter(total - giftcard_sum, self.invoice.event.currency)]
|
||||
)
|
||||
@@ -1008,14 +997,14 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
story.append(Spacer(1, 10 * mm))
|
||||
|
||||
if request_show_service_date:
|
||||
story.append(FontFallbackParagraph(
|
||||
self._normalize(pgettext('invoice', 'Invoice period: {daterange}').format(daterange=request_show_service_date)),
|
||||
story.append(PlainTextParagraph(
|
||||
pgettext('invoice', 'Invoice period: {daterange}').format(daterange=request_show_service_date),
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
if self.invoice.payment_provider_text:
|
||||
story.append(FontFallbackParagraph(
|
||||
self._normalize(self.invoice.payment_provider_text),
|
||||
self._clean_text(self.invoice.payment_provider_text, tags=['br', 'b']),
|
||||
self.stylesheet['Normal']
|
||||
))
|
||||
|
||||
@@ -1039,10 +1028,10 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
('FONTNAME', (0, 0), (-1, -1), self.font_regular),
|
||||
]
|
||||
thead = [
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Tax rate')), self.stylesheet['Fineprint']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Net value')), self.stylesheet['FineprintRight']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Gross value')), self.stylesheet['FineprintRight']),
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Tax')), self.stylesheet['FineprintRight']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Tax rate'), self.stylesheet['Fineprint']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Net value'), self.stylesheet['FineprintRight']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Gross value'), self.stylesheet['FineprintRight']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Tax'), self.stylesheet['FineprintRight']),
|
||||
''
|
||||
]
|
||||
tdata = [thead]
|
||||
@@ -1053,7 +1042,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
continue
|
||||
tax = taxvalue_map[idx]
|
||||
tdata.append([
|
||||
FontFallbackParagraph(self._normalize(localize(rate) + " % " + name), self.stylesheet['Fineprint']),
|
||||
PlainTextParagraph(localize(rate) + " % " + name, self.stylesheet['Fineprint']),
|
||||
money_filter(gross - tax, self.invoice.event.currency),
|
||||
money_filter(gross, self.invoice.event.currency),
|
||||
money_filter(tax, self.invoice.event.currency),
|
||||
@@ -1072,7 +1061,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
table.setStyle(TableStyle(tstyledata))
|
||||
story.append(Spacer(5 * mm, 5 * mm))
|
||||
story.append(KeepTogether([
|
||||
FontFallbackParagraph(self._normalize(pgettext('invoice', 'Included taxes')), self.stylesheet['FineprintHeading']),
|
||||
PlainTextParagraph(pgettext('invoice', 'Included taxes'), self.stylesheet['FineprintHeading']),
|
||||
table
|
||||
]))
|
||||
|
||||
@@ -1089,7 +1078,7 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
net = gross - tax
|
||||
|
||||
tdata.append([
|
||||
FontFallbackParagraph(self._normalize(localize(rate) + " % " + name), self.stylesheet['Fineprint']),
|
||||
PlainTextParagraph(localize(rate) + " % " + name, self.stylesheet['Fineprint']),
|
||||
fmt(net), fmt(gross), fmt(tax), ''
|
||||
])
|
||||
|
||||
@@ -1098,13 +1087,13 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
|
||||
story.append(KeepTogether([
|
||||
Spacer(1, height=2 * mm),
|
||||
FontFallbackParagraph(
|
||||
self._normalize(pgettext(
|
||||
PlainTextParagraph(
|
||||
pgettext(
|
||||
'invoice', 'Using the conversion rate of 1:{rate} as published by the {authority} on '
|
||||
'{date}, this corresponds to:'
|
||||
).format(rate=localize(self.invoice.foreign_currency_rate),
|
||||
authority=SOURCE_NAMES.get(self.invoice.foreign_currency_source, "?"),
|
||||
date=date_format(self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT"))),
|
||||
date=date_format(self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT")),
|
||||
self.stylesheet['Fineprint']
|
||||
),
|
||||
Spacer(1, height=3 * mm),
|
||||
@@ -1113,14 +1102,14 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
|
||||
elif self.invoice.foreign_currency_display and self.invoice.foreign_currency_rate:
|
||||
foreign_total = round_decimal(total * self.invoice.foreign_currency_rate)
|
||||
story.append(Spacer(1, 5 * mm))
|
||||
story.append(FontFallbackParagraph(self._normalize(
|
||||
story.append(PlainTextParagraph(
|
||||
pgettext(
|
||||
'invoice', 'Using the conversion rate of 1:{rate} as published by the {authority} on '
|
||||
'{date}, the invoice total corresponds to {total}.'
|
||||
).format(rate=localize(self.invoice.foreign_currency_rate),
|
||||
date=date_format(self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT"),
|
||||
authority=SOURCE_NAMES.get(self.invoice.foreign_currency_source, "?"),
|
||||
total=fmt(foreign_total))),
|
||||
total=fmt(foreign_total)),
|
||||
self.stylesheet['Fineprint']
|
||||
))
|
||||
|
||||
@@ -1162,11 +1151,8 @@ class Modern1Renderer(ClassicInvoiceRenderer):
|
||||
def _draw_invoice_from(self, canvas):
|
||||
if not self.invoice.invoice_from:
|
||||
return
|
||||
c = [
|
||||
self._clean_text(l)
|
||||
for l in self.invoice.address_invoice_from.strip().split('\n')
|
||||
]
|
||||
p = FontFallbackParagraph(self._normalize(' · '.join(c)), style=self.stylesheet['Sender'])
|
||||
c = self.invoice.address_invoice_from.strip().split('\n')
|
||||
p = PlainTextParagraph(' · '.join(c), style=self.stylesheet['Sender'])
|
||||
p.wrapOn(canvas, self.invoice_to_width, 15.7 * mm)
|
||||
p.drawOn(canvas, self.invoice_to_left, self.pagesize[1] - self.invoice_to_top + 2 * mm)
|
||||
super()._draw_invoice_from(canvas)
|
||||
@@ -1225,8 +1211,8 @@ class Modern1Renderer(ClassicInvoiceRenderer):
|
||||
_draw(pgettext('invoice', 'Order code'), self.invoice.order.full_code, value_size, self.left_margin, 45 * mm, **kwargs)
|
||||
]
|
||||
|
||||
p = FontFallbackParagraph(
|
||||
self._normalize(date_format(self.invoice.date, "DATE_FORMAT")),
|
||||
p = PlainTextParagraph(
|
||||
date_format(self.invoice.date, "DATE_FORMAT"),
|
||||
style=ParagraphStyle(name=f'Normal{value_size}', fontName=self.font_regular, fontSize=value_size, leading=value_size * 1.2)
|
||||
)
|
||||
w = stringWidth(p.text, p.frags[0].fontName, p.frags[0].fontSize)
|
||||
@@ -1283,7 +1269,7 @@ class Modern1SimplifiedRenderer(Modern1Renderer):
|
||||
i = []
|
||||
|
||||
if not self.invoice.event.has_subevents and self.invoice.event.settings.show_dates_on_frontpage:
|
||||
i.append(FontFallbackParagraph(
|
||||
i.append(PlainTextParagraph(
|
||||
pgettext('invoice', 'Event date: {date_range}').format(
|
||||
date_range=self.invoice.event.get_date_range_display(),
|
||||
),
|
||||
|
||||
@@ -19,8 +19,7 @@
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import datetime
|
||||
from dataclasses import dataclass
|
||||
|
||||
# This file is based on an earlier version of pretix which was released under the Apache License 2.0. The full text of
|
||||
# the Apache License 2.0 can be obtained at <http://www.apache.org/licenses/LICENSE-2.0>.
|
||||
#
|
||||
@@ -35,7 +34,6 @@ from dataclasses import dataclass
|
||||
# License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Union
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
@@ -423,33 +421,27 @@ class Voucher(LoggedModel):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_affected_quotas(quota, item, variation, subevent):
|
||||
if quota:
|
||||
return {quota}
|
||||
elif item and variation:
|
||||
return set(variation.quotas.filter(subevent=subevent))
|
||||
elif item and not item.has_variations:
|
||||
return set(item.quotas.filter(subevent=subevent))
|
||||
elif item and item.has_variations:
|
||||
return set(
|
||||
Quota.objects.filter(
|
||||
pk__in=Quota.variations.through.objects.filter(
|
||||
itemvariation__item=item,
|
||||
quota__subevent=subevent,
|
||||
).values('quota_id')
|
||||
)
|
||||
)
|
||||
else:
|
||||
return set()
|
||||
|
||||
@staticmethod
|
||||
def clean_quota_get_ignored(voucher_data: Union["VoucherBulkData", "Voucher"]):
|
||||
if voucher_data:
|
||||
valid = voucher_data.valid_until is None or voucher_data.valid_until >= now()
|
||||
if valid and voucher_data.block_quota and voucher_data.max_usages > voucher_data.redeemed:
|
||||
return Voucher.get_affected_quotas(voucher_data.quota, voucher_data.item, voucher_data.variation, voucher_data.subevent)
|
||||
|
||||
return set()
|
||||
def clean_quota_get_ignored(old_instance):
|
||||
quotas = set()
|
||||
was_valid = old_instance and (
|
||||
old_instance.valid_until is None or old_instance.valid_until >= now()
|
||||
)
|
||||
if old_instance and old_instance.block_quota and was_valid:
|
||||
if old_instance.quota:
|
||||
quotas.add(old_instance.quota)
|
||||
elif old_instance.variation:
|
||||
quotas |= set(old_instance.variation.quotas.filter(subevent=old_instance.subevent))
|
||||
elif old_instance.item:
|
||||
if old_instance.item.has_variations:
|
||||
quotas |= set(
|
||||
Quota.objects.filter(pk__in=Quota.variations.through.objects.filter(
|
||||
itemvariation__item=old_instance.item,
|
||||
quota__subevent=old_instance.subevent,
|
||||
).values('quota_id'))
|
||||
)
|
||||
else:
|
||||
quotas |= set(old_instance.item.quotas.filter(subevent=old_instance.subevent))
|
||||
return quotas
|
||||
|
||||
@staticmethod
|
||||
def clean_quota_check(data, cnt, old_instance, event, quota, item, variation):
|
||||
@@ -461,8 +453,22 @@ class Voucher(LoggedModel):
|
||||
if event.has_subevents and data.get('block_quota') and not data.get('subevent'):
|
||||
raise ValidationError(_('If you want this voucher to block quota, you need to select a specific date.'))
|
||||
|
||||
new_quotas = Voucher.get_affected_quotas(quota, item, variation, data.get('subevent'))
|
||||
if not new_quotas:
|
||||
if quota:
|
||||
new_quotas = {quota}
|
||||
elif item and variation:
|
||||
new_quotas = set(variation.quotas.filter(subevent=data.get('subevent')))
|
||||
elif item and not item.has_variations:
|
||||
new_quotas = set(item.quotas.filter(subevent=data.get('subevent')))
|
||||
elif item and item.has_variations:
|
||||
new_quotas = set(
|
||||
Quota.objects.filter(
|
||||
pk__in=Quota.variations.through.objects.filter(
|
||||
itemvariation__item=item,
|
||||
quota__subevent=data.get('subevent'),
|
||||
).values('quota_id')
|
||||
)
|
||||
)
|
||||
else:
|
||||
raise ValidationError(_('You need to select a specific product or quota if this voucher should reserve '
|
||||
'tickets.'))
|
||||
|
||||
@@ -638,16 +644,3 @@ class Voucher(LoggedModel):
|
||||
]
|
||||
).aggregate(s=Sum('voucher_budget_use'))['s'] or Decimal('0.00')
|
||||
return ops
|
||||
|
||||
|
||||
@dataclass
|
||||
class VoucherBulkData:
|
||||
item: object
|
||||
variation: object
|
||||
quota: object
|
||||
block_quota: bool
|
||||
valid_until: datetime.datetime
|
||||
subevent: object
|
||||
redeemed: int
|
||||
max_usages: int
|
||||
allow_ignore_quota: bool
|
||||
|
||||
@@ -1045,7 +1045,7 @@ class Renderer:
|
||||
except:
|
||||
logger.exception('Reshaping/Bidi fixes failed on string {}'.format(repr(text)))
|
||||
|
||||
p = Paragraph(text, style=style)
|
||||
p = Paragraph(text, style=style) # not using AutoEscapeParagraph is safe as we escape above
|
||||
return p, ad, lineheight
|
||||
|
||||
def _draw_textcontainer(self, canvas: Canvas, op: OrderPosition, order: Order, o: dict):
|
||||
|
||||
@@ -411,7 +411,7 @@ def mail_send_task(self, **kwargs) -> bool:
|
||||
try:
|
||||
outgoing_mail = OutgoingMail.objects.select_for_update(of=OF_SELF).get(pk=outgoing_mail)
|
||||
except OutgoingMail.DoesNotExist:
|
||||
logger.info(f"Ignoring job for non existing email {outgoing_mail.guid}")
|
||||
logger.info(f"Ignoring job for non existing email {outgoing_mail}")
|
||||
return False
|
||||
if outgoing_mail.status == OutgoingMail.STATUS_INFLIGHT:
|
||||
logger.info(f"Ignoring job for inflight email {outgoing_mail.guid}")
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
{% load i18n %}
|
||||
{% load rich_text %}
|
||||
{% load static %}
|
||||
{% load wrap_in %}
|
||||
{% block title %}{% trans "Redirect" %}{% endblock %}
|
||||
{% block content %}
|
||||
<i class="fa fa-link fa-fw big-icon"></i>
|
||||
<div class="error-details">
|
||||
<h1>{% trans "Redirect" %}</h1>
|
||||
<h3>
|
||||
{% blocktrans trimmed with host="<strong>"|add:hostname|add:"</strong>"|safe %}
|
||||
{% blocktrans trimmed with host=hostname|wrap_in:'strong' %}
|
||||
The link you clicked on wants to redirect you to a destination on the website {{ host }}.
|
||||
{% endblocktrans %}
|
||||
{% blocktrans trimmed %}
|
||||
|
||||
@@ -32,20 +32,16 @@
|
||||
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
import copy
|
||||
import csv
|
||||
from collections import Counter, namedtuple
|
||||
from collections import namedtuple
|
||||
from io import StringIO
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
||||
from django.core.validators import EmailValidator
|
||||
from django.db.models import Count, F, Max
|
||||
from django.db.models.functions import Upper
|
||||
from django.forms.utils import ErrorDict
|
||||
from django.urls import reverse
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext_lazy as _, pgettext_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_scopes.forms import SafeModelChoiceField
|
||||
|
||||
from pretix.base.email import get_available_placeholders
|
||||
@@ -54,10 +50,7 @@ from pretix.base.forms import (
|
||||
)
|
||||
from pretix.base.forms.widgets import format_placeholders_help_text
|
||||
from pretix.base.i18n import language
|
||||
from pretix.base.models import Item, ItemVariation, Quota, SubEvent, Voucher
|
||||
from pretix.base.models.vouchers import VoucherBulkData
|
||||
from pretix.base.services.locking import lock_objects
|
||||
from pretix.base.services.quotas import QuotaAvailability
|
||||
from pretix.base.models import Item, Voucher
|
||||
from pretix.control.forms import SplitDateTimeField, SplitDateTimePickerWidget
|
||||
from pretix.control.forms.widgets import Select2, Select2ItemVarQuota
|
||||
from pretix.control.signals import voucher_form_validation
|
||||
@@ -112,17 +105,15 @@ class VoucherForm(I18nModelForm):
|
||||
except Item.DoesNotExist:
|
||||
pass
|
||||
super().__init__(*args, **kwargs)
|
||||
if not self.event and self.instance:
|
||||
self.event = self.instance.event
|
||||
|
||||
if self.event.has_subevents:
|
||||
self.fields['subevent'].queryset = self.event.subevents.all()
|
||||
if instance.event.has_subevents:
|
||||
self.fields['subevent'].queryset = instance.event.subevents.all()
|
||||
self.fields['subevent'].widget = Select2(
|
||||
attrs={
|
||||
'data-model-select2': 'event',
|
||||
'data-select2-url': reverse('control:event.subevents.select2', kwargs={
|
||||
'event': self.event.slug,
|
||||
'organizer': self.event.organizer.slug,
|
||||
'event': instance.event.slug,
|
||||
'organizer': instance.event.organizer.slug,
|
||||
}),
|
||||
}
|
||||
)
|
||||
@@ -132,19 +123,18 @@ class VoucherForm(I18nModelForm):
|
||||
del self.fields['subevent']
|
||||
|
||||
choices = []
|
||||
prefix = (self.prefix + '-') if self.prefix else ''
|
||||
if 'itemvar' in initial or (self.data and prefix + 'itemvar' in self.data):
|
||||
iv = self.data.get(prefix + 'itemvar', '') or initial.get('itemvar', '') or ''
|
||||
if 'itemvar' in initial or (self.data and 'itemvar' in self.data):
|
||||
iv = self.data.get('itemvar') or initial.get('itemvar', '')
|
||||
if iv.startswith('q-'):
|
||||
q = self.event.quotas.get(pk=iv[2:])
|
||||
q = self.instance.event.quotas.get(pk=iv[2:])
|
||||
choices.append(('q-%d' % q.pk, _('Any product in quota "{quota}"').format(quota=q)))
|
||||
elif '-' in iv:
|
||||
itemid, varid = iv.split('-')
|
||||
i = self.event.items.get(pk=itemid)
|
||||
i = self.instance.event.items.get(pk=itemid)
|
||||
v = i.variations.get(pk=varid)
|
||||
choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (str(i), v.value)))
|
||||
elif iv:
|
||||
i = self.event.items.get(pk=iv)
|
||||
i = self.instance.event.items.get(pk=iv)
|
||||
if i.variations.exists():
|
||||
choices.append((str(i.pk), _('{product} – Any variation').format(product=i)))
|
||||
else:
|
||||
@@ -155,8 +145,8 @@ class VoucherForm(I18nModelForm):
|
||||
attrs={
|
||||
'data-model-select2': 'generic',
|
||||
'data-select2-url': reverse('control:event.vouchers.itemselect2', kwargs={
|
||||
'event': self.event.slug,
|
||||
'organizer': self.event.organizer.slug,
|
||||
'event': instance.event.slug,
|
||||
'organizer': instance.event.organizer.slug,
|
||||
}),
|
||||
'data-placeholder': _('All products')
|
||||
}
|
||||
@@ -164,7 +154,7 @@ class VoucherForm(I18nModelForm):
|
||||
self.fields['itemvar'].required = False
|
||||
self.fields['itemvar'].widget.choices = self.fields['itemvar'].choices
|
||||
|
||||
if self.event.seating_plan or self.event.subevents.filter(seating_plan__isnull=False).exists():
|
||||
if self.instance.event.seating_plan or self.instance.event.subevents.filter(seating_plan__isnull=False).exists():
|
||||
self.fields['seat'] = forms.CharField(
|
||||
label=_("Specific seat ID"),
|
||||
max_length=255,
|
||||
@@ -174,45 +164,40 @@ class VoucherForm(I18nModelForm):
|
||||
help_text=str(self.instance.seat) if self.instance.seat else '',
|
||||
)
|
||||
|
||||
def parse_itemvar(self, data):
|
||||
try:
|
||||
itemid = quotaid = None
|
||||
iv = data.get('itemvar', '')
|
||||
if iv.startswith('q-'):
|
||||
quotaid = iv[2:]
|
||||
elif '-' in iv:
|
||||
itemid, varid = iv.split('-')
|
||||
elif iv:
|
||||
itemid, varid = iv, None
|
||||
else:
|
||||
itemid, varid = None, None
|
||||
|
||||
if itemid:
|
||||
item = self.event.items.get(pk=itemid)
|
||||
if varid:
|
||||
variation = item.variations.get(pk=varid)
|
||||
else:
|
||||
variation = None
|
||||
quota = None
|
||||
elif quotaid:
|
||||
quota = self.event.quotas.get(pk=quotaid)
|
||||
item = None
|
||||
variation = None
|
||||
else:
|
||||
quota = None
|
||||
item = None
|
||||
variation = None
|
||||
|
||||
return (item, variation, quota)
|
||||
|
||||
except ObjectDoesNotExist:
|
||||
raise ValidationError(_("Invalid product selected."))
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
|
||||
if not self._errors:
|
||||
self.instance.item, self.instance.variation, self.instance.quota = self.parse_itemvar(self.data)
|
||||
try:
|
||||
itemid = quotaid = None
|
||||
iv = self.data.get('itemvar', '')
|
||||
if iv.startswith('q-'):
|
||||
quotaid = iv[2:]
|
||||
elif '-' in iv:
|
||||
itemid, varid = iv.split('-')
|
||||
elif iv:
|
||||
itemid, varid = iv, None
|
||||
else:
|
||||
itemid, varid = None, None
|
||||
|
||||
if itemid:
|
||||
self.instance.item = self.instance.event.items.get(pk=itemid)
|
||||
if varid:
|
||||
self.instance.variation = self.instance.item.variations.get(pk=varid)
|
||||
else:
|
||||
self.instance.variation = None
|
||||
self.instance.quota = None
|
||||
elif quotaid:
|
||||
self.instance.quota = self.instance.event.quotas.get(pk=quotaid)
|
||||
self.instance.item = None
|
||||
self.instance.variation = None
|
||||
else:
|
||||
self.instance.quota = None
|
||||
self.instance.item = None
|
||||
self.instance.variation = None
|
||||
|
||||
except ObjectDoesNotExist:
|
||||
raise ValidationError(_("Invalid product selected."))
|
||||
|
||||
if 'codes' in data:
|
||||
data['codes'] = [a.strip() for a in data.get('codes', '').strip().split("\n") if a]
|
||||
@@ -224,7 +209,7 @@ class VoucherForm(I18nModelForm):
|
||||
|
||||
try:
|
||||
Voucher.clean_item_properties(
|
||||
data, self.event,
|
||||
data, self.instance.event,
|
||||
self.instance.quota, self.instance.item, self.instance.variation,
|
||||
seats_given=data.get('seat') or data.get('seats'),
|
||||
block_quota=data.get('block_quota')
|
||||
@@ -244,7 +229,7 @@ class VoucherForm(I18nModelForm):
|
||||
|
||||
try:
|
||||
Voucher.clean_subevent(
|
||||
data, self.event
|
||||
data, self.instance.event
|
||||
)
|
||||
except ValidationError as e:
|
||||
raise ValidationError({"subevent": e.message})
|
||||
@@ -260,19 +245,19 @@ class VoucherForm(I18nModelForm):
|
||||
if check_quota:
|
||||
Voucher.clean_quota_check(
|
||||
data, cnt, self.initial_instance_data,
|
||||
self.event, self.instance.quota, self.instance.item, self.instance.variation
|
||||
self.instance.event, self.instance.quota, self.instance.item, self.instance.variation
|
||||
)
|
||||
Voucher.clean_voucher_code(data, self.event, self.instance.pk)
|
||||
Voucher.clean_voucher_code(data, self.instance.event, self.instance.pk)
|
||||
if 'seat' in self.fields:
|
||||
if data.get('seat'):
|
||||
self.instance.seat = Voucher.clean_seat_id(
|
||||
data, self.instance.item, self.instance.quota, self.event, self.instance.pk
|
||||
data, self.instance.item, self.instance.quota, self.instance.event, self.instance.pk
|
||||
)
|
||||
self.instance.item = self.instance.seat.product
|
||||
else:
|
||||
self.instance.seat = None
|
||||
|
||||
voucher_form_validation.send(sender=self.event, form=self, data=data)
|
||||
voucher_form_validation.send(sender=self.instance.event, form=self, data=data)
|
||||
|
||||
return data
|
||||
|
||||
@@ -280,215 +265,6 @@ class VoucherForm(I18nModelForm):
|
||||
return super().save(commit)
|
||||
|
||||
|
||||
class VoucherBulkEditForm(VoucherForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.mixed_values = kwargs.pop('mixed_values')
|
||||
self.queryset = kwargs.pop('queryset')
|
||||
super().__init__(**kwargs)
|
||||
del self.fields["code"]
|
||||
self.fields.pop("seat", None)
|
||||
|
||||
def is_bulk_checked(self, fieldname):
|
||||
return self.prefix + fieldname in self.data.getlist('_bulk')
|
||||
|
||||
def clean(self):
|
||||
# We skip the parent class because it's not suited for bulk editing and implement custom validation here.
|
||||
# This does not validate *everything* we validate in VoucherForm. For example, we skip validation that one does
|
||||
# not create a voucher for an add-on product or that the seat matches the product to save on complexity.
|
||||
# This is a UX validation only anyway, since one could first create the voucher and then make the product an
|
||||
# add-on product. However, we need to validate everything that we don't want violated in the database.
|
||||
data = super(VoucherForm, self).clean()
|
||||
|
||||
if self.is_bulk_checked("itemvar"):
|
||||
data["item"], data["variation"], data["quota"] = self.parse_itemvar(data)
|
||||
|
||||
if self.is_bulk_checked("max_usages") and "max_usages" in data:
|
||||
max_redeemed = self.queryset.aggregate(m=Max("redeemed"))["m"]
|
||||
if data["max_usages"] < max_redeemed:
|
||||
raise ValidationError(_(
|
||||
"You cannot reduce the maximum number of redemptions to %(max_usages)s, because at least one "
|
||||
"of the selected vouchers has already been redeemed %(max_redeemed)s times."
|
||||
) % {"max_usages": data["max_usages"], "max_redeemed": max_redeemed})
|
||||
|
||||
# Check diff on product and quota usage based on old groups of vouchers
|
||||
if any(self.is_bulk_checked(k) for k in ("max_usages", "itemvar", "block_quota", "valid_until", "subevent")):
|
||||
quota_diff = Counter()
|
||||
|
||||
current_vouchers = self.queryset.order_by().values(
|
||||
"item", "variation", "quota", "block_quota", "valid_until", "subevent", "redeemed", "max_usages",
|
||||
"allow_ignore_quota",
|
||||
).annotate(c=Count("*"))
|
||||
item_cache = {i.pk: i for i in Item.objects.filter(pk__in=[c["item"] for c in current_vouchers])}
|
||||
var_cache = {v.pk: v for v in ItemVariation.objects.filter(pk__in=[c["variation"] for c in current_vouchers])}
|
||||
quota_cache = {q.pk: q for q in Quota.objects.filter(pk__in=[c["quota"] for c in current_vouchers])}
|
||||
subevent_cache = {s.pk: s for s in SubEvent.objects.filter(pk__in=[c["subevent"] for c in current_vouchers])}
|
||||
|
||||
for current in current_vouchers:
|
||||
bulk_count = current.pop('c')
|
||||
current = VoucherBulkData(**current)
|
||||
# Get quotas that are currently used
|
||||
if current.item:
|
||||
current.item = item_cache[current.item]
|
||||
if current.variation:
|
||||
current.variation = var_cache[current.variation]
|
||||
if current.quota:
|
||||
current.quota = quota_cache[current.quota]
|
||||
if current.subevent:
|
||||
current.subevent = subevent_cache[current.subevent]
|
||||
|
||||
old_quotas = Voucher.clean_quota_get_ignored(current)
|
||||
old_amount = max(current.max_usages - current.redeemed, 0) * bulk_count
|
||||
|
||||
# Predict state after change
|
||||
after_change = copy.copy(current)
|
||||
if self.is_bulk_checked("itemvar") and "itemvar" in data:
|
||||
after_change.item = data["item"]
|
||||
after_change.variation = data["variation"]
|
||||
after_change.quota = data["quota"]
|
||||
if self.is_bulk_checked("subevent") and "subevent" in data:
|
||||
after_change.subevent = data["subevent"]
|
||||
if self.is_bulk_checked("max_usages") and "max_usages" in data:
|
||||
after_change.max_usages = data["max_usages"]
|
||||
if self.is_bulk_checked("block_quota") and "block_quota" in data:
|
||||
after_change.block_quota = data["block_quota"]
|
||||
if self.is_bulk_checked("valid_until") and "valid_until" in data:
|
||||
after_change.valid_until = data["valid_until"]
|
||||
if self.is_bulk_checked("allow_ignore_quota") and "allow_ignore_quota" in data:
|
||||
after_change.allow_ignore_quota = data["allow_ignore_quota"]
|
||||
|
||||
if after_change.quota and self.event.has_subevents and not after_change.subevent:
|
||||
raise ValidationError(_("You cannot create a voucher that allows selection of a quota but has no date selected."))
|
||||
|
||||
if after_change.quota and after_change.subevent and after_change.quota.subevent_id != after_change.subevent.pk:
|
||||
raise ValidationError(_("The selected quota does not match the selected subevent."))
|
||||
|
||||
if after_change.block_quota and self.event.has_subevents and not after_change.subevent:
|
||||
raise ValidationError(
|
||||
_('If you want this voucher to block quota, you need to select a specific date.'))
|
||||
|
||||
if after_change.block_quota and not after_change.item and not after_change.quota:
|
||||
raise ValidationError(
|
||||
_('You need to select a specific product or quota if this voucher should reserve '
|
||||
'tickets.')
|
||||
)
|
||||
|
||||
if after_change.allow_ignore_quota:
|
||||
# todo: is this the most useful way to do this?
|
||||
continue
|
||||
|
||||
new_quotas = Voucher.clean_quota_get_ignored(after_change)
|
||||
new_amount = max(after_change.max_usages - after_change.redeemed, 0) * bulk_count
|
||||
|
||||
if new_quotas != old_quotas or new_amount != old_amount:
|
||||
for q in old_quotas:
|
||||
quota_diff[q] -= old_amount
|
||||
for q in new_quotas:
|
||||
quota_diff[q] += new_amount
|
||||
|
||||
if any(v > 0 for q, v in quota_diff.items()):
|
||||
lock_objects([q for q, v in quota_diff.items() if q.size is not None and v > 0], shared_lock_objects=[self.event])
|
||||
qa = QuotaAvailability(count_waitinglist=False)
|
||||
qa.queue(*(q for q, v in quota_diff.items() if v > 0))
|
||||
qa.compute()
|
||||
|
||||
if any(qa.results[q][0] != Quota.AVAILABILITY_OK or (qa.results[q][1] is not None and qa.results[q][1] < required)
|
||||
for q, required in quota_diff.items() if required > 0):
|
||||
raise ValidationError(_(
|
||||
'There is no sufficient quota available to perform this change.'
|
||||
))
|
||||
|
||||
has_seat = self.queryset.filter(seat__isnull=False).exists()
|
||||
if has_seat:
|
||||
if self.is_bulk_checked("max_usages"):
|
||||
raise ValidationError(_(
|
||||
'Changing the maximum number of usages in bulk is not supported if any of the selected vouchers '
|
||||
'is assigned a seat.'
|
||||
))
|
||||
if self.is_bulk_checked("subevent"):
|
||||
raise ValidationError(pgettext_lazy(
|
||||
'subevent',
|
||||
'Changing the date in bulk is not supported if any of the selected vouchers '
|
||||
'is assigned a seat.'
|
||||
))
|
||||
if self.is_bulk_checked("itemvar") and data["quota"]:
|
||||
raise ValidationError(_(
|
||||
'Changing the product to a quota is not supported if any of the selected vouchers '
|
||||
'is assigned a seat.'
|
||||
))
|
||||
|
||||
if self.is_bulk_checked("valid_until"):
|
||||
if data["valid_until"] is None or data["valid_until"] >= now():
|
||||
currently_not_blocked_seats = self.queryset.filter(
|
||||
seat__isnull=False,
|
||||
max_usages__gt=F("redeemed"),
|
||||
valid_until__lt=now(),
|
||||
)
|
||||
if self.event.has_subevents:
|
||||
subevents = self.event.subevents.filter(pk__in=currently_not_blocked_seats.values_list("subevent"))
|
||||
for se in subevents:
|
||||
conflicts = currently_not_blocked_seats.filter(
|
||||
subevent=se
|
||||
).exclude(
|
||||
seat_id__in=se.free_seats().values("pk")
|
||||
)
|
||||
if conflicts:
|
||||
raise ValidationError(_(
|
||||
'This change cannot be completed because not all assigned seats of the vouchers are '
|
||||
'still available'
|
||||
))
|
||||
else:
|
||||
conflicts = currently_not_blocked_seats.exclude(
|
||||
seat_id__in=self.event.free_seats().values("pk")
|
||||
)
|
||||
if conflicts:
|
||||
raise ValidationError(_(
|
||||
'This change cannot be completed because not all assigned seats of the vouchers are '
|
||||
'still available'
|
||||
))
|
||||
|
||||
return data
|
||||
|
||||
def save(self, commit=True):
|
||||
objs = list(self.queryset)
|
||||
fields = set()
|
||||
|
||||
check_map = {
|
||||
'price_mode': '__price',
|
||||
'value': '__price',
|
||||
}
|
||||
for k in self.fields:
|
||||
if not self.is_bulk_checked(check_map.get(k, k)):
|
||||
continue
|
||||
|
||||
if k == 'itemvar':
|
||||
fields.add("item")
|
||||
fields.add("variation")
|
||||
fields.add("quota")
|
||||
else:
|
||||
fields.add(k)
|
||||
for obj in objs:
|
||||
if k == 'itemvar':
|
||||
obj.item = self.cleaned_data["item"]
|
||||
obj.variation = self.cleaned_data["variation"]
|
||||
obj.quota = self.cleaned_data["quota"]
|
||||
else:
|
||||
setattr(obj, k, self.cleaned_data[k])
|
||||
|
||||
fields = [f for f in fields if f != 'itemvars']
|
||||
if fields:
|
||||
Voucher.objects.bulk_update(objs, fields, 200)
|
||||
|
||||
def full_clean(self):
|
||||
if len(self.data) == 0:
|
||||
# form wasn't submitted
|
||||
self._errors = ErrorDict()
|
||||
return
|
||||
super().full_clean()
|
||||
|
||||
def _post_clean(self):
|
||||
pass # skip model-level clean
|
||||
|
||||
|
||||
class VoucherBulkForm(VoucherForm):
|
||||
codes = forms.CharField(
|
||||
widget=forms.Textarea,
|
||||
|
||||
@@ -38,6 +38,7 @@ from pretix import __version__
|
||||
from pretix.base.models import Order, OrderPayment, Transaction
|
||||
from pretix.base.plugins import get_all_plugins
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.helpers.reportlab import PlainTextParagraph
|
||||
from pretix.plugins.reports.exporters import ReportlabExportMixin
|
||||
from pretix.settings import DATA_DIR
|
||||
|
||||
@@ -79,23 +80,23 @@ class SysReport(ReportlabExportMixin):
|
||||
style_small.fontSize = 6
|
||||
|
||||
story = [
|
||||
Paragraph("System report", headlinestyle),
|
||||
PlainTextParagraph("System report", headlinestyle),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph("Usage", subheadlinestyle),
|
||||
PlainTextParagraph("Usage", subheadlinestyle),
|
||||
Spacer(1, 5 * mm),
|
||||
self._usage_table(),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph("Installed versions", subheadlinestyle),
|
||||
PlainTextParagraph("Installed versions", subheadlinestyle),
|
||||
Spacer(1, 5 * mm),
|
||||
self._tech_table(),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph("Plugins", subheadlinestyle),
|
||||
PlainTextParagraph("Plugins", subheadlinestyle),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph(self._get_plugin_versions(), style_small),
|
||||
PlainTextParagraph(self._get_plugin_versions(), style_small),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph("Custom templates", subheadlinestyle),
|
||||
PlainTextParagraph("Custom templates", subheadlinestyle),
|
||||
Spacer(1, 5 * mm),
|
||||
Paragraph(self._get_custom_templates(), style_small),
|
||||
PlainTextParagraph(self._get_custom_templates(), style_small),
|
||||
Spacer(1, 5 * mm),
|
||||
]
|
||||
|
||||
@@ -121,13 +122,13 @@ class SysReport(ReportlabExportMixin):
|
||||
("RIGHTPADDING", (-1, 0), (-1, -1), 0),
|
||||
]
|
||||
tdata = [
|
||||
[Paragraph("Site URL:", style), Paragraph(settings.SITE_URL, style)],
|
||||
[Paragraph("pretix version:", style), Paragraph(__version__, style)],
|
||||
[Paragraph("Python version:", style), Paragraph(sys.version, style)],
|
||||
[Paragraph("Platform:", style), Paragraph(platform.platform(), style)],
|
||||
[PlainTextParagraph("Site URL:", style), Paragraph(settings.SITE_URL, style)],
|
||||
[PlainTextParagraph("pretix version:", style), Paragraph(__version__, style)],
|
||||
[PlainTextParagraph("Python version:", style), Paragraph(sys.version, style)],
|
||||
[PlainTextParagraph("Platform:", style), Paragraph(platform.platform(), style)],
|
||||
[
|
||||
Paragraph("Database engine:", style),
|
||||
Paragraph(settings.DATABASES["default"]["ENGINE"], style),
|
||||
PlainTextParagraph("Database engine:", style),
|
||||
PlainTextParagraph(settings.DATABASES["default"]["ENGINE"], style),
|
||||
],
|
||||
]
|
||||
table = Table(tdata, colWidths=colwidths, repeatRows=0)
|
||||
@@ -206,7 +207,7 @@ class SysReport(ReportlabExportMixin):
|
||||
year_last = now().year
|
||||
tdata = [
|
||||
[
|
||||
Paragraph(l, style_small_head)
|
||||
PlainTextParagraph(l, style_small_head)
|
||||
for l in (
|
||||
"Time frame",
|
||||
"Currency",
|
||||
@@ -257,19 +258,19 @@ class SysReport(ReportlabExportMixin):
|
||||
|
||||
tdata.append(
|
||||
(
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
date_format(first_day, "M Y")
|
||||
+ " – "
|
||||
+ date_format(after_day - timedelta(days=1), "M Y"),
|
||||
style_small,
|
||||
),
|
||||
Paragraph(c, style_small),
|
||||
Paragraph(str(orders_count), style_small) if i == 0 else "",
|
||||
Paragraph(money_filter(revenue_data.get("s_net") or 0, c), style_small),
|
||||
Paragraph(str(testmode_count), style_small) if i == 0 else "",
|
||||
Paragraph(str(unconfirmed_count), style_small) if i == 0 else "",
|
||||
Paragraph(str(revenue_data.get("c") or 0), style_small),
|
||||
Paragraph(money_filter(revenue_data.get("s_gross") or 0, c), style_small),
|
||||
PlainTextParagraph(c, style_small),
|
||||
PlainTextParagraph(str(orders_count), style_small) if i == 0 else "",
|
||||
PlainTextParagraph(money_filter(revenue_data.get("s_net") or 0, c), style_small),
|
||||
PlainTextParagraph(str(testmode_count), style_small) if i == 0 else "",
|
||||
PlainTextParagraph(str(unconfirmed_count), style_small) if i == 0 else "",
|
||||
PlainTextParagraph(str(revenue_data.get("c") or 0), style_small),
|
||||
PlainTextParagraph(money_filter(revenue_data.get("s_gross") or 0, c), style_small),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -19,9 +19,7 @@
|
||||
{% endif %}
|
||||
</h1>
|
||||
|
||||
<script type="application/json" id="editor-data">
|
||||
{{ layout|safe }}
|
||||
</script>
|
||||
{{ layout|json_script:"editor-data" }}
|
||||
<div class="row">
|
||||
<div class="col-md-9">
|
||||
<div class="panel panel-default panel-pdf-editor">
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
{% extends "pretixcontrol/items/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load bootstrap3 %}
|
||||
{% load eventsignal %}
|
||||
{% load eventurl %}
|
||||
{% block title %}{% trans "Change multiple vouchers" %}{% endblock %}
|
||||
{% block inside %}
|
||||
<h1>
|
||||
{% trans "Change multiple vouchers" %}
|
||||
<small>
|
||||
{% blocktrans trimmed with number=vouchers.count %}
|
||||
{{ number }} selected
|
||||
{% endblocktrans %}
|
||||
</small>
|
||||
</h1>
|
||||
<form action="" method="post" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="hidden">
|
||||
{% for v in vouchers %}
|
||||
<input type="hidden" name="voucher" value="{{ v.pk }}">
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% bootstrap_form_errors form %}
|
||||
<fieldset>
|
||||
<legend>{% trans "Voucher details" %}</legend>
|
||||
{% bootstrap_field form.max_usages layout="bulkedit" %}
|
||||
{% bootstrap_field form.valid_until layout="bulkedit" %}
|
||||
{% bootstrap_field form.itemvar layout="bulkedit" %}
|
||||
|
||||
<div class="bulk-edit-field-group">
|
||||
<label class="field-toggle">
|
||||
<input type="checkbox" name="_bulk" value="{{ form.prefix }}__price" {% if form.prefix|add:"__price" in bulk_selected %}checked{% endif %}>
|
||||
{% trans "change" context "form_bulk" %}
|
||||
</label>
|
||||
<div class="field-content">
|
||||
<div class="form-group">
|
||||
<label class="col-md-3 control-label" for="id_tag">{% trans "Price effect" %}</label>
|
||||
<div class="col-md-5">
|
||||
{% bootstrap_field form.price_mode show_label=False form_group_class="" %}
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
{% bootstrap_field form.value show_label=False form_group_class="" %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<div class="col-md-9 col-md-offset-3">
|
||||
<div class="controls">
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed %}
|
||||
If you choose "any product" for a specific quota and choose to reserve quota for this
|
||||
voucher above, the product can still be unavailable to the voucher holder if another quota
|
||||
associated with the product is sold out!
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% if form.subevent %}
|
||||
{% bootstrap_field form.subevent layout="bulkedit" %}
|
||||
{% endif %}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{% trans "Advanced settings" %}</legend>
|
||||
{% bootstrap_field form.block_quota layout="bulkedit" %}
|
||||
{% bootstrap_field form.allow_ignore_quota layout="bulkedit" %}
|
||||
{% bootstrap_field form.min_usages layout="bulkedit" %}
|
||||
{% bootstrap_field form.budget addon_after=request.event.currency layout="bulkedit" %}
|
||||
{% bootstrap_field form.tag layout="bulkedit" %}
|
||||
{% bootstrap_field form.comment layout="bulkedit" %}
|
||||
{% bootstrap_field form.show_hidden_items layout="bulkedit" %}
|
||||
{% bootstrap_field form.all_addons_included layout="bulkedit" %}
|
||||
{% bootstrap_field form.all_bundles_included layout="bulkedit" %}
|
||||
</fieldset>
|
||||
<div class="form-group submit-group">
|
||||
<button type="submit" class="btn btn-primary btn-save">
|
||||
{% trans "Save" %}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -99,9 +99,6 @@
|
||||
</p>
|
||||
<form action="{% url "control:event.vouchers.bulkaction" organizer=request.event.organizer.slug event=request.event.slug %}" method="post">
|
||||
{% csrf_token %}
|
||||
{% for field in filter_form %}
|
||||
{{ field.as_hidden }}
|
||||
{% endfor %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-quotas">
|
||||
<thead>
|
||||
@@ -147,18 +144,6 @@
|
||||
{% endif %}
|
||||
<th></th>
|
||||
</tr>
|
||||
{% if "event.vouchers:write" in request.eventpermset and page_obj.paginator.num_pages > 1 %}
|
||||
<tr class="table-select-all warning hidden">
|
||||
<td>
|
||||
<input type="checkbox" name="__ALL" id="__all" data-results-total="{{ page_obj.paginator.count }}">
|
||||
</td>
|
||||
<td colspan="5">
|
||||
<label for="__all">
|
||||
{% trans "Select all results on other pages as well" %}
|
||||
</label>
|
||||
</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for v in vouchers %}
|
||||
@@ -226,10 +211,6 @@
|
||||
<i class="fa fa-trash" aria-hidden="true"></i>
|
||||
{% trans "Delete selected" %}
|
||||
</button>
|
||||
<button type="submit" class="btn btn-primary btn-save" name="action" value="edit"
|
||||
formaction="{% url "control:event.vouchers.bulkedit" organizer=request.event.organizer.slug event=request.event.slug %}">
|
||||
<i class="fa fa-edit"></i>{% trans "Edit selected" %}
|
||||
</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</form>
|
||||
|
||||
@@ -379,7 +379,6 @@ urlpatterns = [
|
||||
re_path(r'^vouchers/bulk_add$', vouchers.VoucherBulkCreate.as_view(), name='event.vouchers.bulk'),
|
||||
re_path(r'^vouchers/bulk_add/mail_preview$', vouchers.VoucherBulkMailPreview.as_view(), name='event.vouchers.bulk.mail_preview'),
|
||||
re_path(r'^vouchers/bulk_action$', vouchers.VoucherBulkAction.as_view(), name='event.vouchers.bulkaction'),
|
||||
re_path(r'^vouchers/bulk_edit$', vouchers.VoucherBulkUpdateView.as_view(), name='event.vouchers.bulkedit'),
|
||||
re_path(r'^vouchers/import/$', modelimport.VoucherImportView.as_view(), name='event.vouchers.import'),
|
||||
re_path(r'^vouchers/import/(?P<file>[^/]+)/$', modelimport.VoucherProcessView.as_view(), name='event.vouchers.import.process'),
|
||||
re_path(r'^orders/(?P<code>[0-9A-Z]+)/transition$', orders.OrderTransition.as_view(),
|
||||
|
||||
@@ -289,7 +289,7 @@ class BaseEditorView(EventPermissionRequiredMixin, TemplateView):
|
||||
ctx['pdf'] = self.get_current_background()
|
||||
ctx['variables'] = self.get_variables()
|
||||
ctx['images'] = self.get_images()
|
||||
ctx['layout'] = json.dumps(self.get_current_layout())
|
||||
ctx['layout'] = self.get_current_layout()
|
||||
ctx['title'] = self.title
|
||||
ctx['locales'] = [p for p in settings.LANGUAGES if p[0] in self.request.event.settings.locales]
|
||||
ctx['maxfilesize'] = self.maxfilesize
|
||||
|
||||
@@ -40,9 +40,9 @@ import bleach
|
||||
from defusedcsv import csv
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.core.exceptions import PermissionDenied, ValidationError, BadRequest
|
||||
from django.core.exceptions import PermissionDenied, ValidationError
|
||||
from django.db import connection, transaction
|
||||
from django.db.models import Count, Exists, OuterRef, Sum
|
||||
from django.db.models import Exists, OuterRef, Sum
|
||||
from django.http import (
|
||||
Http404, HttpResponse, HttpResponseBadRequest, HttpResponseRedirect,
|
||||
JsonResponse,
|
||||
@@ -55,7 +55,7 @@ from django.utils.safestring import mark_safe
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import (
|
||||
CreateView, FormView, ListView, TemplateView, UpdateView, View,
|
||||
CreateView, ListView, TemplateView, UpdateView, View,
|
||||
)
|
||||
from django_scopes import scopes_disabled
|
||||
|
||||
@@ -70,9 +70,7 @@ from pretix.base.services.vouchers import vouchers_send
|
||||
from pretix.base.templatetags.rich_text import markdown_compile_email
|
||||
from pretix.base.views.tasks import AsyncFormView
|
||||
from pretix.control.forms.filter import VoucherFilterForm, VoucherTagFilterForm
|
||||
from pretix.control.forms.vouchers import (
|
||||
VoucherBulkEditForm, VoucherBulkForm, VoucherForm,
|
||||
)
|
||||
from pretix.control.forms.vouchers import VoucherBulkForm, VoucherForm
|
||||
from pretix.control.permissions import EventPermissionRequiredMixin
|
||||
from pretix.control.signals import voucher_form_class
|
||||
from pretix.control.views import PaginationMixin
|
||||
@@ -82,37 +80,7 @@ from pretix.helpers.models import modelcopy
|
||||
from pretix.multidomain.urlreverse import build_absolute_uri
|
||||
|
||||
|
||||
class VoucherQueryMixin:
|
||||
|
||||
@cached_property
|
||||
def request_data(self):
|
||||
if self.request.method == "POST":
|
||||
return self.request.POST
|
||||
return self.request.GET
|
||||
|
||||
@scopes_disabled() # we have an event check here, and we can save some performance on subqueries
|
||||
def get_queryset(self):
|
||||
qs = self.request.event.vouchers.exclude(
|
||||
Exists(WaitingListEntry.objects.filter(voucher_id=OuterRef('pk')))
|
||||
)
|
||||
if 'voucher' in self.request_data and '__ALL' not in self.request_data:
|
||||
qs = qs.filter(
|
||||
id__in=self.request_data.getlist('voucher')
|
||||
)
|
||||
elif self.request.method == 'GET' or '__ALL' in self.request_data:
|
||||
if self.filter_form.is_valid():
|
||||
qs = self.filter_form.filter_qs(qs)
|
||||
else:
|
||||
raise BadRequest("No vouchers selected")
|
||||
|
||||
return qs
|
||||
|
||||
@cached_property
|
||||
def filter_form(self):
|
||||
return VoucherFilterForm(data=self.request_data, prefix='filter', event=self.request.event)
|
||||
|
||||
|
||||
class VoucherList(VoucherQueryMixin, PaginationMixin, EventPermissionRequiredMixin, ListView):
|
||||
class VoucherList(PaginationMixin, EventPermissionRequiredMixin, ListView):
|
||||
model = Voucher
|
||||
context_object_name = 'vouchers'
|
||||
template_name = 'pretixcontrol/vouchers/index.html'
|
||||
@@ -120,15 +88,25 @@ class VoucherList(VoucherQueryMixin, PaginationMixin, EventPermissionRequiredMix
|
||||
|
||||
@scopes_disabled() # we have an event check here, and we can save some performance on subqueries
|
||||
def get_queryset(self):
|
||||
return Voucher.annotate_budget_used(super().get_queryset().select_related(
|
||||
qs = Voucher.annotate_budget_used(self.request.event.vouchers.exclude(
|
||||
Exists(WaitingListEntry.objects.filter(voucher_id=OuterRef('pk')))
|
||||
).select_related(
|
||||
'item', 'variation', 'seat'
|
||||
))
|
||||
if self.filter_form.is_valid():
|
||||
qs = self.filter_form.filter_qs(qs)
|
||||
|
||||
return qs
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
ctx = super().get_context_data(**kwargs)
|
||||
ctx['filter_form'] = self.filter_form
|
||||
return ctx
|
||||
|
||||
@cached_property
|
||||
def filter_form(self):
|
||||
return VoucherFilterForm(data=self.request.GET, event=self.request.event)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
if request.GET.get("download", "") == "yes":
|
||||
return self._download_csv()
|
||||
@@ -315,12 +293,6 @@ class VoucherUpdate(EventPermissionRequiredMixin, UpdateView):
|
||||
f.disabled = True
|
||||
return form
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return {
|
||||
**super().get_form_kwargs(),
|
||||
"event": self.request.event,
|
||||
}
|
||||
|
||||
def get_object(self, queryset=None) -> VoucherForm:
|
||||
url = resolve(self.request.path_info)
|
||||
try:
|
||||
@@ -631,21 +603,26 @@ class VoucherRNG(EventPermissionRequiredMixin, View):
|
||||
})
|
||||
|
||||
|
||||
class VoucherBulkAction(VoucherQueryMixin, EventPermissionRequiredMixin, View):
|
||||
class VoucherBulkAction(EventPermissionRequiredMixin, View):
|
||||
permission = 'event.vouchers:write'
|
||||
|
||||
@cached_property
|
||||
def objects(self):
|
||||
return self.request.event.vouchers.filter(
|
||||
id__in=self.request.POST.getlist('voucher')
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def post(self, request, *args, **kwargs):
|
||||
if request.POST.get('action') == 'delete':
|
||||
return render(request, 'pretixcontrol/vouchers/delete_bulk.html', {
|
||||
'allowed': self.get_queryset().filter(redeemed=0),
|
||||
'forbidden': self.get_queryset().exclude(redeemed=0),
|
||||
'allowed': self.objects.filter(redeemed=0),
|
||||
'forbidden': self.objects.exclude(redeemed=0),
|
||||
})
|
||||
elif request.POST.get('action') == 'delete_confirm':
|
||||
log_entries = []
|
||||
to_delete = []
|
||||
to_update = []
|
||||
for obj in self.get_queryset():
|
||||
for obj in self.objects:
|
||||
if obj.allow_delete():
|
||||
log_entries.append(obj.log_action('pretix.voucher.deleted', user=self.request.user, save=False))
|
||||
to_delete.append(obj.pk)
|
||||
@@ -655,14 +632,12 @@ class VoucherBulkAction(VoucherQueryMixin, EventPermissionRequiredMixin, View):
|
||||
'bulk': True
|
||||
}, save=False))
|
||||
obj.max_usages = min(obj.redeemed, obj.max_usages)
|
||||
to_update.append(obj)
|
||||
obj.save(update_fields=['max_usages'])
|
||||
|
||||
if to_delete:
|
||||
CartPosition.objects.filter(addon_to__voucher_id__in=to_delete).delete()
|
||||
CartPosition.objects.filter(voucher_id__in=to_delete).delete()
|
||||
Voucher.objects.filter(pk__in=to_delete).delete()
|
||||
if to_update:
|
||||
Voucher.objects.bulk_update(to_update, ['max_usages'])
|
||||
|
||||
LogEntry.bulk_create_and_postprocess(log_entries)
|
||||
messages.success(request, _('The selected vouchers have been deleted or disabled.'))
|
||||
@@ -673,117 +648,3 @@ class VoucherBulkAction(VoucherQueryMixin, EventPermissionRequiredMixin, View):
|
||||
'organizer': self.request.event.organizer.slug,
|
||||
'event': self.request.event.slug,
|
||||
})
|
||||
|
||||
|
||||
class VoucherBulkUpdateView(VoucherQueryMixin, EventPermissionRequiredMixin, FormView):
|
||||
template_name = 'pretixcontrol/vouchers/bulk_edit.html'
|
||||
permission = 'event.vouchers:write'
|
||||
context_object_name = 'vouchers'
|
||||
form_class = VoucherBulkEditForm
|
||||
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().prefetch_related(None).order_by()
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
return HttpResponse(status=405)
|
||||
|
||||
@cached_property
|
||||
def is_submitted(self):
|
||||
# Usually, django considers a form "bound" / "submitted" on every POST request. However, this view is always
|
||||
# called with POST method, even if just to pass the selection of objects to work on, so we want to modify
|
||||
# that behavior
|
||||
return '_bulk' in self.request.POST
|
||||
|
||||
def get_form_kwargs(self):
|
||||
initial = {}
|
||||
mixed_values = set()
|
||||
qs = self.get_queryset().annotate()
|
||||
|
||||
fields = (
|
||||
'valid_until', 'block_quota', 'allow_ignore_quota', 'value', 'tag', 'comment', 'max_usages',
|
||||
'min_usages', 'price_mode', 'subevent', 'show_hidden_items', 'all_addons_included', 'all_bundles_included',
|
||||
'budget',
|
||||
)
|
||||
for f in fields:
|
||||
existing_values = list(qs.order_by(f).values(f).annotate(c=Count('*')))
|
||||
if len(existing_values) == 1:
|
||||
initial[f] = existing_values[0][f]
|
||||
elif len(existing_values) > 1:
|
||||
mixed_values.add(f)
|
||||
if f == "max_usages":
|
||||
initial[f] = 1
|
||||
else:
|
||||
initial[f] = None
|
||||
|
||||
existing_values = list(qs.order_by("item", "variation", "quota").values("item", "variation", "quota").annotate(c=Count('*')))
|
||||
if len(existing_values) == 1:
|
||||
i = existing_values[0]
|
||||
if i["quota"]:
|
||||
initial["itemvar"] = f'q-{i["quota"]}'
|
||||
elif i["variation"]:
|
||||
initial["itemvar"] = f'{i["item"]}-{i["variation"]}'
|
||||
elif i["item"]:
|
||||
initial["itemvar"] = f'{i["item"]}'
|
||||
else:
|
||||
initial["itemvar"] = None
|
||||
elif len(existing_values) > 1:
|
||||
mixed_values.add("itemvar")
|
||||
initial["itemvar"] = None
|
||||
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs['event'] = self.request.event
|
||||
kwargs['prefix'] = 'bulkedit'
|
||||
kwargs['initial'] = initial
|
||||
kwargs['queryset'] = self.get_queryset()
|
||||
kwargs['mixed_values'] = mixed_values
|
||||
if not self.is_submitted:
|
||||
kwargs['data'] = None
|
||||
kwargs['files'] = None
|
||||
return kwargs
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse('control:event.vouchers', kwargs={
|
||||
'organizer': self.request.event.organizer.slug,
|
||||
'event': self.request.event.slug,
|
||||
})
|
||||
|
||||
def form_valid(self, form):
|
||||
log_entries = []
|
||||
|
||||
# Main form
|
||||
form.save()
|
||||
data = {
|
||||
k: v
|
||||
for k, v in form.cleaned_data.items()
|
||||
if k in form.changed_data
|
||||
}
|
||||
data['_raw_bulk_data'] = self.request.POST.dict()
|
||||
for obj in self.get_queryset():
|
||||
log_entries.append(
|
||||
obj.log_action('pretix.voucher.changed', data=data, user=self.request.user, save=False)
|
||||
)
|
||||
|
||||
LogEntry.bulk_create_and_postprocess(log_entries)
|
||||
|
||||
messages.success(self.request, _('Your changes have been saved.'))
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
ctx = super().get_context_data(**kwargs)
|
||||
ctx['vouchers'] = self.get_queryset()
|
||||
ctx['bulk_selected'] = self.request.POST.getlist("_bulk")
|
||||
return ctx
|
||||
|
||||
@transaction.atomic
|
||||
def post(self, request, *args, **kwargs):
|
||||
form = self.get_form()
|
||||
is_valid = (
|
||||
self.is_submitted and
|
||||
form.is_valid()
|
||||
)
|
||||
if is_valid:
|
||||
return self.form_valid(form)
|
||||
else:
|
||||
if self.is_submitted:
|
||||
messages.error(self.request, _('We could not save your changes. See below for details.'))
|
||||
return self.form_invalid(form)
|
||||
|
||||
@@ -29,3 +29,8 @@ class PretixHelpersConfig(AppConfig):
|
||||
def ready(self):
|
||||
from .monkeypatching import monkeypatch_all_at_ready
|
||||
monkeypatch_all_at_ready()
|
||||
|
||||
# Ensure reportlab does not make any calls to the internet or the local disk
|
||||
from reportlab import rl_config
|
||||
rl_config.trustedHosts = []
|
||||
rl_config.trustedSchemes = ['data']
|
||||
|
||||
@@ -24,8 +24,11 @@ from datetime import datetime
|
||||
from http import cookies
|
||||
|
||||
from PIL import Image
|
||||
from django.core.exceptions import SuspiciousFileOperation
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
from pretix.helpers.reportlab import ThumbnailingImageReader
|
||||
|
||||
|
||||
def monkeypatch_vobject_performance():
|
||||
"""
|
||||
@@ -95,8 +98,26 @@ def monkeypatch_cookie_morsel():
|
||||
cookies.Morsel._reserved.setdefault("partitioned", "Partitioned")
|
||||
|
||||
|
||||
def monkeypatch_reportlab_imagereader():
|
||||
from reportlab.lib import utils
|
||||
old_init = utils.ImageReader.__init__
|
||||
|
||||
def new_init(self, fileName, ident=None): # noqa
|
||||
if not isinstance(fileName, Image.Image) and not hasattr(fileName, 'read') and not hasattr(fileName, 'str'):
|
||||
if not isinstance(self, ThumbnailingImageReader):
|
||||
# ThumbnailingImageReader is only used by us explicitly and not by using <img> in html, so it is safe
|
||||
raise SuspiciousFileOperation("reportlab should not be reading images from disk")
|
||||
|
||||
return types.MethodType(old_init, self)(
|
||||
fileName, ident
|
||||
)
|
||||
|
||||
utils.ImageReader.__init__ = new_init
|
||||
|
||||
|
||||
def monkeypatch_all_at_ready():
|
||||
monkeypatch_vobject_performance()
|
||||
monkeypatch_pillow_safer()
|
||||
monkeypatch_requests_timeout()
|
||||
monkeypatch_cookie_morsel()
|
||||
monkeypatch_reportlab_imagereader()
|
||||
|
||||
@@ -20,14 +20,19 @@
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from arabic_reshaper import ArabicReshaper
|
||||
from bidi import get_display
|
||||
from django.conf import settings
|
||||
from django.utils.functional import SimpleLazyObject
|
||||
from django.utils.html import escape
|
||||
from PIL import Image
|
||||
from reportlab.lib.styles import ParagraphStyle
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.platypus import Paragraph
|
||||
|
||||
from pretix.presale.style import get_fonts
|
||||
@@ -70,6 +75,20 @@ reshaper = SimpleLazyObject(lambda: ArabicReshaper(configuration={
|
||||
}))
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
# reportlab does not support unicode combination characters
|
||||
# It's important we do this before we use ArabicReshaper
|
||||
text = unicodedata.normalize("NFKC", text)
|
||||
|
||||
# reportlab does not support RTL, ligature-heavy scripts like Arabic. Therefore, we use ArabicReshaper
|
||||
# to resolve all ligatures and python-bidi to switch RTL texts.
|
||||
try:
|
||||
text = "\n".join(get_display(reshaper.reshape(l)) for l in re.split("\n", text))
|
||||
except:
|
||||
logger.exception('Reshaping/Bidi fixes failed on string {}'.format(repr(text)))
|
||||
return text
|
||||
|
||||
|
||||
class FontFallbackParagraph(Paragraph):
|
||||
def __init__(self, text, style=None, *args, **kwargs):
|
||||
if style is None:
|
||||
@@ -87,6 +106,8 @@ class FontFallbackParagraph(Paragraph):
|
||||
if not text:
|
||||
return True
|
||||
font = pdfmetrics.getFont(font_name)
|
||||
if not isinstance(font, TTFont):
|
||||
return True
|
||||
return all(
|
||||
ord(c) in font.face.charToGlyph or not c.isprintable()
|
||||
for c in text
|
||||
@@ -102,6 +123,24 @@ class FontFallbackParagraph(Paragraph):
|
||||
return family
|
||||
|
||||
|
||||
class PlainTextParagraph(FontFallbackParagraph):
|
||||
def __init__(self, text, style=None, linebreaks=True, *args, **kwargs):
|
||||
if not isinstance(text, str):
|
||||
if hasattr(text, '__html__'):
|
||||
raise ValueError("It is contradictory to pass escaped content to PlainTextParagraph")
|
||||
text = str(text)
|
||||
|
||||
# Normalize unicode and apply reshaping
|
||||
text = normalize_text(text)
|
||||
|
||||
# Escape any HTML in the text
|
||||
text = escape(text)
|
||||
|
||||
if linebreaks:
|
||||
text = text.strip().replace("\n", "<br />\n")
|
||||
super().__init__(text, style, *args, **kwargs)
|
||||
|
||||
|
||||
def register_ttf_font_if_new(name, path):
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#
|
||||
# This file is part of pretix (Community Edition).
|
||||
#
|
||||
# Copyright (C) 2014-2020 Raphael Michel and contributors
|
||||
# Copyright (C) 2020-today pretix GmbH and contributors
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
|
||||
# Public License as published by the Free Software Foundation in version 3 of the License.
|
||||
#
|
||||
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
|
||||
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
|
||||
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
|
||||
# this file, see <https://pretix.eu/about/en/license>.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import logging
|
||||
|
||||
from django import template
|
||||
from django.utils.html import format_html
|
||||
|
||||
register = template.Library()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@register.filter
|
||||
def wrap_in(content, tag_name):
|
||||
return format_html(f'<{tag_name}>{{}}</{tag_name}>', content)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -32,6 +32,7 @@ ausgecheckt
|
||||
ausgeklappt
|
||||
auswahl
|
||||
Authentication
|
||||
Authenticator
|
||||
Authenticator-App
|
||||
Autorisierungscode
|
||||
Autorisierungs-Endpunktes
|
||||
@@ -130,6 +131,7 @@ Eingangsscan
|
||||
Einlassbuchung
|
||||
Einlassdatum
|
||||
Einlasskontrolle
|
||||
Einmalpasswörter
|
||||
einzuchecken
|
||||
email
|
||||
E-Mail-Renderer
|
||||
@@ -163,6 +165,7 @@ Explorer
|
||||
FA
|
||||
Favicon
|
||||
F-Droid
|
||||
freeOTP
|
||||
Footer
|
||||
Footer-Link
|
||||
Footer-Text
|
||||
@@ -557,6 +560,7 @@ Zahlungs-ID
|
||||
Zahlungspflichtig
|
||||
Zehnerkarten
|
||||
Zeitbasiert
|
||||
zeitbasierte
|
||||
Zeitslotbuchung
|
||||
Zimpler
|
||||
ZIP-Datei
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -32,6 +32,7 @@ ausgecheckt
|
||||
ausgeklappt
|
||||
auswahl
|
||||
Authentication
|
||||
Authenticator
|
||||
Authenticator-App
|
||||
Autorisierungscode
|
||||
Autorisierungs-Endpunktes
|
||||
@@ -130,6 +131,7 @@ Eingangsscan
|
||||
Einlassbuchung
|
||||
Einlassdatum
|
||||
Einlasskontrolle
|
||||
Einmalpasswörter
|
||||
einzuchecken
|
||||
email
|
||||
E-Mail-Renderer
|
||||
@@ -163,6 +165,7 @@ Explorer
|
||||
FA
|
||||
Favicon
|
||||
F-Droid
|
||||
freeOTP
|
||||
Footer
|
||||
Footer-Link
|
||||
Footer-Text
|
||||
@@ -557,6 +560,7 @@ Zahlungs-ID
|
||||
Zahlungspflichtig
|
||||
Zehnerkarten
|
||||
Zeitbasiert
|
||||
zeitbasierte
|
||||
Zeitslotbuchung
|
||||
Zimpler
|
||||
ZIP-Datei
|
||||
|
||||
+310
-288
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-03-17 14:06+0000\n"
|
||||
"POT-Creation-Date: 2026-03-30 11:25+0000\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-03-17 14:06+0000\n"
|
||||
"PO-Revision-Date: 2026-03-18 12:23+0000\n"
|
||||
"PO-Revision-Date: 2026-03-30 03:00+0000\n"
|
||||
"Last-Translator: CVZ-es <damien.bremont@casadevelazquez.org>\n"
|
||||
"Language-Team: Spanish <https://translate.pretix.eu/projects/pretix/pretix-"
|
||||
"js/es/>\n"
|
||||
@@ -329,7 +329,7 @@ msgstr "Pedido no aprobado"
|
||||
|
||||
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/main.js:68
|
||||
msgid "Checked-in Tickets"
|
||||
msgstr "Registro de código QR"
|
||||
msgstr "Billetes registrados"
|
||||
|
||||
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/main.js:69
|
||||
msgid "Valid Tickets"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@ anonymized
|
||||
Auth
|
||||
authentification
|
||||
authenticator
|
||||
Authenticator
|
||||
automatical
|
||||
availabilities
|
||||
backend
|
||||
@@ -22,6 +23,7 @@ barcodes
|
||||
Bcc
|
||||
BCC
|
||||
BezahlCode
|
||||
biometric
|
||||
BLIK
|
||||
blocklist
|
||||
BN
|
||||
@@ -56,6 +58,7 @@ EPS
|
||||
eps
|
||||
favicon
|
||||
filetype
|
||||
freeOTP
|
||||
frontend
|
||||
frontpage
|
||||
Galician
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -64,7 +64,7 @@ from pretix.base.timeframes import (
|
||||
from pretix.control.forms.widgets import Select2
|
||||
from pretix.helpers.filenames import safe_for_filename
|
||||
from pretix.helpers.iter import chunked_iterable
|
||||
from pretix.helpers.reportlab import FontFallbackParagraph
|
||||
from pretix.helpers.reportlab import PlainTextParagraph
|
||||
from pretix.helpers.templatetags.jsonfield import JSONExtract
|
||||
from pretix.plugins.reports.exporters import ReportlabExportMixin
|
||||
|
||||
@@ -344,7 +344,7 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
|
||||
]
|
||||
|
||||
story = [
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
cl.name,
|
||||
headlinestyle
|
||||
),
|
||||
@@ -352,7 +352,7 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
|
||||
if cl.subevent:
|
||||
story += [
|
||||
Spacer(1, 3 * mm),
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
'{} ({} {})'.format(
|
||||
cl.subevent.name,
|
||||
cl.subevent.get_date_range_display(),
|
||||
@@ -382,10 +382,10 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
|
||||
headrowstyle.fontName = 'OpenSansBd'
|
||||
for q in questions:
|
||||
txt = str(q.question)
|
||||
p = FontFallbackParagraph(txt, headrowstyle)
|
||||
p = PlainTextParagraph(txt, headrowstyle)
|
||||
while p.wrap(colwidths[len(tdata[0])], 5000)[1] > 30 * mm:
|
||||
txt = txt[:len(txt) - 50] + "..."
|
||||
p = FontFallbackParagraph(txt, headrowstyle)
|
||||
p = PlainTextParagraph(txt, headrowstyle)
|
||||
tdata[0].append(p)
|
||||
|
||||
qs = self._get_queryset(cl, form_data)
|
||||
@@ -432,8 +432,8 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
|
||||
CBFlowable(bool(op.last_checked_in)) if not op.blocked else '—',
|
||||
'✘' if op.order.status != Order.STATUS_PAID else '✔',
|
||||
op.order.code,
|
||||
FontFallbackParagraph(name, self.get_style()),
|
||||
FontFallbackParagraph(bleach.clean(str(item), tags={'br'}).strip().replace('<br>', '<br/>'), self.get_style()),
|
||||
PlainTextParagraph(name, self.get_style()),
|
||||
PlainTextParagraph(bleach.clean(str(item), tags={'br'}).strip().replace('<br>', '<br/>'), self.get_style()),
|
||||
]
|
||||
acache = {}
|
||||
if op.addon_to:
|
||||
@@ -444,10 +444,10 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
|
||||
for q in questions:
|
||||
txt = acache.get(q.pk, '')
|
||||
txt = bleach.clean(txt, tags={'br'}).strip().replace('<br>', '<br/>')
|
||||
p = FontFallbackParagraph(txt, self.get_style())
|
||||
p = PlainTextParagraph(txt, self.get_style())
|
||||
while p.wrap(colwidths[len(row)], 5000)[1] > 50 * mm:
|
||||
txt = txt[:len(txt) - 50] + "..."
|
||||
p = FontFallbackParagraph(txt, self.get_style())
|
||||
p = PlainTextParagraph(txt, self.get_style())
|
||||
row.append(p)
|
||||
if op.order.status != Order.STATUS_PAID:
|
||||
tstyledata += [
|
||||
|
||||
@@ -36,7 +36,7 @@ from reportlab.lib import colors, pagesizes
|
||||
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.platypus import (
|
||||
KeepTogether, PageTemplate, Paragraph, Spacer, Table, TableStyle,
|
||||
KeepTogether, PageTemplate, Spacer, Table, TableStyle,
|
||||
)
|
||||
|
||||
from pretix.base.exporter import BaseExporter
|
||||
@@ -49,7 +49,7 @@ from pretix.base.timeframes import (
|
||||
resolve_timeframe_to_datetime_start_inclusive_end_exclusive,
|
||||
)
|
||||
from pretix.control.forms.filter import get_all_payment_providers
|
||||
from pretix.helpers.reportlab import FontFallbackParagraph
|
||||
from pretix.helpers.reportlab import PlainTextParagraph
|
||||
from pretix.plugins.reports.exporters import ReportlabExportMixin
|
||||
|
||||
|
||||
@@ -311,13 +311,13 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
|
||||
tdata = [
|
||||
[
|
||||
FontFallbackParagraph(self._transaction_group_header_label(), tstyle_bold),
|
||||
FontFallbackParagraph(_("Price"), tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Tax rate"), tstyle_bold_right),
|
||||
FontFallbackParagraph("#", tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Net total"), tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Tax total"), tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Gross total"), tstyle_bold_right),
|
||||
PlainTextParagraph(self._transaction_group_header_label(), tstyle_bold),
|
||||
PlainTextParagraph(_("Price"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Tax rate"), tstyle_bold_right),
|
||||
PlainTextParagraph("#", tstyle_bold_right),
|
||||
PlainTextParagraph(_("Net total"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Tax total"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Gross total"), tstyle_bold_right),
|
||||
]
|
||||
]
|
||||
|
||||
@@ -347,12 +347,12 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
|
||||
if e != last_group:
|
||||
if last_group_head_idx > 0 and e is not None:
|
||||
tdata[last_group_head_idx][4] = Paragraph(money_filter(sum_price_by_group - sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][5] = Paragraph(money_filter(sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][6] = Paragraph(money_filter(sum_price_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][4] = PlainTextParagraph(money_filter(sum_price_by_group - sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][5] = PlainTextParagraph(money_filter(sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][6] = PlainTextParagraph(money_filter(sum_price_by_group, currency), tstyle_bold_right),
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
e,
|
||||
tstyle_bold,
|
||||
),
|
||||
@@ -375,20 +375,20 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
text = self._transaction_row_label(r)
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(text, tstyle),
|
||||
Paragraph(
|
||||
PlainTextParagraph(text, tstyle),
|
||||
PlainTextParagraph(
|
||||
money_filter(r["price"], currency)
|
||||
if "price" in r and r["price"] is not None
|
||||
else "",
|
||||
tstyle_right,
|
||||
),
|
||||
Paragraph(localize(r["tax_rate"].normalize()) + " %", tstyle_right),
|
||||
Paragraph(str(r["sum_cont"]), tstyle_right),
|
||||
Paragraph(
|
||||
PlainTextParagraph(localize(r["tax_rate"].normalize()) + " %", tstyle_right),
|
||||
PlainTextParagraph(str(r["sum_cont"]), tstyle_right),
|
||||
PlainTextParagraph(
|
||||
money_filter(r["sum_price"] - r["sum_tax"], currency), tstyle_right
|
||||
),
|
||||
Paragraph(money_filter(r["sum_tax"], currency), tstyle_right),
|
||||
Paragraph(money_filter(r["sum_price"], currency), tstyle_right),
|
||||
PlainTextParagraph(money_filter(r["sum_tax"], currency), tstyle_right),
|
||||
PlainTextParagraph(money_filter(r["sum_price"], currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
sum_cnt_by_tax_rate[r["tax_rate"]] += r["sum_cont"]
|
||||
@@ -398,19 +398,19 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
sum_tax_by_group += r["sum_tax"]
|
||||
|
||||
if last_group_head_idx > 0 and last_group is not None:
|
||||
tdata[last_group_head_idx][4] = Paragraph(money_filter(sum_price_by_group - sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][5] = Paragraph(money_filter(sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][6] = Paragraph(money_filter(sum_price_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][4] = PlainTextParagraph(money_filter(sum_price_by_group - sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][5] = PlainTextParagraph(money_filter(sum_tax_by_group, currency), tstyle_bold_right),
|
||||
tdata[last_group_head_idx][6] = PlainTextParagraph(money_filter(sum_price_by_group, currency), tstyle_bold_right),
|
||||
|
||||
if len(sum_tax_by_tax_rate) > 1:
|
||||
for tax_rate in sorted(sum_tax_by_tax_rate.keys(), reverse=True):
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Sum"), tstyle),
|
||||
Paragraph("", tstyle_right),
|
||||
Paragraph(localize(tax_rate.normalize()) + " %", tstyle_right),
|
||||
Paragraph("", tstyle_right),
|
||||
Paragraph(
|
||||
PlainTextParagraph(_("Sum"), tstyle),
|
||||
PlainTextParagraph("", tstyle_right),
|
||||
PlainTextParagraph(localize(tax_rate.normalize()) + " %", tstyle_right),
|
||||
PlainTextParagraph("", tstyle_right),
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
sum_price_by_tax_rate[tax_rate]
|
||||
- sum_tax_by_tax_rate[tax_rate],
|
||||
@@ -418,10 +418,10 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
),
|
||||
tstyle_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(sum_tax_by_tax_rate[tax_rate], currency), tstyle_right
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(sum_price_by_tax_rate[tax_rate], currency),
|
||||
tstyle_right,
|
||||
),
|
||||
@@ -439,11 +439,11 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Sum"), tstyle_bold),
|
||||
Paragraph("", tstyle_right),
|
||||
Paragraph("", tstyle_right),
|
||||
Paragraph("", tstyle_bold_right),
|
||||
Paragraph(
|
||||
PlainTextParagraph(_("Sum"), tstyle_bold),
|
||||
PlainTextParagraph("", tstyle_right),
|
||||
PlainTextParagraph("", tstyle_right),
|
||||
PlainTextParagraph("", tstyle_bold_right),
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
sum(sum_price_by_tax_rate.values())
|
||||
- sum(sum_tax_by_tax_rate.values()),
|
||||
@@ -451,11 +451,11 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
),
|
||||
tstyle_bold_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(sum(sum_tax_by_tax_rate.values()), currency),
|
||||
tstyle_bold_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(sum(sum_price_by_tax_rate.values()), currency),
|
||||
tstyle_bold_right,
|
||||
),
|
||||
@@ -493,10 +493,10 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
|
||||
tdata = [
|
||||
[
|
||||
FontFallbackParagraph(_("Payment method"), tstyle_bold),
|
||||
FontFallbackParagraph(_("Payments"), tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Refunds"), tstyle_bold_right),
|
||||
FontFallbackParagraph(_("Total"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Payment method"), tstyle_bold),
|
||||
PlainTextParagraph(_("Payments"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Refunds"), tstyle_bold_right),
|
||||
PlainTextParagraph(_("Total"), tstyle_bold_right),
|
||||
]
|
||||
]
|
||||
|
||||
@@ -537,20 +537,20 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
for p in providers:
|
||||
tdata.append(
|
||||
[
|
||||
Paragraph(provider_names.get(p, p), tstyle),
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(provider_names.get(p, p), tstyle),
|
||||
PlainTextParagraph(
|
||||
money_filter(payments_by_provider[p], currency)
|
||||
if p in payments_by_provider
|
||||
else "",
|
||||
tstyle_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(refunds_by_provider[p], currency)
|
||||
if p in refunds_by_provider
|
||||
else "",
|
||||
tstyle_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
payments_by_provider.get(p, Decimal("0.00"))
|
||||
- refunds_by_provider.get(p, Decimal("0.00")),
|
||||
@@ -563,20 +563,20 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Sum"), tstyle_bold),
|
||||
Paragraph(
|
||||
PlainTextParagraph(_("Sum"), tstyle_bold),
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
sum(payments_by_provider.values(), Decimal("0.00")), currency
|
||||
),
|
||||
tstyle_bold_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
sum(refunds_by_provider.values(), Decimal("0.00")), currency
|
||||
),
|
||||
tstyle_bold_right,
|
||||
),
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
money_filter(
|
||||
sum(payments_by_provider.values(), Decimal("0.00"))
|
||||
- sum(refunds_by_provider.values(), Decimal("0.00")),
|
||||
@@ -641,7 +641,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
open_before = tx_before - p_before + r_before
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(
|
||||
PlainTextParagraph(
|
||||
_("Pending payments at {datetime}").format(
|
||||
datetime=date_format(
|
||||
(df_start - datetime.timedelta.resolution).astimezone(
|
||||
@@ -653,7 +653,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
tstyle,
|
||||
),
|
||||
"",
|
||||
Paragraph(money_filter(open_before, currency), tstyle_right),
|
||||
PlainTextParagraph(money_filter(open_before, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
else:
|
||||
@@ -670,30 +670,30 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
] or Decimal("0.00")
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Orders"), tstyle),
|
||||
Paragraph("+", tstyle_center),
|
||||
Paragraph(money_filter(tx_during, currency), tstyle_right),
|
||||
PlainTextParagraph(_("Orders"), tstyle),
|
||||
PlainTextParagraph("+", tstyle_center),
|
||||
PlainTextParagraph(money_filter(tx_during, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Payments"), tstyle),
|
||||
Paragraph("-", tstyle_center),
|
||||
Paragraph(money_filter(p_during, currency), tstyle_right),
|
||||
PlainTextParagraph(_("Payments"), tstyle),
|
||||
PlainTextParagraph("-", tstyle_center),
|
||||
PlainTextParagraph(money_filter(p_during, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Refunds"), tstyle),
|
||||
Paragraph("+", tstyle_center),
|
||||
Paragraph(money_filter(r_during, currency), tstyle_right),
|
||||
PlainTextParagraph(_("Refunds"), tstyle),
|
||||
PlainTextParagraph("+", tstyle_center),
|
||||
PlainTextParagraph(money_filter(r_during, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
|
||||
open_after = open_before + tx_during - p_during + r_during
|
||||
tdata.append(
|
||||
[
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
_("Pending payments at {datetime}").format(
|
||||
datetime=date_format(
|
||||
((df_end or now()) - datetime.timedelta.resolution).astimezone(
|
||||
@@ -704,8 +704,8 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
),
|
||||
tstyle_bold,
|
||||
),
|
||||
Paragraph("=", tstyle_center),
|
||||
Paragraph(money_filter(open_after, currency), tstyle_bold_right),
|
||||
PlainTextParagraph("=", tstyle_center),
|
||||
PlainTextParagraph(money_filter(open_after, currency), tstyle_bold_right),
|
||||
]
|
||||
)
|
||||
tstyledata += [
|
||||
@@ -752,7 +752,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
)
|
||||
tdata.append(
|
||||
[
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
_("Total gift card value at {datetime}").format(
|
||||
datetime=date_format(
|
||||
(df_start - datetime.timedelta.resolution).astimezone(
|
||||
@@ -763,7 +763,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
),
|
||||
tstyle,
|
||||
),
|
||||
Paragraph(money_filter(tx_before, currency), tstyle_right),
|
||||
PlainTextParagraph(money_filter(tx_before, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
else:
|
||||
@@ -774,8 +774,8 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
] or Decimal("0.00")
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Gift card transactions (credit)"), tstyle),
|
||||
Paragraph(money_filter(tx_during_pos, currency), tstyle_right),
|
||||
PlainTextParagraph(_("Gift card transactions (credit)"), tstyle),
|
||||
PlainTextParagraph(money_filter(tx_during_pos, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -784,15 +784,15 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
] or Decimal("0.00")
|
||||
tdata.append(
|
||||
[
|
||||
FontFallbackParagraph(_("Gift card transactions (debit)"), tstyle),
|
||||
Paragraph(money_filter(tx_during_neg, currency), tstyle_right),
|
||||
PlainTextParagraph(_("Gift card transactions (debit)"), tstyle),
|
||||
PlainTextParagraph(money_filter(tx_during_neg, currency), tstyle_right),
|
||||
]
|
||||
)
|
||||
|
||||
open_after = tx_before + tx_during_pos + tx_during_neg
|
||||
tdata.append(
|
||||
[
|
||||
Paragraph(
|
||||
PlainTextParagraph(
|
||||
_("Total gift card value at {datetime}").format(
|
||||
datetime=date_format(
|
||||
((df_end or now()) - datetime.timedelta.resolution).astimezone(
|
||||
@@ -803,7 +803,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
),
|
||||
tstyle_bold,
|
||||
),
|
||||
Paragraph(money_filter(open_after, currency), tstyle_bold_right),
|
||||
PlainTextParagraph(money_filter(open_after, currency), tstyle_bold_right),
|
||||
]
|
||||
)
|
||||
tstyledata += [
|
||||
@@ -854,10 +854,10 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
style_small.leading = 10
|
||||
|
||||
story = [
|
||||
FontFallbackParagraph(self.verbose_name, style_h1),
|
||||
PlainTextParagraph(self.verbose_name, style_h1),
|
||||
Spacer(0, 3 * mm),
|
||||
FontFallbackParagraph(
|
||||
"<br />".join(escape(f) for f in self.describe_filters(form_data)),
|
||||
PlainTextParagraph(
|
||||
"\n".join(escape(f) for f in self.describe_filters(form_data)),
|
||||
style_small,
|
||||
),
|
||||
]
|
||||
@@ -870,7 +870,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
if s:
|
||||
story += [
|
||||
Spacer(0, 3 * mm),
|
||||
FontFallbackParagraph(_("Orders") + c_head, style_h2),
|
||||
PlainTextParagraph(_("Orders") + c_head, style_h2),
|
||||
Spacer(0, 3 * mm),
|
||||
*s
|
||||
]
|
||||
@@ -881,7 +881,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
if s:
|
||||
story += [
|
||||
Spacer(0, 8 * mm),
|
||||
FontFallbackParagraph(_("Payments") + c_head, style_h2),
|
||||
PlainTextParagraph(_("Payments") + c_head, style_h2),
|
||||
Spacer(0, 3 * mm),
|
||||
*s
|
||||
]
|
||||
@@ -894,7 +894,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
Spacer(0, 8 * mm),
|
||||
KeepTogether(
|
||||
[
|
||||
FontFallbackParagraph(_("Open items") + c_head, style_h2),
|
||||
PlainTextParagraph(_("Open items") + c_head, style_h2),
|
||||
Spacer(0, 3 * mm),
|
||||
*s
|
||||
]
|
||||
@@ -912,7 +912,7 @@ class ReportExporter(ReportlabExportMixin, BaseExporter):
|
||||
Spacer(0, 8 * mm),
|
||||
KeepTogether(
|
||||
[
|
||||
FontFallbackParagraph(_("Gift cards") + c_head, style_h2),
|
||||
PlainTextParagraph(_("Gift cards") + c_head, style_h2),
|
||||
Spacer(0, 3 * mm),
|
||||
*s,
|
||||
]
|
||||
|
||||
@@ -70,7 +70,7 @@ from pretix.base.timeframes import (
|
||||
)
|
||||
from pretix.control.forms.filter import OverviewFilterForm
|
||||
from pretix.helpers.reportlab import (
|
||||
FontFallbackParagraph, register_ttf_font_if_new,
|
||||
PlainTextParagraph, register_ttf_font_if_new,
|
||||
)
|
||||
from pretix.presale.style import get_fonts
|
||||
|
||||
@@ -282,7 +282,7 @@ class OverviewReport(Report):
|
||||
headlinestyle.fontSize = 15
|
||||
headlinestyle.fontName = 'OpenSansBd'
|
||||
story = [
|
||||
FontFallbackParagraph(_('Orders by product') + ' ' + (_('(excl. taxes)') if net else _('(incl. taxes)')), headlinestyle),
|
||||
PlainTextParagraph(_('Orders by product') + ' ' + (_('(excl. taxes)') if net else _('(incl. taxes)')), headlinestyle),
|
||||
Spacer(1, 5 * mm)
|
||||
]
|
||||
return story
|
||||
@@ -292,7 +292,7 @@ class OverviewReport(Report):
|
||||
if form_data.get('date_axis') and form_data.get('date_range'):
|
||||
d_start, d_end = resolve_timeframe_to_dates_inclusive(now(), form_data['date_range'], self.timezone)
|
||||
story += [
|
||||
FontFallbackParagraph(_('{axis} between {start} and {end}').format(
|
||||
PlainTextParagraph(_('{axis} between {start} and {end}').format(
|
||||
axis=dict(OverviewFilterForm(event=self.event).fields['date_axis'].choices)[form_data.get('date_axis')],
|
||||
start=date_format(d_start, 'SHORT_DATE_FORMAT') if d_start else '–',
|
||||
end=date_format(d_end, 'SHORT_DATE_FORMAT') if d_end else '–',
|
||||
@@ -305,13 +305,13 @@ class OverviewReport(Report):
|
||||
subevent = self.event.subevents.get(pk=self.form_data.get('subevent'))
|
||||
except SubEvent.DoesNotExist:
|
||||
subevent = self.form_data.get('subevent')
|
||||
story.append(FontFallbackParagraph(pgettext('subevent', 'Date: {}').format(subevent), self.get_style()))
|
||||
story.append(PlainTextParagraph(pgettext('subevent', 'Date: {}').format(subevent), self.get_style()))
|
||||
story.append(Spacer(1, 5 * mm))
|
||||
|
||||
if form_data.get('subevent_date_range'):
|
||||
d_start, d_end = resolve_timeframe_to_datetime_start_inclusive_end_exclusive(now(), form_data['subevent_date_range'], self.timezone)
|
||||
story += [
|
||||
FontFallbackParagraph(_('{axis} between {start} and {end}').format(
|
||||
PlainTextParagraph(_('{axis} between {start} and {end}').format(
|
||||
axis=_('Event date'),
|
||||
start=date_format(d_start, 'SHORT_DATE_FORMAT') if d_start else '–',
|
||||
end=date_format(d_end - timedelta(hours=1), 'SHORT_DATE_FORMAT') if d_end else '–',
|
||||
@@ -384,13 +384,13 @@ class OverviewReport(Report):
|
||||
tdata = [
|
||||
[
|
||||
_('Product'),
|
||||
FontFallbackParagraph(_('Canceled'), tstyle_th),
|
||||
PlainTextParagraph(_('Canceled'), tstyle_th),
|
||||
'',
|
||||
FontFallbackParagraph(_('Expired'), tstyle_th),
|
||||
PlainTextParagraph(_('Expired'), tstyle_th),
|
||||
'',
|
||||
FontFallbackParagraph(_('Approval pending'), tstyle_th),
|
||||
PlainTextParagraph(_('Approval pending'), tstyle_th),
|
||||
'',
|
||||
FontFallbackParagraph(_('Purchased'), tstyle_th),
|
||||
PlainTextParagraph(_('Purchased'), tstyle_th),
|
||||
'', '', '', '', ''
|
||||
],
|
||||
[
|
||||
@@ -421,14 +421,14 @@ class OverviewReport(Report):
|
||||
for tup in items_by_category:
|
||||
if tup[0]:
|
||||
tdata.append([
|
||||
FontFallbackParagraph(str(tup[0]), tstyle_bold)
|
||||
PlainTextParagraph(str(tup[0]), tstyle_bold)
|
||||
])
|
||||
for l, s in states:
|
||||
tdata[-1].append(str(tup[0].num[l][0]))
|
||||
tdata[-1].append(floatformat(tup[0].num[l][2 if net else 1], places))
|
||||
for item in tup[1]:
|
||||
tdata.append([
|
||||
FontFallbackParagraph(str(item), tstyle)
|
||||
PlainTextParagraph(str(item), tstyle)
|
||||
])
|
||||
for l, s in states:
|
||||
tdata[-1].append(str(item.num[l][0]))
|
||||
@@ -436,7 +436,7 @@ class OverviewReport(Report):
|
||||
if item.has_variations:
|
||||
for var in item.all_variations:
|
||||
tdata.append([
|
||||
FontFallbackParagraph(" " + str(var), tstyle)
|
||||
PlainTextParagraph(" " + str(var), tstyle)
|
||||
])
|
||||
for l, s in states:
|
||||
tdata[-1].append(str(var.num[l][0]))
|
||||
@@ -568,7 +568,7 @@ class OrderTaxListReportPDF(Report):
|
||||
tstyledata.append(('SPAN', (5 + 2 * i, 0), (6 + 2 * i, 0)))
|
||||
|
||||
story = [
|
||||
FontFallbackParagraph(_('Orders by tax rate ({currency})').format(currency=self.event.currency), headlinestyle),
|
||||
PlainTextParagraph(_('Orders by tax rate ({currency})').format(currency=self.event.currency), headlinestyle),
|
||||
Spacer(1, 5 * mm)
|
||||
]
|
||||
tdata = [
|
||||
|
||||
@@ -229,6 +229,11 @@ class TicketRendererViewSet(viewsets.ViewSet):
|
||||
@action(detail=False, methods=['GET'], url_name='download', url_path='download/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def download(self, *args, **kwargs):
|
||||
cf = get_object_or_404(CachedFile, id=kwargs['cfid'])
|
||||
if not cf.allowed_for_session(self.request, "ticketoutputpdf-api"):
|
||||
return Response(
|
||||
{'status': 'failed', 'message': 'Unknown file ID or export failed'},
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
if cf.file:
|
||||
resp = ChunkBasedFileResponse(cf.file.file, content_type=cf.type)
|
||||
resp['Content-Disposition'] = 'attachment; filename="{}"'.format(cf.filename).encode("ascii", "ignore")
|
||||
@@ -265,6 +270,7 @@ class TicketRendererViewSet(viewsets.ViewSet):
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
cf = CachedFile(web_download=False)
|
||||
cf.bind_to_session(self.request, "ticketoutputpdf-api")
|
||||
cf.date = now()
|
||||
cf.expires = now() + timedelta(hours=24)
|
||||
cf.save()
|
||||
|
||||
@@ -50,6 +50,7 @@ from django.http import HttpResponseNotAllowed, JsonResponse
|
||||
from django.shortcuts import redirect
|
||||
from django.utils import translation
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.html import conditional_escape
|
||||
from django.utils.translation import (
|
||||
get_language, gettext_lazy as _, pgettext_lazy,
|
||||
)
|
||||
@@ -1614,7 +1615,7 @@ class ConfirmStep(CartMixin, AsyncAction, TemplateFlowStep):
|
||||
meta_info = {
|
||||
'contact_form_data': self.cart_session.get('contact_form_data', {}),
|
||||
'confirm_messages': [
|
||||
str(m) for m in self.confirm_messages.values()
|
||||
conditional_escape(str(m)) for m in self.confirm_messages.values()
|
||||
]
|
||||
}
|
||||
api_meta = {}
|
||||
|
||||
@@ -28,7 +28,7 @@ from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.hashers import check_password
|
||||
from django.contrib.auth.password_validation import (
|
||||
get_password_validators, password_validators_help_texts, validate_password,
|
||||
MinimumLengthValidator, get_password_validators, validate_password,
|
||||
)
|
||||
from django.contrib.auth.tokens import PasswordResetTokenGenerator
|
||||
from django.core import signing
|
||||
@@ -300,13 +300,12 @@ class SetPasswordForm(forms.Form):
|
||||
)
|
||||
password = forms.CharField(
|
||||
label=_('Password'),
|
||||
widget=forms.PasswordInput(attrs={'minlength': '8', 'autocomplete': 'new-password'}),
|
||||
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
|
||||
max_length=4096,
|
||||
required=True
|
||||
)
|
||||
password_repeat = forms.CharField(
|
||||
label=_('Repeat password'),
|
||||
widget=forms.PasswordInput(attrs={'minlength': '8', 'autocomplete': 'new-password'}),
|
||||
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
|
||||
max_length=4096,
|
||||
)
|
||||
|
||||
@@ -316,6 +315,14 @@ class SetPasswordForm(forms.Form):
|
||||
kwargs['initial']['email'] = self.customer.email
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
pw_min_len_validators = [v for v in get_customer_password_validators() if isinstance(v, MinimumLengthValidator)]
|
||||
if pw_min_len_validators:
|
||||
self.fields['password'].widget.attrs['minlength'] = max(v.min_length for v in pw_min_len_validators)
|
||||
self.fields['password_repeat'].widget.attrs['minlength'] = max(v.min_length for v in pw_min_len_validators)
|
||||
|
||||
if 'password' not in self.data:
|
||||
self.fields['password'].help_text = ' '.join(v.get_help_text() for v in pw_min_len_validators)
|
||||
|
||||
def clean(self):
|
||||
password1 = self.cleaned_data.get('password', '')
|
||||
password2 = self.cleaned_data.get('password_repeat')
|
||||
@@ -329,8 +336,7 @@ class SetPasswordForm(forms.Form):
|
||||
|
||||
def clean_password(self):
|
||||
password1 = self.cleaned_data.get('password', '')
|
||||
if validate_password(password1, user=self.customer, password_validators=get_customer_password_validators()) is not None:
|
||||
raise forms.ValidationError(_(password_validators_help_texts()), code='pw_invalid')
|
||||
validate_password(password1, user=self.customer, password_validators=get_customer_password_validators())
|
||||
return password1
|
||||
|
||||
|
||||
@@ -395,13 +401,13 @@ class ChangePasswordForm(forms.Form):
|
||||
)
|
||||
password = forms.CharField(
|
||||
label=_('New password'),
|
||||
widget=forms.PasswordInput(attrs={'minlength': '8', 'autocomplete': 'new-password'}),
|
||||
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
|
||||
max_length=4096,
|
||||
required=True
|
||||
)
|
||||
password_repeat = forms.CharField(
|
||||
label=_('Repeat password'),
|
||||
widget=forms.PasswordInput(attrs={'minlength': '8', 'autocomplete': 'new-password'}),
|
||||
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}),
|
||||
max_length=4096,
|
||||
)
|
||||
|
||||
@@ -411,6 +417,14 @@ class ChangePasswordForm(forms.Form):
|
||||
kwargs['initial']['email'] = self.customer.email
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
pw_min_len_validators = [v for v in get_customer_password_validators() if isinstance(v, MinimumLengthValidator)]
|
||||
if pw_min_len_validators:
|
||||
self.fields['password'].widget.attrs['minlength'] = max(v.min_length for v in pw_min_len_validators)
|
||||
self.fields['password_repeat'].widget.attrs['minlength'] = max(v.min_length for v in pw_min_len_validators)
|
||||
|
||||
if 'password' not in self.data:
|
||||
self.fields['password'].help_text = ' '.join(v.get_help_text() for v in pw_min_len_validators)
|
||||
|
||||
def clean(self):
|
||||
password1 = self.cleaned_data.get('password', '')
|
||||
password2 = self.cleaned_data.get('password_repeat')
|
||||
@@ -424,8 +438,7 @@ class ChangePasswordForm(forms.Form):
|
||||
|
||||
def clean_password(self):
|
||||
password1 = self.cleaned_data.get('password', '')
|
||||
if validate_password(password1, user=self.customer, password_validators=get_customer_password_validators()) is not None:
|
||||
raise forms.ValidationError(_(password_validators_help_texts()), code='pw_invalid')
|
||||
validate_password(password1, user=self.customer, password_validators=get_customer_password_validators())
|
||||
return password1
|
||||
|
||||
def clean_password_current(self):
|
||||
|
||||
@@ -144,7 +144,7 @@ checkout_confirm_messages = EventPluginSignal()
|
||||
This signal is sent out to retrieve short messages that need to be acknowledged by the user before the
|
||||
order can be completed. This is typically used for something like "accept the terms and conditions".
|
||||
Receivers are expected to return a dictionary where the keys are globally unique identifiers for the
|
||||
message and the values can be arbitrary HTML.
|
||||
message and the values can be a SafeString containing arbitrary HTML, or a string that will be HTML-escaped.
|
||||
|
||||
As with all event plugin signals, the ``sender`` keyword argument will contain the event.
|
||||
"""
|
||||
|
||||
@@ -176,7 +176,7 @@
|
||||
<div class="checkbox">
|
||||
<label for="input_confirm_{{ key }}">
|
||||
<input type="checkbox" class="checkbox" value="yes" name="confirm_{{ key }}" id="input_confirm_{{ key }}" required>
|
||||
{{ desc|safe }}
|
||||
{{ desc }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
{% load eventsignal %}
|
||||
{% load money %}
|
||||
{% load eventurl %}
|
||||
{% load wrap_in %}
|
||||
{% block title %}{% trans "Registration details" %}{% endblock %}
|
||||
{% block content %}
|
||||
<h2 class="h1">
|
||||
@@ -48,7 +49,7 @@
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p>
|
||||
{% blocktrans trimmed with email="<strong>"|add:order.email|add:"</strong>"|safe %}
|
||||
{% blocktrans trimmed with email=order.email|wrap_in:"strong" %}
|
||||
This order is managed for you by {{ email }}. Please contact them for any questions regarding
|
||||
payment, cancellation or changes to this order.
|
||||
{% endblocktrans %}
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
import datetime
|
||||
import decimal
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core import mail as djmail
|
||||
from django.test import TransactionTestCase
|
||||
@@ -44,8 +43,8 @@ from django_scopes import scopes_disabled
|
||||
from tests.base import SoupTestMixin, extract_form_fields
|
||||
|
||||
from pretix.base.models import (
|
||||
Event, Item, ItemVariation, Order, OrderPosition, Organizer, Quota,
|
||||
SeatingPlan, Team, User, Voucher,
|
||||
Event, Item, ItemVariation, Order, OrderPosition, Organizer, Quota, Team,
|
||||
User, Voucher,
|
||||
)
|
||||
|
||||
|
||||
@@ -135,49 +134,49 @@ class VoucherFormTest(SoupTestMixin, TransactionTestCase):
|
||||
def test_filter_status_valid(self):
|
||||
with scopes_disabled():
|
||||
v = self.event.vouchers.create(item=self.ticket)
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=v' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=v' % (self.orga.slug, self.event.slug))
|
||||
assert v.code in doc.content.decode()
|
||||
v.redeemed = 1
|
||||
v.save()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=v' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=v' % (self.orga.slug, self.event.slug))
|
||||
assert v.code not in doc.content.decode()
|
||||
|
||||
def test_filter_status_redeemed(self):
|
||||
with scopes_disabled():
|
||||
v = self.event.vouchers.create(item=self.ticket, redeemed=1)
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=r' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=r' % (self.orga.slug, self.event.slug))
|
||||
assert v.code in doc.content.decode()
|
||||
v.redeemed = 0
|
||||
v.save()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=r' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=r' % (self.orga.slug, self.event.slug))
|
||||
assert v.code not in doc.content.decode()
|
||||
|
||||
def test_filter_status_expired(self):
|
||||
with scopes_disabled():
|
||||
v = self.event.vouchers.create(item=self.ticket, valid_until=now() + datetime.timedelta(days=1))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=e' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=e' % (self.orga.slug, self.event.slug))
|
||||
assert v.code not in doc.content.decode()
|
||||
v.valid_until = now() - datetime.timedelta(days=1)
|
||||
v.save()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-status=e' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?status=e' % (self.orga.slug, self.event.slug))
|
||||
assert v.code in doc.content.decode()
|
||||
|
||||
def test_filter_tag(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, code='ABCDEFG', comment='Foo', tag='bar')
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-tag=bar' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?tag=bar' % (self.orga.slug, self.event.slug))
|
||||
assert 'ABCDEFG' in doc.content.decode()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-tag=baz' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?tag=baz' % (self.orga.slug, self.event.slug))
|
||||
assert 'ABCDEFG' not in doc.content.decode()
|
||||
|
||||
def test_search_code(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, code='ABCDEFG', comment='Foo')
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-search=ABCDEFG' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?search=ABCDEFG' % (self.orga.slug, self.event.slug))
|
||||
assert 'ABCDEFG' in doc.content.decode()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-search=Foo' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?search=Foo' % (self.orga.slug, self.event.slug))
|
||||
assert 'ABCDEFG' in doc.content.decode()
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?filter-search=12345' % (self.orga.slug, self.event.slug))
|
||||
doc = self.client.get('/control/event/%s/%s/vouchers/?search=12345' % (self.orga.slug, self.event.slug))
|
||||
assert 'ABCDEFG' not in doc.content.decode()
|
||||
|
||||
def test_bulk_rng(self):
|
||||
@@ -772,426 +771,3 @@ class VoucherFormTest(SoupTestMixin, TransactionTestCase):
|
||||
|
||||
assert len(doc.select('.alert-warning ul li')) == 1 # Check that there's exactly 1 item in the warning list
|
||||
assert doc.text.count('Order DEDUP') == 1 # Check that the order is listed exactly once
|
||||
|
||||
|
||||
class VoucherBulkEditFormTest(SoupTestMixin, TransactionTestCase):
|
||||
@scopes_disabled()
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.user = User.objects.create_user('dummy@dummy.dummy', 'dummy')
|
||||
self.orga = Organizer.objects.create(name='CCC', slug='ccc')
|
||||
self.event = Event.objects.create(
|
||||
organizer=self.orga, name='30C3', slug='30c3',
|
||||
date_from=datetime.datetime(2013, 12, 26, tzinfo=datetime.timezone.utc),
|
||||
)
|
||||
t = Team.objects.create(organizer=self.orga, all_event_permissions=True)
|
||||
t.members.add(self.user)
|
||||
t.limit_events.add(self.event)
|
||||
self.client.login(email='dummy@dummy.dummy', password='dummy')
|
||||
|
||||
self.quota_shirts = Quota.objects.create(event=self.event, name='Shirts', size=2)
|
||||
self.shirt = Item.objects.create(event=self.event, name='T-Shirt', default_price=12)
|
||||
self.quota_shirts.items.add(self.shirt)
|
||||
self.shirt_red = ItemVariation.objects.create(item=self.shirt, default_price=14, value='Red')
|
||||
self.shirt_blue = ItemVariation.objects.create(item=self.shirt, value='Blue')
|
||||
self.quota_shirts.variations.add(self.shirt_red)
|
||||
self.quota_shirts.variations.add(self.shirt_blue)
|
||||
|
||||
self.quota_tickets = Quota.objects.create(event=self.event, name='Tickets', size=2)
|
||||
self.ticket = Item.objects.create(event=self.event, name='Early-bird ticket',
|
||||
default_price=23)
|
||||
self.quota_tickets.items.add(self.ticket)
|
||||
self.url = f'/control/event/{self.orga.slug}/{self.event.slug}/vouchers/bulk_edit'
|
||||
|
||||
def test_simple_edit(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(
|
||||
quota=self.quota_tickets,
|
||||
max_usages=10,
|
||||
price_mode="set",
|
||||
value=13,
|
||||
)
|
||||
self.event.vouchers.create(
|
||||
item=self.ticket,
|
||||
max_usages=10,
|
||||
price_mode="set",
|
||||
value=12,
|
||||
)
|
||||
|
||||
doc = self.post_doc(self.url, {
|
||||
'__ALL': 'on',
|
||||
}, follow=True)
|
||||
fields = extract_form_fields(doc)
|
||||
assert fields.get('bulkedit-max_usages') == '10'
|
||||
assert fields.get('bulkedit-price_mode') == 'set'
|
||||
assert not fields.get('bulkedit-value')
|
||||
fields.update({
|
||||
'_bulk': ['bulkedit__price', 'bulkeditmin_usages', 'bulkedittag', 'bulkeditshow_hidden_items'],
|
||||
'bulkedit-price_mode': 'percent',
|
||||
'bulkedit-value': '15',
|
||||
'bulkedit-min_usages': '3',
|
||||
'bulkedit-tag': 'tagged',
|
||||
'bulkedit-comment': 'This is a comment', # will be ignored, as not included in _bulk
|
||||
'bulkedit-show_hidden_items': '',
|
||||
})
|
||||
doc = self.post_doc(self.url, fields, follow=True)
|
||||
assert doc.select(".alert-success")
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.price_mode == "percent"
|
||||
assert v.value == Decimal("15.00")
|
||||
assert v.min_usages == 3
|
||||
assert v.tag == "tagged"
|
||||
assert v.comment == ""
|
||||
assert v.show_hidden_items is False
|
||||
|
||||
def _update_all(self, data: dict, expect_error: str=None):
|
||||
doc = self.post_doc(self.url, {
|
||||
'__ALL': 'on',
|
||||
}, follow=True)
|
||||
fields = extract_form_fields(doc)
|
||||
fields.update(data)
|
||||
doc = self.post_doc(self.url, fields, follow=True)
|
||||
error_texts = [el.text for el in doc.select(".alert-danger, .has-error")]
|
||||
if expect_error:
|
||||
assert doc.select(".alert-danger")
|
||||
assert any(expect_error in t for t in error_texts), error_texts
|
||||
else:
|
||||
assert doc.select(".alert-success"), error_texts
|
||||
|
||||
def test_change_itemvar_to_product(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets)
|
||||
self.event.vouchers.create(item=self.ticket)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.ticket.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.item == self.ticket
|
||||
assert not v.variation
|
||||
assert not v.quota
|
||||
|
||||
def test_change_itemvar_to_variation(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets)
|
||||
self.event.vouchers.create(item=self.ticket)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.shirt.pk}-{self.shirt_red.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.item == self.shirt
|
||||
assert v.variation == self.shirt_red
|
||||
assert not v.quota
|
||||
|
||||
def test_change_itemvar_to_quota(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets)
|
||||
self.event.vouchers.create(item=self.ticket)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'q-{self.quota_tickets.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert not v.item
|
||||
assert not v.variation
|
||||
assert v.quota == self.quota_tickets
|
||||
|
||||
def test_change_itemvar_to_all(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets)
|
||||
self.event.vouchers.create(item=self.ticket)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': '',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert not v.item
|
||||
assert not v.variation
|
||||
assert not v.quota
|
||||
|
||||
def test_change_max_usages(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets, max_usages=15, redeemed=4)
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=15, redeemed=2)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditmax_usages'],
|
||||
'bulkedit-max_usages': '3',
|
||||
}, expect_error="already been redeemed 4 times")
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditmax_usages'],
|
||||
'bulkedit-max_usages': '4',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.max_usages == 4
|
||||
|
||||
def _requires_one_more_quota(self, data: dict, quota=None):
|
||||
self._update_all(data, expect_error="no sufficient quota")
|
||||
quota = quota or self.quota_tickets
|
||||
quota.size += 1
|
||||
quota.save()
|
||||
self._update_all(data)
|
||||
|
||||
def test_quota_check_change_item(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.shirt, block_quota=True, max_usages=2, redeemed=1)
|
||||
self.event.vouchers.create(item=self.shirt, block_quota=True, max_usages=3, redeemed=1)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.ticket.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.item == self.ticket
|
||||
|
||||
def test_quota_check_change_variation(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=2, redeemed=1)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=3, redeemed=1)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.shirt.pk}-{self.shirt_red.pk}',
|
||||
}, quota=self.quota_shirts)
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.item == self.shirt
|
||||
assert v.variation == self.shirt_red
|
||||
|
||||
def test_quota_check_change_item_with_variations(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=2, redeemed=1)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=3, redeemed=1)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.shirt.pk}',
|
||||
}, quota=self.quota_shirts)
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.item == self.shirt
|
||||
assert not v.variation
|
||||
|
||||
def test_quota_check_change_expired_to_valid(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=2)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=1, valid_until=now() - datetime.timedelta(days=1))
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkeditvalid_until'],
|
||||
'bulkedit-valid_until_0': '',
|
||||
'bulkedit-valid_until_1': '',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert not v.valid_until
|
||||
|
||||
def test_quota_check_change_max_usages(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=2)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, max_usages=1, redeemed=1)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkeditmax_usages'],
|
||||
'bulkedit-max_usages': '2',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.max_usages == 2
|
||||
|
||||
def test_quota_check_no_change(self):
|
||||
with scopes_disabled():
|
||||
# Technically overbooked, but we don't have a diff in quota
|
||||
self.event.vouchers.create(item=self.shirt, variation=self.shirt_red, block_quota=True)
|
||||
self.event.vouchers.create(item=self.shirt, variation=self.shirt_red, block_quota=True)
|
||||
self.event.vouchers.create(item=self.shirt, variation=self.shirt_red, block_quota=True)
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'{self.shirt.pk}-{self.shirt_blue.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.variation == self.shirt_blue
|
||||
|
||||
def test_quota_check_change_subevent(self):
|
||||
with scopes_disabled():
|
||||
self.event.has_subevents = True
|
||||
self.event.save()
|
||||
se1 = self.event.subevents.create(name="Foo", date_from=now())
|
||||
se2 = self.event.subevents.create(name="Bar", date_from=now())
|
||||
self.quota_tickets.subevent = se1
|
||||
self.quota_tickets.save()
|
||||
Quota.objects.create(event=self.event, subevent=se2, name='Tickets', size=3)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, subevent=se2)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, subevent=se2)
|
||||
self.event.vouchers.create(item=self.ticket, block_quota=True, subevent=se2)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkeditsubevent'],
|
||||
'bulkedit-subevent': f'{se1.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.subevent == se1
|
||||
|
||||
def test_change_subevent_quota_invalid(self):
|
||||
with scopes_disabled():
|
||||
self.event.has_subevents = True
|
||||
self.event.save()
|
||||
se1 = self.event.subevents.create(name="Foo", date_from=now())
|
||||
se2 = self.event.subevents.create(name="Bar", date_from=now())
|
||||
self.quota_tickets.subevent = se1
|
||||
self.quota_tickets.save()
|
||||
v1 = self.event.vouchers.create(quota=self.quota_tickets, block_quota=True, subevent=se1)
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditsubevent'],
|
||||
'bulkedit-subevent': f'{se2.pk}',
|
||||
}, expect_error="selected quota does not match the selected subevent")
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditsubevent'],
|
||||
'bulkedit-subevent': '',
|
||||
}, expect_error="has no date selected")
|
||||
v1.quota = None
|
||||
v1.item = self.ticket
|
||||
v1.save()
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditsubevent'],
|
||||
'bulkedit-subevent': '',
|
||||
}, expect_error="If you want this voucher to block quota, you need to select a specific date")
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.subevent == se1
|
||||
|
||||
def test_change_missing_itemvar_with_block_quota(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(quota=self.quota_tickets, block_quota=True)
|
||||
self.event.vouchers.create(quota=self.quota_tickets, block_quota=True)
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': '',
|
||||
}, expect_error="You need to select a specific product or quota if this voucher should reserve")
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar', 'bulkeditblock_quota'],
|
||||
'bulkedit-itemvar': '',
|
||||
'bulkedit-block_quota': '',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert not v.subevent
|
||||
assert not v.block_quota
|
||||
|
||||
def test_change_subevent_and_quota(self):
|
||||
with scopes_disabled():
|
||||
self.event.has_subevents = True
|
||||
self.event.save()
|
||||
se1 = self.event.subevents.create(name="Foo", date_from=now())
|
||||
se2 = self.event.subevents.create(name="Bar", date_from=now())
|
||||
self.quota_tickets.subevent = se1
|
||||
self.quota_tickets.save()
|
||||
q2 = Quota.objects.create(event=self.event, subevent=se2, name='Tickets', size=3)
|
||||
self.event.vouchers.create(quota=self.quota_tickets, block_quota=True, subevent=se1)
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar', 'bulkeditsubevent'],
|
||||
'bulkedit-subevent': f'{se2.pk}',
|
||||
'bulkedit-itemvar': f'q-{q2.pk}',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.subevent == se2
|
||||
assert v.quota == q2
|
||||
|
||||
def test_quota_check_change_block_quota(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=3)
|
||||
self._requires_one_more_quota({
|
||||
'_bulk': ['bulkeditblock_quota'],
|
||||
'bulkedit-block_quota': 'on',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.block_quota
|
||||
|
||||
def test_ignore_quota(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=3)
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditblock_quota', 'bulkeditallow_ignore_quota'],
|
||||
'bulkedit-block_quota': 'on',
|
||||
'bulkedit-allow_ignore_quota': 'on',
|
||||
})
|
||||
with scopes_disabled():
|
||||
for v in self.event.vouchers.all():
|
||||
assert v.block_quota
|
||||
assert v.allow_ignore_quota
|
||||
|
||||
@scopes_disabled()
|
||||
def _create_seat(self, **kwargs):
|
||||
plan = SeatingPlan.objects.create(
|
||||
name="Plan", organizer=self.orga, layout="{}"
|
||||
)
|
||||
self.event.seating_plan = plan
|
||||
self.event.save()
|
||||
return self.event.seats.create(seat_number="A1", product=self.ticket, seat_guid="A1", **kwargs)
|
||||
|
||||
def test_seated_unsupported(self):
|
||||
with scopes_disabled():
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=1, seat=self._create_seat())
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditmax_usages'],
|
||||
'bulkedit-max_usages': '2',
|
||||
}, expect_error="Changing the maximum number of usages in bulk is not supported")
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditsubevent'],
|
||||
'bulkedit-subevent': '',
|
||||
}, expect_error="Changing the date in bulk is not supported")
|
||||
self._update_all({
|
||||
'_bulk': ['bulkedititemvar'],
|
||||
'bulkedit-itemvar': f'q-{self.quota_tickets.pk}',
|
||||
}, expect_error="Changing the product to a quota is not supported")
|
||||
|
||||
def test_seat_changed_to_valid_needs_to_be_available(self):
|
||||
with scopes_disabled():
|
||||
seat = self._create_seat(blocked=True)
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=1, valid_until=now() - datetime.timedelta(days=1), seat=seat)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditvalid_until'],
|
||||
'bulkedit-valid_until_0': '',
|
||||
'bulkedit-valid_until_1': '',
|
||||
}, expect_error="not all assigned seats of the vouchers are still available")
|
||||
|
||||
seat.blocked = False
|
||||
seat.save()
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditvalid_until'],
|
||||
'bulkedit-valid_until_0': '',
|
||||
'bulkedit-valid_until_1': '',
|
||||
})
|
||||
|
||||
def test_seat_changed_to_valid_needs_to_be_available_subevents(self):
|
||||
with scopes_disabled():
|
||||
self.event.has_subevents = True
|
||||
self.event.save()
|
||||
se1 = self.event.subevents.create(name="Foo", date_from=now())
|
||||
seat = self._create_seat(subevent=se1, blocked=True)
|
||||
self.event.vouchers.create(item=self.ticket, max_usages=1, valid_until=now() - datetime.timedelta(days=1), seat=seat, subevent=se1)
|
||||
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditvalid_until'],
|
||||
'bulkedit-valid_until_0': '',
|
||||
'bulkedit-valid_until_1': '',
|
||||
}, expect_error="not all assigned seats of the vouchers are still available")
|
||||
|
||||
seat.blocked = False
|
||||
seat.save()
|
||||
self._update_all({
|
||||
'_bulk': ['bulkeditvalid_until'],
|
||||
'bulkedit-valid_until_0': '',
|
||||
'bulkedit-valid_until_1': '',
|
||||
})
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#
|
||||
# This file is part of pretix (Community Edition).
|
||||
#
|
||||
# Copyright (C) 2014-2020 Raphael Michel and contributors
|
||||
# Copyright (C) 2020-today pretix GmbH and contributors
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
|
||||
# Public License as published by the Free Software Foundation in version 3 of the License.
|
||||
#
|
||||
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
|
||||
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
|
||||
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
|
||||
# this file, see <https://pretix.eu/about/en/license>.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import pytest
|
||||
from django.core.exceptions import SuspiciousFileOperation
|
||||
from reportlab.platypus import Paragraph
|
||||
|
||||
|
||||
def test_http_access_disabled(monkeypatch):
|
||||
def guard(*args, **kwargs):
|
||||
pytest.fail("No internet wanted!")
|
||||
|
||||
monkeypatch.setattr('socket.socket', guard)
|
||||
|
||||
with pytest.raises(SuspiciousFileOperation, match="should not be reading images from disk"):
|
||||
Paragraph(
|
||||
'<img src="https://static.pretix.cloud/static/pretixeu/img/opengraph.png"/>',
|
||||
)
|
||||
|
||||
|
||||
def test_file_access_disabled_scheme(monkeypatch):
|
||||
with pytest.raises(SuspiciousFileOperation, match="should not be reading images from disk"):
|
||||
Paragraph(
|
||||
'<img src="file:///etc/passwd" />',
|
||||
)
|
||||
|
||||
|
||||
def test_file_access_disabled_direct(monkeypatch):
|
||||
with pytest.raises(SuspiciousFileOperation, match="should not be reading images from disk"):
|
||||
Paragraph(
|
||||
'<img src="/etc/passwd" />',
|
||||
)
|
||||
Reference in New Issue
Block a user